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 command in &mut spec.commands {
388        for argument in &mut command.arguments {
389            let suffixed = argument.argument_id.ends_with("_secret");
390            let is_flag = matches!(argument.value_type, ArgValueType::Flag);
391            if argument.sensitive && !suffixed {
392                return Err(CliSpecError {
393                    rule: "sensitive_without_secret_suffix",
394                    message: format!(
395                        "argument `{}` is marked sensitive; rename it to `{}_secret` so AFDATA \
396                         redaction covers it too",
397                        argument.argument_id, argument.argument_id
398                    ),
399                });
400            }
401            if argument.sensitive && is_flag {
402                return Err(CliSpecError {
403                    rule: "sensitive_flag",
404                    message: format!(
405                        "flag `{}` is marked sensitive, but a flag carries no value to redact",
406                        argument.argument_id
407                    ),
408                });
409            }
410            // A flag has no value, so `_secret` in its name says what the flag
411            // is *about* — `--reveal-secret` asks to reveal one, it does not
412            // carry one. Marking it would put the sensitive bit on something
413            // that structurally cannot leak, which reads as a real credential
414            // to anything downstream that trusts the bit.
415            argument.sensitive = suffixed && !is_flag;
416
417            // A prompt suppresses terminal echo and blocks until a person
418            // types — the first only means something for a secret, and the
419            // second is a hang in the agent-run case this CLI is for. So the
420            // source is available exactly where it earns its cost.
421            if let Some(sources) = &argument.sources
422                && sources.accepts(SourceScheme::Prompt)
423                && !argument.sensitive
424            {
425                return Err(CliSpecError {
426                    rule: "prompt_source_without_secret",
427                    message: format!(
428                        "argument `{}` accepts the `prompt` source; rename it to `{}_secret`, or \
429                         drop the source — prompting blocks on a terminal for a value that is not \
430                         a credential",
431                        argument.argument_id, argument.argument_id
432                    ),
433                });
434            }
435        }
436    }
437    spec.build()
438}
439
440/// Wrap a resolved help response in a `cli-help-v2` result event.
441pub fn cli_help_event(help: &ResolvedHelp) -> Event {
442    json_result(serde_json::json!({
443        "code": "help",
444        "help": help.model(),
445    }))
446    .build()
447}
448
449/// Wrap a resolved version response in a protocol result event.
450///
451/// This delegates to [`crate::build_cli_version`] rather than assembling its
452/// own payload. There is one version shape — `{code, name, version}` plus
453/// `display_name`/`build` when the registry carries them — and it is the same
454/// one the Go, Python, and TypeScript SDKs emit.
455pub fn cli_version_event(version: &ResolvedVersion) -> Event {
456    crate::cli::build_cli_version(
457        version.name(),
458        version.display_name(),
459        version.version(),
460        version.build(),
461    )
462}
463
464/// Static prose for the generated CLI reference.
465///
466/// Kept as Markdown files rather than escaped Rust string literals: these are
467/// paragraphs, and as `\`-continued literals they cannot be read as prose in a
468/// diff, need every backtick and quote escaped, and turn a wording change into
469/// an exercise in line continuations. The surrounding structure — headings,
470/// tables, per-command sections — stays in code, because that part is generated
471/// from the registry and is not prose.
472///
473/// This reference is emitted by every spore's `--docs`, not just afdata's, so
474/// the text is shared library data and belongs beside the generator.
475const SHAPES_PROSE: &str = include_str!("cli_reference/shapes.md");
476const CLI_ERRORS_PROSE: &str = include_str!("cli_reference/cli-errors.md");
477
478/// Render an offline Markdown reference for a whole registry.
479///
480/// help-v2 is deliberately lossy: it answers "how do I call this" one command
481/// at a time, in as few tokens as possible. A reference manual wants the
482/// opposite, so it is a separate capability rather than a format on the
483/// discovery path — the agent's `--help` never grows a documentation mode, and
484/// the manual can never disagree with the parser, because both are this
485/// registry. `--docs` is injected into every registry, so a tool exposes this
486/// without registering a command, and without spending a line of its
487/// subcommand listing on something no agent calls.
488///
489/// What is deliberately *not* repeated: a lone combination's description and
490/// id — the command heading already carries the description, and the id only
491/// matters for telling siblings apart — plus the shared output defaults and
492/// each command's arguments per combination. help repeats those because each help
493/// response is read alone; a document is read in order.
494pub fn render_cli_reference(cli: &BuiltCliSpec) -> String {
495    let spec = cli.spec();
496    let name = spec.name.as_str();
497    let mut commands: Vec<&crate::cli_spec::CommandSpec> = spec
498        .commands
499        .iter()
500        .filter(|command| !command.combinations.is_empty())
501        .collect();
502    commands.sort_by(|left, right| left.command_path.cmp(&right.command_path));
503
504    let path_of = |command: &crate::cli_spec::CommandSpec| {
505        if command.command_path.is_empty() {
506            name.to_string()
507        } else {
508            format!("{name} {}", command.command_path.join(" "))
509        }
510    };
511
512    let mut out = String::new();
513    out.push_str(&format!("# {name} CLI reference\n\n"));
514    out.push_str(&format!(
515        "<!-- Generated by `{name} --docs`. Do not edit by hand. -->\n\n"
516    ));
517    if let Some(about) = &spec.about {
518        out.push_str(&format!("{about}\n\n"));
519    }
520    out.push_str(&format!(
521        "`{name}` is compiled from a closed `cli-spec-v1` registry: one source for argv parsing, \
522         typed invocation values, which parameter combinations are legal, output contracts, and \
523         help. An invocation runs only when it matches exactly one registered combination.\n\n"
524    ));
525
526    // Everything AFDATA registers on the caller's behalf, in one place. Split
527    // across sections it reads as unrelated trivia, and `--version`/`--docs`
528    // fall through the gap entirely — they belong to no command, so no command
529    // section would ever mention them.
530    let baseline = baseline_output(&commands);
531    out.push_str("## Global arguments\n\n");
532    // Not "no command declares them": `--version` and `--docs` are answered by
533    // the root alone, so a command may declare its own argument under that
534    // spelling — where one does, the entry below is still only the root's.
535    out.push_str(
536        "AFDATA registers these itself, so the syntax in [Commands](#commands) \
537         leaves them out.\n\n",
538    );
539    out.push_str("| Argument | Where | What it does |\n|---|---|---|\n");
540    out.push_str(
541        "| `--help` | every command | Every legal shape of that command, complete, plus its \
542         subcommands. JSON by default; `--output plain` for a terminal. |\n",
543    );
544    out.push_str(&format!(
545        "| `--version` | {name} only | Name, version, and build identity as one protocol result. \
546         |\n"
547    ));
548    out.push_str(&format!(
549        "| `--docs` | {name} only | This document, rendered from the registry. |\n"
550    ));
551    if let Some(crate::cli_spec::OutputSpec::Protocol {
552        formats,
553        destinations,
554        default_format,
555        default_destination,
556        ..
557    }) = &baseline
558    {
559        out.push_str(&format!(
560            "| `--output <FORMAT>` | per output contract | Render as {} (default \
561             `{default_format}`). |\n",
562            formats.join(", ")
563        ));
564        out.push_str(&format!(
565            "| `--output-to <DESTINATION>` | per output contract | Route results and diagnostics \
566             to {} (default `{default_destination}`). |\n",
567            destinations.join(", ")
568        ));
569    }
570    out.push_str(
571        "| `--stdout-file <PATH>`, `--stderr-file <PATH>` | per output contract | Append that \
572         stream to a file instead. |\n\n",
573    );
574    let baseline_line = baseline.as_ref().map(describe_output);
575    // The table above already lists the arguments and their values; the only
576    // thing left to say is what a successful call actually writes.
577    if baseline.is_some() {
578        out.push_str(
579            "Success output is protocol events, on those terms, unless a command's own \
580             **Output** line says otherwise.\n\n",
581        );
582    }
583    out.push_str(SHAPES_PROSE);
584    out.push('\n');
585
586    out.push_str("## Commands\n\n");
587    for command in &commands {
588        let path = path_of(command);
589        let anchor = path.replace(' ', "-");
590        let about = command.about.as_deref().unwrap_or("");
591        out.push_str(&format!("- [`{path}`](#{anchor}) — {about}\n"));
592    }
593    out.push('\n');
594
595    for command in &commands {
596        let path = path_of(command);
597        out.push_str(&format!("### `{path}`\n\n"));
598        if let Some(about) = &command.about {
599            out.push_str(&format!("{about}\n\n"));
600        }
601
602        let Some(model) = cli.help(&command.command_path) else {
603            continue;
604        };
605        for shape in &model.shapes {
606            if model.shapes.len() > 1 {
607                let differs = shape.about.as_deref().unwrap_or_default();
608                out.push_str(&format!("#### `{}` — {differs}\n\n", shape.id));
609            }
610            out.push_str(&format!(
611                "```\n{}\n```\n\n",
612                trim_output_arguments(&shape.usage)
613            ));
614        }
615
616        let combinations: Vec<&crate::cli_spec::Combination> =
617            command.combinations.iter().collect();
618        let contracts = output_contracts(&combinations);
619        let is_baseline =
620            matches!((contracts.as_slice(), &baseline_line), ([only], Some(line)) if only == line);
621        if !is_baseline {
622            out.push_str(&render_output(&contracts));
623        }
624
625        let documented: Vec<(&crate::cli_spec::ArgSpec, String)> = command
626            .arguments
627            .iter()
628            .filter_map(|argument| Some((argument, argument.rendered_about()?)))
629            .collect();
630        if !documented.is_empty() {
631            if model.shapes.len() > 1 {
632                // One table per command, so it necessarily spans shapes that
633                // cannot be used together; the syntax above is what says which
634                // argument belongs where.
635                out.push_str("Arguments across every shape above:\n\n");
636            }
637            out.push_str("| Argument | Meaning |\n|---|---|\n");
638            for (argument, about) in documented {
639                // The same spelling the usage line above uses, so the table can
640                // be read against it without translating ids back to flags.
641                out.push_str(&format!(
642                    "| `{}` | {about} |\n",
643                    crate::cli_spec::argument_key(argument)
644                ));
645            }
646            out.push('\n');
647        }
648
649        // After the table, because it is the paragraph the table cannot hold.
650        if let Some(note) = &command.reference_note {
651            out.push_str(note.trim_end());
652            out.push_str("\n\n");
653        }
654    }
655
656    out.push_str("## Exit codes\n\n");
657    out.push_str(
658        "| Code | Meaning |\n|---|---|\n\
659         | 0 | The command ran and succeeded. |\n\
660         | 1 | The command ran and failed. The event carries a domain `error.code`. |\n\
661         | 2 | The invocation was rejected before anything ran. `error.code` is one of the \
662         `cli_*` codes below. |\n",
663    );
664    // Sorted rather than left in declaration order: the table is read by code,
665    // and a registry author's ordering is not the reader's.
666    let mut declared_exit_codes: Vec<(u8, &str)> = spec
667        .exit_codes
668        .iter()
669        .map(|exit| (exit.code, exit.meaning.as_str()))
670        .collect();
671    declared_exit_codes.push((
672        4,
673        "Output could not be written (`output_write_failed`); a closed reader is success.",
674    ));
675    declared_exit_codes.sort_by_key(|(code, _)| *code);
676    for (code, meaning) in declared_exit_codes {
677        out.push_str(&format!("| {code} | {meaning} |\n"));
678    }
679    out.push_str(
680        "\nThe split is the useful one for a caller: exit 2 means the call was never made, so \
681         retrying it unchanged cannot help, while exit 1 means it was.\n\n",
682    );
683
684    out.push_str("## CLI errors\n\n");
685    out.push_str(CLI_ERRORS_PROSE);
686    out
687}
688
689/// One line per command saying what its success output is, because the usage
690/// line can only show that by omission.
691fn describe_output(output: &crate::cli_spec::OutputSpec) -> String {
692    use crate::cli_spec::OutputSpec;
693    match output {
694        OutputSpec::Raw { file_sinks } => format!(
695            "raw bytes on success; rejects `--output` and `--output-to`{}. Failures are still \
696             strict JSON on stderr",
697            render_file_sinks(file_sinks)
698        ),
699        OutputSpec::Protocol {
700            formats,
701            destinations,
702            default_format,
703            default_destination,
704            file_sinks,
705            ..
706        } => format!(
707            "protocol events; `--output` {} (default `{default_format}`), `--output-to` {} \
708             (default `{default_destination}`){}",
709            formats.join("/"),
710            destinations.join("/"),
711            render_file_sinks(file_sinks),
712        ),
713    }
714}
715
716/// Each distinct output contract a command exposes, in a stable order.
717fn output_contracts(combinations: &[&crate::cli_spec::Combination]) -> Vec<String> {
718    let mut lines: Vec<String> = Vec::new();
719    for combination in combinations {
720        let line = describe_output(&combination.output);
721        if !lines.contains(&line) {
722            lines.push(line);
723        }
724    }
725    lines
726}
727
728/// The output contract most commands share, if there is one worth hoisting.
729///
730/// Deterministic: ties break on the rendered description, never on registration
731/// order, so the same registry always renders the same document.
732fn baseline_output(
733    commands: &[&crate::cli_spec::CommandSpec],
734) -> Option<crate::cli_spec::OutputSpec> {
735    let mut counts: std::collections::BTreeMap<String, (usize, crate::cli_spec::OutputSpec)> =
736        std::collections::BTreeMap::new();
737    for command in commands {
738        let mut contracts: Vec<&crate::cli_spec::OutputSpec> = Vec::new();
739        for combination in &command.combinations {
740            if !contracts.contains(&&combination.output) {
741                contracts.push(&combination.output);
742            }
743        }
744        if let [only] = contracts.as_slice() {
745            let entry = counts
746                .entry(describe_output(only))
747                .or_insert((0, (*only).clone()));
748            entry.0 += 1;
749        }
750    }
751    counts
752        .into_iter()
753        .max_by(|left, right| left.1.0.cmp(&right.1.0).then_with(|| right.0.cmp(&left.0)))
754        .filter(|(_, (count, _))| *count > 1)
755        .map(|(_, (_, spec))| spec)
756}
757
758fn render_output(contracts: &[String]) -> String {
759    match contracts {
760        [] => String::new(),
761        [only] => format!("Output: {only}.\n\n"),
762        many => {
763            let mut out = String::from("Output differs by combination:\n\n");
764            for line in many {
765                out.push_str(&format!("- {line}\n"));
766            }
767            out.push('\n');
768            out
769        }
770    }
771}
772
773/// Drop the trailing AFDATA output arguments from a usage line.
774///
775/// The compiler always renders them last and in a fixed order, and their names
776/// are reserved, so no application argument can be mistaken for one. A document
777/// states the output contract once per command; only `--help`, whose response
778/// is read on its own, needs them inline.
779fn trim_output_arguments(usage: &str) -> &str {
780    let cut = ["[--output ", "[--stdout-file ", "[--stderr-file "]
781        .iter()
782        .filter_map(|marker| usage.find(marker))
783        .min();
784    match cut {
785        Some(index) => usage[..index].trim_end(),
786        None => usage,
787    }
788}
789
790fn render_file_sinks(file_sinks: &[String]) -> String {
791    let mut names: Vec<&str> = Vec::new();
792    if file_sinks.iter().any(|sink| sink == "stdout") {
793        names.push("`--stdout-file`");
794    }
795    if file_sinks.iter().any(|sink| sink == "stderr") {
796        names.push("`--stderr-file`");
797    }
798    if names.is_empty() {
799        String::new()
800    } else {
801        format!("; redirect with {}", names.join(" or "))
802    }
803}
804
805/// Wrap a CLI-resolution failure in an event whose `code` names the failure.
806///
807/// The classification lives in `code`, the way `document_path_not_found` and
808/// its siblings already do — not in a second field beside a generic
809/// `cli_error`. One error taxonomy, one place to read it, and the skill's
810/// standing instruction ("branch on `error.code`") covers CLI errors too.
811///
812/// The event never carries raw argument values; `message` names the offending
813/// argument, and `hint` says what to run next.
814pub fn cli_error_event(error: &CliError) -> Event {
815    let builder = json_error(error.rule.code(), &error.message).hint(&error.hint);
816    match builder.build() {
817        Ok(event) => event,
818        Err(_) => json_error("cli_error", "failed to build CLI error")
819            .build()
820            .unwrap_or_else(|_| {
821                // All literals above are valid; this branch is unreachable
822                // but keeps production code panic-free.
823                json_result(serde_json::json!({"code":"internal_cli_error"})).build()
824            }),
825    }
826}
827
828/// The standard event for a program that misread its own resolved invocation.
829///
830/// Dispatch itself cannot fail —
831/// [`crate::cli_spec::BoundCliSpec::resolve_from`] binds the handler while
832/// resolving, so there is no undispatchable invocation to report. What remains
833/// is a handler reading an argument the selected combination does not supply:
834/// an id it does not declare, or one whose type does not match the accessor.
835/// [`crate::cli_spec::BoundCliSpec::call_every_combination`] catches the first
836/// from a test; this is for a program that also wants to say something at
837/// runtime.
838///
839/// It is a defect in the program, never in what the user typed, and the code
840/// and exit status have to say so. Reporting it as a usage error tells the
841/// caller to fix their command line and retry, and retrying cannot help — a
842/// mistake that has already been made in the wild, as
843/// `cli_invalid_argument_value` at exit 2. Emit this and exit 1; the
844/// application still owns the exit.
845pub fn cli_invocation_invalid_event(detail: &str) -> Event {
846    let builder = json_error("cli_invocation_invalid", detail)
847        .hint("this is a defect in the program, not in the command; report it");
848    match builder.build() {
849        Ok(event) => event,
850        Err(_) => json_error("cli_invocation_invalid", "invocation cannot be dispatched")
851            .build()
852            .unwrap_or_else(|_| {
853                // The literals above are valid, so this is unreachable; it
854                // keeps the path panic-free the way `cli_error_event` does.
855                json_result(serde_json::json!({"code":"internal_cli_error"})).build()
856            }),
857    }
858}
859
860#[cfg(test)]
861mod tests {
862    use super::*;
863    use crate::cli_spec::SourceSet;
864    use crate::cli_spec::{ArgSpec, CliOutcome, Combination, CommandSpec, OutputSpec};
865
866    fn output() -> OutputSpec {
867        OutputSpec::protocol_finite(["json"], ["split"], "json", "split")
868    }
869
870    fn spec_with(argument: ArgSpec) -> CliSpec {
871        let id = argument.argument_id.clone();
872        CliSpec::new("demo", "1").command(
873            CommandSpec::root().arg(argument).combination(
874                Combination::new("only")
875                    .action("only")
876                    .required([id])
877                    .output(output()),
878            ),
879        )
880    }
881
882    #[test]
883    fn a_cli_declares_exit_codes_beyond_afdatas_own() {
884        let spec = CliSpec::new("demo", "1.0.0")
885            .lifecycle_output(output())
886            .exit_code(5, "An application-specific failure.")
887            .exit_code(3, "The command ran and partly succeeded.")
888            .command(CommandSpec::root())
889            .build()
890            .unwrap();
891        let reference = render_cli_reference(&spec);
892        let table = reference
893            .split("## Exit codes")
894            .nth(1)
895            .expect("the reference documents exit codes");
896        // Sorted by code, not by declaration order: the table is read by code.
897        let partial = table.find("| 3 | The command ran and partly succeeded. |");
898        let write_failed = table.find("| 5 | An application-specific failure. |");
899        assert!(partial.is_some() && write_failed.is_some(), "{table}");
900        assert!(partial < write_failed, "{table}");
901    }
902
903    /// The syntax lives in the declaration, so help and `--docs` render it and
904    /// no `about` string repeats it. This is the duplication the declaration
905    /// exists to remove.
906    #[test]
907    fn a_declared_source_set_renders_itself_into_help_and_docs() {
908        let built = build_afdata_cli(spec_with(
909            ArgSpec::option("--token-secret", "SOURCE")
910                .about("Token this host requires")
911                .sources(SourceSet::config().host_scheme("container", "container:NAME")),
912        ))
913        .expect("registry builds");
914
915        let reference = render_cli_reference(&built);
916        assert!(
917            reference.contains(
918                "Token this host requires (the value, or where to read it: env:NAME, \
919                 file[+FORMAT]:PATH[#DOT_PATH], container:NAME, literal:VALUE)"
920            ),
921            "{reference}"
922        );
923
924        let CliOutcome::Help(help) = built
925            .resolve_from(vec!["demo", "--help"])
926            .expect("help resolves")
927        else {
928            panic!("--help must resolve to help");
929        };
930        let model = serde_json::to_value(help.model()).expect("help serializes");
931        let note = model["notes"]["--token-secret"]
932            .as_str()
933            .unwrap_or_default()
934            .to_string();
935        assert!(note.contains("file[+FORMAT]:PATH[#DOT_PATH]"), "{model}");
936    }
937
938    /// A value naming a scheme the argument does not accept is a usage error,
939    /// beside the other argv rejections — and nothing was opened to find out.
940    #[test]
941    fn an_unaccepted_scheme_is_an_argv_rejection() {
942        let built = build_afdata_cli(spec_with(
943            ArgSpec::option("--token-secret", "SOURCE").sources(SourceSet::config()),
944        ))
945        .expect("registry builds");
946        let error = built
947            .resolve_from(vec!["demo", "--token-secret", "prompt"])
948            .expect_err("prompt is not in config()");
949        assert_eq!(
950            error.rule,
951            crate::cli_spec::CliErrorRule::InvalidArgumentValue
952        );
953        assert!(error.message.contains("env:NAME"), "{}", error.message);
954
955        // …and one it does accept resolves to the raw string, unread.
956        let outcome = built
957            .resolve_from(vec!["demo", "--token-secret", "env:NAME"])
958            .expect("env is accepted");
959        let CliOutcome::Run(invocation) = outcome else {
960            panic!("must resolve to a run");
961        };
962        assert_eq!(
963            invocation.source("token_secret").unwrap(),
964            &crate::cli_spec::ValueSource::Env("NAME".to_string())
965        );
966    }
967
968    /// Prompting suppresses echo and blocks on a terminal. Both only make sense
969    /// for a credential, so the source is refused anywhere else.
970    #[test]
971    fn the_prompt_source_is_refused_on_a_non_secret_argument() {
972        let error = build_afdata_cli(spec_with(
973            ArgSpec::option("--label", "LABEL").sources(SourceSet::stream()),
974        ))
975        .expect_err("prompt on a non-secret argument");
976        assert_eq!(error.rule, "prompt_source_without_secret");
977        // The same set is fine once the name says it carries a credential.
978        assert!(
979            build_afdata_cli(spec_with(
980                ArgSpec::option("--token-secret", "SOURCE").sources(SourceSet::stream())
981            ))
982            .is_ok()
983        );
984    }
985
986    #[test]
987    fn secret_suffix_drives_the_sensitive_bit() {
988        let built = build_afdata_cli(spec_with(ArgSpec::option("--dsn-secret", "DSN"))).unwrap();
989        let argument = &built.spec().commands[0].arguments[0];
990        assert!(argument.sensitive);
991    }
992
993    #[test]
994    fn sensitive_without_the_suffix_fails_the_build() {
995        let error = build_afdata_cli(spec_with(ArgSpec::option("--token", "TOKEN").sensitive()))
996            .unwrap_err();
997        assert_eq!(error.rule, "sensitive_without_secret_suffix");
998    }
999
1000    #[test]
1001    fn a_plain_argument_stays_insensitive() {
1002        let built = build_afdata_cli(spec_with(ArgSpec::option("--host", "HOST"))).unwrap();
1003        assert!(!built.spec().commands[0].arguments[0].sensitive);
1004    }
1005
1006    // Locks the version payload shape. `--version` is a discovery entry point
1007    // agents parse, and it lost `display_name`/`build` once before by going
1008    // through a second, hand-rolled payload instead of `build_cli_version`.
1009    #[test]
1010    fn version_events_carry_the_full_documented_payload() {
1011        let built = CliSpec::new("demo", "1.2.3")
1012            .display_name("Demo Tool")
1013            .build_id("abc1234")
1014            .command(CommandSpec::root())
1015            .build()
1016            .unwrap();
1017        let CliOutcome::Version(version) = built.resolve_from(["demo", "--version"]).unwrap()
1018        else {
1019            panic!("expected a version outcome");
1020        };
1021        assert_eq!(
1022            cli_version_event(&version).as_value(),
1023            &serde_json::json!({
1024                "kind": "result",
1025                "result": {
1026                    "code": "version",
1027                    "name": "demo",
1028                    "display_name": "Demo Tool",
1029                    "version": "1.2.3",
1030                    "build": "abc1234",
1031                },
1032                "trace": {},
1033            })
1034        );
1035    }
1036
1037    #[test]
1038    fn version_events_omit_absent_metadata() {
1039        let built = CliSpec::new("demo", "1.2.3")
1040            .command(CommandSpec::root())
1041            .build()
1042            .unwrap();
1043        let CliOutcome::Version(version) = built.resolve_from(["demo", "--version"]).unwrap()
1044        else {
1045            panic!("expected a version outcome");
1046        };
1047        let payload = serde_json::to_string(cli_version_event(&version).as_value()).unwrap();
1048        assert!(!payload.contains("display_name"), "{payload}");
1049        assert!(!payload.contains("build"), "{payload}");
1050    }
1051
1052    #[test]
1053    fn cli_error_events_never_carry_a_secret_value() {
1054        let built = build_afdata_cli(spec_with(ArgSpec::option("--dsn-secret", "DSN"))).unwrap();
1055        let error = built
1056            .resolve_from([
1057                "demo",
1058                "--dsn-secret",
1059                "postgres://user:password@example.test/db",
1060                "--unknown",
1061            ])
1062            .unwrap_err();
1063        let serialized = serde_json::to_string(cli_error_event(&error).as_value()).unwrap();
1064        assert!(!serialized.contains("password"));
1065        // The classification is the code, not a field beside it.
1066        assert!(serialized.contains("\"code\":\"cli_unknown_argument\""));
1067        // The command to run next reaches the caller through `hint`, which is
1068        // the channel every error event already has.
1069        assert!(serialized.contains("run `demo --help`"));
1070    }
1071
1072    /// The point of shipping this helper is that every consumer reports the
1073    /// same thing. Pin the code, so a consumer branching on it keeps working,
1074    /// and pin that it is not a `cli_*` usage code — a caller must not be told
1075    /// to fix their command line for a defect in the program.
1076    #[test]
1077    fn invocation_invalid_event_is_a_program_defect_not_a_usage_error() {
1078        let event = cli_invocation_invalid_event("no handler for this registry's invocation");
1079        let serialized = serde_json::to_string(event.as_value()).unwrap();
1080
1081        assert!(serialized.contains("\"code\":\"cli_invocation_invalid\""));
1082        assert!(serialized.contains("no handler for this registry's invocation"));
1083        // The hint has to say who should act. A usage hint here would send the
1084        // caller to debug their own arguments for a dispatch-table bug.
1085        assert!(serialized.contains("defect in the program"));
1086        assert!(
1087            crate::validate_protocol_event(event.as_value(), true).is_ok(),
1088            "the helper must emit a strict event: {serialized}"
1089        );
1090    }
1091
1092    #[test]
1093    fn a_secret_named_flag_is_not_marked_sensitive() {
1094        // `--reveal-secret` asks to reveal a secret; it does not carry one, and
1095        // a flag has no value that could leak. The suffix must not put the
1096        // sensitive bit on it.
1097        let built = build_afdata_cli(spec_with(ArgSpec::flag("--reveal-secret"))).unwrap();
1098        let argument = built
1099            .spec()
1100            .commands
1101            .iter()
1102            .flat_map(|command| &command.arguments)
1103            .find(|argument| argument.argument_id == "reveal_secret")
1104            .expect("the flag is registered");
1105        assert!(!argument.sensitive, "a flag has no value to redact");
1106    }
1107
1108    #[test]
1109    fn marking_a_flag_sensitive_is_a_contradiction() {
1110        let error = build_afdata_cli(spec_with(ArgSpec::flag("--reveal-secret").sensitive()))
1111            .expect_err("a sensitive flag must not build");
1112        assert_eq!(error.rule, "sensitive_flag");
1113    }
1114
1115    #[test]
1116    fn a_value_carrying_secret_argument_is_still_marked() {
1117        let built = build_afdata_cli(spec_with(ArgSpec::option("--dsn-secret", "DSN"))).unwrap();
1118        let argument = built
1119            .spec()
1120            .commands
1121            .iter()
1122            .flat_map(|command| &command.arguments)
1123            .find(|argument| argument.argument_id == "dsn_secret")
1124            .expect("the option is registered");
1125        assert!(argument.sensitive, "an option with a value still counts");
1126    }
1127
1128    #[test]
1129    fn an_invalid_argument_stop_is_a_usage_error() {
1130        let stop = CliStop::invalid_argument("expected one character", "pass a single character");
1131        assert_eq!(stop.exit_code(), 2);
1132        let value = stop.event().as_value();
1133        assert_eq!(value["kind"], "error");
1134        assert_eq!(value["error"]["code"], "cli_invalid_argument_value");
1135        assert_eq!(value["error"]["hint"], "pass a single character");
1136        let (event, code) = stop.into_parts();
1137        assert_eq!(code, 2);
1138        assert_eq!(
1139            event.as_value()["error"]["message"],
1140            "expected one character"
1141        );
1142    }
1143
1144    #[test]
1145    fn a_failed_read_stops_as_a_program_defect() {
1146        let built = build_afdata_cli(spec_with(ArgSpec::option("--label", "LABEL"))).unwrap();
1147        let CliOutcome::Run(invocation) = built
1148            .resolve_from(["demo", "--label", "a"])
1149            .expect("resolves")
1150        else {
1151            panic!("must resolve to a run");
1152        };
1153        let error = invocation.text("lable").unwrap_err();
1154        let stop = CliStop::from(error);
1155        assert_eq!(stop.exit_code(), 1);
1156        assert_eq!(
1157            stop.event().as_value()["error"]["code"],
1158            "cli_invocation_invalid"
1159        );
1160        assert!(
1161            stop.event().as_value()["error"]["message"]
1162                .as_str()
1163                .is_some_and(|message| message.contains("lable") && message.contains("only")),
1164            "{:?}",
1165            stop.event()
1166        );
1167    }
1168
1169    #[test]
1170    fn an_argv_rejection_stops_with_its_rule_code_and_exit_two() {
1171        let built = build_afdata_cli(spec_with(ArgSpec::option("--label", "LABEL"))).unwrap();
1172        let error = built
1173            .resolve_from(["demo", "--nope"])
1174            .expect_err("unknown argument");
1175        let stop = CliStop::from(error);
1176        assert_eq!(stop.exit_code(), 2);
1177        assert_eq!(
1178            stop.event().as_value()["error"]["code"],
1179            "cli_unknown_argument"
1180        );
1181    }
1182}