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, BuiltCliSpec, CliError, CliSpec, CliSpecError, ResolvedHelp, ResolvedVersion,
12};
13use crate::protocol::{Event, json_error, json_result};
14
15/// Build a registry under AFDATA's naming conventions.
16///
17/// `ArgSpec::sensitive` is not an independent switch. AFDATA already decides
18/// what a secret is by the `_secret` suffix, and the same convention drives
19/// config keys, log fields, and redaction. Deriving the bit from the argument
20/// id keeps one source of truth: an argument cannot be sensitive to the parser
21/// while staying invisible to redaction downstream. Marking a differently named
22/// argument sensitive is the reverse mistake, so it fails the build instead of
23/// silently diverging.
24pub fn build_afdata_cli(mut spec: CliSpec) -> Result<BuiltCliSpec, CliSpecError> {
25    for command in &mut spec.commands {
26        for argument in &mut command.arguments {
27            let suffixed = argument.argument_id.ends_with("_secret");
28            let is_flag = matches!(argument.value_type, ArgValueType::Flag);
29            if argument.sensitive && !suffixed {
30                return Err(CliSpecError {
31                    rule: "sensitive_without_secret_suffix",
32                    message: format!(
33                        "argument `{}` is marked sensitive; rename it to `{}_secret` so AFDATA \
34                         redaction covers it too",
35                        argument.argument_id, argument.argument_id
36                    ),
37                });
38            }
39            if argument.sensitive && is_flag {
40                return Err(CliSpecError {
41                    rule: "sensitive_flag",
42                    message: format!(
43                        "flag `{}` is marked sensitive, but a flag carries no value to redact",
44                        argument.argument_id
45                    ),
46                });
47            }
48            // A flag has no value, so `_secret` in its name says what the flag
49            // is *about* — `--reveal-secret` asks to reveal one, it does not
50            // carry one. Marking it would put the sensitive bit on something
51            // that structurally cannot leak, which reads as a real credential
52            // to anything downstream that trusts the bit.
53            argument.sensitive = suffixed && !is_flag;
54
55            // A prompt suppresses terminal echo and blocks until a person
56            // types — the first only means something for a secret, and the
57            // second is a hang in the agent-run case this CLI is for. So the
58            // source is available exactly where it earns its cost.
59            if let Some(sources) = &argument.sources
60                && sources.accepts(SourceScheme::Prompt)
61                && !argument.sensitive
62            {
63                return Err(CliSpecError {
64                    rule: "prompt_source_without_secret",
65                    message: format!(
66                        "argument `{}` accepts the `prompt` source; rename it to `{}_secret`, or \
67                         drop the source — prompting blocks on a terminal for a value that is not \
68                         a credential",
69                        argument.argument_id, argument.argument_id
70                    ),
71                });
72            }
73        }
74    }
75    spec.build()
76}
77
78/// Wrap a resolved help response in a `cli-help-v2` result event.
79pub fn cli_help_event(help: &ResolvedHelp) -> Event {
80    json_result(serde_json::json!({
81        "code": "help",
82        "help": help.model(),
83    }))
84    .build()
85}
86
87/// Wrap a resolved version response in a protocol result event.
88///
89/// This delegates to [`crate::build_cli_version`] rather than assembling its
90/// own payload. There is one version shape — `{code, name, version}` plus
91/// `display_name`/`build` when the registry carries them — and it is the same
92/// one the Go, Python, and TypeScript SDKs emit.
93pub fn cli_version_event(version: &ResolvedVersion) -> Event {
94    crate::cli::build_cli_version(
95        version.name(),
96        version.display_name(),
97        version.version(),
98        version.build(),
99    )
100}
101
102/// Static prose for the generated CLI reference.
103///
104/// Kept as Markdown files rather than escaped Rust string literals: these are
105/// paragraphs, and as `\`-continued literals they cannot be read as prose in a
106/// diff, need every backtick and quote escaped, and turn a wording change into
107/// an exercise in line continuations. The surrounding structure — headings,
108/// tables, per-command sections — stays in code, because that part is generated
109/// from the registry and is not prose.
110///
111/// This reference is emitted by every spore's `--docs`, not just afdata's, so
112/// the text is shared library data and belongs beside the generator.
113const SHAPES_PROSE: &str = include_str!("cli_reference/shapes.md");
114const CLI_ERRORS_PROSE: &str = include_str!("cli_reference/cli-errors.md");
115
116/// Render an offline Markdown reference for a whole registry.
117///
118/// help-v2 is deliberately lossy: it answers "how do I call this" one command
119/// at a time, in as few tokens as possible. A reference manual wants the
120/// opposite, so it is a separate capability rather than a format on the
121/// discovery path — the agent's `--help` never grows a documentation mode, and
122/// the manual can never disagree with the parser, because both are this
123/// registry. `--docs` is injected into every registry, so a tool exposes this
124/// without registering a command, and without spending a line of its
125/// subcommand listing on something no agent calls.
126///
127/// What is deliberately *not* repeated: a lone combination's description and
128/// id — the command heading already carries the description, and the id only
129/// matters for telling siblings apart — plus the shared output defaults and
130/// each command's arguments per combination. help repeats those because each help
131/// response is read alone; a document is read in order.
132pub fn render_cli_reference(cli: &BuiltCliSpec) -> String {
133    let spec = cli.spec();
134    let name = spec.name.as_str();
135    let mut commands: Vec<&crate::cli_spec::CommandSpec> = spec
136        .commands
137        .iter()
138        .filter(|command| !command.combinations.is_empty())
139        .collect();
140    commands.sort_by(|left, right| left.command_path.cmp(&right.command_path));
141
142    let path_of = |command: &crate::cli_spec::CommandSpec| {
143        if command.command_path.is_empty() {
144            name.to_string()
145        } else {
146            format!("{name} {}", command.command_path.join(" "))
147        }
148    };
149
150    let mut out = String::new();
151    out.push_str(&format!("# {name} CLI reference\n\n"));
152    out.push_str(&format!(
153        "<!-- Generated by `{name} --docs`. Do not edit by hand. -->\n\n"
154    ));
155    if let Some(about) = &spec.about {
156        out.push_str(&format!("{about}\n\n"));
157    }
158    out.push_str(&format!(
159        "`{name}` is compiled from a closed `cli-spec-v1` registry: one source for argv parsing, \
160         typed invocation values, which parameter combinations are legal, output contracts, and \
161         help. An invocation runs only when it matches exactly one registered combination.\n\n"
162    ));
163
164    // Everything AFDATA registers on the caller's behalf, in one place. Split
165    // across sections it reads as unrelated trivia, and `--version`/`--docs`
166    // fall through the gap entirely — they belong to no command, so no command
167    // section would ever mention them.
168    let baseline = baseline_output(&commands);
169    out.push_str("## Global arguments\n\n");
170    // Not "no command declares them": `--version` and `--docs` are answered by
171    // the root alone, so a command may declare its own argument under that
172    // spelling — where one does, the entry below is still only the root's.
173    out.push_str(
174        "AFDATA registers these itself, so the syntax in [Commands](#commands) \
175         leaves them out.\n\n",
176    );
177    out.push_str("| Argument | Where | What it does |\n|---|---|---|\n");
178    out.push_str(
179        "| `--help` | every command | Every legal shape of that command, complete, plus its \
180         subcommands. JSON by default; `--output plain` for a terminal. |\n",
181    );
182    out.push_str(&format!(
183        "| `--version` | {name} only | Name, version, and build identity as one protocol result. \
184         |\n"
185    ));
186    out.push_str(&format!(
187        "| `--docs` | {name} only | This document, rendered from the registry. |\n"
188    ));
189    if let Some(crate::cli_spec::OutputSpec::Protocol {
190        formats,
191        destinations,
192        default_format,
193        default_destination,
194        ..
195    }) = &baseline
196    {
197        out.push_str(&format!(
198            "| `--output <FORMAT>` | per output contract | Render as {} (default \
199             `{default_format}`). |\n",
200            formats.join(", ")
201        ));
202        out.push_str(&format!(
203            "| `--output-to <DESTINATION>` | per output contract | Route results and diagnostics \
204             to {} (default `{default_destination}`). |\n",
205            destinations.join(", ")
206        ));
207    }
208    out.push_str(
209        "| `--stdout-file <PATH>`, `--stderr-file <PATH>` | per output contract | Append that \
210         stream to a file instead. |\n\n",
211    );
212    let baseline_line = baseline.as_ref().map(describe_output);
213    // The table above already lists the arguments and their values; the only
214    // thing left to say is what a successful call actually writes.
215    if baseline.is_some() {
216        out.push_str(
217            "Success output is protocol events, on those terms, unless a command's own \
218             **Output** line says otherwise.\n\n",
219        );
220    }
221    out.push_str(SHAPES_PROSE);
222    out.push('\n');
223
224    out.push_str("## Commands\n\n");
225    for command in &commands {
226        let path = path_of(command);
227        let anchor = path.replace(' ', "-");
228        let about = command.about.as_deref().unwrap_or("");
229        out.push_str(&format!("- [`{path}`](#{anchor}) — {about}\n"));
230    }
231    out.push('\n');
232
233    for command in &commands {
234        let path = path_of(command);
235        out.push_str(&format!("### `{path}`\n\n"));
236        if let Some(about) = &command.about {
237            out.push_str(&format!("{about}\n\n"));
238        }
239
240        let Some(model) = cli.help(&command.command_path) else {
241            continue;
242        };
243        for shape in &model.shapes {
244            if model.shapes.len() > 1 {
245                let differs = shape.about.as_deref().unwrap_or_default();
246                out.push_str(&format!("#### `{}` — {differs}\n\n", shape.id));
247            }
248            out.push_str(&format!(
249                "```\n{}\n```\n\n",
250                trim_output_arguments(&shape.usage)
251            ));
252        }
253
254        let combinations: Vec<&crate::cli_spec::Combination> =
255            command.combinations.iter().collect();
256        let contracts = output_contracts(&combinations);
257        let is_baseline =
258            matches!((contracts.as_slice(), &baseline_line), ([only], Some(line)) if only == line);
259        if !is_baseline {
260            out.push_str(&render_output(&contracts));
261        }
262
263        let documented: Vec<(&crate::cli_spec::ArgSpec, String)> = command
264            .arguments
265            .iter()
266            .filter_map(|argument| Some((argument, argument.rendered_about()?)))
267            .collect();
268        if !documented.is_empty() {
269            if model.shapes.len() > 1 {
270                // One table per command, so it necessarily spans shapes that
271                // cannot be used together; the syntax above is what says which
272                // argument belongs where.
273                out.push_str("Arguments across every shape above:\n\n");
274            }
275            out.push_str("| Argument | Meaning |\n|---|---|\n");
276            for (argument, about) in documented {
277                // The same spelling the usage line above uses, so the table can
278                // be read against it without translating ids back to flags.
279                out.push_str(&format!(
280                    "| `{}` | {about} |\n",
281                    crate::cli_spec::argument_key(argument)
282                ));
283            }
284            out.push('\n');
285        }
286    }
287
288    out.push_str("## Exit codes\n\n");
289    out.push_str(
290        "| Code | Meaning |\n|---|---|\n\
291         | 0 | The command ran and succeeded. |\n\
292         | 1 | The command ran and failed. The event carries a domain `error.code`. |\n\
293         | 2 | The invocation was rejected before anything ran. `error.code` is one of the \
294         `cli_*` codes below. |\n",
295    );
296    // Sorted rather than left in declaration order: the table is read by code,
297    // and a registry author's ordering is not the reader's.
298    let mut declared_exit_codes: Vec<&crate::cli_spec::ExitCodeSpec> =
299        spec.exit_codes.iter().collect();
300    declared_exit_codes.sort_by_key(|exit| exit.code);
301    for exit in declared_exit_codes {
302        out.push_str(&format!("| {} | {} |\n", exit.code, exit.meaning));
303    }
304    out.push_str(
305        "\nThe split is the useful one for a caller: exit 2 means the call was never made, so \
306         retrying it unchanged cannot help, while exit 1 means it was.\n\n",
307    );
308
309    out.push_str("## CLI errors\n\n");
310    out.push_str(CLI_ERRORS_PROSE);
311    out
312}
313
314/// One line per command saying what its success output is, because the usage
315/// line can only show that by omission.
316fn describe_output(output: &crate::cli_spec::OutputSpec) -> String {
317    use crate::cli_spec::OutputSpec;
318    match output {
319        OutputSpec::Raw { file_sinks } => format!(
320            "raw bytes on success; rejects `--output` and `--output-to`{}. Failures are still \
321             strict JSON on stderr",
322            render_file_sinks(file_sinks)
323        ),
324        OutputSpec::Protocol {
325            formats,
326            destinations,
327            default_format,
328            default_destination,
329            file_sinks,
330            ..
331        } => format!(
332            "protocol events; `--output` {} (default `{default_format}`), `--output-to` {} \
333             (default `{default_destination}`){}",
334            formats.join("/"),
335            destinations.join("/"),
336            render_file_sinks(file_sinks),
337        ),
338    }
339}
340
341/// Each distinct output contract a command exposes, in a stable order.
342fn output_contracts(combinations: &[&crate::cli_spec::Combination]) -> Vec<String> {
343    let mut lines: Vec<String> = Vec::new();
344    for combination in combinations {
345        let line = describe_output(&combination.output);
346        if !lines.contains(&line) {
347            lines.push(line);
348        }
349    }
350    lines
351}
352
353/// The output contract most commands share, if there is one worth hoisting.
354///
355/// Deterministic: ties break on the rendered description, never on registration
356/// order, so the same registry always renders the same document.
357fn baseline_output(
358    commands: &[&crate::cli_spec::CommandSpec],
359) -> Option<crate::cli_spec::OutputSpec> {
360    let mut counts: std::collections::BTreeMap<String, (usize, crate::cli_spec::OutputSpec)> =
361        std::collections::BTreeMap::new();
362    for command in commands {
363        let mut contracts: Vec<&crate::cli_spec::OutputSpec> = Vec::new();
364        for combination in &command.combinations {
365            if !contracts.contains(&&combination.output) {
366                contracts.push(&combination.output);
367            }
368        }
369        if let [only] = contracts.as_slice() {
370            let entry = counts
371                .entry(describe_output(only))
372                .or_insert((0, (*only).clone()));
373            entry.0 += 1;
374        }
375    }
376    counts
377        .into_iter()
378        .max_by(|left, right| left.1.0.cmp(&right.1.0).then_with(|| right.0.cmp(&left.0)))
379        .filter(|(_, (count, _))| *count > 1)
380        .map(|(_, (_, spec))| spec)
381}
382
383fn render_output(contracts: &[String]) -> String {
384    match contracts {
385        [] => String::new(),
386        [only] => format!("Output: {only}.\n\n"),
387        many => {
388            let mut out = String::from("Output differs by combination:\n\n");
389            for line in many {
390                out.push_str(&format!("- {line}\n"));
391            }
392            out.push('\n');
393            out
394        }
395    }
396}
397
398/// Drop the trailing AFDATA output arguments from a usage line.
399///
400/// The compiler always renders them last and in a fixed order, and their names
401/// are reserved, so no application argument can be mistaken for one. A document
402/// states the output contract once per command; only `--help`, whose response
403/// is read on its own, needs them inline.
404fn trim_output_arguments(usage: &str) -> &str {
405    let cut = ["[--output ", "[--stdout-file ", "[--stderr-file "]
406        .iter()
407        .filter_map(|marker| usage.find(marker))
408        .min();
409    match cut {
410        Some(index) => usage[..index].trim_end(),
411        None => usage,
412    }
413}
414
415fn render_file_sinks(file_sinks: &[String]) -> String {
416    let mut names: Vec<&str> = Vec::new();
417    if file_sinks.iter().any(|sink| sink == "stdout") {
418        names.push("`--stdout-file`");
419    }
420    if file_sinks.iter().any(|sink| sink == "stderr") {
421        names.push("`--stderr-file`");
422    }
423    if names.is_empty() {
424        String::new()
425    } else {
426        format!("; redirect with {}", names.join(" or "))
427    }
428}
429
430/// Wrap a CLI-resolution failure in an event whose `code` names the failure.
431///
432/// The classification lives in `code`, the way `document_path_not_found` and
433/// its siblings already do — not in a second field beside a generic
434/// `cli_error`. One error taxonomy, one place to read it, and the skill's
435/// standing instruction ("branch on `error.code`") covers CLI errors too.
436///
437/// The event never carries raw argument values; `message` names the offending
438/// argument, and `hint` says what to run next.
439pub fn cli_error_event(error: &CliError) -> Event {
440    let builder = json_error(error.rule.code(), &error.message).hint(&error.hint);
441    match builder.build() {
442        Ok(event) => event,
443        Err(_) => json_error("cli_error", "failed to build CLI error")
444            .build()
445            .unwrap_or_else(|_| {
446                // All literals above are valid; this branch is unreachable
447                // but keeps production code panic-free.
448                json_result(serde_json::json!({"code":"internal_cli_error"})).build()
449            }),
450    }
451}
452
453/// The standard event for a program that misread its own resolved invocation.
454///
455/// Dispatch itself cannot fail —
456/// [`crate::cli_spec::BoundCliSpec::resolve_from`] binds the handler while
457/// resolving, so there is no undispatchable invocation to report. What remains
458/// is a handler reading an argument the selected combination does not supply:
459/// an id it does not declare, or one whose type does not match the accessor.
460/// [`crate::cli_spec::BoundCliSpec::call_every_combination`] catches the first
461/// from a test; this is for a program that also wants to say something at
462/// runtime.
463///
464/// It is a defect in the program, never in what the user typed, and the code
465/// and exit status have to say so. Reporting it as a usage error tells the
466/// caller to fix their command line and retry, and retrying cannot help — a
467/// mistake that has already been made in the wild, as
468/// `cli_invalid_argument_value` at exit 2. Emit this and exit 1; the
469/// application still owns the exit.
470pub fn cli_invocation_invalid_event(detail: &str) -> Event {
471    let builder = json_error("cli_invocation_invalid", detail)
472        .hint("this is a defect in the program, not in the command; report it");
473    match builder.build() {
474        Ok(event) => event,
475        Err(_) => json_error("cli_invocation_invalid", "invocation cannot be dispatched")
476            .build()
477            .unwrap_or_else(|_| {
478                // The literals above are valid, so this is unreachable; it
479                // keeps the path panic-free the way `cli_error_event` does.
480                json_result(serde_json::json!({"code":"internal_cli_error"})).build()
481            }),
482    }
483}
484
485#[cfg(test)]
486mod tests {
487    use super::*;
488    use crate::cli_spec::SourceSet;
489    use crate::cli_spec::{ArgSpec, CliOutcome, Combination, CommandSpec, OutputSpec};
490
491    fn output() -> OutputSpec {
492        OutputSpec::protocol_finite(["json"], ["split"], "json", "split")
493    }
494
495    fn spec_with(argument: ArgSpec) -> CliSpec {
496        let id = argument.argument_id.clone();
497        CliSpec::new("demo", "1").command(
498            CommandSpec::root().arg(argument).combination(
499                Combination::new("only")
500                    .action("only")
501                    .required([id])
502                    .output(output()),
503            ),
504        )
505    }
506
507    #[test]
508    fn a_cli_declares_exit_codes_beyond_afdatas_own() {
509        let spec = CliSpec::new("demo", "1.0.0")
510            .lifecycle_output(output())
511            .exit_code(4, "The output could not be written.")
512            .exit_code(3, "The command ran and partly succeeded.")
513            .command(CommandSpec::root())
514            .build()
515            .unwrap();
516        let reference = render_cli_reference(&spec);
517        let table = reference
518            .split("## Exit codes")
519            .nth(1)
520            .expect("the reference documents exit codes");
521        // Sorted by code, not by declaration order: the table is read by code.
522        let partial = table.find("| 3 | The command ran and partly succeeded. |");
523        let write_failed = table.find("| 4 | The output could not be written. |");
524        assert!(partial.is_some() && write_failed.is_some(), "{table}");
525        assert!(partial < write_failed, "{table}");
526    }
527
528    /// The syntax lives in the declaration, so help and `--docs` render it and
529    /// no `about` string repeats it. This is the duplication the declaration
530    /// exists to remove.
531    #[test]
532    fn a_declared_source_set_renders_itself_into_help_and_docs() {
533        let built = build_afdata_cli(spec_with(
534            ArgSpec::option("--token-secret", "SOURCE")
535                .about("Token this host requires")
536                .sources(SourceSet::config().host_scheme("container", "container:NAME")),
537        ))
538        .expect("registry builds");
539
540        let reference = render_cli_reference(&built);
541        assert!(
542            reference.contains(
543                "Token this host requires (the value, or where to read it: env:NAME, \
544                 file[+FORMAT]:PATH#DOT_PATH, container:NAME, literal:VALUE)"
545            ),
546            "{reference}"
547        );
548
549        let CliOutcome::Help(help) = built
550            .resolve_from(vec!["demo", "--help"])
551            .expect("help resolves")
552        else {
553            panic!("--help must resolve to help");
554        };
555        let model = serde_json::to_value(help.model()).expect("help serializes");
556        let note = model["notes"]["--token-secret"]
557            .as_str()
558            .unwrap_or_default()
559            .to_string();
560        assert!(note.contains("file[+FORMAT]:PATH#DOT_PATH"), "{model}");
561    }
562
563    /// A value naming a scheme the argument does not accept is a usage error,
564    /// beside the other argv rejections — and nothing was opened to find out.
565    #[test]
566    fn an_unaccepted_scheme_is_an_argv_rejection() {
567        let built = build_afdata_cli(spec_with(
568            ArgSpec::option("--token-secret", "SOURCE").sources(SourceSet::config()),
569        ))
570        .expect("registry builds");
571        let error = built
572            .resolve_from(vec!["demo", "--token-secret", "prompt"])
573            .expect_err("prompt is not in config()");
574        assert_eq!(
575            error.rule,
576            crate::cli_spec::CliErrorRule::InvalidArgumentValue
577        );
578        assert!(error.message.contains("env:NAME"), "{}", error.message);
579
580        // …and one it does accept resolves to the raw string, unread.
581        let outcome = built
582            .resolve_from(vec!["demo", "--token-secret", "env:NAME"])
583            .expect("env is accepted");
584        let CliOutcome::Run(invocation) = outcome else {
585            panic!("must resolve to a run");
586        };
587        assert_eq!(
588            invocation.required("token_secret").as_str(),
589            Some("env:NAME")
590        );
591    }
592
593    /// Prompting suppresses echo and blocks on a terminal. Both only make sense
594    /// for a credential, so the source is refused anywhere else.
595    #[test]
596    fn the_prompt_source_is_refused_on_a_non_secret_argument() {
597        let error = build_afdata_cli(spec_with(
598            ArgSpec::option("--label", "LABEL").sources(SourceSet::stream()),
599        ))
600        .expect_err("prompt on a non-secret argument");
601        assert_eq!(error.rule, "prompt_source_without_secret");
602        // The same set is fine once the name says it carries a credential.
603        assert!(
604            build_afdata_cli(spec_with(
605                ArgSpec::option("--token-secret", "SOURCE").sources(SourceSet::stream())
606            ))
607            .is_ok()
608        );
609    }
610
611    #[test]
612    fn secret_suffix_drives_the_sensitive_bit() {
613        let built = build_afdata_cli(spec_with(ArgSpec::option("--dsn-secret", "DSN"))).unwrap();
614        let argument = &built.spec().commands[0].arguments[0];
615        assert!(argument.sensitive);
616    }
617
618    #[test]
619    fn sensitive_without_the_suffix_fails_the_build() {
620        let error = build_afdata_cli(spec_with(ArgSpec::option("--token", "TOKEN").sensitive()))
621            .unwrap_err();
622        assert_eq!(error.rule, "sensitive_without_secret_suffix");
623    }
624
625    #[test]
626    fn a_plain_argument_stays_insensitive() {
627        let built = build_afdata_cli(spec_with(ArgSpec::option("--host", "HOST"))).unwrap();
628        assert!(!built.spec().commands[0].arguments[0].sensitive);
629    }
630
631    // Locks the version payload shape. `--version` is a discovery entry point
632    // agents parse, and it lost `display_name`/`build` once before by going
633    // through a second, hand-rolled payload instead of `build_cli_version`.
634    #[test]
635    fn version_events_carry_the_full_documented_payload() {
636        let built = CliSpec::new("demo", "1.2.3")
637            .display_name("Demo Tool")
638            .build_id("abc1234")
639            .command(CommandSpec::root())
640            .build()
641            .unwrap();
642        let CliOutcome::Version(version) = built.resolve_from(["demo", "--version"]).unwrap()
643        else {
644            panic!("expected a version outcome");
645        };
646        assert_eq!(
647            cli_version_event(&version).as_value(),
648            &serde_json::json!({
649                "kind": "result",
650                "result": {
651                    "code": "version",
652                    "name": "demo",
653                    "display_name": "Demo Tool",
654                    "version": "1.2.3",
655                    "build": "abc1234",
656                },
657                "trace": {},
658            })
659        );
660    }
661
662    #[test]
663    fn version_events_omit_absent_metadata() {
664        let built = CliSpec::new("demo", "1.2.3")
665            .command(CommandSpec::root())
666            .build()
667            .unwrap();
668        let CliOutcome::Version(version) = built.resolve_from(["demo", "--version"]).unwrap()
669        else {
670            panic!("expected a version outcome");
671        };
672        let payload = serde_json::to_string(cli_version_event(&version).as_value()).unwrap();
673        assert!(!payload.contains("display_name"), "{payload}");
674        assert!(!payload.contains("build"), "{payload}");
675    }
676
677    #[test]
678    fn cli_error_events_never_carry_a_secret_value() {
679        let built = build_afdata_cli(spec_with(ArgSpec::option("--dsn-secret", "DSN"))).unwrap();
680        let error = built
681            .resolve_from([
682                "demo",
683                "--dsn-secret",
684                "postgres://user:password@example.test/db",
685                "--unknown",
686            ])
687            .unwrap_err();
688        let serialized = serde_json::to_string(cli_error_event(&error).as_value()).unwrap();
689        assert!(!serialized.contains("password"));
690        // The classification is the code, not a field beside it.
691        assert!(serialized.contains("\"code\":\"cli_unknown_argument\""));
692        // The command to run next reaches the caller through `hint`, which is
693        // the channel every error event already has.
694        assert!(serialized.contains("run `demo --help`"));
695    }
696
697    /// The point of shipping this helper is that every consumer reports the
698    /// same thing. Pin the code, so a consumer branching on it keeps working,
699    /// and pin that it is not a `cli_*` usage code — a caller must not be told
700    /// to fix their command line for a defect in the program.
701    #[test]
702    fn invocation_invalid_event_is_a_program_defect_not_a_usage_error() {
703        let event = cli_invocation_invalid_event("no handler for this registry's invocation");
704        let serialized = serde_json::to_string(event.as_value()).unwrap();
705
706        assert!(serialized.contains("\"code\":\"cli_invocation_invalid\""));
707        assert!(serialized.contains("no handler for this registry's invocation"));
708        // The hint has to say who should act. A usage hint here would send the
709        // caller to debug their own arguments for a dispatch-table bug.
710        assert!(serialized.contains("defect in the program"));
711        assert!(
712            crate::validate_protocol_event(event.as_value(), true).is_ok(),
713            "the helper must emit a strict event: {serialized}"
714        );
715    }
716
717    #[test]
718    fn a_secret_named_flag_is_not_marked_sensitive() {
719        // `--reveal-secret` asks to reveal a secret; it does not carry one, and
720        // a flag has no value that could leak. The suffix must not put the
721        // sensitive bit on it.
722        let built = build_afdata_cli(spec_with(ArgSpec::flag("--reveal-secret"))).unwrap();
723        let argument = built
724            .spec()
725            .commands
726            .iter()
727            .flat_map(|command| &command.arguments)
728            .find(|argument| argument.argument_id == "reveal_secret")
729            .expect("the flag is registered");
730        assert!(!argument.sensitive, "a flag has no value to redact");
731    }
732
733    #[test]
734    fn marking_a_flag_sensitive_is_a_contradiction() {
735        let error = build_afdata_cli(spec_with(ArgSpec::flag("--reveal-secret").sensitive()))
736            .expect_err("a sensitive flag must not build");
737        assert_eq!(error.rule, "sensitive_flag");
738    }
739
740    #[test]
741    fn a_value_carrying_secret_argument_is_still_marked() {
742        let built = build_afdata_cli(spec_with(ArgSpec::option("--dsn-secret", "DSN"))).unwrap();
743        let argument = built
744            .spec()
745            .commands
746            .iter()
747            .flat_map(|command| &command.arguments)
748            .find(|argument| argument.argument_id == "dsn_secret")
749            .expect("the option is registered");
750        assert!(argument.sensitive, "an option with a value still counts");
751    }
752}