agent-first-data 0.39.0

A naming convention that lets AI agents understand your data without being told what it means, plus the afdata CLI and a Rust library for reading Markdown structure and safely editing structured JSON, TOML, YAML, dotenv, and INI documents.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
//! AFDATA adapter for the closed-world CLI core.
//!
//! [`crate::cli_spec`] decides whether an invocation is legal and what it
//! resolved to. It deliberately knows nothing about how AFDATA expresses that
//! decision. This module is the only place where the two meet: it turns a
//! resolved outcome into a protocol event and owns AFDATA's `_secret` naming
//! convention.

use crate::cli_spec::SourceScheme;
use crate::cli_spec::{
    ArgValueType, BoundCliSpec, BoundOutcome, BuiltCliSpec, CliError, CliErrorRule, CliSpec,
    CliSpecError, InvocationReadError, OutputPlan, ResolvedHelp, ResolvedInvocation,
    ResolvedVersion,
};
use crate::protocol::{Event, json_error, json_result};

/// Standard terminal diagnostic for an output sink that could not be installed.
pub fn cli_output_setup_failed_event(detail: &str) -> Event {
    json_error(
        "output_setup_failed",
        if detail.is_empty() {
            "an output sink could not be established"
        } else {
            detail
        },
    )
    .build()
    .unwrap_or_else(|_| cli_invocation_invalid_event("could not construct output setup diagnostic"))
}

/// Standard terminal diagnostic for a non-broken-pipe output write failure.
pub fn cli_output_write_failed_event() -> Event {
    json_error("output_write_failed", "could not write command output")
        .build()
        .unwrap_or_else(|_| {
            cli_invocation_invalid_event("could not construct output write diagnostic")
        })
}

/// Why a CLI run ends with a given event and exit code instead of its own
/// outcome: an argv rejection, a refused pre-run check, a handler's projection
/// that cannot proceed, or a defect in how the program read its invocation.
///
/// Built from a [`CliError`] (the registry's own usage errors, exit 2), from an
/// [`InvocationReadError`] (`cli_invocation_invalid`, exit 1), with
/// [`CliStop::invalid_argument`] for a value constraint the registry cannot
/// express, or from any event and code with [`CliStop::new`].
#[derive(Debug)]
pub struct CliStop {
    event: Event,
    exit_code: u8,
}

impl CliStop {
    pub fn new(event: Event, exit_code: u8) -> Self {
        Self { event, exit_code }
    }

    /// A value the registry's types cannot judge — exactly one character, a
    /// well-formed address — refused under the same classification the parser
    /// uses for its own value errors: `cli_invalid_argument_value`, exit 2.
    pub fn invalid_argument(message: &str, hint: &str) -> Self {
        let event = json_error(CliErrorRule::InvalidArgumentValue.code(), message)
            .hint(hint)
            .build()
            .unwrap_or_else(|_| cli_invocation_invalid_event("could not construct usage error"));
        Self::new(event, 2)
    }

    pub fn event(&self) -> &Event {
        &self.event
    }

    pub const fn exit_code(&self) -> u8 {
        self.exit_code
    }

    pub fn into_parts(self) -> (Event, u8) {
        (self.event, self.exit_code)
    }
}

impl From<CliError> for CliStop {
    fn from(error: CliError) -> Self {
        Self::new(cli_error_event(&error), error.exit_code())
    }
}

impl From<InvocationReadError> for CliStop {
    fn from(error: InvocationReadError) -> Self {
        Self::new(cli_invocation_invalid_event(&error.to_string()), 1)
    }
}

/// A handler bound to an action: the pure step from a resolved invocation to
/// the program's own command value. It runs before any output sink opens, so
/// a refusal here never leaves a redirect file behind.
pub type CliHandler<C> = fn(&ResolvedInvocation) -> Result<C, CliStop>;

/// The emitter a [`CliMain`] hands to the program, wired to the process
/// streams as the resolved plan asks.
pub type ProcessEmitter = crate::cli::CliEmitter<Box<dyn std::io::Write>>;

type VersionHook<'a> = Box<dyn FnOnce(&ResolvedVersion) -> Event + 'a>;

type CheckHook<'a, C> =
    Box<dyn FnOnce(&BoundOutcome<Result<C, CliStop>>) -> Result<(), CliStop> + 'a>;

/// The whole lifecycle of a registry-compiled CLI, from `main`.
///
/// ```text
/// build registry ─ bind actions ─ resolve argv ─ check ─ project
///     ─ install --stdout-file/--stderr-file ─ help | version | docs | run
///     ─ settle write failures ─ exit code
/// ```
///
/// Each step's failure has one report. A registry that does not build or bind
/// is `cli_spec_invalid` / `cli_actions_invalid` (exit 1); a rejected argv is
/// its [`CliError`] code; a [`check`](Self::check) or a handler may stop with a
/// [`CliStop`]. All of those happen before a sink is opened and are reported as
/// strict JSON on stderr, so a refused call never creates a redirect file.
/// Then the sinks are installed (`output_setup_failed` if they cannot be, or if
/// this build has no `stream-redirect` and one was asked for), and help,
/// version and docs are answered. A run calls `execute` with the handler's
/// command, the invocation and an emitter built from the plan; that emitter
/// is the only route to stdout and stderr, raw bytes included. Whatever
/// `execute` returns is settled against what the emitter wrote: a closed reader
/// is exit 0, any other failed write exit 4 with `output_write_failed`.
pub struct CliMain<'a, C> {
    bound: Result<BoundCliSpec<Result<C, CliStop>>, CliStop>,
    check: Option<CheckHook<'a, C>>,
    version: Option<VersionHook<'a>>,
}

/// A resolved command whose output sinks stay installed until this handle drops.
pub struct PreparedCli<C> {
    /// The projected command, which can be moved out without dropping the sinks.
    pub command: C,
    /// The resolved invocation.
    pub invocation: ResolvedInvocation,
    _sinks: InstalledSinks,
}

impl<C> PreparedCli<C> {
    /// Return the output plan for this process.
    pub fn output_plan(&self) -> &OutputPlan {
        self.invocation.output_plan()
    }

    /// Create an emitter for one command or logical request.
    pub fn emitter(&self) -> ProcessEmitter {
        crate::cli::CliEmitter::from_plan(self.output_plan())
    }

    /// Execute a synchronous command and settle its output status.
    pub fn execute(
        self,
        execute: impl FnOnce(C, &ResolvedInvocation, &mut ProcessEmitter) -> Result<u8, CliStop>,
    ) -> std::process::ExitCode {
        let PreparedCli {
            command,
            invocation,
            _sinks,
        } = self;
        let mut emitter = crate::cli::CliEmitter::from_plan(invocation.output_plan());
        let result = execute(command, &invocation, &mut emitter);
        settle_output(&mut emitter, result)
    }
}

impl<'a, C> CliMain<'a, C> {
    /// Bind `actions` — built from the registry, for a program whose handler
    /// table depends on it — to `cli`.
    pub fn new<I, S>(
        cli: Result<BuiltCliSpec, CliSpecError>,
        actions: impl FnOnce(&BuiltCliSpec) -> I,
    ) -> Self
    where
        I: IntoIterator<Item = (S, CliHandler<C>)>,
        S: Into<String>,
    {
        let bound = match cli {
            Err(error) => Err(startup_stop(
                "cli_spec_invalid",
                &error.to_string(),
                "fix the program's cli-spec-v1 registry",
            )),
            Ok(cli) => cli.bind_actions(actions(&cli)).map_err(|error| {
                startup_stop(
                    "cli_actions_invalid",
                    &error.to_string(),
                    "make the action handlers match the registry's actions exactly",
                )
            }),
        };
        Self {
            bound,
            check: None,
            version: None,
        }
    }

    /// Run `hook` on every resolved outcome before anything is projected or
    /// opened: capability checks that depend on how the program was started,
    /// and argument constraints that span the whole program. A refusal is
    /// reported and no sink is created.
    #[must_use]
    pub fn check(
        mut self,
        hook: impl FnOnce(&BoundOutcome<Result<C, CliStop>>) -> Result<(), CliStop> + 'a,
    ) -> Self {
        self.check = Some(Box::new(hook));
        self
    }

    /// Answer `--version` with this event instead of [`cli_version_event`]:
    /// for a program whose version identity has more to it than the registry
    /// carries, such as the protocol versions it speaks. Build it from
    /// [`crate::build_cli_version`]'s fields so the standard ones stay.
    #[must_use]
    pub fn version(mut self, event: impl FnOnce(&ResolvedVersion) -> Event + 'a) -> Self {
        self.version = Some(Box::new(event));
        self
    }

    /// Resolve `argv` and carry the call through to its exit code.
    pub fn run<A, T>(
        self,
        argv: A,
        execute: impl FnOnce(C, &ResolvedInvocation, &mut ProcessEmitter) -> Result<u8, CliStop>,
    ) -> std::process::ExitCode
    where
        A: IntoIterator<Item = T>,
        T: Into<std::ffi::OsString>,
    {
        match self.prepare(argv) {
            Ok(prepared) => prepared.execute(execute),
            Err(exit) => exit,
        }
    }

    /// Resolve argv and install output sinks, or complete a lifecycle response.
    ///
    /// An exit code represents a completed help, version, or documentation
    /// response, or an error reported during preparation.
    pub fn prepare<A, T>(self, argv: A) -> Result<PreparedCli<C>, std::process::ExitCode>
    where
        A: IntoIterator<Item = T>,
        T: Into<std::ffi::OsString>,
    {
        let outcome = self
            .bound
            .and_then(|bound| bound.resolve_from(argv).map_err(CliStop::from));
        let outcome = match outcome {
            Ok(outcome) => outcome,
            Err(stop) => return Err(stop_before_output(stop)),
        };
        if let Some(check) = self.check
            && let Err(stop) = check(&outcome)
        {
            return Err(stop_before_output(stop));
        }
        match outcome {
            BoundOutcome::Run(invocation) => {
                let (projected, invocation) = invocation.run_with_invocation();
                let command = match projected {
                    Ok(command) => command,
                    Err(stop) => return Err(stop_before_output(stop)),
                };
                let sinks = prepare_sinks(invocation.output_plan())?;
                Ok(PreparedCli {
                    command,
                    invocation,
                    _sinks: sinks,
                })
            }
            BoundOutcome::Docs(docs) => Err(run_with_plan(docs.output_plan(), |emitter| {
                Ok(emitter.finish_raw(render_cli_reference(docs.registry()).as_bytes()))
            })),
            BoundOutcome::Help(help) => Err(run_with_plan(help.output_plan(), |emitter| {
                if help.output_plan().output_format() == Some(crate::OutputFormat::Plain) {
                    Ok(emitter.finish_raw(help.plain().as_bytes()))
                } else {
                    Ok(emitter.finish(cli_help_event(&help), 0))
                }
            })),
            BoundOutcome::Version(version) => {
                Err(run_with_plan(version.output_plan(), |emitter| {
                    let event = match self.version {
                        Some(event) => event(&version),
                        None => cli_version_event(&version),
                    };
                    Ok(emitter.finish(event, 0))
                }))
            }
        }
    }
}

/// The output half of [`CliMain`], for a program that arrived at its
/// [`OutputPlan`] some other way — a translated foreign grammar, say.
///
/// Installs the plan's file sinks, builds the emitter the plan asks for, runs
/// `execute`, and settles its exit code against what the emitter wrote. A
/// [`CliStop`] from `execute` is emitted through that emitter.
pub fn run_with_plan(
    plan: &OutputPlan,
    execute: impl FnOnce(&mut ProcessEmitter) -> Result<u8, CliStop>,
) -> std::process::ExitCode {
    let _sinks = match prepare_sinks(plan) {
        Ok(sinks) => sinks,
        Err(exit) => return exit,
    };
    let mut emitter = crate::cli::CliEmitter::from_plan(plan);
    let result = execute(&mut emitter);
    settle_output(&mut emitter, result)
}

fn settle_output(
    emitter: &mut ProcessEmitter,
    result: Result<u8, CliStop>,
) -> std::process::ExitCode {
    let code = match result {
        Ok(code) => emitter.exit_code(code),
        Err(stop) => {
            let (event, code) = stop.into_parts();
            emitter.finish(event, code)
        }
    };
    std::process::ExitCode::from(code)
}

#[cfg(feature = "stream-redirect")]
type InstalledSinks = Option<crate::stream_redirect::InstalledStreamRedirect>;
#[cfg(not(feature = "stream-redirect"))]
type InstalledSinks = ();

fn prepare_sinks(plan: &OutputPlan) -> Result<InstalledSinks, std::process::ExitCode> {
    install_sinks(plan).map_err(|detail| {
        stop_before_output(CliStop::new(cli_output_setup_failed_event(&detail), 1))
    })
}

#[cfg(feature = "stream-redirect")]
fn install_sinks(plan: &OutputPlan) -> Result<InstalledSinks, String> {
    crate::stream_redirect::install_from_plan(plan).map_err(|error| error.to_string())
}

#[cfg(not(feature = "stream-redirect"))]
fn install_sinks(plan: &OutputPlan) -> Result<InstalledSinks, String> {
    if plan.stdout_file().is_some() || plan.stderr_file().is_some() {
        return Err(
            "this build has no stream-redirect support, so file sinks are unavailable".to_string(),
        );
    }
    Ok(())
}

fn startup_stop(code: &str, message: &str, hint: &str) -> CliStop {
    let event = json_error(code, message)
        .hint(hint)
        .build()
        .unwrap_or_else(|_| cli_invocation_invalid_event("could not construct startup error"));
    CliStop::new(event, 1)
}

/// Nothing has been opened yet, so the report is strict JSON on stderr
/// whatever the argv asked for: a refused call has no output plan to honor.
fn stop_before_output(stop: CliStop) -> std::process::ExitCode {
    let (event, code) = stop.into_parts();
    let mut emitter =
        crate::cli::CliEmitter::from_output_to(crate::OutputTo::Stderr, crate::OutputFormat::Json)
            .with_strict_protocol();
    std::process::ExitCode::from(emitter.finish(event, code))
}

/// Build a registry under AFDATA's naming conventions.
///
/// `ArgSpec::sensitive` is not an independent switch. AFDATA already decides
/// what a secret is by the `_secret` suffix, and the same convention drives
/// config keys, log fields, and redaction. Deriving the bit from the argument
/// id keeps one source of truth: an argument cannot be sensitive to the parser
/// while staying invisible to redaction downstream. Marking a differently named
/// argument sensitive is the reverse mistake, so it fails the build instead of
/// silently diverging.
pub fn build_afdata_cli(mut spec: CliSpec) -> Result<BuiltCliSpec, CliSpecError> {
    for command in &mut spec.commands {
        for argument in &mut command.arguments {
            let suffixed = argument.argument_id.ends_with("_secret");
            let is_flag = matches!(argument.value_type, ArgValueType::Flag);
            if argument.sensitive && !suffixed {
                return Err(CliSpecError {
                    rule: "sensitive_without_secret_suffix",
                    message: format!(
                        "argument `{}` is marked sensitive; rename it to `{}_secret` so AFDATA \
                         redaction covers it too",
                        argument.argument_id, argument.argument_id
                    ),
                });
            }
            if argument.sensitive && is_flag {
                return Err(CliSpecError {
                    rule: "sensitive_flag",
                    message: format!(
                        "flag `{}` is marked sensitive, but a flag carries no value to redact",
                        argument.argument_id
                    ),
                });
            }
            // A flag has no value, so `_secret` in its name says what the flag
            // is *about* — `--reveal-secret` asks to reveal one, it does not
            // carry one. Marking it would put the sensitive bit on something
            // that structurally cannot leak, which reads as a real credential
            // to anything downstream that trusts the bit.
            argument.sensitive = suffixed && !is_flag;

            // A prompt suppresses terminal echo and blocks until a person
            // types — the first only means something for a secret, and the
            // second is a hang in the agent-run case this CLI is for. So the
            // source is available exactly where it earns its cost.
            if let Some(sources) = &argument.sources
                && sources.accepts(SourceScheme::Prompt)
                && !argument.sensitive
            {
                return Err(CliSpecError {
                    rule: "prompt_source_without_secret",
                    message: format!(
                        "argument `{}` accepts the `prompt` source; rename it to `{}_secret`, or \
                         drop the source — prompting blocks on a terminal for a value that is not \
                         a credential",
                        argument.argument_id, argument.argument_id
                    ),
                });
            }
        }
    }
    spec.build()
}

/// Wrap a resolved help response in a `cli-help-v2` result event.
pub fn cli_help_event(help: &ResolvedHelp) -> Event {
    json_result(serde_json::json!({
        "code": "help",
        "help": help.model(),
    }))
    .build()
}

/// Wrap a resolved version response in a protocol result event.
///
/// This delegates to [`crate::build_cli_version`] rather than assembling its
/// own payload. There is one version shape — `{code, name, version}` plus
/// `display_name`/`build` when the registry carries them — and it is the same
/// one the Go, Python, and TypeScript SDKs emit.
pub fn cli_version_event(version: &ResolvedVersion) -> Event {
    crate::cli::build_cli_version(
        version.name(),
        version.display_name(),
        version.version(),
        version.build(),
    )
}

/// Static prose for the generated CLI reference.
///
/// Kept as Markdown files rather than escaped Rust string literals: these are
/// paragraphs, and as `\`-continued literals they cannot be read as prose in a
/// diff, need every backtick and quote escaped, and turn a wording change into
/// an exercise in line continuations. The surrounding structure — headings,
/// tables, per-command sections — stays in code, because that part is generated
/// from the registry and is not prose.
///
/// This reference is emitted by every spore's `--docs`, not just afdata's, so
/// the text is shared library data and belongs beside the generator.
const SHAPES_PROSE: &str = include_str!("cli_reference/shapes.md");
const CLI_ERRORS_PROSE: &str = include_str!("cli_reference/cli-errors.md");

/// Render an offline Markdown reference for a whole registry.
///
/// help-v2 is deliberately lossy: it answers "how do I call this" one command
/// at a time, in as few tokens as possible. A reference manual wants the
/// opposite, so it is a separate capability rather than a format on the
/// discovery path — the agent's `--help` never grows a documentation mode, and
/// the manual can never disagree with the parser, because both are this
/// registry. `--docs` is injected into every registry, so a tool exposes this
/// without registering a command, and without spending a line of its
/// subcommand listing on something no agent calls.
///
/// What is deliberately *not* repeated: a lone combination's description and
/// id — the command heading already carries the description, and the id only
/// matters for telling siblings apart — plus the shared output defaults and
/// each command's arguments per combination. help repeats those because each help
/// response is read alone; a document is read in order.
pub fn render_cli_reference(cli: &BuiltCliSpec) -> String {
    let spec = cli.spec();
    let name = spec.name.as_str();
    let mut commands: Vec<&crate::cli_spec::CommandSpec> = spec
        .commands
        .iter()
        .filter(|command| !command.combinations.is_empty())
        .collect();
    commands.sort_by(|left, right| left.command_path.cmp(&right.command_path));

    let path_of = |command: &crate::cli_spec::CommandSpec| {
        if command.command_path.is_empty() {
            name.to_string()
        } else {
            format!("{name} {}", command.command_path.join(" "))
        }
    };

    let mut out = String::new();
    out.push_str(&format!("# {name} CLI reference\n\n"));
    out.push_str(&format!(
        "<!-- Generated by `{name} --docs`. Do not edit by hand. -->\n\n"
    ));
    if let Some(about) = &spec.about {
        out.push_str(&format!("{about}\n\n"));
    }
    out.push_str(&format!(
        "`{name}` is compiled from a closed `cli-spec-v1` registry: one source for argv parsing, \
         typed invocation values, which parameter combinations are legal, output contracts, and \
         help. An invocation runs only when it matches exactly one registered combination.\n\n"
    ));

    // Everything AFDATA registers on the caller's behalf, in one place. Split
    // across sections it reads as unrelated trivia, and `--version`/`--docs`
    // fall through the gap entirely — they belong to no command, so no command
    // section would ever mention them.
    let baseline = baseline_output(&commands);
    out.push_str("## Global arguments\n\n");
    // Not "no command declares them": `--version` and `--docs` are answered by
    // the root alone, so a command may declare its own argument under that
    // spelling — where one does, the entry below is still only the root's.
    out.push_str(
        "AFDATA registers these itself, so the syntax in [Commands](#commands) \
         leaves them out.\n\n",
    );
    out.push_str("| Argument | Where | What it does |\n|---|---|---|\n");
    out.push_str(
        "| `--help` | every command | Every legal shape of that command, complete, plus its \
         subcommands. JSON by default; `--output plain` for a terminal. |\n",
    );
    out.push_str(&format!(
        "| `--version` | {name} only | Name, version, and build identity as one protocol result. \
         |\n"
    ));
    out.push_str(&format!(
        "| `--docs` | {name} only | This document, rendered from the registry. |\n"
    ));
    if let Some(crate::cli_spec::OutputSpec::Protocol {
        formats,
        destinations,
        default_format,
        default_destination,
        ..
    }) = &baseline
    {
        out.push_str(&format!(
            "| `--output <FORMAT>` | per output contract | Render as {} (default \
             `{default_format}`). |\n",
            formats.join(", ")
        ));
        out.push_str(&format!(
            "| `--output-to <DESTINATION>` | per output contract | Route results and diagnostics \
             to {} (default `{default_destination}`). |\n",
            destinations.join(", ")
        ));
    }
    out.push_str(
        "| `--stdout-file <PATH>`, `--stderr-file <PATH>` | per output contract | Append that \
         stream to a file instead. |\n\n",
    );
    let baseline_line = baseline.as_ref().map(describe_output);
    // The table above already lists the arguments and their values; the only
    // thing left to say is what a successful call actually writes.
    if baseline.is_some() {
        out.push_str(
            "Success output is protocol events, on those terms, unless a command's own \
             **Output** line says otherwise.\n\n",
        );
    }
    out.push_str(SHAPES_PROSE);
    out.push('\n');

    out.push_str("## Commands\n\n");
    for command in &commands {
        let path = path_of(command);
        let anchor = path.replace(' ', "-");
        let about = command.about.as_deref().unwrap_or("");
        out.push_str(&format!("- [`{path}`](#{anchor}) — {about}\n"));
    }
    out.push('\n');

    for command in &commands {
        let path = path_of(command);
        out.push_str(&format!("### `{path}`\n\n"));
        if let Some(about) = &command.about {
            out.push_str(&format!("{about}\n\n"));
        }

        let Some(model) = cli.help(&command.command_path) else {
            continue;
        };
        for shape in &model.shapes {
            if model.shapes.len() > 1 {
                let differs = shape.about.as_deref().unwrap_or_default();
                out.push_str(&format!("#### `{}` — {differs}\n\n", shape.id));
            }
            out.push_str(&format!(
                "```\n{}\n```\n\n",
                trim_output_arguments(&shape.usage)
            ));
        }

        let combinations: Vec<&crate::cli_spec::Combination> =
            command.combinations.iter().collect();
        let contracts = output_contracts(&combinations);
        let is_baseline =
            matches!((contracts.as_slice(), &baseline_line), ([only], Some(line)) if only == line);
        if !is_baseline {
            out.push_str(&render_output(&contracts));
        }

        let documented: Vec<(&crate::cli_spec::ArgSpec, String)> = command
            .arguments
            .iter()
            .filter_map(|argument| Some((argument, argument.rendered_about()?)))
            .collect();
        if !documented.is_empty() {
            if model.shapes.len() > 1 {
                // One table per command, so it necessarily spans shapes that
                // cannot be used together; the syntax above is what says which
                // argument belongs where.
                out.push_str("Arguments across every shape above:\n\n");
            }
            out.push_str("| Argument | Meaning |\n|---|---|\n");
            for (argument, about) in documented {
                // The same spelling the usage line above uses, so the table can
                // be read against it without translating ids back to flags.
                out.push_str(&format!(
                    "| `{}` | {about} |\n",
                    crate::cli_spec::argument_key(argument)
                ));
            }
            out.push('\n');
        }

        // After the table, because it is the paragraph the table cannot hold.
        if let Some(note) = &command.reference_note {
            out.push_str(note.trim_end());
            out.push_str("\n\n");
        }
    }

    out.push_str("## Exit codes\n\n");
    out.push_str(
        "| Code | Meaning |\n|---|---|\n\
         | 0 | The command ran and succeeded. |\n\
         | 1 | The command ran and failed. The event carries a domain `error.code`. |\n\
         | 2 | The invocation was rejected before anything ran. `error.code` is one of the \
         `cli_*` codes below. |\n",
    );
    // Sorted rather than left in declaration order: the table is read by code,
    // and a registry author's ordering is not the reader's.
    let mut declared_exit_codes: Vec<(u8, &str)> = spec
        .exit_codes
        .iter()
        .map(|exit| (exit.code, exit.meaning.as_str()))
        .collect();
    declared_exit_codes.push((
        4,
        "Output could not be written (`output_write_failed`); a closed reader is success.",
    ));
    declared_exit_codes.sort_by_key(|(code, _)| *code);
    for (code, meaning) in declared_exit_codes {
        out.push_str(&format!("| {code} | {meaning} |\n"));
    }
    out.push_str(
        "\nThe split is the useful one for a caller: exit 2 means the call was never made, so \
         retrying it unchanged cannot help, while exit 1 means it was.\n\n",
    );

    out.push_str("## CLI errors\n\n");
    out.push_str(CLI_ERRORS_PROSE);
    out
}

/// One line per command saying what its success output is, because the usage
/// line can only show that by omission.
fn describe_output(output: &crate::cli_spec::OutputSpec) -> String {
    use crate::cli_spec::OutputSpec;
    match output {
        OutputSpec::Raw { file_sinks } => format!(
            "raw bytes on success; rejects `--output` and `--output-to`{}. Failures are still \
             strict JSON on stderr",
            render_file_sinks(file_sinks)
        ),
        OutputSpec::Protocol {
            formats,
            destinations,
            default_format,
            default_destination,
            file_sinks,
            ..
        } => format!(
            "protocol events; `--output` {} (default `{default_format}`), `--output-to` {} \
             (default `{default_destination}`){}",
            formats.join("/"),
            destinations.join("/"),
            render_file_sinks(file_sinks),
        ),
    }
}

/// Each distinct output contract a command exposes, in a stable order.
fn output_contracts(combinations: &[&crate::cli_spec::Combination]) -> Vec<String> {
    let mut lines: Vec<String> = Vec::new();
    for combination in combinations {
        let line = describe_output(&combination.output);
        if !lines.contains(&line) {
            lines.push(line);
        }
    }
    lines
}

/// The output contract most commands share, if there is one worth hoisting.
///
/// Deterministic: ties break on the rendered description, never on registration
/// order, so the same registry always renders the same document.
fn baseline_output(
    commands: &[&crate::cli_spec::CommandSpec],
) -> Option<crate::cli_spec::OutputSpec> {
    let mut counts: std::collections::BTreeMap<String, (usize, crate::cli_spec::OutputSpec)> =
        std::collections::BTreeMap::new();
    for command in commands {
        let mut contracts: Vec<&crate::cli_spec::OutputSpec> = Vec::new();
        for combination in &command.combinations {
            if !contracts.contains(&&combination.output) {
                contracts.push(&combination.output);
            }
        }
        if let [only] = contracts.as_slice() {
            let entry = counts
                .entry(describe_output(only))
                .or_insert((0, (*only).clone()));
            entry.0 += 1;
        }
    }
    counts
        .into_iter()
        .max_by(|left, right| left.1.0.cmp(&right.1.0).then_with(|| right.0.cmp(&left.0)))
        .filter(|(_, (count, _))| *count > 1)
        .map(|(_, (_, spec))| spec)
}

fn render_output(contracts: &[String]) -> String {
    match contracts {
        [] => String::new(),
        [only] => format!("Output: {only}.\n\n"),
        many => {
            let mut out = String::from("Output differs by combination:\n\n");
            for line in many {
                out.push_str(&format!("- {line}\n"));
            }
            out.push('\n');
            out
        }
    }
}

/// Drop the trailing AFDATA output arguments from a usage line.
///
/// The compiler always renders them last and in a fixed order, and their names
/// are reserved, so no application argument can be mistaken for one. A document
/// states the output contract once per command; only `--help`, whose response
/// is read on its own, needs them inline.
fn trim_output_arguments(usage: &str) -> &str {
    let cut = ["[--output ", "[--stdout-file ", "[--stderr-file "]
        .iter()
        .filter_map(|marker| usage.find(marker))
        .min();
    match cut {
        Some(index) => usage[..index].trim_end(),
        None => usage,
    }
}

fn render_file_sinks(file_sinks: &[String]) -> String {
    let mut names: Vec<&str> = Vec::new();
    if file_sinks.iter().any(|sink| sink == "stdout") {
        names.push("`--stdout-file`");
    }
    if file_sinks.iter().any(|sink| sink == "stderr") {
        names.push("`--stderr-file`");
    }
    if names.is_empty() {
        String::new()
    } else {
        format!("; redirect with {}", names.join(" or "))
    }
}

/// Wrap a CLI-resolution failure in an event whose `code` names the failure.
///
/// The classification lives in `code`, the way `document_path_not_found` and
/// its siblings already do — not in a second field beside a generic
/// `cli_error`. One error taxonomy, one place to read it, and the skill's
/// standing instruction ("branch on `error.code`") covers CLI errors too.
///
/// The event never carries raw argument values; `message` names the offending
/// argument, and `hint` says what to run next.
pub fn cli_error_event(error: &CliError) -> Event {
    let builder = json_error(error.rule.code(), &error.message).hint(&error.hint);
    match builder.build() {
        Ok(event) => event,
        Err(_) => json_error("cli_error", "failed to build CLI error")
            .build()
            .unwrap_or_else(|_| {
                // All literals above are valid; this branch is unreachable
                // but keeps production code panic-free.
                json_result(serde_json::json!({"code":"internal_cli_error"})).build()
            }),
    }
}

/// The standard event for a program that misread its own resolved invocation.
///
/// Dispatch itself cannot fail —
/// [`crate::cli_spec::BoundCliSpec::resolve_from`] binds the handler while
/// resolving, so there is no undispatchable invocation to report. What remains
/// is a handler reading an argument the selected combination does not supply:
/// an id it does not declare, or one whose type does not match the accessor.
/// [`crate::cli_spec::BoundCliSpec::call_every_combination`] catches the first
/// from a test; this is for a program that also wants to say something at
/// runtime.
///
/// It is a defect in the program, never in what the user typed, and the code
/// and exit status have to say so. Reporting it as a usage error tells the
/// caller to fix their command line and retry, and retrying cannot help — a
/// mistake that has already been made in the wild, as
/// `cli_invalid_argument_value` at exit 2. Emit this and exit 1; the
/// application still owns the exit.
pub fn cli_invocation_invalid_event(detail: &str) -> Event {
    let builder = json_error("cli_invocation_invalid", detail)
        .hint("this is a defect in the program, not in the command; report it");
    match builder.build() {
        Ok(event) => event,
        Err(_) => json_error("cli_invocation_invalid", "invocation cannot be dispatched")
            .build()
            .unwrap_or_else(|_| {
                // The literals above are valid, so this is unreachable; it
                // keeps the path panic-free the way `cli_error_event` does.
                json_result(serde_json::json!({"code":"internal_cli_error"})).build()
            }),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cli_spec::SourceSet;
    use crate::cli_spec::{ArgSpec, CliOutcome, Combination, CommandSpec, OutputSpec};

    fn output() -> OutputSpec {
        OutputSpec::protocol_finite(["json"], ["split"], "json", "split")
    }

    fn spec_with(argument: ArgSpec) -> CliSpec {
        let id = argument.argument_id.clone();
        CliSpec::new("demo", "1").command(
            CommandSpec::root().arg(argument).combination(
                Combination::new("only")
                    .action("only")
                    .required([id])
                    .output(output()),
            ),
        )
    }

    #[test]
    fn a_cli_declares_exit_codes_beyond_afdatas_own() {
        let spec = CliSpec::new("demo", "1.0.0")
            .lifecycle_output(output())
            .exit_code(5, "An application-specific failure.")
            .exit_code(3, "The command ran and partly succeeded.")
            .command(CommandSpec::root())
            .build()
            .unwrap();
        let reference = render_cli_reference(&spec);
        let table = reference
            .split("## Exit codes")
            .nth(1)
            .expect("the reference documents exit codes");
        // Sorted by code, not by declaration order: the table is read by code.
        let partial = table.find("| 3 | The command ran and partly succeeded. |");
        let write_failed = table.find("| 5 | An application-specific failure. |");
        assert!(partial.is_some() && write_failed.is_some(), "{table}");
        assert!(partial < write_failed, "{table}");
    }

    /// The syntax lives in the declaration, so help and `--docs` render it and
    /// no `about` string repeats it. This is the duplication the declaration
    /// exists to remove.
    #[test]
    fn a_declared_source_set_renders_itself_into_help_and_docs() {
        let built = build_afdata_cli(spec_with(
            ArgSpec::option("--token-secret", "SOURCE")
                .about("Token this host requires")
                .sources(SourceSet::config().host_scheme("container", "container:NAME")),
        ))
        .expect("registry builds");

        let reference = render_cli_reference(&built);
        assert!(
            reference.contains(
                "Token this host requires (the value, or where to read it: env:NAME, \
                 file[+FORMAT]:PATH[#DOT_PATH], container:NAME, literal:VALUE)"
            ),
            "{reference}"
        );

        let CliOutcome::Help(help) = built
            .resolve_from(vec!["demo", "--help"])
            .expect("help resolves")
        else {
            panic!("--help must resolve to help");
        };
        let model = serde_json::to_value(help.model()).expect("help serializes");
        let note = model["notes"]["--token-secret"]
            .as_str()
            .unwrap_or_default()
            .to_string();
        assert!(note.contains("file[+FORMAT]:PATH[#DOT_PATH]"), "{model}");
    }

    /// A value naming a scheme the argument does not accept is a usage error,
    /// beside the other argv rejections — and nothing was opened to find out.
    #[test]
    fn an_unaccepted_scheme_is_an_argv_rejection() {
        let built = build_afdata_cli(spec_with(
            ArgSpec::option("--token-secret", "SOURCE").sources(SourceSet::config()),
        ))
        .expect("registry builds");
        let error = built
            .resolve_from(vec!["demo", "--token-secret", "prompt"])
            .expect_err("prompt is not in config()");
        assert_eq!(
            error.rule,
            crate::cli_spec::CliErrorRule::InvalidArgumentValue
        );
        assert!(error.message.contains("env:NAME"), "{}", error.message);

        // …and one it does accept resolves to the raw string, unread.
        let outcome = built
            .resolve_from(vec!["demo", "--token-secret", "env:NAME"])
            .expect("env is accepted");
        let CliOutcome::Run(invocation) = outcome else {
            panic!("must resolve to a run");
        };
        assert_eq!(
            invocation.source("token_secret").unwrap(),
            &crate::cli_spec::ValueSource::Env("NAME".to_string())
        );
    }

    /// Prompting suppresses echo and blocks on a terminal. Both only make sense
    /// for a credential, so the source is refused anywhere else.
    #[test]
    fn the_prompt_source_is_refused_on_a_non_secret_argument() {
        let error = build_afdata_cli(spec_with(
            ArgSpec::option("--label", "LABEL").sources(SourceSet::stream()),
        ))
        .expect_err("prompt on a non-secret argument");
        assert_eq!(error.rule, "prompt_source_without_secret");
        // The same set is fine once the name says it carries a credential.
        assert!(
            build_afdata_cli(spec_with(
                ArgSpec::option("--token-secret", "SOURCE").sources(SourceSet::stream())
            ))
            .is_ok()
        );
    }

    #[test]
    fn secret_suffix_drives_the_sensitive_bit() {
        let built = build_afdata_cli(spec_with(ArgSpec::option("--dsn-secret", "DSN"))).unwrap();
        let argument = &built.spec().commands[0].arguments[0];
        assert!(argument.sensitive);
    }

    #[test]
    fn sensitive_without_the_suffix_fails_the_build() {
        let error = build_afdata_cli(spec_with(ArgSpec::option("--token", "TOKEN").sensitive()))
            .unwrap_err();
        assert_eq!(error.rule, "sensitive_without_secret_suffix");
    }

    #[test]
    fn a_plain_argument_stays_insensitive() {
        let built = build_afdata_cli(spec_with(ArgSpec::option("--host", "HOST"))).unwrap();
        assert!(!built.spec().commands[0].arguments[0].sensitive);
    }

    // Locks the version payload shape. `--version` is a discovery entry point
    // agents parse, and it lost `display_name`/`build` once before by going
    // through a second, hand-rolled payload instead of `build_cli_version`.
    #[test]
    fn version_events_carry_the_full_documented_payload() {
        let built = CliSpec::new("demo", "1.2.3")
            .display_name("Demo Tool")
            .build_id("abc1234")
            .command(CommandSpec::root())
            .build()
            .unwrap();
        let CliOutcome::Version(version) = built.resolve_from(["demo", "--version"]).unwrap()
        else {
            panic!("expected a version outcome");
        };
        assert_eq!(
            cli_version_event(&version).as_value(),
            &serde_json::json!({
                "kind": "result",
                "result": {
                    "code": "version",
                    "name": "demo",
                    "display_name": "Demo Tool",
                    "version": "1.2.3",
                    "build": "abc1234",
                },
                "trace": {},
            })
        );
    }

    #[test]
    fn version_events_omit_absent_metadata() {
        let built = CliSpec::new("demo", "1.2.3")
            .command(CommandSpec::root())
            .build()
            .unwrap();
        let CliOutcome::Version(version) = built.resolve_from(["demo", "--version"]).unwrap()
        else {
            panic!("expected a version outcome");
        };
        let payload = serde_json::to_string(cli_version_event(&version).as_value()).unwrap();
        assert!(!payload.contains("display_name"), "{payload}");
        assert!(!payload.contains("build"), "{payload}");
    }

    #[test]
    fn cli_error_events_never_carry_a_secret_value() {
        let built = build_afdata_cli(spec_with(ArgSpec::option("--dsn-secret", "DSN"))).unwrap();
        let error = built
            .resolve_from([
                "demo",
                "--dsn-secret",
                "postgres://user:password@example.test/db",
                "--unknown",
            ])
            .unwrap_err();
        let serialized = serde_json::to_string(cli_error_event(&error).as_value()).unwrap();
        assert!(!serialized.contains("password"));
        // The classification is the code, not a field beside it.
        assert!(serialized.contains("\"code\":\"cli_unknown_argument\""));
        // The command to run next reaches the caller through `hint`, which is
        // the channel every error event already has.
        assert!(serialized.contains("run `demo --help`"));
    }

    /// The point of shipping this helper is that every consumer reports the
    /// same thing. Pin the code, so a consumer branching on it keeps working,
    /// and pin that it is not a `cli_*` usage code — a caller must not be told
    /// to fix their command line for a defect in the program.
    #[test]
    fn invocation_invalid_event_is_a_program_defect_not_a_usage_error() {
        let event = cli_invocation_invalid_event("no handler for this registry's invocation");
        let serialized = serde_json::to_string(event.as_value()).unwrap();

        assert!(serialized.contains("\"code\":\"cli_invocation_invalid\""));
        assert!(serialized.contains("no handler for this registry's invocation"));
        // The hint has to say who should act. A usage hint here would send the
        // caller to debug their own arguments for a dispatch-table bug.
        assert!(serialized.contains("defect in the program"));
        assert!(
            crate::validate_protocol_event(event.as_value(), true).is_ok(),
            "the helper must emit a strict event: {serialized}"
        );
    }

    #[test]
    fn a_secret_named_flag_is_not_marked_sensitive() {
        // `--reveal-secret` asks to reveal a secret; it does not carry one, and
        // a flag has no value that could leak. The suffix must not put the
        // sensitive bit on it.
        let built = build_afdata_cli(spec_with(ArgSpec::flag("--reveal-secret"))).unwrap();
        let argument = built
            .spec()
            .commands
            .iter()
            .flat_map(|command| &command.arguments)
            .find(|argument| argument.argument_id == "reveal_secret")
            .expect("the flag is registered");
        assert!(!argument.sensitive, "a flag has no value to redact");
    }

    #[test]
    fn marking_a_flag_sensitive_is_a_contradiction() {
        let error = build_afdata_cli(spec_with(ArgSpec::flag("--reveal-secret").sensitive()))
            .expect_err("a sensitive flag must not build");
        assert_eq!(error.rule, "sensitive_flag");
    }

    #[test]
    fn a_value_carrying_secret_argument_is_still_marked() {
        let built = build_afdata_cli(spec_with(ArgSpec::option("--dsn-secret", "DSN"))).unwrap();
        let argument = built
            .spec()
            .commands
            .iter()
            .flat_map(|command| &command.arguments)
            .find(|argument| argument.argument_id == "dsn_secret")
            .expect("the option is registered");
        assert!(argument.sensitive, "an option with a value still counts");
    }

    #[test]
    fn an_invalid_argument_stop_is_a_usage_error() {
        let stop = CliStop::invalid_argument("expected one character", "pass a single character");
        assert_eq!(stop.exit_code(), 2);
        let value = stop.event().as_value();
        assert_eq!(value["kind"], "error");
        assert_eq!(value["error"]["code"], "cli_invalid_argument_value");
        assert_eq!(value["error"]["hint"], "pass a single character");
        let (event, code) = stop.into_parts();
        assert_eq!(code, 2);
        assert_eq!(
            event.as_value()["error"]["message"],
            "expected one character"
        );
    }

    #[test]
    fn a_failed_read_stops_as_a_program_defect() {
        let built = build_afdata_cli(spec_with(ArgSpec::option("--label", "LABEL"))).unwrap();
        let CliOutcome::Run(invocation) = built
            .resolve_from(["demo", "--label", "a"])
            .expect("resolves")
        else {
            panic!("must resolve to a run");
        };
        let error = invocation.text("lable").unwrap_err();
        let stop = CliStop::from(error);
        assert_eq!(stop.exit_code(), 1);
        assert_eq!(
            stop.event().as_value()["error"]["code"],
            "cli_invocation_invalid"
        );
        assert!(
            stop.event().as_value()["error"]["message"]
                .as_str()
                .is_some_and(|message| message.contains("lable") && message.contains("only")),
            "{:?}",
            stop.event()
        );
    }

    #[test]
    fn an_argv_rejection_stops_with_its_rule_code_and_exit_two() {
        let built = build_afdata_cli(spec_with(ArgSpec::option("--label", "LABEL"))).unwrap();
        let error = built
            .resolve_from(["demo", "--nope"])
            .expect_err("unknown argument");
        let stop = CliStop::from(error);
        assert_eq!(stop.exit_code(), 2);
        assert_eq!(
            stop.event().as_value()["error"]["code"],
            "cli_unknown_argument"
        );
    }
}