# Axiom CLI Technical Specification

**`axi` — the command-line interface for the Axiom intelligence platform**

---

| Property | Value |
|----------|-------|
| Version | 0.6.2 |
| Last Updated | 2026-04-07 |
| Status | Active Development |
| Package | [axi-platform](https://pypi.org/project/axi-platform/) on PyPI |
| PRD | [CLI PRD](../requirements/prd-axi-cli.md) |
| Brand | [CLI Identity](spec-brand-identity.md#cli-identity) |

---

## Overview

`axi` is the command-line interface for Axiom. It uses a **noun-verb pattern** (`axi <noun> <verb> [args] [--flags]`) where each noun is registered by a builtin or user extension via `axiom-extension.toml` manifests.

### Architecture

| Component | Choice | Rationale |
|-----------|--------|-----------|
| **Language** | Python 3.11+ | Rapid iteration, rich ecosystem (Whisper, ML, openpyxl) |
| **CLI framework** | argparse + argcomplete | Standard library, shell completions |
| **HTTP client** | httpx | Async, TLS, connection pooling |
| **Output** | rich + json | Pretty tables/markdown, machine-readable JSON |
| **Config** | TOML (tomlkit) | Human-editable, standard format |
| **Package** | `axi-platform` on PyPI | `pip install axi-platform` |
| **Entry point** | `axi` / `axiom` | Both work; `axi` is the short form |

### Package Structure

```
axiom (Python package)
├── axiom_cli.py              # Entry point, dispatch, core commands
├── extensions/
│   ├── discovery.py          # Extension + CLI command discovery
│   └── builtins/             # All builtin extensions (each registers CLI nouns)
│       ├── neut_agent/       # chat, code
│       ├── eve_agent/        # signal
│       ├── prt_agent/        # pub, doc
│       ├── mo_agent/         # mo
│       ├── federation/       # federation, nodes, knowledge, research, security, chaos
│       └── ...               # 23+ extensions total
└── infra/                    # Shared infrastructure (gateway, router, etc.)
```

Commands are discovered dynamically from `axiom-extension.toml` manifests in each extension directory. Core commands (`config`, `setup`, `ext`, `infra`, `doctor`) are hardcoded in `axiom_cli.py` and take precedence over extensions.

---

## Command Hierarchy

Complete command tree as implemented. Each noun is registered by an extension unless marked **(core)**.

```
axi
│
├── chat [message]             # Interactive agent with tool calling (neut_agent)
│   ├── --resume <id>          # Resume an existing session
│   ├── --context <file>       # Load additional context
│   ├── --no-stream            # Disable streaming output
│   ├── --model <name>         # Override LLM model
│   ├── --provider <name>      # Override LLM provider
│   ├── --mode <auto|public|export-controlled>  # Routing mode
│   ├── --render <rich|ansi>   # Force render provider
│   ├── --input <ptk|basic>    # Force input provider
│   └── --no-tui               # Disable full-screen TUI
│
├── code                       # Alias for chat (neut_agent)
│
├── signal                     # Agentic signal ingestion pipeline (eve_agent)
│   ├── brief [topic]          # Catch up on what happened
│   │   ├── --since TIME       #   Time range start
│   │   ├── --hours N          #   Hours lookback
│   │   ├── --ack              #   Acknowledge all
│   │   ├── --caught-up        #   Mark caught up
│   │   ├── --status           #   Show brief status
│   │   ├── --topics           #   List available topics
│   │   └── --index            #   Index brief to RAG
│   ├── media search <query>   # Search recordings
│   │   ├── --mode <auto|keyword|semantic|hybrid>
│   │   ├── --limit N          #   Result count
│   │   ├── --play             #   Auto-play first result
│   │   └── --discuss          #   Discuss first result
│   ├── media play <id>        # Play a recording
│   ├── media discuss <id>     # Discuss recording with agent
│   ├── media stats            # Media library statistics
│   ├── media index            # Rebuild media index
│   ├── media list             # List indexed recordings
│   ├── draft                  # Generate weekly changelog
│   ├── status                 # Pipeline health
│   ├── watch                  # Watch endpoints for changes
│   ├── pipeline ingest        # Process voice memos / sources
│   ├── pipeline review        # Guided correction review
│   ├── pipeline suggest       # LLM signal-to-PRD matching
│   ├── pipeline sources       # Manage signal sources
│   ├── pipeline subscribers   # Manage subscribers
│   ├── pipeline routes        # Signal routing
│   ├── pipeline providers     # Docflow provider status
│   ├── pipeline serve         # HTTP ingestion server
│   ├── pipeline voice         # Voice identification status
│   └── pipeline timestamps    # Regenerate word-level timestamps
│
├── pub                        # Document publishing lifecycle (prt_agent)
│   ├── overview               # Dashboard of document ecosystem
│   ├── publish [file]         # Generate + publish to storage
│   │   ├── --draft            #   Draft mode
│   │   ├── --all              #   All tracked documents
│   │   ├── --changed-only     #   Only changed files
│   │   ├── --endpoint EP      #   Target endpoint
│   │   └── --force            #   Skip confirmation
│   ├── review [file]          # Interactive human-in-the-loop review
│   │   ├── --fresh            #   Fresh review
│   │   ├── --quick            #   Quick scan
│   │   ├── --status           #   Show review status
│   │   └── --chat             #   Discuss findings
│   ├── generate <file>        # Generate locally (no upload)
│   ├── pull [doc_id]          # Pull external doc → update .md
│   │   ├── --all              #   All tracked
│   │   ├── --dry-run          #   Preview only
│   │   └── --comments         #   Include comments
│   ├── push [path]            # Push to storage (auto-assembles)
│   │   ├── --all              #   All tracked
│   │   ├── --draft            #   Draft mode
│   │   ├── --endpoint EP      #   Target endpoint
│   │   └── --headed           #   Include header
│   ├── status [file]          # Document state + provenance
│   ├── check-links            # Verify cross-document links
│   ├── diff                   # Changed docs since last publish
│   ├── scan [folders...]      # Scan for tracked/untracked docs
│   ├── onboard <id> <file>    # Register document in manifest
│   ├── watch                  # Auto-publish on save
│   ├── providers              # List available providers
│   └── assemble <manifest>    # Assemble multi-section document
│
├── doc                        # Alias for pub (prt_agent)
│
├── rag                        # RAG index management (rag)
│   ├── index [path]           # Index documents into RAG store
│   ├── search <query>         # Search the RAG index
│   ├── status                 # Per-corpus index statistics
│   ├── load-community         # Load pre-built community corpus
│   ├── sync <corpus>          # Sync corpus from remote source
│   ├── watch                  # Watch workspace, re-index on change
│   └── reindex                # Force full re-index
│
├── federation                 # Federation membership (federation)
│   ├── status                 # Show federation status
│   ├── init                   # Initialize node identity
│   ├── join                   # Join a federation
│   ├── leave                  # Leave current federation
│   ├── invite                 # Generate invitation token
│   ├── resources              # List shared resources
│   └── peers                  # List federated peers
│
├── nodes                      # Fleet monitoring (federation)
│   ├── add                    # Register a node
│   ├── status                 # Check node health
│   ├── upgrade                # Run remote upgrade
│   ├── remove                 # Unregister a node
│   └── list                   # List all registered nodes
│
├── knowledge                  # Knowledge observatory (federation)
│   ├── status                 # Knowledge health dashboard
│   ├── velocity               # Ingestion rate
│   ├── accumulation           # What do we know?
│   ├── impact                 # Is knowledge being used?
│   ├── report                 # Full knowledge report
│   ├── gaps                   # Knowledge coverage gaps
│   └── saved                  # Saved findings from /save
│
├── research                   # Call to Research protocol (federation)
│   ├── create                 # Create a Call to Research
│   ├── list                   # List calls
│   ├── show                   # Show call details
│   ├── claim                  # Claim a research part
│   ├── submit                 # Submit response
│   ├── publish                # Publish synthesis
│   └── chain                  # Show research chain
│
├── security                   # SECUR-T guardian (federation)
│   ├── status                 # Security health
│   ├── alerts                 # List alerts
│   ├── resolve                # Resolve an alert
│   ├── trust                  # Show trust score
│   ├── rules                  # Anomaly detection rules
│   ├── escalation             # Escalation path health
│   └── scan                   # Run anomaly check
│
├── chaos                      # Chaos testing (federation)
│   ├── list                   # Available chaos scenarios
│   ├── run                    # Run a chaos scenario
│   └── status                 # Results from last run
│
├── connect [name]             # Connection management (connect)
│   ├── --clear                # Remove saved credentials
│   ├── --check                # Health check all connections
│   └── --json                 # Machine-readable output
│
├── agents                     # Agent service management (agents)
│   ├── status                 # Agent service status
│   ├── start [name]           # Start agent(s)
│   ├── stop [name]            # Stop agent(s)
│   ├── register               # Register as system services
│   ├── unregister [name]      # Remove registrations
│   └── logs [name]            # Tail agent logs
│
├── mo                         # M-O resource steward (mo_agent)
│   ├── status                 # M-O health
│   ├── ls                     # List tracked entries
│   ├── clean                  # Sweep expired/orphaned
│   ├── purge                  # Delete all scratch entries
│   ├── vitals                 # Detailed vitals snapshot
│   ├── diagnose               # LLM-powered diagnosis
│   ├── ci                     # CI/CD pipeline status
│   └── retention              # Data retention status
│
├── release                    # Release management (burn_e_agent + release)
│   ├── status                 # Build and release status
│   ├── mode                   # Developer vs operator mode
│   ├── patterns               # Known CI failure patterns
│   ├── check                  # Pre-push prevention checks
│   └── plan                   # Show release plan
│
├── log                        # Log inspection (log)
│   ├── tail                   # Stream recent routing events
│   ├── verify                 # Verify audit log chain integrity
│   ├── stats                  # Log statistics
│   ├── backend                # Backend configuration
│   ├── sinks                  # Configured sinks
│   └── export                 # Export logs
│
├── db                         # PostgreSQL infrastructure (db)
│   ├── up                     # Start K3D cluster with PG
│   ├── down                   # Stop cluster (preserve data)
│   ├── delete                 # Delete cluster and data
│   ├── status                 # Cluster and DB status
│   ├── migrate                # Alembic migrations
│   └── bootstrap              # Full setup from scratch
│
├── mirror                     # Public mirror gate (mirror_agent)
│   ├── review                 # Scan for sensitive data
│   ├── push                   # Review then push to GitHub
│   └── status                 # Mirror status
│
├── ide                        # IDE configuration (ide)
│   ├── status                 # Detected IDEs and extensions
│   ├── setup                  # Auto-configure IDEs
│   ├── extensions             # Install recommended extensions
│   └── syntax [lang]          # Install syntax highlighting
│
├── settings                   # Configuration (settings)
│   ├── get <key>              # Read a setting
│   ├── set <key> <value>      # Write a setting
│   ├── reset <key>            # Remove override
│   └── edit                   # Open in $EDITOR
│
├── note [text]                # Quick personal notes (note)
│   └── --list                 # Show recent daily note files
│
├── status                     # System health dashboard (status)
│   ├── --db                   # Database status
│   ├── --api                  # API status
│   ├── --services             # Service status
│   ├── --watch                # Continuous monitoring
│   └── --json                 # Machine-readable
│
├── test [profile]             # Test orchestration (test)
│   ├── quick|full|pr|release  # Test profiles
│   ├── unit|integration|...   # Specific suites
│   ├── --verbose              # Verbose output
│   ├── --fail-fast            # Stop on first failure
│   ├── --coverage             # Coverage report
│   └── --watch                # Re-run on change
│
├── update                     # Dependency updates (update)
│   ├── --deps                 # Update dependencies
│   ├── --migrate              # Run migrations
│   ├── --check                # Check for updates
│   └── --pull                 # Pull latest code
│
├── install                    # Environment setup (install)
│   ├── --env <name>           # Target environment
│   ├── --list                 # List available environments
│   ├── --force                # Force re-run
│   └── --step <id>            # Run specific step
│
├── serve                      # HTTP API server (web_api)
│   ├── --port PORT            # Listen port
│   ├── --host HOST            # Bind address
│   ├── --origins ORIGINS      # CORS origins
│   ├── --api-key KEY          # API key
│   ├── --read-only            # Read-only mode
│   └── --static-dir DIR       # Serve static files
│
├── config                     # (core) Interactive onboarding wizard
├── setup                      # (core) Alias for config
├── ext                        # (core) Extension management
├── infra                      # (core) Infrastructure detection
└── doctor | dr                # (core) AI-powered environment diagnostics
```

### Command Discovery

Extension commands are discovered at runtime from `axiom-extension.toml` manifests:

```toml
# axiom-extension.toml example
[[cli.commands]]
noun = "signal"
module = "axiom.extensions.builtins.eve_agent.cli"
description = "Agentic signal ingestion pipeline"
```

Core commands (`config`, `setup`, `ext`, `infra`, `doctor`) are hardcoded in `axiom_cli.py` and take precedence over any extension that registers the same noun.

**Discovery order:**
1. Core commands (SUBCOMMANDS dict in `axiom_cli.py`)
2. Builtin extensions (`src/axiom/extensions/builtins/`)
3. Installed packages with `axiom-extension.toml` (PyPI extensions)
4. User extensions (`~/.axi/extensions/`)

---

## Chat Mode

`axi chat` launches an interactive agentic session — an LLM-powered assistant with tool calling, RAG context injection, and multi-provider routing.

### Capabilities

| Capability | Description |
|------------|-------------|
| **Tool calling** | Multi-turn tool-use loop (up to 10 rounds) via Gateway |
| **RAG grounding** | Automatic context injection from pgvector knowledge base |
| **Tier routing** | Keyword + SLM classification routes to appropriate LLM tier |
| **Streaming** | First round streams; subsequent rounds (after tools) are non-streaming |
| **Approval gates** | Write operations require human confirmation |
| **Session persistence** | PostgreSQL-backed sessions with resume support |
| **Workspace awareness** | Reads CLAUDE.md, model.yaml, personal context |
| **Slash commands** | `/signal`, `/pub`, `/save`, `/model`, `/sessions`, etc. |

### Chat Tools

These tools are available to the LLM during chat. Read tools auto-execute; write tools require approval.

**Read-only (auto-approved):**

| Tool | Description |
|------|-------------|
| `query_docs` | Check publisher status of tracked documents |
| `signal_status` | Show inbox/processed/draft counts |
| `list_providers` | List all registered publisher providers |
| `doc_check_links` | Verify cross-document link resolution |
| `doc_diff` | Show documents changed since last publish |

**Write (require approval):**

| Tool | Description |
|------|-------------|
| `signal_ingest` | Run extractors on inbox data |
| `doc_generate` | Generate .docx from markdown |
| `doc_publish` | Generate and publish document to storage |
| `write_file` | Write content to file |
| `write_inbox_note` | Drop text note into signal inbox |

Tools are extensible: core extensions register tools via `tools_ext/` hot-reloading, user extensions via `discover_and_load_chat_tools()`.

### Slash Commands

Slash commands are in-chat meta-commands. They run locally (no LLM call) and dispatch real CLI commands under the hood.

**Session management:**

| Command | Description |
|---------|-------------|
| `/sessions` | Browse and manage sessions |
| `/sessions rename <title>` | Rename current session |
| `/sessions archive [id]` | Archive session(s) |
| `/resume <id\|#>` | Load a session by ID or number |
| `/new` | Start a fresh session |
| `/clear` | Clear message history |
| `/compact` | Summarize conversation to save tokens |

**Chat control:**

| Command | Description |
|---------|-------------|
| `/help` | Show available commands |
| `/status` | Session info, gateway, usage |
| `/usage` | Token usage and cost breakdown |
| `/model` | Switch LLM provider mid-chat |
| `/context` | Show context window usage |
| `/save` | Save last response to knowledge corpus |
| `/doctor` | Quick health check |
| `/update` | Check for updates |
| `/exit` | Save and exit |

**Signal commands** (forwarded to EVE agent):

| Command | Description |
|---------|-------------|
| `/signal brief` | Catch up on what happened |
| `/signal media` | Search, play, discuss recordings |
| `/signal draft` | Generate weekly changelog |
| `/signal status` | Pipeline health |
| `/signal pipeline <cmd>` | Advanced pipeline operations |

**Publisher commands** (forwarded to PRT agent):

| Command | Description |
|---------|-------------|
| `/pub overview` | Document ecosystem dashboard |
| `/pub publish` | Generate + publish |
| `/pub review` | Interactive review |
| `/pub status` | Document status |
| `/pub diff` | Changed docs since last publish |

**Hidden aliases:** `/sense` → `/signal`, `/doc` → `/pub`

### Session Management

Sessions are stored in PostgreSQL (see [spec-session-store.md](spec-session-store.md)). This enables resume, multi-client access, and interaction logging.

```bash
# Resume most recent session
axi chat --resume

# Resume a specific session
axi chat --session abc123def456

# List recent sessions
axi chat --list

# Sync local JSON sessions to PG
axi chat --sync
```

**`axi chat --list` output:**

```
Recent sessions:
  ID            Title                          Messages  Cost     Last Active
  abc123def456  Fuel temp analysis             12        $0.34    2 min ago
  def456abc123  MCNP model debugging           47        $1.20    3 hours ago
  789012345678  Startup procedure review       8         $0.00    yesterday
```

Sessions fall back to local JSON files when PostgreSQL is unreachable. See [spec-session-store.md §8](spec-session-store.md) for graceful degradation.

### Tool Modes

By default, all tools are available. Tool modes restrict the tool set for safety or simplicity:

```bash
# Read-only tools only (query, search, status — no writes)
axi chat --simple

# Specific tools only
axi chat --tools rag,model

# Full tool access (default)
axi chat
```

`--simple` is recommended for new users and read-only exploration sessions.

### Token Budget

Sessions can have a token budget ceiling to prevent runaway tool loops:

```bash
# Set budget for this session
axi chat --budget 100000

# Configure default budget globally
axi config set chat.max_budget_tokens 200000
```

When the budget is exhausted, the agent stops gracefully.

### Cost Display

Every turn shows token usage and estimated cost:

```
> what materials are in the fuel assembly?

  The fuel assembly contains UO2 pellets (10.97 g/cc, 4.95% enriched)...
  
  ─── 1,234 in / 567 out · $0.02 this turn · $0.15 session ───
```

Qwen (self-hosted) shows `$0.00`. Claude API shows real costs.

### Structured Output

```bash
# Return JSON instead of prose
axi chat "list all models with UO2 fuel" --json

# Pipe to jq
axi chat "what materials are available?" --json | jq '.materials[]'
```

`--json` suppresses streaming, rich rendering, and the cost footer.

### Safety Boundaries

- **Read-heavy**: Most operations are queries and analysis
- **Human-in-loop**: Writes require confirmation via ApprovalGate
- **Audit trail**: All actions logged with session ID in PostgreSQL
- **Scope limits**: Cannot access systems outside configured facility
- **Tool modes**: `--simple` restricts to read-only tools

---

## Rendering Architecture

Two-layer abstraction for terminal output:

| Layer | Purpose |
|-------|---------|
| **RenderProvider** (ABC) | Terminal rendering: streaming, tool results, approvals, status |
| **InputProvider** (ABC) | User input: prompts, history, tab completion |

**Concrete implementations:**

| Provider | Description | Dependency |
|----------|-------------|-----------|
| `AnsiRenderProvider` | Zero-dependency ANSI escape codes | None (stdlib) |
| `RichRenderProvider` | Enhanced output with syntax highlighting | `rich` |
| `PtkInputProvider` | Full readline, history, completion | `prompt_toolkit` |
| `BasicInputProvider` | Fallback `input()` | None (stdlib) |

Selection is automatic (rich if available, else ANSI) or forced via `--render` / `--input` flags.

---

## Configuration

### Config File Location

| Platform | Path |
|----------|------|
| macOS / Linux | `~/.axi/config.toml` or `~/.config/axi/config.toml` |
| Runtime | `runtime/config/` (per-project) |
| Example | `runtime/config.example/` (shipped defaults) |

### Key Config Files

| File | Purpose |
|------|---------|
| `config.toml` / `settings.toml` | General settings |
| `llm-providers.toml` | LLM provider configuration (endpoints, tiers, models) |
| `infrastructure.toml` | Service endpoints (Ceph, OpenBao, etc.) |
| `install.toml` | Environment-aware install steps |
| `retention.yaml` | Data retention policies |
| `logging.toml` | Log levels and sinks |

---

## Extension System

Extensions register CLI commands, tools, connections, and agents via `axiom-extension.toml`:

```toml
[extension]
name = "eve_agent"
version = "0.6.2"
description = "Signal ingestion and analysis agent"

[[cli.commands]]
noun = "signal"
module = "axiom.extensions.builtins.eve_agent.cli"
description = "Agentic signal ingestion pipeline"

[[connections]]
name = "outlook"
type = "oauth2"
description = "Microsoft 365 for voice memo ingestion"
```

### Discovery Tiers

1. **Builtin** — `src/axiom/extensions/builtins/` (shipped with package)
2. **Installed** — PyPI packages with `axiom-extension.toml` in package root
3. **User** — `~/.axi/extensions/` (local user extensions)

---

## Branding

The CLI supports domain-specific branding via `axiom.infra.branding`. The same codebase powers:

| Product | Package | CLI Name | Banner |
|---------|---------|----------|--------|
| **Axiom** (platform) | `axi-platform` | `axi` | Generic intelligence platform |
| **NeutronOS** (nuclear) | `neutron-os` | `neut` | Nuclear engineering assistant |

Domain products inherit all Axiom commands and add domain-specific extensions.

---

## Shell Completions

Via argcomplete (installed as dependency):

```bash
# Bash
eval "$(register-python-argcomplete axi)"

# Zsh
autoload -U bashcompinit && bashcompinit
eval "$(register-python-argcomplete axi)"
```

---

## Distribution

| Method | Command |
|--------|---------|
| **PyPI** | `pip install axi-platform` |
| **PyPI (with domain)** | `pip install neutron-os` (includes axi-platform) |
| **Development** | `pip install -e ".[all]"` |

---

## Testing Strategy

| Test Type | Coverage |
|-----------|----------|
| Unit tests | Command parsing, tool definitions, usage tracking |
| Integration tests | Extension discovery, CLI dispatch, session store |
| E2E tests | `axi chat` → tool use → response pipeline |
| Smoke tests | `axi --help`, `axi status`, extension loading |

Current test count: **2270+** (Axiom platform)

---

## Performance

| Metric | Current |
|--------|---------|
| `axi --help` | <200ms |
| Extension discovery | <100ms (cached) |
| Chat first response | Depends on LLM provider (1-5s typical) |
| RAG search | <500ms (pgvector) |

---

## Unimplemented / Planned

These nouns appear in specs or PRDs but have no CLI implementation:

| Noun | Status | Notes |
|------|--------|-------|
| `data` | Not implemented | Data platform (Iceberg/dbt) not wired to CLI |
| `repo` | Extension exists, no CLI | `axiom-extension.toml` defined but zero `[[cli.commands]]` |
| `demo` | Not implemented | Guided walkthrough deferred |
| `graph` | Spec'd ([spec-knowledge-graph.md](spec-knowledge-graph.md)) | Apache AGE, Phase 0.1 |
| `dmp` | Spec'd ([prd-doe-data-management.md](../requirements/prd-doe-data-management.md)) | FAIR/DMP framework, P4 |

---

## Related Documents

- [CLI PRD](../requirements/prd-axi-cli.md) — Product requirements
- [Agent Architecture](spec-agent-architecture.md) — Agent capabilities and delegation
- [Session Store](spec-session-store.md) — PostgreSQL session backend
- [Gateway & Routing](spec-model-routing.md) — LLM provider routing
- [RAG Architecture](spec-rag-architecture.md) — Knowledge retrieval
- [Observability](spec-observability.md) — Metrics and logging
- [Federation](spec-federation.md) — Multi-node protocol
- [Canary Nodes](spec-canary-nodes.md) — Release promotion via `axi release`
