trusty-mpm 1.8.2

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

use crate::commands::hook_rewrite::{is_env_assignment, strip_wrapper_prefix};
// #8735: the xargs option table moved beside the other wrapper grammars.
use crate::commands::program_word::{
    COMMAND_WRAPPERS, Unresolved, XARGS_OPTS_WITH_ARG, resolve_program_word,
};

/// Shell programs that run their `-c` argument as a command string.
///
/// Why (#6660): the guard resolved a segment's program basename and required it
/// to be `git`. `sh -c "git worktree remove …"` resolves to `sh`, so every rule
/// built on [`git_subcommand`] — the #5791 worktree-remove deny, the ADR-0048
/// main-checkout HEAD-move rule, the destructive-delete rule — saw a program it
/// had no opinion about and allowed the command underneath. Naming the shells
/// in one list is what stops the fix from covering a single spelling.
/// What: the basenames whose `-c` argument is an inner command to re-classify.
/// Test: `wrappers_do_not_hide_the_inner_command_from_the_git_verb_rules`.
// `pub(super)` since #6946: [`super::heredoc`] asks the same question of a
// here-document operator line — a body fed to one of these IS shell source, so
// its separators must keep splitting.
pub(super) const DASH_C_SHELLS: &[&str] = &["sh", "bash", "zsh", "dash", "ksh", "ash"];

/// [`COMMAND_WRAPPERS`] words that are not a process in every shell (#9127
/// critic r3): bash runs `command eval` in place where zsh finds no `eval`,
/// and zsh runs `noglob eval` in place where bash finds no `noglob`. An `eval`
/// behind one of these is [`Scope::Unplaceable`].
const SHELL_PRECOMMANDS: &[&str] = &["command", "builtin", "noglob", "nocorrect", "exec", "time"];

/// Where a wrapper's command string runs, so whether a `cd` in it persists
/// (#9127).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Scope {
    /// The current shell: `eval` behind nothing but assignments and at most a
    /// bare `builtin` as its last prefix word.
    Current,
    /// A child process: a shell's `-c`, `env -S`, `flock -c`, `xargs`, or
    /// `eval` behind a process wrapper (`env`, `nohup`, `sudo`, …).
    Child,
    /// An `eval` behind any other word, which bash and zsh run in different
    /// places — or not at all. Fail closed.
    Unplaceable,
}

/// Whether `segment` contains live `$'…'` or `$"…"` quoting (#6660 review).
///
/// Why: `shlex` 1.3.0 does not implement bash's ANSI-C (`$'…'`) or
/// locale-translation (`$"…"`) quoting. It drops the quotes and keeps the `$`,
/// so `sh -c $'git worktree remove x'` tokenizes as
/// `["sh", "-c", "$git worktree remove x"]` and the program token becomes
/// `$git`, which matches no rule. That is a one-character bypass of every
/// git-verb rule, wrapper or not — `git $'worktree' remove x` mangles the same
/// way with no wrapper at all. Since the guard cannot decode the escapes, the
/// only correct answer is to refuse to classify the segment.
/// What: true when a `$` immediately followed by `'` or `"` appears OUTSIDE any
/// quoted span. An unbalanced-quote segment has an untrustworthy
/// [`QuoteScan`] map, so every such `$` reads as live — the conservative
/// direction. A `$'` that is itself quoted (`echo "cost: $'5'"`) is literal
/// text and is not flagged; when it sits inside a wrapper's `-c` string the
/// caller re-scans that string on its own, where it IS live.
/// Test: `unclassifiable_command_flags_ansi_c_quoting`,
/// `unclassifiable_command_allows_ordinary_commands`, and end to end in
/// `pm_guard_denies_a_wrapped_command_it_cannot_classify_via_subagent_payload`.
pub(super) fn has_live_ansi_c_quoting(segment: &str) -> bool {
    let scan = QuoteScan::new(segment);
    let bytes = segment.as_bytes();
    bytes.iter().enumerate().any(|(i, b)| {
        *b == b'$'
            && matches!(bytes.get(i + 1), Some(b'\'') | Some(b'"'))
            && (!scan.balanced || scan.is_unquoted(i))
    })
}

/// What a segment's leading wrapper hides, if anything (#6660).
///
/// Why: three answers, not two. A segment that is not a wrapper classifies
/// as-is; a wrapper hands back the inner command text to classify instead; and
/// a wrapper whose inner text cannot be lexed is a command the guard cannot
/// classify AT ALL, which must deny rather than fall through — otherwise broken
/// quoting is the bypass.
/// What: see the variants.
/// Test: `wrappers_do_not_hide_the_inner_command_from_the_git_verb_rules`,
/// `an_unparseable_wrapped_command_is_denied`,
/// `wrappers_around_benign_commands_still_allow`,
/// `refuses_a_dump_run_through_eval`.
#[derive(Debug, PartialEq, Eq)]
pub(super) enum WrappedCommand {
    /// No wrapper — classify the segment as given.
    None,
    /// The command text the wrapper would actually run.
    Inner(String),
    /// A wrapper carrying an inner command the guard cannot lex. Fail closed.
    Unlexable,
}

/// Resolve the command a leading `sh -c` / `bash -c` / `env -S` / `xargs` /
/// `eval` wrapper would actually run (#6660).
///
/// Why: [`strip_wrapper_prefix`] advances past a wrapper TOKEN but never
/// descends into an argument that is itself a command — a `-c` string or an
/// `xargs` argv. Every rule downstream therefore classified the wrapper instead
/// of the command. Doing the descent here, on the shared segment text, is what
/// makes one fix reach all of them.
/// What: shlex-splits `segment` and asks [`resolve_program_word`] for its
/// program, past assignments, wrappers and their options (#8735 round 2 — a
/// `timeout 60` or `nice -n 5` in front hid the string). The stop word then
/// names the string: a [`DASH_C_SHELLS`] program's `-c` string
/// ([`dash_c_argument`]); an `xargs` argv past [`XARGS_OPTS_WITH_ARG`],
/// re-joined; `eval`'s operands joined by spaces, as the shell does. `env -S`
/// and `flock -c` fail the resolution by design, so when it fails the words are
/// scanned for the first of those carriers, `env -S`/`--split-string` and
/// `flock -c` included ([`carried_string`]).
/// The result is [`WrappedCommand::Unlexable`] when the inner text will not
/// shlex-split, and [`WrappedCommand::None`] when the segment carries no such
/// wrapper — an unlexable OUTER segment included, since that case already falls
/// back to the quote-unaware scan and is not this function's to change. A
/// lookup (`command -v bash`) runs nothing and is `None`.
/// Test: as [`WrappedCommand`], and
/// `denies_a_delete_in_a_command_string_behind_a_wrapper`,
/// `denies_a_command_string_behind_a_wrapper_option_8735`,
/// `denies_a_delete_in_a_command_string_behind_an_unknown_option`.
pub(super) fn wrapped_command(segment: &str) -> WrappedCommand {
    wrapped_command_scoped(segment).0
}

/// [`wrapped_command`], plus the [`Scope`] its string runs in (#9127): `eval`
/// runs in the current shell, so a `cd` inside it persists; a shell's `-c`,
/// `env -S`, `flock -c` and `xargs` start a child process, whose `cd` ends with
/// it ([`eval_scope`] places an `eval` behind a prefix). The scope of a segment
/// with no wrapper is [`Scope::Child`] and means nothing.
/// Test: `grouped_steps_scopes_a_child_shell_but_not_eval`,
/// `a_cd_inside_eval_persists_9127`.
pub(super) fn wrapped_command_scoped(segment: &str) -> (WrappedCommand, Scope) {
    let Some(argv) = shlex::split(segment) else {
        return (WrappedCommand::None, Scope::Child);
    };
    let carried = |at: usize| {
        carried_string(&argv[at], &argv[at + 1..]).map(|inner| {
            let scope = if carrier(&argv[at]) == "eval" {
                eval_scope(&argv[..at])
            } else {
                Scope::Child
            };
            (inner, scope)
        })
    };
    let found = match resolve_program_word(&argv) {
        Ok(word) if word.lookup => None,
        // `xargs` runs its whole argv, whatever program heads it.
        Ok(word) => Some(word.xargs_at.unwrap_or(word.index))
            .filter(|&at| at < argv.len())
            .and_then(carried),
        // #8735 round 2: an option the resolver cannot measure hides the
        // program, so the first word that carries a command string stands in,
        // as `evaluator_at` does for the credential rules.
        Err(Unresolved) => (0..argv.len()).find_map(carried),
    };
    match found {
        Some((inner, scope)) => (inner_or_none(Some(inner)), scope),
        None => (WrappedCommand::None, Scope::Child),
    }
}

/// The [`Scope`] of an `eval` whose words before it are `prefix` (#9127
/// critic r3).
///
/// What: assignments are skipped. Nothing left, or one bare `builtin` as the
/// last word, is [`Scope::Current`]. A first remaining word that is a
/// [`COMMAND_WRAPPERS`] process (not in [`SHELL_PRECOMMANDS`]) is
/// [`Scope::Child`]. Anything else — `command`, `command -p`, `builtin --`,
/// `noglob`, a path to `builtin` — is [`Scope::Unplaceable`].
fn eval_scope(prefix: &[String]) -> Scope {
    let words: Vec<&str> = prefix
        .iter()
        .map(String::as_str)
        .skip_while(|w| is_env_assignment(w))
        .collect();
    match words.as_slice() {
        [] | ["builtin"] => Scope::Current,
        [first, ..]
            if COMMAND_WRAPPERS.contains(&carrier(first))
                && !SHELL_PRECOMMANDS.contains(&carrier(first)) =>
        {
            Scope::Child
        }
        _ => Scope::Unplaceable,
    }
}

/// `program`'s basename, a leading alias-defeating `\` dropped.
fn carrier(program: &str) -> &str {
    let tok = program.strip_prefix('\\').unwrap_or(program);
    tok.rsplit('/').next().unwrap_or(tok)
}

/// The command string word `program` runs from its arguments `rest`, if it
/// is a carrier: a shell's `-c`, `env`/`genv` `-S`, `flock -c`, `xargs`' argv
/// or `eval`'s operands.
fn carried_string(program: &str, rest: &[String]) -> Option<String> {
    let base = carrier(program);
    match base {
        _ if DASH_C_SHELLS.contains(&base) => dash_c_argument(rest),
        "env" | "genv" => env_split_string(rest),
        "flock" => flock_command(rest),
        "xargs" => xargs_argument(rest),
        // #8756: `eval "pm2 jlist"` runs its operands; unread, it hid them.
        "eval" => {
            let operands = rest
                .split_first()
                .filter(|(head, _)| *head == "--")
                .map_or(rest, |(_, tail)| tail);
            Some(operands.join(" "))
        }
        _ => None,
    }
}

/// Classify an extracted inner command string.
///
/// Why: the fail-closed decision lives in ONE place so no wrapper shape can
/// forget it.
/// What: lexable → [`WrappedCommand::Inner`], not → [`WrappedCommand::Unlexable`],
/// absent or whitespace-only (it runs nothing) → [`WrappedCommand::None`].
/// Test: `an_unparseable_wrapped_command_is_denied`.
fn inner_or_none(inner: Option<String>) -> WrappedCommand {
    let Some(inner) = inner else {
        return WrappedCommand::None;
    };
    if inner.trim().is_empty() {
        return WrappedCommand::None;
    }
    match shlex::split(&inner) {
        Some(_) => WrappedCommand::Inner(inner),
        None => WrappedCommand::Unlexable,
    }
}

/// Shell long options that consume the FOLLOWING token as their value.
const SHELL_LONG_OPTS_WITH_ARG: &[&str] = &["--rcfile", "--init-file"];

/// The command string a shell's `-c` option carries, if present.
///
/// Why: shells accept their options in any order and in clusters (`bash -lc`).
/// `-c` is a flag, not an option taking a value: the shell runs its FIRST
/// operand, so reading the token after `-c` missed `bash -ce "…"`,
/// `bash -c -e "…"` and `sh -c -- "…"` (#8756).
/// What: walks the options — a `-`/`+` short cluster (an `o`/`O` in it takes
/// the next token as its value), a long option (those in
/// [`SHELL_LONG_OPTS_WITH_ARG`] take the next token), and a `--` or `-` that
/// ends them. When a `-` cluster contained `c`, the first operand is the
/// command string. `None` when the shell runs a script file instead, or when
/// no operand follows.
/// Test: `wrappers_do_not_hide_the_inner_command_from_the_git_verb_rules`,
/// `refuses_a_dump_through_every_dash_c_spelling`.
fn dash_c_argument(rest: &[String]) -> Option<String> {
    let mut saw_c = false;
    let mut i = 0;
    while let Some(tok) = rest.get(i) {
        if tok == "--" || tok == "-" {
            i += 1;
            break;
        }
        if tok.starts_with("--") {
            i += if SHELL_LONG_OPTS_WITH_ARG.contains(&tok.as_str()) {
                2
            } else {
                1
            };
            continue;
        }
        let Some(cluster) = tok.strip_prefix('-').or_else(|| tok.strip_prefix('+')) else {
            break;
        };
        saw_c |= tok.starts_with('-') && cluster.contains('c');
        i += if cluster.contains(['o', 'O']) { 2 } else { 1 };
    }
    if saw_c { rest.get(i).cloned() } else { None }
}

/// The command string `env -S` / `--split-string` carries, if present.
///
/// Why: `env -S "git worktree remove …"` runs the string as a command, and
/// [`strip_wrapper_prefix`] refuses a wrapper followed by a flag — so this shape
/// resolved to nothing at all and every rule allowed it.
/// What: handles `-S <str>`, `-S<str>`, a flag cluster ending in `S`
/// (`-iS <str>`) and `--split-string[=]<str>`, read only among env's own
/// options — `env git commit -S` signs a commit. `None` for a plain `env`.
/// Test: `wrappers_do_not_hide_the_inner_command_from_the_git_verb_rules`.
fn env_split_string(rest: &[String]) -> Option<String> {
    option_string(
        rest,
        'S',
        "--split-string",
        &["-C", "-P", "-u", "--chdir", "--unset"],
    )
}

/// The command string `flock -c` / `--command` runs, before or right after
/// the lock file (`flock -c 'cmd' FILE`, `flock FILE -c 'cmd'`).
fn flock_command(rest: &[String]) -> Option<String> {
    let valued = &["-E", "-w", "--conflict-exit-code", "--timeout", "--wait"];
    if let Some(string) = option_string(rest, 'c', "--command", valued) {
        return Some(string);
    }
    let file = options_end(rest, valued);
    option_string(rest.get(file + 1..)?, 'c', "--command", &[])
}

/// The value of the string option `-<short>` / `<long>` among the leading
/// options of `rest`; `valued` options there consume the next token.
fn option_string(rest: &[String], short: char, long: &str, valued: &[&str]) -> Option<String> {
    let mut i = 0;
    while let Some(tok) = rest.get(i) {
        // `env -` is `-i`; `--` or any other non-option ends the options.
        if tok == "-" {
            i += 1;
            continue;
        }
        if tok == "--" || !tok.starts_with('-') {
            return None;
        }
        if tok == long {
            return rest.get(i + 1).cloned();
        }
        if let Some(value) = tok.strip_prefix(long).and_then(|v| v.strip_prefix('=')) {
            return Some(value.to_string());
        }
        let mut width = 1;
        if !tok.starts_with("--") {
            for (at, c) in tok.char_indices().skip(1) {
                let value = &tok[at + c.len_utf8()..];
                if c == short {
                    // Letters before it were flags (`-iS`); the rest is its value.
                    return if value.is_empty() {
                        rest.get(i + 1).cloned()
                    } else {
                        Some(value.to_string())
                    };
                }
                if valued.iter().any(|v| v.len() == 2 && v.ends_with(c)) {
                    // A value-taking letter ends the cluster (`-uNAME`, `-u NAME`).
                    width = if value.is_empty() { 2 } else { 1 };
                    break;
                }
            }
        } else if valued.contains(&tok.as_str()) {
            width = 2;
        }
        i += width;
    }
    None
}

/// The index of the first non-option word of `rest`.
fn options_end(rest: &[String], valued: &[&str]) -> usize {
    let mut i = 0;
    while let Some(tok) = rest.get(i) {
        if tok == "--" {
            return i + 1;
        }
        if !tok.starts_with('-') || tok == "-" {
            return i;
        }
        i += if valued.contains(&tok.as_str()) { 2 } else { 1 };
    }
    i
}

/// The command `xargs` would run, re-joined into a command string.
///
/// Why: `xargs git worktree remove <path>` runs `git`, and reading only the
/// first token gave `xargs`. The stdin-supplied arguments are unknowable here,
/// but the verb and every literal argument on the command line are not — and
/// those are what the git-verb rules classify.
/// What: skips xargs' own options (those in [`XARGS_OPTS_WITH_ARG`] consume the
/// next token; attached and `=`-joined values consume none) and re-quotes the
/// remaining argv with `shlex::try_join`. `None` when nothing follows the
/// options, or when a token cannot be re-quoted (it contains a NUL).
/// Test: `wrappers_do_not_hide_the_inner_command_from_the_git_verb_rules`.
fn xargs_argument(rest: &[String]) -> Option<String> {
    let i = xargs_utility_index(rest);
    if i >= rest.len() {
        return None;
    }
    shlex::try_join(rest[i..].iter().map(String::as_str)).ok()
}

/// The index in `rest`, the words after `xargs`, of the utility it runs:
/// past its options, where an [`XARGS_OPTS_WITH_ARG`] option consumes the
/// next word. `rest.len()` when no utility follows.
/// Test: `wrappers_do_not_hide_the_inner_command_from_the_git_verb_rules`,
/// `xargs_into_a_wrapper_or_runner_naming_tmux_denies_9053`.
pub(super) fn xargs_utility_index(rest: &[String]) -> usize {
    let mut i = 0;
    while i < rest.len() {
        let tok = rest[i].as_str();
        if !tok.starts_with('-') || tok == "-" {
            break;
        }
        i += if XARGS_OPTS_WITH_ARG.contains(&tok) {
            2
        } else {
            1
        };
    }
    i.min(rest.len())
}

/// Quote context of a single byte of a shell command.
///
/// Why: the guard's operator/redirection/substitution scanners must treat a
/// metacharacter inside quotes as literal data, not shell syntax. `Single` and
/// `Double` differ because command substitution (`$(…)`, backticks) is still
/// active inside double quotes but fully suppressed inside single quotes.
/// What: the three POSIX quoting states.
/// Test: `shell_lex::tests` (via [`QuoteScan`]).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(super) enum Quote {
    /// Outside any quotes — metacharacters are live shell syntax.
    None,
    /// Inside `'…'` — everything literal, no substitution, no operators.
    Single,
    /// Inside `"…"` — operators literal, but `$(…)`/backticks still active.
    Double,
}

/// Per-byte quote-context map of a shell command, plus a balanced flag.
///
/// Why: lets the sibling scanners ask "is byte `i` inside quotes?" so a `>`,
/// `|`, `&&`, `$(`, or backtick that is merely quoted argument content is not
/// mistaken for shell syntax. When quotes are *unbalanced* the parse is
/// untrustworthy, so callers fall back to their proven quote-unaware scan (the
/// conservative, over-blocking direction) rather than trust a partial map.
/// What: [`QuoteScan::new`] walks the bytes once tracking quote state (POSIX
/// backslash-escaping honoured outside single quotes), recording each byte's
/// context; `balanced` is `true` iff every opened quote was closed.
/// Test: `quote_scan_*`.
pub(super) struct QuoteScan {
    states: Vec<Quote>,
    /// `true` when the command's quotes are all closed.
    pub(super) balanced: bool,
}

impl QuoteScan {
    /// Build the per-byte quote map for `command`.
    ///
    /// Why: single left-to-right pass so every scanner shares one definition of
    /// "what is quoted", matching real shell tokenisation closely enough to
    /// exclude quoted content while erring toward `None` (live syntax) on any
    /// ambiguity.
    /// What: tracks the current [`Quote`] state; outside single quotes a `\`
    /// escapes the next byte (recorded in the same state); `'`/`"` open/close
    /// their span only when not already inside the other kind. Records one
    /// [`Quote`] per byte so `states[i]` is byte `i`'s context.
    /// Test: `quote_scan_marks_single_and_double`, `quote_scan_backslash_escape`,
    /// `quote_scan_reports_unbalanced`.
    pub(super) fn new(command: &str) -> Self {
        let bytes = command.as_bytes();
        let mut states = Vec::with_capacity(bytes.len());
        let mut cur = Quote::None;
        let mut i = 0;
        while i < bytes.len() {
            let c = bytes[i];
            match cur {
                Quote::Single => {
                    states.push(Quote::Single);
                    if c == b'\'' {
                        cur = Quote::None;
                    }
                    i += 1;
                }
                Quote::Double => {
                    states.push(Quote::Double);
                    if c == b'\\' && i + 1 < bytes.len() {
                        // Backslash escapes the next byte inside double quotes.
                        states.push(Quote::Double);
                        i += 2;
                    } else {
                        if c == b'"' {
                            cur = Quote::None;
                        }
                        i += 1;
                    }
                }
                Quote::None => {
                    if c == b'\\' && i + 1 < bytes.len() {
                        states.push(Quote::None);
                        states.push(Quote::None);
                        i += 2;
                    } else if c == b'\'' {
                        states.push(Quote::Single);
                        cur = Quote::Single;
                        i += 1;
                    } else if c == b'"' {
                        states.push(Quote::Double);
                        cur = Quote::Double;
                        i += 1;
                    } else {
                        states.push(Quote::None);
                        i += 1;
                    }
                }
            }
        }
        QuoteScan {
            states,
            balanced: cur == Quote::None,
        }
    }

    /// Quote context of byte `idx` (defaults to `None` past the end).
    fn at(&self, idx: usize) -> Quote {
        self.states.get(idx).copied().unwrap_or(Quote::None)
    }

    /// Whether byte `idx` is outside all quotes (a live shell metacharacter).
    ///
    /// Why: composition operators (`|`, `&&`, `;`, `&`, newline) and file-write
    /// redirection (`>`) are only real syntax when unquoted.
    /// What: `true` iff `at(idx) == None`.
    /// Test: `quote_scan_marks_single_and_double`.
    pub(super) fn is_unquoted(&self, idx: usize) -> bool {
        self.at(idx) == Quote::None
    }

    /// Whether a command substitution (`$(`, backtick) at byte `idx` is live.
    ///
    /// Why: single quotes suppress substitution entirely, but double quotes do
    /// NOT — `echo "$(sed -i …)"` still runs `sed`, so that case must remain
    /// scannable while `echo '$(sed -i …)'` (literal) is excluded.
    /// What: `true` when the byte is not inside single quotes.
    /// Test: `quote_scan_substitution_live_in_double_quotes`.
    pub(super) fn allows_substitution(&self, idx: usize) -> bool {
        self.at(idx) != Quote::Single
    }
}

/// Git global options that consume a following *separate* argv token.
///
/// Why: to reach the real subcommand the parser must skip both the flag and its
/// argument (`git -C /path commit` → skip `-C` and `/path`, land on `commit`).
/// The `=`-joined long forms (`--git-dir=/p`) carry their value in the same
/// token; only a long name listed here may be spelled that way.
/// What: every value-taking git global option git 2.54 documents, in its
/// space-separated spelling. `--attr-source` is here since #8439: it was
/// walked as valueless, so its VALUE was read as the subcommand.
const GIT_GLOBAL_OPTS_WITH_ARG: &[&str] = &[
    "-C",
    "-c",
    "--git-dir",
    "--work-tree",
    "--namespace",
    "--super-prefix",
    "--config-env",
    "--attr-source",
];

/// Git global options that take no value (#8439).
///
/// Why: every dash-led token that was not in [`GIT_GLOBAL_OPTS_WITH_ARG`] used
/// to be walked as valueless, so an option git gives a value — the internal
/// `--shallow-file <path>`, or any option a later git adds — had its value read
/// as the subcommand, and `git --shallow-file status checkout -- f` resolved to
/// `status`. The walk now knows every option it skips and stops on any other.
/// What: the valueless global options git 2.54 documents. `--exec-path` and
/// `--list-cmds` also take an `=`-joined value; see [`GIT_GLOBAL_OPTS_JOINED`].
const GIT_GLOBAL_FLAGS: &[&str] = &[
    "-p",
    "--paginate",
    "-P",
    "--no-pager",
    "--bare",
    "--no-replace-objects",
    "--no-lazy-fetch",
    "--no-optional-locks",
    "--no-advice",
    "--literal-pathspecs",
    "--glob-pathspecs",
    "--noglob-pathspecs",
    "--icase-pathspecs",
    "--exec-path",
    "--html-path",
    "--man-path",
    "--info-path",
    "--version",
    "--help",
    "-v",
    "-h",
];

/// Long global options that accept only an `=`-joined value (#8439).
const GIT_GLOBAL_OPTS_JOINED: &[&str] = &["--exec-path", "--list-cmds"];

/// Where the global-option walk of a git argv stopped.
///
/// Why (#8439): `None` from [`git_argv_at_subcommand`] used to mean only "not
/// git, or no subcommand". An unknown global option now also stops the walk,
/// and a caller deciding a deny must tell that apart from "not git" — see
/// [`git_subcommand_candidates`].
/// What: the index of the subcommand, the end of the argv, or an option the
/// walk does not know.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum GitWalk {
    /// The subcommand token's index.
    At(usize),
    /// Only known global options; no subcommand follows.
    End,
    /// An unknown global option, a value-taking one with no value, or `--`.
    Unknown,
}

/// Walk git's global options from `start` (the token after `git`).
///
/// Why: one walk serves the strict resolver and the candidate list, so the two
/// cannot disagree on which options are known.
/// What: skips [`GIT_GLOBAL_FLAGS`], a [`GIT_GLOBAL_OPTS_WITH_ARG`] option plus
/// its value (or `=`-joined for a long one), and a [`GIT_GLOBAL_OPTS_JOINED`]
/// `=` form. Anything else dash-led, a missing value, or `--` is
/// [`GitWalk::Unknown`].
/// Test: `git_subcommand_none_for_an_unknown_global_flag`,
/// `git_subcommand_resolves_every_known_global_flag`.
fn walk_git_globals(argv: &[String], start: usize) -> GitWalk {
    let mut i = start;
    while let Some(tok) = argv.get(i) {
        if !tok.starts_with('-') || tok == "-" {
            return GitWalk::At(i);
        }
        if GIT_GLOBAL_FLAGS.contains(&tok.as_str()) {
            i += 1;
            continue;
        }
        if GIT_GLOBAL_OPTS_WITH_ARG.contains(&tok.as_str()) {
            if argv.get(i + 1).is_none() {
                return GitWalk::Unknown;
            }
            i += 2;
            continue;
        }
        let joined = tok.split_once('=').is_some_and(|(name, _)| {
            name.starts_with("--")
                && (GIT_GLOBAL_OPTS_WITH_ARG.contains(&name)
                    || GIT_GLOBAL_OPTS_JOINED.contains(&name))
        });
        if joined {
            i += 1;
            continue;
        }
        return GitWalk::Unknown;
    }
    GitWalk::End
}

/// The argv of `segment` and the index of its program token, when that
/// program is `git`.
///
/// Why: shared by the strict resolver and the candidate list.
/// What: shlex-split (`None` on unbalanced quotes), [`strip_wrapper_prefix`],
/// and a `git` basename check.
fn git_program_argv(segment: &str) -> Option<(Vec<String>, usize)> {
    let argv = shlex::split(segment)?;
    let i = strip_wrapper_prefix(&argv)?;
    let program = argv.get(i)?;
    let program = program.strip_prefix('\\').unwrap_or(program);
    if program.rsplit('/').next().unwrap_or(program) != "git" {
        return None;
    }
    Some((argv, i))
}

/// Every token of a git segment that could be its subcommand (#8439).
///
/// Why: a rule that DENIES a git verb cannot treat an unresolvable git argv as
/// "not that verb" — that is how `git --shallow-file status checkout -- f`
/// passed the main-checkout rule. When the global options resolve, the one
/// subcommand is the answer; when they do not, every later token that is not
/// an option might be it, and a deny rule must check each.
/// What: `None` when the segment is not git (or does not lex). Otherwise the
/// argv and the candidate indices: the resolved subcommand alone, none when
/// only global options follow `git`, or — for [`GitWalk::Unknown`] — every
/// later token that does not start with `-`.
/// Test: `git_subcommand_candidates_cover_every_position_when_unresolved`.
pub(crate) fn git_subcommand_candidates(segment: &str) -> Option<(Vec<String>, Vec<usize>)> {
    let (argv, program) = git_program_argv(segment)?;
    let candidates = match walk_git_globals(&argv, program + 1) {
        GitWalk::At(i) => vec![i],
        GitWalk::End => Vec::new(),
        GitWalk::Unknown => (program + 1..argv.len())
            .filter(|&i| !argv[i].starts_with('-'))
            .collect(),
    };
    Some((argv, candidates))
}

/// Whether any candidate subcommand of `segment` is `verb` (#8439).
///
/// Why: the fail-closed form of `git_subcommand(segment) == Some(verb)` for a
/// rule that denies `verb`.
/// What: [`git_subcommand_candidates`] contains a token equal to `verb`.
/// Test: `git_subcommand_candidates_cover_every_position_when_unresolved`.
pub(crate) fn git_may_run(segment: &str, verb: &str) -> bool {
    git_subcommand_candidates(segment).is_some_and(|(argv, at)| at.iter().any(|&i| argv[i] == verb))
}

/// Resolve the real `git` subcommand of a single pipeline segment.
///
/// Why (issue #2734): the guard must recognise an allowlisted git subcommand
/// (`commit`, `status`, …) — and the one forbidden one (`apply`) — through any
/// leading git global flags, which the earlier two-token `effective_tool_name`
/// matcher could not see past. Parsing the argv properly closes both the
/// `git -C <path> commit` false positive and the `git -C <path> apply`
/// false negative. Issue #4031 review (pass 2): this function had its OWN
/// `sudo`/`env`-only prefix skip, a second enumeration site that inherited the
/// same weakness `hook_rewrite::first_command_token` did — `command git apply
/// -` and `command git worktree remove --force <path>` reached the git guards
/// unresolved. It now shares [`crate::commands::hook_rewrite::strip_wrapper_prefix`]
/// with that function instead of re-enumerating.
/// What: through [`git_argv_at_subcommand`], shlex-splits `segment`
/// (quote-aware; `None` on unbalanced quotes →
/// caller falls back), delegates the leading `KEY=value`/wrapper skip to
/// [`strip_wrapper_prefix`], requires the program basename to be `git`, then
/// walks past global options ([`walk_git_globals`]) and returns the first
/// non-option token (the subcommand). `None` when the segment is not `git`, is
/// unparseable, has no subcommand after the options, or carries a global
/// option the walk does not know (#8439). A rule that DENIES a verb must not
/// read that `None` as "not this verb" — it asks [`git_may_run`] or
/// [`git_subcommand_candidates`] instead.
/// This is where every git rule in the guard decides that a segment IS a git
/// invocation, and it decides on POSITION: the program token, resolved through
/// the wrapper/env-assignment prefix and its own basename. `git` inside any
/// other token — `crates/trusty-git-analytics/`, `.gitignore`, `github.com`,
/// prose inside quotes — is not a command word and yields `None`. #6982
/// reported such commands being refused; the refusals come from the Claude
/// Code harness rather than from here, and the two tests named below pin this
/// side of the contract so a later rule cannot introduce the substring match
/// the report describes.
/// Test: `git_subcommand_skips_global_flags`, `git_subcommand_plain`,
/// `git_subcommand_none_for_non_git`, `git_subcommand_none_when_unbalanced`,
/// `git_subcommand_resolves_through_command_and_nice_wrappers`,
/// `git_is_only_a_git_command_in_command_position`,
/// `git_in_command_position_is_still_a_git_command`.
pub(crate) fn git_subcommand(segment: &str) -> Option<String> {
    let (argv, i) = git_argv_at_subcommand(segment)?;
    Some(argv[i].clone())
}

/// The parsed argv of a git segment, and the index of its subcommand token.
///
/// Why: [`git_subcommand`] answers "which subcommand", and [`git_file_write_target`]
/// asks the same parser "and what did that subcommand's arguments say". One
/// walk over the global options serves both, so a rule about a git ARGUMENT
/// cannot drift from the rule about the git VERB — a second argv parser is the
/// defect this shape prevents.
/// What: the body [`git_subcommand`] used to carry — shlex-split (`None` on
/// unbalanced quotes), [`strip_wrapper_prefix`], a `git` basename check, then
/// the global-option walk described on [`git_subcommand`]. Returns the argv
/// alongside the index of the first non-option token; `None` on an unknown
/// global option (#8439).
/// Test: every `git_subcommand_*` test, plus
/// `git_output_file_finds_both_spellings`.
pub(crate) fn git_argv_at_subcommand(segment: &str) -> Option<(Vec<String>, usize)> {
    let (argv, program) = git_program_argv(segment)?;
    // #8439: an unknown global option is `None`, never a guess at its arity.
    match walk_git_globals(&argv, program + 1) {
        GitWalk::At(i) => Some((argv, i)),
        GitWalk::End | GitWalk::Unknown => None,
    }
}

/// Per-subcommand options whose value is a path git WRITES, beyond the
/// `--output` every diff-generating subcommand takes.
///
/// Why (#7399 round 2): `--output` alone left three writes through —
/// `git format-patch -o <dir>`, `git format-patch --output-directory=<dir>`
/// and `git archive -o <file>` each produced a file against git 2.54.0. The
/// options are subcommand-specific, unlike `--output`: `-o` on `git diff` is
/// a revision (git answers `fatal: ambiguous argument`), and `-o` on
/// `git clone` names the origin remote, so a global `-o` rule would deny
/// reads. A row here is a spelling verified against `git <sub> --help`.
/// What: `(subcommand, options)`; each option is matched whole and takes its
/// value attached (`-o<dir>`, `--output-directory=<dir>`) or separated.
/// Test: `git_file_write_target_finds_the_short_output_options`.
const GIT_SUBCOMMAND_WRITE_OPTS: &[(&str, &[&str])] = &[
    ("format-patch", &["-o", "--output-directory"]),
    ("archive", &["-o"]),
];

/// The `--output` option every diff-generating subcommand accepts.
///
/// Why: `diff`, `log`, `show` and `format-patch` all take it, so it is asked
/// of every subcommand rather than listed per row above.
const GIT_OUTPUT_OPT: &[&str] = &["--output"];

/// The file or directory a git command would WRITE, if its arguments name one.
///
/// Why (#7399): `git diff --output=/tmp/o.diff` writes a file exactly as
/// `git diff > /tmp/o.diff` does, but carries no `>`, so
/// [`super::has_file_write_redirection`] never saw it and the PM's write
/// boundary (ADR-0044, ADR-0048) had an uncaught hole. Round 2 found three
/// more spellings of the same hole — `format-patch -o`,
/// `format-patch --output-directory=`, `archive -o` — plus two writes that
/// need no option at all: a bare `git format-patch` drops `NNNN-*.patch`
/// files into the working directory, and `git bundle create <file>` names its
/// output as a positional.
/// What: walks the subcommand's own arguments from
/// [`git_argv_at_subcommand`] and returns the first write target it finds —
/// [`GIT_OUTPUT_OPT`] on any subcommand, plus that subcommand's row in
/// [`GIT_SUBCOMMAND_WRITE_OPTS`], in the attached and separated spellings git
/// accepts (all verified against git 2.54.0). Every match is on the whole
/// option token, never a prefix, so `--output-indicator-new=+` — which
/// changes one character of the patch body and writes nothing — is untouched.
/// Option scanning stops at `--`, past which git parses pathspecs rather than
/// options. Two subcommands are decided by shape rather than by an option:
/// `format-patch` writes unless `--stdout` is present, and `bundle create`
/// writes to its first positional unless that positional is `-` (stdout).
/// Every candidate subcommand is asked when the global options do not resolve
/// ([`git_subcommand_candidates`], #8439).
/// `Some("")` when the write is real but names no readable path — a valueless
/// flag, or `format-patch`'s implicit working directory: the caller still
/// denies and has no path to report. `None` when the segment is not a git
/// command, cannot be lexed, or names no write — a lexing failure therefore
/// withholds a NEW deny and can never turn an existing deny into an allow.
/// Test: `git_file_write_target_finds_both_output_spellings`,
/// `git_file_write_target_finds_the_short_output_options`,
/// `git_file_write_target_reads_format_patch_and_bundle_by_shape`,
/// `git_file_write_target_ignores_the_indicator_options`,
/// `git_file_write_target_stops_at_the_pathspec_separator`,
/// `git_file_write_target_none_when_unbalanced`, and end to end in
/// `git_diff_output_flag_is_refused_as_a_file_write` and
/// `git_short_output_options_are_refused_as_file_writes`.
pub(crate) fn git_file_write_target(segment: &str) -> Option<String> {
    // #8439: an unresolvable global option leaves several tokens that could be
    // the subcommand; a write through any of them is a write.
    let (argv, candidates) = git_subcommand_candidates(segment)?;
    candidates
        .into_iter()
        .find_map(|at| write_target_at(&argv, at))
}

/// [`git_file_write_target`] for the subcommand at index `subcommand`.
fn write_target_at(argv: &[String], subcommand: usize) -> Option<String> {
    let sub = argv[subcommand].as_str();
    let args = &argv[subcommand + 1..];
    if sub == "bundle" {
        return bundle_create_target(args);
    }
    let extra = GIT_SUBCOMMAND_WRITE_OPTS
        .iter()
        .find(|(name, _)| *name == sub)
        .map_or(&[] as &[&str], |(_, opts)| *opts);
    let mut stdout_requested = false;
    for (i, tok) in args.iter().enumerate() {
        if tok == "--" {
            break;
        }
        if tok == "--stdout" {
            stdout_requested = true;
            continue;
        }
        let next = args.get(i + 1);
        if let Some(target) =
            option_value(tok, next, GIT_OUTPUT_OPT).or_else(|| option_value(tok, next, extra))
        {
            return Some(target);
        }
    }
    // A `format-patch` that was not told to write to stdout writes its patch
    // files into the working directory, naming no path at all.
    if sub == "format-patch" && !stdout_requested {
        return Some(String::new());
    }
    None
}

/// The value `tok` carries for one of `opts`, in either spelling.
///
/// Why: an option's value reaches git three ways — a separate token, joined
/// with `=` on a long option, or attached to a short one (`-o/tmp/d`, which
/// git 2.54.0 accepts). Deciding all three in one place is what keeps the
/// match on the whole option and off its prefix.
/// What: `Some(value)` when `tok` IS one of `opts` (value = the next token, or
/// `""` when the option ends the argv), when it is `<opt>=<value>`, or when it
/// is a short option with the value attached. `None` otherwise.
/// Test: `git_file_write_target_finds_the_short_output_options`.
fn option_value(tok: &str, next: Option<&String>, opts: &[&str]) -> Option<String> {
    for opt in opts {
        if tok == *opt {
            return Some(next.cloned().unwrap_or_default());
        }
        if let Some(rest) = tok.strip_prefix(opt)
            && let Some(value) = rest.strip_prefix('=')
        {
            return Some(value.to_string());
        }
        // A short option (`-o`) takes its value attached; a long one does not.
        if !opt.starts_with("--")
            && let Some(value) = tok.strip_prefix(opt)
            && !value.is_empty()
        {
            return Some(value.to_string());
        }
    }
    None
}

/// The file `git bundle create` would write, if it names one.
///
/// Why: `bundle create` takes its output as a POSITIONAL — `git bundle create
/// /tmp/x.bundle HEAD` wrote 6477 bytes against git 2.54.0 — so no option
/// scan can see it. `-` is the documented stdout spelling and stays allowed.
/// What: requires `create` as the first argument, skips its own valueless
/// flags (`-q`, `--quiet`, `--progress`, `--version=<n>`), and returns the
/// first positional. `None` for `-`, for another `bundle` subcommand
/// (`verify`, `list-heads`, `unbundle` name a file they READ), and when no
/// positional follows.
/// Test: `git_file_write_target_reads_format_patch_and_bundle_by_shape`.
fn bundle_create_target(args: &[String]) -> Option<String> {
    let mut rest = args.iter();
    if rest.next().map(String::as_str) != Some("create") {
        return None;
    }
    for tok in rest {
        if tok == "-" {
            return None;
        }
        if tok.starts_with('-') {
            continue;
        }
        return Some(tok.clone());
    }
    None
}

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

    #[test]
    fn quote_scan_marks_single_and_double() {
        let scan = QuoteScan::new("a '>' b \">\" c");
        assert!(scan.balanced);
        // Byte 0 'a' unquoted; the two `>` are inside quotes.
        assert!(scan.is_unquoted(0));
        let s: String = "a '>' b \">\" c".to_string();
        let first_gt = s.find('>').unwrap();
        let last_gt = s.rfind('>').unwrap();
        assert!(!scan.is_unquoted(first_gt), "first > is single-quoted");
        assert!(!scan.is_unquoted(last_gt), "second > is double-quoted");
    }

    #[test]
    fn quote_scan_backslash_escape() {
        // An escaped quote outside quotes must NOT open a span.
        let scan = QuoteScan::new(r#"echo \" ok"#);
        assert!(scan.balanced, "escaped quote must not open a span");
    }

    #[test]
    fn quote_scan_reports_unbalanced() {
        assert!(!QuoteScan::new("echo 'unterminated").balanced);
        assert!(!QuoteScan::new("echo \"unterminated").balanced);
        assert!(QuoteScan::new("echo 'closed'").balanced);
    }

    #[test]
    fn quote_scan_substitution_live_in_double_quotes() {
        // `$(` inside double quotes is still live; inside single quotes it is
        // literal.
        let dq = "echo \"$(x)\"";
        let scan = QuoteScan::new(dq);
        let dollar = dq.find('$').unwrap();
        assert!(scan.allows_substitution(dollar), "double-quoted $( is live");

        let sq = "echo '$(x)'";
        let scan = QuoteScan::new(sq);
        let dollar = sq.find('$').unwrap();
        assert!(
            !scan.allows_substitution(dollar),
            "single-quoted $( is literal"
        );
    }

    #[test]
    fn git_subcommand_plain() {
        assert_eq!(git_subcommand("git commit -m x").as_deref(), Some("commit"));
        assert_eq!(git_subcommand("git status").as_deref(), Some("status"));
        assert_eq!(git_subcommand("git log --oneline").as_deref(), Some("log"));
        assert_eq!(git_subcommand("git apply p.diff").as_deref(), Some("apply"));
    }

    #[test]
    fn git_subcommand_skips_global_flags() {
        assert_eq!(
            git_subcommand("git -C /some/path commit -m x").as_deref(),
            Some("commit")
        );
        assert_eq!(
            git_subcommand("git -C /some/path apply p.diff").as_deref(),
            Some("apply")
        );
        assert_eq!(
            git_subcommand("git -c user.name=x commit").as_deref(),
            Some("commit")
        );
        assert_eq!(
            git_subcommand("git --git-dir=/p/.git status").as_deref(),
            Some("status")
        );
        assert_eq!(
            git_subcommand("git --work-tree /p -C /p diff").as_deref(),
            Some("diff")
        );
        assert_eq!(
            git_subcommand("FOO=bar git -C /p push").as_deref(),
            Some("push")
        );
    }

    #[test]
    fn git_subcommand_none_for_non_git() {
        assert_eq!(git_subcommand("ls -la"), None);
        assert_eq!(git_subcommand("cargo test"), None);
        assert_eq!(git_subcommand("gitfoo status"), None);
    }

    // #8439: an unknown global option stops the walk; its value is never read
    // as the subcommand.
    #[test]
    fn git_subcommand_none_for_an_unknown_global_flag() {
        for command in [
            "git --shallow-file status checkout -- Cargo.toml",
            "git --shallow-file log reset --hard",
            "git --bogus=x status",
            "git -C",
            "git -- status",
        ] {
            assert_eq!(git_subcommand(command), None, "{command}");
            assert_eq!(git_argv_at_subcommand(command), None, "{command}");
        }
    }

    // #8439: every documented global option still resolves, including the
    // valued `--attr-source` that used to be walked as valueless.
    #[test]
    fn git_subcommand_resolves_every_known_global_flag() {
        for (command, sub) in [
            (
                "git --attr-source status checkout -- Cargo.toml",
                "checkout",
            ),
            ("git --attr-source=HEAD log", "log"),
            ("git --no-pager -P --no-optional-locks diff", "diff"),
            ("git --exec-path=/x --literal-pathspecs status", "status"),
            ("git --config-env=a=B commit", "commit"),
        ] {
            assert_eq!(git_subcommand(command).as_deref(), Some(sub), "{command}");
        }
        assert_eq!(git_subcommand("git --version"), None);
    }

    // #8439: an unresolved walk offers every later non-option token, so a
    // deny rule sees `checkout` behind `--shallow-file status`.
    #[test]
    fn git_subcommand_candidates_cover_every_position_when_unresolved() {
        let (argv, at) = git_subcommand_candidates("git --shallow-file status checkout -- f")
            .expect("a git segment");
        let names: Vec<&str> = at.iter().map(|&i| argv[i].as_str()).collect();
        assert_eq!(names, ["status", "checkout", "f"]);
        assert!(git_may_run("git --shallow-file x apply p.diff", "apply"));
        assert!(!git_may_run("git status", "apply"));
        assert!(!git_may_run("ls apply", "apply"));
        assert_eq!(
            git_file_write_target("git --shallow-file x diff --output=/tmp/o.diff").as_deref(),
            Some("/tmp/o.diff")
        );
    }

    #[test]
    fn git_subcommand_none_when_unbalanced() {
        // Unbalanced quotes → shlex returns None → caller falls back.
        assert_eq!(git_subcommand("git commit -m 'unterminated"), None);
    }

    #[test]
    fn git_subcommand_resolves_path_program() {
        assert_eq!(
            git_subcommand("/usr/bin/git -C /p commit").as_deref(),
            Some("commit")
        );
    }

    #[test]
    fn git_subcommand_resolves_through_command_and_nice_wrappers() {
        // #4031 review, item 4: `git_subcommand` had its own sudo/env-only
        // prefix skip, a second enumeration site independent of
        // `hook_rewrite::first_command_token` — `command git apply -` and a
        // `nice`-wrapped git call both reached the git guards unresolved
        // before sharing `strip_wrapper_prefix`.
        for command in ["command git apply -", "nice git reset --hard"] {
            assert!(
                git_subcommand(command).is_some(),
                "expected a resolved subcommand for: {command}"
            );
        }
        assert_eq!(
            git_subcommand("command git apply -").as_deref(),
            Some("apply")
        );
        assert_eq!(
            git_subcommand("nice git reset --hard").as_deref(),
            Some("reset")
        );
    }

    // #7399: both spellings of `--output` name a file git writes.
    #[test]
    fn git_file_write_target_finds_both_output_spellings() {
        assert_eq!(
            git_file_write_target("git diff --output=/tmp/o.diff").as_deref(),
            Some("/tmp/o.diff")
        );
        assert_eq!(
            git_file_write_target("git diff --output /tmp/o.diff HEAD").as_deref(),
            Some("/tmp/o.diff")
        );
        assert_eq!(
            git_file_write_target("git -C /repo --no-pager log -1 --output=/tmp/l.txt").as_deref(),
            Some("/tmp/l.txt")
        );
        assert_eq!(
            git_file_write_target(r#"git diff --output="/tmp/my out.diff""#).as_deref(),
            Some("/tmp/my out.diff")
        );
        // Present but valueless: still a flag to deny on, with no path to
        // report.
        assert_eq!(
            git_file_write_target("git diff --output").as_deref(),
            Some("")
        );
    }

    // #7399 round 2: the short and directory spellings, each verified to write
    // against git 2.54.0.
    #[test]
    fn git_file_write_target_finds_the_short_output_options() {
        for (command, target) in [
            ("git format-patch -o /tmp/d -1 HEAD", "/tmp/d"),
            ("git format-patch -1 -o/tmp/d HEAD", "/tmp/d"),
            (
                "git format-patch --output-directory=/tmp/d -1 HEAD",
                "/tmp/d",
            ),
            (
                "git format-patch --output-directory /tmp/d -1 HEAD",
                "/tmp/d",
            ),
            ("git archive -o /tmp/a.tar HEAD", "/tmp/a.tar"),
            ("git archive -o/tmp/a.tar HEAD", "/tmp/a.tar"),
            ("git archive --output=/tmp/a.tar HEAD", "/tmp/a.tar"),
        ] {
            assert_eq!(
                git_file_write_target(command).as_deref(),
                Some(target),
                "{command}"
            );
        }
        // `-o` is subcommand-scoped: on `diff` it is a revision (git answers
        // `fatal: ambiguous argument`), on `clone` it names the origin remote.
        assert_eq!(git_file_write_target("git diff -o /tmp/o.diff HEAD"), None);
        assert_eq!(
            git_file_write_target("git clone -o upstream https://x/y.git"),
            None
        );
    }

    // #7399 round 2: two writes carry no option at all.
    #[test]
    fn git_file_write_target_reads_format_patch_and_bundle_by_shape() {
        // A `format-patch` writes `NNNN-*.patch` into the working directory
        // unless it was told to write to stdout.
        assert_eq!(
            git_file_write_target("git format-patch -1 HEAD").as_deref(),
            Some("")
        );
        assert_eq!(
            git_file_write_target("git format-patch --stdout -1 HEAD"),
            None
        );
        assert_eq!(
            git_file_write_target("git format-patch -1 HEAD --stdout"),
            None
        );
        // `bundle create` names its output as a positional; `-` is stdout.
        assert_eq!(
            git_file_write_target("git bundle create /tmp/x.bundle HEAD").as_deref(),
            Some("/tmp/x.bundle")
        );
        assert_eq!(
            git_file_write_target("git bundle create -q /tmp/x.bundle --all").as_deref(),
            Some("/tmp/x.bundle")
        );
        assert_eq!(git_file_write_target("git bundle create - HEAD"), None);
        assert_eq!(
            git_file_write_target("git bundle verify /tmp/x.bundle"),
            None
        );
        assert_eq!(
            git_file_write_target("git bundle list-heads /tmp/x.bundle"),
            None
        );
    }

    // #7399: the rule matches the option, never its prefix.
    #[test]
    fn git_file_write_target_ignores_the_indicator_options() {
        for command in [
            "git diff --output-indicator-new=+",
            "git diff --output-indicator-old=- --stat",
            "git diff --output-indicator-context= ",
            "git diff --stat -- docs/",
            "git diff --no-index /tmp/a.txt /tmp/b.txt",
            "git archive --format=tar HEAD",
        ] {
            assert_eq!(git_file_write_target(command), None, "{command}");
        }
    }

    // #7399: past `--`, git parses pathspecs, so `--output=…` writes nothing.
    #[test]
    fn git_file_write_target_stops_at_the_pathspec_separator() {
        assert_eq!(
            git_file_write_target("git diff -- --output=/tmp/o.diff"),
            None
        );
        assert_eq!(
            git_file_write_target("git diff --output=/tmp/o.diff -- docs/").as_deref(),
            Some("/tmp/o.diff")
        );
    }

    // #7399: a segment that will not lex withholds the deny; it never grants
    // an allow that did not already exist.
    #[test]
    fn git_file_write_target_none_when_unbalanced() {
        assert_eq!(
            git_file_write_target("git diff --output='/tmp/o.diff"),
            None
        );
        assert_eq!(
            git_file_write_target("cargo run -- --output=/tmp/o.diff"),
            None
        );
    }
}