safe-chains 0.243.0

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
use crate::parse::Token;
use crate::policy::{FlagSet, FlagTolerance, UnknownTolerance, check_flags, consumes_next_value, count_positionals, takes_next_word};
use crate::verdict::{SafetyLevel, Verdict};

use super::types::{DispatchKind, PassthroughSpec, TomlLevel, TomlPassthrough};

#[derive(Debug, Clone)]
pub struct OwnedPolicy {
    pub standalone: Vec<String>,
    pub valued: Vec<String>,
    pub bare: bool,
    pub max_positional: Option<usize>,
    pub min_positional: Option<usize>,
    pub tolerance: FlagTolerance,
    pub passthrough: Option<Box<PassthroughSpec>>,
}

impl OwnedPolicy {
    pub(super) fn allow_all() -> Self {
        OwnedPolicy {
            standalone: Vec::new(),
            valued: Vec::new(),
            bare: true,
            max_positional: None,
            min_positional: None,
            tolerance: FlagTolerance { unknown: UnknownTolerance::Both, ..FlagTolerance::strict() },
            passthrough: None,
        }
    }

    pub(super) fn deny_all() -> Self {
        OwnedPolicy {
            standalone: Vec::new(),
            valued: Vec::new(),
            bare: false,
            max_positional: Some(0),
            min_positional: None,
            tolerance: FlagTolerance::default(),
            passthrough: None,
        }
    }
}

/// Whether the command's policy lists `flag` as standalone in any of its scopes, so the flag takes
/// a value only glued or after `=`. The path gate consumes the next word by the same rule the
/// policy walker does (`policy::takes_next_word`). `cmd` is already canonicalized by the caller.
pub(crate) fn declares_standalone(cmd: &str, flag: &str) -> bool {
    super::CUSTOM_REGISTRY
        .get(cmd)
        .or_else(|| super::TOML_REGISTRY.get(cmd))
        .is_some_and(|spec| spec.kind.declares_standalone(flag))
}

impl DispatchKind {
    /// Whether any scope of this command lists `flag` as standalone.
    pub(super) fn declares_standalone(&self, flag: &str) -> bool {
        let lists = |flags: &[String]| flags.iter().any(|f| f == flag);
        match self {
            DispatchKind::Policy { policy, .. }
            | DispatchKind::RequireAny { policy, .. }
            | DispatchKind::WriteFlagged { policy, .. }
            | DispatchKind::Executor { policy, .. } => lists(&policy.standalone),
            DispatchKind::FirstArg { standalone, .. } | DispatchKind::Wrapper { standalone, .. } => lists(standalone),
            DispatchKind::Branching { pre_standalone, subs, .. } => {
                lists(pre_standalone) || subs.iter().any(|sub| sub.kind.declares_standalone(flag))
            }
            DispatchKind::VerbChain(spec) => lists(&spec.main_standalone),
            DispatchKind::Custom { subs, handler_policies, .. } => {
                subs.iter().any(|sub| sub.kind.declares_standalone(flag))
                    || handler_policies.values().any(|policy| lists(&policy.standalone))
            }
            DispatchKind::DelegateAfterSeparator(_) | DispatchKind::DelegateSkip { .. } => false,
        }
    }
}

pub(super) fn build_passthrough(toml: TomlPassthrough) -> Box<PassthroughSpec> {
    let policy = super::build::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 mut require_any = toml.require_any;
    if let Some(guard) = toml.guard {
        require_any.push(guard);
    }
    if let Some(short) = toml.guard_short {
        require_any.push(short);
    }
    let level: SafetyLevel = toml.level.unwrap_or(TomlLevel::Inert).into();
    Box::new(PassthroughSpec { policy, require_any, level })
}

fn has_unvalued_flag(tokens: &[Token], policy: &OwnedPolicy) -> bool {
    let (standalone, valued) = (policy.standalone.as_slice(), policy.valued.as_slice());
    for (i, token) in tokens.iter().enumerate().skip(1) {
        let t = token.as_str();
        if !t.starts_with('-') {
            continue;
        }
        if takes_next_word(standalone, valued, t) {
            if !consumes_next_value(tokens.get(i + 1)) {
                return true;
            }
            continue;
        }
        if !policy.tolerance.single_dash_words {
            let bytes = t.as_bytes();
            for (j, &b) in bytes.iter().enumerate().skip(1) {
                if standalone.contains_short(b) {
                    continue;
                }
                if valued.contains_short(b) {
                    if j + 1 == bytes.len() && !consumes_next_value(tokens.get(i + 1)) {
                        return true;
                    }
                    break;
                }
                break;
            }
        }
    }
    false
}

pub(super) fn check_with_passthrough(tokens: &[Token], policy: &OwnedPolicy, base_level: SafetyLevel) -> Verdict {
    if let Some(pass) = &policy.passthrough
        && let Some(rel) = tokens[1..].iter().position(|t| t == "--")
    {
        let sep = rel + 1;
        let prefix = &tokens[..sep];
        let tail = &tokens[sep..];
        if !check_owned(prefix, policy)
            || has_unvalued_flag(prefix, policy)
            || tail[1..].iter().any(|t| t == "--")
            || !check_owned(tail, &pass.policy)
            || has_unvalued_flag(tail, &pass.policy)
        {
            return Verdict::Denied;
        }
        let guarded = pass.require_any.is_empty()
            || flag_given(tail, &pass.policy, &pass.require_any)
            || flag_given(prefix, policy, &pass.require_any);
        return if guarded { Verdict::Allowed(pass.level) } else { Verdict::Denied };
    }
    if check_owned(tokens, policy) {
        if let Some(pass) = &policy.passthrough {
            if has_unvalued_flag(tokens, policy) {
                return Verdict::Denied;
            }
            if flag_given(tokens, policy, &pass.require_any) {
                return Verdict::Allowed(pass.level);
            }
        }
        Verdict::Allowed(base_level)
    } else {
        Verdict::Denied
    }
}

pub(super) fn check_owned(tokens: &[Token], policy: &OwnedPolicy) -> bool {
    let (standalone, valued) = (policy.standalone.as_slice(), policy.valued.as_slice());
    !(policy.tolerance.reads_commands.stdin && crate::cst::stdin_fed::fed())
        && check_flags(tokens, standalone, valued, policy.bare, policy.max_positional, policy.tolerance)
        && policy
            .min_positional
            .is_none_or(|min| count_positionals(tokens, standalone, valued, policy.tolerance).is_some_and(|n| n >= min))
}

/// Reads `reads_commands_from`: `"plus"` limits a `+word` operand to a line number, and `"stdin"`
/// refuses the command when anything feeds its standard input.
pub(super) fn reads_commands_from(tolerance: &mut FlagTolerance, command: &str, sources: &[String]) -> Result<(), String> {
    for source in sources {
        match source.as_str() {
            "plus" => tolerance.reads_commands.plus = true,
            "stdin" => tolerance.reads_commands.stdin = true,
            other => return Err(format!("command '{command}': unknown reads_commands_from source `{other}` (known: plus, stdin)")),
        }
    }
    Ok(())
}

/// Whether one of `wanted` is given AS A FLAG: not as the value of the flag before it, not glued
/// into a short cluster after a flag that takes the rest as its value (`-rm` is `-r m`), and not
/// after `--`. A valued flag with nothing glued to it takes the next word whatever it looks like,
/// as getopt does: `make -f -n` reads a makefile named `-n`.
///
/// A required flag that only appears to be present is how a guarded sub runs its unguarded form:
/// `jj describe -rm` names revision `m` and opens the editor.
pub(super) fn flag_given(tokens: &[Token], policy: &OwnedPolicy, wanted: &[String]) -> bool {
    let (standalone, valued) = (policy.standalone.as_slice(), policy.valued.as_slice());
    let wants = |flag: &str| wanted.iter().any(|w| w == flag);
    let mut i = 1;
    while i < tokens.len() {
        let t = tokens[i].as_str();
        if t == "--" {
            return false;
        }
        i += 1;
        if wants(t) {
            return true;
        }
        if !t.starts_with('-') || t == "-" {
            continue;
        }
        if t.starts_with("--") {
            let name = t.split_once('=').map_or(t, |(name, _)| name);
            if wants(name) {
                return true;
            }
            if !t.contains('=') && takes_next_word(standalone, valued, name) {
                i += 1;
            }
            continue;
        }
        if policy.tolerance.single_dash_words || valued.contains_flag(t) {
            if takes_next_word(standalone, valued, t) {
                i += 1;
            }
            continue;
        }
        let bytes = t.as_bytes();
        for (j, &b) in bytes.iter().enumerate().skip(1) {
            if wanted.iter().any(|w| w.as_bytes() == [b'-', b]) {
                return true;
            }
            if valued.contains_short(b) {
                if j == bytes.len() - 1 {
                    i += 1;
                }
                break;
            }
            if !standalone.contains_short(b) {
                break;
            }
        }
    }
    false
}

/// Returns the first non-flag token after `tokens[0]`, treating the
/// policy's `valued` flags as consuming the next argument and its
/// `standalone` flags as zero-arg. `--` ends flag scanning. `-` is a
/// positional (the conventional stdin marker). Used by fallback
/// grammars that want to apply a `PositionalShape` predicate to the
/// first positional without re-implementing flag walking.
pub(super) fn min_positional_fits(parent: &str, toml: &super::types::TomlSub, policy_free: bool) -> Result<(), String> {
    let Some(min) = toml.min_positional else { return Ok(()) };
    if policy_free || !toml.sub.is_empty() || !toml.first_arg.is_empty() || !toml.credential_first_arg.is_empty() {
        return Err(format!("command '{parent}' sub `{}`: min_positional needs a flag policy to count operands against", toml.name));
    }
    match toml.max_positional {
        Some(max) if min > max => Err(format!("command '{parent}' sub `{}`: min_positional {min} exceeds max_positional {max}", toml.name)),
        _ => Ok(()),
    }
}

pub(super) fn first_positional<'a>(tokens: &'a [Token], policy: &OwnedPolicy) -> Option<&'a str> {
    first_positional_at(tokens, policy).map(|(_, s)| s)
}

/// [`first_positional`], plus WHERE it was found.
///
/// The index is what lets a caller split an invocation at the executor: everything up to and
/// including that token is the command's own grammar and can be checked against its flag policy,
/// while everything after it is the SCRIPT's argv and cannot. `dispatch_executor` needs exactly
/// that split — see the comment there.
///
/// Expressed as one walk with `first_positional` delegating to it, rather than two functions that
/// scan independently: the value and its index must never disagree about which token is the
/// executor, and two copies of this loop is how they would.
pub(super) fn first_positional_at<'a>(tokens: &'a [Token], policy: &OwnedPolicy) -> Option<(usize, &'a str)> {
    let standalone = policy.standalone.as_slice();
    let valued = policy.valued.as_slice();
    let mut i = 1;
    while i < tokens.len() {
        let t = &tokens[i];
        let s = t.as_str();
        if s == "--" {
            return tokens.get(i + 1).map(|t| (i + 1, t.as_str()));
        }
        if s == "-" || !s.starts_with('-') {
            return Some((i, s));
        }
        if standalone.contains_flag(s) {
            i += 1;
            continue;
        }
        if valued.contains_flag(s) {
            i += 2;
            continue;
        }
        if let Some((flag, _)) = s.split_once('=')
            && valued.contains_flag(flag)
        {
            i += 1;
            continue;
        }
        // Unknown flag: bail out — it's the policy validator's job to
        // accept or reject. Either way, we've reached the end of the
        // recognized flag run without finding a positional.
        return None;
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parse::Token;
    use crate::policy::FlagTolerance;

    fn toks(words: &[&str]) -> Vec<Token> {
        words.iter().map(|s| Token::from_test(s)).collect()
    }

    fn policy(standalone: &[&str], valued: &[&str], max_positional: Option<usize>) -> OwnedPolicy {
        OwnedPolicy {
            standalone: standalone.iter().map(|s| s.to_string()).collect(),
            valued: valued.iter().map(|s| s.to_string()).collect(),
            bare: true,
            max_positional,
            min_positional: None,
            tolerance: FlagTolerance::strict(),
            passthrough: None,
        }
    }

    #[test]
    fn first_positional_finds_bare_arg() {
        let p = policy(&[], &[], None);
        let tokens = toks(&["cmd", "arg"]);
        assert_eq!(first_positional(&tokens, &p), Some("arg"));
    }

    #[test]
    fn first_positional_skips_standalone_flags() {
        let p = policy(&["--verbose"], &[], None);
        let tokens = toks(&["cmd", "--verbose", "file"]);
        assert_eq!(first_positional(&tokens, &p), Some("file"));
    }

    #[test]
    fn first_positional_skips_valued_flag_value() {
        let p = policy(&[], &["--type"], None);
        let tokens = toks(&["cmd", "--type", "erb", "file.erb"]);
        assert_eq!(first_positional(&tokens, &p), Some("file.erb"));
    }

    #[test]
    fn first_positional_skips_valued_flag_eq_form() {
        let p = policy(&[], &["--type"], None);
        let tokens = toks(&["cmd", "--type=erb", "file.erb"]);
        assert_eq!(first_positional(&tokens, &p), Some("file.erb"));
    }

    #[test]
    fn first_positional_treats_double_dash_as_terminator() {
        let p = policy(&["--verbose"], &[], None);
        let tokens = toks(&["cmd", "--", "--verbose"]);
        // After --, the very next token (even if flag-shaped) is positional.
        assert_eq!(first_positional(&tokens, &p), Some("--verbose"));
    }

    #[test]
    fn first_positional_treats_lone_dash_as_positional() {
        let p = policy(&[], &[], None);
        let tokens = toks(&["cmd", "-"]);
        assert_eq!(first_positional(&tokens, &p), Some("-"));
    }

    #[test]
    fn first_positional_returns_none_for_no_args() {
        let p = policy(&[], &[], None);
        let tokens = toks(&["cmd"]);
        assert_eq!(first_positional(&tokens, &p), None);
    }

    #[test]
    fn first_positional_returns_none_for_only_flags() {
        let p = policy(&["--help"], &[], None);
        let tokens = toks(&["cmd", "--help"]);
        assert_eq!(first_positional(&tokens, &p), None);
    }

    #[test]
    fn first_positional_returns_none_on_unknown_flag() {
        // Bails out at the unknown flag rather than guessing — the policy
        // validator is responsible for rejecting or accepting it.
        let p = policy(&[], &[], None);
        let tokens = toks(&["cmd", "--unknown", "file"]);
        assert_eq!(first_positional(&tokens, &p), None);
    }

    /// Property tests for `first_positional` / `first_positional_at` / `check_owned`.
    ///
    /// Each property pins an invariant of the function pair rather than an example. They share
    /// the in-module `policy`/`toks` builders and run under `proptest` so the synthesized tokens
    /// stay inside the alphabet those builders already understand.
    mod prop {
        use super::*;
        use proptest::prelude::*;

        /// A flag-shaped tail token (regex covers `-`, `--`, and `--name=value` shapes).
        const FLAG_RE: &str = "--?[a-zA-Z][a-zA-Z0-9._-]{0,7}(=[a-zA-Z0-9._-]{1,8})?";
        /// A never-flag-shaped token (no leading `-`, otherwise printable).
        const NON_FLAG_RE: &str = "[a-zA-Z][a-zA-Z0-9._]{0,7}";

        fn toks_owned(words: &[String]) -> Vec<Token> {
            words.iter().cloned().map(Token::from_raw).collect()
        }

        /// Reference implementation of `first_positional_at` for the case where BOTH flag lists
        /// are empty. In that mode the documented behavior reduces to: walk forward, return
        /// `(i + 1, next)` after a bare `--`, return `(i, s)` for `-` or any non-`-`-starting
        /// token, and return `None` on any other flag-shaped token. Used as the oracle.
        fn oracle_first_positional_at(tokens: &[Token]) -> Option<(usize, &str)> {
            // Skips index 0 and returns the same answer the documented walk would on an empty
            // grammar: look at one token, then stop. Encoded as `if let` rather than a loop
            // because every branch decides the result on the first token and a loop would loop
            // at most once.
            let (offset, t) = tokens.iter().enumerate().nth(1)?;
            let s = t.as_str();
            if s == "--" {
                let i = offset + 1;
                return tokens.get(i).map(|t| (i, t.as_str()));
            }
            if s == "-" || !s.starts_with('-') {
                return Some((offset, s));
            }
            None
        }

        proptest! {
            /// Consistency / roundtrip: `first_positional` delegates to `first_positional_at`,
            /// so the string it returns must equal the string half of the indexed pair for
            /// EVERY (tokens, policy) pair. A regression that splits the two walks apart —
            /// the very thing the docstring warns against — fails here.
            #[test]
            fn first_positional_and_first_positional_at_agree_on_the_returned_string(
                tail in proptest::collection::vec("(-|--|--?[a-zA-Z][a-zA-Z0-9._-]{0,7}(=[a-zA-Z0-9._-]{1,8})?|[a-zA-Z][a-zA-Z0-9._]{0,7})", 0..8),
                standalone in proptest::collection::vec(FLAG_RE, 0..4),
                valued in proptest::collection::vec(FLAG_RE, 0..4),
            ) {
                let mut words = vec!["cmd".to_string()];
                words.extend(tail);
                let tokens = toks_owned(&words);
                let p = policy(
                    &standalone.iter().map(String::as_str).collect::<Vec<_>>(),
                    &valued.iter().map(String::as_str).collect::<Vec<_>>(),
                    None,
                );
                let expected = first_positional_at(&tokens, &p).map(|(_, s)| s.to_string());
                let actual = first_positional(&tokens, &p).map(|s| s.to_string());
                proptest::prop_assert_eq!(actual, expected);
            }

            /// Index honesty: the index returned by `first_positional_at` must really point
            /// at the token whose text it pairs with. The walk stores `(i, s)` as one
            /// expression so they cannot disagree by construction, and this property pins
            /// that coupling against any future change that recomputes one half from a
            /// different loop variable.
            #[test]
            fn first_positional_at_index_points_at_the_returned_token(
                standalone in proptest::collection::vec(FLAG_RE, 0..3),
                valued in proptest::collection::vec(FLAG_RE, 0..3),
                tail in proptest::collection::vec(
                    "(--|--?[a-zA-Z][a-zA-Z0-9._-]{0,7}(=[a-zA-Z0-9._-]{1,8})?|[a-zA-Z][a-zA-Z0-9._]{0,7})",
                    1..6,
                ),
            ) {
                let mut words = vec!["cmd".to_string()];
                words.extend(tail);
                let tokens = toks_owned(&words);
                let p = policy(
                    &standalone.iter().map(String::as_str).collect::<Vec<_>>(),
                    &valued.iter().map(String::as_str).collect::<Vec<_>>(),
                    None,
                );
                if let Some((i, s)) = first_positional_at(&tokens, &p) {
                    proptest::prop_assert!(i < tokens.len(), "index {} past tokens.len()={}", i, tokens.len());
                    proptest::prop_assert_eq!(tokens[i].as_str(), s);
                }
            }

            /// Oracle / differential: with both `standalone` and `valued` empty the walk
            /// collapses to a four-line scan. This property states that the contracted
            /// implementation equals the inlined reference for EVERY generated shape, so
            /// a refactor that introduced extra logic for the empty-grammar case would be
            /// caught — the empty case is the one that has to match the docstring.
            #[test]
            fn first_positional_with_empty_grammars_matches_a_simple_scan(
                tail in proptest::collection::vec(
                    "(-|--|--?[a-zA-Z][a-zA-Z0-9._-]{0,7}(=[a-zA-Z0-9._-]{1,8})?|[a-zA-Z][a-zA-Z0-9._]{0,7})",
                    0..6,
                ),
            ) {
                let mut words = vec!["cmd".to_string()];
                words.extend(tail);
                let tokens = toks_owned(&words);
                let p = policy(&[], &[], None);
                let oracle = oracle_first_positional_at(&tokens).map(|(i, s)| (i, s.to_string()));
                let actual = first_positional_at(&tokens, &p).map(|(i, s)| (i, s.to_string()));
                proptest::prop_assert_eq!(actual, oracle);
            }

            /// Monotonicity: prepending a token that the policy declares as a STANDALONE flag
            /// does not change the first positional found later. The walk consumes a standalone
            /// in exactly one step (`i += 1`), so the rest of the scan is identical; the
            /// property locks that "additive, not destructive" behavior in. The prepended flag
            /// is taken from the SAME generated standalone list so we are asserting on real
            /// acceptance, not on unknown-flag bailouts.
            #[test]
            fn prepending_a_known_standalone_flag_does_not_change_the_first_positional(
                standalone in proptest::collection::vec(FLAG_RE, 1..4),
                tail in proptest::collection::vec(NON_FLAG_RE, 0..5),
            ) {
                let prefix_token = standalone[0].clone();
                let mut base = vec!["cmd".to_string()];
                base.extend(tail.clone());
                let base_tokens = toks_owned(&base);
                let p = policy(
                    &standalone.iter().map(String::as_str).collect::<Vec<_>>(),
                    &[],
                    None,
                );
                let before = first_positional(&base_tokens, &p).map(|s| s.to_string());

                let mut prefixed = vec!["cmd".to_string(), prefix_token];
                prefixed.extend(tail);
                let prefixed_tokens = toks_owned(&prefixed);
                let after = first_positional(&prefixed_tokens, &p).map(|s| s.to_string());

                proptest::prop_assert_eq!(after, before);
            }
        }
    }
}

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

    fn jj_like(min_positional: Option<usize>) -> OwnedPolicy {
        OwnedPolicy {
            standalone: vec!["--quiet".into(), "-a".into(), "-k".into()],
            valued: vec!["--message".into(), "--revision".into(), "-m".into(), "-r".into()],
            bare: true,
            max_positional: None,
            min_positional,
            tolerance: FlagTolerance::strict(),
            passthrough: None,
        }
    }

    fn toks(words: &[&str]) -> Vec<Token> {
        std::iter::once("cmd").chain(words.iter().copied()).map(Token::from_test).collect()
    }

    fn given(words: &[&str]) -> bool {
        flag_given(&toks(words), &jj_like(None), &["--message".to_string(), "-m".to_string()])
    }

    #[test]
    fn a_flag_is_given_in_each_of_its_spellings() {
        for words in [&["-m", "x"][..], &["-mx"], &["--message", "x"], &["--message=x"], &["-km", "x"], &["-r", "@", "-m", "x"]] {
            assert!(given(words), "{words:?}");
        }
    }

    #[test]
    fn a_flag_that_only_looks_given_is_not() {
        for words in [
            &[][..],
            &["-rm"],
            &["-r", "m"],
            &["--", "-m", "x"],
            &["--revision=-m"],
            &["--revision", "m"],
            &["m"],
            &["-r", "-m"],
            &["--revision", "-m"],
            &["--revision", "--message"],
            &["-ar", "-m"],
            &["-r", "--message=x"],
        ] {
            assert!(!given(words), "{words:?}");
        }
    }

    #[test]
    fn a_required_word_matches_whole() {
        let mut words = jj_like(None);
        words.tolerance.single_dash_words = true;
        let want = |w: &str| vec![w.to_string()];
        assert!(flag_given(&toks(&["-statistics"]), &words, &want("-statistics")));
        assert!(!flag_given(&toks(&["-statsonly"]), &words, &want("-s")));
        assert!(flag_given(&toks(&["-", "bash"]), &jj_like(None), &want("-")));
        assert!(!flag_given(&toks(&["--", "-"]), &jj_like(None), &want("-")));
    }

    #[test]
    fn min_positional_counts_operands_not_flag_values() {
        let p = jj_like(Some(1));
        assert!(!check_owned(&toks(&["-m", "x"]), &p));
        assert!(!check_owned(&toks(&["-m", "x", "-r", "src/a"]), &p));
        assert!(check_owned(&toks(&["-m", "x", "src/a"]), &p));
        assert!(check_owned(&toks(&["-m", "x", "--", "src/a"]), &p));
        assert!(check_owned(&toks(&["-m", "x"]), &jj_like(None)));
    }

    #[test]
    fn min_positional_is_named_in_the_reference() {
        assert!(jj_like(Some(1)).flag_summary().ends_with("At least 1 positional argument"));
        assert!(jj_like(Some(2)).flag_summary().ends_with("At least 2 positional arguments"));
        assert!(!jj_like(None).flag_summary().contains("positional argument"));
    }

    fn demo(sub_fields: &str) -> Result<Vec<crate::registry::CommandSpec>, String> {
        crate::registry::load_toml(&format!("[[command]]\nname = \"demo\"\n[[command.sub]]\nname = \"split\"\n{sub_fields}\n"), "test")
    }

    #[test]
    fn min_positional_dispatches_through_a_loaded_definition() {
        let specs = demo("level = \"SafeWrite\"\nrequire_any = [\"-m\"]\nmin_positional = 1\nvalued = [\"-m\", \"-r\"]").expect("loads");
        let verdict = |words: &[&str]| crate::registry::dispatch_spec(&toks(words), &specs[0]);
        assert_eq!(verdict(&["split", "-m", "x", "a"]), crate::verdict::Verdict::Allowed(crate::verdict::SafetyLevel::SafeWrite));
        assert_eq!(verdict(&["split", "-m", "x"]), crate::verdict::Verdict::Denied);
        assert_eq!(verdict(&["split", "-m", "x", "-r", "a"]), crate::verdict::Verdict::Denied);
        assert_eq!(verdict(&["split", "a"]), crate::verdict::Verdict::Denied);
    }

    #[test]
    fn min_positional_is_refused_where_nothing_would_count_operands() {
        for fields in [
            "min_positional = 1\nallow_all = true",
            "min_positional = 1\nfirst_arg = [\"x\"]",
            "min_positional = 1\nhandler = \"demo\"",
            "level = \"SafeWrite\"\nmin_positional = 2\nmax_positional = 1",
        ] {
            let err = demo(fields).err().unwrap_or_else(|| panic!("{fields:?} loaded"));
            assert!(err.contains("min_positional"), "{fields:?}: {err}");
        }
    }

    #[derive(Debug, Clone)]
    enum Unit {
        Standalone(&'static str),
        Valued(&'static str, &'static str),
        Glued(&'static str),
        Operand(&'static str),
        Wanted(Vec<&'static str>),
        End,
    }

    fn unit() -> impl Strategy<Value = Unit> {
        let value = prop::sample::select(vec!["m", "x", "mx", "@-"]);
        prop_oneof![
            prop::sample::select(vec!["-a", "-k", "-ak", "--quiet"]).prop_map(Unit::Standalone),
            (prop::sample::select(vec!["-r", "--revision", "-ar"]), prop::sample::select(vec!["m", "@-", "-m", "--message", "-k", "--"]))
                .prop_map(|(f, v)| Unit::Valued(f, v)),
            prop::sample::select(vec!["-rm", "-rx", "-arm", "--revision=m", "--revision=-m"]).prop_map(Unit::Glued),
            value.prop_map(Unit::Operand),
            prop::sample::select(vec![vec!["-m", "x"], vec!["-mx"], vec!["-am", "x"], vec!["--message", "m"], vec!["--message=m"]])
                .prop_map(Unit::Wanted),
            Just(Unit::End),
        ]
    }

    proptest! {
        #[test]
        fn flag_given_matches_a_reading_unit_by_unit(units in prop::collection::vec(unit(), 0..8)) {
            let mut words = Vec::new();
            let mut expected = false;
            let mut ended = false;
            for u in &units {
                match u {
                    Unit::Standalone(f) | Unit::Glued(f) | Unit::Operand(f) => words.push(*f),
                    Unit::Valued(f, v) => words.extend([*f, *v]),
                    Unit::Wanted(w) => {
                        expected |= !ended;
                        words.extend(w.iter().copied());
                    }
                    Unit::End => {
                        ended = true;
                        words.push("--");
                    }
                }
            }
            prop_assert_eq!(given(&words), expected, "{:?}", words);
        }
    }
}

#[cfg(test)]
mod passthrough_tests {
    use super::*;
    use crate::policy::FlagTolerance;
    use proptest::prelude::*;

    fn spec() -> OwnedPolicy {
        let inner = |standalone: &[&str], valued: &[&str]| OwnedPolicy {
            standalone: standalone.iter().map(|s| s.to_string()).collect(),
            valued: valued.iter().map(|s| s.to_string()).collect(),
            bare: false,
            max_positional: Some(0),
            min_positional: None,
            tolerance: FlagTolerance::strict(),
            passthrough: None,
        };
        let mut outer = inner(&["--all", "--check", "-q"], &["-p"]);
        outer.bare = true;
        outer.passthrough = Some(Box::new(PassthroughSpec {
            policy: inner(&["--check", "--quiet", "-l"], &["--edition", "--color"]),
            require_any: vec!["--check".to_string()],
            level: SafetyLevel::SafeRead,
        }));
        outer
    }

    fn verdict(words: &[String]) -> Verdict {
        let tokens: Vec<Token> = words.iter().cloned().map(Token::from_raw).collect();
        check_with_passthrough(&tokens, &spec(), SafetyLevel::SafeWrite)
    }

    fn verdict_strs(words: &[&str]) -> Verdict {
        let owned: Vec<String> = words.iter().map(|s| (*s).to_string()).collect();
        verdict(&owned)
    }

    /// One whole unit of the passthrough grammar: a standalone flag or a valued flag with its value.
    fn allowed_unit() -> impl Strategy<Value = Vec<&'static str>> {
        prop_oneof![
            prop::sample::select(vec!["--quiet", "-l", "--check"]).prop_map(|f| vec![f]),
            prop::sample::select(vec!["--edition", "--color"])
                .prop_flat_map(|f| { prop::sample::select(vec!["2024", "never", "always"]).prop_map(move |v| vec![f, v]) }),
        ]
    }

    /// A token the passthrough lists do not hold: an unknown flag, a path or a bare word.
    fn outsider() -> impl Strategy<Value = String> {
        prop_oneof![
            "--[a-z]{3,8}".prop_filter("not a listed flag", |f| !["--check", "--quiet", "--edition", "--color"].contains(&f.as_str())),
            "-[a-km-z]{1,3}",
            "[a-z]{1,6}(\\.rs)?",
            "(/|~/)[a-z]{1,6}",
            prop::sample::select(vec![
                "--emit".to_string(),
                "--backup".to_string(),
                "--config=emit_mode=files".to_string(),
                "--print-config".to_string(),
            ]),
        ]
    }

    fn assemble(units: &[Vec<&str>], outsider_at: Option<(usize, String)>) -> Vec<String> {
        let mut words: Vec<String> = ["cmd", "--all", "--"].iter().map(|s| s.to_string()).collect();
        words.push("--check".to_string());
        for (i, unit) in units.iter().enumerate() {
            if let Some((at, word)) = &outsider_at
                && *at == i
            {
                words.push(word.clone());
            }
            words.extend(unit.iter().map(|s| s.to_string()));
        }
        if let Some((at, word)) = outsider_at
            && at >= units.len()
        {
            words.push(word);
        }
        words
    }

    proptest! {
        /// Never Allowed when the tail holds a token outside the passthrough lists, wherever it sits.
        #[test]
        fn a_tail_token_outside_the_passthrough_lists_is_never_allowed(
            units in prop::collection::vec(allowed_unit(), 0..5),
            at in 0usize..6,
            word in outsider(),
        ) {
            let words = assemble(&units, Some((at, word)));
            prop_assert_eq!(verdict(&words), Verdict::Denied, "{:?}", words);
        }

        /// The same tails without the outsider are approved at the passthrough's level, so the
        /// property above cannot pass by denying everything.
        #[test]
        fn a_tail_of_listed_flags_with_the_guard_is_allowed_at_the_passthrough_level(
            units in prop::collection::vec(allowed_unit(), 0..5),
        ) {
            let words = assemble(&units, None);
            prop_assert_eq!(verdict(&words), Verdict::Allowed(SafetyLevel::SafeRead), "{:?}", words);
        }

        /// A valued flag at the end of the tail with no value is never Allowed.
        #[test]
        fn a_valued_flag_with_no_value_in_the_tail_is_never_allowed(
            units in prop::collection::vec(allowed_unit(), 0..4),
            flag in prop::sample::select(vec!["--edition", "--color"]),
        ) {
            let mut words = assemble(&units, None);
            words.push(flag.to_string());
            prop_assert_eq!(verdict(&words), Verdict::Denied, "{:?}", words);
        }

        /// A second `--` anywhere in the tail is never Allowed.
        #[test]
        fn a_second_separator_is_never_allowed(units in prop::collection::vec(allowed_unit(), 0..4)) {
            let mut words = assemble(&units, None);
            words.push("--".to_string());
            prop_assert_eq!(verdict(&words), Verdict::Denied, "{:?}", words);
        }
    }

    #[test]
    fn an_unvalued_valued_flag_before_the_separator_is_denied() {
        assert_eq!(verdict_strs(&["cmd", "-p", "--", "--check"]), Verdict::Denied);
        assert_eq!(verdict_strs(&["cmd", "-qp", "--", "--check"]), Verdict::Denied);
        assert_eq!(verdict_strs(&["cmd", "-p"]), Verdict::Denied);
        assert_eq!(verdict_strs(&["cmd", "-p", "xp", "--", "--check"]), Verdict::Allowed(SafetyLevel::SafeRead));
        assert_eq!(verdict_strs(&["cmd", "-qp", "xp", "--", "--check"]), Verdict::Allowed(SafetyLevel::SafeRead));
        assert_eq!(verdict_strs(&["cmd", "-qpx", "--", "--check"]), Verdict::Allowed(SafetyLevel::SafeRead));
        assert_eq!(verdict_strs(&["cmd", "--check", "--", "-l"]), Verdict::Allowed(SafetyLevel::SafeRead));
        assert_eq!(verdict_strs(&["cmd", "--check"]), Verdict::Allowed(SafetyLevel::SafeRead));
        assert_eq!(verdict_strs(&["cmd", "--all"]), Verdict::Allowed(SafetyLevel::SafeWrite));
    }
}