agent-first-data 0.39.1

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
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
use super::error::{
    InvocationReadError, InvocationReadProblem, duplicate_error, invalid_value, missing_value,
};
use super::help::combination_usage;
use super::*;
use std::collections::{BTreeMap, BTreeSet};
use std::ffi::OsString;
use std::path::{Path, PathBuf};

/// Validated registry used for resolution and help generation.
#[derive(Clone, Debug, PartialEq)]
pub struct BuiltCliSpec {
    pub(super) spec: CliSpec,
}

impl BuiltCliSpec {
    pub fn spec(&self) -> &CliSpec {
        &self.spec
    }

    pub fn resolve_from<I, S>(&self, args: I) -> Result<CliOutcome, CliError>
    where
        I: IntoIterator<Item = S>,
        S: Into<OsString>,
    {
        let raw: Vec<OsString> = args.into_iter().map(Into::into).collect();
        self.resolve_os(&raw)
    }

    /// Generate type-correct argv for every combination and every fixed
    /// `one_of` member. These fixtures exercise the same normalized shapes
    /// used by help rendering without pretending help placeholders are argv.
    pub fn synthetic_invocations(&self) -> Vec<SyntheticInvocation> {
        let mut fixtures = Vec::new();
        for command in &self.spec.commands {
            for combination in &command.combinations {
                let mut variants = vec![vec![self.spec.name.clone()]];
                for part in &command.command_path {
                    for argv in &mut variants {
                        argv.push(part.clone());
                    }
                }
                for argument in &command.arguments {
                    let values: Vec<String> =
                        if let Some(fixed) = combination.fixed.get(&argument.argument_id) {
                            fixed.values().to_vec()
                        } else if combination
                            .required
                            .iter()
                            .any(|id| id == &argument.argument_id)
                        {
                            vec![synthetic_value(argument)]
                        } else {
                            continue;
                        };
                    let mut expanded = Vec::new();
                    for argv in variants {
                        for value in &values {
                            let mut candidate = argv.clone();
                            append_synthetic_argument(&mut candidate, argument, value);
                            expanded.push(candidate);
                        }
                    }
                    variants = expanded;
                }
                fixtures.extend(variants.into_iter().map(|argv| SyntheticInvocation {
                    command_path: command.command_path.clone(),
                    combination_id: combination.combination_id.clone(),
                    argv,
                }));
            }
        }
        fixtures
    }

    /// The help model for one command.
    ///
    /// The same model `--help` returns, reachable in-process. Build-time
    /// tooling — an offline reference renderer, for example — needs the whole
    /// registry, and this is how it consumes it without a full-spec dump on
    /// the agent's discovery path.
    pub fn help(&self, command_path: &[String]) -> Option<CliHelpV2> {
        let command = self
            .spec
            .commands
            .iter()
            .find(|candidate| candidate.command_path == command_path)?;
        Some(self.help_model(command))
    }

    /// Check exact action coverage and return an executable binding.
    pub fn bind_actions<R, I, S>(&self, handlers: I) -> Result<BoundCliSpec<R>, CliSpecError>
    where
        I: IntoIterator<Item = (S, fn(&ResolvedInvocation) -> R)>,
        S: Into<String>,
    {
        let expected: BTreeSet<&str> = self
            .spec
            .commands
            .iter()
            .flat_map(|command| command.combinations.iter())
            .map(|combination| combination.action_id.as_str())
            .collect();
        let mut actual = BTreeMap::new();
        for (action_id, handler) in handlers {
            let action_id = action_id.into();
            if actual.insert(action_id.clone(), handler).is_some() {
                return Err(CliSpecError::new(
                    "duplicate_action_handler",
                    format!("action `{action_id}` has more than one handler"),
                ));
            }
        }
        let actual_ids: BTreeSet<&str> = actual.keys().map(String::as_str).collect();
        if expected != actual_ids {
            let missing: Vec<&str> = expected.difference(&actual_ids).copied().collect();
            let extra: Vec<&str> = actual_ids.difference(&expected).copied().collect();
            return Err(CliSpecError::new(
                "action_handler_coverage",
                format!("handler coverage mismatch; missing={missing:?}, extra={extra:?}"),
            ));
        }
        Ok(BoundCliSpec {
            cli: self.clone(),
            handlers: actual,
        })
    }

    fn resolve_os(&self, raw: &[OsString]) -> Result<CliOutcome, CliError> {
        let mut utf8 = Vec::with_capacity(raw.len());
        for token in raw {
            let Some(token) = token.to_str() else {
                return Err(CliError::new(
                    CliErrorRule::InvalidUtf8,
                    self.spec.name.clone(),
                    "argv contains a token that is not valid UTF-8",
                ));
            };
            utf8.push(token.to_string());
        }
        let argv = if utf8.is_empty() { &[][..] } else { &utf8[1..] };
        let (command, consumed) = self.select_command(argv)?;
        let command_path = self.display_command_path(command);
        let parsed = tokenize(
            command,
            &argv[consumed..],
            &command_path,
            &self.spec.commands,
        )?;

        if parsed.control_count() > 0 {
            if parsed.control_count() != 1 || !parsed.application_values.is_empty() {
                return Err(CliError::unregistered(command_path));
            }
            // `--docs` renders the whole registry, which is raw bytes, not
            // protocol events. It therefore gets its own contract instead of
            // `lifecycle_output`, and must be settled before the shared
            // protocol plan below would wrongly accept `--output`.
            if parsed.docs {
                // Root-only, like `--version` below: past the command path the
                // spelling belongs to the application, and where it declared
                // one, `tokenize` bound the token to that argument and never
                // set this flag at all.
                if !command.command_path.is_empty() {
                    return Err(CliError::unregistered(command_path));
                }
                let contract = OutputSpec::raw()
                    .file_sinks(self.spec.lifecycle_output.file_sinks_ref().to_vec());
                let output = resolve_output(&contract, &parsed.output, &command_path)?;
                return Ok(CliOutcome::Docs(ResolvedDocs {
                    output,
                    registry: self.clone(),
                }));
            }
            let output =
                resolve_output(&self.spec.lifecycle_output, &parsed.output, &command_path)?;
            if parsed.help {
                return Ok(CliOutcome::Help(ResolvedHelp {
                    model: self.help_model(command),
                    output,
                }));
            }
            if parsed.version {
                if !command.command_path.is_empty() {
                    return Err(CliError::unregistered(command_path));
                }
                return Ok(CliOutcome::Version(ResolvedVersion {
                    name: self.spec.name.clone(),
                    version: self.spec.version.clone(),
                    display_name: self.spec.display_name.clone(),
                    build: self.spec.build.clone(),
                    output,
                }));
            }
        }

        let matching: Vec<&Combination> = command
            .combinations
            .iter()
            .filter(|combination| combination_matches(command, combination, &parsed))
            .collect();
        let Some(combination) = matching.first().copied() else {
            return Err(CliError::unregistered(command_path));
        };
        if matching.len() != 1 {
            return Err(CliError::new(
                CliErrorRule::UnregisteredCombination,
                command_path,
                "arguments match more than one registered CLI combination",
            ));
        }
        let output = resolve_output(&combination.output, &parsed.output, &command_path)?;
        let projected = project_values(command, combination, &parsed);
        Ok(CliOutcome::Run(ResolvedInvocation {
            command_path: command.command_path.clone(),
            action_id: combination.action_id.clone(),
            combination_id: combination.combination_id.clone(),
            values: projected.values,
            sources: projected.sources,
            declared: projected.declared,
            explicit_argument_ids: parsed.explicit_application_ids,
            output,
            strict_reads: false,
        }))
    }

    fn select_command<'a>(&'a self, argv: &[String]) -> Result<(&'a CommandSpec, usize), CliError> {
        let mut commands: Vec<&CommandSpec> = self.spec.commands.iter().collect();
        commands.sort_by_key(|command| std::cmp::Reverse(command.command_path.len()));
        if let Some(command) = commands.iter().copied().find(|command| {
            command.command_path.len() <= argv.len()
                && command
                    .command_path
                    .iter()
                    .zip(argv)
                    .all(|(expected, actual)| expected == actual)
        }) {
            let remaining = &argv[command.command_path.len()..];
            let has_children = self.spec.commands.iter().any(|candidate| {
                candidate.command_path.len() > command.command_path.len()
                    && candidate.command_path.starts_with(&command.command_path)
            });
            if remaining
                .first()
                .is_some_and(|token| !token.starts_with('-'))
                && has_children
            {
                return Err(CliError::new(
                    CliErrorRule::UnknownCommand,
                    self.display_command_path(command),
                    "unknown command",
                ));
            }
            return Ok((command, command.command_path.len()));
        }
        Err(CliError::new(
            CliErrorRule::UnknownCommand,
            self.spec.name.clone(),
            "unknown command",
        ))
    }

    fn display_command_path(&self, command: &CommandSpec) -> String {
        std::iter::once(self.spec.name.as_str())
            .chain(command.command_path.iter().map(String::as_str))
            .collect::<Vec<_>>()
            .join(" ")
    }

    fn child_help_commands(&self, command: &CommandSpec) -> Vec<String> {
        let mut children: Vec<Vec<String>> = self
            .spec
            .commands
            .iter()
            .filter(|candidate| {
                candidate.command_path.len() == command.command_path.len() + 1
                    && candidate.command_path.starts_with(&command.command_path)
            })
            .map(|candidate| candidate.command_path.clone())
            .collect();
        children.sort();
        children
            .into_iter()
            .map(|path| format!("{} {} --help", self.spec.name, path.join(" ")))
            .collect()
    }

    fn help_model(&self, command: &CommandSpec) -> CliHelpV2 {
        let command_path = self.display_command_path(command);
        let mut shapes = Vec::new();
        let mut notes = BTreeMap::new();
        let mut defaults = BTreeMap::new();
        for combination in &command.combinations {
            let (usage, shape_notes, shape_defaults) =
                combination_usage(command, combination, &command_path, true);
            shapes.push(CliShape {
                id: combination.combination_id.clone(),
                // With one shape there is nothing to tell apart, so the
                // command's own description already covers it.
                about: if command.combinations.len() == 1 {
                    None
                } else {
                    combination.about.clone()
                },
                usage,
            });
            // Arguments belong to the command, so a note or default reached
            // through any shape is the same fact; collecting them once keeps
            // the response from repeating itself per shape.
            notes.extend(shape_notes);
            defaults.extend(shape_defaults);
        }
        CliHelpV2 {
            schema: "cli-help-v2".to_string(),
            command_path,
            // The root command has no description of its own — the registry's
            // does double duty, and without this fallback an agent's first
            // discovery call learns every subcommand but never what the tool is.
            about: command.about.clone().or_else(|| {
                command
                    .command_path
                    .is_empty()
                    .then(|| self.spec.about.clone())
                    .flatten()
            }),
            shapes,
            subcommands: self.child_help_commands(command),
            notes,
            defaults,
        }
    }
}

/// Type-correct argv generated from a registered shape.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SyntheticInvocation {
    pub command_path: Vec<String>,
    pub combination_id: String,
    pub argv: Vec<String>,
}

/// A built registry with exactly one handler per action.
pub struct BoundCliSpec<R> {
    cli: BuiltCliSpec,
    handlers: BTreeMap<String, fn(&ResolvedInvocation) -> R>,
}

impl<R> BoundCliSpec<R> {
    /// Resolve argv against this registry, binding the run branch to its
    /// handler as it goes.
    ///
    /// The handler is attached here, where `bind_actions` has already proved
    /// one exists for every action, which is what makes
    /// [`BoundInvocation::run`] infallible. Resolving through the registry that
    /// owns the handlers also removes the possibility of dispatching an
    /// invocation from a *different* registry: there is no longer a step that
    /// takes one.
    pub fn resolve_from<I, S>(&self, args: I) -> Result<BoundOutcome<R>, CliError>
    where
        I: IntoIterator<Item = S>,
        S: Into<OsString>,
    {
        Ok(match self.cli.resolve_from(args)? {
            CliOutcome::Run(invocation) => BoundOutcome::Run(self.bind(invocation)),
            CliOutcome::Help(help) => BoundOutcome::Help(help),
            CliOutcome::Version(version) => BoundOutcome::Version(version),
            CliOutcome::Docs(docs) => BoundOutcome::Docs(docs),
        })
    }

    /// Call every declared combination's handler with strict argument reads,
    /// returning each combination id with what its handler produced.
    ///
    /// **This runs your handlers.** Every one of them, on synthetic argv, in
    /// whatever order the registry declares them. Use it only where a handler
    /// is a pure projection of argv into a command value. Where the handler
    /// *is* the command, this will do whatever the command does — bind a port
    /// and never return, open a terminal, write files, or uninstall something.
    /// The name of this method is not a promise that it is safe to call; the
    /// shape of your handlers is.
    ///
    /// Where it does fit, it is the other half of the typed reads on
    /// [`ResolvedInvocation`]. A handler that reads an argument id its
    /// combination does not declare, or reads one as the wrong type, gets an
    /// [`InvocationReadError`] in production — reported as a program defect,
    /// and exactly the class of typo no compiler catches. Here the read itself
    /// panics naming the combination and the id, driven by the same
    /// synthetic invocations [`BuiltCliSpec::synthetic_invocations`] generates
    /// for help and docs. Production code carries no branch for a case it
    /// cannot reach, and the case is still caught before it ships.
    ///
    /// If your handlers are not callable here, that is worth reading as a
    /// design signal rather than a limitation of this method: separating "parse
    /// argv into a typed command" from "carry the command out" makes the check
    /// available and is the better shape independently.
    ///
    /// The results are returned rather than discarded because a handler that
    /// returns a `Result` has a second thing worth checking — that every
    /// combination actually *builds* — and a caller that had to write its own
    /// loop for that would be back to hand-rolling the half this replaces.
    /// Ignore the return when the handler's output says nothing useful.
    // This method exists to fail loudly from a test; diverging is the whole
    // point, and the doc above says so. The allow records that rather than
    // reshaping a deliberate abort into a value nobody can act on.
    #[allow(clippy::panic)]
    pub fn call_every_combination(&self) -> Vec<(String, R)> {
        let mut results = Vec::new();
        for fixture in self.cli.synthetic_invocations() {
            // A fixture that does not resolve to a run is a registry defect, and
            // skipping it would let this method report success while covering
            // nothing — the one failure a check like this must not have.
            let outcome = self.cli.resolve_from(fixture.argv.clone());
            let Ok(CliOutcome::Run(mut invocation)) = outcome else {
                panic!(
                    "combination `{}` generated argv {:?}, which does not resolve to a run",
                    fixture.combination_id, fixture.argv
                );
            };
            invocation.strict_reads = true;
            let combination = invocation.combination_id.clone();
            results.push((combination, self.bind(invocation).run()));
        }
        assert!(
            !results.is_empty(),
            "no combination was called; a registry with no runnable combination cannot be verified"
        );
        results
    }

    fn bind(&self, invocation: ResolvedInvocation) -> BoundInvocation<R> {
        // `bind_actions` rejected any registry whose action ids and handler ids
        // differ, and `action_id` can only come from a combination in that same
        // registry. The allow records that proof once, here, instead of making
        // every caller carry a branch for it.
        #[allow(clippy::expect_used)]
        let handler = *self
            .handlers
            .get(invocation.action_id())
            .expect("bind_actions guarantees one handler per action id");
        BoundInvocation {
            invocation,
            handler,
        }
    }
}

/// What an argv resolved to, with the run branch already bound to its handler.
pub enum BoundOutcome<R> {
    Run(BoundInvocation<R>),
    Help(ResolvedHelp),
    Version(ResolvedVersion),
    Docs(ResolvedDocs),
}

impl<R> BoundOutcome<R> {
    /// The resolved sink plan, available before lifecycle handling or domain I/O.
    pub fn output_plan(&self) -> &OutputPlan {
        match self {
            Self::Run(invocation) => invocation.output_plan(),
            Self::Docs(docs) => docs.output_plan(),
            Self::Help(help) => help.output_plan(),
            Self::Version(version) => version.output_plan(),
        }
    }
}

impl<R> std::fmt::Debug for BoundOutcome<R> {
    /// Written by hand so it does not require `R: Debug`: `R` is whatever the
    /// application's handlers return, and demanding `Debug` of it would make
    /// this enum unusable in a test that wants to assert on the outcome.
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Run(invocation) => formatter.debug_tuple("Run").field(invocation).finish(),
            Self::Help(help) => formatter.debug_tuple("Help").field(help).finish(),
            Self::Version(version) => formatter.debug_tuple("Version").field(version).finish(),
            Self::Docs(docs) => formatter.debug_tuple("Docs").field(docs).finish(),
        }
    }
}

/// A resolved invocation together with the handler that will run it.
///
/// Running cannot fail: the handler was looked up at resolution, by the
/// registry that owns it.
pub struct BoundInvocation<R> {
    invocation: ResolvedInvocation,
    handler: fn(&ResolvedInvocation) -> R,
}

impl<R> BoundInvocation<R> {
    /// The output contract, readable before the handler runs so a caller can
    /// install redirection first.
    pub fn output_plan(&self) -> &OutputPlan {
        self.invocation.output_plan()
    }

    /// The resolved invocation, for a caller that needs more than the plan.
    pub fn invocation(&self) -> &ResolvedInvocation {
        &self.invocation
    }

    /// Run the bound handler.
    pub fn run(self) -> R {
        (self.handler)(&self.invocation)
    }

    /// Run the bound handler and give the invocation back.
    ///
    /// For a caller that still needs the resolved values afterwards — a command
    /// path, or globals read once the handler has produced its command. Without
    /// this the only way to keep them past [`run`](Self::run) is to clone the
    /// value maps before calling it.
    pub fn run_with_invocation(self) -> (R, ResolvedInvocation) {
        let result = (self.handler)(&self.invocation);
        (result, self.invocation)
    }
}

impl<R> std::fmt::Debug for BoundInvocation<R> {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("BoundInvocation")
            .field("invocation", &self.invocation)
            .finish_non_exhaustive()
    }
}

/// What an argv resolved to.
#[derive(Clone, Debug, PartialEq)]
pub enum CliOutcome {
    Run(ResolvedInvocation),
    Help(ResolvedHelp),
    Version(ResolvedVersion),
    Docs(ResolvedDocs),
}

/// One legal invocation, projected onto the shape that matched it.
///
/// Read it through the typed accessors — [`text`](Self::text),
/// [`flag`](Self::flag), [`integer`](Self::integer), [`source`](Self::source)
/// and their optional and repeated forms. Each one checks the read against
/// what the matched combination declares, and a mismatch is an
/// [`InvocationReadError`]: a defect in the program, reported as
/// `cli_invocation_invalid` at exit 1. There is no untyped read, so no handler
/// can mistake "not declared" for a legitimate `false` or an empty string.
#[derive(Clone, Debug, PartialEq)]
pub struct ResolvedInvocation {
    pub(super) command_path: Vec<String>,
    pub(super) action_id: String,
    pub(super) combination_id: String,
    pub(super) values: BTreeMap<String, InvocationValue>,
    pub(super) sources: BTreeMap<String, Vec<ValueSource>>,
    pub(super) declared: BTreeMap<String, DeclaredArgument>,
    pub(super) explicit_argument_ids: BTreeSet<String>,
    pub(super) output: OutputPlan,
    /// Set only by [`BoundCliSpec::call_every_combination`]. A read the
    /// registry refuses is a defect in the handler, and this is the mode that
    /// fails the test at the read that made it, naming combination and id.
    pub(super) strict_reads: bool,
}

/// What the matched combination declares about one argument id.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct DeclaredArgument {
    pub(super) value_type: ArgValueType,
    pub(super) repeatable: bool,
    pub(super) sourced: bool,
}

/// A parsed argument value, independent of registry default serialization.
#[derive(Clone, Debug, PartialEq)]
pub(super) enum InvocationValue {
    Bool(bool),
    String(String),
    I64(i64),
    FiniteF64(f64),
    Json(String),
    List(Vec<InvocationValue>),
}

impl InvocationValue {
    fn as_bool(&self) -> Option<bool> {
        match self {
            Self::Bool(value) => Some(*value),
            _ => None,
        }
    }

    fn as_str(&self) -> Option<&str> {
        match self {
            Self::String(value) => Some(value),
            _ => None,
        }
    }

    fn as_i64(&self) -> Option<i64> {
        match self {
            Self::I64(value) => Some(*value),
            _ => None,
        }
    }

    fn as_f64(&self) -> Option<f64> {
        match self {
            Self::FiniteF64(value) => Some(*value),
            _ => None,
        }
    }

    /// The raw, still-unparsed JSON source text of a `json` argument.
    fn as_json_str(&self) -> Option<&str> {
        match self {
            Self::Json(value) => Some(value),
            _ => None,
        }
    }

    fn as_list(&self) -> Option<&[InvocationValue]> {
        match self {
            Self::List(values) => Some(values),
            _ => None,
        }
    }
}

impl From<CliValue> for InvocationValue {
    fn from(value: CliValue) -> Self {
        match value {
            CliValue::Bool(value) => Self::Bool(value),
            CliValue::String(value) => Self::String(value),
            CliValue::I64(value) => Self::I64(value),
            CliValue::FiniteF64(value) => Self::FiniteF64(value),
            CliValue::Json(value) => Self::Json(value),
            CliValue::List(items) => Self::List(items.into_iter().map(Self::from).collect()),
        }
    }
}

/// The value types a text read accepts: every type whose value is a string.
const TEXT_TYPES: &[ArgValueType] = &[ArgValueType::String, ArgValueType::Enum, ArgValueType::Uuid];

impl ResolvedInvocation {
    pub fn command_path(&self) -> &[String] {
        &self.command_path
    }

    pub fn action_id(&self) -> &str {
        &self.action_id
    }

    pub fn combination_id(&self) -> &str {
        &self.combination_id
    }

    pub fn output_plan(&self) -> &OutputPlan {
        &self.output
    }

    /// Whether the caller wrote this argument, as opposed to inheriting it
    /// from the shape's fixed value or the argument's default.
    pub fn was_explicit(&self, argument_id: &str) -> Result<bool, InvocationReadError> {
        self.declaration(argument_id, "explicit argument")?;
        Ok(self.explicit_argument_ids.contains(argument_id))
    }

    /// Whether the matched combination declares `argument_id` at all.
    ///
    /// For a handler bound to an action several combinations share, where only
    /// some of them accept an argument: ask, then read. Reading an undeclared id
    /// is still an [`InvocationReadError`].
    pub fn declares(&self, argument_id: &str) -> bool {
        self.declared.contains_key(argument_id)
    }

    /// A string, enum or UUID value the combination always supplies: required,
    /// fixed, or defaulted.
    pub fn text(&self, argument_id: &str) -> Result<&str, InvocationReadError> {
        let value = self.single(argument_id, TEXT_TYPES, "text")?;
        self.required_value(argument_id, value, "text")?
            .as_str()
            .ok_or_else(|| self.refuse(argument_id, "text", InvocationReadProblem::WrongType))
    }

    /// A string, enum or UUID value the caller may omit.
    pub fn optional_text(&self, argument_id: &str) -> Result<Option<&str>, InvocationReadError> {
        Ok(self
            .single(argument_id, TEXT_TYPES, "optional text")?
            .and_then(InvocationValue::as_str))
    }

    /// Every value of a repeatable string, enum or UUID argument, in argv order.
    pub fn texts(&self, argument_id: &str) -> Result<Vec<&str>, InvocationReadError> {
        Ok(self
            .list(argument_id, TEXT_TYPES, "repeated text")?
            .iter()
            .filter_map(InvocationValue::as_str)
            .collect())
    }

    /// Whether a flag was given. An absent flag the combination declares is a
    /// legitimate `false`; an undeclared one is a read error, never `false`.
    pub fn flag(&self, argument_id: &str) -> Result<bool, InvocationReadError> {
        let value = self.single(argument_id, &[ArgValueType::Flag], "flag")?;
        Ok(value.and_then(InvocationValue::as_bool).unwrap_or(false))
    }

    /// The raw source text of a `json` argument the combination always supplies.
    pub fn json_text(&self, argument_id: &str) -> Result<&str, InvocationReadError> {
        let value = self.single(argument_id, &[ArgValueType::Json], "json text")?;
        self.required_value(argument_id, value, "json text")?
            .as_json_str()
            .ok_or_else(|| self.refuse(argument_id, "json text", InvocationReadProblem::WrongType))
    }

    /// The raw source text of a `json` argument the caller may omit.
    pub fn optional_json_text(
        &self,
        argument_id: &str,
    ) -> Result<Option<&str>, InvocationReadError> {
        Ok(self
            .single(argument_id, &[ArgValueType::Json], "optional json text")?
            .and_then(InvocationValue::as_json_str))
    }

    /// An `i64` argument converted to the integer type the handler works in.
    ///
    /// A value that does not fit `T` is a read error: the registry's
    /// [`ArgSpec::range`] is where the bound belongs, so the caller gets a
    /// usage error at exit 2 instead of a handler-side check.
    pub fn integer<T: TryFrom<i64>>(&self, argument_id: &str) -> Result<T, InvocationReadError> {
        let expected = integer_read("integer", std::any::type_name::<T>());
        let value = self.single(argument_id, &[ArgValueType::I64], &expected)?;
        let number = self
            .required_value(argument_id, value, &expected)?
            .as_i64()
            .ok_or_else(|| self.refuse(argument_id, &expected, InvocationReadProblem::WrongType))?;
        T::try_from(number)
            .map_err(|_| self.refuse(argument_id, &expected, InvocationReadProblem::OutOfRange))
    }

    /// An `i64` argument the caller may omit, converted as [`integer`](Self::integer).
    pub fn optional_integer<T: TryFrom<i64>>(
        &self,
        argument_id: &str,
    ) -> Result<Option<T>, InvocationReadError> {
        let expected = integer_read("optional integer", std::any::type_name::<T>());
        let Some(number) = self
            .single(argument_id, &[ArgValueType::I64], &expected)?
            .and_then(InvocationValue::as_i64)
        else {
            return Ok(None);
        };
        T::try_from(number)
            .map(Some)
            .map_err(|_| self.refuse(argument_id, &expected, InvocationReadProblem::OutOfRange))
    }

    /// Every value of a repeatable `i64` argument, each converted as
    /// [`integer`](Self::integer).
    pub fn integers<T: TryFrom<i64>>(
        &self,
        argument_id: &str,
    ) -> Result<Vec<T>, InvocationReadError> {
        let expected = integer_read("repeated integers", std::any::type_name::<T>());
        self.list(argument_id, &[ArgValueType::I64], &expected)?
            .iter()
            .filter_map(InvocationValue::as_i64)
            .map(|number| {
                T::try_from(number).map_err(|_| {
                    self.refuse(argument_id, &expected, InvocationReadProblem::OutOfRange)
                })
            })
            .collect()
    }

    /// A finite `f64` argument the combination always supplies.
    pub fn number(&self, argument_id: &str) -> Result<f64, InvocationReadError> {
        let value = self.single(argument_id, &[ArgValueType::FiniteF64], "number")?;
        self.required_value(argument_id, value, "number")?
            .as_f64()
            .ok_or_else(|| self.refuse(argument_id, "number", InvocationReadProblem::WrongType))
    }

    /// A finite `f64` argument the caller may omit.
    pub fn optional_number(&self, argument_id: &str) -> Result<Option<f64>, InvocationReadError> {
        Ok(self
            .single(argument_id, &[ArgValueType::FiniteF64], "optional number")?
            .and_then(InvocationValue::as_f64))
    }

    /// A `KEY=VALUE` argument the combination always supplies, split at the
    /// first `=`.
    pub fn key_value(&self, argument_id: &str) -> Result<(&str, &str), InvocationReadError> {
        let value = self.single(argument_id, &[ArgValueType::KeyValue], "key-value pair")?;
        self.required_value(argument_id, value, "key-value pair")?
            .as_str()
            .and_then(split_pair)
            .ok_or_else(|| {
                self.refuse(
                    argument_id,
                    "key-value pair",
                    InvocationReadProblem::WrongType,
                )
            })
    }

    /// A `KEY=VALUE` argument the caller may omit.
    pub fn optional_key_value(
        &self,
        argument_id: &str,
    ) -> Result<Option<(&str, &str)>, InvocationReadError> {
        Ok(self
            .single(
                argument_id,
                &[ArgValueType::KeyValue],
                "optional key-value pair",
            )?
            .and_then(InvocationValue::as_str)
            .and_then(split_pair))
    }

    /// Every pair of a repeatable `KEY=VALUE` argument, in argv order.
    pub fn key_values(&self, argument_id: &str) -> Result<Vec<(&str, &str)>, InvocationReadError> {
        Ok(self
            .list(
                argument_id,
                &[ArgValueType::KeyValue],
                "repeated key-value pairs",
            )?
            .iter()
            .filter_map(InvocationValue::as_str)
            .filter_map(split_pair)
            .collect())
    }

    /// Where a sourced argument's value is, as the parser classified it.
    ///
    /// Classification is syntax only: nothing has been read. Call
    /// [`ValueSource::read`](crate::value_source) or `read_secret` when the
    /// value is actually needed, so a variable or file that does not exist is
    /// a failure of the command that needed it, not of argv.
    pub fn source(&self, argument_id: &str) -> Result<&ValueSource, InvocationReadError> {
        let sources = self.sourced(argument_id, false, "source")?;
        sources
            .first()
            .ok_or_else(|| self.refuse(argument_id, "source", InvocationReadProblem::Absent))
    }

    /// A sourced argument the caller may omit.
    pub fn optional_source(
        &self,
        argument_id: &str,
    ) -> Result<Option<&ValueSource>, InvocationReadError> {
        Ok(self.sourced(argument_id, false, "optional source")?.first())
    }

    /// Every source of a repeatable sourced argument, in argv order.
    pub fn sources(&self, argument_id: &str) -> Result<&[ValueSource], InvocationReadError> {
        self.sourced(argument_id, true, "repeated sources")
    }

    fn declaration(
        &self,
        argument_id: &str,
        expected: &str,
    ) -> Result<&DeclaredArgument, InvocationReadError> {
        self.declared
            .get(argument_id)
            .ok_or_else(|| self.refuse(argument_id, expected, InvocationReadProblem::Undeclared))
    }

    /// The value of a non-repeatable, non-sourced argument of one of `types`.
    fn single(
        &self,
        argument_id: &str,
        types: &[ArgValueType],
        expected: &str,
    ) -> Result<Option<&InvocationValue>, InvocationReadError> {
        let declared = self.declaration(argument_id, expected)?;
        if declared.repeatable || declared.sourced || !types.contains(&declared.value_type) {
            return Err(self.refuse(argument_id, expected, InvocationReadProblem::WrongType));
        }
        Ok(self.values.get(argument_id))
    }

    /// The values of a repeatable, non-sourced argument of one of `types`.
    fn list(
        &self,
        argument_id: &str,
        types: &[ArgValueType],
        expected: &str,
    ) -> Result<&[InvocationValue], InvocationReadError> {
        let declared = self.declaration(argument_id, expected)?;
        if !declared.repeatable || declared.sourced || !types.contains(&declared.value_type) {
            return Err(self.refuse(argument_id, expected, InvocationReadProblem::WrongType));
        }
        Ok(self
            .values
            .get(argument_id)
            .and_then(InvocationValue::as_list)
            .unwrap_or(&[]))
    }

    fn sourced(
        &self,
        argument_id: &str,
        repeatable: bool,
        expected: &str,
    ) -> Result<&[ValueSource], InvocationReadError> {
        let declared = self.declaration(argument_id, expected)?;
        if !declared.sourced || declared.repeatable != repeatable {
            return Err(self.refuse(argument_id, expected, InvocationReadProblem::WrongType));
        }
        Ok(self.sources.get(argument_id).map_or(&[][..], Vec::as_slice))
    }

    fn required_value<'a>(
        &self,
        argument_id: &str,
        value: Option<&'a InvocationValue>,
        expected: &str,
    ) -> Result<&'a InvocationValue, InvocationReadError> {
        value.ok_or_else(|| self.refuse(argument_id, expected, InvocationReadProblem::Absent))
    }

    // Diverging here is the point of strict mode: the test fails at the read
    // that is wrong, naming the combination and the id.
    #[allow(clippy::panic)]
    fn refuse(
        &self,
        argument_id: &str,
        expected: &str,
        problem: InvocationReadProblem,
    ) -> InvocationReadError {
        let error = InvocationReadError {
            combination_id: self.combination_id.clone(),
            argument_id: argument_id.to_string(),
            expected: expected.to_string(),
            problem,
        };
        if self.strict_reads {
            panic!("{error}");
        }
        error
    }
}

fn integer_read(read: &str, type_name: &str) -> String {
    format!(
        "{read} as {}",
        type_name.rsplit("::").next().unwrap_or(type_name)
    )
}

fn split_pair(text: &str) -> Option<(&str, &str)> {
    text.split_once('=').filter(|(key, _)| !key.is_empty())
}

/// Where a resolved call's output goes, and in what form.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum OutputPlan {
    Raw {
        stdout_file: Option<PathBuf>,
        stderr_file: Option<PathBuf>,
    },
    Protocol {
        lifecycle: OutputLifecycle,
        format: OutputFormat,
        destination: OutputTo,
        stdout_file: Option<PathBuf>,
        stderr_file: Option<PathBuf>,
    },
}

impl OutputPlan {
    /// Structured output format, or `None` for a raw-byte command.
    pub const fn output_format(&self) -> Option<OutputFormat> {
        match self {
            Self::Raw { .. } => None,
            Self::Protocol { format, .. } => Some(*format),
        }
    }

    /// Structured output routing, or `None` for a raw-byte command.
    pub const fn output_to(&self) -> Option<OutputTo> {
        match self {
            Self::Raw { .. } => None,
            Self::Protocol { destination, .. } => Some(*destination),
        }
    }

    pub fn stdout_file(&self) -> Option<&Path> {
        match self {
            Self::Raw { stdout_file, .. } | Self::Protocol { stdout_file, .. } => {
                stdout_file.as_deref()
            }
        }
    }

    pub fn stderr_file(&self) -> Option<&Path> {
        match self {
            Self::Raw { stderr_file, .. } | Self::Protocol { stderr_file, .. } => {
                stderr_file.as_deref()
            }
        }
    }
}

#[derive(Default)]
struct ParsedArgs {
    application_values: BTreeMap<String, Vec<InvocationValue>>,
    /// The classified source of every value of a sourced argument, in argv
    /// order, beside its raw text in `application_values`.
    application_sources: BTreeMap<String, Vec<ValueSource>>,
    explicit_application_ids: BTreeSet<String>,
    output: ParsedOutput,
    help: bool,
    version: bool,
    docs: bool,
}

impl ParsedArgs {
    fn control_count(&self) -> usize {
        usize::from(self.help) + usize::from(self.version) + usize::from(self.docs)
    }
}

#[derive(Default)]
struct ParsedOutput {
    format: Option<String>,
    destination: Option<String>,
    stdout_file: Option<PathBuf>,
    stderr_file: Option<PathBuf>,
}

fn tokenize(
    command: &CommandSpec,
    tokens: &[String],
    command_path: &str,
    all_commands: &[CommandSpec],
) -> Result<ParsedArgs, CliError> {
    let longs: BTreeMap<&str, &ArgSpec> = command
        .arguments
        .iter()
        .filter_map(|argument| match &argument.syntax {
            ArgSyntax::Long { name } => Some((name.as_str(), argument)),
            ArgSyntax::Positional { .. } => None,
        })
        .collect();
    let mut positionals: Vec<&ArgSpec> = command
        .arguments
        .iter()
        .filter(|argument| matches!(argument.syntax, ArgSyntax::Positional { .. }))
        .collect();
    positionals.sort_by_key(|argument| match argument.syntax {
        ArgSyntax::Positional { index } => index,
        ArgSyntax::Long { .. } => usize::MAX,
    });

    let mut parsed = ParsedArgs::default();
    let mut index = 0;
    let mut positional_index = 0;
    let mut options_done = false;
    while index < tokens.len() {
        let token = &tokens[index];
        if !options_done && token == "--" {
            options_done = true;
            index += 1;
            continue;
        }
        if !options_done && token.starts_with("--") {
            let (name, inline_value) = token
                .split_once('=')
                .map_or((token.as_str(), None), |(name, value)| (name, Some(value)));
            if let Some(argument) = longs.get(name).copied() {
                let display = name.to_string();
                let raw_value = if argument.value_type == ArgValueType::Flag {
                    if inline_value.is_some() {
                        return Err(invalid_value(
                            command_path,
                            display,
                            "flags do not accept values",
                        ));
                    }
                    None
                } else {
                    Some(take_value(
                        tokens,
                        &mut index,
                        inline_value,
                        Some(argument),
                        &longs,
                        name,
                        command_path,
                    )?)
                };
                let value = match raw_value {
                    Some(value) => parse_value(argument, value).map_err(|message| {
                        invalid_value(command_path, display.clone(), &message)
                    })?,
                    None => InvocationValue::Bool(true),
                };
                insert_application(&mut parsed, argument, value, display, command_path)?;
                index += 1;
                continue;
            }
            match name {
                "--help" => {
                    reject_inline_value(inline_value, name, command_path)?;
                    set_once(&mut parsed.help, name, command_path)?;
                }
                "--version" => {
                    reject_inline_value(inline_value, name, command_path)?;
                    set_once(&mut parsed.version, name, command_path)?;
                }
                "--docs" => {
                    reject_inline_value(inline_value, name, command_path)?;
                    set_once(&mut parsed.docs, name, command_path)?;
                }
                "--output" => {
                    parsed.output.format = Some(set_output_value(
                        parsed.output.format.as_ref(),
                        take_value(
                            tokens,
                            &mut index,
                            inline_value,
                            None,
                            &longs,
                            name,
                            command_path,
                        )?,
                        name,
                        command_path,
                    )?);
                }
                "--output-to" => {
                    parsed.output.destination = Some(set_output_value(
                        parsed.output.destination.as_ref(),
                        take_value(
                            tokens,
                            &mut index,
                            inline_value,
                            None,
                            &longs,
                            name,
                            command_path,
                        )?,
                        name,
                        command_path,
                    )?);
                }
                "--stdout-file" => {
                    parsed.output.stdout_file = Some(PathBuf::from(set_output_value(
                        parsed.output.stdout_file.as_ref(),
                        take_value(
                            tokens,
                            &mut index,
                            inline_value,
                            None,
                            &longs,
                            name,
                            command_path,
                        )?,
                        name,
                        command_path,
                    )?));
                }
                "--stderr-file" => {
                    parsed.output.stderr_file = Some(PathBuf::from(set_output_value(
                        parsed.output.stderr_file.as_ref(),
                        take_value(
                            tokens,
                            &mut index,
                            inline_value,
                            None,
                            &longs,
                            name,
                            command_path,
                        )?,
                        name,
                        command_path,
                    )?));
                }
                _ => {
                    return Err(CliError::new(
                        CliErrorRule::UnknownArgument,
                        command_path.to_string(),
                        format!("unknown argument `{name}`"),
                    ));
                }
            }
            index += 1;
            continue;
        }
        if !options_done && token.starts_with('-') && token != "-" {
            let positional_accepts_value = positionals
                .get(positional_index)
                .is_some_and(|argument| accepts_hyphen_prefixed_value(argument, token));
            if !positional_accepts_value {
                let mut error = CliError::new(
                    CliErrorRule::UnknownArgument,
                    command_path.to_string(),
                    "unknown short argument",
                );
                error.hint = format!(
                    "flags are long-only; pass `--` before a positional value that starts with `-`, or run `{command_path} --help`"
                );
                return Err(error);
            }
        }
        let Some(argument) = positionals.get(positional_index).copied() else {
            // A registered command name here is almost always a caller who put
            // the command after its arguments. Saying only "unexpected
            // positional argument" is true and useless: the fix is an ordering
            // one, and nothing else in the message would suggest it.
            let message = if is_registered_command_segment(token, all_commands) {
                "command name must come before its arguments"
            } else {
                "unexpected positional argument"
            };
            return Err(CliError::new(
                CliErrorRule::UnexpectedPositional,
                command_path.to_string(),
                message,
            ));
        };
        let value = parse_value(argument, token).map_err(|message| {
            invalid_value(command_path, argument.argument_id.clone(), &message)
        })?;
        insert_application(
            &mut parsed,
            argument,
            value,
            argument.argument_id.clone(),
            command_path,
        )?;
        if !argument.repeatable {
            positional_index += 1;
        }
        index += 1;
    }
    Ok(parsed)
}

fn take_value<'a>(
    tokens: &'a [String],
    index: &mut usize,
    inline_value: Option<&'a str>,
    argument: Option<&ArgSpec>,
    longs: &BTreeMap<&str, &ArgSpec>,
    name: &str,
    command_path: &str,
) -> Result<&'a str, CliError> {
    if let Some(value) = inline_value {
        if value.is_empty() && argument.is_none() {
            return Err(missing_value(command_path, name));
        }
        return Ok(value);
    }
    let Some(value) = tokens.get(*index + 1) else {
        return Err(missing_value(command_path, name));
    };
    if value.starts_with('-')
        && value != "-"
        && !argument.is_some_and(|argument| accepts_hyphen_prefixed_value(argument, value))
    {
        let mut error = missing_value(command_path, name);
        // A registered flag next is a value left out, not a value that happens
        // to start with `-`; the `=` spelling would only pass the flag's name
        // off as the value.
        if !names_registered_flag(longs, value) {
            error.hint = format!("write `{name}=VALUE` for a value that starts with `-`");
        }
        return Err(error);
    }
    *index += 1;
    Ok(value)
}

/// Whether `token` (with or without an inline `=VALUE`) names one of the
/// command's own long flags or a control flag every command accepts.
fn names_registered_flag(longs: &BTreeMap<&str, &ArgSpec>, token: &str) -> bool {
    let name = token.split_once('=').map_or(token, |(name, _)| name);
    longs.contains_key(name)
        || matches!(
            name,
            "--help"
                | "--version"
                | "--docs"
                | "--output"
                | "--output-to"
                | "--stdout-file"
                | "--stderr-file"
        )
}

/// Whether a `-`-prefixed token is this argument's value rather than a flag.
///
/// Deliberately a *syntax* question, not a validity one. Asking `parse_value`
/// would fold semantic constraints in, so `--limit -1` against a `1..=1000`
/// range would be read as "no value supplied" — reporting a missing argument
/// for a value the caller plainly typed. Range and enum membership are checked
/// after the token is claimed, where they can say what is actually wrong.
///
/// A free-form string takes a negative number too: flags are long-only, so
/// `-5` can only ever be a value, and a config value or default is routinely
/// one (`set n -5 --value-type number`, `--default -1`).
fn accepts_hyphen_prefixed_value(argument: &ArgSpec, value: &str) -> bool {
    match argument.value_type {
        ArgValueType::I64 => value.parse::<i64>().is_ok(),
        ArgValueType::FiniteF64 => value.parse::<f64>().is_ok_and(f64::is_finite),
        ArgValueType::String => {
            value.parse::<i64>().is_ok() || value.parse::<f64>().is_ok_and(f64::is_finite)
        }
        ArgValueType::Json => serde_json::from_str::<serde::de::IgnoredAny>(value).is_ok(),
        _ => false,
    }
}

fn reject_inline_value(
    inline_value: Option<&str>,
    name: &str,
    command_path: &str,
) -> Result<(), CliError> {
    if inline_value.is_some() {
        return Err(invalid_value(
            command_path,
            name.to_string(),
            "control flags do not accept values",
        ));
    }
    Ok(())
}

fn set_once(value: &mut bool, name: &str, command_path: &str) -> Result<(), CliError> {
    if *value {
        return Err(duplicate_error(command_path, name));
    }
    *value = true;
    Ok(())
}

fn set_output_value<T>(
    existing: Option<&T>,
    value: &str,
    name: &str,
    command_path: &str,
) -> Result<String, CliError> {
    if existing.is_some() {
        return Err(duplicate_error(command_path, name));
    }
    Ok(value.to_string())
}

fn insert_application(
    parsed: &mut ParsedArgs,
    argument: &ArgSpec,
    value: InvocationValue,
    display: String,
    command_path: &str,
) -> Result<(), CliError> {
    let values = parsed
        .application_values
        .entry(argument.argument_id.clone())
        .or_default();
    if !argument.repeatable && !values.is_empty() {
        return Err(duplicate_error(command_path, &display));
    }
    if let (Some(sources), InvocationValue::String(raw)) = (&argument.sources, &value) {
        // Classify the source once without reading it.
        let source = sources
            .parse(raw)
            .map_err(|error| invalid_value(command_path, display.clone(), error.message()))?;
        parsed
            .application_sources
            .entry(argument.argument_id.clone())
            .or_default()
            .push(source);
    }
    values.push(value);
    parsed
        .explicit_application_ids
        .insert(argument.argument_id.clone());
    Ok(())
}

fn parse_value(argument: &ArgSpec, raw: &str) -> Result<InvocationValue, String> {
    match argument.value_type {
        ArgValueType::Flag => Ok(InvocationValue::Bool(true)),
        ArgValueType::String | ArgValueType::Enum => {
            if argument.value_type == ArgValueType::Enum
                && !argument.enum_values.iter().any(|value| value == raw)
            {
                return Err(format!(
                    "expected one of {}",
                    argument.enum_values.join(", ")
                ));
            }
            Ok(InvocationValue::String(raw.to_string()))
        }
        ArgValueType::KeyValue => match raw.split_once('=') {
            Some((key, _)) if !key.is_empty() => Ok(InvocationValue::String(raw.to_string())),
            Some(_) => Err("expected KEY=VALUE with a non-empty KEY".to_string()),
            None => Err("expected KEY=VALUE".to_string()),
        },
        ArgValueType::I64 => {
            let value = raw
                .parse::<i64>()
                .map_err(|_| "expected an i64 integer".to_string())?;
            if let Some([minimum, maximum]) = argument.range
                && !(minimum..=maximum).contains(&value)
            {
                return Err(format!("expected an integer in {minimum}..={maximum}"));
            }
            Ok(InvocationValue::I64(value))
        }
        ArgValueType::Uuid => {
            if is_canonical_uuid(raw) {
                Ok(InvocationValue::String(raw.to_string()))
            } else {
                Err("expected a UUID (8-4-4-4-12 hexadecimal digits)".to_string())
            }
        }
        ArgValueType::FiniteF64 => raw
            .parse::<f64>()
            .ok()
            .filter(|value| value.is_finite())
            .map(InvocationValue::FiniteF64)
            .ok_or_else(|| "expected a finite f64 number".to_string()),
        // Validate that `raw` is exactly one JSON value, then keep the source
        // text. `IgnoredAny` checks the grammar without building a
        // `serde_json::Value`, so the core never commits to a number
        // representation on the caller's behalf.
        ArgValueType::Json => serde_json::from_str::<serde::de::IgnoredAny>(raw)
            .map(|_| InvocationValue::Json(raw.to_string()))
            .map_err(|_| "expected one valid JSON value".to_string()),
    }
}

pub(super) fn validate_value_type(argument: &ArgSpec, value: &CliValue) -> Result<(), String> {
    match (&argument.value_type, value) {
        (ArgValueType::Flag, CliValue::Bool(_))
        | (ArgValueType::String, CliValue::String(_))
        | (ArgValueType::Json, CliValue::Json(_)) => Ok(()),
        // A default or fixed value is held to the same range as one typed on
        // the command line. Checking only the type would let a registry ship a
        // default its own argument rejects — a contradiction nothing downstream
        // could report, because the value never passes through the parser.
        (ArgValueType::I64, CliValue::I64(number)) => match argument.range {
            Some([minimum, maximum]) if !(minimum..=maximum).contains(number) => Err(format!(
                "value {number} is outside the argument's {minimum}..={maximum} range"
            )),
            _ => Ok(()),
        },
        (ArgValueType::Uuid, CliValue::String(text)) if is_canonical_uuid(text) => Ok(()),
        (ArgValueType::Uuid, CliValue::String(_)) => {
            Err("value is not a UUID (8-4-4-4-12 hexadecimal digits)".to_string())
        }
        (ArgValueType::FiniteF64, CliValue::FiniteF64(value)) if value.is_finite() => Ok(()),
        (ArgValueType::KeyValue, CliValue::String(text))
            if text.split_once('=').is_some_and(|(key, _)| !key.is_empty()) =>
        {
            Ok(())
        }
        (ArgValueType::KeyValue, CliValue::String(_)) => {
            Err("value is not KEY=VALUE with a non-empty KEY".to_string())
        }
        (ArgValueType::Enum, CliValue::String(value)) if argument.enum_values.contains(value) => {
            Ok(())
        }
        _ => Err("value type does not match the argument".to_string()),
    }
}

fn combination_matches(
    command: &CommandSpec,
    combination: &Combination,
    parsed: &ParsedArgs,
) -> bool {
    let allowed: BTreeSet<&str> = combination
        .fixed
        .keys()
        .map(String::as_str)
        .chain(combination.required.iter().map(String::as_str))
        .chain(combination.optional.iter().map(String::as_str))
        .collect();
    if parsed
        .explicit_application_ids
        .iter()
        .any(|id| !allowed.contains(id.as_str()))
        || combination
            .required
            .iter()
            .any(|id| !parsed.explicit_application_ids.contains(id))
    {
        return false;
    }
    combination.fixed.iter().all(|(id, fixed)| {
        let argument = command
            .arguments
            .iter()
            .find(|argument| argument.argument_id == *id);
        let effective = parsed
            .application_values
            .get(id)
            .and_then(|values| values.first())
            .and_then(InvocationValue::as_str)
            .or_else(|| {
                argument
                    .and_then(|arg| arg.default.as_ref())
                    .and_then(CliValue::as_str)
            });
        effective.is_some_and(|value| fixed.values().iter().any(|fixed| fixed == value))
    })
}

/// What the matched combination supplies, split by how a handler reads it.
struct Projected {
    values: BTreeMap<String, InvocationValue>,
    sources: BTreeMap<String, Vec<ValueSource>>,
    declared: BTreeMap<String, DeclaredArgument>,
}

fn project_values(
    command: &CommandSpec,
    combination: &Combination,
    parsed: &ParsedArgs,
) -> Projected {
    let allowed: BTreeSet<&str> = combination
        .fixed
        .keys()
        .map(String::as_str)
        .chain(combination.required.iter().map(String::as_str))
        .chain(combination.optional.iter().map(String::as_str))
        .collect();
    let mut projected = Projected {
        values: BTreeMap::new(),
        sources: BTreeMap::new(),
        declared: BTreeMap::new(),
    };
    for argument in command
        .arguments
        .iter()
        .filter(|argument| allowed.contains(argument.argument_id.as_str()))
    {
        let id = argument.argument_id.clone();
        projected.declared.insert(
            id.clone(),
            DeclaredArgument {
                value_type: argument.value_type.clone(),
                repeatable: argument.repeatable,
                sourced: argument.sources.is_some(),
            },
        );
        // The parser has already classified a sourced argument; hand that
        // classification over instead of the raw text it came from, so no
        // handler parses the same grammar a second time.
        if argument.sources.is_some() {
            if let Some(sources) = parsed.application_sources.get(&id) {
                projected.sources.insert(id, sources.clone());
            }
            continue;
        }
        let value = parsed
            .application_values
            .get(&id)
            .map(|values| {
                if argument.repeatable {
                    InvocationValue::List(values.clone())
                } else {
                    values[0].clone()
                }
            })
            .or_else(|| {
                argument
                    .default
                    .clone()
                    .map(InvocationValue::from)
                    .map(|default| {
                        if argument.repeatable {
                            InvocationValue::List(vec![default])
                        } else {
                            default
                        }
                    })
            })
            .or_else(|| {
                (argument.value_type == ArgValueType::Flag).then_some(InvocationValue::Bool(false))
            });
        if let Some(value) = value {
            projected.values.insert(id, value);
        }
    }
    projected
}

fn resolve_output(
    spec: &OutputSpec,
    parsed: &ParsedOutput,
    command_path: &str,
) -> Result<OutputPlan, CliError> {
    match spec {
        OutputSpec::Raw { file_sinks } => {
            if parsed.format.is_some() || parsed.destination.is_some() {
                return Err(CliError::unregistered(command_path.to_string()));
            }
            ensure_sinks(file_sinks, parsed, command_path)?;
            Ok(OutputPlan::Raw {
                stdout_file: parsed.stdout_file.clone(),
                stderr_file: parsed.stderr_file.clone(),
            })
        }
        OutputSpec::Protocol {
            lifecycle,
            formats,
            destinations,
            default_format,
            default_destination,
            file_sinks,
        } => {
            ensure_sinks(file_sinks, parsed, command_path)?;
            let format = parsed.format.as_ref().unwrap_or(default_format);
            if !formats.contains(format) {
                return Err(invalid_value(
                    command_path,
                    "--output".to_string(),
                    &format!("expected one of {}", formats.join(", ")),
                ));
            }
            let destination = parsed.destination.as_ref().unwrap_or(default_destination);
            if !destinations.contains(destination) {
                return Err(invalid_value(
                    command_path,
                    "--output-to".to_string(),
                    &format!("expected one of {}", destinations.join(", ")),
                ));
            }
            let output_format = format.parse::<OutputFormat>().map_err(|_| {
                invalid_value(
                    command_path,
                    "--output".to_string(),
                    "expected one of json, yaml, plain",
                )
            })?;
            let output_to = destination.parse::<OutputTo>().map_err(|_| {
                invalid_value(
                    command_path,
                    "--output-to".to_string(),
                    "expected one of split, stdout, stderr",
                )
            })?;
            Ok(OutputPlan::Protocol {
                lifecycle: *lifecycle,
                format: output_format,
                destination: output_to,
                stdout_file: parsed.stdout_file.clone(),
                stderr_file: parsed.stderr_file.clone(),
            })
        }
    }
}

fn ensure_sinks(
    allowed: &[String],
    parsed: &ParsedOutput,
    command_path: &str,
) -> Result<(), CliError> {
    if (parsed.stdout_file.is_some() && !allowed.iter().any(|sink| sink == "stdout"))
        || (parsed.stderr_file.is_some() && !allowed.iter().any(|sink| sink == "stderr"))
    {
        return Err(CliError::unregistered(command_path.to_string()));
    }
    Ok(())
}

/// Whether `token` names a segment of some registered command path.
///
/// Used only to sharpen a diagnosis, so a plain containment test is enough: the
/// point is to recognise that the caller typed a command where a value was
/// expected, not to work out which command they meant.
fn is_registered_command_segment(token: &str, all_commands: &[CommandSpec]) -> bool {
    all_commands
        .iter()
        .any(|command| command.command_path.iter().any(|segment| segment == token))
}

/// Whether `raw` is a canonical 8-4-4-4-12 hexadecimal UUID.
///
/// Hand-written rather than pulled from a crate: the check has to be something
/// another language can reimplement from `cli-spec-v1` alone, and it keeps the
/// core free of a dependency for one argument shape.
fn is_canonical_uuid(raw: &str) -> bool {
    const GROUPS: [usize; 5] = [8, 4, 4, 4, 12];
    let mut parts = raw.split('-');
    for width in GROUPS {
        let Some(part) = parts.next() else {
            return false;
        };
        if part.len() != width || !part.bytes().all(|byte| byte.is_ascii_hexdigit()) {
            return false;
        }
    }
    parts.next().is_none()
}

fn synthetic_value(argument: &ArgSpec) -> String {
    match argument.value_type {
        ArgValueType::Flag => String::new(),
        ArgValueType::String => {
            if argument.sensitive {
                "synthetic-sensitive".to_string()
            } else {
                "value".to_string()
            }
        }
        ArgValueType::I64 => argument
            .range
            .map_or_else(|| "1".to_string(), |[minimum, _]| minimum.to_string()),
        ArgValueType::Uuid => "00000000-0000-0000-0000-000000000000".to_string(),
        ArgValueType::FiniteF64 => "1.5".to_string(),
        ArgValueType::Enum => argument.enum_values.first().cloned().unwrap_or_default(),
        ArgValueType::Json => "{}".to_string(),
        ArgValueType::KeyValue => "key=value".to_string(),
    }
}

fn append_synthetic_argument(argv: &mut Vec<String>, argument: &ArgSpec, value: &str) {
    match &argument.syntax {
        ArgSyntax::Long { name } => {
            argv.push(name.clone());
            if argument.value_type != ArgValueType::Flag {
                argv.push(value.to_string());
            }
        }
        ArgSyntax::Positional { .. } => argv.push(value.to_string()),
    }
}