selfware 0.6.1

Your personal AI workshop — software you own, software that lasts
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
//! Safety Validation Logic
//!
//! Core validation functions for checking tool calls, shell commands, and paths.

use crate::errors::{Result, SafetyError, SelfwareError};
use regex::Regex;
use std::path::PathBuf;
use std::sync::LazyLock;

use crate::api::types::ToolCall;
use crate::config::{is_local_endpoint, SafetyConfig};
use crate::safety::scanner::SecuritySeverity;

use super::types::*;

impl SafetyChecker {
    /// Create a safety checker with the given configuration
    pub fn new(config: &SafetyConfig) -> Self {
        Self {
            config: config.clone(),
            working_dir: std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
            security_scanner: crate::safety::scanner::SecurityScanner::new(),
        }
    }

    /// Create a safety checker with a specific working directory (test helper)
    #[cfg(test)]
    pub fn with_working_dir(config: &SafetyConfig, working_dir: PathBuf) -> Self {
        Self {
            config: config.clone(),
            working_dir,
            security_scanner: crate::safety::scanner::SecurityScanner::new(),
        }
    }

    /// Check if a tool call is safe to execute
    pub fn check_tool_call(&self, call: &ToolCall) -> Result<()> {
        let raw_name = &call.function.name;
        let tool_name = raw_name.trim();
        if raw_name != tool_name {
            tracing::debug!(
                "Tool name had whitespace: '{}' -> '{}'",
                raw_name,
                tool_name
            );
        }
        match tool_name {
            "file_write" | "file_edit" | "file_read" | "file_delete" | "search"
            | "directory_tree" | "file_list" | "analyze" | "tech_debt_report" => {
                let args: serde_json::Value = serde_json::from_str(&call.function.arguments)?;
                if let Some(path) = args.get("path").and_then(|v| v.as_str()) {
                    self.check_path(path)?;
                }
                // Scan content of file_write and file_edit for secrets
                if tool_name == "file_write" || tool_name == "file_edit" {
                    let content = args
                        .get("content")
                        .or_else(|| args.get("new_str"))
                        .and_then(|v| v.as_str())
                        .unwrap_or("");
                    if !content.is_empty() {
                        self.check_content_for_secrets(content)?;
                    }
                }
            }
            "shell_exec" => {
                let args: serde_json::Value = serde_json::from_str(&call.function.arguments)?;
                let cmd = args.get("command").and_then(|v| v.as_str()).unwrap_or("");
                self.check_shell_command(cmd)?;

                if let Some(cwd) = args.get("cwd").and_then(|v| v.as_str()) {
                    self.check_path(cwd)?;
                }
            }
            "git_commit" | "git_checkpoint" => {
                // Git operations are generally safe
            }
            "git_push" => {
                let args: serde_json::Value = serde_json::from_str(&call.function.arguments)?;
                let force = args.get("force").and_then(|v| v.as_bool()).unwrap_or(false);
                if force {
                    return Err(SelfwareError::Safety(SafetyError::BlockedForcePush));
                }
                // Only checkable here when the branch is explicit in the call --
                // when omitted the tool pushes whatever branch is currently
                // checked out, which GitPush::execute() itself re-checks
                // after resolving it (see src/tools/git.rs).
                if let Some(branch) = args.get("branch").and_then(|v| v.as_str()) {
                    if self
                        .config
                        .protected_branches
                        .iter()
                        .any(|b| b == branch)
                    {
                        return Err(SelfwareError::Safety(
                            SafetyError::BlockedProtectedBranchPush {
                                branch: branch.to_string(),
                                protected: self.config.protected_branches.clone(),
                            },
                        ));
                    }
                }
            }
            "container_exec" => {
                let args: serde_json::Value = serde_json::from_str(&call.function.arguments)?;
                if let Some(cmd) = args.get("command").and_then(|v| v.as_str()) {
                    self.check_shell_command(cmd)?;
                }
            }
            "container_run" => {
                let args: serde_json::Value = serde_json::from_str(&call.function.arguments)?;
                if let Some(cmd) = args.get("command").and_then(|v| v.as_str()) {
                    self.check_shell_command(cmd)?;
                }
                // Check for dangerous volume mounts
                if let Some(volumes) = args.get("volumes").and_then(|v| v.as_array()) {
                    for vol in volumes {
                        if let Some(mount) = vol.as_str() {
                            self.check_volume_mount(mount)?;
                        }
                    }
                }
            }
            "process_start" => {
                let args: serde_json::Value = serde_json::from_str(&call.function.arguments)?;
                if let Some(cmd) = args.get("command").and_then(|v| v.as_str()) {
                    self.check_shell_command(cmd)?;
                }
                if let Some(cwd) = args.get("cwd").and_then(|v| v.as_str()) {
                    self.check_path(cwd)?;
                }
            }
            "http_request" => {
                let args: serde_json::Value = serde_json::from_str(&call.function.arguments)?;
                if let Some(url) = args.get("url").and_then(|v| v.as_str()) {
                    self.check_http_request_url(url)?;
                }
            }
            "browser_fetch" | "browser_links" => {
                let args: serde_json::Value = serde_json::from_str(&call.function.arguments)?;
                if let Some(url) = args.get("url").and_then(|v| v.as_str()) {
                    self.check_browser_url(url)?;
                }
            }
            "browser_screenshot" | "browser_pdf" => {
                let args: serde_json::Value = serde_json::from_str(&call.function.arguments)?;
                if let Some(url) = args.get("url").and_then(|v| v.as_str()) {
                    self.check_browser_url(url)?;
                }
                if let Some(output_path) = args.get("output_path").and_then(|v| v.as_str()) {
                    self.check_path(output_path)?;
                }
            }
            "screen_capture" => {
                let args: serde_json::Value = serde_json::from_str(&call.function.arguments)?;
                if let Some(output_path) = args.get("output_path").and_then(|v| v.as_str()) {
                    self.check_path(output_path)?;
                }
            }
            "browser_eval" => {
                let args: serde_json::Value = serde_json::from_str(&call.function.arguments)?;
                if let Some(url) = args.get("url").and_then(|v| v.as_str()) {
                    self.check_browser_url(url)?;
                }
                if let Some(code) = args
                    .get("code")
                    .or_else(|| args.get("expression"))
                    .and_then(|v| v.as_str())
                {
                    self.check_browser_eval(code)?;
                }
            }
            "npm_install" | "pip_install" | "yarn_install" => {
                let args: serde_json::Value = serde_json::from_str(&call.function.arguments)?;
                if let Some(script) = args.get("script").and_then(|v| v.as_str()) {
                    self.check_shell_command(script)?;
                }
            }
            "git_status" | "git_diff" | "grep_search" | "glob_find" | "symbol_search"
            | "tool_search" | "process_list" | "process_logs" | "port_check" | "pip_list"
            | "pip_freeze" | "npm_scripts" | "container_list" | "container_logs"
            | "container_images" | "knowledge_query" | "knowledge_stats" | "knowledge_export"
            => {
                // These are read-only operations, safe to execute
            }
            "knowledge_add" | "knowledge_relate" | "knowledge_remove" | "knowledge_clear" => {
                // Knowledge graph mutations are in-memory only, no filesystem risk
            }
            "cargo_test" | "cargo_check" | "cargo_clippy" | "cargo_fmt" => {
                // These run predefined cargo subcommands, not arbitrary shell
            }
            "npm_run" => {
                let args: serde_json::Value = serde_json::from_str(&call.function.arguments)?;
                if let Some(script) = args.get("script").and_then(|v| v.as_str()) {
                    self.check_shell_command(script)?;
                }
            }
            "process_stop" | "process_restart" => {
                // These affect running processes by ID, no shell injection risk
            }
            "container_stop" | "container_remove" | "container_pull" | "container_build"
            | "compose_up" | "compose_down" => {
                // Container management by name/ID
            }
            "vision_analyze" | "vision_compare" => {
                let args: serde_json::Value = serde_json::from_str(&call.function.arguments)?;
                if let Some(endpoint) = args.get("endpoint").and_then(|v| v.as_str()) {
                    self.check_vision_endpoint_url(endpoint)?;
                }
                for key in &["image_path", "image_a", "image_b"] {
                    if let Some(p) = args.get(*key).and_then(|v| v.as_str()) {
                        self.check_path(p)?;
                    }
                }
            }
            "file_fim_edit" => {
                let args: serde_json::Value = serde_json::from_str(&call.function.arguments)?;
                if let Some(path) = args.get("path").and_then(|v| v.as_str()) {
                    self.check_path(path)?;
                }
            }
            "computer_screen" | "computer_window" => {
                // Screen capture returns base64 PNG in-memory
            }
            "code_introspect" | "code_query" | "code_plan" => {
                // These tools accept filesystem paths — validate them.
                let args: serde_json::Value = serde_json::from_str(&call.function.arguments)?;
                if let Some(path) = args.get("target").and_then(|v| v.as_str()) {
                    self.check_path(path)?;
                }
                if let Some(path) = args.get("path").and_then(|v| v.as_str()) {
                    self.check_path(path)?;
                }
            }
            "context_status"
            | "context_focus"
            | "context_evict"
            | "context_recommend"
            | "context_load_skeleton"
            | "context_bulk_read"
            | "context_summary" => {
                // Context tools interact with internal state only
            }
            "computer_mouse" | "computer_keyboard" => {
                // These manipulate the desktop
            }
            "page_control" => {
                let args: serde_json::Value = serde_json::from_str(&call.function.arguments)?;
                if let Some(url) = args.get("url").and_then(|v| v.as_str()) {
                    self.check_page_control_url(url)?;
                }
                if let Some(path) = args.get("path").and_then(|v| v.as_str()) {
                    self.check_path(path)?;
                }
                if let Some(expr) = args.get("expression").and_then(|v| v.as_str()) {
                    self.check_browser_eval(expr)?;
                }
            }
            // pty_shell is a shell tool — apply the same command checks as shell_exec.
            "pty_shell" => {
                let args: serde_json::Value = serde_json::from_str(&call.function.arguments)?;
                if let Some(cmd) = args.get("command").and_then(|v| v.as_str()) {
                    self.check_shell_command(cmd)?;
                }
            }
            // file_multi_edit mutates several files — validate EVERY edit path and
            // secret-scan each replacement, not just a top-level "path".
            "file_multi_edit" => {
                let args: serde_json::Value = serde_json::from_str(&call.function.arguments)?;
                if let Some(edits) = args.get("edits").and_then(|v| v.as_array()) {
                    for edit in edits {
                        if let Some(path) = edit.get("path").and_then(|v| v.as_str()) {
                            self.check_path(path)?;
                        }
                        if let Some(new_str) = edit.get("new_str").and_then(|v| v.as_str()) {
                            if !new_str.is_empty() {
                                self.check_content_for_secrets(new_str)?;
                            }
                        }
                    }
                }
            }
            // patch_apply targets paths embedded in the unified diff — validate the
            // `+++ b/<path>` targets and secret-scan the diff body.
            "patch_apply" => {
                let args: serde_json::Value = serde_json::from_str(&call.function.arguments)?;
                if let Some(diff) = args.get("diff").and_then(|v| v.as_str()) {
                    for line in diff.lines() {
                        if let Some(rest) = line.strip_prefix("+++ ") {
                            let p = rest.trim().trim_start_matches("b/");
                            if !p.is_empty() && p != "/dev/null" {
                                self.check_path(p)?;
                            }
                        }
                    }
                    self.check_content_for_secrets(diff)?;
                }
            }
            // Worktree tools operate on a worktree path — validate it.
            "enter_worktree" | "exit_worktree" => {
                let args: serde_json::Value = serde_json::from_str(&call.function.arguments)?;
                if let Some(path) = args.get("path").and_then(|v| v.as_str()) {
                    self.check_path(path)?;
                }
            }
            // Runtime dynamic-library loader (feature-gated, off by default) —
            // a native-code execution vector. Validate the library path it
            // loads so it can't pull code in from a denied location.
            "hot_reload" => {
                if let Ok(args) =
                    serde_json::from_str::<serde_json::Value>(&call.function.arguments)
                {
                    if let Some(path) = args.get("path").and_then(|v| v.as_str()) {
                        self.check_path(path)?;
                    }
                }
            }
            // Read-only / introspection tools: no filesystem or shell mutation.
            "list_worktrees"
            | "lsp_goto_definition"
            | "lsp_goto_implementation"
            | "lsp_find_references"
            | "lsp_hover"
            | "lsp_document_symbols"
            | "lsp_workspace_symbols"
            | "lsp_diagnostics"
            // Analysis / context / interaction tools: no filesystem or shell
            // mutation (metadata-classified read-only).
            | "code_metrics"
            | "code_map"
            | "code_diff_plan"
            | "context_budget"
            | "context_action"
            | "localize_issue"
            | "ask_user"
            | "knowledge_auto_extract" => {
                // Metadata-classified as read-only / network probes; nothing to
                // path- or command-check.
            }
            unknown => {
                // MCP tools are dynamically named `mcp_<server>_<tool>`; they are
                // registered (user-configured servers), so don't hard-block them.
                // Apply generic argument checks (path + command) and allow.
                if unknown.starts_with("mcp_") {
                    if let Ok(args) =
                        serde_json::from_str::<serde_json::Value>(&call.function.arguments)
                    {
                        if let Some(path) = args.get("path").and_then(|v| v.as_str()) {
                            self.check_path(path)?;
                        }
                        if let Some(cmd) = args.get("command").and_then(|v| v.as_str()) {
                            self.check_shell_command(cmd)?;
                        }
                    }
                    return Ok(());
                }
                tracing::error!(
                    "Safety checker: unregistered tool '{}' blocked — add to checker.rs dispatch if legitimate.",
                    unknown
                );
                return Err(SelfwareError::Safety(SafetyError::UnregisteredTool {
                    tool: unknown.to_string(),
                }));
            }
        }

        Ok(())
    }

    /// Check if a shell command is safe to execute
    ///
    /// SECURITY: This function implements multiple layers of protection:
    /// 1. Pattern matching against known dangerous commands (rm -rf /, mkfs, etc.)
    /// 2. Base64/hex encoded command detection (prevents `echo <base64> | base64 -d | sh`)
    /// 3. Command chaining analysis (checks each segment of chained commands)
    /// 4. Environment variable injection prevention
    pub fn check_shell_command(&self, cmd: &str) -> Result<()> {
        let normalized = normalize_shell_command(cmd);
        let dequoted = dequote_and_lowercase(&normalized);

        // SECURITY: Check for dangerous patterns
        for (pattern, description) in DANGEROUS_COMMAND_PATTERNS.iter() {
            if pattern.is_match(&normalized) || pattern.is_match(&dequoted) {
                return Err(SelfwareError::Safety(
                    SafetyError::DangerousCommandPattern {
                        description: (*description).to_string(),
                    },
                ));
            }
        }

        // Check for base64-encoded command execution
        if BASE64_EXEC_PATTERN.is_match(&normalized) || BASE64_EXEC_PATTERN.is_match(&dequoted) {
            return Err(SelfwareError::Safety(SafetyError::BlockedBase64Command));
        }

        // Check for hex-encoded command execution
        if HEX_EXEC_PATTERN.is_match(&normalized) || HEX_EXEC_PATTERN.is_match(&dequoted) {
            return Err(SelfwareError::Safety(SafetyError::BlockedHexCommand));
        }

        // Check for other encoding/obfuscation
        if ENCODED_EXEC_PATTERN.is_match(&normalized) || ENCODED_EXEC_PATTERN.is_match(&dequoted) {
            return Err(SelfwareError::Safety(SafetyError::BlockedEncodedCommand));
        }

        // denied_paths must also guard shell output redirects: without this,
        // `echo x > denied_file` bypasses the file-tool path checks entirely
        // (P1-8). Parse `>`/`>>` targets from the RAW command (preserving
        // case and quoting) and match them against the deny globs.
        for target in shell_output_redirect_targets(cmd) {
            if let Some(pattern) = redirect_target_matches_denied(
                &target,
                &self.working_dir,
                &self.config.denied_paths,
            ) {
                return Err(SelfwareError::Safety(SafetyError::PathDeniedPattern {
                    pattern,
                }));
            }
        }

        // `tee`/`sponge` writes bypass the redirect guard entirely — no `>`
        // appears in the command, so `echo KEY | tee -a ~/.ssh/authorized_keys`
        // sailed through BOTH write guards (whole-repo review, Safety P1).
        // Extract their file targets from every pipeline segment and run
        // them through the same denied-path matching as redirects.
        for target in shell_tee_write_targets(cmd) {
            if let Some(pattern) = redirect_target_matches_denied(
                &target,
                &self.working_dir,
                &self.config.denied_paths,
            ) {
                return Err(SelfwareError::Safety(SafetyError::PathDeniedPattern {
                    pattern,
                }));
            }
        }

        // The command BODY is also not covered by the allowed_paths
        // allow-list: only file_* tool `path` args and shell_exec's `cwd`
        // were validated, so `cat /etc/passwd` or `cp x ~/.ssh/y` succeeded
        // where the equivalent file_read/file_write was blocked (Safety P1).
        // Apply a conservative lexical check to file-targeting tokens.
        self.check_shell_command_paths(cmd)?;

        // Check command chaining
        for part in split_shell_commands(&normalized) {
            let part_trimmed = part.trim();
            for (pattern, description) in DANGEROUS_COMMAND_PATTERNS.iter() {
                if pattern.is_match(part_trimmed) {
                    return Err(SelfwareError::Safety(
                        SafetyError::DangerousCommandPattern {
                            description: format!("{} (in chain)", *description),
                        },
                    ));
                }
            }
        }

        // Check for environment variable injection
        static DANGEROUS_ENV_VARS: LazyLock<Regex> = LazyLock::new(|| {
            Regex::new(r"(?i)^\s*(PATH|LD_PRELOAD|LD_LIBRARY_PATH|DYLD_INSERT_LIBRARIES|DYLD_LIBRARY_PATH|PYTHONPATH|NODE_PATH|PERL5LIB|RUBYLIB|CLASSPATH|HOME|SHELL|USER|TERM|IFS)\s*=")
                .expect("Invalid regex")
        });

        for part in split_shell_commands(&normalized) {
            let part_trimmed = part.trim();
            if DANGEROUS_ENV_VARS.is_match(part_trimmed) {
                return Err(SelfwareError::Safety(SafetyError::BlockedEnvInjection));
            }
        }

        // The dedicated git_push tool enforces protected_branches, but an
        // agent can bypass that entirely by invoking git directly through
        // shell_exec/container_exec -- catch explicit protected-branch
        // targets here too (see git_push_protected_branch_target's doc
        // comment for what this does and doesn't catch).
        for part in split_shell_commands(&normalized) {
            if let Some(branch) =
                git_push_protected_branch_target(part.trim(), &self.config.protected_branches)
            {
                return Err(SelfwareError::Safety(
                    SafetyError::BlockedProtectedBranchPush {
                        branch,
                        protected: self.config.protected_branches.clone(),
                    },
                ));
            }
        }

        Ok(())
    }

    /// Conservative `allowed_paths`/`denied_paths` check for shell command
    /// bodies (whole-repo review, Safety P1).
    ///
    /// `file_*` tools validate their `path` argument, but shell tools
    /// (`shell_exec`, `pty_shell`, `container_exec`, `process_start`, npm/pip
    /// scripts) used to check only the `cwd` argument — the command body
    /// could read or write any path, asymmetric with the blocked
    /// `file_read`/`file_write` of the very same path. This closes the gap
    /// with a deliberately conservative heuristic (fail-open where unsure,
    /// to keep everyday commands working):
    ///
    /// - Candidate paths are (a) the non-flag operands of common file verbs
    ///   (see [`FILE_TARGET_VERBS`] — `dd` contributes its `if=`/`of=`
    ///   values, `chmod` skips its mode operand) and (b) any token that
    ///   *looks like an explicit path*: absolute (`/x`, `C:/x`),
    ///   home-relative (`~/x`), or dot-relative (`./x`, `../x`). Bare words
    ///   (`README.md`) are only candidates after a file verb, so strings,
    ///   URLs, and parenthesized arguments are never treated as paths.
    /// - The command word itself (running system binaries like
    ///   `/usr/bin/python` stays allowed), redirect targets (`>`/`>>` —
    ///   owned by the denied-path redirect guard above, which deliberately
    ///   allows scratch writes like `2> /tmp/x.log`), and `tee`/`sponge`
    ///   operands (owned by the tee guard above) are excluded.
    /// - Each candidate is matched against `denied_paths` with the same
    ///   matcher the redirect guard uses, and — only when `allowed_paths`
    ///   is non-empty — must match the allow-list after lexical resolution
    ///   against the working dir (with a leading `~` expanded). Failures
    ///   return the same errors the file tools return
    ///   (`PathDeniedPattern`/`PathNotAllowed`).
    ///
    /// Documented fail-open gaps: paths hidden in `--flag=VALUE` pairs,
    /// command substitution `$(…)`, nested `sh -c '…'`, and remote
    /// `host:path` operands are not extracted.
    fn check_shell_command_paths(&self, cmd: &str) -> Result<()> {
        for segment in split_shell_pipeline(cmd) {
            let Some(tokens) = shlex::split(segment) else {
                continue;
            };
            let Some(cmd_idx) = command_word_index(&tokens) else {
                continue;
            };
            let verb = command_basename(&tokens[cmd_idx]);
            // tee/sponge operands are write targets owned by the tee guard
            // (denied-only semantics, same as redirects) — skip them here.
            if verb == "tee" || verb == "sponge" {
                continue;
            }
            let is_file_verb = FILE_TARGET_VERBS.contains(&verb);
            let mut chmod_mode_seen = false;
            let mut flags_done = false;
            // What to do with the token after a redirect operator: `>`
            // targets belong to the redirect guard (skip), `<` targets are
            // reads we must check (take), `<<` heredoc delimiters are not
            // paths (skip).
            enum Redirect {
                None,
                Skip,
                Take,
            }
            let mut pending = Redirect::None;
            for (i, tok) in tokens.iter().enumerate() {
                if i == cmd_idx {
                    continue; // the program being run is not a path operand
                }
                match pending {
                    Redirect::Skip => {
                        pending = Redirect::None;
                        continue;
                    }
                    Redirect::Take => {
                        pending = Redirect::None;
                        self.check_shell_path_candidate(tok)?;
                        continue;
                    }
                    Redirect::None => {}
                }
                let stripped = tok.trim_start_matches(|c: char| c.is_ascii_digit());
                if let Some(rest) = stripped.strip_prefix("<<") {
                    // Heredoc: `<<EOF` glues the delimiter word onto the
                    // token; `<< EOF` takes the next one. Neither is a path.
                    if rest.is_empty() {
                        pending = Redirect::Skip;
                    }
                    continue;
                }
                if let Some(rest) = stripped.strip_prefix('<') {
                    // Input redirect = a read target, glued (`</etc/passwd`)
                    // or separate (`< /etc/passwd`).
                    if rest.is_empty() {
                        pending = Redirect::Take;
                    } else {
                        self.check_shell_path_candidate(rest)?;
                    }
                    continue;
                }
                if matches!(stripped, ">" | ">>" | ">|") {
                    // A separated output-redirect target (`> file`) belongs
                    // to the redirect guard — skip it here. Glued forms
                    // (`>file`, `2>file`, `>&1`) keep no state: their
                    // targets are extracted from the raw command by the
                    // redirect guard.
                    pending = Redirect::Skip;
                    continue;
                }
                if stripped.starts_with('>') {
                    continue;
                }
                if tok == "--" {
                    flags_done = true;
                    continue;
                }
                if !flags_done && tok.starts_with('-') && tok.len() > 1 {
                    continue; // flag (possibly glued `-oFILE` — a documented gap)
                }
                if is_file_verb {
                    if verb == "dd" {
                        if let Some(v) = tok.strip_prefix("if=").or_else(|| tok.strip_prefix("of="))
                        {
                            self.check_shell_path_candidate(v)?;
                        }
                        continue; // bs=/count=/… operands are not paths
                    }
                    if verb == "chmod" && !chmod_mode_seen {
                        chmod_mode_seen = true; // the mode operand is not a path
                        continue;
                    }
                    self.check_shell_path_candidate(tok)?;
                    continue;
                }
                if looks_like_explicit_path(tok) {
                    self.check_shell_path_candidate(tok)?;
                }
            }
        }
        Ok(())
    }

    /// Validate one extracted shell-command path token against
    /// `denied_paths` (same matcher as redirect targets) and, when
    /// `allowed_paths` is non-empty, against the allow-list. A leading `~`
    /// is expanded so home-relative tokens see the same absolute path the
    /// shell would use.
    fn check_shell_path_candidate(&self, candidate: &str) -> Result<()> {
        let expanded = expand_home_token(candidate);
        {
            let forms: &[&str] = if expanded == candidate {
                &[candidate]
            } else {
                &[candidate, expanded.as_str()]
            };
            for form in forms {
                if let Some(pattern) = redirect_target_matches_denied(
                    form,
                    &self.working_dir,
                    &self.config.denied_paths,
                ) {
                    return Err(SelfwareError::Safety(SafetyError::PathDeniedPattern {
                        pattern,
                    }));
                }
            }
        }
        if self.config.allowed_paths.is_empty() {
            return Ok(());
        }
        let resolved = resolve_redirect_target_lexical(&expanded, &self.working_dir);
        use crate::safety::path_validator::PathValidator;
        let validator = PathValidator::new(&self.config, self.working_dir.clone());
        let allowed = validator
            .is_path_in_allowed_list(&resolved, candidate)
            .unwrap_or(false);
        if !allowed {
            return Err(SelfwareError::Safety(SafetyError::PathNotAllowed {
                path: resolved,
            }));
        }
        Ok(())
    }

    /// Scan content for hardcoded secrets
    fn check_content_for_secrets(&self, content: &str) -> Result<()> {
        let result = self.security_scanner.scan_content(content, None, "");
        let blocked: Vec<_> = result
            .findings
            .iter()
            .filter(|f| f.severity >= SecuritySeverity::High)
            .collect();
        if !blocked.is_empty() {
            let titles: Vec<_> = blocked.iter().map(|f| f.title.as_str()).collect();
            return Err(SelfwareError::Safety(SafetyError::SecretDetected {
                finding: titles.join(", "),
            }));
        }
        Ok(())
    }

    /// Check a container volume mount
    fn check_volume_mount(&self, mount: &str) -> Result<()> {
        let host_path = mount.split(':').next().unwrap_or("");
        let dangerous_mounts = [
            "/", "/etc", "/boot", "/usr", "/var", "/root", "/sys", "/proc", "/lib", "/lib64",
            "/opt", "/run",
        ];
        if host_path.contains("/.ssh")
            || host_path == ".ssh"
            || host_path == "~/.ssh"
            || host_path.starts_with("~/.ssh/")
        {
            return Err(SelfwareError::Safety(SafetyError::ContainerSshMount {
                mount: mount.to_string(),
            }));
        }
        for dm in &dangerous_mounts {
            if host_path == *dm
                || (host_path.starts_with(dm) && host_path.as_bytes().get(dm.len()) == Some(&b'/'))
            {
                return Err(SelfwareError::Safety(SafetyError::ContainerSystemMount {
                    mount: mount.to_string(),
                    directory: (*dm).to_string(),
                }));
            }
        }
        Ok(())
    }

    /// Check HTTP request URL for SSRF
    fn check_http_request_url(&self, url: &str) -> Result<()> {
        self.check_url_ssrf_with_options(
            url,
            UrlSafetyOptions {
                allow_file_scheme: false,
                allow_localhost: true,
            },
            std::env::var("SELFWARE_ALLOW_PRIVATE_NETWORK").unwrap_or_default() == "1",
        )
    }

    /// Check browser URL
    fn check_browser_url(&self, url: &str) -> Result<()> {
        self.check_url_ssrf_with_options(
            url,
            UrlSafetyOptions {
                allow_file_scheme: false,
                allow_localhost: true,
            },
            std::env::var("SELFWARE_ALLOW_PRIVATE_NETWORK").unwrap_or_default() == "1",
        )
    }

    /// Check page control URL
    fn check_page_control_url(&self, url: &str) -> Result<()> {
        if url.starts_with("file://") {
            let parsed = url::Url::parse(url)?;
            let path = parsed
                .to_file_path()
                .map_err(|_| anyhow::anyhow!("file:// URL must point to a local absolute path"))?;
            let path_str = path.to_string_lossy();
            return self.check_path(&path_str);
        }

        self.check_url_ssrf_with_options(
            url,
            UrlSafetyOptions {
                allow_file_scheme: false,
                allow_localhost: true,
            },
            std::env::var("SELFWARE_ALLOW_PRIVATE_NETWORK").unwrap_or_default() == "1",
        )
    }

    /// Check vision endpoint URL
    fn check_vision_endpoint_url(&self, url: &str) -> Result<()> {
        self.check_url_ssrf_with_options(
            url,
            UrlSafetyOptions {
                allow_file_scheme: false,
                allow_localhost: true,
            },
            std::env::var("SELFWARE_ALLOW_PRIVATE_NETWORK").unwrap_or_default() == "1",
        )
    }

    /// Check URL for SSRF with options
    ///
    /// SECURITY: Implements SSRF (Server-Side Request Forgery) protection by:
    /// 1. Blocking dangerous URI schemes (file:, gopher:, dict:, ftp:)
    /// 2. Blocking cloud metadata endpoints (169.254.169.254, etc.)
    /// 3. Blocking encoded IP bypass attempts (hex, octal, decimal representations)
    /// 4. Blocking link-local addresses
    /// 5. Validating IP literals against private/internal ranges
    pub(crate) fn check_url_ssrf_with_options(
        &self,
        url: &str,
        options: UrlSafetyOptions,
        allow_private: bool,
    ) -> Result<()> {
        let lower = url.to_lowercase();

        // SECURITY: Block dangerous URI schemes that could access local resources
        for scheme in &["file:", "gopher:", "dict:", "ftp:"] {
            if *scheme == "file:" && options.allow_file_scheme && lower.starts_with("file:") {
                return Ok(());
            }
            if lower.starts_with(scheme) {
                return Err(SelfwareError::Safety(SafetyError::BlockedUrlScheme {
                    scheme: (*scheme).trim_end_matches(':').to_string(),
                }));
            }
        }

        // Block cloud metadata endpoints
        let blocked_hosts = [
            "169.254.169.254",
            "metadata.google.internal",
            "[fd00:ec2::254]",
            "100.100.100.200",
        ];
        for host in &blocked_hosts {
            if lower.contains(host) {
                return Err(SelfwareError::Safety(SafetyError::BlockedCloudMetadata {
                    host: (*host).to_string(),
                }));
            }
        }

        // Block encoded IP bypasses
        let encoded_bypasses = [
            "0xa9fea9fe",
            "0xa9.0xfe.0xa9.0xfe",
            "2852039166",
            "0251.0376.0251.0376",
            "0x646464c8",
            "0x64.0x64.0x64.0xc8",
            "1684300232",
            "0144.0144.0144.0310",
        ];
        for encoded in &encoded_bypasses {
            if lower.contains(encoded) {
                return Err(SelfwareError::Safety(SafetyError::BlockedEncodedMetadata));
            }
        }

        // Block link-local range
        if lower.contains("169.254.") {
            return Err(SelfwareError::Safety(SafetyError::BlockedLinkLocal));
        }

        // Check IP literals
        if let Ok(parsed) = url::Url::parse(url) {
            if options.allow_localhost && is_local_endpoint(url) {
                return Ok(());
            }
            if let Some(host) = parsed.host_str() {
                if let Ok(ip) = host.parse::<std::net::IpAddr>() {
                    if is_private_or_internal(ip) && !allow_private {
                        return Err(SelfwareError::Safety(SafetyError::BlockedPrivateNetwork {
                            ip: ip.to_string(),
                        }));
                    }
                }
            }
        }

        Ok(())
    }

    /// Check browser eval for data exfiltration
    fn check_browser_eval(&self, code: &str) -> Result<()> {
        let lower = code.to_lowercase();
        if (lower.contains("fetch(") || lower.contains("xmlhttprequest"))
            && (lower.contains("document.cookie") || lower.contains("localstorage"))
        {
            return Err(SelfwareError::Safety(SafetyError::BlockedBrowserEval));
        }
        Ok(())
    }

    /// Check file path
    fn check_path(&self, path: &str) -> Result<()> {
        use crate::safety::path_validator::PathValidator;
        let validator = PathValidator::new(&self.config, self.working_dir.clone());
        validator.validate(path).map_err(|e| match e {
            crate::errors::SelfwareError::Safety(safety_err) => {
                crate::errors::SelfwareError::Safety(safety_err)
            }
            other => other,
        })
    }

    /// Check if path is in allowed list (test helper)
    #[cfg(test)]
    #[allow(dead_code)]
    fn is_path_in_allowed_list(&self, canonical_str: &str, _original_path: &str) -> Result<bool> {
        use crate::safety::path_validator::PathValidator;
        let validator = PathValidator::new(&self.config, self.working_dir.clone());
        validator
            .is_path_in_allowed_list(canonical_str, _original_path)
            .map_err(|e| match e {
                crate::errors::SelfwareError::Safety(safety_err) => {
                    crate::errors::SelfwareError::Safety(safety_err)
                }
                other => other,
            })
    }
}

/// Normalize a shell command
pub fn normalize_shell_command(cmd: &str) -> String {
    let mut quoted_segments: Vec<String> = Vec::new();
    let mut unquoted = String::with_capacity(cmd.len());
    let bytes = cmd.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        let c = bytes[i];
        if (c == b'"' || c == b'\'') && (i == 0 || bytes[i - 1] != b'\\') {
            let quote = c;
            let seg_start = i;
            i += 1;
            while i < bytes.len() && !(bytes[i] == quote && bytes[i - 1] != b'\\') {
                i += 1;
            }
            if i < bytes.len() {
                i += 1;
            }
            let placeholder = format!("\x00\x01{}\x00", quoted_segments.len());
            quoted_segments.push(cmd[seg_start..i].to_string());
            unquoted.push_str(&placeholder);
        } else {
            unquoted.push(c as char);
            i += 1;
        }
    }

    let mut result: String = unquoted.split_whitespace().collect::<Vec<_>>().join(" ");
    result = result.to_lowercase();
    while result.contains("//") {
        result = result.replace("//", "/");
    }
    result = result.replace("\\n", "").replace("\\t", " ");

    // Remove backslash escapes
    let mut deslashed = String::with_capacity(result.len());
    let result_bytes = result.as_bytes();
    let mut j = 0;
    while j < result_bytes.len() {
        if result_bytes[j] == b'\\' && j + 1 < result_bytes.len() {
            let next = result_bytes[j + 1];
            if next.is_ascii_alphanumeric() || next == b'_' || next == b'-' || next == b'/' {
                j += 1;
                continue;
            }
        }
        deslashed.push(result_bytes[j] as char);
        j += 1;
    }
    result = deslashed;

    result = result.replace('`', "$(");
    result = result.replace("$(", " $( ");
    result = result.replace(')', " ) ");
    result = result.replace(" | ", "|");
    result = result.replace("| ", "|");
    result = result.replace(" |", "|");
    result = result.replace('|', " | ");
    result = result.split_whitespace().collect::<Vec<_>>().join(" ");

    // Restore quoted segments
    for (idx, segment) in quoted_segments.iter().enumerate() {
        let placeholder = format!("\x00\x01{}\x00", idx);
        result = result.replace(&placeholder, segment);
    }
    result
}

/// Strip quotes and lowercase
pub(crate) fn dequote_and_lowercase(cmd: &str) -> String {
    let mut out = String::with_capacity(cmd.len());
    let bytes = cmd.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        let c = bytes[i];
        if (c == b'\'' || c == b'"') && (i == 0 || bytes[i - 1] != b'\\') {
            let quote = c;
            i += 1;
            while i < bytes.len() && !(bytes[i] == quote && (i == 0 || bytes[i - 1] != b'\\')) {
                out.push(bytes[i] as char);
                i += 1;
            }
            if i < bytes.len() {
                i += 1;
            }
        } else {
            out.push(c as char);
            i += 1;
        }
    }
    out.to_lowercase()
}

/// Split shell commands on separators
pub fn split_shell_commands(cmd: &str) -> Vec<&str> {
    let mut parts = Vec::new();
    let mut start = 0;
    let mut in_quotes = false;
    let mut quote_char = b' ';
    let bytes = cmd.as_bytes();

    let mut i = 0;
    while i < bytes.len() {
        let c = bytes[i];

        if (c == b'"' || c == b'\'') && (i == 0 || bytes[i - 1] != b'\\') {
            if !in_quotes {
                in_quotes = true;
                quote_char = c;
            } else if c == quote_char {
                in_quotes = false;
            }
        }

        if !in_quotes {
            if c == b';' {
                if start < i {
                    parts.push(&cmd[start..i]);
                }
                start = i + 1;
            } else if (c == b'&' || c == b'|') && i + 1 < bytes.len() && bytes[i + 1] == c {
                if start < i {
                    parts.push(&cmd[start..i]);
                }
                start = i + 2;
                i += 1;
            }
        }
        i += 1;
    }

    if start < cmd.len() {
        parts.push(&cmd[start..]);
    }

    parts
}

/// Split a shell command into pipeline segments: splits on `|`, `||`,
/// `&&`, `;` and a backgrounding `&` appearing outside single/double
/// quotes. Unlike [`split_shell_commands`] this also splits on a bare `|`
/// so each stage of a pipeline can be inspected on its own (e.g. the `tee`
/// in `echo x | tee file`).
fn split_shell_pipeline(cmd: &str) -> Vec<&str> {
    let mut parts = Vec::new();
    let mut start = 0;
    let mut in_quotes = false;
    let mut quote_char = b' ';
    let bytes = cmd.as_bytes();

    let mut i = 0;
    while i < bytes.len() {
        let c = bytes[i];

        if (c == b'"' || c == b'\'') && (i == 0 || bytes[i - 1] != b'\\') {
            if !in_quotes {
                in_quotes = true;
                quote_char = c;
            } else if c == quote_char {
                in_quotes = false;
            }
        }

        if !in_quotes && matches!(c, b';' | b'|' | b'&') {
            // `||` and `&&` are two-byte operators (`;;` is not a thing).
            let is_double = c != b';' && i + 1 < bytes.len() && bytes[i + 1] == c;
            if start < i {
                parts.push(&cmd[start..i]);
            }
            start = i + if is_double { 2 } else { 1 };
            if is_double {
                i += 1;
            }
        }
        i += 1;
    }

    if start < cmd.len() {
        parts.push(&cmd[start..]);
    }

    parts
}

/// Whether a token is a leading `VAR=value` environment assignment prefix
/// (`FOO=bar cmd …`), which is not the command word.
fn is_env_assignment(tok: &str) -> bool {
    let Some(eq) = tok.find('=') else {
        return false;
    };
    let name = &tok[..eq];
    !name.is_empty()
        && name
            .chars()
            .next()
            .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
        && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
}

/// The basename of a command word (`/usr/bin/tee` → `tee`).
fn command_basename(word: &str) -> &str {
    word.rsplit(['/', '\\']).next().unwrap_or(word)
}

/// Locate the command word of one pipeline segment: the first token after
/// any `VAR=value` prefixes, looking through ONE leading `sudo`/`doas`
/// wrapper (the canonical `… | sudo tee /root/file` form). Flags known to
/// take a separate value (`sudo -u root …`) consume one extra token.
fn command_word_index(tokens: &[String]) -> Option<usize> {
    let mut idx = 0;
    while tokens.get(idx).is_some_and(|t| is_env_assignment(t)) {
        idx += 1;
    }
    if tokens
        .get(idx)
        .is_some_and(|t| matches!(command_basename(t), "sudo" | "doas"))
    {
        idx += 1;
        while let Some(t) = tokens.get(idx) {
            if !t.starts_with('-') || t.as_str() == "-" {
                break;
            }
            idx += 1;
            if matches!(
                t.as_str(),
                "-u" | "--user"
                    | "-g"
                    | "--group"
                    | "-h"
                    | "--host"
                    | "-p"
                    | "--prompt"
                    | "-C"
                    | "-D"
                    | "--chdir"
                    | "-R"
                    | "-U"
            ) {
                idx += 1;
            }
        }
    }
    (idx < tokens.len()).then_some(idx)
}

/// Whether a token is shell plumbing rather than an operand: redirections
/// (`>`, `2>`, `>>`, `<`, `<<`) or command separators that survived
/// quoting.
fn is_shell_metachar_token(tok: &str) -> bool {
    let stripped = tok.trim_start_matches(|c: char| c.is_ascii_digit());
    stripped.starts_with('>')
        || stripped.starts_with('<')
        || stripped.starts_with('|')
        || stripped.starts_with('&')
        || stripped.starts_with(';')
}

/// Extract the file targets of `tee` and `sponge` invocations anywhere in a
/// shell command's pipeline. Both write (or append, `-a`) their stdin to
/// the named files, so they are write primitives exactly like `>`/`>>` —
/// but the redirect guard cannot see them because no `>` appears in the
/// command. Quoting is handled via `shlex`; the command word is found per
/// pipeline segment after `VAR=value` prefixes and one `sudo`/`doas`
/// wrapper; flags (`-a`, `--append`) are skipped and collection stops at
/// shell plumbing tokens. Everything else after the command word is a file
/// by the tools' own syntax.
pub fn shell_tee_write_targets(cmd: &str) -> Vec<String> {
    let mut targets = Vec::new();
    for segment in split_shell_pipeline(cmd) {
        let Some(tokens) = shlex::split(segment) else {
            continue;
        };
        let Some(cmd_idx) = command_word_index(&tokens) else {
            continue;
        };
        if !matches!(command_basename(&tokens[cmd_idx]), "tee" | "sponge") {
            continue;
        }
        let mut flags_done = false;
        for tok in &tokens[cmd_idx + 1..] {
            if is_shell_metachar_token(tok) {
                break;
            }
            if tok == "--" {
                flags_done = true;
                continue;
            }
            if !flags_done && tok.starts_with('-') && tok.len() > 1 {
                continue; // -a, --append, …
            }
            targets.push(tok.clone());
        }
    }
    targets
}

/// File verbs whose non-flag operands are file targets by their own
/// syntax. `dd` is special-cased (`if=`/`of=` operands) and `chmod` skips
/// its mode operand; see [`SafetyChecker::check_shell_command_paths`].
const FILE_TARGET_VERBS: &[&str] = &[
    "cat", "cp", "mv", "rm", "chmod", "ln", "mkdir", "touch", "head", "tail", "less", "more", "dd",
    "install", "rsync", "scp",
];

/// Whether a shell token has the shape of an explicit filesystem path:
/// absolute (`/x`, `C:/x`, `C:\x`), home-relative (`~/x`), or dot-relative
/// (`./x`, `../x`). Tokens containing substitution characters (`$`,
/// backtick, parentheses) are excluded — they are shell-expansion
/// artifacts, not literal paths. Bare words (`README.md`) deliberately do
/// not qualify: outside file-verb operands they are far more often strings
/// than paths.
fn looks_like_explicit_path(tok: &str) -> bool {
    if tok.contains(['$', '`', '(', ')']) {
        return false;
    }
    if tok.starts_with('/')
        || tok.starts_with("~/")
        || tok.starts_with("./")
        || tok.starts_with("../")
        || tok.starts_with(".\\")
        || tok.starts_with("..\\")
    {
        return true;
    }
    // Windows drive-letter absolute path (both separator flavors).
    let b = tok.as_bytes();
    b.len() >= 3 && b[0].is_ascii_alphabetic() && b[1] == b':' && (b[2] == b'/' || b[2] == b'\\')
}

/// Expand a leading `~`/`~/` against the user's home directory so a
/// home-relative shell token is validated against the same absolute path
/// the shell would resolve it to. `~user/...` forms are left untouched.
fn expand_home_token(tok: &str) -> String {
    if tok == "~" || tok.starts_with("~/") {
        let home =
            std::env::var_os("HOME").or_else(|| dirs::home_dir().map(|p| p.into_os_string()));
        if let Some(home) = home {
            return format!("{}{}", home.to_string_lossy(), &tok[1..]);
        }
    }
    tok.to_string()
}

/// Whether the platform's default shell treats `\` as an escape character
/// outside quotes. Unix `sh` does; Windows `cmd`/`powershell` do not — there
/// `\` is a literal path separator, so `C:\work\.env` must keep its
/// backslashes or the redirect target gets mangled (`C:work.env`) and evades
/// the denied_paths match entirely.
fn shell_treats_backslash_as_escape() -> bool {
    !cfg!(target_os = "windows")
}

/// Extract the file targets of output redirections (`>`, `>>`) from a shell
/// command. `>` inside single/double quotes is ignored, as is descriptor
/// duplication that writes no file (`2>&1`, `>&2`) and process substitution
/// (`>(...)`). Fd-qualified redirects that DO write a file (`2> err.log`,
/// `&> all.log`, `>| clobbered`) are included, quotes around the target are
/// stripped. Input redirects (`<`) and here-docs (`<<`) are not writes and
/// are ignored.
pub fn shell_output_redirect_targets(cmd: &str) -> Vec<String> {
    let chars: Vec<char> = cmd.chars().collect();
    let mut targets = Vec::new();
    let mut in_single = false;
    let mut in_double = false;
    let mut i = 0;
    while i < chars.len() {
        let c = chars[i];
        // Backslash escapes the next character (outside single quotes) in
        // Unix shells; on Windows it is a literal path separator.
        if c == '\\' && !in_single && shell_treats_backslash_as_escape() {
            i += 2;
            continue;
        }
        if c == '\'' && !in_double {
            in_single = !in_single;
            i += 1;
            continue;
        }
        if c == '"' && !in_single {
            in_double = !in_double;
            i += 1;
            continue;
        }
        if c != '>' || in_single || in_double {
            i += 1;
            continue;
        }

        // A `>` outside quotes. Consume the operator: `>`, `>>`, then an
        // optional `|` (`>|` noclobber override still writes a file).
        let mut j = i + 1;
        if j < chars.len() && chars[j] == '>' {
            j += 1;
        }
        // Descriptor duplication (`>&1`, `>>&2`) and process substitution
        // (`>(...)`) write no file.
        if j < chars.len() && (chars[j] == '&' || chars[j] == '(') {
            i = j + 1;
            continue;
        }
        if j < chars.len() && chars[j] == '|' {
            j += 1;
        }
        while j < chars.len() && chars[j].is_whitespace() {
            j += 1;
        }

        // Read the target token, stripping quotes (quoted segments may
        // contain whitespace) and resolving backslash escapes the way the
        // platform's shell would (Unix only — Windows shells treat `\` as a
        // literal path separator).
        let mut token = String::new();
        let mut token_quote: Option<char> = None;
        while j < chars.len() {
            let t = chars[j];
            if let Some(q) = token_quote {
                if t == q {
                    token_quote = None;
                } else {
                    token.push(t);
                }
                j += 1;
                continue;
            }
            if t.is_whitespace() || matches!(t, ';' | '|' | '&' | '<' | '>' | '(' | ')') {
                break;
            }
            if t == '\'' || t == '"' {
                token_quote = Some(t);
                j += 1;
                continue;
            }
            if t == '\\' && j + 1 < chars.len() && shell_treats_backslash_as_escape() {
                token.push(chars[j + 1]);
                j += 2;
                continue;
            }
            token.push(t);
            j += 1;
        }
        // A token still starting with `&` (`foo>&2` without whitespace) is
        // descriptor duplication, not a file.
        if !token.is_empty() && !token.starts_with('&') {
            targets.push(token);
        }
        i = j.max(i + 1);
    }
    targets
}

/// Match a shell output-redirect target against the configured `denied_paths`
/// globs, mirroring `PathValidator`'s matching: full-path glob match on both
/// the raw target and the working-dir-resolved form, plus basename matching
/// for filename-only patterns (e.g. `.env`). Resolution is lexical only (no
/// filesystem access), so prospective output paths work. Returns the matched
/// pattern, or `None` when the target is not denied.
///
/// Matching is separator-agnostic: both `/` and `\` are treated as path
/// separators and drive-letter prefixes (`C:\...`, `C:/...`) count as
/// absolute, so Windows-shaped targets resolve and match identically on every
/// host OS. Relying on `std::path::Path` alone would only recognize the HOST
/// separator and let `echo x > C:\work\.env` slip past a `.env` deny glob.
pub(super) fn redirect_target_matches_denied(
    target: &str,
    working_dir: &std::path::Path,
    denied_paths: &[String],
) -> Option<String> {
    if denied_paths.is_empty() {
        return None;
    }
    let resolved = resolve_redirect_target_lexical(target, working_dir);
    let raw_glob = target.trim_start_matches("./").replace('\\', "/");

    for pattern in denied_paths {
        let compiled = match glob::Pattern::new(&super::to_glob_form(pattern)) {
            Ok(p) => p,
            Err(_) => continue,
        };
        if compiled.matches(&resolved) || compiled.matches(&raw_glob) {
            return Some(pattern.clone());
        }
        // Filename-only patterns (no separator, e.g. ".env") also match by
        // basename; the basename is taken across both separator kinds.
        if !pattern.contains('/') && !pattern.contains('\\') {
            let base = resolved.rsplit('/').next().unwrap_or(resolved.as_str());
            if !base.is_empty() && compiled.matches(base) {
                return Some(pattern.clone());
            }
        }
    }
    None
}

/// Lexically resolve a shell redirect target against `working_dir`, treating
/// both `/` and `\` as path separators, and return the result in
/// forward-slash (glob) form with `.`/`..` segments resolved. Purely lexical
/// — no filesystem access — so prospective output paths and foreign-OS path
/// shapes resolve identically on any host.
fn resolve_redirect_target_lexical(target: &str, working_dir: &std::path::Path) -> String {
    let target_fwd = target.replace('\\', "/");
    let joined = if redirect_target_is_absolute(&target_fwd) {
        target_fwd
    } else {
        let wd = working_dir.to_string_lossy().replace('\\', "/");
        format!("{}/{}", wd.trim_end_matches('/'), target_fwd)
    };

    // Resolve `.` and `..` segments lexically. `..` never pops past the
    // root, a drive letter (`C:`), or a leading `..` of a relative path.
    let mut segments: Vec<&str> = Vec::new();
    for seg in joined.split('/') {
        match seg {
            "" | "." => {}
            ".." => {
                if matches!(segments.last(), Some(&last) if last != ".." && !is_drive_letter_segment(last))
                {
                    segments.pop();
                }
            }
            s => segments.push(s),
        }
    }
    let prefix = if joined.starts_with('/') { "/" } else { "" };
    format!("{}{}", prefix, segments.join("/"))
}

/// A redirect target is absolute when rooted (`/x`, or `\x` after separator
/// normalization) or drive-qualified (`C:/x`).
fn redirect_target_is_absolute(target_fwd: &str) -> bool {
    if target_fwd.starts_with('/') {
        return true;
    }
    let bytes = target_fwd.as_bytes();
    bytes.len() >= 3 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':' && bytes[2] == b'/'
}

/// Whether a normalized path segment is a Windows drive letter (`C:`).
fn is_drive_letter_segment(seg: &str) -> bool {
    let bytes = seg.as_bytes();
    bytes.len() == 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':'
}

/// Detect `git push` invocations (via shell_exec/container_exec, not the
/// dedicated git_push tool) that explicitly target a protected branch, and
/// return the offending branch name if found.
///
/// Only catches an *explicit* branch argument (`git push origin main`,
/// `git push origin --delete main`, `git push origin :main`,
/// `git push --force-with-lease origin main`, etc.). A bare `git push` with
/// no branch argument pushes whatever the current branch's configured
/// upstream is, which can't be determined from the command string alone --
/// that case isn't caught here.
fn git_push_protected_branch_target(cmd: &str, protected_branches: &[String]) -> Option<String> {
    if protected_branches.is_empty() {
        return None;
    }
    let tokens = shlex::split(cmd)?;
    let git_pos = tokens.iter().position(|t| t == "git")?;
    let rest = &tokens[git_pos + 1..];
    let push_pos = rest.iter().position(|t| t == "push")?;
    let args = &rest[push_pos + 1..];

    let mut delete_next = false;
    let mut candidates: Vec<&str> = Vec::new();
    for arg in args {
        if delete_next {
            candidates.push(arg.as_str());
            delete_next = false;
            continue;
        }
        if arg == "--delete" || arg == "-d" {
            delete_next = true;
            continue;
        }
        if let Some(stripped) = arg.strip_prefix(':') {
            // `git push origin :branch` (delete-by-refspec syntax)
            candidates.push(stripped);
            continue;
        }
        if arg.starts_with('-') {
            continue; // other flags: --force, --force-with-lease, -u, etc.
        }
        candidates.push(arg.as_str());
    }

    // The remaining non-flag tokens are typically [remote] [branch[:refspec]].
    // Check both sides of a local:remote refspec against protected_branches.
    for candidate in candidates {
        let (local, remote) = match candidate.split_once(':') {
            Some((l, r)) => (l, Some(r)),
            None => (candidate, None),
        };
        for name in [Some(local), remote].into_iter().flatten() {
            if protected_branches.iter().any(|b| b == name) {
                return Some(name.to_string());
            }
        }
    }
    None
}

/// Check if an IP is private or internal
pub fn is_private_or_internal(ip: std::net::IpAddr) -> bool {
    match ip {
        std::net::IpAddr::V4(v4) => {
            v4.is_private()
                || v4.is_loopback()
                || v4.is_link_local()
                || v4.is_broadcast()
                || v4.is_unspecified()
                || (v4.octets()[0] == 169 && v4.octets()[1] == 254)
                || (v4.octets()[0] == 192 && v4.octets()[1] == 0 && v4.octets()[2] == 2)
                || (v4.octets()[0] == 198 && v4.octets()[1] == 51 && v4.octets()[2] == 100)
                || (v4.octets()[0] == 203 && v4.octets()[1] == 0 && v4.octets()[2] == 113)
                || (v4.octets()[0] == 100 && (v4.octets()[1] & 0xc0) == 64)
        }
        std::net::IpAddr::V6(v6) => {
            v6.is_loopback()
                || v6.is_unspecified()
                || (v6.segments()[0] & 0xffc0) == 0xfe80
                || (v6.segments()[0] & 0xfe00) == 0xfc00
                || v6.to_ipv4_mapped().is_some_and(|v4| {
                    v4.is_private()
                        || v4.is_loopback()
                        || v4.is_link_local()
                        || v4.is_broadcast()
                        || v4.is_unspecified()
                        || (v4.octets()[0] == 169 && v4.octets()[1] == 254)
                        || (v4.octets()[0] == 100 && (v4.octets()[1] & 0xc0) == 64)
                })
        }
    }
}

/// DNS resolver that pins resolved IPs
#[derive(Clone)]
pub struct PinnedDnsResolver {
    allow_private: bool,
}

impl PinnedDnsResolver {
    pub fn new(allow_private: bool) -> Self {
        Self { allow_private }
    }
}

impl reqwest::dns::Resolve for PinnedDnsResolver {
    fn resolve(&self, name: reqwest::dns::Name) -> reqwest::dns::Resolving {
        let allow_private = self.allow_private;
        Box::pin(async move {
            let addrs: Vec<std::net::SocketAddr> =
                tokio::net::lookup_host(format!("{}:0", name.as_str()))
                    .await
                    .map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)?
                    .collect();

            if allow_private {
                let iter: reqwest::dns::Addrs = Box::new(addrs.into_iter());
                return Ok(iter);
            }

            let safe_addrs: Vec<std::net::SocketAddr> = addrs
                .into_iter()
                .filter(|addr| !is_private_or_internal(addr.ip()))
                .collect();

            if safe_addrs.is_empty() {
                return Err(Box::new(std::io::Error::new(
                    std::io::ErrorKind::PermissionDenied,
                    "DNS resolved to private/internal IP address",
                ))
                    as Box<dyn std::error::Error + Send + Sync>);
            }

            let iter: reqwest::dns::Addrs = Box::new(safe_addrs.into_iter());
            Ok(iter)
        })
    }
}