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
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
//! Whole-tree-destructive git commands, denied in a project's main checkout
//! ([ADR-0037](../../../../../../../docs/adr/0037-pm-placement-precedence-main-checkout-by-default.md)).
//!
//! Why: ADR-0037's write-restriction amendment makes the main checkout
//! read-only except for documents and configuration, and records that the
//! enforcement "is mechanical and NOT YET BUILT". This module is that
//! mechanism for the destructive-git half. The incident it is built from: a
//! `local-ops` agent dispatched by a DIFFERENT session ran `git checkout <sha>
//! -- .`, `git reset HEAD`, then `git clean -fdx -- crates/ docs/` in the
//! shared main checkout — switching the branch under another live session,
//! discarding uncommitted work, and sweeping build caches across seven UI
//! packages and two crate `target/` directories. Its dispatch brief said that
//! checkout was off-limits. A prohibition in a brief is not enforcement, and a
//! brief is invisible to agents from other sessions.
//!
//! What: [`evaluate_main_checkout_destructive_command`] denies a `Bash` call
//! when BOTH halves hold — the command names a whole-tree-destructive git verb
//! ([`is_whole_tree_destructive`]) AND the directory that verb would act on
//! ([`git_verb_target_dir`]) is a main checkout
//! ([`trusty_mpm::core::project_aliases::is_main_checkout`]). Anything under
//! `.claude/worktrees/**` or `.worktrees/**` is a worktree, never a main
//! checkout, so delegated work stays fully writable — that is where it is
//! supposed to happen.
//!
//! **It pierces the subagent exemptions, deliberately.** Like the
//! `git worktree add` denylist (#3977) and the fan-out denial (#4784), this is
//! called from `pm_guard()` BEFORE Guard 1's and Guard 4's early returns —
//! see that call site's comment. The incident was an AGENT, dispatched by
//! another session, so a PM-only rule would be a no-op for exactly the case it
//! exists for. The owner's 2026-07-26 ruling on #3973 permits this only for a
//! SAFETY rule, and the scope here is drawn to match: irreversible destruction
//! of another session's uncommitted work, nothing wider. It is not a role rule
//! and not a style rule — a subagent keeps every other tool and every
//! non-destructive git verb, in the main checkout and everywhere else.
//!
//! **Fail-open / fail-closed, decided per branch.** The guard consults NO
//! daemon, so it has no unreachable-daemon arm to fail open through — the
//! classification is filesystem-lexical and answers the same way whether or
//! not anything else on the machine is running
//! (`pm_guard_denies_main_checkout_destructive_git_with_the_daemon_unreachable`
//! pins that). The registry was considered and rejected as the authority:
//! `DaemonState::projects` is an in-memory map populated only by an explicit
//! `POST /projects` (or the Telegram `/setproj` command), never from session
//! history, so gating on "registered" would make the guard silently inert on
//! any machine where nobody had registered the path by hand — and the
//! persisted `Project` record carries a `repo_url`, no local path, so it
//! cannot answer the question at all. The remaining indeterminate arms all
//! resolve to ALLOW, and each one is a case where nothing was positively
//! identified: a directory with no `.git` ancestor is not a checkout; a
//! segment `shlex` cannot split (unbalanced quotes) yields no argv to
//! classify; a git verb that is not in the destructive table is not this
//! rule's business. The guard denies only on positive evidence of both halves.
//!
//! A `cd`/`-C` argument built from a shell variable, a surviving `~`, or a
//! `$(…)`/backtick substitution is not resolved, and the rules here refuse
//! rather than clear it ([`super::unresolved_target`]). The destructive rule
//! refuses it from any cwd (#8572), including an unquoted multi-word `$(…)`
//! before the subcommand. The commit rule refuses it only when the resolved
//! path walks up into a main checkout, so from a worktree cwd
//! `git -C $MAIN commit` is not refused. The HEAD-move rule does not ask at all.
//!
//! Residual bypasses, stated rather than hidden — each is the same shape the
//! sibling `evaluate_worktree_add_command` documents, because both reuse the
//! same lexical path resolution: a symlink into a checkout is not followed; a
//! destructive verb hidden inside a `$(…)` substitution is not scanned; a `..`
//! after an unresolved component (`$MAIN/..`) collapses it before the check
//! sees it. And the Guard 2/3 operator escape hatches
//! (`TRUSTY_MPM_DISABLE_HOOKS`, `TRUSTY_MPM_PM_UNRESTRICTED`) lift this rule
//! along with every other, which remains tracked as #3981.
//!
//! **The HEAD-moving verbs decide with the daemon, not alone (ADR-0048
//! decision 10, narrowed by ADR-0053).** [`main_checkout_head_move`] classifies
//! `git merge` and `git rebase` the same lexical way, but it returns the verb
//! and the directory
//! instead of a reason: the caller then asks the daemon's directory-keyed
//! `live_shared_tree_writers` who else is writing there and denies only when
//! the answer is non-empty. That second half is what makes the rule safe to
//! state by verb alone. A solo session updating its own checkout is ordinary
//! work and stays allowed; only a HEAD move under another live writer is
//! refused, and a daemon that cannot answer answers "nobody here", so this
//! branch fails open exactly like the #4480 guard it borrows the query from.
//! `git fetch` and `git pull` are outside the classifier entirely (ADR-0048
//! decision 9, ADR-0053) and never reach that query — see
//! [`starts_a_head_move`] for why `pull` left the table on 2026-08-17.
//!
//! **Residuals specific to the HEAD-move rule, stated rather than hidden
//! (#5769).** Four of them, each an ALLOW where a deny might be expected:
//!
//! * `--git-dir=` and `--work-tree=` are skipped when resolving the subcommand
//!   name ([`shell_lex::git_subcommand`]) but are never resolved into a target
//!   directory — only `cd` and `git -C` are. So
//!   `git --git-dir=/repo/.git --work-tree=/repo pull`, run from anywhere,
//!   resolves the running directory rather than `/repo` and is allowed when the
//!   running directory is not itself a shared checkout. Closing it means
//!   teaching [`git_verb_target_dir`] a third override, which the destructive
//!   and commit rules would inherit — a wider change than this rule.
//! * The deny quotes the daemon's delegation records, and a record can be wrong
//!   in the ALLOW direction as well as the deny one. A grant whose isolation
//!   POST failed (that path fails open) leaves a genuinely unisolated record for
//!   an agent that does have a worktree, and the deny then names it. The text
//!   attributes the claim for exactly this reason — see
//!   [`head_move_deny_reason`].
//! * The query is keyed by directory, and this rule asks two — the resolved
//!   target and its checkout root. A record stamped at some THIRD directory
//!   inside the same checkout (a hook that ran from another subdirectory) is
//!   still invisible.
//! * [`IN_PROGRESS_CONTROL_FLAGS`] is matched on the first tail token only, so a
//!   real in-progress control that git would accept in a later position — none
//!   exists today — would be denied rather than exempted. That is the fail
//!   direction this carve-out can afford; the reverse cost a whole `git merge`
//!   its deny.
//!
//! **The commit rule reads the index, and is the one branch here that spawns a
//! subprocess (ADR-0049).** Everything above is filesystem-lexical, and the
//! commit rule was too until the owner ruled that documents may be committed in
//! a main checkout. Which files a commit will land is a question only git can
//! answer, so [`evaluate_main_checkout_commit_command`] runs
//! [`trusty_mpm::core::staged_paths::staged_paths`] — but only after both
//! lexical halves already match, so ordinary Bash traffic never pays for it,
//! the same discipline the HEAD-move rule uses before its daemon call. A
//! documents-only staged set then takes the same live-writer query, because a
//! commit moves the shared HEAD exactly as far as a merge does. Every other
//! arm — a staged source file, an unreadable index, an empty index, and every
//! flag form that commits content the index does not hold — keeps the
//! unconditional deny ADR-0048 decision 4 shipped, so this rule can only turn a
//! deny into an allow and never the reverse.
//!
//! Test: `is_whole_tree_destructive_*`, `destructive_target_dir_*`,
//! `commit_target_dir_*`, `classify_staged_commit_*`,
//! `commit_flags_leave_the_index_authoritative_*`, `main_checkout_head_move_*`,
//! `starts_a_head_move_*` below;
//! `is_main_checkout_*` in `trusty_mpm::core::project_aliases`;
//! `pm_guard_denies_the_incident_commands_in_a_main_checkout` and siblings in
//! `tests/tm_hook_pm_guard.rs` run the stdin→decision→stdout path through the
//! real binary, including the subagent-marked payload.

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

use trusty_mpm::core::project_aliases::{is_main_checkout, main_checkout_root};
use trusty_mpm::core::staged_paths::staged_paths;

use super::shell_groups::{self, Step};
use super::{
    PathEnv, git_dash_c_override, operator_checkouts, resolve_target_path, unresolved_target,
};
use crate::commands::hook_rewrite::first_command_token;
use crate::commands::pm_guard::is_source_code_path;
use crate::commands::pm_guard_bash::shell_lex;
use crate::commands::pm_guard_write_boundary::write_lands_in_a_scratchpad_clone;

/// Deny a whole-tree-destructive git command aimed at a main checkout.
///
/// Why: the one entry point `pm_guard` calls. It is kept to the wrapper shape
/// the sibling worktree guard uses so the process-environment read
/// ([`PathEnv::from_process`]) happens in exactly one place and the policy
/// underneath stays testable without it.
/// What: `Some(reason)` — naming the verb, the directory, and the remedy —
/// for the first segment, in command order, whose destructive verb targets a
/// directory that [`is_main_checkout`] or that the guard cannot resolve;
/// `None` (ALLOW) otherwise. Every segment is judged (#8572).
///
/// A `-C` or `cd` path the guard could not fully expand still denies, but with
/// its OWN reason (#7100): `git -C $WT checkout -- <path>` resolved to
/// `<repo>/$WT`, whose nearest `.git` ancestor is the checkout root, so the
/// deny claimed a directory the agent never named was "a project's main
/// checkout". The verdict cannot flip to ALLOW — an empty `$WT` runs the
/// command in the checkout itself — so what changes is what the refusal says.
/// It denies from any cwd (#8572): from a worktree, `-C $MAIN` resolves to
/// `<worktree>/$MAIN`, which lexically names the worktree.
/// A `-C` path that lexically names a harness worktree
/// (`.claude/worktrees/…`, `.worktrees/…`) was and stays outside this rule:
/// [`is_main_checkout`] answers `false` for it, whether or not the directory
/// exists yet.
///
/// A disposable clone under the session scratchpad is exempt (#8339). The
/// #5769 residual still applies there: `git --git-dir=<main>/.git
/// --work-tree=<main> checkout -- .` and the `GIT_DIR=`/`GIT_WORK_TREE=`
/// prefixes, run from a scratchpad clone or any non-repo cwd, resolve to the
/// cwd rather than `<main>` and stay ALLOWED.
///
/// Grouping that does not parse (#9127) refuses, from any directory, any
/// command carrying a destructive git verb in a destructive form, as the
/// commit rule does for `git commit`.
/// Test: the two halves are covered separately (see the module doc);
/// `commit_or_reset_behind_coproc_must_deny_9127`;
/// `destructive_deny_names_an_unresolved_variable_rather_than_the_checkout`,
/// `destructive_deny_names_a_surviving_tilde_rather_than_the_checkout`,
/// `destructive_denies_an_unresolved_directory_from_a_worktree` (#8572),
/// `destructive_judges_every_segment` (#8572),
/// `destructive_allows_a_path_restoring_checkout_in_a_sibling_worktree`,
/// `destructive_allows_a_checkout_in_a_scratchpad_clone_only` (#8339); the
/// composition runs end to end in `tests/tm_hook_pm_guard.rs`.
pub(crate) fn evaluate_main_checkout_destructive_command(
    command: &str,
    cwd: &Path,
) -> Option<String> {
    evaluate_main_checkout_destructive_command_in(command, cwd, &PathEnv::from_process())
}

/// [`evaluate_main_checkout_destructive_command`] against an explicit
/// environment.
///
/// Why: see [`PathEnv`] — the `~` arm of the unresolved-target rule (#7234) is
/// reachable only with `$HOME` absent, and pinning that in a test by mutating
/// process-global env would leak into every sibling in the `tm` test binary.
/// Test: `destructive_deny_names_a_surviving_tilde_rather_than_the_checkout`.
fn evaluate_main_checkout_destructive_command_in(
    command: &str,
    cwd: &Path,
    env: &PathEnv,
) -> Option<String> {
    // #9127 critic MEDIUM-2: fail closed as the commit rule does — grouping
    // that does not parse cannot be placed.
    if let Some(reason) = shell_groups::unplaced_git_verb_reason(command, is_whole_tree_destructive)
    {
        return Some(reason);
    }
    // #8572: every destructive segment is judged, not only the first — from a
    // worktree, `git reset --hard && git -C $MAIN reset --hard` was cleared on
    // its first segment.
    for (verb, target, tail) in
        git_verb_targets_with_tail(command, cwd, env, is_whole_tree_destructive)
    {
        // #7100: an unexpanded variable in the path is not evidence about which
        // tree this lands in, so the refusal must not read as if it were.
        // #7234: a `~` left literal because `$HOME` was unset says the same thing.
        // #8572: checked before `is_main_checkout` — from a worktree cwd,
        // `-C $MAIN` resolves to `<worktree>/$MAIN`, which reads as a worktree.
        // The same ordering keeps a scratchpad cwd from clearing a literal `$WT`.
        if let Some(unresolved) = unresolved_target(&target) {
            return Some(unresolved_directory_deny_reason(
                DESTRUCTIVE_UNRESOLVED_HEADLINE,
                &verb,
                &unresolved.shown,
                &unresolved.token,
            ));
        }
        if !is_main_checkout(&target) {
            continue;
        }
        // #8339: a disposable clone under the session scratchpad is nobody's
        // shared tree — the #7778 proof, canonicalized.
        // Residual (#5769, module doc): `--git-dir=`/`--work-tree=` and a
        // `GIT_DIR=`/`GIT_WORK_TREE=` prefix are never resolved into the
        // target, so from a scratchpad clone (or any non-repo cwd) they still
        // reach a main checkout unrefused.
        if main_checkout_root(&target)
            .is_some_and(|root| write_lands_in_a_scratchpad_clone(&target, &root))
        {
            continue;
        }
        // #8524: owner ruling Option C — an allowlisted runtime checkout, a lone
        // `reset --keep`, and an empty content diff against its target.
        if operator_checkouts::reset_keep_is_exempt(command, &verb, &tail, &target) {
            continue;
        }
        return Some(deny_reason(&verb, &target));
    }
    None
}

/// What a `git commit` aimed at a main checkout is allowed to do (ADR-0049).
///
/// Why: the rule stopped being decidable from the verb alone when the owner
/// ruled that documents may be committed there, so the caller needs two
/// answers, not one. A source commit is refused outright; a docs-only commit is
/// permitted unless the daemon reports another live writer sharing the HEAD,
/// which only the caller can ask.
/// Test: `evaluate_main_checkout_commit_*`.
pub(crate) enum CommitVerdict {
    /// Refuse, with the reason already built.
    Deny(String),
    /// Documents and configuration only. Permit unless another live writer
    /// holds this HEAD; `dirs` are the query keys, checkout root first then the
    /// command's own directory — the same order and the same reason as the
    /// HEAD-move rule (#5769: `tm hook` stamps a record from its own process
    /// directory, and the root is the spelling a record most often carries).
    DocsOnly { root: PathBuf, dirs: [PathBuf; 2] },
}

/// Classify a `git commit` aimed at a main checkout (ADR-0048, amended by
/// ADR-0049).
///
/// Why: ADR-0044 makes the main checkout read-only apart from documents and
/// configuration, and a commit is the step that makes a write permanent on a
/// branch other sessions are standing on. The reported incident is exactly
/// this: commit `f1da7bce` landed on `fix/1646-drive-query-v2-migration`, a
/// branch belonging to a different workstream, because three sessions shared
/// one checkout and one of them committed on whichever branch HEAD happened to
/// point at. Blocking the source write alone would not have stopped it — the
/// files were already there.
///
/// ADR-0049 then found the other half of that rule stranded work: documents are
/// WRITABLE in a main checkout and a commit was denied unconditionally, so a
/// doc could be written where it could never be landed. The gate now reads what
/// is STAGED rather than the verb — the verb is `git commit` either way, and
/// only the content tells a safe commit from an unsafe one.
///
/// What: `None` (ALLOW, this rule's business does not arise) unless a
/// `git commit` segment's effective directory belongs to a main checkout. When
/// it does, the command must first be a LONE commit
/// ([`command_is_a_lone_commit`]) — one index read describes one commit and
/// only when nothing between the read and the commit can restage — and
/// [`classify_staged_commit`] then decides between [`CommitVerdict::Deny`] and
/// [`CommitVerdict::DocsOnly`]. The staged set is read only once both lexical
/// halves match, so ordinary Bash traffic never pays for the subprocess.
///
/// **The direction this can move a verdict is one-way, and the property is
/// stated per COMMAND rather than per arm (#5788 review).** Before ADR-0049
/// every `git commit` reaching this function was denied. After it, a command is
/// allowed only when it is a lone commit whose staged set is positively
/// evidenced as documents and configuration; every other command still denies.
/// The first cut stated this per-arm — true of [`classify_staged_commit`] in
/// isolation, false of the composed rule, and the gap between the two was the
/// `git commit -m docs && git commit -a -m src` exploit. Read this way it holds
/// for the whole entry point, which is what keeps it off ordinary work without
/// a #5356-shaped false-deny risk.
///
/// Scope, stated because the near neighbours are tempting: `git checkout
/// <branch>` and `git switch <branch>` are NOT covered here even though
/// switching a branch under another session is part of the same incident.
/// Their safe and unsafe forms differ by argument rather than by verb, so they
/// have their own argument-aware rule in [`super::head_switch`] (#8572): an
/// AGENT's switch is refused only when the main checkout holds uncommitted
/// work, which keeps a clean checkout clear of the #5356 false deny.
/// `merge` and `rebase` left that family in ADR-0048 decision 10 and
/// are handled by [`main_checkout_head_move`], which needs no argument
/// analysis: neither has a form that leaves HEAD alone. `pull` was there too
/// until ADR-0053 permitted it.
/// `git add` is not covered by any of them and deliberately so: it writes the
/// index and moves no ref, so it creates none of the shared-HEAD hazard these
/// rules exist for (ADR-0049 decision 4). It is still refused when CHAINED to a
/// commit, which is a statement about the index read above, not about `git add`.
/// Grouping (#9127): a commit inside `( … )`, `{ …; }` or behind a reserved
/// word (`coproc` included) is judged on its own command, and grouping that
/// does not parse — or a `case`, function definition or coproc the walker
/// cannot place — refuses any command carrying `git commit`.
/// Test: `commit_target_dir_*`, `evaluate_main_checkout_commit_*`,
/// `commit_deny_names_a_surviving_tilde_rather_than_the_checkout`,
/// `command_is_a_lone_commit_*`, `commit_allows_a_scratchpad_clone_only` (#8485),
/// `commit_in_a_subshell_or_brace_group_must_deny`,
/// `commit_in_an_unbalanced_group_is_refused`,
/// `grouped_commits_outside_a_main_checkout_and_grouped_reads_stay_allowed`,
/// `a_cd_inside_eval_persists_9127`, `commit_or_reset_behind_coproc_must_deny_9127`,
/// `commit_in_a_shape_the_walker_cannot_place_is_refused_9127`.
pub(crate) fn evaluate_main_checkout_commit_command(
    command: &str,
    cwd: &Path,
) -> Option<CommitVerdict> {
    evaluate_main_checkout_commit_command_in(command, cwd, &PathEnv::from_process())
}

/// [`evaluate_main_checkout_commit_command`] against an explicit environment.
///
/// Why: as [`evaluate_main_checkout_destructive_command_in`] — the `~` arm of
/// the unresolved-target rule (#7234) needs `$HOME` absent, and this is the
/// seam that pins it without touching process-global env.
/// Test: `commit_deny_names_a_surviving_tilde_rather_than_the_checkout`.
fn evaluate_main_checkout_commit_command_in(
    command: &str,
    cwd: &Path,
    env: &PathEnv,
) -> Option<CommitVerdict> {
    // #9127: fail closed — grouping that does not parse cannot be placed.
    if !shell_groups::grouped_steps(command).parsed && shell_groups::mentions_git_commit(command) {
        return Some(CommitVerdict::Deny(
            shell_groups::UNPARSED_GROUP_COMMIT_REASON.to_string(),
        ));
    }
    // `main_checkout_root` rather than `is_main_checkout` for the reason #5769
    // gave the HEAD-move rule: `cd crates/foo && git commit` resolves a
    // subdirectory that shares the checkout's HEAD, and the writer query has to
    // be keyed on a directory a delegation record can actually carry.
    // #8485 review: the first commit aimed at a main checkout, not the first
    // commit segment — `git -C <worktree> commit && git -C <main> commit -a`
    // returned early on the worktree and never reached the lone-commit check.
    let (verb, target, tail, root) =
        git_verb_targets_with_tail(command, cwd, env, |verb, _| verb == "commit")
            .into_iter()
            .find_map(|(verb, target, tail)| {
                main_checkout_root(&target).map(|root| (verb, target, tail, root))
            })?;
    // #7234: that upward walk is exactly what an unresolved component subverts.
    // `git -C ~/scratch/repo commit` with `$HOME` unset leaves `~` literal, the
    // path is joined onto the launch directory, and the walk finds the LAUNCH
    // directory's `.git` — so the refusal named a checkout the command never
    // addressed. Asked before the index is read, because a target this cannot
    // place is refused whatever is staged.
    if let Some(unresolved) = unresolved_target(&target) {
        return Some(CommitVerdict::Deny(unresolved_directory_deny_reason(
            COMMIT_UNRESOLVED_HEADLINE,
            &verb,
            &unresolved.shown,
            &unresolved.token,
        )));
    }
    // #5788 review, CRITICAL 1: one index read authorises at most one commit,
    // and only when nothing between the read and that commit can change the
    // index. Asked before the staged set is even read, because a composition
    // this cannot vouch for is refused whatever is staged.
    if !command_is_a_lone_commit(command) {
        return Some(CommitVerdict::Deny(composed_commit_deny_reason(&root)));
    }
    // #8485: a disposable clone under the session scratchpad shares no HEAD with
    // anyone — the same canonicalized proof the destructive rule uses (#8339).
    // Asked only after the lone-commit check, and of EVERY commit target: a
    // first-segment-only answer let `git -C <pad>/c commit; git -C <main>
    // commit -a` through (the #5788 CRITICAL-1 shape).
    if every_commit_lands_in_a_scratchpad_clone(command, cwd, env) {
        return None;
    }
    Some(classify_staged_commit(
        &tail,
        staged_paths(&target),
        &target,
        root,
        operator_checkouts::is_documents_repo,
    ))
}

/// Whether every `git commit` target in `command` is a scratchpad clone (#8485).
///
/// What: `false` when no commit target is found; otherwise `true` only when
/// each target's checkout root resolves and
/// [`write_lands_in_a_scratchpad_clone`] accepts it.
/// Test: `commit_allows_a_scratchpad_clone_only`,
/// `commit_refuses_a_scratchpad_clone_chained_to_a_main_checkout_commit`.
fn every_commit_lands_in_a_scratchpad_clone(command: &str, cwd: &Path, env: &PathEnv) -> bool {
    let targets = git_verb_targets_with_tail(command, cwd, env, |verb, _| verb == "commit");
    !targets.is_empty()
        && targets.iter().all(|(_, target, _)| {
            main_checkout_root(target)
                .is_some_and(|root| write_lands_in_a_scratchpad_clone(target, &root))
        })
}

/// Whether `command` is a single `git commit` and nothing that could restage.
///
/// Why (#5788 review, CRITICAL 1): the staged set is read once, at hook time,
/// and describes the index at that instant. A composition breaks that in two
/// ways, both demonstrated live against the first cut of this rule.
/// `git commit -m docs && git add -A && git commit -a -m src` was ALLOWED — the
/// walker returned on the FIRST commit segment, so the docs-only staged set
/// licensed a source commit two segments later. And `git add -A &&
/// git commit -m docs` has one commit segment but restages before it runs, so
/// the read describes an index the commit never sees. Both were denied before
/// ADR-0049 and must stay denied.
///
/// The sibling destructive rule judges every segment (#8572), which suffices
/// there because each verdict depends only on that segment's verb and
/// directory. This rule cannot fix it the same way: judging later segments
/// still would not tell it what the index holds by the time they run. The only
/// defensible answer is to refuse the composition.
///
/// What: `true` when every non-empty segment is either a `cd` — which moves no
/// files and touches no index — or THE one `git commit`. Any second commit, any
/// other command, and any segment `shlex` cannot split all return `false`,
/// which the caller turns into the pre-ADR-0049 deny. The remedy is one extra
/// tool call, and [`composed_commit_deny_reason`] names it.
/// Test: `command_is_a_lone_commit_accepts_a_commit_and_cd`,
/// `command_is_a_lone_commit_rejects_a_second_commit`,
/// `command_is_a_lone_commit_rejects_anything_that_can_restage`.
fn command_is_a_lone_commit(command: &str) -> bool {
    let mut commits = 0;
    // #9127: the same peeled segments the walker reads.
    for step in shell_groups::grouped_steps(command).steps {
        let Step::Command(segment) = step else {
            continue;
        };
        let trimmed = segment.trim();
        if trimmed.is_empty() {
            continue;
        }
        if first_command_token(trimmed).as_deref() == Some("cd") {
            continue;
        }
        if shell_lex::git_subcommand(trimmed).as_deref() != Some("commit") {
            return false;
        }
        commits += 1;
    }
    commits == 1
}

/// The verdict for a commit already known to be aimed at a main checkout.
///
/// Why: split from [`evaluate_main_checkout_commit_command`] so the whole
/// policy is a pure function of the argv tail and the staged set. Every arm
/// below is a failure arm except one, and a test that had to build a real
/// repository to reach each of them would exercise git rather than the policy.
/// What: [`CommitVerdict::DocsOnly`] only when BOTH halves are positively
/// evidenced — the flags leave the index authoritative
/// ([`commit_flags_leave_the_index_authoritative`]) AND the staged set is
/// non-empty and contains no source file. Everything else is a
/// [`CommitVerdict::Deny`], which is the pre-ADR-0049 behaviour:
///
/// * a staged set containing source, mixed or not, names the offending files;
/// * `None` — git could not be asked — is UNKNOWN, not empty;
/// * an empty staged set is not evidence of a docs commit, and `git commit`
///   with nothing staged is either an error or one of the forms below;
/// * a flag that commits content the index does not hold (`-a`, `--amend`,
///   `--include`, `--only`, a bare pathspec) makes the staged set a lie about
///   what will land, so the staged set cannot license it.
///
/// Test: `classify_staged_commit_permits_documents_and_configuration`,
/// `classify_staged_commit_denies_source_and_names_it`,
/// `classify_staged_commit_denies_a_mixed_set_and_names_only_the_source`,
/// `classify_staged_commit_denies_an_unreadable_or_empty_index`,
/// `classify_staged_commit_denies_the_forms_the_index_does_not_describe`,
/// `classify_staged_commit_counts_source_as_documents_in_a_documents_repo` (#7905).
fn classify_staged_commit(
    tail: &[String],
    staged: Option<Vec<String>>,
    target: &Path,
    root: PathBuf,
    documents_repo: impl FnOnce(&Path) -> bool,
) -> CommitVerdict {
    if !commit_flags_leave_the_index_authoritative(tail) {
        return CommitVerdict::Deny(commit_deny_reason(&root));
    }
    let Some(staged) = staged.filter(|s| !s.is_empty()) else {
        return CommitVerdict::Deny(commit_deny_reason(&root));
    };
    let source: Vec<&str> = staged
        .iter()
        .map(String::as_str)
        .filter(|p| is_source_code_path(p))
        .collect();
    // #7905: an operator-listed documents repo counts every path as a document.
    if source.is_empty() || documents_repo(&root) {
        CommitVerdict::DocsOnly {
            dirs: [root.clone(), target.to_path_buf()],
            root,
        }
    } else {
        CommitVerdict::Deny(staged_source_deny_reason(&root, &source))
    }
}

/// `git commit` flags under which the index IS what the commit will contain.
///
/// Why: the docs-only carve-out rests entirely on the staged set describing the
/// commit, and four flag families break that. `-a`/`--all` stages every tracked
/// modification at commit time; `-i`/`--include` adds paths to the index first;
/// `-o`/`--only` commits the named paths from the working tree instead of the
/// index; `--amend` reuses the previous commit's tree, whose contents this
/// process never looked at. A bare pathspec implies `--only`. Under any of
/// them the staged set answers a different question than the one being asked.
/// What: an ALLOWLIST, walked left to right, so an unrecognised token — a
/// pathspec, a short cluster, a flag added by a future git — is `false`. That
/// direction is safe by construction here: `false` returns the pre-ADR-0049
/// deny, which is what the caller did for every commit before this rule
/// existed. A denylist would have the opposite bias and would license a commit
/// on a flag nobody had heard of.
///
/// `-S`/`--gpg-sign` sit in the no-value list because git accepts their
/// optional key id only glued (`-S<keyid>`, `--gpg-sign=<keyid>`), never as a
/// following token.
/// Test: `commit_flags_leave_the_index_authoritative_accepts_message_forms`,
/// `commit_flags_leave_the_index_authoritative_rejects_content_flags`,
/// `commit_flags_leave_the_index_authoritative_rejects_a_pathspec`.
fn commit_flags_leave_the_index_authoritative(tail: &[String]) -> bool {
    const NO_VALUE: &[&str] = &[
        "-s",
        "--signoff",
        "--no-signoff",
        "-n",
        "--no-verify",
        "--verify",
        "-q",
        "--quiet",
        "-v",
        "--verbose",
        "-e",
        "--edit",
        "--no-edit",
        "--allow-empty",
        "--allow-empty-message",
        "--status",
        "--no-status",
        "--no-post-rewrite",
        "-S",
        "--gpg-sign",
        "--no-gpg-sign",
    ];
    const WITH_VALUE: &[&str] = &[
        "-m",
        "--message",
        "-F",
        "--file",
        "--author",
        "--date",
        "--cleanup",
        "--trailer",
    ];

    let mut expecting_value = false;
    for token in tail {
        if expecting_value {
            expecting_value = false;
            continue;
        }
        // `--flag=value` and `-S<keyid>` carry their value glued on.
        let name = match token.split_once('=') {
            Some((head, _)) if head.starts_with("--") => head,
            _ if token.starts_with("-S") => "-S",
            _ => token.as_str(),
        };
        if NO_VALUE.contains(&name) {
            continue;
        }
        if WITH_VALUE.contains(&name) {
            expecting_value = name == token.as_str();
            continue;
        }
        return false;
    }
    true
}

/// The verb and directory of a HEAD-moving git command aimed at a main
/// checkout (ADR-0048 decision 10).
///
/// Why: `merge` and `rebase` move HEAD and write the working tree of
/// the directory they run in. In a worktree that HEAD belongs to the one
/// session that owns it, so the move races nothing. In a main checkout the HEAD
/// is shared, and moving it changes the ground another session's uncommitted
/// work is sitting on — with no error at any step, the same silence the commit
/// rule above exists for.
/// What: `Some(Ok((verb, directory, checkout_root)))` when a segment
/// [`starts_a_head_move`] and the directory it would act on belongs to a main
/// checkout. It returns those rather than a reason because the deny is not
/// decided here: the caller asks the daemon who else is live and denies only on
/// a positive answer. See [`head_move_deny_reason`]. The one deny decided here
/// is `Some(Err(reason))`: a command the shared walker cannot place that names
/// such a verb, refused without a daemon query (#9127).
///
/// **Why two directories and not one (#5769).** `directory` is what the command
/// resolves to through `cd` and `git -C`; `checkout_root` is the main checkout
/// that directory sits in. They differ whenever the command runs from a
/// subdirectory, and the delegation records the caller queries are stamped from
/// `tm hook`'s own process directory, which may be either. Both name one HEAD,
/// so the caller asks both — and the test that the directory belongs to a
/// checkout is now [`main_checkout_root`], not [`is_main_checkout`], which
/// closes a second hole in the same place: `cd crates/foo && git merge` resolved
/// a subdirectory, `is_main_checkout` on it was still true, and the query then
/// keyed a directory no record could match.
/// Test: `main_checkout_head_move_*`, and end to end in
/// `tests/tm_hook_pm_guard.rs`.
pub(crate) fn main_checkout_head_move(
    command: &str,
    cwd: &Path,
) -> Option<Result<(String, PathBuf, PathBuf), String>> {
    // #9127 critic r4 HIGH: an unplaced `eval "cd <wt>"` must not place it.
    if let Some(reason) = shell_groups::unplaced_git_verb_reason(command, starts_a_head_move) {
        return Some(Err(reason));
    }
    let (verb, target) =
        git_verb_target_dir(command, cwd, &PathEnv::from_process(), starts_a_head_move)?;
    let root = main_checkout_root(&target)?;
    Some(Ok((verb, target, root)))
}

/// Flags that operate on an operation already in progress rather than start a
/// new one.
///
/// Why: see [`starts_a_head_move`] — a deny on these would strand a session
/// mid-rebase with no way out, which is the retried-differently-and-worse
/// failure ADR-0048 decision 6 exists to prevent.
const IN_PROGRESS_CONTROL_FLAGS: &[&str] = &[
    "--abort",
    "--quit",
    "--continue",
    "--skip",
    "--edit-todo",
    "--show-current-patch",
];

/// Whether a git subcommand, given its argv tail, would START moving HEAD.
///
/// Why: this is the second false-positive boundary in this module, and the
/// reason ADR-0048 originally left these verbs uncovered is that a loose rule
/// here costs false denies on ordinary work (#5356). What makes a verb-only
/// rule safe for `merge` and `rebase` is that neither has a form that leaves
/// HEAD and the working tree alone: both rewrite the current branch, and a
/// merge can stop with conflict markers in a tree another session is standing
/// in. There is no pathspec-vs-ref ambiguity to resolve, which is what keeps
/// `checkout` and `switch` out of this rule and in the doc comment above.
/// Neighbouring verbs are separate subcommand names (`merge-base`,
/// `merge-tree`, `rebase--helper`) and never match.
///
/// **`pull` left this table in ADR-0053 (2026-08-17).** It was here from
/// ADR-0048 decision 10 on the same has-no-safe-form ground, which is true of
/// it and not decisive: a pull that fast-forwards advances the branch to an
/// already-published commit and git refuses to run it when the working tree
/// would be disturbed. Owner ruling, verbatim: "fetch and pull operations are
/// permitted. Only direct code editing is not." So a pull never reaches the
/// caller's live-writer query and is allowed whoever else is in the tree.
/// `fetch` was never classified (ADR-0048 decision 9). The residual is stated
/// in ADR-0053's Consequences and accepted: a bare `git pull` can still merge,
/// and this rule reads the verb rather than the arguments, so it permits that
/// form too. The write boundary is untouched — this is about moving HEAD, never
/// about editing.
///
/// The one carve-out is [`IN_PROGRESS_CONTROL_FLAGS`]. Those resolve a state
/// that already exists — the operation started before this call — and denying
/// them would leave the shared checkout parked mid-rebase, which is worse for
/// every other session in it than letting the operation finish or unwind. The
/// deny that matters is the one that stops the move from starting.
///
/// The carve-out is matched POSITIONALLY, on the first tail token only (#5769).
/// Scanning the whole tail exempted any command carrying one of those strings
/// anywhere in it, so `git merge -m "--continue" origin/main` — a real merge,
/// with the flag as a commit message — passed straight through. Git itself
/// accepts these only as the first argument, so the narrower match is also the
/// accurate one.
/// Test: `starts_a_head_move_still_covers_merge_and_rebase`,
/// `starts_a_head_move_permits_pull_and_fetch`,
/// `starts_a_head_move_allows_in_progress_control`,
/// `starts_a_head_move_matches_in_progress_control_positionally`,
/// `starts_a_head_move_ignores_everything_else`.
pub(super) fn starts_a_head_move(subcommand: &str, tail: &[String]) -> bool {
    // ADR-0053: `pull` was in this table until 2026-08-17.
    matches!(subcommand, "merge" | "rebase")
        && !tail
            .first()
            .is_some_and(|t| IN_PROGRESS_CONTROL_FLAGS.contains(&t.as_str()))
}

/// Build the deny message for a blocked HEAD move.
///
/// Why: as [`deny_reason`] and [`commit_deny_reason`] — ADR-0048 decision 6
/// requires every deny to name what to do instead. This one has two remedies to
/// offer rather than one, and the cheap one comes first: most calls that reach
/// here want an updated checkout, and `git fetch` or `git pull` gives exactly
/// that (ADR-0048 decision 9, ADR-0053), so a reader who only needed the
/// checkout refreshed is unblocked without provisioning anything.
/// What: names the verb, the directory, the sibling agents the daemon reports,
/// `git fetch` and `git pull` as the update remedies, a worktree as the
/// merge-or-rebase remedy, and the forms this rule never blocks.
///
/// **It attributes, rather than asserts (#5769).** The text used to state as
/// fact that another agent "is already writing there without a worktree of its
/// own". This process cannot know that — it knows only what the daemon's
/// delegation records say, and a record can outlive its agent (nothing closes
/// one whose `SubagentStop` never arrives, for `RUNNING_STALE_AFTER_SECS`) or
/// misdescribe it (a granted dispatch whose isolation POST failed is recorded
/// unisolated, fail-open). Saying whose claim it is keeps the deny honest and
/// tells the reader where to look when it is wrong.
/// Test: `head_move_deny_reason_names_the_verb_the_path_and_both_remedies`,
/// `head_move_deny_reason_attributes_the_claim_to_the_daemon`.
pub(crate) fn head_move_deny_reason(verb: &str, target: &Path, live: &[String]) -> String {
    let mut names: Vec<&str> = live.iter().map(String::as_str).collect();
    names.sort_unstable();
    names.dedup();
    format!(
        "HEAD-moving git command denied in a shared main checkout (ADR-0048): `git {verb}` moves \
         HEAD and writes the working tree of {}, and the daemon's delegation records name {} as \
         running there with no worktree of its own, dispatched by a DIFFERENT session standing in \
         the same directory (#6797: your own session's agents are excluded from this answer, so \
         this is not you). Moving HEAD under a live writer changes the branch its \
         uncommitted work sits on, and git reports no error when it happens. If you \
         believe that record is stale — the agent finished without its stop signal reaching the \
         daemon — report it to the PM rather than retrying this command. If you only need this \
         checkout updated, run `git fetch` or `git pull` instead: both are permitted here \
         whoever else is in the tree (ADR-0053), and `git fetch` writes only \
         `refs/remotes/origin/*` without touching HEAD or the working tree — then branch and \
         diff against `origin/main` rather than local `main`, which only a pull moves. If you \
         need the merge \
         or rebase itself, do it in a worktree: ask the PM to re-dispatch you with \
         `isolation: \"worktree\"`, or `git worktree add .claude/worktrees/<name>`. Read-only git \
         (`status`, `log`, `diff`), `git fetch`, `git pull`, `git rebase --abort`/`--continue`, \
         `git merge --abort`, and everything under `.claude/worktrees/**` are never blocked by \
         this rule.",
        target.display(),
        names.join(", ")
    )
}

/// Build the deny message for a blocked commit whose content this rule could
/// not read as documents.
///
/// Why: as [`deny_reason`] — a bare refusal is retried differently and worse.
/// This one has to be clear that the work is not lost and does not need
/// redoing, only moved, because the reflex on a blocked commit is to reach for
/// `git stash` or a second `-m` attempt. Since ADR-0049 it also has to name the
/// docs-only carve-out, because the reader who lands here after editing one
/// `.md` file has usually hit the `-a`/`--amend`/nothing-staged arm and the fix
/// is one `git add`, not a worktree.
/// Test: `commit_deny_reason_names_the_path_and_the_remedy`.
fn commit_deny_reason(target: &Path) -> String {
    format!(
        "Commit denied in a main checkout (ADR-0044): {} is a project's main checkout, which is \
         read-only apart from documents and configuration, and other sessions are standing on \
         this same git HEAD. A commit here lands on whichever branch HEAD currently points at — \
         the reported failure is a commit landing on another workstream's branch and the branch \
         it belonged to left empty, with no error at any step. A DOCUMENTS-ONLY commit is \
         permitted here (ADR-0049), but only when the staged set says so: stage the documents \
         explicitly (`git add -- <paths>`) and commit with a plain `git commit -m …`. This call \
         was refused because the staged set does not describe what it would commit — nothing is \
         staged, the index could not be read, or the command carries `-a`, `--amend`, \
         `--include`, `--only`, or a pathspec, each of which commits content the index does not \
         hold. For source changes, commit from a worktree instead: ask the PM to re-dispatch you \
         with `isolation: \"worktree\"`, or move the work with \
         `git worktree add .claude/worktrees/<name>` and commit there. Nothing is lost — the \
         changes are still in the tree. Read-only git (`status`, `log`, `diff`), `git add`, and \
         everything under `.claude/worktrees/**` are never blocked by this rule.",
        target.display()
    )
}

/// Build the deny message for a commit this rule cannot read the index for,
/// because the command composes it with something else.
///
/// Why (#5788 review, CRITICAL 1): the reader has staged documents and is being
/// refused anyway, so the text has to name the composition as the cause — not
/// the content — or the retry is to unstage something that was never the
/// problem. The remedy is one extra tool call and the message says exactly
/// which one.
/// Test: `composed_commit_deny_reason_names_the_composition_and_the_remedy`.
fn composed_commit_deny_reason(target: &Path) -> String {
    format!(
        "Composed commit denied in a main checkout (ADR-0049): {} is a project's main checkout, \
         where a documents-only commit is permitted — but only when the guard can see what the \
         commit will contain. It reads the index once, before this command runs, and that reading \
         describes exactly one commit with nothing in between: a second `git commit`, a \
         `git add`, or any other command in the same call can change the index after the reading \
         and before the commit, so the reading would be describing a commit that never happens. \
         Split the call: stage in one Bash call (`git add -- <paths>`), then run \
         `git commit -m …` as its own call with nothing chained to it. `cd` is the one exception \
         and may be chained, since it touches no index. Nothing is lost — the changes are still \
         in the tree, and `git add` is never blocked by this rule.",
        target.display()
    )
}

/// Build the deny message for a commit whose staged set contains source.
///
/// Why: ADR-0049 decision 2 — a mixed staged set fails safe, and a refusal that
/// does not say WHICH file made it unsafe leaves the reader unstaging by
/// guesswork. Naming them turns the remedy into a mechanical
/// `git restore --staged` of a listed path.
/// What: names the checkout, every staged source path, and the two ways
/// forward — unstage the source and commit the documents here, or move the
/// whole change to a worktree.
/// Test: `staged_source_deny_reason_names_every_source_file`.
fn staged_source_deny_reason(target: &Path, source: &[&str]) -> String {
    let mut names: Vec<&str> = source.to_vec();
    names.sort_unstable();
    names.dedup();
    format!(
        "Source commit denied in a main checkout (ADR-0044, amended by ADR-0049): {} is a \
         project's main checkout, which is read-only apart from documents and configuration, and \
         other sessions are standing on this same git HEAD. Documents may be committed here; \
         these staged paths are source and may not be: {}. A mixed staged set is refused as a \
         whole rather than split, because a commit is one object and half of it cannot be sent \
         elsewhere. Two ways forward. To land the documents from here, unstage the source \
         (`git restore --staged -- <paths above>`) and commit again. To land the source, do it \
         in a worktree: ask the PM to re-dispatch you with `isolation: \"worktree\"`, or \
         `git worktree add .claude/worktrees/<name>` and commit there. Nothing is lost — the \
         changes are still in the tree, and `git add` is never blocked by this rule.",
        target.display(),
        names.join(", ")
    )
}

/// Build the deny message for a documents-only commit refused because another
/// live writer shares the HEAD.
///
/// Why: ADR-0049 decision 3 gives a docs commit the same concurrency test
/// ADR-0048 decision 10 gives `merge`/`rebase`, because the hazard is
/// the same one — a commit MOVES HEAD, and the branch it moves is whichever one
/// the other session's uncommitted work is sitting on. The reader has to be
/// told that the content was fine and the timing was not, or the obvious retry
/// is to unstage the document that was never the problem.
/// What: names the checkout, the writers the daemon reports, and the remedy.
/// It attributes the claim to the daemon's records for the reason
/// [`head_move_deny_reason`] gives: a record can outlive its agent.
/// Test: `docs_commit_deny_reason_names_the_writer_and_attributes_the_claim`.
pub(crate) fn docs_commit_deny_reason(target: &Path, live: &[String]) -> String {
    let mut names: Vec<&str> = live.iter().map(String::as_str).collect();
    names.sort_unstable();
    names.dedup();
    format!(
        "Documents-only commit denied in a SHARED main checkout (ADR-0049): the staged set is \
         documents and configuration, which may be committed in {} — but a commit moves HEAD, \
         and the daemon's delegation records name {} as running there with no worktree of its \
         own, dispatched by a DIFFERENT session standing in the same directory (#6797: your own \
         session's agents are excluded from this answer, so this is not one of yours). Moving \
         HEAD under a live writer changes the branch its uncommitted work sits on, and git \
         reports no error when it happens. The content is not the problem here and unstaging it \
         will not help. Wait for that agent to finish and commit then, or commit from a worktree: \
         ask the PM to re-dispatch you with `isolation: \"worktree\"`, or \
         `git worktree add .claude/worktrees/<name>`. If you believe that record is stale — the \
         agent finished without its stop signal reaching the daemon — report it to the PM rather \
         than retrying this command. Nothing is lost; the staged changes are still in the tree.",
        target.display(),
        names.join(", ")
    )
}

/// Build the deny message.
///
/// Why: a bare refusal leaves the model guessing and it retries the identical
/// call. The text names what was blocked, WHERE (the reader's next question is
/// always "which tree?"), why the directory is special, and the one remedy
/// that always works — do the work in a worktree. Built per call rather than
/// kept as a constant because naming the actual directory is most of its value.
/// Test: `deny_reason_names_the_verb_the_path_and_the_remedy`.
fn deny_reason(verb: &str, target: &Path) -> String {
    format!(
        "Destructive git command denied in a main checkout (ADR-0037): `git {verb}` would \
         overwrite or delete uncommitted work in {}, which is a project's main checkout rather \
         than a worktree. Another session may be standing in that directory, and what this \
         removes is not in git — it cannot be recovered. ADR-0037's rule is that a main \
         checkout's files are not EDITED or destroyed; UPDATING it is expected, and `git fetch` \
         is never blocked. Do this work in a worktree instead: \
         `git worktree add .claude/worktrees/<name>`, or ask the PM to re-dispatch you with \
         `isolation: \"worktree\"`. Read-only git (`status`, `log`, `diff`), branch creation \
         (`checkout -b`), and a plain `git reset` are never blocked by this rule.",
        target.display()
    )
}

/// How the destructive rule opens its unresolved-target refusal.
const DESTRUCTIVE_UNRESOLVED_HEADLINE: &str =
    "Destructive git command denied because its target directory is unresolvable (ADR-0037)";

/// How the commit rule opens the same refusal (#7234).
const COMMIT_UNRESOLVED_HEADLINE: &str =
    "Commit denied because its target directory is unresolvable (ADR-0044, amended by ADR-0049)";

/// Build the deny message for a target directory the guard could not resolve
/// (#7100, extended to a surviving `~` by #7234).
///
/// Why: [`deny_reason`] and [`commit_deny_reason`] both assert the directory IS
/// a main checkout, and that assertion is what a `version-control` agent acted
/// on when it abandoned `git -C "$WT" checkout -- <file>` and hand-edited the
/// file instead. The guard reached the checkout root only by walking upwards
/// from a path it could not place, so the honest statement is that it does not
/// know where the target points — and the remedy is a different one from "do
/// this work in a worktree", because the agent already was. `headline` is a
/// parameter because both rules refuse for the same reason and differ only in
/// which ADR they enforce; a second copy of the body would drift on what the
/// guard actually expands.
/// What: the refusal, naming the verb, the path [`super::unresolved_target`]
/// chose to quote, the expansion that failed, and the two forms that work.
/// Test: `unresolved_directory_deny_reason_names_the_variable_and_the_remedy`.
fn unresolved_directory_deny_reason(
    headline: &str,
    verb: &str,
    target: &Path,
    token: &str,
) -> String {
    format!(
        "{headline}: `git {verb}` names {}, which still carries the unresolved shell expansion \
         `{token}`. The guard expands `$TMPDIR`, `$TMP`, `$HOME` and `$PWD`, and a leading `~` \
         only when `$HOME` is set, so it cannot tell whether this lands in a sibling worktree or \
         in the main checkout it walked up to — and it will not clear a directory it cannot name. \
         Spell the directory out (`git -C /abs/path/.claude/worktrees/<name> {verb} …`) or `cd` \
         into the worktree first. A `-C` path that names a harness worktree \
         (`.claude/worktrees/`, `.worktrees/`) is not restricted by this rule, so the same command \
         with the path written out is allowed.",
        target.display()
    )
}

/// The directory the first git segment matching `matches` would act on, with
/// that segment's verb.
///
/// Why: split from the filesystem classification so the whole text-and-path
/// half — which is where a false positive would come from — is a pure function
/// with no filesystem or environment of its own. The classifier is a parameter
/// rather than hardcoded so the destructive-verb rule and the commit rule share
/// one walker: `cd` tracking, `git -C` resolution, and segment splitting are
/// the parts a second copy would drift on, and they are identical for both.
/// What: walks the composition segments ([`shell_groups::grouped_steps`], so
/// `true && git reset --hard` is classified on its second segment and
/// `(git reset --hard)` on its command, #9127), tracks the effective working
/// directory across `cd` segments and a leading `git -C` — restoring it when a
/// subshell, a coproc or a child-process wrapper's string ends, but not after
/// an `eval`, which runs in the current shell — and returns the first segment
/// whose `(verb, argv-tail)` satisfies `matches`.
/// `None` when no segment qualifies — including a segment `shlex` cannot split,
/// which yields no argv to classify.
/// Test: `destructive_target_dir_*`, `commit_target_dir_*`.
fn git_verb_target_dir(
    command: &str,
    cwd: &Path,
    env: &PathEnv,
    matches: impl Fn(&str, &[String]) -> bool,
) -> Option<(String, PathBuf)> {
    git_verb_target_dir_with_tail(command, cwd, env, matches).map(|(verb, dir, _)| (verb, dir))
}

/// [`git_verb_target_dir`], also handing back the matched segment's argv tail.
///
/// Why: the commit rule decides on the flags as well as the directory
/// (ADR-0049 — `--amend` and `-a` commit content the index does not describe),
/// and the tail was already computed here to run `matches`. Returning it beats
/// a second lexer in the commit rule, which is the copy that would drift on
/// `cd` tracking and `git -C` resolution.
/// Test: as [`git_verb_target_dir`], plus
/// `commit_target_dir_hands_back_the_argv_tail`.
// `pub(super)` since ADR-0057: the worktree-removal rule resolves the same
// `cd`/`git -C` chain to find which directory a `git worktree remove` would
// delete, and a second walker there would drift on exactly the two things this
// one gets right.
pub(super) fn git_verb_target_dir_with_tail(
    command: &str,
    cwd: &Path,
    env: &PathEnv,
    matches: impl Fn(&str, &[String]) -> bool,
) -> Option<(String, PathBuf, Vec<String>)> {
    git_verb_targets_with_tail(command, cwd, env, matches)
        .into_iter()
        .next()
}

/// Every segment's match, in order — one per segment (#8572).
///
/// Why: the HEAD-switch rule must judge `git -C <wt> checkout a && git
/// checkout b` on its SECOND segment too; the first match alone misses it.
/// Test: `head_switch_judges_every_segment`.
pub(super) fn git_verb_targets_with_tail(
    command: &str,
    cwd: &Path,
    env: &PathEnv,
    matches: impl Fn(&str, &[String]) -> bool,
) -> Vec<(String, PathBuf, Vec<String>)> {
    let mut found = Vec::new();
    let mut effective_cwd = cwd.to_path_buf();
    // #9127: grouping peeled off, and a subshell's `cd` scoped to it.
    let mut outer_cwds = Vec::new();
    for step in shell_groups::grouped_steps(command).steps {
        let segment = match step {
            Step::Enter => {
                outer_cwds.push(effective_cwd.clone());
                continue;
            }
            Step::Leave => {
                effective_cwd = outer_cwds.pop().unwrap_or(effective_cwd);
                continue;
            }
            Step::Command(segment) => segment,
        };
        let trimmed = segment.trim();
        if trimmed.is_empty() {
            continue;
        }
        if first_command_token(trimmed).as_deref() == Some("cd") {
            if let Some(argv) = shlex::split(trimmed)
                && let Some(dest) = argv.get(1)
            {
                effective_cwd = resolve_target_path(dest, &effective_cwd, env);
            }
            continue;
        }
        // #8439: every token that could be the subcommand. One when the global
        // options resolve; every non-option token after an unknown one, so
        // `git --shallow-file status checkout -- f` is judged as `checkout`.
        let Some((argv, mut candidates)) = shell_lex::git_subcommand_candidates(trimmed) else {
            continue;
        };
        // #8572: `git -C $(cat /tmp/main) checkout x` splits the substitution
        // into `$(cat` and `/tmp/main)`, and the second reads as the
        // subcommand. Every later non-option token becomes a candidate, and the
        // directory is the substitution, which no rule can resolve.
        let split = split_substitution_before(&argv, candidates.first().copied());
        if let Some(at) = split {
            candidates = (at + 1..argv.len())
                .filter(|&i| !argv[i].starts_with('-'))
                .collect();
        }
        for idx in candidates {
            let subcommand = &argv[idx];
            let tail = &argv[idx + 1..];
            if !matches(subcommand, tail) {
                continue;
            }
            let base = match (split, git_dash_c_override(&argv, idx)) {
                (Some(at), _) => resolve_target_path(&argv[at], &effective_cwd, env),
                (None, Some(dash_c)) => resolve_target_path(dash_c, &effective_cwd, env),
                (None, None) => effective_cwd.clone(),
            };
            found.push((subcommand.clone(), base, tail.to_vec()));
            break;
        }
    }
    found
}

/// The index of the first token, up to and including `first_candidate`, that
/// opens a `$(…)` or backtick substitution it does not close (#8572).
///
/// Why: shlex splits an unquoted `$(cat /tmp/main)` at the space, so the
/// global-option walk takes `/tmp/main)` as the subcommand and the real verb
/// is never classified. A balanced single-token substitution hides nothing
/// and is left to [`super::unresolved_target`], so `git -c
/// user.name=$(whoami) commit` keeps its ordinary verdict.
/// What: `Some(index)` for a token with more `$(` than `)`, or an odd number of
/// backticks; `None` when no such token precedes the subcommand.
/// Test: `walker_sees_past_a_split_substitution`.
fn split_substitution_before(argv: &[String], first_candidate: Option<usize>) -> Option<usize> {
    let end = first_candidate.map_or(argv.len(), |i| i + 1);
    argv[..end].iter().position(|t| {
        t.matches("$(").count() > t.matches(')').count() || t.matches('`').count() % 2 == 1
    })
}

/// Whether a git subcommand, given its argv tail, overwrites or deletes work
/// in the working tree.
///
/// Why: this table IS the false-positive boundary, and #5356 (a `pm_guard`
/// deny landing on a turn of purely read-only `git status`/`git log` calls) is
/// the live reminder of what a loose one costs. So each verb is narrowed to
/// the forms that actually destroy, and everything else — every other
/// subcommand, and every non-destructive form of these five — falls through to
/// ALLOW.
/// What, per verb:
/// - `reset`: only the modes that touch the working tree (`--hard`,
///   `--merge`, `--keep`). A bare `git reset` and its default `--mixed`
///   unstage without destroying anything, and stay allowed.
/// - `clean`: any force flag (`--force`, or a short cluster containing `f`;
///   `x`/`X` too, which are inert without force but cost nothing to include)
///   — UNLESS the command is a dry run (`-n`/`--dry-run`), which only prints.
/// - `checkout`: the pathspec-restoring forms (`-- <pathspec>`, a bare `.`)
///   and `-f`/`--force`, which discards the whole tree. `checkout -b`, a
///   plain branch switch, and a detaching `checkout <sha>` are untouched
///   here; an agent's switch in a DIRTY checkout is [`super::head_switch`]'s.
/// - `restore`: the modern equivalent of `checkout -- <pathspec>`, and the
///   easy one to miss. Its DEFAULT target is the working tree, so the rule
///   inverts: destructive unless `--staged`/`-S` is present without
///   `--worktree`/`-W` (index-only, which destroys nothing).
/// - `switch`: `--discard-changes`, plus `-f`/`--force` which implies it.
///   Included so the `checkout`/`switch` pair cannot be used to reach the
///   same destruction through the newer spelling.
///
/// Test: `is_whole_tree_destructive_denies_*`, `is_whole_tree_destructive_allows_*`.
fn is_whole_tree_destructive(subcommand: &str, tail: &[String]) -> bool {
    let has = |names: &[&str]| tail.iter().any(|t| names.contains(&t.as_str()));
    let cluster_has = |chars: &[char]| {
        tail.iter().any(|t| {
            t.starts_with('-')
                && !t.starts_with("--")
                && t.chars().skip(1).any(|c| chars.contains(&c))
        })
    };
    match subcommand {
        "reset" => has(&["--hard", "--merge", "--keep"]),
        "clean" => {
            let dry_run = has(&["--dry-run"]) || cluster_has(&['n']);
            let forced = has(&["--force"]) || cluster_has(&['f', 'x', 'X']);
            forced && !dry_run
        }
        "checkout" => {
            has(&["-f", "--force"])
                || tail.iter().any(|t| t == "." || t == "./")
                || pathspec_separator_with_paths(tail)
        }
        "restore" => {
            let staged = has(&["--staged", "-S"]);
            let worktree = has(&["--worktree", "-W"]);
            worktree || !staged
        }
        "switch" => has(&["--discard-changes", "-f", "--force"]),
        _ => false,
    }
}

/// Whether the tail carries a `--` end-of-options separator with at least one
/// pathspec after it — the `git checkout <ref> -- <pathspec>` shape that
/// restores files over uncommitted work.
fn pathspec_separator_with_paths(tail: &[String]) -> bool {
    tail.iter()
        .position(|t| t == "--")
        .is_some_and(|i| i + 1 < tail.len())
}

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

    fn tail(args: &[&str]) -> Vec<String> {
        args.iter().map(|s| (*s).to_string()).collect()
    }

    /// The destructive-verb specialisation of [`git_verb_target_dir`], so the
    /// pre-existing cases below keep asserting on the shape they were written
    /// against rather than restating the classifier at every call.
    fn destructive_target_dir(
        command: &str,
        cwd: &Path,
        env: &PathEnv,
    ) -> Option<(String, PathBuf)> {
        git_verb_target_dir(command, cwd, env, is_whole_tree_destructive)
    }

    /// 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_dir() -> TempDir {
        let dir = tempfile::tempdir().expect("tempdir");
        std::fs::create_dir(dir.path().join(".git")).expect("mkdir .git");
        dir
    }

    #[test]
    fn is_whole_tree_destructive_denies_the_incident_shapes() {
        // The two commands from the 2026-08-10 incident that this rule owns.
        // The third, `git reset HEAD`, is deliberately NOT here — see
        // `is_whole_tree_destructive_allows_the_near_misses`.
        assert!(is_whole_tree_destructive(
            "checkout",
            &tail(&["a1b2c3d", "--", "."])
        ));
        assert!(is_whole_tree_destructive(
            "clean",
            &tail(&["-fdx", "--", "crates/", "docs/"])
        ));
    }

    #[test]
    fn is_whole_tree_destructive_denies_every_listed_form() {
        for (verb, args) in [
            ("checkout", vec!["--", "src/lib.rs"]),
            ("checkout", vec!["HEAD~1", "--", "crates/"]),
            ("checkout", vec!["."]),
            ("checkout", vec!["./"]),
            ("checkout", vec!["-f", "main"]),
            ("checkout", vec!["--force", "main"]),
            ("restore", vec!["src/lib.rs"]),
            ("restore", vec!["--source=HEAD~1", "--", "src/"]),
            ("restore", vec!["--staged", "--worktree", "src/"]),
            ("restore", vec!["-S", "-W", "src/"]),
            ("reset", vec!["--hard"]),
            ("reset", vec!["--hard", "origin/main"]),
            ("reset", vec!["--merge", "HEAD"]),
            ("reset", vec!["--keep", "HEAD~2"]),
            ("clean", vec!["-f"]),
            ("clean", vec!["-fd"]),
            ("clean", vec!["-fdx"]),
            ("clean", vec!["-x"]),
            ("clean", vec!["--force", "-d"]),
            ("switch", vec!["--discard-changes", "main"]),
            ("switch", vec!["-f", "main"]),
        ] {
            assert!(
                is_whole_tree_destructive(verb, &tail(&args)),
                "expected `git {verb} {}` to be destructive",
                args.join(" ")
            );
        }
    }

    #[test]
    fn is_whole_tree_destructive_allows_the_near_misses() {
        // The false-positive boundary, and the reason it is tested: #5356 is
        // an open P2 filed because pm_guard denied a turn of purely read-only
        // git calls. `git reset HEAD` is here on the owner's explicit rule —
        // the default `--mixed` unstages and destroys nothing — even though it
        // was one of the three commands the incident agent ran.
        for (verb, args) in [
            ("reset", vec!["HEAD"]),
            ("reset", vec![]),
            ("reset", vec!["--soft", "HEAD~1"]),
            ("reset", vec!["--mixed", "HEAD"]),
            ("checkout", vec!["-b", "feature/x"]),
            ("checkout", vec!["-B", "feature/x", "origin/main"]),
            ("checkout", vec!["main"]),
            ("checkout", vec!["a1b2c3d"]),
            ("restore", vec!["--staged", "src/lib.rs"]),
            ("restore", vec!["-S", "src/lib.rs"]),
            ("clean", vec!["-n"]),
            ("clean", vec!["-nfd"]),
            ("clean", vec!["--dry-run", "-fdx"]),
            ("clean", vec!["-d"]),
            ("switch", vec!["main"]),
            ("switch", vec!["-c", "feature/x"]),
            ("status", vec!["--short"]),
            ("log", vec!["--oneline", "-20"]),
            ("diff", vec!["--stat", "HEAD~1"]),
            ("stash", vec!["list"]),
            ("add", vec!["-A"]),
            ("commit", vec!["-m", "wip"]),
        ] {
            assert!(
                !is_whole_tree_destructive(verb, &tail(&args)),
                "`git {verb} {}` must NOT be treated as destructive",
                args.join(" ")
            );
        }
    }

    #[test]
    fn destructive_target_dir_defaults_to_the_hook_cwd() {
        let env = PathEnv::from_process();
        let (verb, dir) =
            destructive_target_dir("git reset --hard origin/main", Path::new("/repo"), &env)
                .expect("a destructive verb must resolve a target");
        assert_eq!(verb, "reset");
        assert_eq!(dir, PathBuf::from("/repo"));
    }

    #[test]
    fn destructive_target_dir_follows_cd_and_dash_c() {
        // Both bypasses the sibling worktree guard already closes: a `cd` in an
        // earlier segment, and git's own `-C` working-directory override.
        let env = PathEnv::from_process();
        let (_, via_cd) = destructive_target_dir(
            "cd /elsewhere/main && git clean -fdx",
            Path::new("/repo"),
            &env,
        )
        .expect("cd must move the target");
        assert_eq!(via_cd, PathBuf::from("/elsewhere/main"));

        let (_, via_dash_c) = destructive_target_dir(
            "git -C /elsewhere/main reset --hard",
            Path::new("/repo"),
            &env,
        )
        .expect("-C must move the target");
        assert_eq!(via_dash_c, PathBuf::from("/elsewhere/main"));

        // Relative targets resolve against the running directory, and `..`
        // collapses lexically.
        let (_, relative) =
            destructive_target_dir("git -C ../other reset --hard", Path::new("/a/b"), &env)
                .expect("relative -C must resolve");
        assert_eq!(relative, PathBuf::from("/a/other"));
    }

    #[test]
    fn destructive_target_dir_finds_a_verb_hidden_in_a_later_segment() {
        // A benign leading verb must not hide the destructive one behind it.
        let env = PathEnv::from_process();
        let (verb, _) = destructive_target_dir(
            "git status --short; git checkout -- crates/",
            Path::new("/repo"),
            &env,
        )
        .expect("the second segment must be classified");
        assert_eq!(verb, "checkout");
    }

    #[test]
    fn destructive_target_dir_is_none_for_ordinary_work() {
        // The overwhelmingly common traffic: nothing here may reach the
        // filesystem classification at all.
        let env = PathEnv::from_process();
        for command in [
            "git status",
            "git log --oneline -20",
            "git diff HEAD~1",
            "ls -la",
            "cargo test -p trusty-mpm",
            "git checkout -b feature/x",
            "git reset HEAD",
            "git commit -m 'x'",
            "",
            // Unbalanced quotes: shlex yields no argv, so nothing is
            // positively identified and the rule stays out of it.
            "git reset --hard 'unterminated",
        ] {
            assert!(
                destructive_target_dir(command, Path::new("/repo"), &env).is_none(),
                "`{command}` must not resolve a destructive target"
            );
        }
    }

    #[test]
    fn commit_target_dir_finds_the_commit_and_follows_cd_and_dash_c() {
        let env = PathEnv::from_process();
        let is_commit = |verb: &str, _: &[String]| verb == "commit";

        let (verb, dir) =
            git_verb_target_dir("git commit -m 'wip'", Path::new("/repo"), &env, is_commit)
                .expect("a commit must resolve a target");
        assert_eq!(verb, "commit");
        assert_eq!(dir, PathBuf::from("/repo"));

        // The composition shape `git add -A && git commit -m …` is the ordinary
        // one, so the commit must be found in a later segment.
        let (_, chained) = git_verb_target_dir(
            "git add -A && git commit -m 'wip'",
            Path::new("/repo"),
            &env,
            is_commit,
        )
        .expect("the second segment must be classified");
        assert_eq!(chained, PathBuf::from("/repo"));

        // Both directory overrides the destructive rule already closes.
        let (_, via_cd) = git_verb_target_dir(
            "cd /elsewhere/main && git commit -m x",
            Path::new("/repo"),
            &env,
            is_commit,
        )
        .expect("cd must move the target");
        assert_eq!(via_cd, PathBuf::from("/elsewhere/main"));

        let (_, via_dash_c) = git_verb_target_dir(
            "git -C /elsewhere/main commit -m x",
            Path::new("/repo"),
            &env,
            is_commit,
        )
        .expect("-C must move the target");
        assert_eq!(via_dash_c, PathBuf::from("/elsewhere/main"));
    }

    #[test]
    fn commit_target_dir_is_none_for_everything_else() {
        let env = PathEnv::from_process();
        let is_commit = |verb: &str, _: &[String]| verb == "commit";
        for command in [
            "git status",
            "git log --oneline -5",
            "git add -A",
            "git push origin HEAD",
            "cargo test -p trusty-mpm",
            "",
        ] {
            assert!(
                git_verb_target_dir(command, Path::new("/repo"), &env, is_commit).is_none(),
                "`{command}` is not a commit"
            );
        }
    }

    #[test]
    fn evaluate_main_checkout_commit_denies_in_a_checkout_and_allows_in_a_worktree() {
        // `main_checkout_dir` fabricates `.git` as a directory, so `git diff
        // --cached` cannot run there and the staged set is UNKNOWN — the
        // deny arm of ADR-0049 decision 5, which is also the pre-ADR-0049
        // behaviour for every commit.
        let checkout = main_checkout_dir();
        let CommitVerdict::Deny(reason) =
            evaluate_main_checkout_commit_command("git commit -m 'wip'", checkout.path())
                .expect("a commit in a main checkout must be classified")
        else {
            panic!("an unreadable staged set must deny");
        };
        assert!(reason.contains("ADR-0044"), "{reason}");

        // A linked worktree carries a `.git` FILE. Committing there is the
        // whole remedy the deny offers, so it must work.
        let worktree = tempfile::tempdir().expect("tempdir");
        std::fs::write(worktree.path().join(".git"), "gitdir: /elsewhere").expect("write .git");
        assert!(
            evaluate_main_checkout_commit_command("git commit -m 'wip'", worktree.path()).is_none()
        );

        // Not a repository at all: nothing to protect.
        let plain = tempfile::tempdir().expect("tempdir");
        assert!(
            evaluate_main_checkout_commit_command("git commit -m 'wip'", plain.path()).is_none()
        );
    }

    /// #7100: the `version-control` agent stands in the main checkout
    /// (ADR-0056), so `git -C "$WT" checkout -- <file>` aimed at a sibling
    /// worktree resolved to `<checkout>/$WT`, whose nearest `.git` ancestor is
    /// the checkout itself. The refusal then told the agent it was destroying
    /// the main checkout, which it was not, and the agent hand-edited the file
    /// instead. It is still refused — an empty `$WT` really would run there —
    /// but the refusal now names the variable and the two forms that work.
    #[test]
    fn destructive_deny_names_an_unresolved_variable_rather_than_the_checkout() {
        let checkout = main_checkout_dir();
        let reason = evaluate_main_checkout_destructive_command(
            "git -C $WT checkout -- src/lib.rs",
            checkout.path(),
        )
        .expect("an unresolvable target directory must still deny");
        assert!(reason.contains("$WT"), "{reason}");
        assert!(reason.contains("unresolvable"), "{reason}");
        assert!(
            !reason.contains("which is a project's main checkout"),
            "the guard must not assert what it could not establish: {reason}"
        );
    }

    /// 🔴 REGRESSION (#8572 review): from the agent's own worktree,
    /// `git -C $MAIN reset --hard` resolved to `<worktree>/$MAIN`, which
    /// `is_main_checkout` answers `false` for, so the rule allowed it while the
    /// shell ran it in the main checkout.
    #[test]
    fn destructive_denies_an_unresolved_directory_from_a_worktree() {
        let checkout = main_checkout_dir();
        let wt = checkout.path().join(".claude/worktrees/agent-a");
        std::fs::create_dir_all(&wt).expect("mkdir wt");
        std::fs::write(wt.join(".git"), "gitdir: /elsewhere").expect("write .git");
        for (command, token) in [
            ("git -C $MAIN reset --hard", "$MAIN"),
            ("cd $MAIN && git checkout -- .", "$MAIN"),
            // #8572: a command substitution is unresolved the same way.
            ("git -C \"$(cat /tmp/main)\" reset --hard", "$("),
            ("cd \"`cat /tmp/main`\" && git clean -fdx", "`"),
        ] {
            let reason = evaluate_main_checkout_destructive_command(command, &wt)
                .unwrap_or_else(|| panic!("`{command}` from a worktree must be denied"));
            assert!(reason.contains(token), "{command}: {reason}");
            assert!(reason.contains("unresolvable"), "{reason}");
        }
        assert!(
            evaluate_main_checkout_destructive_command("git reset --hard", &wt).is_none(),
            "the worktree's own destructive command stays allowed"
        );
    }

    /// #8572 review: an unquoted multi-word `$(…)` after `-C` hid the verb —
    /// `/tmp/main)` read as the subcommand. A balanced one hides nothing.
    #[test]
    fn walker_sees_past_a_split_substitution() {
        let checkout = main_checkout_dir();
        let wt = checkout.path().join(".claude/worktrees/agent-a");
        std::fs::create_dir_all(&wt).expect("mkdir wt");
        std::fs::write(wt.join(".git"), "gitdir: /elsewhere").expect("write .git");
        for command in [
            "git -C $(cat /tmp/main) reset --hard",
            "git -C `cat /tmp/main` checkout -- .",
            "git $(echo -C /tmp/main) reset --hard",
        ] {
            let reason = evaluate_main_checkout_destructive_command(command, &wt)
                .unwrap_or_else(|| panic!("`{command}` from a worktree must be denied"));
            assert!(reason.contains("unresolvable"), "{command}: {reason}");
        }
        let env = PathEnv::from_process();
        let any = |_: &str, _: &[String]| true;
        let found = git_verb_targets_with_tail(
            "git -C $(git rev-parse --show-toplevel) status",
            &wt,
            &env,
            is_whole_tree_destructive,
        );
        assert!(found.is_empty(), "a read stays a read: {found:?}");
        let found =
            git_verb_targets_with_tail("git -c user.name=$(whoami) commit -m x", &wt, &env, any);
        assert_eq!(found.len(), 1);
        assert_eq!(found[0].0, "commit");
        assert_eq!(found[0].1, wt, "a balanced substitution leaves the cwd");
    }

    /// 🔴 REGRESSION (#8572 review): only the first destructive segment was
    /// judged, so the worktree's own `git reset --hard` cleared a second
    /// segment aimed at the main checkout.
    #[test]
    fn destructive_judges_every_segment() {
        let checkout = main_checkout_dir();
        let wt = checkout.path().join(".claude/worktrees/agent-a");
        std::fs::create_dir_all(&wt).expect("mkdir wt");
        std::fs::write(wt.join(".git"), "gitdir: /elsewhere").expect("write .git");
        let spelled_out = format!(
            "git reset --hard && git -C {} reset --hard",
            checkout.path().display()
        );
        for command in [
            "git reset --hard && git -C $MAIN reset --hard",
            spelled_out.as_str(),
        ] {
            assert!(
                evaluate_main_checkout_destructive_command(command, &wt).is_some(),
                "`{command}` from a worktree must be denied"
            );
        }
    }

    /// #8439: an unknown git global option cannot hide a destructive verb —
    /// `git --shallow-file status checkout -- f` restored a file past this rule.
    #[test]
    fn destructive_sees_past_an_unknown_git_global_option() {
        let checkout = main_checkout_dir();
        for command in [
            "git --shallow-file status checkout -- Cargo.toml",
            "git --attr-source status checkout -- Cargo.toml",
            "git --shallow-file log reset --hard",
        ] {
            assert!(
                evaluate_main_checkout_destructive_command(command, checkout.path()).is_some(),
                "must deny: {command}"
            );
        }
        assert!(!command_is_a_lone_commit(
            "git --shallow-file x commit -m wip"
        ));
    }

    /// The half of #7100 that must NOT change: a `-C` path spelled out to a
    /// sibling harness worktree is outside this rule, whether or not the
    /// directory exists yet, and the main checkout stays denied.
    #[test]
    fn destructive_allows_a_path_restoring_checkout_in_a_sibling_worktree() {
        let checkout = main_checkout_dir();
        let sibling = checkout.path().join(".claude/worktrees/agent-b");
        for command in [
            format!("git -C {} checkout -- src/lib.rs", sibling.display()),
            "git -C .claude/worktrees/agent-b checkout -- src/lib.rs".to_string(),
            "cd .claude/worktrees/agent-b && git restore src/lib.rs".to_string(),
        ] {
            assert!(
                evaluate_main_checkout_destructive_command(&command, checkout.path()).is_none(),
                "a sibling worktree is not the main checkout: {command}"
            );
        }
        // The boundary this exception must not cross.
        assert!(
            evaluate_main_checkout_destructive_command(
                "git checkout -- src/lib.rs",
                checkout.path()
            )
            .is_some(),
            "the main checkout itself stays denied"
        );
    }

    /// 🔴 REGRESSION (#8339): `git checkout <sha> -- <paths>` inside a
    /// disposable clone under the session scratchpad — the git-workflow
    /// skill's pre-fix red-proof recipe — is not a main checkout. Denied on
    /// origin/main. The adjacent cases still deny: a symlink in the scratchpad
    /// pointing at a real checkout, and an unresolved `-C $WT` run from the
    /// clone.
    #[test]
    fn destructive_allows_a_checkout_in_a_scratchpad_clone_only() {
        let dir = tempfile::tempdir().expect("tempdir");
        let clone = dir.path().join("scratchpad").join("red-proof");
        std::fs::create_dir_all(clone.join(".git")).expect("mkdir clone .git");
        assert!(
            evaluate_main_checkout_destructive_command(
                "git checkout abc1234 -- src/lib.rs",
                &clone
            )
            .is_none(),
            "a scratchpad clone is nobody's shared tree"
        );

        let real = dir.path().join("realrepo");
        std::fs::create_dir_all(real.join(".git")).expect("mkdir real .git");
        let link = dir.path().join("scratchpad").join("linkrepo");
        std::os::unix::fs::symlink(&real, &link).expect("symlink");
        assert!(
            evaluate_main_checkout_destructive_command("git checkout abc1234 -- src/lib.rs", &link)
                .is_some(),
            "a symlink into a real checkout must not buy the exemption"
        );
        assert!(
            evaluate_main_checkout_destructive_command("git -C $WT checkout -- .", &clone)
                .is_some(),
            "an unresolved directory proves nothing about where the checkout runs"
        );
    }

    /// 🔴 REGRESSION (#8485): `git commit -F-` fed a heredoc inside a
    /// disposable clone under the session scratchpad was refused as a
    /// composed commit in a main checkout. The clone is classified by its
    /// canonical path, so a symlink into a real checkout still denies.
    #[test]
    fn commit_allows_a_scratchpad_clone_only() {
        let dir = tempfile::tempdir().expect("tempdir");
        let clone = dir.path().join("scratchpad").join("red-proof");
        std::fs::create_dir_all(clone.join(".git")).expect("mkdir clone .git");
        for command in [
            "git commit -F- <<'EOF'\nfix: x\n\nbody\nEOF",
            "git commit -m 'wip'",
        ] {
            assert!(
                evaluate_main_checkout_commit_command(command, &clone).is_none(),
                "`{command}` in a scratchpad clone shares no HEAD"
            );
        }
        let real = dir.path().join("realrepo");
        std::fs::create_dir_all(real.join(".git")).expect("mkdir real .git");
        let link = dir.path().join("scratchpad").join("linkrepo");
        std::os::unix::fs::symlink(&real, &link).expect("symlink");
        assert!(
            evaluate_main_checkout_commit_command("git commit -m 'wip'", &link).is_some(),
            "a symlink into a real checkout must not buy the exemption"
        );
    }

    /// 🔴 REGRESSION (#8485 review, CRITICAL): the scratchpad exemption read
    /// only the FIRST commit segment, so a clone commit chained to a main
    /// checkout commit was allowed — the #5788 CRITICAL-1 shape. Both orders,
    /// every separator, and a linked worktree in the first slot must deny.
    #[test]
    fn commit_refuses_a_scratchpad_clone_chained_to_a_main_checkout_commit() {
        let dir = tempfile::tempdir().expect("tempdir");
        let clone = dir.path().join("scratchpad").join("c");
        std::fs::create_dir_all(clone.join(".git")).expect("mkdir clone .git");
        let main = main_checkout_dir();
        let worktree = dir.path().join("wt");
        std::fs::create_dir_all(&worktree).expect("mkdir wt");
        std::fs::write(worktree.join(".git"), "gitdir: /elsewhere").expect("write .git");
        let (pad, real, wt) = (clone.display(), main.path().display(), worktree.display());
        let pad_first = format!("git -C {pad} commit --allow-empty -m x");
        let main_side = format!("git -C {real} commit -a -m src");
        let wt_first = format!("git -C {wt} commit --allow-empty -m x");
        for sep in [" && ", " ; ", " || ", " | ", "\n"] {
            for command in [
                format!("{pad_first}{sep}{main_side}"),
                format!("{main_side}{sep}{pad_first}"),
                format!("{wt_first}{sep}{main_side}"),
            ] {
                assert!(
                    matches!(
                        evaluate_main_checkout_commit_command(&command, &clone),
                        Some(CommitVerdict::Deny(_))
                    ),
                    "`{command}` must deny"
                );
            }
        }
    }

    /// The commands in `commands` that the commit rule, run from `cwd`, does
    /// not deny.
    fn commits_not_denied(commands: &[String], cwd: &Path) -> Vec<String> {
        commands
            .iter()
            .filter(|command| {
                !matches!(
                    evaluate_main_checkout_commit_command(command, cwd),
                    Some(CommitVerdict::Deny(_))
                )
            })
            .cloned()
            .collect()
    }

    /// The `commands` from `cwd` the commit rule does not refuse as
    /// unplaceable — any other verdict, another deny reason included (#9127).
    fn unplaced_commits_not_refused(commands: &[String], cwd: &Path) -> Vec<String> {
        commands
            .iter()
            .filter(|command| {
                !matches!(
                    evaluate_main_checkout_commit_command(command, cwd),
                    Some(CommitVerdict::Deny(reason)) if reason.contains("cannot place it")
                )
            })
            .cloned()
            .collect()
    }

    /// 🔴 REGRESSION (#9127): a main-checkout commit wrapped in a subshell or a
    /// brace group lexed as `(git` or `{`, so the commit rule never saw it.
    /// All four forms were allowed on origin/main and in the released 1.7.10.
    #[test]
    fn commit_in_a_subshell_or_brace_group_must_deny() {
        let main = main_checkout_dir();
        let elsewhere = tempfile::tempdir().expect("tempdir");
        let real = main.path().display();
        let missed = commits_not_denied(
            &[
                format!("(git -C {real} commit -a -m x)"),
                format!("( git -C {real} commit -a -m x)"),
                format!("( git -C {real} commit -a -m x )"),
                format!("{{ git -C {real} commit -a -m x; }}"),
            ],
            elsewhere.path(),
        );
        assert!(missed.is_empty(), "not denied:\n{}", missed.join("\n"));
    }

    /// 🔴 REGRESSION (#9127): nesting, a `cd` inside the subshell, a trailing
    /// operator or redirect, and a commit after a separator inside the group.
    #[test]
    fn commit_in_a_nested_or_chained_group_must_deny() {
        let main = main_checkout_dir();
        let elsewhere = tempfile::tempdir().expect("tempdir");
        let real = main.path().display();
        let missed = commits_not_denied(
            &[
                format!("( ( git -C {real} commit -a -m x ) )"),
                format!("((git -C {real} commit -a -m x))"),
                format!("( {{ git -C {real} commit -a -m x; }} )"),
                format!("{{ git -C {real} commit -a -m x; }} && echo done"),
                format!("{{ git -C {real} commit -a -m x; }} > /dev/null 2>&1"),
                format!("(git -C {real} commit -a -m x) || true"),
                format!("(cd {real} && git commit -a -m x)"),
                format!("(cd {real}; git commit -a -m x)"),
                format!("(true && git -C {real} commit -a -m x)"),
                format!("(false || git -C {real} commit -a -m x)"),
                format!("{{ true; git -C {real} commit -a -m x; }}"),
            ],
            elsewhere.path(),
        );
        assert!(missed.is_empty(), "not denied:\n{}", missed.join("\n"));
    }

    /// 🔴 REGRESSION (#9127): a reserved word in command position hid the
    /// program word the same way a `(` did, and so did a group handed to a
    /// `sh -c`/`bash -c` wrapper, whose string the guard already descends into.
    #[test]
    fn commit_behind_a_reserved_word_or_in_a_wrapped_group_must_deny() {
        let main = main_checkout_dir();
        let elsewhere = tempfile::tempdir().expect("tempdir");
        let real = main.path().display();
        let missed = commits_not_denied(
            &[
                format!("if true; then git -C {real} commit -a -m x; fi"),
                format!("! git -C {real} commit -a -m x"),
                format!("while true; do git -C {real} commit -a -m x; break; done"),
                format!("bash -c '(git -C {real} commit -a -m x)'"),
                format!("sh -c '{{ git -C {real} commit -a -m x; }}'"),
            ],
            elsewhere.path(),
        );
        assert!(missed.is_empty(), "not denied:\n{}", missed.join("\n"));
    }

    /// 🔴 REGRESSION (#9127): a `cd` inside a subshell or a `sh -c` string does
    /// not move the caller's directory. Read as if it did, `sh -c 'cd <wt>'`
    /// cleared a commit that runs in the main checkout.
    #[test]
    fn a_cd_inside_a_subshell_or_wrapper_does_not_leak() {
        let main = main_checkout_dir();
        let wt = main.path().join(".claude/worktrees/agent-a");
        std::fs::create_dir_all(&wt).expect("mkdir wt");
        std::fs::write(wt.join(".git"), "gitdir: /elsewhere").expect("write .git");
        let wt = wt.display();
        let missed = commits_not_denied(
            &[
                format!("sh -c 'cd {wt}' && git commit -a -m x"),
                format!("(cd {wt}) && git commit -a -m x"),
                format!("(cd {wt} && git commit --allow-empty -m a); git commit -a -m b"),
            ],
            main.path(),
        );
        assert!(missed.is_empty(), "not denied:\n{}", missed.join("\n"));

        let env = PathEnv::from_process();
        let is_commit = |verb: &str, _: &[String]| verb == "commit";
        let targets: Vec<PathBuf> = git_verb_targets_with_tail(
            "(cd /wt && git commit -m a); git commit -m b",
            Path::new("/repo"),
            &env,
            is_commit,
        )
        .into_iter()
        .map(|(_, target, _)| target)
        .collect();
        assert_eq!(targets, [PathBuf::from("/wt"), PathBuf::from("/repo")]);
    }

    /// 🔴 REGRESSION (#9127): a group the guard cannot parse is refused when it
    /// carries a `git commit`, from any directory, since the guard cannot say
    /// where the commit lands. Bash rejects most of these too, so the deny
    /// costs nothing; a function body is the shape bash does run.
    #[test]
    fn commit_in_an_unbalanced_group_is_refused() {
        let main = main_checkout_dir();
        let wt = main.path().join(".claude/worktrees/agent-a");
        std::fs::create_dir_all(&wt).expect("mkdir wt");
        std::fs::write(wt.join(".git"), "gitdir: /elsewhere").expect("write .git");
        let real = main.path().display();
        let missed = commits_not_denied(
            &[
                format!("(git -C {real} commit -a -m x"),
                format!("{{ git -C {real} commit -a -m x"),
                format!("f() {{ git -C {real} commit -a -m x; }}; f"),
                "(git commit -m x".to_string(),
            ],
            &wt,
        );
        assert!(missed.is_empty(), "not denied:\n{}", missed.join("\n"));
        // An unbalanced group with no commit in it is not this rule's business.
        assert!(evaluate_main_checkout_commit_command("(git status", &wt).is_none());
    }

    /// The other half of #9127: grouping must not cost a commit that was
    /// allowed — in a linked worktree, in a scratchpad clone, or with a
    /// here-document or quoted message carrying an unbalanced `)` — and a read
    /// in a group stays a read.
    #[test]
    fn grouped_commits_outside_a_main_checkout_and_grouped_reads_stay_allowed() {
        let main = main_checkout_dir();
        let wt = main.path().join(".claude/worktrees/agent-a");
        std::fs::create_dir_all(wt.join("crates")).expect("mkdir wt");
        std::fs::write(wt.join(".git"), "gitdir: /elsewhere").expect("write .git");
        let dir = tempfile::tempdir().expect("tempdir");
        let clone = dir.path().join("scratchpad").join("red-proof");
        std::fs::create_dir_all(clone.join(".git")).expect("mkdir clone .git");
        let heredoc = "git commit -F- <<'EOF'\nfix: x\n\n1) one\n2) two\nEOF";
        for (command, cwd) in [
            ("(git commit -m x)", wt.as_path()),
            ("( ( git commit -m x ) )", wt.as_path()),
            ("{ git commit -m x; }", wt.as_path()),
            ("{ git commit -m x; } > /dev/null", wt.as_path()),
            ("(cd crates && git commit -m x)", wt.as_path()),
            (heredoc, wt.as_path()),
            ("git commit -m 'fix: case a) and b)'", wt.as_path()),
            ("git commit -m \"fix(x): y\"", wt.as_path()),
            ("(git commit -m x)", clone.as_path()),
            ("{ git commit -m x; }", clone.as_path()),
            (heredoc, clone.as_path()),
            ("(git status)", main.path()),
            ("{ git log; }", main.path()),
            ("( git log --oneline -5 ) | head", main.path()),
        ] {
            assert!(
                evaluate_main_checkout_commit_command(command, cwd).is_none(),
                "`{command}` in {} must stay allowed",
                cwd.display()
            );
        }
        let spelled = format!("(git -C {} commit -m x)", wt.display());
        assert!(evaluate_main_checkout_commit_command(&spelled, main.path()).is_none());
    }

    /// #9127: the destructive rule reads the same walker, so a grouped
    /// `reset --hard` is refused too, and a grouped read is not.
    #[test]
    fn destructive_sees_inside_a_subshell_or_brace_group() {
        let checkout = main_checkout_dir();
        for command in [
            "(git reset --hard)",
            "{ git checkout -- .; }",
            "if true; then git clean -fdx; fi",
        ] {
            assert!(
                evaluate_main_checkout_destructive_command(command, checkout.path()).is_some(),
                "must deny: {command}"
            );
        }
        assert!(
            evaluate_main_checkout_destructive_command("(git status)", checkout.path()).is_none()
        );
    }

    /// A linked worktree under `main`: a `.git` FILE, as `git worktree add`
    /// leaves it.
    fn linked_worktree(main: &Path) -> PathBuf {
        let wt = main.join(".claude/worktrees/agent-a");
        std::fs::create_dir_all(&wt).expect("mkdir wt");
        std::fs::write(wt.join(".git"), "gitdir: /elsewhere").expect("write .git");
        wt
    }

    /// 🔴 REGRESSION (#9127 critic HIGH-1): `eval` runs in the current shell,
    /// so its `cd` persists. Scoping it like `sh -c` cleared a commit and a
    /// `reset --hard` that run in the main checkout.
    #[test]
    fn a_cd_inside_eval_persists_9127() {
        let main = main_checkout_dir();
        let wt = linked_worktree(main.path());
        let real = main.path().display();
        let missed = commits_not_denied(
            &[
                format!("eval \"cd {real}\"; git commit -a -m x"),
                format!("eval cd {real} && git commit -a -m x"),
                format!("(eval \"cd {real}\"; git commit -a -m x)"),
            ],
            &wt,
        );
        assert!(missed.is_empty(), "not denied:\n{}", missed.join("\n"));
        for command in [
            format!("eval \"cd {real}\"; git reset --hard"),
            format!("eval \"cd {real}\" && git checkout -- ."),
        ] {
            assert!(
                evaluate_main_checkout_destructive_command(&command, &wt).is_some(),
                "must deny: {command}"
            );
        }
        // The other direction holds too: an `eval` cd into the worktree is real.
        let into_wt = format!("eval \"cd {}\" && git commit -m x", wt.display());
        assert!(evaluate_main_checkout_commit_command(&into_wt, main.path()).is_none());
        // A bare `builtin eval` runs in place in bash and zsh alike.
        let builtin = format!("builtin eval \"cd {}\" && git commit -m x", wt.display());
        assert!(evaluate_main_checkout_commit_command(&builtin, main.path()).is_none());
        // #9127 critic r3: bash runs `command eval` in place and zsh finds no
        // `eval`, so its `cd` cannot be placed — refused from either side.
        let unplaced = unplaced_commits_not_refused(
            &[
                format!("command -p eval \"cd {real}\"; git commit -a -m x"),
                format!("command -- eval \"cd {real}\"; git commit -a -m x"),
                format!("builtin -- eval \"cd {real}\"; git commit -a -m x"),
                format!("noglob eval \"cd {real}\"; git commit -a -m x"),
            ],
            &wt,
        );
        assert!(unplaced.is_empty(), "not refused:\n{}", unplaced.join("\n"));
        let unplaced = unplaced_commits_not_refused(
            &[format!(
                "command eval \"cd {}\"; git commit -a -m x",
                wt.display()
            )],
            main.path(),
        );
        assert!(unplaced.is_empty(), "not refused:\n{}", unplaced.join("\n"));
        // #9127 critic MEDIUM-1: behind a process wrapper `eval` is a child
        // process, so its `cd` into the worktree ends with it.
        let wt = wt.display();
        let mut missed = commits_not_denied(
            &[format!("env eval \"cd {wt}\"; git commit -a -m x")],
            main.path(),
        );
        let nohup = format!("nohup eval \"cd {wt}\"; git reset --hard");
        if evaluate_main_checkout_destructive_command(&nohup, main.path()).is_none() {
            missed.push(nohup);
        }
        assert!(missed.is_empty(), "not denied:\n{}", missed.join("\n"));
    }

    /// 🔴 REGRESSION (#9127 critic HIGH-2): `coproc` hid the program word the
    /// way `(` did, with or without a NAME and a compound body.
    #[test]
    fn commit_or_reset_behind_coproc_must_deny_9127() {
        let main = main_checkout_dir();
        let elsewhere = tempfile::tempdir().expect("tempdir");
        let real = main.path().display();
        let missed = commits_not_denied(
            &[
                format!("coproc git -C {real} commit -a -m x"),
                format!("coproc NAME {{ git -C {real} commit -a -m x; }}"),
                format!("coproc NAME ( git -C {real} commit -a -m x )"),
                format!("coproc {{ git -C {real} commit -a -m x; }}"),
                format!("coproc NAME while true; do git -C {real} commit -a; done"),
            ],
            elsewhere.path(),
        );
        assert!(missed.is_empty(), "not denied:\n{}", missed.join("\n"));
        for command in [
            "coproc git reset --hard",
            "coproc NAME { git checkout -- .; }",
        ] {
            assert!(
                evaluate_main_checkout_destructive_command(command, main.path()).is_some(),
                "must deny: {command}"
            );
        }
        // A coproc is a child shell: its `cd` does not clear the caller.
        let wt = linked_worktree(main.path());
        let leak = format!("coproc cd {}; git reset --hard", wt.display());
        assert!(evaluate_main_checkout_destructive_command(&leak, main.path()).is_some());
        // #9127 critic MEDIUM-2: a coproc of a compound command leaves the
        // grouping unparsed, so a destructive verb in it is refused unplaced.
        let unparsed = "coproc while :; do :; done; (git reset --hard)";
        assert!(
            evaluate_main_checkout_destructive_command(unparsed, main.path())
                .is_some_and(|reason| reason.contains("cannot place it")),
            "must refuse unplaced: {unparsed}"
        );
        // A parsed worktree-only reset stays allowed.
        let in_wt = format!("(git -C {} reset --hard)", wt.display());
        assert!(evaluate_main_checkout_destructive_command(&in_wt, main.path()).is_none());
        assert!(evaluate_main_checkout_destructive_command("(git reset --hard)", &wt).is_none());
    }

    /// 🔴 REGRESSION (#9127 critic HIGH-3): a paren-form `case` arm and a
    /// function definition balance but run elsewhere than they stand, and a
    /// quote or backslash inside `git`/`commit` hid the fail-closed check.
    #[test]
    fn commit_in_a_shape_the_walker_cannot_place_is_refused_9127() {
        let main = main_checkout_dir();
        let wt = linked_worktree(main.path());
        let real = main.path().display();
        let missed = commits_not_denied(
            &[
                format!("case x in (x) git -C {real} commit -a -m x;; esac"),
                format!("f() ( git -C {real} commit -a -m x ); f"),
                format!("function f ( git -C {real} commit -a -m x )"),
                format!("(g''it -C {real} c''ommit -a -m x"),
                format!("(git -C {real} co\\mmit -a -m x"),
            ],
            &wt,
        );
        assert!(missed.is_empty(), "not denied:\n{}", missed.join("\n"));
        // #9127 critic MEDIUM-3: a brace expansion off the program word.
        let unplaced = unplaced_commits_not_refused(
            &[
                format!("case x in (x) {{git,-C,{real},commit,-a}};; esac"),
                format!("f() ( {{git,-C,{real},commit,-a}} ); f"),
            ],
            &wt,
        );
        assert!(unplaced.is_empty(), "not refused:\n{}", unplaced.join("\n"));
        for command in [
            "git add src/{a,b}.rs",
            "mkdir -p src/{a,b}",
            "cp f{,.bak}",
            "git commit -m 'fix(x): {a,b}'",
        ] {
            assert!(
                evaluate_main_checkout_commit_command(command, &wt).is_none(),
                "must stay allowed: {command}"
            );
        }
        // #9127 critic LOW: a stray `)` in a comment is named in the deny.
        let Some(CommitVerdict::Deny(reason)) =
            evaluate_main_checkout_commit_command("(git commit -m x) # a)", &wt)
        else {
            panic!("a stray `)` in a comment must deny");
        };
        assert!(reason.contains("comment"), "{reason}");
    }

    #[test]
    fn unresolved_directory_deny_reason_names_the_variable_and_the_remedy() {
        let reason = unresolved_directory_deny_reason(
            DESTRUCTIVE_UNRESOLVED_HEADLINE,
            "checkout",
            Path::new("/repo/$WT"),
            "$WT",
        );
        assert!(reason.contains("/repo/$WT"), "{reason}");
        assert!(reason.contains("$WT"), "{reason}");
        assert!(reason.contains(".claude/worktrees/"), "{reason}");
    }

    /// An environment with no `$HOME`, which is the only way a leading `~`
    /// reaches the rules as literal text (#7234).
    fn no_home() -> PathEnv {
        PathEnv {
            tmpdir: None,
            tmp: None,
            home: None,
        }
    }

    /// The `~` half of #7100's rule (#7234). `git -C ~/… checkout -- .` with
    /// `$HOME` unset joins `~` onto the launch directory, `is_main_checkout`
    /// then answers `true` for the fabricated path, and the refusal used to
    /// call the launch directory a main checkout.
    #[test]
    fn destructive_deny_names_a_surviving_tilde_rather_than_the_checkout() {
        let checkout = main_checkout_dir();
        let reason = evaluate_main_checkout_destructive_command_in(
            "git -C ~/audit-live-check-7137/repo-acme-test checkout -- .",
            checkout.path(),
            &no_home(),
        )
        .expect("an unresolvable target directory must still deny");
        assert!(reason.contains("unresolvable"), "{reason}");
        assert!(reason.contains('~'), "{reason}");
        assert!(
            !reason.contains("which is a project's main checkout"),
            "the guard must not assert what it could not establish: {reason}"
        );
        assert!(
            !reason.contains(&checkout.path().display().to_string()),
            "the launch directory is not where this command lands: {reason}"
        );
    }

    /// The incident command from #7234, which is a COMMIT and so never reached
    /// the destructive rule above: the deny has to come from the commit rule,
    /// and it must not name the launch directory it walked up into.
    #[test]
    fn commit_deny_names_a_surviving_tilde_rather_than_the_checkout() {
        let checkout = main_checkout_dir();
        let verdict = evaluate_main_checkout_commit_command_in(
            "git -C ~/audit-live-check-7137/repo-acme-test commit --allow-empty -m test",
            checkout.path(),
            &no_home(),
        )
        .expect("an unresolvable target directory must still deny");
        let CommitVerdict::Deny(reason) = verdict else {
            panic!("a target the guard cannot place must never reach the docs-only carve-out");
        };
        assert!(reason.contains("unresolvable"), "{reason}");
        assert!(
            reason.contains("~/audit-live-check-7137/repo-acme-test"),
            "the refusal must quote the token as written: {reason}"
        );
        assert!(
            !reason.contains("is a project's main checkout"),
            "the guard must not assert what it could not establish: {reason}"
        );
        assert!(
            !reason.contains(&checkout.path().display().to_string()),
            "the launch directory is not where this command lands: {reason}"
        );
    }

    /// The half that must NOT change: with `$HOME` set the tilde expands, the
    /// target is a scratch repository outside the checkout, and the commit rule
    /// has no business with it at all.
    #[test]
    fn commit_with_home_set_resolves_the_tilde_and_leaves_the_checkout_alone() {
        let checkout = main_checkout_dir();
        let home = tempfile::tempdir().expect("tempdir");
        let env = PathEnv {
            tmpdir: None,
            tmp: None,
            home: Some(home.path().display().to_string()),
        };
        assert!(
            evaluate_main_checkout_commit_command_in(
                "git -C ~/audit-live-check-7137/repo-acme-test commit --allow-empty -m test",
                checkout.path(),
                &env,
            )
            .is_none(),
            "a resolved target outside any checkout is not this rule's business"
        );
    }

    #[test]
    fn commit_deny_reason_names_the_path_and_the_remedy() {
        let reason = commit_deny_reason(Path::new("/repo/main"));
        assert!(reason.contains("/repo/main"), "{reason}");
        assert!(reason.contains(r#"isolation: "worktree""#), "{reason}");
        assert!(reason.contains("Nothing is lost"), "{reason}");
        // ADR-0049: the reader who lands here after editing one `.md` needs to
        // know the carve-out exists and what it wants.
        assert!(reason.contains("ADR-0049"), "{reason}");
        assert!(reason.contains("git add"), "{reason}");
    }

    // ── ADR-0049: the commit gate reads the staged set ──────────────────────

    /// `classify_staged_commit` with the shapes the caller supplies, so each
    /// case reads as the argv tail plus the staged set and nothing else.
    fn classify(tail: &[&str], staged: Option<&[&str]>) -> CommitVerdict {
        classify_in(tail, staged, false)
    }

    /// [`classify`] with the #7905 documents-repo answer chosen.
    fn classify_in(tail: &[&str], staged: Option<&[&str]>, documents: bool) -> CommitVerdict {
        let tail: Vec<String> = tail.iter().map(|s| (*s).to_string()).collect();
        let staged = staged.map(|s| s.iter().map(|p| (*p).to_string()).collect());
        classify_staged_commit(
            &tail,
            staged,
            Path::new("/repo/crates"),
            PathBuf::from("/repo"),
            |_| documents,
        )
    }

    /// 🔴 REGRESSION (#7905): in an operator-listed documents repo a staged
    /// `.py` is a document, so the rename commit is not refused as source.
    /// Every other deny arm still holds there: `-a` and an empty index.
    #[test]
    fn classify_staged_commit_counts_source_as_documents_in_a_documents_repo() {
        let staged = &["drafts/video/make-graphics.py", "archive/x.md"][..];
        assert!(is_docs_only(&classify_in(
            &["-m", "s", "-m", "b"],
            Some(staged),
            true
        )));
        assert!(!is_docs_only(&classify_in(
            &["-m", "s"],
            Some(staged),
            false
        )));
        assert!(!is_docs_only(&classify_in(
            &["-a", "-m", "s"],
            Some(staged),
            true
        )));
        assert!(!is_docs_only(&classify_in(&["-m", "s"], Some(&[]), true)));
        assert!(!is_docs_only(&classify_in(&["-m", "s"], None, true)));
    }

    fn is_docs_only(verdict: &CommitVerdict) -> bool {
        matches!(verdict, CommitVerdict::DocsOnly { .. })
    }

    fn deny_text(verdict: &CommitVerdict) -> &str {
        match verdict {
            CommitVerdict::Deny(reason) => reason,
            CommitVerdict::DocsOnly { .. } => panic!("expected a deny"),
        }
    }

    #[test]
    fn classify_staged_commit_permits_documents_and_configuration() {
        // ADR-0049 decision 1 and 2: the same non-source classification the
        // write boundary uses, so a file that may be WRITTEN here may be
        // COMMITTED here.
        for staged in [
            &["docs/adr/0049-x.md"][..],
            &["CLAUDE.md", "Cargo.toml"][..],
            &[".claude/settings.json", "TASK.md", "Makefile"][..],
            &["crates/trusty-mpm/changelog.d/5782-x.md"][..],
        ] {
            let verdict = classify(&["-m", "docs: x"], Some(staged));
            assert!(is_docs_only(&verdict), "{staged:?} is documents-only");
        }
        // The DocsOnly arm hands back both query keys, checkout ROOT first —
        // the order the HEAD-move rule uses, and the spelling a delegation
        // record most often carries (#5769).
        let CommitVerdict::DocsOnly { root, dirs } = classify(&[], Some(&["README.md"])) else {
            panic!("expected DocsOnly");
        };
        assert_eq!(root, PathBuf::from("/repo"));
        assert_eq!(
            dirs,
            [PathBuf::from("/repo"), PathBuf::from("/repo/crates")]
        );
    }

    #[test]
    fn classify_staged_commit_denies_source_and_names_it() {
        let verdict = classify(&["-m", "feat: x"], Some(&["crates/a/src/lib.rs"]));
        let reason = deny_text(&verdict);
        assert!(reason.contains("crates/a/src/lib.rs"), "{reason}");
        assert!(reason.contains("ADR-0049"), "{reason}");
        assert!(reason.contains("git restore --staged"), "{reason}");
    }

    #[test]
    fn classify_staged_commit_denies_a_mixed_set_and_names_only_the_source() {
        // ADR-0049 decision 6: fail safe on a mixed set, and name what made it
        // unsafe. Naming the documents too would send the reader unstaging the
        // files that were fine.
        let verdict = classify(
            &["-m", "wip"],
            Some(&["docs/x.md", "src/a.rs", "Cargo.toml", "src/b.py"]),
        );
        let reason = deny_text(&verdict);
        assert!(
            reason.contains("src/a.rs") && reason.contains("src/b.py"),
            "{reason}"
        );
        assert!(!reason.contains("docs/x.md"), "{reason}");
        assert!(!reason.contains("Cargo.toml"), "{reason}");
    }

    #[test]
    fn classify_staged_commit_denies_an_unreadable_or_empty_index() {
        // ADR-0045's distinction, on a gate: `None` is UNKNOWN and
        // `Some(vec![])` is empty, and neither is evidence of a docs commit.
        for staged in [None, Some(&[][..])] {
            let verdict = classify(&["-m", "wip"], staged);
            assert!(deny_text(&verdict).contains("ADR-0044"), "{staged:?}");
        }
    }

    #[test]
    fn classify_staged_commit_denies_the_forms_the_index_does_not_describe() {
        // ADR-0049 decision 5. Each of these commits content the staged set
        // does not hold, so a staged set of pure documents cannot license it.
        for tail in [
            &["-a", "-m", "wip"][..],
            &["-am", "wip"][..],
            &["--all"][..],
            &["--amend", "--no-edit"][..],
            &["-i", "--", "src/lib.rs"][..],
            &["--include", "src/lib.rs"][..],
            &["-o", "docs/x.md"][..],
            &["--only", "docs/x.md"][..],
            // A bare pathspec implies `--only`.
            &["docs/x.md"][..],
            &["-m", "wip", "--", "docs/x.md"][..],
        ] {
            let verdict = classify(tail, Some(&["docs/x.md"]));
            assert!(
                !is_docs_only(&verdict),
                "`git commit {}` must not be licensed by the index",
                tail.join(" ")
            );
        }
    }

    #[test]
    fn commit_flags_leave_the_index_authoritative_accepts_message_forms() {
        // The forms an agent actually types. A false `false` here costs the
        // carve-out; it never costs a new deny, because `false` is the
        // pre-ADR-0049 behaviour.
        for tail in [
            &[][..],
            &["-m", "docs: x"][..],
            &["--message", "docs: x"][..],
            &["--message=docs: x"][..],
            &["-m", "docs: x", "-s"][..],
            &["-m", "x", "--no-verify"][..],
            &["-q", "-m", "x"][..],
            &["--author", "A <a@b>", "-m", "x"][..],
            &["--date=2026-08-16", "-m", "x"][..],
            &["-S", "-m", "x"][..],
            &["-Sdeadbeef", "-m", "x"][..],
            &["--gpg-sign=deadbeef", "-m", "x"][..],
            &["-F", "/tmp/msg", "--cleanup=strip"][..],
            &["--trailer", "Closes: #1", "-m", "x"][..],
            &["--allow-empty", "-m", "x"][..],
            // A message that happens to contain a content flag is a VALUE,
            // consumed by the `-m` before it.
            &["-m", "--amend"][..],
        ] {
            let tail: Vec<String> = tail.iter().map(|s| (*s).to_string()).collect();
            assert!(
                commit_flags_leave_the_index_authoritative(&tail),
                "`git commit {}` leaves the index authoritative",
                tail.join(" ")
            );
        }
    }

    #[test]
    fn commit_flags_leave_the_index_authoritative_rejects_content_flags() {
        for tail in [
            &["-a"][..],
            &["--all"][..],
            &["--amend"][..],
            &["-i"][..],
            &["--include"][..],
            &["-o"][..],
            &["--only"][..],
            // Unrecognised: a short cluster, and a flag this list has never
            // heard of. The allowlist denies both rather than guessing.
            &["-sn"][..],
            &["--some-future-flag"][..],
        ] {
            let tail: Vec<String> = tail.iter().map(|s| (*s).to_string()).collect();
            assert!(
                !commit_flags_leave_the_index_authoritative(&tail),
                "`git commit {}` must not be licensed by the index",
                tail.join(" ")
            );
        }
    }

    #[test]
    fn commit_flags_leave_the_index_authoritative_rejects_a_pathspec() {
        for tail in [
            &["docs/x.md"][..],
            &["-m", "x", "docs/x.md"][..],
            &["--"][..],
        ] {
            let tail: Vec<String> = tail.iter().map(|s| (*s).to_string()).collect();
            assert!(
                !commit_flags_leave_the_index_authoritative(&tail),
                "a pathspec is `--only` by implication: {}",
                tail.join(" ")
            );
        }
    }

    #[test]
    fn command_is_a_lone_commit_accepts_a_commit_and_cd() {
        // `cd` moves no files and touches no index, so it cannot invalidate the
        // reading. Everything a documents commit legitimately needs is here.
        for command in [
            "git commit -m 'docs: x'",
            "cd /repo && git commit -m 'docs: x'",
            "cd /repo && cd docs && git commit -m x",
            "git -C /repo commit -m x",
        ] {
            assert!(
                command_is_a_lone_commit(command),
                "`{command}` is a lone commit"
            );
        }
    }

    #[test]
    fn command_is_a_lone_commit_rejects_a_second_commit() {
        // #5788 review, CRITICAL 1 — the demonstrated exploit. The walker
        // returns on the first commit segment, so without this the docs-only
        // reading licensed the later source commit.
        for command in [
            "git commit -m docs && git add -A && git commit -a -m src",
            "git commit -m docs ; git commit --amend --no-edit",
            "git commit -m a || git commit -m b",
        ] {
            assert!(
                !command_is_a_lone_commit(command),
                "`{command}` carries more than one commit"
            );
        }
    }

    #[test]
    fn command_is_a_lone_commit_rejects_anything_that_can_restage() {
        // One commit segment is not enough — anything running before it can
        // change the index after the reading. `git add -A && git commit` is the
        // shape that matters, and it was denied before ADR-0049 too.
        for command in [
            "git add -A && git commit -m docs",
            "echo x > src/lib.rs && git commit -m docs",
            "git status && git commit -m docs",
            "git commit -m docs && cargo test",
            // No commit at all: this rule has nothing to license.
            "git status",
        ] {
            assert!(
                !command_is_a_lone_commit(command),
                "`{command}` is not a lone commit"
            );
        }
    }

    #[test]
    fn composed_commit_deny_reason_names_the_composition_and_the_remedy() {
        let reason = composed_commit_deny_reason(Path::new("/repo"));
        assert!(reason.contains("/repo"), "{reason}");
        assert!(reason.contains("ADR-0049"), "{reason}");
        // The cause is the composition, not the content — say so, or the retry
        // is to unstage the document that was fine.
        assert!(reason.contains("Split the call"), "{reason}");
        assert!(reason.contains("git add -- <paths>"), "{reason}");
    }

    #[test]
    fn commit_target_dir_hands_back_the_argv_tail() {
        let env = PathEnv::from_process();
        let (verb, dir, tail) = git_verb_target_dir_with_tail(
            "cd /repo && git -C sub commit --amend -m wip",
            Path::new("/start"),
            &env,
            |verb, _| verb == "commit",
        )
        .expect("a commit must resolve");
        assert_eq!(verb, "commit");
        assert_eq!(dir, PathBuf::from("/repo/sub"));
        assert_eq!(tail, vec!["--amend", "-m", "wip"]);
    }

    #[test]
    fn staged_source_deny_reason_names_every_source_file() {
        let reason = staged_source_deny_reason(Path::new("/repo"), &["src/b.rs", "src/a.rs"]);
        assert!(
            reason.contains("src/a.rs") && reason.contains("src/b.rs"),
            "{reason}"
        );
        // Sorted, so two runs over the same set read identically.
        assert!(
            reason.find("src/a.rs") < reason.find("src/b.rs"),
            "{reason}"
        );
        assert!(reason.contains(r#"isolation: "worktree""#), "{reason}");
    }

    #[test]
    fn docs_commit_deny_reason_names_the_writer_and_attributes_the_claim() {
        let reason = docs_commit_deny_reason(Path::new("/repo"), &["rust-engineer".to_string()]);
        assert!(reason.contains("/repo"), "{reason}");
        assert!(reason.contains("rust-engineer"), "{reason}");
        assert!(reason.contains("ADR-0049"), "{reason}");
        // The claim is the daemon's, not this process's — a record can outlive
        // its agent. Same wording discipline as `head_move_deny_reason`.
        assert!(reason.contains("delegation records"), "{reason}");
        // Unstaging is the wrong retry here and the text has to say so.
        assert!(reason.contains("unstaging it will not help"), "{reason}");
        assert!(reason.contains(r#"isolation: "worktree""#), "{reason}");
    }

    #[test]
    fn starts_a_head_move_permits_pull_and_fetch() {
        // ADR-0053. Owner ruling of 2026-08-17: "fetch and pull operations are
        // permitted. Only direct code editing is not." Every `pull` form below
        // was DENIED under ADR-0048 decision 10 — `("pull", vec!["--ff-only"])`
        // sat in the covers-the-three-verbs table this test inverts. `fetch` was
        // already permitted (decision 9) and is pinned here beside it so the
        // remedy the deny still names cannot regress with it.
        for (verb, args) in [
            ("pull", vec![]),
            ("pull", vec!["--rebase"]),
            ("pull", vec!["origin", "main"]),
            ("pull", vec!["--ff-only"]),
            ("fetch", vec!["origin"]),
            ("fetch", vec!["--all", "--prune"]),
        ] {
            assert!(
                !starts_a_head_move(verb, &tail(&args)),
                "`git {verb} {}` is permitted in a main checkout (ADR-0053)",
                args.join(" ")
            );
        }
    }

    #[test]
    fn starts_a_head_move_still_covers_merge_and_rebase() {
        // ADR-0053 permits `pull` and leaves these two exactly as ADR-0048
        // decision 10 shipped them: a merge can conflict the shared tree and a
        // rebase rewrites the branch another session's work sits on, neither of
        // which `pull --ff-only` can do. Every form of both moves HEAD, which is
        // what lets the rule be stated by verb with no argument analysis.
        for (verb, args) in [
            ("merge", vec!["origin/main"]),
            ("merge", vec!["--no-ff", "feature/x"]),
            ("merge", vec!["--squash", "feature/x"]),
            ("rebase", vec!["origin/main"]),
            ("rebase", vec!["-i", "HEAD~3"]),
            ("rebase", vec!["--onto", "main", "feature/x"]),
        ] {
            assert!(
                starts_a_head_move(verb, &tail(&args)),
                "expected `git {verb} {}` to start a HEAD move",
                args.join(" ")
            );
        }
    }

    #[test]
    fn starts_a_head_move_allows_in_progress_control() {
        // The carve-out: these resolve an operation that already started.
        // Denying them would park the shared checkout mid-rebase with no way
        // out, and the deny would carry no remedy that works from there.
        for (verb, args) in [
            ("rebase", vec!["--abort"]),
            ("rebase", vec!["--continue"]),
            ("rebase", vec!["--skip"]),
            ("rebase", vec!["--quit"]),
            ("rebase", vec!["--edit-todo"]),
            ("rebase", vec!["--show-current-patch"]),
            ("merge", vec!["--abort"]),
            ("merge", vec!["--quit"]),
            ("merge", vec!["--continue"]),
        ] {
            assert!(
                !starts_a_head_move(verb, &tail(&args)),
                "`git {verb} {}` resolves an in-progress operation and must be allowed",
                args.join(" ")
            );
        }
    }

    #[test]
    fn starts_a_head_move_ignores_everything_else() {
        // The false-positive boundary #5356 is the reminder for. `fetch` is the
        // remedy the deny offers and must never be classified (ADR-0048
        // decision 9); `checkout`/`switch` are deliberately out of this rule;
        // `merge-base` and `merge-tree` are separate subcommand names that read
        // without writing.
        for (verb, args) in [
            ("fetch", vec!["origin"]),
            ("fetch", vec!["--all", "--prune"]),
            ("status", vec!["--short"]),
            ("log", vec!["--oneline", "-20"]),
            ("diff", vec!["--stat"]),
            ("merge-base", vec!["main", "HEAD"]),
            ("merge-tree", vec!["main", "HEAD"]),
            ("checkout", vec!["main"]),
            ("switch", vec!["main"]),
            ("pull-request", vec![]),
            ("commit", vec!["-m", "wip"]),
        ] {
            assert!(
                !starts_a_head_move(verb, &tail(&args)),
                "`git {verb} {}` must not be treated as a HEAD move",
                args.join(" ")
            );
        }
    }

    #[test]
    fn starts_a_head_move_matches_in_progress_control_positionally() {
        // #5769: the carve-out used to scan the whole tail, so any command
        // carrying one of those strings anywhere — a commit message is the
        // realistic shape — exempted itself from the rule.
        for args in [
            vec!["-m", "--continue", "origin/main"],
            vec!["origin/main", "-m", "--abort"],
        ] {
            assert!(
                starts_a_head_move("merge", &tail(&args)),
                "`git merge {}` is a real merge and must still classify",
                args.join(" ")
            );
        }
        // The genuine form — the flag first — stays exempt.
        assert!(!starts_a_head_move("rebase", &tail(&["--continue"])));
    }

    /// [`main_checkout_head_move`] for a command the walker places.
    fn placed_head_move(command: &str, cwd: &Path) -> Option<(String, PathBuf, PathBuf)> {
        main_checkout_head_move(command, cwd).map(|r| r.expect("the walker places it"))
    }

    /// 🔴 REGRESSION (#9127 critic r4 HIGH): an unplaced `eval "cd <wt>"`
    /// placed the merge in the worktree, so no daemon query was made; zsh
    /// never runs that `cd`, and the merge lands on the main checkout.
    #[test]
    fn main_checkout_head_move_refuses_an_eval_it_cannot_place() {
        let main = main_checkout_dir();
        let wt = linked_worktree(main.path());
        let wt = wt.display();
        for command in [
            format!("command -p eval \"cd {wt}\"; git merge x"),
            format!("noglob eval \"cd {wt}\"; git rebase origin/main"),
        ] {
            let verdict = main_checkout_head_move(&command, main.path());
            assert!(
                matches!(&verdict, Some(Err(reason)) if reason.contains("cannot place it")),
                "`{command}` must be refused unplaced: {verdict:?}"
            );
        }
        // A parsed `cd` into the worktree still resolves nothing.
        let parsed = format!("cd {wt} && git merge x");
        assert_eq!(main_checkout_head_move(&parsed, main.path()), None);
    }

    #[test]
    fn main_checkout_head_move_resolves_a_subdirectory_to_the_checkout_root() {
        // #5769: a delegation record is stamped from `tm hook`'s own process
        // directory, so a command aimed at a subdirectory has to report the
        // checkout root as well or the query keys a directory no record matches.
        let checkout = main_checkout_dir();
        let sub = checkout.path().join("crates/foo");
        std::fs::create_dir_all(&sub).expect("mkdir sub");
        let (verb, target, root) = placed_head_move(
            &format!("cd {} && git merge origin/main", sub.display()),
            checkout.path(),
        )
        .expect("a merge from a subdirectory must resolve");
        assert_eq!(verb, "merge");
        assert_eq!(target, sub);
        assert_eq!(root, checkout.path());
    }

    #[test]
    fn main_checkout_head_move_finds_the_checkout_and_skips_a_worktree() {
        let checkout = main_checkout_dir();
        let (verb, target, root) = placed_head_move("git rebase origin/main", checkout.path())
            .expect("a rebase in a main checkout must resolve");
        assert_eq!(verb, "rebase");
        assert_eq!(target, checkout.path());
        assert_eq!(root, checkout.path());

        // A linked worktree carries a `.git` FILE. Its HEAD belongs to the one
        // session that owns it, so a rebase there races nothing and must resolve
        // nothing — this is the ordinary-work case the directory test protects.
        let worktree = tempfile::tempdir().expect("tempdir");
        std::fs::write(worktree.path().join(".git"), "gitdir: /elsewhere").expect("write .git");
        assert_eq!(
            placed_head_move("git rebase origin/main", worktree.path()),
            None
        );

        // Not a repository at all: nothing to protect.
        let plain = tempfile::tempdir().expect("tempdir");
        assert_eq!(placed_head_move("git merge main", plain.path()), None);
    }

    #[test]
    fn main_checkout_head_move_follows_cd_and_dash_c_and_later_segments() {
        let checkout = main_checkout_dir();
        let path = checkout.path().display();
        let outside = tempfile::tempdir().expect("tempdir");

        // `-C` and `cd` both aim the verb at a checkout the hook is not
        // standing in — the two overrides the sibling rules already close.
        let (_, via_dash_c, _) =
            placed_head_move(&format!("git -C {path} rebase origin/main"), outside.path())
                .expect("-C must move the target");
        assert_eq!(via_dash_c, checkout.path());

        let (_, via_cd, _) = placed_head_move(
            &format!("cd {path} && git merge origin/main"),
            outside.path(),
        )
        .expect("cd must move the target");
        assert_eq!(via_cd, checkout.path());

        // A benign leading verb must not hide the HEAD move behind it — this is
        // the ordinary `git fetch && git merge` shape, and since ADR-0053
        // `git pull && git merge` is one too: the permitted first segment must
        // not shield the second.
        for command in [
            "git fetch origin && git merge origin/main",
            "git pull && git merge origin/main",
        ] {
            let (verb, _, _) = placed_head_move(command, checkout.path())
                .expect("the second segment must be classified");
            assert_eq!(verb, "merge", "`{command}` must classify its merge");
        }
    }

    #[test]
    fn main_checkout_head_move_is_none_for_ordinary_work_in_a_checkout() {
        // Even inside a main checkout, everything that is not `merge` or
        // `rebase` resolves nothing and never reaches the daemon query.
        let checkout = main_checkout_dir();
        for command in [
            "git fetch origin",
            // ADR-0053: every pull form resolves nothing, so the daemon is
            // never asked and the answer cannot deny.
            "git pull",
            "git pull --ff-only",
            "git pull --rebase",
            "cd crates/foo && git pull",
            "git status --porcelain",
            "git log --oneline -5",
            "git worktree list",
            "cargo test -p trusty-mpm",
            "git rebase --abort",
            "",
        ] {
            assert_eq!(
                placed_head_move(command, checkout.path()),
                None,
                "`{command}` must not resolve a HEAD move"
            );
        }
    }

    #[test]
    fn head_move_deny_reason_names_the_verb_the_path_and_both_remedies() {
        let reason = head_move_deny_reason(
            "merge",
            Path::new("/repo/main"),
            &["rust-engineer".to_string(), "rust-engineer".to_string()],
        );
        assert!(reason.contains("ADR-0048"), "{reason}");
        assert!(reason.contains("git merge"), "{reason}");
        assert!(reason.contains("/repo/main"), "{reason}");
        // The sibling is named once, not repeated per delegation.
        assert_eq!(reason.matches("rust-engineer").count(), 1, "{reason}");
        // Both remedies: the cheap one (update the checkout in place) and the
        // general one (worktree). Since ADR-0053 the cheap one is two commands,
        // and naming only `fetch` would send a reader looking for a workaround
        // to a restriction that no longer exists.
        assert!(reason.contains("git fetch"), "{reason}");
        assert!(reason.contains("git pull"), "{reason}");
        assert!(reason.contains("ADR-0053"), "{reason}");
        assert!(reason.contains(r#"isolation: "worktree""#), "{reason}");
    }

    #[test]
    fn head_move_deny_reason_attributes_the_claim_to_the_daemon() {
        // #5769: this process knows what the daemon's records SAY, never what
        // another agent is doing. A record can outlive its agent, and a grant
        // whose isolation POST failed is recorded unisolated — so stating the
        // claim as fact made the deny assert something it could not check.
        let reason = head_move_deny_reason("merge", Path::new("/repo/main"), &["qa".to_string()]);
        assert!(
            reason.contains("the daemon's delegation records name"),
            "the claim must be attributed to its source: {reason}"
        );
        assert!(
            !reason.contains("is already writing there"),
            "the deny must not assert another agent's behaviour as fact: {reason}"
        );
    }

    #[test]
    fn deny_reason_names_the_verb_the_path_and_the_remedy() {
        let reason = deny_reason("clean", Path::new("/repo/main"));
        assert!(reason.contains("ADR-0037"), "{reason}");
        assert!(reason.contains("git clean"), "{reason}");
        assert!(reason.contains("/repo/main"), "{reason}");
        assert!(reason.contains(".claude/worktrees"), "{reason}");
        assert!(reason.contains(r#"isolation: "worktree""#), "{reason}");
    }
}