eidetic-engine 0.15.1

Durable, local-first, explainable memory for coding agents.
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
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
//! `doctor_runtime` — the single `mutate()` chokepoint for `ee doctor --fix`.
//!
//! Pass-1 scaffolding from the world-class-doctor-mode workspace at
//! `doctor_workspace/`. This module implements the foundational primitives the
//! upgraded doctor will route every state-changing operation through:
//!
//! - `RunContext`     — one per `ee doctor --fix` invocation; owns the
//!   `.doctor/runs/<run-id>/` directory and an OS advisory lock on the
//!   persistent `<workspace>/.ee/.doctor.lock` file.
//! - `Op`             — the closed set of write-flavored operations. The
//!   Phase-2 repair specs reference these variants verbatim.
//! - `mutate()`       — the chokepoint. Every fixer must call this; nothing
//!   else may write to disk under `--fix`. Each call captures a verbatim
//!   backup, hashes before/after with blake3, appends an entry to
//!   `actions.jsonl`, and performs the mutation atomically.
//! - `replay_undo()`  — reads `actions.jsonl` in reverse and restores each
//!   touched file from its backup, verifying hashes at every step.
//! - `CapabilitiesReport` — the agent-facing contract printed by
//!   `ee doctor capabilities --json` (Phase 6 wires the CLI surface).
//!
//! ## Polish Bar coverage (per the world-class-doctor-mode skill)
//!
//! - 🩺 Detect-then-fix: this module is the FIX side; detectors live in
//!   `core::doctor` and stay pure (no writes).
//! - 🚪 Single chokepoint: all writes route through `mutate()`. The
//!   blast-radius unit test (`tests::no_external_writes_in_mutate`) asserts
//!   the only `std::fs` write sites inside the runtime are inside `mutate()`.
//! - 💾 Verbatim backup before mutate.
//! - ↩ Inverse pair: `actions.jsonl` + `replay_undo()`.
//! - 🔁 Idempotent-twice: second `mutate()` call observes the after-hash
//!   matches the desired state and reports `no_op` instead of re-writing.
//! - ⚡ Crash-mid-fix: tempfile-rename is atomic. SIGKILL during a `mutate()`
//!   leaves either the unchanged original or the fully-written new file
//!   on disk; never a partial write.
//! - 🔒 Lock-or-refuse: `RunContext::start` refuses with
//!   `DoctorRuntimeError::ConcurrencyLost` if a sibling lock is held.
//! - 🆔 Unique run-id: timestamp + per-process sequence + hash witness.
//! - 🔢 Hash-witnessed: blake3 before/after in `actions.jsonl`.
//! - 🛡 Refuse-on-unsafe: `mutate()` validates `path` is inside the
//!   declared blast radius before doing anything.
//!
//! Pass 1 deliberately does NOT wire the CLI surface (`ee doctor --fix`,
//! `ee doctor undo`, etc.) — that requires edits to the 52k-line
//! `src/cli/mod.rs` and is queued as a follow-up bead. The chokepoint is
//! self-contained, fully testable, and ready for the wiring pass.

use std::ffi::{OsStr, OsString};
use std::fs;
use std::io::{self, Read, Seek, SeekFrom, Write};
use std::path::{Component, Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};

use chrono::Utc;
#[cfg(any(
    target_os = "linux",
    target_os = "android",
    target_vendor = "apple",
    windows
))]
use fs4::FileExt as Fs4FileExt;
use serde::{Deserialize, Serialize};

/// Public schema string for the doctor capabilities report. Bump only on a
/// breaking contract change; additive changes keep `v1`.
pub const CAPABILITIES_SCHEMA_V1: &str = "ee.doctor.capabilities.v1";

/// Public schema string for `actions.jsonl` lines.
pub const ACTION_LINE_SCHEMA_V1: &str = "ee.doctor.action.v1";

/// Public schema string for the run state file (`<run-dir>/state.json`).
pub const RUN_STATE_SCHEMA_V2: &str = "ee.doctor.run_state.v2";

/// Stable contents written only when doctor atomically creates the persistent
/// advisory-lock inode. Reacquisition never rewrites an existing path because
/// it may have been substituted by a same-user peer between runs.
const DOCTOR_LOCK_FILE_MARKER: &str = "ee.doctor.persistent_lock.v1\n";

static DOCTOR_RUN_ID_SEQUENCE: AtomicU64 = AtomicU64::new(0);
#[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))]
static DOCTOR_STATE_FILE_SEQUENCE: AtomicU64 = AtomicU64::new(0);
#[cfg(test)]
std::thread_local! {
    static DOCTOR_LOCK_BEFORE_UNLOCK_HOOK:
        std::cell::RefCell<Option<Box<dyn FnOnce()>>> =
        const { std::cell::RefCell::new(None) };
    static DOCTOR_LOCK_FAIL_NEXT_WRITE: std::cell::Cell<bool> =
        const { std::cell::Cell::new(false) };
}

/// Canonical doctor-runtime errors. The CLI wiring maps unsafe-path errors
/// (`BlastRadiusExceeded`, `SymlinkedRunRoot`, `LifecycleRootChanged`, and
/// `UnsafeLatestEntry`) to `ProcessExitCode::PolicyDenied` (7), storage and
/// backup failures to `ProcessExitCode::Storage` (3), and concurrency/no-op
/// outcomes to `ProcessExitCode::Configuration` (2).
#[derive(Debug)]
pub enum DoctorRuntimeError {
    /// The target path is outside the declared blast radius.
    BlastRadiusExceeded {
        path: PathBuf,
        allowed_roots: Vec<PathBuf>,
    },
    /// Another doctor run is already in progress.
    ConcurrencyLost {
        lock_path: PathBuf,
        holder_run_id: Option<String>,
    },
    /// The `.doctor/runs/<run-id>/backups/` dir cannot be created or written.
    BackupDirUnwritable { dir: PathBuf, source: io::Error },
    /// A workspace lifecycle path (`.ee`, `.doctor`, or one of their
    /// descendants) traverses an existing symbolic link. Doctor refuses
    /// before creating a lock or run artifact so a redirected root cannot
    /// escape the canonical workspace.
    SymlinkedRunRoot { path: PathBuf },
    /// A lifecycle directory no longer resolves to the directory descriptor
    /// opened by `RunContext::start`. This detects rename-and-substitute races
    /// before any path-based backup or quarantine operation can follow the
    /// replacement tree.
    LifecycleRootChanged { path: PathBuf },
    /// `<workspace>/.doctor/latest` is not safe to replace. In particular,
    /// doctor never removes or overwrites a regular file at this path.
    UnsafeLatestEntry {
        path: PathBuf,
        observed_kind: String,
    },
    /// Underlying I/O failure (open/read/write/rename).
    Io { context: String, source: io::Error },
    /// The `actions.jsonl` is malformed during an undo.
    ActionsLogCorrupt { line_number: usize, reason: String },
    /// A caller supplied a run identifier that is not one opaque path
    /// component. Run IDs are data, never paths.
    InvalidRunId { run_id: String, reason: String },
    /// A persisted doctor run artifact does not bind to the workspace/run the
    /// caller selected, or violates the run-ledger contract.
    RunArtifactInvalid { path: PathBuf, reason: String },
    /// The operator supplied an invalid doctor blast-radius override.
    InvalidBlastRadius { reason: String },
    /// Dry-run actions describe a hypothetical plan and never changed the
    /// filesystem. Replaying them as real inverses would target unrelated
    /// state created after the plan was recorded.
    DryRunNotUndoable { run_id: String },
    /// During undo, the on-disk after_hash didn't match what `actions.jsonl`
    /// recorded — something outside the doctor mutated the file.
    UndoStateDrifted {
        path: PathBuf,
        expected_hash: String,
        observed_hash: String,
    },
    /// During undo, the on-disk backup is missing or its hash doesn't match
    /// the recorded before_hash.
    UndoBackupCorrupt {
        backup_path: PathBuf,
        expected_hash: String,
        observed_hash: Option<String>,
    },
    /// Finalization failed and the runtime was also unable to persist the
    /// terminal `failed` state. Both failures are retained so callers never
    /// lose the original cause while diagnosing the incomplete run.
    FinishStateUpdateFailed {
        finish_error: Box<DoctorRuntimeError>,
        state_error: Box<DoctorRuntimeError>,
    },
    /// The fixer planned a write but the target's current bytes already match
    /// the desired bytes. Not an error — the caller can treat this as
    /// "idempotent no-op".
    NoOpIdempotent,
}

impl std::fmt::Display for DoctorRuntimeError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::BlastRadiusExceeded {
                path,
                allowed_roots,
            } => write!(
                f,
                "doctor refused write to {}: outside blast radius (allowed roots: {})",
                path.display(),
                allowed_roots
                    .iter()
                    .map(|p| p.display().to_string())
                    .collect::<Vec<_>>()
                    .join(", ")
            ),
            Self::ConcurrencyLost {
                lock_path,
                holder_run_id,
            } => match holder_run_id {
                Some(rid) => write!(
                    f,
                    "doctor lock held at {} (run_id={}); refusing concurrent fix",
                    lock_path.display(),
                    rid
                ),
                None => write!(
                    f,
                    "doctor lock held at {} (holder unknown); refusing concurrent fix",
                    lock_path.display()
                ),
            },
            Self::BackupDirUnwritable { dir, source } => write!(
                f,
                "cannot write doctor backups under {}: {}",
                dir.display(),
                source
            ),
            Self::SymlinkedRunRoot { path } => write!(
                f,
                "doctor refused lifecycle path {}: symbolic-link components are not allowed",
                path.display()
            ),
            Self::LifecycleRootChanged { path } => write!(
                f,
                "doctor refused lifecycle path {}: it no longer resolves to the directory opened at run start",
                path.display()
            ),
            Self::UnsafeLatestEntry {
                path,
                observed_kind,
            } => write!(
                f,
                "doctor refused to replace {}: expected a symbolic link or an absent entry, observed {}",
                path.display(),
                observed_kind
            ),
            Self::Io { context, source } => {
                write!(f, "doctor I/O failure ({}): {}", context, source)
            }
            Self::ActionsLogCorrupt {
                line_number,
                reason,
            } => write!(
                f,
                "actions.jsonl corrupt at line {}: {}",
                line_number, reason
            ),
            Self::InvalidRunId { run_id, reason } => {
                write!(f, "invalid doctor run id {run_id:?}: {reason}")
            }
            Self::RunArtifactInvalid { path, reason } => write!(
                f,
                "doctor run artifact {} is invalid: {}",
                path.display(),
                reason
            ),
            Self::InvalidBlastRadius { reason } => {
                write!(f, "invalid doctor blast radius: {reason}")
            }
            Self::DryRunNotUndoable { run_id } => write!(
                f,
                "doctor run {run_id:?} is a dry-run plan and has no filesystem mutations to undo"
            ),
            Self::UndoStateDrifted {
                path,
                expected_hash,
                observed_hash,
            } => write!(
                f,
                "undo: {} drifted after the doctor run (expected after_hash={}, observed={})",
                path.display(),
                expected_hash,
                observed_hash
            ),
            Self::UndoBackupCorrupt {
                backup_path,
                expected_hash,
                observed_hash,
            } => match observed_hash {
                Some(h) => write!(
                    f,
                    "undo: backup at {} hash mismatch (expected before_hash={}, observed={})",
                    backup_path.display(),
                    expected_hash,
                    h
                ),
                None => write!(
                    f,
                    "undo: backup at {} missing (expected before_hash={})",
                    backup_path.display(),
                    expected_hash
                ),
            },
            Self::FinishStateUpdateFailed {
                finish_error,
                state_error,
            } => write!(
                f,
                "doctor finalization failed ({finish_error}); additionally failed to persist terminal run state ({state_error})"
            ),
            Self::NoOpIdempotent => {
                write!(f, "idempotent no-op: target already in desired state")
            }
        }
    }
}

impl std::error::Error for DoctorRuntimeError {}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DoctorRuntimeFailureClass {
    Configuration,
    Storage,
    Policy,
}

impl DoctorRuntimeError {
    /// Stable machine-readable classification for doctor runtime receipts.
    #[must_use]
    pub const fn code(&self) -> &'static str {
        match self {
            Self::BlastRadiusExceeded { .. } => "doctor_blast_radius_exceeded",
            Self::ConcurrencyLost { .. } => "doctor_concurrency_lost",
            Self::BackupDirUnwritable { .. } => "doctor_backup_directory_unwritable",
            Self::SymlinkedRunRoot { .. } => "doctor_run_root_symlink_refused",
            Self::LifecycleRootChanged { .. } => "doctor_run_root_changed",
            Self::UnsafeLatestEntry { .. } => "doctor_latest_entry_unsafe",
            Self::Io { .. } => "doctor_runtime_io",
            Self::ActionsLogCorrupt { .. } => "doctor_actions_log_corrupt",
            Self::InvalidRunId { .. } => "doctor_run_id_invalid",
            Self::RunArtifactInvalid { .. } => "doctor_run_artifact_invalid",
            Self::InvalidBlastRadius { .. } => "doctor_blast_radius_env_invalid",
            Self::DryRunNotUndoable { .. } => "doctor_dry_run_not_undoable",
            Self::UndoStateDrifted { .. } => "doctor_undo_state_drifted",
            Self::UndoBackupCorrupt { .. } => "doctor_undo_backup_corrupt",
            Self::FinishStateUpdateFailed { .. } => "doctor_finish_state_update_failed",
            Self::NoOpIdempotent => "doctor_runtime_noop",
        }
    }

    #[must_use]
    pub const fn failure_class(&self) -> DoctorRuntimeFailureClass {
        match self {
            Self::BlastRadiusExceeded { .. }
            | Self::SymlinkedRunRoot { .. }
            | Self::LifecycleRootChanged { .. }
            | Self::UnsafeLatestEntry { .. } => DoctorRuntimeFailureClass::Policy,
            Self::ConcurrencyLost { .. }
            | Self::InvalidBlastRadius { .. }
            | Self::DryRunNotUndoable { .. }
            | Self::NoOpIdempotent => DoctorRuntimeFailureClass::Configuration,
            Self::BackupDirUnwritable { .. }
            | Self::Io { .. }
            | Self::ActionsLogCorrupt { .. }
            | Self::InvalidRunId { .. }
            | Self::RunArtifactInvalid { .. }
            | Self::UndoStateDrifted { .. }
            | Self::UndoBackupCorrupt { .. }
            | Self::FinishStateUpdateFailed { .. } => DoctorRuntimeFailureClass::Storage,
        }
    }
}

impl From<io::Error> for DoctorRuntimeError {
    fn from(source: io::Error) -> Self {
        Self::Io {
            context: "underlying I/O".into(),
            source,
        }
    }
}

/// The mutation operation the chokepoint will perform. Each variant
/// corresponds to a row in Phase 2's per-FM op tables.
///
/// The closed-set design is intentional: a new mutation kind requires a
/// pull request that updates this enum AND the conformance test in
/// `tests/doctor_blast_radius.rs`, ensuring every write path is reviewed.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Op {
    /// Atomic write of arbitrary bytes (file may or may not exist).
    /// Used for config rewrites, JSONL rewrites, manifest writes.
    WriteFile { bytes: Vec<u8> },

    /// Create a directory tree with the specified mode (mode is advisory
    /// on platforms that don't support it; recorded for audit).
    CreateDirAll { mode: u32 },

    /// Change file permissions (mode bits).
    Chmod { mode: u32 },

    /// AGENTS.md RULE 1: doctor never deletes. To remove a file from a
    /// canonical location, rename it under
    /// `.doctor/runs/<run-id>/quarantine/<rel-path>`.
    QuarantineByRename { dest_under_quarantine: PathBuf },

    /// Manual op: the fixer surfaces guidance only; doctor never executes.
    /// `mutate()` records the manual finding in `actions.jsonl` but
    /// performs no disk write. Used for refused-unsafe and observability
    /// findings.
    Manual { steps: Vec<String> },

    /// Diagnostic-only: emit a structured finding to the run report; no
    /// disk write of any kind. The only Op that can safely run when the
    /// blast-radius check would otherwise refuse.
    EmitDiagnostic { code: String, severity: String },

    /// Run the search-index rebuild pipeline. Phase-1 (bd-tu4s8): records
    /// the planned rebuild as actions.jsonl evidence with manual operator
    /// steps until the subsystem actor handle lands; the doctor never
    /// directly performs the rebuild from this Op today.
    RunIndexRebuild { steps: Vec<String> },

    /// Refresh the graph snapshot subsystem. Phase-1 (bd-tu4s8): records
    /// the planned refresh as evidence with manual operator steps.
    RunGraphRefresh { steps: Vec<String> },

    /// Run a WAL checkpoint of the requested mode. Phase-1 (bd-tu4s8):
    /// records the planned checkpoint as evidence; subsystem actor
    /// wiring lands in a follow-up slice.
    RunWalCheckpoint { mode: String, steps: Vec<String> },

    /// Run pending schema migrations. Phase-1 (bd-tu4s8): records the
    /// planned migration as evidence; subsystem actor wiring lands in
    /// a follow-up slice.
    RunMigration {
        target_version: String,
        steps: Vec<String>,
    },

    /// Atomically rewrite a JSONL file as `rows` (idempotent). Phase-1
    /// (bd-tu4s8): records the planned rewrite as evidence with manual
    /// operator steps; subsystem-aware rewrite lands in a follow-up.
    RewriteJsonl {
        row_count: usize,
        steps: Vec<String>,
    },

    /// Atomically rewrite a TOML file. Phase-1 (bd-tu4s8): records the
    /// planned rewrite as evidence with manual operator steps; the
    /// format-preserving toml_edit driver lands in a follow-up slice.
    AtomicRewriteToml { steps: Vec<String> },

    /// Take a pre-mutation full snapshot backup. Phase-1 (bd-tu4s8):
    /// records the planned snapshot as evidence with manual operator
    /// steps; the backup writer actor lands in a follow-up slice.
    SnapshotBackup { label: String, steps: Vec<String> },
}

impl Op {
    /// Operations that produce verbatim disk writes (require backup + hash).
    #[must_use]
    pub const fn is_writing(&self) -> bool {
        matches!(
            self,
            Self::WriteFile { .. }
                | Self::Chmod { .. }
                | Self::QuarantineByRename { .. }
                | Self::CreateDirAll { .. }
        )
    }

    /// Operations that have no inverse beyond "do nothing".
    #[must_use]
    pub const fn is_advisory(&self) -> bool {
        matches!(
            self,
            Self::Manual { .. }
                | Self::EmitDiagnostic { .. }
                | Self::RunIndexRebuild { .. }
                | Self::RunGraphRefresh { .. }
                | Self::RunWalCheckpoint { .. }
                | Self::RunMigration { .. }
                | Self::RewriteJsonl { .. }
                | Self::AtomicRewriteToml { .. }
                | Self::SnapshotBackup { .. }
        )
    }

    /// Stable lowercase wire form for `kind` field.
    #[must_use]
    pub const fn kind_str(&self) -> &'static str {
        match self {
            Self::WriteFile { .. } => "write_file",
            Self::CreateDirAll { .. } => "create_dir_all",
            Self::Chmod { .. } => "chmod",
            Self::QuarantineByRename { .. } => "quarantine_by_rename",
            Self::Manual { .. } => "manual",
            Self::EmitDiagnostic { .. } => "emit_diagnostic",
            Self::RunIndexRebuild { .. } => "run_index_rebuild",
            Self::RunGraphRefresh { .. } => "run_graph_refresh",
            Self::RunWalCheckpoint { .. } => "run_wal_checkpoint",
            Self::RunMigration { .. } => "run_migration",
            Self::RewriteJsonl { .. } => "rewrite_jsonl",
            Self::AtomicRewriteToml { .. } => "atomic_rewrite_toml",
            Self::SnapshotBackup { .. } => "snapshot_backup",
        }
    }
}

/// One line of `actions.jsonl`. Serialized to disk in append-only fashion;
/// read in reverse during undo.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ActionLine {
    /// Schema pin so future contract bumps can be detected.
    pub schema: String,
    /// `run_id` of the parent `RunContext`.
    pub run_id: String,
    /// Action index within the run (1-based).
    pub sequence: u64,
    /// Absolute path the action targeted.
    pub path: PathBuf,
    /// `kind` (matches `Op::kind_str()`).
    pub kind: String,
    /// blake3 hex of bytes BEFORE the action (None when the file did not
    /// exist).
    pub before_hash: Option<String>,
    /// blake3 hex of bytes AFTER the action (None for QuarantineByRename of
    /// existing files — the after state is "not present").
    pub after_hash: Option<String>,
    /// Backup path (relative to the run dir's `backups/` root).
    pub backup_rel_path: Option<PathBuf>,
    /// For Chmod actions, the before/after mode bits.
    pub before_mode: Option<u32>,
    pub after_mode: Option<u32>,
    /// For QuarantineByRename, the quarantine destination (relative to
    /// `quarantine/`).
    pub quarantine_dest_rel: Option<PathBuf>,
    /// RFC 3339 UTC timestamp when the action committed.
    pub committed_at: String,
    /// Free-form notes (for Manual / EmitDiagnostic).
    pub notes: Option<String>,
}

/// State of the run, serialized to `<run-dir>/state.json`.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RunState {
    pub schema: String,
    pub run_id: String,
    pub target_sha: String,
    pub workspace: PathBuf,
    pub started_at: String,
    pub finished_at: Option<String>,
    pub status: RunStatus,
    pub action_count: u64,
    pub dry_run: bool,
    /// Canonical roots that authorized mutations when the run was created.
    /// Replay intersects these with the operator's current authorization so
    /// neither a widened environment nor a tampered action ledger can expand
    /// an old run's original write surface.
    pub blast_radius_roots: Vec<PathBuf>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RunStatus {
    Running,
    CompletedOk,
    CompletedPartial,
    Failed,
    Undone,
    UndonePartial,
}

#[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))]
#[derive(Debug)]
struct DoctorLifecycleHandles {
    workspace_dir: fs::File,
    ee_dir: fs::File,
    lock_file: fs::File,
    doctor_dir: fs::File,
    runs_dir: fs::File,
    run_dir: fs::File,
    backups_dir: fs::File,
    quarantine_dir: fs::File,
}

#[cfg(windows)]
#[derive(Debug)]
struct DoctorLifecycleHandles {
    lock_file: fs::File,
}

#[cfg(not(any(
    target_os = "linux",
    target_os = "android",
    target_vendor = "apple",
    windows
)))]
#[derive(Debug)]
struct DoctorLifecycleHandles;

/// One `ee doctor --fix` invocation's state. Owns the advisory lock handle and
/// the `.doctor/runs/<run-id>/` directory.
#[derive(Debug)]
pub struct RunContext {
    run_id: String,
    // Round-5 self-review: `target_sha` used to live here too, but the same
    // value is already persisted in `state.target_sha` (which IS used —
    // serialized to state.json). The struct-field copy was write-only and
    // surfaced a `field never read` clippy warning. Drop it; if a caller
    // ever needs to recover the target_sha at runtime, `ctx.state.target_sha`
    // is the canonical source.
    workspace: PathBuf,
    run_dir: PathBuf,
    lock_path: PathBuf,
    lifecycle: DoctorLifecycleHandles,
    state: RunState,
    actions_handle: Option<fs::File>,
    blast_radius_roots: Vec<PathBuf>,
    dry_run: bool,
    // True between successful advisory-lock acquisition and release.
    // `finish()` flips this to false only after explicitly unlocking the
    // retained file handle so the `Drop` impl below can distinguish:
    //
    //   - normal teardown via `finish()` → already released, no-op.
    //   - error/panic teardown via implicit drop → lock held, unlock it.
    //
    // Critically the flip happens only AFTER a successful release. If release
    // fails, `finish()` propagates the error with this flag still true so Drop
    // performs one final best-effort retry.
    lock_owned: bool,
}

impl Drop for RunContext {
    fn drop(&mut self) {
        // RunContext owns the advisory lock for its lifetime. `finish()` is
        // the canonical release path and flips `lock_owned` to false. If
        // `finish()` was never called because the caller propagated an error,
        // a panic unwound, or a future code path forgot to finish, dropping the
        // retained handle releases the OS lock. The persistent public lock
        // path is deliberately never unlinked, renamed, or overwritten here:
        // a same-user peer may have substituted that name at any point.
        //
        // A destructor cannot report an I/O error, so only this final
        // best-effort unlock intentionally discards a release failure;
        // `finish()` itself always propagates one.
        if self.lock_owned {
            let _ = release_doctor_lock(&self.lifecycle, &self.lock_path);
        }
    }
}

impl RunContext {
    /// Open a new run. Acquires the lock; refuses with `ConcurrencyLost` if
    /// held. Creates the `.doctor/runs/<run-id>/{backups,quarantine}` tree.
    ///
    /// `blast_radius_roots` is the set of directories `mutate()` is allowed
    /// to write to. The lock file and the run dir itself are always
    /// implicitly allowed.
    pub fn start(
        workspace: &Path,
        target_sha: &str,
        blast_radius_roots: Vec<PathBuf>,
        dry_run: bool,
    ) -> Result<Self, DoctorRuntimeError> {
        // Resolve the workspace to one canonical directory before deriving
        // any lifecycle path. This prevents relative-path drift between
        // `--fix` and `--undo` and removes platform aliases such as macOS
        // `/var -> /private/var` from the path used by the no-follow walk.
        // The input leaf itself is still rejected when it is a symlink.
        let workspace_buf = canonical_doctor_workspace(workspace)?;
        let workspace = workspace_buf.as_path();
        let blast_radius_roots =
            normalize_blast_radius_roots(workspace, &blast_radius_roots, true)?;

        let run_id = derive_run_id(target_sha);
        let started_at = Utc::now().to_rfc3339();
        let ee_dir = workspace.join(".ee");
        let lock_path = ee_dir.join(".doctor.lock");
        let doctor_dir = workspace.join(".doctor");
        let runs_dir = doctor_dir.join("runs");
        let run_dir = runs_dir.join(&run_id);
        let backups_dir = run_dir.join("backups");
        let quarantine_dir = run_dir.join("quarantine");
        let actions_path = run_dir.join("actions.jsonl");
        let state_path = run_dir.join("state.json");

        // This entire scan runs before `.ee` creation, lock acquisition, or
        // run-directory allocation. A pre-existing redirect therefore fails
        // closed without touching either the workspace or the symlink target.
        validate_doctor_lifecycle_paths([
            workspace,
            ee_dir.as_path(),
            lock_path.as_path(),
            doctor_dir.as_path(),
            runs_dir.as_path(),
            run_dir.as_path(),
            backups_dir.as_path(),
            quarantine_dir.as_path(),
            actions_path.as_path(),
            state_path.as_path(),
        ])?;

        let (lifecycle, actions_handle) =
            prepare_doctor_lifecycle(workspace, &run_id, &lock_path, &run_dir)?;
        if let Err(error) = ensure_doctor_lifecycle_bindings(&lifecycle, workspace, &run_dir) {
            let _ = release_doctor_lock(&lifecycle, &lock_path);
            return Err(error);
        }

        let state = RunState {
            schema: RUN_STATE_SCHEMA_V2.into(),
            run_id: run_id.clone(),
            target_sha: target_sha.into(),
            workspace: workspace.to_path_buf(),
            started_at,
            finished_at: None,
            status: RunStatus::Running,
            action_count: 0,
            dry_run,
            blast_radius_roots: blast_radius_roots.clone(),
        };
        if let Err(e) = write_lifecycle_state(&lifecycle, &run_dir, &state) {
            let _ = release_doctor_lock(&lifecycle, &lock_path);
            return Err(e);
        }

        Ok(Self {
            run_id,
            workspace: workspace.to_path_buf(),
            run_dir,
            lock_path,
            lifecycle,
            state,
            actions_handle: Some(actions_handle),
            blast_radius_roots,
            dry_run,
            lock_owned: true,
        })
    }

    /// The opaque run identifier ( `<6-hex>` ).
    #[must_use]
    pub fn run_id(&self) -> &str {
        &self.run_id
    }

    /// Run directory under `<workspace>/.doctor/runs/`.
    #[must_use]
    pub fn run_dir(&self) -> &Path {
        &self.run_dir
    }

    /// Whether this run is in dry-run mode (no disk mutations except the
    /// lock + state file + actions.jsonl entries which we still record so
    /// the plan is fully visible).
    #[must_use]
    pub const fn dry_run(&self) -> bool {
        self.dry_run
    }

    /// Mark the run complete. Releases the lock. Updates `state.json` and
    /// flushes `actions.jsonl`. The symlink `<workspace>/.doctor/latest` is
    /// updated atomically to point at this run.
    pub fn finish(mut self, status: RunStatus) -> Result<RunSummary, DoctorRuntimeError> {
        let finish_result = (|| {
            ensure_doctor_lifecycle_bindings(&self.lifecycle, &self.workspace, &self.run_dir)?;

            self.state.finished_at = Some(Utc::now().to_rfc3339());
            self.state.status = status.clone();
            write_lifecycle_state(&self.lifecycle, &self.run_dir, &self.state)?;

            // Flush the actions log.
            if let Some(mut h) = self.actions_handle.take() {
                h.flush().map_err(|source| DoctorRuntimeError::Io {
                    context: "flush actions.jsonl".into(),
                    source,
                })?;
            }

            // Update `latest` through the descriptor-anchored lifecycle root.
            // On Linux and Apple platforms this uses an atomic no-replace or
            // exchange rename. A displaced entry is retained inside this run
            // directory; doctor never deletes an existing `latest` entry.
            let latest_link = self.workspace.join(".doctor").join("latest");
            ensure_doctor_lifecycle_bindings(&self.lifecycle, &self.workspace, &self.run_dir)?;
            publish_doctor_latest(&self.lifecycle, &self.run_id, &self.run_dir, &latest_link)?;
            // Do not return a lexical run path after a concurrent namespace
            // substitution. Publishing is descriptor-anchored, so a race
            // cannot escape, but the summary must fail closed instead of
            // reporting a path that now resolves somewhere else.
            ensure_doctor_lifecycle_bindings(&self.lifecycle, &self.workspace, &self.run_dir)?;

            // Clear ownership only after release succeeds. On failure, the
            // typed I/O error is returned while `lock_owned` remains true,
            // causing Drop to make one final best-effort retry.
            release_doctor_lock(&self.lifecycle, &self.lock_path).map_err(|source| {
                DoctorRuntimeError::Io {
                    context: format!("release doctor lock {}", self.lock_path.display()),
                    source,
                }
            })?;
            self.lock_owned = false;
            Ok(())
        })();

        if let Err(finish_error) = finish_result {
            // A run is not completed merely because its requested terminal
            // status was written before a later flush, publication, binding,
            // or lock-release failure. Persist the truthful terminal state
            // through the descriptor-anchored run handle before returning.
            self.state
                .finished_at
                .get_or_insert_with(|| Utc::now().to_rfc3339());
            self.state.status = RunStatus::Failed;
            if let Err(state_error) =
                write_lifecycle_state(&self.lifecycle, &self.run_dir, &self.state)
            {
                return Err(DoctorRuntimeError::FinishStateUpdateFailed {
                    finish_error: Box::new(finish_error),
                    state_error: Box::new(state_error),
                });
            }
            return Err(finish_error);
        }

        Ok(RunSummary {
            run_id: self.run_id.clone(),
            run_dir: self.run_dir.clone(),
            action_count: self.state.action_count,
            status,
        })
    }
}

/// A run lifecycle ends with this small summary value.
#[derive(Clone, Debug)]
pub struct RunSummary {
    pub run_id: String,
    pub run_dir: PathBuf,
    pub action_count: u64,
    pub status: RunStatus,
}

/// THE chokepoint. Every fixer must funnel writes through this function.
///
/// Steps:
/// 1. Validate `path` against the run's blast radius. Refuse with
///    `BlastRadiusExceeded` if outside.
/// 2. Capture `before_hash` and (when the path exists) a verbatim backup.
/// 3. Apply the op:
///    - `WriteFile`: atomic tempfile-rename.
///    - `Chmod`: `fs::set_permissions`.
///    - `CreateDirAll`: `fs::create_dir_all`.
///    - `QuarantineByRename`: `fs::rename` to `<run-dir>/quarantine/<dest>`.
///    - `Manual` / `EmitDiagnostic`: no disk write; just record.
/// 4. Capture `after_hash`.
/// 5. Append the action to `actions.jsonl`.
/// 6. Increment `ctx.state.action_count` and persist `state.json`.
///
/// For idempotence: if the on-disk state already matches the desired state
/// (same bytes for `WriteFile`, same mode for `Chmod`, target already gone
/// for `QuarantineByRename`), returns `NoOpIdempotent` and records nothing.
pub fn mutate(ctx: &mut RunContext, path: &Path, op: Op) -> Result<ActionLine, DoctorRuntimeError> {
    ensure_doctor_lifecycle_bindings(&ctx.lifecycle, &ctx.workspace, &ctx.run_dir)?;

    // Every writing action is later replayed by path from actions.jsonl. A
    // relative path may pass the blast-radius check when the current directory
    // is inside an allowed root, but undo from a different current directory
    // would then target a different filesystem location. Refuse before backup,
    // mutation, or logging.
    if op.is_writing() && !path.is_absolute() {
        return Err(DoctorRuntimeError::BlastRadiusExceeded {
            path: path.to_path_buf(),
            allowed_roots: ctx.blast_radius_roots.clone(),
        });
    }

    // Blast-radius check. Advisory ops (Manual/EmitDiagnostic) skip this so
    // the doctor can emit observability findings about external state.
    if op.is_writing() && !is_path_in_blast_radius(path, &ctx.blast_radius_roots) {
        return Err(DoctorRuntimeError::BlastRadiusExceeded {
            path: path.to_path_buf(),
            allowed_roots: ctx.blast_radius_roots.clone(),
        });
    }

    let before_hash = if path.exists() && path.is_file() {
        Some(hash_file(path)?)
    } else {
        None
    };
    let before_mode = read_mode(path);

    // Round-3 self-review (Bug #1): pre-check idempotence BEFORE staging a
    // backup. Previously `stage_backup` ran unconditionally for writing ops
    // on existing files; if a NoOpIdempotent fired in the match arm below,
    // the backup directory was created on disk but no action was recorded,
    // and a subsequent mutate at the same sequence would trip the collision
    // check in `stage_backup`. Round-3 also moves validation of
    // `Op::QuarantineByRename`'s destination here so it errors before the
    // backup is staged, and adds the missing destination-collision check
    // (Bug #4) so two QuarantineByRename ops with the same dest in one run
    // can't silently overwrite each other (`fs::rename` replaces on Unix).
    match &op {
        Op::WriteFile { bytes } => {
            if let Some(existing) = before_hash.as_deref() {
                if hash_bytes(bytes) == existing {
                    return Err(DoctorRuntimeError::NoOpIdempotent);
                }
            }
        }
        Op::Chmod { mode } => {
            #[cfg(unix)]
            {
                // Bug #2: `read_mode` returns the full `st_mode` (with
                // file-type bits like `0o100000` for regular files), while
                // the user-supplied `mode` is just the permission bits.
                // Comparing them directly never matched, so the documented
                // idempotence was unreachable in practice. Mask both to the
                // permission-bit window (0o7777 covers sticky/setuid/setgid
                // plus user/group/other rwx).
                let cur = before_mode.map(|m| m & 0o7777);
                let want = *mode & 0o7777;
                if cur == Some(want) {
                    return Err(DoctorRuntimeError::NoOpIdempotent);
                }
            }
        }
        Op::CreateDirAll { .. } => {
            if path.is_dir() {
                return Err(DoctorRuntimeError::NoOpIdempotent);
            }
        }
        Op::QuarantineByRename {
            dest_under_quarantine,
        } => {
            if !path.exists() {
                return Err(DoctorRuntimeError::NoOpIdempotent);
            }
            // Path-traversal defense — round-1 fresh-eyes.
            validate_relative_quarantine_dest(dest_under_quarantine, &ctx.run_dir)?;
            #[cfg(not(any(target_os = "linux", target_os = "android", target_vendor = "apple")))]
            {
                // The supported Unix path below performs this check and the
                // eventual move relative to a retained quarantine dirfd.
                let dest = ctx.run_dir.join("quarantine").join(dest_under_quarantine);
                if dest.exists() {
                    return Err(DoctorRuntimeError::Io {
                        context: format!(
                            "quarantine destination already exists: {}",
                            dest.display()
                        ),
                        source: io::Error::new(
                            io::ErrorKind::AlreadyExists,
                            "quarantine destination collision",
                        ),
                    });
                }
            }
        }
        // Advisory ops (Manual, EmitDiagnostic, RunX, RewriteJsonl,
        // AtomicRewriteToml, SnapshotBackup): no idempotence pre-check;
        // they just record evidence.
        _ => {}
    }

    #[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))]
    let quarantine_destination = match &op {
        Op::QuarantineByRename {
            dest_under_quarantine,
        } => {
            let destination = prepare_doctor_relative_destination(
                &ctx.lifecycle.quarantine_dir,
                &ctx.run_dir.join("quarantine"),
                dest_under_quarantine,
            )?;
            if doctor_entry_type_at(&destination.parent, destination.leaf.as_os_str())?.is_some() {
                return Err(DoctorRuntimeError::Io {
                    context: format!(
                        "quarantine destination already exists: {}",
                        destination.display_path.display()
                    ),
                    source: io::Error::new(
                        io::ErrorKind::AlreadyExists,
                        "quarantine destination collision",
                    ),
                });
            }
            Some(destination)
        }
        _ => None,
    };

    // Backup (only for writing ops on existing files). Runs AFTER the
    // idempotence + validation pre-check above so NoOp / validation
    // failures don't leave orphan backup directories.
    let backup_rel_path = if op.is_writing() && path.is_file() {
        Some(stage_backup(ctx, path, &before_hash)?)
    } else {
        None
    };

    let mut after_hash: Option<String> = None;
    let mut after_mode: Option<u32> = None;
    let mut quarantine_dest_rel: Option<PathBuf> = None;
    let mut notes: Option<String> = None;

    match &op {
        Op::WriteFile { bytes } => {
            // Idempotence already pre-checked above.
            if !ctx.dry_run {
                write_file_atomic(path, bytes).map_err(|source| DoctorRuntimeError::Io {
                    context: format!("WriteFile({})", path.display()),
                    source,
                })?;
                after_hash = Some(hash_file(path)?);
            } else {
                after_hash = Some(hash_bytes(bytes));
            }
        }
        Op::Chmod { mode } => {
            #[cfg(unix)]
            {
                if !ctx.dry_run {
                    use std::os::unix::fs::PermissionsExt as _;
                    let perms = fs::Permissions::from_mode(*mode);
                    fs::set_permissions(path, perms).map_err(|source| DoctorRuntimeError::Io {
                        context: format!("Chmod({})", path.display()),
                        source,
                    })?;
                }
            }
            #[cfg(not(unix))]
            {
                // Windows: mode bits are advisory; record the intent but
                // don't compare (the OS won't honor them anyway).
                let _ = path;
            }
            // Mask to permission bits — the OS only honors 0o7777 for chmod,
            // and storing the user's input verbatim could mislead operators
            // reading actions.jsonl into thinking we wrote file-type bits too.
            after_mode = Some(*mode & 0o7777);
            after_hash = before_hash.clone();
        }
        Op::CreateDirAll { mode: _ } => {
            // Idempotence already pre-checked.
            if !ctx.dry_run {
                fs::create_dir_all(path).map_err(|source| DoctorRuntimeError::Io {
                    context: format!("CreateDirAll({})", path.display()),
                    source,
                })?;
            }
        }
        Op::QuarantineByRename {
            dest_under_quarantine,
        } => {
            #[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))]
            {
                use rustix::fs::RenameFlags;

                let destination =
                    quarantine_destination
                        .as_ref()
                        .ok_or_else(|| DoctorRuntimeError::Io {
                            context: "prepare descriptor-anchored quarantine destination".into(),
                            source: io::Error::new(
                                io::ErrorKind::InvalidInput,
                                "quarantine destination was not prepared",
                            ),
                        })?;
                ensure_doctor_lifecycle_bindings(&ctx.lifecycle, &ctx.workspace, &ctx.run_dir)?;
                if !ctx.dry_run {
                    rustix::fs::renameat_with(
                        rustix::fs::CWD,
                        path,
                        &destination.parent,
                        destination.leaf.as_os_str(),
                        RenameFlags::NOREPLACE,
                    )
                    .map_err(|source| {
                        if source == rustix::io::Errno::EXIST {
                            DoctorRuntimeError::Io {
                                context: format!(
                                    "quarantine destination already exists: {}",
                                    destination.display_path.display()
                                ),
                                source: io::Error::new(
                                    io::ErrorKind::AlreadyExists,
                                    "quarantine destination collision",
                                ),
                            }
                        } else {
                            doctor_lifecycle_errno(
                                &destination.display_path,
                                &format!("rename {} into quarantine", path.display()),
                                source,
                            )
                        }
                    })?;
                }
            }

            #[cfg(not(any(target_os = "linux", target_os = "android", target_vendor = "apple")))]
            {
                // Compatibility path for platforms without the required
                // openat/renameat no-follow primitives.
                let dest = ctx.run_dir.join("quarantine").join(dest_under_quarantine);
                if let Some(parent) = dest.parent() {
                    fs::create_dir_all(parent).map_err(|source| DoctorRuntimeError::Io {
                        context: format!("create_dir_all({}) for quarantine", parent.display()),
                        source,
                    })?;
                }
                if !ctx.dry_run {
                    fs::rename(path, &dest).map_err(|source| DoctorRuntimeError::Io {
                        context: format!("rename({} -> {})", path.display(), dest.display()),
                        source,
                    })?;
                }
            }
            quarantine_dest_rel = Some(dest_under_quarantine.clone());
            // After quarantine, original is gone.
            after_hash = None;
        }
        Op::Manual { steps } => {
            notes = Some(steps.join(" ; "));
        }
        Op::EmitDiagnostic { code, severity } => {
            notes = Some(format!("{} severity={}", code, severity));
        }
        Op::RunIndexRebuild { steps } => {
            notes = Some(format!("run_index_rebuild: {}", steps.join(" ; ")));
        }
        Op::RunGraphRefresh { steps } => {
            notes = Some(format!("run_graph_refresh: {}", steps.join(" ; ")));
        }
        Op::RunWalCheckpoint { mode, steps } => {
            notes = Some(format!(
                "run_wal_checkpoint mode={} steps={}",
                mode,
                steps.join(" ; ")
            ));
        }
        Op::RunMigration {
            target_version,
            steps,
        } => {
            notes = Some(format!(
                "run_migration target={} steps={}",
                target_version,
                steps.join(" ; ")
            ));
        }
        Op::RewriteJsonl { row_count, steps } => {
            notes = Some(format!(
                "rewrite_jsonl rows={} steps={}",
                row_count,
                steps.join(" ; ")
            ));
        }
        Op::AtomicRewriteToml { steps } => {
            notes = Some(format!("atomic_rewrite_toml: {}", steps.join(" ; ")));
        }
        Op::SnapshotBackup { label, steps } => {
            notes = Some(format!(
                "snapshot_backup label={} steps={}",
                label,
                steps.join(" ; ")
            ));
        }
    }

    // Build the line.
    //
    // Round-2 fresh-eyes (R2-P2-02): tentatively allocate the next
    // sequence number but DO NOT increment ctx.state.action_count until
    // the actions.jsonl append succeeds. Crashes between the increment
    // and the append used to leave state.json one ahead of the log,
    // breaking sequence-based undo semantics.
    let proposed_seq = ctx.state.action_count + 1;
    let line = ActionLine {
        schema: ACTION_LINE_SCHEMA_V1.into(),
        run_id: ctx.run_id.clone(),
        sequence: proposed_seq,
        path: path.to_path_buf(),
        kind: op.kind_str().into(),
        before_hash,
        after_hash,
        backup_rel_path,
        before_mode,
        after_mode,
        quarantine_dest_rel,
        committed_at: Utc::now().to_rfc3339(),
        notes,
    };

    // Append to actions.jsonl. Only after this succeeds do we commit the
    // sequence advance into state.json.
    if let Some(handle) = ctx.actions_handle.as_mut() {
        let json = serde_json::to_string(&line).map_err(|e| DoctorRuntimeError::Io {
            context: "serialize ActionLine".into(),
            source: io::Error::new(io::ErrorKind::InvalidData, e),
        })?;
        writeln!(handle, "{}", json).map_err(|source| DoctorRuntimeError::Io {
            context: "append actions.jsonl".into(),
            source,
        })?;
        handle.flush().map_err(|source| DoctorRuntimeError::Io {
            context: "flush actions.jsonl".into(),
            source,
        })?;
    }

    // Commit the sequence advance now that the action is durably logged.
    ctx.state.action_count = proposed_seq;
    write_lifecycle_state(&ctx.lifecycle, &ctx.run_dir, &ctx.state)?;
    ensure_doctor_lifecycle_bindings(&ctx.lifecycle, &ctx.workspace, &ctx.run_dir)?;

    Ok(line)
}

/// Read `actions.jsonl` and restore byte-for-byte to the pre-run state.
///
/// Idempotent: re-running `replay_undo` on a fully-undone run is a no-op.
/// On partial failure, the function returns the count of actions reverted
/// plus the first error encountered; the caller can inspect
/// `<run-dir>/undo_log.jsonl` for line-level detail.
///
/// Acquires an exclusive OS advisory lock on the workspace's persistent
/// `.ee/.doctor.lock` file so two concurrent `ee doctor --undo <run-id>`
/// invocations cannot race on the same `actions.jsonl` / `undo_log.jsonl`.
/// The exact locked handle is held in a Drop guard, so it is released even on
/// partial-undo aborts without deleting or renaming the public lock path.
/// If the workspace lock is held by another doctor (concurrent --fix or
/// --undo), returns `ConcurrencyLost` with exit semantics that match
/// `RunContext::start`.
pub fn replay_undo(run_dir: &Path) -> Result<UndoSummary, DoctorRuntimeError> {
    let absolute = if run_dir.is_absolute() {
        run_dir.to_path_buf()
    } else {
        std::env::current_dir()
            .map(|cwd| cwd.join(run_dir))
            .map_err(|source| DoctorRuntimeError::Io {
                context: format!("resolve relative doctor run {}", run_dir.display()),
                source,
            })?
    };
    validate_doctor_lifecycle_paths([absolute.as_path()])?;
    let run_id = absolute
        .file_name()
        .and_then(|name| name.to_str())
        .ok_or_else(|| DoctorRuntimeError::InvalidRunId {
            run_id: absolute.display().to_string(),
            reason: "run directory has no UTF-8 leaf identifier".into(),
        })?;
    validate_doctor_run_id(run_id)?;
    let runs_dir = absolute
        .parent()
        .filter(|path| path.file_name() == Some(OsStr::new("runs")))
        .ok_or_else(|| DoctorRuntimeError::RunArtifactInvalid {
            path: absolute.clone(),
            reason: "run directory must be a direct child of .doctor/runs".into(),
        })?;
    let doctor_dir = runs_dir
        .parent()
        .filter(|path| path.file_name() == Some(OsStr::new(".doctor")))
        .ok_or_else(|| DoctorRuntimeError::RunArtifactInvalid {
            path: absolute.clone(),
            reason: "run directory must be a direct child of .doctor/runs".into(),
        })?;
    let workspace = doctor_dir
        .parent()
        .ok_or_else(|| DoctorRuntimeError::RunArtifactInvalid {
            path: absolute.clone(),
            reason: "run directory has no workspace parent".into(),
        })?;
    replay_undo_for_workspace(workspace, run_id)
}

/// Replay a prior run selected by an expected workspace and opaque run ID.
/// Both values are revalidated by the runtime; callers must not construct a
/// run path by joining untrusted input themselves.
pub fn replay_undo_for_workspace(
    workspace: &Path,
    run_id: &str,
) -> Result<UndoSummary, DoctorRuntimeError> {
    let workspace = canonical_doctor_workspace(workspace)?;
    let allowed_roots = blast_radius_roots_from_env(&workspace)
        .map_err(|reason| DoctorRuntimeError::InvalidBlastRadius { reason })?;
    replay_undo_with_authorized_roots(&workspace, run_id, &allowed_roots)
}

/// Replay with an explicit set of roots authorized by the caller for this
/// invocation. Production CLI code uses [`replay_undo_for_workspace`], which
/// derives these roots from the current operator configuration; test and
/// embedding callers that created a run with narrower custom roots can supply
/// the same authorization explicitly.
pub fn replay_undo_with_authorized_roots(
    workspace: &Path,
    run_id: &str,
    allowed_roots: &[PathBuf],
) -> Result<UndoSummary, DoctorRuntimeError> {
    let (run_dir, mut state) = read_doctor_run_state(workspace, run_id)?;
    let workspace = canonical_doctor_workspace(workspace)?;
    if state.dry_run {
        return Err(DoctorRuntimeError::DryRunNotUndoable {
            run_id: run_id.to_owned(),
        });
    }
    let allowed_roots = normalize_blast_radius_roots(&workspace, allowed_roots, false)?;
    let recorded_roots = validate_recorded_blast_radius_roots(&run_dir, &state.blast_radius_roots)?;
    validate_doctor_lifecycle_paths([
        run_dir.as_path(),
        run_dir.join("state.json").as_path(),
        run_dir.join("actions.jsonl").as_path(),
        run_dir.join("undo_log.jsonl").as_path(),
        run_dir.join("backups").as_path(),
        run_dir.join("quarantine").as_path(),
    ])?;
    let _lock_guard = acquire_undo_lock(&workspace)?;

    let actions_path = run_dir.join("actions.jsonl");
    let raw = read_required_doctor_jsonl_file(&actions_path, "actions.jsonl")?;
    let mut lines: Vec<ActionLine> = Vec::new();
    for (i, line) in raw.lines().enumerate() {
        if line.trim().is_empty() {
            continue;
        }
        let parsed: ActionLine =
            serde_json::from_str(line).map_err(|e| DoctorRuntimeError::ActionsLogCorrupt {
                line_number: i + 1,
                reason: e.to_string(),
            })?;
        lines.push(parsed);
    }
    let observed_action_count =
        validate_undo_action_ledger(&run_dir, &state, &recorded_roots, &allowed_roots, &lines)?;
    // Read existing undo_log to skip already-undone actions.
    //
    // Only a SUCCESSFUL entry retires an action. Failure entries carry the
    // same `sequence` but record `failed_at`/`error` instead of `undone_at`,
    // so matching on `sequence` alone made a retry skip the very action that
    // failed and then finish with a `RunStatus::Undone` receipt for work that
    // never happened. Retrying a failed action is safe: `undo_one` re-checks
    // the live bytes against `after_hash` and fails closed with
    // `UndoStateDrifted` rather than clobbering drifted content.
    let undo_log_path = run_dir.join("undo_log.jsonl");
    let already_undone_sequences =
        match read_optional_doctor_jsonl_file(&undo_log_path, "undo_log.jsonl")? {
            Some(raw) => validate_undo_log(&run_dir, &raw, &lines)?,
            None => std::collections::HashSet::new(),
        };
    if observed_action_count != state.action_count {
        state.action_count = observed_action_count;
        persist_replay_state(&workspace, run_id, &run_dir, &state)?;
    }

    let mut undone = 0u64;
    let mut skipped = 0u64;
    let mut undo_log_options = fs::OpenOptions::new();
    undo_log_options.create(true).append(true);
    configure_doctor_inspect_open_no_follow(&mut undo_log_options);
    let mut undo_log =
        undo_log_options
            .open(&undo_log_path)
            .map_err(|source| DoctorRuntimeError::Io {
                context: format!("open undo_log.jsonl {}", undo_log_path.display()),
                source,
            })?;
    if !undo_log.metadata()?.is_file() {
        return Err(DoctorRuntimeError::RunArtifactInvalid {
            path: undo_log_path,
            reason: "undo log is not a regular file".into(),
        });
    }

    // bd-doctor-undo-state: the undo outcome is part of the run's durable
    // lifecycle. Persist the terminal status into state.json while the
    // workspace lock is still held so `ee doctor --list-runs`, `--diff`, and
    // the gc planner observe the truthful post-undo state instead of the
    // pre-undo terminal status.
    let persist_undo_status = |status: &RunStatus| -> Result<(), DoctorRuntimeError> {
        let mut persisted_state = read_state(&run_dir)?;
        validate_run_state_binding(&workspace, run_id, &run_dir, &persisted_state)?;
        persisted_state.status = status.clone();
        persisted_state
            .finished_at
            .get_or_insert_with(|| Utc::now().to_rfc3339());
        persist_replay_state(&workspace, run_id, &run_dir, &persisted_state)
    };

    for action in lines.iter().rev() {
        if already_undone_sequences.contains(&action.sequence) {
            skipped += 1;
            continue;
        }
        match undo_one(&run_dir, action) {
            Ok(()) => {
                undone += 1;
                let entry = serde_json::json!({
                    "schema": "ee.doctor.undo_entry.v1",
                    "sequence": action.sequence,
                    "path": action.path.display().to_string(),
                    "kind": action.kind,
                    "undone_at": Utc::now().to_rfc3339(),
                });
                writeln!(undo_log, "{}", entry)?;
            }
            Err(e) => {
                let entry = serde_json::json!({
                    "schema": "ee.doctor.undo_entry.v1",
                    "sequence": action.sequence,
                    "path": action.path.display().to_string(),
                    "kind": action.kind,
                    "failed_at": Utc::now().to_rfc3339(),
                    "error": e.to_string(),
                });
                writeln!(undo_log, "{}", entry)?;
                persist_undo_status(&RunStatus::UndonePartial)?;
                return Ok(UndoSummary {
                    actions_undone: undone,
                    actions_skipped: skipped,
                    status: RunStatus::UndonePartial,
                    first_error: Some(e.to_string()),
                    first_error_code: Some(e.code()),
                    first_error_class: Some(e.failure_class()),
                });
            }
        }
    }

    persist_undo_status(&RunStatus::Undone)?;

    Ok(UndoSummary {
        actions_undone: undone,
        actions_skipped: skipped,
        status: RunStatus::Undone,
        first_error: None,
        first_error_code: None,
        first_error_class: None,
    })
}

#[derive(Clone, Debug)]
pub struct UndoSummary {
    pub actions_undone: u64,
    pub actions_skipped: u64,
    pub status: RunStatus,
    pub first_error: Option<String>,
    pub first_error_code: Option<&'static str>,
    pub first_error_class: Option<DoctorRuntimeFailureClass>,
}

fn persist_replay_state(
    workspace: &Path,
    run_id: &str,
    run_dir: &Path,
    state: &RunState,
) -> Result<(), DoctorRuntimeError> {
    validate_run_state_binding(workspace, run_id, run_dir, state)?;
    validate_doctor_lifecycle_paths([run_dir, run_dir.join("state.json").as_path()])?;
    let bytes = serde_json::to_vec_pretty(state).map_err(|error| DoctorRuntimeError::Io {
        context: "serialize RunState".into(),
        source: io::Error::new(io::ErrorKind::InvalidData, error),
    })?;
    write_file_atomic(&run_dir.join("state.json"), &bytes).map_err(|source| {
        DoctorRuntimeError::Io {
            context: format!("write state.json {}", run_dir.join("state.json").display()),
            source,
        }
    })
}

fn validate_relative_run_artifact_path(
    run_dir: &Path,
    root_name: &str,
    rel: &Path,
) -> Result<(), DoctorRuntimeError> {
    if rel.as_os_str().is_empty()
        || rel
            .components()
            .any(|component| !matches!(component, Component::Normal(_)))
    {
        return Err(DoctorRuntimeError::RunArtifactInvalid {
            path: run_dir.join(root_name).join(rel),
            reason: format!("{root_name} path must contain only normal relative components"),
        });
    }
    Ok(())
}

fn validate_undo_action_ledger(
    run_dir: &Path,
    state: &RunState,
    recorded_roots: &[PathBuf],
    current_roots: &[PathBuf],
    lines: &[ActionLine],
) -> Result<u64, DoctorRuntimeError> {
    let run_artifact_roots = [run_dir.to_path_buf()];
    let observed_count =
        u64::try_from(lines.len()).map_err(|_| DoctorRuntimeError::RunArtifactInvalid {
            path: run_dir.join("actions.jsonl"),
            reason: "action count does not fit in u64".into(),
        })?;
    let recoverable_append_gap = matches!(state.status, RunStatus::Running | RunStatus::Failed)
        && state.action_count.checked_add(1) == Some(observed_count);
    if state.action_count != observed_count && !recoverable_append_gap {
        return Err(DoctorRuntimeError::RunArtifactInvalid {
            path: run_dir.join("actions.jsonl"),
            reason: format!(
                "state action_count {} does not match {} action lines",
                state.action_count, observed_count
            ),
        });
    }

    for (index, action) in lines.iter().enumerate() {
        let line_number = index + 1;
        let expected_sequence =
            u64::try_from(line_number).map_err(|_| DoctorRuntimeError::ActionsLogCorrupt {
                line_number,
                reason: "action sequence does not fit in u64".into(),
            })?;
        if action.schema != ACTION_LINE_SCHEMA_V1 {
            return Err(DoctorRuntimeError::ActionsLogCorrupt {
                line_number,
                reason: format!(
                    "unsupported schema {:?}; expected {ACTION_LINE_SCHEMA_V1:?}",
                    action.schema
                ),
            });
        }
        if action.run_id != state.run_id {
            return Err(DoctorRuntimeError::ActionsLogCorrupt {
                line_number,
                reason: format!(
                    "action run_id {:?} does not match state run_id {:?}",
                    action.run_id, state.run_id
                ),
            });
        }
        if action.sequence != expected_sequence {
            return Err(DoctorRuntimeError::ActionsLogCorrupt {
                line_number,
                reason: format!(
                    "action sequence {} is not the expected contiguous sequence {}",
                    action.sequence, expected_sequence
                ),
            });
        }
        let mutating = match action.kind.as_str() {
            "write_file" | "chmod" | "create_dir_all" | "quarantine_by_rename" => true,
            "manual"
            | "emit_diagnostic"
            | "run_index_rebuild"
            | "run_graph_refresh"
            | "run_wal_checkpoint"
            | "run_migration"
            | "rewrite_jsonl"
            | "atomic_rewrite_toml"
            | "snapshot_backup" => false,
            other => {
                return Err(DoctorRuntimeError::ActionsLogCorrupt {
                    line_number,
                    reason: format!("unknown action kind: {other}"),
                });
            }
        };
        if mutating {
            if !action.path.is_absolute() {
                return Err(DoctorRuntimeError::ActionsLogCorrupt {
                    line_number,
                    reason: format!(
                        "mutating action path must be absolute: {}",
                        action.path.display()
                    ),
                });
            }
            if is_path_in_blast_radius(&action.path, &run_artifact_roots)
                || !is_path_in_blast_radius(&action.path, recorded_roots)
                || !is_path_in_blast_radius(&action.path, current_roots)
            {
                let mut effective_roots = Vec::new();
                for recorded in recorded_roots {
                    for current in current_roots {
                        if recorded.starts_with(current) {
                            effective_roots.push(recorded.clone());
                        } else if current.starts_with(recorded) {
                            effective_roots.push(current.clone());
                        }
                    }
                }
                effective_roots.sort();
                effective_roots.dedup();
                return Err(DoctorRuntimeError::BlastRadiusExceeded {
                    path: action.path.clone(),
                    allowed_roots: effective_roots,
                });
            }
        }
        if let Some(rel) = action.backup_rel_path.as_deref() {
            validate_relative_run_artifact_path(run_dir, "backups", rel)?;
        }
        if let Some(rel) = action.quarantine_dest_rel.as_deref() {
            validate_relative_run_artifact_path(run_dir, "quarantine", rel)?;
        }
        match action.kind.as_str() {
            "write_file" if action.before_hash.is_some() && action.backup_rel_path.is_none() => {
                return Err(DoctorRuntimeError::ActionsLogCorrupt {
                    line_number,
                    reason: "write_file action with before_hash requires backup_rel_path".into(),
                });
            }
            "chmod" if action.before_mode.is_none() || action.after_mode.is_none() => {
                return Err(DoctorRuntimeError::ActionsLogCorrupt {
                    line_number,
                    reason: "chmod action requires before_mode and after_mode".into(),
                });
            }
            "quarantine_by_rename" if action.quarantine_dest_rel.is_none() => {
                return Err(DoctorRuntimeError::ActionsLogCorrupt {
                    line_number,
                    reason: "quarantine_by_rename requires quarantine_dest_rel".into(),
                });
            }
            _ => {}
        }
    }
    Ok(observed_count)
}

fn validate_undo_log(
    run_dir: &Path,
    raw: &str,
    actions: &[ActionLine],
) -> Result<std::collections::HashSet<u64>, DoctorRuntimeError> {
    let undo_log_path = run_dir.join("undo_log.jsonl");
    let mut successful = std::collections::HashSet::new();
    for (index, line) in raw.lines().enumerate() {
        if line.trim().is_empty() {
            continue;
        }
        let line_number = index + 1;
        let entry = serde_json::from_str::<serde_json::Value>(line).map_err(|error| {
            DoctorRuntimeError::RunArtifactInvalid {
                path: undo_log_path.clone(),
                reason: format!("line {line_number} is invalid JSON: {error}"),
            }
        })?;
        if entry.get("schema").and_then(serde_json::Value::as_str)
            != Some("ee.doctor.undo_entry.v1")
        {
            return Err(DoctorRuntimeError::RunArtifactInvalid {
                path: undo_log_path.clone(),
                reason: format!("line {line_number} has an unsupported schema"),
            });
        }
        let sequence = entry
            .get("sequence")
            .and_then(serde_json::Value::as_u64)
            .ok_or_else(|| DoctorRuntimeError::RunArtifactInvalid {
                path: undo_log_path.clone(),
                reason: format!("line {line_number} has no integer sequence"),
            })?;
        let action = sequence
            .checked_sub(1)
            .and_then(|offset| usize::try_from(offset).ok())
            .and_then(|offset| actions.get(offset))
            .filter(|action| action.sequence == sequence)
            .ok_or_else(|| DoctorRuntimeError::RunArtifactInvalid {
                path: undo_log_path.clone(),
                reason: format!("line {line_number} references unknown sequence {sequence}"),
            })?;
        if successful.contains(&sequence) {
            return Err(DoctorRuntimeError::RunArtifactInvalid {
                path: undo_log_path.clone(),
                reason: format!(
                    "line {line_number} appears after sequence {sequence} was already completed"
                ),
            });
        }
        let expected_path = action.path.display().to_string();
        if entry.get("path").and_then(serde_json::Value::as_str) != Some(expected_path.as_str())
            || entry.get("kind").and_then(serde_json::Value::as_str) != Some(action.kind.as_str())
        {
            return Err(DoctorRuntimeError::RunArtifactInvalid {
                path: undo_log_path.clone(),
                reason: format!("line {line_number} does not match action sequence {sequence}"),
            });
        }
        let completed = entry.get("undone_at").and_then(serde_json::Value::as_str);
        let failed = entry.get("failed_at").and_then(serde_json::Value::as_str);
        if completed.is_some() == failed.is_some() {
            return Err(DoctorRuntimeError::RunArtifactInvalid {
                path: undo_log_path.clone(),
                reason: format!(
                    "line {line_number} must contain exactly one of undone_at or failed_at"
                ),
            });
        }
        if completed.is_some() {
            successful.insert(sequence);
        }
    }
    if let Some(first_success) = successful.iter().min().copied() {
        let action_count =
            u64::try_from(actions.len()).map_err(|_| DoctorRuntimeError::RunArtifactInvalid {
                path: undo_log_path.clone(),
                reason: "action count does not fit in u64".into(),
            })?;
        if (first_success..=action_count).any(|sequence| !successful.contains(&sequence)) {
            return Err(DoctorRuntimeError::RunArtifactInvalid {
                path: undo_log_path.clone(),
                reason: "successful undo receipts must form a contiguous action suffix".into(),
            });
        }

        let mut final_actions_by_path = std::collections::BTreeMap::new();
        for action in actions {
            if successful.contains(&action.sequence) && is_mutating_action_kind(&action.kind) {
                final_actions_by_path
                    .entry(action.path.clone())
                    .or_insert(action);
            }
        }
        for action in final_actions_by_path.values() {
            if !action_pre_state_matches(run_dir, action)? {
                return Err(DoctorRuntimeError::RunArtifactInvalid {
                    path: undo_log_path.clone(),
                    reason: format!(
                        "successful receipt for sequence {} does not match the live post-undo state",
                        action.sequence
                    ),
                });
            }
        }
    }
    Ok(successful)
}

fn is_mutating_action_kind(kind: &str) -> bool {
    matches!(
        kind,
        "write_file" | "chmod" | "create_dir_all" | "quarantine_by_rename"
    )
}

fn undo_created_quarantine_path(run_dir: &Path, action: &ActionLine, root: &str) -> PathBuf {
    run_dir
        .join("quarantine")
        .join(root)
        .join(format!("{:06}", action.sequence))
        .join(sanitize_path_for_run_dir(&action.path))
}

fn action_pre_state_matches(
    run_dir: &Path,
    action: &ActionLine,
) -> Result<bool, DoctorRuntimeError> {
    match action.kind.as_str() {
        "write_file" => match action.before_hash.as_deref() {
            Some(expected) => {
                if !action.path.is_file() {
                    return Ok(false);
                }
                Ok(hash_file(&action.path)? == expected)
            }
            None => {
                let quarantine = undo_created_quarantine_path(run_dir, action, "undo_created");
                validate_doctor_lifecycle_paths([quarantine.as_path()])?;
                Ok(!action.path.exists() && quarantine.exists())
            }
        },
        "chmod" => {
            #[cfg(unix)]
            {
                Ok(read_mode(&action.path).map(|mode| mode & 0o7777)
                    == action.before_mode.map(|mode| mode & 0o7777))
            }
            #[cfg(not(unix))]
            {
                Ok(true)
            }
        }
        "create_dir_all" => {
            let quarantine = undo_created_quarantine_path(run_dir, action, "undo_created_dirs");
            validate_doctor_lifecycle_paths([quarantine.as_path()])?;
            Ok(!action.path.exists() && quarantine.exists())
        }
        "quarantine_by_rename" => {
            let source = action
                .quarantine_dest_rel
                .as_ref()
                .map(|rel| run_dir.join("quarantine").join(rel));
            if let Some(source) = source.as_deref() {
                validate_doctor_lifecycle_paths([source])?;
            }
            let source_exists = source.as_deref().is_some_and(Path::exists);
            let target_matches = match action.before_hash.as_deref() {
                Some(expected) if action.path.is_file() => hash_file(&action.path)? == expected,
                Some(_) => false,
                None => action.path.exists(),
            };
            Ok(target_matches && !source_exists)
        }
        "manual"
        | "emit_diagnostic"
        | "run_index_rebuild"
        | "run_graph_refresh"
        | "run_wal_checkpoint"
        | "run_migration"
        | "rewrite_jsonl"
        | "atomic_rewrite_toml"
        | "snapshot_backup" => Ok(true),
        other => Err(DoctorRuntimeError::ActionsLogCorrupt {
            line_number: action.sequence as usize,
            reason: format!("unknown action kind: {other}"),
        }),
    }
}

fn undo_one(run_dir: &Path, action: &ActionLine) -> Result<(), DoctorRuntimeError> {
    if action_pre_state_matches(run_dir, action)? {
        return Ok(());
    }
    match action.kind.as_str() {
        "write_file" => {
            // Restore from backup. If `before_hash` is None, the file didn't
            // exist before — quarantine the current file (RULE 1 — no
            // deletion, even on undo of a create).
            //
            // Round-2 fresh-eyes (F5): before overwriting, verify the live
            // file's current bytes match what `mutate()` originally wrote
            // (`action.after_hash`). If not, an external writer modified the
            // file after the doctor ran. Refuse with `UndoStateDrifted` rather
            // than silently destroy that change.
            match (&action.before_hash, &action.backup_rel_path) {
                (Some(expected_before), Some(rel)) => {
                    // Round-3 self-review: only refuse on drift when the
                    // post-mutate file is still present. If something deleted
                    // it after the doctor ran, the user's most-likely intent
                    // when calling --undo is "restore the pre-state" — i.e.,
                    // recreate from backup. Drift detection should fire only
                    // for the "bytes were modified" scenario, not "file
                    // disappeared".
                    if action.path.exists() {
                        let live_hash = if action.path.is_file() {
                            hash_file(&action.path)?
                        } else {
                            "<directory>".to_string()
                        };
                        if Some(live_hash.as_str()) != action.after_hash.as_deref() {
                            return Err(DoctorRuntimeError::UndoStateDrifted {
                                path: action.path.clone(),
                                expected_hash: action.after_hash.clone().unwrap_or_default(),
                                observed_hash: live_hash,
                            });
                        }
                    }
                    let backup = run_dir.join("backups").join(rel);
                    validate_doctor_lifecycle_paths([backup.as_path()])?;
                    if !backup.exists() {
                        return Err(DoctorRuntimeError::UndoBackupCorrupt {
                            backup_path: backup,
                            expected_hash: expected_before.clone(),
                            observed_hash: None,
                        });
                    }
                    // Read the backup ONCE into memory, then hash the
                    // in-memory bytes and write those same bytes. The
                    // prior shape opened the file twice — first via
                    // `hash_file` (streaming hash, then drop), then via
                    // `fs::read` for the write — which left a TOCTOU
                    // window: a peer with write access to
                    // `.doctor/runs/<run_id>/backups/` could swap the
                    // file between the hash and the read so the integrity
                    // check passed on the original backup while
                    // `fs::read` returned attacker-controlled bytes that
                    // `write_file_atomic` then wrote to `action.path`.
                    // Reading once + hashing the bytes binds the integrity
                    // check to exactly what gets written. No second open,
                    // no race window.
                    let backup_bytes = read_doctor_backup_bytes(&backup)?;
                    let backup_hash = hash_bytes(&backup_bytes);
                    if &backup_hash != expected_before {
                        return Err(DoctorRuntimeError::UndoBackupCorrupt {
                            backup_path: backup,
                            expected_hash: expected_before.clone(),
                            observed_hash: Some(backup_hash),
                        });
                    }
                    write_file_atomic(&action.path, &backup_bytes)?;
                }
                (None, _) => {
                    // The file didn't exist before. Quarantine instead of
                    // delete per AGENTS.md RULE 1.
                    //
                    // Round-2 fresh-eyes (F5 + R2-P0-03): only quarantine if
                    // the live file still matches what we wrote. If someone
                    // replaced it, refuse with UndoStateDrifted. Namespace
                    // the quarantine destination by both action.sequence
                    // AND the sanitized full source path (not just
                    // file_name()) so two mutations that created files with
                    // the same basename in different dirs don't collide on
                    // undo.
                    if action.path.exists() {
                        let live_hash = if action.path.is_file() {
                            hash_file(&action.path)?
                        } else {
                            "<directory>".to_string()
                        };
                        if action.after_hash.as_deref() != Some(live_hash.as_str()) {
                            return Err(DoctorRuntimeError::UndoStateDrifted {
                                path: action.path.clone(),
                                expected_hash: action.after_hash.clone().unwrap_or_default(),
                                observed_hash: live_hash,
                            });
                        }
                        let quarantine_dest =
                            undo_created_quarantine_path(run_dir, action, "undo_created");
                        if let Some(parent) = quarantine_dest.parent() {
                            fs::create_dir_all(parent)?;
                        }
                        if quarantine_dest.exists() {
                            return Err(DoctorRuntimeError::Io {
                                context: format!(
                                    "undo quarantine collision at {}",
                                    quarantine_dest.display()
                                ),
                                source: io::Error::new(
                                    io::ErrorKind::AlreadyExists,
                                    "undo quarantine collision",
                                ),
                            });
                        }
                        fs::rename(&action.path, &quarantine_dest)?;
                    }
                }
                (Some(_), None) => {
                    // Logically impossible: action wrote bytes to an
                    // existing file but didn't record a backup. Surface
                    // as corrupt.
                    return Err(DoctorRuntimeError::ActionsLogCorrupt {
                        line_number: action.sequence as usize,
                        reason: "write_file action has before_hash but no backup_rel_path".into(),
                    });
                }
            }
        }
        "chmod" => {
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt as _;
                let current_mode = read_mode(&action.path).map(|mode| mode & 0o7777);
                let expected_after = action.after_mode.map(|mode| mode & 0o7777);
                if current_mode != expected_after {
                    return Err(DoctorRuntimeError::UndoStateDrifted {
                        path: action.path.clone(),
                        expected_hash: expected_after.map_or_else(
                            || "<missing mode>".into(),
                            |mode| format!("mode {mode:o}"),
                        ),
                        observed_hash: current_mode
                            .map_or_else(|| "<missing>".into(), |mode| format!("mode {mode:o}")),
                    });
                }
                if let Some(mode) = action.before_mode.map(|mode| mode & 0o7777) {
                    let perms = fs::Permissions::from_mode(mode);
                    fs::set_permissions(&action.path, perms)?;
                }
            }
            #[cfg(not(unix))]
            {
                let _ = action;
            }
        }
        "create_dir_all" => {
            // Undo of create_dir_all is QuarantineByRename of the created
            // directory (RULE 1). Only undo if directory is empty — else
            // refuse (we may have created the dir but another agent put
            // something in it).
            //
            // Round-2 fresh-eyes (R2-P0-03 + R2-P1-05): namespace the
            // quarantine destination by action.sequence + sanitized full
            // path to prevent collisions; propagate read_dir errors instead
            // of silently treating them as "non-empty".
            if action.path.exists() && !action.path.is_dir() {
                return Err(DoctorRuntimeError::UndoStateDrifted {
                    path: action.path.clone(),
                    expected_hash: "<empty directory created by doctor>".to_owned(),
                    observed_hash: "<non-directory occupant>".to_owned(),
                });
            }
            if action.path.is_dir() {
                let is_empty = match fs::read_dir(&action.path) {
                    Ok(mut it) => match it.next() {
                        Some(Ok(_)) => false,
                        Some(Err(source)) => {
                            return Err(DoctorRuntimeError::Io {
                                context: format!(
                                    "read_dir entry for undo of create_dir_all({})",
                                    action.path.display()
                                ),
                                source,
                            });
                        }
                        None => true,
                    },
                    Err(source) => {
                        return Err(DoctorRuntimeError::Io {
                            context: format!(
                                "read_dir for undo of create_dir_all({})",
                                action.path.display()
                            ),
                            source,
                        });
                    }
                };
                if !is_empty {
                    return Err(DoctorRuntimeError::UndoStateDrifted {
                        path: action.path.clone(),
                        expected_hash: "<empty directory created by doctor>".to_owned(),
                        observed_hash: "<non-empty directory>".to_owned(),
                    });
                }
                let quarantine_dest =
                    undo_created_quarantine_path(run_dir, action, "undo_created_dirs");
                if let Some(parent) = quarantine_dest.parent() {
                    fs::create_dir_all(parent)?;
                }
                if quarantine_dest.exists() {
                    return Err(DoctorRuntimeError::Io {
                        context: format!(
                            "undo quarantine collision at {}",
                            quarantine_dest.display()
                        ),
                        source: io::Error::new(
                            io::ErrorKind::AlreadyExists,
                            "undo quarantine collision",
                        ),
                    });
                }
                fs::rename(&action.path, &quarantine_dest)?;
            }
        }
        "quarantine_by_rename" => {
            // Restore: move the quarantined file back to its original path.
            //
            // Round-2 fresh-eyes (F6): if something has occupied the original
            // path between quarantine and undo, refuse rather than overwrite.
            // `UndoStateDrifted` is the right signal — the user can inspect
            // both the new occupant and the quarantine and decide.
            if action.path.exists() {
                let live_hash = if action.path.is_file() {
                    hash_file(&action.path)?
                } else {
                    "<directory>".to_string()
                };
                return Err(DoctorRuntimeError::UndoStateDrifted {
                    path: action.path.clone(),
                    expected_hash: "<not present (quarantined)>".into(),
                    observed_hash: live_hash,
                });
            }
            let quarantine_dest = action
                .quarantine_dest_rel
                .as_ref()
                .map(|rel| run_dir.join("quarantine").join(rel));
            if let Some(source) = quarantine_dest {
                validate_doctor_lifecycle_paths([source.as_path()])?;
                if source.exists() {
                    if let Some(parent) = action.path.parent() {
                        fs::create_dir_all(parent)?;
                    }
                    fs::rename(&source, &action.path)?;
                }
            }
        }
        "manual"
        | "emit_diagnostic"
        | "run_index_rebuild"
        | "run_graph_refresh"
        | "run_wal_checkpoint"
        | "run_migration"
        | "rewrite_jsonl"
        | "atomic_rewrite_toml"
        | "snapshot_backup" => {
            // No-op for undo. These op kinds are advisory: `mutate()`
            // records planned-mutation evidence in `actions.jsonl` but does
            // not touch the doctor's blast-radius files itself. The actual
            // subsystem mutation (when those actor handles land) is undone
            // via the subsystem's own rollback, not by doctor's
            // tempfile-rename inverse pair.
        }
        other => {
            return Err(DoctorRuntimeError::ActionsLogCorrupt {
                line_number: action.sequence as usize,
                reason: format!("unknown action kind: {}", other),
            });
        }
    }
    Ok(())
}

/// The shape printed by `ee doctor capabilities --json`.
#[derive(Clone, Debug, Serialize)]
pub struct CapabilitiesReport {
    pub schema: String,
    pub doctor_version: String,
    pub doctor_contract_version: String,
    pub tool_version: String,
    pub run_artifact_schema: String,
    pub blast_radius: Vec<String>,
    pub op_kinds: Vec<&'static str>,
    pub exit_codes: Vec<ExitCodeEntry>,
    pub env_vars: Vec<EnvVarEntry>,
    pub action_line_schema: String,
}

#[derive(Clone, Debug, Serialize)]
pub struct ExitCodeEntry {
    pub code: i32,
    pub name: &'static str,
    pub meaning: &'static str,
}

#[derive(Clone, Debug, Serialize)]
pub struct EnvVarEntry {
    pub name: &'static str,
    pub purpose: &'static str,
}

impl CapabilitiesReport {
    /// Build the report. All fields are deterministic at this build's
    /// compile time except `tool_version` (from the package version).
    #[must_use]
    pub fn build(tool_version: &str, workspace: &Path) -> Self {
        let blast_radius = default_blast_radius_roots(workspace)
            .iter()
            .map(|p| p.display().to_string())
            .collect::<Vec<_>>();
        Self {
            schema: CAPABILITIES_SCHEMA_V1.into(),
            doctor_version: env!("CARGO_PKG_VERSION").into(),
            doctor_contract_version: "1.0.0".into(),
            tool_version: tool_version.into(),
            run_artifact_schema: RUN_STATE_SCHEMA_V2.into(),
            blast_radius,
            op_kinds: vec![
                "write_file",
                "create_dir_all",
                "chmod",
                "quarantine_by_rename",
                "manual",
                "emit_diagnostic",
                "run_index_rebuild",
                "run_graph_refresh",
                "run_wal_checkpoint",
                "run_migration",
                "rewrite_jsonl",
                "atomic_rewrite_toml",
                "snapshot_backup",
            ],
            exit_codes: vec![
                ExitCodeEntry {
                    code: 0,
                    name: "ok",
                    meaning: "no findings, or all fixes applied successfully",
                },
                ExitCodeEntry {
                    code: 1,
                    name: "usage",
                    meaning: "command-line usage or argument validation failed",
                },
                ExitCodeEntry {
                    code: 2,
                    name: "configuration",
                    meaning: "configuration, concurrency, or no-op precondition prevented the operation",
                },
                ExitCodeEntry {
                    code: 3,
                    name: "storage",
                    meaning: "doctor storage, ledger, backup, or state restoration failed",
                },
                ExitCodeEntry {
                    code: 4,
                    name: "search_index",
                    meaning: "search index operation failed",
                },
                ExitCodeEntry {
                    code: 5,
                    name: "import",
                    meaning: "import operation failed",
                },
                ExitCodeEntry {
                    code: 6,
                    name: "unsatisfied_degraded_mode",
                    meaning: "the requested operation cannot proceed in the current degraded mode",
                },
                ExitCodeEntry {
                    code: 7,
                    name: "policy_denied",
                    meaning: "blast-radius or another safety policy denied the operation",
                },
                ExitCodeEntry {
                    code: 8,
                    name: "migration_required",
                    meaning: "doctor refuses because `ee migrate run` is needed first",
                },
            ],
            // Every variable listed here must be registered in
            // `config::env_registry` and actually read by the runtime.
            // `EE_DOCTOR_LOCK_STALE_AFTER_SECS` was removed (bd-awm6r): the
            // doctor lock is an OS advisory lock that releases when its holder
            // exits, so "stale after N seconds" has no meaning here and the
            // advertised control was a silent no-op.
            env_vars: vec![
                EnvVarEntry {
                    name: "EE_DOCTOR_BLAST_RADIUS",
                    purpose: "Override default blast radius (colon-separated abs paths)",
                },
                EnvVarEntry {
                    name: "EE_NO_COLOR",
                    purpose: "Disables ANSI styling on stderr (inherited from ee)",
                },
            ],
            action_line_schema: ACTION_LINE_SCHEMA_V1.into(),
        }
    }
}

/// Default blast radius for an ee workspace: the four canonical roots
/// doctor is allowed to write to.
#[must_use]
pub fn default_blast_radius_roots(workspace: &Path) -> Vec<PathBuf> {
    let mut roots = vec![workspace.join(".ee"), workspace.join(".doctor")];
    if let Some(home) = std::env::var_os("HOME") {
        let home = PathBuf::from(home);
        roots.push(home.join(".local").join("share").join("ee"));
    }
    roots
}

fn normalize_blast_radius_roots(
    workspace: &Path,
    roots: &[PathBuf],
    resolve_relative_from_cwd: bool,
) -> Result<Vec<PathBuf>, DoctorRuntimeError> {
    if roots.is_empty() {
        return Err(DoctorRuntimeError::RunArtifactInvalid {
            path: workspace.to_path_buf(),
            reason: "doctor blast radius must contain at least one root".into(),
        });
    }

    let mut normalized = Vec::with_capacity(roots.len());
    for root in roots {
        let absolute = if root.is_absolute() {
            root.clone()
        } else if resolve_relative_from_cwd {
            std::env::current_dir()
                .map(|current_dir| current_dir.join(root))
                .map_err(|source| DoctorRuntimeError::Io {
                    context: format!(
                        "resolve relative doctor blast-radius root {}",
                        root.display()
                    ),
                    source,
                })?
        } else {
            return Err(DoctorRuntimeError::RunArtifactInvalid {
                path: root.clone(),
                reason:
                    "persisted and replay-time doctor blast-radius roots must be absolute paths"
                        .into(),
            });
        };
        let canonical = if absolute.exists() {
            fs::canonicalize(&absolute).map_err(|source| DoctorRuntimeError::Io {
                context: format!(
                    "canonicalize doctor blast-radius root {}",
                    absolute.display()
                ),
                source,
            })?
        } else {
            nearest_existing_ancestor_canonical(&absolute).ok_or_else(|| {
                DoctorRuntimeError::RunArtifactInvalid {
                    path: absolute.clone(),
                    reason: "doctor blast-radius root has no safe existing ancestor".into(),
                }
            })?
        };
        normalized.push(canonical);
    }
    normalized.sort();
    normalized.dedup();
    Ok(normalized)
}

fn validate_recorded_blast_radius_roots(
    run_dir: &Path,
    roots: &[PathBuf],
) -> Result<Vec<PathBuf>, DoctorRuntimeError> {
    if roots.is_empty() {
        return Err(DoctorRuntimeError::RunArtifactInvalid {
            path: run_dir.join("state.json"),
            reason: "run state has no recorded blast-radius roots".into(),
        });
    }

    let mut validated = Vec::with_capacity(roots.len());
    for root in roots {
        if !root.is_absolute()
            || root.components().any(|component| {
                !matches!(
                    component,
                    Component::Prefix(_) | Component::RootDir | Component::Normal(_)
                )
            })
        {
            return Err(DoctorRuntimeError::RunArtifactInvalid {
                path: run_dir.join("state.json"),
                reason: format!(
                    "recorded blast-radius root must be an absolute normalized path: {}",
                    root.display()
                ),
            });
        }
        validated.push(root.clone());
    }
    validated.sort();
    validated.dedup();
    Ok(validated)
}

/// Blast-radius roots for `ee doctor --fix`, honoring the
/// `EE_DOCTOR_BLAST_RADIUS` override advertised by `--capabilities`
/// (colon-separated absolute paths). Unset or blank falls back to
/// [`default_blast_radius_roots`].
///
/// # Errors
///
/// Returns a human-readable reason when the override is set but invalid
/// (empty segment or relative entry). Doctor must refuse rather than fall
/// back: a typo that silently restored the default roots could widen the
/// write surface past what the operator constrained it to.
pub fn blast_radius_roots_from_env(workspace: &Path) -> Result<Vec<PathBuf>, String> {
    use crate::config::env_registry::{EnvVar, read};
    match read(EnvVar::DoctorBlastRadius) {
        Some(raw) if !raw.trim().is_empty() => parse_blast_radius_override(&raw),
        _ => Ok(default_blast_radius_roots(workspace)),
    }
}

fn parse_blast_radius_override(raw: &str) -> Result<Vec<PathBuf>, String> {
    let mut roots = Vec::new();
    for entry in raw.split(':') {
        let entry = entry.trim();
        if entry.is_empty() {
            return Err(format!(
                "EE_DOCTOR_BLAST_RADIUS contains an empty path segment: {raw:?}"
            ));
        }
        let path = PathBuf::from(entry);
        if !path.is_absolute() {
            return Err(format!(
                "EE_DOCTOR_BLAST_RADIUS entries must be absolute paths; got {entry:?}"
            ));
        }
        roots.push(path);
    }
    Ok(roots)
}

// ---------- private helpers ----------

fn canonical_doctor_workspace(workspace: &Path) -> Result<PathBuf, DoctorRuntimeError> {
    let absolute = if workspace.is_absolute() {
        workspace.to_path_buf()
    } else {
        std::env::current_dir()
            .map(|cwd| cwd.join(workspace))
            .map_err(|source| DoctorRuntimeError::Io {
                context: format!("resolve relative doctor workspace {}", workspace.display()),
                source,
            })?
    };

    let metadata = fs::symlink_metadata(&absolute).map_err(|source| DoctorRuntimeError::Io {
        context: format!("inspect doctor workspace {}", absolute.display()),
        source,
    })?;
    if metadata.file_type().is_symlink() {
        return Err(DoctorRuntimeError::SymlinkedRunRoot { path: absolute });
    }
    if !metadata.is_dir() {
        return Err(DoctorRuntimeError::Io {
            context: format!("inspect doctor workspace {}", absolute.display()),
            source: io::Error::new(
                io::ErrorKind::InvalidInput,
                "doctor workspace is not a directory",
            ),
        });
    }

    fs::canonicalize(&absolute).map_err(|source| DoctorRuntimeError::Io {
        context: format!("canonicalize doctor workspace {}", absolute.display()),
        source,
    })
}

const DOCTOR_RUN_ID_MAX_BYTES: usize = 128;

/// Validate that a doctor run identifier is one short opaque path component.
///
/// This check is intentionally platform-independent: backslashes are rejected
/// even on Unix so an identifier accepted on one host cannot become a path on
/// another. The generated timestamp/sequence/hash IDs use only this alphabet.
pub fn validate_doctor_run_id(run_id: &str) -> Result<(), DoctorRuntimeError> {
    if run_id.is_empty() {
        return Err(DoctorRuntimeError::InvalidRunId {
            run_id: run_id.to_owned(),
            reason: "run id must not be empty".into(),
        });
    }
    if run_id.len() > DOCTOR_RUN_ID_MAX_BYTES {
        return Err(DoctorRuntimeError::InvalidRunId {
            run_id: run_id.to_owned(),
            reason: format!("run id exceeds {DOCTOR_RUN_ID_MAX_BYTES} bytes"),
        });
    }
    if run_id == "." || run_id == ".." {
        return Err(DoctorRuntimeError::InvalidRunId {
            run_id: run_id.to_owned(),
            reason: "dot path components are not run ids".into(),
        });
    }
    if !run_id
        .bytes()
        .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'))
    {
        return Err(DoctorRuntimeError::InvalidRunId {
            run_id: run_id.to_owned(),
            reason: "allowed characters are ASCII letters, digits, '.', '_', and '-'".into(),
        });
    }
    let mut components = Path::new(run_id).components();
    if !matches!(components.next(), Some(Component::Normal(_))) || components.next().is_some() {
        return Err(DoctorRuntimeError::InvalidRunId {
            run_id: run_id.to_owned(),
            reason: "run id must be exactly one normal path component".into(),
        });
    }
    Ok(())
}

fn resolve_doctor_run_dir(
    workspace: &Path,
    run_id: &str,
) -> Result<(PathBuf, PathBuf), DoctorRuntimeError> {
    validate_doctor_run_id(run_id)?;
    let workspace = canonical_doctor_workspace(workspace)?;
    let doctor_dir = workspace.join(".doctor");
    let runs_dir = doctor_dir.join("runs");
    let run_dir = runs_dir.join(run_id);
    validate_doctor_lifecycle_paths([
        workspace.as_path(),
        doctor_dir.as_path(),
        runs_dir.as_path(),
        run_dir.as_path(),
        run_dir.join("state.json").as_path(),
    ])?;
    let metadata = fs::symlink_metadata(&run_dir).map_err(|source| DoctorRuntimeError::Io {
        context: format!("inspect doctor run directory {}", run_dir.display()),
        source,
    })?;
    if !metadata.is_dir() {
        return Err(DoctorRuntimeError::RunArtifactInvalid {
            path: run_dir,
            reason: "run path is not a directory".into(),
        });
    }
    Ok((workspace, run_dir))
}

fn validate_run_state_binding(
    workspace: &Path,
    run_id: &str,
    run_dir: &Path,
    state: &RunState,
) -> Result<(), DoctorRuntimeError> {
    if state.schema != RUN_STATE_SCHEMA_V2 {
        return Err(DoctorRuntimeError::RunArtifactInvalid {
            path: run_dir.join("state.json"),
            reason: format!(
                "unsupported schema {:?}; expected {RUN_STATE_SCHEMA_V2:?}",
                state.schema
            ),
        });
    }
    if state.run_id != run_id {
        return Err(DoctorRuntimeError::RunArtifactInvalid {
            path: run_dir.join("state.json"),
            reason: format!(
                "state run_id {:?} does not match requested run {run_id:?}",
                state.run_id
            ),
        });
    }
    let state_workspace = canonical_doctor_workspace(&state.workspace)?;
    if state_workspace != workspace {
        return Err(DoctorRuntimeError::RunArtifactInvalid {
            path: run_dir.join("state.json"),
            reason: format!(
                "state workspace {} does not match requested workspace {}",
                state_workspace.display(),
                workspace.display()
            ),
        });
    }
    Ok(())
}

/// Resolve and validate one persisted doctor run without following run-root or
/// state-file symlinks. The returned state is bound to both the requested
/// workspace and run identifier.
pub fn read_doctor_run_state(
    workspace: &Path,
    run_id: &str,
) -> Result<(PathBuf, RunState), DoctorRuntimeError> {
    let (workspace, run_dir) = resolve_doctor_run_dir(workspace, run_id)?;
    let state = read_state(&run_dir)?;
    validate_run_state_binding(&workspace, run_id, &run_dir, &state)?;
    Ok((run_dir, state))
}

fn validate_doctor_lifecycle_paths<'a>(
    paths: impl IntoIterator<Item = &'a Path>,
) -> Result<(), DoctorRuntimeError> {
    for path in paths {
        match super::path_safety::first_existing_symlink_component(path) {
            Ok(Some(path)) => return Err(DoctorRuntimeError::SymlinkedRunRoot { path }),
            Ok(None) => {}
            Err(source) => {
                return Err(DoctorRuntimeError::Io {
                    context: format!("inspect doctor lifecycle path {}", path.display()),
                    source,
                });
            }
        }
    }
    Ok(())
}

#[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))]
fn prepare_doctor_lifecycle(
    workspace: &Path,
    run_id: &str,
    lock_path: &Path,
    run_dir: &Path,
) -> Result<(DoctorLifecycleHandles, fs::File), DoctorRuntimeError> {
    use rustix::fs::{Mode, OFlags};

    let directory_flags = OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC;
    let workspace_fd = rustix::fs::openat(
        rustix::fs::CWD,
        workspace,
        directory_flags,
        Mode::from_raw_mode(0),
    )
    .map(fs::File::from)
    .map_err(|source| doctor_lifecycle_errno(workspace, "open canonical workspace", source))?;

    let ee_path = workspace.join(".ee");
    let ee_dir =
        open_or_create_doctor_directory_at(&workspace_fd, OsStr::new(".ee"), &ee_path, true)?;
    let lock_file = acquire_doctor_lock_at(&ee_dir, lock_path)?;

    let prepared = (|| {
        let doctor_path = workspace.join(".doctor");
        let doctor_dir = open_or_create_doctor_directory_at(
            &workspace_fd,
            OsStr::new(".doctor"),
            &doctor_path,
            true,
        )?;
        let runs_path = doctor_path.join("runs");
        let runs_dir =
            open_or_create_doctor_directory_at(&doctor_dir, OsStr::new("runs"), &runs_path, true)?;
        let run_dir_fd =
            open_or_create_doctor_directory_at(&runs_dir, OsStr::new(run_id), run_dir, false)?;
        let backups_dir = open_or_create_doctor_directory_at(
            &run_dir_fd,
            OsStr::new("backups"),
            &run_dir.join("backups"),
            false,
        )?;
        let quarantine_dir = open_or_create_doctor_directory_at(
            &run_dir_fd,
            OsStr::new("quarantine"),
            &run_dir.join("quarantine"),
            false,
        )?;

        let actions_path = run_dir.join("actions.jsonl");
        let actions_fd = rustix::fs::openat(
            &run_dir_fd,
            "actions.jsonl",
            OFlags::WRONLY
                | OFlags::CREATE
                | OFlags::EXCL
                | OFlags::APPEND
                | OFlags::NOFOLLOW
                | OFlags::CLOEXEC,
            Mode::from_raw_mode(0o600),
        )
        .map_err(|source| doctor_lifecycle_errno(&actions_path, "create actions.jsonl", source))?;

        Ok((
            doctor_dir,
            runs_dir,
            run_dir_fd,
            backups_dir,
            quarantine_dir,
            fs::File::from(actions_fd),
        ))
    })();

    match prepared {
        Ok((doctor_dir, runs_dir, run_dir, backups_dir, quarantine_dir, actions_handle)) => Ok((
            DoctorLifecycleHandles {
                workspace_dir: workspace_fd,
                ee_dir,
                lock_file,
                doctor_dir,
                runs_dir,
                run_dir,
                backups_dir,
                quarantine_dir,
            },
            actions_handle,
        )),
        Err(error) => {
            let _ = Fs4FileExt::unlock(&lock_file);
            Err(error)
        }
    }
}

#[cfg(windows)]
fn prepare_doctor_lifecycle(
    workspace: &Path,
    _run_id: &str,
    lock_path: &Path,
    run_dir: &Path,
) -> Result<(DoctorLifecycleHandles, fs::File), DoctorRuntimeError> {
    let ee_dir = workspace.join(".ee");
    fs::create_dir_all(&ee_dir).map_err(|source| DoctorRuntimeError::Io {
        context: format!("create_dir_all({})", ee_dir.display()),
        source,
    })?;

    let lock = acquire_windows_doctor_lock(lock_path)?;

    let backups_dir = run_dir.join("backups");
    let quarantine_dir = run_dir.join("quarantine");
    for dir in [run_dir, backups_dir.as_path(), quarantine_dir.as_path()] {
        if let Err(source) = fs::create_dir_all(dir) {
            let _ = Fs4FileExt::unlock(&lock);
            return Err(DoctorRuntimeError::BackupDirUnwritable {
                dir: dir.to_path_buf(),
                source,
            });
        }
    }

    let actions_path = run_dir.join("actions.jsonl");
    let actions_handle = match fs::OpenOptions::new()
        .create_new(true)
        .append(true)
        .open(&actions_path)
    {
        Ok(handle) => handle,
        Err(source) => {
            let _ = Fs4FileExt::unlock(&lock);
            return Err(DoctorRuntimeError::Io {
                context: format!("open actions.jsonl {}", actions_path.display()),
                source,
            });
        }
    };

    Ok((DoctorLifecycleHandles { lock_file: lock }, actions_handle))
}

#[cfg(windows)]
fn configure_windows_doctor_lock_open_no_follow(options: &mut fs::OpenOptions) {
    use std::os::windows::fs::OpenOptionsExt;

    // Open the reparse-point object itself instead of following it. The
    // metadata check above/below then rejects symlink/junction substitutions
    // without ever opening their target for writing.
    const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000;
    options.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT);
}

#[cfg(windows)]
fn acquire_windows_doctor_lock(lock_path: &Path) -> Result<fs::File, DoctorRuntimeError> {
    use std::os::windows::fs::MetadataExt;

    if fs::symlink_metadata(lock_path).is_ok_and(|metadata| metadata.file_type().is_symlink()) {
        return Err(DoctorRuntimeError::SymlinkedRunRoot {
            path: lock_path.to_path_buf(),
        });
    }

    let mut create_options = fs::OpenOptions::new();
    create_options
        .read(true)
        .write(true)
        .create_new(true)
        .truncate(false);
    configure_windows_doctor_lock_open_no_follow(&mut create_options);
    let (mut lock, created) = match create_options.open(lock_path) {
        Ok(lock) => (lock, true),
        Err(source) if source.kind() == io::ErrorKind::AlreadyExists => {
            let mut existing_options = fs::OpenOptions::new();
            existing_options.read(true).write(true).truncate(false);
            configure_windows_doctor_lock_open_no_follow(&mut existing_options);
            let lock =
                existing_options
                    .open(lock_path)
                    .map_err(|source| DoctorRuntimeError::Io {
                        context: format!(
                            "open existing persistent doctor lock {}",
                            lock_path.display()
                        ),
                        source,
                    })?;
            (lock, false)
        }
        Err(source) => {
            return Err(DoctorRuntimeError::Io {
                context: format!("create persistent doctor lock {}", lock_path.display()),
                source,
            });
        }
    };
    let metadata = lock.metadata().map_err(|source| DoctorRuntimeError::Io {
        context: format!("inspect persistent doctor lock {}", lock_path.display()),
        source,
    })?;
    const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x0000_0400;
    if !metadata.is_file() || metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 {
        return Err(DoctorRuntimeError::Io {
            context: format!("inspect persistent doctor lock {}", lock_path.display()),
            source: io::Error::new(
                io::ErrorKind::InvalidInput,
                "doctor lock is not a regular non-reparse file",
            ),
        });
    }
    acquire_doctor_advisory_lock(&lock, lock_path)?;
    if created && let Err(source) = write_doctor_lock_contents(&mut lock, DOCTOR_LOCK_FILE_MARKER) {
        let _ = Fs4FileExt::unlock(&lock);
        return Err(DoctorRuntimeError::Io {
            context: format!("initialize persistent doctor lock {}", lock_path.display()),
            source,
        });
    }
    Ok(lock)
}

#[cfg(not(any(
    target_os = "linux",
    target_os = "android",
    target_vendor = "apple",
    windows
)))]
fn prepare_doctor_lifecycle(
    _workspace: &Path,
    _run_id: &str,
    lock_path: &Path,
    _run_dir: &Path,
) -> Result<(DoctorLifecycleHandles, fs::File), DoctorRuntimeError> {
    Err(DoctorRuntimeError::Io {
        context: format!("acquire persistent doctor lock {}", lock_path.display()),
        source: io::Error::new(
            io::ErrorKind::Unsupported,
            "doctor mutation is disabled because this platform cannot prove lock ownership",
        ),
    })
}

#[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))]
fn open_or_create_doctor_directory_at(
    parent: &fs::File,
    name: &OsStr,
    full_path: &Path,
    allow_existing: bool,
) -> Result<fs::File, DoctorRuntimeError> {
    use rustix::fs::{FileType, Mode, OFlags};
    use rustix::io::Errno;

    match rustix::fs::mkdirat(parent, name, Mode::from_raw_mode(0o700)) {
        Ok(()) => {}
        Err(source) if source == Errno::EXIST && allow_existing => {}
        Err(source) if source == Errno::EXIST => {
            if doctor_entry_type_at(parent, name)? == Some(FileType::Symlink) {
                return Err(DoctorRuntimeError::SymlinkedRunRoot {
                    path: full_path.to_path_buf(),
                });
            }
            return Err(DoctorRuntimeError::Io {
                context: format!("create unique doctor directory {}", full_path.display()),
                source: io::Error::new(
                    io::ErrorKind::AlreadyExists,
                    "doctor run directory already exists",
                ),
            });
        }
        Err(source) => {
            return Err(doctor_lifecycle_errno(
                full_path,
                "create doctor directory",
                source,
            ));
        }
    }

    rustix::fs::openat(
        parent,
        name,
        OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
        Mode::from_raw_mode(0),
    )
    .map(fs::File::from)
    .map_err(|source| doctor_lifecycle_errno(full_path, "open doctor directory", source))
}

#[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))]
#[derive(Debug)]
struct DoctorRelativeDestination {
    parent: fs::File,
    leaf: OsString,
    display_path: PathBuf,
}

#[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))]
fn prepare_doctor_relative_destination(
    root: &fs::File,
    root_path: &Path,
    relative: &Path,
) -> Result<DoctorRelativeDestination, DoctorRuntimeError> {
    let leaf = relative
        .file_name()
        .filter(|name| !name.is_empty())
        .ok_or_else(|| DoctorRuntimeError::BlastRadiusExceeded {
            path: relative.to_path_buf(),
            allowed_roots: vec![root_path.to_path_buf()],
        })?
        .to_os_string();
    let parent_relative = relative.parent().unwrap_or_else(|| Path::new(""));
    let parent = open_or_create_doctor_relative_directory(root, root_path, parent_relative)?;

    Ok(DoctorRelativeDestination {
        parent,
        leaf,
        display_path: root_path.join(relative),
    })
}

#[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))]
fn open_or_create_doctor_relative_directory(
    root: &fs::File,
    root_path: &Path,
    relative: &Path,
) -> Result<fs::File, DoctorRuntimeError> {
    let mut directory = root.try_clone().map_err(|source| DoctorRuntimeError::Io {
        context: format!(
            "duplicate doctor directory descriptor {}",
            root_path.display()
        ),
        source,
    })?;
    let mut display_path = root_path.to_path_buf();

    for component in relative.components() {
        let Component::Normal(name) = component else {
            return Err(DoctorRuntimeError::BlastRadiusExceeded {
                path: relative.to_path_buf(),
                allowed_roots: vec![root_path.to_path_buf()],
            });
        };
        display_path.push(name);
        directory = open_or_create_doctor_directory_at(&directory, name, &display_path, true)?;
    }

    Ok(directory)
}

#[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))]
fn acquire_doctor_lock_at(
    ee_dir: &fs::File,
    lock_path: &Path,
) -> Result<fs::File, DoctorRuntimeError> {
    use rustix::fs::{Mode, OFlags};
    use rustix::io::Errno;

    let create_flags =
        OFlags::RDWR | OFlags::CREATE | OFlags::EXCL | OFlags::NOFOLLOW | OFlags::CLOEXEC;
    let (fd, created) = match rustix::fs::openat(
        ee_dir,
        ".doctor.lock",
        create_flags,
        Mode::from_raw_mode(0o600),
    ) {
        Ok(fd) => (fd, true),
        Err(source) if source == Errno::EXIST => {
            let fd = rustix::fs::openat(
                ee_dir,
                ".doctor.lock",
                OFlags::RDWR | OFlags::NOFOLLOW | OFlags::CLOEXEC,
                Mode::from_raw_mode(0),
            )
            .map_err(|source| {
                doctor_lifecycle_errno(lock_path, "open existing persistent doctor lock", source)
            })?;
            (fd, false)
        }
        Err(source) => {
            return Err(doctor_lifecycle_errno(
                lock_path,
                "create persistent doctor lock",
                source,
            ));
        }
    };

    let mut lock = fs::File::from(fd);
    acquire_doctor_advisory_lock(&lock, lock_path)?;
    let initialized = ensure_doctor_lock_binding_at(ee_dir, &lock).and_then(|()| {
        if created {
            write_doctor_lock_contents(&mut lock, DOCTOR_LOCK_FILE_MARKER)
        } else {
            Ok(())
        }
    });
    if let Err(source) = initialized {
        let _ = Fs4FileExt::unlock(&lock);
        return Err(DoctorRuntimeError::Io {
            context: format!("initialize persistent doctor lock {}", lock_path.display()),
            source,
        });
    }
    Ok(lock)
}

fn acquire_doctor_advisory_lock(
    lock_file: &fs::File,
    lock_path: &Path,
) -> Result<(), DoctorRuntimeError> {
    match Fs4FileExt::try_lock(lock_file) {
        Ok(()) => Ok(()),
        Err(fs4::TryLockError::WouldBlock) => Err(DoctorRuntimeError::ConcurrencyLost {
            lock_path: lock_path.to_path_buf(),
            holder_run_id: read_doctor_lock_holder_file(lock_file),
        }),
        Err(fs4::TryLockError::Error(source)) => Err(DoctorRuntimeError::Io {
            context: format!("acquire persistent doctor lock {}", lock_path.display()),
            source,
        }),
    }
}

fn read_doctor_lock_holder_file(lock_file: &fs::File) -> Option<String> {
    let metadata = lock_file.metadata().ok()?;
    if !metadata.is_file() || metadata.len() > DOCTOR_LOCK_FILE_INSPECT_LIMIT {
        return None;
    }
    let mut raw = String::new();
    lock_file
        .take(DOCTOR_LOCK_FILE_INSPECT_LIMIT.saturating_add(1))
        .read_to_string(&mut raw)
        .ok()?;
    if u64::try_from(raw.len()).unwrap_or(u64::MAX) > DOCTOR_LOCK_FILE_INSPECT_LIMIT {
        return None;
    }
    doctor_lock_holder_from_raw(&raw)
}

fn write_doctor_lock_contents(lock_file: &mut fs::File, contents: &str) -> io::Result<()> {
    #[cfg(test)]
    if DOCTOR_LOCK_FAIL_NEXT_WRITE.with(|flag| flag.replace(false)) {
        return Err(io::Error::other(
            "injected doctor lock metadata write failure",
        ));
    }

    // The advisory lock is already held and every write is descriptor-based.
    // If a peer renames or replaces `.doctor.lock` now, this still updates
    // only the exact inode/handle acquired above and never the replacement.
    lock_file.set_len(0)?;
    lock_file.seek(SeekFrom::Start(0))?;
    lock_file.write_all(contents.as_bytes())?;
    lock_file.flush()
}

#[cfg(test)]
fn fail_next_doctor_lock_metadata_write() {
    DOCTOR_LOCK_FAIL_NEXT_WRITE.with(|flag| flag.set(true));
}

#[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))]
fn ensure_doctor_lock_binding_at(ee_dir: &fs::File, lock_file: &fs::File) -> io::Result<()> {
    use rustix::fs::{AtFlags, FileType};

    let expected = rustix::fs::fstat(lock_file).map_err(io::Error::from)?;
    let observed = rustix::fs::statat(ee_dir, ".doctor.lock", AtFlags::SYMLINK_NOFOLLOW).map_err(
        |source| {
            if source == rustix::io::Errno::NOENT {
                io::Error::new(
                    io::ErrorKind::PermissionDenied,
                    "doctor lock path disappeared during acquisition",
                )
            } else {
                io::Error::from(source)
            }
        },
    )?;

    if FileType::from_raw_mode(expected.st_mode) != FileType::RegularFile
        || FileType::from_raw_mode(observed.st_mode) != FileType::RegularFile
        || observed.st_dev != expected.st_dev
        || observed.st_ino != expected.st_ino
        || expected.st_nlink != 1
        || observed.st_nlink != 1
        || expected.st_uid != rustix::process::geteuid().as_raw()
        || observed.st_uid != expected.st_uid
    {
        return Err(io::Error::new(
            io::ErrorKind::PermissionDenied,
            "doctor lock path changed or lacks single-link process ownership",
        ));
    }
    Ok(())
}

fn doctor_lock_holder_from_raw(raw: &str) -> Option<String> {
    raw.lines()
        .next()
        .filter(|holder| *holder != DOCTOR_LOCK_FILE_MARKER.trim_end())
        .map(str::to_owned)
}

#[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))]
fn doctor_entry_type_at(
    directory: &fs::File,
    name: &OsStr,
) -> Result<Option<rustix::fs::FileType>, DoctorRuntimeError> {
    use rustix::fs::{AtFlags, FileType};
    use rustix::io::Errno;

    match rustix::fs::statat(directory, name, AtFlags::SYMLINK_NOFOLLOW) {
        Ok(stat) => Ok(Some(FileType::from_raw_mode(stat.st_mode))),
        Err(source) if source == Errno::NOENT => Ok(None),
        Err(source) => Err(DoctorRuntimeError::Io {
            context: format!("inspect doctor lifecycle entry {}", name.to_string_lossy()),
            source: io::Error::from(source),
        }),
    }
}

#[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))]
fn doctor_file_type_name(file_type: rustix::fs::FileType) -> &'static str {
    use rustix::fs::FileType;

    match file_type {
        FileType::RegularFile => "regular file",
        FileType::Directory => "directory",
        FileType::Symlink => "symbolic link",
        FileType::Fifo => "fifo",
        FileType::Socket => "socket",
        FileType::CharacterDevice => "character device",
        FileType::BlockDevice => "block device",
        FileType::Unknown => "unknown filesystem entry",
    }
}

#[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))]
fn doctor_lifecycle_errno(
    path: &Path,
    operation: &str,
    source: rustix::io::Errno,
) -> DoctorRuntimeError {
    if matches!(source, rustix::io::Errno::LOOP | rustix::io::Errno::NOTDIR)
        && let Ok(Some(path)) = super::path_safety::first_existing_symlink_component(path)
    {
        return DoctorRuntimeError::SymlinkedRunRoot { path };
    }
    DoctorRuntimeError::Io {
        context: format!("{operation} {}", path.display()),
        source: io::Error::from(source),
    }
}

#[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))]
/// Detects whether the public workspace names still identify the directories
/// opened at run start. Device/inode equality is only a substitution detector;
/// it is not TOCTOU-safe authorization for a later pathname write. Backup and
/// quarantine mutations are therefore performed relative to their retained
/// directory descriptors even after this check succeeds.
fn ensure_doctor_lifecycle_bindings(
    lifecycle: &DoctorLifecycleHandles,
    workspace: &Path,
    run_dir: &Path,
) -> Result<(), DoctorRuntimeError> {
    let doctor_dir = workspace.join(".doctor");
    let runs_dir = doctor_dir.join("runs");

    ensure_doctor_directory_binding(
        rustix::fs::CWD,
        workspace,
        &lifecycle.workspace_dir,
        workspace,
    )?;
    ensure_doctor_directory_binding(
        &lifecycle.workspace_dir,
        Path::new(".ee"),
        &lifecycle.ee_dir,
        &workspace.join(".ee"),
    )?;
    ensure_doctor_directory_binding(
        &lifecycle.workspace_dir,
        Path::new(".doctor"),
        &lifecycle.doctor_dir,
        &doctor_dir,
    )?;
    ensure_doctor_directory_binding(
        &lifecycle.doctor_dir,
        Path::new("runs"),
        &lifecycle.runs_dir,
        &runs_dir,
    )?;
    let run_name = run_dir.file_name().ok_or_else(|| DoctorRuntimeError::Io {
        context: format!(
            "derive doctor run directory name from {}",
            run_dir.display()
        ),
        source: io::Error::new(
            io::ErrorKind::InvalidInput,
            "run directory has no file name",
        ),
    })?;
    ensure_doctor_directory_binding(
        &lifecycle.runs_dir,
        Path::new(run_name),
        &lifecycle.run_dir,
        run_dir,
    )?;
    ensure_doctor_directory_binding(
        &lifecycle.run_dir,
        Path::new("backups"),
        &lifecycle.backups_dir,
        &run_dir.join("backups"),
    )?;
    ensure_doctor_directory_binding(
        &lifecycle.run_dir,
        Path::new("quarantine"),
        &lifecycle.quarantine_dir,
        &run_dir.join("quarantine"),
    )
}

#[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))]
fn ensure_doctor_directory_binding<Fd: std::os::fd::AsFd>(
    parent: Fd,
    name: &Path,
    opened: &fs::File,
    full_path: &Path,
) -> Result<(), DoctorRuntimeError> {
    use rustix::fs::{AtFlags, FileType};

    let observed = match rustix::fs::statat(parent, name, AtFlags::SYMLINK_NOFOLLOW) {
        Ok(stat) => stat,
        Err(source)
            if matches!(
                source,
                rustix::io::Errno::NOENT | rustix::io::Errno::LOOP | rustix::io::Errno::NOTDIR
            ) =>
        {
            return Err(DoctorRuntimeError::LifecycleRootChanged {
                path: full_path.to_path_buf(),
            });
        }
        Err(source) => {
            return Err(DoctorRuntimeError::Io {
                context: format!("inspect doctor lifecycle binding {}", full_path.display()),
                source: io::Error::from(source),
            });
        }
    };
    let expected = rustix::fs::fstat(opened).map_err(|source| DoctorRuntimeError::Io {
        context: format!("inspect opened doctor directory {}", full_path.display()),
        source: io::Error::from(source),
    })?;

    if FileType::from_raw_mode(observed.st_mode) != FileType::Directory
        || observed.st_dev != expected.st_dev
        || observed.st_ino != expected.st_ino
    {
        return Err(DoctorRuntimeError::LifecycleRootChanged {
            path: full_path.to_path_buf(),
        });
    }
    Ok(())
}

#[cfg(not(any(target_os = "linux", target_os = "android", target_vendor = "apple")))]
fn ensure_doctor_lifecycle_bindings(
    _lifecycle: &DoctorLifecycleHandles,
    workspace: &Path,
    run_dir: &Path,
) -> Result<(), DoctorRuntimeError> {
    let ee_dir = workspace.join(".ee");
    let doctor_dir = workspace.join(".doctor");
    let backups_dir = run_dir.join("backups");
    let quarantine_dir = run_dir.join("quarantine");
    validate_doctor_lifecycle_paths([
        workspace,
        ee_dir.as_path(),
        doctor_dir.as_path(),
        run_dir,
        backups_dir.as_path(),
        quarantine_dir.as_path(),
    ])
}

fn write_lifecycle_state(
    lifecycle: &DoctorLifecycleHandles,
    run_dir: &Path,
    state: &RunState,
) -> Result<(), DoctorRuntimeError> {
    let bytes = serde_json::to_vec_pretty(state).map_err(|error| DoctorRuntimeError::Io {
        context: "serialize RunState".into(),
        source: io::Error::new(io::ErrorKind::InvalidData, error),
    })?;

    #[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))]
    {
        return write_doctor_file_atomic_at(&lifecycle.run_dir, "state.json", &bytes).map_err(
            |source| DoctorRuntimeError::Io {
                context: format!("write state.json {}", run_dir.join("state.json").display()),
                source,
            },
        );
    }

    #[cfg(not(any(target_os = "linux", target_os = "android", target_vendor = "apple")))]
    {
        let _ = lifecycle;
        let path = run_dir.join("state.json");
        write_file_atomic(&path, &bytes).map_err(|source| DoctorRuntimeError::Io {
            context: format!("write state.json {}", path.display()),
            source,
        })
    }
}

#[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))]
fn write_doctor_file_atomic_at(directory: &fs::File, name: &str, bytes: &[u8]) -> io::Result<()> {
    use rustix::fs::{Mode, OFlags};

    let sequence = DOCTOR_STATE_FILE_SEQUENCE.fetch_add(1, Ordering::Relaxed);
    let temporary = format!(".{name}.tmp.{}.{}", std::process::id(), sequence);
    let fd = rustix::fs::openat(
        directory,
        temporary.as_str(),
        OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL | OFlags::NOFOLLOW | OFlags::CLOEXEC,
        Mode::from_raw_mode(0o600),
    )
    .map_err(io::Error::from)?;
    let mut file = fs::File::from(fd);
    file.write_all(bytes)?;
    file.flush()?;
    drop(file);
    rustix::fs::renameat(directory, temporary.as_str(), directory, name).map_err(io::Error::from)
}

#[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))]
fn publish_doctor_latest(
    lifecycle: &DoctorLifecycleHandles,
    run_id: &str,
    run_dir: &Path,
    latest_link: &Path,
) -> Result<(), DoctorRuntimeError> {
    use rustix::fs::{FileType, RenameFlags};

    const CANDIDATE: &str = "latest-candidate";
    const PREVIOUS: &str = "previous-latest";

    let target = Path::new("runs").join(run_id);
    rustix::fs::symlinkat(&target, &lifecycle.run_dir, CANDIDATE).map_err(|source| {
        doctor_lifecycle_errno(
            &latest_link.with_file_name(CANDIDATE),
            "create latest candidate",
            source,
        )
    })?;

    match doctor_entry_type_at(&lifecycle.doctor_dir, OsStr::new("latest"))? {
        None => rustix::fs::renameat_with(
            &lifecycle.run_dir,
            CANDIDATE,
            &lifecycle.doctor_dir,
            "latest",
            RenameFlags::NOREPLACE,
        )
        .map_err(|source| {
            if source == rustix::io::Errno::EXIST {
                let observed = doctor_entry_type_at(&lifecycle.doctor_dir, OsStr::new("latest"))
                    .ok()
                    .flatten()
                    .map(doctor_file_type_name)
                    .unwrap_or("concurrently-created entry");
                DoctorRuntimeError::UnsafeLatestEntry {
                    path: latest_link.to_path_buf(),
                    observed_kind: observed.to_owned(),
                }
            } else {
                doctor_lifecycle_errno(latest_link, "publish latest", source)
            }
        }),
        Some(FileType::Symlink) => {
            rustix::fs::renameat_with(
                &lifecycle.run_dir,
                CANDIDATE,
                &lifecycle.doctor_dir,
                "latest",
                RenameFlags::EXCHANGE,
            )
            .map_err(|source| doctor_lifecycle_errno(latest_link, "exchange latest", source))?;

            let displaced = doctor_entry_type_at(&lifecycle.run_dir, OsStr::new(CANDIDATE))?;
            if displaced == Some(FileType::Symlink) {
                // Preserve the prior pointer as a run artifact. This is an
                // atomic rename, not a delete, and the unique run directory
                // guarantees `previous-latest` is not an existing user path.
                return rustix::fs::renameat_with(
                    &lifecycle.run_dir,
                    CANDIDATE,
                    &lifecycle.run_dir,
                    PREVIOUS,
                    RenameFlags::NOREPLACE,
                )
                .map_err(|source| DoctorRuntimeError::Io {
                    context: format!(
                        "preserve prior latest at {}",
                        run_dir.join(PREVIOUS).display()
                    ),
                    source: io::Error::from(source),
                });
            }

            // A peer substituted a non-symlink after our initial inspection.
            // Exchange it back so no regular file is overwritten or removed.
            let rollback = rustix::fs::renameat_with(
                &lifecycle.run_dir,
                CANDIDATE,
                &lifecycle.doctor_dir,
                "latest",
                RenameFlags::EXCHANGE,
            );
            let observed = displaced
                .map(doctor_file_type_name)
                .unwrap_or("missing entry")
                .to_owned();
            if let Err(source) = rollback {
                return Err(DoctorRuntimeError::Io {
                    context: format!(
                        "rollback concurrent latest substitution at {} (displaced {observed})",
                        latest_link.display()
                    ),
                    source: io::Error::from(source),
                });
            }
            Err(DoctorRuntimeError::UnsafeLatestEntry {
                path: latest_link.to_path_buf(),
                observed_kind: observed,
            })
        }
        Some(file_type) => Err(DoctorRuntimeError::UnsafeLatestEntry {
            path: latest_link.to_path_buf(),
            observed_kind: doctor_file_type_name(file_type).to_owned(),
        }),
    }
}

#[cfg(not(any(target_os = "linux", target_os = "android", target_vendor = "apple")))]
fn publish_doctor_latest(
    _lifecycle: &DoctorLifecycleHandles,
    run_id: &str,
    run_dir: &Path,
    latest_link: &Path,
) -> Result<(), DoctorRuntimeError> {
    // The parent directories must be real, but the latest leaf is itself a
    // symlink after a successful run. Inspect that leaf without following it
    // below so a second run can preserve and replace the prior pointer.
    validate_doctor_lifecycle_paths([run_dir, latest_link.parent().unwrap_or(latest_link)])?;

    match fs::symlink_metadata(latest_link) {
        Ok(metadata) if !metadata.file_type().is_symlink() => {
            return Err(DoctorRuntimeError::UnsafeLatestEntry {
                path: latest_link.to_path_buf(),
                observed_kind: if metadata.is_dir() {
                    "directory".to_owned()
                } else {
                    "regular file".to_owned()
                },
            });
        }
        Ok(_) => {
            let previous = run_dir.join("previous-latest");
            if fs::symlink_metadata(&previous).is_ok() {
                return Err(DoctorRuntimeError::Io {
                    context: format!("preserve prior latest at {}", previous.display()),
                    source: io::Error::new(
                        io::ErrorKind::AlreadyExists,
                        "previous-latest run artifact already exists",
                    ),
                });
            }

            fs::rename(latest_link, &previous).map_err(|source| DoctorRuntimeError::Io {
                context: format!(
                    "preserve existing latest {} at {}",
                    latest_link.display(),
                    previous.display()
                ),
                source,
            })?;
            let displaced =
                fs::symlink_metadata(&previous).map_err(|source| DoctorRuntimeError::Io {
                    context: format!("inspect preserved latest {}", previous.display()),
                    source,
                })?;
            if !displaced.file_type().is_symlink() {
                let observed_kind = if displaced.is_dir() {
                    "directory"
                } else {
                    "regular file"
                };
                let _ = fs::rename(&previous, latest_link);
                return Err(DoctorRuntimeError::UnsafeLatestEntry {
                    path: latest_link.to_path_buf(),
                    observed_kind: observed_kind.to_owned(),
                });
            }

            let target = Path::new("runs").join(run_id);
            let created = create_doctor_latest_symlink(&target, latest_link);
            if let Err(source) = created {
                if fs::symlink_metadata(latest_link).is_err() {
                    let _ = fs::rename(&previous, latest_link);
                }
                return Err(DoctorRuntimeError::Io {
                    context: format!("create latest link {}", latest_link.display()),
                    source,
                });
            }
            return Ok(());
        }
        Err(source) if source.kind() == io::ErrorKind::NotFound => {
            let target = Path::new("runs").join(run_id);
            create_doctor_latest_symlink(&target, latest_link).map_err(|source| {
                DoctorRuntimeError::Io {
                    context: format!("create latest link {}", latest_link.display()),
                    source,
                }
            })?;
            return Ok(());
        }
        Err(source) => {
            return Err(DoctorRuntimeError::Io {
                context: format!("inspect latest link {}", latest_link.display()),
                source,
            });
        }
    }
}

#[cfg(all(
    unix,
    not(any(target_os = "linux", target_os = "android", target_vendor = "apple"))
))]
fn create_doctor_latest_symlink(target: &Path, latest_link: &Path) -> io::Result<()> {
    std::os::unix::fs::symlink(target, latest_link)
}

#[cfg(windows)]
fn create_doctor_latest_symlink(target: &Path, latest_link: &Path) -> io::Result<()> {
    std::os::windows::fs::symlink_dir(target, latest_link)
}

#[cfg(not(any(unix, windows)))]
fn create_doctor_latest_symlink(_target: &Path, _latest_link: &Path) -> io::Result<()> {
    Err(io::Error::new(
        io::ErrorKind::Unsupported,
        "symbolic links are unsupported on this platform",
    ))
}

#[cfg(test)]
fn set_doctor_lock_before_unlock_hook(hook: impl FnOnce() + 'static) {
    DOCTOR_LOCK_BEFORE_UNLOCK_HOOK.with(|slot| {
        *slot.borrow_mut() = Some(Box::new(hook));
    });
}

#[cfg(test)]
fn run_doctor_lock_before_unlock_hook() {
    DOCTOR_LOCK_BEFORE_UNLOCK_HOOK.with(|slot| {
        if let Some(hook) = slot.borrow_mut().take() {
            hook();
        }
    });
}

#[cfg(any(
    target_os = "linux",
    target_os = "android",
    target_vendor = "apple",
    windows
))]
fn release_doctor_lock(lifecycle: &DoctorLifecycleHandles, _lock_path: &Path) -> io::Result<()> {
    unlock_doctor_lock_file(&lifecycle.lock_file)
}

#[cfg(any(
    target_os = "linux",
    target_os = "android",
    target_vendor = "apple",
    windows
))]
fn unlock_doctor_lock_file(lock_file: &fs::File) -> io::Result<()> {
    #[cfg(test)]
    run_doctor_lock_before_unlock_hook();

    // Release only the retained kernel lock. The `.doctor.lock` pathname is
    // persistent and may now name a peer replacement, so teardown must never
    // inspect, unlink, overwrite, or rename it.
    Fs4FileExt::unlock(lock_file)
}

#[cfg(not(any(
    target_os = "linux",
    target_os = "android",
    target_vendor = "apple",
    windows
)))]
fn unlock_doctor_lock_file(_lock_file: &fs::File) -> io::Result<()> {
    Err(io::Error::new(
        io::ErrorKind::Unsupported,
        "doctor lock ownership cannot be proven on this platform",
    ))
}

#[cfg(not(any(
    target_os = "linux",
    target_os = "android",
    target_vendor = "apple",
    windows
)))]
fn release_doctor_lock(_lifecycle: &DoctorLifecycleHandles, _lock_path: &Path) -> io::Result<()> {
    Err(io::Error::new(
        io::ErrorKind::Unsupported,
        "doctor mutation is disabled because this platform cannot prove lock ownership",
    ))
}

fn derive_run_id(target_sha: &str) -> String {
    let now = Utc::now();
    let sequence = DOCTOR_RUN_ID_SEQUENCE.fetch_add(1, Ordering::Relaxed);
    let timestamp_nanos = now.timestamp_nanos_opt().unwrap_or_default();
    let mut hasher = blake3::Hasher::new();
    hasher.update(target_sha.as_bytes());
    hasher.update(b"|");
    hasher.update(timestamp_nanos.to_string().as_bytes());
    hasher.update(b"|");
    hasher.update(std::process::id().to_string().as_bytes());
    hasher.update(b"|");
    hasher.update(sequence.to_string().as_bytes());
    let hash = hasher.finalize();
    let hex = hash.to_hex();
    let short = &hex.as_str()[..6];
    format!(
        "{}__{}__{}",
        now.format("%Y-%m-%dT%H-%M-%S%.9fZ"),
        sequence,
        short
    )
}

fn hash_file(path: &Path) -> Result<String, DoctorRuntimeError> {
    let mut hasher = blake3::Hasher::new();
    let mut file = fs::File::open(path).map_err(|source| DoctorRuntimeError::Io {
        context: format!("open for hashing: {}", path.display()),
        source,
    })?;
    let mut buf = [0u8; 8192];
    loop {
        let n = file
            .read(&mut buf)
            .map_err(|source| DoctorRuntimeError::Io {
                context: format!("read for hashing: {}", path.display()),
                source,
            })?;
        if n == 0 {
            break;
        }
        hasher.update(&buf[..n]);
    }
    Ok(hasher.finalize().to_hex().to_string())
}

fn hash_bytes(bytes: &[u8]) -> String {
    blake3::hash(bytes).to_hex().to_string()
}

fn read_mode(path: &Path) -> Option<u32> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt as _;
        fs::metadata(path).ok().map(|m| m.permissions().mode())
    }
    #[cfg(not(unix))]
    {
        let _ = path;
        None
    }
}

/// Validate that a `dest_under_quarantine` PathBuf is a relative path containing
/// only `Normal` components. Refuses absolute paths, `..` (`ParentDir`), Windows
/// drive prefixes, etc. Returns `BlastRadiusExceeded` on failure so the caller
/// surfaces it as the global policy-denied exit (7), matching the rest of the
/// containment story.
///
/// This is defense-in-depth: callers are SUPPOSED to pass safe relative paths,
/// but the runtime validates anyway so a buggy fixer can't escape the
/// `<run-dir>/quarantine/` root.
fn validate_relative_quarantine_dest(
    dest: &Path,
    run_dir: &Path,
) -> Result<(), DoctorRuntimeError> {
    if dest.as_os_str().is_empty() {
        return Err(DoctorRuntimeError::BlastRadiusExceeded {
            path: dest.to_path_buf(),
            allowed_roots: vec![run_dir.join("quarantine")],
        });
    }
    for component in dest.components() {
        match component {
            std::path::Component::Normal(_) => continue,
            _ => {
                return Err(DoctorRuntimeError::BlastRadiusExceeded {
                    path: dest.to_path_buf(),
                    allowed_roots: vec![run_dir.join("quarantine")],
                });
            }
        }
    }
    Ok(())
}

fn is_path_in_blast_radius(path: &Path, roots: &[PathBuf]) -> bool {
    // Round-2 fresh-eyes (R2-P1-03): walk upward to the nearest existing
    // ancestor and canonicalize THAT, then re-append the tail. The prior
    // implementation refused any path whose immediate parent didn't yet
    // exist (so `WriteFile` to `<workspace>/.ee/cache/sub/leaf.json` was
    // refused if `cache/sub/` didn't exist, even though `write_file_atomic`
    // would have created it). This blocked legitimate Phase-4 fixer
    // scenarios.
    let probe = if path.exists() {
        path.canonicalize().ok()
    } else {
        nearest_existing_ancestor_canonical(path)
    };
    let probe = match probe {
        Some(p) => p,
        None => return false,
    };
    roots
        .iter()
        .any(|root| root.is_absolute() && probe.starts_with(root))
}

/// Walk upward from `path` to the nearest existing ancestor, canonicalize
/// it, then re-append the not-yet-existing tail. Returns the resulting
/// concrete (canonical + tail) path if an existing ancestor was found.
///
/// The not-yet-existing tail is accepted only when every component is
/// `Normal`. Refusing `..` here is the defense-in-depth boundary that keeps a
/// missing intermediate directory from turning a literal in-radius prefix into
/// an out-of-radius write once the kernel resolves the final path.
fn nearest_existing_ancestor_canonical(path: &Path) -> Option<PathBuf> {
    let mut tail: Vec<OsString> = Vec::new();
    let mut p = path.to_path_buf();
    loop {
        if p.exists() {
            let mut canon = p.canonicalize().ok()?;
            for component in tail.iter().rev() {
                canon.push(component);
            }
            return Some(canon);
        }

        let name = match p.components().next_back()? {
            Component::Normal(name) => name.to_os_string(),
            Component::CurDir
            | Component::ParentDir
            | Component::Prefix(_)
            | Component::RootDir => {
                return None;
            }
        };

        let parent = p.parent()?.to_path_buf();
        tail.push(name);
        p = parent;
    }
}

fn write_file_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> {
    // Round-2 fresh-eyes (R2-P1-04): refuse paths without a parent rather
    // than falling back to "." (the CWD of an invoking shell, which could
    // be outside the blast radius and break the cross-filesystem rename
    // assumption that persist() relies on).
    //
    // Round-5 self-review: `Path::new("foo.txt").parent()` returns `Some("")`
    // (an empty Path, not None). The original guard accepted that and then
    // happily wrote a tempfile in CWD via `NamedTempFile::new_in("")`. Filter
    // out the empty-parent case too so bare-filename paths get the same
    // refusal as truly parentless ones.
    //
    // Round-6 self-review: `Path::new("./foo.txt").parent()` returns
    // `Some(".")` (non-empty) which slipped past the round-5 filter and
    // produced the same CWD-leak via `NamedTempFile::new_in(".")`. The
    // chokepoint's invariant after R5-3 is that all writes are to absolute
    // paths (R5-3 absolutizes the workspace, which propagates everywhere).
    // Enforce that invariant at the leaf: refuse any parent that isn't
    // itself absolute. This catches `""`, `"."`, `"./sub"`, `".."` etc.
    let parent = path.parent().filter(|p| p.is_absolute()).ok_or_else(|| {
        io::Error::new(
            io::ErrorKind::InvalidInput,
            format!(
                "write_file_atomic: path lacks an absolute parent: {}",
                path.display()
            ),
        )
    })?;
    fs::create_dir_all(parent)?;
    let mut tmp = tempfile::NamedTempFile::new_in(parent)?;
    tmp.write_all(bytes)?;
    tmp.flush()?;
    tmp.persist(path).map_err(|e| e.error)?;
    Ok(())
}

/// Compute the sanitized relative path under `<run-dir>/backups/<seq>/` (or
/// quarantine equivalent) that maps an arbitrary absolute path to a safe
/// destination. Drops `Prefix` / `RootDir` / `CurDir`, replaces `ParentDir`
/// with the literal `__parent__` placeholder, keeps `Normal` components.
fn sanitize_path_for_run_dir(path: &Path) -> PathBuf {
    let mut rel = PathBuf::new();
    for component in path.components() {
        match component {
            std::path::Component::Prefix(_) | std::path::Component::RootDir => continue,
            std::path::Component::CurDir => continue,
            std::path::Component::ParentDir => rel.push("__parent__"),
            std::path::Component::Normal(s) => rel.push(s),
        }
    }
    rel
}

#[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))]
fn stage_backup(
    ctx: &RunContext,
    path: &Path,
    expected_hash: &Option<String>,
) -> Result<PathBuf, DoctorRuntimeError> {
    use rustix::fs::{Mode, OFlags};

    let path_rel = sanitize_path_for_run_dir(path);
    let next_seq = ctx.state.action_count + 1;
    let seq_dir = PathBuf::from(format!("{:06}", next_seq));
    let rel = seq_dir.join(&path_rel);
    let backups_path = ctx.run_dir.join("backups");

    // Open the source before allocating its destination so a missing or
    // unreadable target cannot leave an empty backup artifact.
    let mut source = if ctx.dry_run {
        None
    } else {
        Some(
            fs::File::open(path).map_err(|source| DoctorRuntimeError::Io {
                context: format!("open backup source {}", path.display()),
                source,
            })?,
        )
    };
    let destination =
        prepare_doctor_relative_destination(&ctx.lifecycle.backups_dir, &backups_path, &rel)?;

    if ctx.dry_run {
        if doctor_entry_type_at(&destination.parent, destination.leaf.as_os_str())?.is_some() {
            return Err(DoctorRuntimeError::Io {
                context: format!(
                    "backup collision at sequence {} target {}: {} already exists",
                    next_seq,
                    path.display(),
                    destination.display_path.display()
                ),
                source: io::Error::new(io::ErrorKind::AlreadyExists, "backup collision"),
            });
        }
        return Ok(rel);
    }

    // The destination is created relative to the retained backups descriptor.
    // The earlier device/inode audit is deliberately not used as authorization
    // for this write: openat + O_EXCL + O_NOFOLLOW binds it atomically.
    let destination_fd = rustix::fs::openat(
        &destination.parent,
        destination.leaf.as_os_str(),
        OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL | OFlags::NOFOLLOW | OFlags::CLOEXEC,
        Mode::from_raw_mode(0o600),
    )
    .map_err(|source| {
        if source == rustix::io::Errno::EXIST {
            DoctorRuntimeError::Io {
                context: format!(
                    "backup collision at sequence {} target {}: {} already exists",
                    next_seq,
                    path.display(),
                    destination.display_path.display()
                ),
                source: io::Error::new(io::ErrorKind::AlreadyExists, "backup collision"),
            }
        } else {
            doctor_lifecycle_errno(&destination.display_path, "create doctor backup", source)
        }
    })?;
    let mut destination_file = fs::File::from(destination_fd);
    let mut hasher = blake3::Hasher::new();
    let mut buffer = [0_u8; 8192];
    let source = source.as_mut().ok_or_else(|| DoctorRuntimeError::Io {
        context: format!("open backup source {}", path.display()),
        source: io::Error::new(io::ErrorKind::InvalidInput, "backup source was not opened"),
    })?;
    loop {
        let read = source
            .read(&mut buffer)
            .map_err(|source| DoctorRuntimeError::Io {
                context: format!("read backup source {}", path.display()),
                source,
            })?;
        if read == 0 {
            break;
        }
        hasher.update(&buffer[..read]);
        destination_file
            .write_all(&buffer[..read])
            .map_err(|source| DoctorRuntimeError::Io {
                context: format!(
                    "write descriptor-anchored backup {}",
                    destination.display_path.display()
                ),
                source,
            })?;
    }
    destination_file
        .flush()
        .map_err(|source| DoctorRuntimeError::Io {
            context: format!(
                "flush descriptor-anchored backup {}",
                destination.display_path.display()
            ),
            source,
        })?;

    if let Some(expected) = expected_hash {
        let observed = hasher.finalize().to_hex().to_string();
        if &observed != expected {
            return Err(DoctorRuntimeError::Io {
                context: format!(
                    "backup hash mismatch after copy ({}): expected {}, observed {}",
                    destination.display_path.display(),
                    expected,
                    observed
                ),
                source: io::Error::new(io::ErrorKind::Other, "backup race"),
            });
        }
    }

    Ok(rel)
}

#[cfg(not(any(target_os = "linux", target_os = "android", target_vendor = "apple")))]
fn stage_backup(
    ctx: &RunContext,
    path: &Path,
    expected_hash: &Option<String>,
) -> Result<PathBuf, DoctorRuntimeError> {
    // Backups are addressed by sequence-prefixed relative path under the
    // run's backups/ root. Round-2 fresh-eyes (R2-P0-01) found that
    // sharing the path-derived relative key for two mutations of the same
    // target file silently overwrites the first backup, breaking the
    // byte-identical-undo invariant the chokepoint advertises.
    //
    // The sequence prefix is `{:06}` of the action number we're about to
    // commit (i.e. `ctx.state.action_count + 1`) since `mutate()` does
    // `ctx.state.action_count += 1` AFTER calling stage_backup. Six digits
    // keeps lexical sort = numerical sort up to 999,999 actions per run.
    let path_rel = sanitize_path_for_run_dir(path);
    let next_seq = ctx.state.action_count + 1;
    let seq_dir = PathBuf::from(format!("{:06}", next_seq));
    let rel = seq_dir.join(&path_rel);
    let backup_path = ctx.run_dir.join("backups").join(&rel);
    // Defense in depth: the sequence-prefixed slot must not already exist.
    // If it does, a prior mutate() partially completed at this sequence
    // and the run state is inconsistent — refuse.
    if backup_path.exists() {
        return Err(DoctorRuntimeError::Io {
            context: format!(
                "backup collision at sequence {} target {}: {} already exists",
                next_seq,
                path.display(),
                backup_path.display()
            ),
            source: io::Error::new(io::ErrorKind::AlreadyExists, "backup collision"),
        });
    }
    if let Some(parent) = backup_path.parent() {
        fs::create_dir_all(parent)?;
    }
    if !ctx.dry_run {
        // Verbatim copy. We use fs::copy which is byte-identical.
        fs::copy(path, &backup_path).map_err(|source| DoctorRuntimeError::Io {
            context: format!(
                "backup copy {} -> {}",
                path.display(),
                backup_path.display()
            ),
            source,
        })?;
        // Hash verify (the backup must hash to the same value as the
        // original at this exact moment).
        if let Some(expected) = expected_hash {
            let observed = hash_file(&backup_path)?;
            if &observed != expected {
                return Err(DoctorRuntimeError::Io {
                    context: format!(
                        "backup hash mismatch after copy ({}): expected {}, observed {}",
                        backup_path.display(),
                        expected,
                        observed
                    ),
                    source: io::Error::new(io::ErrorKind::Other, "backup race"),
                });
            }
        }
    }
    Ok(rel)
}

/// Maximum bytes inspected when reading `<run_dir>/state.json`. Real
/// `RunState` is a tiny JSON object (`schema`, `run_id`, `target_sha`,
/// `workspace`, two timestamps, `status` enum, `action_count`, `dry_run` —
/// well under 1 KiB in practice); 4 MiB gives many orders of magnitude of
/// headroom while bounding peer plants on shared multi-agent checkouts.
///
/// Without this cap, a peer-planted or accidentally-inflated state.json
/// (corrupt write, `cat /dev/urandom > state.json`, hostile multi-agent
/// checkout) would pin a matching allocation through `fs::read` on every
/// `replay_undo` (`ee doctor --undo`) invocation. The previous shape also
/// had no symlink guard: a peer-swapped symlink at the same path would
/// have followed off-tree to attacker-chosen bytes. Matches the cap +
/// read-shape the parallel hardening pass applied to
/// `src/core/index.rs::read_index_metadata_contents` (ad2d302e) and
/// `src/core/preflight_guard.rs::read_preflight_rules_file_no_follow`
/// (7f56d89b).
const DOCTOR_RUN_STATE_INSPECT_LIMIT: u64 = 4 * 1024 * 1024;

/// Maximum bytes inspected when reading doctor JSONL logs during undo.
/// Action lines store paths, hashes, modes, and diagnostic notes rather than
/// file payload bytes, so 16 MiB leaves room for thousands of actions while
/// bounding corrupted or hostile `.doctor/runs/<run-id>/*.jsonl` allocations.
const DOCTOR_ACTION_LOG_INSPECT_LIMIT: u64 = 16 * 1024 * 1024;

/// Maximum bytes inspected when reading `<workspace>/.ee/.doctor.lock`.
/// Doctor-created files contain only the stable marker; external conformance
/// holders may add a short diagnostic label and process id.
const DOCTOR_LOCK_FILE_INSPECT_LIMIT: u64 = 4 * 1024;

fn read_required_doctor_jsonl_file(
    path: &Path,
    label: &'static str,
) -> Result<String, DoctorRuntimeError> {
    let metadata = fs::symlink_metadata(path).map_err(|source| DoctorRuntimeError::Io {
        context: format!("read {label} {}", path.display()),
        source,
    })?;
    read_doctor_text_file_with_metadata(path, label, metadata, DOCTOR_ACTION_LOG_INSPECT_LIMIT)
}

fn read_optional_doctor_jsonl_file(
    path: &Path,
    label: &'static str,
) -> Result<Option<String>, DoctorRuntimeError> {
    read_optional_doctor_text_file(path, label, DOCTOR_ACTION_LOG_INSPECT_LIMIT)
}

fn read_optional_doctor_text_file(
    path: &Path,
    label: &'static str,
    byte_limit: u64,
) -> Result<Option<String>, DoctorRuntimeError> {
    let metadata = match fs::symlink_metadata(path) {
        Ok(metadata) => metadata,
        Err(source) if source.kind() == io::ErrorKind::NotFound => return Ok(None),
        Err(source) => {
            return Err(DoctorRuntimeError::Io {
                context: format!("read {label} {}", path.display()),
                source,
            });
        }
    };
    read_doctor_text_file_with_metadata(path, label, metadata, byte_limit).map(Some)
}

fn read_doctor_text_file_with_metadata(
    path: &Path,
    label: &'static str,
    metadata: fs::Metadata,
    byte_limit: u64,
) -> Result<String, DoctorRuntimeError> {
    if !metadata.file_type().is_file() {
        return Err(DoctorRuntimeError::Io {
            context: format!("read {label} {}", path.display()),
            source: io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("{label} is not a regular file"),
            ),
        });
    }
    if metadata.len() > byte_limit {
        return Err(DoctorRuntimeError::Io {
            context: format!("read {label} {}", path.display()),
            source: io::Error::new(
                io::ErrorKind::InvalidData,
                format!(
                    "{label} size {} exceeds {byte_limit} byte cap",
                    metadata.len()
                ),
            ),
        });
    }
    let file =
        open_doctor_inspect_file_for_read(path).map_err(|source| DoctorRuntimeError::Io {
            context: format!("read {label} {}", path.display()),
            source,
        })?;
    let mut raw = String::new();
    file.take(byte_limit.saturating_add(1))
        .read_to_string(&mut raw)
        .map_err(|source| DoctorRuntimeError::Io {
            context: format!("read {label} {}", path.display()),
            source,
        })?;
    if u64::try_from(raw.len()).unwrap_or(u64::MAX) > byte_limit {
        return Err(DoctorRuntimeError::Io {
            context: format!("read {label} {}", path.display()),
            source: io::Error::new(
                io::ErrorKind::InvalidData,
                format!("{label} grew past cap during read"),
            ),
        });
    }
    Ok(raw)
}

fn read_doctor_backup_bytes(path: &Path) -> Result<Vec<u8>, DoctorRuntimeError> {
    let metadata =
        fs::symlink_metadata(path).map_err(|source| DoctorRuntimeError::UndoBackupCorrupt {
            backup_path: path.to_path_buf(),
            expected_hash: "<recorded before_hash>".into(),
            observed_hash: Some(format!("unreadable: {source}")),
        })?;
    if !metadata.file_type().is_file() {
        return Err(DoctorRuntimeError::RunArtifactInvalid {
            path: path.to_path_buf(),
            reason: "backup is not a regular file".into(),
        });
    }
    let mut file =
        open_doctor_inspect_file_for_read(path).map_err(|source| DoctorRuntimeError::Io {
            context: format!("open doctor backup {}", path.display()),
            source,
        })?;
    let mut bytes = Vec::new();
    file.read_to_end(&mut bytes)
        .map_err(|source| DoctorRuntimeError::Io {
            context: format!("read doctor backup {}", path.display()),
            source,
        })?;
    Ok(bytes)
}

fn open_doctor_inspect_file_for_read(path: &Path) -> io::Result<fs::File> {
    let mut options = fs::OpenOptions::new();
    options.read(true);
    configure_doctor_inspect_open_no_follow(&mut options);
    options.open(path)
}

#[cfg(all(unix, not(any(target_os = "espidf", target_os = "horizon"))))]
fn configure_doctor_inspect_open_no_follow(options: &mut fs::OpenOptions) {
    use std::os::unix::fs::OpenOptionsExt;

    options.custom_flags(rustix::fs::OFlags::NOFOLLOW.bits() as i32);
}

#[cfg(not(all(unix, not(any(target_os = "espidf", target_os = "horizon")))))]
fn configure_doctor_inspect_open_no_follow(_options: &mut fs::OpenOptions) {}

/// Read the persisted [`RunState`] from `<run_dir>/state.json`.
fn read_state(run_dir: &Path) -> Result<RunState, DoctorRuntimeError> {
    let path = run_dir.join("state.json");
    let metadata = fs::symlink_metadata(&path).map_err(|source| DoctorRuntimeError::Io {
        context: format!("read state.json {}", path.display()),
        source,
    })?;
    if !metadata.file_type().is_file() {
        return Err(DoctorRuntimeError::Io {
            context: format!("read state.json {}", path.display()),
            source: io::Error::new(
                io::ErrorKind::InvalidInput,
                "state.json is not a regular file",
            ),
        });
    }
    if metadata.len() > DOCTOR_RUN_STATE_INSPECT_LIMIT {
        return Err(DoctorRuntimeError::Io {
            context: format!("read state.json {}", path.display()),
            source: io::Error::new(
                io::ErrorKind::InvalidData,
                format!(
                    "state.json size {} exceeds {DOCTOR_RUN_STATE_INSPECT_LIMIT} byte cap",
                    metadata.len()
                ),
            ),
        });
    }
    let file =
        open_doctor_inspect_file_for_read(&path).map_err(|source| DoctorRuntimeError::Io {
            context: format!("read state.json {}", path.display()),
            source,
        })?;
    let mut bytes = Vec::new();
    file.take(DOCTOR_RUN_STATE_INSPECT_LIMIT.saturating_add(1))
        .read_to_end(&mut bytes)
        .map_err(|source| DoctorRuntimeError::Io {
            context: format!("read state.json {}", path.display()),
            source,
        })?;
    if u64::try_from(bytes.len()).unwrap_or(u64::MAX) > DOCTOR_RUN_STATE_INSPECT_LIMIT {
        return Err(DoctorRuntimeError::Io {
            context: format!("read state.json {}", path.display()),
            source: io::Error::new(
                io::ErrorKind::InvalidData,
                "state.json grew past cap during read",
            ),
        });
    }
    serde_json::from_slice(&bytes).map_err(|e| DoctorRuntimeError::Io {
        context: format!("parse state.json {}", path.display()),
        source: io::Error::new(io::ErrorKind::InvalidData, e),
    })
}

/// Drop-guarded lock around `<workspace>/.ee/.doctor.lock` used by
/// [`replay_undo`] to serialize against concurrent `--fix` or `--undo` runs.
///
/// The public file is persistent. Ownership is the retained OS advisory lock,
/// and release only unlocks/drops this exact handle. Drop never removes a
/// pathname that a peer could have replaced.
struct UndoLockGuard {
    lock_file: fs::File,
}

impl Drop for UndoLockGuard {
    fn drop(&mut self) {
        let _ = unlock_doctor_lock_file(&self.lock_file);
    }
}

#[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))]
fn acquire_undo_lock(workspace: &Path) -> Result<UndoLockGuard, DoctorRuntimeError> {
    use rustix::fs::{Mode, OFlags};

    let workspace_abs = canonical_doctor_workspace(workspace)?;
    let ee_dir = workspace_abs.join(".ee");
    let lock_path = ee_dir.join(".doctor.lock");
    validate_doctor_lifecycle_paths([
        workspace_abs.as_path(),
        ee_dir.as_path(),
        lock_path.as_path(),
    ])?;

    let directory_flags = OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC;
    let workspace_fd = rustix::fs::openat(
        rustix::fs::CWD,
        &workspace_abs,
        directory_flags,
        Mode::from_raw_mode(0),
    )
    .map(fs::File::from)
    .map_err(|source| {
        doctor_lifecycle_errno(&workspace_abs, "open canonical undo workspace", source)
    })?;
    let ee_dir_fd =
        open_or_create_doctor_directory_at(&workspace_fd, OsStr::new(".ee"), &ee_dir, true)?;
    let lock_file = acquire_doctor_lock_at(&ee_dir_fd, &lock_path)?;
    Ok(UndoLockGuard { lock_file })
}

#[cfg(windows)]
fn acquire_undo_lock(workspace: &Path) -> Result<UndoLockGuard, DoctorRuntimeError> {
    let workspace_abs = canonical_doctor_workspace(workspace)?;
    let ee_dir = workspace_abs.join(".ee");
    let lock_path = ee_dir.join(".doctor.lock");
    validate_doctor_lifecycle_paths([
        workspace_abs.as_path(),
        ee_dir.as_path(),
        lock_path.as_path(),
    ])?;
    fs::create_dir_all(&ee_dir).map_err(|source| DoctorRuntimeError::Io {
        context: format!("create_dir_all({}) for undo lock", ee_dir.display()),
        source,
    })?;
    let lock_file = acquire_windows_doctor_lock(&lock_path)?;
    Ok(UndoLockGuard { lock_file })
}

#[cfg(not(any(
    target_os = "linux",
    target_os = "android",
    target_vendor = "apple",
    windows
)))]
fn acquire_undo_lock(workspace: &Path) -> Result<UndoLockGuard, DoctorRuntimeError> {
    Err(DoctorRuntimeError::Io {
        context: format!("acquire doctor undo lock for {}", workspace.display()),
        source: io::Error::new(
            io::ErrorKind::Unsupported,
            "doctor undo is disabled because this platform cannot prove lock ownership",
        ),
    })
}

// ----------------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------------

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

    fn fresh_workspace() -> TempDir {
        TempDir::new().expect("tempdir")
    }

    fn start_run(ws: &Path) -> RunContext {
        let mut roots = default_blast_radius_roots(ws);
        // Tests should be able to mutate inside the workspace's root, not
        // just `.ee/` — push the workspace root itself so the unit tests
        // can write a file at workspace.join("data.txt").
        roots.push(ws.to_path_buf());
        RunContext::start(ws, "deadbeefcafe", roots, false).expect("start run")
    }

    fn replay_test_undo(run_dir: &Path) -> Result<UndoSummary, DoctorRuntimeError> {
        let run_id = run_dir
            .file_name()
            .and_then(|name| name.to_str())
            .expect("test run id");
        let workspace = run_dir
            .parent()
            .and_then(Path::parent)
            .and_then(Path::parent)
            .expect("test workspace");
        let mut roots = default_blast_radius_roots(workspace);
        roots.push(workspace.to_path_buf());
        replay_undo_with_authorized_roots(workspace, run_id, &roots)
    }

    fn assert_persistent_doctor_lock_released(workspace: &Path) {
        let lock_path = workspace.join(".ee").join(".doctor.lock");
        assert!(
            lock_path.is_file(),
            "persistent doctor lock file is missing"
        );
        let lock = fs::OpenOptions::new()
            .read(true)
            .write(true)
            .open(&lock_path)
            .expect("open persistent doctor lock");
        Fs4FileExt::try_lock(&lock).expect("persistent doctor advisory lock should be released");
        Fs4FileExt::unlock(&lock).expect("unlock test doctor lock");
    }

    #[cfg(unix)]
    #[test]
    fn blast_radius_override_parses_absolute_colon_separated_paths() {
        let roots = parse_blast_radius_override("/a/b:/c/d").expect("valid override");
        assert_eq!(roots, vec![PathBuf::from("/a/b"), PathBuf::from("/c/d")]);
    }

    #[test]
    fn blast_radius_override_rejects_relative_and_empty_segments() {
        assert!(parse_blast_radius_override("relative/path").is_err());
        assert!(parse_blast_radius_override("/abs::/tail").is_err());
        assert!(parse_blast_radius_override(":/lead").is_err());
    }

    #[test]
    fn doctor_run_id_is_one_bounded_portable_component() {
        assert!(validate_doctor_run_id("2026-08-31T00-00-00.000000000Z__1__abc123").is_ok());
        for invalid in [
            "",
            ".",
            "..",
            "../escape",
            "nested/run",
            r"nested\run",
            "/tmp/run",
        ] {
            assert!(
                matches!(
                    validate_doctor_run_id(invalid),
                    Err(DoctorRuntimeError::InvalidRunId { .. })
                ),
                "accepted invalid run id {invalid:?}"
            );
        }
        let overlong = "a".repeat(DOCTOR_RUN_ID_MAX_BYTES + 1);
        assert!(matches!(
            validate_doctor_run_id(&overlong),
            Err(DoctorRuntimeError::InvalidRunId { .. })
        ));
    }

    #[test]
    fn run_state_reader_rejects_forged_run_binding() {
        let ws = fresh_workspace();
        let ctx = start_run(ws.path());
        let run_dir = ctx.run_dir().to_path_buf();
        let run_id = ctx.run_id().to_owned();
        ctx.finish(RunStatus::CompletedOk).unwrap();

        let mut state = read_state(&run_dir).unwrap();
        state.run_id = "different-run".into();
        fs::write(
            run_dir.join("state.json"),
            serde_json::to_vec_pretty(&state).unwrap(),
        )
        .unwrap();

        assert!(matches!(
            read_doctor_run_state(ws.path(), &run_id),
            Err(DoctorRuntimeError::RunArtifactInvalid { .. })
        ));
    }

    #[test]
    fn undo_prevalidates_entire_action_ledger_before_mutating() {
        let ws = fresh_workspace();
        let first = ws.path().join("first.txt");
        let second = ws.path().join("second.txt");
        fs::write(&first, b"first-before").unwrap();
        fs::write(&second, b"second-before").unwrap();

        let mut ctx = start_run(ws.path());
        let run_dir = ctx.run_dir().to_path_buf();
        let run_id = ctx.run_id().to_owned();
        mutate(
            &mut ctx,
            &first,
            Op::WriteFile {
                bytes: b"first-after".to_vec(),
            },
        )
        .unwrap();
        mutate(
            &mut ctx,
            &second,
            Op::WriteFile {
                bytes: b"second-after".to_vec(),
            },
        )
        .unwrap();
        ctx.finish(RunStatus::CompletedOk).unwrap();

        let actions_path = run_dir.join("actions.jsonl");
        let raw = fs::read_to_string(&actions_path).unwrap();
        let mut actions = raw
            .lines()
            .map(|line| serde_json::from_str::<serde_json::Value>(line).unwrap())
            .collect::<Vec<_>>();
        let outside = ws
            .path()
            .parent()
            .expect("workspace parent")
            .join("forged-doctor-target.txt");
        actions[0]["path"] = serde_json::Value::String(outside.display().to_string());
        let tampered = actions
            .into_iter()
            .map(|action| serde_json::to_string(&action).unwrap())
            .collect::<Vec<_>>()
            .join("\n");
        fs::write(&actions_path, format!("{tampered}\n")).unwrap();

        let mut roots = default_blast_radius_roots(ws.path());
        roots.push(ws.path().to_path_buf());
        assert!(matches!(
            replay_undo_with_authorized_roots(ws.path(), &run_id, &roots),
            Err(DoctorRuntimeError::BlastRadiusExceeded { .. })
        ));
        assert_eq!(fs::read(&first).unwrap(), b"first-after");
        assert_eq!(fs::read(&second).unwrap(), b"second-after");
        assert!(
            !run_dir.join("undo_log.jsonl").exists(),
            "prevalidation failure must not append an undo record"
        );
    }

    #[test]
    fn undo_recovers_durable_action_appended_before_failed_state_update() {
        let ws = fresh_workspace();
        let target = ws.path().join("crash-window.txt");
        fs::write(&target, b"before").unwrap();

        let mut ctx = start_run(ws.path());
        let run_dir = ctx.run_dir().to_path_buf();
        let run_id = ctx.run_id().to_owned();
        mutate(
            &mut ctx,
            &target,
            Op::WriteFile {
                bytes: b"after".to_vec(),
            },
        )
        .unwrap();
        ctx.finish(RunStatus::CompletedOk).unwrap();

        let mut stale_state = read_state(&run_dir).unwrap();
        stale_state.status = RunStatus::Failed;
        stale_state.action_count = 0;
        fs::write(
            run_dir.join("state.json"),
            serde_json::to_vec_pretty(&stale_state).unwrap(),
        )
        .unwrap();

        let mut roots = default_blast_radius_roots(ws.path());
        roots.push(ws.path().to_path_buf());
        let summary = replay_undo_with_authorized_roots(ws.path(), &run_id, &roots).unwrap();
        assert_eq!(summary.actions_undone, 1);
        assert!(matches!(summary.status, RunStatus::Undone));
        assert_eq!(fs::read(&target).unwrap(), b"before");
        assert_eq!(read_state(&run_dir).unwrap().action_count, 1);
    }

    #[test]
    fn undo_rejects_action_count_gap_larger_than_single_crash_window() {
        let ws = fresh_workspace();
        let first = ws.path().join("gap-first.txt");
        let second = ws.path().join("gap-second.txt");
        fs::write(&first, b"first-before").unwrap();
        fs::write(&second, b"second-before").unwrap();

        let mut ctx = start_run(ws.path());
        let run_dir = ctx.run_dir().to_path_buf();
        let run_id = ctx.run_id().to_owned();
        for (path, bytes) in [
            (&first, b"first-after".as_slice()),
            (&second, b"second-after".as_slice()),
        ] {
            mutate(
                &mut ctx,
                path,
                Op::WriteFile {
                    bytes: bytes.to_vec(),
                },
            )
            .unwrap();
        }
        ctx.finish(RunStatus::CompletedOk).unwrap();

        let mut stale_state = read_state(&run_dir).unwrap();
        stale_state.status = RunStatus::Failed;
        stale_state.action_count = 0;
        fs::write(
            run_dir.join("state.json"),
            serde_json::to_vec_pretty(&stale_state).unwrap(),
        )
        .unwrap();

        let mut roots = default_blast_radius_roots(ws.path());
        roots.push(ws.path().to_path_buf());
        assert!(matches!(
            replay_undo_with_authorized_roots(ws.path(), &run_id, &roots),
            Err(DoctorRuntimeError::RunArtifactInvalid { .. })
        ));
        assert_eq!(fs::read(&first).unwrap(), b"first-after");
        assert_eq!(fs::read(&second).unwrap(), b"second-after");
        assert!(!run_dir.join("undo_log.jsonl").exists());
    }

    #[test]
    fn undo_intersects_recorded_and_current_blast_radius() {
        let root = tempfile::tempdir().unwrap();
        let workspace = root.path().join("workspace");
        let sibling = root.path().join("sibling");
        fs::create_dir(&workspace).unwrap();
        fs::create_dir(&sibling).unwrap();
        let original = workspace.join("original.txt");
        let forged = sibling.join("forged.txt");
        fs::write(&original, b"before").unwrap();
        fs::write(&forged, b"peer-owned").unwrap();

        let mut ctx =
            RunContext::start(&workspace, "recorded-roots", vec![workspace.clone()], false)
                .unwrap();
        let run_dir = ctx.run_dir().to_path_buf();
        let run_id = ctx.run_id().to_owned();
        mutate(
            &mut ctx,
            &original,
            Op::WriteFile {
                bytes: b"after".to_vec(),
            },
        )
        .unwrap();
        ctx.finish(RunStatus::CompletedOk).unwrap();

        let actions_path = run_dir.join("actions.jsonl");
        let raw = fs::read_to_string(&actions_path).unwrap();
        let mut action: serde_json::Value = serde_json::from_str(raw.trim()).unwrap();
        action["path"] = serde_json::Value::String(forged.display().to_string());
        fs::write(&actions_path, format!("{}\n", action)).unwrap();

        assert!(matches!(
            replay_undo_with_authorized_roots(&workspace, &run_id, &[root.path().to_path_buf()],),
            Err(DoctorRuntimeError::BlastRadiusExceeded { .. })
        ));
        assert_eq!(fs::read(&forged).unwrap(), b"peer-owned");
        assert_eq!(fs::read(&original).unwrap(), b"after");
        assert!(!run_dir.join("undo_log.jsonl").exists());
    }

    #[test]
    fn undo_never_reuses_recorded_authority_missing_from_current_roots() {
        let root = tempfile::tempdir().unwrap();
        let workspace = root.path().join("workspace");
        let external = root.path().join("external");
        fs::create_dir(&workspace).unwrap();
        fs::create_dir(&external).unwrap();
        let target = external.join("target.txt");
        fs::write(&target, b"before").unwrap();

        let mut ctx = RunContext::start(
            &workspace,
            "current-roots",
            vec![root.path().to_path_buf()],
            false,
        )
        .unwrap();
        let run_dir = ctx.run_dir().to_path_buf();
        let run_id = ctx.run_id().to_owned();
        mutate(
            &mut ctx,
            &target,
            Op::WriteFile {
                bytes: b"after".to_vec(),
            },
        )
        .unwrap();
        ctx.finish(RunStatus::CompletedOk).unwrap();

        assert!(matches!(
            replay_undo_with_authorized_roots(
                &workspace,
                &run_id,
                std::slice::from_ref(&workspace),
            ),
            Err(DoctorRuntimeError::BlastRadiusExceeded { .. })
        ));
        assert_eq!(fs::read(&target).unwrap(), b"after");
        assert!(!run_dir.join("undo_log.jsonl").exists());
    }

    #[cfg(unix)]
    #[test]
    fn undo_rejects_recorded_root_retargeted_by_symlink() {
        use std::os::unix::fs::symlink;

        let root = tempfile::tempdir().unwrap();
        let workspace = root.path().join("workspace");
        let recorded_root = root.path().join("recorded-root");
        let retained_root = root.path().join("retained-root");
        let replacement_root = root.path().join("replacement-root");
        fs::create_dir(&workspace).unwrap();
        fs::create_dir(&recorded_root).unwrap();
        fs::create_dir(&replacement_root).unwrap();
        let target = recorded_root.join("target.txt");
        fs::write(&target, b"before").unwrap();

        let mut ctx = RunContext::start(
            &workspace,
            "retargeted-root",
            vec![recorded_root.clone()],
            false,
        )
        .unwrap();
        let run_dir = ctx.run_dir().to_path_buf();
        let run_id = ctx.run_id().to_owned();
        mutate(
            &mut ctx,
            &target,
            Op::WriteFile {
                bytes: b"after".to_vec(),
            },
        )
        .unwrap();
        ctx.finish(RunStatus::CompletedOk).unwrap();

        fs::rename(&recorded_root, &retained_root).unwrap();
        fs::write(replacement_root.join("target.txt"), b"after").unwrap();
        symlink(&replacement_root, &recorded_root).unwrap();

        assert!(matches!(
            replay_undo_with_authorized_roots(
                &workspace,
                &run_id,
                std::slice::from_ref(&recorded_root),
            ),
            Err(DoctorRuntimeError::BlastRadiusExceeded { .. })
        ));
        assert_eq!(
            fs::read(replacement_root.join("target.txt")).unwrap(),
            b"after"
        );
        assert_eq!(
            fs::read(retained_root.join("target.txt")).unwrap(),
            b"after"
        );
        assert!(!run_dir.join("undo_log.jsonl").exists());
    }

    #[test]
    fn capabilities_report_only_advertises_wired_env_vars() {
        let report = CapabilitiesReport::build("0.0.0-test", Path::new("/ws"));
        let names: Vec<&str> = report.env_vars.iter().map(|entry| entry.name).collect();
        assert_eq!(
            names,
            vec!["EE_DOCTOR_BLAST_RADIUS", "EE_NO_COLOR"],
            "capabilities must only advertise env vars the runtime actually reads"
        );
    }

    #[test]
    fn write_file_creates_file_and_records_action() {
        let ws = fresh_workspace();
        let mut ctx = start_run(ws.path());
        let target = ws.path().join("data.txt");

        let line = mutate(
            &mut ctx,
            &target,
            Op::WriteFile {
                bytes: b"hello".to_vec(),
            },
        )
        .expect("mutate");
        assert_eq!(fs::read(&target).unwrap(), b"hello");
        assert_eq!(line.kind, "write_file");
        assert!(line.before_hash.is_none());
        assert!(line.after_hash.is_some());

        // actions.jsonl exists and has one line.
        let actions_path = ctx.run_dir().join("actions.jsonl");
        let raw = fs::read_to_string(&actions_path).unwrap();
        assert_eq!(raw.lines().count(), 1);
    }

    #[test]
    fn write_file_idempotent_same_bytes_returns_no_op() {
        let ws = fresh_workspace();
        let mut ctx = start_run(ws.path());
        let target = ws.path().join("data.txt");

        let _ = mutate(
            &mut ctx,
            &target,
            Op::WriteFile {
                bytes: b"same".to_vec(),
            },
        )
        .expect("first");
        let result = mutate(
            &mut ctx,
            &target,
            Op::WriteFile {
                bytes: b"same".to_vec(),
            },
        );
        assert!(matches!(result, Err(DoctorRuntimeError::NoOpIdempotent)));
    }

    #[test]
    fn write_file_backs_up_existing_content_before_overwrite() {
        let ws = fresh_workspace();
        let target = ws.path().join("data.txt");
        fs::write(&target, b"original").unwrap();

        let mut ctx = start_run(ws.path());
        let line = mutate(
            &mut ctx,
            &target,
            Op::WriteFile {
                bytes: b"updated".to_vec(),
            },
        )
        .expect("mutate");

        let rel = line.backup_rel_path.expect("backup rel path");
        let backup_path = ctx.run_dir().join("backups").join(&rel);
        assert_eq!(fs::read(&backup_path).unwrap(), b"original");
        assert_eq!(fs::read(&target).unwrap(), b"updated");
    }

    #[test]
    fn blast_radius_refuses_writes_outside_allowed_roots() {
        let ws = fresh_workspace();
        // Restricted roots: only .ee under the workspace.
        let restricted = vec![ws.path().join(".ee")];
        let mut ctx = RunContext::start(ws.path(), "abc1234", restricted, false).unwrap();

        // Write to a parent of the workspace — should refuse.
        let outside = ws.path().parent().unwrap().join("evil.txt");
        let result = mutate(
            &mut ctx,
            &outside,
            Op::WriteFile {
                bytes: b"nope".to_vec(),
            },
        );
        assert!(matches!(
            result,
            Err(DoctorRuntimeError::BlastRadiusExceeded { .. })
        ));
    }

    #[test]
    fn concurrency_second_start_refuses_with_lost() {
        let ws = fresh_workspace();
        let _first = start_run(ws.path());
        let result = RunContext::start(
            ws.path(),
            "deadbeefcafe2",
            vec![ws.path().to_path_buf()],
            false,
        );
        assert!(matches!(
            result,
            Err(DoctorRuntimeError::ConcurrencyLost {
                holder_run_id: None,
                ..
            })
        ));
    }

    #[test]
    fn concurrency_diagnostic_preserves_explicit_external_holder_label() {
        let ws = fresh_workspace();
        let ee_dir = ws.path().join(".ee");
        fs::create_dir_all(&ee_dir).unwrap();
        let lock_path = ee_dir.join(".doctor.lock");
        fs::write(&lock_path, b"external-verifier-holder\n42\n").unwrap();
        let lock = fs::OpenOptions::new()
            .read(true)
            .write(true)
            .open(&lock_path)
            .unwrap();
        Fs4FileExt::try_lock(&lock).expect("external advisory lock should be available");

        let result = RunContext::start(
            ws.path(),
            "contended-by-external-holder",
            default_blast_radius_roots(ws.path()),
            false,
        );

        assert!(matches!(
            result,
            Err(DoctorRuntimeError::ConcurrencyLost {
                holder_run_id: Some(holder),
                ..
            }) if holder == "external-verifier-holder"
        ));
        Fs4FileExt::unlock(&lock).expect("release external advisory lock");
    }

    #[test]
    fn reacquisition_never_overwrites_preexisting_unlocked_lock_path() {
        let ws = fresh_workspace();
        let ee_dir = ws.path().join(".ee");
        fs::create_dir_all(&ee_dir).unwrap();
        let lock_path = ee_dir.join(".doctor.lock");
        let peer_bytes = b"unlocked peer replacement remains immutable";
        fs::write(&lock_path, peer_bytes).unwrap();

        let context = start_run(ws.path());
        assert_eq!(fs::read(&lock_path).unwrap(), peer_bytes);
        context.finish(RunStatus::CompletedOk).unwrap();
        assert_eq!(fs::read(&lock_path).unwrap(), peer_bytes);
    }

    #[test]
    fn finish_unlocks_persistent_lock_and_writes_state() {
        let ws = fresh_workspace();
        let ctx = start_run(ws.path());
        let run_dir = ctx.run_dir().to_path_buf();
        let lock = ws.path().join(".ee").join(".doctor.lock");
        assert!(lock.exists());

        ctx.finish(RunStatus::CompletedOk).expect("finish");
        assert!(
            lock.is_file(),
            "the advisory lock file is intentionally persistent"
        );

        let state: RunState =
            serde_json::from_slice(&fs::read(run_dir.join("state.json")).unwrap()).unwrap();
        assert!(matches!(state.status, RunStatus::CompletedOk));
        assert!(state.finished_at.is_some());

        let next = start_run(ws.path());
        next.finish(RunStatus::CompletedOk)
            .expect("persistent lock must be reacquirable after finish");
    }

    #[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))]
    #[test]
    fn finish_never_touches_lock_path_substituted_before_release() {
        let ws = fresh_workspace();
        let ctx = start_run(ws.path());
        let lock = ws.path().join(".ee").join(".doctor.lock");
        let retained_lock = ws.path().join(".ee").join(".doctor.lock-retained");
        fs::rename(&lock, &retained_lock).expect("retain original lock inode");
        let peer_bytes = b"peer-owned replacement lock";
        fs::write(&lock, peer_bytes).expect("substitute peer-owned regular file");

        let result = ctx.finish(RunStatus::CompletedOk);

        assert!(result.is_ok(), "unlocking the retained handle must succeed");
        assert_eq!(
            fs::read(&lock).expect("read preserved replacement lock"),
            peer_bytes,
            "finish may not unlink or overwrite a substituted regular file"
        );
        assert!(
            retained_lock.is_file(),
            "the acquired lock inode remains untouched under its peer-assigned name"
        );
    }

    #[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))]
    #[test]
    fn finish_never_touches_lock_path_substituted_during_release() {
        let ws = fresh_workspace();
        let ctx = start_run(ws.path());
        let lock = ws.path().join(".ee").join(".doctor.lock");
        let retained_lock = ws.path().join(".ee").join(".doctor.lock-retained");
        let peer_bytes = b"peer replacement installed at the unlock boundary";
        let hook_lock = lock.clone();
        let hook_retained = retained_lock.clone();
        set_doctor_lock_before_unlock_hook(move || {
            fs::rename(&hook_lock, &hook_retained)
                .expect("retain acquired lock at unlock boundary");
            fs::write(&hook_lock, peer_bytes).expect("install peer replacement at unlock boundary");
        });

        ctx.finish(RunStatus::CompletedOk)
            .expect("descriptor-only unlock must ignore namespace substitution");

        assert_eq!(fs::read(&lock).expect("read peer replacement"), peer_bytes);
        assert!(retained_lock.is_file());
    }

    #[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))]
    #[test]
    fn drop_never_touches_lock_path_substituted_after_acquisition() {
        let ws = fresh_workspace();
        let lock = ws.path().join(".ee").join(".doctor.lock");
        let retained_lock = ws.path().join(".ee").join(".doctor.lock-retained");
        let peer_bytes = b"peer replacement before implicit drop";
        {
            let _ctx = start_run(ws.path());
            fs::rename(&lock, &retained_lock).expect("retain acquired lock inode");
            fs::write(&lock, peer_bytes).expect("install peer replacement");
        }

        assert_eq!(
            fs::read(&lock).expect("read replacement after drop"),
            peer_bytes
        );
        assert!(retained_lock.is_file());
    }

    #[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))]
    #[test]
    fn completed_context_never_touches_lock_path_substituted_after_release() {
        let ws = fresh_workspace();
        let lock = ws.path().join(".ee").join(".doctor.lock");
        let prior_lock = ws.path().join(".ee").join(".doctor.lock-prior");
        start_run(ws.path())
            .finish(RunStatus::CompletedOk)
            .expect("finish releases advisory lock");

        fs::rename(&lock, &prior_lock).expect("retain persistent lock after release");
        let peer_bytes = b"peer replacement after release";
        fs::write(&lock, peer_bytes).expect("install post-release replacement");

        assert_eq!(fs::read(&lock).unwrap(), peer_bytes);
        assert!(prior_lock.is_file());
    }

    #[test]
    fn drop_unlocks_persistent_lock_when_finish_was_skipped() {
        let ws = fresh_workspace();
        let lock = ws.path().join(".ee").join(".doctor.lock");
        {
            let _ctx = start_run(ws.path());
            assert!(lock.exists(), "lock should be held while ctx is alive");
            // _ctx is intentionally not `.finish()`-ed; it drops here.
        }
        assert!(
            lock.is_file(),
            "Drop releases the advisory lock without deleting its persistent file"
        );
        let ctx2 = start_run(ws.path());
        ctx2.finish(RunStatus::CompletedOk).expect("finish");
        assert!(lock.is_file());
    }

    #[test]
    fn start_bounds_existing_lock_holder_read() {
        let ws = fresh_workspace();
        let ee_dir = ws.path().join(".ee");
        fs::create_dir_all(&ee_dir).unwrap();
        let lock_path = ee_dir.join(".doctor.lock");
        let lock = fs::File::create(&lock_path).unwrap();
        lock.set_len(DOCTOR_LOCK_FILE_INSPECT_LIMIT.saturating_add(1))
            .unwrap();
        Fs4FileExt::try_lock(&lock).expect("oversized advisory lock should be available");

        let result = RunContext::start(
            ws.path(),
            "deadbeefcafe",
            default_blast_radius_roots(ws.path()),
            false,
        );

        match result {
            Ok(_) => panic!("oversized doctor lock unexpectedly allowed RunContext::start"),
            Err(DoctorRuntimeError::ConcurrencyLost {
                lock_path: observed_lock_path,
                holder_run_id,
            }) => {
                assert_eq!(
                    observed_lock_path,
                    fs::canonicalize(&lock_path).expect("canonicalize oversized doctor lock")
                );
                assert_eq!(holder_run_id, None);
            }
            Err(other) => {
                panic!("expected oversized doctor lock to report concurrency, got {other:?}")
            }
        }
    }

    #[test]
    fn failed_lock_metadata_write_never_removes_or_truncates_public_path() {
        let ws = fresh_workspace();
        let ee_dir = ws.path().join(".ee");
        fs::create_dir_all(&ee_dir).unwrap();
        let lock_path = ee_dir.join(".doctor.lock");
        let original = b"peer-owned read-only lock contents";
        fs::write(&lock_path, original).unwrap();
        let mut read_only = fs::OpenOptions::new().read(true).open(&lock_path).unwrap();
        Fs4FileExt::try_lock(&read_only).expect("read-only test advisory lock should be available");

        let result = write_doctor_lock_contents(&mut read_only, "replacement\n");

        assert!(
            result.is_err(),
            "read-only handle must reject lock metadata write"
        );
        assert_eq!(fs::read(&lock_path).unwrap(), original);
        assert!(lock_path.is_file());
        Fs4FileExt::unlock(&read_only).expect("release test advisory lock");
    }

    #[cfg(any(
        target_os = "linux",
        target_os = "android",
        target_vendor = "apple",
        windows
    ))]
    #[test]
    fn failed_initial_lock_write_leaves_an_unlocked_reusable_persistent_file() {
        let ws = fresh_workspace();
        fail_next_doctor_lock_metadata_write();

        let result = RunContext::start(
            ws.path(),
            "injected-lock-write-failure",
            default_blast_radius_roots(ws.path()),
            false,
        );

        assert!(matches!(
            result,
            Err(DoctorRuntimeError::Io { ref context, .. })
                if context.contains("initialize persistent doctor lock")
        ));
        assert_persistent_doctor_lock_released(ws.path());

        let next = start_run(ws.path());
        next.finish(RunStatus::CompletedOk)
            .expect("existing persistent file must be reusable after failed initial write");
    }

    #[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))]
    #[test]
    fn start_rejects_hard_linked_lock_without_overwriting_peer_inode() {
        let ws = fresh_workspace();
        let ee_dir = ws.path().join(".ee");
        fs::create_dir_all(&ee_dir).unwrap();
        let peer_path = ws.path().join("peer-owned-lock-source");
        let peer_bytes = b"peer inode must remain byte-identical";
        fs::write(&peer_path, peer_bytes).unwrap();
        let lock_path = ee_dir.join(".doctor.lock");
        fs::hard_link(&peer_path, &lock_path).unwrap();

        let result = RunContext::start(
            ws.path(),
            "hard-linked-lock",
            default_blast_radius_roots(ws.path()),
            false,
        );

        assert!(matches!(result, Err(DoctorRuntimeError::Io { .. })));
        assert_eq!(fs::read(&peer_path).unwrap(), peer_bytes);
        assert_eq!(fs::read(&lock_path).unwrap(), peer_bytes);
    }

    #[test]
    fn undo_restores_byte_identical_state_for_write_file() {
        let ws = fresh_workspace();
        let target = ws.path().join("data.txt");
        fs::write(&target, b"original").unwrap();
        let original_hash = hash_file(&target).unwrap();

        let run_dir;
        {
            let mut ctx = start_run(ws.path());
            run_dir = ctx.run_dir().to_path_buf();
            mutate(
                &mut ctx,
                &target,
                Op::WriteFile {
                    bytes: b"updated_v1".to_vec(),
                },
            )
            .unwrap();
            mutate(
                &mut ctx,
                &target,
                Op::WriteFile {
                    bytes: b"updated_v2".to_vec(),
                },
            )
            .unwrap();
            ctx.finish(RunStatus::CompletedOk).unwrap();
        }

        // Two mutations applied. After replay_undo, target must match
        // original bytes byte-for-byte.
        assert_eq!(fs::read(&target).unwrap(), b"updated_v2");
        let summary = replay_test_undo(&run_dir).expect("undo");
        assert_eq!(summary.actions_undone, 2);
        assert_eq!(fs::read(&target).unwrap(), b"original");
        assert_eq!(hash_file(&target).unwrap(), original_hash);
    }

    #[test]
    fn undo_quarantines_files_that_didnt_exist_pre_run() {
        let ws = fresh_workspace();
        let target = ws.path().join("created.txt");

        let run_dir;
        {
            let mut ctx = start_run(ws.path());
            run_dir = ctx.run_dir().to_path_buf();
            mutate(
                &mut ctx,
                &target,
                Op::WriteFile {
                    bytes: b"new".to_vec(),
                },
            )
            .unwrap();
            ctx.finish(RunStatus::CompletedOk).unwrap();
        }

        // After undo, the created file should NOT exist at its original
        // path, but should be quarantined under
        // <run_dir>/quarantine/undo_created/<seq>/<sanitized-path>/created.txt
        // per the round-2 sequence-prefixing fix (R2-P0-03).
        replay_test_undo(&run_dir).expect("undo");
        assert!(!target.exists());
        let undo_root = run_dir.join("quarantine").join("undo_created");
        assert!(undo_root.is_dir());
        // Walk the tree and confirm exactly one `created.txt` exists somewhere
        // under undo_created/<sequence>/.../created.txt.
        let mut found = false;
        let mut stack = vec![undo_root.clone()];
        while let Some(d) = stack.pop() {
            for entry in fs::read_dir(&d).unwrap().flatten() {
                let p = entry.path();
                if p.is_dir() {
                    stack.push(p);
                } else if p.file_name().and_then(|s| s.to_str()) == Some("created.txt") {
                    found = true;
                }
            }
        }
        assert!(
            found,
            "quarantined created.txt not found under {}",
            undo_root.display()
        );
    }

    #[test]
    fn undo_is_idempotent_when_called_twice() {
        let ws = fresh_workspace();
        let target = ws.path().join("d.txt");
        fs::write(&target, b"orig").unwrap();

        let run_dir;
        {
            let mut ctx = start_run(ws.path());
            run_dir = ctx.run_dir().to_path_buf();
            mutate(
                &mut ctx,
                &target,
                Op::WriteFile {
                    bytes: b"new".to_vec(),
                },
            )
            .unwrap();
            ctx.finish(RunStatus::CompletedOk).unwrap();
        }
        let s1 = replay_test_undo(&run_dir).unwrap();
        assert_eq!(s1.actions_undone, 1);
        let s2 = replay_test_undo(&run_dir).unwrap();
        assert_eq!(s2.actions_undone, 0);
        assert_eq!(s2.actions_skipped, 1);
    }

    #[test]
    fn undo_recovers_when_inverse_completed_before_success_receipt() {
        let ws = fresh_workspace();
        let target = ws.path().join("inverse-before-receipt.txt");
        fs::write(&target, b"before").unwrap();

        let mut ctx = start_run(ws.path());
        let run_dir = ctx.run_dir().to_path_buf();
        mutate(
            &mut ctx,
            &target,
            Op::WriteFile {
                bytes: b"after".to_vec(),
            },
        )
        .unwrap();
        ctx.finish(RunStatus::CompletedOk).unwrap();

        // Simulate a process that restored the verified pre-state and then
        // crashed before appending its success receipt.
        fs::write(&target, b"before").unwrap();
        assert!(!run_dir.join("undo_log.jsonl").exists());

        let summary = replay_test_undo(&run_dir).unwrap();
        assert_eq!(summary.actions_undone, 1);
        assert!(matches!(summary.status, RunStatus::Undone));
        assert_eq!(fs::read(&target).unwrap(), b"before");
        assert!(run_dir.join("undo_log.jsonl").is_file());
    }

    #[test]
    fn undo_rejects_matching_success_receipt_when_live_state_is_not_undone() {
        let ws = fresh_workspace();
        let target = ws.path().join("forged-log-target.txt");
        fs::write(&target, b"before").unwrap();

        let mut ctx = start_run(ws.path());
        let run_dir = ctx.run_dir().to_path_buf();
        mutate(
            &mut ctx,
            &target,
            Op::WriteFile {
                bytes: b"after".to_vec(),
            },
        )
        .unwrap();
        ctx.finish(RunStatus::CompletedOk).unwrap();

        fs::write(
            run_dir.join("undo_log.jsonl"),
            serde_json::json!({
                "schema": "ee.doctor.undo_entry.v1",
                "sequence": 1,
                "path": target.display().to_string(),
                "kind": "write_file",
                "undone_at": Utc::now().to_rfc3339(),
            })
            .to_string()
                + "\n",
        )
        .unwrap();

        assert!(matches!(
            replay_test_undo(&run_dir),
            Err(DoctorRuntimeError::RunArtifactInvalid { .. })
        ));
        assert_eq!(fs::read(&target).unwrap(), b"after");
    }

    #[test]
    fn undo_fails_closed_when_state_json_is_missing() {
        let runs = fresh_workspace();
        let run_dir = runs
            .path()
            .join(".doctor")
            .join("runs")
            .join("run_without_state");
        fs::create_dir_all(&run_dir).unwrap();
        fs::write(run_dir.join("actions.jsonl"), "").unwrap();

        let result = replay_test_undo(&run_dir);

        match result {
            Err(DoctorRuntimeError::Io { context, source }) => {
                assert!(context.contains("read state.json"), "{context}");
                assert_eq!(source.kind(), io::ErrorKind::NotFound);
            }
            other => panic!("expected missing state.json to fail closed, got {other:?}"),
        }
        assert!(
            !run_dir.join("undo_log.jsonl").exists(),
            "undo must stop before replay artifacts are written"
        );
    }

    #[test]
    fn undo_fails_closed_when_state_json_is_corrupt() {
        let runs = fresh_workspace();
        let run_dir = runs
            .path()
            .join(".doctor")
            .join("runs")
            .join("run_with_corrupt_state");
        fs::create_dir_all(&run_dir).unwrap();
        fs::write(run_dir.join("state.json"), b"{not valid json").unwrap();
        fs::write(run_dir.join("actions.jsonl"), "").unwrap();

        let result = replay_test_undo(&run_dir);

        match result {
            Err(DoctorRuntimeError::Io { context, source }) => {
                assert!(context.contains("parse state.json"), "{context}");
                assert_eq!(source.kind(), io::ErrorKind::InvalidData);
            }
            other => panic!("expected corrupt state.json to fail closed, got {other:?}"),
        }
        assert!(
            !run_dir.join("undo_log.jsonl").exists(),
            "undo must stop before replay artifacts are written"
        );
    }

    #[test]
    fn undo_fails_closed_when_actions_jsonl_is_oversized() {
        let ws = fresh_workspace();
        let run_dir;
        {
            let ctx = start_run(ws.path());
            run_dir = ctx.run_dir().to_path_buf();
            ctx.finish(RunStatus::CompletedOk).unwrap();
        }

        let actions_path = run_dir.join("actions.jsonl");
        let actions = fs::File::create(&actions_path).unwrap();
        actions
            .set_len(DOCTOR_ACTION_LOG_INSPECT_LIMIT.saturating_add(1))
            .unwrap();

        let result = replay_test_undo(&run_dir);

        match result {
            Err(DoctorRuntimeError::Io { context, source }) => {
                assert!(context.contains("read actions.jsonl"), "{context}");
                assert_eq!(source.kind(), io::ErrorKind::InvalidData);
            }
            other => panic!("expected oversized actions.jsonl to fail closed, got {other:?}"),
        }
        assert!(
            !run_dir.join("undo_log.jsonl").exists(),
            "undo must stop before replay artifacts are written"
        );
        assert_persistent_doctor_lock_released(ws.path());
    }

    #[test]
    fn undo_fails_closed_when_undo_log_jsonl_is_oversized() {
        let ws = fresh_workspace();
        let target = ws.path().join("data.txt");
        fs::write(&target, b"original").unwrap();

        let run_dir;
        {
            let mut ctx = start_run(ws.path());
            run_dir = ctx.run_dir().to_path_buf();
            mutate(
                &mut ctx,
                &target,
                Op::WriteFile {
                    bytes: b"updated".to_vec(),
                },
            )
            .unwrap();
            ctx.finish(RunStatus::CompletedOk).unwrap();
        }

        let undo_log_path = run_dir.join("undo_log.jsonl");
        let undo_log = fs::File::create(&undo_log_path).unwrap();
        undo_log
            .set_len(DOCTOR_ACTION_LOG_INSPECT_LIMIT.saturating_add(1))
            .unwrap();

        let result = replay_test_undo(&run_dir);

        match result {
            Err(DoctorRuntimeError::Io { context, source }) => {
                assert!(context.contains("read undo_log.jsonl"), "{context}");
                assert_eq!(source.kind(), io::ErrorKind::InvalidData);
            }
            other => panic!("expected oversized undo_log.jsonl to fail closed, got {other:?}"),
        }
        assert_eq!(
            fs::read(&target).unwrap(),
            b"updated",
            "undo must not start mutating before it can inspect the undo log"
        );
        assert_persistent_doctor_lock_released(ws.path());
    }

    #[test]
    fn quarantine_by_rename_moves_file_into_run_quarantine() {
        let ws = fresh_workspace();
        let target = ws.path().join("trash.tmp");
        fs::write(&target, b"junk").unwrap();

        let mut ctx = start_run(ws.path());
        let line = mutate(
            &mut ctx,
            &target,
            Op::QuarantineByRename {
                dest_under_quarantine: PathBuf::from("trash.tmp"),
            },
        )
        .unwrap();
        assert!(!target.exists());
        assert!(ctx.run_dir().join("quarantine").join("trash.tmp").exists());
        assert_eq!(line.kind, "quarantine_by_rename");
    }

    #[test]
    fn manual_op_records_action_but_writes_nothing_to_disk() {
        let ws = fresh_workspace();
        let mut ctx = start_run(ws.path());
        let target = ws.path().join("nonexistent");
        let line = mutate(
            &mut ctx,
            &target,
            Op::Manual {
                steps: vec!["run X".into(), "then Y".into()],
            },
        )
        .unwrap();
        assert!(!target.exists());
        assert_eq!(line.kind, "manual");
        assert!(line.notes.is_some());
    }

    #[test]
    fn capabilities_report_is_stable_and_self_describing() {
        let ws = fresh_workspace();
        let report = CapabilitiesReport::build("0.1.0", ws.path());
        let json = serde_json::to_string_pretty(&report).unwrap();
        assert!(json.contains("ee.doctor.capabilities.v1"));
        assert!(json.contains("write_file"));
        assert!(json.contains("quarantine_by_rename"));
        assert!(json.contains("\"code\": 5"));
        assert!(json.contains("configuration"));
        assert!(json.contains("storage"));
        assert!(json.contains("policy_denied"));
    }

    #[test]
    fn derive_run_id_is_unique_for_fast_same_target_runs() {
        let ids = (0..16)
            .map(|_| derive_run_id("deadbeefcafe"))
            .collect::<Vec<_>>();
        let unique = ids.iter().collect::<std::collections::HashSet<_>>();

        assert_eq!(
            unique.len(),
            ids.len(),
            "same-target doctor runs must not reuse run directories: {ids:?}"
        );
    }

    #[test]
    fn dry_run_records_actions_without_touching_disk() {
        let ws = fresh_workspace();
        let target = ws.path().join("data.txt");
        fs::write(&target, b"orig").unwrap();

        let mut roots = default_blast_radius_roots(ws.path());
        roots.push(ws.path().to_path_buf());
        let mut ctx = RunContext::start(ws.path(), "sha", roots, /*dry_run*/ true).unwrap();

        let _line = mutate(
            &mut ctx,
            &target,
            Op::WriteFile {
                bytes: b"new".to_vec(),
            },
        )
        .unwrap();
        // Disk is unchanged.
        assert_eq!(fs::read(&target).unwrap(), b"orig");
        // But the action is recorded.
        let actions = fs::read_to_string(ctx.run_dir().join("actions.jsonl")).unwrap();
        assert!(actions.contains("write_file"));
    }

    #[test]
    fn undo_refuses_dry_run_plan_without_touching_later_state() {
        let ws = fresh_workspace();
        let target = ws.path().join("created-after-dry-run");
        let mut roots = default_blast_radius_roots(ws.path());
        roots.push(ws.path().to_path_buf());
        let mut ctx = RunContext::start(ws.path(), "dry-undo", roots, true).unwrap();
        let run_dir = ctx.run_dir().to_path_buf();
        let run_id = ctx.run_id().to_owned();

        mutate(&mut ctx, &target, Op::CreateDirAll { mode: 0o755 }).unwrap();
        ctx.finish(RunStatus::CompletedOk).unwrap();
        fs::create_dir(&target).unwrap();
        let state_before = fs::read(run_dir.join("state.json")).unwrap();

        let mut current_roots = default_blast_radius_roots(ws.path());
        current_roots.push(ws.path().to_path_buf());
        assert!(matches!(
            replay_undo_with_authorized_roots(ws.path(), &run_id, &current_roots),
            Err(DoctorRuntimeError::DryRunNotUndoable { .. })
        ));
        assert!(target.is_dir());
        assert!(!run_dir.join("undo_log.jsonl").exists());
        assert_eq!(fs::read(run_dir.join("state.json")).unwrap(), state_before);
    }

    #[test]
    fn mutate_refuses_relative_writing_paths_before_logging_actions() {
        let ws = fresh_workspace();
        let cwd = std::env::current_dir().expect("current dir");
        let mut ctx = RunContext::start(ws.path(), "sha", vec![cwd], /*dry_run*/ true).unwrap();

        let result = mutate(
            &mut ctx,
            Path::new("./relative-doctor-runtime-created-dir"),
            Op::CreateDirAll { mode: 0o755 },
        );

        assert!(matches!(
            result,
            Err(DoctorRuntimeError::BlastRadiusExceeded { .. })
        ));
        let actions = fs::read_to_string(ctx.run_dir().join("actions.jsonl")).unwrap();
        assert!(
            actions.is_empty(),
            "relative writing paths must fail before actions are logged"
        );
    }

    #[test]
    fn create_dir_all_is_idempotent_on_existing_dir() {
        let ws = fresh_workspace();
        let mut ctx = start_run(ws.path());
        let target = ws.path().join("subdir");
        fs::create_dir_all(&target).unwrap();

        let result = mutate(&mut ctx, &target, Op::CreateDirAll { mode: 0o755 });
        assert!(matches!(result, Err(DoctorRuntimeError::NoOpIdempotent)));
    }

    #[test]
    fn quarantine_refuses_path_traversal_with_parent_dir_components() {
        // Defense-in-depth: a buggy fixer could pass `../../etc/passwd` as the
        // quarantine destination. Validate that the chokepoint refuses with
        // BlastRadiusExceeded rather than letting `fs::rename` resolve the `..`
        // and escape the run-dir quarantine root. Round-1 fresh-eyes review.
        let ws = fresh_workspace();
        let target = ws.path().join("victim.txt");
        fs::write(&target, b"hi").unwrap();

        let mut ctx = start_run(ws.path());
        let result = mutate(
            &mut ctx,
            &target,
            Op::QuarantineByRename {
                dest_under_quarantine: PathBuf::from("../../etc/passwd"),
            },
        );
        assert!(matches!(
            result,
            Err(DoctorRuntimeError::BlastRadiusExceeded { .. })
        ));
        // Victim is untouched.
        assert!(target.exists());
        assert_eq!(fs::read(&target).unwrap(), b"hi");
    }

    #[test]
    fn undo_refuses_when_live_file_drifted_after_doctor_run() {
        // Round-2 fresh-eyes (F5): if an external writer modified the file
        // after the doctor's --fix, undo must NOT silently overwrite. Refuse
        // with UndoStateDrifted; let the operator inspect.
        let ws = fresh_workspace();
        let target = ws.path().join("data.txt");
        fs::write(&target, b"original").unwrap();

        let run_dir;
        {
            let mut ctx = start_run(ws.path());
            run_dir = ctx.run_dir().to_path_buf();
            mutate(
                &mut ctx,
                &target,
                Op::WriteFile {
                    bytes: b"doctor_wrote".to_vec(),
                },
            )
            .unwrap();
            ctx.finish(RunStatus::CompletedOk).unwrap();
        }

        // Simulate external writer modifying the file after the doctor ran.
        fs::write(&target, b"external_writer_changed_this").unwrap();

        let result = replay_test_undo(&run_dir);
        let summary = result.expect("replay_undo returns Ok with partial status");
        // The undo refused this action; status reflects partial completion.
        assert!(matches!(summary.status, RunStatus::UndonePartial));
        assert!(summary.first_error.is_some());
        let err = summary.first_error.unwrap();
        assert!(
            err.contains("drifted"),
            "expected drift error, got: {}",
            err
        );
        // Live file is untouched — the external writer's change is preserved.
        assert_eq!(fs::read(&target).unwrap(), b"external_writer_changed_this");
    }

    #[test]
    fn undo_refuses_when_path_reoccupied_after_quarantine() {
        // Round-2 fresh-eyes (F6): if something landed at the original path
        // between quarantine and undo, refuse rather than overwrite.
        let ws = fresh_workspace();
        let victim = ws.path().join("orphan.wal");
        fs::write(&victim, b"original wal").unwrap();

        let run_dir;
        {
            let mut ctx = start_run(ws.path());
            run_dir = ctx.run_dir().to_path_buf();
            mutate(
                &mut ctx,
                &victim,
                Op::QuarantineByRename {
                    dest_under_quarantine: PathBuf::from("orphan.wal"),
                },
            )
            .unwrap();
            ctx.finish(RunStatus::CompletedOk).unwrap();
        }

        // Simulate: an unrelated process creates a NEW file at the same
        // path after the doctor quarantined the original.
        fs::write(&victim, b"new_unrelated_file").unwrap();

        let summary = replay_test_undo(&run_dir).expect("returns Ok with partial");
        assert!(matches!(summary.status, RunStatus::UndonePartial));
        let err = summary.first_error.unwrap();
        assert!(
            err.contains("drifted"),
            "expected drift error, got: {}",
            err
        );
        // The new unrelated file is preserved.
        assert_eq!(fs::read(&victim).unwrap(), b"new_unrelated_file");
        // The quarantined original is still safely in quarantine.
        let quarantine = run_dir.join("quarantine").join("orphan.wal");
        assert!(quarantine.exists());
        assert_eq!(fs::read(&quarantine).unwrap(), b"original wal");
    }

    #[test]
    fn two_writes_to_same_path_in_one_run_undo_byte_identical() {
        // Round-2 fresh-eyes R2-P0-01: the headline finding. Two
        // WriteFile mutations of the SAME target file in a single run
        // must each store their own backup, so undo can walk both
        // actions in reverse and end at the original bytes.
        let ws = fresh_workspace();
        let target = ws.path().join("data.txt");
        fs::write(&target, b"orig").unwrap();

        let run_dir;
        {
            let mut ctx = start_run(ws.path());
            run_dir = ctx.run_dir().to_path_buf();
            // First write.
            mutate(
                &mut ctx,
                &target,
                Op::WriteFile {
                    bytes: b"v1".to_vec(),
                },
            )
            .unwrap();
            // Second write (same path, different bytes).
            mutate(
                &mut ctx,
                &target,
                Op::WriteFile {
                    bytes: b"v2".to_vec(),
                },
            )
            .unwrap();
            ctx.finish(RunStatus::CompletedOk).unwrap();
        }

        // Two distinct backups must exist under their sequence-prefixed
        // directories.
        let b1 = run_dir.join("backups").join("000001");
        let b2 = run_dir.join("backups").join("000002");
        assert!(b1.is_dir(), "first backup dir missing: {}", b1.display());
        assert!(b2.is_dir(), "second backup dir missing: {}", b2.display());

        // Undo restores byte-identical original.
        let summary = replay_test_undo(&run_dir).unwrap();
        assert_eq!(summary.actions_undone, 2);
        assert_eq!(fs::read(&target).unwrap(), b"orig");
    }

    #[test]
    fn chmod_idempotent_when_mode_already_matches() {
        // Round-2 fresh-eyes R2-P1-02: Chmod with the same mode the file
        // already has must return NoOpIdempotent rather than spuriously
        // recording a bumped-but-unchanged mtime in actions.jsonl.
        // Unix-only because Windows treats mode bits as advisory.
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt as _;
            let ws = fresh_workspace();
            let target = ws.path().join("perm.txt");
            fs::write(&target, b"x").unwrap();
            fs::set_permissions(&target, fs::Permissions::from_mode(0o644)).unwrap();

            let mut ctx = start_run(ws.path());
            let result = mutate(&mut ctx, &target, Op::Chmod { mode: 0o644 });
            assert!(
                matches!(result, Err(DoctorRuntimeError::NoOpIdempotent)),
                "expected NoOpIdempotent, got: {:?}",
                result
            );
        }
    }

    #[test]
    fn write_file_atomic_refuses_path_without_parent() {
        // Round-2 R2-P1-04 → round-5 → round-6 self-review.
        // `write_file_atomic` used to fall back to the CWD of an invoking
        // shell when given a parentless or relative path. Round-6 tightened
        // the filter to refuse any parent that isn't absolute, since the
        // chokepoint's invariant (after R5-3 absolutized the workspace) is
        // that every write goes to an absolute path. Each parent form below
        // would have leaked into CWD under the previous, weaker guards.
        //
        // - `Path::new("")` has `.parent() == None`.
        // - `Path::new("foo.txt")` has `.parent() == Some("")` — slipped
        //   past the original R2-P1-04 None-only guard.
        // - `Path::new("./foo.txt")` has `.parent() == Some(".")`
        //   (non-empty, non-absolute) — slipped past the R5-2 is_empty
        //   filter.
        // - `Path::new("../foo.txt")` has `.parent() == Some("..")` —
        //   same class as `./foo.txt`.
        for parentless in [
            Path::new(""),
            Path::new("foo.txt"),
            Path::new("./foo.txt"),
            Path::new("../foo.txt"),
        ] {
            let result = write_file_atomic(parentless, b"x");
            assert!(
                result.is_err(),
                "write_file_atomic should refuse path lacking an absolute parent: {}",
                parentless.display()
            );
            let err = result.unwrap_err();
            assert!(
                matches!(
                    err.kind(),
                    io::ErrorKind::InvalidInput | io::ErrorKind::NotFound
                ),
                "unexpected error kind for {}: {:?}",
                parentless.display(),
                err.kind()
            );
        }
    }

    #[test]
    fn two_writes_to_different_paths_with_same_basename_undo_correctly() {
        // Round-2 fresh-eyes R2-P0-03: undo of `Op::WriteFile { bytes: ... }`
        // where two files share a basename (e.g., a/config.toml and
        // b/config.toml) — previously the undo quarantine destination was
        // namespaced only by `file_name()`, so the second undo would
        // overwrite the first. Now namespaced by sequence + sanitized path.
        let ws = fresh_workspace();
        let a = ws.path().join("a/config.toml");
        let b = ws.path().join("b/config.toml");
        fs::create_dir_all(a.parent().unwrap()).unwrap();
        fs::create_dir_all(b.parent().unwrap()).unwrap();
        // Neither file exists initially.

        let run_dir;
        {
            let mut ctx = start_run(ws.path());
            run_dir = ctx.run_dir().to_path_buf();
            mutate(
                &mut ctx,
                &a,
                Op::WriteFile {
                    bytes: b"contents-a".to_vec(),
                },
            )
            .unwrap();
            mutate(
                &mut ctx,
                &b,
                Op::WriteFile {
                    bytes: b"contents-b".to_vec(),
                },
            )
            .unwrap();
            ctx.finish(RunStatus::CompletedOk).unwrap();
        }

        // After undo, both files are quarantined; the doctor never deletes.
        // Verify both quarantine destinations are distinct paths and both
        // hold their original creation bytes.
        replay_test_undo(&run_dir).unwrap();
        assert!(!a.exists());
        assert!(!b.exists());

        let q_root = run_dir.join("quarantine").join("undo_created");
        // Two sequence-prefixed quarantine dirs must exist.
        let mut entries: Vec<String> = fs::read_dir(&q_root)
            .unwrap()
            .map(|e| e.unwrap().file_name().into_string().unwrap())
            .collect();
        entries.sort();
        assert_eq!(
            entries,
            vec!["000001".to_string(), "000002".to_string()],
            "expected sequence-prefixed quarantine dirs, found: {:?}",
            entries
        );
    }

    #[test]
    fn quarantine_refuses_absolute_path_destination() {
        // Defense-in-depth: `Path::join(absolute)` replaces the prefix entirely.
        // Without validation, `dest_under_quarantine = "/etc/passwd"` would
        // overwrite or move to `/etc/passwd`. Refuse instead.
        let ws = fresh_workspace();
        let target = ws.path().join("victim.txt");
        fs::write(&target, b"hi").unwrap();

        let mut ctx = start_run(ws.path());
        let result = mutate(
            &mut ctx,
            &target,
            Op::QuarantineByRename {
                dest_under_quarantine: PathBuf::from("/tmp/escape"),
            },
        );
        assert!(matches!(
            result,
            Err(DoctorRuntimeError::BlastRadiusExceeded { .. })
        ));
        assert!(target.exists());
    }
}