amont-agent 2.15.0

A guard that inspects a shell command before Claude Code runs it
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
//! A shell reader that gives rules an argv, not a string.
//!
//! Every false positive this crate is designed to avoid comes from the same
//! mistake: matching a pattern against the raw text of a command. The text of a
//! command contains things that are not the command — a commit message, a
//! `--body` value, a comment, the inside of a `$(…)`, the name of a file being
//! redirected to. A regex cannot tell those apart. Measured against 43,242 real
//! commands, a hand-written regex for one rule was wrong **one time in five**,
//! and the four causes were all this:
//!
//! ```text
//!   292  the match was inside a quoted string
//!   131  the verb and the pipe were in different clauses
//!    99  `git tag --sort=… | head` — the LISTING form, not the mutating one
//!     6  an explicit --dry-run
//! ```
//!
//! So rules never see a string. They see [`Simple`] commands with their words
//! already separated, quoting already resolved, substitutions already blanked,
//! and clause boundaries already drawn. A rule that asks
//! `has_flag("--force")` cannot be answered by the word `--force` sitting
//! inside a commit message, because that word is marked [`Word::quoted`] and
//! `has_flag` skips it.
//!
//! A blanked substitution is not a lost one. The inside of `$(…)`, of
//! backticks and of `<(…)` is a command too, and it is read as clauses of its
//! own — appended after the line's, marked [`Simple::nested`] — so that
//! `$(git push | tail -1)` is the pipe-to-tail it is, and a `stat -f` inside
//! a `$( )` is the BSD spelling it is. The word that holds the substitution
//! stays blank: to the clause around it, the value is still unknowable.
//!
//! The blanking discipline is lifted from
//! amont's `ban_terms::blank_non_code`: blank rather than delete,
//! so byte offsets stay meaningful and a reported span still points at the
//! right part of the original text.
//!
//! ## Not understood means no opinion
//!
//! [`Parsed::Opaque`] is returned for anything this reader cannot claim to
//! understand — an unterminated quote, an unbalanced substitution, `eval`,
//! `sh -c`. Opaque never fires a rule. Guessing at a construct we cannot parse
//! is how a guard learns to be confidently wrong, and a guard that is
//! confidently wrong gets uninstalled.

/// Past this, a "command" is a generated payload rather than something a person
/// or a model composed, and parsing it cannot be worth the time. The largest
/// real command in the corpus was 13 KB.
const MAX_SRC: usize = 256 * 1024;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Connector {
    Pipe,
    AndAnd,
    OrOr,
    Semi,
    Amp,
}

impl Connector {
    /// Does this connector end a *pipeline*? `|` chains a command's output into
    /// the next; everything else starts an unrelated command. The distinction
    /// is the whole of `pipe-to-tail`'s correctness.
    pub fn is_pipe(self) -> bool {
        matches!(self, Connector::Pipe)
    }
}

/// One word of a command, after quoting is resolved.
///
/// `raw`, `expanded` and `at` are part of the lexer's contract rather than of
/// any current rule: `raw` is what a rule ABOUT quoting would read, `expanded`
/// marks a word whose value we cannot know, and `at` is what lets a finding
/// point at the original text. The rule that used `raw` was removed before the
/// first commit (see rules/mod.rs); the fields stay because dropping and
/// re-deriving them is how a lexer quietly loses the ability to explain itself.
#[allow(dead_code)]
#[derive(Debug, Clone)]
pub struct Word {
    /// Quotes removed, substitutions blanked to spaces. What rules match on.
    pub text: String,
    /// Exactly as written, including quotes. Only a rule that is *about*
    /// quoting may read this — `fish-glob` is the one such rule.
    pub raw: String,
    /// Any part of this word sat inside quotes. A quoted word is never a flag.
    pub quoted: bool,
    /// Any part of it came from `$(…)`, backticks or `${…}`.
    pub expanded: bool,
    /// Byte offset of the word's start in the original source.
    pub at: usize,
}

/// A single command: its words, and the connectors on either side of it.
#[derive(Debug, Clone, Default)]
pub struct Simple {
    pub words: Vec<Word>,
    pub prev: Option<Connector>,
    pub next: Option<Connector>,
    /// Redirect targets, deliberately kept OUT of `words` so that
    /// `git push > --force` can never be read as a `--force` flag.
    pub redirects: Vec<(String, Word)>,
    /// The clause carries a `<<TAG` heredoc. The operator and tag are consumed
    /// by the lexer and the body is skipped as data, so nothing else records
    /// that stdin is fed — and `stdin-hang` needs to know.
    pub heredoc: bool,
    /// Byte range of this clause within the original source.
    pub at: usize,
    pub end: usize,
    /// This clause ran inside a command substitution — `$(…)`, backticks,
    /// `<(…)` — and this is the byte offset of the substitution that holds
    /// it, in the original source. `None` for a clause of the line itself.
    ///
    /// A substitution is a subshell: what it prints goes to the shell, not
    /// to the tool result, and a `cd` inside it moves nothing outside it.
    /// The two places that care — `dump` and `cwd_at` — read this; every
    /// other rule judges a nested clause as it would any other, because
    /// `$(git push | tail -1)` hides a failed push exactly as the bare form
    /// does. Measured before this field existed: a `stat -f` inside `$( )`
    /// was invisible to the rule whose own header uses it as the example.
    pub nested: Option<usize>,
    /// Why this clause could not be read, when it could not.
    ///
    /// Marked in place rather than removed, and marked across the WHOLE
    /// pipeline the unreadable clause sits in. Removing it would be the one
    /// mistake this crate must never make: in
    /// `git push origin main | xargs -0 foo | tail -2`, dropping the `xargs`
    /// leaves `git push`'s `next` still saying `Pipe` while the next element
    /// is now `tail` — inventing a `git push | tail` in the only rule that
    /// refuses. Keeping every clause keeps `prev`, `next` and every
    /// positional walk true.
    pub opaque: Option<Opaque>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Opaque {
    UnterminatedQuote,
    UnterminatedSubstitution,
    UnterminatedHeredoc,
    IndirectExecution(&'static str),
    TooLong,
}

impl Opaque {
    pub fn why(&self) -> String {
        match self {
            Opaque::UnterminatedQuote => "an unterminated quote".into(),
            Opaque::UnterminatedSubstitution => "an unbalanced substitution".into(),
            Opaque::UnterminatedHeredoc => "a heredoc with no terminator".into(),
            Opaque::IndirectExecution(w) => format!("`{w}` runs a command we cannot read"),
            Opaque::TooLong => "a command too large to read".into(),
        }
    }
}

#[derive(Debug, Clone)]
pub enum Parsed {
    Clear(Vec<Simple>),
    Opaque(Opaque),
}

impl Parsed {
    /// Every clause, readable or not.
    ///
    /// The truth about what RAN. `cwd_at` and `path-operand-missing`'s
    /// `excused` want this: a `cd` or a directory-creating clause counts
    /// whether or not we understood it.
    pub fn clauses(&self) -> &[Simple] {
        match self {
            Parsed::Clear(c) => c,
            Parsed::Opaque(_) => &[],
        }
    }

    /// The clauses a rule may have an opinion about.
    ///
    /// The truth about what we UNDERSTOOD. Every rule wants this.
    pub fn judgeable(&self) -> impl Iterator<Item = &Simple> {
        self.clauses().iter().filter(|c| c.opaque.is_none())
    }

    /// The pipelines that were not read, if any.
    pub fn hidden(&self) -> impl Iterator<Item = &Simple> {
        self.clauses().iter().filter(|c| c.opaque.is_some())
    }

    /// Was the whole command read? False when a pipeline was skipped.
    ///
    /// Anything that acts BEYOND the command in front of it — an assertion
    /// about the world, a write to session state — must ask this first. A
    /// half-read command is not grounds for either.
    pub fn fully_read(&self) -> bool {
        matches!(self, Parsed::Clear(c) if c.iter().all(|s| s.opaque.is_none()))
    }
}

/// Commands whose arguments are themselves a program we would have to be a
/// shell to read, and which run in THIS shell.
///
/// They can `cd`, export, and rewrite the environment every later clause on
/// the line depends on, so one of them makes the whole command unreadable —
/// not because we cannot parse what follows, but because we no longer know
/// where it runs. `cwd_at` and every `confirm` that resolves a path depend
/// on that.
const INDIRECT_IN_PROCESS: &[&str] = &["eval", "source", "."];
/// The same problem in a child process. `xargs` and `sh -c` cannot move this
/// shell or touch its environment, so only their own pipeline is unreadable.
const INDIRECT_FORKING: &[&str] = &["xargs"];
/// These are only indirect when handed `-c`; `bash script.sh` is readable.
const SHELLS: &[&str] = &["sh", "bash", "zsh", "fish", "dash", "ksh"];

struct Build {
    text: Vec<u8>,
    raw: Vec<u8>,
    quoted: bool,
    expanded: bool,
    at: usize,
}

impl Build {
    fn new(at: usize) -> Self {
        Build {
            text: Vec::new(),
            raw: Vec::new(),
            quoted: false,
            expanded: false,
            at,
        }
    }
    fn finish(self) -> Option<Word> {
        if self.raw.is_empty() {
            return None;
        }
        Some(Word {
            text: String::from_utf8(self.text).ok()?,
            raw: String::from_utf8(self.raw).ok()?,
            quoted: self.quoted,
            expanded: self.expanded,
            at: self.at,
        })
    }
}

/// Read a shell command into clauses.
pub fn lex(src: &str) -> Parsed {
    if src.len() > MAX_SRC {
        return Parsed::Opaque(Opaque::TooLong);
    }
    let b = src.as_bytes();
    let n = b.len();
    let mut i = 0usize;

    let mut out: Vec<Simple> = Vec::new();
    let mut cur = Simple {
        at: 0,
        ..Default::default()
    };
    let mut word: Option<Build> = None;
    let mut redirect: Option<String> = None;
    // Heredoc tags awaiting their body, which begins at the next newline.
    let mut heredocs: Vec<Vec<u8>> = Vec::new();
    // Command substitutions met on the way: (offset of the opener, inner
    // byte range). Their insides are read as clauses of their own once the
    // line is done — see the end of this function.
    let mut subs: Vec<(usize, std::ops::Range<usize>)> = Vec::new();

    macro_rules! end_word {
        () => {
            if let Some(w) = word.take() {
                if let Some(w) = w.finish() {
                    match redirect.take() {
                        Some(op) => cur.redirects.push((op, w)),
                        None => cur.words.push(w),
                    }
                }
            }
        };
    }

    macro_rules! end_clause {
        ($conn:expr, $at:expr) => {{
            end_word!();
            cur.end = $at;
            if !cur.words.is_empty() || !cur.redirects.is_empty() {
                cur.next = $conn;
                let prev = $conn;
                out.push(std::mem::take(&mut cur));
                cur.prev = prev;
            } else {
                cur.prev = $conn;
            }
            cur.at = $at;
        }};
    }

    while i < n {
        let c = b[i];

        // A comment runs to end of line, but only where a word could start.
        if c == b'#' && word.is_none() {
            while i < n && b[i] != b'\n' {
                i += 1;
            }
            continue;
        }

        match c {
            b'\'' => {
                let w = word.get_or_insert_with(|| Build::new(i));
                w.quoted = true;
                w.raw.push(c);
                i += 1;
                let start = i;
                while i < n && b[i] != b'\'' {
                    i += 1;
                }
                if i >= n {
                    return Parsed::Opaque(Opaque::UnterminatedQuote);
                }
                w.text.extend_from_slice(&b[start..i]);
                w.raw.extend_from_slice(&b[start..i]);
                w.raw.push(b'\'');
                i += 1;
            }
            b'"' => {
                let w = word.get_or_insert_with(|| Build::new(i));
                w.quoted = true;
                w.raw.push(c);
                i += 1;
                let mut closed = false;
                while i < n {
                    match b[i] {
                        b'"' => {
                            closed = true;
                            w.raw.push(b'"');
                            i += 1;
                            break;
                        }
                        b'\\' if i + 1 < n => {
                            w.raw.push(b'\\');
                            w.raw.push(b[i + 1]);
                            w.text.push(b[i + 1]);
                            i += 2;
                        }
                        b'$' if i + 1 < n && b[i + 1] == b'(' => {
                            let Some(close) = balanced(b, i + 1, b'(', b')') else {
                                return Parsed::Opaque(Opaque::UnterminatedSubstitution);
                            };
                            w.expanded = true;
                            w.raw.extend_from_slice(&b[i..=close]);
                            w.text.extend(std::iter::repeat_n(b' ', close - i + 1));
                            subs.push((i, i + 2..close));
                            i = close + 1;
                        }
                        other => {
                            w.raw.push(other);
                            w.text.push(other);
                            i += 1;
                        }
                    }
                }
                if !closed {
                    return Parsed::Opaque(Opaque::UnterminatedQuote);
                }
            }
            b'\\' if i + 1 < n => {
                let w = word.get_or_insert_with(|| Build::new(i));
                // An escaped newline is a line continuation, not a word.
                if b[i + 1] == b'\n' {
                    i += 2;
                    continue;
                }
                w.quoted = true;
                w.raw.push(b'\\');
                w.raw.push(b[i + 1]);
                w.text.push(b[i + 1]);
                i += 2;
            }
            b'`' => {
                let w = word.get_or_insert_with(|| Build::new(i));
                let mut j = i + 1;
                while j < n && b[j] != b'`' {
                    j += 1;
                }
                if j >= n {
                    return Parsed::Opaque(Opaque::UnterminatedSubstitution);
                }
                w.expanded = true;
                w.raw.extend_from_slice(&b[i..=j]);
                w.text.extend(std::iter::repeat_n(b' ', j - i + 1));
                subs.push((i, i + 1..j));
                i = j + 1;
            }
            b'$' if i + 1 < n && (b[i + 1] == b'(' || b[i + 1] == b'{') => {
                let (open, close) = if b[i + 1] == b'(' {
                    (b'(', b')')
                } else {
                    (b'{', b'}')
                };
                let Some(end) = balanced(b, i + 1, open, close) else {
                    return Parsed::Opaque(Opaque::UnterminatedSubstitution);
                };
                let w = word.get_or_insert_with(|| Build::new(i));
                w.expanded = true;
                w.raw.extend_from_slice(&b[i..=end]);
                w.text.extend(std::iter::repeat_n(b' ', end - i + 1));
                // `${…}` is a parameter, not a command.
                if open == b'(' {
                    subs.push((i, i + 2..end));
                }
                i = end + 1;
            }
            b'<' if i + 2 < n && b[i + 1] == b'<' && b[i + 2] == b'<' => {
                // A here-string: `bc <<< '1+1'`. Read as a heredoc this was an
                // "unterminated heredoc", which made the whole command opaque
                // to every rule. It is a redirect whose target is the next
                // word, and it feeds stdin.
                end_word!();
                redirect = Some("<<<".into());
                i += 3;
            }
            b'<' if i + 1 < n && b[i + 1] == b'<' => {
                // A heredoc. The BODY is data and starts on the next line, but
                // the rest of THIS line is still command — `git commit -F-
                // <<'MSG' 2>&1 | tail -8` is a real pipe-to-tail, and treating
                // the whole command as opaque from the operator onward hid 89
                // true positives when measured. Read the operator's line; skip
                // the body at the newline.
                end_word!();
                i += 2;
                if i < n && b[i] == b'-' {
                    i += 1;
                }
                while i < n && (b[i] == b' ' || b[i] == b'\t') {
                    i += 1;
                }
                let mut tag = Vec::new();
                while i < n
                    && (b[i].is_ascii_alphanumeric()
                        || b[i] == b'_'
                        || b[i] == b'\''
                        || b[i] == b'"')
                {
                    if b[i] != b'\'' && b[i] != b'"' {
                        tag.push(b[i]);
                    }
                    i += 1;
                }
                cur.heredoc = true;
                heredocs.push(tag);
            }
            b'>' | b'<' => {
                end_word!();
                let start = i;
                i += 1;
                if i < n && b[i] == b'>' {
                    i += 1;
                }
                // `2>&1` / `>&2`: the `&N` belongs to the redirect, not to a
                // following clause. Consume it here so `&` is not read as a
                // background operator.
                if i < n && b[i] == b'&' {
                    i += 1;
                    while i < n && (b[i].is_ascii_digit() || b[i] == b'-') {
                        i += 1;
                    }
                    cur.redirects.push((
                        String::from_utf8_lossy(&b[start..i]).into_owned(),
                        Word {
                            text: String::new(),
                            raw: String::new(),
                            quoted: false,
                            expanded: false,
                            at: start,
                        },
                    ));
                    continue;
                }
                let op = String::from_utf8_lossy(&b[start..i]).into_owned();
                // A process substitution as the target — `< <(sort a)`,
                // `cat <(cmd)`: the balanced `(…)` is one expanded word. Left
                // to the grouping branch, `(` ended the clause and the redirect
                // was lost, which read `cmd < <(…)` as a command fed by nothing.
                let mut j = i;
                while j < n && (b[j] == b' ' || b[j] == b'\t') {
                    j += 1;
                }
                if j < n && b[j] == b'(' {
                    if let Some(close) = balanced(b, j, b'(', b')') {
                        cur.redirects.push((
                            op,
                            Word {
                                text: " ".repeat(close - j + 1),
                                raw: String::from_utf8_lossy(&b[j..=close]).into_owned(),
                                quoted: false,
                                expanded: true,
                                at: j,
                            },
                        ));
                        subs.push((j, j + 1..close));
                        i = close + 1;
                        continue;
                    }
                }
                redirect = Some(op);
            }
            b'0'..=b'9'
                if word.is_none()
                    && i + 1 < n
                    && (b[i + 1] == b'>' || b[i + 1] == b'<')
                    && !matches!(b.get(i + 2), Some(b'<')) =>
            {
                // A file-descriptor prefix on a redirect: `2>`, `2>>`.
                let start = i;
                i += 1;
                i += 1;
                if i < n && b[i] == b'>' {
                    i += 1;
                }
                if i < n && b[i] == b'&' {
                    i += 1;
                    while i < n && (b[i].is_ascii_digit() || b[i] == b'-') {
                        i += 1;
                    }
                    cur.redirects.push((
                        String::from_utf8_lossy(&b[start..i]).into_owned(),
                        Word {
                            text: String::new(),
                            raw: String::new(),
                            quoted: false,
                            expanded: false,
                            at: start,
                        },
                    ));
                    continue;
                }
                redirect = Some(String::from_utf8_lossy(&b[start..i]).into_owned());
            }
            b'|' => {
                let conn = if i + 1 < n && b[i + 1] == b'|' {
                    i += 2;
                    Connector::OrOr
                } else {
                    // `|&` pipes stderr too; it is still a pipe.
                    i += 1;
                    if i < n && b[i] == b'&' {
                        i += 1;
                    }
                    Connector::Pipe
                };
                end_clause!(Some(conn), i);
            }
            b'&' => {
                let conn = if i + 1 < n && b[i + 1] == b'&' {
                    i += 2;
                    Connector::AndAnd
                } else {
                    i += 1;
                    Connector::Amp
                };
                end_clause!(Some(conn), i);
            }
            b';' => {
                i += 1;
                end_clause!(Some(Connector::Semi), i);
            }
            b'\n' => {
                i += 1;
                end_clause!(Some(Connector::Semi), i);
                // The heredoc bodies queued on the previous line start here.
                while let Some(tag) = heredocs.first().cloned() {
                    heredocs.remove(0);
                    match find_terminator(b, i, &tag) {
                        Some(next) => i = next,
                        None => return Parsed::Opaque(Opaque::UnterminatedHeredoc),
                    }
                }
            }
            b'(' | b')' | b'{' | b'}' if word.is_none() => {
                // Grouping, and only when it STARTS a word: `{ cmd; }`, `(sub)`.
                // None of the rules need its semantics, and descending flat can
                // only ever LOSE a fire, never invent one.
                end_clause!(None, i);
                i += 1;
            }
            b'{' | b'}' => {
                // A brace ATTACHED to a word belongs to that word: `stash@{2}`,
                // `HEAD@{1}`, `refs/stash@{0}`. Ending the clause here truncated
                // the word to `stash@` and INVENTED a fire in bare-stash-pop —
                // the one thing the branch above promises never to do.
                let w = word.get_or_insert_with(|| Build::new(i));
                w.raw.push(b[i]);
                w.text.push(b[i]);
                i += 1;
            }
            b' ' | b'\t' | b'\r' => {
                end_word!();
                i += 1;
            }
            other => {
                let w = word.get_or_insert_with(|| Build::new(i));
                w.raw.push(other);
                w.text.push(other);
                i += 1;
            }
        }
    }
    if !heredocs.is_empty() {
        return Parsed::Opaque(Opaque::UnterminatedHeredoc);
    }
    end_clause!(None, n);

    // One clause that could move this shell makes the whole line unreadable.
    for cmd in &out {
        if let Some(why) = indirect_in_process(cmd) {
            return Parsed::Opaque(Opaque::IndirectExecution(why));
        }
    }
    let mut parsed = hide_forking_pipelines(out);
    if let Parsed::Clear(clauses) = &mut parsed {
        for (opener, inner) in subs {
            read_substitution(src, opener, inner, clauses);
        }
    }
    parsed
}

/// Read the inside of one command substitution as clauses of its own, and
/// append them — AFTER every clause of the line, never between two of them.
///
/// Appended, not interleaved: `pipe-to-tail` walks from a clause whose
/// `next` is a pipe to the element that follows it in this list, and a
/// substitution sitting inside `git push $(…) | tail -1` would otherwise
/// land between the push and the `tail`, inventing a gap where the pipe is.
/// Every offset is shifted into the original source, so a finding's span and
/// `cwd_at` still point at the right bytes; a nested substitution inside this
/// one has already been shifted into `inner` by the recursive read and is
/// shifted once more here.
///
/// An inside this reader cannot claim to understand — `$(eval …)`, an
/// unbalanced quote — adds nothing: the word stays blank, as it was before
/// substitutions were read at all. Descending can only lose a fire, never
/// invent one, and the line around it is judged as it always was. The one
/// thing a substitution cannot do is move THIS shell, so an `eval` inside it
/// is not the in-process opacity it would be on the line.
fn read_substitution(
    src: &str,
    opener: usize,
    inner: std::ops::Range<usize>,
    clauses: &mut Vec<Simple>,
) {
    let Some(text) = src.get(inner.clone()) else {
        return;
    };
    let Parsed::Clear(found) = lex(text) else {
        return;
    };
    let shift = inner.start;
    for mut cmd in found {
        cmd.at += shift;
        cmd.end += shift;
        for w in &mut cmd.words {
            w.at += shift;
        }
        for (_, w) in &mut cmd.redirects {
            w.at += shift;
        }
        cmd.nested = Some(match cmd.nested {
            Some(deeper) => deeper + shift,
            None => opener,
        });
        clauses.push(cmd);
    }
}

/// Mark the pipelines we cannot read; leave the rest to be judged.
///
/// The unit is the PIPELINE, not the line. `|` chains one command's output
/// into the next, so a stage we cannot read makes the whole run unreadable —
/// we do not know what reached the sink, and that is exactly `pipe-to-tail`'s
/// question. `&&`, `||` and `;` start a command as independent of an
/// unreadable neighbour as of any other clause, and treating the whole line as
/// opaque cost every rule on it: measured over 33,638 real commands, 262 had a
/// readable pipeline thrown away, 218 of them beside a `sh -c` or an `xargs`.
fn hide_forking_pipelines(mut out: Vec<Simple>) -> Parsed {
    let mut i = 0;
    while i < out.len() {
        // The pipeline running from `i`: a clause whose `next` is a pipe is
        // never the last of its run.
        let mut end = i;
        while end + 1 < out.len() && out[end].next.is_some_and(Connector::is_pipe) {
            end += 1;
        }
        if let Some(why) = out[i..=end].iter().find_map(indirect_forking) {
            for cmd in &mut out[i..=end] {
                cmd.opaque = Some(Opaque::IndirectExecution(why));
            }
        }
        i = end + 1;
    }
    // Nothing survived: this is the old whole-command opacity, and every
    // caller that stayed silent before stays silent now.
    if let Some(why) = out
        .iter()
        .all(|c| c.opaque.is_some())
        .then(|| out.first().and_then(|c| c.opaque.clone()))
        .flatten()
    {
        return Parsed::Opaque(why);
    }
    Parsed::Clear(out)
}

/// Runs a command we cannot read, in THIS shell.
fn indirect_in_process(cmd: &Simple) -> Option<&'static str> {
    let p = cmd.program()?;
    INDIRECT_IN_PROCESS.iter().find(|k| **k == p).copied()
}

/// Runs a command we cannot read, in a child.
fn indirect_forking(cmd: &Simple) -> Option<&'static str> {
    let p = cmd.program()?;
    if let Some(hit) = INDIRECT_FORKING.iter().find(|k| **k == p) {
        return Some(hit);
    }
    if SHELLS.contains(&p) && cmd.has_flag("-c") {
        return SHELLS.iter().find(|s| **s == p).copied();
    }
    None
}

/// The index of the byte closing a run opened at `from`, honouring nesting.
fn balanced(b: &[u8], from: usize, open: u8, close: u8) -> Option<usize> {
    let mut depth = 0usize;
    let mut i = from;
    while i < b.len() {
        if b[i] == open {
            depth += 1;
        } else if b[i] == close {
            depth -= 1;
            if depth == 0 {
                return Some(i);
            }
        }
        i += 1;
    }
    None
}

/// Index just past the heredoc terminator line starting the search at `from`.
fn find_terminator(b: &[u8], from: usize, tag: &[u8]) -> Option<usize> {
    let mut line = from;
    while line <= b.len() {
        let end = b[line..]
            .iter()
            .position(|&c| c == b'\n')
            .map(|p| line + p)
            .unwrap_or(b.len());
        let trimmed: &[u8] = {
            let s = &b[line..end];
            let a = s.iter().position(|c| !c.is_ascii_whitespace()).unwrap_or(0);
            let z = s
                .iter()
                .rposition(|c| !c.is_ascii_whitespace())
                .map(|p| p + 1)
                .unwrap_or(a);
            &s[a..z]
        };
        if trimmed == tag {
            return Some(if end < b.len() { end + 1 } else { b.len() });
        }
        if end >= b.len() {
            return None;
        }
        line = end + 1;
    }
    None
}

/// Wrappers that stand in front of the real program without changing what it
/// is. `sudo git push` is a `git push`.
const WRAPPERS: &[&str] = &[
    "sudo", "command", "builtin", "nice", "time", "timeout", "env",
];

/// `90`, `1.5m`, `30s` — what `timeout` and `nice` take before the program.
/// A unit suffix is optional and singular; `git` and `main` are not durations.
fn is_duration(t: &str) -> bool {
    let body = t.strip_suffix(['s', 'm', 'h', 'd']).unwrap_or(t);
    !body.is_empty() && body.bytes().all(|c| c.is_ascii_digit() || c == b'.')
}

/// git's own options, which sit before the subcommand.
const GIT_GLOBAL_VALUED: &[&str] = &["-C", "-c", "--git-dir", "--work-tree", "--exec-path"];
const GIT_GLOBAL_BARE: &[&str] = &[
    "--no-pager",
    "--paginate",
    "-p",
    "--bare",
    "--literal-pathspecs",
];

impl Simple {
    /// argv0, with leading `VAR=value` assignments and wrapper commands peeled
    /// off. Returns `None` when the command is only assignments or is empty.
    pub fn program(&self) -> Option<&str> {
        self.program_at().map(|(_, t)| t)
    }

    /// The same answer with its INDEX, which is what every caller that needs
    /// to read past the program actually wants.
    ///
    /// Derived together rather than re-found by name: searching the words for
    /// the first one equal to the program name finds the wrong occurrence
    /// whenever the name appears earlier as somebody's argument — `sudo -u git
    /// git push` is the honest example — and a wrong program index is a wrong
    /// subcommand, which is a wrong rule.
    fn program_at(&self) -> Option<(usize, &str)> {
        let mut idx = 0;
        loop {
            let w = self.words.get(idx)?;
            let t = w.text.as_str();
            // `FOO=1 git push` is a `git push`.
            if !w.quoted && t.contains('=') && !t.starts_with('-') {
                let name = &t[..t.find('=').unwrap()];
                if !name.is_empty() && name.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'_')
                {
                    idx += 1;
                    continue;
                }
            }
            if !w.quoted && WRAPPERS.contains(&t) {
                idx = self.past_wrapper_args(t, idx + 1);
                continue;
            }
            return Some((idx, t));
        }
    }

    /// Index of the first word after `wrapper`'s OWN options.
    ///
    /// Without this, `nice -n 10 git push` had a program of `-n`: only bare
    /// numeric arguments were skipped, so the flag stopped the walk and every
    /// rule keyed on `git` went silent. Same for `sudo -u root git push`,
    /// `timeout -k 5 90 git push` and `env -i git push` — the ordinary
    /// spellings of three of the six wrappers this table exists to see past.
    ///
    /// Unknown options are skipped: a program name never starts with `-`, so
    /// a flag we do not recognise cannot be the thing we are looking for. The
    /// per-wrapper lists below are only for the options that take a SEPARATE
    /// value, since that value is the one word in the run that does not
    /// announce itself with a dash.
    fn past_wrapper_args(&self, wrapper: &str, mut idx: usize) -> usize {
        let valued: &[&str] = match wrapper {
            "sudo" => &[
                "-u",
                "--user",
                "-g",
                "--group",
                "-p",
                "--prompt",
                "-C",
                "--close-from",
                "-h",
                "--host",
                "-R",
                "--chroot",
                "-D",
                "--chdir",
                "-T",
                "--command-timeout",
                "-U",
                "--other-user",
                "-r",
                "--role",
                "-t",
                "--type",
            ],
            "env" => &["-u", "--unset", "-C", "--chdir", "-S", "--split-string"],
            "timeout" => &["-k", "--kill-after", "-s", "--signal"],
            "nice" => &["-n", "--adjustment"],
            "time" => &["-o", "--output", "-f", "--format"],
            _ => &[],
        };
        while let Some(w) = self.words.get(idx) {
            let t = w.text.as_str();
            // A quoted word is never a flag — the same rule `has_flag` obeys.
            if w.quoted || !t.starts_with('-') || t.len() < 2 {
                break;
            }
            if t == "--" {
                return idx + 1;
            }
            idx += 1;
            // `--flag=value` carries its value; `--flag value` takes the next
            // word, which would otherwise read as the program.
            if !t.contains('=') && valued.contains(&t) {
                idx += 1;
            }
        }
        // `timeout 90 …` and `nice 10 …` take a bare operand of their own.
        if matches!(wrapper, "timeout" | "nice") {
            while self
                .words
                .get(idx)
                .is_some_and(|w| !w.quoted && is_duration(&w.text))
            {
                idx += 1;
            }
        }
        idx
    }

    /// Where [`Self::program`] sits in `words`.
    ///
    /// `pub(crate)` because a rule that needs to read past the program must
    /// ask for this rather than re-derive it: `position(|w| w.text == program)`
    /// finds the wrong occurrence whenever the name appears earlier as
    /// somebody's argument, which is exactly how `kubectl-gitops` came to miss
    /// `sudo -u kubectl kubectl apply`.
    pub(crate) fn program_index(&self) -> Option<usize> {
        self.program_at().map(|(i, _)| i)
    }

    /// The first operand after the program, skipping the program's own global
    /// options. An UNKNOWN leading `-x` yields `None` — giving up is the safe
    /// direction, because a wrong subcommand is a wrong rule.
    pub fn subcommand(&self) -> Option<&str> {
        let mut idx = self.program_index()? + 1;
        while let Some(w) = self.words.get(idx) {
            let t = w.text.as_str();
            if !t.starts_with('-') {
                return Some(t);
            }
            if GIT_GLOBAL_BARE.contains(&t) {
                idx += 1;
                continue;
            }
            if let Some(flag) = GIT_GLOBAL_VALUED.iter().find(|f| t == **f) {
                let _ = flag;
                idx += 2;
                continue;
            }
            if GIT_GLOBAL_VALUED
                .iter()
                .any(|f| t.starts_with(&format!("{f}=")))
            {
                idx += 1;
                continue;
            }
            return None;
        }
        None
    }

    /// The words that are the PROGRAM'S arguments — everything after argv0.
    ///
    /// A wrapper's flags belong to the wrapper, not to what it runs, and
    /// every accessor below reads this rather than `words`. Without it,
    /// `nice -n 10 git push | tail -2` was silent: `has_short('n')` found
    /// nice's `-n`, `pipe-to-tail` read it as `git push -n`, and a dry run
    /// disarms every rule that is about mutation. `sudo -n` (non-interactive)
    /// and `timeout -s KILL` are the same shape.
    ///
    /// Empty when there is no program at all — a clause of only assignments
    /// has no flags to ask about.
    pub fn args(&self) -> &[Word] {
        match self.program_index() {
            Some(i) => self.words.get(i + 1..).unwrap_or_default(),
            None => &[],
        }
    }

    /// Whole-token flag test. Stops at `--`, and **skips quoted words** — which
    /// is the single highest-leverage precision decision in this crate. It is
    /// what makes `gh pr create --body "…use --auto…"` not a `--auto`.
    pub fn has_flag(&self, flag: &str) -> bool {
        for w in self.args() {
            if !w.quoted && w.text == "--" {
                return false;
            }
            if w.quoted {
                continue;
            }
            if w.text == flag {
                return true;
            }
        }
        false
    }

    /// A letter inside a short cluster: `-Au` contains `u`. Stops at `--`.
    pub fn has_short(&self, c: char) -> bool {
        for w in self.args() {
            if !w.quoted && w.text == "--" {
                return false;
            }
            if w.quoted || w.text.len() < 2 {
                continue;
            }
            let t = w.text.as_str();
            if t.starts_with('-') && !t.starts_with("--") && t[1..].contains(c) {
                return true;
            }
        }
        false
    }

    /// `--flag=value` or `--flag value`.
    #[allow(dead_code)]
    pub fn flag_value(&self, flag: &str) -> Option<&str> {
        let eq = format!("{flag}=");
        let args = self.args();
        for (i, w) in args.iter().enumerate() {
            if !w.quoted && w.text == "--" {
                return None;
            }
            if w.quoted {
                continue;
            }
            if let Some(v) = w.text.strip_prefix(&eq) {
                return Some(v);
            }
            if w.text == flag {
                return args.get(i + 1).map(|w| w.text.as_str());
            }
        }
        None
    }

    /// Non-flag words after the program, plus everything after `--`.
    pub fn operands(&self) -> Vec<&Word> {
        let Some(start) = self.program_index() else {
            return Vec::new();
        };
        let mut out = Vec::new();
        let mut after_ddash = false;
        for w in self.words.iter().skip(start + 1) {
            if !w.quoted && w.text == "--" {
                after_ddash = true;
                continue;
            }
            if after_ddash || !w.text.starts_with('-') {
                out.push(w);
            }
        }
        out
    }

    /// Any form of `--dry-run`. A dry run mutates nothing, so it disarms every
    /// rule that is about mutation.
    pub fn is_dry_run(&self) -> bool {
        self.args()
            .iter()
            .any(|w| !w.quoted && (w.text == "--dry-run" || w.text.starts_with("--dry-run=")))
    }
}

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

    fn clauses(src: &str) -> Vec<Simple> {
        match lex(src) {
            Parsed::Clear(c) => c,
            Parsed::Opaque(o) => panic!("expected a readable command, got {o:?}"),
        }
    }

    fn opaque(src: &str) -> Opaque {
        match lex(src) {
            Parsed::Opaque(o) => o,
            Parsed::Clear(_) => panic!("expected opacity"),
        }
    }

    /// The single most common false positive in the corpus: 292 of 501 measured
    /// misfires were a pattern sitting inside a quoted string. An operator
    /// inside quotes is text, and a word built from quoted text is never a flag.
    #[test]
    fn quotes_hide_operators_and_flags() {
        let c = clauses(r#"pkill -f "git push origin v1 | tail""#);
        assert_eq!(c.len(), 1, "the quoted pipe must not split the command");
        assert_eq!(c[0].program(), Some("pkill"));

        let c = clauses(r#"gh pr create --body "use --auto here""#);
        assert!(!c[0].has_flag("--auto"), "a quoted --auto is not a flag");
        assert!(c[0].has_flag("--body"), "an unquoted flag still is one");
    }

    /// `&&` and `;` start unrelated commands. 131 measured misfires were a verb
    /// in one clause and a pipe in another, which reads as plausible and is
    /// wrong.
    #[test]
    fn a_connector_starts_a_new_command() {
        let c = clauses("git push origin main && echo done | tail -1");
        assert_eq!(c.len(), 3);
        assert_eq!(c[0].program(), Some("git"));
        assert_eq!(c[0].next, Some(Connector::AndAnd));
        assert_eq!(c[1].program(), Some("echo"));
        assert_eq!(c[1].next, Some(Connector::Pipe));
        assert_eq!(c[2].program(), Some("tail"));
    }

    /// A pipe chains one command's output into the next; every other connector
    /// does not. `pipe-to-tail`'s entire correctness rests on the difference.
    #[test]
    fn only_a_pipe_is_a_pipe() {
        assert!(Connector::Pipe.is_pipe());
        for c in [
            Connector::AndAnd,
            Connector::OrOr,
            Connector::Semi,
            Connector::Amp,
        ] {
            assert!(!c.is_pipe(), "{c:?} is not a pipe");
        }
        // `|&` pipes stderr too, and is still a pipe.
        let c = clauses("git push |& tail -2");
        assert_eq!(c[0].next, Some(Connector::Pipe));
    }

    /// The heredoc BODY is data; the rest of the operator's own line is still
    /// command. Blanking from the operator instead of from the newline swallows
    /// `2>&1 | tail -8` and silently hid 89 true positives when measured.
    #[test]
    fn a_heredoc_body_is_data_but_its_own_line_is_not() {
        let c = clauses("git commit -F- <<'MSG' 2>&1 | tail -8\nsubject\nMSG\n");
        assert_eq!(c[0].program(), Some("git"));
        assert_eq!(c[0].subcommand(), Some("commit"));
        assert_eq!(
            c[0].next,
            Some(Connector::Pipe),
            "the pipe survives the heredoc"
        );
        assert!(
            c.iter().all(|s| s.program() != Some("subject")),
            "the body must not be read as commands"
        );
    }

    /// A heredoc we cannot find the end of means the rest of the text is of
    /// unknown kind. Guessing there is how a guard becomes confidently wrong.
    #[test]
    fn an_unterminated_heredoc_is_not_an_opinion() {
        assert_eq!(
            opaque("git commit -F- <<'MSG'\nbody\n"),
            Opaque::UnterminatedHeredoc
        );
    }

    #[test]
    fn an_unterminated_quote_is_not_an_opinion() {
        assert_eq!(opaque("git push \"origin"), Opaque::UnterminatedQuote);
        assert_eq!(opaque("git push 'origin"), Opaque::UnterminatedQuote);
    }

    /// We would have to BE a shell to know what `eval` runs.
    #[test]
    fn indirect_execution_is_not_inspected() {
        assert!(matches!(
            opaque("eval \"$cmd\""),
            Opaque::IndirectExecution(_)
        ));
        assert!(matches!(
            opaque("sh -c 'git push | tail'"),
            Opaque::IndirectExecution(_)
        ));
        // A shell running a FILE is readable; only `-c` hides a command.
        assert_eq!(clauses("bash deploy.sh")[0].program(), Some("bash"));
    }

    /// A pipeline we cannot read costs us that pipeline, not the line.
    #[test]
    fn opacity_is_per_pipeline_not_per_line() {
        let src = "cd /r && git status -s | xargs git add && git commit -m x 2>&1 | tail -1";
        let c = clauses(src);
        let programs: Vec<Option<&str>> = c.iter().map(|s| s.program()).collect();
        assert_eq!(
            programs,
            vec![
                Some("cd"),
                Some("git"),
                Some("xargs"),
                Some("git"),
                Some("tail")
            ],
            "every clause is kept, readable or not"
        );
        let unread: Vec<Option<&str>> = c
            .iter()
            .filter(|s| s.opaque.is_some())
            .map(|s| s.program())
            .collect();
        assert_eq!(
            unread,
            vec![Some("git"), Some("xargs")],
            "the WHOLE pipeline the xargs sits in is marked, and nothing else"
        );
    }

    /// The invariant that makes dropping unnecessary: a pipe never points at a
    /// clause from some other run, because whole pipelines are marked together.
    #[test]
    fn a_pipe_never_crosses_into_a_pipeline_we_could_not_read() {
        for src in [
            "cd /r && git status -s | xargs git add && git commit -m x 2>&1 | tail -1",
            "a | xargs b && c | tail -1",
            "git push | xargs -0 foo | tail -2 && ls",
        ] {
            let c = clauses(src);
            for (i, cmd) in c.iter().enumerate() {
                if cmd.next.is_some_and(Connector::is_pipe) {
                    assert_eq!(
                        cmd.opaque.is_some(),
                        c[i + 1].opaque.is_some(),
                        "a pipe joins two clauses of different readability in {src:?}"
                    );
                }
            }
        }
    }

    /// Nothing readable survived, so this is the whole-command opacity it
    /// always was — and every caller that stayed silent stays silent.
    #[test]
    fn a_command_that_is_all_indirect_is_still_wholly_opaque() {
        for src in [
            "git status --short | xargs git add",
            "eval \"$cmd\"",
            "sh -c 'git push | tail'",
        ] {
            assert!(matches!(opaque(src), Opaque::IndirectExecution(_)), "{src}");
        }
    }

    /// `eval`, `source` and `.` run in THIS shell, so they can move it. The
    /// line stays wholly opaque rather than judging clauses whose directory we
    /// can no longer vouch for.
    #[test]
    fn an_in_process_indirect_still_hides_the_whole_line() {
        for src in [
            "source setup.sh && cat data.txt",
            ". ./.env && kubectl apply -f x.yaml",
            "eval \"$(direnv export bash)\" && git push | tail -1",
        ] {
            assert!(matches!(opaque(src), Opaque::IndirectExecution(_)), "{src}");
        }
    }

    /// A substitution's contents are blanked, not deleted, so byte offsets into
    /// the original text stay meaningful for a reported span.
    #[test]
    fn a_substitution_is_blanked_and_the_word_keeps_its_length() {
        let c = clauses("echo $(git push | tail -1)");
        let w = &c[0].words[1];
        assert!(w.expanded);
        assert_eq!(w.text.len(), w.raw.len(), "blanking preserves length");
        assert!(w.text.trim().is_empty());
        assert_eq!(c[0].next, None, "the pipe inside is not the echo's pipe");
    }

    /// The inside of a substitution is a command, read as clauses of its own:
    /// after the line's clauses, marked with the offset of the substitution,
    /// every byte offset pointing into the original source. `$(git push |
    /// tail -1)` was invisible to every rule before this — including the one
    /// whose own header uses `$(stat -f …)` as its example.
    #[test]
    fn a_substitution_is_read_as_clauses_of_its_own() {
        let src = "echo $(git push | tail -1)";
        let c = clauses(src);
        assert_eq!(c.len(), 3);
        assert_eq!(c[0].program(), Some("echo"));
        assert_eq!(c[0].nested, None);
        assert_eq!(c[1].program(), Some("git"));
        assert_eq!(c[1].nested, Some(5), "the offset of the `$(`");
        assert_eq!(c[1].next, Some(Connector::Pipe));
        assert_eq!(c[2].program(), Some("tail"));
        assert_eq!(c[2].nested, Some(5));
        assert!(
            src[c[1].at..].starts_with("git push"),
            "offsets are the source's"
        );
        assert!(src[c[2].words[0].at..].starts_with("tail"));
        assert_eq!(src[c[2].at..c[2].end].trim(), "tail -1");

        let c = clauses("echo `stat -f '%Sm' x`");
        assert_eq!(c.len(), 2);
        assert_eq!(c[1].program(), Some("stat"));
        assert_eq!(c[1].nested, Some(5));
        assert!(c[1].has_flag("-f"));

        let c = clauses(r#"echo "mtime: $(stat -f '%Sm' "$LOG")""#);
        assert_eq!(c.len(), 2, "inside double quotes too");
        assert_eq!(c[1].program(), Some("stat"));

        let c = clauses("diff <(sort a) <(sort b)");
        assert_eq!(c.len(), 3, "a process substitution is a command too");
        assert_eq!(c[1].program(), Some("sort"));
        assert_ne!(c[1].nested, c[2].nested, "two substitutions, two ids");

        let c = clauses("echo ${HOME} $VAR");
        assert_eq!(c.len(), 1, "a parameter is not a command");
    }

    /// Appended after the line, never between two of its clauses: the pipe
    /// walk from `git push` must still land on `tail`.
    #[test]
    fn a_substitutions_clauses_never_sit_between_the_lines() {
        let c = clauses("git push $(cat v) | tail -1");
        assert_eq!(c.len(), 3);
        assert_eq!(c[0].program(), Some("git"));
        assert_eq!(c[0].next, Some(Connector::Pipe));
        assert_eq!(c[1].program(), Some("tail"));
        assert_eq!(c[2].program(), Some("cat"));
        assert!(c[2].nested.is_some());
    }

    /// A substitution inside a substitution: read by the recursive call,
    /// shifted twice, id pointing at ITS opener.
    #[test]
    fn a_nested_substitution_is_read_and_shifted_twice() {
        let src = "echo $(echo $(git push | tail -1))";
        let c = clauses(src);
        assert_eq!(c.len(), 4);
        let push = c.iter().find(|s| s.program() == Some("git")).expect("push");
        assert!(src[push.at..].starts_with("git push"));
        assert_eq!(push.nested, Some(12), "the inner `$(`");
        assert_eq!(push.next, Some(Connector::Pipe));
        let inner_echo = &c[1];
        assert_eq!(inner_echo.program(), Some("echo"));
        assert_eq!(inner_echo.nested, Some(5), "the outer `$(`");
    }

    /// An inside we cannot read adds nothing and costs nothing: the word
    /// stays blank as before, and the line is judged as it always was. An
    /// `eval` in a subshell cannot move this shell, so it is not the whole-
    /// line opacity it would be on the line.
    #[test]
    fn an_unreadable_substitution_adds_nothing() {
        let c = clauses("echo $(eval \"$x\") && git push | tail -1");
        assert_eq!(c.len(), 3);
        assert!(c.iter().all(|s| s.nested.is_none()));
        assert_eq!(c[1].program(), Some("git"));
        assert_eq!(c[1].next, Some(Connector::Pipe));
        assert!(matches!(
            opaque("echo $(git push | tail -1"),
            Opaque::UnterminatedSubstitution
        ));
    }

    #[test]
    fn a_comment_ends_the_command() {
        let c = clauses("git push origin main # then | tail -5");
        assert_eq!(c.len(), 1);
        assert_eq!(c[0].operands().len(), 3);
    }

    /// A redirect target is not argv. Without this, `git push > --force` offers
    /// a `--force` flag that was never typed as one.
    #[test]
    fn a_brace_attached_to_a_word_stays_in_the_word() {
        // `stash@{2}` is ONE operand. Ending the clause at `{` truncated it to
        // `stash@`, which turned an explicit stash reference into a bare one —
        // the flattening comment promises to lose fires, never invent them.
        let c = clauses("git stash pop stash@{2}");
        assert_eq!(c.len(), 1);
        let ops: Vec<&str> = c[0].operands().iter().map(|w| w.text.as_str()).collect();
        assert_eq!(ops, vec!["stash", "pop", "stash@{2}"]);
        // A brace that STARTS a word is still grouping, not part of a word:
        // the program is `echo`, never `{`.
        let g = clauses("{ echo a; }");
        assert_eq!(
            g.iter().filter_map(|c| c.program()).collect::<Vec<_>>(),
            vec!["echo"]
        );
    }

    #[test]
    fn a_redirect_target_is_not_argv() {
        let c = clauses("git push > --force");
        assert!(!c[0].has_flag("--force"));
        assert_eq!(c[0].redirects.len(), 1);
        // `2>&1` is a redirect, not a background `&` starting a new command.
        let c = clauses("git push 2>&1 | tail -3");
        assert_eq!(c.len(), 2);
        assert_eq!(c[0].next, Some(Connector::Pipe));
    }

    /// `--` ends the flags. `git add -- -A` stages a FILE called `-A`.
    #[test]
    fn flags_stop_at_the_double_dash() {
        let c = clauses("git add -- -A");
        assert!(!c[0].has_short('A'));
        assert!(c[0].operands().iter().any(|w| w.text == "-A"));
    }

    #[test]
    fn short_clusters_are_searched_by_letter() {
        let c = clauses("git add -Au");
        assert!(c[0].has_short('A') && c[0].has_short('u'));
        assert!(!c[0].has_short('p'));
    }

    /// `FOO=1 git push` and `sudo git push` are both a `git push`. A rule keyed
    /// on argv0 would miss every one of them.
    #[test]
    fn assignments_and_wrappers_are_not_the_program() {
        for src in [
            "GIT_SSH_COMMAND=ssh git push",
            "sudo git push",
            "timeout 90 git push",
            "command git push",
        ] {
            let c = clauses(src);
            assert_eq!(c[0].program(), Some("git"), "{src}");
            assert_eq!(c[0].subcommand(), Some("push"), "{src}");
        }
    }

    /// A wrapper's own FLAGS are not the program either. Only bare numeric
    /// arguments used to be skipped, so `nice -n 10 git push` had a program
    /// of `-n` and every git rule went quiet on the ordinary spelling of
    /// three of these wrappers.
    #[test]
    fn a_wrappers_own_options_are_not_the_program() {
        for src in [
            "nice -n 10 git push",
            "timeout -k 5 90 git push",
            "timeout --signal=TERM 90 git push",
            "timeout 1.5m git push",
            "env -i git push",
            "env -u GIT_DIR git push",
            "sudo -u root git push",
            "sudo -n -u root git push",
            "time -p git push",
            "env -- git push",
        ] {
            let c = clauses(src);
            assert_eq!(c[0].program(), Some("git"), "{src}");
            assert_eq!(c[0].subcommand(), Some("push"), "{src}");
        }
    }

    /// The index must come from the same walk as the name. Re-finding the
    /// program by searching for its text lands on the `git` that is somebody
    /// ELSE'S argument, and reads `push` as the subcommand of the wrong word.
    #[test]
    fn the_program_index_is_not_re_found_by_name() {
        let c = clauses("sudo -u git git push origin main");
        assert_eq!(c[0].program(), Some("git"));
        assert_eq!(c[0].subcommand(), Some("push"));
        let ops: Vec<&str> = c[0].operands().iter().map(|w| w.text.as_str()).collect();
        assert_eq!(ops, vec!["push", "origin", "main"]);
    }

    /// A wrapper's flags are the WRAPPER'S. Reading them as the program's is
    /// how resolving `nice -n 10 git push` correctly made `pipe-to-tail` go
    /// quiet: `-n` on `git push` is `--dry-run`, and a dry run disarms every
    /// rule about mutation.
    #[test]
    fn a_wrappers_flags_are_not_the_programs_flags() {
        let c = clauses("nice -n 10 git push origin main");
        assert!(!c[0].has_short('n'), "nice's -n read as `git push -n`");
        let c = clauses("sudo -n git push origin main");
        assert!(!c[0].has_short('n'), "sudo's -n read as `git push -n`");
        let c = clauses("timeout -s KILL 90 git push origin main");
        assert!(!c[0].has_flag("-s"));
        // The program's OWN flags still read, wrapper or not.
        let c = clauses("sudo git push -n origin main");
        assert!(c[0].has_short('n'));
        let c = clauses("nice -n 10 git push --dry-run");
        assert!(c[0].is_dry_run());
        let c = clauses("nice -n 10 git push");
        assert!(!c[0].is_dry_run());
    }

    #[test]
    fn a_duration_is_a_number_with_an_optional_unit() {
        for yes in ["90", "1.5", "30s", "5m", "2h", "1d"] {
            assert!(is_duration(yes), "{yes}");
        }
        for no in ["git", "main", "s", "", "v1.2.3", "-n"] {
            assert!(!is_duration(no), "{no}");
        }
    }

    /// git's own options sit before the subcommand, so a naive "second word"
    /// read of `git -C dir push` finds `dir`.
    #[test]
    fn git_global_options_precede_the_subcommand() {
        assert_eq!(clauses("git -C /tmp/x push")[0].subcommand(), Some("push"));
        assert_eq!(clauses("git --no-pager log")[0].subcommand(), Some("log"));
        assert_eq!(
            clauses("git -c user.name=x commit")[0].subcommand(),
            Some("commit")
        );
        // An option we do not know is a reason to stop, not to guess.
        assert_eq!(clauses("git --future-flag push")[0].subcommand(), None);
    }

    #[test]
    fn a_flag_value_is_read_either_way_it_is_written() {
        assert_eq!(
            clauses("grep --include=*.py x")[0].flag_value("--include"),
            Some("*.py")
        );
        assert_eq!(
            clauses("grep --include *.py x")[0].flag_value("--include"),
            Some("*.py")
        );
    }

    #[test]
    fn a_dry_run_is_recognised_in_both_forms() {
        assert!(clauses("kubectl apply --dry-run=client -f x")[0].is_dry_run());
        assert!(clauses("git push --dry-run")[0].is_dry_run());
        assert!(!clauses("git push")[0].is_dry_run());
    }
}