beads_rust 0.5.10

Agent-first issue tracker (SQLite + JSONL)
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
//! WP6 — agent-ergonomics surface for `br doctor`.
//!
//! Implements the dispatch targets for the `br doctor <subcommand>` group
//! defined by [`crate::cli::DoctorSubcommand`]:
//!
//! - `capabilities` — `br.doctor.capabilities.v1` envelope (JSON or table).
//! - `robot-docs`  — paste-ready agent handbook (Markdown or wrapped JSON).
//! - `health`      — sub-200 ms liveness summary; exit-code = liveness.
//! - `ls`          — list runs in `.doctor/runs/`.
//! - `undo`        — restore from `.doctor/runs/<run-id>/backups/`.
//! - `explain`     — expand a single finding (stub).
//!
//! Every JSON surface pins a `schema_version`. The `--robot-triage` flag
//! on the flat doctor command also lives here ([`emit_robot_triage`]).
//!
//! ## Safety
//!
//! - `health`, `capabilities`, `robot-docs`, `ls`, `explain` are
//!   read-only.
//! - `undo` mutates. File restores flow through
//!   [`super::mutate::mutate`] with a fresh undo run-dir; DB restores
//!   replay the recorded JSON snapshots inside one SQLite transaction.

#![allow(clippy::needless_pass_by_value)]

use std::collections::HashMap;
use std::fs::{self, OpenOptions};
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::time::Instant;

use serde::{Deserialize, Serialize};

use crate::cli::commands::doctor_subsystems::capabilities_doctor::DoctorCapabilities;
use crate::cli::commands::doctor_subsystems::exit_codes::DoctorExitCode;
use crate::cli::commands::doctor_subsystems::mutate::{
    self as chokepoint, Capabilities as MutateCapabilities, MutateContext, Op,
};
use crate::cli::commands::doctor_subsystems::run_dir;
use crate::cli::{
    DoctorCapabilitiesArgs, DoctorExplainArgs, DoctorHealthArgs, DoctorLsArgs, DoctorRobotDocsArgs,
    DoctorSubcommand, DoctorUndoArgs, OutputFormatBasic,
};
use crate::config;
use crate::error::{BeadsError, Result};
use crate::output::OutputContext;
use crate::storage::schema::CURRENT_SCHEMA_VERSION;
use crate::storage::sqlite::database_header_user_version;

#[cfg(unix)]
fn metadata_mode(metadata: &fs::Metadata) -> u32 {
    use std::os::unix::fs::PermissionsExt;
    metadata.permissions().mode()
}

#[cfg(not(unix))]
fn metadata_mode(metadata: &fs::Metadata) -> u32 {
    if metadata.permissions().readonly() {
        0o444
    } else {
        0o666
    }
}

/// Top-level dispatcher for `br doctor <subcommand>`. Resolves the
/// repo root via `config::discover_optional_beads_dir_with_cli` and
/// hands off to the per-subcommand handler.
///
/// # Errors
///
/// Returns [`BeadsError`] if subcommand-specific I/O or serialization
/// faults.
pub fn dispatch_subcommand(
    sub: &DoctorSubcommand,
    cli: &config::CliOverrides,
    ctx: &OutputContext,
) -> Result<()> {
    let repo_root = match config::discover_optional_beads_dir_with_cli(cli)? {
        Some(beads) => beads
            .parent()
            .map(Path::to_path_buf)
            .unwrap_or_else(|| beads.clone()),
        None => std::env::current_dir().map_err(BeadsError::Io)?,
    };
    match sub {
        DoctorSubcommand::Capabilities(a) => execute_capabilities(a, ctx),
        DoctorSubcommand::RobotDocs(a) => execute_robot_docs(a, ctx),
        DoctorSubcommand::Health(a) => {
            let code = execute_health(a, &repo_root)?;
            if code != 0 {
                crate::shutdown::exit_process(code);
            }
            Ok(())
        }
        DoctorSubcommand::Ls(a) => execute_ls(a, &repo_root),
        DoctorSubcommand::Undo(a) => execute_undo(a, &repo_root),
        DoctorSubcommand::MigrateSchema(a) => super::schema_migration::execute(a, cli, ctx),
        DoctorSubcommand::Explain(a) => execute_explain(a, cli),
    }
}

/// Stable schema-version constants — every JSON envelope pins one.
pub const CAPABILITIES_SCHEMA: &str = "br.doctor.capabilities.v1";
pub const HEALTH_SCHEMA: &str = "br.doctor.health.v1";
pub const RUNS_LIST_SCHEMA: &str = "br.doctor.runs_list.v1";
pub const TRIAGE_SCHEMA: &str = "br.doctor.triage.v1";
pub const ROBOT_DOCS_SCHEMA: &str = "br.doctor.robot_docs.v1";
pub const UNDO_SCHEMA: &str = "br.doctor.undo.v1";
pub const EXPLAIN_SCHEMA: &str = "br.doctor.explain.v1";

// =============================================================================
// capabilities
// =============================================================================

/// Top-level envelope for `br doctor capabilities`. Wraps the inner
/// [`DoctorCapabilities`] struct with a stable
/// `schema_version = "br.doctor.capabilities.v1"`.
#[derive(Debug, Clone, Serialize)]
pub struct CapabilitiesEnvelope<'a> {
    pub schema_version: &'static str,
    #[serde(flatten)]
    pub inner: &'a DoctorCapabilities,
}

/// Execute `br doctor capabilities`.
///
/// Read-only. Always exits 0 (the doctor's contract: capabilities is a
/// pure diagnostic).
///
/// # Errors
///
/// Returns [`BeadsError`] if JSON serialization fails (effectively
/// never with the data shapes used here).
pub fn execute_capabilities(args: &DoctorCapabilitiesArgs, _ctx: &OutputContext) -> Result<()> {
    let caps = DoctorCapabilities::build();

    // `--command <id>` narrows the envelope to the fixers, detectors, and
    // finding-id rows whose ids contain the filter (case-insensitive), so an
    // agent can ask "what does the doctor know about gitignore?" without
    // paging through the full contract.
    let caps = match args.command.as_deref().map(str::trim) {
        Some(filter) if !filter.is_empty() => filter_capabilities(&caps, filter),
        _ => caps,
    };
    let envelope = CapabilitiesEnvelope {
        schema_version: CAPABILITIES_SCHEMA,
        inner: &caps,
    };

    match args.format {
        OutputFormatBasic::Json | OutputFormatBasic::Toon => {
            // The capabilities subcommand is a pure machine-readable
            // surface — emit pretty JSON to stdout regardless of the
            // outer OutputContext (which may be Quiet for CI runs).
            let json = serde_json::to_string_pretty(&envelope).map_err(BeadsError::Json)?;
            println!("{json}");
        }
        OutputFormatBasic::Text => render_capabilities_text(&envelope),
    }
    Ok(())
}

fn render_capabilities_text(env: &CapabilitiesEnvelope<'_>) {
    println!("br doctor capabilities");
    println!("  schema_version  : {}", env.schema_version);
    println!("  contract_version: {}", env.inner.contract_version);
    println!("  doctor_version  : {}", env.inner.doctor_version);
    println!();
    println!("  Exit codes:");
    for entry in &env.inner.exit_codes {
        println!(
            "    {:>3} {:<24} {}",
            entry.code, entry.name, entry.description
        );
    }
    println!();
    println!("  Write scopes:");
    for scope in &env.inner.write_scopes {
        println!("    - {scope}");
    }
    println!();
    println!("  Env vars:");
    for var in &env.inner.env_vars {
        println!("    - {var}");
    }
    println!();
    println!("  Fixers     : {} registered", env.inner.fixers.len());
    println!("  Detectors  : {} registered", env.inner.detectors.len());
    println!();
    println!("Use `br doctor capabilities --format json` for the machine envelope.");
}

// =============================================================================
// robot-docs
// =============================================================================

const ROBOT_HANDBOOK_BODY: &str = r#"# br doctor — Agent Handbook

Contract version: **br.doctor.contract.v1**

`br doctor` is a diagnose-and-(optionally)-repair surface designed for AI
agents. Every disk write under `--repair` flows through a single
[`mutate()`](https://docs.rs/beads_rust) chokepoint that records a verbatim
backup, an `actions.jsonl` audit line, and an `undo.sh` fallback before
touching any byte of state.

## Subcommand surface

| Subcommand | Purpose | Mutates? |
|------------|---------|----------|
| (flat) `br doctor` | Run all detectors. Print findings. | NO |
| (flat) `br doctor --repair` | Apply fixers; back up everything. | YES (via `mutate()`) |
| `br doctor --robot-triage` | Single JSON envelope for swarm triage. | NO |
| `br doctor capabilities --format json` | Machine-readable contract. | NO |
| `br doctor robot-docs` | This handbook. | NO |
| `br doctor health` | Cheap one-line liveness summary. | NO |
| `br doctor ls` | List `.doctor/runs/` directories. | NO |
| `br doctor undo <run-id>` | Restore from `.doctor/runs/<id>/backups/`. | YES (restore) |
| `br doctor undo latest` | Resolve `latest` and restore. | YES (restore) |
| `br doctor explain <finding-id>` | Expand a single finding. | NO |

## Top-level flags (flat command)

| Flag | Purpose |
|------|---------|
| `--repair` | Apply fixers. Routes through `mutate()`. |
| `--dry-run` | Print the plan; do NOT execute. Pair with `--repair`. |
| `--allow-repeated-repair` | Permit a fresh JSONL rebuild after a prior failed recovery. |
| `--robot-triage` | Emit `br.doctor.triage.v1` and exit. |

## Exit codes

| Code | Name | Meaning |
|------|------|---------|
| `0`  | `healthy` | every check passed |
| `1`  | `findings_present` | findings exist; `--repair` not requested |
| `2`  | `fix_partial` | `--repair` ran; some fixers failed |
| `3`  | `fix_failed_rolled_back` | `--repair` faulted and rolled back from backup |
| `4`  | `refused_unsafe` | precondition gate refused (scope / schema / fingerprint) |
| `5`  | `concurrency_lost` | workspace lock unavailable |
| `6`  | `online_required` | network probe required `--online` |
| `64` | `usage_error` | clap rejected the invocation |
| `66` | `no_input` | required input missing (no `.beads/`) |
| `73` | `cannot_create_output` | could not create the run-dir |
| `74` | `io_error` | generic I/O fault during a non-mutating op |

## Canonical examples

### Happy path (workspace healthy)

```sh
br doctor               # exit 0; no findings
br doctor --robot-triage  # exit 0; envelope shows zero findings
```

### Broken path (findings present)

```sh
br doctor                                   # exit 1; findings printed
br doctor --robot-triage                    # exit 1; JSON shows recommended_command
br doctor --repair --dry-run                # exit 0; prints the plan
br doctor --repair                          # exit 0/2/3 depending on fixer outcomes
br doctor undo latest                       # exit 0; restores from the latest run
```

### Recovery (worked through `mutate()`)

Every `--repair` lays down `<repo>/.doctor/runs/<run-id>/`:

```text
.doctor/runs/<run-id>/
  actions.jsonl     # one JSON line per mutation
  backups/          # verbatim pre-mutation copies
  report.json       # final report (written at end of run)
  undo.sh           # pure-bash fallback when br itself is broken
.doctor/latest -> runs/<run-id>/   # best-effort convenience symlink
```

## What `br doctor` will NEVER do

1. Delete files. Anything that "needs to delete" is renamed into
   `<run-dir>/quarantine/` instead, so `undo` can reverse it.
2. Run destructive shell. There is no `Command::new("git")` in the
   doctor — the chokepoint is the only writer.
3. Write outside its declared `write_scopes` (`.beads/`, `.doctor/`).
4. Skip the verbatim backup — every mutation is preceded by a strict
   byte-by-byte `cmp -s` of the live file against the freshly-written
   backup.
5. Mutate without an audit trail — every action lands in
   `actions.jsonl` so `br doctor undo` can replay it in reverse.

## Recovery without br

If the `br` binary itself is broken, the per-run directory ships with a
pure-bash `undo.sh` that needs only `bash`, `jq`, `cp`, and `mv`. Run:

```sh
bash .doctor/runs/<run-id>/undo.sh
```

## See also

- `br doctor capabilities --format json` — machine-readable contract
- `br doctor health --json` — liveness summary
- The operator playbook lives at
  `<repo>/.../doctor_workspace/playbook.md`; consult it before running
  `--repair` on production workspaces.
"#;

/// Execute `br doctor robot-docs`.
///
/// # Errors
///
/// Returns [`BeadsError`] only if the JSON envelope fails to serialize.
pub fn execute_robot_docs(args: &DoctorRobotDocsArgs, _ctx: &OutputContext) -> Result<()> {
    match args.format {
        OutputFormatBasic::Json | OutputFormatBasic::Toon => {
            #[derive(Serialize)]
            struct Envelope<'a> {
                schema_version: &'static str,
                tool: &'static str,
                tool_version: &'static str,
                contract_version: &'static str,
                title: &'static str,
                line_count: usize,
                handbook: &'a str,
            }
            let envelope = Envelope {
                schema_version: ROBOT_DOCS_SCHEMA,
                tool: "br",
                tool_version: env!("CARGO_PKG_VERSION"),
                contract_version: "br.doctor.contract.v1",
                title: "br doctor — Agent Handbook",
                line_count: ROBOT_HANDBOOK_BODY.lines().count(),
                handbook: ROBOT_HANDBOOK_BODY,
            };
            let json = serde_json::to_string_pretty(&envelope).map_err(BeadsError::Json)?;
            println!("{json}");
        }
        OutputFormatBasic::Text => {
            print!("{ROBOT_HANDBOOK_BODY}");
        }
    }
    Ok(())
}

/// Pure accessor — used by tests and by `--robot-triage` to embed the
/// handbook command in the envelope.
#[must_use]
pub const fn robot_handbook_body() -> &'static str {
    ROBOT_HANDBOOK_BODY
}

// =============================================================================
// health
// =============================================================================

/// Output of `br doctor health`. Shape pinned by [`HEALTH_SCHEMA`].
#[derive(Debug, Clone, Serialize)]
pub struct HealthOutput {
    pub schema_version: &'static str,
    pub status: &'static str,
    pub exit_code: i32,
    pub beads_dir_present: bool,
    pub db_present: bool,
    pub jsonl_present: bool,
    pub merge_artifacts_present: bool,
    pub orphan_write_lock: bool,
    pub orphan_sync_lock: bool,
    /// Checkpointed schema `user_version` read from the database file header,
    /// or `None` when there is no readable SQLite database to probe (#464).
    pub schema_user_version: Option<u32>,
    /// Schema version this binary requires ([`CURRENT_SCHEMA_VERSION`]).
    pub schema_expected: i32,
    /// `false` when a database is present but its header schema version is a
    /// non-zero value other than [`CURRENT_SCHEMA_VERSION`] — mutations refuse
    /// such a database even though the file exists.
    pub schema_compatible: bool,
    pub elapsed_ms: u128,
    /// One-line summary suitable for stdout.
    pub line: String,
}

/// Execute `br doctor health`.
///
/// Stays under 200 ms by avoiding any DB query — only stat checks
/// against the workspace tree.
///
/// # Errors
///
/// Always returns `Ok`; the doctor exit code is the liveness signal,
/// not an error.
pub fn execute_health(args: &DoctorHealthArgs, repo_root: &Path) -> Result<i32> {
    let output = build_health_output(repo_root, Instant::now());
    emit_health(args, &output);
    Ok(output.exit_code)
}

fn build_health_output(repo_root: &Path, start: Instant) -> HealthOutput {
    let beads = repo_root.join(".beads");
    let beads_dir_present = beads.is_dir();

    if !beads_dir_present {
        let line = format!(
            "no_workspace  br={} reason=missing_dot_beads",
            env!("CARGO_PKG_VERSION")
        );
        let exit_code = DoctorExitCode::NoInput.as_i32();
        return HealthOutput {
            schema_version: HEALTH_SCHEMA,
            status: "no_workspace",
            exit_code,
            beads_dir_present,
            db_present: false,
            jsonl_present: false,
            merge_artifacts_present: false,
            orphan_write_lock: false,
            orphan_sync_lock: false,
            schema_user_version: None,
            schema_expected: CURRENT_SCHEMA_VERSION,
            schema_compatible: true,
            elapsed_ms: start.elapsed().as_millis(),
            line,
        };
    }

    let db = beads.join("beads.db");
    let db_present = db.is_file();
    let jsonl_present = beads.join("issues.jsonl").is_file() || beads.join("beads.jsonl").is_file();

    // Engine-free schema-version tripwire (#464): a database file can exist yet
    // carry a schema version this binary refuses to mutate ("Schema version
    // mismatch: expected N, found M"). Read the checkpointed header version
    // (no engine open, well under the 200 ms budget) and treat any present,
    // non-zero value other than CURRENT_SCHEMA_VERSION as an incompatibility so
    // `health` no longer reports "healthy" on a tracker that rejects every
    // write. A value of 0 (no user_version set) stays indeterminate.
    let schema_expected = CURRENT_SCHEMA_VERSION;
    let schema_user_version = if db_present {
        database_header_user_version(&db)
    } else {
        None
    };
    let schema_incompatible = matches!(
        schema_user_version,
        Some(found) if found != 0 && i64::from(found) != i64::from(schema_expected)
    );
    let schema_compatible = !schema_incompatible;

    // MERGE_* artifacts indicate a torn previous merge.
    let merge_artifacts_present = match fs::read_dir(&beads) {
        Ok(it) => it.flatten().any(|e| {
            let n = e.file_name();
            let s = n.to_string_lossy();
            s.starts_with("MERGE_") || s.contains(".bad_") || s.contains(".rej")
        }),
        Err(_) => false,
    };

    // Orphan locks: present-but-empty, owner unknown.
    let orphan_write_lock = beads.join(".write.lock").exists();
    let orphan_sync_lock = beads.join(".sync.lock").exists();

    let findings_present =
        !db_present || !jsonl_present || merge_artifacts_present || schema_incompatible;

    let (status, exit_code) = if findings_present {
        ("findings_present", DoctorExitCode::FindingsPresent.as_i32())
    } else {
        // Lock files alone are advisory only; keep status healthy but
        // tag the line below so agents can see them.
        ("healthy", DoctorExitCode::Healthy.as_i32())
    };

    let mut line = format!(
        "{status}  br={ver} doctor=1 db={db} jsonl={jsonl}",
        status = status,
        ver = env!("CARGO_PKG_VERSION"),
        db = if !db_present {
            "missing"
        } else if schema_incompatible {
            "schema_incompatible"
        } else {
            "ok"
        },
        jsonl = if jsonl_present { "ok" } else { "missing" },
    );
    if schema_incompatible && let Some(found) = schema_user_version {
        line.push_str(&format!(" schema={found}/{schema_expected}"));
    }
    if merge_artifacts_present {
        line.push_str(" merge_artifacts=present");
    }
    if orphan_write_lock {
        line.push_str(" write_lock=present");
    }
    if orphan_sync_lock {
        line.push_str(" sync_lock=present");
    }

    HealthOutput {
        schema_version: HEALTH_SCHEMA,
        status,
        exit_code,
        beads_dir_present,
        db_present,
        jsonl_present,
        merge_artifacts_present,
        orphan_write_lock,
        orphan_sync_lock,
        schema_user_version,
        schema_expected,
        schema_compatible,
        elapsed_ms: start.elapsed().as_millis(),
        line,
    }
}

fn emit_health(args: &DoctorHealthArgs, payload: &HealthOutput) {
    if args.json {
        if let Ok(json) = serde_json::to_string_pretty(payload) {
            println!("{json}");
        }
    } else {
        println!("{}", payload.line);
    }
}

// =============================================================================
// ls
// =============================================================================

/// One row of `br doctor ls`.
#[derive(Debug, Clone, Serialize)]
pub struct RunListRow {
    pub run_id: String,
    pub started_at: String,
    pub exit_code: Option<i32>,
    pub action_count: usize,
}

/// Top-level `runs_list` envelope.
#[derive(Debug, Clone, Serialize)]
pub struct RunsListEnvelope {
    pub schema_version: &'static str,
    pub runs_dir: String,
    pub count: usize,
    pub runs: Vec<RunListRow>,
}

/// Execute `br doctor ls`.
///
/// # Errors
///
/// Returns [`BeadsError`] for I/O faults reading `.doctor/runs/`.
pub fn execute_ls(args: &DoctorLsArgs, repo_root: &Path) -> Result<()> {
    let runs_dir = resolve_runs_root(repo_root);
    let mut rows = Vec::new();
    if runs_dir.is_dir() {
        for entry in fs::read_dir(&runs_dir).map_err(BeadsError::Io)? {
            let entry = entry.map_err(BeadsError::Io)?;
            let ft = entry.file_type().map_err(BeadsError::Io)?;
            if !ft.is_dir() {
                continue;
            }
            let run_id = entry.file_name().to_string_lossy().into_owned();
            // Skip top-level non-run housekeeping (e.g. symlinks named
            // `latest` end up under the parent of `runs_dir`, not inside).
            let actions = entry.path().join("actions.jsonl");
            let action_count = count_lines(&actions);
            let report = entry.path().join("report.json");
            let exit_code = read_exit_code_from_report(&report);
            let started_at = run_id.split("__").next().unwrap_or("").to_string();
            rows.push(RunListRow {
                run_id,
                started_at,
                exit_code,
                action_count,
            });
        }
    }
    rows.sort_by(|a, b| b.started_at.cmp(&a.started_at));

    if args.json {
        let envelope = RunsListEnvelope {
            schema_version: RUNS_LIST_SCHEMA,
            runs_dir: runs_dir.to_string_lossy().into_owned(),
            count: rows.len(),
            runs: rows,
        };
        if let Ok(json) = serde_json::to_string_pretty(&envelope) {
            println!("{json}");
        }
    } else {
        if rows.is_empty() {
            println!("no doctor runs in {}", runs_dir.display());
            return Ok(());
        }
        println!(
            "{:<32} {:<20} {:>8} {:>10}",
            "run_id", "started_at", "exit", "actions"
        );
        for row in &rows {
            println!(
                "{:<32} {:<20} {:>8} {:>10}",
                row.run_id,
                row.started_at,
                row.exit_code
                    .map_or_else(|| "-".to_string(), |c| c.to_string()),
                row.action_count
            );
        }
    }
    Ok(())
}

fn resolve_runs_root(repo_root: &Path) -> PathBuf {
    if let Some(over) = std::env::var_os(run_dir::ENV_RUNS_DIR) {
        PathBuf::from(over).join("runs")
    } else {
        repo_root.join(".doctor").join("runs")
    }
}

fn count_lines(path: &Path) -> usize {
    let Ok(f) = std::fs::File::open(path) else {
        return 0;
    };
    BufReader::new(f)
        .lines()
        .map_while(std::io::Result::ok)
        .count()
}

fn read_exit_code_from_report(path: &Path) -> Option<i32> {
    let bytes = fs::read(path).ok()?;
    if bytes.is_empty() {
        return None;
    }
    let v: serde_json::Value = serde_json::from_slice(&bytes).ok()?;
    v.get("exit_code")
        .and_then(serde_json::Value::as_i64)
        .and_then(|n| i32::try_from(n).ok())
}

// =============================================================================
// undo
// =============================================================================

/// JSONL line shape on disk in `.doctor/runs/<id>/actions.jsonl`. We
/// only need a subset of fields for replay.
#[derive(Debug, Deserialize, Clone)]
struct StoredActionRecord {
    path: String,
    op: String,
    before_hash: String,
    /// Backup path relative to this run's `backups/` directory. Older and
    /// first-write records omit it and use the workspace-relative `path`.
    #[serde(default)]
    backup_path: Option<String>,
    #[serde(default)]
    rename_to: Option<String>,
    /// Workspace-relative paths of the JSON snapshot files written by
    /// the corresponding DbExec call. Empty for non-DbExec ops.
    #[serde(default)]
    db_snapshots: Vec<String>,
    /// Optional `sha256:<hex>` digests of each `db_snapshots` body, in
    /// matching order. Older action records may omit this; if present,
    /// undo verifies every snapshot before parsing and replay.
    #[serde(default)]
    db_snapshot_sha256: Vec<String>,
    /// Comma-separated list of affected table names recorded by the
    /// DbExec forward path. The undo replay cross-checks this against
    /// the table names inside `db_snapshots` before touching the DB.
    #[serde(default)]
    affected_tables: Option<String>,
    /// SQL predicate (WHERE clause body) used by the DbExec forward
    /// path; `None` means "snapshot the whole table". The undo replay
    /// cross-checks this against every snapshot envelope predicate.
    #[serde(default)]
    affected_predicate: Option<String>,
}

/// One restore step.
#[derive(Debug, Clone, Serialize)]
pub struct UndoStep {
    pub path: String,
    pub op: String,
    pub status: String,
    pub backup_used: Option<String>,
}

/// Top-level envelope for `br doctor undo`.
#[derive(Debug, Clone, Serialize)]
pub struct UndoEnvelope {
    pub schema_version: &'static str,
    pub run_id: String,
    pub run_dir: String,
    pub undo_run_id: Option<String>,
    pub dry_run: bool,
    pub steps: Vec<UndoStep>,
    pub restored: usize,
    pub skipped: usize,
    pub failed: usize,
}

/// Execute `br doctor undo`.
///
/// Per-action contract:
/// 1. Look up the verbatim backup at `<run-dir>/backups/<rel-path>`.
/// 2. Verify the backup matches the action's `before_hash`.
/// 3. Restore the backup contents via [`chokepoint::mutate`] under a
///    fresh undo run-dir, so the restore itself is auditable.
/// 4. After all restored, mark the original run as undone in
///    `report.json`.
///
/// # Errors
///
/// Returns [`BeadsError`] if the run-id cannot be resolved or if the
/// `.doctor/runs/` tree is unreadable.
pub fn execute_undo(args: &DoctorUndoArgs, repo_root: &Path) -> Result<()> {
    let runs_root = resolve_runs_root(repo_root);
    let run_id = if args.run_id == "latest" {
        find_latest_run(&runs_root)?
            .ok_or_else(|| BeadsError::internal("doctor: no runs found in .doctor/runs/"))?
    } else {
        validate_run_id_arg(&args.run_id)?;
        args.run_id.clone()
    };
    let run_dir_path = runs_root.join(&run_id);
    if !run_dir_path.is_dir() {
        return Err(BeadsError::internal(format!(
            "doctor: run-id `{run_id}` not found at {}",
            run_dir_path.display()
        )));
    }
    let actions_path = run_dir_path.join("actions.jsonl");
    let (actions, parse_failures) = read_actions_reverse(&actions_path)?;
    let backups_dir = run_dir_path.join("backups");

    // Build a fresh "undo" run-dir so the restore writes are
    // themselves audited via mutate(). If we can't create one (e.g.,
    // dry-run on a read-only tree), fall back to a synthetic ctx that
    // refuses real writes.
    let mut steps = parse_failures;
    let mut restored = 0;
    let mut skipped = 0;
    let mut failed = steps.len();

    let undo_run = if args.dry_run {
        None
    } else {
        Some(run_dir::create_run_dir(repo_root)?)
    };

    if let Some(ref undo) = undo_run {
        let actions_file = OpenOptions::new()
            .create(true)
            .append(true)
            .open(&undo.actions_file)
            .map_err(BeadsError::Io)?;
        // Undo writes target whatever paths the original repair touched.
        // The forward `--repair` run extended write_scopes (e.g. to a
        // root `.gitignore` for the `doctor.gitignore_repair` fixer); the
        // undo must permit the same paths or `mutate()` will refuse the
        // restore with `outside write_scopes`. Paths from the action log
        // are still revalidated before being added here.
        let mut capabilities = MutateCapabilities::for_repo(repo_root);
        for record in &actions {
            if let Ok(target) = workspace_relative_path(repo_root, &record.path)
                && !capabilities
                    .write_scopes
                    .iter()
                    .any(|scope| target.starts_with(scope))
            {
                capabilities.write_scopes.push(target);
            }
            if let Some(rt) = &record.rename_to {
                let Ok(rt_path) = validate_rename_source_path(repo_root, &run_dir_path, rt) else {
                    continue;
                };
                if !capabilities
                    .write_scopes
                    .iter()
                    .any(|scope| rt_path.starts_with(scope))
                {
                    capabilities.write_scopes.push(rt_path);
                }
            }
        }
        let ctx = MutateContext {
            run_id: undo.run_id.clone(),
            run_dir: undo.root.clone(),
            capabilities,
            actions_file: Mutex::new(actions_file),
            fixer_id: format!("doctor_undo[{run_id}]"),
            repo_root: repo_root.to_path_buf(),
            dry_run: false,
            start_ns: now_ns(),
        };
        for record in actions {
            let step = restore_one(&ctx, repo_root, &run_dir_path, &backups_dir, &record);
            update_counts(&step, &mut restored, &mut skipped, &mut failed);
            steps.push(step);
        }
    } else {
        // Dry-run: report the plan but never call mutate().
        for record in actions {
            let step = plan_one(repo_root, &run_dir_path, &backups_dir, &record);
            update_counts(&step, &mut restored, &mut skipped, &mut failed);
            steps.push(step);
        }
    }

    if !args.dry_run && failed == 0 {
        let _ = mark_report_undone(&run_dir_path, &run_id);
    }

    let envelope = UndoEnvelope {
        schema_version: UNDO_SCHEMA,
        run_id: run_id.clone(),
        run_dir: run_dir_path.to_string_lossy().into_owned(),
        undo_run_id: undo_run.as_ref().map(|r| r.run_id.clone()),
        dry_run: args.dry_run,
        steps,
        restored,
        skipped,
        failed,
    };
    emit_undo_result(&envelope, args.json);
    Ok(())
}

fn emit_undo_result(envelope: &UndoEnvelope, json: bool) {
    if json {
        if let Ok(json) = serde_json::to_string_pretty(envelope) {
            println!("{json}");
        }
    } else {
        println!(
            "doctor undo {run_id}: restored={restored} skipped={skipped} failed={failed}",
            run_id = envelope.run_id,
            restored = envelope.restored,
            skipped = envelope.skipped,
            failed = envelope.failed,
        );
    }
}

fn update_counts(step: &UndoStep, restored: &mut usize, skipped: &mut usize, failed: &mut usize) {
    match step.status.as_str() {
        "restored" | "would_restore" => *restored += 1,
        "skipped_idempotent" | "skipped_no_op" => *skipped += 1,
        _ => *failed += 1,
    }
}

fn read_actions_reverse(path: &Path) -> Result<(Vec<StoredActionRecord>, Vec<UndoStep>)> {
    let bytes = match fs::read(path) {
        Ok(b) => b,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            return Ok((Vec::new(), Vec::new()));
        }
        Err(e) => return Err(BeadsError::Io(e)),
    };
    let mut actions = Vec::new();
    let mut parse_failures = Vec::new();
    for (line_number, line) in bytes.split(|b| *b == b'\n').enumerate() {
        if line.is_empty() {
            continue;
        }
        match serde_json::from_slice::<StoredActionRecord>(line) {
            Ok(rec) => actions.push(rec),
            Err(err) => parse_failures.push(UndoStep {
                path: format!("actions.jsonl:{}", line_number + 1),
                op: "parse_action".to_string(),
                status: format!("failed_parse_action:{err}"),
                backup_used: Some(path.to_string_lossy().into_owned()),
            }),
        }
    }
    actions.reverse();
    Ok((actions, parse_failures))
}

fn validate_run_id_arg(run_id: &str) -> Result<()> {
    let valid = !run_id.is_empty()
        && run_id
            .chars()
            .all(|ch| ch.is_ascii_alphanumeric() || ch == '_' || ch == '-');
    if valid {
        Ok(())
    } else {
        Err(BeadsError::validation(
            "run_id",
            "must be a single doctor run identifier; path separators and absolute paths are refused",
        ))
    }
}

fn canonicalize_existing_or_parent(path: &Path) -> std::io::Result<PathBuf> {
    if path.exists() {
        return path.canonicalize();
    }

    let mut tail = Vec::new();
    let mut cursor = path;
    loop {
        if let Some(name) = cursor.file_name() {
            tail.push(name);
        }
        match cursor.parent() {
            Some(parent) if !parent.as_os_str().is_empty() => {
                if parent.exists() {
                    let mut canonical = parent.canonicalize()?;
                    for segment in tail.iter().rev() {
                        canonical.push(segment);
                    }
                    return Ok(canonical);
                }
                cursor = parent;
            }
            _ => {
                let mut canonical = Path::new(".").canonicalize()?;
                for segment in tail.iter().rev() {
                    canonical.push(segment);
                }
                return Ok(canonical);
            }
        }
    }
}

fn validate_rename_source_path(
    repo_root: &Path,
    run_dir_path: &Path,
    raw: &str,
) -> std::result::Result<PathBuf, String> {
    let raw_path = PathBuf::from(raw);
    let candidate = if raw_path.is_absolute() || raw_path.starts_with(run_dir_path) {
        raw_path
    } else {
        repo_root.join(raw_path)
    };
    let canonical_candidate = canonicalize_existing_or_parent(&candidate)
        .map_err(|err| format!("failed_canonicalize_rename_to:{err}"))?;
    let canonical_run = run_dir_path
        .canonicalize()
        .map_err(|err| format!("failed_canonicalize_run_dir:{err}"))?;
    if canonical_candidate.starts_with(&canonical_run) {
        Ok(candidate)
    } else {
        Err(format!("outside_run_dir:{}", candidate.display()))
    }
}

fn live_bytes_match(target: &Path, expected: &[u8]) -> bool {
    fs::read(target).is_ok_and(|live| live == expected)
}

fn live_mode_matches(target: &Path, expected: Option<u32>) -> bool {
    expected.is_none_or(|mode| {
        fs::metadata(target).is_ok_and(|metadata| metadata_mode(&metadata) == mode)
    })
}

fn live_backup_matches(target: &Path, backup_bytes: &[u8], backup_mode: Option<u32>) -> bool {
    live_bytes_match(target, backup_bytes) && live_mode_matches(target, backup_mode)
}

fn restore_one(
    ctx: &MutateContext,
    repo_root: &Path,
    run_dir_path: &Path,
    backups_dir: &Path,
    record: &StoredActionRecord,
) -> UndoStep {
    let target = match validated_action_target_path(repo_root, record) {
        Ok(target) => target,
        Err(step) => return step,
    };
    let backup = match validated_action_backup_path(backups_dir, record) {
        Ok(backup) => backup,
        Err(step) => return step,
    };

    // For Rename ops we recorded an empty after-hash; the recovery is
    // to move the renamed file back from its destination.
    if record.op == "rename" {
        return restore_rename(ctx, repo_root, run_dir_path, record, target, &backup);
    }

    // For DbExec we replay the JSON snapshot back into the live DB
    // inside a single BEGIN IMMEDIATE / COMMIT. The chokepoint
    // recorded snapshot file paths under `db_snapshots`; each snapshot
    // is a `br.doctor.db_snapshot.v1` envelope with the table, the
    // predicate, the column list, and the row vector taken before the
    // forward DbExec ran.
    if record.op == "db_exec" {
        return restore_db_exec(repo_root, record, target);
    }

    let backup_bytes = match read_verified_backup(record, &backup) {
        Ok(bytes) => bytes,
        Err(step) => return step,
    };
    let backup_mode = fs::metadata(&backup).ok().map(|m| metadata_mode(&m));

    // Idempotence: bytes alone are not enough for chmod-only repairs.
    // The backup is verbatim metadata too; skip only once both the live
    // bytes and the live mode match the verified backup.
    let bytes_match = live_bytes_match(&target, &backup_bytes);
    if bytes_match {
        if live_mode_matches(&target, backup_mode) {
            return UndoStep {
                path: record.path.clone(),
                op: record.op.clone(),
                status: "skipped_idempotent".to_string(),
                backup_used: Some(backup.to_string_lossy().into_owned()),
            };
        }
        if record.op == "chmod"
            && let Some(mode) = backup_mode
        {
            return match chokepoint::mutate(ctx, &target, Op::Chmod { mode }) {
                Ok(_) => step_with_backup(record, "restored", &backup),
                Err(e) => step_with_backup(record, &format!("failed_mutate:{e}"), &backup),
            };
        }
    }

    match chokepoint::mutate(
        ctx,
        &target,
        Op::WriteFile {
            content: backup_bytes,
            mode: backup_mode,
        },
    ) {
        Ok(_) => step_with_backup(record, "restored", &backup),
        Err(e) => step_with_backup(record, &format!("failed_mutate:{e}"), &backup),
    }
}

/// Replay a `db_exec` action by restoring the rows captured in the
/// snapshot envelope back into the live DB. We expect each entry in
/// `record.db_snapshots` to be a workspace-relative path to a
/// `br.doctor.db_snapshot.v1` JSON file. The snapshot envelope carries
/// the table name, predicate, column list, and pre-mutation rows.
///
/// Replay shape (per snapshot):
/// 1. `BEGIN IMMEDIATE`.
/// 2. `DELETE FROM <table>` (whole table) or `DELETE ... WHERE
///    <predicate>` if the forward path used a predicate.
/// 3. `INSERT INTO <table>(<cols>) VALUES (?, ?, ...)` for every
///    snapshot row.
/// 4. `COMMIT`, or `ROLLBACK` on any error.
///
/// All snapshots inside ONE record are replayed inside ONE transaction
/// so the restore is atomic across tables.
fn restore_db_exec(repo_root: &Path, record: &StoredActionRecord, target: PathBuf) -> UndoStep {
    use crate::franken_sync::Connection;

    if record.db_snapshots.is_empty() {
        return UndoStep {
            path: record.path.clone(),
            op: record.op.clone(),
            status: "skipped_no_snapshots".to_string(),
            backup_used: None,
        };
    }

    if !target.is_file() {
        return UndoStep {
            path: record.path.clone(),
            op: record.op.clone(),
            status: "failed_db_missing".to_string(),
            backup_used: None,
        };
    }

    let envelopes = match read_db_snapshot_envelopes(repo_root, record) {
        Ok(envelopes) => envelopes,
        Err(step) => return step,
    };
    if let Err(e) = validate_db_snapshot_envelopes(record, &envelopes) {
        return UndoStep {
            path: record.path.clone(),
            op: record.op.clone(),
            status: e,
            backup_used: Some(record.db_snapshots.join(",")),
        };
    }

    // Replay every snapshot inside one BEGIN IMMEDIATE / COMMIT.
    let conn = match Connection::open(target.to_string_lossy().into_owned()) {
        Ok(c) => c,
        Err(e) => {
            return UndoStep {
                path: record.path.clone(),
                op: record.op.clone(),
                status: format!("failed_open_db:{e}"),
                backup_used: None,
            };
        }
    };
    if let Err(e) = conn.execute("BEGIN IMMEDIATE") {
        let _ = conn.close();
        return UndoStep {
            path: record.path.clone(),
            op: record.op.clone(),
            status: format!("failed_begin:{e}"),
            backup_used: None,
        };
    }

    let replay_result = replay_db_snapshot_envelopes(&conn, &envelopes);
    finish_db_replay(conn, record, replay_result)
}

fn read_db_snapshot_envelopes(
    repo_root: &Path,
    record: &StoredActionRecord,
) -> std::result::Result<Vec<DbSnapshotEnvelope>, UndoStep> {
    if !record.db_snapshot_sha256.is_empty()
        && record.db_snapshot_sha256.len() != record.db_snapshots.len()
    {
        return Err(UndoStep {
            path: record.path.clone(),
            op: record.op.clone(),
            status: "failed_snapshot_sha_count_mismatch".to_string(),
            backup_used: Some(record.db_snapshots.join(",")),
        });
    }

    let mut envelopes = Vec::with_capacity(record.db_snapshots.len());
    for (idx, rel_snap) in record.db_snapshots.iter().enumerate() {
        let snap_path = workspace_relative_path(repo_root, rel_snap).map_err(|e| UndoStep {
            path: record.path.clone(),
            op: record.op.clone(),
            status: format!("failed_invalid_snapshot_path:{e}"),
            backup_used: Some(rel_snap.clone()),
        })?;
        let body = fs::read(&snap_path).map_err(|e| UndoStep {
            path: record.path.clone(),
            op: record.op.clone(),
            status: format!("failed_read_snapshot:{e}"),
            backup_used: Some(snap_path.to_string_lossy().into_owned()),
        })?;
        if let Some(expected) = record.db_snapshot_sha256.get(idx) {
            let actual = sha256_bytes_hex_prefixed(&body);
            if &actual != expected {
                return Err(UndoStep {
                    path: record.path.clone(),
                    op: record.op.clone(),
                    status: format!("failed_snapshot_sha_mismatch:{rel_snap}"),
                    backup_used: Some(snap_path.to_string_lossy().into_owned()),
                });
            }
        }
        let env = serde_json::from_slice(&body).map_err(|e| UndoStep {
            path: record.path.clone(),
            op: record.op.clone(),
            status: format!("failed_parse_snapshot:{e}"),
            backup_used: Some(snap_path.to_string_lossy().into_owned()),
        })?;
        envelopes.push(env);
    }
    Ok(envelopes)
}

fn validate_db_snapshot_envelopes(
    record: &StoredActionRecord,
    envelopes: &[DbSnapshotEnvelope],
) -> std::result::Result<(), String> {
    for env in envelopes {
        if env.schema_version != "br.doctor.db_snapshot.v1" {
            return Err(format!(
                "failed_unknown_snapshot_schema:{}",
                env.schema_version
            ));
        }
        if !is_safe_sql_ident(&env.table) {
            return Err(format!("failed_invalid_table_ident:{}", env.table));
        }
        for col in &env.columns {
            if !is_safe_sql_ident(col) {
                return Err(format!("failed_invalid_column_ident:{col}"));
            }
        }
    }
    validate_db_snapshot_contract(record, envelopes)
}

fn replay_db_snapshot_envelopes(
    conn: &crate::franken_sync::Connection,
    envelopes: &[DbSnapshotEnvelope],
) -> std::result::Result<(), String> {
    for env in envelopes {
        delete_db_snapshot_region(conn, env)?;
        insert_db_snapshot_rows(conn, env)?;
    }
    Ok(())
}

fn delete_db_snapshot_region(
    conn: &crate::franken_sync::Connection,
    env: &DbSnapshotEnvelope,
) -> std::result::Result<(), String> {
    let predicate = env.predicate.as_deref().unwrap_or("").trim();
    let table_ident = quote_sql_ident(&env.table);
    let delete_sql = if predicate.is_empty() {
        format!("DELETE FROM {table_ident}")
    } else {
        format!("DELETE FROM {table_ident} WHERE {predicate}")
    };
    conn.execute(&delete_sql)
        .map(|_| ())
        .map_err(|e| format!("delete:{e}"))
}

fn insert_db_snapshot_rows(
    conn: &crate::franken_sync::Connection,
    env: &DbSnapshotEnvelope,
) -> std::result::Result<(), String> {
    use fsqlite_types::value::SqliteValue;

    if env.rows.is_empty() {
        return Ok(());
    }
    let cols_csv = env
        .columns
        .iter()
        .map(|c| quote_sql_ident(c))
        .collect::<Vec<_>>()
        .join(", ");
    let placeholders: Vec<&str> = vec!["?"; env.columns.len()];
    let insert_sql = format!(
        "INSERT INTO {}({cols_csv}) VALUES ({})",
        quote_sql_ident(&env.table),
        placeholders.join(", ")
    );
    for row in &env.rows {
        let mut bound: Vec<SqliteValue> = Vec::with_capacity(env.columns.len());
        for col in &env.columns {
            let val = row.get(col).cloned().unwrap_or(serde_json::Value::Null);
            bound.push(json_to_sqlite_value(&val).map_err(|e| format!("bind:{e}"))?);
        }
        conn.execute_with_params(&insert_sql, &bound)
            .map_err(|e| format!("insert:{e}"))?;
    }
    Ok(())
}

fn finish_db_replay(
    conn: crate::franken_sync::Connection,
    record: &StoredActionRecord,
    replay_result: std::result::Result<(), String>,
) -> UndoStep {
    match replay_result {
        Ok(()) => match conn.execute("COMMIT") {
            Ok(_) => {
                let _ = conn.close();
                UndoStep {
                    path: record.path.clone(),
                    op: record.op.clone(),
                    status: "restored".to_string(),
                    backup_used: Some(record.db_snapshots.join(",")),
                }
            }
            Err(e) => {
                let _ = conn.execute("ROLLBACK");
                let _ = conn.close();
                UndoStep {
                    path: record.path.clone(),
                    op: record.op.clone(),
                    status: format!("failed_commit:{e}"),
                    backup_used: Some(record.db_snapshots.join(",")),
                }
            }
        },
        Err(e) => {
            let _ = conn.execute("ROLLBACK");
            let _ = conn.close();
            UndoStep {
                path: record.path.clone(),
                op: record.op.clone(),
                status: format!("failed_replay:{e}"),
                backup_used: Some(record.db_snapshots.join(",")),
            }
        }
    }
}

fn validate_db_snapshot_contract(
    record: &StoredActionRecord,
    envelopes: &[DbSnapshotEnvelope],
) -> std::result::Result<(), String> {
    let expected_tables = parse_affected_tables(record.affected_tables.as_deref())?;
    let actual_tables: Vec<String> = envelopes.iter().map(|env| env.table.clone()).collect();
    if expected_tables != actual_tables {
        return Err(format!(
            "failed_snapshot_table_mismatch:expected={} actual={}",
            expected_tables.join(","),
            actual_tables.join(",")
        ));
    }

    let expected_predicate = normalize_predicate(record.affected_predicate.as_deref());
    for env in envelopes {
        let actual_predicate = normalize_predicate(env.predicate.as_deref());
        if actual_predicate != expected_predicate {
            return Err(format!(
                "failed_snapshot_predicate_mismatch:table={}",
                env.table
            ));
        }
    }
    Ok(())
}

fn parse_affected_tables(raw: Option<&str>) -> std::result::Result<Vec<String>, String> {
    let Some(raw) = raw else {
        return Err("failed_missing_affected_tables".to_string());
    };
    let tables: Vec<String> = raw
        .split(',')
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .map(ToString::to_string)
        .collect();
    if tables.is_empty() {
        return Err("failed_empty_affected_tables".to_string());
    }
    for table in &tables {
        if !is_safe_sql_ident(table) {
            return Err(format!("failed_invalid_record_table_ident:{table}"));
        }
    }
    Ok(tables)
}

fn normalize_predicate(raw: Option<&str>) -> Option<&str> {
    raw.map(str::trim).filter(|s| !s.is_empty())
}

/// In-memory shape of `br.doctor.db_snapshot.v1`. Mirrors the writer
/// in `mutate.rs::run_db_exec`.
#[derive(Debug, Clone, Deserialize)]
struct DbSnapshotEnvelope {
    schema_version: String,
    table: String,
    #[serde(default)]
    predicate: Option<String>,
    columns: Vec<String>,
    rows: Vec<serde_json::Map<String, serde_json::Value>>,
}

/// Defensive ASCII-alphanumeric+underscore identifier check; mirrors
/// the chokepoint's `validate_identifier`. Empty input is rejected so
/// no replay path can interpolate "" into SQL.
fn is_safe_sql_ident(s: &str) -> bool {
    !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
}

fn quote_sql_ident(s: &str) -> String {
    debug_assert!(is_safe_sql_ident(s));
    format!("\"{s}\"")
}

fn workspace_relative_path(repo_root: &Path, rel: &str) -> std::result::Result<PathBuf, String> {
    let path = Path::new(rel);
    if path.is_absolute() {
        return Err("absolute".to_string());
    }
    if path.components().any(|component| {
        matches!(
            component,
            std::path::Component::ParentDir
                | std::path::Component::RootDir
                | std::path::Component::Prefix(_)
        )
    }) {
        return Err("path_traversal".to_string());
    }
    Ok(repo_root.join(path))
}

fn validated_action_target_path(
    repo_root: &Path,
    record: &StoredActionRecord,
) -> std::result::Result<PathBuf, UndoStep> {
    workspace_relative_path(repo_root, &record.path).map_err(|error| UndoStep {
        path: record.path.clone(),
        op: record.op.clone(),
        status: format!("failed_invalid_action_path:{error}"),
        backup_used: None,
    })
}

fn action_backup_path(
    backups_dir: &Path,
    record: &StoredActionRecord,
) -> std::result::Result<PathBuf, String> {
    let relative = record.backup_path.as_deref().unwrap_or(&record.path);
    let path = Path::new(relative);
    if path.is_absolute() {
        return Err("absolute".to_string());
    }
    if path.components().any(|component| {
        matches!(
            component,
            std::path::Component::ParentDir
                | std::path::Component::RootDir
                | std::path::Component::Prefix(_)
        )
    }) {
        return Err("path_traversal".to_string());
    }
    Ok(backups_dir.join(path))
}

fn validated_action_backup_path(
    backups_dir: &Path,
    record: &StoredActionRecord,
) -> std::result::Result<PathBuf, UndoStep> {
    action_backup_path(backups_dir, record).map_err(|error| UndoStep {
        path: record.path.clone(),
        op: record.op.clone(),
        status: format!("failed_invalid_backup_path:{error}"),
        backup_used: None,
    })
}

/// Convert one JSON value back into an `SqliteValue` for re-binding.
/// Mirrors the inverse of `mutate.rs::sqlite_value_to_json`.
fn json_to_sqlite_value(
    val: &serde_json::Value,
) -> std::result::Result<fsqlite_types::value::SqliteValue, String> {
    use fsqlite_types::value::SqliteValue;
    match val {
        serde_json::Value::Null => Ok(SqliteValue::Null),
        serde_json::Value::Bool(b) => Ok(SqliteValue::Integer(i64::from(*b))),
        serde_json::Value::Number(n) => {
            if let Some(i) = n.as_i64() {
                Ok(SqliteValue::Integer(i))
            } else if let Some(f) = n.as_f64() {
                Ok(SqliteValue::Float(f))
            } else {
                Err(format!("non-finite number {n}"))
            }
        }
        serde_json::Value::String(s) => Ok(SqliteValue::Text(s.clone().into())),
        serde_json::Value::Object(map) => {
            // {"$blob_hex": "..."} encoding from the snapshot writer.
            if let Some(serde_json::Value::String(hex)) = map.get("$blob_hex") {
                let bytes = decode_hex(hex).map_err(|e| format!("blob hex decode: {e}"))?;
                return Ok(SqliteValue::Blob(bytes.into()));
            }
            Err(format!("unsupported object shape in snapshot: {map:?}"))
        }
        serde_json::Value::Array(_) => Err("unsupported array value in snapshot".to_string()),
    }
}

/// Hex decoder for the `$blob_hex` envelope. Lowercase / uppercase
/// both accepted; whitespace not tolerated.
fn decode_hex(s: &str) -> std::result::Result<Vec<u8>, String> {
    if !s.len().is_multiple_of(2) {
        return Err("odd hex length".to_string());
    }
    let mut out = Vec::with_capacity(s.len() / 2);
    let bytes = s.as_bytes();
    for pair in bytes.chunks(2) {
        let hi = hex_nibble(pair[0])?;
        let lo = hex_nibble(pair[1])?;
        out.push((hi << 4) | lo);
    }
    Ok(out)
}

fn hex_nibble(b: u8) -> std::result::Result<u8, String> {
    match b {
        b'0'..=b'9' => Ok(b - b'0'),
        b'a'..=b'f' => Ok(b - b'a' + 10),
        b'A'..=b'F' => Ok(b - b'A' + 10),
        other => Err(format!("non-hex byte 0x{other:02x}")),
    }
}

fn read_verified_backup(
    record: &StoredActionRecord,
    backup: &Path,
) -> std::result::Result<Vec<u8>, UndoStep> {
    if !backup.exists() {
        return Err(UndoStep {
            path: record.path.clone(),
            op: record.op.clone(),
            status: "failed_no_backup".to_string(),
            backup_used: None,
        });
    }
    let backup_bytes = fs::read(backup).map_err(|err| UndoStep {
        path: record.path.clone(),
        op: record.op.clone(),
        status: format!("failed_read_backup:{err}"),
        backup_used: Some(backup.to_string_lossy().into_owned()),
    })?;

    if !record.before_hash.is_empty() && !before_hash_matches(&record.before_hash, &backup_bytes) {
        return Err(UndoStep {
            path: record.path.clone(),
            op: record.op.clone(),
            status: "failed_hash_mismatch".to_string(),
            backup_used: Some(backup.to_string_lossy().into_owned()),
        });
    }

    Ok(backup_bytes)
}

fn step_with_backup(record: &StoredActionRecord, status: &str, backup: &Path) -> UndoStep {
    UndoStep {
        path: record.path.clone(),
        op: record.op.clone(),
        status: status.to_string(),
        backup_used: Some(backup.to_string_lossy().into_owned()),
    }
}

fn restore_rename(
    ctx: &MutateContext,
    repo_root: &Path,
    run_dir_path: &Path,
    record: &StoredActionRecord,
    target: PathBuf,
    backup: &Path,
) -> UndoStep {
    let Some(rt) = &record.rename_to else {
        return UndoStep {
            path: record.path.clone(),
            op: record.op.clone(),
            status: "skipped_no_op".to_string(),
            backup_used: None,
        };
    };

    let backup_bytes = match read_verified_backup(record, backup) {
        Ok(bytes) => bytes,
        Err(step) => return step,
    };

    let from = match validate_rename_source_path(repo_root, run_dir_path, rt) {
        Ok(path) => path,
        Err(err) => {
            return UndoStep {
                path: record.path.clone(),
                op: record.op.clone(),
                status: format!("failed_invalid_rename_to:{err}"),
                backup_used: Some(rt.clone()),
            };
        }
    };
    if !from.exists() {
        if let Ok(live) = fs::read(&target)
            && live == backup_bytes
        {
            return UndoStep {
                path: record.path.clone(),
                op: record.op.clone(),
                status: "skipped_idempotent".to_string(),
                backup_used: Some(backup.to_string_lossy().into_owned()),
            };
        }

        let mode = fs::metadata(backup)
            .ok()
            .map(|metadata| metadata_mode(&metadata));
        return match chokepoint::mutate(
            ctx,
            &target,
            Op::WriteFile {
                content: backup_bytes,
                mode,
            },
        ) {
            Ok(_) => step_with_backup(record, "restored", backup),
            Err(err) => step_with_backup(record, &format!("failed_mutate:{err}"), backup),
        };
    }

    let from_bytes = match fs::read(&from) {
        Ok(bytes) => bytes,
        Err(err) => {
            return UndoStep {
                path: record.path.clone(),
                op: record.op.clone(),
                status: format!("failed_read_rename_to:{err}"),
                backup_used: Some(rt.clone()),
            };
        }
    };
    if !record.before_hash.is_empty() && !before_hash_matches(&record.before_hash, &from_bytes) {
        return UndoStep {
            path: record.path.clone(),
            op: record.op.clone(),
            status: "failed_hash_mismatch_rename_to".to_string(),
            backup_used: Some(rt.clone()),
        };
    }

    match chokepoint::mutate(ctx, &from, Op::Rename { to: target }) {
        Ok(result) if result.ok => UndoStep {
            path: record.path.clone(),
            op: record.op.clone(),
            status: "restored".to_string(),
            backup_used: Some(rt.clone()),
        },
        Ok(result) => UndoStep {
            path: record.path.clone(),
            op: record.op.clone(),
            status: format!(
                "failed_mutate:{}",
                result.error.unwrap_or_else(|| "unknown".to_string())
            ),
            backup_used: Some(rt.clone()),
        },
        Err(e) => UndoStep {
            path: record.path.clone(),
            op: record.op.clone(),
            status: format!("failed_mutate:{e}"),
            backup_used: Some(rt.clone()),
        },
    }
}

fn plan_one(
    repo_root: &Path,
    run_dir_path: &Path,
    backups_dir: &Path,
    record: &StoredActionRecord,
) -> UndoStep {
    let target = match validated_action_target_path(repo_root, record) {
        Ok(target) => target,
        Err(step) => return step,
    };
    let backup = match validated_action_backup_path(backups_dir, record) {
        Ok(backup) => backup,
        Err(step) => return step,
    };
    if record.op == "rename"
        && let Some(rt) = &record.rename_to
    {
        let backup_bytes = match read_verified_backup(record, &backup) {
            Ok(bytes) => bytes,
            Err(step) => return step,
        };
        let from = match validate_rename_source_path(repo_root, run_dir_path, rt) {
            Ok(path) => path,
            Err(err) => {
                return UndoStep {
                    path: record.path.clone(),
                    op: record.op.clone(),
                    status: format!("failed_invalid_rename_to:{err}"),
                    backup_used: Some(rt.clone()),
                };
            }
        };
        if from.exists() {
            let from_bytes = match fs::read(&from) {
                Ok(bytes) => bytes,
                Err(err) => {
                    return UndoStep {
                        path: record.path.clone(),
                        op: record.op.clone(),
                        status: format!("failed_read_rename_to:{err}"),
                        backup_used: Some(rt.clone()),
                    };
                }
            };
            if !record.before_hash.is_empty()
                && !before_hash_matches(&record.before_hash, &from_bytes)
            {
                return UndoStep {
                    path: record.path.clone(),
                    op: record.op.clone(),
                    status: "failed_hash_mismatch_rename_to".to_string(),
                    backup_used: Some(rt.clone()),
                };
            }
            return UndoStep {
                path: record.path.clone(),
                op: record.op.clone(),
                status: "would_restore".to_string(),
                backup_used: Some(rt.clone()),
            };
        }
        if let Ok(live) = fs::read(&target)
            && live == backup_bytes
        {
            return UndoStep {
                path: record.path.clone(),
                op: record.op.clone(),
                status: "skipped_idempotent".to_string(),
                backup_used: Some(backup.to_string_lossy().into_owned()),
            };
        }
        return UndoStep {
            path: record.path.clone(),
            op: record.op.clone(),
            status: "would_restore".to_string(),
            backup_used: Some(backup.to_string_lossy().into_owned()),
        };
    }
    if record.op == "db_exec" {
        return plan_db_exec(repo_root, record);
    }
    let backup_bytes = match read_verified_backup(record, &backup) {
        Ok(bytes) => bytes,
        Err(step) => return step,
    };
    let backup_mode = fs::metadata(&backup).ok().map(|m| metadata_mode(&m));
    if live_backup_matches(&target, &backup_bytes, backup_mode) {
        return UndoStep {
            path: record.path.clone(),
            op: record.op.clone(),
            status: "skipped_idempotent".to_string(),
            backup_used: Some(backup.to_string_lossy().into_owned()),
        };
    }
    UndoStep {
        path: record.path.clone(),
        op: record.op.clone(),
        status: "would_restore".to_string(),
        backup_used: Some(backup.to_string_lossy().into_owned()),
    }
}

fn plan_db_exec(repo_root: &Path, record: &StoredActionRecord) -> UndoStep {
    if record.db_snapshots.is_empty() {
        return UndoStep {
            path: record.path.clone(),
            op: record.op.clone(),
            status: "skipped_no_snapshots".to_string(),
            backup_used: None,
        };
    }
    // Same length-binding the live undo path enforces, applied here too
    // so `--dry-run` reports the hash gap before a real replay does.
    if !record.db_snapshot_sha256.is_empty()
        && record.db_snapshot_sha256.len() != record.db_snapshots.len()
    {
        return UndoStep {
            path: record.path.clone(),
            op: record.op.clone(),
            status: "failed_snapshot_sha_count_mismatch".to_string(),
            backup_used: Some(record.db_snapshots.join(",")),
        };
    }
    for (idx, rel_snap) in record.db_snapshots.iter().enumerate() {
        let snap_path = match workspace_relative_path(repo_root, rel_snap) {
            Ok(p) => p,
            Err(e) => {
                return UndoStep {
                    path: record.path.clone(),
                    op: record.op.clone(),
                    status: format!("failed_invalid_snapshot_path:{e}"),
                    backup_used: Some(rel_snap.clone()),
                };
            }
        };
        if !snap_path.exists() {
            return UndoStep {
                path: record.path.clone(),
                op: record.op.clone(),
                status: "failed_no_snapshot".to_string(),
                backup_used: Some(snap_path.to_string_lossy().into_owned()),
            };
        }
        // If the action record carries a hash, verify the on-disk body
        // matches it. A mismatch here flags snapshot tampering — exactly
        // the round-2 left-open item — and we refuse rather than
        // pretend the dry-run would have worked.
        if let Some(expected) = record.db_snapshot_sha256.get(idx) {
            let bytes = match fs::read(&snap_path) {
                Ok(b) => b,
                Err(e) => {
                    return UndoStep {
                        path: record.path.clone(),
                        op: record.op.clone(),
                        status: format!("failed_read_snapshot:{e}"),
                        backup_used: Some(snap_path.to_string_lossy().into_owned()),
                    };
                }
            };
            if &sha256_bytes_hex_prefixed(&bytes) != expected {
                return UndoStep {
                    path: record.path.clone(),
                    op: record.op.clone(),
                    status: format!("failed_snapshot_sha_mismatch:{rel_snap}"),
                    backup_used: Some(snap_path.to_string_lossy().into_owned()),
                };
            }
        }
    }
    UndoStep {
        path: record.path.clone(),
        op: record.op.clone(),
        status: "would_restore".to_string(),
        backup_used: Some(record.db_snapshots.join(",")),
    }
}

fn before_hash_matches(expected: &str, bytes: &[u8]) -> bool {
    sha256_bytes_hex_prefixed(bytes) == expected
}

fn sha256_bytes_hex_prefixed(bytes: &[u8]) -> String {
    use sha2::{Digest, Sha256};
    let h = Sha256::digest(bytes);
    format!("sha256:{}", crate::util::hex_encode(&h))
}

fn find_latest_run(runs_root: &Path) -> Result<Option<String>> {
    if !runs_root.is_dir() {
        return Ok(None);
    }
    // The convenience symlink can be absent on Windows when the process
    // lacks symlink privileges, or stale after a run that could not update
    // it. Treat it as one validated candidate and still scan the run dirs.
    let mut best = latest_run_from_symlink(runs_root)?;
    for entry in fs::read_dir(runs_root).map_err(BeadsError::Io)? {
        let entry = entry.map_err(BeadsError::Io)?;
        if !entry.file_type().map_err(BeadsError::Io)?.is_dir() {
            continue;
        }
        let name = entry.file_name().to_string_lossy().into_owned();
        if validate_run_id_arg(&name).is_err() {
            continue;
        }
        match &best {
            Some(curr) => {
                if name.as_str() > curr.as_str() {
                    best = Some(name);
                }
            }
            None => best = Some(name),
        }
    }
    Ok(best)
}

fn latest_run_from_symlink(runs_root: &Path) -> Result<Option<String>> {
    let latest_link = runs_root.parent().unwrap_or(runs_root).join("latest");
    let link_target = match fs::read_link(&latest_link) {
        Ok(target) => target,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
        Err(e) if e.kind() == std::io::ErrorKind::InvalidInput => return Ok(None),
        Err(e) => return Err(BeadsError::Io(e)),
    };
    let base = latest_link.parent().unwrap_or(runs_root);
    let target = if link_target.is_absolute() {
        link_target
    } else {
        base.join(link_target)
    };
    // Canonicalize *before* the prefix check so we cannot be fooled by:
    //   - `..` traversal embedded in the symlink target (lexical
    //     `starts_with` accepts `<runs_root>/../../etc/...` because the
    //     string prefix is preserved even though the resolved path
    //     escapes `runs_root`);
    //   - symlinks anywhere in `runs_root`'s ancestor chain that make
    //     the canonical and lexical forms diverge.
    // If canonicalization fails (target missing, broken link, …) we
    // fall through to "no symlinked run available" rather than handing
    // back a path we can't reason about.
    let Ok(canonical_target) = target.canonicalize() else {
        return Ok(None);
    };
    let Ok(canonical_root) = runs_root.canonicalize() else {
        // If runs_root itself does not exist we can't have a valid
        // latest symlink under it.
        return Ok(None);
    };
    if !canonical_target.is_dir() || !canonical_target.starts_with(&canonical_root) {
        return Ok(None);
    }
    let Some(run_id) = canonical_target
        .file_name()
        .and_then(|name| name.to_str())
        .map(ToString::to_string)
    else {
        return Ok(None);
    };
    if validate_run_id_arg(&run_id).is_err() {
        return Ok(None);
    }
    Ok(Some(run_id))
}

fn mark_report_undone(run_dir_path: &Path, run_id: &str) -> Result<()> {
    let report = run_dir_path.join("report.json");
    let mut map: HashMap<String, serde_json::Value> = match fs::read(&report) {
        Ok(b) if !b.is_empty() => serde_json::from_slice(&b).unwrap_or_else(|_| HashMap::new()),
        _ => HashMap::new(),
    };
    map.insert("run_id".into(), serde_json::Value::String(run_id.into()));
    map.insert(
        "undone_at".into(),
        serde_json::Value::String(chrono::Utc::now().to_rfc3339()),
    );
    let bytes = serde_json::to_vec_pretty(&map).map_err(BeadsError::Json)?;

    // Atomic write: tmp + rename. A raw fs::write truncates the file
    // first, so a crash mid-write would leave report.json either empty
    // or torn — exactly the failure mode the chokepoint's execute_atomic
    // exists to prevent. Use the same tmp-then-rename pattern here so
    // undo bookkeeping is itself crash-safe.
    let parent = report.parent().unwrap_or_else(|| Path::new("."));
    let mut tmp = tempfile::NamedTempFile::new_in(parent).map_err(BeadsError::Io)?;
    tmp.write_all(&bytes).map_err(BeadsError::Io)?;
    tmp.as_file().sync_data().map_err(BeadsError::Io)?;
    tmp.persist(&report).map_err(|e| BeadsError::Io(e.error))?;
    fsync_report_dir(parent)?;
    Ok(())
}

/// Fsync a directory entry so a freshly-renamed file is durable across
/// power loss. Best-effort: filesystems that reject directory fsync
/// (some tmpfs variants) are tolerated by treating InvalidInput as
/// success, and Windows (no directory fsync, #450) skips the step.
fn fsync_report_dir(dir: &Path) -> Result<()> {
    crate::util::sync_directory_best_effort(dir).map_err(BeadsError::Io)
}

fn now_ns() -> u128 {
    use std::time::{SystemTime, UNIX_EPOCH};
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |d| d.as_nanos())
}

// =============================================================================
// explain (stub)
// =============================================================================

/// Narrow a capabilities document to the rows whose ids mention `filter`.
fn filter_capabilities(caps: &DoctorCapabilities, filter: &str) -> DoctorCapabilities {
    let needle = filter.to_ascii_lowercase();
    let matches = |value: &str| value.to_ascii_lowercase().contains(&needle);
    let mut filtered = caps.clone();
    filtered.fixers.retain(|fixer| {
        matches(&fixer.id)
            || fixer.addressed_findings.iter().any(|item| matches(item))
            || fixer.filter_ids.iter().any(|item| matches(item))
    });
    filtered.detectors.retain(|detector| matches(&detector.id));
    filtered
        .finding_id_map
        .retain(|entry| matches(entry.check_name) || matches(entry.finding_id));
    filtered
}

/// One remediation the doctor can apply for a finding.
#[derive(Debug, Clone, Serialize)]
struct ExplainFixer {
    id: String,
    subsystem: String,
    auto_fixable: bool,
    mutates: bool,
    dry_run_command: String,
    command: String,
}

/// `br.doctor.explain.v1` envelope.
#[derive(Debug, Clone, Serialize)]
struct ExplainEnvelope {
    schema_version: &'static str,
    finding_id: String,
    check_name: String,
    subsystem: Option<String>,
    severity_default: Option<String>,
    fast_path: Option<bool>,
    /// `no_workspace`, `not_observed`, or the check's current status.
    observed_status: String,
    observed_at: String,
    message: Option<String>,
    details: Option<serde_json::Value>,
    fixers: Vec<ExplainFixer>,
    next_commands: Vec<String>,
}

/// Finding ids and check names closest to an unknown query, for the error hint.
fn nearest_finding_ids(caps: &DoctorCapabilities, query: &str) -> Vec<String> {
    let needle = query.trim().to_ascii_lowercase();
    let tokens: Vec<&str> = needle
        .split(['-', '_', '.', ' '])
        .filter(|token| token.len() >= 3 && *token != "fm")
        .collect();
    let mut scored: Vec<(usize, &str)> = caps
        .finding_id_map
        .iter()
        .flat_map(|entry| [entry.finding_id, entry.check_name])
        .map(|candidate| {
            let lower = candidate.to_ascii_lowercase();
            let score = tokens.iter().filter(|token| lower.contains(*token)).count();
            (score, candidate)
        })
        .filter(|(score, _)| *score > 0)
        .collect();
    scored.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.cmp(b.1)));
    scored.dedup_by(|a, b| a.1 == b.1);
    scored
        .into_iter()
        .take(5)
        .map(|(_, id)| id.to_string())
        .collect()
}

/// Execute `br doctor explain <finding-id|check-name>` and `--list`.
///
/// The finding registry (`CHECK_NAME_TO_FINDING_ID`) resolves the query to a
/// check; the flat doctor checks are then run against the discovered
/// workspace so the envelope reports what the check sees right now, and the
/// fixer registry names the `--repair` invocation that addresses it.
///
/// # Errors
///
/// Unknown ids are a validation error (exit 4) whose message lists the
/// nearest known ids; workspace resolution and check failures propagate.
pub fn execute_explain(args: &DoctorExplainArgs, cli: &config::CliOverrides) -> Result<()> {
    let caps = DoctorCapabilities::build();

    if args.list {
        return print_explain_list(&caps, args.json);
    }

    let query = args
        .finding_id
        .as_deref()
        .map(str::trim)
        .unwrap_or_default();
    let Some(entry) = caps
        .finding_id_map
        .iter()
        .find(|entry| entry.finding_id == query || entry.check_name == query)
    else {
        let nearest = nearest_finding_ids(&caps, query);
        let hint = if nearest.is_empty() {
            "run `br doctor explain --list` to see every finding id".to_string()
        } else {
            format!("nearest: {}", nearest.join(", "))
        };
        return Err(BeadsError::validation(
            "finding_id",
            format!("unknown finding id or check name '{query}'; {hint}"),
        ));
    };
    let finding_id = entry.finding_id.to_string();
    let check_name = entry.check_name.to_string();

    let detector = caps
        .detectors
        .iter()
        .find(|detector| detector.id == check_name);
    let fixers = explain_fixers(&caps, &finding_id, &check_name);

    let observation =
        crate::cli::commands::doctor::observe_check_for_explain(cli, &check_name, &finding_id)?;
    let (observed_status, message, details) = match observation {
        crate::cli::commands::doctor::ExplainObservation::NoWorkspace => (
            "no_workspace".to_string(),
            Some("No .beads workspace found; run `br init` or `cd` into one".to_string()),
            None,
        ),
        crate::cli::commands::doctor::ExplainObservation::NotObserved => (
            "not_observed".to_string(),
            Some(format!(
                "The flat doctor run did not emit `{check_name}` for this workspace (the check may only run in --repair or in a mode this workspace does not trigger)"
            )),
            None,
        ),
        crate::cli::commands::doctor::ExplainObservation::Check(check) => (
            check
                .get("status")
                .and_then(serde_json::Value::as_str)
                .unwrap_or("unknown")
                .to_string(),
            check
                .get("message")
                .and_then(serde_json::Value::as_str)
                .map(ToString::to_string),
            check.get("details").cloned(),
        ),
    };

    let mut next_commands = vec!["br doctor --json".to_string()];
    next_commands.extend(fixers.iter().map(|fixer| fixer.dry_run_command.clone()));
    next_commands.push(format!(
        "br doctor capabilities --format json --command {check_name}"
    ));

    let envelope = ExplainEnvelope {
        schema_version: EXPLAIN_SCHEMA,
        finding_id,
        check_name,
        subsystem: detector.map(|d| d.subsystem.clone()),
        severity_default: detector.map(|d| d.severity_default.clone()),
        fast_path: detector.map(|d| d.fast_path),
        observed_status,
        observed_at: chrono::Utc::now().to_rfc3339(),
        message,
        details,
        fixers,
        next_commands,
    };

    if args.json {
        let json = serde_json::to_string_pretty(&envelope).map_err(BeadsError::Json)?;
        println!("{json}");
    } else {
        print_explain_text(&envelope);
    }
    Ok(())
}

/// `br doctor explain --list`: every finding id with its check name.
fn print_explain_list(caps: &DoctorCapabilities, json: bool) -> Result<()> {
    #[derive(Serialize)]
    struct ListEnvelope<'a> {
        schema_version: &'static str,
        findings:
            &'a [crate::cli::commands::doctor_subsystems::capabilities_doctor::FindingIdEntry],
    }
    if json {
        let json = serde_json::to_string_pretty(&ListEnvelope {
            schema_version: EXPLAIN_SCHEMA,
            findings: &caps.finding_id_map,
        })
        .map_err(BeadsError::Json)?;
        println!("{json}");
    } else {
        for entry in &caps.finding_id_map {
            println!("{:<56} {}", entry.finding_id, entry.check_name);
        }
    }
    Ok(())
}

/// The fixers that can act on a finding, with the exact repair commands.
fn explain_fixers(
    caps: &DoctorCapabilities,
    finding_id: &str,
    check_name: &str,
) -> Vec<ExplainFixer> {
    caps.fixers
        .iter()
        .filter(|fixer| {
            fixer.filter_ids.iter().any(|id| id == finding_id)
                || fixer
                    .addressed_findings
                    .iter()
                    .any(|name| name == check_name)
        })
        .map(|fixer| {
            let only = fixer
                .filter_ids
                .first()
                .map_or_else(|| fixer.id.clone(), ToString::to_string);
            ExplainFixer {
                id: fixer.id.clone(),
                subsystem: fixer.subsystem.clone(),
                auto_fixable: fixer.auto_fixable,
                mutates: fixer.mutates,
                dry_run_command: format!("br doctor --repair --dry-run --only {only}"),
                command: format!("br doctor --repair --only {only}"),
            }
        })
        .collect()
}

/// Human rendering of the explain envelope.
fn print_explain_text(envelope: &ExplainEnvelope) {
    println!("{} ({})", envelope.finding_id, envelope.check_name);
    if let Some(subsystem) = &envelope.subsystem {
        println!(
            "  subsystem : {subsystem}  severity: {}  fast-path: {}",
            envelope.severity_default.as_deref().unwrap_or("-"),
            envelope
                .fast_path
                .map_or("-", |fast| if fast { "yes" } else { "no" })
        );
    }
    println!("  observed  : {}", envelope.observed_status);
    if let Some(message) = &envelope.message {
        println!("  message   : {message}");
    }
    if let Some(details) = &envelope.details {
        println!("  details   : {details}");
    }
    if envelope.fixers.is_empty() {
        println!("  fixers    : none (advisory finding; resolve by hand or rerun after a repair)");
    } else {
        for fixer in &envelope.fixers {
            println!(
                "  fixer     : {} (auto: {}, mutates: {}) -> {}",
                fixer.id, fixer.auto_fixable, fixer.mutates, fixer.dry_run_command
            );
        }
    }
    for command in &envelope.next_commands {
        println!("  next      : {command}");
    }
}

// =============================================================================
// --robot-triage
// =============================================================================

/// Lightweight finding shape for the triage envelope.
#[derive(Debug, Clone, Serialize)]
pub struct TriageFinding {
    pub id: String,
    pub severity: String,
    pub message: String,
}

/// Top-level envelope for `--robot-triage`.
#[derive(Debug, Clone, Serialize)]
pub struct TriageEnvelope {
    pub schema_version: &'static str,
    pub summary: String,
    pub findings: Vec<TriageFinding>,
    pub actions_planned: Vec<serde_json::Value>,
    pub recommended_command: String,
    pub capabilities_url: String,
    pub robot_docs_command: String,
    pub quick_ref: TriageQuickRef,
}

#[derive(Debug, Clone, Serialize)]
pub struct TriageQuickRef {
    pub healthy: usize,
    pub warn: usize,
    pub error: usize,
}

/// Build a triage envelope from raw counts and a list of compact
/// findings. The doctor driver passes the values it already computed
/// for the flat run.
#[must_use]
pub fn build_triage_envelope(
    healthy: usize,
    warn: usize,
    error: usize,
    findings: Vec<TriageFinding>,
) -> TriageEnvelope {
    let any_findings = warn > 0 || error > 0;
    let summary = if !any_findings {
        "workspace healthy".to_string()
    } else {
        format!("{error} error(s) and {warn} warning(s) detected")
    };
    let recommended_command = if error > 0 {
        "br doctor --repair --dry-run".to_string()
    } else if warn > 0 {
        "br doctor".to_string()
    } else {
        "br doctor health".to_string()
    };
    TriageEnvelope {
        schema_version: TRIAGE_SCHEMA,
        summary,
        findings,
        actions_planned: Vec::new(),
        recommended_command,
        capabilities_url: "br doctor capabilities --format json".to_string(),
        robot_docs_command: "br doctor robot-docs".to_string(),
        quick_ref: TriageQuickRef {
            healthy,
            warn,
            error,
        },
    }
}

/// Emit the triage envelope to stdout.
pub fn emit_robot_triage(envelope: &TriageEnvelope) {
    if let Ok(json) = serde_json::to_string_pretty(envelope) {
        println!("{json}");
    }
}

// =============================================================================
// tests
// =============================================================================

#[cfg(all(test, unix))]
mod tests {
    use super::*;
    use std::time::Instant;

    fn unique_temp_root(label: &str) -> tempfile::TempDir {
        let prefix = format!("br-doctor-surface-{label}-");
        tempfile::Builder::new()
            .prefix(prefix.as_str())
            .tempdir()
            .expect("tempdir")
    }

    #[test]
    fn test_doctor_capabilities_json_emits_v1_envelope() {
        let caps = DoctorCapabilities::build();
        let env = CapabilitiesEnvelope {
            schema_version: CAPABILITIES_SCHEMA,
            inner: &caps,
        };
        let json = serde_json::to_string(&env).expect("json");
        let v: serde_json::Value = serde_json::from_str(&json).expect("parse");
        assert_eq!(v["schema_version"], "br.doctor.capabilities.v1");
        assert!(v["exit_codes"].is_array());
        assert!(v["write_scopes"].is_array());
        assert!(v["env_vars"].is_array());
        // Inner contract still intact.
        assert_eq!(v["contract_version"], "1");
    }

    #[test]
    fn test_doctor_robot_docs_includes_exit_codes() {
        let body = robot_handbook_body();
        // Spot-check the most critical exit codes are documented.
        for code in ["0", "1", "2", "3", "4", "5", "73"] {
            assert!(
                body.contains(&format!("`{code}`")),
                "robot-docs missing exit code {code}"
            );
        }
        assert!(body.contains("br doctor undo"));
        assert!(body.contains("br doctor capabilities"));
        assert!(body.contains("br doctor health"));
    }

    #[test]
    fn test_doctor_health_under_200ms_on_healthy() {
        let tmp = unique_temp_root("health-fast");
        let beads = tmp.path().join(".beads");
        fs::create_dir_all(&beads).unwrap();
        fs::write(beads.join("beads.db"), b"sqlite header...").unwrap();
        fs::write(beads.join("issues.jsonl"), b"{}\n").unwrap();
        let args = DoctorHealthArgs { json: false };
        let start = Instant::now();
        // Use the inner pure helper to avoid println noise in test.
        let beads_present = beads.is_dir();
        let elapsed_pre = start.elapsed();
        let _ = beads_present;
        // The full execute_health writes to stdout — call it and check
        // wall-clock from start.
        let started = Instant::now();
        let code = execute_health(&args, tmp.path()).expect("health");
        let dur = started.elapsed();
        assert_eq!(code, 0, "should be healthy");
        assert!(
            dur.as_millis() < 200,
            "health must finish in <200ms; took {}ms",
            dur.as_millis()
        );
        let _ = elapsed_pre;
    }

    #[test]
    fn doctor_health_output_uses_resolved_repo_root_state() {
        let tmp = unique_temp_root("health-json-root");
        let repo = tmp.path().join("repo");
        let unrelated = tmp.path().join("unrelated");
        let beads = repo.join(".beads");
        fs::create_dir_all(&beads).unwrap();
        fs::create_dir_all(unrelated.join(".beads")).unwrap();
        fs::write(beads.join("beads.db"), b"sqlite header...").unwrap();
        fs::write(beads.join("issues.jsonl"), b"{}\n").unwrap();
        fs::write(beads.join("MERGE_HEAD"), b"pending merge").unwrap();
        fs::write(beads.join(".write.lock"), b"").unwrap();

        let output = build_health_output(&repo, Instant::now());

        assert_eq!(output.status, "findings_present");
        assert!(output.beads_dir_present);
        assert!(output.db_present);
        assert!(output.jsonl_present);
        assert!(output.merge_artifacts_present);
        assert!(output.orphan_write_lock);
        assert!(!output.orphan_sync_lock);
        assert!(output.line.contains("merge_artifacts=present"));
        assert!(output.line.contains("write_lock=present"));
    }

    #[test]
    fn doctor_health_flags_schema_incompatible_database() {
        // #464: a database file that exists but carries a schema version this
        // binary refuses to mutate ("Schema version mismatch: expected N,
        // found M") must not read as "healthy" — agents gate on this tripwire.
        let tmp = unique_temp_root("health-schema-stale");
        let repo = tmp.path();
        let beads = repo.join(".beads");
        fs::create_dir_all(&beads).unwrap();
        let db_path = beads.join("beads.db");
        {
            let storage = crate::storage::SqliteStorage::open(&db_path).unwrap();
            storage.execute_raw("PRAGMA user_version = 15").unwrap();
        }
        fs::write(beads.join("issues.jsonl"), b"").unwrap();

        let output = build_health_output(repo, Instant::now());

        assert_eq!(
            output.schema_user_version,
            Some(15),
            "checkpointed header schema version must be read"
        );
        assert_eq!(output.schema_expected, CURRENT_SCHEMA_VERSION);
        assert!(
            !output.schema_compatible,
            "schema 15 is incompatible with {CURRENT_SCHEMA_VERSION}"
        );
        assert_eq!(output.status, "findings_present");
        assert_ne!(
            output.exit_code, 0,
            "must not exit healthy on a stale schema"
        );
        assert!(output.db_present, "the database file is present");
        assert!(
            output.line.contains("db=schema_incompatible"),
            "line: {}",
            output.line
        );
        assert!(
            output
                .line
                .contains(&format!("schema=15/{CURRENT_SCHEMA_VERSION}")),
            "line: {}",
            output.line
        );
    }

    #[test]
    fn doctor_health_accepts_current_schema_database() {
        // Guard against a false positive: a genuine current-schema database
        // must still read as healthy (the header probe returns the expected
        // version, not a spurious mismatch).
        let tmp = unique_temp_root("health-schema-ok");
        let repo = tmp.path();
        let beads = repo.join(".beads");
        fs::create_dir_all(&beads).unwrap();
        let db_path = beads.join("beads.db");
        {
            // A fresh database is created at CURRENT_SCHEMA_VERSION.
            let _storage = crate::storage::SqliteStorage::open(&db_path).unwrap();
        }
        fs::write(beads.join("issues.jsonl"), b"").unwrap();

        let output = build_health_output(repo, Instant::now());

        assert_eq!(
            output.schema_user_version,
            u32::try_from(CURRENT_SCHEMA_VERSION).ok(),
            "fresh database must report the current schema version"
        );
        assert!(output.schema_compatible);
        assert_eq!(output.status, "healthy");
        assert!(output.line.contains("db=ok"), "line: {}", output.line);
        assert!(
            !output.line.contains("schema="),
            "no schema token when compatible: {}",
            output.line
        );
    }

    #[test]
    fn test_doctor_ls_returns_empty_when_no_runs() {
        let tmp = unique_temp_root("ls-empty");
        let args = DoctorLsArgs { json: true };
        // No .doctor/runs/ exists yet — ls must succeed and report 0.
        execute_ls(&args, tmp.path()).expect("ls");
        // Now create the runs dir empty.
        fs::create_dir_all(tmp.path().join(".doctor/runs")).unwrap();
        execute_ls(&args, tmp.path()).expect("ls (existing dir, empty)");
    }

    #[test]
    fn db_snapshot_contract_rejects_tampered_table_metadata() {
        let record = StoredActionRecord {
            path: ".beads/beads.db".to_string(),
            op: "db_exec".to_string(),
            before_hash: "sha256:test".to_string(),
            backup_path: None,
            rename_to: None,
            db_snapshots: vec![".doctor/runs/r/backups/db/cache.json".to_string()],
            db_snapshot_sha256: Vec::new(),
            affected_tables: Some("blocked_issues_cache".to_string()),
            affected_predicate: None,
        };
        let envelopes = vec![DbSnapshotEnvelope {
            schema_version: "br.doctor.db_snapshot.v1".to_string(),
            table: "other_cache".to_string(),
            predicate: None,
            columns: vec!["issue_id".to_string()],
            rows: Vec::new(),
        }];

        let err = validate_db_snapshot_contract(&record, &envelopes).unwrap_err();

        assert!(err.starts_with("failed_snapshot_table_mismatch"));
    }

    #[test]
    fn db_snapshot_contract_rejects_tampered_predicate_metadata() {
        let record = StoredActionRecord {
            path: ".beads/beads.db".to_string(),
            op: "db_exec".to_string(),
            before_hash: "sha256:test".to_string(),
            backup_path: None,
            rename_to: None,
            db_snapshots: vec![".doctor/runs/r/backups/db/cache.json".to_string()],
            db_snapshot_sha256: Vec::new(),
            affected_tables: Some("blocked_issues_cache".to_string()),
            affected_predicate: Some("issue_id = 'bd-1'".to_string()),
        };
        let envelopes = vec![DbSnapshotEnvelope {
            schema_version: "br.doctor.db_snapshot.v1".to_string(),
            table: "blocked_issues_cache".to_string(),
            predicate: Some("issue_id = 'bd-2'".to_string()),
            columns: vec!["issue_id".to_string()],
            rows: Vec::new(),
        }];

        let err = validate_db_snapshot_contract(&record, &envelopes).unwrap_err();

        assert_eq!(
            err,
            "failed_snapshot_predicate_mismatch:table=blocked_issues_cache"
        );
    }

    #[test]
    fn workspace_relative_snapshot_paths_cannot_escape_repo() {
        let tmp = unique_temp_root("snapshot-paths");

        assert!(workspace_relative_path(tmp.path(), ".doctor/runs/r/s.json").is_ok());
        assert!(workspace_relative_path(tmp.path(), "../outside.json").is_err());
        assert!(workspace_relative_path(tmp.path(), "/tmp/outside.json").is_err());
    }

    #[test]
    fn versioned_backup_paths_cannot_escape_backups_dir() {
        let tmp = unique_temp_root("versioned-backup-paths");
        let backups = tmp.path().join("backups");
        let mut record = StoredActionRecord {
            path: ".beads/beads.db".to_string(),
            op: "legacy_op".to_string(),
            before_hash: "sha256:test".to_string(),
            backup_path: Some(".versions/1/.beads/beads.db".to_string()),
            rename_to: None,
            db_snapshots: Vec::new(),
            db_snapshot_sha256: Vec::new(),
            affected_tables: None,
            affected_predicate: None,
        };

        assert_eq!(
            action_backup_path(&backups, &record).unwrap(),
            backups.join(".versions/1/.beads/beads.db")
        );
        record.backup_path = Some("../outside.db".to_string());
        assert_eq!(
            action_backup_path(&backups, &record).unwrap_err(),
            "path_traversal"
        );
    }

    #[test]
    fn doctor_undo_run_ids_are_identifiers_not_paths() {
        assert!(validate_run_id_arg("20260101T000000Z__abc123").is_ok());

        for bad in ["", "../escape", "/tmp/escape", "runs/foo", "foo.bar"] {
            let err = validate_run_id_arg(bad).expect_err("path-shaped run id must be refused");
            assert!(
                err.to_string().contains("run_id"),
                "error should identify run_id, got {err}"
            );
        }
    }

    #[test]
    fn doctor_undo_rejects_non_workspace_action_paths() {
        let tmp = unique_temp_root("invalid-action-path");
        let run_dir = tmp.path().join(".doctor/runs/r");
        let backups = run_dir.join("backups");
        let record = StoredActionRecord {
            path: "../outside.db".to_string(),
            op: "db_exec".to_string(),
            before_hash: "sha256:test".to_string(),
            backup_path: None,
            rename_to: None,
            db_snapshots: vec![".doctor/runs/r/backups/db/cache.json".to_string()],
            db_snapshot_sha256: Vec::new(),
            affected_tables: Some("blocked_issues_cache".to_string()),
            affected_predicate: None,
        };

        let step = plan_one(tmp.path(), &run_dir, &backups, &record);

        assert_eq!(step.status, "failed_invalid_action_path:path_traversal");
    }

    #[test]
    fn doctor_undo_dry_run_reports_tampered_file_backup() {
        let tmp = unique_temp_root("plan-file-backup-tamper");
        let repo = tmp.path();
        let run_dir = repo.join(".doctor/runs/r");
        let backups = run_dir.join("backups");
        let live = repo.join(".beads/foo.txt");
        let backup = backups.join(".beads/foo.txt");
        fs::create_dir_all(live.parent().unwrap()).unwrap();
        fs::create_dir_all(backup.parent().unwrap()).unwrap();
        fs::write(&live, b"updated").unwrap();
        fs::write(&backup, b"tampered").unwrap();
        let record = StoredActionRecord {
            path: ".beads/foo.txt".to_string(),
            op: "write_file".to_string(),
            before_hash: sha256_bytes_hex_prefixed(b"original"),
            backup_path: None,
            rename_to: None,
            db_snapshots: Vec::new(),
            db_snapshot_sha256: Vec::new(),
            affected_tables: None,
            affected_predicate: None,
        };

        let step = plan_one(repo, &run_dir, &backups, &record);

        assert_eq!(step.status, "failed_hash_mismatch");
    }

    #[test]
    fn db_snapshot_reader_rejects_snapshot_sha_mismatch() {
        let tmp = unique_temp_root("snapshot-sha-mismatch");
        let rel = ".doctor/runs/r/backups/db/cache.json";
        let snap = tmp.path().join(rel);
        fs::create_dir_all(snap.parent().unwrap()).unwrap();
        fs::write(
            &snap,
            br#"{"schema_version":"br.doctor.db_snapshot.v1","table":"blocked_issues_cache","predicate":null,"columns":[],"rows":[]}"#,
        )
        .unwrap();
        let record = StoredActionRecord {
            path: ".beads/beads.db".to_string(),
            op: "db_exec".to_string(),
            before_hash: "sha256:test".to_string(),
            backup_path: None,
            rename_to: None,
            db_snapshots: vec![rel.to_string()],
            db_snapshot_sha256: vec!["sha256:not-the-snapshot".to_string()],
            affected_tables: Some("blocked_issues_cache".to_string()),
            affected_predicate: None,
        };

        let step = read_db_snapshot_envelopes(tmp.path(), &record).unwrap_err();

        assert!(step.status.starts_with("failed_snapshot_sha_mismatch:"));
    }

    #[test]
    fn mark_report_undone_preserves_report_fields() {
        let tmp = unique_temp_root("mark-report-undone");
        let run_dir = tmp.path().join(".doctor/runs/run-a");
        fs::create_dir_all(&run_dir).unwrap();
        fs::write(
            run_dir.join("report.json"),
            br#"{"run_id":"old","kept":true}"#,
        )
        .unwrap();

        mark_report_undone(&run_dir, "run-a").expect("mark undone");

        let report = fs::read_to_string(run_dir.join("report.json")).unwrap();
        let value: serde_json::Value = serde_json::from_str(&report).unwrap();
        assert_eq!(value["run_id"], "run-a");
        assert_eq!(value["kept"], true);
        assert!(value["undone_at"].as_str().is_some_and(|s| !s.is_empty()));
    }

    #[test]
    fn test_doctor_undo_restores_from_backup() {
        let tmp = unique_temp_root("undo");
        let repo = tmp.path();
        // Set up a workspace with a tracked file.
        let beads = repo.join(".beads");
        fs::create_dir_all(&beads).unwrap();
        let target = beads.join("foo.txt");
        fs::write(&target, b"original").unwrap();

        // Create an initial doctor run-dir and write through the
        // chokepoint.
        let initial_run = run_dir::create_run_dir(repo).expect("create run");
        let actions_file = OpenOptions::new()
            .create(true)
            .append(true)
            .open(&initial_run.actions_file)
            .unwrap();
        let ctx = MutateContext {
            run_id: initial_run.run_id.clone(),
            run_dir: initial_run.root.clone(),
            capabilities: MutateCapabilities::for_repo(repo),
            actions_file: Mutex::new(actions_file),
            fixer_id: "test".into(),
            repo_root: repo.to_path_buf(),
            dry_run: false,
            start_ns: now_ns(),
        };
        chokepoint::mutate(
            &ctx,
            &target,
            Op::WriteFile {
                content: b"updated".to_vec(),
                mode: Some(0o644),
            },
        )
        .expect("mutate");
        // After the write, the live file is "updated".
        assert_eq!(fs::read(&target).unwrap(), b"updated");

        // Now run undo.
        let args = DoctorUndoArgs {
            run_id: initial_run.run_id.clone(),
            dry_run: false,
            json: true,
        };
        execute_undo(&args, repo).expect("undo");
        // The original bytes are back.
        assert_eq!(fs::read(&target).unwrap(), b"original");

        // Idempotence: running undo again is a no-op.
        execute_undo(&args, repo).expect("undo idempotent");
        assert_eq!(fs::read(&target).unwrap(), b"original");
    }

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

        let tmp = unique_temp_root("undo-chmod-mode");
        let repo = tmp.path();
        let beads = repo.join(".beads");
        fs::create_dir_all(&beads).unwrap();
        let target = beads.join("issues.jsonl");
        fs::write(&target, b"{}\n").unwrap();
        fs::set_permissions(&target, fs::Permissions::from_mode(0o666)).unwrap();

        let initial_run = run_dir::create_run_dir(repo).expect("create run");
        let actions_file = OpenOptions::new()
            .create(true)
            .append(true)
            .open(&initial_run.actions_file)
            .unwrap();
        let ctx = MutateContext {
            run_id: initial_run.run_id.clone(),
            run_dir: initial_run.root.clone(),
            capabilities: MutateCapabilities::for_repo(repo),
            actions_file: Mutex::new(actions_file),
            fixer_id: "test".into(),
            repo_root: repo.to_path_buf(),
            dry_run: false,
            start_ns: now_ns(),
        };

        chokepoint::mutate(&ctx, &target, Op::Chmod { mode: 0o664 }).expect("chmod");
        assert_eq!(
            fs::metadata(&target).unwrap().permissions().mode() & 0o777,
            0o664
        );
        assert_eq!(fs::read(&target).unwrap(), b"{}\n");

        let args = DoctorUndoArgs {
            run_id: initial_run.run_id.clone(),
            dry_run: false,
            json: true,
        };
        execute_undo(&args, repo).expect("undo chmod");

        assert_eq!(fs::read(&target).unwrap(), b"{}\n");
        assert_eq!(
            fs::metadata(&target).unwrap().permissions().mode() & 0o777,
            0o666
        );
    }

    #[test]
    fn test_doctor_undo_failure_does_not_mark_original_run_undone() {
        let tmp = unique_temp_root("undo-failure");
        let repo = tmp.path();
        let beads = repo.join(".beads");
        fs::create_dir_all(&beads).unwrap();
        fs::write(beads.join("foo.txt"), b"updated").unwrap();

        let initial_run = run_dir::create_run_dir(repo).expect("create run");
        let backup = initial_run.backups.join(".beads/foo.txt");
        fs::create_dir_all(backup.parent().unwrap()).unwrap();
        fs::write(&backup, b"original").unwrap();
        let action = serde_json::json!({
            "path": ".beads/foo.txt",
            "op": "write_file",
            "before_hash": "sha256:not-the-backup-hash"
        });
        fs::write(&initial_run.actions_file, format!("{action}\n")).unwrap();

        let args = DoctorUndoArgs {
            run_id: initial_run.run_id.clone(),
            dry_run: false,
            json: true,
        };
        execute_undo(&args, repo).expect("undo returns envelope even when a step fails");

        let report = fs::read_to_string(&initial_run.report_file).unwrap_or_default();
        assert!(
            !report.contains("undone_at"),
            "failed undo attempt must not stamp original report as undone: {report}"
        );
    }

    #[test]
    fn test_doctor_undo_malformed_action_does_not_mark_original_run_undone() {
        let tmp = unique_temp_root("undo-malformed-action");
        let repo = tmp.path();
        fs::create_dir_all(repo.join(".beads")).unwrap();

        let initial_run = run_dir::create_run_dir(repo).expect("create run");
        fs::write(&initial_run.actions_file, b"{ not valid json }\n").unwrap();

        let (actions, parse_failures) = read_actions_reverse(&initial_run.actions_file).unwrap();
        assert!(
            actions.is_empty(),
            "malformed line must not produce an action"
        );
        assert_eq!(parse_failures.len(), 1);
        assert_eq!(parse_failures[0].path, "actions.jsonl:1");
        assert_eq!(parse_failures[0].op, "parse_action");
        assert!(parse_failures[0].status.starts_with("failed_parse_action:"));

        let args = DoctorUndoArgs {
            run_id: initial_run.run_id.clone(),
            dry_run: false,
            json: true,
        };
        execute_undo(&args, repo).expect("undo returns envelope even when action log is malformed");

        let report = fs::read_to_string(&initial_run.report_file).unwrap_or_default();
        assert!(
            !report.contains("undone_at"),
            "malformed action log must not stamp original report as undone: {report}"
        );
    }

    #[test]
    fn test_doctor_undo_missing_backup_does_not_mark_original_run_undone() {
        let tmp = unique_temp_root("undo-missing-backup");
        let repo = tmp.path();
        let beads = repo.join(".beads");
        fs::create_dir_all(&beads).unwrap();
        fs::write(beads.join("foo.txt"), b"updated").unwrap();

        let initial_run = run_dir::create_run_dir(repo).expect("create run");
        let action = serde_json::json!({
            "path": ".beads/foo.txt",
            "op": "write_file",
            "before_hash": "sha256:backup-was-not-preserved"
        });
        fs::write(&initial_run.actions_file, format!("{action}\n")).unwrap();

        let args = DoctorUndoArgs {
            run_id: initial_run.run_id.clone(),
            dry_run: false,
            json: true,
        };
        execute_undo(&args, repo).expect("undo returns envelope even when backup is missing");

        let report = fs::read_to_string(&initial_run.report_file).unwrap_or_default();
        assert!(
            !report.contains("undone_at"),
            "missing backup must not stamp original report as undone: {report}"
        );
    }

    #[test]
    fn test_doctor_undo_rename_routes_through_mutate() {
        let tmp = unique_temp_root("undo-rename");
        let repo = tmp.path();
        let beads = repo.join(".beads");
        fs::create_dir_all(&beads).unwrap();
        let target = beads.join("renamed.txt");
        fs::write(&target, b"payload").unwrap();

        let initial_run = run_dir::create_run_dir(repo).expect("create run");
        let actions_file = OpenOptions::new()
            .create(true)
            .append(true)
            .open(&initial_run.actions_file)
            .unwrap();
        let ctx = MutateContext {
            run_id: initial_run.run_id.clone(),
            run_dir: initial_run.root.clone(),
            capabilities: MutateCapabilities::for_repo(repo),
            actions_file: Mutex::new(actions_file),
            fixer_id: "test".into(),
            repo_root: repo.to_path_buf(),
            dry_run: false,
            start_ns: now_ns(),
        };
        let quarantine_path = initial_run.root.join("quarantine/renamed.txt");
        chokepoint::mutate(
            &ctx,
            &target,
            Op::Rename {
                to: quarantine_path.clone(),
            },
        )
        .expect("rename into quarantine");
        assert!(!target.exists());
        assert_eq!(fs::read(&quarantine_path).unwrap(), b"payload");

        let args = DoctorUndoArgs {
            run_id: initial_run.run_id.clone(),
            dry_run: false,
            json: true,
        };
        execute_undo(&args, repo).expect("undo rename");
        assert_eq!(fs::read(&target).unwrap(), b"payload");
        assert!(!quarantine_path.exists());

        let runs_root = repo.join(".doctor/runs");
        let undo_run_id = fs::read_dir(&runs_root)
            .unwrap()
            .find_map(|entry| {
                let entry = entry.ok()?;
                let name = entry.file_name().to_string_lossy().into_owned();
                (name != initial_run.run_id).then_some(name)
            })
            .expect("undo run id");
        let undo_actions = fs::read_to_string(runs_root.join(undo_run_id).join("actions.jsonl"))
            .expect("undo actions");
        let line = undo_actions
            .lines()
            .next()
            .expect("undo action should be logged");
        let action: serde_json::Value = serde_json::from_str(line).expect("undo action json");
        assert_eq!(action["op"], "rename");
        assert_eq!(
            action["fixer_id"],
            format!("doctor_undo[{}]", initial_run.run_id)
        );
        assert_eq!(action["rename_to"], target.to_string_lossy().as_ref());
    }

    #[test]
    fn doctor_undo_refuses_tampered_quarantine_rename_payload() {
        let tmp = unique_temp_root("undo-rename-tamper");
        let repo = tmp.path();
        let beads = repo.join(".beads");
        fs::create_dir_all(&beads).unwrap();
        let target = beads.join("renamed.txt");
        fs::write(&target, b"payload").unwrap();

        let initial_run = run_dir::create_run_dir(repo).expect("create run");
        let actions_file = OpenOptions::new()
            .create(true)
            .append(true)
            .open(&initial_run.actions_file)
            .unwrap();
        let ctx = MutateContext {
            run_id: initial_run.run_id.clone(),
            run_dir: initial_run.root.clone(),
            capabilities: MutateCapabilities::for_repo(repo),
            actions_file: Mutex::new(actions_file),
            fixer_id: "test".into(),
            repo_root: repo.to_path_buf(),
            dry_run: false,
            start_ns: now_ns(),
        };
        let quarantine_path = initial_run.root.join("quarantine/renamed.txt");
        chokepoint::mutate(
            &ctx,
            &target,
            Op::Rename {
                to: quarantine_path.clone(),
            },
        )
        .expect("rename into quarantine");
        let action_line = fs::read_to_string(&initial_run.actions_file)
            .unwrap()
            .lines()
            .next()
            .unwrap()
            .to_string();
        let record: StoredActionRecord = serde_json::from_str(&action_line).unwrap();

        fs::write(&quarantine_path, b"tampered").unwrap();
        let undo_run = run_dir::create_run_dir(repo).expect("create undo run");
        let undo_actions = OpenOptions::new()
            .create(true)
            .append(true)
            .open(&undo_run.actions_file)
            .unwrap();
        let mut capabilities = MutateCapabilities::for_repo(repo);
        capabilities.write_scopes.push(quarantine_path.clone());
        let undo_ctx = MutateContext {
            run_id: undo_run.run_id,
            run_dir: undo_run.root,
            capabilities,
            actions_file: Mutex::new(undo_actions),
            fixer_id: "doctor_undo[test]".into(),
            repo_root: repo.to_path_buf(),
            dry_run: false,
            start_ns: now_ns(),
        };

        let step = restore_one(
            &undo_ctx,
            repo,
            &initial_run.root,
            &initial_run.root.join("backups"),
            &record,
        );

        assert_eq!(step.status, "failed_hash_mismatch_rename_to");
        assert!(
            !target.exists(),
            "tampered quarantine payload must not be moved back"
        );
        assert_eq!(fs::read(&quarantine_path).unwrap(), b"tampered");
    }

    #[test]
    fn doctor_undo_refuses_rename_source_outside_original_run_dir() {
        let tmp = unique_temp_root("undo-rename-outside");
        let repo = tmp.path();
        let beads = repo.join(".beads");
        fs::create_dir_all(&beads).unwrap();
        let initial_run = run_dir::create_run_dir(repo).expect("create run");
        let backup = initial_run.root.join("backups/.beads/renamed.txt");
        fs::create_dir_all(backup.parent().unwrap()).unwrap();
        fs::write(&backup, b"payload").unwrap();

        let outside = unique_temp_root("undo-rename-outside-source");
        let outside_source = outside.path().join("renamed.txt");
        fs::write(&outside_source, b"payload").unwrap();
        let record = StoredActionRecord {
            path: ".beads/renamed.txt".to_string(),
            op: "rename".to_string(),
            before_hash: sha256_bytes_hex_prefixed(b"payload"),
            backup_path: None,
            rename_to: Some(outside_source.to_string_lossy().into_owned()),
            db_snapshots: Vec::new(),
            db_snapshot_sha256: Vec::new(),
            affected_tables: None,
            affected_predicate: None,
        };
        let undo_run = run_dir::create_run_dir(repo).expect("create undo run");
        let undo_actions = OpenOptions::new()
            .create(true)
            .append(true)
            .open(&undo_run.actions_file)
            .unwrap();
        let undo_ctx = MutateContext {
            run_id: undo_run.run_id,
            run_dir: undo_run.root,
            capabilities: MutateCapabilities::for_repo(repo),
            actions_file: Mutex::new(undo_actions),
            fixer_id: "doctor_undo[test]".into(),
            repo_root: repo.to_path_buf(),
            dry_run: false,
            start_ns: now_ns(),
        };

        let step = restore_one(
            &undo_ctx,
            repo,
            &initial_run.root,
            &initial_run.root.join("backups"),
            &record,
        );

        assert!(
            step.status.starts_with("failed_invalid_rename_to:"),
            "unexpected status: {}",
            step.status
        );
        assert!(!beads.join("renamed.txt").exists());
        assert_eq!(fs::read(outside_source).unwrap(), b"payload");
    }

    #[test]
    fn test_doctor_undo_latest_resolves_to_most_recent() {
        let tmp = unique_temp_root("undo-latest");
        let repo = tmp.path();
        let runs_root = repo.join(".doctor").join("runs");
        fs::create_dir_all(&runs_root).unwrap();
        // Three subdirs with sortable names; latest is the largest.
        for name in [
            "20260101T000000Z__a",
            "20260301T000000Z__b",
            "20260201T000000Z__c",
        ] {
            fs::create_dir_all(runs_root.join(name).join("backups")).unwrap();
            fs::write(runs_root.join(name).join("actions.jsonl"), b"").unwrap();
        }
        let latest = find_latest_run(&runs_root).unwrap().unwrap();
        assert_eq!(latest, "20260301T000000Z__b");
    }

    #[test]
    fn test_doctor_undo_latest_skips_path_shaped_run_dirs() {
        let tmp = unique_temp_root("undo-latest-invalid-name");
        let repo = tmp.path();
        let runs_root = repo.join(".doctor").join("runs");
        fs::create_dir_all(&runs_root).unwrap();
        for name in ["20260101T000000Z__valid", "zz.invalid"] {
            fs::create_dir_all(runs_root.join(name).join("backups")).unwrap();
            fs::write(runs_root.join(name).join("actions.jsonl"), b"").unwrap();
        }

        let latest = find_latest_run(&runs_root).unwrap().unwrap();

        assert_eq!(latest, "20260101T000000Z__valid");
    }

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

        let tmp = unique_temp_root("undo-latest-link");
        let repo = tmp.path();
        let runs_root = repo.join(".doctor").join("runs");
        fs::create_dir_all(&runs_root).unwrap();
        for name in ["20260102T000000Z__newer", "20260101T000000Z__linked"] {
            fs::create_dir_all(runs_root.join(name).join("backups")).unwrap();
            fs::write(runs_root.join(name).join("actions.jsonl"), b"").unwrap();
        }
        symlink("runs/20260101T000000Z__linked", repo.join(".doctor/latest")).unwrap();

        let latest = find_latest_run(&runs_root).unwrap().unwrap();
        assert_eq!(latest, "20260102T000000Z__newer");
    }

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

        let tmp = unique_temp_root("undo-latest-link-traversal");
        let repo = tmp.path();
        let doctor = repo.join(".doctor");
        let runs_root = doctor.join("runs");
        fs::create_dir_all(runs_root.join("escape")).unwrap();
        fs::create_dir_all(doctor.join("outside-run")).unwrap();

        symlink("runs/escape/../../outside-run", doctor.join("latest")).unwrap();

        let latest = latest_run_from_symlink(&runs_root).unwrap();
        assert_eq!(latest, None);
    }

    /// Round-2 fresh-eyes regression test: a symlink whose target
    /// reaches the same canonical run dir via a different lexical path
    /// (i.e. via `..` segments that resolve back into `runs_root`)
    /// must still be accepted. The prefix check has to canonicalize
    /// *both* sides — not just refuse anything containing `..`.
    #[test]
    fn test_doctor_undo_latest_accepts_canonical_target_with_dot_dot() {
        use std::os::unix::fs::symlink;

        let tmp = unique_temp_root("undo-latest-link-dotdot-canonical");
        let repo = tmp.path();
        let runs_root = repo.join(".doctor").join("runs");
        let run_dir = runs_root.join("20260101T000000Z__legit");
        fs::create_dir_all(run_dir.join("backups")).unwrap();
        fs::write(run_dir.join("actions.jsonl"), b"").unwrap();

        // Lexical target contains `..` but canonicalizes back inside
        // runs_root. Pre-fix, this would also pass (string prefix
        // matches accidentally). Post-fix, canonicalization is what
        // makes it pass — and the parallel test
        // `..._rejects_symlink_traversal_outside_runs_root` ensures
        // the escape case still fails.
        symlink(
            "runs/20260101T000000Z__legit/../20260101T000000Z__legit",
            repo.join(".doctor/latest"),
        )
        .unwrap();

        let latest = latest_run_from_symlink(&runs_root).unwrap();
        assert_eq!(latest, Some("20260101T000000Z__legit".into()));
    }

    /// Regression for the round-3 hash-bind: plan_db_exec must refuse
    /// when the on-disk snapshot body has been edited under our feet,
    /// even in `--dry-run` mode. Without the hash-bind, a tampered
    /// snapshot would parse and be reported as `would_restore`, then
    /// silently inject the attacker's rows on a real undo.
    #[test]
    fn plan_db_exec_rejects_tampered_snapshot_body() {
        let tmp = unique_temp_root("plan-db-tamper");
        let repo = tmp.path();
        let snap_rel = ".doctor/runs/r/backups/db/cache.json";
        let snap_abs = repo.join(snap_rel);
        fs::create_dir_all(snap_abs.parent().unwrap()).unwrap();
        // Write a "genuine" snapshot body and record its hash. Then
        // overwrite the file (simulating tampering) and ask the plan
        // path what it thinks.
        let genuine = b"{\"schema_version\":\"br.doctor.db_snapshot.v1\",\"rows\":[]}";
        fs::write(&snap_abs, genuine).unwrap();
        let expected_sha = sha256_bytes_hex_prefixed(genuine);

        // Tamper.
        fs::write(
            &snap_abs,
            b"{\"schema_version\":\"br.doctor.db_snapshot.v1\",\"rows\":[{\"injected\":true}]}",
        )
        .unwrap();

        let record = StoredActionRecord {
            path: ".beads/beads.db".to_string(),
            op: "db_exec".to_string(),
            before_hash: "sha256:test".to_string(),
            backup_path: None,
            rename_to: None,
            db_snapshots: vec![snap_rel.to_string()],
            db_snapshot_sha256: vec![expected_sha],
            affected_tables: Some("cache".to_string()),
            affected_predicate: None,
        };

        let step = plan_db_exec(repo, &record);
        assert!(
            step.status.starts_with("failed_snapshot_sha_mismatch"),
            "plan must refuse tampered snapshot bodies, got {}",
            step.status
        );
    }

    #[test]
    fn test_doctor_robot_triage_emits_v1() {
        let env = build_triage_envelope(
            5,
            2,
            1,
            vec![TriageFinding {
                id: "fm-test".into(),
                severity: "P2".into(),
                message: "demo".into(),
            }],
        );
        let json = serde_json::to_string(&env).unwrap();
        let v: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert_eq!(v["schema_version"], "br.doctor.triage.v1");
        assert!(v["findings"].is_array());
        assert_eq!(v["quick_ref"]["error"], 1);
        assert_eq!(v["quick_ref"]["warn"], 2);
        assert_eq!(v["quick_ref"]["healthy"], 5);
        assert!(
            v["recommended_command"]
                .as_str()
                .unwrap()
                .starts_with("br doctor")
        );
    }
}