car-server-core 0.52.0

Transport-neutral library for the CAR daemon JSON-RPC dispatcher (used by car-server and tokhn-daemon)
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
//! The coder's inspector chain — policy hardening for host tool execution.
//!
//! Every tool call the coder makes (model-proposed AND contract checks) passes
//! through this chain before dispatch; first Deny wins. CAR's built-ins run
//! first, followed by the operator's additive rules from `<CAR_HOME>/policies/`
//! and `<worktree>/.car/policies/`. The checks are deliberately conservative
//! token/substring matchers, not a shell parser — they block the unambiguous
//! footguns. The one exception in shape is
//! [`DenyForgePublication`], which pairs a read-only *allowlist* for the forge
//! CLIs (`gh`, `glab`, `hub`) with a small publication blacklist, because the
//! set of read-only `gh` subcommands is finite and the set of mutating ones is
//! not. This is hardening, not a sandbox — `command gh …`, a shell alias, and a
//! script wrapping the binary all still get through; the real gates are
//! contract confirmation and merge approval (see `coder::` module docs).

use std::collections::HashMap;
use std::path::{Component, Path, PathBuf};

use car_ir::Action;
use car_policy::{InspectionResult, Inspector, InspectorChain, PolicyEngine, PolicyRules};
use car_state::StateStore;
use serde_json::Value;

/// Build the standard coder chain for a worktree.
pub fn coder_inspector_chain(worktree: &Path) -> InspectorChain {
    InspectorChain::new()
        .with(Box::new(DenyGitRemoteMutation))
        .with(Box::new(DenyForgePublication))
        .with(Box::new(DenyHistoryRewrite))
        .with(Box::new(DenyPrivilegeEscalation))
        .with(Box::new(DenyCredentialAccess))
        .with(Box::new(DenyEnvironmentRepair))
        .with(Box::new(DenyDestructiveOutsideWorktree {
            worktree: worktree.to_path_buf(),
        }))
        .with(Box::new(DenyPathEscape {
            worktree: worktree.to_path_buf(),
        }))
}

/// Build the standard coder chain plus every operator-authored policy that
/// governs this session.
///
/// The source order deliberately matches `car_policy::tool_gate`: machine-wide
/// rules first, then rules committed with the project. All current rule kinds
/// are prohibitions, so merging cannot relax a built-in or an earlier rule.
/// Built-ins remain ahead of the declarative inspector because first-Deny-wins
/// decides which actionable reason the model sees.
///
/// Tool names stay exact. A policy for a surface-specific tool the coder does
/// not expose (for example Claude Code's `WebFetch`) is loaded but has nothing
/// to match; CAR does not guess aliases between tools with different schemas.
/// Stateful `trace_rule` is also deliberately excluded: the shared loader
/// rejects it as unenforced instead of silently claiming it took effect.
pub fn coder_inspector_chain_with_project_policies(
    worktree: &Path,
) -> Result<InspectorChain, car_policy::PolicyLoadError> {
    let dirs = [
        car_home::root_or_relative().join("policies"),
        worktree.join(".car").join("policies"),
    ];
    coder_inspector_chain_from_policy_dirs(worktree, &dirs)
}

fn coder_inspector_chain_from_policy_dirs(
    worktree: &Path,
    dirs: &[PathBuf],
) -> Result<InspectorChain, car_policy::PolicyLoadError> {
    let mut rules = PolicyRules::default();
    for dir in dirs {
        rules.merge(car_policy::load_policy_dir(dir)?);
    }

    let mut engine = PolicyEngine::new();
    rules.apply(&mut engine);
    Ok(
        coder_inspector_chain(worktree).with(Box::new(ProjectPolicyInspector {
            engine,
            state: StateStore::new(),
        })),
    )
}

/// Adapter from the declarative `PolicyEngine` to the coder's dispatch-time
/// inspector seam. One instance lives for the session, so rate-limit windows
/// cover the whole run rather than resetting for every tool call.
struct ProjectPolicyInspector {
    engine: PolicyEngine,
    state: StateStore,
}

impl Inspector for ProjectPolicyInspector {
    fn name(&self) -> &'static str {
        "project_policy"
    }

    fn inspect(&self, tool: &str, params: &Value) -> InspectionResult {
        // Action is non-exhaustive outside car-ir; use its constructor so a new
        // field cannot make this adapter silently construct a stale shape.
        let mut action = Action::tool_call(tool);
        action.id = "coder-policy-check".to_string();
        action.parameters = params
            .as_object()
            .map(|m| {
                m.iter()
                    .map(|(key, value)| (key.clone(), value.clone()))
                    .collect::<HashMap<_, _>>()
            })
            .unwrap_or_default();

        match self.engine.check(&action, &self.state).into_iter().next() {
            Some(violation) => InspectionResult::Deny(format!(
                "operator policy '{}': {}",
                violation.policy_name, violation.reason
            )),
            None => InspectionResult::Allow,
        }
    }
}

/// Governed host execution is deliberately narrower than the legacy coder:
/// direct shell reads and directory changes must remain under the selected
/// repository. Toolchains may still load their own executables and libraries;
/// this gate prevents the model from naming host files as command operands.
struct DenyGovernedShellPathEscape {
    worktree: PathBuf,
}

const READ_OR_CHDIR_VERBS: &[&str] = &[
    "cat", "head", "tail", "less", "more", "grep", "egrep", "fgrep", "rg", "sed", "awk", "find",
    "ls", "stat", "wc", "strings", "readlink", "realpath", "cd", "type",
];

impl Inspector for DenyGovernedShellPathEscape {
    fn name(&self) -> &'static str {
        "governed_host.deny_shell_path_escape"
    }

    fn inspect(&self, tool: &str, params: &Value) -> InspectionResult {
        let Some(cmd) = shell_command(tool, params) else {
            return InspectionResult::Allow;
        };
        for seg in segments(&cmd) {
            let Some(v) = verb(&seg) else { continue };
            let v = Path::new(v)
                .file_name()
                .and_then(|name| name.to_str())
                .unwrap_or(v)
                .to_ascii_lowercase();
            if !READ_OR_CHDIR_VERBS.contains(&v.as_str()) {
                continue;
            }
            for arg in seg.iter().skip(1).filter(|arg| !arg.starts_with('-')) {
                let candidate =
                    arg.trim_matches(|c: char| matches!(c, '"' | '\'' | '(' | ')' | ',' | ';'));
                let names_path = candidate.starts_with('~')
                    || is_abs_or_traversal(candidate)
                    || self.worktree.join(candidate).exists();
                if names_path && !stays_under(&self.worktree, candidate) {
                    return InspectionResult::Deny(format!(
                        "'{v}' path '{candidate}' resolves outside the governed repository"
                    ));
                }
            }
        }
        InspectionResult::Allow
    }
}

/// Unlike the general coder, governed host mode does not permit file-tool
/// reads outside the selected repository either.
struct DenyGovernedFilePathEscape {
    worktree: PathBuf,
}

impl Inspector for DenyGovernedFilePathEscape {
    fn name(&self) -> &'static str {
        "governed_host.deny_file_path_escape"
    }

    fn inspect(&self, tool: &str, params: &Value) -> InspectionResult {
        if !matches!(
            tool,
            "read_file" | "write_file" | "edit_file" | "grep_files"
        ) {
            return InspectionResult::Allow;
        }
        let Some(path) = params.get("path").and_then(Value::as_str) else {
            return InspectionResult::Allow;
        };
        if stays_under(&self.worktree, path) {
            InspectionResult::Allow
        } else {
            InspectionResult::Deny(format!(
                "file access to '{path}' resolves outside the governed repository"
            ))
        }
    }
}

/// Host hardening for the governed supervised assistant. Unlike a coder
/// worktree, this workflow may perform one explicitly approved normal push;
/// remote reconfiguration, force pushes, history rewrite, credential access,
/// and path escape remain unconditional denials.
pub fn governed_host_inspector_chain(worktree: &Path) -> InspectorChain {
    InspectorChain::new()
        .with(Box::new(DenyGuiShellAutomation))
        .with(Box::new(DenyForcePushAndRemoteReconfiguration))
        .with(Box::new(DenyBroadGitStage))
        .with(Box::new(DenyHistoryRewrite))
        .with(Box::new(DenyPrivilegeEscalation))
        .with(Box::new(DenyCredentialAccess))
        .with(Box::new(DenyEnvironmentRepair))
        .with(Box::new(DenyDestructiveOutsideWorktree {
            worktree: worktree.to_path_buf(),
        }))
        .with(Box::new(DenyGovernedShellPathEscape {
            worktree: worktree.to_path_buf(),
        }))
        .with(Box::new(DenyGovernedFilePathEscape {
            worktree: worktree.to_path_buf(),
        }))
}

/// A governed engineering session has a first-class host shell. Driving a
/// terminal (or a PowerShell window) through desktop automation would bypass
/// repository scoping, action classification, gate checks, and receipts.
struct DenyGuiShellAutomation;

impl Inspector for DenyGuiShellAutomation {
    fn name(&self) -> &'static str {
        "governed_host.deny_gui_shell_automation"
    }

    fn inspect(&self, tool: &str, _params: &Value) -> InspectionResult {
        if matches!(tool, "run_applescript" | "run_powershell") {
            InspectionResult::Deny(
                "desktop-driven shell execution is not allowed; use the governed shell tool".into(),
            )
        } else {
            InspectionResult::Allow
        }
    }
}

/// Preserve unrelated dirty-checkout changes by requiring explicit paths at
/// the staging boundary. Targeted `git add path` remains available.
struct DenyBroadGitStage;

impl Inspector for DenyBroadGitStage {
    fn name(&self) -> &'static str {
        "governed_host.deny_broad_git_stage"
    }

    fn inspect(&self, tool: &str, params: &Value) -> InspectionResult {
        let Some(cmd) = shell_command(tool, params) else {
            return InspectionResult::Allow;
        };
        for seg in segments(&cmd) {
            if verb(&seg) != Some("git") {
                continue;
            }
            let add = seg.iter().position(|token| token == "add");
            if let Some(index) = add {
                if seg
                    .iter()
                    .skip(index + 1)
                    .any(|token| matches!(token.as_str(), "." | "-A" | "--all" | "-u" | "--update"))
                {
                    return InspectionResult::Deny(
                        "broad git staging is not allowed; name only the files changed for this task"
                            .into(),
                    );
                }
            }
            if seg.iter().any(|token| token == "commit")
                && seg.iter().any(|token| {
                    token == "--all"
                        || token
                            .strip_prefix('-')
                            .filter(|short| !short.starts_with('-'))
                            .is_some_and(|short| short.contains('a'))
                })
            {
                return InspectionResult::Deny(
                    "git commit -a is not allowed; stage only explicit task files".into(),
                );
            }
        }
        InspectionResult::Allow
    }
}

/// Lexically resolve `candidate` against `root` and decide whether it stays
/// under `root`. Purely lexical (`..` popping) — symlinks inside the worktree
/// are out of scope here, consistent with the hardening-not-sandbox stance.
pub(crate) fn stays_under(root: &Path, candidate: &str) -> bool {
    let p = Path::new(candidate);
    let joined = if p.is_absolute() {
        p.to_path_buf()
    } else {
        root.join(p)
    };
    // Existing paths get a filesystem-authoritative check first. This closes
    // the symlink escape (`repo/link -> /outside`, then `read_file link/x`)
    // that a purely lexical `..` clamp cannot see. Prospective writes fall
    // through to the lexical check; their nearest existing ancestor is also
    // checked by the governed RepositoryScope before host binding.
    if joined.exists() {
        if let (Ok(real_root), Ok(real_candidate)) = (root.canonicalize(), joined.canonicalize()) {
            return path_starts_with(&real_candidate, &real_root);
        }
        return false;
    }
    if let Ok(real_root) = root.canonicalize() {
        let mut ancestor = joined.as_path();
        while !ancestor.exists() {
            let Some(parent) = ancestor.parent() else {
                return false;
            };
            ancestor = parent;
        }
        match ancestor.canonicalize() {
            Ok(real_ancestor) if path_starts_with(&real_ancestor, &real_root) => {}
            _ => return false,
        }
    }
    let mut stack: Vec<Component> = Vec::new();
    for c in joined.components() {
        match c {
            Component::CurDir => {}
            Component::ParentDir => {
                if stack.pop().is_none() {
                    return false;
                }
            }
            other => stack.push(other),
        }
    }
    let normalized: PathBuf = stack.iter().collect();
    path_starts_with(&normalized, root)
}

/// Component-boundary prefix test. On Unix this is `Path::starts_with`. On
/// Windows it additionally strips the `\\?\` verbatim prefix (which
/// `Path::canonicalize` adds to the worktree root but a model-supplied absolute
/// path lacks) and folds case (NTFS is case-insensitive), so a legitimate
/// absolute write inside the worktree isn't spuriously denied.
#[cfg(not(windows))]
fn path_starts_with(path: &Path, base: &Path) -> bool {
    path.starts_with(base)
}

#[cfg(windows)]
fn path_starts_with(path: &Path, base: &Path) -> bool {
    fn key(p: &Path) -> String {
        let s = p.to_string_lossy().into_owned();
        let s = if let Some(r) = s.strip_prefix(r"\\?\UNC\") {
            format!(r"\\{r}")
        } else if let Some(r) = s.strip_prefix(r"\\?\") {
            r.to_string()
        } else {
            s
        };
        s.replace('/', "\\").to_ascii_lowercase()
    }
    let base_key = key(base);
    let base_trim = base_key.trim_end_matches('\\');
    let path_key = key(path);
    path_key == base_trim || path_key.starts_with(&format!("{base_trim}\\"))
}

/// True when a shell argument names an absolute path (POSIX `/…`, Windows
/// `C:\…` / `\\server\…`) or contains a `..` traversal — i.e. the argument may
/// point outside the worktree and must be checked against [`stays_under`].
/// The old code tested only `starts_with('/')`, which never matches a Windows
/// absolute path, so `del C:\…` slipped past the destructive-op guard.
fn is_abs_or_traversal(arg: &str) -> bool {
    arg.starts_with('/')
        || arg.starts_with('\\')
        || arg.contains("..")
        || Path::new(arg).is_absolute()
}

/// True for a Windows `cmd` switch like `/q`, `/s`, `/f` — a leading `/`
/// followed by one or two alphanumerics and nothing else. Distinguished from a
/// POSIX absolute path (`/etc`, `/wt/...`), which is longer or contains another
/// separator. Only ever true on Windows, so Unix argument handling (where a
/// leading `/` is always a path) is unchanged.
fn is_windows_switch(arg: &str) -> bool {
    #[cfg(not(windows))]
    {
        let _ = arg;
        false
    }
    #[cfg(windows)]
    {
        arg.strip_prefix('/')
            .map(|rest| {
                (1..=2).contains(&rest.len()) && rest.chars().all(|c| c.is_ascii_alphanumeric())
            })
            .unwrap_or(false)
    }
}

/// Split a shell command into segments at unquoted-ish separators and each
/// segment into whitespace tokens. Naive on purpose (no quote handling): a
/// quoted `";"` may split a segment too eagerly, which only ever makes the
/// chain MORE likely to deny — never less.
fn segments(command: &str) -> Vec<Vec<String>> {
    command
        .replace("&&", "\n")
        .replace("||", "\n")
        .replace(['ï¼›', ';', '|'], "\n")
        .lines()
        .map(|seg| {
            seg.split_whitespace()
                .map(|t| t.trim_matches(|c| c == '"' || c == '\'').to_string())
                .filter(|t| !t.is_empty())
                .collect::<Vec<_>>()
        })
        .filter(|toks: &Vec<String>| !toks.is_empty())
        .collect()
}

/// First non-env-assignment token of a segment (`FOO=bar cmd …` → `cmd`).
fn verb(tokens: &[String]) -> Option<&str> {
    tokens.iter().map(String::as_str).find(|t| !t.contains('='))
}

fn shell_command(tool: &str, params: &Value) -> Option<String> {
    if tool != "shell" {
        return None;
    }
    params
        .get("command")
        .and_then(Value::as_str)
        .map(str::to_string)
}

/// `git push`, `git remote add/set-url`, `git fetch --force` — the coder's
/// output leaves the machine only via the approved merge branch.
struct DenyGitRemoteMutation;

impl Inspector for DenyGitRemoteMutation {
    fn name(&self) -> &'static str {
        "coder.deny_git_remote_mutation"
    }

    fn inspect(&self, tool: &str, params: &Value) -> InspectionResult {
        let Some(cmd) = shell_command(tool, params) else {
            return InspectionResult::Allow;
        };
        for seg in segments(&cmd) {
            let is_git = verb(&seg) == Some("git");
            if !is_git {
                continue;
            }
            if seg.iter().any(|t| t == "push") {
                return InspectionResult::Deny(
                    "git push is not allowed from a coder session — results are delivered \
                     via the approved local branch"
                        .into(),
                );
            }
            if seg.iter().any(|t| t == "remote")
                && seg
                    .iter()
                    .any(|t| t == "add" || t == "set-url" || t == "remove")
            {
                return InspectionResult::Deny("mutating git remotes is not allowed".into());
            }
        }
        InspectionResult::Allow
    }
}

/// Publication by any route other than the approved merge branch. `git push`
/// is denied above, but a forge CLI reaches the world without touching git:
/// `gh pr create` opens a pull request, `gh release create` ships a release,
/// `gh api --method DELETE` edits branch protection, and `gh auth token`
/// prints the credential that does all three. The property the coder's gates
/// claim is "work leaves the worktree only through `coder.approve_merge`", and
/// one extra binary was enough to break it (car#1074).
///
/// Shape, deliberately mixed. For the forge CLIs (`gh`, `glab`, `hub`) this is
/// an **allowlist**: the read-only subcommands are a small finite set while the
/// mutating ones are not, so a `gh` verb nobody has vetted arrives denied. For
/// package registries it is a short **blacklist** of publish subcommands,
/// because the surrounding verbs (`npm`, `cargo`, `docker`) are ordinary build
/// tools a task legitimately runs. An unparseable forge invocation falls to
/// Deny, which is the safe side — the model gets a reason, not a silent push.
///
/// Out of scope on purpose: `aws`, `kubectl`, `terraform`, `gcloud`. Those are
/// cloud/infra mutation rather than publishing *this repo's work*, the blast
/// radius of a false denial is larger, and the honest fix for them is an
/// allowlist over network-reaching verbs (car#1074 option 2) rather than one
/// more name on a blacklist. Unchanged too: `command gh …`, a shell alias, and
/// a script that wraps `gh` all still reach the binary — hardening, not a
/// sandbox.
struct DenyForgePublication;

/// Forge CLIs: anything not on [`FORGE_READS`] is denied.
const FORGE_VERBS: &[&str] = &["gh", "glab", "hub"];

/// (group, allowed subcommands) for a forge CLI. An empty subcommand list
/// allows the whole group.
const FORGE_READS: &[(&str, &[&str])] = &[
    ("pr", &["view", "list", "diff", "checks", "status"]),
    ("mr", &["view", "list", "diff", "checks", "status"]),
    ("issue", &["view", "list"]),
    ("repo", &["view"]),
    ("run", &["view", "list", "watch"]),
    ("release", &["view", "list"]),
    ("workflow", &["view", "list"]),
    ("label", &["list"]),
    ("cache", &["list"]),
    ("gist", &["view", "list"]),
    ("auth", &["status"]),
    ("search", &[]),
    ("status", &[]),
    ("version", &[]),
];

/// Global flags that take a separate value, so the value isn't mistaken for
/// the subcommand group (`gh --repo o/r pr view` → group `pr`, not `o/r`).
const FORGE_VALUE_FLAGS: &[&str] = &["-r", "--repo", "--hostname"];

/// Registry/artifact publication, matched as (verb, first operand).
const PUBLICATION_COMMANDS: &[(&str, &[&str])] = &[
    ("npm", &["publish"]),
    ("pnpm", &["publish"]),
    ("yarn", &["publish"]),
    ("cargo", &["publish"]),
    ("gem", &["push"]),
    ("twine", &["upload"]),
    ("docker", &["push", "login"]),
];

impl Inspector for DenyForgePublication {
    fn name(&self) -> &'static str {
        "coder.deny_forge_publication"
    }

    fn inspect(&self, tool: &str, params: &Value) -> InspectionResult {
        let Some(cmd) = shell_command(tool, params) else {
            return InspectionResult::Allow;
        };
        for seg in segments(&cmd) {
            let Some(v) = verb(&seg) else { continue };
            // Match on the program NAME, as `DenyEnvironmentRepair` does:
            // `/opt/homebrew/bin/gh` is the same action as the bare verb.
            let v = Path::new(&v.to_ascii_lowercase())
                .file_name()
                .map(|f| f.to_string_lossy().into_owned())
                .unwrap_or_default();
            let v = v.strip_suffix(".exe").unwrap_or(&v).to_string();
            let args: Vec<String> = seg.iter().skip(1).map(|a| a.to_ascii_lowercase()).collect();

            if FORGE_VERBS.contains(&v.as_str()) {
                if let Some(reason) = forge_denial(&v, &args) {
                    return InspectionResult::Deny(reason);
                }
                continue;
            }

            for (mgr, subs) in PUBLICATION_COMMANDS {
                if v != *mgr {
                    continue;
                }
                if leading_operands(&args).iter().any(|sub| subs.contains(sub)) {
                    return InspectionResult::Deny(format!(
                        "'{mgr}' publication is not allowed from a coder session — results \
                         leave the worktree only through the approved merge branch"
                    ));
                }
            }
        }
        InspectionResult::Allow
    }
}

/// Positional operands of a forge invocation, in order, with the values of the
/// known value-taking global flags skipped.
fn forge_operands(args: &[String]) -> Vec<&str> {
    let mut operands = Vec::new();
    let mut skip_value = false;
    for arg in args {
        if std::mem::take(&mut skip_value) {
            continue;
        }
        if FORGE_VALUE_FLAGS.contains(&arg.as_str()) {
            skip_value = true;
            continue;
        }
        if arg.starts_with('-') {
            continue;
        }
        operands.push(arg.as_str());
    }
    operands
}

/// The leading positional operands of a command, enough to find a subcommand
/// that ordinary leading tokens have pushed out of first place.
///
/// Reading only the FIRST operand missed three everyday spellings, each of
/// which reaches a registry:
///
/// - `cargo +stable publish` — the rustup toolchain selector is an operand
/// - `docker image push img` — the canonical modern form, subcommand in a group
/// - `npm --workspace x publish` — the flag's VALUE lands in first place
///
/// A `+toolchain` selector is dropped outright, and the next two operands are
/// returned so a group + subcommand pair is visible.
///
/// The trade-off is deliberate and worth stating: scanning two operands can
/// over-match a flag value (`cargo build --features publish` would be denied).
/// This half of the chain is a deny-list over registries, so it is defence in
/// depth rather than the boundary — a false positive is a red check with an
/// explicit reason, while a false negative publishes a package.
fn leading_operands(args: &[String]) -> Vec<&str> {
    args.iter()
        .map(String::as_str)
        .filter(|a| !a.starts_with('-') && !a.starts_with('+'))
        .take(2)
        .collect()
}

/// `Some(reason)` when this forge invocation is not on the read-only
/// allowlist. Everything unrecognised — a new subcommand, a group with no
/// subcommand, an argument shape this matcher cannot read — comes back denied.
fn forge_denial(verb: &str, args: &[String]) -> Option<String> {
    const BLOCKED: &str = "publishing from a coder session is not allowed — the runtime opens \
                           the pull request after `coder.approve_merge`";

    // `--version`/`--help` are flags, not operands, so read them off the raw
    // argument list before operand filtering drops them.
    //
    // `-h` is NOT in this set, and must not be. It was, and it made the whole
    // inspector an allow-all: pflag consumes the next token as a string flag's
    // value even when it starts with a dash, so `gh release create v9 --notes -h`
    // and `gh pr create --title -h --body b --head x --base main` both reached
    // this and returned None before the group was ever read. The premise was
    // wrong on its own terms too — in `gh auth status`, `-h` is `--hostname`.
    //
    // Matching only the long forms costs a coder nothing: `gh --help` still
    // works, and a denied `-h` is one retry away from the spelling that does.
    if args
        .iter()
        .any(|a| matches!(a.as_str(), "--version" | "--help"))
    {
        return None;
    }
    let operands = forge_operands(args);
    let Some(group) = operands.first().copied() else {
        return None; // bare `gh` prints usage
    };

    // `gh api` defaults to GET; an explicit non-GET method, or a field/input
    // flag (which implicitly switches it to POST), makes it a write.
    if group == "api" {
        // Every one of these must match the ATTACHED forms too. pflag accepts
        // `-XPOST` and `--field=k=v` exactly as it accepts the separated
        // spellings, so a matcher that only reads two-token pairs and exact
        // flag names lets `gh api -XPOST repos/O/R/pulls --input=-` straight
        // through — a pull request opened past the gate.
        let is_write_method = |v: &str| !v.is_empty() && v != "get";
        let explicit_method = args
            .windows(2)
            .any(|pair| matches!(pair[0].as_str(), "--method" | "-x") && is_write_method(&pair[1]))
            || args.iter().any(|a| {
                a.strip_prefix("--method=")
                    .or_else(|| a.strip_prefix("-x"))
                    .is_some_and(is_write_method)
            });
        // NB: args are lowercased, so `-f` covers `gh api -F` too.
        let field_flag = |a: &String| {
            matches!(a.as_str(), "-f" | "--field" | "--raw-field" | "--input")
                || a.starts_with("--field=")
                || a.starts_with("--raw-field=")
                || a.starts_with("--input=")
                || a.starts_with("-f")
        };
        // A field alone is not a write: read-only GraphQL REQUIRES `-f query=`,
        // and denying that while allowing `--field=query=mutation{…}` had the
        // detector inverted on the single endpoint where it matters most. What
        // makes a GraphQL call a write is the operation, not the flag shape.
        let graphql = operands.get(1).is_some_and(|o| *o == "graphql");
        let mutating_graphql = graphql
            && args
                .iter()
                .any(|a| a.contains("mutation") || a.contains("deletion"));
        let implicit_post = !graphql && args.iter().any(field_flag);
        return (explicit_method || implicit_post || mutating_graphql)
            .then(|| format!("'{verb} api' with a write method is not allowed — {BLOCKED}"));
    }

    // `gh auth status` is a read — except with `-t`/`--show-token`, which
    // PRINTS THE TOKEN. #1074 named `gh auth token` as the credential leak and
    // this allowlist quietly kept the other spelling of it. With the token in
    // hand the whole forge matcher is moot: `curl -X POST -H "Authorization:
    // bearer $T" .../pulls` has verb `curl` and is inspected by nothing.
    if group == "auth"
        && args
            .iter()
            .any(|a| a == "-t" || a == "--show-token" || a.starts_with("--show-token="))
    {
        return Some(format!(
            "'{verb} auth status --show-token' prints the forge credential — {BLOCKED}"
        ));
    }

    let Some((_, subs)) = FORGE_READS.iter().find(|(g, _)| *g == group) else {
        return Some(format!("'{verb} {group}' is not allowed — {BLOCKED}"));
    };
    if subs.is_empty() {
        return None;
    }
    match operands.get(1).copied() {
        Some(sub) if subs.contains(&sub) => None,
        Some(sub) => Some(format!("'{verb} {group} {sub}' is not allowed — {BLOCKED}")),
        // `gh pr` alone only prints usage, but a missing subcommand is exactly
        // the parse ambiguity to fail closed on.
        None => Some(format!(
            "'{verb} {group}' without a read-only subcommand is not allowed — {BLOCKED}"
        )),
    }
}

/// The governed assistant may perform an approved ordinary push, but never a
/// force push or remote-configuration mutation.
struct DenyForcePushAndRemoteReconfiguration;

impl Inspector for DenyForcePushAndRemoteReconfiguration {
    fn name(&self) -> &'static str {
        "governed_host.deny_force_push_and_remote_reconfiguration"
    }

    fn inspect(&self, tool: &str, params: &Value) -> InspectionResult {
        let Some(cmd) = shell_command(tool, params) else {
            return InspectionResult::Allow;
        };
        for seg in segments(&cmd) {
            if verb(&seg) != Some("git") {
                continue;
            }
            let push = seg.iter().any(|token| token == "push");
            let forced = seg.iter().any(|token| {
                token == "--force"
                    || token == "-f"
                    || token.starts_with("--force-with-lease")
                    || token.starts_with('+')
            });
            if push && forced {
                return InspectionResult::Deny("force-push is never allowed".into());
            }
            if seg.iter().any(|token| token == "remote")
                && seg.iter().any(|token| {
                    token == "add" || token == "set-url" || token == "remove" || token == "rename"
                })
            {
                return InspectionResult::Deny(
                    "mutating git remote configuration is not allowed".into(),
                );
            }
        }
        InspectionResult::Allow
    }
}

/// `git rebase/reset --hard/filter-branch` — the worktree HEAD is detached;
/// history rewrite is never needed and only ever destroys evidence.
struct DenyHistoryRewrite;

impl Inspector for DenyHistoryRewrite {
    fn name(&self) -> &'static str {
        "coder.deny_history_rewrite"
    }

    fn inspect(&self, tool: &str, params: &Value) -> InspectionResult {
        let Some(cmd) = shell_command(tool, params) else {
            return InspectionResult::Allow;
        };
        for seg in segments(&cmd) {
            if verb(&seg) != Some("git") {
                continue;
            }
            if seg.iter().any(|t| t == "rebase" || t == "filter-branch") {
                return InspectionResult::Deny("git history rewrite is not allowed".into());
            }
            if seg.iter().any(|t| t == "reset") && seg.iter().any(|t| t == "--hard") {
                return InspectionResult::Deny("git reset --hard is not allowed".into());
            }
            if seg.iter().any(|t| t == "worktree") && seg.iter().any(|t| t == "remove") {
                return InspectionResult::Deny(
                    "removing worktrees is the runtime's job, not the agent's".into(),
                );
            }
        }
        InspectionResult::Allow
    }
}

/// `sudo`/`doas`/service managers — the coder runs with user privileges, full
/// stop.
struct DenyPrivilegeEscalation;

const PRIVILEGE_VERBS: &[&str] = &[
    // POSIX
    "sudo",
    "doas",
    "su",
    "launchctl",
    "systemctl", //
    // Windows privilege elevation / service control.
    "runas",
    "sc",
    "psexec",
];

impl Inspector for DenyPrivilegeEscalation {
    fn name(&self) -> &'static str {
        "coder.deny_privilege_escalation"
    }

    fn inspect(&self, tool: &str, params: &Value) -> InspectionResult {
        let Some(cmd) = shell_command(tool, params) else {
            return InspectionResult::Allow;
        };
        for seg in segments(&cmd) {
            if let Some(v) = verb(&seg) {
                if PRIVILEGE_VERBS.contains(&v.to_ascii_lowercase().as_str()) {
                    return InspectionResult::Deny(format!(
                        "'{v}' is not allowed in a coder session"
                    ));
                }
            }
        }
        InspectionResult::Allow
    }
}

/// Reads of key stores and credential directories, via shell or file tools.
struct DenyCredentialAccess;

const CREDENTIAL_PATH_MARKERS: [&str; 6] = [
    "/.ssh",
    "/.aws",
    "/.gnupg",
    "/.kube",
    "/.car/secrets",
    "/.netrc",
];

impl Inspector for DenyCredentialAccess {
    fn name(&self) -> &'static str {
        "coder.deny_credential_access"
    }

    fn inspect(&self, tool: &str, params: &Value) -> InspectionResult {
        let haystacks: Vec<String> = if let Some(cmd) = shell_command(tool, params) {
            if cmd.contains("find-generic-password") || cmd.contains("find-internet-password") {
                return InspectionResult::Deny("keychain access is not allowed".into());
            }
            // Windows Credential Manager / DPAPI vault tooling.
            let cmd_lower = cmd.to_ascii_lowercase();
            if cmd_lower.contains("cmdkey") || cmd_lower.contains("vaultcmd") {
                return InspectionResult::Deny(
                    "Windows Credential Manager access is not allowed".into(),
                );
            }
            let sensitive_env = [
                "_key",
                "_token",
                "_secret",
                "_password",
                "openai_",
                "anthropic_",
                "azure_client_",
                "github_token",
                "connection_string",
            ];
            if sensitive_env
                .iter()
                .any(|marker| cmd_lower.contains(marker))
            {
                return InspectionResult::Deny(
                    "reading or expanding credential environment variables is not allowed".into(),
                );
            }
            for seg in segments(&cmd) {
                let Some(command) = verb(&seg).map(|value| value.to_ascii_lowercase()) else {
                    continue;
                };
                if command == "env" && seg.len() == 1
                    || command == "printenv"
                    || command == "set" && seg.len() == 1
                {
                    return InspectionResult::Deny(
                        "dumping the process environment is not allowed".into(),
                    );
                }
            }
            vec![cmd]
        } else if matches!(
            tool,
            "read_file" | "write_file" | "edit_file" | "grep_files"
        ) {
            params
                .get("path")
                .and_then(Value::as_str)
                .map(|p| vec![p.to_string()])
                .unwrap_or_default()
        } else {
            return InspectionResult::Allow;
        };
        for hay in &haystacks {
            // Normalize Windows separators and the various home spellings
            // ("~/.ssh", "$HOME/.ssh", "%USERPROFILE%\.ssh") into the same
            // forward-slash marker space as POSIX absolute paths.
            let hay = hay.replace('\\', "/");
            let hay = hay
                .replace("~/", "/HOME/.")
                .replace("$HOME/", "/HOME/.")
                .replace("%USERPROFILE%/", "/HOME/.")
                .replace("%HOMEPATH%/", "/HOME/.");
            let hay = hay.replace("/HOME/..", "/."); // "~/.ssh" → "/.ssh"
            for marker in CREDENTIAL_PATH_MARKERS {
                if hay.contains(marker) {
                    return InspectionResult::Deny(format!(
                        "access to credential path matching '{marker}' is not allowed"
                    ));
                }
            }
        }
        InspectionResult::Allow
    }
}

/// Destructive shell verbs aimed outside the worktree (absolute paths, `..`
/// escapes, `~`).
struct DenyDestructiveOutsideWorktree {
    worktree: PathBuf,
}

const DESTRUCTIVE_VERBS: &[&str] = &[
    // POSIX
    "rm", "rmdir", "mv", "cp", "chmod", "chown", "truncate", "dd", //
    // Windows `cmd.exe` (the coder shell runs `cmd /C` there) — without these
    // the destructive-outside-worktree guard did nothing on Windows.
    "del", "erase", "rd", "move", "copy", "format", "ren", "rename",
];

impl Inspector for DenyDestructiveOutsideWorktree {
    fn name(&self) -> &'static str {
        "coder.deny_destructive_outside_worktree"
    }

    fn inspect(&self, tool: &str, params: &Value) -> InspectionResult {
        let Some(cmd) = shell_command(tool, params) else {
            return InspectionResult::Allow;
        };
        for seg in segments(&cmd) {
            let Some(v) = verb(&seg) else { continue };
            // Case-insensitive: `cmd.exe` verbs are case-insensitive (DEL/del).
            let v_lower = v.to_ascii_lowercase();
            if !DESTRUCTIVE_VERBS.contains(&v_lower.as_str()) {
                continue;
            }
            // Skip flag-like args: POSIX `-x` and Windows `/x` (e.g. `del /q`).
            for arg in seg
                .iter()
                .skip(1)
                .filter(|a| !a.starts_with('-') && !is_windows_switch(a))
            {
                if arg.starts_with('~') {
                    return InspectionResult::Deny(format!(
                        "'{v}' on a home-relative path ('{arg}') is not allowed"
                    ));
                }
                if is_abs_or_traversal(arg) && !stays_under(&self.worktree, arg) {
                    return InspectionResult::Deny(format!(
                        "'{v}' outside the worktree ('{arg}') is not allowed"
                    ));
                }
            }
        }
        InspectionResult::Allow
    }
}

/// Environment repair — installing packages, creating interpreters, or dropping
/// an interpreter shim. The coder's job is the code; the runtime re-runs the
/// outcome contract in the correct environment to decide done, so a session that
/// "fixes" its interpreter is burning turns on a verdict it cannot change.
///
/// This used to live as ~140 words of prose in the coder system prompt — an
/// enumerated blacklist a model could reason its way around. As an inspector it
/// is enforced, and the model gets a denial *with a reason* instead, which the
/// loop already knows how to handle.
///
/// Deliberately scoped to what is mechanically decidable. `conftest.py`,
/// `pyproject.toml`, `tox.ini`, and `setup.cfg` are NOT denied: editing them is
/// often the actual task, and no matcher can separate "add a fixture" from
/// "change how tests run". Those stay a matter of judgment in the prompt.
/// `sitecustomize.py` has no legitimate task purpose and is denied.
struct DenyEnvironmentRepair;

/// Package-manager invocations that MUTATE the environment. Matched as
/// (verb, subcommand); a read-only subcommand (`pip list`, `pip show`) passes,
/// so a coder can still inspect what is installed.
const PACKAGE_MUTATIONS: &[(&str, &[&str])] = &[
    ("pip", &["install", "uninstall"]),
    ("pip3", &["install", "uninstall"]),
    ("conda", &["install", "remove", "uninstall", "update"]),
    ("poetry", &["add", "remove", "install", "update"]),
    ("uv", &["add", "remove", "sync"]),
    ("easy_install", &[]),
];

/// Interpreter/test-runner shims a coder has no task reason to author.
const SHIM_FILES: &[&str] = &["sitecustomize.py", "usercustomize.py"];

impl Inspector for DenyEnvironmentRepair {
    fn name(&self) -> &'static str {
        "coder.deny_environment_repair"
    }

    fn inspect(&self, tool: &str, params: &Value) -> InspectionResult {
        if matches!(tool, "write_file" | "edit_file") {
            let path = params.get("path").and_then(Value::as_str).unwrap_or("");
            let base = Path::new(path)
                .file_name()
                .map(|f| f.to_string_lossy().to_ascii_lowercase())
                .unwrap_or_default();
            if SHIM_FILES.contains(&base.as_str()) {
                return InspectionResult::Deny(format!(
                    "writing '{base}' changes how the interpreter loads, not what your code \
                     does — the runtime re-runs the contract in the correct environment"
                ));
            }
            return InspectionResult::Allow;
        }

        let Some(cmd) = shell_command(tool, params) else {
            return InspectionResult::Allow;
        };
        for seg in segments(&cmd) {
            let Some(v) = verb(&seg) else { continue };
            // Match on the program NAME, not the path it was invoked by:
            // `/usr/bin/python3.11 -m pip install` and `.venv/bin/pip install`
            // are the same action as the bare verb.
            let v = Path::new(&v.to_ascii_lowercase())
                .file_name()
                .map(|f| f.to_string_lossy().into_owned())
                .unwrap_or_default();
            let v = v.strip_suffix(".exe").unwrap_or(&v).to_string();
            let args: Vec<String> = seg.iter().skip(1).map(|a| a.to_ascii_lowercase()).collect();

            // `python -m pip install …` / `python -m venv …` — the verb is the
            // interpreter, so look past `-m` for the real module.
            let module = args
                .iter()
                .position(|a| a == "-m")
                .and_then(|i| args.get(i + 1))
                .cloned();
            let (effective, effective_args): (String, Vec<String>) = match module {
                Some(m) if v.starts_with("python") || v.starts_with("py") => {
                    let rest = args
                        .iter()
                        .skip_while(|a| **a != m)
                        .skip(1)
                        .cloned()
                        .collect();
                    (m, rest)
                }
                _ => (v.clone(), args.clone()),
            };

            if effective == "venv" || effective == "virtualenv" {
                return InspectionResult::Deny(
                    "creating an interpreter is environment repair, not part of the task — \
                     the runtime re-runs the contract in the correct environment"
                        .into(),
                );
            }
            for (mgr, subs) in PACKAGE_MUTATIONS {
                if effective != *mgr {
                    continue;
                }
                let mutates = subs.is_empty()
                    || effective_args.iter().any(|a| subs.contains(&a.as_str()))
                    // `uv pip install …` nests one level deeper.
                    || (effective == "uv" && effective_args.iter().any(|a| a == "install"));
                if mutates {
                    return InspectionResult::Deny(format!(
                        "'{mgr}' package mutation is environment repair, not part of the task \
                         — the runtime re-runs the contract in the correct environment"
                    ));
                }
            }
        }
        InspectionResult::Allow
    }
}

/// File-tool writes whose path resolves outside the worktree. (The executor
/// also clamps; defense in depth so a future executor change can't silently
/// drop the rule.)
struct DenyPathEscape {
    worktree: PathBuf,
}

impl Inspector for DenyPathEscape {
    fn name(&self) -> &'static str {
        "coder.deny_path_escape"
    }

    fn inspect(&self, tool: &str, params: &Value) -> InspectionResult {
        if !matches!(tool, "write_file" | "edit_file") {
            return InspectionResult::Allow;
        }
        let Some(path) = params.get("path").and_then(Value::as_str) else {
            return InspectionResult::Allow; // missing param fails in the tool itself
        };
        if stays_under(&self.worktree, path) {
            InspectionResult::Allow
        } else {
            InspectionResult::Deny(format!("write to '{path}' resolves outside the worktree"))
        }
    }
}

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

    fn chain() -> InspectorChain {
        coder_inspector_chain(Path::new("/wt"))
    }

    fn denied(tool: &str, params: Value) -> bool {
        chain().check(tool, &params).is_some()
    }

    fn sh(cmd: &str) -> Value {
        json!({ "command": cmd })
    }

    fn write_policy(dir: &Path, body: &str) {
        std::fs::create_dir_all(dir).unwrap();
        std::fs::write(dir.join("rules.toml"), body).unwrap();
    }

    #[test]
    fn coder_chain_merges_machine_and_project_deny_rules() {
        let root = tempfile::tempdir().unwrap();
        let repo = root.path().join("repo");
        let machine = root.path().join("machine-policies");
        let project = repo.join(".car").join("policies");
        std::fs::create_dir_all(&repo).unwrap();
        write_policy(&machine, "deny_tool = [\"write_file\"]\n");
        write_policy(&project, "deny_keyword = [\"DO NOT RUN\"]\n");

        let chain =
            coder_inspector_chain_from_policy_dirs(&repo, &[machine.clone(), project.clone()])
                .unwrap();
        assert!(chain
            .check("write_file", &json!({"path": "x", "content": "ok"}))
            .is_some());
        assert!(chain
            .check("shell", &json!({"command": "echo DO NOT RUN"}))
            .is_some());
        assert!(chain.check("read_file", &json!({"path": "x"})).is_none());
    }

    #[test]
    fn built_in_denial_reason_wins_before_project_policy() {
        let root = tempfile::tempdir().unwrap();
        let policies = root.path().join("policies");
        write_policy(&policies, "deny_tool = [\"shell\"]\n");
        let chain = coder_inspector_chain_from_policy_dirs(root.path(), &[policies]).unwrap();

        let reason = chain
            .check("shell", &sh("git push origin main"))
            .expect("both rules deny");
        assert!(
            reason.contains("git push"),
            "built-in reason must win: {reason}"
        );
        assert!(
            !reason.contains("operator policy"),
            "wrong precedence: {reason}"
        );
    }

    #[test]
    fn malformed_or_unenforced_policy_refuses_chain_construction() {
        let root = tempfile::tempdir().unwrap();
        let malformed = root.path().join("malformed");
        write_policy(&malformed, "deny_tool = [not valid TOML\n");
        assert!(coder_inspector_chain_from_policy_dirs(root.path(), &[malformed]).is_err());

        let trace = root.path().join("trace");
        write_policy(
            &trace,
            "[[trace_rule]]\nkind = \"never\"\ntool = \"deploy\"\n",
        );
        let err = coder_inspector_chain_from_policy_dirs(root.path(), &[trace])
            .err()
            .expect("trace rules are deliberately unenforced");
        assert!(err.to_string().contains("not enforced"), "{err}");
    }

    #[test]
    fn denies_package_mutation_and_interpreter_creation() {
        for cmd in [
            "pip install requests",
            "pip3 uninstall -y six",
            "python -m pip install --upgrade pip",
            "/usr/bin/python3.11 -m pip install pytest",
            "conda install numpy",
            "poetry add httpx",
            "uv pip install ruff",
            "python -m venv .venv",
            "virtualenv env",
            "easy_install foo",
            "cd /wt && pip install -e .",
        ] {
            assert!(denied("shell", sh(cmd)), "should be denied: {cmd}");
        }
    }

    #[test]
    fn allows_read_only_package_queries_and_real_test_runs() {
        // Inspecting the environment is fine; only mutation is env repair. And
        // the contract's own verify command must never be caught by this rule.
        for cmd in [
            "pip list",
            "pip show pytest",
            "python -m pytest -q tests/test_x.py",
            "/wt/.venv/bin/python -m pytest -q tests/test_x.py",
            "cargo test -p car-engine",
            "npm test",
        ] {
            assert!(!denied("shell", sh(cmd)), "should be allowed: {cmd}");
        }
    }

    #[test]
    fn denies_interpreter_shims_but_not_ordinary_test_config() {
        assert!(denied(
            "write_file",
            json!({ "path": "sitecustomize.py", "content": "x" })
        ));
        assert!(denied(
            "write_file",
            json!({ "path": "src/usercustomize.py", "content": "x" })
        ));
        // Editing test config is often the actual task — no matcher can tell
        // "add a fixture" from "change how tests run", so it stays judgment.
        for path in ["conftest.py", "pyproject.toml", "tox.ini", "setup.cfg"] {
            assert!(
                !denied("write_file", json!({ "path": path, "content": "x" })),
                "must stay allowed: {path}"
            );
        }
    }

    #[test]
    fn git_push_and_remote_mutation_denied() {
        assert!(denied("shell", sh("git push origin main")));
        assert!(denied("shell", sh("cargo test && git push --force")));
        assert!(denied("shell", sh("git remote add evil https://x")));
        assert!(denied("shell", sh("git remote set-url origin https://x")));
        // Reading remotes and committing are fine.
        assert!(!denied("shell", sh("git remote -v")));
        assert!(!denied("shell", sh("git commit -m 'x'")));
        assert!(!denied("shell", sh("git status && git diff")));
        // "push" in a non-git segment is fine.
        assert!(!denied("shell", sh("echo push")));
    }

    /// car#1074: `git push` was denied and `gh pr create` was not, so a coder
    /// session could publish its work without passing `coder.approve_merge`.
    #[test]
    fn forge_publication_denied_but_reads_allowed() {
        for cmd in [
            "gh pr create --fill",
            "gh pr merge --admin",
            "gh api --method DELETE /repos/o/r/branches/main/protection",
            "gh api -X POST /repos/o/r/issues",
            "gh api repos/o/r/issues -f title=x",
            "gh release create v9.9.9 ./x",
            "gh auth token",
            "gh repo fork",
            "glab mr create",
            "npm publish",
            "cargo publish",
            "docker push img",
            "docker login ghcr.io",
            "cargo test && gh pr create",
            "/opt/homebrew/bin/gh pr create --fill",
            // --- Adversarial shapes (review of #1076). Every one of these was
            // a working bypass; without them here they regress silently. ---
            //
            // `-h` was in the help allow-all, so ANY command carrying it was
            // waved through before its group was read. pflag takes the next
            // token as a string flag's value even when it starts with a dash.
            "gh release create v9.9.9 --notes -h",
            "gh pr create --title -h --body b --head mybranch --base main",
            // `-t`/`--show-token` PRINTS the credential. #1074 named
            // `gh auth token`; this is the same leak by another spelling, and
            // it sat on the read allowlist.
            "gh auth status -t",
            "gh auth status --show-token",
            // Attached-value forms. pflag parses these exactly like the
            // separated spellings the matcher already knew.
            "gh api -XPOST repos/o/r/pulls --input=-",
            "gh api -XPOST repos/o/r/pulls --field=title=x",
            "gh api --method=post repos/o/r/pulls",
            "gh api repos/o/r/issues --raw-field=title=x",
            // A GraphQL mutation, whatever flag shape carries it.
            "gh api graphql --field=query=mutation{createpullrequest}",
            // Leading operands that shifted the subcommand out of first place.
            "cargo +stable publish",
            "docker image push img",
            "npm --workspace x publish",
        ] {
            assert!(denied("shell", sh(cmd)), "should be denied: {cmd}");
        }

        // Reading the forge is how a coder checks CI on its own branch.
        for cmd in [
            "gh pr view 12",
            "gh pr checks",
            "gh pr diff 12",
            "gh issue list",
            "gh run view 5",
            "gh run watch 5",
            "gh api repos/o/r",
            "gh api --method GET /repos/o/r",
            "gh --repo o/r pr view 12",
            "gh auth status",
            "gh --version",
            "/opt/homebrew/bin/gh pr list",
            // Verb position only, as elsewhere in this chain.
            "echo gh pr create",
            // Ordinary build verbs keep their non-publish subcommands.
            "cargo test -p car-engine",
            "npm run build",
            "docker build -t img .",
            // Read-only GraphQL REQUIRES `-f query=`. Denying it while the
            // attached mutation form passed had the detector inverted on the
            // one endpoint where it matters most.
            "gh api graphql -f query=query{viewer{login}}",
        ] {
            assert!(!denied("shell", sh(cmd)), "should be allowed: {cmd}");
        }
    }

    /// The governed assistant is designed to reach production: `governance.rs`
    /// scores `gh run` / `az pipelines` as CI evidence and an approved
    /// `git push` as remote-main evidence. The forge guard is coder-only, and
    /// that carve-out is pinned here rather than by a comment.
    #[test]
    fn governed_host_still_allows_ci_reads_and_approved_push() {
        let chain = governed_host_inspector_chain(Path::new("/wt"));
        for command in [
            "gh run list",
            "az pipelines runs list",
            "git push origin HEAD:main",
        ] {
            assert!(
                chain.check("shell", &sh(command)).is_none(),
                "governed host must still allow {command}"
            );
        }
    }

    #[test]
    fn governed_host_allows_only_normal_push_shape() {
        let chain = governed_host_inspector_chain(Path::new("/wt"));
        assert!(chain
            .check("shell", &sh("git push origin HEAD:main"))
            .is_none());
        for command in [
            "git push --force origin main",
            "git push --force-with-lease origin main",
            "git push origin +HEAD:main",
            "git remote set-url origin https://evil",
            "git rebase -i HEAD~2",
            "git add .",
            "git add -A",
            "git commit -am fix",
        ] {
            assert!(
                chain.check("shell", &sh(command)).is_some(),
                "must deny {command}"
            );
        }
    }

    #[test]
    fn governed_host_denies_direct_reads_outside_repository() {
        let temp = tempfile::tempdir().unwrap();
        let repo = temp.path().join("repo");
        let outside = temp.path().join("outside.txt");
        std::fs::create_dir(&repo).unwrap();
        std::fs::write(&outside, "secret").unwrap();
        let chain = governed_host_inspector_chain(&repo);

        assert!(chain
            .check("read_file", &json!({"path": outside}))
            .is_some());
        assert!(chain
            .check("shell", &sh(&format!("cat {}", outside.display())))
            .is_some());
        assert!(chain.check("shell", &sh("cd ..")).is_some());
        assert!(chain.check("shell", &sh("cat src/lib.rs")).is_none());

        #[cfg(unix)]
        {
            std::os::unix::fs::symlink(&outside, repo.join("escape")).unwrap();
            assert!(chain
                .check("read_file", &json!({"path": "escape"}))
                .is_some());
            assert!(chain.check("shell", &sh("cat escape")).is_some());
        }
    }

    #[test]
    fn governed_host_denies_gui_shell_automation() {
        let chain = governed_host_inspector_chain(Path::new("/wt"));
        assert!(chain
            .check(
                "run_applescript",
                &json!({"script": "tell application \"Terminal\" to do script \"az deploy\""})
            )
            .is_some());
        assert!(chain
            .check("run_powershell", &json!({"script": "az deploy"}))
            .is_some());
    }

    #[test]
    fn history_rewrite_denied() {
        assert!(denied("shell", sh("git rebase -i HEAD~3")));
        assert!(denied("shell", sh("git reset --hard HEAD~1")));
        assert!(denied("shell", sh("git filter-branch --all")));
        assert!(denied("shell", sh("git worktree remove /wt")));
        assert!(!denied("shell", sh("git reset HEAD file.txt"))); // soft reset ok
    }

    #[test]
    fn privilege_escalation_denied() {
        assert!(denied("shell", sh("sudo rm -rf /tmp/x")));
        assert!(denied("shell", sh("doas pkg_add x")));
        assert!(denied("shell", sh("FOO=1 sudo make install")));
        assert!(denied("shell", sh("launchctl unload foo")));
        assert!(!denied("shell", sh("echo sudo"))); // verb position only
    }

    #[test]
    fn credential_access_denied_for_shell_and_file_tools() {
        assert!(denied("shell", sh("cat ~/.ssh/id_rsa")));
        assert!(denied("shell", sh("cat $HOME/.aws/credentials")));
        assert!(denied("shell", sh("security find-generic-password -s x")));
        assert!(denied("read_file", json!({"path": "/Users/u/.ssh/id_rsa"})));
        assert!(denied("read_file", json!({"path": "~/.netrc"})));
        assert!(!denied("read_file", json!({"path": "src/main.rs"})));
        // ".ssh" as a repo-relative dir name is unfortunate but stays denied —
        // conservative beats clever here.
    }

    #[test]
    fn destructive_ops_scoped_to_worktree() {
        assert!(denied("shell", sh("rm -rf /etc")));
        assert!(denied("shell", sh("rm -rf ../other-checkout")));
        assert!(denied("shell", sh("mv target ~/elsewhere")));
        assert!(denied("shell", sh("chmod 777 /usr/local/bin/x")));
        // Inside the worktree: fine, relative or absolute.
        assert!(!denied("shell", sh("rm -rf target/debug")));
        assert!(!denied("shell", sh("rm /wt/scratch.txt")));
        assert!(!denied("shell", sh("cp a.txt b.txt")));
    }

    #[test]
    fn write_path_escape_denied_but_reads_allowed() {
        assert!(denied(
            "write_file",
            json!({"path": "/etc/hosts", "content": "x"})
        ));
        assert!(denied("edit_file", json!({"path": "../outside.txt"})));
        assert!(!denied(
            "write_file",
            json!({"path": "src/new.rs", "content": "x"})
        ));
        assert!(!denied(
            "write_file",
            json!({"path": "/wt/src/new.rs", "content": "x"})
        ));
        // Reads outside the worktree are allowed (context gathering) unless
        // they hit credential markers.
        assert!(!denied(
            "read_file",
            json!({"path": "/usr/include/stdio.h"})
        ));
    }

    #[test]
    fn stays_under_is_lexical_and_strict() {
        let root = Path::new("/wt");
        assert!(stays_under(root, "src/x.rs"));
        assert!(stays_under(root, "a/../b.txt"));
        assert!(stays_under(root, "/wt/deep/file"));
        assert!(!stays_under(root, "../escape"));
        assert!(!stays_under(root, "a/../../escape"));
        assert!(!stays_under(root, "/etc/passwd"));
        assert!(!stays_under(root, "/wtevil/file")); // prefix, not component, match
    }

    #[cfg(windows)]
    #[test]
    fn windows_destructive_and_privilege_denied() {
        let chain = coder_inspector_chain(Path::new(r"C:\wt"));
        let denied = |cmd: &str| chain.check("shell", &sh(cmd)).is_some();
        // `cmd.exe` destructive verbs aimed outside the worktree.
        assert!(denied(r"del C:\Windows\System32\drivers\etc\hosts"));
        assert!(denied(r"rd /s /q C:\Windows"));
        assert!(denied(r"del /q C:\Users\victim\file")); // `/q` switch is skipped
        assert!(denied(r"move C:\wt\keep.txt C:\Users\public\stolen.txt"));
        // Windows privilege elevation.
        assert!(denied("runas /user:Administrator cmd"));
        assert!(denied("sc stop windefend"));
        // Inside the worktree: allowed (absolute or relative).
        assert!(!denied(r"del C:\wt\target\debug\app.exe"));
        assert!(!denied(r"del build\out.txt"));
        assert!(!denied("dir")); // non-destructive verb untouched
    }

    #[cfg(windows)]
    #[test]
    fn windows_credential_access_denied() {
        let chain = coder_inspector_chain(Path::new(r"C:\wt"));
        assert!(chain
            .check("shell", &sh(r"type %USERPROFILE%\.ssh\id_rsa"))
            .is_some());
        assert!(chain.check("shell", &sh("cmdkey /list")).is_some());
        assert!(chain
            .check(
                "read_file",
                &json!({"path": r"C:\Users\u\.aws\credentials"})
            )
            .is_some());
        // A normal source read is fine.
        assert!(chain
            .check("read_file", &json!({"path": r"C:\wt\src\main.rs"}))
            .is_none());
    }

    #[cfg(windows)]
    #[test]
    fn stays_under_handles_verbatim_prefix_and_case() {
        // A canonicalized worktree carries the `\\?\` verbatim prefix; a plain
        // absolute candidate inside it (any case) must still count as inside,
        // and NTFS case-insensitivity is honoured.
        let root = Path::new(r"\\?\C:\wt");
        assert!(stays_under(root, r"C:\WT\src\main.rs"));
        assert!(stays_under(root, r"c:\wt\src\main.rs"));
        assert!(!stays_under(root, r"C:\other\x"));
        assert!(!stays_under(root, r"C:\wtevil\x")); // prefix, not component
    }
}