agent-bridle-tool-shell 0.7.14

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

use brush_parser::ast::{
    AndOr, ArithmeticExpr, Command, CommandPrefixOrSuffixItem, CompoundCommand, CompoundList,
    IoFileRedirectKind, IoFileRedirectTarget, IoRedirect, SeparatorOperator, SimpleCommand,
    SourceLocation, Word,
};
use brush_parser::word::{
    self, Parameter, ParameterExpr, ParameterTransformOp, WordPiece, WordPieceWithSource,
};
use brush_parser::{Parser, ParserOptions};
use serde::Serialize;

const INSPECTION_SCHEMA_VERSION: u8 = 1;
const MAX_SOURCE_BYTES: usize = 32 * 1024;
const MAX_INSPECTION_DEPTH: usize = 32;

/// A stable, serializable, flattened inventory of a shell command's source.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct ShellInspection {
    /// Version of this stable projection.
    pub schema_version: u8,
    /// The exact shell source inspected.
    pub source: String,
    /// Simple commands in source order, without control-flow or pipeline edges.
    pub commands: Vec<InspectedCommand>,
    /// Dynamic shell constructs directly present in this source.
    pub constructs: Vec<InspectedConstruct>,
    /// Human-readable safety facts discovered during inspection.
    pub warnings: Vec<String>,
}

/// One simple shell command or pipeline stage.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct InspectedCommand {
    /// Source slice spanning this stage's words and redirect targets, excluding
    /// pipeline/list separators. The inspection root always retains the exact
    /// complete source; a redirect written before the first word may begin just
    /// outside this best-effort stage slice.
    pub source: String,
    /// Statically resolved executable/builtin name, when the node executes one.
    pub program: Option<String>,
    /// Shell words in argv position, before runtime expansion.
    pub argv: Vec<String>,
    /// Redirections attached to this stage.
    pub redirects: Vec<InspectedRedirect>,
    /// Commands delegated to a child program rather than spawned by Brush itself.
    pub descendant_execs: Vec<DescendantExec>,
}

/// One redirection attached to a command.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct InspectedRedirect {
    /// Explicit file descriptor, if one was written.
    pub fd: Option<i32>,
    /// The redirection operation.
    pub operation: RedirectOperation,
    /// The raw target word or descriptor.
    pub target: String,
}

/// A redirection operation.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum RedirectOperation {
    /// Read from a file.
    Read,
    /// Write to a file.
    Write,
    /// Append to a file.
    Append,
    /// Open a file for reading and writing.
    ReadWrite,
    /// Write while overriding noclobber.
    Clobber,
    /// Duplicate an input descriptor.
    DuplicateInput,
    /// Duplicate an output descriptor.
    DuplicateOutput,
    /// Supply a here-document.
    HereDocument,
    /// Supply a here-string.
    HereString,
    /// Redirect stdout and stderr together.
    OutputAndError,
    /// Append stdout and stderr together.
    AppendOutputAndError,
}

/// A command that an admitted external program can spawn outside Brush's interceptor.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct DescendantExec {
    /// Statically resolved child program name.
    pub program: String,
    /// Child argv in source form, including the program at index zero.
    pub argv: Vec<String>,
    /// Exact source for the delegating action.
    pub source: String,
    /// Why this is a distinct approval hazard.
    pub reason: String,
}

/// A shell expansion or substitution.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct InspectedConstruct {
    /// The kind of dynamic construct.
    pub kind: ShellConstructKind,
    /// Exact construct source, including delimiters.
    pub source: String,
    /// Construct body without its outer delimiters.
    pub body: String,
    /// Whether the construct occurs inside double quotes.
    pub quoted: bool,
    /// Recursive command inspection for command substitutions. State-free
    /// arithmetic expansions have no nested command inventory and use `None`.
    pub inspection: Option<Box<ShellInspection>>,
}

/// A dynamic construct recognized in a shell word.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ShellConstructKind {
    /// `$(...)`.
    CommandSubstitution,
    /// Legacy backquote substitution.
    BackquoteSubstitution,
    /// A state-free `$((...))` or `$[...]` expression. Arithmetic that reads or
    /// mutates shell state is rejected instead of emitting this projection.
    ArithmeticExpansion,
}

/// A fail-closed shell-inspection error.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ShellInspectionError {
    message: String,
}

impl ShellInspectionError {
    fn new(message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
        }
    }

    /// Return the human-readable refusal reason.
    #[must_use]
    pub fn message(&self) -> &str {
        &self.message
    }
}

impl std::fmt::Display for ShellInspectionError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(&self.message)
    }
}

impl std::error::Error for ShellInspectionError {}

/// Parse and inspect shell source without evaluating expansions or executing commands.
///
/// # Errors
///
/// Returns an error when the source is malformed, when the inspector cannot
/// statically identify an executable that could run, when arithmetic depends
/// on variables, arrays, assignments, or nested shell expansion, or when a
/// parameter expansion can reinterpret runtime state as shell syntax. Brush
/// builtins that evaluate deferred source (`trap` and `fc`) are refused, as is
/// every `printf -v` form: Brush reparses that option's assignment target, so
/// even an apparently simple target is outside this projection's safe subset.
pub fn inspect_shell(cmd: &str) -> Result<ShellInspection, ShellInspectionError> {
    inspect_shell_at_depth(cmd, 0)
}

fn inspect_shell_at_depth(
    source: &str,
    depth: usize,
) -> Result<ShellInspection, ShellInspectionError> {
    if source.len() > MAX_SOURCE_BYTES {
        return Err(ShellInspectionError::new(format!(
            "shell inspection source exceeds the {MAX_SOURCE_BYTES}-byte limit"
        )));
    }
    if depth > MAX_INSPECTION_DEPTH {
        return Err(ShellInspectionError::new(format!(
            "shell inspection exceeded the maximum nesting depth of {MAX_INSPECTION_DEPTH}"
        )));
    }

    let options = ParserOptions::default();
    let mut parser = Parser::new(std::io::Cursor::new(source.as_bytes()), &options);
    let program = parser
        .parse_program()
        .map_err(|error| ShellInspectionError::new(format!("malformed shell syntax: {error}")))?;
    let mut nodes = Vec::new();
    let mut control_warnings = Vec::new();
    collect_inspection_nodes(&program, &mut nodes, &mut control_warnings)?;

    let mut constructs = Vec::new();
    let mut warnings = control_warnings;
    let mut commands = Vec::new();
    for node in nodes {
        match node {
            InspectNode::ControlWord(word) => {
                inspect_word_constructs(word, &options, depth, &mut constructs, &mut warnings)?;
            }
            InspectNode::Simple(simple) => {
                let stage_source = simple_command_source(simple, source)?;
                commands.push(inspect_simple_command(
                    simple,
                    stage_source,
                    source,
                    &options,
                    depth,
                    &mut constructs,
                    &mut warnings,
                )?);
            }
        }
    }

    Ok(ShellInspection {
        schema_version: INSPECTION_SCHEMA_VERSION,
        source: source.to_string(),
        commands,
        constructs,
        warnings,
    })
}

enum InspectNode<'a> {
    ControlWord(&'a Word),
    Simple(&'a SimpleCommand),
}

fn collect_inspection_nodes<'a>(
    program: &'a brush_parser::ast::Program,
    nodes: &mut Vec<InspectNode<'a>>,
    warnings: &mut Vec<String>,
) -> Result<(), ShellInspectionError> {
    for complete_command in &program.complete_commands {
        collect_compound_list(complete_command, nodes, warnings)?;
    }
    Ok(())
}

fn collect_compound_list<'a>(
    list: &'a CompoundList,
    nodes: &mut Vec<InspectNode<'a>>,
    warnings: &mut Vec<String>,
) -> Result<(), ShellInspectionError> {
    for item in &list.0 {
        if !item.0.additional.is_empty() {
            push_warning_once(
                warnings,
                "`&&`/`||` conditional relationship is retained in exact `source` but is not \
                 encoded in the flattened command inventory",
            );
        }
        collect_pipeline_nodes(&item.0.first, nodes, warnings)?;
        for additional in &item.0.additional {
            match additional {
                AndOr::And(pipeline) | AndOr::Or(pipeline) => {
                    collect_pipeline_nodes(pipeline, nodes, warnings)?;
                }
            }
        }
        if matches!(item.1, SeparatorOperator::Async) {
            push_warning_once(
                warnings,
                "`&` background lifecycle is retained in exact `source` but is not encoded in \
                 the flattened command inventory",
            );
        }
    }
    Ok(())
}

fn collect_pipeline_nodes<'a>(
    pipeline: &'a brush_parser::ast::Pipeline,
    nodes: &mut Vec<InspectNode<'a>>,
    warnings: &mut Vec<String>,
) -> Result<(), ShellInspectionError> {
    if pipeline.seq.len() > 1 {
        push_warning_once(
            warnings,
            "`|` pipeline topology is retained in exact `source` but is not encoded as edges in \
             the flattened command inventory",
        );
    }
    if pipeline.bang {
        push_warning_once(
            warnings,
            "`!` status negation is retained in exact `source` but is not encoded in the \
             flattened command inventory",
        );
    }
    if pipeline.timed.is_some() {
        push_warning_once(
            warnings,
            "`time` pipeline modifier is retained in exact `source` but is not encoded in the \
             flattened command inventory",
        );
    }
    for command in &pipeline.seq {
        match command {
            Command::Simple(simple) => nodes.push(InspectNode::Simple(simple)),
            Command::Compound(CompoundCommand::ForClause(for_clause), redirects) => {
                if redirects
                    .as_ref()
                    .is_some_and(|redirects| !redirects.0.is_empty())
                {
                    return Err(ShellInspectionError::new(
                        "redirections on a for loop are not yet represented by the stable inspection projection",
                    ));
                }
                if let Some(values) = &for_clause.values {
                    nodes.extend(values.iter().map(InspectNode::ControlWord));
                }
                warnings.push(format!(
                    "for-loop over `{}` is represented as a flattened control-flow projection; \
                     its value expansions are inspected before its body commands",
                    for_clause.variable_name
                ));
                collect_compound_list(&for_clause.body.list, nodes, warnings)?;
            }
            Command::Compound(_, _) => {
                return Err(ShellInspectionError::new(
                    "compound shell commands are not yet represented by the stable inspection projection",
                ));
            }
            Command::Function(_) => {
                return Err(ShellInspectionError::new(
                    "shell function definitions are not yet represented by the stable inspection projection",
                ));
            }
            Command::ExtendedTest(_, _) => {
                return Err(ShellInspectionError::new(
                    "extended test commands are not yet represented by the stable inspection projection",
                ));
            }
        }
    }
    Ok(())
}

fn push_warning_once(warnings: &mut Vec<String>, warning: &str) {
    if !warnings.iter().any(|existing| existing == warning) {
        warnings.push(warning.to_string());
    }
}

fn simple_command_source(
    simple: &SimpleCommand,
    source: &str,
) -> Result<String, ShellInspectionError> {
    let mut start = usize::MAX;
    let mut end = 0_usize;
    let mut include = |word: &Word| {
        if let Some(span) = word.location() {
            start = start.min(span.start.index);
            end = end.max(span.end.index);
        }
    };
    if let Some(prefix) = &simple.prefix {
        for item in &prefix.0 {
            include_item_words(item, &mut include);
        }
    }
    if let Some(word) = &simple.word_or_name {
        include(word);
    }
    if let Some(suffix) = &simple.suffix {
        for item in &suffix.0 {
            include_item_words(item, &mut include);
        }
    }
    if start == usize::MAX || end < start {
        return Err(ShellInspectionError::new(
            "simple command has no complete source location",
        ));
    }
    Ok(slice_char_range(source, start, end)?.to_string())
}

fn include_item_words(item: &CommandPrefixOrSuffixItem, include: &mut impl FnMut(&Word)) {
    match item {
        CommandPrefixOrSuffixItem::Word(word)
        | CommandPrefixOrSuffixItem::AssignmentWord(_, word) => include(word),
        CommandPrefixOrSuffixItem::IoRedirect(redirect) => match redirect {
            IoRedirect::File(_, _, target) => match target {
                IoFileRedirectTarget::Filename(word) | IoFileRedirectTarget::Duplicate(word) => {
                    include(word)
                }
                IoFileRedirectTarget::Fd(_) | IoFileRedirectTarget::ProcessSubstitution(_, _) => {}
            },
            IoRedirect::HereString(_, word) | IoRedirect::OutputAndError(word, _) => include(word),
            IoRedirect::HereDocument(_, _) => {}
        },
        CommandPrefixOrSuffixItem::ProcessSubstitution(_, _) => {}
    }
}

fn slice_char_range(source: &str, start: usize, end: usize) -> Result<&str, ShellInspectionError> {
    if start > end {
        return Err(ShellInspectionError::new(
            "parser returned an inverted source span",
        ));
    }
    let byte_start = char_index_to_byte(source, start).ok_or_else(|| {
        ShellInspectionError::new("parser returned a source-span start outside the command")
    })?;
    let byte_end = char_index_to_byte(source, end).ok_or_else(|| {
        ShellInspectionError::new("parser returned a source-span end outside the command")
    })?;
    source.get(byte_start..byte_end).ok_or_else(|| {
        ShellInspectionError::new("parser returned a source span that is not a UTF-8 boundary")
    })
}

fn char_index_to_byte(source: &str, index: usize) -> Option<usize> {
    if index == source.chars().count() {
        return Some(source.len());
    }
    source.char_indices().nth(index).map(|(byte, _)| byte)
}

#[allow(clippy::too_many_arguments)]
fn inspect_simple_command(
    simple: &SimpleCommand,
    stage_source: String,
    containing_source: &str,
    options: &ParserOptions,
    depth: usize,
    constructs: &mut Vec<InspectedConstruct>,
    warnings: &mut Vec<String>,
) -> Result<InspectedCommand, ShellInspectionError> {
    let mut argv = Vec::new();
    let mut argv_words = Vec::new();
    let mut redirects = Vec::new();

    if let Some(prefix) = &simple.prefix {
        for item in &prefix.0 {
            inspect_non_argv_item(item, options, depth, constructs, warnings, &mut redirects)?;
        }
    }

    let resolved_program = if let Some(command_word) = &simple.word_or_name {
        inspect_word_constructs(command_word, options, depth, constructs, warnings)?;
        let resolved = static_shell_word(command_word, options).map_err(|reason| {
            ShellInspectionError::new(format!(
                "dynamic executable name `{}` cannot be approved statically: {reason}",
                command_word.value
            ))
        })?;
        argv.push(command_word.value.clone());
        argv_words.push(command_word);
        Some(resolved)
    } else {
        None
    };
    if let Some((program, reason)) = resolved_program
        .as_deref()
        .and_then(|program| unprojectable_program_reason(program).map(|reason| (program, reason)))
    {
        return Err(ShellInspectionError::new(format!(
            "`{program}` cannot be projected statically: {reason}; submit the delegated command \
             directly when possible"
        )));
    }
    if let Some(suffix) = &simple.suffix {
        for item in &suffix.0 {
            match item {
                CommandPrefixOrSuffixItem::Word(word)
                | CommandPrefixOrSuffixItem::AssignmentWord(_, word) => {
                    inspect_word_constructs(word, options, depth, constructs, warnings)?;
                    argv.push(word.value.clone());
                    argv_words.push(word);
                }
                CommandPrefixOrSuffixItem::IoRedirect(redirect) => {
                    redirects.push(inspect_redirect(
                        redirect, options, depth, constructs, warnings,
                    )?);
                }
                CommandPrefixOrSuffixItem::ProcessSubstitution(_, _) => {
                    return Err(ShellInspectionError::new(
                        "process substitution is not yet represented by the stable inspection projection",
                    ));
                }
            }
        }
    }

    if resolved_program.as_deref() == Some("printf") {
        ensure_brush_printf_is_projectable(&argv_words, options)?;
    }

    let descendant_execs = if resolved_program.as_deref().is_some_and(is_find_program) {
        inspect_find_descendants(&argv_words, containing_source, options, warnings)?
    } else {
        Vec::new()
    };

    Ok(InspectedCommand {
        source: stage_source,
        program: resolved_program,
        argv,
        redirects,
        descendant_execs,
    })
}

fn inspect_non_argv_item(
    item: &CommandPrefixOrSuffixItem,
    options: &ParserOptions,
    depth: usize,
    constructs: &mut Vec<InspectedConstruct>,
    warnings: &mut Vec<String>,
    redirects: &mut Vec<InspectedRedirect>,
) -> Result<(), ShellInspectionError> {
    match item {
        CommandPrefixOrSuffixItem::Word(word)
        | CommandPrefixOrSuffixItem::AssignmentWord(_, word) => {
            inspect_word_constructs(word, options, depth, constructs, warnings)
        }
        CommandPrefixOrSuffixItem::IoRedirect(redirect) => {
            redirects.push(inspect_redirect(
                redirect, options, depth, constructs, warnings,
            )?);
            Ok(())
        }
        CommandPrefixOrSuffixItem::ProcessSubstitution(_, _) => Err(ShellInspectionError::new(
            "process substitution is not yet represented by the stable inspection projection",
        )),
    }
}

fn inspect_redirect(
    redirect: &IoRedirect,
    options: &ParserOptions,
    depth: usize,
    constructs: &mut Vec<InspectedConstruct>,
    warnings: &mut Vec<String>,
) -> Result<InspectedRedirect, ShellInspectionError> {
    match redirect {
        IoRedirect::File(fd, kind, target) => {
            let operation = match kind {
                IoFileRedirectKind::Read => RedirectOperation::Read,
                IoFileRedirectKind::Write => RedirectOperation::Write,
                IoFileRedirectKind::Append => RedirectOperation::Append,
                IoFileRedirectKind::ReadAndWrite => RedirectOperation::ReadWrite,
                IoFileRedirectKind::Clobber => RedirectOperation::Clobber,
                IoFileRedirectKind::DuplicateInput => RedirectOperation::DuplicateInput,
                IoFileRedirectKind::DuplicateOutput => RedirectOperation::DuplicateOutput,
            };
            let target = match target {
                IoFileRedirectTarget::Filename(word) | IoFileRedirectTarget::Duplicate(word) => {
                    inspect_word_constructs(word, options, depth, constructs, warnings)?;
                    word.value.clone()
                }
                IoFileRedirectTarget::Fd(descriptor) => descriptor.to_string(),
                IoFileRedirectTarget::ProcessSubstitution(_, _) => {
                    return Err(ShellInspectionError::new(
                        "process substitution in a redirection is not yet represented by the stable inspection projection",
                    ));
                }
            };
            Ok(InspectedRedirect {
                fd: *fd,
                operation,
                target,
            })
        }
        IoRedirect::HereDocument(_, _) => Err(ShellInspectionError::new(
            "here-document inspection is not yet represented by the stable inspection projection",
        )),
        IoRedirect::HereString(fd, word) => {
            inspect_word_constructs(word, options, depth, constructs, warnings)?;
            Ok(InspectedRedirect {
                fd: *fd,
                operation: RedirectOperation::HereString,
                target: word.value.clone(),
            })
        }
        IoRedirect::OutputAndError(word, append) => {
            inspect_word_constructs(word, options, depth, constructs, warnings)?;
            Ok(InspectedRedirect {
                fd: None,
                operation: if *append {
                    RedirectOperation::AppendOutputAndError
                } else {
                    RedirectOperation::OutputAndError
                },
                target: word.value.clone(),
            })
        }
    }
}

fn inspect_word_constructs(
    word: &Word,
    options: &ParserOptions,
    depth: usize,
    constructs: &mut Vec<InspectedConstruct>,
    warnings: &mut Vec<String>,
) -> Result<(), ShellInspectionError> {
    let pieces = word::parse(&word.value, options).map_err(|error| {
        ShellInspectionError::new(format!(
            "cannot inspect shell word `{}`: {error}",
            word.value
        ))
    })?;
    inspect_word_pieces(&word.value, &pieces, false, depth, constructs, warnings)
}

fn inspect_word_pieces(
    raw_word: &str,
    pieces: &[WordPieceWithSource],
    quoted: bool,
    depth: usize,
    constructs: &mut Vec<InspectedConstruct>,
    warnings: &mut Vec<String>,
) -> Result<(), ShellInspectionError> {
    for piece_with_source in pieces {
        let source = raw_word
            .get(piece_with_source.start_index..piece_with_source.end_index)
            .ok_or_else(|| {
                ShellInspectionError::new(
                    "word parser returned a construct span that is not a UTF-8 boundary",
                )
            })?;
        match &piece_with_source.piece {
            WordPiece::DoubleQuotedSequence(nested)
            | WordPiece::GettextDoubleQuotedSequence(nested) => {
                inspect_word_pieces(raw_word, nested, true, depth, constructs, warnings)?;
            }
            WordPiece::CommandSubstitution(body) => {
                let inspection = inspect_shell_at_depth(body, depth + 1)?;
                constructs.push(InspectedConstruct {
                    kind: ShellConstructKind::CommandSubstitution,
                    source: source.to_string(),
                    body: body.clone(),
                    quoted,
                    inspection: Some(Box::new(inspection)),
                });
                warnings.push(substitution_value_warning(source, quoted));
            }
            WordPiece::BackquotedCommandSubstitution(body) => {
                let inspection = inspect_shell_at_depth(body, depth + 1)?;
                constructs.push(InspectedConstruct {
                    kind: ShellConstructKind::BackquoteSubstitution,
                    source: source.to_string(),
                    body: body.clone(),
                    quoted,
                    inspection: Some(Box::new(inspection)),
                });
                warnings.push(substitution_value_warning(source, quoted));
            }
            WordPiece::ArithmeticExpression(expression) => {
                if contains_nested_command_syntax(&expression.value) {
                    return Err(ShellInspectionError::new(
                        "command syntax nested inside arithmetic expansion cannot be represented safely",
                    ));
                }
                ensure_static_arithmetic_expression(&expression.value, "arithmetic expansion")?;
                constructs.push(InspectedConstruct {
                    kind: ShellConstructKind::ArithmeticExpansion,
                    source: source.to_string(),
                    body: expression.value.clone(),
                    quoted,
                    inspection: None,
                });
            }
            WordPiece::ParameterExpansion(expression) => {
                if contains_nested_command_syntax(source) {
                    return Err(ShellInspectionError::new(
                        "command syntax nested inside parameter expansion cannot be represented safely",
                    ));
                }
                ensure_parameter_expansion_is_non_executing(expression)?;
            }
            WordPiece::Text(_)
            | WordPiece::SingleQuotedText(_)
            | WordPiece::AnsiCQuotedText(_)
            | WordPiece::TildeExpansion(_)
            | WordPiece::EscapeSequence(_) => {}
        }
    }
    Ok(())
}

fn ensure_static_arithmetic_expression(
    expression: &str,
    context: &str,
) -> Result<(), ShellInspectionError> {
    let parsed = brush_parser::arithmetic::parse(expression).map_err(|_| {
        ShellInspectionError::new(format!(
            "{context} is not statically evaluable; only integer literals and operators without \
             shell expansions may be approved"
        ))
    })?;
    if is_state_free_arithmetic_expression(&parsed) {
        Ok(())
    } else {
        Err(ShellInspectionError::new(format!(
            "{context} depends on runtime shell state; variables, array references, and \
             assignments cannot be approved from source alone"
        )))
    }
}

fn is_state_free_arithmetic_expression(expression: &ArithmeticExpr) -> bool {
    match expression {
        ArithmeticExpr::Literal(_) => true,
        ArithmeticExpr::UnaryOp(_, operand) => is_state_free_arithmetic_expression(operand),
        ArithmeticExpr::BinaryOp(_, left, right) => {
            is_state_free_arithmetic_expression(left) && is_state_free_arithmetic_expression(right)
        }
        ArithmeticExpr::Conditional(condition, then_expression, else_expression) => {
            is_state_free_arithmetic_expression(condition)
                && is_state_free_arithmetic_expression(then_expression)
                && is_state_free_arithmetic_expression(else_expression)
        }
        ArithmeticExpr::Reference(_)
        | ArithmeticExpr::Assignment(_, _)
        | ArithmeticExpr::BinaryAssignment(_, _, _)
        | ArithmeticExpr::UnaryAssignment(_, _) => false,
    }
}

fn ensure_parameter_expansion_is_non_executing(
    expression: &ParameterExpr,
) -> Result<(), ShellInspectionError> {
    if let ParameterExpr::Transform {
        op: ParameterTransformOp::PromptExpand,
        ..
    } = expression
    {
        return Err(ShellInspectionError::new(
            "prompt-expanding parameter transformation `@P` can execute shell syntax obtained \
             from runtime state",
        ));
    }

    if let ParameterExpr::Substring { offset, length, .. } = expression {
        ensure_static_arithmetic_expression(&offset.value, "parameter substring offset")?;
        if let Some(length) = length {
            ensure_static_arithmetic_expression(&length.value, "parameter substring length")?;
        }
    }

    let Some((parameter, indirect)) = parameter_reference(expression) else {
        return Ok(());
    };
    if indirect {
        return Err(ShellInspectionError::new(
            "indirect parameter expansion can reinterpret runtime state as an array reference \
             and cannot be approved from source alone",
        ));
    }
    if let Parameter::NamedWithIndex { index, .. } = parameter {
        ensure_static_arithmetic_expression(index, "parameter array subscript")?;
    }
    Ok(())
}

#[allow(clippy::match_same_arms)]
fn parameter_reference(expression: &ParameterExpr) -> Option<(&Parameter, bool)> {
    match expression {
        ParameterExpr::Parameter {
            parameter,
            indirect,
        }
        | ParameterExpr::UseDefaultValues {
            parameter,
            indirect,
            ..
        }
        | ParameterExpr::AssignDefaultValues {
            parameter,
            indirect,
            ..
        }
        | ParameterExpr::IndicateErrorIfNullOrUnset {
            parameter,
            indirect,
            ..
        }
        | ParameterExpr::UseAlternativeValue {
            parameter,
            indirect,
            ..
        }
        | ParameterExpr::ParameterLength {
            parameter,
            indirect,
        }
        | ParameterExpr::RemoveSmallestSuffixPattern {
            parameter,
            indirect,
            ..
        }
        | ParameterExpr::RemoveLargestSuffixPattern {
            parameter,
            indirect,
            ..
        }
        | ParameterExpr::RemoveSmallestPrefixPattern {
            parameter,
            indirect,
            ..
        }
        | ParameterExpr::RemoveLargestPrefixPattern {
            parameter,
            indirect,
            ..
        }
        | ParameterExpr::Substring {
            parameter,
            indirect,
            ..
        }
        | ParameterExpr::Transform {
            parameter,
            indirect,
            ..
        }
        | ParameterExpr::UppercaseFirstChar {
            parameter,
            indirect,
            ..
        }
        | ParameterExpr::UppercasePattern {
            parameter,
            indirect,
            ..
        }
        | ParameterExpr::LowercaseFirstChar {
            parameter,
            indirect,
            ..
        }
        | ParameterExpr::LowercasePattern {
            parameter,
            indirect,
            ..
        }
        | ParameterExpr::ReplaceSubstring {
            parameter,
            indirect,
            ..
        } => Some((parameter, *indirect)),
        ParameterExpr::VariableNames { .. } | ParameterExpr::MemberKeys { .. } => None,
    }
}

fn contains_nested_command_syntax(source: &str) -> bool {
    source.contains("$(") || source.contains('`')
}

fn substitution_value_warning(source: &str, quoted: bool) -> String {
    if quoted {
        format!(
            "substitution `{source}` has no inspectable value until its inner command source runs; double quotes preserve the captured output as one shell field"
        )
    } else {
        format!(
            "substitution `{source}` has no inspectable value until its inner command source runs; unquoted output is subject to field splitting and pathname expansion"
        )
    }
}

fn static_shell_word(word: &Word, options: &ParserOptions) -> Result<String, ShellInspectionError> {
    if may_contain_brace_expansion(&word.value)
        && word::parse_brace_expansions(&word.value, options)
            .map_err(|error| {
                ShellInspectionError::new(format!(
                    "cannot analyze brace expansion in `{}`: {error}",
                    word.value
                ))
            })?
            .is_some()
    {
        return Err(ShellInspectionError::new(
            "brace expansion can produce multiple runtime words",
        ));
    }
    let pieces = word::parse(&word.value, options).map_err(|error| {
        ShellInspectionError::new(format!("cannot parse `{}`: {error}", word.value))
    })?;
    let mut value = String::new();
    append_static_pieces(&pieces, false, &mut value)?;
    Ok(value)
}

fn may_contain_brace_expansion(word: &str) -> bool {
    word.split_once('{').is_some_and(|(_, after_open)| {
        after_open
            .split_once('}')
            .is_some_and(|(inside, _)| inside.contains(',') || inside.contains(".."))
    })
}

fn append_static_pieces(
    pieces: &[WordPieceWithSource],
    quoted: bool,
    output: &mut String,
) -> Result<(), ShellInspectionError> {
    for piece_with_source in pieces {
        match &piece_with_source.piece {
            WordPiece::Text(text) => {
                if !quoted && has_pathname_expansion(text) {
                    return Err(ShellInspectionError::new(
                        "unquoted pathname expansion makes the runtime word dynamic",
                    ));
                }
                output.push_str(text);
            }
            WordPiece::SingleQuotedText(text) => output.push_str(text),
            WordPiece::DoubleQuotedSequence(nested) => {
                append_static_pieces(nested, true, output)?;
            }
            WordPiece::EscapeSequence(escaped) => {
                output.extend(escaped.chars().skip(1));
            }
            WordPiece::AnsiCQuotedText(_)
            | WordPiece::GettextDoubleQuotedSequence(_)
            | WordPiece::TildeExpansion(_)
            | WordPiece::ParameterExpansion(_)
            | WordPiece::CommandSubstitution(_)
            | WordPiece::BackquotedCommandSubstitution(_)
            | WordPiece::ArithmeticExpression(_) => {
                return Err(ShellInspectionError::new(
                    "runtime expansion determines the resulting word",
                ));
            }
        }
    }
    Ok(())
}

fn has_pathname_expansion(text: &str) -> bool {
    text.contains(['*', '?', '['])
}

/// Refuse Brush's assignment-producing `printf` mode. `assign_to_named_parameter`
/// reparses the `-v` target as shell assignment syntax, including array
/// subscripts. Rejecting every `-v` target is intentionally more conservative
/// than attempting to duplicate that runtime grammar here.
///
/// A dynamic first argument also fails closed: after expansion and field
/// splitting it could select `-v` (or disappear and expose a following `-v`).
fn ensure_brush_printf_is_projectable(
    argv_words: &[&Word],
    options: &ParserOptions,
) -> Result<(), ShellInspectionError> {
    let Some(first_argument) = argv_words.get(1) else {
        return Ok(());
    };
    let first_argument = static_shell_word(first_argument, options).map_err(|_| {
        ShellInspectionError::new(
            "Brush `printf` has a dynamic first argument that could select `-v`; assignment \
             targets that are reparsed from runtime shell state cannot be approved from source",
        )
    })?;

    if first_argument != "--" && first_argument.starts_with("-v") {
        return Err(ShellInspectionError::new(
            "Brush `printf -v` reparses its assignment target against runtime shell state and is \
             deliberately excluded from the stable inspection projection",
        ));
    }

    Ok(())
}

fn is_find_program(program: &str) -> bool {
    classification_basename(program) == "find"
}

fn unprojectable_program_reason(program: &str) -> Option<&'static str> {
    let basename = classification_basename(program);

    if matches!(
        basename.as_str(),
        "eval"
            | "source"
            | "."
            | "trap"
            | "fc"
            | "builtin"
            | "command"
            | "env"
            | "xargs"
            | "exec"
            | "parallel"
            | "sudo"
            | "doas"
            | "nice"
            | "nohup"
            | "setsid"
            | "time"
            | "timeout"
            | "stdbuf"
            | "chroot"
            | "su"
            | "runuser"
            | "busybox"
            | "watch"
    ) {
        return Some(
            "this dispatcher can select, construct, or evaluate another command that is absent \
             from the flattened inventory",
        );
    }

    if is_shell_or_interpreter(&basename) {
        return Some(
            "this shell or interpreter can load or evaluate runtime code whose commands are \
             absent from the flattened inventory",
        );
    }

    None
}

/// Produce a classification-only basename for Windows and Unix spellings.
///
/// Windows executable lookup is case-insensitive and recognizes the standard
/// PATHEXT executable suffixes. This normalized copy is never written into the
/// public projection; `program`, `argv`, and exact source retain their original
/// spelling.
fn classification_basename(program: &str) -> String {
    let basename = program.rsplit(['/', '\\']).next().unwrap_or(program);
    let lowercase = basename.to_ascii_lowercase();
    for suffix in [".exe", ".com", ".bat", ".cmd"] {
        if let Some(stem) = lowercase.strip_suffix(suffix) {
            if !stem.is_empty() {
                return stem.to_string();
            }
        }
    }
    lowercase
}

fn is_shell_or_interpreter(basename: &str) -> bool {
    matches!(
        basename,
        "sh" | "ash"
            | "bash"
            | "dash"
            | "zsh"
            | "ksh"
            | "ksh93"
            | "mksh"
            | "fish"
            | "csh"
            | "tcsh"
            | "nu"
            | "elvish"
            | "xonsh"
            | "pwsh"
            | "powershell"
            | "cmd"
            | "python"
            | "python2"
            | "python3"
            | "pypy"
            | "pypy3"
            | "perl"
            | "ruby"
            | "php"
            | "lua"
            | "luajit"
            | "node"
            | "nodejs"
            | "deno"
            | "bun"
            | "tclsh"
            | "wish"
            | "awk"
            | "gawk"
            | "mawk"
            | "nawk"
            | "r"
            | "rscript"
            | "julia"
            | "osascript"
    ) || ["python", "pypy", "perl", "ruby", "php", "lua", "node"]
        .iter()
        .any(|stem| has_numeric_version_suffix(basename, stem))
}

fn has_numeric_version_suffix(basename: &str, stem: &str) -> bool {
    basename.strip_prefix(stem).is_some_and(|suffix| {
        !suffix.is_empty()
            && suffix.chars().any(|character| character.is_ascii_digit())
            && suffix
                .chars()
                .all(|character| character.is_ascii_digit() || matches!(character, '.' | '-'))
    })
}

fn inspect_find_descendants(
    argv_words: &[&Word],
    containing_source: &str,
    options: &ParserOptions,
    warnings: &mut Vec<String>,
) -> Result<Vec<DescendantExec>, ShellInspectionError> {
    let argv = argv_words
        .iter()
        .map(|word| {
            static_shell_word(word, options).map_err(|reason| {
                ShellInspectionError::new(format!(
                    "dynamic `find` argument `{}` prevents proving whether it delegates child execution: {reason}",
                    word.value
                ))
            })
        })
        .collect::<Result<Vec<_>, _>>()?;
    let mut descendants = Vec::new();
    let mut index = 1_usize;

    while index < argv.len() {
        let action = argv[index].as_str();
        if !matches!(action, "-exec" | "-execdir" | "-ok" | "-okdir") {
            index += 1;
            continue;
        }
        let program_index = index + 1;
        if program_index >= argv.len() {
            return Err(ShellInspectionError::new(format!(
                "`find {action}` is missing its descendant executable"
            )));
        }
        let terminator_index = (program_index + 1..argv.len())
            .find(|candidate| {
                argv[*candidate] == ";"
                    || (argv[*candidate] == "+"
                        && *candidate > program_index
                        && argv[*candidate - 1] == "{}")
            })
            .ok_or_else(|| {
                ShellInspectionError::new(format!(
                    "`find {action}` is missing its `;` or `+` terminator"
                ))
            })?;
        let descendant_argv = argv[program_index..terminator_index].to_vec();
        let program = descendant_argv.first().cloned().ok_or_else(|| {
            ShellInspectionError::new(format!(
                "`find {action}` is missing its descendant executable"
            ))
        })?;
        if program.is_empty() {
            return Err(ShellInspectionError::new(format!(
                "`find {action}` has an empty descendant executable"
            )));
        }
        let source = source_between_words(
            argv_words[index],
            argv_words[terminator_index],
            containing_source,
        )
        .unwrap_or_else(|| {
            argv_words[index..=terminator_index]
                .iter()
                .map(|word| word.value.as_str())
                .collect::<Vec<_>>()
                .join(" ")
        });
        let reason = format!(
            "external `find` interprets `{action}` and spawns `{program}` itself; Brush cannot independently intercept that descendant process"
        );
        warnings.push(format!("find {action}: {reason}"));
        descendants.push(DescendantExec {
            program,
            argv: descendant_argv,
            source,
            reason,
        });
        index = terminator_index + 1;
    }

    Ok(descendants)
}

fn source_between_words(first: &Word, last: &Word, source: &str) -> Option<String> {
    let first = first.location()?;
    let last = last.location()?;
    slice_char_range(source, first.start.index, last.end.index)
        .ok()
        .map(str::to_string)
}

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

    const COMPOUND_EXAMPLE: &str = r#"ls -1 $(find . -name "*.rs" -type f -exec wc -l {} + 2>/dev/null | sort -nr | head -10)"#;

    #[test]
    fn inspects_compound_substitution_pipeline_and_find_descendant() {
        let inspected = inspect_shell(COMPOUND_EXAMPLE).expect("inspection");

        assert_eq!(inspected.source, COMPOUND_EXAMPLE);
        assert_eq!(inspected.schema_version, INSPECTION_SCHEMA_VERSION);
        assert_eq!(inspected.commands.len(), 1);
        assert_eq!(inspected.commands[0].source, COMPOUND_EXAMPLE);
        assert_eq!(inspected.commands[0].program.as_deref(), Some("ls"));
        assert_eq!(
            inspected.commands[0].argv,
            vec![
                "ls",
                "-1",
                r#"$(find . -name "*.rs" -type f -exec wc -l {} + 2>/dev/null | sort -nr | head -10)"#
            ]
        );

        let construct = &inspected.constructs[0];
        assert_eq!(construct.kind, ShellConstructKind::CommandSubstitution);
        assert!(!construct.quoted);
        assert_eq!(
            construct.source,
            r#"$(find . -name "*.rs" -type f -exec wc -l {} + 2>/dev/null | sort -nr | head -10)"#
        );
        let inner = construct.inspection.as_deref().expect("inner inspection");
        assert_eq!(inner.commands.len(), 3);
        assert_eq!(
            inner
                .commands
                .iter()
                .map(|command| command.source.as_str())
                .collect::<Vec<_>>(),
            vec![
                r#"find . -name "*.rs" -type f -exec wc -l {} + 2>/dev/null"#,
                "sort -nr",
                "head -10"
            ]
        );
        assert_eq!(
            inner.commands[0].redirects,
            vec![InspectedRedirect {
                fd: Some(2),
                operation: RedirectOperation::Write,
                target: "/dev/null".to_string(),
            }]
        );
        assert_eq!(inner.commands[0].descendant_execs.len(), 1);
        assert_eq!(inner.commands[0].descendant_execs[0].program, "wc");
        assert_eq!(
            inner.commands[0].descendant_execs[0].argv,
            vec!["wc", "-l", "{}"]
        );
        assert_eq!(
            inner.commands[0].descendant_execs[0].source,
            "-exec wc -l {} +"
        );
        assert!(inner.warnings.iter().any(|warning| {
            warning.contains("find -exec") && warning.contains("cannot independently intercept")
        }));
    }

    #[test]
    fn preserves_nested_quoted_and_multiple_substitutions() {
        let source = r#"echo "$(printf '%s' "$(uname)")" $(pwd)"#;
        let inspected = inspect_shell(source).expect("inspection");

        assert_eq!(inspected.constructs.len(), 2);
        assert!(inspected.constructs[0].quoted);
        assert!(!inspected.constructs[1].quoted);
        let first_inner = inspected.constructs[0]
            .inspection
            .as_deref()
            .expect("first inner");
        assert_eq!(first_inner.constructs.len(), 1);
        assert!(first_inner.constructs[0].quoted);
        assert_eq!(first_inner.constructs[0].source, "$(uname)");
    }

    #[test]
    fn inspects_for_loop_values_before_flattened_body_commands() {
        let source = r#"for f in $(find . -name '*.rs' -type f); do wc -l "$f"; done"#;
        let inspected = inspect_shell(source).expect("inspection");

        assert_eq!(inspected.constructs.len(), 1);
        assert_eq!(
            inspected.constructs[0].kind,
            ShellConstructKind::CommandSubstitution
        );
        let inner = inspected.constructs[0]
            .inspection
            .as_deref()
            .expect("find substitution");
        assert_eq!(inner.commands[0].program.as_deref(), Some("find"));
        assert_eq!(inspected.commands.len(), 1);
        assert_eq!(inspected.commands[0].program.as_deref(), Some("wc"));
        assert_eq!(inspected.commands[0].source, r#"wc -l "$f""#);
        assert!(inspected
            .warnings
            .iter()
            .any(|warning| warning.contains("flattened control-flow projection")));
    }

    #[test]
    fn inspects_for_loop_piped_into_sort_and_head() {
        let source = r#"for f in $(find . -name '*.rs' -type f -not -path '*/target/*' -not -path '*/.git/*'); do wc -l "$f"; done | sort -nr | head -10"#;
        let inspected = inspect_shell(source).expect("inspection");

        assert_eq!(inspected.source, source);
        assert_eq!(inspected.constructs.len(), 1);
        assert_eq!(
            inspected.constructs[0].kind,
            ShellConstructKind::CommandSubstitution
        );
        assert!(!inspected.constructs[0].quoted);
        assert_eq!(
            inspected.constructs[0].body,
            r#"find . -name '*.rs' -type f -not -path '*/target/*' -not -path '*/.git/*'"#
        );
        let find = inspected.constructs[0]
            .inspection
            .as_deref()
            .expect("find substitution");
        assert_eq!(find.commands.len(), 1);
        assert_eq!(find.commands[0].program.as_deref(), Some("find"));
        assert_eq!(
            find.commands[0].argv,
            vec![
                "find",
                ".",
                "-name",
                "'*.rs'",
                "-type",
                "f",
                "-not",
                "-path",
                "'*/target/*'",
                "-not",
                "-path",
                "'*/.git/*'",
            ]
        );

        assert_eq!(
            inspected
                .commands
                .iter()
                .map(|command| command.program.as_deref())
                .collect::<Vec<_>>(),
            vec![Some("wc"), Some("sort"), Some("head")]
        );
        assert_eq!(
            inspected
                .commands
                .iter()
                .map(|command| command.source.as_str())
                .collect::<Vec<_>>(),
            vec![r#"wc -l "$f""#, "sort -nr", "head -10"]
        );
        assert!(inspected
            .warnings
            .iter()
            .any(|warning| warning.contains("flattened control-flow projection")));
    }

    #[test]
    fn reports_backquotes_and_arithmetic_without_evaluating_them() {
        let inspected = inspect_shell(r#"echo "$((1 + 2))" `pwd`"#).expect("inspection");
        assert_eq!(
            inspected
                .constructs
                .iter()
                .map(|construct| (construct.kind, construct.quoted))
                .collect::<Vec<_>>(),
            vec![
                (ShellConstructKind::ArithmeticExpansion, true),
                (ShellConstructKind::BackquoteSubstitution, false),
            ]
        );
        assert!(inspected.constructs[0].inspection.is_none());
        assert!(inspected.constructs[1].inspection.is_some());
    }

    #[test]
    fn accepts_only_state_free_arithmetic_for_complete_preflight() {
        let source = r#"echo "$((1 + 2 * (3 - 4)))" "$((1 ? 2 : 3))" "$((16#ff & 7))" "$[4 + 5]""#;
        let inspected = inspect_shell(source).expect("static arithmetic inspection");

        assert_eq!(inspected.constructs.len(), 4);
        assert!(inspected.constructs.iter().all(|construct| {
            construct.kind == ShellConstructKind::ArithmeticExpansion
                && construct.inspection.is_none()
        }));
        assert_eq!(inspected.constructs[0].body, "1 + 2 * (3 - 4)");
        assert_eq!(inspected.constructs[1].body, "1 ? 2 : 3");
        assert_eq!(inspected.constructs[2].body, "16#ff & 7");
        assert_eq!(inspected.constructs[3].body, "4 + 5");
    }

    #[test]
    fn non_static_arithmetic_fails_closed_before_brush_dispatch() {
        for source in [
            "echo $((counter))",
            "echo $[counter]",
            "echo $((array[index]))",
            "echo $((counter += 1))",
            "echo $((++counter))",
            "counter=2; echo $((counter + 1))",
            r#"payload='array[$(printf SHOULD_NOT_RUN >&2)0]'; echo "$((payload))""#,
            r#"index='$(printf SHOULD_NOT_RUN >&2)'; echo "$((array[index]))""#,
        ] {
            let error =
                inspect_shell(source).expect_err("runtime-state arithmetic must fail closed");
            assert!(
                error.message().contains("runtime shell state"),
                "unexpected refusal for `{source}`: {error}"
            );
        }

        for source in [
            "echo $(( $counter + 1 ))",
            "echo $(( ${counter} + 1 ))",
            "echo $(( $(printf 1) + 1 ))",
            "echo $(( `printf 1` + 1 ))",
            "echo $((1 + $((2))))",
        ] {
            assert!(
                inspect_shell(source).is_err(),
                "nested expansion must fail closed: {source}"
            );
        }
    }

    #[test]
    fn parameter_arithmetic_and_runtime_reexpansion_fail_closed() {
        inspect_shell(r#"echo "${array[1 + 2]}" "${value:1 + 2:3}""#)
            .expect("state-free parameter arithmetic");

        for (source, expected_reason) in [
            (
                r#"echo "${array[index]}""#,
                "parameter array subscript depends on runtime shell state",
            ),
            (
                r#"echo "${value:offset:2}""#,
                "parameter substring offset depends on runtime shell state",
            ),
            (
                r#"echo "${value:1:length}""#,
                "parameter substring length depends on runtime shell state",
            ),
            (
                r#"payload='$(printf SHOULD_NOT_RUN >&2)'; echo "${payload@P}""#,
                "prompt-expanding parameter transformation",
            ),
            (
                r#"ref='array[$(printf SHOULD_NOT_RUN >&2)0]'; echo "${!ref}""#,
                "indirect parameter expansion",
            ),
        ] {
            let error = inspect_shell(source)
                .expect_err("runtime-derived parameter evaluation must fail closed");
            assert!(
                error.message().contains(expected_reason),
                "unexpected refusal for `{source}`: {error}"
            );
        }
    }

    #[test]
    fn unicode_before_and_inside_substitution_keeps_exact_sources() {
        let source = r#"printf -- λπ"$(echo café)""#;
        let inspected = inspect_shell(source).expect("inspection");
        assert_eq!(inspected.commands[0].source, source);
        assert_eq!(inspected.constructs[0].source, "$(echo café)");
        assert_eq!(inspected.constructs[0].body, "echo café");
        assert!(inspected.constructs[0].quoted);
    }

    #[test]
    fn malformed_syntax_and_dynamic_executables_fail_closed() {
        assert!(inspect_shell("echo $(uname").is_err());
        assert!(inspect_shell("$PROGRAM --version").is_err());
        assert!(inspect_shell("find . -exec \"$PROGRAM\" {} +").is_err());
        assert!(inspect_shell(r#"eval "$(generate-script)""#).is_err());
        assert!(inspect_shell(r#"source "$(choose-file)""#).is_err());
    }

    #[test]
    fn executable_dispatchers_and_interpreters_fail_closed() {
        for source in [
            r#"builtin eval "$(generate-script)""#,
            r#"command source "$(choose-file)""#,
            r#"command find . -exec rm {} +"#,
            r#"env MODE=test sh -c "run-hidden-command""#,
            r#"xargs rm"#,
            r#"/usr/bin/env python3 -c "run_hidden_command()""#,
            r#"/opt/tools/python3.12 -c "run_hidden_command()""#,
        ] {
            let error = inspect_shell(source)
                .expect_err("a dispatcher or interpreter must not bypass inspection");
            assert!(
                error.message().contains("cannot be projected statically"),
                "unexpected refusal for `{source}`: {error}"
            );
        }
    }

    #[test]
    fn deferred_brush_builtins_fail_closed() {
        for source in [r#"trap 'run-hidden-command' EXIT"#, "fc -s"] {
            let error =
                inspect_shell(source).expect_err("a deferred evaluator must not be projected");
            assert!(
                error.message().contains("cannot be projected statically"),
                "unexpected refusal for `{source}`: {error}"
            );
        }
    }

    #[test]
    fn brush_printf_assignment_targets_fail_closed() {
        for source in [
            r#"printf -v result '%s' value"#,
            r#"printf -vresult '%s' value"#,
            r#"printf '-v' result '%s' value"#,
        ] {
            let error =
                inspect_shell(source).expect_err("Brush printf -v must not reparse a target");
            assert!(
                error.message().contains("`printf -v`")
                    && error.message().contains("reparses its assignment target"),
                "unexpected refusal for `{source}`: {error}"
            );
        }

        let dynamic = inspect_shell(r#"option=-v; printf "$option" result '%s' value"#)
            .expect_err("a dynamic first argument could select -v");
        assert!(
            dynamic.message().contains("dynamic first argument")
                && dynamic.message().contains("could select `-v`"),
            "unexpected dynamic-option refusal: {dynamic}"
        );

        inspect_shell(r#"printf -- -v literal"#).expect("`--` makes -v the literal format operand");
        inspect_shell(r#"printf '%s' -v literal"#)
            .expect("arguments after the format operand cannot select -v");
    }

    #[test]
    fn windows_executable_spellings_are_classified_without_changing_projection() {
        for (program, expected) in [
            ("python.exe", "python"),
            ("PowerShell.EXE", "powershell"),
            ("pwsh.exe", "pwsh"),
            ("find.exe", "find"),
            ("cmd.exe", "cmd"),
            ("python.COM", "python"),
            ("python.BAT", "python"),
            ("python.CMD", "python"),
        ] {
            assert_eq!(
                classification_basename(program),
                expected,
                "unexpected classification for {program}"
            );
        }

        for source in [
            r#"C:/Tools/PYTHON.EXE -c "run_hidden_command()""#,
            r#"C:/Tools/PowerShell.ExE -Command "run-hidden-command""#,
            r#"C:/Tools/PwSh.ExE -Command "run-hidden-command""#,
            r#"C:/Windows/System32/CmD.ExE /C "run-hidden-command""#,
        ] {
            let error =
                inspect_shell(source).expect_err("a Windows-spelled interpreter must fail closed");
            assert!(
                error.message().contains("cannot be projected statically"),
                "unexpected refusal for `{source}`: {error}"
            );
        }

        let source = r#"C:/Windows/System32/FIND.EXE . -exec WC.EXE -l {} +"#;
        let inspected = inspect_shell(source).expect("Windows-spelled find inspection");
        let find = &inspected.commands[0];
        assert_eq!(
            find.program.as_deref(),
            Some("C:/Windows/System32/FIND.EXE")
        );
        assert_eq!(find.argv[0], "C:/Windows/System32/FIND.EXE");
        assert_eq!(find.descendant_execs[0].program, "WC.EXE");
        assert_eq!(find.descendant_execs[0].source, "-exec WC.EXE -l {} +");
    }

    #[test]
    fn flattened_inventory_warns_when_control_relationships_are_not_encoded() {
        let inspected =
            inspect_shell("printf a | head -1 && printf b &").expect("flattened inspection");

        assert!(inspected
            .warnings
            .iter()
            .any(|warning| warning.contains("pipeline topology")));
        assert!(inspected
            .warnings
            .iter()
            .any(|warning| warning.contains("conditional relationship")));
        assert!(inspected
            .warnings
            .iter()
            .any(|warning| warning.contains("background lifecycle")));
    }

    #[test]
    fn find_exec_plus_is_a_terminator_only_after_placeholder() {
        let inspected =
            inspect_shell(r#"find . -exec printf '[%s]\n' + {} \;"#).expect("inspection");
        let descendant = &inspected.commands[0].descendant_execs[0];
        assert_eq!(
            descendant.argv,
            vec!["printf", "[%s]\\n", "+", "{}"],
            "a literal plus argument must not truncate the disclosed child argv"
        );
    }

    #[test]
    fn inspection_never_executes_substitutions() {
        let mut suffix = 0_u32;
        let marker = loop {
            let candidate = std::env::temp_dir().join(format!(
                "agent-bridle-shell-inspect-no-exec-{}-{suffix}",
                std::process::id()
            ));
            if !candidate.exists() {
                break candidate;
            }
            suffix += 1;
        };
        let source = format!("echo $(touch '{}')", marker.display());

        let inspected = inspect_shell(&source).expect("inspection");

        assert_eq!(inspected.constructs.len(), 1);
        assert!(!marker.exists(), "inspection executed the substitution");
    }

    #[test]
    fn projection_serializes_with_stable_field_names() {
        let value = serde_json::to_value(inspect_shell("printf ok").expect("inspection"))
            .expect("serialize");
        assert_eq!(value["source"], "printf ok");
        assert_eq!(value["schema_version"], INSPECTION_SCHEMA_VERSION);
        assert_eq!(value["commands"][0]["program"], "printf");
        assert_eq!(value["commands"][0]["argv"][0], "printf");
        assert!(value["commands"][0]["redirects"].is_array());
        assert!(value["commands"][0]["descendant_execs"].is_array());
        assert!(value["constructs"].is_array());
        assert!(value["warnings"].is_array());
    }
}