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::{
10    ArgValueType, BuiltCliSpec, CliError, CliSpec, CliSpecError, ResolvedHelp, ResolvedVersion,
11};
12use crate::protocol::{Event, json_error, json_result};
13
14/// Build a registry under AFDATA's naming conventions.
15///
16/// `ArgSpec::sensitive` is not an independent switch. AFDATA already decides
17/// what a secret is by the `_secret` suffix, and the same convention drives
18/// config keys, log fields, and redaction. Deriving the bit from the argument
19/// id keeps one source of truth: an argument cannot be sensitive to the parser
20/// while staying invisible to redaction downstream. Marking a differently named
21/// argument sensitive is the reverse mistake, so it fails the build instead of
22/// silently diverging.
23pub fn build_afdata_cli(mut spec: CliSpec) -> Result<BuiltCliSpec, CliSpecError> {
24    for command in &mut spec.commands {
25        for argument in &mut command.arguments {
26            let suffixed = argument.argument_id.ends_with("_secret");
27            let is_flag = matches!(argument.value_type, ArgValueType::Flag);
28            if argument.sensitive && !suffixed {
29                return Err(CliSpecError {
30                    rule: "sensitive_without_secret_suffix",
31                    message: format!(
32                        "argument `{}` is marked sensitive; rename it to `{}_secret` so AFDATA \
33                         redaction covers it too",
34                        argument.argument_id, argument.argument_id
35                    ),
36                });
37            }
38            if argument.sensitive && is_flag {
39                return Err(CliSpecError {
40                    rule: "sensitive_flag",
41                    message: format!(
42                        "flag `{}` is marked sensitive, but a flag carries no value to redact",
43                        argument.argument_id
44                    ),
45                });
46            }
47            // A flag has no value, so `_secret` in its name says what the flag
48            // is *about* — `--reveal-secret` asks to reveal one, it does not
49            // carry one. Marking it would put the sensitive bit on something
50            // that structurally cannot leak, which reads as a real credential
51            // to anything downstream that trusts the bit.
52            argument.sensitive = suffixed && !is_flag;
53        }
54    }
55    spec.build()
56}
57
58/// Wrap a resolved help response in a `cli-help-v2` result event.
59pub fn cli_help_event(help: &ResolvedHelp) -> Event {
60    json_result(serde_json::json!({
61        "code": "help",
62        "help": help.model(),
63    }))
64    .build()
65}
66
67/// Wrap a resolved version response in a protocol result event.
68///
69/// This delegates to [`crate::build_cli_version`] rather than assembling its
70/// own payload. There is one version shape — `{code, name, version}` plus
71/// `display_name`/`build` when the registry carries them — and it is the same
72/// one the Go, Python, and TypeScript SDKs emit.
73pub fn cli_version_event(version: &ResolvedVersion) -> Event {
74    crate::cli::build_cli_version(
75        version.name(),
76        version.display_name(),
77        version.version(),
78        version.build(),
79    )
80}
81
82/// Render an offline Markdown reference for a whole registry.
83///
84/// help-v2 is deliberately lossy: it answers "how do I call this" one command
85/// at a time, in as few tokens as possible. A reference manual wants the
86/// opposite, so it is a separate capability rather than a format on the
87/// discovery path — the agent's `--help` never grows a documentation mode, and
88/// the manual can never disagree with the parser, because both are this
89/// registry. `--docs` is injected into every registry, so a tool exposes this
90/// without registering a command, and without spending a line of its
91/// subcommand listing on something no agent calls.
92///
93/// What is deliberately *not* repeated: a lone combination's description and
94/// id — the command heading already carries the description, and the id only
95/// matters for telling siblings apart — plus the shared output defaults and
96/// each command's arguments per combination. help repeats those because each help
97/// response is read alone; a document is read in order.
98pub fn render_cli_reference(cli: &BuiltCliSpec) -> String {
99    let spec = cli.spec();
100    let name = spec.name.as_str();
101    let mut commands: Vec<&crate::cli_spec::CommandSpec> = spec
102        .commands
103        .iter()
104        .filter(|command| !command.combinations.is_empty())
105        .collect();
106    commands.sort_by(|left, right| left.command_path.cmp(&right.command_path));
107
108    let path_of = |command: &crate::cli_spec::CommandSpec| {
109        if command.command_path.is_empty() {
110            name.to_string()
111        } else {
112            format!("{name} {}", command.command_path.join(" "))
113        }
114    };
115
116    let mut out = String::new();
117    out.push_str(&format!("# {name} CLI reference\n\n"));
118    out.push_str(&format!(
119        "<!-- Generated by `{name} --docs`. Do not edit by hand. -->\n\n"
120    ));
121    if let Some(about) = &spec.about {
122        out.push_str(&format!("{about}\n\n"));
123    }
124    out.push_str(&format!(
125        "`{name}` is compiled from a closed `cli-spec-v1` registry: one source for argv parsing, \
126         typed invocation values, which parameter combinations are legal, output contracts, and \
127         help. An invocation runs only when it matches exactly one registered combination.\n\n"
128    ));
129
130    // Everything AFDATA registers on the caller's behalf, in one place. Split
131    // across sections it reads as unrelated trivia, and `--version`/`--docs`
132    // fall through the gap entirely — they belong to no command, so no command
133    // section would ever mention them.
134    let baseline = baseline_output(&commands);
135    out.push_str("## Global arguments\n\n");
136    // Not "no command declares them": `--version` and `--docs` are answered by
137    // the root alone, so a command may declare its own argument under that
138    // spelling — where one does, the entry below is still only the root's.
139    out.push_str(
140        "AFDATA registers these itself, so the syntax in [Commands](#commands) \
141         leaves them out.\n\n",
142    );
143    out.push_str("| Argument | Where | What it does |\n|---|---|---|\n");
144    out.push_str(
145        "| `--help` | every command | Every legal shape of that command, complete, plus its \
146         subcommands. JSON by default; `--output plain` for a terminal. |\n",
147    );
148    out.push_str(&format!(
149        "| `--version` | {name} only | Name, version, and build identity as one protocol result. \
150         |\n"
151    ));
152    out.push_str(&format!(
153        "| `--docs` | {name} only | This document, rendered from the registry. |\n"
154    ));
155    if let Some(crate::cli_spec::OutputSpec::Protocol {
156        formats,
157        destinations,
158        default_format,
159        default_destination,
160        ..
161    }) = &baseline
162    {
163        out.push_str(&format!(
164            "| `--output <FORMAT>` | per output contract | Render as {} (default \
165             `{default_format}`). |\n",
166            formats.join(", ")
167        ));
168        out.push_str(&format!(
169            "| `--output-to <DESTINATION>` | per output contract | Route results and diagnostics \
170             to {} (default `{default_destination}`). |\n",
171            destinations.join(", ")
172        ));
173    }
174    out.push_str(
175        "| `--stdout-file <PATH>`, `--stderr-file <PATH>` | per output contract | Append that \
176         stream to a file instead. |\n\n",
177    );
178    let baseline_line = baseline.as_ref().map(describe_output);
179    // The table above already lists the arguments and their values; the only
180    // thing left to say is what a successful call actually writes.
181    if baseline.is_some() {
182        out.push_str(
183            "Success output is protocol events, on those terms, unless a command's own \
184             **Output** line says otherwise.\n\n",
185        );
186    }
187    out.push_str(
188        "A **shape** is one legal set of arguments that may appear together, under a stable id. \
189         Where a command has more than one, each id is a heading below. `--help` returns them \
190         all at once, so discovering a command costs one call; there is no recursive mode across \
191         commands, and this document is that view.\n\n",
192    );
193
194    out.push_str("## Commands\n\n");
195    for command in &commands {
196        let path = path_of(command);
197        let anchor = path.replace(' ', "-");
198        let about = command.about.as_deref().unwrap_or("");
199        out.push_str(&format!("- [`{path}`](#{anchor}) — {about}\n"));
200    }
201    out.push('\n');
202
203    for command in &commands {
204        let path = path_of(command);
205        out.push_str(&format!("### `{path}`\n\n"));
206        if let Some(about) = &command.about {
207            out.push_str(&format!("{about}\n\n"));
208        }
209
210        let Some(model) = cli.help(&command.command_path) else {
211            continue;
212        };
213        for shape in &model.shapes {
214            if model.shapes.len() > 1 {
215                let differs = shape.about.as_deref().unwrap_or_default();
216                out.push_str(&format!("#### `{}` — {differs}\n\n", shape.id));
217            }
218            out.push_str(&format!(
219                "```\n{}\n```\n\n",
220                trim_output_arguments(&shape.usage)
221            ));
222        }
223
224        let combinations: Vec<&crate::cli_spec::Combination> =
225            command.combinations.iter().collect();
226        let contracts = output_contracts(&combinations);
227        let is_baseline =
228            matches!((contracts.as_slice(), &baseline_line), ([only], Some(line)) if only == line);
229        if !is_baseline {
230            out.push_str(&render_output(&contracts));
231        }
232
233        let documented: Vec<&crate::cli_spec::ArgSpec> = command
234            .arguments
235            .iter()
236            .filter(|argument| argument.about.is_some())
237            .collect();
238        if !documented.is_empty() {
239            if model.shapes.len() > 1 {
240                // One table per command, so it necessarily spans shapes that
241                // cannot be used together; the syntax above is what says which
242                // argument belongs where.
243                out.push_str("Arguments across every shape above:\n\n");
244            }
245            out.push_str("| Argument | Meaning |\n|---|---|\n");
246            for argument in documented {
247                let about = argument.about.as_deref().unwrap_or_default();
248                // The same spelling the usage line above uses, so the table can
249                // be read against it without translating ids back to flags.
250                out.push_str(&format!(
251                    "| `{}` | {about} |\n",
252                    crate::cli_spec::argument_key(argument)
253                ));
254            }
255            out.push('\n');
256        }
257    }
258
259    out.push_str("## Exit codes\n\n");
260    out.push_str(
261        "| Code | Meaning |\n|---|---|\n\
262         | 0 | The command ran and succeeded. |\n\
263         | 1 | The command ran and failed. The event carries a domain `error.code`. |\n\
264         | 2 | The invocation was rejected before anything ran. `error.code` is one of the \
265         `cli_*` codes below. |\n\n\
266         The split is the useful one for a caller: exit 2 means the call was never made, so \
267         retrying it unchanged cannot help, while exit 1 means it was.\n\n",
268    );
269
270    out.push_str("## CLI errors\n\n");
271    out.push_str(
272        "Every structural failure emits one strict JSON `kind:\"error\"` event on stderr, leaves \
273         stdout empty, and exits 2. The `code` names the failure — `cli_unknown_argument` for an \
274         unknown spelling, `cli_unregistered_combination` for registered arguments in a mixture \
275         that is not, and one each for `cli_unknown_command`, `cli_missing_argument_value`, \
276         `cli_invalid_argument_value`, `cli_duplicate_argument`, `cli_unexpected_positional`, and \
277         `cli_invalid_utf8`. `message` names the offending argument and `hint` gives the command \
278         to run next; neither ever quotes a raw value, including secrets. These are decided \
279         before any config, secret source, filesystem, network, or domain I/O.\n\n\
280         Domain failures (exit 1) carry their own stable `error.code` instead, drawn from \
281         whatever this tool defines rather than from the `cli_*` set. No error message quotes a \
282         raw value it was given — an error event is routinely logged, and the input may hold \
283         secrets.\n",
284    );
285    out
286}
287
288/// One line per command saying what its success output is, because the usage
289/// line can only show that by omission.
290fn describe_output(output: &crate::cli_spec::OutputSpec) -> String {
291    use crate::cli_spec::OutputSpec;
292    match output {
293        OutputSpec::Raw { file_sinks } => format!(
294            "raw bytes on success; rejects `--output` and `--output-to`{}. Failures are still \
295             strict JSON on stderr",
296            render_file_sinks(file_sinks)
297        ),
298        OutputSpec::Protocol {
299            formats,
300            destinations,
301            default_format,
302            default_destination,
303            file_sinks,
304            ..
305        } => format!(
306            "protocol events; `--output` {} (default `{default_format}`), `--output-to` {} \
307             (default `{default_destination}`){}",
308            formats.join("/"),
309            destinations.join("/"),
310            render_file_sinks(file_sinks),
311        ),
312    }
313}
314
315/// Each distinct output contract a command exposes, in a stable order.
316fn output_contracts(combinations: &[&crate::cli_spec::Combination]) -> Vec<String> {
317    let mut lines: Vec<String> = Vec::new();
318    for combination in combinations {
319        let line = describe_output(&combination.output);
320        if !lines.contains(&line) {
321            lines.push(line);
322        }
323    }
324    lines
325}
326
327/// The output contract most commands share, if there is one worth hoisting.
328///
329/// Deterministic: ties break on the rendered description, never on registration
330/// order, so the same registry always renders the same document.
331fn baseline_output(
332    commands: &[&crate::cli_spec::CommandSpec],
333) -> Option<crate::cli_spec::OutputSpec> {
334    let mut counts: std::collections::BTreeMap<String, (usize, crate::cli_spec::OutputSpec)> =
335        std::collections::BTreeMap::new();
336    for command in commands {
337        let mut contracts: Vec<&crate::cli_spec::OutputSpec> = Vec::new();
338        for combination in &command.combinations {
339            if !contracts.contains(&&combination.output) {
340                contracts.push(&combination.output);
341            }
342        }
343        if let [only] = contracts.as_slice() {
344            let entry = counts
345                .entry(describe_output(only))
346                .or_insert((0, (*only).clone()));
347            entry.0 += 1;
348        }
349    }
350    counts
351        .into_iter()
352        .max_by(|left, right| left.1.0.cmp(&right.1.0).then_with(|| right.0.cmp(&left.0)))
353        .filter(|(_, (count, _))| *count > 1)
354        .map(|(_, (_, spec))| spec)
355}
356
357fn render_output(contracts: &[String]) -> String {
358    match contracts {
359        [] => String::new(),
360        [only] => format!("Output: {only}.\n\n"),
361        many => {
362            let mut out = String::from("Output differs by combination:\n\n");
363            for line in many {
364                out.push_str(&format!("- {line}\n"));
365            }
366            out.push('\n');
367            out
368        }
369    }
370}
371
372/// Drop the trailing AFDATA output arguments from a usage line.
373///
374/// The compiler always renders them last and in a fixed order, and their names
375/// are reserved, so no application argument can be mistaken for one. A document
376/// states the output contract once per command; only `--help`, whose response
377/// is read on its own, needs them inline.
378fn trim_output_arguments(usage: &str) -> &str {
379    let cut = ["[--output ", "[--stdout-file ", "[--stderr-file "]
380        .iter()
381        .filter_map(|marker| usage.find(marker))
382        .min();
383    match cut {
384        Some(index) => usage[..index].trim_end(),
385        None => usage,
386    }
387}
388
389fn render_file_sinks(file_sinks: &[String]) -> String {
390    let mut names: Vec<&str> = Vec::new();
391    if file_sinks.iter().any(|sink| sink == "stdout") {
392        names.push("`--stdout-file`");
393    }
394    if file_sinks.iter().any(|sink| sink == "stderr") {
395        names.push("`--stderr-file`");
396    }
397    if names.is_empty() {
398        String::new()
399    } else {
400        format!("; redirect with {}", names.join(" or "))
401    }
402}
403
404/// Wrap a CLI-resolution failure in an event whose `code` names the failure.
405///
406/// The classification lives in `code`, the way `document_path_not_found` and
407/// its siblings already do — not in a second field beside a generic
408/// `cli_error`. One error taxonomy, one place to read it, and the skill's
409/// standing instruction ("branch on `error.code`") covers CLI errors too.
410///
411/// The event never carries raw argument values; `message` names the offending
412/// argument, and `hint` says what to run next.
413pub fn cli_error_event(error: &CliError) -> Event {
414    let builder = json_error(error.rule.code(), &error.message).hint(&error.hint);
415    match builder.build() {
416        Ok(event) => event,
417        Err(_) => json_error("cli_error", "failed to build CLI error")
418            .build()
419            .unwrap_or_else(|_| {
420                // All literals above are valid; this branch is unreachable
421                // but keeps production code panic-free.
422                json_result(serde_json::json!({"code":"internal_cli_error"})).build()
423            }),
424    }
425}
426
427#[cfg(test)]
428mod tests {
429    use super::*;
430    use crate::cli_spec::{ArgSpec, CliOutcome, Combination, CommandSpec, OutputSpec};
431
432    fn output() -> OutputSpec {
433        OutputSpec::protocol_finite(["json"], ["split"], "json", "split")
434    }
435
436    fn spec_with(argument: ArgSpec) -> CliSpec {
437        let id = argument.argument_id.clone();
438        CliSpec::new("demo", "1").command(
439            CommandSpec::root().arg(argument).combination(
440                Combination::new("only")
441                    .action("only")
442                    .required([id])
443                    .output(output()),
444            ),
445        )
446    }
447
448    #[test]
449    fn secret_suffix_drives_the_sensitive_bit() {
450        let built = build_afdata_cli(spec_with(ArgSpec::option("--dsn-secret", "DSN"))).unwrap();
451        let argument = &built.spec().commands[0].arguments[0];
452        assert!(argument.sensitive);
453    }
454
455    #[test]
456    fn sensitive_without_the_suffix_fails_the_build() {
457        let error = build_afdata_cli(spec_with(ArgSpec::option("--token", "TOKEN").sensitive()))
458            .unwrap_err();
459        assert_eq!(error.rule, "sensitive_without_secret_suffix");
460    }
461
462    #[test]
463    fn a_plain_argument_stays_insensitive() {
464        let built = build_afdata_cli(spec_with(ArgSpec::option("--host", "HOST"))).unwrap();
465        assert!(!built.spec().commands[0].arguments[0].sensitive);
466    }
467
468    // Locks the version payload shape. `--version` is a discovery entry point
469    // agents parse, and it lost `display_name`/`build` once before by going
470    // through a second, hand-rolled payload instead of `build_cli_version`.
471    #[test]
472    fn version_events_carry_the_full_documented_payload() {
473        let built = CliSpec::new("demo", "1.2.3")
474            .display_name("Demo Tool")
475            .build_id("abc1234")
476            .command(CommandSpec::root())
477            .build()
478            .unwrap();
479        let CliOutcome::Version(version) = built.resolve_from(["demo", "--version"]).unwrap()
480        else {
481            panic!("expected a version outcome");
482        };
483        assert_eq!(
484            cli_version_event(&version).as_value(),
485            &serde_json::json!({
486                "kind": "result",
487                "result": {
488                    "code": "version",
489                    "name": "demo",
490                    "display_name": "Demo Tool",
491                    "version": "1.2.3",
492                    "build": "abc1234",
493                },
494                "trace": {},
495            })
496        );
497    }
498
499    #[test]
500    fn version_events_omit_absent_metadata() {
501        let built = CliSpec::new("demo", "1.2.3")
502            .command(CommandSpec::root())
503            .build()
504            .unwrap();
505        let CliOutcome::Version(version) = built.resolve_from(["demo", "--version"]).unwrap()
506        else {
507            panic!("expected a version outcome");
508        };
509        let payload = serde_json::to_string(cli_version_event(&version).as_value()).unwrap();
510        assert!(!payload.contains("display_name"), "{payload}");
511        assert!(!payload.contains("build"), "{payload}");
512    }
513
514    #[test]
515    fn cli_error_events_never_carry_a_secret_value() {
516        let built = build_afdata_cli(spec_with(ArgSpec::option("--dsn-secret", "DSN"))).unwrap();
517        let error = built
518            .resolve_from([
519                "demo",
520                "--dsn-secret",
521                "postgres://user:password@example.test/db",
522                "--unknown",
523            ])
524            .unwrap_err();
525        let serialized = serde_json::to_string(cli_error_event(&error).as_value()).unwrap();
526        assert!(!serialized.contains("password"));
527        // The classification is the code, not a field beside it.
528        assert!(serialized.contains("\"code\":\"cli_unknown_argument\""));
529        // The command to run next reaches the caller through `hint`, which is
530        // the channel every error event already has.
531        assert!(serialized.contains("run `demo --help`"));
532    }
533
534    #[test]
535    fn a_secret_named_flag_is_not_marked_sensitive() {
536        // `--reveal-secret` asks to reveal a secret; it does not carry one, and
537        // a flag has no value that could leak. The suffix must not put the
538        // sensitive bit on it.
539        let built = build_afdata_cli(spec_with(ArgSpec::flag("--reveal-secret"))).unwrap();
540        let argument = built
541            .spec()
542            .commands
543            .iter()
544            .flat_map(|command| &command.arguments)
545            .find(|argument| argument.argument_id == "reveal_secret")
546            .expect("the flag is registered");
547        assert!(!argument.sensitive, "a flag has no value to redact");
548    }
549
550    #[test]
551    fn marking_a_flag_sensitive_is_a_contradiction() {
552        let error = build_afdata_cli(spec_with(ArgSpec::flag("--reveal-secret").sensitive()))
553            .expect_err("a sensitive flag must not build");
554        assert_eq!(error.rule, "sensitive_flag");
555    }
556
557    #[test]
558    fn a_value_carrying_secret_argument_is_still_marked() {
559        let built = build_afdata_cli(spec_with(ArgSpec::option("--dsn-secret", "DSN"))).unwrap();
560        let argument = built
561            .spec()
562            .commands
563            .iter()
564            .flat_map(|command| &command.arguments)
565            .find(|argument| argument.argument_id == "dsn_secret")
566            .expect("the option is registered");
567        assert!(argument.sensitive, "an option with a value still counts");
568    }
569}