Skip to main content

aristo_cli/
lib.rs

1//! Library form of the Aristo CLI. The `aristo` binary (`src/main.rs`) is
2//! a thin wrapper that calls [`run`] and exits with its return code.
3//!
4//! Splitting the CLI into a lib + tiny bin lets integration tests exercise
5//! `dispatch` directly without spawning a child process for every case
6//! (the `binary_smoke` test still spawns one, on purpose, as the canary
7//! for the binary's own glue).
8
9mod commands;
10mod data_plane;
11mod error;
12mod filter;
13/// The nudge/progress engine (Phase 18 #9). Public so the as-yet-unwired
14/// scorer is part of the lib API surface; the `aristo nudge` emitter (S0d)
15/// is its in-crate consumer.
16pub mod nudge;
17mod pipeline;
18mod session;
19mod skills;
20mod update_notify;
21mod workspace;
22
23pub use error::{CliError, CliResult};
24pub use filter::{Filter, FilterParseError};
25pub use workspace::{Workspace, WorkspaceError};
26
27use clap::{Parser, Subcommand};
28use std::path::PathBuf;
29use std::process::ExitCode;
30
31/// Aristo annotation SDK CLI.
32///
33/// Each subcommand handles one stage of the annotation lifecycle:
34/// authoring (`init`, `lang`, `install-skills`), indexing and stamping
35/// (`index`, `stamp`, `rename`), inspection (`show`, `list`, `status`,
36/// `graph`, `doc`, `badge`), quality gates (`lint`, `verify`,
37/// `critique`), review-session management (`session`), and canon
38/// binding against the Aretta server (`auth`, `canon`).
39#[derive(Parser, Debug)]
40#[command(
41    name = "aristo",
42    version,
43    about = "Aristo annotation SDK — write, verify, and document intent.",
44    long_about = None,
45)]
46struct Cli {
47    #[command(subcommand)]
48    command: Commands,
49}
50
51#[derive(Subcommand, Debug)]
52enum Commands {
53    /// Set up Aristo in this repo (creates `aristo.toml`, `.aristo/`,
54    /// pre-commit hook). Pass `--ci` / `--ci-verify` to also add CI workflows.
55    Init {
56        /// Modify Cargo.toml to add `aristo` as a dependency. Default
57        /// behavior just prints the dep line for the user to paste in.
58        #[arg(short, long)]
59        force: bool,
60
61        /// Also write a lite PR-gate workflow (`.github/workflows/aristo.yml`)
62        /// that runs audit/lint/doc via the shared aristo-action. No token needed.
63        #[arg(long)]
64        ci: bool,
65
66        /// Also write the nightly/manual verify workflow
67        /// (`.github/workflows/aristo-verify.yml`). Needs an `ARETTA_TOKEN` repo
68        /// secret (paid tier). Implies `--ci`.
69        #[arg(long)]
70        ci_verify: bool,
71
72        /// Install a local pre-commit hook (DEPRECATED). Off by default and no
73        /// longer auto-installed: the index is a gitignored cache, so CI
74        /// (`aristo verify --audit`) is the enforcement point. The hook only
75        /// runs `aristo doc` + `lint` locally as a convenience.
76        #[arg(long)]
77        hook: bool,
78    },
79
80    /// Print a syntax cheat sheet for the detected language.
81    Lang {
82        /// Detect language for a specific file. Currently only Rust
83        /// (`.rs`) is supported; other extensions error out.
84        #[arg(long)]
85        file: Option<PathBuf>,
86    },
87
88    /// Install Aristo skills for a coding agent (claude-code, cursor, codex, opencode, antigravity).
89    InstallSkills {
90        /// Target agent. Required unless `--list-agents` is used.
91        #[arg(long, value_name = "name")]
92        agent: Option<String>,
93        /// List supported agents and exit.
94        #[arg(long)]
95        list_agents: bool,
96        /// Install at user-level (e.g. ~/.claude/skills/) instead of project-level.
97        #[arg(long)]
98        user: bool,
99        /// Re-pin installed skills to this binary's version. With `--agent`,
100        /// re-installs that agent; without it, heals every already-installed
101        /// agent in place (both scopes, or just `--user`).
102        #[arg(long)]
103        update: bool,
104        /// Report whether installed skills are stale relative to this binary
105        /// (read-only). Exits non-zero if any are out of date.
106        #[arg(long)]
107        check: bool,
108        /// Internal: emit a SessionStart hook `additionalContext` block when
109        /// installed skills are stale (used by the hook this command installs).
110        #[arg(long, hide = true)]
111        hook_format: bool,
112    },
113
114    /// Reverse `install-skills`: remove SDK-bundled skills.
115    UninstallSkills {
116        /// Target agent. Required.
117        #[arg(long, value_name = "name")]
118        agent: String,
119        /// Uninstall from user-level instead of project-level.
120        #[arg(long)]
121        user: bool,
122        /// Override the "skip locally-modified" safety check.
123        #[arg(long)]
124        force: bool,
125    },
126
127    /// Scan source for annotations and write the index (`.aristo/index.toml`).
128    Index {
129        /// Force a full re-walk, ignoring the per-file mtime cache.
130        #[arg(long)]
131        all: bool,
132    },
133
134    /// Refresh the annotation index — pick up new annotations, detect
135    /// drift, and (when signed in) match against the Aretta canon.
136    Stamp {
137        /// CI mode: report whether `stamp` would change the index or
138        /// `.aristo/canon-matches.toml`, without writing either.
139        /// Exits non-zero if it would. Skips the canon-match step
140        /// too (no outbound network calls in this mode).
141        #[arg(long)]
142        check: bool,
143        /// Skip the canon-match step for this run. Doesn't disable
144        /// canon globally — set `[canon] enabled = false` in
145        /// `aristo.toml` for that. Useful when you're offline or want
146        /// a fast local stamp.
147        #[arg(long = "skip-canon")]
148        skip_canon: bool,
149        /// Invalidate the local canon-match cache and re-query every
150        /// annotation on this run. Equivalent to
151        /// `aristo canon refresh && aristo stamp`.
152        #[arg(long = "refresh-canon", conflicts_with = "skip_canon")]
153        refresh_canon: bool,
154        /// Garbage-collect archived orphan proofs after stamping. Removed
155        /// annotations' `.proof` files are normally *archived* (moved to
156        /// `.aristo/archive/proofs/`) so a stray stamp never loses a verdict;
157        /// `--gc` is the only path that hard-deletes them. No-op under
158        /// `--check` (CI must not mutate the workspace).
159        #[arg(long = "gc")]
160        gc: bool,
161    },
162
163    /// Look up an annotation by id, fn / mod / struct name, or file:line.
164    Show {
165        /// Selector: bare id, `fn <name>`, `mod <name>`, `struct <name>`,
166        /// `enum <name>`, `trait <name>`, or `<file>:<line>`.
167        selector: String,
168        /// Emit the entry as JSON instead of human-readable text.
169        #[arg(long, conflicts_with = "toml_out")]
170        json: bool,
171        /// Emit the entry as TOML (mirrors the on-disk index schema).
172        #[arg(long = "toml", conflicts_with = "json")]
173        toml_out: bool,
174    },
175
176    /// List every annotation in the index.
177    List {
178        /// Unified filter clause (`id=<id>`, `file=<path>`,
179        /// `parent=<id>`, `status=<state>`). Repeatable; multiple
180        /// `--filter` flags AND together.
181        #[arg(long = "filter", value_name = "key=value")]
182        filters: Vec<String>,
183        /// Emit a JSON array of records instead of human-readable text.
184        #[arg(long)]
185        json: bool,
186    },
187
188    /// Project-level summary (tier, counts, freshness).
189    Status,
190
191    /// Machine-readable project metrics (counts, unverified backlog, tier).
192    /// The same `Metrics` value the nudge engine computes internally.
193    Metrics {
194        /// Emit the metrics as a JSON object instead of a human summary.
195        #[arg(long)]
196        json: bool,
197    },
198
199    /// The nudge/progress engine. With no `--event`, prints what the engine
200    /// would surface right now (human introspection). With `--event`, runs as
201    /// a Claude Code hook emitter (`post-tool-use` / `user-prompt-submit` /
202    /// `session-start`) — always exits 0 so a nudge can never break the
203    /// agent's workflow. Agent-facing output uses `additionalContext` (the
204    /// only channel that reaches the model); `Stop` is intentionally not
205    /// served (its output never reaches the agent).
206    Nudge {
207        /// Hook event to serve (omit for the human readout).
208        #[arg(long)]
209        event: Option<String>,
210    },
211
212    /// Ambient one-line status segment for the Claude Code `statusLine`
213    /// (e.g. `aristo  3 review · 2 unverified · Apprentice`). Read-only;
214    /// prints nothing when there's no workspace or nudges are off.
215    Statusline,
216
217    /// Review newly-authored intents (#7). With no flags, lists what awaits
218    /// review (split into new-this-session vs backlog when a baseline exists).
219    /// `--mark <id>` records intents as reviewed once you've looked at them.
220    Review {
221        /// Mark these authored intents reviewed (repeatable; comma-lists OK).
222        /// The whole batch is validated before anything is written.
223        #[arg(long = "mark", value_name = "ID")]
224        mark: Vec<String>,
225        /// Emit the review snapshot (or mark result) as JSON instead of a
226        /// human summary.
227        #[arg(long)]
228        json: bool,
229    },
230
231    /// Check annotation prose for quality issues (rule-based; no LLM).
232    Lint {
233        /// Read-only mode: exit non-zero on `error` findings (or
234        /// `warn` with `--strict`); never modifies source.
235        #[arg(long)]
236        check: bool,
237        /// Apply auto-fixable lint rules (whitespace only) to source
238        /// files in place.
239        #[arg(long, conflicts_with = "check")]
240        fix: bool,
241        /// Treat `warn` severity as failure too (only meaningful with `--check`).
242        #[arg(long)]
243        strict: bool,
244    },
245
246    /// Run verification for every annotation that opted in.
247    Verify {
248        /// Unified filter clause (`id=<id>`, `file=<path>`,
249        /// `parent=<id>`, `status=<state>`). Repeatable; multiple
250        /// `--filter` flags AND together.
251        #[arg(long = "filter", value_name = "key=value")]
252        filters: Vec<String>,
253        /// Re-verify entries that are already in a clean verified
254        /// state. By default they're skipped; pass `--rerun` to force
255        /// a re-check.
256        #[arg(long)]
257        rerun: bool,
258        /// CI mode: report whether any status would change, without
259        /// writing the index. Exits non-zero if any change is needed.
260        #[arg(long)]
261        check: bool,
262        /// Treat warn-severity verification outcomes as failure too.
263        #[arg(long)]
264        strict: bool,
265        /// Audit mode: regenerate the index in memory and validate every
266        /// `.aristo/proofs/<id>.proof` against current source. Reports
267        /// fresh / stale / refuted / orphan counts; with `--strict`, exits
268        /// non-zero on any stale, counterexample, or orphan proof. The CI
269        /// freshness gate (replaces `aristo stamp --check`) — no dispatch,
270        /// no network, no token.
271        #[arg(long = "audit")]
272        audit: bool,
273        /// Apply pending verdict files in `.aristo/proofs/` to the
274        /// index. Reads every `<id>.proof`, runs the mechanical
275        /// validator, and (if it passes) flips the entry's status.
276        /// Skips dispatch of new verifications when set.
277        #[arg(long = "apply-verdicts", conflicts_with = "submit_verdict")]
278        apply_verdicts: bool,
279        /// Migration only: ignore any agent-stamped ground hashes in
280        /// the `.proof` files and recompute them from the cited file
281        /// ranges and index entries. Use this once when migrating
282        /// from older proof files that recorded hashes the SDK now
283        /// fills in itself. Without this flag, a stamped hash that
284        /// mismatches the current source is reported as staleness
285        /// and the proof is rejected. Only meaningful with
286        /// `--apply-verdicts`.
287        #[arg(long = "rewrite-hashes", requires = "apply_verdicts")]
288        rewrite_hashes: bool,
289        /// **Internal — invoked by the verification skill.** Submit
290        /// a single verdict: parse the JSON payload, validate it,
291        /// and (on pass) atomically write `.aristo/proofs/<id>.proof`.
292        /// Prints `accepted: sha256:<hex>` on success; structured
293        /// errors on reject. Agents never write `.proof` files
294        /// directly — the SDK is the sole writer.
295        #[arg(long = "submit-verdict", requires = "id", requires = "json")]
296        submit_verdict: bool,
297        /// Annotation id this verdict is about. Required with
298        /// `--submit-verdict`. The `.proof` file lands at
299        /// `.aristo/proofs/<id>.proof` (with `:` rewritten to `__`).
300        #[arg(long = "id", requires = "submit_verdict")]
301        id: Option<String>,
302        /// JSON-serialized ProofFile body. Required with
303        /// `--submit-verdict`. Pass as a single-quoted shell string;
304        /// the SDK parses it into a ProofFile and rejects anything
305        /// the validator would reject. Same schema as the TOML body
306        /// written on accept.
307        #[arg(long = "json", requires = "submit_verdict")]
308        json: Option<String>,
309        /// **Internal — invoked by the verification skill.**
310        /// Atomically claim one task from the pending queue and
311        /// print its TOML body to stdout. Empty stdout means the
312        /// queue is drained (exit 0 either way). Verify workers are
313        /// single-shot — call once, process the task, exit — so
314        /// context doesn't carry between verifications. The
315        /// orchestrator runs N workers in parallel and uses
316        /// `--queue-status` to decide when to spawn the next wave.
317        #[arg(long = "pop-next", conflicts_with_all = ["apply_verdicts", "submit_verdict", "queue_status"])]
318        pop_next: bool,
319        /// Peek at queue state without claiming. Prints `pending: N`,
320        /// `claimed: M` to stdout, exit 0. Used by the orchestrator
321        /// to decide whether to dispatch another wave of workers.
322        /// Safe to call concurrently.
323        #[arg(long = "queue-status", conflicts_with_all = ["apply_verdicts", "submit_verdict"])]
324        queue_status: bool,
325        /// Block until the canon-verify session reaches a terminal
326        /// state, rendering a snapshot at each long-poll return and
327        /// emitting a `still running…` heartbeat every 60s. Exit code
328        /// is derived from the final summary: `0` iff every
329        /// annotation is `verified` or `no_coverage`. Transient poll
330        /// failures (server 5xx, network, timeout) are retried with
331        /// backoff; the whole wait is bounded by a 2-hour deadline
332        /// (override via `ARISTO_VERIFY_WAIT_TIMEOUT_SECS`; `0`
333        /// disables the deadline). Without
334        /// `--wait` the SDK detaches after dispatch (prints session
335        /// id and exits 0). Combine with `--view <id>` to attach to
336        /// a session another invocation started.
337        #[arg(long = "wait")]
338        wait: bool,
339        /// CI guard against vacuous green: exit non-zero when the
340        /// canon-verify dispatch set is empty (no annotations were
341        /// sent to the server — e.g. a missing/stale canon-matches
342        /// cache, zero canon-bound `verify="full"` entries, or
343        /// everything skipped as already clean). Without this flag a
344        /// zero-dispatch run exits 0, which CI reads as "verified"
345        /// even though nothing ran. Usable only on the dispatch path:
346        /// combining it with a verb that cannot dispatch is a usage
347        /// error, never a silent no-op.
348        #[arg(
349            long = "require-dispatch",
350            conflicts_with_all = [
351                "view", "audit", "pop_next", "queue_status",
352                "submit_verdict", "apply_verdicts", "accept"
353            ]
354        )]
355        require_dispatch: bool,
356        /// Re-attach to a previously-dispatched canon-verify session
357        /// by id. Skips the source eligibility scan, push-first
358        /// precheck, and POST — just GETs the session state and
359        /// renders. Combine with `--wait` to block until terminal.
360        #[arg(long = "view", value_name = "SESSION_ID")]
361        view: Option<String>,
362        /// Subset the canon-verify dispatch to the listed annotation
363        /// ids. Comma-separated; each id must be a canon-bound entry
364        /// (`aristos:foo` or `kanon:bar`) in the workspace's index.
365        /// Bare canon-id suffixes (e.g. `foo`) are accepted as a
366        /// shorthand. `arta_*` (server-side opaque) ids are rejected
367        /// — those are not user-facing.
368        #[arg(long = "tags", value_name = "id1,id2,...", value_delimiter = ',')]
369        tags: Vec<String>,
370        /// Phase 16 (c): record a user-side known-failure waiver for a
371        /// canon-bound property your code currently violates. Write-only
372        /// — does NOT dispatch a verification. Requires `--because`. The
373        /// gap lands in `.aristo/expectations.toml` (commit it); at
374        /// verify time it renders as a "known gap (accepted)" instead of
375        /// a failure, and the strict ratchet flips it back to red if the
376        /// property ever starts passing — so stale waivers can't rot.
377        /// Accepts a bare canon-id suffix (e.g. `foo`) as shorthand.
378        #[arg(
379            long = "accept",
380            value_name = "CANON_ID",
381            requires = "because",
382            conflicts_with_all = [
383                "view", "wait", "tags", "rerun", "check", "strict", "filters",
384                "apply_verdicts", "rewrite_hashes", "submit_verdict", "id",
385                "json", "pop_next", "queue_status"
386            ]
387        )]
388        accept: Option<String>,
389        /// Reason the gap is accepted (mandatory with `--accept`).
390        /// Recorded verbatim and shown on the verify card. A reasonless
391        /// waiver is how baselines rot, so it is required.
392        #[arg(long = "because", value_name = "REASON", requires = "accept")]
393        because: Option<String>,
394        /// Optional tracking reference (issue URL, ticket id) for the
395        /// accepted gap. Only meaningful with `--accept`.
396        #[arg(long = "tracking", value_name = "REF", requires = "accept")]
397        tracking: Option<String>,
398    },
399
400    /// Run the critique skill against annotation prose — opinionated
401    /// suggestions, severity-tagged findings.
402    Critique {
403        /// Unified filter clause (`id=<id>[,<id>,...]`,
404        /// `file=<path>`, `parent=<id>`, `status=<state>`). Repeatable;
405        /// multiple `--filter` flags AND together; values may be
406        /// comma-separated. **REQUIRED** — `aristo critique` with no
407        /// filter errors with usage. To sweep every annotation in the
408        /// index, opt in explicitly with `--all --yes`.
409        #[arg(long = "filter", value_name = "key=value")]
410        filters: Vec<String>,
411        /// Apply pending critique files in `.aristo/critiques/` —
412        /// re-validate every `<id>.critique` and print a summary
413        /// grouped by id. Defaults to listing only findings whose
414        /// `disposition` is `None` (open / not yet reviewed); pass
415        /// `--include-closed` for the full view including findings
416        /// already triaged via `aristo session decide`.
417        #[arg(long = "apply-findings", conflicts_with_all = ["submit_findings", "pop_next", "queue_status"])]
418        apply_findings: bool,
419        /// Include findings whose `disposition` has been set (Accepted /
420        /// Rejected / Deferred) in the `--apply-findings` summary.
421        /// By default only open findings are listed — closed ones
422        /// stop re-surfacing on every apply, which is how a review
423        /// closes the loop. Only meaningful with `--apply-findings`.
424        #[arg(long = "include-closed", requires = "apply_findings")]
425        include_closed: bool,
426        /// Force re-enqueue of every matched annotation, bypassing the
427        /// `last_critiqued_at_text_hash` cache. Default behavior skips
428        /// annotations whose text hasn't drifted since the cached
429        /// critique was produced (so re-runs of `aristo critique
430        /// --filter id=X` are free when X is unchanged).
431        #[arg(long = "rerun")]
432        rerun: bool,
433        /// Restrict scope to annotations in files git-staged for the
434        /// next commit (`git diff --cached --name-only`). Useful for
435        /// pre-commit hook integration. Satisfies the filter-required
436        /// guard on its own; composes with explicit `--filter`
437        /// clauses via intersection (annotations must match BOTH
438        /// `--filter` and appear in the staged set).
439        #[arg(long = "staged")]
440        staged: bool,
441        /// Sweep every intent annotation that has a real `verify`
442        /// method (skips documentation-only `verify = false`). Loud
443        /// on purpose: prints `(this will enqueue N annotations;
444        /// ~$X cost — proceed with --all --yes?)` and exits 2 unless
445        /// you also pass `--yes`. Without the confirmation, an agent
446        /// could accidentally fire hundreds of LLM calls in one go.
447        #[arg(long = "all", conflicts_with_all = ["filters", "staged"])]
448        all: bool,
449        /// Skip the confirmation prompt for `--all`. Required
450        /// alongside `--all` to actually enqueue the sweep; without
451        /// it `--all` just prints the cost estimate and exits 2.
452        #[arg(long = "yes", requires = "all")]
453        yes: bool,
454        /// **Internal — invoked by the critique skill.** Atomically
455        /// claim one task from the critique queue and print its TOML
456        /// body to stdout. Empty stdout means the queue is drained
457        /// (exit 0 either way). Unlike verify, critique workers loop
458        /// on this call — the tasks are shallow and vocabulary stays
459        /// consistent when one worker handles several.
460        #[arg(long = "pop-next", conflicts_with_all = ["apply_findings", "submit_findings", "queue_status"])]
461        pop_next: bool,
462        /// Peek at queue state without claiming. Prints `pending: N`
463        /// + `claimed: M` to stdout, exit 0.
464        #[arg(long = "queue-status", conflicts_with_all = ["apply_findings", "submit_findings"])]
465        queue_status: bool,
466        /// **Internal — invoked by the critique skill.** Submit a
467        /// single critique: parse the JSON payload, validate it, and
468        /// (on accept) atomically write
469        /// `.aristo/critiques/<id>.critique`. Prints
470        /// `accepted: sha256:<hex>` on success.
471        #[arg(long = "submit-findings", requires = "id", requires = "json")]
472        submit_findings: bool,
473        /// Annotation id this submission is about. Required with
474        /// `--submit-findings`.
475        #[arg(long = "id", requires = "submit_findings")]
476        id: Option<String>,
477        /// JSON-serialized CritiqueFile body. Required with
478        /// `--submit-findings`.
479        #[arg(long = "json", requires = "submit_findings")]
480        json: Option<String>,
481    },
482
483    /// Generate per-annotation markdown to .aristo/doc/.
484    Doc {
485        /// Write only the crate-root summary (`_summary.md`); skip the
486        /// per-annotation pass.
487        #[arg(long)]
488        summary: bool,
489        /// Include each annotation's current verification status in
490        /// the rendered markdown. Status is a build-time snapshot
491        /// that drifts as code evolves; the default omits it so doc
492        /// artifacts stay reproducible on a clean checkout.
493        #[arg(long = "include-status")]
494        include_status: bool,
495        /// CI mode: recompute expected per-annotation MD from the index,
496        /// compare against `.aristo/doc/`, exit non-zero on drift. Never
497        /// writes.
498        #[arg(long)]
499        check: bool,
500        /// Composite: also generate the annotation graph (Mermaid)
501        /// and embed it inline in `_summary.md`. Implies `--summary`.
502        /// Conflicts with `--check` (read-only mode can't write the
503        /// graph block).
504        #[arg(long = "include-graph", conflicts_with = "check")]
505        include_graph: bool,
506    },
507
508    /// Generate the annotation graph (Mermaid / DOT / SVG).
509    Graph {
510        /// Output format. `mermaid` (default) emits a fenced
511        /// flowchart TD block; `dot` emits Graphviz DOT; `svg`
512        /// requires `dot` on PATH and shells out to render.
513        #[arg(long, default_value = "mermaid")]
514        format: String,
515        /// Write to this path instead of stdout. Atomic via
516        /// temp-file + rename. Relative paths resolve against the
517        /// invoking directory.
518        #[arg(long)]
519        out: Option<PathBuf>,
520        /// Unified filter clause (`id=<id>`, `file=<path>[:<LO>-<HI>]`,
521        /// `parent=<id>`, `status=<state>`). Repeatable; multiple
522        /// `--filter` flags AND together. With no filter, the scope
523        /// is the whole index.
524        #[arg(long = "filter", value_name = "key=value")]
525        filters: Vec<String>,
526        /// Drop `assume` nodes from the rendered graph. They're
527        /// included by default because assumes describe the
528        /// background facts your intents rely on — dropping them by
529        /// default would hide those.
530        #[arg(long = "exclude-assumes")]
531        exclude_assumes: bool,
532        /// Walk N hops from each filter-matched node in both
533        /// directions (ancestors + descendants) and include them in
534        /// the rendered graph. Useful for "show me this annotation
535        /// plus some context". Only meaningful with `--filter`;
536        /// without a filter, the scope is already the whole index.
537        #[arg(long, value_name = "N")]
538        depth: Option<u32>,
539        /// Include intent nodes that have no parent and no children.
540        /// They're omitted by default — usually they're standalone
541        /// claims that don't add structure to the rendered graph.
542        /// Assumes are always included (see `--exclude-assumes` for
543        /// that opt-out).
544        #[arg(long = "include-orphans")]
545        include_orphans: bool,
546        /// Color nodes by their current verification status instead
547        /// of by `verify` level (verified=green / tested=blue /
548        /// neural=yellow / stale=orange / orphan=purple /
549        /// forged=red+border / unknown=gray /
550        /// counterexample=red+border / inconclusive=red+border /
551        /// pending-deepen=gray). The `verify` level moves to the
552        /// in-node label. Use when you want to see what's still
553        /// unverified.
554        #[arg(long = "include-status")]
555        include_status: bool,
556    },
557
558    /// Generate a shareable SVG verification badge for README / docs.
559    Badge {
560        /// Write SVG to this path (relative to workspace root, or absolute).
561        /// Default: stdout.
562        #[arg(long)]
563        out: Option<PathBuf>,
564        /// Badge style: `flat-square` (default), `flat`, or `plastic`.
565        #[arg(long, default_value = "flat-square")]
566        style: String,
567        /// Which metric the SVG value half displays. `tier` (default,
568        /// the locked D7 score → D8 tier) is the headline signal;
569        /// `count` and `rate` preserve the slice-31 surfaces for
570        /// projects that prefer the simpler counters.
571        #[arg(long, default_value = "tier")]
572        metric: String,
573    },
574
575    /// Rename an annotation id everywhere it appears — source files,
576    /// index, and doc artifacts. Either every change lands or none do.
577    ///
578    /// Supported renames: bare → bare, and stamp-assigned opaque
579    /// (`aret_*`) → bare. Canon-bound prefixes (`aristos:` / `kanon:`)
580    /// are rejected in either direction — those prefixes are applied
581    /// by `aristo canon accept` and removed by `aristo canon unbind`.
582    /// The new id cannot itself be an opaque `aret_*` id (those are
583    /// stamp-assigned only).
584    Rename {
585        /// Annotation id to rename FROM. Must exist in the current
586        /// `.aristo/index.toml`.
587        old_id: String,
588        /// Annotation id to rename TO. Must not already exist and must
589        /// not use the reserved `aret_*` / `aristos:` / `kanon:`
590        /// prefixes.
591        new_id: String,
592        /// Compute and print the rename plan (source edits + per-id
593        /// artifact moves + index updates) without writing anything.
594        #[arg(long = "dry-run")]
595        dry_run: bool,
596    },
597
598    /// Run a review session over a pipeline's open artifacts —
599    /// critique findings, proof verdicts, and so on. Start it,
600    /// inspect bucket counts, record decisions, and close out.
601    Session {
602        #[command(subcommand)]
603        action: SessionAction,
604    },
605
606    /// Sign in to the Aretta canon API. Required for `aristo stamp`
607    /// and `aristo critique` to see canon matches on the Pro /
608    /// Enterprise tiers.
609    Auth {
610        #[command(subcommand)]
611        action: AuthAction,
612    },
613
614    /// Manage canon bindings: accept or reject pending matches,
615    /// inspect or refresh the local cache, unbind bound ids, and
616    /// request a verifier for a canon entry.
617    Canon {
618        #[command(subcommand)]
619        action: CanonAction,
620    },
621
622    /// Manage C instrumentation artifacts: vendor the C runtime, run codegen.
623    Instrument {
624        #[command(subcommand)]
625        action: InstrumentAction,
626    },
627}
628
629/// Subcommands under `aristo auth`. Each operates on the persistent
630/// credentials store under `$XDG_CONFIG_HOME/aristo/credentials`
631/// (or the platform default per `aristo_core::auth`).
632#[derive(clap::Subcommand, Debug)]
633pub(crate) enum AuthAction {
634    /// Sign in with GitHub and store the minted token.
635    ///
636    /// The CLI fetches the GitHub authorization URL from the Aretta
637    /// server, tries to open it in your browser, and prompts you to
638    /// paste the code shown on the callback page. The server then
639    /// mints an `arta_*` token scoped to your `(user, repo)` pair,
640    /// stored under `$XDG_CONFIG_HOME/aristo/credentials` with `0600`
641    /// Unix permissions.
642    ///
643    /// CI and scripts do not log in: set `ARETTA_TOKEN` (and
644    /// `ARETTA_API_URL`) in the environment instead.
645    Login {
646        /// Your org's Aretta host — your dashboard's hostname, e.g.
647        /// `https://<org>.aretta.ai` (a bare host gets `https://`).
648        /// Required: this flag, else the `ARETTA_API_URL` env var.
649        #[arg(long, value_name = "URL")]
650        server: Option<String>,
651        /// Repo to scope the minted token to (`owner/repo`). Defaults to
652        /// auto-deriving from `<cwd>/.git/config`'s `remote.origin.url`.
653        /// Required for non-git directories or when the remote isn't a
654        /// GitHub URL.
655        #[arg(long, value_name = "OWNER/REPO")]
656        repo: Option<String>,
657    },
658    /// Show the current authentication state. Lists every stored
659    /// credential (server, repo, user) — never the token itself — plus
660    /// any `ARETTA_TOKEN` env override. Handy for sanity-checking before
661    /// running `aristo stamp`.
662    Status,
663    /// Print the resolved `arta_*` token to stdout — the `ARETTA_TOKEN`
664    /// env var if set, else the stored credential for the current repo.
665    /// Nothing else is printed, so it pipes cleanly to your clipboard,
666    /// e.g. `aristo auth token | pbcopy` (macOS) or
667    /// `aristo auth token | xclip -selection clipboard` (Linux). Handy for
668    /// setting the `ARETTA_TOKEN` CI secret. Errors if not authenticated.
669    Token {
670        /// Repo (`owner/repo`) whose token to print. Defaults to the
671        /// cwd's git remote; with several credentials stored and no
672        /// match, errors telling you to pass this.
673        #[arg(long, value_name = "OWNER/REPO")]
674        repo: Option<String>,
675    },
676    /// Remove a stored credential. By default removes the current repo's
677    /// entry (from `--repo` or the cwd's git remote); `--all` clears
678    /// every credential. Idempotent — logging out when not logged in is
679    /// not an error.
680    Logout {
681        /// Remove every stored credential, not just the current repo's.
682        #[arg(long)]
683        all: bool,
684        /// Repo (`owner/repo`) whose credential to remove. Defaults to
685        /// the cwd's git remote. Ignored with `--all`.
686        #[arg(long, value_name = "OWNER/REPO", conflicts_with = "all")]
687        repo: Option<String>,
688    },
689}
690
691/// Subcommands under `aristo instrument`.
692#[derive(clap::Subcommand, Debug)]
693pub(crate) enum InstrumentAction {
694    /// Emit the vendored C runtime (`aristo.h` + `aristo.c`) into a SUT so it
695    /// can link Aristo's fault-injection / observation points. C11, gated by
696    /// `-DARISTO_INSTRUMENT`.
697    VendorC {
698        /// Directory to write `aristo.h` / `aristo.c` into.
699        #[arg(long, default_value = "aristo")]
700        out: PathBuf,
701    },
702
703    /// Render read-only field accessors from `// @aristo inspect(...)`
704    /// directives into a gated `aristo_generated.{h,c}` pair.
705    GenC {
706        /// One or more C source files to read directives from.
707        #[arg(required = true)]
708        paths: Vec<PathBuf>,
709        /// The opaque-handle header the generated `.h` includes.
710        #[arg(long, default_value = "db.h")]
711        handle_header: String,
712        /// Directory to write `aristo_generated.{h,c}` into.
713        #[arg(long, default_value = "aristo")]
714        out: PathBuf,
715        /// Verify committed generated files match the directives; write
716        /// nothing, exit non-zero on drift (CI gate).
717        #[arg(long)]
718        check: bool,
719    },
720}
721
722/// Subcommands under `aristo canon`.
723#[derive(clap::Subcommand, Debug)]
724pub(crate) enum CanonAction {
725    /// Accept a pending canon match: rewrite source to use the
726    /// canonical text + apply the `aristos:` / `kanon:` prefix to
727    /// the annotation id, update the index entry's binding state
728    /// to `Bound`, and move the cache entry from `pending_matches`
729    /// to `accepted_matches`.
730    ///
731    /// Both arguments are required: the bare annotation id as it
732    /// appears in `.aristo/index.toml` (NOT prefixed; the prefix
733    /// is applied by accept) and the bare canon id from the
734    /// pending match (e.g. `cell_written_exactly_once_per_page_edit`).
735    Accept {
736        /// Annotation id whose pending match you're accepting. Use
737        /// the bare form (no `aristos:` / `kanon:` prefix); the
738        /// prefix is applied by the accept itself based on the
739        /// pending match's `prefix_tier`.
740        annotation_id: String,
741        /// Canon id from the pending match (also bare — no
742        /// prefix). The pair `(annotation_id, canon_id)` locates
743        /// the exact pending match in `.aristo/canon-matches.toml`.
744        canon_id: String,
745    },
746
747    /// Reject a pending canon match: move the entry from
748    /// `pending_matches` to `rejected_matches`, pinned to the
749    /// current annotation `text_hash`. The rejection keeps the same
750    /// `(canon_id, text_hash)` pair from re-surfacing on future
751    /// `aristo stamp` runs; once the annotation text changes, the
752    /// rejection no longer applies and the match is re-evaluated.
753    /// Source and index are not touched — rejection is a cache-only
754    /// operation.
755    Reject {
756        /// Annotation id whose pending match you're rejecting.
757        annotation_id: String,
758        /// Canon id from the pending match.
759        canon_id: String,
760        /// Optional note recorded with the rejection. Useful for
761        /// capturing the *why* (e.g. "this canon entry is too broad",
762        /// "wrong category") for whoever revisits it later.
763        #[arg(long = "reason")]
764        reason: Option<String>,
765    },
766
767    /// List the current canon match state: one line per annotation
768    /// with pending / accepted / rejected counts, plus per-bucket
769    /// detail lines for each match. Reads `.aristo/canon-matches.toml`;
770    /// does not call the canon API.
771    List,
772
773    /// Fetch the canon entry detail for `<canon_id>` via the canon
774    /// API and render the longer description + example + references.
775    /// For the full trust card (server description + local binding
776    /// state combined), use `aristo show <bound_id>` instead.
777    Show {
778        /// Bare canon id (no `aristos:` / `kanon:` prefix). The
779        /// server's `GET /canon/entry/<canon_id>` endpoint returns
780        /// the same entry regardless of which tier you'd bind into;
781        /// the prefix is a per-user, per-scope attribute.
782        canon_id: String,
783        /// Optional explicit version (`v<minor>.<patch>`). Omit to
784        /// get the catalog's currently active version.
785        #[arg(long = "version")]
786        version: Option<String>,
787    },
788
789    /// Re-query the canon API for every annotation in the index,
790    /// bypassing the local match cache. Equivalent to
791    /// `aristo stamp --refresh-canon` without the rest of the stamp
792    /// pipeline — no source walk, no drift check, no index rewrite.
793    /// Useful when you know a new catalog version has shipped and
794    /// want fresh matches without a full stamp.
795    Refresh,
796
797    /// Reverse of `aristo canon accept`: strip the `aristos:` /
798    /// `kanon:` prefix from a canon-bound annotation, revert its
799    /// binding to `Local`, and drop the accepted_matches cache
800    /// entry. Source is rewritten in place (only the `id =` value
801    /// changes; canonical text + verify + parent are preserved).
802    /// The next `aristo stamp` may re-pull a fresh pending match
803    /// against the same annotation text.
804    ///
805    /// Unbind is for LIVE annotations. If the annotation was deleted
806    /// from source, no unbind is needed: the next `aristo stamp`
807    /// prunes its `.aristo/canon-matches.toml` entry automatically.
808    Unbind {
809        /// Canon-bound annotation id including the prefix (e.g.
810        /// `aristos:cell_written_exactly_once_per_page_edit`).
811        prefixed_id: String,
812    },
813
814    /// Record a verification-demand signal against a canon entry.
815    /// Idempotent on `(canon_id, repo, user)` — repeated calls don't
816    /// pile up. Use when an annotation is bound at the `kanon:` tier
817    /// and you'd like Aretta to invest in a verifier for that canon
818    /// entry.
819    RequestVerify {
820        /// Canon id (no prefix). The same id the trust card shows,
821        /// or that `aristo canon list` reports.
822        canon_id: String,
823        /// Optional note to attach to the demand signal (e.g.
824        /// "critical for our financial-tx audit"). A repeat call
825        /// with a new note replaces the previous one server-side.
826        #[arg(long = "notes")]
827        notes: Option<String>,
828    },
829
830    /// Report per-binding version drift between the local cache and
831    /// the canon API. Reports three classes: `current` (no change),
832    /// `patch-bump` (same canon_id, newer version — recommended
833    /// action: `aristo canon refresh`), and `minor-bump` (canon_id
834    /// retired — recommended action: `aristo canon unbind <id>` then
835    /// re-stamp). Currently diagnostic-only; automatic patch-bump
836    /// application is planned.
837    Migrate,
838
839    /// Download the canon catalogue (the full list of available canon
840    /// entries) to `.aristo/catalogue.json` — a gitignored local
841    /// snapshot — and print a summary. Requires authentication; served
842    /// by the org's server.
843    Catalogue,
844
845    /// Run the S2 presence probe against a local SUT checkout: union
846    /// the instrumentation bundles carried by this repo's accepted
847    /// canon matches, generate an ephemeral probe crate (one
848    /// type-checked accessor call per record), `[patch]` the SUT
849    /// package to `--sut-path`, and `cargo check` it twice — with the
850    /// bundle's instrumentation features on (presence) and off (the
851    /// accessors must vanish; gating check). Failures are classified
852    /// per accessor — missing (rustc E0599/E0609) vs
853    /// SUT_FEATURE_UNDECLARED (cargo feature resolution) — and
854    /// rendered as escalation cards naming the conformance catch that
855    /// needs the accessor. Reuses the SUT's Cargo.lock + target/ so a
856    /// warm probe compile takes seconds. Fully offline: reads
857    /// `.aristo/canon-matches.toml`; never calls the canon API.
858    Probe {
859        /// Path to the local SUT checkout root (e.g. your
860        /// aretta-ai/turso fork clone). The probe `[patch]`es the SUT
861        /// package to this path and docks into its build graph
862        /// (Cargo.lock, target/, toolchain file).
863        #[arg(long = "sut-path", value_name = "DIR")]
864        sut_path: PathBuf,
865        /// The escalation card's `[ flag-broken ]` decision: run the
866        /// probe, verify this accessor still fails, and append the
867        /// rustc evidence to `.aristo/instrumentation-debt.jsonl`
868        /// (committed, append-only). Flagged accessors are re-surfaced
869        /// as `SKIPPED(instr-debt: <id>)` on later runs — visible
870        /// debt, never silently green.
871        #[arg(
872            long = "flag-broken",
873            value_name = "ACCESSOR_ID",
874            conflicts_with = "gen_only"
875        )]
876        flag_broken: Option<String>,
877        /// Keep the generated probe crate directory (under the SUT
878        /// target dir) instead of removing it after the run.
879        #[arg(long = "keep-probe")]
880        keep_probe: bool,
881        /// Generate and write the probe crate, then stop before
882        /// compiling (implies --keep-probe). Useful for inspecting
883        /// exactly what the probe will check.
884        #[arg(long = "gen-only")]
885        gen_only: bool,
886    },
887
888    /// List or inspect queued §17 proof-tree suggestions (the related
889    /// canon entries dragged in alongside a primary match). Read-only:
890    /// it does not open a review session or mutate the queue. To review
891    /// and adopt suggestions, run `aristo session start intent-review`.
892    ///
893    /// With no argument, lists every queued cluster. With an
894    /// `<objective>` (the cluster's objective canon_id, or the seeding
895    /// primary id for siblings-only clusters), shows that cluster's
896    /// detail. With `--counts`, emits a machine-readable JSON summary
897    /// `{matches:{new,pending}, suggestions:{new,pending}}` for the
898    /// menu / skill entry Q&A.
899    Suggestions {
900        /// Objective canon_id (or seeding primary id) of the cluster to
901        /// show. Omit to list all queued clusters.
902        objective: Option<String>,
903        /// Emit counts only (`{matches:{...}, suggestions:{...}}`) as
904        /// JSON; no per-cluster detail. Mutually exclusive with
905        /// passing an `<objective>`.
906        #[arg(long = "counts", conflicts_with = "objective")]
907        counts: bool,
908        /// Scope the listing with the shared `--filter` grammar
909        /// (`id=`, `file=[:LO-HI]`, `parent=`, `status=`). The
910        /// `cluster <objective>` mode (§6B) is `--filter
911        /// parent=<kanon:objective>` — it scopes the list to one proof
912        /// cluster (leaves carry `parent=`). Multiple `--filter` flags
913        /// AND together. No new grammar — reuses `filter.rs` verbatim.
914        #[arg(
915            long = "filter",
916            value_name = "KEY=VALUE",
917            conflicts_with = "objective"
918        )]
919        filter: Vec<Filter>,
920    },
921}
922
923/// Subcommands under `aristo session`. Each maps to one substrate
924/// operation; per-kind side effects (e.g. mutating a `.critique`
925/// file on accept) plug in via the `SessionKind` trait wired in
926/// step 5.
927#[derive(clap::Subcommand, Debug)]
928pub(crate) enum SessionAction {
929    /// Begin a new review session of the given kind. Fails if a
930    /// session is already active — pass `--allow-nesting` to override
931    /// (currently no kind allows nesting).
932    Start {
933        /// Session kind (`critique-review`, `proof-review`).
934        kind: String,
935        /// Display label for the artifact under review (e.g.
936        /// `src/critique/pending.rs` or
937        /// `proof:balance_no_duplicate_cells`).
938        #[arg(long = "subject")]
939        subject: String,
940        /// Override the kind's default nesting policy. Currently only
941        /// `Disallow` is implemented; the flag is reserved for future
942        /// per-kind opt-ins.
943        #[arg(long = "allow-nesting", default_value_t = false)]
944        allow_nesting: bool,
945    },
946    /// Print the active session id (or empty stdout if none).
947    /// Exit 0 either way.
948    Active {
949        /// Emit the full `<system-reminder>` block instead of just
950        /// the id — for the `UserPromptSubmit` hook installed by
951        /// `aristo install-skills`. Empty stdout when no session
952        /// is active (the hook then injects nothing).
953        #[arg(long = "hook-format", default_value_t = false)]
954        hook_format: bool,
955    },
956    /// Print bucket counts + open items for the active session.
957    /// Exit 0; errors out if no session is active.
958    Status,
959    /// Record a decision on one item in the active session.
960    Decide {
961        /// Item reference (`<id>#<index>` for indexed items, or any
962        /// opaque per-kind string).
963        #[arg(long = "item")]
964        item: String,
965        /// Which bucket the item lands in.
966        #[arg(long = "bucket", value_enum)]
967        bucket: BucketArg,
968        /// Optional note recorded with the decision.
969        #[arg(long = "note")]
970        note: Option<String>,
971    },
972    /// Close the active session. Strict by default — errors out if
973    /// any items are still in the open bucket.
974    Exit {
975        /// Move open items to the per-kind backlog instead of
976        /// erroring. Items are never silently dropped; the next
977        /// session of this kind surfaces them via the backlog menu.
978        #[arg(long = "defer-undecided", default_value_t = false)]
979        defer_undecided: bool,
980    },
981    /// Cancel the session and discard every decision recorded so far.
982    /// Requires `--yes` to skip the confirmation prompt.
983    Abort {
984        /// Skip the confirmation prompt.
985        #[arg(long = "yes", default_value_t = false)]
986        yes: bool,
987    },
988    /// List the active session and the most recent N closed sessions.
989    List {
990        /// Maximum number of closed-session rows to include.
991        #[arg(long = "limit", default_value_t = 10)]
992        limit: usize,
993    },
994}
995
996/// User-facing bucket choices for `aristo session decide`. Maps to
997/// the substrate's [`session::types::ItemStatus`] (minus `Open`,
998/// which is the implicit pre-decision state).
999#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
1000pub(crate) enum BucketArg {
1001    Accepted,
1002    Rejected,
1003    Pending,
1004}
1005
1006/// Process entry point. Parses `argv`, dispatches to the chosen subcommand,
1007/// and returns the exit code. Prints `error: <msg>` to stderr on any
1008/// `CliError`.
1009pub fn run() -> ExitCode {
1010    let cli = Cli::parse();
1011    let code = match dispatch(cli.command) {
1012        Ok(()) => ExitCode::SUCCESS,
1013        Err(e) => {
1014            if !e.is_silent() {
1015                eprintln!("error: {e}");
1016            }
1017            ExitCode::from(e.exit_code())
1018        }
1019    };
1020    // Best-effort "newer aristo available" notice, printed after the
1021    // command's own output and never affecting its exit code. Silent in
1022    // CI / pipes / on opt-out (see `update_notify`).
1023    update_notify::maybe_notify();
1024    code
1025}
1026
1027/// Maps a parsed `Commands` variant to its handler.
1028fn dispatch(cmd: Commands) -> CliResult<()> {
1029    match cmd {
1030        Commands::Init {
1031            force,
1032            ci,
1033            ci_verify,
1034            hook,
1035        } => commands::init::run(force, ci, ci_verify, hook),
1036        Commands::Lang { file } => commands::lang::run(file),
1037        Commands::InstallSkills {
1038            agent,
1039            list_agents,
1040            user,
1041            update,
1042            check,
1043            hook_format,
1044        } => {
1045            commands::install_skills::install(agent, list_agents, user, update, check, hook_format)
1046        }
1047        Commands::UninstallSkills { agent, user, force } => {
1048            commands::install_skills::uninstall(agent, user, force)
1049        }
1050        Commands::Index { all } => commands::index::run(all),
1051        Commands::Stamp {
1052            check,
1053            skip_canon,
1054            refresh_canon,
1055            gc,
1056        } => commands::stamp::run(check, skip_canon, refresh_canon, gc),
1057        Commands::Show {
1058            selector,
1059            json,
1060            toml_out,
1061        } => commands::show::run(&selector, output_mode(json, toml_out)),
1062        Commands::List { filters, json } => commands::list::run(&filters, json),
1063        Commands::Status => commands::status::run(),
1064        Commands::Metrics { json } => commands::metrics::run(json),
1065        Commands::Nudge { event } => commands::nudge::run(event),
1066        Commands::Statusline => commands::statusline::run(),
1067        Commands::Review { mark, json } => commands::review::run(json, mark),
1068        Commands::Lint { check, fix, strict } => commands::lint::run(check, fix, strict),
1069        Commands::Verify {
1070            filters,
1071            rerun,
1072            check,
1073            strict,
1074            audit,
1075            apply_verdicts,
1076            rewrite_hashes,
1077            submit_verdict,
1078            id,
1079            json,
1080            pop_next,
1081            queue_status,
1082            wait,
1083            require_dispatch,
1084            view,
1085            tags,
1086            accept,
1087            because,
1088            tracking,
1089        } => commands::verify::run(
1090            &filters,
1091            rerun,
1092            check,
1093            strict,
1094            audit,
1095            apply_verdicts,
1096            rewrite_hashes,
1097            submit_verdict,
1098            pop_next,
1099            queue_status,
1100            id,
1101            json,
1102            wait,
1103            require_dispatch,
1104            view,
1105            &tags,
1106            accept,
1107            because,
1108            tracking,
1109        ),
1110        Commands::Critique {
1111            filters,
1112            apply_findings,
1113            include_closed,
1114            rerun,
1115            staged,
1116            all,
1117            yes,
1118            pop_next,
1119            queue_status,
1120            submit_findings,
1121            id,
1122            json,
1123        } => commands::critique::run(
1124            &filters,
1125            submit_findings,
1126            pop_next,
1127            queue_status,
1128            apply_findings,
1129            include_closed,
1130            rerun,
1131            staged,
1132            all,
1133            yes,
1134            id,
1135            json,
1136        ),
1137        Commands::Doc {
1138            summary,
1139            include_status,
1140            check,
1141            include_graph,
1142        } => commands::doc::run(summary, include_status, check, include_graph),
1143        Commands::Graph {
1144            format,
1145            out,
1146            filters,
1147            exclude_assumes,
1148            depth,
1149            include_orphans,
1150            include_status,
1151        } => commands::graph::run(
1152            &format,
1153            out,
1154            &filters,
1155            exclude_assumes,
1156            depth,
1157            include_orphans,
1158            include_status,
1159        ),
1160        Commands::Badge { out, style, metric } => {
1161            let style =
1162                commands::badge::Style::parse(&style).map_err(|message| CliError::Other {
1163                    message,
1164                    exit_code: 2,
1165                })?;
1166            let metric =
1167                commands::badge::Metric::parse(&metric).map_err(|message| CliError::Other {
1168                    message,
1169                    exit_code: 2,
1170                })?;
1171            commands::badge::run(out, style, metric)
1172        }
1173        Commands::Rename {
1174            old_id,
1175            new_id,
1176            dry_run,
1177        } => commands::rename::run(&old_id, &new_id, dry_run),
1178        Commands::Session { action } => commands::session::run(action),
1179        Commands::Auth { action } => commands::auth::run(action),
1180        Commands::Canon { action } => match action {
1181            CanonAction::Accept {
1182                annotation_id,
1183                canon_id,
1184            } => commands::canon::accept::run(&annotation_id, &canon_id),
1185            CanonAction::Reject {
1186                annotation_id,
1187                canon_id,
1188                reason,
1189            } => commands::canon::reject::run(&annotation_id, &canon_id, reason),
1190            CanonAction::List => commands::canon::list::run(),
1191            CanonAction::Show { canon_id, version } => {
1192                commands::canon::show::run(&canon_id, version)
1193            }
1194            CanonAction::Refresh => commands::canon::refresh::run(),
1195            CanonAction::Unbind { prefixed_id } => commands::canon::unbind::run(&prefixed_id),
1196            CanonAction::RequestVerify { canon_id, notes } => {
1197                commands::canon::request_verify::run(&canon_id, notes)
1198            }
1199            CanonAction::Migrate => commands::canon::migrate::run(),
1200            CanonAction::Catalogue => commands::canon::catalogue::run(),
1201            CanonAction::Probe {
1202                sut_path,
1203                flag_broken,
1204                keep_probe,
1205                gen_only,
1206            } => {
1207                commands::canon::probe::run(&sut_path, flag_broken.as_deref(), keep_probe, gen_only)
1208            }
1209            CanonAction::Suggestions {
1210                objective,
1211                counts,
1212                filter,
1213            } => commands::canon::suggestions::run(objective, counts, filter),
1214        },
1215        Commands::Instrument { action } => match action {
1216            InstrumentAction::VendorC { out } => commands::instrument::vendor_c::run(out),
1217            InstrumentAction::GenC {
1218                paths,
1219                handle_header,
1220                out,
1221                check,
1222            } => commands::instrument::gen_c::run(paths, handle_header, out, check),
1223        },
1224    }
1225}
1226
1227fn output_mode(json: bool, toml_out: bool) -> commands::show::OutputMode {
1228    if json {
1229        commands::show::OutputMode::Json
1230    } else if toml_out {
1231        commands::show::OutputMode::Toml
1232    } else {
1233        commands::show::OutputMode::Text
1234    }
1235}
1236
1237#[cfg(test)]
1238mod tests {
1239    use super::*;
1240    use clap::CommandFactory;
1241
1242    #[test]
1243    fn cli_parser_construction_is_valid() {
1244        // clap performs a structural sanity check (e.g. no duplicate
1245        // subcommand names) when CommandFactory::command() runs. We assert
1246        // it succeeds rather than panicking at runtime when a user types
1247        // `--help`. Cheap canary against future enum-shape mistakes.
1248        Cli::command().debug_assert();
1249    }
1250
1251    // Note: slice 32 removed the last `not_yet(...)` stub (Rename now
1252    // has a real implementation). The `CliError::NotImplemented` variant
1253    // is kept for future stubs but is no longer reachable from dispatch.
1254}