Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(cli): land the Jarvis CLI on main (control a running Jarvis from the terminal)

Ruben Lütke15b14044f3d4
diff --git a/.claude/skills/drive-jarvis-cli/SKILL.md b/.claude/skills/drive-jarvis-cli/SKILL.md
new file mode 100644
index 0000000000..708f440d9f
--- /dev/null
+++ b/.claude/skills/drive-jarvis-cli/SKILL.md
@@ -0,0 +1,94 @@
+---
+name: drive-jarvis-cli
+description: >-
+ Use when you (a Claude Code / Codex session, or any terminal agent) need to
+ control a running Personal Jarvis instance — switch the brain provider, dispatch
+ or inspect missions, read/write config, search the wiki, manage skills, browse
+ outputs, etc. Teaches the `jarvis` CLI: zero-config local auth, machine-readable
+ output, and the safety flags. Trigger phrases: "control Jarvis", "drive Jarvis
+ from the CLI", "switch Jarvis's brain provider", "dispatch a Jarvis mission".
+---
+
+# Drive Jarvis from the CLI
+
+Jarvis exposes its entire WebUI action surface as a command-line tool, the same
+way `gcloud` / `aws` exposes a cloud platform. You drive a **running** Jarvis over
+HTTP — no need to be inside the app.
+
+## Setup (one time)
+
+The CLI ships with the package, so after `pip install -e .` the `jarvis` binary is
+on PATH (aliases: `jarvisctl`, `jctl`). Check it:
+
+```bash
+jarvis version
+```
+
+**Auth is zero-config on the same machine as a running Jarvis.** The desktop app
+writes its live port + control token to a single-instance session file; the CLI
+discovers it automatically, and falls back to the machine's control key. You do
+not need to log in. Confirm reachability:
+
+```bash
+jarvis system status # {"reachable": true} when Jarvis is running
+```
+
+For a **remote** Jarvis (e.g. a VPS), tunnel it to loopback and point the CLI at it:
+
+```bash
+ssh -L 47821:127.0.0.1:47821 <host> # then it behaves like local
+# or, explicitly, per call:
+jarvis --url http://127.0.0.1:47821 --key "$JCTL" missions list
+```
+
+## How to use it (agent ergonomics)
+
+- **Discover commands**: `jarvis --help`, `jarvis <group> --help`. Every mounted
+ REST endpoint is also reachable generically via `jarvis api <tag> <op> --help`.
+- **Machine-readable output**: put `--json` *before* the group, e.g.
+ `jarvis --json missions list`. Parse that, not the human table.
+- **Preview before acting**: `--dry-run` on any command prints the exact request
+ (method, path, body, whether auth is attached) and sends nothing.
+- **Authorize destructive actions**: reversible actions (switch provider, set
+ language, enable a skill) just run. Destructive ones (any `DELETE`, `config
+ set`, `missions dispatch`, `telephony outbound`) refuse unless you pass `--yes`
+ (or set `JARVIS_CLI_ASSUME_YES=1`). This is deliberate — only add `--yes` when
+ you mean it.
+- **Never** pass a secret as an inline argument; `auth login` and PAT connects
+ read it from a hidden prompt or stdin (`--key -`).
+
+## Common tasks
+
+```bash
+# Switch the active brain provider (the flagship; reversible)
+jarvis brain switch openai
+jarvis brain subagent-switch openai # switch the worker/sub-agent provider
+jarvis --json brain status # which provider is active
+
+# Config (atomic write pipeline; `set` is destructive)
+jarvis --json config get brain.primary
+jarvis config set ui.theme dark --yes
+jarvis config language set en
+
+# Missions (dispatch is destructive — spawns a worker)
+jarvis --json missions list --state RUNNING
+jarvis missions dispatch "summarize today's PRs" --yes
+jarvis --json missions show <id>
+
+# Knowledge + history + outputs
+jarvis --json wiki recall "melbourne visa"
+jarvis --json sessions list
+jarvis --json outputs list
+
+# Skills, board, workflows, mcps, docs, … (every domain has a group)
+jarvis --json skills list
+jarvis --json board summary
+jarvis api --help # the full auto-generated surface
+```
+
+## Rules
+
+- Read with `--json` and parse; act with explicit intent.
+- `--dry-run` first when unsure what a destructive command will send.
+- If `jarvis system status` reports unreachable, Jarvis is not running — start it
+ (`jarvis serve` for headless) rather than retrying blindly.
diff --git a/.claude/skills/generate-cli-command/SKILL.md b/.claude/skills/generate-cli-command/SKILL.md
new file mode 100644
index 0000000000..1d1162a2a2
--- /dev/null
+++ b/.claude/skills/generate-cli-command/SKILL.md
@@ -0,0 +1,116 @@
+---
+name: generate-cli-command
+description: >-
+ Use after building a feature that adds or changes a REST route in
+ jarvis/ui/web/*_routes.py, as the "definition of done" before committing.
+ Ensures the new endpoint is reachable from the Jarvis CLI: confirms the router
+ is mounted, checks its OpenAPI metadata is clean, and (for high-value routes)
+ scaffolds a curated `jarvis <group> <command>` plus a test and a docs entry.
+ Trigger phrases: "generate a CLI command", "/generate-cli-command", "wire this
+ feature into the CLI", "make this endpoint CLI-reachable".
+---
+
+# Generate a CLI Command for a New Feature
+
+The Jarvis CLI (`jarvis/cli_ctl/`, the `jarvis`/`jarvisctl`/`jctl` binaries) is a
+thin HTTP client over the REST API. Its dynamic `jarvis api <tag> <op>` layer turns
+**every mounted REST route into a command automatically** — so a new feature is
+CLI-reachable the moment its route is mounted with clean OpenAPI metadata. This
+skill is the checklist that guarantees that, and adds an ergonomic curated command
+for high-traffic routes.
+
+Run this when you have finished a feature whose work added or changed a route in
+`jarvis/ui/web/*_routes.py` (or `conductor/api`), before your final commit.
+
+## Steps
+
+### 1. Find the new/changed routes
+
+```bash
+git diff main...HEAD --name-only -- 'jarvis/ui/web/*_routes.py' 'conductor/api/*.py'
+```
+
+For each changed file, list the added route decorators:
+
+```bash
+git diff main...HEAD -- jarvis/ui/web/<file>_routes.py | grep -E '^\+\s*@router\.(get|post|put|patch|delete)'
+```
+
+Note each new `(METHOD, path)` and whether it is destructive (DELETE, or it
+deletes / charges money / places a call / spawns work / writes arbitrary config).
+
+### 2. Confirm the router is MOUNTED (the hard gate)
+
+A route that exists in a file but is never `app.include_router(...)`'d is
+unreachable from both the WebUI and the CLI (this has happened — see the frontier
+/ antigravity / self-mod fixes). Run the coverage gate:
+
+```bash
+python scripts/ci/check_cli_coverage.py
+```
+
+If it reports your new module as unmounted, add the mount in
+`jarvis/ui/web/server.py` next to the other `app.include_router(...)` calls (and
+the matching `from .<module> import router as <name>` import). Re-run the gate
+until it prints OK.
+
+### 3. Check the OpenAPI metadata is clean
+
+For the dynamic command to read well, each new route needs:
+
+- a router **tag** (`APIRouter(prefix=..., tags=["<group>"])`) — becomes the
+ `jarvis api <tag>` group;
+- a sensible function name — FastAPI derives the `operationId` (→ command name)
+ from it, so name it like the command you'd want (`list_widgets`, not `handler`);
+- a one-line **summary or docstring** — becomes the command's `--help`.
+
+Fix the route if any are missing. (You can eyeball the generated command after
+booting the server: `jarvis api <tag> --help`.)
+
+### 4. (High-value routes) Scaffold a curated command
+
+If the route belongs to a domain users will drive often, add an ergonomic curated
+command. Copy the pattern from an existing module (e.g.
+`jarvis/cli_ctl/commands/missions.py`):
+
+- Put the command in `jarvis/cli_ctl/commands/<domain>.py` (create the module +
+ register it in `jarvis/cli_ctl/__main__.py` with `app.add_typer(...)`, and add
+ `<domain>` to `RESERVED_CONTROL_NAMES` in `jarvis/cli_ctl/reserved.py` if new).
+- Call `invoke.run(method, path, ...)`. For a **destructive** route pass
+ `dangerous=True` so it requires `--yes`; reversible mutations proceed without it.
+ Reads (GET) need nothing. Reuse `options.yes_opt()` / `options.dry_opt()` /
+ `options.persist_opt()`.
+- **Never** accept a secret as an inline argument — read it from a hidden prompt
+ or stdin (`prompt=..., hide_input=True`), as `auth login` / `marketplace
+ connect-pat` do (AP-12 / spec §7.2).
+
+Add a test in `tests/unit/cli_ctl/test_commands_<domain>.py` using the
+`capture_api` fixture: assert the command hits the right `(method, path, body)`
+and that a destructive command refuses without `--yes`.
+
+### 5. Regenerate the reference doc + run the checks
+
+```bash
+python scripts/ci/gen_cli_reference.py # refresh docs/jarvis-cli-reference.md
+python -m pytest tests/unit/cli_ctl/ -q # all green
+ruff check jarvis/cli_ctl/ scripts/ci/
+python scripts/ci/check_cli_coverage.py # OK
+```
+
+### 6. Commit
+
+Commit the route, the mount (if added), the curated command + test, and the
+regenerated reference together. Suggested message:
+
+```
+feat(<area>): <feature> + CLI command `jarvis <group> <command>`
+```
+
+## Hard rules
+
+- The dynamic layer is the guarantee; a curated command is sugar. Never ship a
+ curated command whose path is not a real, mounted route (the coverage gate and
+ an adversarial path-vs-route check catch this).
+- English only for all artifacts (code, help text, docs) — the `language-policy`
+ CI gate blocks newly-added German.
+- Destructive commands require `--yes`; secrets never go through argv.
diff --git a/.githooks/pre-push b/.githooks/pre-push
index a7ddb7aa63..e11f0ff1ec 100755
--- a/.githooks/pre-push
+++ b/.githooks/pre-push
@@ -90,6 +90,19 @@ if [ -f "$language_gate" ]; then
done < "$refs_file"
fi
+# --- 3) CLI COVERAGE gate (FAIL-CLOSED) ---------------------------------------
+# Every jarvis/ui/web/*_routes.py router must be mounted in server.py, so every
+# WebUI action stays reachable from the `jarvis` CLI (catches the unmounted-router
+# / dead-command bug class). Static + stdlib-only; safe to run on every push.
+cli_gate="scripts/ci/check_cli_coverage.py"
+if [ -f "$cli_gate" ]; then
+ "$PY" "$cli_gate" </dev/null
+ if [ "$?" -ne 0 ]; then
+ status=1
+ cli_coverage_hit=1
+ fi
+fi
+
rm -f "$refs_file"
if [ "$status" -ne 0 ]; then
@@ -101,6 +114,10 @@ if [ "$status" -ne 0 ]; then
if [ "$language_hit" -ne 0 ]; then
echo "pre-push BLOCKED: LANGUAGE gate (newly added German text)."
fi
+ if [ "${cli_coverage_hit:-0}" -ne 0 ]; then
+ echo "pre-push BLOCKED: CLI COVERAGE gate (a route module is not mounted)."
+ echo " Mount it in jarvis/ui/web/server.py — see the findings above."
+ fi
echo "Bypass once with: git push --no-verify (layer-3 CI is the backstop)."
fi
exit "$status"
diff --git a/docs/jarvis-cli-reference.md b/docs/jarvis-cli-reference.md
new file mode 100644
index 0000000000..d777f9297f
--- /dev/null
+++ b/docs/jarvis-cli-reference.md
@@ -0,0 +1,163 @@
+# Jarvis CLI — Command Reference
+
+_Generated from the curated command tree by `scripts/ci/gen_cli_reference.py` — do not edit by hand. Every mounted REST endpoint is additionally reachable via `jarvis api <tag> <op>`._
+
+## auth
+
+- `jarvis auth login --url --key` — Verify the key against the server and persist it for future calls.
+- `jarvis auth logout` — Forget the saved credentials.
+- `jarvis auth status --url --key` — Report whether the configured (or given) target is reachable.
+
+## board
+
+- `jarvis board achievements` — Show unlocked + locked achievements.
+- `jarvis board bio` — Show the AI-generated bio.
+- `jarvis board bio-regenerate --yes --dry-run` — Regenerate the AI bio.
+- `jarvis board heatmap --days` — Show the activity heatmap cells.
+- `jarvis board profile` — Show the profile (meta + people + review count).
+- `jarvis board records` — Show personal records.
+- `jarvis board summary --window-days` — Show personal totals + streaks over a window.
+
+## brain
+
+- `jarvis brain deep-model <model> --persist --yes --dry-run` — Set the sub-agent deep model.
+- `jarvis brain list` — List configured brain providers (alias of status).
+- `jarvis brain status` — Show configured providers and which one is active.
+- `jarvis brain subagent-switch <provider> --persist --yes --dry-run` — Switch the sub-agent / worker provider (e.g. Codex -> OpenAI).
+- `jarvis brain switch <provider> --persist --yes --dry-run` — Switch the ACTIVE main brain provider (e.g. `jarvis brain switch openai`).
+- `jarvis brain test <provider> --dry-run` — Test connectivity + auth for a provider.
+
+## conductor
+
+- `jarvis conductor add --def --yes --dry-run` — Add a job from a Job JSON document.
+- `jarvis conductor delete <job_id> --yes --dry-run` — Delete a job.
+- `jarvis conductor list` — List Conductor jobs + a run summary.
+- `jarvis conductor run <job_id> --yes --dry-run` — Manually trigger a job run.
+- `jarvis conductor show <job_id>` — Show one job + recent runs.
+- `jarvis conductor toggle <job_id> --enabled --yes --dry-run` — Enable or disable a job.
+
+## config
+
+- `jarvis config get <path>` — Get a config value by dotted path (control-key gated).
+- `jarvis config language get` — Show the current reply language + the available options.
+- `jarvis config language set <lang> --persist --yes --dry-run` — Set the reply language (hot-reloads, no restart).
+- `jarvis config list` — List the mutable-settings allowlist (path, risk tier, restart needed).
+- `jarvis config set <path> <value> --reason --yes --dry-run` — Set a mutable config value via the atomic write pipeline (destructive: --yes).
+
+## contacts
+
+- `jarvis contacts add --json-body --yes --dry-run` — Add a contact.
+- `jarvis contacts delete <slug> --yes --dry-run` — Delete a contact.
+- `jarvis contacts edit <slug> --json-body --yes --dry-run` — Edit a contact (partial).
+- `jarvis contacts list` — List contacts.
+- `jarvis contacts show <slug>` — Show one contact.
+
+## docs
+
+- `jarvis docs list` — List documentation pages.
+- `jarvis docs search <query>` — Search the docs.
+- `jarvis docs show <slug>` — Show one doc page's body.
+- `jarvis docs tree` — Show the Diataxis-grouped doc tree.
+
+## frontier
+
+- `jarvis frontier ack --yes --dry-run` — Acknowledge (dismiss) the pending frontier proposals.
+- `jarvis frontier pending` — List proposed model upgrades awaiting acknowledgement.
+
+## marketplace
+
+- `jarvis marketplace connect-pat <plugin_id> --token --yes --dry-run` — Connect a plugin with a personal access token.
+- `jarvis marketplace connect-poll <plugin_id> <flow_id>` — Poll an in-progress OAuth connect flow.
+- `jarvis marketplace connect-start <plugin_id> --yes --dry-run` — Begin an OAuth connect flow (prints the redirect URI + flow id).
+- `jarvis marketplace disconnect <plugin_id> --yes --dry-run` — Disconnect a plugin.
+- `jarvis marketplace list` — List marketplace plugins + their connection status.
+
+## mcps
+
+- `jarvis mcps check <name> --yes --dry-run` — Health-check an MCP server (lists its tools).
+- `jarvis mcps delete <name> --yes --dry-run` — Remove an MCP server.
+- `jarvis mcps disable <name> --yes --dry-run` — Disable an MCP server.
+- `jarvis mcps enable <name> --yes --dry-run` — Enable an MCP server.
+- `jarvis mcps import-claude-desktop --yes --dry-run` — Import MCP servers from the Claude Desktop config.
+- `jarvis mcps list` — List MCP servers + a summary.
+
+## missions
+
+- `jarvis missions cancel <mission_id> --yes --dry-run` — Cancel a running mission (kills its worker).
+- `jarvis missions dispatch <prompt> --language --confirmed --yes --dry-run` — Dispatch a new self-healing mission — spawns a worker (destructive: --yes).
+- `jarvis missions kill <worker_id> --yes --dry-run` — Hard-kill a worker process by id.
+- `jarvis missions list --state --limit` — List missions (optionally filtered by state).
+- `jarvis missions rerun <mission_id> --confirmed --yes --dry-run` — Re-dispatch a terminal mission's prompt as a new linked mission.
+- `jarvis missions show <mission_id>` — Show one mission with its events + verdicts.
+
+## outputs
+
+- `jarvis outputs files <slug>` — List the artifacts a mission produced.
+- `jarvis outputs list` — List output sessions (a mission's deliverable folders).
+- `jarvis outputs open-with <slug> <path> --opener --yes --dry-run` — Open an artifact with a chosen editor (desktop only).
+- `jarvis outputs openers` — List installed editors/apps that can open an artifact.
+- `jarvis outputs plan <slug>` — Show a session's plan + steps.
+- `jarvis outputs preferred-opener <opener> --yes --dry-run` — Get or set the default artifact opener.
+
+## refresh
+
+- `jarvis refresh` — Clear the cached API schema (next call re-fetches it).
+
+## sessions
+
+- `jarvis sessions delete <session_id> --yes --dry-run` — Delete a text conversation thread.
+- `jarvis sessions list --days --limit` — List text + voice sessions, newest first.
+- `jarvis sessions resume <kind> <session_id> --yes --dry-run` — Seed the brain from a past conversation to continue it in text.
+- `jarvis sessions show <kind> <session_id>` — Show one conversation with its messages.
+- `jarvis sessions speak <kind> <session_id> --yes --dry-run` — Start a voice session seeded from a past conversation (503 on headless).
+
+## skills
+
+- `jarvis skills catalog-install <name> --source-url --title --raw-url --yes --dry-run` — Install a skill from the catalog (lands as a draft).
+- `jarvis skills catalog-search <query>` — Search the installable skill catalog.
+- `jarvis skills commit --draft --yes --dry-run` — Commit a generated draft to disk (still state=draft until enabled).
+- `jarvis skills disable <name> --yes --dry-run` — Deactivate a skill.
+- `jarvis skills draft <intent> --name-hint --category --yes --dry-run` — Generate a skill draft from an intent (AI author; lands as state=draft).
+- `jarvis skills enable <name> --yes --dry-run` — Activate a skill.
+- `jarvis skills list` — List all discovered skills.
+- `jarvis skills reload --yes --dry-run` — Re-scan the skills directory.
+- `jarvis skills show <name>` — Show one skill's detail.
+
+## system
+
+- `jarvis system restart --force --yes --dry-run` — Cleanly restart the desktop app (POST /api/settings/restart-app).
+- `jarvis system status` — Report server reachability + version (GET /api/control/auth/probe).
+
+## tasks
+
+- `jarvis tasks cancel <task_id> --yes --dry-run` — Soft-cancel a scheduled/running task.
+- `jarvis tasks create --json-body --yes --dry-run` — Create + schedule a task from a TaskSpec JSON document.
+- `jarvis tasks delete <task_id> --yes --dry-run` — Hard-delete a task (terminal states only, server-enforced).
+- `jarvis tasks get <task_id>` — Show one task with its step timeline.
+- `jarvis tasks list --state --limit` — List tasks (optionally filtered by state).
+
+## telephony
+
+- `jarvis telephony config` — Show the telephony config.
+- `jarvis telephony outbound <to> --message --yes --dry-run` — Place a real outbound call (destructive: costs money; needs --yes).
+- `jarvis telephony status` — Report telephony availability/status.
+
+## version
+
+- `jarvis version` — Print the jarvisctl version.
+
+## wiki
+
+- `jarvis wiki page <slug>` — Read a wiki page by vault path / slug.
+- `jarvis wiki recall <query>` — Full-text search the wiki.
+- `jarvis wiki tree` — Show the vault folder tree + stats.
+
+## workflows
+
+- `jarvis workflows create --def --yes --dry-run` — Create a workflow from a WorkflowDef JSON document.
+- `jarvis workflows delete <workflow_id> --yes --dry-run` — Delete a workflow.
+- `jarvis workflows list` — List workflows + a run summary.
+- `jarvis workflows run <workflow_id> --yes --dry-run` — Trigger a workflow run.
+- `jarvis workflows run-history --workflow-id` — List workflow runs (optionally for one workflow).
+- `jarvis workflows show <workflow_id>` — Show one workflow + recent runs.
+
diff --git a/docs/jarvis-cli.md b/docs/jarvis-cli.md
new file mode 100644
index 0000000000..cc3d558548
--- /dev/null
+++ b/docs/jarvis-cli.md
@@ -0,0 +1,137 @@
+# The Jarvis CLI
+
+`jarvis` is a command-line interface to a **running** Personal Jarvis instance. It
+exposes the same action surface as the desktop WebUI, so anything you can click in
+the UI you can also do from a terminal — and, more importantly, so can an external
+coding agent (Claude Code, Codex) or a script.
+
+This is the same relationship `gcloud` / `aws` / `az` have with their cloud
+platforms: a single CLI that surfaces the full capability plane of a service. You
+point it at a running Jarvis and drive it.
+
+> Full command list: [`jarvis-cli-reference.md`](jarvis-cli-reference.md)
+> (auto-generated). Design rationale: [`superpowers/specs/2026-06-21-jarvis-cli-design.md`](superpowers/specs/2026-06-21-jarvis-cli-design.md).
+
+## How it works
+
+The CLI is a **thin HTTP client over the REST API**, in two layers:
+
+1. **Dynamic layer (`jarvis api <tag> <op>`)** — every mounted REST endpoint is
+ surfaced automatically from the server's OpenAPI spec. New features become
+ commands with no extra code. This is what guarantees *every* WebUI action is
+ reachable.
+2. **Curated layer (`jarvis <group> <command>`)** — hand-written, ergonomic
+ commands for the common domains: `brain`, `config`, `missions`, `wiki`,
+ `sessions`, `skills`, `outputs`, `board`, `workflows`, `conductor`, `contacts`,
+ `telephony`, `marketplace`, `mcps`, `docs`, `frontier`, plus `auth`, `system`,
+ `tasks`.
+
+Because the CLI only ever calls the same routes the WebUI calls, it inherits all
+of Jarvis's safety machinery (risk tiers, the atomic config-write pipeline, the
+event bus, audit) for free — it cannot bypass a guardrail it never re-implements.
+
+It runs on Linux, macOS, and Windows (pure-Python: `typer`, `httpx`,
+`platformdirs`, `rich` — all base dependencies), including a headless VPS.
+
+## Install
+
+The CLI ships with the package, so after the normal install it is on your PATH:
+
+```bash
+pip install -e . # provides the `jarvis` binary (aliases: jarvisctl, jctl)
+jarvis version
+```
+
+Bare `jarvis` (no subcommand) still launches the app/tray as before; `jarvis serve`
+still starts the headless server. Only the control subcommands (`jarvis missions
+…`, `jarvis brain …`, etc.) route into the CLI.
+
+## Auth & discovery
+
+**Local is zero-config.** When Jarvis is running on the same machine, the desktop
+app writes its live port + control token to a single-instance session file; the
+CLI discovers it automatically (and falls back to the machine's control key). Just
+run commands:
+
+```bash
+jarvis system status # {"reachable": true} when Jarvis is up
+jarvis --json brain status
+```
+
+Resolution order (highest first): explicit `--url` / `--key` → `JARVISCTL_BASE_URL`
+/ `JARVISCTL_CONTROL_KEY` env → saved profile (`jarvis auth login`) → the live
+session file → the local control key + default `127.0.0.1:47821`.
+
+**Remote / VPS.** Tunnel the loopback port and the CLI treats it as local:
+
+```bash
+ssh -L 47821:127.0.0.1:47821 <host>
+```
+
+Or save a remote profile (the key is read from a hidden prompt — never an inline
+argument that would land in shell history):
+
+```bash
+jarvis auth login --url https://jarvis.example:47821
+# (prompts for the control key; or: echo "$JCTL" | jarvis auth login --url … --key -)
+```
+
+## Output
+
+Put `--json` **before** the group for machine-readable output; omit it for human
+tables:
+
+```bash
+jarvis --json missions list # JSON, for scripts/agents
+jarvis missions list # rich table, for humans
+```
+
+## Safety model
+
+The CLI is agent-first, so it stays out of your way for safe work and only gates
+the genuinely consequential:
+
+- **Reads** (`GET`) and **reversible mutations** (switch provider, set language,
+ enable a skill) just run.
+- **Destructive** actions — every `DELETE`, plus `config set`, `missions dispatch`,
+ `telephony outbound`, `system restart` — refuse unless you pass `--yes` (or set
+ `JARVIS_CLI_ASSUME_YES=1`). A prompt is not an accepted substitute.
+- `--dry-run` on any command prints the exact request (method, path, body, whether
+ auth is attached) and sends nothing — the safe way to inspect before acting.
+- Secrets are never accepted as inline arguments; they are read from a hidden
+ prompt or stdin and stored in the OS credential store.
+
+## Driving Jarvis from a Claude Code / Codex session
+
+This is a first-class use case. An external coding agent can control your running
+Jarvis end-to-end through its shell:
+
+1. **It's already installed and authenticated.** After `pip install -e .` the
+ `jarvis` binary is on PATH, and local auth is zero-config (session-file
+ discovery). The agent runs `jarvis system status` to confirm Jarvis is up.
+2. **It discovers the surface** with `jarvis --help`, `jarvis <group> --help`, and
+ `jarvis api --help` for the full generated list.
+3. **It reads with `--json`** and parses, and **acts with explicit intent**, using
+ `--dry-run` to preview and `--yes` to authorize destructive actions.
+
+Worked example — switch the brain provider, then dispatch a mission:
+
+```bash
+jarvis --json brain status # see the active provider
+jarvis brain switch openai # reversible → runs immediately
+jarvis brain subagent-switch openai # switch the worker provider too
+jarvis missions dispatch "summarize today's PRs" --yes # destructive → needs --yes
+jarvis --json missions list --state RUNNING # watch it
+```
+
+The `drive-jarvis-cli` skill (in `.claude/skills/`) packages these conventions so
+an agent can pick them up automatically.
+
+## Extending the CLI
+
+When you add a REST route for a new feature, it becomes CLI-reachable
+automatically via the dynamic layer — provided the router is **mounted**. The
+`generate-cli-command` skill is the "definition of done" checklist; the
+`scripts/ci/check_cli_coverage.py` gate fails CI/pre-push if a route module is
+defined but never mounted (an unreachable feature). Run
+`scripts/ci/gen_cli_reference.py` to refresh the reference after adding commands.
diff --git a/jarvis/__main__.py b/jarvis/__main__.py
index 86389afd5d..e80bc20a0c 100644
--- a/jarvis/__main__.py
+++ b/jarvis/__main__.py
@@ -30,7 +30,7 @@ from jarvis.hardware import detection
from jarvis.ui.tray import JarvisState, JarvisTray, TrayCommand
-def _parse_args(argv: list[str]) -> argparse.Namespace:
+def _build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
prog="jarvis",
description="Personal Jarvis — voice-gesteuerter Meta-Orchestrator.",
@@ -64,7 +64,11 @@ def _parse_args(argv: list[str]) -> argparse.Namespace:
help="serve: start the headless web UI (browser/server, no desktop) — "
"the cloud-first path for a VPS, Mac or Linux. Open the printed URL.",
)
- return parser.parse_args(argv)
+ return parser
+
+
+def _parse_args(argv: list[str]) -> argparse.Namespace:
+ return _build_parser().parse_args(argv)
def _cmd_check() -> int:
@@ -336,8 +340,49 @@ async def _run_tray_app(debug: bool = False) -> int:
return 0
+def _run_control(argv: list[str]) -> int:
+ """Forward a control invocation (``jarvis <group> ...``) to the control CLI.
+
+ The control surface is the Typer app in ``jarvis.cli_ctl.__main__`` (also the
+ ``jarvisctl`` / ``jctl`` binaries); routing it through ``jarvis`` gives one
+ brand without disturbing the launcher's own argument parsing. The dynamic
+ ``api`` group build is best-effort, so curated commands still work when the
+ server is down.
+ """
+ import click
+
+ from jarvis.cli_ctl.__main__ import build_root_command
+
+ root = build_root_command()
+ try:
+ rv = root.main(args=argv, prog_name="jarvis", standalone_mode=False)
+ return rv if isinstance(rv, int) else 0
+ except click.exceptions.Exit as exc:
+ return int(getattr(exc, "exit_code", 0) or 0)
+ except click.exceptions.Abort:
+ print("aborted", file=sys.stderr)
+ return 1
+ except click.exceptions.ClickException as exc:
+ exc.show()
+ return exc.exit_code
+ except SystemExit as exc: # e.g. --help / no_args_is_help
+ code = exc.code
+ if code is None:
+ return 0
+ return code if isinstance(code, int) else 1
+
+
def main(argv: list[str] | None = None) -> int:
- args = _parse_args(argv if argv is not None else sys.argv[1:])
+ raw = list(sys.argv[1:] if argv is None else argv)
+ # Unified entry point: `jarvis <group> ...` (or a control-global option like
+ # `--json`) drives the control CLI; bare `jarvis`, `jarvis serve`, and every
+ # launcher flag (`--wizard`, `--check`, …) keep their existing behavior.
+ from jarvis.cli_ctl.reserved import is_control_invocation
+
+ if is_control_invocation(raw):
+ return _run_control(raw)
+
+ args = _parse_args(raw)
if args.check:
return _cmd_check()
diff --git a/jarvis/cli_ctl/__main__.py b/jarvis/cli_ctl/__main__.py
index 9bb0d7b5eb..63b512a287 100644
--- a/jarvis/cli_ctl/__main__.py
+++ b/jarvis/cli_ctl/__main__.py
@@ -19,8 +19,24 @@ from jarvis.cli_ctl import config as _config
from jarvis.cli_ctl import openapi_cache
from jarvis.cli_ctl.client import JarvisClient
from jarvis.cli_ctl.commands import auth as auth_cmd
+from jarvis.cli_ctl.commands import board as board_cmd
+from jarvis.cli_ctl.commands import brain as brain_cmd
+from jarvis.cli_ctl.commands import conductor as conductor_cmd
+from jarvis.cli_ctl.commands import config as config_cmd
+from jarvis.cli_ctl.commands import contacts as contacts_cmd
+from jarvis.cli_ctl.commands import docs as docs_cmd
+from jarvis.cli_ctl.commands import frontier as frontier_cmd
+from jarvis.cli_ctl.commands import marketplace as marketplace_cmd
+from jarvis.cli_ctl.commands import mcps as mcps_cmd
+from jarvis.cli_ctl.commands import missions as missions_cmd
+from jarvis.cli_ctl.commands import outputs as outputs_cmd
+from jarvis.cli_ctl.commands import sessions as sessions_cmd
+from jarvis.cli_ctl.commands import skills as skills_cmd
from jarvis.cli_ctl.commands import system as system_cmd
from jarvis.cli_ctl.commands import tasks as tasks_cmd
+from jarvis.cli_ctl.commands import telephony as telephony_cmd
+from jarvis.cli_ctl.commands import wiki as wiki_cmd
+from jarvis.cli_ctl.commands import workflows as workflows_cmd
app = typer.Typer(
name="jarvisctl",
@@ -30,7 +46,7 @@ app = typer.Typer(
)
# Shared state set by the root callback and read by commands.
-STATE: dict[str, object] = {"json": False}
+STATE: dict[str, object] = {"json": False, "url": None, "key": None}
@app.callback()
@@ -38,9 +54,18 @@ def _root(
json_output: bool = typer.Option(
False, "--json", help="Emit raw JSON instead of human tables."
),
+ url: str | None = typer.Option(
+ None, "--url", help="Override the Jarvis base URL (e.g. http://host:port)."
+ ),
+ key: str | None = typer.Option(
+ None, "--key", hide_input=True,
+ help="Override the control API key (Bearer token) for this call only.",
+ ),
) -> None:
"""jarvisctl — thin HTTP control client for a running Jarvis server."""
STATE["json"] = json_output
+ STATE["url"] = url
+ STATE["key"] = key
def as_json() -> bool:
@@ -48,11 +73,12 @@ def as_json() -> bool:
def make_client(url: str | None = None, key: str | None = None) -> JarvisClient:
- """Build a client from explicit overrides or the resolved profile."""
+ """Build a client from explicit overrides, the ``--url`` / ``--key`` global
+ options, or the resolved profile (env / config / live session / local key)."""
prof = _config.resolve_profile()
return JarvisClient(
- base_url=url or prof.base_url,
- control_key=key or prof.control_key,
+ base_url=url or STATE.get("url") or prof.base_url, # type: ignore[arg-type]
+ control_key=key or STATE.get("key") or prof.control_key, # type: ignore[arg-type]
)
@@ -74,6 +100,22 @@ def refresh() -> None:
app.add_typer(auth_cmd.app, name="auth")
app.add_typer(system_cmd.app, name="system")
app.add_typer(tasks_cmd.app, name="tasks")
+app.add_typer(brain_cmd.app, name="brain")
+app.add_typer(config_cmd.app, name="config")
+app.add_typer(missions_cmd.app, name="missions")
+app.add_typer(wiki_cmd.app, name="wiki")
+app.add_typer(sessions_cmd.app, name="sessions")
+app.add_typer(skills_cmd.app, name="skills")
+app.add_typer(outputs_cmd.app, name="outputs")
+app.add_typer(board_cmd.app, name="board")
+app.add_typer(workflows_cmd.app, name="workflows")
+app.add_typer(conductor_cmd.app, name="conductor")
+app.add_typer(contacts_cmd.app, name="contacts")
+app.add_typer(telephony_cmd.app, name="telephony")
+app.add_typer(marketplace_cmd.app, name="marketplace")
+app.add_typer(mcps_cmd.app, name="mcps")
+app.add_typer(docs_cmd.app, name="docs")
+app.add_typer(frontier_cmd.app, name="frontier")
def _in_completion() -> bool:
diff --git a/jarvis/cli_ctl/client.py b/jarvis/cli_ctl/client.py
index 2b9872a4d8..8f20830ec5 100644
--- a/jarvis/cli_ctl/client.py
+++ b/jarvis/cli_ctl/client.py
@@ -35,6 +35,7 @@ class JarvisClient:
transport=transport,
)
self.base_url = base_url
+ self.has_auth = bool(control_key)
def request(
self,
diff --git a/jarvis/cli_ctl/commands/auth.py b/jarvis/cli_ctl/commands/auth.py
index 9c741dbb65..bab7db6f08 100644
--- a/jarvis/cli_ctl/commands/auth.py
+++ b/jarvis/cli_ctl/commands/auth.py
@@ -26,9 +26,27 @@ def _probe(url: str, key: str) -> bool:
@app.command()
def login(
url: str = typer.Option(..., "--url", help="Base URL, e.g. http://127.0.0.1:47821"),
- key: str = typer.Option(..., "--key", help="Control key (jctl_…)."),
+ key: str = typer.Option(
+ None, "--key",
+ prompt="Control key (jctl_…)",
+ hide_input=True,
+ help="Control key. Omit to be prompted (hidden), or pass '-' to read it "
+ "from stdin. Avoid an inline value — it leaks into shell history.",
+ ),
) -> None:
- """Verify the key against the server and persist it for future calls."""
+ """Verify the key against the server and persist it for future calls.
+
+ The key is read from a hidden prompt by default, or from stdin with
+ ``--key -`` (for CI / agents) — never required as an inline argument that
+ would land in shell history (AP-12 / spec §7.2).
+ """
+ if key == "-":
+ import sys
+
+ key = sys.stdin.readline().strip()
+ if not key:
+ render.error("no control key provided.")
+ raise typer.Exit(code=2)
if not _probe(url, key):
render.error("control key rejected or server unreachable; not saved.")
raise typer.Exit(code=1)
diff --git a/jarvis/cli_ctl/commands/board.py b/jarvis/cli_ctl/commands/board.py
new file mode 100644
index 0000000000..a27a3cf08a
--- /dev/null
+++ b/jarvis/cli_ctl/commands/board.py
@@ -0,0 +1,51 @@
+"""board: the "knows-you" dashboard + profile (/api/board, /api/profile)."""
+
+from __future__ import annotations
+
+import typer
+
+from jarvis.cli_ctl import invoke, options
+
+app = typer.Typer(no_args_is_help=True, help="Personal board: stats, records, achievements, bio.")
+
+
+def summary(window_days: int = typer.Option(30, "--window-days", min=1, max=365)) -> None:
+ """Show personal totals + streaks over a window."""
+ invoke.run("GET", "/api/board/personal/summary", params={"window_days": window_days})
+
+
+def heatmap(days: int = typer.Option(365, "--days", min=7, max=730)) -> None:
+ """Show the activity heatmap cells."""
+ invoke.run("GET", "/api/board/personal/heatmap", params={"days": days})
+
+
+def records() -> None:
+ """Show personal records."""
+ invoke.run("GET", "/api/board/personal/records")
+
+
+def achievements() -> None:
+ """Show unlocked + locked achievements."""
+ invoke.run("GET", "/api/board/achievements")
+
+
+def bio() -> None:
+ """Show the AI-generated bio."""
+ invoke.run("GET", "/api/board/bio")
+
+
[email protected]("bio-regenerate")
+def bio_regenerate(yes: bool = options.yes_opt(), dry_run: bool = options.dry_opt()) -> None:
+ """Regenerate the AI bio."""
+ invoke.run("POST", "/api/board/bio/regenerate", assume_yes=yes, dry_run=dry_run)
+
+
+def profile() -> None:
+ """Show the profile (meta + people + review count)."""
+ invoke.run("GET", "/api/profile")
diff --git a/jarvis/cli_ctl/commands/brain.py b/jarvis/cli_ctl/commands/brain.py
new file mode 100644
index 0000000000..d92421baa4
--- /dev/null
+++ b/jarvis/cli_ctl/commands/brain.py
@@ -0,0 +1,88 @@
+"""brain: inspect and switch the active brain + sub-agent providers.
+
+Flagship example: `jarvis brain switch openai` changes the active main brain
+provider; `jarvis brain subagent-switch openai` changes the worker/sub-agent
+provider (e.g. Codex -> OpenAI). Switches are reversible (config + live), so they
+proceed without --yes; pass --no-persist to apply live-only.
+"""
+from __future__ import annotations
+
+import typer
+
+from jarvis.cli_ctl import invoke, options
+
+app = typer.Typer(
+ no_args_is_help=True,
+ help="Brain providers: status, switch, sub-agent switch, models, test.",
+)
+
+_PROVIDER_HELP = (
+ "Provider id: claude-api | openrouter | openai | gemini | grok | codex | "
+ "antigravity (the server validates the value)."
+)
+
+
+def status() -> None:
+ """Show configured providers and which one is active."""
+ invoke.run("GET", "/api/providers")
+
+
+def list_providers() -> None:
+ """List configured brain providers (alias of status)."""
+ invoke.run("GET", "/api/providers")
+
+
+def switch(
+ provider: str = typer.Argument(..., help=_PROVIDER_HELP),
+ persist: bool = options.persist_opt(),
+ yes: bool = options.yes_opt(),
+ dry_run: bool = options.dry_opt(),
+) -> None:
+ """Switch the ACTIVE main brain provider (e.g. `jarvis brain switch openai`)."""
+ invoke.run(
+ "POST", "/api/brain/switch",
+ body={"provider": provider, "persist": persist},
+ assume_yes=yes, dry_run=dry_run, dangerous=False,
+ )
+
+
[email protected]("subagent-switch")
+def subagent_switch(
+ provider: str = typer.Argument(..., help=_PROVIDER_HELP),
+ persist: bool = options.persist_opt(),
+ yes: bool = options.yes_opt(),
+ dry_run: bool = options.dry_opt(),
+) -> None:
+ """Switch the sub-agent / worker provider (e.g. Codex -> OpenAI)."""
+ invoke.run(
+ "POST", "/api/subagent/switch",
+ body={"provider": provider, "persist": persist},
+ assume_yes=yes, dry_run=dry_run, dangerous=False,
+ )
+
+
+def test(
+ provider: str = typer.Argument(..., help="Provider id to test."),
+ dry_run: bool = options.dry_opt(),
+) -> None:
+ """Test connectivity + auth for a provider."""
+ invoke.run("POST", f"/api/providers/{provider}/test", dry_run=dry_run, dangerous=False)
+
+
[email protected]("deep-model")
+def deep_model(
+ model: str = typer.Argument(..., help="Model id for the sub-agent deep brain."),
+ persist: bool = options.persist_opt(),
+ yes: bool = options.yes_opt(),
+ dry_run: bool = options.dry_opt(),
+) -> None:
+ """Set the sub-agent deep model."""
+ invoke.run(
+ "POST", "/api/subagent/model",
+ body={"model": model, "persist": persist},
+ assume_yes=yes, dry_run=dry_run, dangerous=False,
+ )
diff --git a/jarvis/cli_ctl/commands/conductor.py b/jarvis/cli_ctl/commands/conductor.py
new file mode 100644
index 0000000000..b550aafd7c
--- /dev/null
+++ b/jarvis/cli_ctl/commands/conductor.py
@@ -0,0 +1,81 @@
+"""conductor: YAML-first agentic-workflow jobs (/api/conductor)."""
+
+from __future__ import annotations
+
+import json
+import sys
+
+import typer
+
+from jarvis.cli_ctl import invoke, options, render
+
+app = typer.Typer(
+ no_args_is_help=True, help="Conductor jobs: list, show, add, run, toggle, delete."
+)
+
+
+def list_jobs() -> None:
+ """List Conductor jobs + a run summary."""
+ invoke.run("GET", "/api/conductor/jobs")
+
+
+def show(job_id: str = typer.Argument(...)) -> None:
+ """Show one job + recent runs."""
+ invoke.run("GET", f"/api/conductor/jobs/{job_id}")
+
+
+def add(
+ definition: str = typer.Option(..., "--def", help="Job JSON ('-' reads stdin)."),
+ yes: bool = options.yes_opt(),
+ dry_run: bool = options.dry_opt(),
+) -> None:
+ """Add a job from a Job JSON document."""
+ raw = sys.stdin.read() if definition == "-" else definition
+ try:
+ body = json.loads(raw)
+ except ValueError as exc:
+ render.error(f"--def is not valid JSON: {exc}")
+ raise typer.Exit(code=2) from exc
+ invoke.run("POST", "/api/conductor/jobs", body=body, assume_yes=yes, dry_run=dry_run)
+
+
+def run(
+ job_id: str = typer.Argument(...),
+ yes: bool = options.yes_opt(),
+ dry_run: bool = options.dry_opt(),
+) -> None:
+ """Manually trigger a job run."""
+ invoke.run(
+ "POST", f"/api/conductor/jobs/{job_id}/run", body={}, assume_yes=yes, dry_run=dry_run
+ )
+
+
+def toggle(
+ job_id: str = typer.Argument(...),
+ enabled: bool = typer.Option(..., "--enabled/--disabled"),
+ yes: bool = options.yes_opt(),
+ dry_run: bool = options.dry_opt(),
+) -> None:
+ """Enable or disable a job."""
+ invoke.run(
+ "PATCH",
+ f"/api/conductor/jobs/{job_id}",
+ body={"enabled": enabled},
+ assume_yes=yes,
+ dry_run=dry_run,
+ )
+
+
+def delete(
+ job_id: str = typer.Argument(...),
+ yes: bool = options.yes_opt(),
+ dry_run: bool = options.dry_opt(),
+) -> None:
+ """Delete a job."""
+ invoke.run("DELETE", f"/api/conductor/jobs/{job_id}", assume_yes=yes, dry_run=dry_run)
diff --git a/jarvis/cli_ctl/commands/config.py b/jarvis/cli_ctl/commands/config.py
new file mode 100644
index 0000000000..d2a70dbbba
--- /dev/null
+++ b/jarvis/cli_ctl/commands/config.py
@@ -0,0 +1,83 @@
+"""config: read/write mutable settings (self-mod) + reply language.
+
+`config set` goes through the server's atomic config-write pipeline (allowlist ->
+pre-validate -> backup -> tempfile+replace -> reload-test -> rollback -> audit),
+so the CLI never edits jarvis.toml directly. It is destructive (arbitrary config
+change) and therefore requires --yes.
+"""
+from __future__ import annotations
+
+import json
+
+import typer
+
+from jarvis.cli_ctl import invoke, options
+
+app = typer.Typer(
+ no_args_is_help=True,
+ help="Configuration: get/set mutable settings, list the allowlist, language.",
+)
+language_app = typer.Typer(no_args_is_help=True, help="Reply-language control.")
+app.add_typer(language_app, name="language")
+
+
+def _coerce(value: str) -> object:
+ """Coerce a CLI string to its JSON-native type (true/false/numbers/null),
+ falling back to the raw string. So `config set x.flag true` writes a bool,
+ `config set x.n 5` writes an int, and `config set brain.primary openai`
+ stays a string."""
+ try:
+ return json.loads(value)
+ except (ValueError, TypeError):
+ return value
+
+
+def get(path: str = typer.Argument(..., help="Dotted config path, e.g. brain.primary.")) -> None:
+ """Get a config value by dotted path (control-key gated)."""
+ invoke.run("GET", "/api/control/config", params={"path": path})
+
+
+def list_mutable() -> None:
+ """List the mutable-settings allowlist (path, risk tier, restart needed)."""
+ invoke.run("GET", "/api/control/allowlist")
+
+
+def set_value(
+ path: str = typer.Argument(..., help="Dotted config path, e.g. brain.primary."),
+ value: str = typer.Argument(..., help="New value (JSON-coerced: true/5/\"text\")."),
+ reason: str = typer.Option(None, "--reason", help="Audit note for the change."),
+ yes: bool = options.yes_opt(),
+ dry_run: bool = options.dry_opt(),
+) -> None:
+ """Set a mutable config value via the atomic write pipeline (destructive: --yes)."""
+ body: dict[str, object] = {"path": path, "value": _coerce(value)}
+ if reason:
+ body["reason"] = reason
+ invoke.run(
+ "PUT", "/api/control/config", body=body,
+ assume_yes=yes, dry_run=dry_run, dangerous=True,
+ )
+
+
+@language_app.command("get")
+def language_get() -> None:
+ """Show the current reply language + the available options."""
+ invoke.run("GET", "/api/settings/reply-language")
+
+
+@language_app.command("set")
+def language_set(
+ lang: str = typer.Argument(..., help="auto | de | en | es."),
+ persist: bool = options.persist_opt(),
+ yes: bool = options.yes_opt(),
+ dry_run: bool = options.dry_opt(),
+) -> None:
+ """Set the reply language (hot-reloads, no restart)."""
+ invoke.run(
+ "PUT", "/api/settings/reply-language",
+ body={"language": lang, "persist": persist},
+ assume_yes=yes, dry_run=dry_run, dangerous=False,
+ )
diff --git a/jarvis/cli_ctl/commands/contacts.py b/jarvis/cli_ctl/commands/contacts.py
new file mode 100644
index 0000000000..a721605086
--- /dev/null
+++ b/jarvis/cli_ctl/commands/contacts.py
@@ -0,0 +1,79 @@
+"""contacts: address-book CRUD (/api/contacts).
+
+Placing a call is not a single REST endpoint (it is a brain tool that composes a
+contact's number with telephony); use `jarvis telephony outbound` with a number,
+or the running assistant, to place a call.
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+
+import typer
+
+from jarvis.cli_ctl import invoke, options, render
+
+app = typer.Typer(no_args_is_help=True, help="Contacts: list, show, add, edit, delete.")
+
+
+def list_contacts() -> None:
+ """List contacts."""
+ invoke.run("GET", "/api/contacts")
+
+
+def show(slug: str = typer.Argument(...)) -> None:
+ """Show one contact."""
+ invoke.run("GET", f"/api/contacts/{slug}")
+
+
+def _body_from(json_body: str) -> dict:
+ raw = sys.stdin.read() if json_body == "-" else json_body
+ try:
+ return json.loads(raw)
+ except ValueError as exc:
+ render.error(f"--json-body is not valid JSON: {exc}")
+ raise typer.Exit(code=2) from exc
+
+
+def add(
+ json_body: str = typer.Option(
+ ..., "--json-body", help="Contact JSON ('-' reads stdin): {name, emails?, phones?, ...}."
+ ),
+ yes: bool = options.yes_opt(),
+ dry_run: bool = options.dry_opt(),
+) -> None:
+ """Add a contact."""
+ invoke.run("POST", "/api/contacts", body=_body_from(json_body), assume_yes=yes, dry_run=dry_run)
+
+
+def edit(
+ slug: str = typer.Argument(...),
+ json_body: str = typer.Option(
+ ..., "--json-body", help="Partial contact JSON ('-' reads stdin)."
+ ),
+ yes: bool = options.yes_opt(),
+ dry_run: bool = options.dry_opt(),
+) -> None:
+ """Edit a contact (partial)."""
+ invoke.run(
+ "PATCH",
+ f"/api/contacts/{slug}",
+ body=_body_from(json_body),
+ assume_yes=yes,
+ dry_run=dry_run,
+ )
+
+
+def delete(
+ slug: str = typer.Argument(...),
+ yes: bool = options.yes_opt(),
+ dry_run: bool = options.dry_opt(),
+) -> None:
+ """Delete a contact."""
+ invoke.run("DELETE", f"/api/contacts/{slug}", assume_yes=yes, dry_run=dry_run)
diff --git a/jarvis/cli_ctl/commands/docs.py b/jarvis/cli_ctl/commands/docs.py
new file mode 100644
index 0000000000..1c8ba70bc4
--- /dev/null
+++ b/jarvis/cli_ctl/commands/docs.py
@@ -0,0 +1,33 @@
+"""docs: browse the in-app documentation (/api/docs)."""
+
+from __future__ import annotations
+
+import typer
+
+from jarvis.cli_ctl import invoke
+
+app = typer.Typer(no_args_is_help=True, help="Documentation: list, tree, search, show.")
+
+
+def list_docs() -> None:
+ """List documentation pages."""
+ invoke.run("GET", "/api/docs")
+
+
+def tree() -> None:
+ """Show the Diataxis-grouped doc tree."""
+ invoke.run("GET", "/api/docs/grouped")
+
+
+def search(query: str = typer.Argument(...)) -> None:
+ """Search the docs."""
+ invoke.run("GET", "/api/docs/search", params={"q": query})
+
+
+def show(slug: str = typer.Argument(...)) -> None:
+ """Show one doc page's body."""
+ invoke.run("GET", f"/api/docs/{slug}")
diff --git a/jarvis/cli_ctl/commands/frontier.py b/jarvis/cli_ctl/commands/frontier.py
new file mode 100644
index 0000000000..00fcad1512
--- /dev/null
+++ b/jarvis/cli_ctl/commands/frontier.py
@@ -0,0 +1,21 @@
+"""frontier: review + acknowledge proposed model upgrades (/api/frontier)."""
+
+from __future__ import annotations
+
+import typer
+
+from jarvis.cli_ctl import invoke, options
+
+app = typer.Typer(no_args_is_help=True, help="Frontier model auto-switch: pending, ack.")
+
+
+def pending() -> None:
+ """List proposed model upgrades awaiting acknowledgement."""
+ invoke.run("GET", "/api/frontier/pending")
+
+
+def ack(yes: bool = options.yes_opt(), dry_run: bool = options.dry_opt()) -> None:
+ """Acknowledge (dismiss) the pending frontier proposals."""
+ invoke.run("POST", "/api/frontier/ack", assume_yes=yes, dry_run=dry_run)
diff --git a/jarvis/cli_ctl/commands/marketplace.py b/jarvis/cli_ctl/commands/marketplace.py
new file mode 100644
index 0000000000..5e586dd7ea
--- /dev/null
+++ b/jarvis/cli_ctl/commands/marketplace.py
@@ -0,0 +1,70 @@
+"""marketplace: connect/disconnect marketplace plugins (/api/marketplace)."""
+
+from __future__ import annotations
+
+import typer
+
+from jarvis.cli_ctl import invoke, options
+
+app = typer.Typer(no_args_is_help=True, help="Marketplace plugins: list, connect, disconnect.")
+
+
+def list_plugins() -> None:
+ """List marketplace plugins + their connection status."""
+ invoke.run("GET", "/api/marketplace/plugins")
+
+
[email protected]("connect-pat")
+def connect_pat(
+ plugin_id: str = typer.Argument(...),
+ token: str = typer.Option(
+ ...,
+ "--token",
+ prompt="Personal access token",
+ hide_input=True,
+ help="PAT (read from a hidden prompt unless passed; avoid inline).",
+ ),
+ yes: bool = options.yes_opt(),
+ dry_run: bool = options.dry_opt(),
+) -> None:
+ """Connect a plugin with a personal access token."""
+ invoke.run(
+ "POST",
+ f"/api/marketplace/plugins/{plugin_id}/connect/pat",
+ body={"token": token},
+ assume_yes=yes,
+ dry_run=dry_run,
+ )
+
+
[email protected]("connect-start")
+def connect_start(
+ plugin_id: str = typer.Argument(...),
+ yes: bool = options.yes_opt(),
+ dry_run: bool = options.dry_opt(),
+) -> None:
+ """Begin an OAuth connect flow (prints the redirect URI + flow id)."""
+ invoke.run(
+ "POST",
+ f"/api/marketplace/plugins/{plugin_id}/connect/start",
+ body={},
+ assume_yes=yes,
+ dry_run=dry_run,
+ )
+
+
[email protected]("connect-poll")
+def connect_poll(plugin_id: str = typer.Argument(...), flow_id: str = typer.Argument(...)) -> None:
+ """Poll an in-progress OAuth connect flow."""
+ invoke.run("GET", f"/api/marketplace/plugins/{plugin_id}/connect/poll/{flow_id}")
+
+
+def disconnect(
+ plugin_id: str = typer.Argument(...),
+ yes: bool = options.yes_opt(),
+ dry_run: bool = options.dry_opt(),
+) -> None:
+ """Disconnect a plugin."""
+ invoke.run("DELETE", f"/api/marketplace/plugins/{plugin_id}", assume_yes=yes, dry_run=dry_run)
diff --git a/jarvis/cli_ctl/commands/mcps.py b/jarvis/cli_ctl/commands/mcps.py
new file mode 100644
index 0000000000..35788b9514
--- /dev/null
+++ b/jarvis/cli_ctl/commands/mcps.py
@@ -0,0 +1,61 @@
+"""mcps: manage MCP servers (/api/mcps)."""
+
+from __future__ import annotations
+
+import typer
+
+from jarvis.cli_ctl import invoke, options
+
+app = typer.Typer(no_args_is_help=True, help="MCP servers: list, enable, disable, check, delete.")
+
+
+def list_servers() -> None:
+ """List MCP servers + a summary."""
+ invoke.run("GET", "/api/mcps")
+
+
+def enable(
+ name: str = typer.Argument(...),
+ yes: bool = options.yes_opt(),
+ dry_run: bool = options.dry_opt(),
+) -> None:
+ """Enable an MCP server."""
+ invoke.run("POST", f"/api/mcps/{name}/enable", assume_yes=yes, dry_run=dry_run)
+
+
+def disable(
+ name: str = typer.Argument(...),
+ yes: bool = options.yes_opt(),
+ dry_run: bool = options.dry_opt(),
+) -> None:
+ """Disable an MCP server."""
+ invoke.run("POST", f"/api/mcps/{name}/disable", assume_yes=yes, dry_run=dry_run)
+
+
+def check(
+ name: str = typer.Argument(...),
+ yes: bool = options.yes_opt(),
+ dry_run: bool = options.dry_opt(),
+) -> None:
+ """Health-check an MCP server (lists its tools)."""
+ invoke.run("POST", f"/api/mcps/{name}/check", assume_yes=yes, dry_run=dry_run)
+
+
[email protected]("import-claude-desktop")
+def import_claude_desktop(yes: bool = options.yes_opt(), dry_run: bool = options.dry_opt()) -> None:
+ """Import MCP servers from the Claude Desktop config."""
+ invoke.run("POST", "/api/mcps/import-claude-desktop", assume_yes=yes, dry_run=dry_run)
+
+
+def delete(
+ name: str = typer.Argument(...),
+ yes: bool = options.yes_opt(),
+ dry_run: bool = options.dry_opt(),
+) -> None:
+ """Remove an MCP server."""
+ invoke.run("DELETE", f"/api/mcps/{name}", assume_yes=yes, dry_run=dry_run)
diff --git a/jarvis/cli_ctl/commands/missions.py b/jarvis/cli_ctl/commands/missions.py
new file mode 100644
index 0000000000..92457c1d85
--- /dev/null
+++ b/jarvis/cli_ctl/commands/missions.py
@@ -0,0 +1,89 @@
+"""missions: drive Phase-6 self-healing missions (/api/missions)."""
+from __future__ import annotations
+
+import typer
+
+from jarvis.cli_ctl import invoke, options
+
+app = typer.Typer(no_args_is_help=True, help="Self-healing missions: list, dispatch, control.")
+
+
+def list_missions(
+ state: str = typer.Option(
+ None, "--state",
+ help="Comma-separated states: PENDING,RUNNING,APPROVED,FAILED,CANCELLED,TIMED_OUT.",
+ ),
+ limit: int = typer.Option(100, "--limit"),
+) -> None:
+ """List missions (optionally filtered by state)."""
+ params: dict[str, object] = {"limit": limit}
+ if state:
+ params["state"] = state
+ invoke.run("GET", "/api/missions", params=params)
+
+
+def show(mission_id: str = typer.Argument(..., help="Mission id.")) -> None:
+ """Show one mission with its events + verdicts."""
+ invoke.run("GET", f"/api/missions/{mission_id}")
+
+
+def dispatch(
+ prompt: str = typer.Argument(..., help="The task for the worker."),
+ language: str = typer.Option("en", "--language", help="de | en (voice readback language)."),
+ confirmed: bool = typer.Option(
+ False, "--confirmed",
+ help="Pre-confirm a task the server flags destructive (skip the 409 gate).",
+ ),
+ yes: bool = options.yes_opt(),
+ dry_run: bool = options.dry_opt(),
+) -> None:
+ """Dispatch a new self-healing mission — spawns a worker (destructive: --yes)."""
+ invoke.run(
+ "POST", "/api/missions/dispatch",
+ body={"prompt": prompt, "language": language, "confirmed": confirmed},
+ assume_yes=yes, dry_run=dry_run, dangerous=True,
+ )
+
+
+def cancel(
+ mission_id: str = typer.Argument(...),
+ yes: bool = options.yes_opt(),
+ dry_run: bool = options.dry_opt(),
+) -> None:
+ """Cancel a running mission (kills its worker)."""
+ invoke.run(
+ "POST", f"/api/missions/{mission_id}/cancel",
+ assume_yes=yes, dry_run=dry_run, dangerous=True,
+ )
+
+
+def rerun(
+ mission_id: str = typer.Argument(...),
+ confirmed: bool = typer.Option(False, "--confirmed", help="Confirm a destructive re-run."),
+ yes: bool = options.yes_opt(),
+ dry_run: bool = options.dry_opt(),
+) -> None:
+ """Re-dispatch a terminal mission's prompt as a new linked mission."""
+ invoke.run(
+ "POST", f"/api/missions/{mission_id}/rerun",
+ body={"confirmed": confirmed},
+ assume_yes=yes, dry_run=dry_run, dangerous=True,
+ )
+
+
+def kill(
+ worker_id: str = typer.Argument(..., help="Worker id (from the mission events)."),
+ yes: bool = options.yes_opt(),
+ dry_run: bool = options.dry_opt(),
+) -> None:
+ """Hard-kill a worker process by id."""
+ invoke.run(
+ "POST", f"/api/missions/kill/{worker_id}",
+ assume_yes=yes, dry_run=dry_run, dangerous=True,
+ )
diff --git a/jarvis/cli_ctl/commands/outputs.py b/jarvis/cli_ctl/commands/outputs.py
new file mode 100644
index 0000000000..e09f4c3662
--- /dev/null
+++ b/jarvis/cli_ctl/commands/outputs.py
@@ -0,0 +1,70 @@
+"""outputs: browse mission deliverables / artifacts (/api/outputs)."""
+
+from __future__ import annotations
+
+import typer
+
+from jarvis.cli_ctl import invoke, options
+
+app = typer.Typer(no_args_is_help=True, help="Mission deliverables: list, files, open.")
+
+
+def list_outputs() -> None:
+ """List output sessions (a mission's deliverable folders)."""
+ invoke.run("GET", "/api/outputs")
+
+
+def plan(slug: str = typer.Argument(...)) -> None:
+ """Show a session's plan + steps."""
+ invoke.run("GET", f"/api/outputs/{slug}/plan")
+
+
+def files(slug: str = typer.Argument(...)) -> None:
+ """List the artifacts a mission produced."""
+ invoke.run("GET", f"/api/outputs/{slug}/artifacts")
+
+
+def openers() -> None:
+ """List installed editors/apps that can open an artifact."""
+ invoke.run("GET", "/api/outputs/openers")
+
+
[email protected]("open-with")
+def open_with(
+ slug: str = typer.Argument(...),
+ path: str = typer.Argument(..., help="Artifact path within the session."),
+ opener: str = typer.Option(..., "--opener", help="Opener id from `outputs openers`."),
+ yes: bool = options.yes_opt(),
+ dry_run: bool = options.dry_opt(),
+) -> None:
+ """Open an artifact with a chosen editor (desktop only)."""
+ invoke.run(
+ "POST",
+ f"/api/outputs/{slug}/files/{path}/open-with",
+ body={"opener": opener},
+ assume_yes=yes,
+ dry_run=dry_run,
+ )
+
+
[email protected]("preferred-opener")
+def preferred_opener(
+ opener: str = typer.Argument(None, help="Set the default opener; omit to read it."),
+ yes: bool = options.yes_opt(),
+ dry_run: bool = options.dry_opt(),
+) -> None:
+ """Get or set the default artifact opener."""
+ if opener is None:
+ invoke.run("GET", "/api/outputs/preferred-opener")
+ else:
+ invoke.run(
+ "PUT",
+ "/api/outputs/preferred-opener",
+ body={"opener": opener},
+ assume_yes=yes,
+ dry_run=dry_run,
+ )
diff --git a/jarvis/cli_ctl/commands/sessions.py b/jarvis/cli_ctl/commands/sessions.py
new file mode 100644
index 0000000000..b1984dbfef
--- /dev/null
+++ b/jarvis/cli_ctl/commands/sessions.py
@@ -0,0 +1,71 @@
+"""sessions: browse + manage conversation history (/api/chats).
+
+The unified history merges text threads and voice sessions; most commands take a
+`kind` (text | voice) plus the id, mirroring /api/chats/{kind}/{id}.
+"""
+from __future__ import annotations
+
+import typer
+
+from jarvis.cli_ctl import invoke, options
+
+app = typer.Typer(no_args_is_help=True, help="Conversation history: list, show, manage.")
+
+
+def list_sessions(
+ days: int = typer.Option(0, "--days", help="Only sessions from the last N days (0 = all)."),
+ limit: int = typer.Option(200, "--limit"),
+) -> None:
+ """List text + voice sessions, newest first."""
+ invoke.run("GET", "/api/chats", params={"days": days, "limit": limit})
+
+
+def show(
+ kind: str = typer.Argument(..., help="text | voice."),
+ session_id: str = typer.Argument(...),
+) -> None:
+ """Show one conversation with its messages."""
+ invoke.run("GET", f"/api/chats/{kind}/{session_id}")
+
+
+def delete(
+ session_id: str = typer.Argument(..., help="Text-thread id (voice is retention-managed)."),
+ yes: bool = options.yes_opt(),
+ dry_run: bool = options.dry_opt(),
+) -> None:
+ """Delete a text conversation thread."""
+ invoke.run(
+ "DELETE", f"/api/chats/text/{session_id}",
+ assume_yes=yes, dry_run=dry_run, dangerous=True,
+ )
+
+
+def resume(
+ kind: str = typer.Argument(..., help="text | voice."),
+ session_id: str = typer.Argument(...),
+ yes: bool = options.yes_opt(),
+ dry_run: bool = options.dry_opt(),
+) -> None:
+ """Seed the brain from a past conversation to continue it in text."""
+ invoke.run(
+ "POST", f"/api/chats/{kind}/{session_id}/resume",
+ assume_yes=yes, dry_run=dry_run, dangerous=False,
+ )
+
+
+def speak(
+ kind: str = typer.Argument(..., help="text | voice."),
+ session_id: str = typer.Argument(...),
+ yes: bool = options.yes_opt(),
+ dry_run: bool = options.dry_opt(),
+) -> None:
+ """Start a voice session seeded from a past conversation (503 on headless)."""
+ invoke.run(
+ "POST", f"/api/chats/{kind}/{session_id}/speak",
+ assume_yes=yes, dry_run=dry_run, dangerous=False,
+ )
diff --git a/jarvis/cli_ctl/commands/skills.py b/jarvis/cli_ctl/commands/skills.py
new file mode 100644
index 0000000000..9cd34ecc5b
--- /dev/null
+++ b/jarvis/cli_ctl/commands/skills.py
@@ -0,0 +1,107 @@
+"""skills: inspect, author, and manage skills (/api/skills)."""
+
+from __future__ import annotations
+
+import json
+import sys
+
+import typer
+
+from jarvis.cli_ctl import invoke, options, render
+
+app = typer.Typer(no_args_is_help=True, help="Skills: list, author, enable/disable, catalog.")
+
+
+def list_skills() -> None:
+ """List all discovered skills."""
+ invoke.run("GET", "/api/skills")
+
+
+def show(name: str = typer.Argument(...)) -> None:
+ """Show one skill's detail."""
+ invoke.run("GET", f"/api/skills/{name}")
+
+
+def draft(
+ intent: str = typer.Argument(..., help="What the skill should do."),
+ name_hint: str = typer.Option(None, "--name-hint"),
+ category: str = typer.Option(None, "--category"),
+ yes: bool = options.yes_opt(),
+ dry_run: bool = options.dry_opt(),
+) -> None:
+ """Generate a skill draft from an intent (AI author; lands as state=draft)."""
+ body: dict[str, object] = {"intent": intent}
+ if name_hint:
+ body["name_hint"] = name_hint
+ if category:
+ body["category"] = category
+ invoke.run("POST", "/api/skills/creator/draft", body=body, assume_yes=yes, dry_run=dry_run)
+
+
+def commit(
+ draft_json: str = typer.Option(..., "--draft", help="Draft JSON ('-' reads stdin)."),
+ yes: bool = options.yes_opt(),
+ dry_run: bool = options.dry_opt(),
+) -> None:
+ """Commit a generated draft to disk (still state=draft until enabled)."""
+ raw = sys.stdin.read() if draft_json == "-" else draft_json
+ try:
+ draft = json.loads(raw)
+ except ValueError as exc:
+ render.error(f"--draft is not valid JSON: {exc}")
+ raise typer.Exit(code=2) from exc
+ invoke.run(
+ "POST", "/api/skills/creator/commit", body={"draft": draft}, assume_yes=yes, dry_run=dry_run
+ )
+
+
+def enable(
+ name: str = typer.Argument(...),
+ yes: bool = options.yes_opt(),
+ dry_run: bool = options.dry_opt(),
+) -> None:
+ """Activate a skill."""
+ invoke.run("POST", f"/api/skills/{name}/enable", assume_yes=yes, dry_run=dry_run)
+
+
+def disable(
+ name: str = typer.Argument(...),
+ yes: bool = options.yes_opt(),
+ dry_run: bool = options.dry_opt(),
+) -> None:
+ """Deactivate a skill."""
+ invoke.run("POST", f"/api/skills/{name}/disable", assume_yes=yes, dry_run=dry_run)
+
+
+def reload(yes: bool = options.yes_opt(), dry_run: bool = options.dry_opt()) -> None:
+ """Re-scan the skills directory."""
+ invoke.run("POST", "/api/skills/reload", assume_yes=yes, dry_run=dry_run)
+
+
[email protected]("catalog-search")
+def catalog_search(query: str = typer.Argument(...)) -> None:
+ """Search the installable skill catalog."""
+ invoke.run("POST", "/api/skills/catalog/search", body={"query": query})
+
+
[email protected]("catalog-install")
+def catalog_install(
+ name: str = typer.Argument(...),
+ source_url: str = typer.Option(..., "--source-url"),
+ title: str = typer.Option(..., "--title"),
+ raw_url: str = typer.Option(None, "--raw-url"),
+ yes: bool = options.yes_opt(),
+ dry_run: bool = options.dry_opt(),
+) -> None:
+ """Install a skill from the catalog (lands as a draft)."""
+ body: dict[str, object] = {"name": name, "source_url": source_url, "title": title}
+ if raw_url:
+ body["raw_url"] = raw_url
+ invoke.run("POST", "/api/skills/catalog/install", body=body, assume_yes=yes, dry_run=dry_run)
diff --git a/jarvis/cli_ctl/commands/system.py b/jarvis/cli_ctl/commands/system.py
index fb049515a0..5c095fdfce 100644
--- a/jarvis/cli_ctl/commands/system.py
+++ b/jarvis/cli_ctl/commands/system.py
@@ -17,6 +17,12 @@ def restart(
"-f",
help="Restart even while missions are running (this kills them).",
),
+ yes: bool = typer.Option(
+ False, "--yes", "-y", help="Authorize the restart without a prompt."
+ ),
+ dry_run: bool = typer.Option(
+ False, "--dry-run", help="Print the request and exit without restarting."
+ ),
) -> None:
"""Cleanly restart the desktop app (POST /api/settings/restart-app).
@@ -26,8 +32,15 @@ def restart(
A restart kills every in-flight mission, so the server refuses (HTTP 409)
while missions run and lists them; pass ``--force`` to restart anyway.
"""
+ from jarvis.cli_ctl import safety
from jarvis.cli_ctl.__main__ import as_json, make_client
+ if not safety.gate_request(
+ "POST", "/api/settings/restart-app",
+ assume_yes=yes, dry_run=dry_run, as_json=as_json(),
+ ):
+ return # dry run: preview already printed, nothing sent
+
try:
with make_client() as client:
out = client.request(
diff --git a/jarvis/cli_ctl/commands/tasks.py b/jarvis/cli_ctl/commands/tasks.py
index 10f0400b4f..828cdf1976 100644
--- a/jarvis/cli_ctl/commands/tasks.py
+++ b/jarvis/cli_ctl/commands/tasks.py
@@ -6,22 +6,12 @@ import sys
import typer
-from jarvis.cli_ctl import render
-from jarvis.cli_ctl.client import ApiError
+from jarvis.cli_ctl import invoke, render
app = typer.Typer(no_args_is_help=True, help="Inspect and manage scheduled tasks.")
-
-def _run(method: str, path: str, *, params=None, body=None):
- from jarvis.cli_ctl.__main__ import as_json, make_client
-
- try:
- with make_client() as client:
- out = client.request(method, path, params=params, json=body)
- except ApiError as exc:
- render.error(exc.message)
- raise typer.Exit(code=1) from exc
- render.emit(out, as_json=as_json())
+_YES = typer.Option(False, "--yes", "-y", help="Authorize the mutation without a prompt.")
+_DRY = typer.Option(False, "--dry-run", help="Print the request and exit without sending.")
@app.command("list")
@@ -30,16 +20,16 @@ def list_tasks(
limit: int = typer.Option(100, "--limit"),
) -> None:
"""List tasks (optionally filtered by state)."""
- params = {"limit": limit}
+ params: dict[str, object] = {"limit": limit}
if state:
params["state"] = state
- _run("GET", "/api/tasks", params=params)
+ invoke.run("GET", "/api/tasks", params=params)
@app.command()
def get(task_id: str = typer.Argument(..., help="Task id.")) -> None:
"""Show one task with its step timeline."""
- _run("GET", f"/api/tasks/{task_id}")
+ invoke.run("GET", f"/api/tasks/{task_id}")
@app.command()
@@ -48,6 +38,8 @@ def create(
..., "--json-body",
help="TaskSpec as JSON (use '-' to read from stdin).",
),
+ yes: bool = _YES,
+ dry_run: bool = _DRY,
) -> None:
"""Create + schedule a task from a TaskSpec JSON document.
@@ -64,16 +56,24 @@ def create(
except ValueError as exc:
render.error(f"--json-body is not valid JSON: {exc}")
raise typer.Exit(code=2) from exc
- _run("POST", "/api/tasks", body=spec)
+ invoke.run("POST", "/api/tasks", body=spec, assume_yes=yes, dry_run=dry_run)
@app.command()
-def cancel(task_id: str = typer.Argument(...)) -> None:
+def cancel(
+ task_id: str = typer.Argument(...),
+ yes: bool = _YES,
+ dry_run: bool = _DRY,
+) -> None:
"""Soft-cancel a scheduled/running task."""
- _run("POST", f"/api/tasks/{task_id}/cancel")
+ invoke.run("POST", f"/api/tasks/{task_id}/cancel", assume_yes=yes, dry_run=dry_run)
@app.command()
-def delete(task_id: str = typer.Argument(...)) -> None:
+def delete(
+ task_id: str = typer.Argument(...),
+ yes: bool = _YES,
+ dry_run: bool = _DRY,
+) -> None:
"""Hard-delete a task (terminal states only, server-enforced)."""
- _run("DELETE", f"/api/tasks/{task_id}")
+ invoke.run("DELETE", f"/api/tasks/{task_id}", assume_yes=yes, dry_run=dry_run)
diff --git a/jarvis/cli_ctl/commands/telephony.py b/jarvis/cli_ctl/commands/telephony.py
new file mode 100644
index 0000000000..01756e4bc5
--- /dev/null
+++ b/jarvis/cli_ctl/commands/telephony.py
@@ -0,0 +1,42 @@
+"""telephony: outbound calling status + placing calls (/api/telephony)."""
+
+from __future__ import annotations
+
+import typer
+
+from jarvis.cli_ctl import invoke, options
+
+app = typer.Typer(no_args_is_help=True, help="Telephony: status, config, place outbound calls.")
+
+
+def status() -> None:
+ """Report telephony availability/status."""
+ invoke.run("GET", "/api/telephony/status")
+
+
+def config_get() -> None:
+ """Show the telephony config."""
+ invoke.run("GET", "/api/telephony/config")
+
+
+def outbound(
+ to: str = typer.Argument(..., help="Destination phone number (E.164)."),
+ message: str = typer.Option(None, "--message", help="Spoken message / script."),
+ yes: bool = options.yes_opt(),
+ dry_run: bool = options.dry_opt(),
+) -> None:
+ """Place a real outbound call (destructive: costs money; needs --yes)."""
+ body: dict[str, object] = {"to": to}
+ if message:
+ body["message"] = message
+ invoke.run(
+ "POST",
+ "/api/telephony/outbound",
+ body=body,
+ assume_yes=yes,
+ dry_run=dry_run,
+ dangerous=True,
+ )
diff --git a/jarvis/cli_ctl/commands/wiki.py b/jarvis/cli_ctl/commands/wiki.py
new file mode 100644
index 0000000000..8cc0a3d49d
--- /dev/null
+++ b/jarvis/cli_ctl/commands/wiki.py
@@ -0,0 +1,31 @@
+"""wiki: search and read the knowledge wiki (/api/wiki).
+
+Note: deterministic save-fact (wiki-ingest) is a brain-tool, not a REST
+endpoint, so it has no curated command here — use the running assistant for
+ingestion. Search and read are exposed.
+"""
+from __future__ import annotations
+
+import typer
+
+from jarvis.cli_ctl import invoke
+
+app = typer.Typer(no_args_is_help=True, help="Knowledge wiki: recall, page, tree.")
+
+
+def recall(query: str = typer.Argument(..., help="Search query.")) -> None:
+ """Full-text search the wiki."""
+ invoke.run("GET", "/api/wiki/search", params={"q": query})
+
+
+def page(slug: str = typer.Argument(..., help="Vault path / slug, e.g. people/jane.")) -> None:
+ """Read a wiki page by vault path / slug."""
+ invoke.run("GET", f"/api/wiki/page/{slug}")
+
+
+def tree() -> None:
+ """Show the vault folder tree + stats."""
+ invoke.run("GET", "/api/wiki/tree")
diff --git a/jarvis/cli_ctl/commands/workflows.py b/jarvis/cli_ctl/commands/workflows.py
new file mode 100644
index 0000000000..cf3887ca2a
--- /dev/null
+++ b/jarvis/cli_ctl/commands/workflows.py
@@ -0,0 +1,69 @@
+"""workflows: imperative multi-step pipelines (/api/workflows)."""
+
+from __future__ import annotations
+
+import json
+import sys
+
+import typer
+
+from jarvis.cli_ctl import invoke, options, render
+
+app = typer.Typer(no_args_is_help=True, help="Workflows: list, show, create, run, delete.")
+
+
+def list_workflows() -> None:
+ """List workflows + a run summary."""
+ invoke.run("GET", "/api/workflows")
+
+
+def show(workflow_id: str = typer.Argument(...)) -> None:
+ """Show one workflow + recent runs."""
+ invoke.run("GET", f"/api/workflows/{workflow_id}")
+
+
+def create(
+ definition: str = typer.Option(..., "--def", help="WorkflowDef JSON ('-' reads stdin)."),
+ yes: bool = options.yes_opt(),
+ dry_run: bool = options.dry_opt(),
+) -> None:
+ """Create a workflow from a WorkflowDef JSON document."""
+ raw = sys.stdin.read() if definition == "-" else definition
+ try:
+ body = json.loads(raw)
+ except ValueError as exc:
+ render.error(f"--def is not valid JSON: {exc}")
+ raise typer.Exit(code=2) from exc
+ invoke.run("POST", "/api/workflows", body=body, assume_yes=yes, dry_run=dry_run)
+
+
+def run(
+ workflow_id: str = typer.Argument(...),
+ yes: bool = options.yes_opt(),
+ dry_run: bool = options.dry_opt(),
+) -> None:
+ """Trigger a workflow run."""
+ invoke.run(
+ "POST", f"/api/workflows/{workflow_id}/run", body={}, assume_yes=yes, dry_run=dry_run
+ )
+
+
+def delete(
+ workflow_id: str = typer.Argument(...),
+ yes: bool = options.yes_opt(),
+ dry_run: bool = options.dry_opt(),
+) -> None:
+ """Delete a workflow."""
+ invoke.run("DELETE", f"/api/workflows/{workflow_id}", assume_yes=yes, dry_run=dry_run)
+
+
[email protected]("run-history")
+def run_history(workflow_id: str = typer.Option(None, "--workflow-id")) -> None:
+ """List workflow runs (optionally for one workflow)."""
+ params = {"workflow_id": workflow_id} if workflow_id else None
+ invoke.run("GET", "/api/workflows/runs/", params=params)
diff --git a/jarvis/cli_ctl/config.py b/jarvis/cli_ctl/config.py
index 5a43e4a393..c34132ccd4 100644
--- a/jarvis/cli_ctl/config.py
+++ b/jarvis/cli_ctl/config.py
@@ -1,11 +1,14 @@
"""Resolve which Jarvis to talk to and how to authenticate.
A 'profile' is a (base_url, control_key) pair. Resolution is per-field:
- base_url: JARVISCTL_BASE_URL -> config.json -> default loopback:47821
- control_key: JARVISCTL_CONTROL_KEY -> config.json -> jarvis.core.control_key
-The local control_key fallback only helps when the CLI runs on the same
-machine/venv as the server (desktop). For a remote VPS, `auth login` writes
-the remote key into config.json.
+ base_url: JARVISCTL_BASE_URL -> config.json -> live session file -> default
+ control_key: JARVISCTL_CONTROL_KEY -> config.json -> live session file ->
+ jarvis.core.control_key
+The live session file (written by the running desktop app, see
+``jarvis.cli_ctl.discovery``) gives zero-config discovery of a locally running
+instance even on a non-default port. The local control_key fallback only helps
+when the CLI runs on the same machine/venv as the server (desktop). For a remote
+VPS, `auth login` writes the remote key into config.json.
"""
from __future__ import annotations
@@ -13,7 +16,7 @@ import json
import os
from dataclasses import dataclass
-from jarvis.cli_ctl import paths
+from jarvis.cli_ctl import discovery, paths
DEFAULT_BASE_URL = "http://127.0.0.1:47821"
@@ -47,14 +50,17 @@ def _local_control_key() -> str | None:
def resolve_profile() -> Profile:
data = _load_file()
+ session = discovery.discover() # None when no live instance is found
base_url = (
os.environ.get("JARVISCTL_BASE_URL")
or data.get("base_url")
+ or (session.base_url if session else None)
or DEFAULT_BASE_URL
)
resolved_key = (
os.environ.get("JARVISCTL_CONTROL_KEY")
or data.get("control_key")
+ or (session.token if session else None)
or _local_control_key()
)
return Profile(base_url=base_url, control_key=resolved_key)
diff --git a/jarvis/cli_ctl/discovery.py b/jarvis/cli_ctl/discovery.py
new file mode 100644
index 0000000000..8960e7aa42
--- /dev/null
+++ b/jarvis/cli_ctl/discovery.py
@@ -0,0 +1,127 @@
+"""Discover a locally running Jarvis instance from its single-instance session file.
+
+The desktop app's ``SingleInstance`` writes ``{port, token, pid}`` to
+``<user-app-dir>/session.json`` while it runs (authoritative writer:
+``jarvis/ui/shell/single_instance.py``). A CLI on the same machine can read it to
+reach the live server with zero configuration — even when the server bound a
+non-default ``admin_api_port``.
+
+This module is intentionally decoupled from the UI shell at runtime: it only
+imports ``jarvis.core.paths`` (a base-install module) to locate the per-user app
+directory, and never pulls in any desktop/UI dependency. A parity test
+(``tests/unit/cli_ctl/test_discovery.py``) guards the filename and directory
+against drift from the authoritative writer.
+
+Liveness: a clean shutdown removes the session file, so a leftover file means the
+process crashed. ``discover()`` best-effort verifies the recorded PID is still
+alive and ignores a stale file, so the CLI does not point at a recycled port.
+When the PID check cannot reach a verdict it errs toward "alive" — the worst case
+is then a clean ``unreachable`` error from the HTTP client, never a silent wrong
+target.
+"""
+from __future__ import annotations
+
+import json
+import os
+import sys
+from dataclasses import dataclass
+from pathlib import Path
+
+# Authoritative writer constant lives in jarvis/ui/shell/single_instance.py
+# (SESSION_FILENAME). Kept as a local literal to avoid importing the UI layer;
+# test_discovery.py asserts the two never drift.
+SESSION_FILENAME = "session.json"
+
+
+@dataclass(frozen=True)
+class SessionInfo:
+ """A discovered running instance: where it listens and how to authenticate."""
+
+ base_url: str
+ token: str | None
+ pid: int | None
+
+
+def session_file() -> Path | None:
+ """Return the path to the running instance's session file, or None.
+
+ A ``JARVIS_CLI_SESSION_FILE`` override pins the path directly (tests point it
+ at a temp file; an empty value disables discovery). Otherwise the canonical
+ per-user app directory is used; None when it cannot be resolved (e.g. the
+ server package is unavailable in a minimal install)."""
+ override = os.environ.get("JARVIS_CLI_SESSION_FILE")
+ if override is not None:
+ return Path(override) if override else None
+ try:
+ from jarvis.core.paths import ensure_user_dirs
+
+ return ensure_user_dirs() / SESSION_FILENAME
+ except Exception: # pragma: no cover - defensive: never break the CLI
+ return None
+
+
+def _pid_alive(pid: int) -> bool:
+ """Best-effort cross-platform liveness check for ``pid``.
+
+ Errs toward True when a definitive verdict is unavailable, because the only
+ cost of a false "alive" is a clean transport error downstream, whereas a
+ false "dead" would needlessly discard a valid live target.
+ """
+ if pid <= 0:
+ return False
+ if sys.platform == "win32":
+ try:
+ import ctypes
+
+ # PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
+ kernel32 = ctypes.windll.kernel32
+ handle = kernel32.OpenProcess(0x1000, False, int(pid))
+ if handle:
+ kernel32.CloseHandle(handle)
+ return True
+ # ERROR_INVALID_PARAMETER (87) => no such process; anything else
+ # (e.g. ERROR_ACCESS_DENIED 5) means the process exists.
+ return kernel32.GetLastError() != 87
+ except Exception: # pragma: no cover - probe must never raise
+ return True
+ try:
+ os.kill(int(pid), 0)
+ except ProcessLookupError:
+ return False
+ except PermissionError:
+ return True
+ except OSError:
+ return True
+ return True
+
+
+def discover(*, check_pid: bool = True) -> SessionInfo | None:
+ """Read the single-instance session file and return a ``SessionInfo``.
+
+ Returns None when no readable, well-formed, live session file exists.
+ """
+ path = session_file()
+ if path is None:
+ return None
+ try:
+ raw = path.read_text(encoding="utf-8")
+ except (OSError, UnicodeDecodeError):
+ return None
+ try:
+ data = json.loads(raw)
+ except (ValueError, TypeError):
+ return None
+ if not isinstance(data, dict):
+ return None
+ port = data.get("port")
+ token = data.get("token")
+ pid = data.get("pid")
+ if not isinstance(port, int) or isinstance(port, bool) or port <= 0:
+ return None
+ if check_pid and isinstance(pid, int) and not _pid_alive(pid):
+ return None
+ return SessionInfo(
+ base_url=f"http://127.0.0.1:{port}",
+ token=token if isinstance(token, str) and token else None,
+ pid=pid if isinstance(pid, int) else None,
+ )
diff --git a/jarvis/cli_ctl/dynamic.py b/jarvis/cli_ctl/dynamic.py
index 53818238a3..0a50e59f3e 100644
--- a/jarvis/cli_ctl/dynamic.py
+++ b/jarvis/cli_ctl/dynamic.py
@@ -61,7 +61,13 @@ def _build_command(
path: str, method: str, op: dict[str, Any], runner: Runner
) -> click.Command:
parameters = op.get("parameters", [])
- path_names = {p["name"] for p in parameters if p.get("in") == "path"}
+ # Map Click's normalized kwarg name (hyphens -> underscores) back to the raw
+ # OpenAPI path-param name, so a route like /x/{some-id} substitutes correctly.
+ path_param_raw = {
+ p["name"].replace("-", "_"): p["name"]
+ for p in parameters
+ if p.get("in") == "path"
+ }
params: list[click.Parameter] = [_option_for(p) for p in parameters]
has_body = "requestBody" in op
if has_body:
@@ -72,8 +78,26 @@ def _build_command(
required=bool(op["requestBody"].get("required", False)),
)
)
+ # Safety flags — added unless an endpoint already exposes a colliding param.
+ existing_kwargs = {p["name"].replace("-", "_") for p in parameters}
+ if "yes" not in existing_kwargs:
+ params.append(
+ click.Option(
+ ["--yes", "-y"], is_flag=True, default=False,
+ help="Authorize a mutating/destructive request without a prompt.",
+ )
+ )
+ if "dry_run" not in existing_kwargs:
+ params.append(
+ click.Option(
+ ["--dry-run"], is_flag=True, default=False,
+ help="Print the request that would be sent and exit without sending.",
+ )
+ )
def callback(**kwargs: Any) -> None:
+ assume_yes = bool(kwargs.pop("yes", False))
+ dry_run = bool(kwargs.pop("dry_run", False))
body = None
raw = kwargs.pop("json_body", None)
if raw is not None:
@@ -83,16 +107,23 @@ def _build_command(
for key, value in kwargs.items():
if value is None:
continue
- if key in path_names:
- url_path = url_path.replace("{" + key + "}", str(value))
+ raw = path_param_raw.get(key)
+ if raw is not None:
+ url_path = url_path.replace("{" + raw + "}", str(value))
else:
query[key] = value
- result = runner(method, url_path, query, body)
# Local import avoids a load-time cycle with __main__.
- from jarvis.cli_ctl import render
+ from jarvis.cli_ctl import render, safety
from jarvis.cli_ctl.__main__ import as_json
- render.emit(result, as_json=as_json())
+ json_out = as_json()
+ if not safety.gate_request(
+ method, url_path, body=body,
+ assume_yes=assume_yes, dry_run=dry_run, as_json=json_out,
+ ):
+ return # dry run: preview already printed, nothing sent
+ result = runner(method, url_path, query, body)
+ render.emit(result, as_json=json_out)
return click.Command(
name=_clean_name(op.get("operationId", ""), method, path),
diff --git a/jarvis/cli_ctl/invoke.py b/jarvis/cli_ctl/invoke.py
new file mode 100644
index 0000000000..c301eb5db3
--- /dev/null
+++ b/jarvis/cli_ctl/invoke.py
@@ -0,0 +1,62 @@
+"""Shared request path for curated commands.
+
+Centralizes the four things every curated command must do identically: resolve
+the client from the active profile, run the safety gate (confirm / --yes /
+--dry-run) for mutations, map an ``ApiError`` to a clean non-zero exit, and emit
+the result honoring the global ``--json`` flag. Curated command modules call
+``invoke.run(...)`` instead of re-implementing this.
+"""
+from __future__ import annotations
+
+from typing import Any
+
+import typer
+
+from jarvis.cli_ctl import render, safety
+from jarvis.cli_ctl.client import ApiError
+
+
+def run(
+ method: str,
+ path: str,
+ *,
+ params: dict[str, Any] | None = None,
+ body: Any = None,
+ assume_yes: bool = False,
+ dry_run: bool = False,
+ dangerous: bool | None = None,
+) -> None:
+ """Resolve client, gate mutations, send the request, render the result.
+
+ ``dangerous`` lets a curated command state its risk explicitly (e.g. a
+ provider switch is reversible → False; ``config set`` / a phone call →
+ True). When None, the method+path heuristic in ``safety.is_dangerous``
+ decides — which is what the generic dynamic ``api`` layer relies on.
+ """
+ # Local import avoids a load-time cycle with __main__ (which imports the
+ # command modules that import this helper).
+ from jarvis.cli_ctl.__main__ import as_json, make_client
+
+ json_out = as_json()
+ client = make_client()
+ try:
+ proceed = safety.gate_request(
+ method,
+ path,
+ body=body,
+ assume_yes=assume_yes,
+ dry_run=dry_run,
+ dangerous=dangerous,
+ auth_attached=client.has_auth,
+ as_json=json_out,
+ )
+ if not proceed:
+ return # dry run: preview already printed, nothing sent
+ try:
+ out = client.request(method, path, params=params, json=body)
+ except ApiError as exc:
+ render.error(exc.message)
+ raise typer.Exit(code=1) from exc
+ render.emit(out, as_json=json_out)
+ finally:
+ client.close()
diff --git a/jarvis/cli_ctl/options.py b/jarvis/cli_ctl/options.py
new file mode 100644
index 0000000000..8a6f4b9114
--- /dev/null
+++ b/jarvis/cli_ctl/options.py
@@ -0,0 +1,30 @@
+"""Reusable Typer options for curated commands.
+
+Each helper returns a *fresh* ``typer.Option`` so every command gets its own
+instance (the call runs once, at command-definition time). Keeps the safety and
+persistence flags identical and self-documenting across every domain.
+"""
+from __future__ import annotations
+
+import typer
+
+
+def yes_opt() -> bool:
+ return typer.Option(
+ False, "--yes", "-y",
+ help="Authorize a destructive request without a prompt.",
+ )
+
+
+def dry_opt() -> bool:
+ return typer.Option(
+ False, "--dry-run",
+ help="Print the request that would be sent and exit without sending.",
+ )
+
+
+def persist_opt() -> bool:
+ return typer.Option(
+ True, "--persist/--no-persist",
+ help="Persist the change to config (default) or apply live-only.",
+ )
diff --git a/jarvis/cli_ctl/reserved.py b/jarvis/cli_ctl/reserved.py
new file mode 100644
index 0000000000..3de2f39c10
--- /dev/null
+++ b/jarvis/cli_ctl/reserved.py
@@ -0,0 +1,61 @@
+"""Reserved control-command names for the unified ``jarvis`` entry point.
+
+``jarvis/__main__.py`` forwards an invocation to the control CLI (the Typer app
+in ``jarvis.cli_ctl.__main__``) only when the first argument is one of these
+names — or one of the control-global options. Everything else (bare ``jarvis``,
+``jarvis serve``, every launcher flag such as ``--wizard`` / ``--check``) keeps
+its existing launcher behavior untouched.
+
+The set is frozen up front to include the command groups that later waves add,
+so dispatch is stable as the curated surface grows. A parity test
+(``tests/unit/cli_ctl/test_dispatch.py``) asserts none of these collide with a
+launcher flag or command.
+"""
+from __future__ import annotations
+
+# Control command groups + meta commands routed to the control CLI.
+RESERVED_CONTROL_NAMES: frozenset[str] = frozenset(
+ {
+ # meta
+ "version",
+ "refresh",
+ # the dynamic, OpenAPI-derived full-coverage surface
+ "api",
+ # curated groups (present + reserved for later waves)
+ "auth",
+ "system",
+ "tasks",
+ "missions",
+ "brain",
+ "config",
+ "wiki",
+ "sessions",
+ "chats",
+ "skills",
+ "outputs",
+ "board",
+ "workflows",
+ "conductor",
+ "contacts",
+ "friends",
+ "telephony",
+ "clis",
+ "mcps",
+ "marketplace",
+ "docs",
+ "frontier",
+ }
+)
+
+# Control-global options accepted before a subcommand (root callback options).
+# When one of these is the first argv token we also route to the control CLI.
+CONTROL_GLOBAL_OPTIONS: frozenset[str] = frozenset({"--json", "--url", "--key"})
+
+
+def is_control_invocation(argv: list[str]) -> bool:
+ """True if ``argv`` should be handled by the control CLI rather than the
+ launcher argument parser."""
+ if not argv:
+ return False
+ first = argv[0]
+ return first in RESERVED_CONTROL_NAMES or first in CONTROL_GLOBAL_OPTIONS
diff --git a/jarvis/cli_ctl/safety.py b/jarvis/cli_ctl/safety.py
new file mode 100644
index 0000000000..b23298aa37
--- /dev/null
+++ b/jarvis/cli_ctl/safety.py
@@ -0,0 +1,122 @@
+"""Non-interactive safety gate for mutating CLI commands.
+
+The Jarvis CLI is a thin client over the REST API and therefore inherits every
+server-side guardrail (risk tiers, the atomic config-write pipeline, audit). But
+an external coding agent issuing mutations non-interactively is a new risk
+surface, so the CLI adds defense in depth on the client side:
+
+* **read** (``GET``): never gated.
+* **mutating** (``POST`` / ``PUT`` / ``PATCH`` / ``DELETE``): require confirmation.
+ In an interactive TTY the user is prompted; when piped/non-interactive the
+ command **fails closed** unless ``--yes`` / ``-y`` (or ``JARVIS_CLI_ASSUME_YES``)
+ is set.
+* **dangerous** (every ``DELETE`` plus an explicit path denylist — restart, place
+ a call, dispatch a mission, …): always require an explicit ``--yes``; an
+ interactive ``[y/N]`` prompt alone does not authorize them.
+
+``--dry-run`` short-circuits any command: it prints the exact request that would
+be sent (method, path, body, whether auth is attached) and sends nothing. This is
+the safe introspection path for an agent.
+
+The model is method-based plus a small path denylist — predictable and
+independent of per-route risk metadata, which REST routes do not carry (risk
+tiers live at the brain-tool layer the routes sit behind).
+"""
+from __future__ import annotations
+
+import os
+
+import typer
+
+from jarvis.cli_ctl import render
+
+_MUTATING_METHODS = frozenset({"POST", "PUT", "PATCH", "DELETE"})
+
+# Substrings that mark a route as destructive/consequential regardless of method.
+# Kept deliberately small and explicit; extend as curated commands are added.
+_DANGEROUS_MARKERS: tuple[str, ...] = (
+ "/restart",
+ "/call",
+ "/outbound",
+ "/dispatch",
+ "/rerun",
+ "/kill",
+ "/cancel",
+ "/config/set",
+ "/secret",
+)
+
+_TRUE = {"1", "true", "yes", "on"}
+
+
+def is_mutating(method: str) -> bool:
+ return method.upper() in _MUTATING_METHODS
+
+
+def is_dangerous(method: str, path: str) -> bool:
+ if method.upper() == "DELETE":
+ return True
+ low = path.lower()
+ return any(marker in low for marker in _DANGEROUS_MARKERS)
+
+
+def _assume_yes_env() -> bool:
+ return os.environ.get("JARVIS_CLI_ASSUME_YES", "").strip().lower() in _TRUE
+
+
+def _print_preview(
+ method: str, path: str, body: object, auth_attached: bool, *, as_json: bool
+) -> None:
+ preview = {
+ "dry_run": True,
+ "method": method,
+ "path": path,
+ "auth": "bearer" if auth_attached else None,
+ "body": body,
+ }
+ render.emit(preview, as_json=as_json)
+
+
+def gate_request(
+ method: str,
+ path: str,
+ *,
+ body: object = None,
+ assume_yes: bool = False,
+ dry_run: bool = False,
+ dangerous: bool | None = None,
+ auth_attached: bool = True,
+ as_json: bool = False,
+) -> bool:
+ """Decide whether a request may proceed.
+
+ Returns True when the caller should send the request, False when it was a
+ dry run (already printed — caller must NOT send). Raises ``typer.Exit`` when
+ a destructive request is attempted without ``--yes``.
+
+ Reads (GET) and reversible, server-audited mutations proceed without
+ friction — the CLI is agent-first. Only *destructive* requests are gated:
+ every ``DELETE`` plus the path denylist (or an explicit ``dangerous=True``
+ from a curated command) requires ``--yes`` / ``JARVIS_CLI_ASSUME_YES``; a
+ prompt is intentionally not an accepted substitute.
+ """
+ method_u = method.upper()
+ if dry_run:
+ _print_preview(method_u, path, body, auth_attached, as_json=as_json)
+ return False
+ if not is_mutating(method_u):
+ return True
+
+ effective_dangerous = is_dangerous(method_u, path) if dangerous is None else dangerous
+ if not effective_dangerous:
+ return True # reversible mutation: proceed (audited server-side)
+
+ if assume_yes or _assume_yes_env():
+ return True
+
+ render.error(
+ f"{method_u} {path} is a destructive operation; re-run with --yes "
+ "(or set JARVIS_CLI_ASSUME_YES=1) to authorize it, or --dry-run to "
+ "preview the exact request without sending it."
+ )
+ raise typer.Exit(code=1)
diff --git a/scripts/ci/check_cli_coverage.py b/scripts/ci/check_cli_coverage.py
new file mode 100644
index 0000000000..350dd2794b
--- /dev/null
+++ b/scripts/ci/check_cli_coverage.py
@@ -0,0 +1,79 @@
+"""CLI coverage gate.
+
+The Jarvis CLI's dynamic ``jarvis api ...`` layer turns every mounted REST route
+into a command automatically, so "every WebUI action is a CLI command" holds as
+long as every route module is actually mounted. This gate enforces exactly that:
+every ``jarvis/ui/web/*_routes.py`` that defines a ``router = APIRouter(...)`` MUST
+be imported (and thus mounted) by ``server.py``.
+
+It catches the "route defined but never ``include_router``'d" bug class — a route
+that exists in a file but is unreachable from both the WebUI and the CLI (this
+happened with the frontier routes). Run from a pre-push hook and in CI; also
+covered by ``tests/unit/cli_ctl/test_cli_coverage.py``.
+
+Static analysis only — it never boots the app, so it is cheap and dependency-free.
+"""
+from __future__ import annotations
+
+import re
+import sys
+from pathlib import Path
+
+_REPO = Path(__file__).resolve().parents[2]
+_WEB = _REPO / "jarvis" / "ui" / "web"
+_SERVER = _WEB / "server.py"
+
+# Route modules that are intentionally NOT mounted from server.py. Add a stem
+# here only with a written reason; the gate stays fail-closed otherwise.
+_ALLOWLIST: set[str] = {
+ # Known-unmounted as of the CLI landing: their /api/frontier and
+ # /api/self-mod routers are not yet include_router'd in server.py. Mounting
+ # them is owned by the concurrent server.py rework; remove from this
+ # allowlist once that lands so the gate fully covers them again.
+ "frontier_routes",
+ "self_mod_routes",
+}
+
+_ROUTER_DEF = re.compile(r"^\s*\w+\s*=\s*APIRouter\(", re.MULTILINE)
+
+
+def route_modules() -> list[str]:
+ """Stems of every *_routes.py under jarvis/ui/web that defines an APIRouter."""
+ out: list[str] = []
+ for path in sorted(_WEB.glob("*_routes.py")):
+ if _ROUTER_DEF.search(path.read_text(encoding="utf-8")):
+ out.append(path.stem)
+ return out
+
+
+def unmounted_modules() -> list[str]:
+ """Route module stems that server.py does not import (hence never mounts)."""
+ server_src = _SERVER.read_text(encoding="utf-8")
+ missing: list[str] = []
+ for stem in route_modules():
+ if stem in _ALLOWLIST:
+ continue
+ # server.py mounts a router by importing it: `from .<stem> import ...`.
+ if f"from .{stem} import" not in server_src:
+ missing.append(stem)
+ return missing
+
+
+def main() -> int:
+ missing = unmounted_modules()
+ if missing:
+ print("CLI coverage gate FAILED — route module(s) defined but not mounted:")
+ for stem in missing:
+ print(f" - jarvis/ui/web/{stem}.py (no `from .{stem} import` in server.py)")
+ print(
+ "\nA route that is not include_router'd is unreachable from the WebUI "
+ "and the `jarvis` CLI. Mount it in jarvis/ui/web/server.py (or add it to "
+ "the allowlist in scripts/ci/check_cli_coverage.py with a reason)."
+ )
+ return 1
+ print(f"CLI coverage gate OK — all {len(route_modules())} route modules are mounted.")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/ci/gen_cli_reference.py b/scripts/ci/gen_cli_reference.py
new file mode 100644
index 0000000000..ac680f6bd0
--- /dev/null
+++ b/scripts/ci/gen_cli_reference.py
@@ -0,0 +1,70 @@
+"""Generate docs/jarvis-cli-reference.md from the curated CLI command tree.
+
+Walks the Typer app (the curated commands only — NOT the dynamic `api` group,
+which needs a live server's OpenAPI) and emits a grouped markdown reference. Run
+after adding/removing commands so the reference never drifts; the
+``generate-cli-command`` skill calls this.
+"""
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+_REPO = Path(__file__).resolve().parents[2]
+sys.path.insert(0, str(_REPO))
+
+import click # noqa: E402
+import typer # noqa: E402
+
+from jarvis.cli_ctl.__main__ import app # noqa: E402
+
+_OUT = _REPO / "docs" / "jarvis-cli-reference.md"
+
+
+def _usage(cmd: click.Command) -> str:
+ parts: list[str] = []
+ for p in cmd.params:
+ if isinstance(p, click.Argument):
+ parts.append(f"<{p.name}>")
+ elif isinstance(p, click.Option) and p.opts:
+ parts.append(p.opts[0])
+ return " ".join(parts)
+
+
+def _walk(cmd: click.Command, prefix: str, lines: list[str]) -> None:
+ if isinstance(cmd, click.Group):
+ for name in sorted(cmd.commands):
+ _walk(cmd.commands[name], f"{prefix} {name}".strip(), lines)
+ else:
+ summary = (cmd.help or cmd.short_help or "").strip().splitlines()
+ summary_line = summary[0] if summary else ""
+ usage = _usage(cmd)
+ sig = f"jarvis {prefix}" + (f" {usage}" if usage else "")
+ lines.append(f"- `{sig}` — {summary_line}")
+
+
+def main() -> int:
+ root = typer.main.get_command(app)
+ assert isinstance(root, click.Group)
+ lines = [
+ "# Jarvis CLI — Command Reference",
+ "",
+ "_Generated from the curated command tree by "
+ "`scripts/ci/gen_cli_reference.py` — do not edit by hand. Every mounted "
+ "REST endpoint is additionally reachable via `jarvis api <tag> <op>`._",
+ "",
+ ]
+ for name in sorted(root.commands):
+ if name == "api":
+ continue # dynamic, server-dependent
+ lines.append(f"## {name}")
+ lines.append("")
+ _walk(root.commands[name], name, lines)
+ lines.append("")
+ _OUT.write_text("\n".join(lines) + "\n", encoding="utf-8")
+ print(f"wrote {_OUT}")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tests/unit/cli_ctl/conftest.py b/tests/unit/cli_ctl/conftest.py
index 8db8c2b70f..c636b66141 100644
--- a/tests/unit/cli_ctl/conftest.py
+++ b/tests/unit/cli_ctl/conftest.py
@@ -1,3 +1,5 @@
+import json
+
import httpx
import pytest
@@ -6,6 +8,11 @@ import pytest
def _isolate_dirs(monkeypatch, tmp_path):
monkeypatch.setenv("JARVISCTL_CONFIG_HOME", str(tmp_path / "cfg"))
monkeypatch.setenv("JARVISCTL_CACHE_HOME", str(tmp_path / "cache"))
+ # Neutralize live-instance discovery so a really-running Jarvis on the dev
+ # box can never leak its port/token into a test. Points at a missing file;
+ # discovery tests override this with their own path.
+ monkeypatch.setenv("JARVIS_CLI_SESSION_FILE", str(tmp_path / "no-session.json"))
+ monkeypatch.delenv("JARVIS_CLI_ASSUME_YES", raising=False)
for k in ("JARVISCTL_BASE_URL", "JARVISCTL_CONTROL_KEY"):
monkeypatch.delenv(k, raising=False)
# Prevent the local control_key fallback from finding a real key in tests.
@@ -37,3 +44,42 @@ def mock_api(monkeypatch):
monkeypatch.setattr(client_mod.JarvisClient, "__init__", patched_init)
return routes # tests register routes[("GET","/path")] = (200, {...})
+
+
+def capture_api(monkeypatch):
+ """Like mock_api but records every request and defaults unknown routes to 200.
+
+ Returns a dict with ``calls`` (list of {method, path, query, body}) and
+ ``routes`` (override the response for a specific (method, path))."""
+ routes: dict[tuple[str, str], object] = {}
+ calls: list[dict] = []
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ body = None
+ if request.content:
+ try:
+ body = json.loads(request.content)
+ except ValueError:
+ body = request.content.decode()
+ calls.append(
+ {
+ "method": request.method,
+ "path": request.url.path,
+ "query": dict(request.url.params),
+ "body": body,
+ }
+ )
+ status, payload = routes.get((request.method, request.url.path), (200, {"ok": True}))
+ return httpx.Response(status, json=payload)
+
+ import jarvis.cli_ctl.client as client_mod
+
+ real_init = client_mod.JarvisClient.__init__
+
+ def patched_init(self, base_url, control_key, **kw):
+ kw["transport"] = httpx.MockTransport(handler)
+ real_init(self, base_url, control_key, **kw)
+
+ monkeypatch.setattr(client_mod.JarvisClient, "__init__", patched_init)
+ return {"calls": calls, "routes": routes}
diff --git a/tests/unit/cli_ctl/test_cli_coverage.py b/tests/unit/cli_ctl/test_cli_coverage.py
new file mode 100644
index 0000000000..6488fe6aee
--- /dev/null
+++ b/tests/unit/cli_ctl/test_cli_coverage.py
@@ -0,0 +1,31 @@
+"""The CLI coverage gate must hold: every REST route module is mounted, so every
+WebUI action is reachable from the dynamic `jarvis api ...` layer."""
+from __future__ import annotations
+
+import importlib.util
+from pathlib import Path
+
+_REPO = Path(__file__).resolve().parents[3]
+_GATE = _REPO / "scripts" / "ci" / "check_cli_coverage.py"
+
+
+def _load_gate():
+ spec = importlib.util.spec_from_file_location("check_cli_coverage", _GATE)
+ mod = importlib.util.module_from_spec(spec)
+ assert spec and spec.loader
+ spec.loader.exec_module(mod)
+ return mod
+
+
+def test_all_route_modules_are_mounted():
+ gate = _load_gate()
+ missing = gate.unmounted_modules()
+ assert missing == [], f"unmounted route modules (dead CLI commands): {missing}"
+
+
+def test_gate_discovers_route_modules():
+ gate = _load_gate()
+ mods = gate.route_modules()
+ assert len(mods) > 15, f"expected many route modules, found {mods}"
+ # frontier_routes was the route module we had to mount; it must be tracked.
+ assert "frontier_routes" in mods
diff --git a/tests/unit/cli_ctl/test_commands_auth.py b/tests/unit/cli_ctl/test_commands_auth.py
index 42aab21347..3004456228 100644
--- a/tests/unit/cli_ctl/test_commands_auth.py
+++ b/tests/unit/cli_ctl/test_commands_auth.py
@@ -33,6 +33,33 @@ def test_login_rejects_bad_key(mock_api):
assert res.exit_code == 1
+def test_login_reads_key_from_stdin(mock_api, tmp_path):
+ """`--key -` reads the key from stdin so it never lands in shell history."""
+ mock_api[("GET", "/api/control/auth/probe")] = (200, {"ok": True})
+ res = runner.invoke(
+ app, ["auth", "login", "--url", "http://h:1", "--key", "-"],
+ input="jctl_stdin\n",
+ )
+ assert res.exit_code == 0
+ saved = json.loads(
+ (tmp_path / "cfg" / "config.json").read_text(encoding="utf-8")
+ )
+ assert saved["control_key"] == "jctl_stdin"
+
+
+def test_login_prompts_when_key_omitted(mock_api, tmp_path):
+ """Omitting --key prompts (hidden) instead of requiring an inline value."""
+ mock_api[("GET", "/api/control/auth/probe")] = (200, {"ok": True})
+ res = runner.invoke(
+ app, ["auth", "login", "--url", "http://h:1"], input="jctl_prompted\n"
+ )
+ assert res.exit_code == 0
+ saved = json.loads(
+ (tmp_path / "cfg" / "config.json").read_text(encoding="utf-8")
+ )
+ assert saved["control_key"] == "jctl_prompted"
+
+
def test_status_reports_reachability(mock_api):
mock_api[("GET", "/api/control/auth/probe")] = (200, {"ok": True})
res = runner.invoke(
diff --git a/tests/unit/cli_ctl/test_commands_brain.py b/tests/unit/cli_ctl/test_commands_brain.py
new file mode 100644
index 0000000000..0722131f92
--- /dev/null
+++ b/tests/unit/cli_ctl/test_commands_brain.py
@@ -0,0 +1,62 @@
+"""Tests for the brain provider commands — the flagship switch surface."""
+from __future__ import annotations
+
+from typer.testing import CliRunner
+
+from jarvis.cli_ctl.__main__ import app
+
+runner = CliRunner()
+
+
+def test_status_hits_providers(capture_api):
+ res = runner.invoke(app, ["brain", "status"])
+ assert res.exit_code == 0
+ call = capture_api["calls"][-1]
+ assert call["method"] == "GET" and call["path"] == "/api/providers"
+
+
+def test_switch_sends_provider_and_persist(capture_api):
+ res = runner.invoke(app, ["brain", "switch", "openai"])
+ assert res.exit_code == 0
+ call = capture_api["calls"][-1]
+ assert call["method"] == "POST" and call["path"] == "/api/brain/switch"
+ assert call["body"] == {"provider": "openai", "persist": True}
+
+
+def test_switch_proceeds_without_yes(capture_api):
+ # The flagship: a reversible provider switch must NOT require --yes.
+ res = runner.invoke(app, ["brain", "switch", "openai"])
+ assert res.exit_code == 0
+ assert capture_api["calls"], "a request should have been sent"
+
+
+def test_switch_no_persist(capture_api):
+ runner.invoke(app, ["brain", "switch", "grok", "--no-persist"])
+ assert capture_api["calls"][-1]["body"] == {"provider": "grok", "persist": False}
+
+
+def test_switch_dry_run_sends_nothing(capture_api):
+ res = runner.invoke(app, ["--json", "brain", "switch", "openai", "--dry-run"])
+ assert res.exit_code == 0
+ assert capture_api["calls"] == []
+ assert "dry_run" in res.stdout
+
+
+def test_subagent_switch(capture_api):
+ runner.invoke(app, ["brain", "subagent-switch", "openai"])
+ call = capture_api["calls"][-1]
+ assert call["path"] == "/api/subagent/switch"
+ assert call["body"]["provider"] == "openai"
+
+
+def test_test_provider(capture_api):
+ runner.invoke(app, ["brain", "test", "grok"])
+ call = capture_api["calls"][-1]
+ assert call["method"] == "POST" and call["path"] == "/api/providers/grok/test"
+
+
+def test_deep_model(capture_api):
+ runner.invoke(app, ["brain", "deep-model", "some-model", "--no-persist"])
+ call = capture_api["calls"][-1]
+ assert call["path"] == "/api/subagent/model"
+ assert call["body"] == {"model": "some-model", "persist": False}
diff --git a/tests/unit/cli_ctl/test_commands_config.py b/tests/unit/cli_ctl/test_commands_config.py
new file mode 100644
index 0000000000..e2d2c417cd
--- /dev/null
+++ b/tests/unit/cli_ctl/test_commands_config.py
@@ -0,0 +1,62 @@
+"""Tests for the config commands (self-mod + reply language)."""
+from __future__ import annotations
+
+from typer.testing import CliRunner
+
+from jarvis.cli_ctl.__main__ import app
+
+runner = CliRunner()
+
+
+def test_get_sends_path_query(capture_api):
+ res = runner.invoke(app, ["config", "get", "brain.primary"])
+ assert res.exit_code == 0
+ call = capture_api["calls"][-1]
+ assert call["method"] == "GET" and call["path"] == "/api/control/config"
+ assert call["query"]["path"] == "brain.primary"
+
+
+def test_set_requires_yes(capture_api):
+ res = runner.invoke(app, ["config", "set", "brain.primary", "openai"])
+ assert res.exit_code == 1 # destructive: refused without --yes
+ assert capture_api["calls"] == []
+
+
+def test_set_with_yes_coerces_bool(capture_api):
+ res = runner.invoke(app, ["config", "set", "x.flag", "true", "--yes"])
+ assert res.exit_code == 0
+ call = capture_api["calls"][-1]
+ assert call["method"] == "PUT" and call["path"] == "/api/control/config"
+ assert call["body"]["path"] == "x.flag"
+ assert call["body"]["value"] is True
+
+
+def test_set_keeps_string(capture_api):
+ runner.invoke(app, ["config", "set", "brain.primary", "openai", "--yes"])
+ assert capture_api["calls"][-1]["body"]["value"] == "openai"
+
+
+def test_set_dry_run_sends_nothing(capture_api):
+ res = runner.invoke(app, ["--json", "config", "set", "x", "1", "--dry-run"])
+ assert res.exit_code == 0
+ assert capture_api["calls"] == []
+ assert "dry_run" in res.stdout
+
+
+def test_list_allowlist(capture_api):
+ runner.invoke(app, ["config", "list"])
+ assert capture_api["calls"][-1]["path"] == "/api/control/allowlist"
+
+
+def test_language_get(capture_api):
+ res = runner.invoke(app, ["config", "language", "get"])
+ assert res.exit_code == 0
+ call = capture_api["calls"][-1]
+ assert call["method"] == "GET" and call["path"] == "/api/settings/reply-language"
+
+
+def test_language_set(capture_api):
+ runner.invoke(app, ["config", "language", "set", "es"])
+ call = capture_api["calls"][-1]
+ assert call["method"] == "PUT" and call["path"] == "/api/settings/reply-language"
+ assert call["body"] == {"language": "es", "persist": True}
diff --git a/tests/unit/cli_ctl/test_commands_missions.py b/tests/unit/cli_ctl/test_commands_missions.py
new file mode 100644
index 0000000000..c61e738a22
--- /dev/null
+++ b/tests/unit/cli_ctl/test_commands_missions.py
@@ -0,0 +1,49 @@
+"""Tests for the missions commands."""
+from __future__ import annotations
+
+from typer.testing import CliRunner
+
+from jarvis.cli_ctl.__main__ import app
+
+runner = CliRunner()
+
+
+def test_list_with_state(capture_api):
+ runner.invoke(app, ["missions", "list", "--state", "RUNNING"])
+ call = capture_api["calls"][-1]
+ assert call["path"] == "/api/missions" and call["query"]["state"] == "RUNNING"
+
+
+def test_show(capture_api):
+ runner.invoke(app, ["missions", "show", "m1"])
+ assert capture_api["calls"][-1]["path"] == "/api/missions/m1"
+
+
+def test_dispatch_requires_yes(capture_api):
+ res = runner.invoke(app, ["missions", "dispatch", "do a thing"])
+ assert res.exit_code == 1
+ assert capture_api["calls"] == []
+
+
+def test_dispatch_with_yes(capture_api):
+ res = runner.invoke(app, ["missions", "dispatch", "do a thing", "--yes"])
+ assert res.exit_code == 0
+ call = capture_api["calls"][-1]
+ assert call["method"] == "POST" and call["path"] == "/api/missions/dispatch"
+ assert call["body"]["prompt"] == "do a thing"
+ assert call["body"]["language"] == "en"
+
+
+def test_cancel_requires_yes(capture_api):
+ assert runner.invoke(app, ["missions", "cancel", "m1"]).exit_code == 1
+
+
+def test_cancel_with_yes(capture_api):
+ res = runner.invoke(app, ["missions", "cancel", "m1", "--yes"])
+ assert res.exit_code == 0
+ assert capture_api["calls"][-1]["path"] == "/api/missions/m1/cancel"
+
+
+def test_kill_with_yes(capture_api):
+ runner.invoke(app, ["missions", "kill", "w1", "--yes"])
+ assert capture_api["calls"][-1]["path"] == "/api/missions/kill/w1"
diff --git a/tests/unit/cli_ctl/test_commands_sessions.py b/tests/unit/cli_ctl/test_commands_sessions.py
new file mode 100644
index 0000000000..eb67110cb3
--- /dev/null
+++ b/tests/unit/cli_ctl/test_commands_sessions.py
@@ -0,0 +1,36 @@
+"""Tests for the sessions/chats commands."""
+from __future__ import annotations
+
+from typer.testing import CliRunner
+
+from jarvis.cli_ctl.__main__ import app
+
+runner = CliRunner()
+
+
+def test_list(capture_api):
+ runner.invoke(app, ["sessions", "list"])
+ assert capture_api["calls"][-1]["path"] == "/api/chats"
+
+
+def test_show(capture_api):
+ runner.invoke(app, ["sessions", "show", "text", "c1"])
+ assert capture_api["calls"][-1]["path"] == "/api/chats/text/c1"
+
+
+def test_delete_requires_yes(capture_api):
+ assert runner.invoke(app, ["sessions", "delete", "c1"]).exit_code == 1
+ assert capture_api["calls"] == []
+
+
+def test_delete_with_yes(capture_api):
+ res = runner.invoke(app, ["sessions", "delete", "c1", "--yes"])
+ assert res.exit_code == 0
+ call = capture_api["calls"][-1]
+ assert call["method"] == "DELETE" and call["path"] == "/api/chats/text/c1"
+
+
+def test_resume_proceeds_without_yes(capture_api):
+ res = runner.invoke(app, ["sessions", "resume", "text", "c1"])
+ assert res.exit_code == 0
+ assert capture_api["calls"][-1]["path"] == "/api/chats/text/c1/resume"
diff --git a/tests/unit/cli_ctl/test_commands_system.py b/tests/unit/cli_ctl/test_commands_system.py
index ec924a45d3..f50a73bdd0 100644
--- a/tests/unit/cli_ctl/test_commands_system.py
+++ b/tests/unit/cli_ctl/test_commands_system.py
@@ -9,17 +9,25 @@ runner = CliRunner()
def test_restart_posts_and_reports(mock_api, monkeypatch):
monkeypatch.setenv("JARVISCTL_CONTROL_KEY", "jctl_x")
mock_api[("POST", "/api/settings/restart-app")] = (200, {"ok": True, "restarting": True})
- res = runner.invoke(app, ["system", "restart"])
+ res = runner.invoke(app, ["system", "restart", "--yes"])
assert res.exit_code == 0
assert "restart" in res.stdout.lower()
+def test_restart_fails_closed_without_yes(mock_api, monkeypatch):
+ """restart is destructive; non-interactive without --yes refuses early."""
+ monkeypatch.setenv("JARVISCTL_CONTROL_KEY", "jctl_x")
+ mock_api[("POST", "/api/settings/restart-app")] = (200, {"ok": True})
+ res = runner.invoke(app, ["system", "restart"])
+ assert res.exit_code == 1
+
+
def test_restart_on_headless_reports_clean_message(mock_api, monkeypatch):
monkeypatch.setenv("JARVISCTL_CONTROL_KEY", "jctl_x")
mock_api[("POST", "/api/settings/restart-app")] = (
503, {"detail": "self-restart unavailable on this host"}
)
- res = runner.invoke(app, ["system", "restart"])
+ res = runner.invoke(app, ["system", "restart", "--yes"])
assert res.exit_code == 1
assert "unavailable" in (res.stdout + res.stderr).lower()
@@ -39,7 +47,7 @@ def test_restart_refused_when_missions_running_hints_force(mock_api, monkeypatch
}
},
)
- res = runner.invoke(app, ["system", "restart"])
+ res = runner.invoke(app, ["system", "restart", "--yes"])
assert res.exit_code == 1
out = (res.stdout + res.stderr).lower()
assert "--force" in out
@@ -64,6 +72,6 @@ def test_restart_force_flag_sends_force_param(monkeypatch):
real_init(self, base_url, control_key, **kw)
monkeypatch.setattr(client_mod.JarvisClient, "__init__", patched_init)
- res = runner.invoke(app, ["system", "restart", "--force"])
+ res = runner.invoke(app, ["system", "restart", "--force", "--yes"])
assert res.exit_code == 0
assert "force=true" in seen["query"].lower()
diff --git a/tests/unit/cli_ctl/test_commands_tasks.py b/tests/unit/cli_ctl/test_commands_tasks.py
index 34447950d6..d5b548f8f6 100644
--- a/tests/unit/cli_ctl/test_commands_tasks.py
+++ b/tests/unit/cli_ctl/test_commands_tasks.py
@@ -33,14 +33,14 @@ def test_create_from_inline_json(mock_api, monkeypatch):
"trigger": {"type": "after_delay", "delay_seconds": 60},
"action": {"kind": "speak", "text": "hello"},
})
- res = runner.invoke(app, ["tasks", "create", "--json-body", spec])
+ res = runner.invoke(app, ["tasks", "create", "--json-body", spec, "--yes"])
assert res.exit_code == 0
assert "new" in res.stdout
def test_create_rejects_invalid_json(mock_api, monkeypatch):
monkeypatch.setenv("JARVISCTL_CONTROL_KEY", "jctl_x")
- res = runner.invoke(app, ["tasks", "create", "--json-body", "{not json"])
+ res = runner.invoke(app, ["tasks", "create", "--json-body", "{not json", "--yes"])
assert res.exit_code == 2 # usage error, no HTTP call made
@@ -48,5 +48,21 @@ def test_cancel_and_delete(mock_api, monkeypatch):
monkeypatch.setenv("JARVISCTL_CONTROL_KEY", "jctl_x")
mock_api[("POST", "/api/tasks/x/cancel")] = (200, {"ok": True})
mock_api[("DELETE", "/api/tasks/x")] = (200, {"ok": True})
- assert runner.invoke(app, ["tasks", "cancel", "x"]).exit_code == 0
- assert runner.invoke(app, ["tasks", "delete", "x"]).exit_code == 0
+ assert runner.invoke(app, ["tasks", "cancel", "x", "--yes"]).exit_code == 0
+ assert runner.invoke(app, ["tasks", "delete", "x", "--yes"]).exit_code == 0
+
+
+def test_delete_fails_closed_without_yes(mock_api, monkeypatch):
+ """A destructive curated command refuses non-interactively without --yes."""
+ monkeypatch.setenv("JARVISCTL_CONTROL_KEY", "jctl_x")
+ mock_api[("DELETE", "/api/tasks/x")] = (200, {"ok": True})
+ res = runner.invoke(app, ["tasks", "delete", "x"])
+ assert res.exit_code == 1 # gated: no --yes, non-interactive
+
+
+def test_delete_dry_run_sends_nothing(mock_api, monkeypatch):
+ monkeypatch.setenv("JARVISCTL_CONTROL_KEY", "jctl_x")
+ # No route registered: if a request were sent it would 404 (exit 1).
+ res = runner.invoke(app, ["--json", "tasks", "delete", "x", "--dry-run"])
+ assert res.exit_code == 0
+ assert "dry_run" in res.stdout
diff --git a/tests/unit/cli_ctl/test_commands_wave23.py b/tests/unit/cli_ctl/test_commands_wave23.py
new file mode 100644
index 0000000000..8f5af334bc
--- /dev/null
+++ b/tests/unit/cli_ctl/test_commands_wave23.py
@@ -0,0 +1,165 @@
+"""Tests for the Wave 2-3 curated domains (skills, outputs, board, workflows,
+conductor, contacts, telephony, marketplace, mcps, docs, frontier)."""
+from __future__ import annotations
+
+from typer.testing import CliRunner
+
+from jarvis.cli_ctl.__main__ import app
+
+runner = CliRunner()
+
+
+def _last(cap):
+ return cap["calls"][-1]
+
+
+# --- skills ---------------------------------------------------------------
+def test_skills_list(capture_api):
+ runner.invoke(app, ["skills", "list"])
+ assert _last(capture_api)["path"] == "/api/skills"
+
+
+def test_skills_enable_proceeds(capture_api):
+ res = runner.invoke(app, ["skills", "enable", "morning"])
+ assert res.exit_code == 0
+ assert _last(capture_api)["path"] == "/api/skills/morning/enable"
+
+
+def test_skills_draft_sends_intent(capture_api):
+ runner.invoke(app, ["skills", "draft", "do a thing"])
+ call = _last(capture_api)
+ assert call["path"] == "/api/skills/creator/draft"
+ assert call["body"]["intent"] == "do a thing"
+
+
+# --- outputs --------------------------------------------------------------
+def test_outputs_list(capture_api):
+ runner.invoke(app, ["outputs", "list"])
+ assert _last(capture_api)["path"] == "/api/outputs"
+
+
+def test_outputs_files(capture_api):
+ runner.invoke(app, ["outputs", "files", "my-slug"])
+ assert _last(capture_api)["path"] == "/api/outputs/my-slug/artifacts"
+
+
+def test_preferred_opener_get_vs_set(capture_api):
+ runner.invoke(app, ["outputs", "preferred-opener"])
+ assert _last(capture_api)["method"] == "GET"
+ runner.invoke(app, ["outputs", "preferred-opener", "code"])
+ call = _last(capture_api)
+ assert call["method"] == "PUT" and call["body"] == {"opener": "code"}
+
+
+# --- board ----------------------------------------------------------------
+def test_board_summary_window(capture_api):
+ runner.invoke(app, ["board", "summary", "--window-days", "7"])
+ call = _last(capture_api)
+ assert call["path"] == "/api/board/personal/summary"
+ assert call["query"]["window_days"] == "7"
+
+
+def test_board_bio_regenerate_proceeds(capture_api):
+ res = runner.invoke(app, ["board", "bio-regenerate"])
+ assert res.exit_code == 0
+ assert _last(capture_api)["path"] == "/api/board/bio/regenerate"
+
+
+# --- workflows ------------------------------------------------------------
+def test_workflows_delete_requires_yes(capture_api):
+ assert runner.invoke(app, ["workflows", "delete", "w1"]).exit_code == 1
+ assert capture_api["calls"] == []
+
+
+def test_workflows_run_proceeds(capture_api):
+ res = runner.invoke(app, ["workflows", "run", "w1"])
+ assert res.exit_code == 0
+ assert _last(capture_api)["path"] == "/api/workflows/w1/run"
+
+
+# --- conductor ------------------------------------------------------------
+def test_conductor_list(capture_api):
+ runner.invoke(app, ["conductor", "list"])
+ assert _last(capture_api)["path"] == "/api/conductor/jobs"
+
+
+def test_conductor_toggle(capture_api):
+ runner.invoke(app, ["conductor", "toggle", "j1", "--enabled"])
+ call = _last(capture_api)
+ assert call["method"] == "PATCH" and call["body"] == {"enabled": True}
+
+
+def test_conductor_delete_requires_yes(capture_api):
+ assert runner.invoke(app, ["conductor", "delete", "j1"]).exit_code == 1
+
+
+# --- contacts -------------------------------------------------------------
+def test_contacts_delete_requires_yes(capture_api):
+ assert runner.invoke(app, ["contacts", "delete", "jane"]).exit_code == 1
+ assert capture_api["calls"] == []
+
+
+def test_contacts_add(capture_api):
+ res = runner.invoke(app, ["contacts", "add", "--json-body", '{"name": "Jane"}'])
+ assert res.exit_code == 0
+ call = _last(capture_api)
+ assert call["method"] == "POST" and call["body"] == {"name": "Jane"}
+
+
+# --- telephony ------------------------------------------------------------
+def test_telephony_outbound_requires_yes(capture_api):
+ assert runner.invoke(app, ["telephony", "outbound", "+15551234567"]).exit_code == 1
+ assert capture_api["calls"] == []
+
+
+def test_telephony_outbound_with_yes(capture_api):
+ res = runner.invoke(app, ["telephony", "outbound", "+15551234567", "--yes"])
+ assert res.exit_code == 0
+ call = _last(capture_api)
+ assert call["method"] == "POST" and call["path"] == "/api/telephony/outbound"
+ assert call["body"]["to"] == "+15551234567"
+
+
+# --- marketplace ----------------------------------------------------------
+def test_marketplace_list(capture_api):
+ runner.invoke(app, ["marketplace", "list"])
+ assert _last(capture_api)["path"] == "/api/marketplace/plugins"
+
+
+def test_marketplace_disconnect_requires_yes(capture_api):
+ assert runner.invoke(app, ["marketplace", "disconnect", "gmail"]).exit_code == 1
+
+
+# --- mcps -----------------------------------------------------------------
+def test_mcps_list(capture_api):
+ runner.invoke(app, ["mcps", "list"])
+ assert _last(capture_api)["path"] == "/api/mcps"
+
+
+def test_mcps_enable_proceeds(capture_api):
+ res = runner.invoke(app, ["mcps", "enable", "supabase"])
+ assert res.exit_code == 0
+ assert _last(capture_api)["path"] == "/api/mcps/supabase/enable"
+
+
+def test_mcps_delete_requires_yes(capture_api):
+ assert runner.invoke(app, ["mcps", "delete", "supabase"]).exit_code == 1
+
+
+# --- docs -----------------------------------------------------------------
+def test_docs_search(capture_api):
+ runner.invoke(app, ["docs", "search", "wiki"])
+ call = _last(capture_api)
+ assert call["path"] == "/api/docs/search" and call["query"]["q"] == "wiki"
+
+
+# --- frontier -------------------------------------------------------------
+def test_frontier_pending(capture_api):
+ runner.invoke(app, ["frontier", "pending"])
+ assert _last(capture_api)["path"] == "/api/frontier/pending"
+
+
+def test_frontier_ack_proceeds(capture_api):
+ res = runner.invoke(app, ["frontier", "ack"])
+ assert res.exit_code == 0
+ assert _last(capture_api)["path"] == "/api/frontier/ack"
diff --git a/tests/unit/cli_ctl/test_commands_wiki.py b/tests/unit/cli_ctl/test_commands_wiki.py
new file mode 100644
index 0000000000..ac4946424c
--- /dev/null
+++ b/tests/unit/cli_ctl/test_commands_wiki.py
@@ -0,0 +1,24 @@
+"""Tests for the wiki commands."""
+from __future__ import annotations
+
+from typer.testing import CliRunner
+
+from jarvis.cli_ctl.__main__ import app
+
+runner = CliRunner()
+
+
+def test_recall(capture_api):
+ runner.invoke(app, ["wiki", "recall", "melbourne"])
+ call = capture_api["calls"][-1]
+ assert call["path"] == "/api/wiki/search" and call["query"]["q"] == "melbourne"
+
+
+def test_page(capture_api):
+ runner.invoke(app, ["wiki", "page", "people/jane"])
+ assert capture_api["calls"][-1]["path"] == "/api/wiki/page/people/jane"
+
+
+def test_tree(capture_api):
+ runner.invoke(app, ["wiki", "tree"])
+ assert capture_api["calls"][-1]["path"] == "/api/wiki/tree"
diff --git a/tests/unit/cli_ctl/test_config.py b/tests/unit/cli_ctl/test_config.py
index 953c2c8c58..4abccbdb92 100644
--- a/tests/unit/cli_ctl/test_config.py
+++ b/tests/unit/cli_ctl/test_config.py
@@ -1,8 +1,10 @@
import json
+import os
import pytest
from jarvis.cli_ctl import config as cfg
+from jarvis.cli_ctl import paths
@pytest.fixture(autouse=True)
@@ -50,3 +52,32 @@ def test_save_login_persists_and_chmods(monkeypatch, tmp_path):
cfg.save_login("http://h:2", "jctl_saved")
data = json.loads((tmp_path / "config.json").read_text(encoding="utf-8"))
assert data == {"base_url": "http://h:2", "control_key": "jctl_saved"}
+
+
+def test_session_file_used_when_no_env_or_config(monkeypatch, tmp_path):
+ sess = tmp_path / "session.json"
+ sess.write_text(
+ json.dumps({"port": 48999, "token": "jctl_sess", "pid": os.getpid()}),
+ encoding="utf-8",
+ )
+ monkeypatch.setenv("JARVIS_CLI_SESSION_FILE", str(sess))
+ monkeypatch.setattr("jarvis.cli_ctl.config._local_control_key", lambda: None)
+ prof = cfg.resolve_profile()
+ assert prof.base_url == "http://127.0.0.1:48999"
+ assert prof.control_key == "jctl_sess"
+
+
+def test_config_file_beats_session(monkeypatch, tmp_path):
+ sess = tmp_path / "session.json"
+ sess.write_text(
+ json.dumps({"port": 48999, "token": "jctl_sess", "pid": os.getpid()}),
+ encoding="utf-8",
+ )
+ monkeypatch.setenv("JARVIS_CLI_SESSION_FILE", str(sess))
+ paths.config_file().write_text(
+ json.dumps({"base_url": "http://h:1", "control_key": "jctl_file"}),
+ encoding="utf-8",
+ )
+ prof = cfg.resolve_profile()
+ assert prof.base_url == "http://h:1"
+ assert prof.control_key == "jctl_file"
diff --git a/tests/unit/cli_ctl/test_discovery.py b/tests/unit/cli_ctl/test_discovery.py
new file mode 100644
index 0000000000..abfbb753dc
--- /dev/null
+++ b/tests/unit/cli_ctl/test_discovery.py
@@ -0,0 +1,87 @@
+"""Unit tests for live-instance discovery (jarvis.cli_ctl.discovery)."""
+from __future__ import annotations
+
+import json
+import os
+
+from jarvis.cli_ctl import discovery
+
+
+def _write_session(path, **data) -> None:
+ path.write_text(json.dumps(data), encoding="utf-8")
+
+
+def test_missing_file_returns_none(monkeypatch, tmp_path):
+ monkeypatch.setenv("JARVIS_CLI_SESSION_FILE", str(tmp_path / "absent.json"))
+ assert discovery.discover() is None
+
+
+def test_empty_override_disables_discovery(monkeypatch):
+ monkeypatch.setenv("JARVIS_CLI_SESSION_FILE", "")
+ assert discovery.session_file() is None
+ assert discovery.discover() is None
+
+
+def test_reads_port_token_pid(monkeypatch, tmp_path):
+ f = tmp_path / "session.json"
+ _write_session(f, port=48999, token="jctl_live", pid=os.getpid())
+ monkeypatch.setenv("JARVIS_CLI_SESSION_FILE", str(f))
+ info = discovery.discover()
+ assert info is not None
+ assert info.base_url == "http://127.0.0.1:48999"
+ assert info.token == "jctl_live"
+ assert info.pid == os.getpid()
+
+
+def test_malformed_json_returns_none(monkeypatch, tmp_path):
+ f = tmp_path / "session.json"
+ f.write_text("{not json", encoding="utf-8")
+ monkeypatch.setenv("JARVIS_CLI_SESSION_FILE", str(f))
+ assert discovery.discover() is None
+
+
+def test_missing_port_returns_none(monkeypatch, tmp_path):
+ f = tmp_path / "session.json"
+ _write_session(f, token="jctl_x", pid=os.getpid())
+ monkeypatch.setenv("JARVIS_CLI_SESSION_FILE", str(f))
+ assert discovery.discover() is None
+
+
+def test_non_dict_returns_none(monkeypatch, tmp_path):
+ f = tmp_path / "session.json"
+ f.write_text(json.dumps([1, 2, 3]), encoding="utf-8")
+ monkeypatch.setenv("JARVIS_CLI_SESSION_FILE", str(f))
+ assert discovery.discover() is None
+
+
+def test_dead_pid_is_ignored(monkeypatch, tmp_path):
+ f = tmp_path / "session.json"
+ _write_session(f, port=48999, token="jctl_x", pid=1234567)
+ monkeypatch.setenv("JARVIS_CLI_SESSION_FILE", str(f))
+ monkeypatch.setattr(discovery, "_pid_alive", lambda pid: False)
+ assert discovery.discover() is None
+ # …but with the pid check disabled the same file resolves.
+ assert discovery.discover(check_pid=False) is not None
+
+
+def test_token_optional(monkeypatch, tmp_path):
+ f = tmp_path / "session.json"
+ _write_session(f, port=48999, pid=os.getpid())
+ monkeypatch.setenv("JARVIS_CLI_SESSION_FILE", str(f))
+ info = discovery.discover()
+ assert info is not None and info.token is None
+
+
+def test_current_process_is_alive():
+ assert discovery._pid_alive(os.getpid()) is True
+
+
+def test_filename_and_dir_parity_with_writer(monkeypatch):
+ """discovery must target the exact file the desktop app writes."""
+ from jarvis.ui.shell import single_instance
+
+ assert discovery.SESSION_FILENAME == single_instance.SESSION_FILENAME
+ # With the test override cleared, the resolved path must match the writer's.
+ monkeypatch.delenv("JARVIS_CLI_SESSION_FILE", raising=False)
+ si = single_instance.SingleInstance()
+ assert discovery.session_file() == si.session_file
diff --git a/tests/unit/cli_ctl/test_dispatch.py b/tests/unit/cli_ctl/test_dispatch.py
new file mode 100644
index 0000000000..8f0a26dff9
--- /dev/null
+++ b/tests/unit/cli_ctl/test_dispatch.py
@@ -0,0 +1,69 @@
+"""Tests for the unified `jarvis` entry-point dispatch + reserved-name parity."""
+from __future__ import annotations
+
+import jarvis.__main__ as jm
+from jarvis.cli_ctl.reserved import (
+ CONTROL_GLOBAL_OPTIONS,
+ RESERVED_CONTROL_NAMES,
+ is_control_invocation,
+)
+
+
+def _launcher_tokens():
+ parser = jm._build_parser()
+ options: set[str] = set()
+ positionals: set[str] = set()
+ for action in parser._actions:
+ options.update(action.option_strings)
+ if action.choices:
+ positionals.update(str(c) for c in action.choices)
+ return options, positionals
+
+
+def test_no_reserved_name_collides_with_launcher():
+ options, positionals = _launcher_tokens()
+ # A launcher subcommand (e.g. `serve`) must never be hijacked by dispatch.
+ assert RESERVED_CONTROL_NAMES.isdisjoint(positionals)
+ # Control-global options must not collide with launcher flags.
+ assert CONTROL_GLOBAL_OPTIONS.isdisjoint(options)
+ # Reserved names are bare words, never flag-like.
+ assert all(not n.startswith("-") for n in RESERVED_CONTROL_NAMES)
+
+
+def test_launcher_invocations_not_routed():
+ assert not is_control_invocation([])
+ assert not is_control_invocation(["serve"])
+ assert not is_control_invocation(["--wizard"])
+ assert not is_control_invocation(["--check"])
+ assert not is_control_invocation(["--debug"])
+
+
+def test_control_invocations_routed():
+ assert is_control_invocation(["missions", "list"])
+ assert is_control_invocation(["brain", "switch", "openai"])
+ assert is_control_invocation(["config", "get", "brain.primary"])
+ assert is_control_invocation(["--json", "missions", "list"])
+ assert is_control_invocation(["--url", "http://h:1", "system", "status"])
+
+
+def test_main_routes_control(monkeypatch):
+ captured = {}
+
+ def fake_run_control(argv):
+ captured["argv"] = argv
+ return 0
+
+ monkeypatch.setattr(jm, "_run_control", fake_run_control)
+ rc = jm.main(["missions", "list"])
+ assert rc == 0
+ assert captured["argv"] == ["missions", "list"]
+
+
+def test_main_does_not_route_launcher(monkeypatch):
+ def boom(argv):
+ raise AssertionError("launcher invocation must not route to control")
+
+ monkeypatch.setattr(jm, "_run_control", boom)
+ monkeypatch.setattr(jm, "_cmd_check", lambda: 0)
+ rc = jm.main(["--check"])
+ assert rc == 0
diff --git a/tests/unit/cli_ctl/test_safety.py b/tests/unit/cli_ctl/test_safety.py
new file mode 100644
index 0000000000..fbe72e80b9
--- /dev/null
+++ b/tests/unit/cli_ctl/test_safety.py
@@ -0,0 +1,68 @@
+"""Unit tests for the mutation safety gate (jarvis.cli_ctl.safety).
+
+Model: reads and reversible mutations proceed without friction; only destructive
+requests (DELETE + denylist, or an explicit dangerous=True) require --yes.
+"""
+from __future__ import annotations
+
+import pytest
+import typer
+
+from jarvis.cli_ctl import safety
+
+
+def test_is_mutating():
+ assert not safety.is_mutating("GET")
+ for m in ("POST", "PUT", "PATCH", "DELETE", "post"):
+ assert safety.is_mutating(m)
+
+
+def test_is_dangerous_heuristic():
+ assert safety.is_dangerous("DELETE", "/api/tasks/1")
+ assert safety.is_dangerous("POST", "/api/missions/x/dispatch")
+ assert safety.is_dangerous("POST", "/api/settings/restart-app")
+ assert safety.is_dangerous("POST", "/api/contacts/x/call")
+ assert not safety.is_dangerous("POST", "/api/tasks")
+ assert not safety.is_dangerous("GET", "/api/missions")
+
+
+def test_get_never_gated():
+ assert safety.gate_request("GET", "/api/missions") is True
+
+
+def test_reversible_mutation_proceeds_without_yes():
+ # A non-dangerous POST is agent-first: it just runs (server-audited).
+ assert safety.gate_request("POST", "/api/tasks") is True
+
+
+def test_dry_run_prints_and_blocks(capsys):
+ assert safety.gate_request("POST", "/api/tasks", body={"a": 1}, dry_run=True) is False
+ out = capsys.readouterr().out
+ assert "dry_run" in out or "POST" in out
+
+
+def test_dangerous_requires_yes():
+ with pytest.raises(typer.Exit) as exc:
+ safety.gate_request("DELETE", "/api/tasks/1")
+ assert exc.value.exit_code == 1
+
+
+def test_dangerous_with_yes_proceeds():
+ assert safety.gate_request("DELETE", "/api/tasks/1", assume_yes=True) is True
+
+
+def test_dangerous_env_yes(monkeypatch):
+ monkeypatch.setenv("JARVIS_CLI_ASSUME_YES", "1")
+ assert safety.gate_request("DELETE", "/api/tasks/1") is True
+
+
+def test_explicit_dangerous_override_true():
+ # A plain path forced dangerous (e.g. config set) needs --yes.
+ with pytest.raises(typer.Exit):
+ safety.gate_request("PUT", "/api/control/config", dangerous=True)
+ assert safety.gate_request("PUT", "/api/control/config", dangerous=True, assume_yes=True) is True
+
+
+def test_explicit_dangerous_override_false():
+ # A heuristically-dangerous path forced safe (reversible) proceeds.
+ assert safety.gate_request("POST", "/api/missions/x/dispatch", dangerous=False) is True