trusty-mpm 1.8.2

trusty-mpm: unified multi-agent orchestration platform (core, daemon, CLI, TUI, Telegram)
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
//! Source writes into a main checkout, denied for the PM and for every agent
//! it dispatches ([ADR-0044](../../../../../../docs/adr/0044-main-checkout-write-boundary-and-agent-worktree-ownership.md),
//! enforced by [ADR-0048](../../../../../../docs/adr/0048-dispatched-writers-get-a-worktree-and-the-write-boundary-is-enforced.md)).
//!
//! Why: ADR-0044 decision 1 says a main-checkout session may write documents
//! and configuration only, and decision 2 says the restriction is enforced
//! mechanically rather than by convention. Only the destructive-git half was
//! ever built (`pm_guard_bash::main_checkout`), which covers `git reset --hard`
//! and its siblings and nothing else — an ordinary `Write` to a `.rs` file in
//! the shared checkout passed every guard in the process. That is the write the
//! reported incident was made of.
//!
//! What: [`evaluate_main_checkout_write`] denies an [`EDIT_TOOLS`] call whose
//! target file is source code AND lives in a main checkout. The two halves are
//! deliberately different questions from the ones `evaluate_edit_tool` asks:
//! that rule is about WHO is writing (the PM, subject to a per-turn budget, and
//! exempt for dispatched agents), while this one is about WHERE the write
//! lands, and it holds for everyone. Documents and configuration stay writable
//! because [`is_source_code_path`] does not classify `.md`, `.toml`, `.json`,
//! or an extension-less file as source — that is the same list ADR-0044's
//! "documents and configuration" boundary was written against, so the two agree
//! by construction rather than by a second list kept in step by hand.
//!
//! **It pierces the subagent exemptions**, exactly as the destructive-git rule
//! next door does and for the same reason: ADR-0044 binds "the PM and every
//! agent it dispatches", and both `CLAUDE_MPM_SUB_AGENT` (Guard 1) and the
//! `agent_id` dispatch marker (Guard 4) return ALLOW precisely for the agents
//! this rule exists to bind. A version placed after either would be a no-op for
//! its whole population. The operator escape hatches (Guard 2's
//! `TRUSTY_MPM_DISABLE_HOOKS`, Guard 3's `TRUSTY_MPM_PM_UNRESTRICTED`) still
//! lift it, unchanged, along with every other rule — #3981.
//!
//! **Fail-open, decided per branch, and this one does not consult a daemon** —
//! so unlike `pm_guard_dispatch` it has no unreachable-daemon arm to degrade
//! through, and its answer does not depend on anything else running on the
//! machine. The indeterminate arms all resolve to ALLOW, and each is a case
//! where nothing was positively identified: a tool call with no readable target
//! path names no file; a target with no `.git` ancestor is not a checkout; a
//! non-source extension is not this rule's business. The guard denies only on
//! positive evidence of both halves — with one fail-CLOSED arm (#8730): a
//! `Bash` write the parser found but could not delimit (an unclosed `$(`,
//! `(` or backtick, a `tee` that will not lex, nesting past the cap) denies,
//! because its target cannot be judged at all.
//!
//! **A `Bash` write lands here too (#7399).** A shell write used to reach only
//! `pm_guard_bash`'s `SHELL_EDIT_REASON`, which asks WHO is writing: it is
//! budget-tiered and both subagent exemptions skip it, so `git diff
//! --output=<file>` and `echo … > <file>` each landed a source file in a shared
//! main checkout within budget. `Bash` now takes the same two halves as an edit
//! tool, reading its targets from
//! [`pm_guard_bash::shell_write_targets`](super::pm_guard_bash::shell_write_targets)
//! — the redirect-or-git-write-option half of the one detector `pm_guard_bash`
//! already keeps, never a second parser. `SHELL_EDIT_REASON` is unchanged and
//! still fires for the PM on every shell write; this rule adds the WHERE
//! dimension ADR-0048's Consequences recorded as open.
//!
//! **Every segment is judged, none against anything but the hook cwd (#8468
//! option B).** A command with several write-bearing segments used to be
//! judged on only the FIRST segment `shell_write_targets` returned — a benign
//! first write (`echo hi > notes.md`) hid a later source write
//! (`&& echo … > src/lib.rs`) from this rule entirely. Three rounds tried
//! resolving a later segment's relative target against an earlier `cd`
//! instead, and the third round's critic found a symlink shape that allowed a
//! write main denies today; under the supervisor's hard-exit rule, #8468
//! ships this fallback instead: [`evaluate_main_checkout_write_with`] checks
//! EVERY target `shell_write_targets` names — including a `cd` segment's own
//! redirect, which was always one of those targets — and every one of them
//! resolves against the hook's `cwd`, never a directory a `cd` moved to.
//! Following `cd` moves to #8704.
//!
//! **A scratchpad-rooted clone is not a shared tree (#7778).** ADR-0044
//! protects the checkout other sessions are standing in; a disposable
//! `git clone --local` under the session scratchpad has no other session in it
//! and is reaped with the session. Treating it as a main checkout refused two
//! read-only reviews their probe file and blocks #7628's revert-experiment
//! recipe, so [`write_lands_in_a_scratchpad_clone`] lifts the deny for it —
//! keyed on the CHECKOUT ROOT, so a `scratchpad` directory inside a real
//! checkout exempts nothing, and fail-closed, so a scratchpad root that cannot
//! be determined leaves the refusal exactly as it was. It is the ONE question in
//! this module answered on CANONICALIZED paths, because it is the one whose
//! "yes" removes a deny; see that function for the three shapes that bought an
//! exemption from a lexical answer.
//!
//! Residual bypasses, stated rather than hidden. The deny half resolves the
//! path lexically, so a symlink into a checkout is not followed — the same
//! limit [`main_checkout_root`] carries and documents, and a fail-OPEN one: it
//! costs a missed refusal, never a wrong one. The exemption half is the
//! exception and resolves BOTH the root and the write target, so neither a
//! symlink nor a `..` chain can manufacture a `scratchpad` segment that is not
//! there, and neither can carry a write out of an exempt clone. Only the
//! nearest EXISTING ancestor of the target is resolved, which is as deep as the
//! filesystem can answer; a component created between this check and the write
//! is not seen, the TOCTOU window every `PreToolUse` path check has. The `Bash` half sees only the
//! shapes that NAME their target unambiguously — a redirect, a git write
//! option, and a `tee` operand, in every segment, subshell and substitution
//! (#8730) — so everything else keeps only the `SHELL_EDIT_REASON` treatment
//! and gets no WHERE dimension:
//!
//! * `git apply` and `git am` write the files a patch names, and the patch
//!   names them, not the argv.
//! * `cp`, `mv`, `install` and `dd` write a target that is an ordinary
//!   argument, indistinguishable here from the source they read.
//! * `sed -i` and the awk family put their target in the trailing position,
//!   which a read (`sed -n '1,5p' <file>`) occupies identically.
//! * An interpreter (`python -c`, `node -e`) carries its write inside a
//!   program string this guard does not parse.
//!
//! Each is a candidate for the same detector rather than a second rule; none
//! is closed here.
//!
//! **What an unexpanded expansion costs, exactly (#7838).** Three leading
//! forms ARE resolved, because this process holds their values rather than
//! guessing them ([`expand_leading_base`]): `~` and `$HOME`/`${HOME}` against
//! the hook's own HOME, which it shares with the shell it is judging, and
//! `$PWD`/`${PWD}` against the `cwd` the hook is handed. Any other variable or
//! command substitution is not resolved: nothing in this process holds the
//! value. The allowance is therefore scoped to the one thing such an expansion
//! actually hides, the BASE directory — [`base_directory_is_unresolvable`] —
//! leaving exactly three gaps:
//!
//! * A target whose FIRST segment is an unresolvable expansion (`$SP/v1.zsh`,
//!   `$FOO.rs`) is allowed even when it would have expanded into the checkout.
//!   This is the bypass #7838 chose over refusing every scratchpad write.
//! * A `~user/…` target names another account's home and is allowed unread;
//!   so is a `~`- or `$HOME`-rooted target when HOME is unset.
//! * An expansion in a deeper segment or in the filename is classified from
//!   the literal segments around it, so one that expands to `..` — or to a
//!   name carrying `/` — is judged against the wrong directory. That error
//!   runs toward DENY, never toward a silent allow, so it costs a refusal the
//!   operator can see and never the write ADR-0044 exists to stop. The #7778
//!   exemption does not soften it: a `..` that walks out of the scratchpad is
//!   resolved away before the root is judged.
//!
//! Test: `denies_*`, `allows_*` below; `pm_guard_denies_a_source_write_in_a_main_checkout`
//! and siblings in `tests/tm_hook_pm_guard.rs` run the real binary, including
//! the subagent-marked payload.

use std::path::{Path, PathBuf};

use trusty_mpm::core::project_aliases::main_checkout_root;

use super::pm_guard::{EDIT_TOOLS, edit_tool_target_path, is_source_code_path};
use super::pm_guard_bash::operator_checkouts::is_documents_repo;
use super::pm_guard_bash::{UnplaceableWrite, shell_write_targets};

/// Deny a source-file write whose target lives in a project's main checkout.
///
/// Why: the one entry point `pm_guard` calls, ordered cheapest test first so
/// the overwhelming majority of tool calls — everything that is neither an edit
/// nor a `Bash` call — costs one slice comparison and nothing else.
/// What: `Some(reason)` when the call names a write target, that target
/// [`is_source_code_path`], and the directory it resolves into
/// [`main_checkout_root`] — except when that checkout is rooted under the
/// session scratchpad ([`write_lands_in_a_scratchpad_clone`], #7778). The
/// targets come from
/// [`edit_tool_target_path`] for an [`EDIT_TOOLS`] member and from
/// [`shell_write_targets`] for `Bash` (#7399); every target is judged, in
/// order, and the first that qualifies denies (#8468 option B). `None`
/// (ALLOW) when none does.
/// Test: `denies_a_source_write_in_a_main_checkout`,
/// `allows_a_source_write_in_a_scratchpad_rooted_clone`,
/// `allows_documents_and_configuration`, `allows_a_write_inside_a_worktree`,
/// `denies_a_git_output_write_in_a_main_checkout`,
/// `allows_a_git_read_in_a_main_checkout`,
/// `allows_a_target_whose_base_directory_is_an_unexpanded_expansion`,
/// `denies_an_expansion_confined_to_the_filename`,
/// `denies_a_leading_tilde_that_resolves_into_the_checkout`,
/// `denies_a_dollar_pwd_first_segment_that_resolves_into_the_checkout`,
/// `denies_a_dollar_home_first_segment_that_resolves_into_the_checkout`.
pub(crate) fn evaluate_main_checkout_write(
    tool_name: &str,
    tool_input: Option<&serde_json::Value>,
    cwd: &Path,
) -> Option<String> {
    evaluate_main_checkout_write_with(tool_name, tool_input, cwd, home_dir().as_deref())
}

/// [`evaluate_main_checkout_write`] with the home directory injected.
///
/// Why (#7838 review, CRITICAL): the tilde arm needs a home that resolves into
/// a fixture checkout to be tested at all, and mutating `$HOME` in-process
/// races every sibling test in the binary — the failure #7746/#7989 fixed by
/// adding seams rather than by locking the environment. So the ambient read
/// happens once, in the wrapper above, and the decision itself is pure.
///
/// Why it loops (#8468 option B): this function used to decide on the single
/// first target `pm_guard_bash` found across the whole command, so a benign
/// first segment's write hid a source write in a later segment from this rule
/// entirely. [`write_targets`] now names one candidate per write-bearing
/// segment, each still resolved against `cwd` alone — never a directory a
/// `cd` moved to — and the first one that qualifies denies.
/// What: identical to [`evaluate_main_checkout_write`] except that `home` is
/// supplied. `None` for `home` is the HOME-unset case, which makes a `~`- or
/// `$HOME`-rooted target indeterminate.
/// Test: `denies_a_leading_tilde_that_resolves_into_the_checkout`,
/// `denies_a_dollar_home_first_segment_that_resolves_into_the_checkout`,
/// `allows_a_leading_tilde_when_home_is_unknown`,
/// `denies_a_second_segments_source_write_when_the_first_writes_elsewhere`.
fn evaluate_main_checkout_write_with(
    tool_name: &str,
    tool_input: Option<&serde_json::Value>,
    cwd: &Path,
    home: Option<&str>,
) -> Option<String> {
    // #8730: fail closed — a write whose target cannot be placed is refused.
    let targets = match write_targets(tool_name, tool_input) {
        Ok(targets) => targets,
        Err(what) => return Some(unplaceable_write_reason(what)),
    };
    targets
        .into_iter()
        .find_map(|target| deny_reason_for_target(&target, cwd, home))
}

/// [`evaluate_main_checkout_write_with`]'s per-target decision, unchanged from
/// before #8468 except for its caller now supplying one of several targets
/// instead of the command's only one.
///
/// Why/What/Test: see [`evaluate_main_checkout_write_with`].
fn deny_reason_for_target(target: &str, cwd: &Path, home: Option<&str>) -> Option<String> {
    // #7838: only the part of the path that decides the BASE directory has to
    // be literal; an expansion deeper in the path lands under a base this
    // guard already knows.
    let resolvable = expand_leading_base(target, cwd, home)?;
    if base_directory_is_unresolvable(&resolvable) {
        return None;
    }
    if !is_source_code_path(&resolvable) {
        return None;
    }
    let resolved = resolve_write_target(&resolvable, cwd);
    // One ancestor walk, reused by both halves below.
    let root = main_checkout_root(&resolved)?;
    // #7778: a disposable clone under the session scratchpad is nobody's shared
    // tree, so ADR-0044 has no other session's work to protect there.
    if write_lands_in_a_scratchpad_clone(&resolved, &root) {
        return None;
    }
    // #7905: an operator-listed documents repo has no source to protect.
    if is_documents_repo(&root) {
        return None;
    }
    // The message quotes the spelling the caller used, not the expansion.
    Some(deny_reason(target))
}

/// The directory name the agent harness gives each session's scratch space.
///
/// Matched exactly, never case-folded: a `SCRATCHPAD` directory that is not the
/// harness's own costs a refusal the operator can see, which is the direction
/// this trust boundary may err in.
const SCRATCHPAD_SEGMENT: &str = "scratchpad";

/// Does this write BOTH belong to a scratchpad-rooted checkout and land inside
/// it?
///
/// Why (#7778): two read-only reviews were refused a probe file (`.rs`, `.py`)
/// inside a disposable `git clone --local` placed in the scratchpad, and
/// neither could re-run a new test against pre-fix code as a result. A clone
/// made for one agent's own experiment is not the shared tree ADR-0044 protects
/// — no other session stands in it, and the harness reaps it — so the
/// main-checkout match is wrong there. #7628's revert-experiment recipe needs
/// the same exemption.
///
/// Why it CANONICALIZES, when nothing else in this module does (#7778 review,
/// HIGH): every other question here is answered lexically because a lexical
/// miss costs a missed deny — fail-open, the direction a guard can afford. This
/// one runs the other way: a lexical answer of "scratchpad" REMOVES a deny, so
/// a `scratchpad` segment that is only a spelling buys an exemption. Two shapes
/// did, on a binary built from the first cut of this fix — a symlink
/// `<scratchpad>/linkrepo -> <real checkout>`, and a literal `..` chain walking
/// out of the scratchpad — because [`main_checkout_root`] compares strings while
/// `find_git_root` `stat`s through both. Resolving the root first is what makes
/// the segment mean the directory rather than the spelling.
/// Canonicalizing the ROOT alone was not enough (#7778 review round 2,
/// MEDIUM): a symlink placed BELOW an exempt root — `<clone>/srclink ->
/// <real checkout>/crates/trusty-mpm/src` — left the root scratchpad-rooted
/// while the bytes landed in the real checkout, and both spellings ALLOWed on a
/// live binary. The root says which checkout the guard is reasoning about; only
/// the target says where the write goes. Both have to answer.
/// What: three conditions, all required. `root` canonicalizes; its canonical
/// form has a [`scratchpad_root`]; and the canonical form of `resolved`'s
/// nearest existing ancestor ([`canonical_existing_ancestor`] — the target
/// directory of a `Write` need not exist yet) is under that canonical root.
/// Every `Err` and every `None` returns `false` and the deny stands, so no
/// unresolvable path can widen the exemption. Called only once a deny is
/// otherwise certain, so ordinary traffic never pays for the syscalls.
/// Test: `allows_a_source_write_in_a_scratchpad_rooted_clone`,
/// `allows_a_dotdot_that_lands_back_inside_the_exempt_clone`,
/// `denies_a_symlink_below_an_exempt_root`,
/// `denies_a_checkout_reached_through_a_symlink_in_the_scratchpad`,
/// `denies_a_dotdot_escape_from_the_scratchpad`,
/// `denies_a_checkout_whose_path_merely_contains_the_scratchpad_name`,
/// `denies_when_no_scratchpad_root_can_be_determined`.
// #8339: shared with the ADR-0037 destructive-git rule, so both boundaries
// exempt the same scratchpad clones by the same proof.
pub(crate) fn write_lands_in_a_scratchpad_clone(resolved: &Path, root: &Path) -> bool {
    let Ok(real_root) = root.canonicalize() else {
        return false;
    };
    if scratchpad_root(&real_root).is_none() {
        return false;
    }
    canonical_existing_ancestor(resolved).is_some_and(|dir| dir.starts_with(&real_root))
}

/// The canonical form of the nearest ancestor of `path` that exists on disk.
///
/// Why: a `Write` routinely names a directory that does not exist yet, so
/// canonicalizing `path` itself would `Err` on the ordinary case and — under
/// [`write_lands_in_a_scratchpad_clone`]'s fail-closed rule — refuse every new
/// file in an exempt clone. The nearest EXISTING ancestor is the deepest point
/// the filesystem can actually answer about, and it is enough: a symlink can
/// only redirect a component that exists, so any redirection is already
/// resolved by the time the walk stops.
/// What: the first of [`Path::ancestors`] that [`Path::canonicalize`] accepts.
/// `None` only when no ancestor resolves at all.
/// Test: `denies_a_symlink_below_an_exempt_root`,
/// `allows_a_source_write_in_a_scratchpad_rooted_clone` (whose target directory
/// does not exist).
pub(crate) fn canonical_existing_ancestor(path: &Path) -> Option<PathBuf> {
    path.ancestors().find_map(|dir| dir.canonicalize().ok())
}

/// The session scratchpad directory `path` sits under, when it sits under one.
///
/// Why (#7778): nothing hands this process the scratchpad path — no env var, no
/// hook-payload field — so the root is read off the path itself, by the SAME
/// two-part definition `commands::projects::offerable` already uses for the
/// same directory: a `scratchpad` component under a system temp root. Inventing
/// a config knob would add a second, driftable answer to a question the crate
/// already answers.
/// What: the SHORTEST prefix of `path` whose final component is exactly
/// [`SCRATCHPAD_SEGMENT`] and which is itself under a system temp root
/// ([`trusty_common::bin_resolve::is_under_system_temp`], which compares whole
/// path components, so `/tmpfoo` is not `/tmp`). `None` — the root cannot be
/// determined — when no component matches or the matching prefix is outside
/// every temp root; the caller then refuses exactly as it did before, so the
/// undetermined case can never widen the exemption.
/// Test: `scratchpad_root_names_only_a_temp_rooted_harness_directory`,
/// `denies_when_no_scratchpad_root_can_be_determined`.
pub(crate) fn scratchpad_root(path: &Path) -> Option<PathBuf> {
    let mut prefix = PathBuf::new();
    for component in path.components() {
        prefix.push(component);
        if component.as_os_str() == SCRATCHPAD_SEGMENT
            && trusty_common::bin_resolve::is_under_system_temp(&prefix)
        {
            return Some(prefix);
        }
    }
    None
}

/// Every file this tool call would write, whichever tool named it.
///
/// Why (#7399, #8468 option B): the boundary's question is WHERE a write
/// lands, and the answer is the same question for an edit tool and for a
/// shell write — only the place the path is written down differs. Resolving
/// both here keeps one deny, one message and one pair of halves rather than a
/// second rule for `Bash`. A `Bash` command can name several writes across its
/// composition segments, and each must be judged — see
/// [`evaluate_main_checkout_write_with`].
/// What: `tool_input.file_path` for an [`EDIT_TOOLS`] member (at most one), and
/// for `Bash` every positively identified write target of its command
/// ([`shell_write_targets`]) — redirects, git write options and `tee` operands,
/// in every segment, subshell and substitution (#8730). Empty for every other
/// tool, and for a command that names no write. `Err` when the command holds a
/// write the guard cannot place.
/// Test: `denies_a_git_output_write_in_a_main_checkout`,
/// `denies_a_shell_redirect_into_a_main_checkout`,
/// `denies_a_second_segments_source_write_when_the_first_writes_elsewhere`,
/// `denies_a_tee_write_in_a_main_checkout`.
fn write_targets(
    tool_name: &str,
    tool_input: Option<&serde_json::Value>,
) -> Result<Vec<String>, UnplaceableWrite> {
    if EDIT_TOOLS.contains(&tool_name) {
        return Ok(edit_tool_target_path(tool_input)
            .map(str::to_owned)
            .into_iter()
            .collect());
    }
    if tool_name != "Bash" {
        return Ok(Vec::new());
    }
    let Some(command) = tool_input
        .and_then(|v| v.get("command"))
        .and_then(|v| v.as_str())
    else {
        return Ok(Vec::new());
    };
    shell_write_targets(command)
}

/// This process's home directory, read once at the ambient entry point.
///
/// Why: the `~` and `$HOME` arms of [`expand_leading_base`] need it, and a
/// `PreToolUse` hook inherits HOME from the very shell whose command it is
/// judging — unlike an arbitrary variable, the two agree by construction.
/// What: `$HOME`, `None` when unset or blank.
/// Test: `denies_a_leading_tilde_that_resolves_into_the_checkout` exercises the
/// value through the injected seam.
fn home_dir() -> Option<String> {
    std::env::var("HOME").ok().filter(|home| !home.is_empty())
}

/// Substitute a first segment this process can compute, or refuse to guess.
///
/// Why (#7838 review, CRITICAL): three leading forms are NOT arbitrary
/// variables. A `PreToolUse` hook shares the invoking shell's HOME and is
/// handed that shell's working directory, so `~`, `$HOME` and `$PWD` each name
/// a directory this process holds exactly. Routing them into the generic
/// unknown-expansion arm handed a real in-checkout write an ALLOW on any
/// machine whose checkout sits under `$HOME` — the ordinary layout — and on
/// every `$PWD`-rooted write without exception. Only these spellings are
/// substituted; a value guessed for any other name would be a guess, which is
/// the thing this rule refuses to make.
/// What: `Some(<base><rest>)` for `~`, `~/…`, and a FIRST SEGMENT spelled
/// exactly `$PWD`, `${PWD}`, `$HOME` or `${HOME}` — `cwd` for the two `PWD`
/// spellings, `home` for `~` and the two `HOME` spellings. `Some(target)`
/// unchanged for every other target, which then meets
/// [`base_directory_is_unresolvable`] as before. `None` when HOME is needed and
/// unknown, or for the `~user/…` form, which names another account's home and
/// is not this process's to resolve; `None` is indeterminate and the caller
/// allows.
/// Test: `denies_a_leading_tilde_that_resolves_into_the_checkout`,
/// `denies_a_dollar_pwd_first_segment_that_resolves_into_the_checkout`,
/// `denies_a_dollar_home_first_segment_that_resolves_into_the_checkout`,
/// `allows_a_leading_tilde_when_home_is_unknown`.
fn expand_leading_base(target: &str, cwd: &Path, home: Option<&str>) -> Option<String> {
    if let Some(rest) = target.strip_prefix('~') {
        if !(rest.is_empty() || rest.starts_with('/')) {
            return None;
        }
        return Some(join_base(home?, rest));
    }
    let (first, rest) = match target.split_once('/') {
        Some((first, rest)) => (first, format!("/{rest}")),
        None => (target, String::new()),
    };
    match first {
        "$PWD" | "${PWD}" => Some(join_base(&cwd.to_string_lossy(), &rest)),
        "$HOME" | "${HOME}" => Some(join_base(home?, &rest)),
        _ => Some(target.to_string()),
    }
}

/// Glue a substituted base to the remainder of the path.
///
/// What: `base` with any trailing `/` dropped, then `rest`, which is either
/// empty or already starts with `/` — so `$PWD/x` and a `cwd` of `/` yield
/// `/x`, not `//x`.
/// Test: `denies_a_dollar_pwd_first_segment_that_resolves_into_the_checkout`.
fn join_base(base: &str, rest: &str) -> String {
    format!("{}{rest}", base.trim_end_matches('/'))
}

/// Is the BASE directory of `target` hidden behind an unexpanded expansion?
///
/// Why (#7838, narrowed by its review): the guard runs in its own process and
/// never sees the calling shell's variables, so `$SP/v1.zsh` reaches it
/// verbatim, `Path::is_absolute` says false, and [`resolve_write_target`]
/// joined it to the hook cwd — a scratchpad write denied as a source write in
/// the checkout it merely happened to be launched from. But only the LEADING
/// segment decides which directory the path is relative to. Testing the whole
/// string for `$` allowed `crates/x/src/$(true)lib.rs` and
/// `crates/$(echo x)/src/lib.rs`, both of which land in the checkout no matter
/// what the expansion yields, and both of which this rule exists to deny.
/// Expanding the variable from THIS process's environment is still refused: a
/// shell variable set in the command's own shell is absent here, and one that
/// shares a name with an inherited variable may not share its value.
/// What: true only when the first non-empty segment of the directory component
/// carries `$` or a backtick — the segment that fixes the base. A target with
/// no `/` at all is its own filename, and an expansion there can still expand
/// to contain separators, so that case is indeterminate too. Every deeper
/// segment is left to [`main_checkout_root`], whose ancestor walk answers from
/// the literal segments that remain.
/// Test: `allows_a_target_whose_base_directory_is_an_unexpanded_expansion`,
/// `denies_an_expansion_confined_to_the_filename`,
/// `denies_an_expansion_in_a_middle_segment`.
fn base_directory_is_unresolvable(target: &str) -> bool {
    let Some((directory, _file)) = target.rsplit_once('/') else {
        return names_an_expansion(target);
    };
    directory
        .split('/')
        .find(|segment| !segment.is_empty())
        .is_some_and(names_an_expansion)
}

/// Does one path segment carry a shell expansion?
///
/// What: `$` (a variable or a `$(…)` substitution) or a backtick. Fail-open — a
/// literal `$` in a real directory name costs one missed deny, never a wrong one.
/// Test: `a_literal_target_is_not_read_as_an_expansion`.
fn names_an_expansion(segment: &str) -> bool {
    segment.contains('$') || segment.contains('`')
}

/// The directory a write to `target` would land in.
///
/// Why: [`main_checkout_root`] answers about a DIRECTORY, and the target names a
/// file that may not exist yet. Asking about the file's parent is what makes
/// the answer well defined for a `Write` that creates a new file, which is the
/// common case for the write this rule is trying to stop.
/// What: `target` resolved against `cwd` when relative, then its parent. A
/// target with no parent component (a bare filename at the filesystem root)
/// falls back to the resolved path itself.
/// Test: `resolves_a_relative_target_against_the_hook_cwd`.
fn resolve_write_target(target: &str, cwd: &Path) -> PathBuf {
    let path = Path::new(target);
    let absolute = if path.is_absolute() {
        path.to_path_buf()
    } else {
        cwd.join(path)
    };
    absolute
        .parent()
        .map_or_else(|| absolute.clone(), Path::to_path_buf)
}

/// Build the deny message.
///
/// Why: a bare refusal leaves the model guessing, and the guessed retry is
/// worse than the original call — the observed shape is an agent that reaches
/// for `Bash` and `cat >` after an `Edit` is refused. So the text names what
/// was blocked, why this directory is different from every other directory the
/// agent can write to, and the two remedies that actually exist. It says what
/// IS still writable in the same breath, because "read-only" reads as "you can
/// do nothing here" and that is not what ADR-0044 decided.
/// Test: `deny_reason_names_the_file_and_both_remedies`.
fn deny_reason(target: &str) -> String {
    format!(
        "Source write denied in a main checkout (ADR-0044): `{target}` is a source file in a \
         project's main checkout, which is read-only apart from documents and configuration. \
         Other sessions stand in this same directory — the reported failure is branches \
         switching under each other and a commit landing on a workstream it did not belong to, \
         with no error at any step. Do this work in a worktree instead: if you are a dispatched \
         agent, ask the PM to re-dispatch you with `isolation: \"worktree\"`, which gets you \
         your own tree; if you are the PM, dispatch the change to an agent rather than writing \
         it here. Documents (`.md`), configuration (`.toml`, `.json`, `.yaml`), and everything \
         under `.claude/worktrees/**` stay writable and are not affected by this rule."
    )
}

/// The deny for a `Bash` write whose target the guard cannot place (#8730).
///
/// Why: the boundary cannot tell whether an unparsed write lands in a main
/// checkout, and a missed deny is the direction ADR-0044 exists to prevent.
/// Bash rejects each such shape bar the nesting cap, so nothing that would
/// have run is lost.
/// Test: `denies_a_write_whose_target_cannot_be_placed`.
fn unplaceable_write_reason(what: UnplaceableWrite) -> String {
    format!(
        "Write target could not be placed (ADR-0044, #8730): this command writes through {what}, \
         so the guard cannot tell whether the write lands in a project's main checkout, and it \
         refuses rather than guess. Close the quote or parenthesis (bash rejects the command as \
         written), or flatten the nesting, and run it again."
    )
}

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

    /// A directory that answers `is_main_checkout`: a `.git` DIRECTORY, which
    /// is how git marks a main checkout and never a linked worktree.
    fn main_checkout() -> TempDir {
        let dir = tempfile::tempdir().expect("tempdir");
        std::fs::create_dir(dir.path().join(".git")).expect("mkdir .git");
        dir
    }

    fn write_input(path: &Path) -> serde_json::Value {
        serde_json::json!({"file_path": path.to_string_lossy(), "content": "fn main() {}"})
    }

    #[test]
    fn denies_a_source_write_in_a_main_checkout() {
        let dir = main_checkout();
        for tool in EDIT_TOOLS {
            let reason = evaluate_main_checkout_write(
                tool,
                Some(&write_input(&dir.path().join("src/lib.rs"))),
                dir.path(),
            )
            .unwrap_or_else(|| panic!("{tool} on a source file in a main checkout must be denied"));
            assert!(reason.contains("ADR-0044"), "{reason}");
        }
    }

    #[test]
    fn allows_documents_and_configuration() {
        // ADR-0044 decision 1 and decision 3: documents and configuration are
        // what a main-checkout session is FOR, and framework deployment writes
        // `.claude/` and `TASK.md` on every launch.
        let dir = main_checkout();
        for name in [
            "README.md",
            "CLAUDE.md",
            "Cargo.toml",
            ".claude/settings.json",
            "TASK.md",
            "docs/adr/0044-x.md",
            "Makefile",
        ] {
            assert_eq!(
                evaluate_main_checkout_write(
                    "Write",
                    Some(&write_input(&dir.path().join(name))),
                    dir.path()
                ),
                None,
                "{name} is a document or configuration and must stay writable"
            );
        }
    }

    #[test]
    fn allows_a_write_inside_a_worktree() {
        // The whole point of the rule is that there IS somewhere to write. A
        // linked worktree carries a `.git` FILE rather than a directory.
        let dir = tempfile::tempdir().expect("tempdir");
        std::fs::write(dir.path().join(".git"), "gitdir: /elsewhere").expect("write .git");
        assert_eq!(
            evaluate_main_checkout_write(
                "Write",
                Some(&write_input(&dir.path().join("src/lib.rs"))),
                dir.path()
            ),
            None
        );
    }

    #[test]
    fn allows_a_write_outside_any_repository() {
        // Not a checkout at all, so there is nothing for this rule to protect.
        let dir = tempfile::tempdir().expect("tempdir");
        assert_eq!(
            evaluate_main_checkout_write(
                "Write",
                Some(&write_input(&dir.path().join("scratch.rs"))),
                dir.path()
            ),
            None
        );
    }

    #[test]
    fn allows_every_tool_that_names_no_write() {
        // `Bash` is in the list since #7399, and stays here: this payload
        // carries a `file_path` and no `command`, so the shell half finds
        // nothing to resolve.
        let dir = main_checkout();
        for tool in ["Read", "Bash", "Grep", "Agent", "SendMessage"] {
            assert_eq!(
                evaluate_main_checkout_write(
                    tool,
                    Some(&write_input(&dir.path().join("src/lib.rs"))),
                    dir.path()
                ),
                None,
                "{tool} names no write here"
            );
        }
    }

    /// A `Bash` payload running `command`.
    fn bash_input(command: &str) -> serde_json::Value {
        serde_json::json!({"command": command})
    }

    // #7399: `git diff --output=<file>` writes exactly as `> <file>` does, so
    // the boundary must answer the same way for both.
    #[test]
    fn denies_a_git_output_write_in_a_main_checkout() {
        let dir = main_checkout();
        let target = dir.path().join("crates/x/src/lib.rs");
        let target = target.display().to_string();
        for command in [
            format!("git diff --output={target} HEAD~1 HEAD"),
            format!("git diff --output {target} HEAD"),
            format!("git log -1 --output={target}"),
            format!("git show HEAD --output={target}"),
            // `format-patch -o` and `archive -o` reach the same detector; they
            // name a directory and an archive, which `is_source_code_path`
            // does not classify as source, so the boundary leaves them to the
            // `SHELL_EDIT_REASON` deny #7405 already gives them.
            format!("git -C {} diff --output={target}", dir.path().display()),
        ] {
            let reason =
                evaluate_main_checkout_write("Bash", Some(&bash_input(&command)), dir.path())
                    .unwrap_or_else(|| {
                        panic!("`{command}` writes into a main checkout and must deny")
                    });
            assert!(reason.contains("ADR-0044"), "{reason}");
        }
    }

    // #7399: the redirect the boundary is made to match, proving both spellings
    // reach one deny with one message.
    #[test]
    fn denies_a_shell_redirect_into_a_main_checkout() {
        let dir = main_checkout();
        let target = dir.path().join("crates/x/src/lib.rs");
        let command = format!("echo 'fn main() {{}}' > {}", target.display());
        let reason = evaluate_main_checkout_write("Bash", Some(&bash_input(&command)), dir.path())
            .expect("a redirect into a main checkout's source must deny");
        assert!(reason.contains("ADR-0044"), "{reason}");
    }

    // #8468 option B: before the fix, `write_target` returned only the FIRST
    // segment's write across the whole command, so a benign first write
    // (`notes.md`) hid the second segment's source write from this rule
    // entirely — a false ALLOW. Every segment's own write must be judged.
    #[test]
    fn denies_a_second_segments_source_write_when_the_first_writes_elsewhere() {
        let dir = main_checkout();
        let target = dir.path().join("crates/x/src/lib.rs");
        let command = format!(
            "echo hi > {}/notes.md && echo 'fn main() {{}}' > {}",
            dir.path().display(),
            target.display()
        );
        let reason = evaluate_main_checkout_write("Bash", Some(&bash_input(&command)), dir.path())
            .unwrap_or_else(|| {
                panic!("`{command}`'s second segment writes source into the checkout")
            });
        assert!(reason.contains("ADR-0044"), "{reason}");
    }

    // #8468 option B: a `cd` segment's own trailing redirect is a write like
    // any other segment's, and — like every target this rule judges — it
    // resolves against the hook's `cwd` alone, never a directory the `cd`
    // moved to (following `cd` moved to #8704 after round 3's BLOCK).
    #[test]
    fn denies_a_cd_segments_own_redirect_in_a_main_checkout() {
        let dir = main_checkout();
        let command = "cd . > crates/x/src/lib.rs";
        let reason = evaluate_main_checkout_write("Bash", Some(&bash_input(command)), dir.path())
            .expect("a `cd` segment's own redirect into a main checkout's source must deny");
        assert!(reason.contains("ADR-0044"), "{reason}");
    }

    // #8468 option B: no `cd` is followed, so a later segment's relative
    // target still resolves against the hook `cwd` even though an earlier
    // segment `cd`s elsewhere — the deny direction this rule always prefers.
    #[test]
    fn denies_a_later_segments_write_resolved_against_the_hook_cwd_not_a_preceding_cd() {
        let dir = main_checkout();
        let command = "cd /tmp && echo 'fn main() {}' > crates/x/src/lib.rs";
        let reason = evaluate_main_checkout_write("Bash", Some(&bash_input(command)), dir.path())
            .expect("the relative target must resolve against the hook cwd, not /tmp");
        assert!(reason.contains("ADR-0044"), "{reason}");
    }

    /// Assert every command writes source into `dir`'s main checkout and denies.
    fn assert_each_denies(dir: &Path, commands: &[String]) {
        for command in commands {
            let reason = evaluate_main_checkout_write("Bash", Some(&bash_input(command)), dir)
                .unwrap_or_else(|| panic!("`{command}` writes source into a main checkout"));
            assert!(reason.contains("ADR-0044"), "{reason}");
        }
    }

    // #8730: `tee` names its file as an argument, never a redirect, so the
    // boundary read no target from it and every spelling was allowed.
    #[test]
    fn denies_a_tee_write_in_a_main_checkout() {
        let dir = main_checkout();
        let target = dir.path().join("crates/x/src/lib.rs").display().to_string();
        assert_each_denies(
            dir.path(),
            &[
                format!("tee {target}"),
                format!("echo x | tee {target}"),
                format!("echo x | tee -a {target} > /dev/null"),
                format!("echo x | sudo tee -- {target}"),
            ],
        );
    }

    // #8730: a write inside `$(…)` reached the redirect scan as `lib.rs)`, and
    // one inside a double-quoted `"$(…)"` was never scanned at all.
    #[test]
    fn denies_a_command_substitution_write_in_a_main_checkout() {
        let dir = main_checkout();
        let target = dir.path().join("crates/x/src/lib.rs").display().to_string();
        assert_each_denies(
            dir.path(),
            &[
                format!("echo $(echo x > {target})"),
                format!("echo \"$(echo x > {target})\""),
                format!("echo `echo x > {target}`"),
                format!("echo $(echo x | tee {target})"),
                format!("echo x > >(tee {target})"),
            ],
        );
    }

    // #8730: a subshell's closing `)` was glued to the redirect target.
    #[test]
    fn denies_a_subshell_write_in_a_main_checkout() {
        let dir = main_checkout();
        let target = dir.path().join("crates/x/src/lib.rs").display().to_string();
        assert_each_denies(
            dir.path(),
            &[
                format!("(echo x > {target})"),
                format!("( cd /tmp && echo x > {target} )"),
                format!("(echo x | tee {target})"),
            ],
        );
    }

    // #8730 critic, CRITICAL 1: `>|` was cut into a segment ending in `>` and a
    // segment naming the file as a command, so the clobber write was allowed.
    #[test]
    fn denies_a_clobber_redirect_in_a_main_checkout() {
        let dir = main_checkout();
        let target = dir.path().join("crates/x/src/lib.rs").display().to_string();
        assert_each_denies(
            dir.path(),
            &[
                format!("echo x >|{target}"),
                format!("echo x >| {target}"),
                format!("echo x >>| {target}"),
                format!("echo x >! {target}"),
                format!("echo $(echo x >| {target})"),
            ],
        );
    }

    // #8730 round 3: `>&word` opens `word` (bash), and zsh's `>&!`/`>&|`
    // always do; the scanner read each as a descriptor copy and allowed it.
    #[test]
    fn denies_a_descriptor_redirect_that_names_a_file_in_a_main_checkout() {
        let dir = main_checkout();
        let target = dir.path().join("crates/x/src/lib.rs").display().to_string();
        assert_each_denies(
            dir.path(),
            &[
                format!("echo x >&{target}"),
                format!("echo x >& {target}"),
                format!("echo x >&!{target}"),
                format!("echo x >&| {target}"),
            ],
        );
        let benign = "cargo test 2>&1 >&2";
        assert_eq!(
            evaluate_main_checkout_write("Bash", Some(&bash_input(benign)), dir.path()),
            None
        );
    }

    // #8730 critic, CRITICAL 2: a shell-run here-document body is shell
    // source; its substitutions were skipped with the body. A data body that
    // quotes the same text, written to the scratchpad, stays allowed.
    #[test]
    fn denies_a_substitution_inside_a_shell_heredoc_in_a_main_checkout() {
        let dir = main_checkout();
        let target = dir.path().join("crates/x/src/lib.rs").display().to_string();
        assert_each_denies(
            dir.path(),
            &[
                format!("bash <<'EOF'\n$(tee {target})\nEOF"),
                format!("bash <<'EOF'\necho $(echo x | tee {target})\nEOF"),
                format!("sh <<'EOF'\nsh -c \"$(echo x > {target})\"\nEOF"),
                format!("bash <<'EOF'\necho x > {target}\nEOF"),
                format!("bash <<'EOF'\necho x | tee {target}\nEOF"),
            ],
        );
        let pad = tempfile::tempdir().expect("tempdir");
        let pad = pad.path().join("scratchpad");
        std::fs::create_dir_all(&pad).expect("mkdir scratchpad");
        let data = format!(
            "cat <<'EOF' > {}\n$(tee {target})\nEOF",
            pad.join("x.md").display()
        );
        assert_eq!(
            evaluate_main_checkout_write("Bash", Some(&bash_input(&data)), dir.path()),
            None,
            "a data here-document quoting a write is not a write"
        );
    }

    // #8730 Fail-Open Check: a write whose body or arguments cannot be parsed
    // has no target to judge, so it denies wherever the hook stands — here a
    // directory that is no checkout at all.
    #[test]
    fn denies_a_write_whose_target_cannot_be_placed() {
        let dir = tempfile::tempdir().expect("tempdir");
        for command in [
            "echo $(echo x > src/lib.rs",
            "(echo x > src/lib.rs",
            "echo `echo x > src/lib.rs",
            "echo x | tee 'src/lib.rs",
        ] {
            let reason =
                evaluate_main_checkout_write("Bash", Some(&bash_input(command)), dir.path())
                    .unwrap_or_else(|| panic!("`{command}` cannot be placed and must deny"));
            assert!(reason.contains("#8730"), "{reason}");
        }
    }

    // #8730: the new shapes judge WHERE, like a redirect — a worktree, a
    // document, and literal text all stay allowed.
    #[test]
    fn allows_tee_substitution_and_subshell_writes_that_are_not_source_in_a_checkout() {
        let worktree = tempfile::tempdir().expect("tempdir");
        std::fs::write(worktree.path().join(".git"), "gitdir: /elsewhere").expect("write .git");
        let main = main_checkout();
        let in_worktree = worktree
            .path()
            .join("crates/x/src/lib.rs")
            .display()
            .to_string();
        let notes = main.path().join("notes.md").display().to_string();
        let source = main
            .path()
            .join("crates/x/src/lib.rs")
            .display()
            .to_string();
        for command in [
            format!("echo x | tee {in_worktree}"),
            format!("echo $(echo x > {in_worktree})"),
            format!("(echo x > {in_worktree})"),
            format!("echo x | tee -a {notes}"),
            format!("(echo x > {notes})"),
            format!("echo '$(echo x > {source})'"),
            format!("grep -n tee {source}"),
        ] {
            assert_eq!(
                evaluate_main_checkout_write("Bash", Some(&bash_input(&command)), main.path()),
                None,
                "`{command}` writes no source into a main checkout"
            );
        }
    }

    // #8111: a heredoc report into the session scratchpad was refused when its
    // body held an apostrophe (`it's`): the unbalanced quote made the heredoc
    // scan claim no body, so body prose (`echo x > <source>`) read as a live
    // redirect into the checkout. #8730's wider detection must not refuse the
    // quoted shapes either. The same text run as shell, and the same heredoc
    // aimed at the checkout, still deny.
    #[test]
    fn allows_a_scratchpad_heredoc_whose_body_names_a_source_write() {
        let main = main_checkout();
        let pad = tempfile::tempdir().expect("tempdir");
        let pad = pad.path().join("scratchpad");
        std::fs::create_dir_all(&pad).expect("mkdir scratchpad");
        let source = main
            .path()
            .join("crates/x/src/lib.rs")
            .display()
            .to_string();
        let body = format!(
            "see: echo x > {source}\nrun $(echo x > {source}), (echo x > {source}) or \
             `tee {source}`;\nit's done"
        );
        for name in ["report.md", "probe.rs"] {
            let command = format!("cat > {} <<'EOF'\n{body}\nEOF", pad.join(name).display());
            assert_eq!(
                evaluate_main_checkout_write("Bash", Some(&bash_input(&command)), main.path()),
                None,
                "`{command}` writes only the scratchpad"
            );
        }
        assert_each_denies(
            main.path(),
            &[
                format!("cat > {source} <<'EOF'\nfn main() {{}}\nEOF"),
                format!("echo x | tee {source} <<'EOF'\nfn main() {{}}\nEOF"),
                format!("cat > {}/r.md; echo x | tee {source}", pad.display()),
            ],
        );
    }

    // #7399: the worktree is where the write is SUPPOSED to land.
    #[test]
    fn allows_a_git_output_write_inside_a_worktree() {
        let dir = tempfile::tempdir().expect("tempdir");
        std::fs::write(dir.path().join(".git"), "gitdir: /elsewhere").expect("write .git");
        let target = dir.path().join("crates/x/src/lib.rs");
        let command = format!("git diff --output={} HEAD", target.display());
        assert_eq!(
            evaluate_main_checkout_write("Bash", Some(&bash_input(&command)), dir.path()),
            None
        );
    }

    // #7399 must not cost a single read. `--no-index` compares two files and
    // writes none; the plain forms write nothing either.
    #[test]
    fn allows_a_git_read_in_a_main_checkout() {
        let dir = main_checkout();
        let a = dir.path().join("crates/x/src/lib.rs");
        let a = a.display().to_string();
        for command in [
            format!("git diff --no-index {a} {a}"),
            "git diff HEAD~1 HEAD".to_string(),
            "git diff --stat".to_string(),
            format!("git diff --output-indicator-new=+ -- {a}"),
            format!("git format-patch --stdout -1 HEAD -- {a}"),
            // The sed/awk trailing token names a file `sed -n` only READS, so
            // the boundary deliberately does not resolve it.
            format!("sed -n '1,5p' {a}"),
        ] {
            assert_eq!(
                evaluate_main_checkout_write("Bash", Some(&bash_input(&command)), dir.path()),
                None,
                "`{command}` writes nothing"
            );
        }
    }

    // #7399 review, HIGH: a `>` inside a here-document BODY is prose, and the
    // whole heredoc reaches the guard as one segment (#6946). Denying on it
    // would refuse a command that writes nothing, through a deny no budget and
    // no subagent marker can soften.
    #[test]
    fn allows_a_heredoc_body_redirect_in_a_main_checkout() {
        let dir = main_checkout();
        let target = dir.path().join("crates/x/src/lib.rs");
        let command = format!("cat <<'EOF'\nsee: git diff > {}\nEOF", target.display());
        assert_eq!(
            evaluate_main_checkout_write("Bash", Some(&bash_input(&command)), dir.path()),
            None,
            "a here-document body is data, not a write"
        );
        // The operator line is still live.
        let live = format!("python3 <<'PY' > {}\nprint(1)\nPY", target.display());
        assert!(
            evaluate_main_checkout_write("Bash", Some(&bash_input(&live)), dir.path()).is_some(),
            "a redirect on the operator line is still a write"
        );
    }

    // #7399: documents keep the ADR-0049 carve-out through the shell too.
    #[test]
    fn allows_a_git_output_write_of_a_document() {
        let dir = main_checkout();
        let command = format!("git diff --output={}/notes.md HEAD", dir.path().display());
        assert_eq!(
            evaluate_main_checkout_write("Bash", Some(&bash_input(&command)), dir.path()),
            None
        );
    }

    #[test]
    fn allows_a_call_with_no_readable_target() {
        // Indeterminate: nothing was positively identified, so nothing is
        // denied. An input with no path names no file to classify.
        let dir = main_checkout();
        for input in [
            None,
            Some(serde_json::json!({})),
            Some(serde_json::json!({"file_path": ""})),
            Some(serde_json::json!({"file_path": 7})),
        ] {
            assert_eq!(
                evaluate_main_checkout_write("Write", input.as_ref(), dir.path()),
                None,
                "{input:?} names no target"
            );
        }
    }

    #[test]
    fn resolves_a_relative_target_against_the_hook_cwd() {
        // The hook payload carries relative paths routinely; resolving them
        // against the wrong base would make the rule miss every one of them.
        let dir = main_checkout();
        assert!(
            evaluate_main_checkout_write(
                "Edit",
                Some(&serde_json::json!({"file_path": "src/lib.rs"})),
                dir.path()
            )
            .is_some(),
            "a relative source path must resolve against the hook cwd"
        );
    }

    #[test]
    fn denies_an_absolute_write_from_outside_the_checkout() {
        // The shape a dispatched agent standing in its own worktree produces
        // when it reaches back into the shared tree by absolute path. The cwd
        // is innocent; the target is not.
        let checkout = main_checkout();
        let elsewhere = tempfile::tempdir().expect("tempdir");
        assert!(
            evaluate_main_checkout_write(
                "Write",
                Some(&write_input(&checkout.path().join("src/lib.rs"))),
                elsewhere.path()
            )
            .is_some(),
            "the target decides, not the caller's directory"
        );
    }

    // #7838: the reported shape is `$SP/v1.zsh`, the session scratchpad written
    // through a variable. The FIRST segment is the expansion, so the base
    // directory is unknown and none of these is evidence of a write into the
    // checkout.
    #[test]
    fn allows_a_target_whose_base_directory_is_an_unexpanded_expansion() {
        let dir = main_checkout();
        for command in [
            "cat <<'EOF' > $SP/v1.zsh\necho hi\nEOF",
            "echo hi > ${SP}/v1.zsh",
            "echo hi > $(mktemp -d)/probe.rs",
            // No separator at all: the token can still expand to contain one.
            "echo hi > $SCRATCH.rs",
        ] {
            assert_eq!(
                evaluate_main_checkout_write("Bash", Some(&bash_input(command)), dir.path()),
                None,
                "`{command}` names no base directory this guard can resolve"
            );
        }
        // An edit tool carries the same unresolved spelling through
        // `file_path`, and must answer the same way.
        assert_eq!(
            evaluate_main_checkout_write(
                "Write",
                Some(&serde_json::json!({"file_path": "$SP/v1.zsh"})),
                dir.path()
            ),
            None,
        );
    }

    // #7838 review, CRITICAL: an expansion AFTER a literal directory hides
    // nothing about WHERE the write lands — these were DENY before #7838 and
    // the allowance must not have reached them.
    #[test]
    fn denies_an_expansion_confined_to_the_filename() {
        let dir = main_checkout();
        for command in [
            "echo hi > crates/x/src/$(true)lib.rs",
            "echo hi > crates/x/src/`true`lib.rs",
        ] {
            let reason =
                evaluate_main_checkout_write("Bash", Some(&bash_input(command)), dir.path())
                    .unwrap_or_else(|| {
                        panic!("`{command}` lands in a literal in-checkout directory")
                    });
            assert!(reason.contains("ADR-0044"), "{reason}");
        }
    }

    // #7838 review, CRITICAL: same for a middle segment. Whatever
    // `$(echo trusty-mpm)` yields, the path is still relative to the hook cwd,
    // so `is_main_checkout`'s ancestor walk answers from the literal segments.
    #[test]
    fn denies_an_expansion_in_a_middle_segment() {
        let dir = main_checkout();
        // Through an edit tool, which carries the path verbatim. The shell
        // route is the `${PKG}` spelling below: `shell_write_targets`
        // tokenizes on whitespace, so a `$( … )` carrying a space never
        // reaches here as one target at all — a limit of that lexer, not of
        // this rule.
        for input in [
            serde_json::json!({"file_path": "crates/$(echo trusty-mpm)/src/lib.rs"}),
            serde_json::json!({"file_path": "crates/${PKG}/src/lib.rs"}),
        ] {
            let reason = evaluate_main_checkout_write("Write", Some(&input), dir.path())
                .unwrap_or_else(|| panic!("{input} is still relative to the hook cwd"));
            assert!(reason.contains("ADR-0044"), "{reason}");
        }
        let command = "echo hi > crates/${PKG}/src/lib.rs";
        let reason = evaluate_main_checkout_write("Bash", Some(&bash_input(command)), dir.path())
            .expect("a relative path under the hook cwd is still in the checkout");
        assert!(reason.contains("ADR-0044"), "{reason}");
    }

    // #7838 review, CRITICAL: a tilde is not an arbitrary variable — the hook
    // shares the invoking shell's HOME. HOME is injected rather than set, so
    // this cannot race a sibling test (#7746, #7989).
    #[test]
    fn denies_a_leading_tilde_that_resolves_into_the_checkout() {
        let home = tempfile::tempdir().expect("tempdir");
        let checkout = home.path().join("proj");
        std::fs::create_dir_all(checkout.join(".git")).expect("mkdir .git");
        let elsewhere = tempfile::tempdir().expect("tempdir");
        let home = home.path().to_string_lossy().into_owned();
        let reason = evaluate_main_checkout_write_with(
            "Write",
            Some(&serde_json::json!({"file_path": "~/proj/src/lib.rs"})),
            elsewhere.path(),
            Some(&home),
        )
        .expect("a tilde path resolving into a main checkout must deny");
        assert!(reason.contains("ADR-0044"), "{reason}");
        // The message quotes what the caller wrote, not the expansion.
        assert!(reason.contains("~/proj/src/lib.rs"), "{reason}");
    }

    // The fail-open half: with no HOME, and for another account's home, the
    // tilde names a directory this process cannot compute.
    #[test]
    fn allows_a_leading_tilde_when_home_is_unknown() {
        let dir = main_checkout();
        assert_eq!(
            evaluate_main_checkout_write_with(
                "Write",
                Some(&serde_json::json!({"file_path": "~/proj/src/lib.rs"})),
                dir.path(),
                None,
            ),
            None,
            "HOME unset leaves the tilde unresolvable"
        );
        let cwd = dir.path();
        assert_eq!(
            expand_leading_base("~someone/src/lib.rs", cwd, Some("/home/me")),
            None
        );
        assert_eq!(
            expand_leading_base("$HOME/src/lib.rs", cwd, None),
            None,
            "HOME unset leaves `$HOME` unresolvable too"
        );
        assert_eq!(
            expand_leading_base("/tmp/a~b.rs", cwd, None),
            Some("/tmp/a~b.rs".to_string()),
            "a tilde that is not leading is an ordinary character"
        );
        // Only the four exact spellings substitute; a name that merely starts
        // with one stays in the generic unresolvable arm.
        for target in ["$PWDX/src/lib.rs", "$HOMEDIR/src/lib.rs", "$SP/v1.zsh"] {
            assert_eq!(
                expand_leading_base(target, cwd, Some("/home/me")),
                Some(target.to_string()),
                "{target} is not one of the four resolvable spellings"
            );
        }
    }

    // #7838 review round 2, CRITICAL: `$PWD` is not an arbitrary variable —
    // `cwd` is a parameter of this very function. Both routes that name a
    // target must resolve it.
    #[test]
    fn denies_a_dollar_pwd_first_segment_that_resolves_into_the_checkout() {
        let dir = main_checkout();
        let inputs = [
            ("Bash", bash_input("echo hi > $PWD/crates/x/src/lib.rs")),
            (
                "Write",
                serde_json::json!({"file_path": "$PWD/crates/x/src/lib.rs"}),
            ),
            (
                "Edit",
                serde_json::json!({"file_path": "${PWD}/crates/x/src/lib.rs"}),
            ),
        ];
        for (tool, input) in inputs {
            let reason = evaluate_main_checkout_write_with(tool, Some(&input), dir.path(), None)
                .unwrap_or_else(|| panic!("{tool} {input} resolves to the hook cwd"));
            assert!(reason.contains("ADR-0044"), "{reason}");
        }
    }

    // #7838 review round 2, CRITICAL: `$HOME` reaches the same value the `~`
    // arm already uses, so the two spellings must answer alike.
    #[test]
    fn denies_a_dollar_home_first_segment_that_resolves_into_the_checkout() {
        let home = tempfile::tempdir().expect("tempdir");
        let checkout = home.path().join("proj");
        std::fs::create_dir_all(checkout.join(".git")).expect("mkdir .git");
        let elsewhere = tempfile::tempdir().expect("tempdir");
        let home = home.path().to_string_lossy().into_owned();
        for spelling in ["$HOME", "${HOME}"] {
            let target = format!("{spelling}/proj/src/lib.rs");
            let reason = evaluate_main_checkout_write_with(
                "Write",
                Some(&serde_json::json!({ "file_path": target })),
                elsewhere.path(),
                Some(&home),
            )
            .unwrap_or_else(|| panic!("{target} resolves into a main checkout"));
            assert!(reason.contains("ADR-0044"), "{reason}");
            assert!(reason.contains(&target), "{reason}");
        }
    }

    // The other half of #7838: the allowance is scoped to the base directory,
    // so a literal relative path still denies exactly as it did before.
    #[test]
    fn a_literal_target_is_not_read_as_an_expansion() {
        assert!(!base_directory_is_unresolvable("src/lib.rs"));
        assert!(!base_directory_is_unresolvable("/tmp/a~b.rs"));
        assert!(!base_directory_is_unresolvable(
            "crates/x/src/$(true)lib.rs"
        ));
        assert!(!base_directory_is_unresolvable(
            "crates/$(echo x)/src/lib.rs"
        ));
        assert!(base_directory_is_unresolvable("$SP/v1.zsh"));
        assert!(base_directory_is_unresolvable("/$(echo tmp)/v1.zsh"));
        let dir = main_checkout();
        assert!(
            evaluate_main_checkout_write(
                "Write",
                Some(&serde_json::json!({"file_path": "src/lib.rs"})),
                dir.path()
            )
            .is_some(),
            "a literal relative source path must still deny"
        );
    }

    /// A `<temp>/scratchpad/<name>` clone, `.git` DIRECTORY and all — the shape
    /// `git clone --local` leaves in the harness scratchpad (#7778).
    ///
    /// `tempfile::tempdir()` lands under `std::env::temp_dir()`, which is the
    /// same value `is_under_system_temp` consults, so the fixture is temp-rooted
    /// on every host rather than only on the one that wrote the test.
    fn scratchpad_clone(name: &str) -> (TempDir, PathBuf) {
        let dir = tempfile::tempdir().expect("tempdir");
        let clone = dir.path().join("scratchpad").join(name);
        std::fs::create_dir_all(clone.join(".git")).expect("mkdir .git");
        (dir, clone)
    }

    // #7778 condition 1. RED before the fix: the clone answers
    // `is_main_checkout`, so both spellings were denied and two read-only
    // reviews could not drop a probe file into their own throwaway clone.
    #[test]
    fn allows_a_source_write_in_a_scratchpad_rooted_clone() {
        let (_dir, clone) = scratchpad_clone("revert-probe");
        for name in ["crates/x/src/lib.rs", "probe.py"] {
            assert_eq!(
                evaluate_main_checkout_write(
                    "Write",
                    Some(&write_input(&clone.join(name))),
                    &clone
                ),
                None,
                "{name} lands in a disposable scratchpad clone, not a shared tree"
            );
        }
        // The shell half shares the one decision point, so it must agree.
        let command = format!(
            "echo 'fn main() {{}}' > {}",
            clone.join("probe.rs").display()
        );
        assert_eq!(
            evaluate_main_checkout_write("Bash", Some(&bash_input(&command)), &clone),
            None
        );
    }

    // #7778 review, HIGH: a symlink under the scratchpad pointing at a REAL
    // checkout made that checkout answer as scratchpad-rooted, because the root
    // was judged as the lexical string `find_git_root` stat'ed through. Both
    // spellings must deny.
    #[test]
    fn denies_a_checkout_reached_through_a_symlink_in_the_scratchpad() {
        let dir = tempfile::tempdir().expect("tempdir");
        let real = dir.path().join("realrepo");
        std::fs::create_dir_all(real.join(".git")).expect("mkdir .git");
        let pad = dir.path().join("scratchpad");
        std::fs::create_dir_all(&pad).expect("mkdir scratchpad");
        let link = pad.join("linkrepo");
        std::os::unix::fs::symlink(&real, &link).expect("symlink");

        let target = link.join("crates/trusty-mpm/src/zzz_probe.rs");
        let reason = evaluate_main_checkout_write("Write", Some(&write_input(&target)), dir.path())
            .expect("a symlink into a real checkout must not buy an exemption");
        assert!(reason.contains("ADR-0044"), "{reason}");

        let command = format!("echo 'fn main() {{}}' > {}", target.display());
        assert!(
            evaluate_main_checkout_write("Bash", Some(&bash_input(&command)), dir.path()).is_some(),
            "the shell half must answer the same way"
        );
    }

    // #7778 review, HIGH: the sibling shape — no symlink, a literal `..` chain
    // that walks out of the scratchpad into a real checkout. `find_git_root`
    // stats through `..`, so the root string still carried a `scratchpad`
    // component.
    #[test]
    fn denies_a_dotdot_escape_from_the_scratchpad() {
        let dir = tempfile::tempdir().expect("tempdir");
        let real = dir.path().join("realrepo");
        std::fs::create_dir_all(real.join(".git")).expect("mkdir .git");
        let clone = dir.path().join("scratchpad").join("revert-probe");
        std::fs::create_dir_all(clone.join(".git")).expect("mkdir .git");

        // `<dir>/scratchpad/revert-probe/../../realrepo/src/zzz_probe.rs`
        let target = clone.join("../../realrepo/src/zzz_probe.rs");
        let reason = evaluate_main_checkout_write("Write", Some(&write_input(&target)), dir.path())
            .expect("a `..` escape into a real checkout must not buy an exemption");
        assert!(reason.contains("ADR-0044"), "{reason}");
    }

    // #7778 review round 2, MEDIUM: canonicalizing the ROOT alone left a
    // symlink BELOW an exempt root free to route the write into a real
    // checkout — the root stayed scratchpad-rooted, the bytes did not.
    #[test]
    fn denies_a_symlink_below_an_exempt_root() {
        let dir = tempfile::tempdir().expect("tempdir");
        let real = dir.path().join("realrepo");
        std::fs::create_dir_all(real.join(".git")).expect("mkdir .git");
        let real_src = real.join("crates/trusty-mpm/src");
        std::fs::create_dir_all(&real_src).expect("mkdir src");
        let clone = dir.path().join("scratchpad").join("revert-probe");
        std::fs::create_dir_all(clone.join(".git")).expect("mkdir .git");
        let link = clone.join("srclink");
        std::os::unix::fs::symlink(&real_src, &link).expect("symlink");

        let target = link.join("zzz_probe.rs");
        let reason = evaluate_main_checkout_write("Write", Some(&write_input(&target)), &clone)
            .expect("a symlink below an exempt root must not carry the write out");
        assert!(reason.contains("ADR-0044"), "{reason}");

        let command = format!("echo 'fn main() {{}}' > {}", target.display());
        assert!(
            evaluate_main_checkout_write("Bash", Some(&bash_input(&command)), &clone).is_some(),
            "the shell half must answer the same way"
        );
    }

    // The other side of the same rule: a `..` that leaves and RE-ENTERS the
    // exempt clone still lands inside it, so it must stay allowed.
    #[test]
    fn allows_a_dotdot_that_lands_back_inside_the_exempt_clone() {
        let (_dir, clone) = scratchpad_clone("revert-probe");
        std::fs::create_dir_all(clone.join("crates")).expect("mkdir crates");
        let target = clone.join("crates/../src/lib.rs");
        assert_eq!(
            evaluate_main_checkout_write("Write", Some(&write_input(&target)), &clone),
            None,
            "the write lands inside the exempt clone"
        );
    }

    // #7778 condition 3: the exemption is decided on the CHECKOUT ROOT, so a
    // `scratchpad` directory sitting INSIDE a real checkout exempts nothing —
    // the case a target-path test would have got wrong.
    #[test]
    fn denies_a_checkout_whose_path_merely_contains_the_scratchpad_name() {
        let dir = main_checkout();
        for name in ["scratchpad/probe.rs", "scratchpad/nested/probe.py"] {
            let reason = evaluate_main_checkout_write(
                "Write",
                Some(&write_input(&dir.path().join(name))),
                dir.path(),
            )
            .unwrap_or_else(|| panic!("{name} is inside a real checkout and must be refused"));
            assert!(reason.contains("ADR-0044"), "{reason}");
        }
    }

    // #7778 Fail-Open Check: an undeterminable scratchpad root leaves the
    // refusal exactly as it was. A temp-rooted clone with no `scratchpad`
    // component is the case, and it denies.
    #[test]
    fn denies_when_no_scratchpad_root_can_be_determined() {
        let dir = tempfile::tempdir().expect("tempdir");
        let clone = dir.path().join("revert-probe");
        std::fs::create_dir_all(clone.join(".git")).expect("mkdir .git");
        assert_eq!(scratchpad_root(&clone), None);
        assert!(
            evaluate_main_checkout_write(
                "Write",
                Some(&write_input(&clone.join("probe.rs"))),
                &clone
            )
            .is_some(),
            "no scratchpad root could be determined, so the deny must stand"
        );
    }

    /// The root finder on its own: both halves of the definition are required,
    /// and the match is component-exact.
    #[test]
    fn scratchpad_root_names_only_a_temp_rooted_harness_directory() {
        assert_eq!(
            scratchpad_root(Path::new(
                "/private/tmp/claude-502/proj/9f1c/scratchpad/clone/src"
            )),
            Some(PathBuf::from(
                "/private/tmp/claude-502/proj/9f1c/scratchpad"
            ))
        );
        // Outside every temp root, `scratchpad` is just somebody's directory.
        assert_eq!(
            scratchpad_root(Path::new("/Users/x/repos/scratchpad/clone")),
            None
        );
        // Component-exact: a name that merely CONTAINS the string is not it.
        assert_eq!(
            scratchpad_root(Path::new("/private/tmp/claude-502/scratchpad-notes/clone")),
            None
        );
        assert_eq!(
            scratchpad_root(Path::new("/private/tmp/claude-502/x")),
            None
        );
    }

    #[test]
    fn deny_reason_names_the_file_and_both_remedies() {
        let reason = deny_reason("src/lib.rs");
        assert!(reason.contains("src/lib.rs"), "{reason}");
        assert!(reason.contains(r#"isolation: "worktree""#), "{reason}");
        assert!(reason.contains("Documents"), "{reason}");
    }
}