eggsact 1.2.7

Deterministic MCP and in-process utility tools for coding agents
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
use crate::mcp::machine_codes;
use crate::mcp::schemas::{disposition, finding, severity, verdict, ToolResponse};
use crate::tools::helpers::*;
use serde_json::Value;

pub fn shell_split(args: &Value) -> ToolResponse {
    let command = match args.get("command").and_then(|v| v.as_str()) {
        Some(s) => s,
        None => {
            return ToolResponse::error_with_code(
                "invalid_arguments",
                machine_codes::INVALID_ARGUMENTS,
                "Missing 'command' parameter",
                None,
                Some("shell_split"),
            )
        }
    };
    let shell = args
        .get("shell")
        .and_then(|v| v.as_str())
        .unwrap_or("posix");
    let detect_risky_features = args
        .get("detect_risky_features")
        .and_then(|v| v.as_bool())
        .unwrap_or(true);

    if command.len() > MAX_TEXT_LENGTH {
        return ToolResponse::error_with_code(
            "input_too_large",
            machine_codes::INPUT_TOO_LARGE,
            &format!("Command exceeds {} bytes", MAX_TEXT_LENGTH),
            None,
            Some("shell_split"),
        );
    }

    let valid_shells = ["posix"];
    if !valid_shells.contains(&shell) {
        return ToolResponse::error_with_code(
            "invalid_arguments",
            machine_codes::INVALID_ARGUMENTS,
            &format!("Unsupported shell: {}", shell),
            Some(vec!["Use one of: posix".to_string()]),
            Some("shell_split"),
        );
    }

    let result = crate::text::shell_split(command, shell, detect_risky_features);

    ToolResponse::success(
        serde_json::json!({
            "parse_ok": result.parse_ok,
            "argv": result.argv,
            "argc": result.argc,
            "features": {
                "has_pipe": result.features.has_pipe,
                "has_redirection": result.features.has_redirection,
                "has_command_substitution": result.features.has_command_substitution,
                "has_variable_expansion": result.features.has_variable_expansion,
                "has_glob_pattern": result.features.has_glob_pattern,
                "has_control_operator": result.features.has_control_operator,
                "has_background": result.features.has_background,
                "has_unbalanced_quotes": result.features.has_unbalanced_quotes,
            },
            "findings": result.findings,
        }),
        Some("shell_split"),
    )
    .with_tool("shell_split")
}

/// Project a typed `ShellSplitResult` to the `subresults["shell_split"]`
/// wire shape used by `command_preflight`. The standalone `shell_split`
/// tool keeps its full wire shape; the composite only needs argv and
/// features for downstream analysis.
fn shell_split_to_wire(result: &crate::text::shell::ShellSplitResult) -> serde_json::Value {
    serde_json::json!({
        "argv": result.argv,
        "features": {
            "has_pipe": result.features.has_pipe,
            "has_redirection": result.features.has_redirection,
            "has_command_substitution": result.features.has_command_substitution,
            "has_variable_expansion": result.features.has_variable_expansion,
            "has_glob_pattern": result.features.has_glob_pattern,
            "has_control_operator": result.features.has_control_operator,
            "has_background": result.features.has_background,
            "has_unbalanced_quotes": result.features.has_unbalanced_quotes,
        },
    })
}

pub fn shell_quote_join(args: &Value) -> ToolResponse {
    let argv_raw = match args.get("argv").and_then(|v| v.as_array()) {
        Some(arr) => arr,
        None => {
            return ToolResponse::error_with_code(
                "invalid_arguments",
                machine_codes::INVALID_ARGUMENTS,
                "Missing 'argv' parameter",
                None,
                Some("shell_quote_join"),
            )
        }
    };
    let shell = args
        .get("shell")
        .and_then(|v| v.as_str())
        .unwrap_or("posix");

    if argv_raw.len() > MAX_LIST_ITEMS {
        return ToolResponse::error_with_code(
            "input_too_large",
            machine_codes::INPUT_TOO_LARGE,
            &format!("argv length {} exceeds MAX_LIST_ITEMS", argv_raw.len()),
            None,
            Some("shell_quote_join"),
        );
    }

    let non_str_indices: Vec<usize> = argv_raw
        .iter()
        .enumerate()
        .filter(|(_, v)| !v.is_string())
        .map(|(i, _)| i)
        .collect();
    if !non_str_indices.is_empty() {
        return ToolResponse::error_with_code(
            "invalid_arguments",
            machine_codes::INVALID_ARGUMENTS,
            "All argv elements must be strings",
            Some(vec![format!(
                "Non-string items at indices: {:?}",
                &non_str_indices[..5.min(non_str_indices.len())]
            )]),
            Some("shell_quote_join"),
        );
    }
    let oversized_indices: Vec<usize> = argv_raw
        .iter()
        .enumerate()
        .filter(|(_, v)| v.as_str().is_some_and(|s| s.len() > MAX_TEXT_LENGTH))
        .map(|(i, _)| i)
        .collect();
    if !oversized_indices.is_empty() {
        return ToolResponse::error_with_code(
            "input_too_large",
            machine_codes::INPUT_TOO_LARGE,
            &format!("argv items exceed max length {}", MAX_TEXT_LENGTH),
            Some(vec![format!(
                "Oversized items at indices: {:?}",
                &oversized_indices[..5.min(oversized_indices.len())]
            )]),
            Some("shell_quote_join"),
        );
    }
    let mut argv: Vec<String> = Vec::with_capacity(argv_raw.len());
    for v in argv_raw.iter() {
        if let Some(s) = v.as_str() {
            argv.push(s.to_string());
        }
    }

    let valid_shells = ["posix"];
    if !valid_shells.contains(&shell) {
        return ToolResponse::error_with_code(
            "invalid_arguments",
            machine_codes::INVALID_ARGUMENTS,
            &format!("Unsupported shell: {}", shell),
            Some(vec![format!("Use one of: {}", valid_shells.join(", "))]),
            Some("shell_quote_join"),
        );
    }

    let result = crate::text::shell_quote_join(&argv, shell);

    ToolResponse::success(
        serde_json::json!({
            "command": result.command,
            "roundtrip_ok": result.roundtrip_ok,
            "findings": result.findings,
        }),
        Some("shell_quote_join"),
    )
    .with_tool("shell_quote_join")
}

pub fn argv_compare(args: &Value) -> ToolResponse {
    let left_command = args.get("left_command").and_then(|v| v.as_str());
    let right_command = args.get("right_command").and_then(|v| v.as_str());
    let left_argv = match args.get("left_argv").and_then(|v| v.as_array()) {
        Some(arr) => {
            if arr.len() > MAX_LIST_ITEMS {
                return ToolResponse::error_with_code(
                    "input_too_large",
                    machine_codes::INPUT_TOO_LARGE,
                    &format!("left_argv length {} exceeds {}", arr.len(), MAX_LIST_ITEMS),
                    None,
                    Some("argv_compare"),
                );
            }
            let non_str: Vec<usize> = arr
                .iter()
                .enumerate()
                .filter(|(_, v)| !v.is_string())
                .map(|(i, _)| i)
                .collect();
            if !non_str.is_empty() {
                return ToolResponse::error_with_code(
                    "invalid_arguments",
                    machine_codes::INVALID_ARGUMENTS,
                    "All left_argv elements must be strings",
                    Some(vec![format!(
                        "Non-string items at indices: {:?}",
                        &non_str[..5.min(non_str.len())]
                    )]),
                    Some("argv_compare"),
                );
            }
            let oversized: Vec<usize> = arr
                .iter()
                .enumerate()
                .filter(|(_, v)| v.as_str().is_some_and(|s| s.len() > MAX_TEXT_LENGTH))
                .map(|(i, _)| i)
                .collect();
            if !oversized.is_empty() {
                return ToolResponse::error_with_code(
                    "input_too_large",
                    machine_codes::INPUT_TOO_LARGE,
                    &format!("left_argv items exceed max length {}", MAX_TEXT_LENGTH),
                    Some(vec![format!(
                        "Oversized items at indices: {:?}",
                        &oversized[..5.min(oversized.len())]
                    )]),
                    Some("argv_compare"),
                );
            }
            Some(
                arr.iter()
                    .filter_map(|v| v.as_str().map(String::from))
                    .collect::<Vec<_>>(),
            )
        }
        None => None,
    };
    let right_argv = match args.get("right_argv").and_then(|v| v.as_array()) {
        Some(arr) => {
            if arr.len() > MAX_LIST_ITEMS {
                return ToolResponse::error_with_code(
                    "input_too_large",
                    machine_codes::INPUT_TOO_LARGE,
                    &format!("right_argv length {} exceeds {}", arr.len(), MAX_LIST_ITEMS),
                    None,
                    Some("argv_compare"),
                );
            }
            let non_str: Vec<usize> = arr
                .iter()
                .enumerate()
                .filter(|(_, v)| !v.is_string())
                .map(|(i, _)| i)
                .collect();
            if !non_str.is_empty() {
                return ToolResponse::error_with_code(
                    "invalid_arguments",
                    machine_codes::INVALID_ARGUMENTS,
                    "All right_argv elements must be strings",
                    Some(vec![format!(
                        "Non-string items at indices: {:?}",
                        &non_str[..5.min(non_str.len())]
                    )]),
                    Some("argv_compare"),
                );
            }
            let oversized: Vec<usize> = arr
                .iter()
                .enumerate()
                .filter(|(_, v)| v.as_str().is_some_and(|s| s.len() > MAX_TEXT_LENGTH))
                .map(|(i, _)| i)
                .collect();
            if !oversized.is_empty() {
                return ToolResponse::error_with_code(
                    "input_too_large",
                    machine_codes::INPUT_TOO_LARGE,
                    &format!("right_argv items exceed max length {}", MAX_TEXT_LENGTH),
                    Some(vec![format!(
                        "Oversized items at indices: {:?}",
                        &oversized[..5.min(oversized.len())]
                    )]),
                    Some("argv_compare"),
                );
            }
            Some(
                arr.iter()
                    .filter_map(|v| v.as_str().map(String::from))
                    .collect::<Vec<_>>(),
            )
        }
        None => None,
    };
    let shell = args
        .get("shell")
        .and_then(|v| v.as_str())
        .unwrap_or("posix");

    let valid_shells = ["posix"];
    if !valid_shells.contains(&shell) {
        return ToolResponse::error_with_code(
            "invalid_arguments",
            machine_codes::INVALID_ARGUMENTS,
            &format!("Unsupported shell: {}", shell),
            Some(vec![format!("Use one of: {}", valid_shells.join(", "))]),
            Some("argv_compare"),
        );
    }

    // XOR validation: each side must be either a *_command OR an *_argv, not both (and not neither).
    let left_both = left_command.is_some() == left_argv.is_some();
    let right_both = right_command.is_some() == right_argv.is_some();
    if left_both {
        let msg = if left_command.is_some() && left_argv.is_some() {
            "Provide exactly one of left_command or left_argv, not both"
        } else {
            "Provide exactly one of left_command or left_argv"
        };
        return ToolResponse::error_with_code(
            "invalid_arguments",
            machine_codes::INVALID_ARGUMENTS,
            msg,
            None,
            Some("argv_compare"),
        );
    }
    if right_both {
        let msg = if right_command.is_some() && right_argv.is_some() {
            "Provide exactly one of right_command or right_argv, not both"
        } else {
            "Provide exactly one of right_command or right_argv"
        };
        return ToolResponse::error_with_code(
            "invalid_arguments",
            machine_codes::INVALID_ARGUMENTS,
            msg,
            None,
            Some("argv_compare"),
        );
    }

    if let Some(cmd) = left_command {
        if cmd.len() > MAX_TEXT_LENGTH {
            return ToolResponse::error_with_code(
                "input_too_large",
                machine_codes::INPUT_TOO_LARGE,
                "Left command exceeds MAX_TEXT_LENGTH",
                None,
                Some("argv_compare"),
            );
        }
    }
    if let Some(cmd) = right_command {
        if cmd.len() > MAX_TEXT_LENGTH {
            return ToolResponse::error_with_code(
                "input_too_large",
                machine_codes::INPUT_TOO_LARGE,
                "Right command exceeds MAX_TEXT_LENGTH",
                None,
                Some("argv_compare"),
            );
        }
    }

    let left_ref = left_command;
    let right_ref = right_command;
    let left_argv_ref = left_argv.as_deref();
    let right_argv_ref = right_argv.as_deref();

    let result =
        crate::text::argv_compare(left_ref, right_ref, left_argv_ref, right_argv_ref, shell);

    ToolResponse::success(
        serde_json::json!({
            "argv_equal": result.argv_equal,
            "left_argv": result.left_argv,
            "right_argv": result.right_argv,
            "first_difference": result.first_difference,
            "findings": result.findings,
        }),
        Some("argv_compare"),
    )
    .with_tool("argv_compare")
}

// ---------------------------------------------------------------------------
// Command Policy Engine
// ---------------------------------------------------------------------------

/// Command classification for the allow/review/block matrix.
/// `allow` = permitted under this policy; `review` = needs human review;
/// `block` = always blocked.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum CmdDisposition {
    Allow,
    Review,
    Block,
}

/// Default classification matrix for the "default" policy.
/// Returns `(program, subcommand) -> CmdDisposition`.
fn classify_default(program: &str, subcommand: &str) -> CmdDisposition {
    match program {
        // Read-only tools — always allowed
        "rg" | "grep" | "find" | "ls" | "cat" | "head" | "tail" | "wc" | "file" | "which"
        | "where" | "type" | "echo" | "printf" | "realpath" | "pwd" | "readlink" | "stat"
        | "du" | "df" | "id" | "whoami" | "uname" | "date" => CmdDisposition::Allow,

        // Rust build/test — `cargo build` and `cargo bench` are reviewed because
        // build scripts and benches execute arbitrary code; safe subcommands are
        // allowed.
        "cargo" | "rustc" | "rustup" => match subcommand {
            "check" | "test" | "clippy" | "doc" | "search" | "version" | "list" | "tree"
            | "loc" => CmdDisposition::Allow,
            "fmt" | "fix" | "clean" | "publish" | "build" | "bench" => CmdDisposition::Review,
            _ => CmdDisposition::Review,
        },

        // Git — read operations allowed, write operations reviewed
        "git" => match subcommand {
            "status" | "diff" | "log" | "show" | "describe" | "rev-parse" | "remote" | "tag"
            | "blame" | "shortlog" => CmdDisposition::Allow,
            "add" | "checkout" | "restore" | "merge" | "rebase" | "cherry-pick" | "commit"
            | "fetch" | "pull" | "push" | "reset" | "revert" | "clean" | "config" | "branch"
            | "stash" => CmdDisposition::Review,
            _ => CmdDisposition::Review,
        },

        // Package managers
        "npm" | "yarn" | "pnpm" | "bun" => match subcommand {
            "list" | "ls" | "outdated" | "version" => CmdDisposition::Allow,
            "install" | "ci" | "update" | "add" | "remove" | "run" => CmdDisposition::Review,
            _ => CmdDisposition::Review,
        },
        "pip" | "pip3" => match subcommand {
            "install" | "uninstall" | "upgrade" => CmdDisposition::Review,
            _ => CmdDisposition::Review,
        },
        "python" | "python3" => match subcommand {
            "-c" | "-m" => CmdDisposition::Review,
            "install" | "uninstall" | "upgrade" => CmdDisposition::Review,
            _ => CmdDisposition::Review,
        },

        // Network tools — review
        "curl" | "wget" | "http" | "https" => CmdDisposition::Review,

        // Destructive tools — blocked
        "rm" | "rmdir" | "shred" | "wipefs" => CmdDisposition::Block,
        "chmod" | "chown" | "chgrp" => CmdDisposition::Block,
        "dd" | "mkfs" | "fdisk" | "parted" => CmdDisposition::Block,
        "sudo" | "su" | "doas" | "pkexec" => CmdDisposition::Block,

        // Wrapper programs — always review in strict mode
        "sh" | "bash" | "zsh" | "ksh" | "dash" | "fish" | "ash" | "busybox" | "node" | "deno"
        | "ruby" | "perl" | "lua" | "php" | "Rscript" => CmdDisposition::Review,

        // Script runners — review (cannot inspect underlying task)
        "make" | "just" | "task" => CmdDisposition::Review,

        // Process control — review
        "kill" | "pkill" | "killall" | "xkill" => CmdDisposition::Review,
        "nohup" | "screen" | "tmux" | "setsid" => CmdDisposition::Review,

        _ => CmdDisposition::Review,
    }
}

/// Strict policy: only explicitly safe commands are allowed.
fn classify_strict(program: &str, subcommand: &str) -> CmdDisposition {
    match program {
        "cargo" | "rustc" | "rustup" => match subcommand {
            "check" | "test" | "clippy" | "fmt" | "doc" | "search" | "version" | "list"
            | "tree" | "loc" => CmdDisposition::Allow,
            _ => CmdDisposition::Review,
        },
        "git" => match subcommand {
            "status" | "diff" | "log" | "show" | "describe" | "rev-parse" => CmdDisposition::Allow,
            _ => CmdDisposition::Review,
        },
        "rg" | "grep" | "find" | "ls" | "cat" | "head" | "tail" | "wc" | "which" | "echo"
        | "pwd" | "uname" | "date" => CmdDisposition::Allow,
        "rm" | "rmdir" | "shred" | "chmod" | "chown" | "chgrp" | "dd" | "mkfs" | "sudo" | "su"
        | "doas" => CmdDisposition::Block,
        // Wrapper programs — review under strict
        "sh" | "bash" | "zsh" | "ksh" | "dash" | "fish" | "node" | "deno" | "ruby" | "perl"
        | "lua" | "php" | "Rscript" => CmdDisposition::Review,
        // Script runners — review under strict
        "make" | "just" | "task" => CmdDisposition::Review,
        _ => CmdDisposition::Review,
    }
}

/// Permissive policy: only block clearly destructive or exfiltration patterns.
/// Wrapper programs with code-execution flags are reviewed even in permissive mode.
fn classify_permissive(program: &str, subcommand: &str) -> CmdDisposition {
    match program {
        "rm" | "rmdir" | "shred" | "wipefs" | "dd" | "mkfs" | "fdisk" | "parted" | "chmod"
        | "chown" | "chgrp" | "sudo" | "su" | "doas" | "pkexec" => CmdDisposition::Block,
        // Wrapper programs with code-execution flags — review (can't inspect nested command)
        "sh" | "bash" | "zsh" | "ksh" | "dash" | "fish" | "node" | "deno" | "bun" | "ruby"
        | "perl" | "lua" | "php" | "Rscript" | "python" | "python3" => {
            let code_flags = ["-c", "-e", "-x", "-l", "-eval"];
            if code_flags.contains(&subcommand) {
                CmdDisposition::Review
            } else {
                CmdDisposition::Allow
            }
        }
        _ => CmdDisposition::Allow,
    }
}

/// Select the classification function based on policy mode.
fn classify(program: &str, subcommand: &str, policy: &str) -> CmdDisposition {
    match policy {
        "strict" => classify_strict(program, subcommand),
        "permissive" => classify_permissive(program, subcommand),
        _ => classify_default(program, subcommand),
    }
}

/// Detect behavioral features of a command that may trigger findings.
fn detect_behavioral_features(
    argv: &[String],
    features: &Value,
) -> Vec<(&'static str, &'static str, &'static str)> {
    let mut result: Vec<(&str, &str, &str)> = Vec::new();
    if argv.is_empty() {
        return result;
    }
    let program = argv[0].as_str();

    // Network access detection
    let network_programs = [
        "curl",
        "wget",
        "http",
        "https",
        "nc",
        "ncat",
        "socat",
        "ssh",
        "scp",
        "sftp",
        "rsync",
        "telnet",
        "ftp",
        "nmap",
        "ping",
        "traceroute",
        "dig",
        "nslookup",
        "host",
    ];
    if network_programs.contains(&program) {
        result.push((
            machine_codes::SHELL_NETWORK_ACCESS,
            "NetworkAccess",
            "command accesses the network",
        ));
    }

    // Filesystem write detection
    let fs_write_programs = [
        "rm", "rmdir", "shred", "wipefs", "dd", "mkfs", "fdisk", "parted",
    ];
    let fs_write_subcommands = ["write", "create", "delete", "remove", "unlink"];
    if fs_write_programs.contains(&program) {
        result.push((
            machine_codes::SHELL_FILESYSTEM_WRITE,
            "FilesystemWrite",
            "command performs filesystem write/deletion",
        ));
    }
    if argv.len() > 1 && fs_write_subcommands.contains(&argv[1].as_str()) {
        result.push((
            machine_codes::SHELL_FILESYSTEM_WRITE,
            "FilesystemWrite",
            "subcommand performs filesystem write/deletion",
        ));
    }

    // Privilege escalation detection
    let priv_esc_programs = ["sudo", "su", "doas", "pkexec", "runas"];
    if priv_esc_programs.contains(&program) {
        result.push((
            machine_codes::SHELL_PRIVILEGE_ESCALATION,
            "PrivilegeEscalation",
            "command attempts privilege escalation",
        ));
    }

    // Process control detection
    let proc_control_programs = [
        "kill", "pkill", "killall", "xkill", "nohup", "screen", "tmux", "setsid",
    ];
    if proc_control_programs.contains(&program) {
        result.push((
            machine_codes::SHELL_PROCESS_CONTROL,
            "ProcessControl",
            "command controls system processes",
        ));
    }

    // Environment mutation detection (FOO=bar cmd pattern)
    // Scan all argv entries for env prefix assignments (shell_split may split FOO=bar cargo test)
    let is_assignment = argv.first().is_some_and(|arg| {
        arg.split_once('=').is_some_and(|(name, _)| {
            !name.is_empty()
                && name.chars().enumerate().all(|(i, c)| {
                    if i == 0 {
                        c.is_ascii_alphabetic() || c == '_'
                    } else {
                        c.is_ascii_alphanumeric() || c == '_'
                    }
                })
        })
    });
    if is_assignment {
        result.push((
            machine_codes::SHELL_ENV_MUTATION,
            "EnvMutation",
            "command mutates environment variables",
        ));
    }

    // Shell feature-based detection
    if let Some(obj) = features.as_object() {
        if obj
            .get("has_command_substitution")
            .and_then(|v| v.as_bool())
            == Some(true)
        {
            result.push((
                machine_codes::SHELL_COMMAND_SUBSTITUTION,
                "CommandSubstitution",
                "command uses command substitution",
            ));
        }
        if obj.get("has_redirection").and_then(|v| v.as_bool()) == Some(true) {
            result.push((
                machine_codes::SHELL_REDIRECTION,
                "Redirection",
                "command uses I/O redirection",
            ));
        }
        if obj.get("has_pipe").and_then(|v| v.as_bool()) == Some(true) {
            result.push((
                machine_codes::SHELL_PIPELINE,
                "Pipeline",
                "command uses a pipeline",
            ));
        }
        if obj.get("has_background").and_then(|v| v.as_bool()) == Some(true) {
            result.push((
                machine_codes::SHELL_BACKGROUND_EXECUTION,
                "BackgroundExecution",
                "command uses background execution (&)",
            ));
        }
    }

    result
}

/// Priority-ordered primary code selection.
/// Returns the highest-priority machine code from the collected codes.
fn select_primary_code(codes: &[String]) -> String {
    let priority = [
        machine_codes::SHELL_PARSE_ERROR,
        machine_codes::SHELL_DESTRUCTIVE_COMMAND,
        machine_codes::SHELL_PRIVILEGE_ESCALATION,
        machine_codes::SHELL_NETWORK_ACCESS,
        machine_codes::SHELL_FILESYSTEM_WRITE,
        machine_codes::SHELL_PROCESS_CONTROL,
        machine_codes::SHELL_COMMAND_SUBSTITUTION,
        machine_codes::SHELL_REDIRECTION,
        machine_codes::SHELL_PIPELINE,
        machine_codes::SHELL_BACKGROUND_EXECUTION,
        machine_codes::SHELL_UNAPPROVED_COMMAND,
        machine_codes::SHELL_ENV_MUTATION,
        machine_codes::SHELL_POLICY_REVIEW,
        machine_codes::SHELL_RISK,
        machine_codes::REGEX_RISK,
    ];
    for code in priority {
        if codes.iter().any(|c| c == code) {
            return code.to_string();
        }
    }
    machine_codes::COMMAND_OK.to_string()
}

/// Check for destructive shell patterns that should always block.
fn check_destructive_patterns(
    command: &str,
    argv: &[String],
) -> Vec<(&'static str, &'static str, &'static str)> {
    let mut result = Vec::new();
    let lower = command.to_lowercase();

    // Pipe-to-shell pattern: curl/wget ... | sh/bash/zsh
    if lower.contains("| sh")
        || lower.contains("| bash")
        || lower.contains("| zsh")
        || lower.contains("| python")
        || lower.contains("| perl")
        || lower.contains("| ruby")
    {
        result.push((
            machine_codes::SHELL_DESTRUCTIVE_COMMAND,
            "PipeToShell",
            "piping output to a shell interpreter is dangerous",
        ));
    }

    // rm -rf / or similar
    if argv.len() >= 2 && argv[0] == "rm" {
        let has_force_recursive = argv
            .iter()
            .any(|a| a == "-rf" || a == "-fr" || a == "-r" || a == "-f");
        let has_root = argv.iter().any(|a| a == "/" || a == "/*" || a == ".");
        if has_force_recursive && has_root {
            result.push((
                machine_codes::SHELL_DESTRUCTIVE_COMMAND,
                "DestructiveRemove",
                "rm -rf on root/parent paths is destructive",
            ));
        }
    }

    // git reset --hard, git clean -fdx, git push --force
    if argv.len() >= 3 && argv[0] == "git" {
        match argv[1].as_str() {
            "reset" if argv[2] == "--hard" => {
                result.push((
                    machine_codes::SHELL_DESTRUCTIVE_COMMAND,
                    "DestructiveGitReset",
                    "git reset --hard discards uncommitted changes",
                ));
            }
            "clean" => {
                let has_force = argv
                    .iter()
                    .any(|a| a == "-f" || a == "-fd" || a == "-fdx" || a == "-xdf");
                if has_force {
                    result.push((
                        machine_codes::SHELL_DESTRUCTIVE_COMMAND,
                        "DestructiveGitClean",
                        "git clean -f removes untracked files",
                    ));
                }
            }
            "push" => {
                let has_force = argv
                    .iter()
                    .any(|a| a == "--force" || a == "-f" || a == "--force-with-lease");
                if has_force {
                    result.push((
                        machine_codes::SHELL_DESTRUCTIVE_COMMAND,
                        "ForceGitPush",
                        "force-pushing rewrites remote history",
                    ));
                }
            }
            _ => {}
        }
    }

    // chmod -R 777 or chown -R
    if argv.len() >= 2 && argv[0] == "chmod" {
        let has_recursive = argv.iter().any(|a| a == "-R" || a == "--recursive");
        let has_permissive = argv
            .iter()
            .any(|a| a == "777" || a == "a+rwx" || a == "u+s");
        if has_recursive && has_permissive {
            result.push((
                machine_codes::SHELL_DESTRUCTIVE_COMMAND,
                "PermissiveChmod",
                "chmod -R 777 opens permissions globally",
            ));
        }
    }
    if argv.len() >= 2 && argv[0] == "chown" {
        let has_recursive = argv.iter().any(|a| a == "-R" || a == "--recursive");
        if has_recursive {
            result.push((
                machine_codes::SHELL_DESTRUCTIVE_COMMAND,
                "RecursiveChown",
                "recursive chown changes ownership broadly",
            ));
        }
    }

    result
}

pub fn command_preflight(args: &Value) -> ToolResponse {
    let budget_ctx = crate::mcp::budget::for_handler(crate::mcp::budget::ToolBudget::HEAVY);

    let command = match args.get("command").and_then(|v| v.as_str()) {
        Some(s) => s,
        None => {
            return ToolResponse::error_with_code(
                "invalid_arguments",
                machine_codes::INVALID_ARGUMENTS,
                "Missing 'command' parameter",
                None,
                Some("command_preflight"),
            )
        }
    };
    let platform = args
        .get("platform")
        .and_then(|v| v.as_str())
        .unwrap_or("posix");
    let policy = args
        .get("policy")
        .and_then(|v| v.as_str())
        .unwrap_or("default");
    let working_directory = args.get("working_directory").and_then(|v| v.as_str());

    if command.len() > MAX_TEXT_LENGTH {
        return ToolResponse::error_with_code(
            "input_too_large",
            machine_codes::INPUT_TOO_LARGE,
            &format!("Command exceeds {} bytes", MAX_TEXT_LENGTH),
            None,
            Some("command_preflight"),
        );
    }

    if let Some(wd) = working_directory {
        if wd.len() > MAX_TEXT_LENGTH {
            return ToolResponse::error_with_code(
                "input_too_large",
                machine_codes::INPUT_TOO_LARGE,
                &format!(
                    "working_directory length {} bytes exceeds {}",
                    wd.len(),
                    MAX_TEXT_LENGTH
                ),
                None,
                Some("command_preflight"),
            );
        }
        if wd.contains('\0') {
            return ToolResponse::error_with_code(
                "invalid_arguments",
                machine_codes::INVALID_ARGUMENTS,
                "working_directory must not contain null bytes",
                None,
                Some("command_preflight"),
            );
        }
    }

    let valid_platforms = ["posix", "windows", "auto"];
    if !valid_platforms.contains(&platform) {
        return ToolResponse::error_with_code(
            "invalid_arguments",
            machine_codes::INVALID_ARGUMENTS,
            &format!("Unsupported platform: {}", platform),
            Some(vec![format!("Use one of: {}", valid_platforms.join(", "))]),
            Some("command_preflight"),
        );
    }

    let valid_policies = ["default", "strict", "permissive"];
    if !valid_policies.contains(&policy) {
        return ToolResponse::error_with_code(
            "invalid_arguments",
            machine_codes::INVALID_ARGUMENTS,
            &format!("Unsupported policy: {}", policy),
            Some(vec![format!("Use one of: {}", valid_policies.join(", "))]),
            Some("command_preflight"),
        );
    }

    // Parse optional policy_config (structured override on top of policy enum)
    let policy_config = args.get("policy_config").cloned();
    let max_command_length = policy_config
        .as_ref()
        .and_then(|pc| pc.get("max_command_length").and_then(|v| v.as_u64()))
        .unwrap_or(MAX_TEXT_LENGTH as u64);

    if command.len() > max_command_length as usize {
        return ToolResponse::error_with_code(
            "input_too_large",
            machine_codes::INPUT_TOO_LARGE,
            &format!("Command exceeds {} bytes", max_command_length),
            None,
            Some("command_preflight"),
        );
    }

    let mut subresults = serde_json::Map::new();
    let mut findings: Vec<serde_json::Value> = Vec::new();
    let mut code_list: Vec<String> = Vec::new();
    let mut matched_rules: Vec<String> = Vec::new();

    // 1. Parse command via shell_split
    if platform == "windows" {
        return ToolResponse::error_with_code(
            "unsupported_platform",
            machine_codes::UNSUPPORTED_FEATURE,
            "Windows shell splitting is not supported; only 'posix' is available",
            Some(vec!["Use platform='posix' or platform='auto'".to_string()]),
            Some("command_preflight"),
        );
    }

    if budget_ctx.should_stop() {
        return budget_ctx
            .check_should_stop("command_preflight")
            .unwrap_err();
    }

    let shell = "posix";
    // Typed composition: consume the typed `text::shell::shell_split` core
    // directly. The `shell_split` subresult is a private projection of
    // `ShellSplitResult` to the standalone tool's wire shape (argv +
    // features). Parse-error info is captured in the typed result and
    // surfaced only via the `shell_split` subresult; the policy engine's
    // `RISKY_SHELL_FEATURE` finding (with `has_unbalanced_quotes`) drives
    // the wire-level primary machine code, preserving the prior
    // `SHELL_RISK` selection for unbalanced-quote inputs.
    let ss_result = crate::text::shell::shell_split(command, shell, true);
    subresults.insert("shell_split".to_string(), shell_split_to_wire(&ss_result));

    // Extract argv and features for downstream analysis
    let argv: Vec<String> = subresults
        .get("shell_split")
        .and_then(|r| r.get("argv"))
        .and_then(|v| v.as_array())
        .map(|arr| {
            arr.iter()
                .filter_map(|v| v.as_str().map(String::from))
                .collect()
        })
        .unwrap_or_default();

    let shell_features = subresults
        .get("shell_split")
        .and_then(|r| r.get("features"))
        .cloned()
        .unwrap_or(serde_json::json!({}));

    let program = argv.first().map(|s| s.as_str()).unwrap_or("");
    let subcommand = if argv.len() > 1 { argv[1].as_str() } else { "" };

    // 2. Apply policy_config custom allow/deny rules (deny beats allow)
    if let Some(ref config) = policy_config {
        let deny_commands: Vec<String> = config
            .get("deny_commands")
            .and_then(|v| v.as_array())
            .map(|arr| {
                arr.iter()
                    .filter_map(|v| v.as_str().map(String::from))
                    .collect()
            })
            .unwrap_or_default();
        let allow_commands: Vec<String> = config
            .get("allow_commands")
            .and_then(|v| v.as_array())
            .map(|arr| {
                arr.iter()
                    .filter_map(|v| v.as_str().map(String::from))
                    .collect()
            })
            .unwrap_or_default();

        if deny_commands.iter().any(|d| d == program) {
            code_list.push(machine_codes::SHELL_UNAPPROVED_COMMAND.to_string());
            findings.push(finding(
                "SHELL_UNAPPROVED_COMMAND",
                severity::HIGH,
                &format!("'{}' is in the deny list", program),
                Some(disposition::BLOCKING),
                None,
            ));
            matched_rules.push("deny_command".to_string());
        } else if !allow_commands.is_empty() && !allow_commands.iter().any(|a| a == program) {
            code_list.push(machine_codes::SHELL_UNAPPROVED_COMMAND.to_string());
            findings.push(finding(
                "SHELL_UNAPPROVED_COMMAND",
                severity::MEDIUM,
                &format!("'{}' is not in the allow list", program),
                Some(disposition::CAUTION),
                None,
            ));
            matched_rules.push("not_in_allow_list".to_string());
        }

        // Subcommand-level allow/deny
        let deny_subcommands: std::collections::HashMap<String, Vec<String>> = config
            .get("deny_subcommands")
            .and_then(|v| v.as_object())
            .map(|obj| {
                obj.iter()
                    .filter_map(|(k, v)| {
                        v.as_array().map(|arr| {
                            (
                                k.clone(),
                                arr.iter()
                                    .filter_map(|v| v.as_str().map(String::from))
                                    .collect(),
                            )
                        })
                    })
                    .collect()
            })
            .unwrap_or_default();
        if let Some(denied_subs) = deny_subcommands.get(program) {
            if denied_subs.iter().any(|s| s == subcommand) {
                code_list.push(machine_codes::SHELL_UNAPPROVED_COMMAND.to_string());
                findings.push(finding(
                    "SHELL_UNAPPROVED_COMMAND",
                    severity::HIGH,
                    &format!(
                        "'{} {}' is in the deny subcommands list",
                        program, subcommand
                    ),
                    Some(disposition::BLOCKING),
                    None,
                ));
                matched_rules.push("deny_subcommand".to_string());
            }
        }
    }

    // 3. Apply built-in policy classification (deny rules beat allow rules)
    let classify_disposition =
        if !code_list.contains(&machine_codes::SHELL_UNAPPROVED_COMMAND.to_string()) {
            classify(program, subcommand, policy)
        } else {
            CmdDisposition::Block
        };

    // If policy classifies as block and we don't already have a block finding, add it
    if classify_disposition == CmdDisposition::Block
        && !findings
            .iter()
            .any(|f| f.get("severity").and_then(|v| v.as_str()) == Some(severity::HIGH))
    {
        code_list.push(machine_codes::SHELL_UNAPPROVED_COMMAND.to_string());
        findings.push(finding(
            "SHELL_UNAPPROVED_COMMAND",
            severity::HIGH,
            &format!("'{}' is not permitted under {} policy", program, policy),
            Some(disposition::BLOCKING),
            None,
        ));
        matched_rules.push("policy_classify_block".to_string());
    } else if classify_disposition == CmdDisposition::Review
        && !findings
            .iter()
            .any(|f| f.get("severity").and_then(|v| v.as_str()) == Some(severity::HIGH))
        && !findings
            .iter()
            .any(|f| f.get("severity").and_then(|v| v.as_str()) == Some(severity::MEDIUM))
    {
        // Only add review finding if no higher-severity finding already present
        matched_rules.push("policy_classify_review".to_string());
        if !code_list.contains(&machine_codes::SHELL_POLICY_REVIEW.to_string()) {
            code_list.push(machine_codes::SHELL_POLICY_REVIEW.to_string());
        }
        findings.push(finding(
            machine_codes::SHELL_POLICY_REVIEW,
            severity::MEDIUM,
            &format!("'{}' requires review under {} policy", program, policy),
            Some(disposition::CAUTION),
            None,
        ));
    } else if classify_disposition == CmdDisposition::Allow {
        matched_rules.push("policy_classify_allow".to_string());
    }

    // 4. Detect destructive patterns (always block regardless of policy)
    let destructive = check_destructive_patterns(command, &argv);
    for (code, kind, message) in &destructive {
        if !code_list.contains(&code.to_string()) {
            code_list.push(code.to_string());
        }
        findings.push(finding(
            kind,
            severity::HIGH,
            message,
            Some(disposition::BLOCKING),
            None,
        ));
        matched_rules.push(format!("destructive:{}", kind));
    }

    // 5. Detect behavioral features (network, filesystem, process, env, shell features)
    let behavioral = detect_behavioral_features(&argv, &shell_features);

    // 5a. Filter behavioral findings based on policy_config allow_* overrides
    let allow_network = policy_config
        .as_ref()
        .and_then(|pc| pc.get("allow_network").and_then(|v| v.as_bool()))
        .unwrap_or(false);
    let allow_filesystem_write = policy_config
        .as_ref()
        .and_then(|pc| pc.get("allow_filesystem_write").and_then(|v| v.as_bool()))
        .unwrap_or(false);
    let allow_process_control = policy_config
        .as_ref()
        .and_then(|pc| pc.get("allow_process_control").and_then(|v| v.as_bool()))
        .unwrap_or(false);
    let allow_env_mutation = policy_config
        .as_ref()
        .and_then(|pc| pc.get("allow_env_mutation").and_then(|v| v.as_bool()))
        .unwrap_or(false);

    let behavioral: Vec<_> = behavioral
        .into_iter()
        .filter(|(code, _, _)| {
            if allow_network && *code == machine_codes::SHELL_NETWORK_ACCESS {
                matched_rules.push("allow_network".to_string());
                return false;
            }
            if allow_filesystem_write && *code == machine_codes::SHELL_FILESYSTEM_WRITE {
                matched_rules.push("allow_filesystem_write".to_string());
                return false;
            }
            if allow_process_control && *code == machine_codes::SHELL_PROCESS_CONTROL {
                matched_rules.push("allow_process_control".to_string());
                return false;
            }
            if allow_env_mutation && *code == machine_codes::SHELL_ENV_MUTATION {
                matched_rules.push("allow_env_mutation".to_string());
                return false;
            }
            true
        })
        .collect();
    for (code, kind, message) in &behavioral {
        let (sev, disp) = match *code {
            c if c == machine_codes::SHELL_PRIVILEGE_ESCALATION
                || c == machine_codes::SHELL_NETWORK_ACCESS =>
            {
                if policy == "strict" {
                    (severity::HIGH, disposition::BLOCKING)
                } else {
                    (severity::MEDIUM, disposition::CAUTION)
                }
            }
            _ => {
                if policy == "strict" {
                    (severity::MEDIUM, disposition::CAUTION)
                } else {
                    (severity::INFO, disposition::INFORMATIONAL)
                }
            }
        };
        if !code_list.contains(&code.to_string()) {
            code_list.push(code.to_string());
        }
        findings.push(finding(kind, sev, message, Some(disp), None));
        matched_rules.push(format!("feature:{}", kind));
    }

    // 6. Emit shell feature findings (pipe, redirect, command substitution, etc.)
    if budget_ctx.should_stop() {
        return budget_ctx
            .check_should_stop("command_preflight")
            .unwrap_err();
    }

    if let Some(obj) = shell_features.as_object() {
        let risky: Vec<&String> = obj
            .iter()
            .filter(|(_, v)| v.as_bool() == Some(true))
            .map(|(k, _)| k)
            .collect();
        for rf in &risky {
            let (sev, disp) = if policy == "strict" {
                (severity::HIGH, disposition::BLOCKING)
            } else {
                (severity::MEDIUM, disposition::CAUTION)
            };
            findings.push(finding("RISKY_SHELL_FEATURE", sev, rf, Some(disp), None));
        }
        if !risky.is_empty() && !code_list.contains(&machine_codes::SHELL_RISK.to_string()) {
            code_list.push(machine_codes::SHELL_RISK.to_string());
        }
    }

    // 7. Check for regex-like args in the command
    if budget_ctx.should_stop() {
        return budget_ctx
            .check_should_stop("command_preflight")
            .unwrap_err();
    }

    let looks_like_regex = command.contains("grep")
        || command.contains("sed")
        || command.contains("awk")
        || command.to_lowercase().contains("regex");

    if looks_like_regex && !argv.is_empty() {
        let regex_metachars: std::collections::HashSet<char> = ".*+?[]|^$\\(){}".chars().collect();
        let regex_args: Vec<&String> = argv
            .iter()
            .filter(|arg| {
                !arg.starts_with('-')
                    && !arg.is_empty()
                    && arg.chars().any(|c| regex_metachars.contains(&c))
            })
            .collect();
        for pattern in &regex_args {
            // Typed composition: call the deterministic core directly instead
            // of the regex_safety_check adapter (no JSON envelope round-trip).
            let rs_typed = crate::text::regex_safety_check(pattern.as_str());
            let risk = rs_typed.risk.as_str();
            let has_rs_findings = !rs_typed.findings.is_empty();
            for f in &rs_typed.findings {
                let (sev, disp) = if risk != "none" {
                    (severity::MEDIUM, disposition::CAUTION)
                } else {
                    (severity::INFO, disposition::INFORMATIONAL)
                };
                let kind = f.kind.as_str();
                findings.push(finding(
                    &kind.to_uppercase(),
                    sev,
                    f.message.as_str(),
                    Some(disp),
                    None,
                ));
            }
            if has_rs_findings
                && risk != "none"
                && !code_list.contains(&machine_codes::REGEX_RISK.to_string())
            {
                code_list.push(machine_codes::REGEX_RISK.to_string());
            }
            {
                let findings_count = rs_typed.findings.len();
                let regex_summary = serde_json::json!({
                    "pattern": pattern.as_str(),
                    "findings_count": findings_count,
                    "risk": risk,
                });
                let regex_subresults = subresults
                    .entry("regex_safety_check".to_string())
                    .or_insert_with(|| serde_json::json!([]));
                if let Some(items) = regex_subresults.as_array_mut() {
                    items.push(regex_summary);
                } else {
                    *regex_subresults = serde_json::json!([regex_summary]);
                }
            }
        }
    }

    // Handle working_directory traversal hint so it appears in findings/summary.
    if let Some(wd) = working_directory {
        if wd.contains("..") {
            findings.push(serde_json::json!({
                "machine_code": machine_codes::PATH_HAS_TRAVERSAL,
                "severity": "low",
                "message": format!("working_directory '{}' contains '..' traversal", wd),
                "disposition": "informational"
            }));
            code_list.push(machine_codes::PATH_HAS_TRAVERSAL.to_string());
        }
    }

    // 8. Determine verdict based on findings severity
    let has_critical = findings
        .iter()
        .any(|f| f.get("severity").and_then(|v| v.as_str()) == Some(severity::CRITICAL));
    let has_error = findings
        .iter()
        .any(|f| f.get("severity").and_then(|v| v.as_str()) == Some(severity::HIGH));
    let has_warn = findings
        .iter()
        .any(|f| f.get("severity").and_then(|v| v.as_str()) == Some(severity::MEDIUM));
    let response_verdict = if has_critical || has_error {
        verdict::BLOCK
    } else if has_warn {
        verdict::REVIEW
    } else {
        verdict::ALLOW
    };

    // 9. Select primary machine code by priority
    let has_parse_error = code_list.contains(&machine_codes::SHELL_PARSE_ERROR.to_string());
    let unique_codes: Vec<String> = code_list.into_iter().fold(Vec::new(), |mut acc, c| {
        if !acc.contains(&c) {
            acc.push(c);
        }
        acc
    });
    let primary_code = select_primary_code(&unique_codes);

    let feature_names: Vec<String> = shell_features
        .as_object()
        .map(|obj| {
            obj.iter()
                .filter(|(_, v)| v.as_bool() == Some(true))
                .map(|(k, _)| k.clone())
                .collect()
        })
        .unwrap_or_default();

    let summary = format!(
        "Command {} under {} policy ({} finding(s))",
        response_verdict,
        policy,
        findings.len()
    );

    let mut result = serde_json::json!({
        "verdict": response_verdict,
        "command": command,
        "platform": platform,
        "policy": policy,
        "program": program,
        "subcommand": subcommand,
        "features": feature_names,
        "findings": findings,
        "matched_rules": matched_rules,
        "machine_code": primary_code,
        "summary": summary,
    });
    if let Some(wd) = working_directory {
        result["working_directory"] = serde_json::json!(wd);
    }
    if !subresults.is_empty() {
        result["subresults"] = serde_json::Value::Object(subresults);
    }

    let mut resp =
        ToolResponse::success(result, Some("command_preflight")).with_tool("command_preflight");
    resp = resp
        .with_machine_code(&primary_code)
        .with_verdict(response_verdict);
    if !findings.is_empty() {
        resp = resp.with_findings(findings);
    }

    // 10. Emit recommended_next_tool when appropriate
    let has_unbalanced = shell_features
        .as_object()
        .and_then(|o| o.get("has_unbalanced_quotes"))
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    let has_non_ascii = !command.is_ascii();
    if has_unbalanced || has_parse_error {
        resp = resp.with_recommended_next_tool(ToolResponse::next_tool(
            "shell_split",
            "command has ambiguous parsing — verify with shell_split",
            Some(serde_json::json!({"command": command, "shell": shell})),
        ));
    } else if has_non_ascii {
        resp = resp.with_recommended_next_tool(ToolResponse::next_tool(
            "text_security_inspect",
            "command contains non-ASCII characters — run unicode security check",
            Some(serde_json::json!({"text": command})),
        ));
    }
    resp
}