Skip to main content

agent_first_data/
cli_afdata.rs

1//! AFDATA adapter for the closed-world CLI core.
2//!
3//! [`crate::cli_spec`] decides whether an invocation is legal and what it
4//! resolved to. It deliberately knows nothing about how AFDATA expresses that
5//! decision. This module is the only place where the two meet: it turns a
6//! resolved outcome into a protocol event and owns AFDATA's `_secret` naming
7//! convention.
8
9use crate::cli_spec::SourceScheme;
10use crate::cli_spec::{
11    ArgValueType, BoundCliSpec, BoundOutcome, BuiltCliSpec, CliError, CliErrorRule, CliSpec,
12    CliSpecError, InvocationReadError, OutputPlan, ResolvedHelp, ResolvedInvocation,
13    ResolvedVersion,
14};
15use crate::protocol::{Event, json_error, json_result};
16
17/// Standard terminal diagnostic for an output sink that could not be installed.
18pub fn cli_output_setup_failed_event(detail: &str) -> Event {
19    json_error(
20        "output_setup_failed",
21        if detail.is_empty() {
22            "an output sink could not be established"
23        } else {
24            detail
25        },
26    )
27    .build()
28    .unwrap_or_else(|_| cli_invocation_invalid_event("could not construct output setup diagnostic"))
29}
30
31/// Standard terminal diagnostic for a non-broken-pipe output write failure.
32pub fn cli_output_write_failed_event() -> Event {
33    json_error("output_write_failed", "could not write command output")
34        .build()
35        .unwrap_or_else(|_| {
36            cli_invocation_invalid_event("could not construct output write diagnostic")
37        })
38}
39
40/// Why a CLI run ends with a given event and exit code instead of its own
41/// outcome: an argv rejection, a refused pre-run check, a handler's projection
42/// that cannot proceed, or a defect in how the program read its invocation.
43///
44/// Built from a [`CliError`] (the registry's own usage errors, exit 2), from an
45/// [`InvocationReadError`] (`cli_invocation_invalid`, exit 1), with
46/// [`CliStop::invalid_argument`] for a value constraint the registry cannot
47/// express, or from any event and code with [`CliStop::new`].
48#[derive(Debug)]
49pub struct CliStop {
50    event: Event,
51    exit_code: u8,
52}
53
54impl CliStop {
55    pub fn new(event: Event, exit_code: u8) -> Self {
56        Self { event, exit_code }
57    }
58
59    /// A value the registry's types cannot judge — exactly one character, a
60    /// well-formed address — refused under the same classification the parser
61    /// uses for its own value errors: `cli_invalid_argument_value`, exit 2.
62    pub fn invalid_argument(message: &str, hint: &str) -> Self {
63        let event = json_error(CliErrorRule::InvalidArgumentValue.code(), message)
64            .hint(hint)
65            .build()
66            .unwrap_or_else(|_| cli_invocation_invalid_event("could not construct usage error"));
67        Self::new(event, 2)
68    }
69
70    pub fn event(&self) -> &Event {
71        &self.event
72    }
73
74    pub const fn exit_code(&self) -> u8 {
75        self.exit_code
76    }
77
78    pub fn into_parts(self) -> (Event, u8) {
79        (self.event, self.exit_code)
80    }
81}
82
83impl From<CliError> for CliStop {
84    fn from(error: CliError) -> Self {
85        Self::new(cli_error_event(&error), error.exit_code())
86    }
87}
88
89impl From<InvocationReadError> for CliStop {
90    fn from(error: InvocationReadError) -> Self {
91        Self::new(cli_invocation_invalid_event(&error.to_string()), 1)
92    }
93}
94
95/// A handler bound to an action: the pure step from a resolved invocation to
96/// the program's own command value. It runs before any output sink opens, so
97/// a refusal here never leaves a redirect file behind.
98pub type CliHandler<C> = fn(&ResolvedInvocation) -> Result<C, CliStop>;
99
100/// The emitter a [`CliMain`] hands to the program, wired to the process
101/// streams as the resolved plan asks.
102pub type ProcessEmitter = crate::cli::CliEmitter<Box<dyn std::io::Write>>;
103
104type VersionHook<'a> = Box<dyn FnOnce(&ResolvedVersion) -> Event + 'a>;
105
106type CheckHook<'a, C> =
107    Box<dyn FnOnce(&BoundOutcome<Result<C, CliStop>>) -> Result<(), CliStop> + 'a>;
108
109/// The whole lifecycle of a registry-compiled CLI, from `main`.
110///
111/// ```text
112/// build registry ─ bind actions ─ resolve argv ─ check ─ project
113///     ─ install --stdout-file/--stderr-file ─ help | version | docs | run
114///     ─ settle write failures ─ exit code
115/// ```
116///
117/// Each step's failure has one report. A registry that does not build or bind
118/// is `cli_spec_invalid` / `cli_actions_invalid` (exit 1); a rejected argv is
119/// its [`CliError`] code; a [`check`](Self::check) or a handler may stop with a
120/// [`CliStop`]. All of those happen before a sink is opened and are reported as
121/// strict JSON on stderr, so a refused call never creates a redirect file.
122/// Then the sinks are installed (`output_setup_failed` if they cannot be, or if
123/// this build has no `stream-redirect` and one was asked for), and help,
124/// version and docs are answered. A run calls `execute` with the handler's
125/// command, the invocation and an emitter built from the plan; that emitter
126/// is the only route to stdout and stderr, raw bytes included. Whatever
127/// `execute` returns is settled against what the emitter wrote: a closed reader
128/// is exit 0, any other failed write exit 4 with `output_write_failed`.
129pub struct CliMain<'a, C> {
130    bound: Result<BoundCliSpec<Result<C, CliStop>>, CliStop>,
131    check: Option<CheckHook<'a, C>>,
132    version: Option<VersionHook<'a>>,
133}
134
135/// A resolved command whose output sinks stay installed until this handle drops.
136pub struct PreparedCli<C> {
137    /// The projected command, which can be moved out without dropping the sinks.
138    pub command: C,
139    /// The resolved invocation.
140    pub invocation: ResolvedInvocation,
141    _sinks: InstalledSinks,
142}
143
144impl<C> PreparedCli<C> {
145    /// Return the output plan for this process.
146    pub fn output_plan(&self) -> &OutputPlan {
147        self.invocation.output_plan()
148    }
149
150    /// Create an emitter for one command or logical request.
151    pub fn emitter(&self) -> ProcessEmitter {
152        crate::cli::CliEmitter::from_plan(self.output_plan())
153    }
154
155    /// Execute a synchronous command and settle its output status.
156    pub fn execute(
157        self,
158        execute: impl FnOnce(C, &ResolvedInvocation, &mut ProcessEmitter) -> Result<u8, CliStop>,
159    ) -> std::process::ExitCode {
160        let PreparedCli {
161            command,
162            invocation,
163            _sinks,
164        } = self;
165        let mut emitter = crate::cli::CliEmitter::from_plan(invocation.output_plan());
166        let result = execute(command, &invocation, &mut emitter);
167        settle_output(&mut emitter, result)
168    }
169}
170
171impl<'a, C> CliMain<'a, C> {
172    /// Bind `actions` — built from the registry, for a program whose handler
173    /// table depends on it — to `cli`.
174    pub fn new<I, S>(
175        cli: Result<BuiltCliSpec, CliSpecError>,
176        actions: impl FnOnce(&BuiltCliSpec) -> I,
177    ) -> Self
178    where
179        I: IntoIterator<Item = (S, CliHandler<C>)>,
180        S: Into<String>,
181    {
182        let bound = match cli {
183            Err(error) => Err(startup_stop(
184                "cli_spec_invalid",
185                &error.to_string(),
186                "fix the program's cli-spec-v1 registry",
187            )),
188            Ok(cli) => cli.bind_actions(actions(&cli)).map_err(|error| {
189                startup_stop(
190                    "cli_actions_invalid",
191                    &error.to_string(),
192                    "make the action handlers match the registry's actions exactly",
193                )
194            }),
195        };
196        Self {
197            bound,
198            check: None,
199            version: None,
200        }
201    }
202
203    /// Run `hook` on every resolved outcome before anything is projected or
204    /// opened: capability checks that depend on how the program was started,
205    /// and argument constraints that span the whole program. A refusal is
206    /// reported and no sink is created.
207    #[must_use]
208    pub fn check(
209        mut self,
210        hook: impl FnOnce(&BoundOutcome<Result<C, CliStop>>) -> Result<(), CliStop> + 'a,
211    ) -> Self {
212        self.check = Some(Box::new(hook));
213        self
214    }
215
216    /// Answer `--version` with this event instead of [`cli_version_event`]:
217    /// for a program whose version identity has more to it than the registry
218    /// carries, such as the protocol versions it speaks. Build it from
219    /// [`crate::build_cli_version`]'s fields so the standard ones stay.
220    #[must_use]
221    pub fn version(mut self, event: impl FnOnce(&ResolvedVersion) -> Event + 'a) -> Self {
222        self.version = Some(Box::new(event));
223        self
224    }
225
226    /// Resolve `argv` and carry the call through to its exit code.
227    pub fn run<A, T>(
228        self,
229        argv: A,
230        execute: impl FnOnce(C, &ResolvedInvocation, &mut ProcessEmitter) -> Result<u8, CliStop>,
231    ) -> std::process::ExitCode
232    where
233        A: IntoIterator<Item = T>,
234        T: Into<std::ffi::OsString>,
235    {
236        match self.prepare(argv) {
237            Ok(prepared) => prepared.execute(execute),
238            Err(exit) => exit,
239        }
240    }
241
242    /// Resolve argv and install output sinks, or complete a lifecycle response.
243    ///
244    /// An exit code represents a completed help, version, or documentation
245    /// response, or an error reported during preparation.
246    pub fn prepare<A, T>(self, argv: A) -> Result<PreparedCli<C>, std::process::ExitCode>
247    where
248        A: IntoIterator<Item = T>,
249        T: Into<std::ffi::OsString>,
250    {
251        let outcome = self
252            .bound
253            .and_then(|bound| bound.resolve_from(argv).map_err(CliStop::from));
254        let outcome = match outcome {
255            Ok(outcome) => outcome,
256            Err(stop) => return Err(stop_before_output(stop)),
257        };
258        if let Some(check) = self.check
259            && let Err(stop) = check(&outcome)
260        {
261            return Err(stop_before_output(stop));
262        }
263        match outcome {
264            BoundOutcome::Run(invocation) => {
265                let (projected, invocation) = invocation.run_with_invocation();
266                let command = match projected {
267                    Ok(command) => command,
268                    Err(stop) => return Err(stop_before_output(stop)),
269                };
270                let sinks = prepare_sinks(invocation.output_plan())?;
271                Ok(PreparedCli {
272                    command,
273                    invocation,
274                    _sinks: sinks,
275                })
276            }
277            BoundOutcome::Docs(docs) => Err(run_with_plan(docs.output_plan(), |emitter| {
278                Ok(emitter.finish_raw(render_cli_reference(docs.registry()).as_bytes()))
279            })),
280            BoundOutcome::Help(help) => Err(run_with_plan(help.output_plan(), |emitter| {
281                if help.output_plan().output_format() == Some(crate::OutputFormat::Plain) {
282                    Ok(emitter.finish_raw(help.plain().as_bytes()))
283                } else {
284                    Ok(emitter.finish(cli_help_event(&help), 0))
285                }
286            })),
287            BoundOutcome::Version(version) => {
288                Err(run_with_plan(version.output_plan(), |emitter| {
289                    let event = match self.version {
290                        Some(event) => event(&version),
291                        None => cli_version_event(&version),
292                    };
293                    Ok(emitter.finish(event, 0))
294                }))
295            }
296        }
297    }
298}
299
300/// The output half of [`CliMain`], for a program that arrived at its
301/// [`OutputPlan`] some other way — a translated foreign grammar, say.
302///
303/// Installs the plan's file sinks, builds the emitter the plan asks for, runs
304/// `execute`, and settles its exit code against what the emitter wrote. A
305/// [`CliStop`] from `execute` is emitted through that emitter.
306pub fn run_with_plan(
307    plan: &OutputPlan,
308    execute: impl FnOnce(&mut ProcessEmitter) -> Result<u8, CliStop>,
309) -> std::process::ExitCode {
310    let _sinks = match prepare_sinks(plan) {
311        Ok(sinks) => sinks,
312        Err(exit) => return exit,
313    };
314    let mut emitter = crate::cli::CliEmitter::from_plan(plan);
315    let result = execute(&mut emitter);
316    settle_output(&mut emitter, result)
317}
318
319fn settle_output(
320    emitter: &mut ProcessEmitter,
321    result: Result<u8, CliStop>,
322) -> std::process::ExitCode {
323    let code = match result {
324        Ok(code) => emitter.exit_code(code),
325        Err(stop) => {
326            let (event, code) = stop.into_parts();
327            emitter.finish(event, code)
328        }
329    };
330    std::process::ExitCode::from(code)
331}
332
333#[cfg(feature = "stream-redirect")]
334type InstalledSinks = Option<crate::stream_redirect::InstalledStreamRedirect>;
335#[cfg(not(feature = "stream-redirect"))]
336type InstalledSinks = ();
337
338fn prepare_sinks(plan: &OutputPlan) -> Result<InstalledSinks, std::process::ExitCode> {
339    install_sinks(plan).map_err(|detail| {
340        stop_before_output(CliStop::new(cli_output_setup_failed_event(&detail), 1))
341    })
342}
343
344#[cfg(feature = "stream-redirect")]
345fn install_sinks(plan: &OutputPlan) -> Result<InstalledSinks, String> {
346    crate::stream_redirect::install_from_plan(plan).map_err(|error| error.to_string())
347}
348
349#[cfg(not(feature = "stream-redirect"))]
350fn install_sinks(plan: &OutputPlan) -> Result<InstalledSinks, String> {
351    if plan.stdout_file().is_some() || plan.stderr_file().is_some() {
352        return Err(
353            "this build has no stream-redirect support, so file sinks are unavailable".to_string(),
354        );
355    }
356    Ok(())
357}
358
359fn startup_stop(code: &str, message: &str, hint: &str) -> CliStop {
360    let event = json_error(code, message)
361        .hint(hint)
362        .build()
363        .unwrap_or_else(|_| cli_invocation_invalid_event("could not construct startup error"));
364    CliStop::new(event, 1)
365}
366
367/// Nothing has been opened yet, so the report is strict JSON on stderr
368/// whatever the argv asked for: a refused call has no output plan to honor.
369fn stop_before_output(stop: CliStop) -> std::process::ExitCode {
370    let (event, code) = stop.into_parts();
371    let mut emitter =
372        crate::cli::CliEmitter::from_output_to(crate::OutputTo::Stderr, crate::OutputFormat::Json)
373            .with_strict_protocol();
374    std::process::ExitCode::from(emitter.finish(event, code))
375}
376
377/// Build a registry under AFDATA's naming conventions.
378///
379/// `ArgSpec::sensitive` is not an independent switch. AFDATA already decides
380/// what a secret is by the `_secret` suffix, and the same convention drives
381/// config keys, log fields, and redaction. Deriving the bit from the argument
382/// id keeps one source of truth: an argument cannot be sensitive to the parser
383/// while staying invisible to redaction downstream. Marking a differently named
384/// argument sensitive is the reverse mistake, so it fails the build instead of
385/// silently diverging.
386pub fn build_afdata_cli(mut spec: CliSpec) -> Result<BuiltCliSpec, CliSpecError> {
387    for argument in spec.shared_arguments.iter_mut().chain(
388        spec.commands
389            .iter_mut()
390            .flat_map(|command| &mut command.arguments),
391    ) {
392        let suffixed = argument.argument_id.ends_with("_secret");
393        let is_flag = matches!(argument.value_type, ArgValueType::Flag);
394        if argument.sensitive && !suffixed {
395            return Err(CliSpecError {
396                rule: "sensitive_without_secret_suffix",
397                message: format!(
398                    "argument `{}` is marked sensitive; rename it to `{}_secret` so AFDATA \
399                     redaction covers it too",
400                    argument.argument_id, argument.argument_id
401                ),
402            });
403        }
404        if argument.sensitive && is_flag {
405            return Err(CliSpecError {
406                rule: "sensitive_flag",
407                message: format!(
408                    "flag `{}` is marked sensitive, but a flag carries no value to redact",
409                    argument.argument_id
410                ),
411            });
412        }
413        // A flag has no value, so `_secret` in its name says what the flag
414        // is *about* — `--reveal-secret` asks to reveal one, it does not
415        // carry one. Marking it would put the sensitive bit on something
416        // that structurally cannot leak, which reads as a real credential
417        // to anything downstream that trusts the bit.
418        argument.sensitive = suffixed && !is_flag;
419
420        // A prompt suppresses terminal echo and blocks until a person
421        // types — the first only means something for a secret, and the
422        // second is a hang in the agent-run case this CLI is for. So the
423        // source is available exactly where it earns its cost.
424        if let Some(sources) = &argument.sources
425            && sources.accepts(SourceScheme::Prompt)
426            && !argument.sensitive
427        {
428            return Err(CliSpecError {
429                rule: "prompt_source_without_secret",
430                message: format!(
431                    "argument `{}` accepts the `prompt` source; rename it to `{}_secret`, or \
432                     drop the source — prompting blocks on a terminal for a value that is not \
433                     a credential",
434                    argument.argument_id, argument.argument_id
435                ),
436            });
437        }
438    }
439    let mut cli = spec.build()?;
440    let redactor = crate::Redactor::new();
441    cli.hide_help_defaults(|argument| {
442        redactor.is_url_name(&argument.argument_id)
443            || redactor.is_url_name(&crate::cli_spec::argument_key(argument).replace('-', "_"))
444    });
445    Ok(cli)
446}
447
448/// Wrap a resolved help response in a `cli-help-v2` result event.
449pub fn cli_help_event(help: &ResolvedHelp) -> Event {
450    json_result(serde_json::json!({
451        "code": "help",
452        "help": help.model(),
453    }))
454    .build()
455}
456
457/// Wrap a resolved version response in a protocol result event.
458///
459/// This delegates to [`crate::build_cli_version`] rather than assembling its
460/// own payload. There is one version shape — `{code, name, version}` plus
461/// `display_name`/`build` when the registry carries them — and it is the same
462/// one the Go, Python, and TypeScript SDKs emit.
463pub fn cli_version_event(version: &ResolvedVersion) -> Event {
464    crate::cli::build_cli_version(
465        version.name(),
466        version.display_name(),
467        version.version(),
468        version.build(),
469    )
470}
471
472/// Static prose for the generated CLI reference.
473///
474/// Kept as Markdown files rather than escaped Rust string literals: these are
475/// paragraphs, and as `\`-continued literals they cannot be read as prose in a
476/// diff, need every backtick and quote escaped, and turn a wording change into
477/// an exercise in line continuations. The surrounding structure — headings,
478/// tables, per-command sections — stays in code, because that part is generated
479/// from the registry and is not prose.
480///
481/// This reference is emitted by every spore's `--docs`, not just afdata's, so
482/// the text is shared library data and belongs beside the generator.
483const SHAPES_PROSE: &str = include_str!("cli_reference/shapes.md");
484const CLI_ERRORS_PROSE: &str = include_str!("cli_reference/cli-errors.md");
485
486/// Render an offline Markdown reference for a whole registry.
487///
488/// help-v2 is deliberately lossy: it answers "how do I call this" one command
489/// at a time, in as few tokens as possible. A reference manual wants the
490/// opposite, so it is a separate capability rather than a format on the
491/// discovery path — the agent's `--help` never grows a documentation mode, and
492/// the manual can never disagree with the parser, because both are this
493/// registry. `--docs` is injected into every registry, so a tool exposes this
494/// without registering a command, and without spending a line of its
495/// subcommand listing on something no agent calls.
496///
497/// What is deliberately *not* repeated: a lone combination's description and
498/// id — the command heading already carries the description, and the id only
499/// matters for telling siblings apart. Shared output and argument defaults
500/// are stated once at the widest scope at which they apply.
501pub fn render_cli_reference(cli: &BuiltCliSpec) -> String {
502    let spec = cli.spec();
503    let name = spec.name.as_str();
504    let mut commands: Vec<&crate::cli_spec::CommandSpec> = spec
505        .commands
506        .iter()
507        .filter(|command| !command.combinations.is_empty())
508        .collect();
509    commands.sort_by(|left, right| left.command_path.cmp(&right.command_path));
510
511    let path_of = |command: &crate::cli_spec::CommandSpec| {
512        if command.command_path.is_empty() {
513            name.to_string()
514        } else {
515            format!("{name} {}", command.command_path.join(" "))
516        }
517    };
518
519    let mut out = String::new();
520    out.push_str(&format!("# {name} CLI reference\n\n"));
521    out.push_str(&format!(
522        "<!-- Generated by `{name} --docs`. Do not edit by hand. -->\n\n"
523    ));
524    if let Some(about) = &spec.about {
525        out.push_str(&format!("{about}\n\n"));
526    }
527    out.push_str(&format!(
528        "`{name}` is compiled from a closed `cli-spec-v1` registry: one source for argv parsing, \
529         typed invocation values, which parameter combinations are legal, output contracts, and \
530         help. An invocation runs only when it matches exactly one registered combination.\n\n"
531    ));
532
533    // Everything AFDATA registers on the caller's behalf, in one place. Split
534    // across sections it reads as unrelated trivia, and `--version`/`--docs`
535    // fall through the gap entirely — they belong to no command, so no command
536    // section would ever mention them.
537    let baseline = baseline_output(&commands);
538    out.push_str("## Global arguments\n\n");
539    // Not "no command declares them": `--version` and `--docs` are answered by
540    // the root alone, so a command may declare its own argument under that
541    // spelling — where one does, the entry below is still only the root's.
542    out.push_str(
543        "AFDATA registers these itself, so the syntax in [Commands](#commands) \
544         leaves them out.\n\n",
545    );
546    out.push_str("| Argument | Where | What it does |\n|---|---|---|\n");
547    out.push_str(
548        "| `--help` | every command | Every legal shape of that command, complete, plus its \
549         subcommands. JSON by default; `--output plain` for a terminal. |\n",
550    );
551    out.push_str(&format!(
552        "| `--version` | {name} only | Name, version, and build identity as one protocol result. \
553         |\n"
554    ));
555    out.push_str(&format!(
556        "| `--docs` | {name} only | This document, rendered from the registry. |\n"
557    ));
558    if let Some(crate::cli_spec::OutputSpec::Protocol {
559        formats,
560        destinations,
561        default_format,
562        default_destination,
563        ..
564    }) = &baseline
565    {
566        out.push_str(&format!(
567            "| `--output <FORMAT>` | per output contract | Render as {} (default \
568             `{default_format}`). |\n",
569            formats.join(", ")
570        ));
571        out.push_str(&format!(
572            "| `--output-to <DESTINATION>` | per output contract | Route results and diagnostics \
573             to {} (default `{default_destination}`). |\n",
574            destinations.join(", ")
575        ));
576    }
577    out.push_str(
578        "| `--stdout-file <PATH>`, `--stderr-file <PATH>` | per output contract | Append that \
579         stream to a file instead. |\n\n",
580    );
581    let baseline_line = baseline.as_ref().map(describe_output);
582    // The table above already lists the arguments and their values; the only
583    // thing left to say is what a successful call actually writes.
584    if baseline.is_some() {
585        out.push_str(
586            "Success output is protocol events, on those terms, unless a command's own \
587             **Output** line says otherwise.\n\n",
588        );
589    }
590    out.push_str(SHAPES_PROSE);
591    out.push('\n');
592
593    out.push_str("## Commands\n\n");
594    for command in &commands {
595        let path = path_of(command);
596        let anchor = path.replace(' ', "-");
597        let about = command.about.as_deref().unwrap_or("");
598        out.push_str(&format!("- [`{path}`](#{anchor}) — {about}\n"));
599    }
600    out.push('\n');
601
602    for command in &commands {
603        let path = path_of(command);
604        out.push_str(&format!("### `{path}`\n\n"));
605        if let Some(about) = &command.about {
606            out.push_str(&format!("{about}\n\n"));
607        }
608
609        let catalog = cli.help_catalog(command, false);
610        let model = catalog.model;
611        let output_varies = command
612            .combinations
613            .windows(2)
614            .any(|pair| describe_output(&pair[0].output) != describe_output(&pair[1].output));
615        let shapes = model.shapes.iter().zip(&catalog.shape_defaults);
616        for ((shape, defaults), combination) in shapes.zip(&command.combinations) {
617            if model.shapes.len() > 1 {
618                let differs = shape.about.as_deref().unwrap_or_default();
619                out.push_str(&format!("#### `{}` — {differs}\n\n", shape.id));
620            }
621            let usage = &shape.usage;
622            let fence = "`".repeat(backtick_fence_len(usage).max(3));
623            out.push_str(&format!("{fence}\n{usage}\n{fence}\n\n"));
624            if output_varies {
625                out.push_str(&format!(
626                    "Output: {}.\n\n",
627                    describe_output(&combination.output)
628                ));
629            }
630            render_reference_defaults(&mut out, defaults);
631        }
632
633        if !output_varies {
634            let contract = describe_output(&command.combinations[0].output);
635            if Some(&contract) != baseline_line.as_ref() {
636                out.push_str(&format!("Output: {contract}.\n\n"));
637            }
638        }
639        if model.shapes.len() > 1 && model.defaults.keys().any(|name| !is_output_default(name)) {
640            out.push_str("#### Shared defaults\n\n");
641        }
642        render_reference_defaults(&mut out, &model.defaults);
643
644        let documented: Vec<(&crate::cli_spec::ArgSpec, String)> = command
645            .arguments
646            .iter()
647            .filter_map(|argument| Some((argument, argument.rendered_about()?)))
648            .collect();
649        if !documented.is_empty() {
650            if model.shapes.len() > 1 {
651                // One table per command, so it necessarily spans shapes that
652                // cannot be used together; the syntax above is what says which
653                // argument belongs where.
654                out.push_str("Arguments across every shape above:\n\n");
655            }
656            out.push_str("| Argument | Meaning |\n|---|---|\n");
657            for (argument, about) in documented {
658                // The same spelling the usage line above uses, so the table can
659                // be read against it without translating ids back to flags.
660                out.push_str(&format!(
661                    "| `{}` | {about} |\n",
662                    crate::cli_spec::argument_key(argument)
663                ));
664            }
665            out.push('\n');
666        }
667
668        // After the table, because it is the paragraph the table cannot hold.
669        if let Some(note) = &command.reference_note {
670            out.push_str(note.trim_end());
671            out.push_str("\n\n");
672        }
673    }
674
675    out.push_str("## Exit codes\n\n");
676    out.push_str(
677        "| Code | Meaning |\n|---|---|\n\
678         | 0 | The command ran and succeeded. |\n\
679         | 1 | The command ran and failed. The event carries a domain `error.code`. |\n\
680         | 2 | The invocation was rejected before anything ran. `error.code` is one of the \
681         `cli_*` codes below. |\n",
682    );
683    // Sorted rather than left in declaration order: the table is read by code,
684    // and a registry author's ordering is not the reader's.
685    let mut declared_exit_codes: Vec<(u8, &str)> = spec
686        .exit_codes
687        .iter()
688        .map(|exit| (exit.code, exit.meaning.as_str()))
689        .collect();
690    declared_exit_codes.push((
691        4,
692        "Output could not be written (`output_write_failed`); a closed reader is success.",
693    ));
694    declared_exit_codes.sort_by_key(|(code, _)| *code);
695    for (code, meaning) in declared_exit_codes {
696        out.push_str(&format!("| {code} | {meaning} |\n"));
697    }
698    out.push_str(
699        "\nThe split is the useful one for a caller: exit 2 means the call was never made, so \
700         retrying it unchanged cannot help, while exit 1 means it was.\n\n",
701    );
702
703    out.push_str("## CLI errors\n\n");
704    out.push_str(CLI_ERRORS_PROSE);
705    out
706}
707
708/// One line per command saying what its success output is, because the usage
709/// line can only show that by omission.
710fn describe_output(output: &crate::cli_spec::OutputSpec) -> String {
711    use crate::cli_spec::OutputSpec;
712    match output {
713        OutputSpec::Raw { file_sinks } => format!(
714            "raw bytes on success; rejects `--output` and `--output-to`{}. Failures are still \
715             strict JSON on stderr",
716            render_file_sinks(file_sinks)
717        ),
718        OutputSpec::Protocol {
719            formats,
720            destinations,
721            default_format,
722            default_destination,
723            file_sinks,
724            ..
725        } => format!(
726            "protocol events; `--output` {} (default `{default_format}`), `--output-to` {} \
727             (default `{default_destination}`){}",
728            formats.join("/"),
729            destinations.join("/"),
730            render_file_sinks(file_sinks),
731        ),
732    }
733}
734
735/// The output contract most commands share, if there is one worth hoisting.
736///
737/// Deterministic: ties break on the rendered description, never on registration
738/// order, so the same registry always renders the same document.
739fn baseline_output(
740    commands: &[&crate::cli_spec::CommandSpec],
741) -> Option<crate::cli_spec::OutputSpec> {
742    let mut counts: std::collections::BTreeMap<String, (usize, crate::cli_spec::OutputSpec)> =
743        std::collections::BTreeMap::new();
744    for command in commands {
745        let mut contracts: Vec<&crate::cli_spec::OutputSpec> = Vec::new();
746        for combination in &command.combinations {
747            if !contracts.contains(&&combination.output) {
748                contracts.push(&combination.output);
749            }
750        }
751        if let [only] = contracts.as_slice() {
752            let entry = counts
753                .entry(describe_output(only))
754                .or_insert((0, (*only).clone()));
755            entry.0 += 1;
756        }
757    }
758    counts
759        .into_iter()
760        .max_by(|left, right| left.1.0.cmp(&right.1.0).then_with(|| right.0.cmp(&left.0)))
761        .filter(|(_, (count, _))| *count > 1)
762        .map(|(_, (_, spec))| spec)
763}
764
765fn is_output_default(name: &str) -> bool {
766    matches!(name, "--output" | "--output-to")
767}
768
769fn render_reference_defaults(
770    out: &mut String,
771    defaults: &std::collections::BTreeMap<String, crate::cli_spec::CliValue>,
772) {
773    let items: Vec<_> = defaults
774        .iter()
775        .filter(|(name, _)| !is_output_default(name))
776        .map(|(name, value)| {
777            let literal = crate::cli_spec::display_help_default(value);
778            format!("{} = {}", code_span(name), code_span(&literal))
779        })
780        .collect();
781    if !items.is_empty() {
782        out.push_str(&format!("If omitted, {}.\n\n", items.join(", ")));
783    }
784}
785
786fn backtick_fence_len(text: &str) -> usize {
787    let mut longest = 0;
788    let mut run = 0;
789    for byte in text.bytes() {
790        if byte == b'`' {
791            run += 1;
792            longest = longest.max(run);
793        } else {
794            run = 0;
795        }
796    }
797    longest + 1
798}
799
800fn code_span(text: &str) -> String {
801    let fence = "`".repeat(backtick_fence_len(text));
802    if text.starts_with('`') || text.ends_with('`') {
803        format!("{fence} {text} {fence}")
804    } else {
805        format!("{fence}{text}{fence}")
806    }
807}
808
809fn render_file_sinks(file_sinks: &[String]) -> String {
810    let mut names: Vec<&str> = Vec::new();
811    if file_sinks.iter().any(|sink| sink == "stdout") {
812        names.push("`--stdout-file`");
813    }
814    if file_sinks.iter().any(|sink| sink == "stderr") {
815        names.push("`--stderr-file`");
816    }
817    if names.is_empty() {
818        String::new()
819    } else {
820        format!("; redirect with {}", names.join(" or "))
821    }
822}
823
824/// Wrap a CLI-resolution failure in an event whose `code` names the failure.
825///
826/// The classification lives in `code`, the way `document_path_not_found` and
827/// its siblings already do — not in a second field beside a generic
828/// `cli_error`. One error taxonomy, one place to read it, and the skill's
829/// standing instruction ("branch on `error.code`") covers CLI errors too.
830///
831/// The event never carries raw argument values; `message` names the offending
832/// argument, and `hint` says what to run next.
833pub fn cli_error_event(error: &CliError) -> Event {
834    let builder = json_error(error.rule.code(), &error.message).hint(&error.hint);
835    match builder.build() {
836        Ok(event) => event,
837        Err(_) => json_error("cli_error", "failed to build CLI error")
838            .build()
839            .unwrap_or_else(|_| {
840                // All literals above are valid; this branch is unreachable
841                // but keeps production code panic-free.
842                json_result(serde_json::json!({"code":"internal_cli_error"})).build()
843            }),
844    }
845}
846
847/// The standard event for a program that misread its own resolved invocation.
848///
849/// Dispatch itself cannot fail —
850/// [`crate::cli_spec::BoundCliSpec::resolve_from`] binds the handler while
851/// resolving, so there is no undispatchable invocation to report. What remains
852/// is a handler reading an argument the selected combination does not supply:
853/// an id it does not declare, or one whose type does not match the accessor.
854/// [`crate::cli_spec::BoundCliSpec::call_every_combination`] catches the first
855/// from a test; this is for a program that also wants to say something at
856/// runtime.
857///
858/// It is a defect in the program, never in what the user typed, and the code
859/// and exit status have to say so. Reporting it as a usage error tells the
860/// caller to fix their command line and retry, and retrying cannot help — a
861/// mistake that has already been made in the wild, as
862/// `cli_invalid_argument_value` at exit 2. Emit this and exit 1; the
863/// application still owns the exit.
864pub fn cli_invocation_invalid_event(detail: &str) -> Event {
865    let builder = json_error("cli_invocation_invalid", detail)
866        .hint("this is a defect in the program, not in the command; report it");
867    match builder.build() {
868        Ok(event) => event,
869        Err(_) => json_error("cli_invocation_invalid", "invocation cannot be dispatched")
870            .build()
871            .unwrap_or_else(|_| {
872                // The literals above are valid, so this is unreachable; it
873                // keeps the path panic-free the way `cli_error_event` does.
874                json_result(serde_json::json!({"code":"internal_cli_error"})).build()
875            }),
876    }
877}
878
879#[cfg(test)]
880mod tests {
881    use super::*;
882    use crate::cli_spec::SourceSet;
883    use crate::cli_spec::{ArgSpec, CliOutcome, Combination, CommandSpec, OutputSpec};
884
885    fn output() -> OutputSpec {
886        OutputSpec::protocol_finite(["json"], ["split"], "json", "split")
887    }
888
889    fn spec_with(argument: ArgSpec) -> CliSpec {
890        let id = argument.argument_id.clone();
891        CliSpec::new("demo", "1").command(
892            CommandSpec::root().arg(argument).combination(
893                Combination::new("only")
894                    .action("only")
895                    .required([id])
896                    .output(output()),
897            ),
898        )
899    }
900
901    #[test]
902    fn a_cli_declares_exit_codes_beyond_afdatas_own() {
903        let spec = CliSpec::new("demo", "1.0.0")
904            .lifecycle_output(output())
905            .exit_code(5, "An application-specific failure.")
906            .exit_code(3, "The command ran and partly succeeded.")
907            .command(CommandSpec::root())
908            .build()
909            .unwrap();
910        let reference = render_cli_reference(&spec);
911        let table = reference
912            .split("## Exit codes")
913            .nth(1)
914            .expect("the reference documents exit codes");
915        // Sorted by code, not by declaration order: the table is read by code.
916        let partial = table.find("| 3 | The command ran and partly succeeded. |");
917        let write_failed = table.find("| 5 | An application-specific failure. |");
918        assert!(partial.is_some() && write_failed.is_some(), "{table}");
919        assert!(partial < write_failed, "{table}");
920    }
921
922    /// The syntax lives in the declaration, so help and `--docs` render it and
923    /// no `about` string repeats it. This is the duplication the declaration
924    /// exists to remove.
925    #[test]
926    fn a_declared_source_set_renders_itself_into_help_and_docs() {
927        let built = build_afdata_cli(spec_with(
928            ArgSpec::option("--token-secret", "SOURCE")
929                .about("Token this host requires")
930                .sources(SourceSet::config().host_scheme("container", "container:NAME")),
931        ))
932        .expect("registry builds");
933
934        let reference = render_cli_reference(&built);
935        assert!(
936            reference.contains(
937                "Token this host requires (the value, or where to read it: env:NAME, \
938                 file[+FORMAT]:PATH[#DOT_PATH], container:NAME, literal:VALUE)"
939            ),
940            "{reference}"
941        );
942
943        let CliOutcome::Help(help) = built
944            .resolve_from(vec!["demo", "--help"])
945            .expect("help resolves")
946        else {
947            panic!("--help must resolve to help");
948        };
949        let model = serde_json::to_value(help.model()).expect("help serializes");
950        let note = model["notes"]["--token-secret"]
951            .as_str()
952            .unwrap_or_default()
953            .to_string();
954        assert!(note.contains("file[+FORMAT]:PATH[#DOT_PATH]"), "{model}");
955    }
956
957    #[test]
958    fn reference_and_help_scope_public_defaults_and_preserve_literals() {
959        let literal = "`<value>|[--output fake]\nnext\\line`";
960        let url = "https://reader:url-canary@sample.invalid/";
961        let spec = CliSpec::new("demo", "1")
962            .shared_arg(ArgSpec::option("--endpoint-url", "URL").default(url))
963            .command(
964                CommandSpec::root()
965                    .arg(ArgSpec::option("--text", "TEXT").default(literal))
966                    .arg(ArgSpec::option_enum("--mode", ["first", "second"]).default("first"))
967                    .arg(ArgSpec::option_enum("--backup-url", [url]).default(url))
968                    .combination(
969                        Combination::new("first")
970                            .about("First invocation")
971                            .action("first")
972                            .fixed("mode", "first")
973                            .optional(["text", "backup_url"])
974                            .output(output()),
975                    )
976                    .combination(
977                        Combination::new("second")
978                            .about("Second invocation")
979                            .action("second")
980                            .fixed("mode", "second")
981                            .output(OutputSpec::protocol_finite(
982                                ["plain"],
983                                ["split"],
984                                "plain",
985                                "split",
986                            )),
987                    ),
988            );
989        let built = build_afdata_cli(spec).expect("registry builds");
990        let CliOutcome::Help(help) = built.resolve_from(["demo", "--help"]).unwrap() else {
991            panic!("expected help");
992        };
993        let model = serde_json::to_value(help.model()).unwrap();
994        assert_eq!(
995            model["defaults"],
996            serde_json::json!({"--mode": "first", "--output-to": "split", "--text": literal})
997        );
998        let first_about = model["shapes"][0]["about"].as_str().unwrap();
999        let second_about = model["shapes"][1]["about"].as_str().unwrap();
1000        assert!(
1001            first_about.contains("--mode=first, --output=json, --text="),
1002            "{first_about}"
1003        );
1004        assert!(
1005            first_about.contains(&format!("{literal:?}")),
1006            "{first_about}"
1007        );
1008        assert!(second_about.contains("--output=plain"), "{second_about}");
1009        assert!(!second_about.contains("--mode=first"), "{second_about}");
1010        assert!(model["notes"]["--text"].is_null());
1011        assert!(!model.to_string().contains("url-canary"), "{model}");
1012
1013        let plain = help.plain();
1014        assert!(plain.contains(first_about), "{plain}");
1015        assert!(plain.contains(second_about), "{plain}");
1016        assert!(!plain.contains("url-canary"), "{plain}");
1017
1018        let reference = render_cli_reference(&built);
1019        let (first, second) = reference.split_once("#### `second`").unwrap();
1020        assert!(
1021            first.contains("If omitted, `--mode` = `first`, `--text` ="),
1022            "{first}"
1023        );
1024        assert!(first.contains(&format!("``{literal:?}``")), "{first}");
1025        assert!(first.contains("default `json`"), "{first}");
1026        assert!(second.contains("default `plain`"), "{second}");
1027        assert!(!second.contains("`--mode` = `first`"), "{second}");
1028        assert!(!reference.contains("url-canary"), "{reference}");
1029
1030        let CliOutcome::Run(invocation) = built.resolve_from(["demo"]).unwrap() else {
1031            panic!("expected default invocation");
1032        };
1033        assert_eq!(invocation.text("endpoint_url").unwrap(), url);
1034    }
1035
1036    #[test]
1037    fn a_shared_secret_cannot_declare_a_default() {
1038        let error = build_afdata_cli(
1039            CliSpec::new("demo", "1")
1040                .shared_arg(ArgSpec::option("--token-secret", "TOKEN").default("secret-canary"))
1041                .command(
1042                    CommandSpec::root()
1043                        .combination(Combination::new("only").action("only").output(output())),
1044                ),
1045        )
1046        .expect_err("secret defaults must fail the build");
1047        assert_eq!(error.rule, "sensitive_default");
1048        assert!(!error.message.contains("secret-canary"));
1049    }
1050
1051    /// A value naming a scheme the argument does not accept is a usage error,
1052    /// beside the other argv rejections — and nothing was opened to find out.
1053    #[test]
1054    fn an_unaccepted_scheme_is_an_argv_rejection() {
1055        let built = build_afdata_cli(spec_with(
1056            ArgSpec::option("--token-secret", "SOURCE").sources(SourceSet::config()),
1057        ))
1058        .expect("registry builds");
1059        let error = built
1060            .resolve_from(vec!["demo", "--token-secret", "prompt"])
1061            .expect_err("prompt is not in config()");
1062        assert_eq!(
1063            error.rule,
1064            crate::cli_spec::CliErrorRule::InvalidArgumentValue
1065        );
1066        assert!(error.message.contains("env:NAME"), "{}", error.message);
1067
1068        // …and one it does accept resolves to the raw string, unread.
1069        let outcome = built
1070            .resolve_from(vec!["demo", "--token-secret", "env:NAME"])
1071            .expect("env is accepted");
1072        let CliOutcome::Run(invocation) = outcome else {
1073            panic!("must resolve to a run");
1074        };
1075        assert_eq!(
1076            invocation.source("token_secret").unwrap(),
1077            &crate::cli_spec::ValueSource::Env("NAME".to_string())
1078        );
1079    }
1080
1081    /// Prompting suppresses echo and blocks on a terminal. Both only make sense
1082    /// for a credential, so the source is refused anywhere else.
1083    #[test]
1084    fn the_prompt_source_is_refused_on_a_non_secret_argument() {
1085        let error = build_afdata_cli(spec_with(
1086            ArgSpec::option("--label", "LABEL").sources(SourceSet::stream()),
1087        ))
1088        .expect_err("prompt on a non-secret argument");
1089        assert_eq!(error.rule, "prompt_source_without_secret");
1090        // The same set is fine once the name says it carries a credential.
1091        assert!(
1092            build_afdata_cli(spec_with(
1093                ArgSpec::option("--token-secret", "SOURCE").sources(SourceSet::stream())
1094            ))
1095            .is_ok()
1096        );
1097    }
1098
1099    #[test]
1100    fn secret_suffix_drives_the_sensitive_bit() {
1101        let built = build_afdata_cli(spec_with(ArgSpec::option("--dsn-secret", "DSN"))).unwrap();
1102        let argument = &built.spec().commands[0].arguments[0];
1103        assert!(argument.sensitive);
1104    }
1105
1106    #[test]
1107    fn sensitive_without_the_suffix_fails_the_build() {
1108        let error = build_afdata_cli(spec_with(ArgSpec::option("--token", "TOKEN").sensitive()))
1109            .unwrap_err();
1110        assert_eq!(error.rule, "sensitive_without_secret_suffix");
1111    }
1112
1113    #[test]
1114    fn a_plain_argument_stays_insensitive() {
1115        let built = build_afdata_cli(spec_with(ArgSpec::option("--host", "HOST"))).unwrap();
1116        assert!(!built.spec().commands[0].arguments[0].sensitive);
1117    }
1118
1119    // Locks the version payload shape. `--version` is a discovery entry point
1120    // agents parse, and it lost `display_name`/`build` once before by going
1121    // through a second, hand-rolled payload instead of `build_cli_version`.
1122    #[test]
1123    fn version_events_carry_the_full_documented_payload() {
1124        let built = CliSpec::new("demo", "1.2.3")
1125            .display_name("Demo Tool")
1126            .build_id("abc1234")
1127            .command(CommandSpec::root())
1128            .build()
1129            .unwrap();
1130        let CliOutcome::Version(version) = built.resolve_from(["demo", "--version"]).unwrap()
1131        else {
1132            panic!("expected a version outcome");
1133        };
1134        assert_eq!(
1135            cli_version_event(&version).as_value(),
1136            &serde_json::json!({
1137                "kind": "result",
1138                "result": {
1139                    "code": "version",
1140                    "name": "demo",
1141                    "display_name": "Demo Tool",
1142                    "version": "1.2.3",
1143                    "build": "abc1234",
1144                },
1145                "trace": {},
1146            })
1147        );
1148    }
1149
1150    #[test]
1151    fn version_events_omit_absent_metadata() {
1152        let built = CliSpec::new("demo", "1.2.3")
1153            .command(CommandSpec::root())
1154            .build()
1155            .unwrap();
1156        let CliOutcome::Version(version) = built.resolve_from(["demo", "--version"]).unwrap()
1157        else {
1158            panic!("expected a version outcome");
1159        };
1160        let payload = serde_json::to_string(cli_version_event(&version).as_value()).unwrap();
1161        assert!(!payload.contains("display_name"), "{payload}");
1162        assert!(!payload.contains("build"), "{payload}");
1163    }
1164
1165    #[test]
1166    fn cli_error_events_never_carry_a_secret_value() {
1167        let built = build_afdata_cli(spec_with(ArgSpec::option("--dsn-secret", "DSN"))).unwrap();
1168        let error = built
1169            .resolve_from([
1170                "demo",
1171                "--dsn-secret",
1172                "postgres://user:password@example.test/db",
1173                "--unknown",
1174            ])
1175            .unwrap_err();
1176        let serialized = serde_json::to_string(cli_error_event(&error).as_value()).unwrap();
1177        assert!(!serialized.contains("password"));
1178        // The classification is the code, not a field beside it.
1179        assert!(serialized.contains("\"code\":\"cli_unknown_argument\""));
1180        // The command to run next reaches the caller through `hint`, which is
1181        // the channel every error event already has.
1182        assert!(serialized.contains("run `demo --help`"));
1183    }
1184
1185    /// The point of shipping this helper is that every consumer reports the
1186    /// same thing. Pin the code, so a consumer branching on it keeps working,
1187    /// and pin that it is not a `cli_*` usage code — a caller must not be told
1188    /// to fix their command line for a defect in the program.
1189    #[test]
1190    fn invocation_invalid_event_is_a_program_defect_not_a_usage_error() {
1191        let event = cli_invocation_invalid_event("no handler for this registry's invocation");
1192        let serialized = serde_json::to_string(event.as_value()).unwrap();
1193
1194        assert!(serialized.contains("\"code\":\"cli_invocation_invalid\""));
1195        assert!(serialized.contains("no handler for this registry's invocation"));
1196        // The hint has to say who should act. A usage hint here would send the
1197        // caller to debug their own arguments for a dispatch-table bug.
1198        assert!(serialized.contains("defect in the program"));
1199        assert!(
1200            crate::validate_protocol_event(event.as_value(), true).is_ok(),
1201            "the helper must emit a strict event: {serialized}"
1202        );
1203    }
1204
1205    #[test]
1206    fn a_secret_named_flag_is_not_marked_sensitive() {
1207        // `--reveal-secret` asks to reveal a secret; it does not carry one, and
1208        // a flag has no value that could leak. The suffix must not put the
1209        // sensitive bit on it.
1210        let built = build_afdata_cli(spec_with(ArgSpec::flag("--reveal-secret"))).unwrap();
1211        let argument = built
1212            .spec()
1213            .commands
1214            .iter()
1215            .flat_map(|command| &command.arguments)
1216            .find(|argument| argument.argument_id == "reveal_secret")
1217            .expect("the flag is registered");
1218        assert!(!argument.sensitive, "a flag has no value to redact");
1219    }
1220
1221    #[test]
1222    fn marking_a_flag_sensitive_is_a_contradiction() {
1223        let error = build_afdata_cli(spec_with(ArgSpec::flag("--reveal-secret").sensitive()))
1224            .expect_err("a sensitive flag must not build");
1225        assert_eq!(error.rule, "sensitive_flag");
1226    }
1227
1228    #[test]
1229    fn a_value_carrying_secret_argument_is_still_marked() {
1230        let built = build_afdata_cli(spec_with(ArgSpec::option("--dsn-secret", "DSN"))).unwrap();
1231        let argument = built
1232            .spec()
1233            .commands
1234            .iter()
1235            .flat_map(|command| &command.arguments)
1236            .find(|argument| argument.argument_id == "dsn_secret")
1237            .expect("the option is registered");
1238        assert!(argument.sensitive, "an option with a value still counts");
1239    }
1240
1241    #[test]
1242    fn an_invalid_argument_stop_is_a_usage_error() {
1243        let stop = CliStop::invalid_argument("expected one character", "pass a single character");
1244        assert_eq!(stop.exit_code(), 2);
1245        let value = stop.event().as_value();
1246        assert_eq!(value["kind"], "error");
1247        assert_eq!(value["error"]["code"], "cli_invalid_argument_value");
1248        assert_eq!(value["error"]["hint"], "pass a single character");
1249        let (event, code) = stop.into_parts();
1250        assert_eq!(code, 2);
1251        assert_eq!(
1252            event.as_value()["error"]["message"],
1253            "expected one character"
1254        );
1255    }
1256
1257    #[test]
1258    fn a_failed_read_stops_as_a_program_defect() {
1259        let built = build_afdata_cli(spec_with(ArgSpec::option("--label", "LABEL"))).unwrap();
1260        let CliOutcome::Run(invocation) = built
1261            .resolve_from(["demo", "--label", "a"])
1262            .expect("resolves")
1263        else {
1264            panic!("must resolve to a run");
1265        };
1266        let error = invocation.text("lable").unwrap_err();
1267        let stop = CliStop::from(error);
1268        assert_eq!(stop.exit_code(), 1);
1269        assert_eq!(
1270            stop.event().as_value()["error"]["code"],
1271            "cli_invocation_invalid"
1272        );
1273        assert!(
1274            stop.event().as_value()["error"]["message"]
1275                .as_str()
1276                .is_some_and(|message| message.contains("lable") && message.contains("only")),
1277            "{:?}",
1278            stop.event()
1279        );
1280    }
1281
1282    #[test]
1283    fn an_argv_rejection_stops_with_its_rule_code_and_exit_two() {
1284        let built = build_afdata_cli(spec_with(ArgSpec::option("--label", "LABEL"))).unwrap();
1285        let error = built
1286            .resolve_from(["demo", "--nope"])
1287            .expect_err("unknown argument");
1288        let stop = CliStop::from(error);
1289        assert_eq!(stop.exit_code(), 2);
1290        assert_eq!(
1291            stop.event().as_value()["error"]["code"],
1292            "cli_unknown_argument"
1293        );
1294    }
1295}