safe-chains 0.243.2

Auto-allow safe bash commands in agentic coding tools
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
use std::collections::HashMap;

use crate::policy::{FlagTolerance, UnknownTolerance};
use crate::verdict::SafetyLevel;

use super::types::*;

/// A command definition is invalid. Returns `Err` from the enclosing function instead of panicking.
///
/// These checks run on USER-supplied configs as well as the built-in `commands/*.toml`: a
/// `~/.config/safe-chains.toml` or a repo `.safe-chains.toml` goes through exactly this code. An
/// abort there takes a PreToolUse hook down, and a crashed hook means the harness PROCEEDS — so a
/// typo in a config file used to disable safe-chains altogether. It was caught downstream by
/// `catch_unwind`, but panicking across a library boundary as control flow left two marks: the
/// default hook printed a panic and a backtrace to stderr on every invocation before anything could
/// catch it, and under libFuzzer a caught panic is still an abort (how `config_load` kept failing).
///
/// The built-in definitions are compiled in and turn an `Err` back into a panic AT THE CALL SITE,
/// where it belongs: a broken `commands/*.toml` is a bug in this repository, not something a user
/// typed, and it should stop the process loudly.
macro_rules! fail {
    ($($arg:tt)*) => { return Err(format!($($arg)*)) };
}

/// `assert!` for the same checks: the condition must hold or the definition is rejected.
macro_rules! ensure {
    ($cond:expr, $($arg:tt)*) => {
        if !($cond) {
            return Err(format!($($arg)*));
        }
    };
}

#[path = "build_archetype_flags.rs"]
mod archetype_flags;
#[path = "build_eval_safe.rs"]
mod eval_safe;
#[path = "build_lower.rs"]
mod lower;
#[path = "build_sub.rs"]
mod sub;
pub(crate) use archetype_flags::ArchetypeFlags;
use eval_safe::*;
use lower::{lower_behavior, lower_output};
use sub::build_subs;

/// `optional_valued` compiles down to membership in BOTH other lists, and that is the whole
/// mechanism — the walk needs no third state.
///
/// Measured before choosing this (`policy::tests::a_flag_declared_in_both_lists_…`): `check_flags`
/// consults `standalone` first, so the BARE spelling matches there and cannot swallow the next
/// token; its `=` branch consults `valued`, so the GLUED spelling matches too. Both are honoured,
/// for different spellings, which is exactly what an optional-value flag means — and it matches
/// getopt, where an optional argument must be glued (`--flag=x`, never `--flag x`).
///
/// So this field buys INTENT, not behaviour. That distinction is the point: the same pair of
/// memberships previously meant either "a deliberate optional-value flag" or "somebody made a
/// mistake", and nothing could tell those apart — which is why the overlap audit was blocked on
/// this. Declaring it here says which one it is, and leaves a raw `standalone`+`valued` overlap
/// free to become a build error once the existing scopes are sorted.
///
/// NOT covered: the short glued form (`-r0`). That reaches the cluster loop, which walks byte by
/// byte and has no notion of "the rest of this token is my value". Recorded in TODO.md.
pub(super) fn build_policy(
    standalone: Vec<String>,
    valued: Vec<String>,
    optional_valued: Vec<String>,
    bare: Option<bool>,
    max_positional: Option<usize>,
    tolerate_unknown_short: Option<bool>,
    tolerate_unknown_long: Option<bool>,
    numeric_dash: Option<bool>,
) -> OwnedPolicy {
    let (mut standalone, mut valued) = (standalone, valued);
    for flag in optional_valued {
        standalone.push(flag.clone());
        valued.push(flag);
    }
    let unknown = match (tolerate_unknown_short.unwrap_or(false), tolerate_unknown_long.unwrap_or(false)) {
        (false, false) => UnknownTolerance::Strict,
        (true, false) => UnknownTolerance::Short,
        (false, true) => UnknownTolerance::Long,
        (true, true) => UnknownTolerance::Both,
    };
    OwnedPolicy {
        standalone,
        valued,
        bare: bare.unwrap_or(true),
        max_positional,
        min_positional: None,
        tolerance: FlagTolerance { unknown, numeric_dash: numeric_dash.unwrap_or(false), ..FlagTolerance::strict() },
        passthrough: None,
    }
}

fn build_matrix(toml: TomlMatrix) -> MatrixSpec {
    let actions = toml
        .actions
        .into_iter()
        .map(|(name, action)| {
            let built = match action {
                TomlMatrixAction::Policy(policy_key) => MatrixAction { policy_key, guard: None, guard_short: None },
                TomlMatrixAction::Detailed(d) => MatrixAction { policy_key: d.policy, guard: d.guard, guard_short: d.guard_short },
            };
            (name, built)
        })
        .collect();
    MatrixSpec { parents: toml.parents, level: toml.level.into(), actions }
}

fn build_handler_policy(toml: TomlHandlerPolicy) -> OwnedPolicy {
    build_policy(
        toml.standalone, toml.valued, toml.optional_valued, toml.bare, toml.max_positional, toml.tolerate_unknown_short,
        toml.tolerate_unknown_long, toml.numeric_dash,
    )
}

fn build_verb_chain(toml: TomlVerbChain) -> VerbChainSpec {
    VerbChainSpec {
        level: toml.level.unwrap_or(TomlLevel::Inert).into(),
        separator: toml.separator.unwrap_or_else(|| "then".to_string()),
        main_standalone: toml.main_standalone,
        main_valued: toml.main_valued,
        main_variadic: toml.main_variadic,
        verbs: toml.verbs.into_iter().collect(),
    }
}

fn build_fallback(parent: &str, toml: TomlFallback) -> Result<FallbackSpec, String> {
    let policy = build_policy(
        toml.standalone, toml.valued, toml.optional_valued, toml.bare, toml.max_positional, toml.tolerate_unknown_short,
        toml.tolerate_unknown_long, toml.numeric_dash,
    );
    let level: SafetyLevel = toml.level.unwrap_or(TomlLevel::Inert).into();
    let positional_shape = crate::policy::PositionalShape::from_toml(toml.positional_shape.as_deref(), &format!("{parent} fallback"))?;
    let executor = match toml.executor.as_deref() {
        None => None,
        Some(name) => match ExecutorKind::from_name(name) {
            Some(kind) => Some(kind),
            None => fail!("{parent}: unknown fallback executor `{name}` (known: file, project)"),
        },
    };
    Ok(FallbackSpec {
        policy,
        level,
        positional_shape,
        executor,
        executor_redirect_flag: toml.executor_redirect_flag,
        passes_argv: toml.passes_argv.unwrap_or(false),
        write_flags: toml.write_flags,
    })
}

fn check_no_legacy_positional_style(name: &str, ps: Option<bool>) -> Result<(), String> {
    if ps.is_some() {
        fail!(
            "command '{name}': `positional_style` was removed. Use \
             `tolerate_unknown_short = true` for tools with single-dash \
             flags (pdftotext -help, sample -mayDie). Use \
             `tolerate_unknown_long = true` ONLY for tools whose \
             double-dash flag surface is genuinely unbounded (AWS CLI \
             style); double-dash unknowns silently pass when this is \
             on, which has caused safety bugs. Most tools need neither."
        );
    }
    Ok(())
}

fn filter_candidates(subs: Vec<TomlSub>) -> Result<impl Iterator<Item = TomlSub>, String> {
    // Asserted HERE, not in `build_subs`, because that is the whole point: a candidate sub is
    // dropped by this filter and never reaches `build_subs`, so a check placed there could never
    // fire for the case it targets. Nested subs a candidate declares are dropped with it, silently:
    // dead data that a reader would take to be in force.
    for s in &subs {
        ensure!(
            !s.candidate.unwrap_or(false) || s.sub.is_empty(),
            "sub `{}`: a `candidate` sub is filtered out, so its nested subs are dead — drop the \
             nested subs, or drop `candidate` if the sub is meant to be live",
            s.name,
        );
    }
    // A `per_database` sub must not be a PREFIX of another declared task, or the two are
    // indistinguishable by shape and the suffix rule swallows the sibling.
    //
    // Rails makes this concrete: `db:migrate:primary` names a database and `db:migrate:redo` names
    // a different task, and nothing in the string says which. Marking `db:migrate` therefore read
    // `redo` as a database name and admitted a destructive task that is deliberately `candidate`.
    // The existing `examples_denied` entry caught it, which is why the check belongs here rather
    // than in a test.
    //
    // Checked in THIS function for the same reason the assert above is: candidates are filtered
    // out below, so a check placed after the filter could not see the very siblings that create
    // the ambiguity — `db:migrate:redo` and `db:migrate:reset` are both candidates.
    for s in &subs {
        if !s.per_database {
            continue;
        }
        let clash = subs.iter().find(|o| o.name.starts_with(&format!("{}:", s.name)));
        ensure!(
            clash.is_none(),
            "sub `{}`: `per_database` is unsound on a task that prefixes another (`{}`) — a \
             suffix cannot be told from a subtask name. Enumerate the variants, or drop the flag",
            s.name,
            clash.map(|c| c.name.as_str()).unwrap_or(""),
        );
    }
    Ok(subs.into_iter().filter(|s| !s.candidate.unwrap_or(false)))
}

/// Whether `name` is matched by a `first_arg` pattern (`get-*` prefix glob, or an exact token).
fn first_arg_matches(name: &str, patterns: &[String]) -> bool {
    patterns.iter().any(|p| match p.strip_suffix('*') {
        Some(prefix) => name.starts_with(prefix),
        None => p == name,
    })
}

/// Fail-closed guard for the `candidate`-under-glob footgun. A `candidate = true` sub is REMOVED from
/// the registry (so an older client sees "not found" and denies) — but if a sibling `first_arg` glob
/// would MATCH that removed name, the token falls through to the glob and AUTO-APPROVES, silently
/// inverting the author's intent (a deny becomes an allow). This panics at load when it detects that
/// shape, directing the author to a `profile`/explicit sub-sub instead. (The AWS blob-readers hit
/// exactly this: a `candidate` under `get-*` would have auto-approved.)
fn assert_no_candidate_shadowed_by_glob(parent: &str, subs: &[TomlSub], first_arg: &[String]) -> Result<(), String> {
    if first_arg.is_empty() {
        return Ok(());
    }
    for s in subs {
        if s.candidate.unwrap_or(false) && first_arg_matches(&s.name, first_arg) {
            fail!(
                "'{parent}' sub `{}` is `candidate = true` but its name is MATCHED by the sibling \
                 first_arg glob {first_arg:?} — it would fall through the filter and AUTO-APPROVE \
                 (a silent deny→allow inversion). Use `profile`/an explicit sub-sub to deny it, or \
                 drop it from the glob.",
                s.name,
            );
        }
    }
    Ok(())
}

pub(super) fn build_sub_kind_unchecked(
    parent: &str,
    toml: TomlSub,
    handler_policies: &std::collections::HashMap<String, OwnedPolicy>,
) -> Result<DispatchKind, String> {
    let policy_free = toml.handler.is_some() || toml.allow_all.is_some() || toml.delegate_after.is_some() || toml.delegate_skip.is_some();
    super::policy::min_positional_fits(parent, &toml, policy_free)?;
    if let Some(handler_name) = toml.handler {
        return Ok(DispatchKind::Custom {
            handler_name,
            doc_body: toml.doc_body,
            subs: Vec::new(),
            fallback: None,
            handler_policies: std::collections::HashMap::new(),
            matrices: Vec::new(),
        });
    }
    if toml.allow_all.unwrap_or(false) {
        return Ok(DispatchKind::Policy {
            policy: OwnedPolicy::allow_all(),
            level: toml.level.unwrap_or(TomlLevel::Inert).into(),
            shape: None,
        });
    }
    if let Some(sep) = toml.delegate_after {
        return Ok(DispatchKind::DelegateAfterSeparator(DelegateAfter::new(sep, toml.standalone, toml.valued)));
    }
    if let Some(skip) = toml.delegate_skip {
        let shape = crate::policy::PositionalShape::from_toml(
            toml.positional_shape.as_deref(),
            &format!("command '{parent}' sub `{}`", toml.name),
        )?;
        if shape.is_some() && skip < 2 {
            fail!("command '{parent}' sub `{}`: positional_shape needs delegate_skip of 2 or more", toml.name);
        }
        return Ok(DispatchKind::DelegateSkip { skip, shape });
    }
    // A `credential_first_arg` gate forces the Branching path even with no sub-subs: only Branching
    // runs `skip_pre_flags`, so the credential check sees the real resource arg (`get -o yaml secret`),
    // not a leading flag — `FirstArg` reads `tokens[1]` verbatim and would be bypassed by a flag.
    if !toml.sub.is_empty() || !toml.credential_first_arg.is_empty() {
        // A sub may carry BOTH explicit sub-subs AND a fallback `first_arg` glob (a service that
        // auto-approves its read verbs via `get-*`/`describe-*` but carves specific dangerous actions
        // out to profiled sub-subs). Dispatch checks the explicit subs FIRST, then the glob
        // (dispatch.rs), so the carve-outs escalate while the benign reads still glob-match. Mirror
        // the command-level Branching, which already threads `first_arg` through; the sub level used
        // to hard-drop it (`Vec::new()`), which made "glob + carve-out" inexpressible.
        let first_arg_level = toml.level.unwrap_or(TomlLevel::Inert).into();
        return Ok(DispatchKind::Branching {
            subs: filter_candidates(toml.sub)?
                .map(|s| build_subs(parent, s, handler_policies))
                .collect::<Result<Vec<_>, _>>()?
                .into_iter()
                .flatten()
                .collect(),
            bare_flags: Vec::new(),
            bare_ok: toml.nested_bare.unwrap_or(false),
            pre_standalone: toml.standalone,
            pre_valued: toml.valued,
            first_arg: toml.first_arg,
            first_arg_level,
            first_arg_standalone: toml.first_arg_standalone,
            first_arg_valued: toml.first_arg_valued,
            first_arg_loopback_valued: toml.first_arg_loopback_valued,
            credential_first_arg: toml.credential_first_arg,
            // A nested sub level; the selector is only ever leading, so it belongs to the command.
            toolchain_selector: false,
        });
    }
    build_policy_sub_kind(parent, toml, handler_policies)
}

fn build_policy_sub_kind(
    parent: &str,
    toml: TomlSub,
    handler_policies: &std::collections::HashMap<String, OwnedPolicy>,
) -> Result<DispatchKind, String> {
    let shape = sub_shape(parent, &toml)?;
    let mut policy = if let Some(key) = &toml.policy {
        if !toml.standalone.is_empty() || !toml.valued.is_empty() {
            fail!(
                "command '{parent}' sub `{}` sets both `policy = \"{}\"` and \
                 inline standalone/valued — pick one. Either drop the inline \
                 lists (and rely on the referenced handler_policy) or drop \
                 the `policy` field.",
                toml.name,
                key,
            );
        }
        match handler_policies.get(key).cloned() {
            Some(p) => p,
            None => fail!(
                "command '{parent}' sub `{}` references handler_policy \
                 `{key}` which is not declared. Add a \
                 [command.handler_policy.{key}] block or fix the typo.",
                toml.name,
            ),
        }
    } else {
        build_policy(
            toml.standalone, toml.valued, toml.optional_valued, toml.bare, toml.max_positional, toml.tolerate_unknown_short,
            toml.tolerate_unknown_long, toml.numeric_dash,
        )
    };
    policy.min_positional = toml.min_positional;
    policy.passthrough = toml.passthrough.map(super::policy::build_passthrough);
    let level: SafetyLevel = toml.level.unwrap_or(TomlLevel::Inert).into();
    if let Some(name) = toml.executor.as_deref() {
        let Some(kind) = ExecutorKind::from_name(name) else {
            fail!("command '{parent}' sub `{}`: unknown executor `{name}` (known: file, project)", toml.name)
        };
        return Ok(DispatchKind::Executor {
            policy,
            level,
            kind,
            redirect_flag: toml.executor_redirect_flag,
            shape,
            passes_argv: toml.passes_argv.unwrap_or(false),
        });
    }
    if !toml.write_flags.is_empty() {
        return Ok(DispatchKind::WriteFlagged { policy, base_level: level, write_flags: toml.write_flags });
    }
    if let Some(guard) = toml.guard {
        let mut require_any = vec![guard];
        if let Some(short) = toml.guard_short {
            require_any.push(short);
        }
        return Ok(DispatchKind::RequireAny { require_any, policy, level, accept_bare_help: true });
    }
    if !toml.first_arg.is_empty() {
        return Ok(DispatchKind::FirstArg {
            patterns: toml.first_arg,
            level,
            standalone: toml.first_arg_standalone,
            valued: toml.first_arg_valued,
            loopback_valued: toml.first_arg_loopback_valued,
        });
    }
    if !toml.require_any.is_empty() {
        return Ok(DispatchKind::RequireAny { require_any: toml.require_any, policy, level, accept_bare_help: false });
    }
    Ok(DispatchKind::Policy { policy, level, shape })
}

/// Diagnostic for a configuration class that silently breaks flag dispatch:
/// a structured command (with `[[command.sub]]` blocks) cannot also use the
/// flat-style top-level fields. When subs are present, top-level standalone/
/// valued/max_positional/positional_style/numeric_dash are dropped — the
/// dispatch routes through the Branching path. The fix is to either remove
/// the subs (if the command is meant to be flat) or move global flags into
/// a `[command.wrapper]` block.
fn assert_flat_or_structured(toml: &TomlCommand) -> Result<(), String> {
    if toml.sub.is_empty() {
        return Ok(());
    }
    let set = [
        ("standalone", !toml.standalone.is_empty()),
        ("valued", !toml.valued.is_empty()),
        ("max_positional", toml.max_positional.is_some()),
        ("tolerate_unknown_short", toml.tolerate_unknown_short.is_some()),
        ("tolerate_unknown_long", toml.tolerate_unknown_long.is_some()),
        ("numeric_dash", toml.numeric_dash.is_some()),
        ("single_dash_words", toml.single_dash_words.is_some()),
        ("reads_commands_from", !toml.reads_commands_from.is_empty()),
    ];
    let conflicts: Vec<&str> = set.iter().filter(|(_, present)| *present).map(|(name, _)| *name).collect();
    if !conflicts.is_empty() {
        fail!(
            "command '{}' mixes flat-style top-level fields ({}) with [[command.sub]] blocks. \
             When subs are present these fields are silently dropped. \
             Either drop the subs (if the command is flat) or move global \
             flags into a [command.wrapper] block.",
            toml.name,
            conflicts.join(", "),
        );
    }
    Ok(())
}

fn assert_matrix_policy_keys_exist(toml: &TomlCommand) -> Result<(), String> {
    if toml.matrix.is_empty() {
        return Ok(());
    }
    for matrix in &toml.matrix {
        for (action_name, action) in &matrix.actions {
            let policy_key = match action {
                TomlMatrixAction::Policy(k) => k,
                TomlMatrixAction::Detailed(d) => &d.policy,
            };
            if !toml.handler_policy.contains_key(policy_key) {
                fail!(
                    "command '{}' matrix action `{}` references \
                     handler_policy `{}` which is not declared. \
                     Add a [command.handler_policy.{}] block or fix the typo.",
                    toml.name,
                    action_name,
                    policy_key,
                    policy_key,
                );
            }
        }
    }
    Ok(())
}

fn assert_matrix_no_duplicate_parent_action(toml: &TomlCommand) -> Result<(), String> {
    if toml.matrix.len() < 2 {
        return Ok(());
    }
    let mut seen: std::collections::HashSet<(String, String)> = std::collections::HashSet::new();
    for matrix in &toml.matrix {
        for parent in &matrix.parents {
            for action in matrix.actions.keys() {
                let key = (parent.clone(), action.clone());
                if !seen.insert(key) {
                    fail!(
                        "command '{}' matrix has duplicate (parent, action) pair \
                         (`{}`, `{}`). The first match would silently win — \
                         consolidate into one matrix block or remove the duplicate.",
                        toml.name,
                        parent,
                        action,
                    );
                }
            }
        }
    }
    Ok(())
}

fn assert_fallback_requires_handler(toml: &TomlCommand) -> Result<(), String> {
    if toml.fallback.is_some() && toml.handler.is_none() {
        fail!(
            "command '{}' declares [command.fallback] without a handler. \
             Fallback grammars are only consulted via \
             registry::try_fallback_grammar() from a Rust handler — without \
             handler = \"...\" the block is silently dropped. \
             Either set handler or remove [command.fallback].",
            toml.name,
        );
    }
    Ok(())
}

#[allow(clippy::too_many_lines)]
pub(super) fn build_command(toml: TomlCommand, category: &str) -> Result<CommandSpec, String> {
    assert_flat_or_structured(&toml)?;
    assert_fallback_requires_handler(&toml)?;
    assert_matrix_policy_keys_exist(&toml)?;
    assert_no_candidate_shadowed_by_glob(&toml.name, &toml.sub, &toml.first_arg)?;
    assert_matrix_no_duplicate_parent_action(&toml)?;
    assert_command_eval_safe_only_on_leaf(&toml)?;
    assert_eval_safe_tagged_command_has_researched_version(&toml)?;
    check_no_legacy_positional_style(&toml.name, toml.positional_style)?;
    let cat = category.to_string();
    let desc = toml.description.unwrap_or_default();
    let researched_version = toml.researched_version;
    let examples_safe = toml.examples_safe;
    let examples_denied = toml.examples_denied;
    let eval_safe = toml.eval_safe.unwrap_or(false);
    let eval_safe_flags = toml.eval_safe_flags;
    let eval_safe_flag_values = toml.eval_safe_flag_values;
    let eval_safe_required_flags = toml.eval_safe_required_flags;
    if !eval_safe_flags.is_empty() && !eval_safe {
        fail!(
            "command '{}' declares `eval_safe_flags` without `eval_safe = true`. \
             The flag allowlist only takes effect when the command is tagged \
             eval-safe. Add `eval_safe = true` or drop `eval_safe_flags`.",
            toml.name,
        );
    }
    assert_eval_safe_flag_values_consistent(&toml.name, "<command>", &eval_safe_flags, &eval_safe_flag_values)?;
    assert_eval_safe_valued_flags_declared(&toml.name, "<command>", &eval_safe_flags, &toml.valued, &eval_safe_flag_values)?;
    assert_eval_safe_required_flags_consistent(&toml.name, "<command>", &eval_safe_flags, &eval_safe_required_flags)?;
    let behavior = lower_behavior(&toml.name, toml.behavior.as_ref())?;
    let output = lower_output(&toml.name, toml.output.as_ref())?;
    let writes_cwd = super::cwd_writes::lower(&toml.name, "<command>", toml.writes_cwd.as_deref(), &toml.output_dirs, None)?;
    let line_checks = LineChecks::lower(&toml.name, &toml.flag_value_shapes)?;
    let hooks = SpecHooks::lower(toml.env_assignment_positionals, toml.ghc_rts);
    let archetype_flags = archetype_flags::lower(&toml.name, toml.flag, &toml.flag_valued, &toml.valued, toml.wrapper.as_ref())?;
    if toml.deny.unwrap_or(false) {
        return Ok(CommandSpec {
            name: toml.name,
            description: desc,
            aliases: toml.aliases,
            url: toml.url,
            category: cat,
            researched_version,
            examples_safe,
            examples_denied,
            eval_safe,
            eval_safe_flags: eval_safe_flags.clone(),
            eval_safe_flag_values: eval_safe_flag_values.clone(),
            eval_safe_required_flags: eval_safe_required_flags.clone(),
            path_gate: toml.path_gate,
            archetype_flags: archetype_flags.clone(),
            behavior: behavior.clone(),
            output,
            writes_cwd,
            line_checks: line_checks.clone(),
            hooks,
            kind: DispatchKind::Policy { policy: OwnedPolicy::deny_all(), level: SafetyLevel::Inert, shape: None },
        });
    }
    if let Some(vc) = toml.verb_chain {
        return Ok(CommandSpec {
            name: toml.name,
            description: desc,
            aliases: toml.aliases,
            url: toml.url,
            category: cat,
            researched_version,
            examples_safe,
            examples_denied,
            eval_safe,
            eval_safe_flags: eval_safe_flags.clone(),
            eval_safe_flag_values: eval_safe_flag_values.clone(),
            eval_safe_required_flags: eval_safe_required_flags.clone(),
            path_gate: toml.path_gate,
            archetype_flags: archetype_flags.clone(),
            behavior: behavior.clone(),
            output,
            writes_cwd,
            line_checks: line_checks.clone(),
            hooks,
            kind: DispatchKind::VerbChain(build_verb_chain(vc)),
        });
    }

    if let Some(handler_name) = toml.handler {
        // Build handler_policies first so subs that use `policy = "key"`
        // can resolve the reference at build time.
        let handler_policies: std::collections::HashMap<String, OwnedPolicy> =
            toml.handler_policy.into_iter().map(|(k, v)| (k, build_handler_policy(v))).collect();
        let parent_name = toml.name.clone();
        let subs: Vec<SubSpec> = filter_candidates(toml.sub)?
            .map(|s| build_subs(&parent_name, s, &handler_policies))
            .collect::<Result<Vec<_>, _>>()?
            .into_iter()
            .flatten()
            .collect();
        let fallback = toml.fallback.map(|f| build_fallback(&toml.name, f)).transpose()?;
        let matrices = toml.matrix.into_iter().map(build_matrix).collect();
        return Ok(CommandSpec {
            name: toml.name,
            description: desc,
            aliases: toml.aliases,
            url: toml.url,
            category: cat,
            researched_version,
            examples_safe,
            examples_denied,
            eval_safe,
            eval_safe_flags: eval_safe_flags.clone(),
            eval_safe_flag_values: eval_safe_flag_values.clone(),
            eval_safe_required_flags: eval_safe_required_flags.clone(),
            path_gate: toml.path_gate,
            archetype_flags: archetype_flags.clone(),
            behavior: behavior.clone(),
            output,
            writes_cwd,
            line_checks: line_checks.clone(),
            hooks,
            kind: DispatchKind::Custom { handler_name, doc_body: toml.doc_body, subs, fallback, handler_policies, matrices },
        });
    }

    if let Some(w) = toml.wrapper {
        if !toml.sub.is_empty() || !toml.bare_flags.is_empty() {
            let first_arg_level = toml.level.unwrap_or(TomlLevel::Inert).into();
            let parent_name = toml.name.clone();
            return Ok(CommandSpec {
                name: toml.name,
                description: desc,
                aliases: toml.aliases,
                url: toml.url,
                category: cat,
                researched_version,
                examples_safe,
                examples_denied,
                eval_safe,
                eval_safe_flags: eval_safe_flags.clone(),
                eval_safe_flag_values: eval_safe_flag_values.clone(),
                eval_safe_required_flags: eval_safe_required_flags.clone(),
                path_gate: toml.path_gate,
                archetype_flags: archetype_flags.clone(),
                behavior: behavior.clone(),
                output,
                writes_cwd,
                line_checks: line_checks.clone(),
                hooks,
                kind: DispatchKind::Branching {
                    bare_flags: toml.bare_flags,
                    subs: filter_candidates(super::glob_flags::with_wrapper_flags(toml.sub, &w.standalone, &w.valued))?
                        .map(|s| build_subs(&parent_name, s, &std::collections::HashMap::new()))
                        .collect::<Result<Vec<_>, _>>()?
                        .into_iter()
                        .flatten()
                        .collect(),
                    pre_standalone: w.standalone,
                    pre_valued: w.valued,
                    bare_ok: toml.bare.unwrap_or(false),
                    first_arg: toml.first_arg,
                    first_arg_standalone: toml.first_arg_standalone,
                    first_arg_valued: toml.first_arg_valued,
                    first_arg_loopback_valued: toml.first_arg_loopback_valued,
                    first_arg_level,
                    credential_first_arg: toml.credential_first_arg,
                    toolchain_selector: w.toolchain_selector.unwrap_or(false),
                },
            });
        }
        return Ok(CommandSpec {
            name: toml.name,
            description: desc,
            aliases: toml.aliases,
            url: toml.url,
            category: cat,
            researched_version,
            examples_safe,
            examples_denied,
            eval_safe,
            eval_safe_flags: eval_safe_flags.clone(),
            eval_safe_flag_values: eval_safe_flag_values.clone(),
            eval_safe_required_flags: eval_safe_required_flags.clone(),
            path_gate: toml.path_gate,
            archetype_flags: archetype_flags.clone(),
            behavior: behavior.clone(),
            output,
            writes_cwd,
            line_checks: line_checks.clone(),
            hooks,
            kind: DispatchKind::Wrapper {
                standalone: w.standalone,
                valued: w.valued,
                positional_skip: w.positional_skip.unwrap_or(0),
                separator: w.separator,
                bare_ok: w.bare_ok.unwrap_or(false),
            },
        });
    }

    if !toml.sub.is_empty() || !toml.bare_flags.is_empty() {
        let first_arg_level = toml.level.unwrap_or(TomlLevel::Inert).into();
        let parent_name = toml.name.clone();
        return Ok(CommandSpec {
            name: toml.name,
            description: desc,
            aliases: toml.aliases,
            url: toml.url,
            category: cat,
            researched_version,
            examples_safe,
            examples_denied,
            eval_safe,
            eval_safe_flags: eval_safe_flags.clone(),
            eval_safe_flag_values: eval_safe_flag_values.clone(),
            eval_safe_required_flags: eval_safe_required_flags.clone(),
            path_gate: toml.path_gate,
            archetype_flags: archetype_flags.clone(),
            behavior: behavior.clone(),
            output,
            writes_cwd,
            line_checks: line_checks.clone(),
            hooks,
            kind: DispatchKind::Branching {
                bare_flags: toml.bare_flags,
                subs: filter_candidates(toml.sub)?
                    .map(|s| build_subs(&parent_name, s, &std::collections::HashMap::new()))
                    .collect::<Result<Vec<_>, _>>()?
                    .into_iter()
                    .flatten()
                    .collect(),
                pre_standalone: Vec::new(),
                pre_valued: Vec::new(),
                bare_ok: toml.bare.unwrap_or(false),
                first_arg: toml.first_arg,
                first_arg_level,
                first_arg_standalone: toml.first_arg_standalone,
                first_arg_valued: toml.first_arg_valued,
                first_arg_loopback_valued: toml.first_arg_loopback_valued,
                credential_first_arg: toml.credential_first_arg,
                // Declared on `[command.wrapper]`, which this arm is the no-wrapper case of.
                toolchain_selector: false,
            },
        });
    }

    let mut policy = build_policy(
        toml.standalone, toml.valued, toml.optional_valued, toml.bare, toml.max_positional, toml.tolerate_unknown_short,
        toml.tolerate_unknown_long, toml.numeric_dash,
    );
    policy.tolerance.single_dash_words = toml.single_dash_words.unwrap_or(false);
    super::policy::reads_commands_from(&mut policy.tolerance, &toml.name, &toml.reads_commands_from)?;

    let level = toml.level.unwrap_or(TomlLevel::Inert).into();

    if !toml.first_arg.is_empty() {
        return Ok(CommandSpec {
            name: toml.name,
            description: desc,
            aliases: toml.aliases,
            url: toml.url,
            category: cat,
            researched_version,
            examples_safe,
            examples_denied,
            eval_safe,
            eval_safe_flags: eval_safe_flags.clone(),
            eval_safe_flag_values: eval_safe_flag_values.clone(),
            eval_safe_required_flags: eval_safe_required_flags.clone(),
            path_gate: toml.path_gate,
            archetype_flags: archetype_flags.clone(),
            behavior: behavior.clone(),
            output,
            writes_cwd,
            line_checks: line_checks.clone(),
            hooks,
            kind: DispatchKind::FirstArg {
                patterns: toml.first_arg,
                level,
                standalone: toml.first_arg_standalone,
                valued: toml.first_arg_valued,
                loopback_valued: toml.first_arg_loopback_valued,
            },
        });
    }

    if !toml.write_flags.is_empty() {
        return Ok(CommandSpec {
            name: toml.name,
            description: desc,
            aliases: toml.aliases,
            url: toml.url,
            category: cat,
            researched_version,
            examples_safe,
            examples_denied,
            eval_safe,
            eval_safe_flags: eval_safe_flags.clone(),
            eval_safe_flag_values: eval_safe_flag_values.clone(),
            eval_safe_required_flags: eval_safe_required_flags.clone(),
            path_gate: toml.path_gate,
            archetype_flags: archetype_flags.clone(),
            behavior: behavior.clone(),
            output,
            writes_cwd,
            line_checks: line_checks.clone(),
            hooks,
            kind: DispatchKind::WriteFlagged { policy, base_level: level, write_flags: toml.write_flags },
        });
    }

    if !toml.require_any.is_empty() {
        return Ok(CommandSpec {
            name: toml.name,
            description: desc,
            aliases: toml.aliases,
            url: toml.url,
            category: cat,
            researched_version,
            examples_safe,
            examples_denied,
            eval_safe,
            eval_safe_flags: eval_safe_flags.clone(),
            eval_safe_flag_values: eval_safe_flag_values.clone(),
            eval_safe_required_flags: eval_safe_required_flags.clone(),
            path_gate: toml.path_gate,
            archetype_flags: archetype_flags.clone(),
            behavior: behavior.clone(),
            output,
            writes_cwd,
            line_checks: line_checks.clone(),
            hooks,
            kind: DispatchKind::RequireAny { require_any: toml.require_any, policy, level, accept_bare_help: false },
        });
    }

    Ok(CommandSpec {
        line_checks: line_checks.clone(),
        hooks,
        name: toml.name,
        description: desc,
        aliases: toml.aliases,
        url: toml.url,
        category: cat,
        researched_version,
        examples_safe,
        examples_denied,
        eval_safe,
        eval_safe_flags,
        eval_safe_flag_values,
        eval_safe_required_flags,
        path_gate: toml.path_gate,
        archetype_flags,
        behavior,
        output,
        writes_cwd,
        kind: DispatchKind::Policy { policy, level, shape: None },
    })
}

/// Build every command definition in `source`, or the first reason one is invalid.
///
/// Returns `Err` rather than panicking because this reads USER files too — see the `fail!` macro at
/// the top of this module. The built-in `commands/*.toml` are compiled in and unwrap the result at
/// their call site, so a broken definition in this repository still stops the process loudly.
pub fn load_toml(source: &str, category: &str) -> Result<Vec<CommandSpec>, String> {
    let file: TomlFile = match toml::from_str(source) {
        Ok(f) => f,
        Err(e) => {
            let preview: String = source.chars().take(80).collect();
            fail!("invalid TOML command definition: {e}\n  source begins: {preview}");
        }
    };
    file.command
        .into_iter()
        .filter(|cmd| !cmd.candidate.unwrap_or(false))
        .map(|cmd| build_command(cmd, category))
        .collect()
}

pub fn build_registry(specs: Vec<CommandSpec>) -> HashMap<String, CommandSpec> {
    let mut map = HashMap::new();
    for spec in specs {
        insert_spec(&mut map, spec);
    }
    map
}

/// Insert a CommandSpec into the registry, registering both its canonical
/// name and each alias. Existing entries for the same command name are
/// removed first, so a custom-TOML override of `gh` replaces every
/// built-in alias of `gh` rather than leaving stale aliases pointing at
/// the old spec.
pub fn insert_spec(map: &mut HashMap<String, CommandSpec>, spec: CommandSpec) {
    map.retain(|_, s| s.name != spec.name);
    for alias in &spec.aliases {
        map.insert(
            alias.clone(),
            CommandSpec {
                // Carried, not defaulted: `typeset` is an alias of `declare`, and dropping this here
                // would let the alias put a variable into the environment unclassified while the
                // canonical spelling denied.
                line_checks: spec.line_checks.clone(),
                hooks: spec.hooks,
                name: spec.name.clone(),
                description: spec.description.clone(),
                aliases: vec![],
                url: spec.url.clone(),
                category: spec.category.clone(),
                researched_version: spec.researched_version.clone(),
                examples_safe: vec![],
                examples_denied: vec![],
                eval_safe: spec.eval_safe,
                eval_safe_flags: spec.eval_safe_flags.clone(),
                eval_safe_flag_values: spec.eval_safe_flag_values.clone(),
                eval_safe_required_flags: spec.eval_safe_required_flags.clone(),
                // Aliases are canonicalized (`registry::canonical_name`) before `should_deny` and
                // before the engine's behavior lookup, so the canonical spec's `path_gate` /
                // `behavior` is what's consulted — the alias entry never needs either.
                path_gate: None,
                archetype_flags: ArchetypeFlags::default(),
                behavior: None,
                output: None,
                writes_cwd: None,
                kind: spec.kind.clone(),
            },
        );
    }
    map.insert(spec.name.clone(), spec);
}

#[cfg(test)]
mod tests {
    use super::*;
    use proptest::prelude::*;

    /// `single_dash_words` is read only on the flat path, so on a structured command it would
    /// silently leave every sub clustering its single-dash words.
    #[test]
    fn single_dash_words_on_a_structured_command_is_rejected() {
        crate::registry::tests::assert_rejected(
            "[[command]]\nname = \"tc\"\nsingle_dash_words = true\n[[command.sub]]\nname = \"ls\"\n",
            "single_dash_words",
        );
    }

    #[test]
    fn reads_commands_from_is_flat_only_and_names_known_sources() {
        crate::registry::tests::assert_rejected(
            "[[command]]\nname = \"tc\"\nreads_commands_from = [\"plus\"]\n[[command.sub]]\nname = \"ls\"\n",
            "reads_commands_from",
        );
        crate::registry::tests::assert_rejected("[[command]]\nname = \"tc\"\nreads_commands_from = [\"argv\"]\n", "argv");
    }

    /// Strategies for built-policy inputs. `flag_name` keeps test strings small and distinct
    /// enough that overlap between `standalone`/`valued` is rare; the policy builder does not
    /// dedup, so properties that compare counts must tolerate the duplicates the generator
    /// produces naturally.
    fn flag_name() -> impl Strategy<Value = String> {
        "[a-zA-Z][a-zA-Z0-9_-]{0,8}".prop_map(String::from)
    }

    fn opt_bool() -> impl Strategy<Value = Option<bool>> {
        proptest::option::of(any::<bool>())
    }

    /// Pure-reference `first_arg_matches`: same branch table the function uses, expressed once
    /// here so a property can compare the function against an oracle. Proptest keeps both
    /// implementations out of the main code path so a future refactor (e.g. migrating the
    /// glob mechanism to `regex`) can be checked against the prior contract.
    fn oracle_first_arg_matches(name: &str, patterns: &[String]) -> bool {
        patterns.iter().any(|p| match p.strip_suffix('*') {
            Some(prefix) => name.starts_with(prefix),
            None => p == name,
        })
    }

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(256))]

        /// INVARIANT (`build_policy` optional-valued mechanism). The whole point of the
        /// `optional_valued` list — see the docstring on `build_policy` — is that each entry
        /// lands in BOTH the `standalone` and the `valued` allowlist, so the rest of the walk
        /// can use one canonical "did the user declare this flag?" test. This property pins
        /// that contract: for every generated set of inputs, the count of each
        /// `optional_valued` flag in the output lists is the original count plus however
        /// many times the flag was also declared in `optional_valued`. The originals are
        /// preserved at the front (the function appends, it does not rebuild), and the
        /// append fires once per `optional_valued` occurrence — duplicates in the input
        /// propagate, which matters for the overlap audit in `check_flags`. A regression
        /// that folded the two push-loops into one, or that dropped the append for one list
        /// only, would break one direction while keeping the other, and the asymmetry is
        /// what this property catches.
        #[test]
        fn build_policy_optional_valued_mechanism_appends_to_both_lists(
            standalone in proptest::collection::vec(flag_name(), 0..5),
            valued in proptest::collection::vec(flag_name(), 0..5),
            optional_valued in proptest::collection::vec(flag_name(), 0..5),
            bare in opt_bool(),
            max_positional in proptest::option::of(any::<usize>()),
            tolerate_unknown_short in opt_bool(),
            tolerate_unknown_long in opt_bool(),
            numeric_dash in opt_bool(),
        ) {
            let p = build_policy(
                standalone.clone(),
                valued.clone(),
                optional_valued.clone(),
                bare,
                max_positional,
                tolerate_unknown_short,
                tolerate_unknown_long,
                numeric_dash,
            );
            // The set of unique `optional_valued` entries — covers the union of every flag
            // appended in this test, including any duplicates the generator happened to
            // produce (which the function faithfully copies through).
            let unique: std::collections::BTreeSet<String> =
                optional_valued.iter().cloned().collect();
            for flag in &unique {
                let sa = p.standalone.iter().filter(|f| f.as_str() == flag.as_str()).count();
                let va = p.valued.iter().filter(|f| f.as_str() == flag.as_str()).count();
                let s_orig = standalone.iter().filter(|f| f.as_str() == flag.as_str()).count();
                let v_orig = valued.iter().filter(|f| f.as_str() == flag.as_str()).count();
                let s_ov = optional_valued.iter().filter(|f| f.as_str() == flag.as_str()).count();
                prop_assert_eq!(
                    sa,
                    s_orig + s_ov,
                    "optional_valued entry {} ended up {} times in standalone (expected originals {} + ov {})",
                    flag, sa, s_orig, s_ov,
                );
                prop_assert_eq!(
                    va,
                    v_orig + s_ov,
                    "optional_valued entry {} ended up {} times in valued (expected originals {} + ov {})",
                    flag, va, v_orig, s_ov,
                );
            }
            // The pre-existing lists are kept verbatim — `optional_valued` is *appended*, not
            // used to rebuild the lists from scratch.
            prop_assert!(
                p.standalone.starts_with(&standalone),
                "standalone prefix not preserved: {:?}", p.standalone,
            );
            prop_assert!(
                p.valued.starts_with(&valued),
                "valued prefix not preserved: {:?}", p.valued,
            );
        }

        /// INVARIANT (`build_policy` unknown tolerance). The 2x2 (short, long) boolean
        /// combination must map to the matching `UnknownTolerance` variant — the four-way
        /// truth table the function documents. A regression that dropped one arm or wired
        /// the booleans to the wrong variants (e.g. swapped Short and Long) would land here
        /// on exactly those inputs and nowhere else, since this is the only place those
        /// four values are produced.
        #[test]
        fn build_policy_unknown_tolerance_tracks_the_boolean_pair(
            short in any::<bool>(),
            long in any::<bool>(),
        ) {
            let p = build_policy(
                Vec::new(),
                Vec::new(),
                Vec::new(),
                Some(true),
                None,
                Some(short),
                Some(long),
                None,
            );
            let expected = match (short, long) {
                (false, false) => UnknownTolerance::Strict,
                (true, false) => UnknownTolerance::Short,
                (false, true) => UnknownTolerance::Long,
                (true, true) => UnknownTolerance::Both,
            };
            prop_assert_eq!(p.tolerance.unknown, expected);
        }

        /// INVARIANT / differential (oracle). `first_arg_matches` is a four-line branch over
        /// each pattern, and the pattern language is small enough to spell out a reference
        /// implementation that has no other behavior. This property pins the function to
        /// the reference for every generated (name, patterns) pair so a future refactor —
        /// switching to `regex`, anchoring the prefix, or skipping empty patterns — has to
        /// keep the documented outcomes identical, not just "panics less than before".
        #[test]
        fn first_arg_matches_agrees_with_a_simple_reference(
            name in "[a-zA-Z0-9][a-zA-Z0-9._:-]{0,12}",
            patterns in proptest::collection::vec(
                "(-\\*|[a-zA-Z][a-zA-Z0-9._:-]{0,8}(\\*)?)",
                0..6,
            ),
        ) {
            let patterns: Vec<String> = patterns;
            prop_assert_eq!(
                first_arg_matches(&name, &patterns),
                oracle_first_arg_matches(&name, &patterns),
            );
        }

        /// MONOTONICITY (`first_arg_matches`). The function tests `any` over the pattern
        /// list, so adding a matching pattern can never turn a hit into a miss — the
        /// property holds for a synthetic name (forced not to match any base pattern) and a
        /// single `*`-suffixed pattern whose prefix the name starts with. A regression that
        /// replaced `any` with `all`, or that re-applied the loop on each pattern's match
        /// to update some shared state, would break the monotonicity direction on the second
        /// assertion: matches on a pattern that was already a miss would need a flip, and
        /// that's exactly the failure mode the property isolates.
        #[test]
        fn first_arg_matches_is_monotone_in_adding_a_matching_pattern(
            base in proptest::collection::vec(
                "[a-zA-Z][a-zA-Z0-9._:-]{0,8}",
                0..4,
            ),
            prefix in "[a-zA-Z][a-zA-Z0-9._:-]{0,4}",
            tail in "[a-zA-Z0-9._:-]{1,6}",
        ) {
            let name = format!("{}{}", prefix, tail);
            // The base patterns do NOT match `name` (no pattern starts with `prefix*`, and
            // none equals `name`). The added pattern `prefix*` does.
            prop_assume!(!base.iter().any(|p| p == &name
                || (p.ends_with('*') && name.starts_with(&p[..p.len() - 1]))));

            let before = first_arg_matches(&name, &base);
            let mut extended = base.clone();
            extended.push(format!("{}*", prefix));
            let after = first_arg_matches(&name, &extended);
            prop_assert!(!before, "base should not match: base={:?} name={}", base, name);
            prop_assert!(after, "adding matching pattern should have flipped to true");
        }
    }
}