openlatch-client 0.6.1

OpenLatch runtime enforcement node — the capture-and-enforce adapter that evaluates every covered action against a coding agent's Autonomy Zone before it runs
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
//! `openlatch doctor --fix` — auto-heal common issues.
//!
//! Step 4 lands `heal_state` (config.toml, daemon.token, agent_id,
//! telemetry.json, daemon.pid). Steps 5–6 layer in `heal_hooks`,
//! `heal_binaries`, and `heal_daemon` (with auto-rollback on restart
//! failure). Each mutation writes a `.bak` sibling and appends a
//! `FixAction` to a journal at `~/.openlatch/fix-journal.json` so
//! `--restore` can reverse it.

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

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

use crate::cli::commands::doctor::{print_diagnostic_results, run_all_checks, DoctorReport};
use crate::cli::commands::{doctor_restore, lifecycle};
use crate::cli::output::{OutputConfig, OutputFormat};
use crate::cli::DoctorArgs;
use crate::config;
use crate::error::OlError;
use crate::hooks;
use crate::hooks::binding::HookSurface;
use crate::hooks::DetectedAgent;
use crate::telemetry::{self, Event};

/// Filename of the per-run journal stored under the openlatch state dir.
pub(crate) const JOURNAL_FILENAME: &str = "fix-journal.json";

/// Categories of self-heal action recorded in the journal.
///
/// Used by `--restore` to dispatch the correct rollback strategy
/// (surgical merge for hooks, blind file swap for everything else,
/// process actions are not reversed).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum FixKind {
    /// `config.toml` rewritten from defaults (parse failure or missing).
    ConfigRewrite,
    /// `daemon.token` regenerated (missing or empty).
    TokenRegenerate,
    /// `[daemon] agent_id` inserted into `config.toml`.
    AgentIdInsert,
    /// `telemetry.json` reset to a safe default after a parse failure.
    TelemetryReset,
    /// Stale `daemon.pid` removed (PID no longer alive).
    PidStaleRemove,
    /// Hook entries rewritten in the agent's `settings.json`.
    HookReinstall,
    /// Daemon process cycled (stop → restart). Not reversible by `--restore`.
    DaemonRestart,
    /// `~/.openlatch/bin/openlatch-hook` re-staged from the resolved source.
    BinaryCopy,
    /// OS-native supervisor (launchd / systemd-user / Task Scheduler) reinstalled
    /// because config said `mode=active` but the OS artifact was missing. Not
    /// reversible by `--restore` — rerun `openlatch system supervision uninstall` to undo.
    SupervisionInstall,
    /// The agent's own trust granted to our hooks (Codex's `[hooks.state]`),
    /// on an install whose hook file needed no rewrite. Not reversible by
    /// `--restore`: restoring would replace the agent's whole config file.
    /// `openlatch uninstall` takes the grant back.
    HookTrustGrant,
    /// The relay's certificate authority (re)installed into the user's trust store (D-29's
    /// "doctor --fix retries"). Not reversible by `--restore`: `openlatch uninstall` takes it
    /// back with the read-back D-06r requires.
    RelayCaTrust,
    /// The relay's certificate authority rotated (D-31: mint → install → prove → promote →
    /// remove old). Not reversible by `--restore` — reverting would mean silently regenerating
    /// a CA under a possibly-running session, exactly what D-06 forbids.
    RelayCaRotate,
    /// A due rotation was NOT run because the daemon could not be confirmed stopped (C2): it
    /// still holds the old CA in memory, and rotating would remove that root from the trust
    /// store out from under it. Nothing changed, so this carries no reversal and never triggers
    /// `heal_daemon`'s restart.
    RelayCaRotateSkipped,
}

/// One self-heal action recorded in the journal.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FixAction {
    /// OL-XXXX code that motivated the fix (matches the diagnostic check).
    pub ol_code: String,
    /// What kind of mutation was performed.
    pub kind: FixKind,
    /// Path that was mutated (for rollback) or `""` for process actions.
    pub file: PathBuf,
    /// Path to the `.bak` sibling created before the mutation, if any.
    pub backup: Option<PathBuf>,
    /// Whether `--restore` can reverse this action.
    pub reversible: bool,
    /// UTC timestamp when the action was applied.
    pub applied_at: DateTime<Utc>,
    /// Human-readable note shown in the summary output.
    pub note: String,
}

/// The journal of fixes applied during a single `--fix` invocation.
///
/// Serialized to `~/.openlatch/fix-journal.json` at the end of every
/// `--fix` run (overwriting any prior journal). `--restore` reads this
/// file to reverse the most recent run's actions.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Journal {
    /// Per-run identifier (UUIDv4 simple) for telemetry/log correlation.
    pub run_id: String,
    /// UTC timestamp of when the run began.
    pub started_at: DateTime<Utc>,
    /// Ordered list of fixes applied during this run.
    pub actions: Vec<FixAction>,
}

impl Journal {
    /// Start a fresh journal with a new `run_id`.
    pub fn new() -> Self {
        Self {
            run_id: uuid::Uuid::new_v4().simple().to_string(),
            started_at: Utc::now(),
            actions: Vec::new(),
        }
    }

    /// Persist the journal to `<ol_dir>/fix-journal.json`.
    ///
    /// Overwrites any prior journal — `--restore` only ever reverses the
    /// most recent run.
    pub fn save(&self, ol_dir: &Path) -> Result<PathBuf, OlError> {
        let path = ol_dir.join(JOURNAL_FILENAME);
        let raw = serde_json::to_string_pretty(self).map_err(|e| {
            OlError::new(
                crate::error::ERR_DOCTOR_JOURNAL_CORRUPT,
                format!("cannot serialize fix journal: {e}"),
            )
        })?;
        std::fs::write(&path, raw).map_err(|e| {
            OlError::new(
                crate::error::ERR_DOCTOR_JOURNAL_CORRUPT,
                format!("cannot write fix journal '{}': {e}", path.display()),
            )
        })?;
        Ok(path)
    }

    /// Read the journal from `<ol_dir>/fix-journal.json`.
    ///
    /// Returns `OL-1801` if the file is absent (no prior `--fix` to
    /// reverse) and `OL-1800` if it exists but cannot be parsed.
    pub fn load(ol_dir: &Path) -> Result<Self, OlError> {
        let path = ol_dir.join(JOURNAL_FILENAME);
        let raw = match std::fs::read_to_string(&path) {
            Ok(s) => s,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                return Err(OlError::new(
                    crate::error::ERR_DOCTOR_RESTORE_NO_JOURNAL,
                    format!("no prior --fix run found at '{}'", path.display()),
                )
                .with_suggestion(
                    "Run `openlatch doctor --fix` first; --restore reverses the most recent run.",
                ));
            }
            Err(e) => {
                return Err(OlError::new(
                    crate::error::ERR_DOCTOR_JOURNAL_CORRUPT,
                    format!("cannot read fix journal '{}': {e}", path.display()),
                ))
            }
        };
        serde_json::from_str(&raw).map_err(|e| {
            OlError::new(
                crate::error::ERR_DOCTOR_JOURNAL_CORRUPT,
                format!("fix journal at '{}' is malformed: {e}", path.display()),
            )
            .with_suggestion(
                "Delete `fix-journal.json` and re-run `openlatch init` to reset state.",
            )
        })
    }
}

impl Default for Journal {
    fn default() -> Self {
        Self::new()
    }
}

/// Entry point for `openlatch doctor --fix`.
///
/// Pre-fix: snapshot diagnostic checks (best-effort — a totally broken
/// install may not even pass `Config::load`, in which case the snapshot
/// is `None` and the report only shows post-fix state).
///
/// Heal: state → (steps 5+: hooks, binaries, daemon).
///
/// Post-fix: re-run all diagnostic checks. Exit 0 if all pass; 1 if any
/// remain failing (lists the unfixable OL-XXXX codes in the output).
pub fn run(_args: &DoctorArgs, output: &OutputConfig) -> Result<(), OlError> {
    let started = std::time::Instant::now();
    let ol_dir = config::openlatch_dir();
    // Ensure the directory exists before any heal step touches it; without
    // this a brand-new install would error out on the first `.bak` write.
    std::fs::create_dir_all(&ol_dir).map_err(|e| {
        OlError::new(
            crate::error::ERR_INVALID_CONFIG,
            format!("cannot create openlatch dir '{}': {e}", ol_dir.display()),
        )
    })?;

    crate::cli::header::print(output, &["doctor", "--fix"]);

    // Pre-fix snapshot — best-effort. A corrupt config.toml may make
    // run_all_checks itself error; that's expected and the fix run still
    // proceeds (heal_state will rewrite the bad config).
    let before = run_all_checks(output).ok();

    let pre_fix = capture_pre_fix_state(&ol_dir);
    let mut journal = Journal::new();

    // Stop the daemon before mutating files so it cannot reload a
    // half-written config. We only attempt a restart if it was running
    // before, OR if a fix touched config/token/hooks/binaries.
    //
    // `daemon_confirmed_stopped` (C2): when it was running and the stop attempt did not confirm
    // it dead, `heal_relay_ca` must not rotate the CA out from under it — that removes the old
    // root from the trust store while a still-live daemon serves leaves nobody trusts any more.
    let daemon_confirmed_stopped = if pre_fix.was_running {
        stop_daemon_for_fix(&pre_fix, &ol_dir)
    } else {
        true
    };

    journal.actions.extend(heal_state(&ol_dir));
    // Hooks and binaries depend on a healed config + token, so they run
    // after heal_state. heal_hooks no-ops when no agent is detected.
    journal.actions.extend(heal_binaries(&ol_dir));
    journal.actions.extend(heal_hooks(&ol_dir));
    journal.actions.extend(heal_supervision(&ol_dir));
    #[cfg(feature = "model-relay")]
    journal.actions.extend(heal_relay_ca(
        &ol_dir,
        &hooks::detect_agents(),
        time::OffsetDateTime::now_utc(),
        daemon_confirmed_stopped,
    ));

    let mut auto_rollback_triggered = false;
    let (daemon_actions, restart_failed) = heal_daemon(&ol_dir, &pre_fix, &journal.actions);
    journal.actions.extend(daemon_actions);

    if restart_failed {
        auto_rollback_triggered = true;
        tracing::error!("doctor --fix: daemon restart failed — rolling back this run's actions");
        // Best-effort rollback. If this also fails the user is no worse
        // off than they would have been after a manual `--restore`.
        let _ = doctor_restore::restore_actions(&journal.actions, &ol_dir);
        if pre_fix.was_running && !lifecycle::start_via_supervisor(pre_fix.port) {
            let token = std::fs::read_to_string(ol_dir.join("daemon.token"))
                .map(|s| s.trim().to_string())
                .unwrap_or_default();
            if !token.is_empty() {
                let _ = lifecycle::spawn_daemon_background(pre_fix.port, &token);
            }
        }
    }

    // Persist the journal even when zero actions were taken — that way
    // `--restore` can give a precise "nothing to reverse" message instead
    // of falling through to OL-1801 ("no prior --fix").
    let journal_path = journal.save(&ol_dir)?;

    let after = run_all_checks(output)?;

    let categories: Vec<&str> = {
        let mut cats: Vec<&str> = Vec::new();
        for a in &journal.actions {
            let cat = match a.kind {
                FixKind::ConfigRewrite
                | FixKind::TokenRegenerate
                | FixKind::AgentIdInsert
                | FixKind::TelemetryReset
                | FixKind::PidStaleRemove => "state",
                FixKind::HookReinstall | FixKind::HookTrustGrant => "hooks",
                FixKind::DaemonRestart => "daemon",
                FixKind::BinaryCopy => "binary",
                FixKind::SupervisionInstall => "supervision",
                FixKind::RelayCaTrust | FixKind::RelayCaRotate | FixKind::RelayCaRotateSkipped => {
                    "relay"
                }
            };
            if !cats.contains(&cat) {
                cats.push(cat);
            }
        }
        cats
    };
    // Everything still not green after the run. `--fix` heals defects; it
    // deliberately does not re-enable what the operator switched off, so a
    // disabled model relay shows up here as unresolved rather than being flipped
    // back on behind their back.
    let unresolved = after.unresolved();
    let unfixable: Vec<&str> = unresolved.iter().map(String::as_str).collect();
    let (before_pass, before_fail) = before
        .as_ref()
        .map(|r| (r.pass_count(), r.fail_count()))
        .unwrap_or((0, 0));
    telemetry::capture_global(Event::doctor_fix_run(
        categories,
        before_pass,
        before_fail,
        after.pass_count(),
        after.fail_count(),
        unfixable,
        started.elapsed().as_millis() as u64,
        auto_rollback_triggered,
    ));

    print_fix_results(
        &journal,
        &journal_path,
        before.as_ref(),
        &after,
        auto_rollback_triggered,
        output,
    );

    if after.all_pass() && !auto_rollback_triggered {
        Ok(())
    } else {
        // Exit 1 without going through OlError so the caller's error
        // formatter doesn't double-print. Matches the brainstorm's
        // "exit 1 = unfixable remaining" contract.
        std::process::exit(1);
    }
}

/// Snapshot of the daemon's state before any `--fix` mutation.
///
/// Used to (a) decide whether a restart is necessary and (b) revert the
/// daemon to its pre-fix state if the post-fix restart fails.
#[derive(Debug, Clone)]
#[allow(dead_code)] // was_healthy is captured for telemetry / debug output (step 7)
pub(crate) struct PreFixState {
    pub was_running: bool,
    pub was_healthy: bool,
    pub port: u16,
    pub pid: Option<u32>,
}

/// Capture the daemon's pre-fix state.
pub(crate) fn capture_pre_fix_state(_ol_dir: &Path) -> PreFixState {
    let port = config::Config::load(None, None, false)
        .map(|c| c.port)
        .unwrap_or(config::PORT_RANGE_START);
    let pid = lifecycle::read_pid_file();
    let was_running = pid.map(lifecycle::is_process_alive).unwrap_or(false);
    let was_healthy = if was_running {
        lifecycle::check_health(port)
    } else {
        false
    };
    PreFixState {
        was_running,
        was_healthy,
        port,
        pid,
    }
}

/// Stop the daemon ahead of file mutations.
///
/// Tries the bearer-authenticated POST /shutdown first (graceful), then
/// falls back to force-kill via the PID. Cleans up the PID file when
/// the process is confirmed dead. Best-effort — failures are logged and
/// allowed; heal_daemon's restart attempt will surface anything
/// genuinely broken.
///
/// Returns whether the daemon is now CONFIRMED stopped (C2): `state.pid` was
/// `None`, the supervisor's own stop path reported success, or a live-PID
/// check reads it as dead after the attempts above. `heal_relay_ca` gates its
/// rotation step on this — a live daemon still holds the old CA in memory,
/// and rotation removes that old root from the trust store, which would
/// leave a daemon we failed to stop serving leaves nothing trusts any more.
fn stop_daemon_for_fix(state: &PreFixState, ol_dir: &Path) -> bool {
    // Under a supervisor, `/shutdown` + SIGTERM is not a stop: `Restart=always`
    // brings the daemon back within `RestartSec`, i.e. in the middle of the
    // heal. `heal_state` rewrites config.toml and daemon.token, so a daemon
    // restarting under it reads half-written state. The supervisor has to be
    // the one told to stop.
    if lifecycle::stop_via_supervisor() {
        let _ = std::fs::remove_file(ol_dir.join("daemon.pid"));
        return true;
    }

    let Some(pid) = state.pid else {
        return true;
    };

    // Read the token to send the bearer-authenticated shutdown.
    let token = std::fs::read_to_string(ol_dir.join("daemon.token"))
        .map(|s| s.trim().to_string())
        .unwrap_or_default();

    if !token.is_empty() {
        let _ = lifecycle::send_shutdown_request(state.port, &token);
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
        while std::time::Instant::now() < deadline && lifecycle::is_process_alive(pid) {
            std::thread::sleep(std::time::Duration::from_millis(100));
        }
    }

    if lifecycle::is_process_alive(pid) {
        lifecycle::force_kill(pid);
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(3);
        while std::time::Instant::now() < deadline && lifecycle::is_process_alive(pid) {
            std::thread::sleep(std::time::Duration::from_millis(100));
        }
    }

    // Best-effort PID file cleanup.
    let _ = std::fs::remove_file(ol_dir.join("daemon.pid"));
    !lifecycle::is_process_alive(pid)
}

/// Restart the daemon when needed.
///
/// Returns `(actions, restart_failed)`:
/// - `actions` carries a `DaemonRestart` `FixAction` when a restart was
///   attempted AND `/health` came back 200 within 3 s.
/// - `restart_failed` is `true` only when a restart was attempted and
///   did not finish healthy. The caller then drives auto-rollback.
///
/// Skips the restart entirely when the daemon was off pre-fix AND no
/// fix touched a file the daemon reads on boot — pure churn isn't worth
/// disrupting in-flight hooks.
pub(crate) fn heal_daemon(
    ol_dir: &Path,
    pre_fix: &PreFixState,
    prior_actions: &[FixAction],
) -> (Vec<FixAction>, bool) {
    let mut actions = Vec::new();

    let touched_critical = prior_actions.iter().any(|a| {
        matches!(
            a.kind,
            FixKind::ConfigRewrite
                | FixKind::TokenRegenerate
                | FixKind::AgentIdInsert
                | FixKind::HookReinstall
                // The relay reads its CA once per process (D-06): a restart is what loads a
                // rotated CA and clears the daemon's refusal holds (§3) — the only way
                // `doctor --fix` re-arms a tripped host.
                | FixKind::RelayCaTrust
                | FixKind::RelayCaRotate
        )
    });
    let should_restart = pre_fix.was_running || touched_critical;
    if !should_restart {
        return (actions, false);
    }

    // Re-probe in case our own port is now contested by something else
    // that grabbed it during the stop window. We start the probe at the
    // pre-fix port so the common case (still free) returns immediately.
    let port = config::probe_free_port(pre_fix.port, config::PORT_RANGE_END)
        .or_else(|_| config::probe_free_port(config::PORT_RANGE_START, config::PORT_RANGE_END))
        .unwrap_or(pre_fix.port);
    if port != pre_fix.port {
        let _ = config::write_port_file(port);
    }

    let token = match std::fs::read_to_string(ol_dir.join("daemon.token")) {
        Ok(s) if !s.trim().is_empty() => s.trim().to_string(),
        _ => {
            tracing::error!(
                "doctor --fix: cannot restart daemon — daemon.token missing/empty after heal_state"
            );
            return (actions, true);
        }
    };

    // Hand the restart back to the supervisor when it owns the daemon, so the
    // heal ends with the one supervised daemon it started with — not with an
    // unsupervised one this process spawned next to a unit that will start its
    // own at the next login.
    if lifecycle::start_via_supervisor(port) {
        actions.push(FixAction {
            ol_code: crate::error::ERR_DAEMON_START_FAILED.to_string(),
            kind: FixKind::DaemonRestart,
            file: PathBuf::new(),
            backup: None,
            reversible: false,
            applied_at: Utc::now(),
            note: format!("supervised daemon restarted on port {port} (/health=200)"),
        });
        return (actions, false);
    }

    let pid = match lifecycle::spawn_daemon_background(port, &token) {
        Ok(pid) => pid,
        Err(e) => {
            tracing::error!(error = %e.message, code = e.code, "doctor --fix: daemon spawn failed");
            return (actions, true);
        }
    };

    if !lifecycle::wait_for_health(port, 3) {
        tracing::error!(
            pid = pid,
            port = port,
            "doctor --fix: daemon spawned but /health did not return 200 within 3s"
        );
        return (actions, true);
    }

    actions.push(FixAction {
        ol_code: crate::error::ERR_DAEMON_START_FAILED.to_string(),
        kind: FixKind::DaemonRestart,
        file: PathBuf::new(),
        backup: None,
        reversible: false,
        applied_at: Utc::now(),
        note: format!("daemon restarted on port {port} (PID {pid}, /health=200)"),
    });
    (actions, false)
}

/// Heal state files (config.toml, daemon.token, agent_id, telemetry.json,
/// daemon.pid).
///
/// Best-effort: a single mutation failure does not abort the rest of the
/// category. Each successful mutation appends a `FixAction`. Failures are
/// logged via `tracing::warn!` so the post-fix `run_all_checks` still
/// reports the underlying diagnostic.
///
/// Takes `&Path` rather than calling `openlatch_dir()` internally so
/// tests can drive the function with a tempdir without env-var
/// manipulation.
pub(crate) fn heal_state(ol_dir: &Path) -> Vec<FixAction> {
    let mut actions = Vec::new();

    // 1. config.toml — parse-or-regenerate.
    let config_path = ol_dir.join("config.toml");
    let config_needs_rewrite = match std::fs::read_to_string(&config_path) {
        Ok(raw) => toml::from_str::<toml::Value>(&raw).is_err(),
        Err(_) => true,
    };
    if config_needs_rewrite {
        let backup = if config_path.exists() {
            backup_file(&config_path).ok()
        } else {
            None
        };
        let content = config::generate_default_config_toml(config::PORT_RANGE_START);
        if let Err(e) = std::fs::write(&config_path, content) {
            tracing::warn!(error = %e, path = %config_path.display(), "doctor --fix: config rewrite failed");
        } else {
            actions.push(FixAction {
                ol_code: crate::error::ERR_INVALID_CONFIG.to_string(),
                kind: FixKind::ConfigRewrite,
                file: config_path.clone(),
                backup,
                reversible: true,
                applied_at: Utc::now(),
                note: format!("regenerated {} from defaults", config_path.display()),
            });
        }
    }

    // 2. daemon.token — regenerate if missing or empty.
    let token_path = ol_dir.join("daemon.token");
    let token_needs_regen = match std::fs::read_to_string(&token_path) {
        Ok(raw) => raw.trim().is_empty(),
        Err(_) => true,
    };
    if token_needs_regen {
        let backup = if token_path.exists() {
            backup_file(&token_path).ok()
        } else {
            None
        };
        // Force regeneration: ensure_token only generates when the file
        // is absent, so an empty file would otherwise survive.
        if token_path.exists() {
            let _ = std::fs::remove_file(&token_path);
        }
        match config::ensure_token(ol_dir) {
            Ok(_) => {
                actions.push(FixAction {
                    ol_code: crate::error::ERR_INVALID_CONFIG.to_string(),
                    kind: FixKind::TokenRegenerate,
                    file: token_path.clone(),
                    backup,
                    reversible: true,
                    applied_at: Utc::now(),
                    note: format!("regenerated {} (mode 0600 on Unix)", token_path.display()),
                });
            }
            Err(e) => {
                tracing::warn!(error = %e.message, code = e.code, "doctor --fix: token regenerate failed");
            }
        }
    }

    // 3. agent_id — ensure inserted into [daemon] section.
    if config_path.exists() {
        let needs_insert = std::fs::read_to_string(&config_path)
            .map(|raw| !raw.contains("agent_id"))
            .unwrap_or(false);
        if needs_insert {
            let backup = backup_file(&config_path).ok();
            match config::ensure_agent_id(&config_path) {
                Ok(id) => {
                    actions.push(FixAction {
                        ol_code: crate::error::ERR_INVALID_CONFIG.to_string(),
                        kind: FixKind::AgentIdInsert,
                        file: config_path.clone(),
                        backup,
                        reversible: true,
                        applied_at: Utc::now(),
                        note: format!("inserted agent_id={id} into [daemon] section"),
                    });
                }
                Err(e) => {
                    tracing::warn!(error = %e.message, code = e.code, "doctor --fix: agent_id insert failed");
                }
            }
        }
    }

    // 4. telemetry.json — reset to a safe default if corrupt.
    //    Resetting to `enabled: false` requires re-consent via the next
    //    `openlatch init` invocation — never silently flips a user back
    //    to opted-in (telemetry.md invariant I9).
    let telem_path = ol_dir.join("telemetry.json");
    if telem_path.exists() {
        let valid = std::fs::read_to_string(&telem_path)
            .ok()
            .and_then(|raw| serde_json::from_str::<serde_json::Value>(&raw).ok())
            .is_some();
        if !valid {
            let backup = backup_file(&telem_path).ok();
            let reset = serde_json::json!({
                "enabled": false,
                "schema_version": 1,
                "notice_shown_at": null,
            });
            match serde_json::to_string_pretty(&reset)
                .map_err(std::io::Error::other)
                .and_then(|s| std::fs::write(&telem_path, s))
            {
                Ok(_) => {
                    actions.push(FixAction {
                        ol_code: crate::error::ERR_TELEMETRY_CONFIG_CORRUPT.to_string(),
                        kind: FixKind::TelemetryReset,
                        file: telem_path.clone(),
                        backup,
                        reversible: true,
                        applied_at: Utc::now(),
                        note: format!(
                            "reset {} to enabled=false (re-consent required via init)",
                            telem_path.display()
                        ),
                    });
                }
                Err(e) => {
                    tracing::warn!(error = %e, "doctor --fix: telemetry reset failed");
                }
            }
        }
    }

    // 5. daemon.pid — remove if PID no longer alive.
    let pid_path = ol_dir.join("daemon.pid");
    if pid_path.exists() {
        let pid_alive = std::fs::read_to_string(&pid_path)
            .ok()
            .and_then(|s| s.trim().parse::<u32>().ok())
            .map(lifecycle::is_process_alive)
            .unwrap_or(false);
        if !pid_alive {
            if let Err(e) = std::fs::remove_file(&pid_path) {
                tracing::warn!(error = %e, path = %pid_path.display(), "doctor --fix: stale PID removal failed");
            } else {
                actions.push(FixAction {
                    ol_code: crate::error::ERR_ALREADY_RUNNING.to_string(),
                    kind: FixKind::PidStaleRemove,
                    file: pid_path.clone(),
                    backup: None,
                    reversible: false,
                    applied_at: Utc::now(),
                    note: format!("removed stale {} (process not alive)", pid_path.display()),
                });
            }
        }
    }

    actions
}

/// Heal every detected agent's hook installation.
///
/// When no supported agent is detected, this is a no-op. When an agent is
/// present but its config is missing one of its own load-bearing entries, or
/// names a hook binary that does not resolve, the file is backed up and the
/// full hook set is reinstalled via the idempotent `hooks::install_hooks()`
/// (which preserves non-OpenLatch entries through the `_openlatch` marker
/// contract).
///
/// Re-reads `port` and `token` from the freshly-healed state files so
/// the rewrite always uses the canonical pair.
pub(crate) fn heal_hooks(ol_dir: &Path) -> Vec<FixAction> {
    heal_hooks_for(&hooks::detect_agents(), ol_dir)
}

/// The seam `heal_hooks` is a shim over.
///
/// `heal_hooks` resolves its agents internally, and the two tests that drive it
/// go through `CLAUDE_CONFIG_DIR` — which can only ever yield one agent, on a
/// build that detects one. Taking the slice is what lets a test state the
/// multi-agent case at all.
fn heal_hooks_for(detected: &[DetectedAgent], ol_dir: &Path) -> Vec<FixAction> {
    let mut actions = Vec::new();

    // An empty slice is the old `Err(_) => return actions` arm: OL-1400 is
    // surfaced by run_all_checks and there is no fix to apply. Notably NOT a
    // FixAction — and the return has to come before the reads below, which is
    // what today's early return also achieved.
    if detected.is_empty() {
        return actions;
    }

    let token_path = ol_dir.join("daemon.token");
    let token = match std::fs::read_to_string(&token_path) {
        Ok(s) if !s.trim().is_empty() => s.trim().to_string(),
        _ => {
            tracing::warn!(
                path = %token_path.display(),
                "doctor --fix: skipping hook reinstall — daemon.token missing/empty after heal_state"
            );
            return actions;
        }
    };

    let port = config::Config::load(None, None, false)
        .map(|c| c.port)
        .unwrap_or(config::PORT_RANGE_START);

    // Stage the binary before rewriting any command: reinstalling a command
    // that points at the same missing path would be a no-op repair.
    //
    // Hoisted, with the token and the port, above the per-agent work: all three
    // are per-INSTANCE facts, not per-agent ones. Re-reading `daemon.token`
    // once per agent is a second chance for two agents to be pinned to
    // different tokens, and a staging failure is a reason to leave the whole
    // host alone rather than the first agent of it.
    if let Err(e) = hooks::staging::stage_hook_binary(ol_dir) {
        tracing::warn!(
            error = %e.message,
            code = e.code,
            "doctor --fix: cannot stage hook binary — leaving hooks alone rather than rewriting a dead command"
        );
        return actions;
    }

    for agent in detected {
        // Never reinstall into an agent whose hook surface this build cannot
        // write. `install_hooks` refuses too, but reaching it is already too
        // late: `inspect_file` below reports a path we do not own as needing a
        // reinstall, `backup_file` then copies it, and `--fix` accumulates a
        // fresh `.bak` on every run for a file it will never repair. The
        // diagnostic that sent the user here skips this agent for the same
        // reason (`doctor.rs`'s `check_hooks`) — a diagnostic and its own fix
        // must not be allowed to disagree, and here they agree by both saying
        // nothing.
        if !agent.installable() {
            continue;
        }

        // And never through a path whose SHAPE is a directory. `inspect_file`
        // below reads and parses this as JSONC and `backup_file` copies it;
        // `Path::exists()` is true for a directory, so neither is a guard. A
        // directory surface gets the file-shaped repair instead, which shares
        // this loop's staged binary, token and port.
        let settings_path = match agent.hook_surface() {
            HookSurface::ConfigFile(path) => path,
            HookSurface::Directory(hooks_dir) => {
                if let Some(action) = heal_hook_files(agent, &hooks_dir, ol_dir, port, &token) {
                    actions.push(action);
                }
                continue;
            }
        };

        // Share the predicate with the diagnostic that sent the user here.
        //
        // This used to be four substring tests over the raw JSONC, which only
        // ever asked "is an entry present?". An entry that existed but pointed
        // at a binary that did not exist passed — so on the machine in #165,
        // `doctor` printed `ERR Hook binary missing: openlatch-hook` twelve
        // times and `--fix` staged the binary and left all twelve commands
        // untouched, because by its own test nothing was wrong. A diagnostic
        // and its own fix must not be allowed to disagree; `hooks::health` is
        // now the single answer.
        let needs_reinstall = match hooks::health::inspect_file(&settings_path, &*agent.binding) {
            Ok(health) => health.needs_reinstall(),
            Err(_) => true, // absent or unparseable → install_hooks rewrites it
        };

        // `continue`, never `return`. A healthy agent is a reason to move on to
        // the next one, not to end the walk: detection order puts Claude Code
        // first, so a bare return here would silently abandon every later agent
        // on the realistic dual-agent host — healthy Claude Code in front of the
        // broken agent the remedy told the user this command would repair.
        //
        // A healthy file can still be a hook the agent will not run: untrusted,
        // trusted for a command that has since changed, or switched off. The
        // liveness check sends the user here for exactly that, so the grant is
        // made here too. A reinstall below makes it on its own.
        if !needs_reinstall {
            match agent
                .binding
                .trust_own_hooks(hooks::binding::TrustOccasion::Install)
            {
                Ok(0) => {}
                Ok(granted) => actions.push(FixAction {
                    ol_code: crate::error::ERR_HOOK_NOT_ARMED.to_string(),
                    kind: FixKind::HookTrustGrant,
                    file: settings_path.clone(),
                    backup: None,
                    reversible: false,
                    applied_at: Utc::now(),
                    note: format!(
                        "trusted {granted} OpenLatch hook(s) in {}",
                        agent.binding.display_name()
                    ),
                }),
                Err(e) => tracing::warn!(
                    error = %e.message,
                    code = e.code,
                    "doctor --fix: could not grant the agent's trust to our hooks"
                ),
            }
            continue;
        }

        let backup = if settings_path.exists() {
            backup_file(&settings_path).ok()
        } else {
            None
        };

        match hooks::install_hooks(&*agent.binding, port, &token) {
            Ok(_) => {
                actions.push(FixAction {
                    ol_code: crate::error::ERR_HOOK_WRITE_FAILED.to_string(),
                    kind: FixKind::HookReinstall,
                    // The only thing naming WHICH agent this healed: `FixAction`
                    // has no agent field and gains none.
                    file: settings_path.clone(),
                    backup,
                    reversible: true,
                    applied_at: Utc::now(),
                    note: format!("reinstalled hooks in {}", settings_path.display()),
                });
            }
            Err(e) => {
                tracing::warn!(
                    error = %e.message,
                    code = e.code,
                    "doctor --fix: hook reinstall failed"
                );
            }
        }
    }

    actions
}

/// The `Directory` half of [`heal_hooks_for`]: rewrite the hook **scripts**
/// that are missing, foreign-occupied or no longer the bytes we wrote.
///
/// Shares the diagnostic that sent the user here — `health::inspect_directory`,
/// the same predicate `doctor`'s `check_hook_files` renders from — because a
/// diagnostic and its own fix disagreeing is the defect class this file exists
/// to prevent, and it does not stop being one because the surface is a
/// directory.
///
/// **The backup is per file and the installer makes it.** `hook_files::write_all`
/// copies each script it is about to rewrite to `<name>.bak` beside it, and it
/// only ever rewrites a script that satisfies the ownership predicate — a file
/// the developer put at one of our names is skipped, never backed up and never
/// overwritten. One `backup_file` call on the directory, which is what the
/// `ConfigFile` arm's shape would suggest, cannot express either half of that.
///
/// So the recorded action is **not reversible**, and deliberately:
/// `FixKind::HookReinstall` restores through `restore_hooks_surgical`, which
/// parses the `.bak` as JSONC and writes JSON to the live path — over a shell
/// script, that is not a rollback, it is the corruption the rollback was meant
/// to prevent. `restore_one` refuses an action with no backup before it reaches
/// the dispatch, so `backup: None` is the guard rather than a comment asking for
/// one. What a rollback here could restore is in any case only a *previous
/// shim of ours*; the developer's own files were never touched.
fn heal_hook_files(
    agent: &DetectedAgent,
    hooks_dir: &Path,
    ol_dir: &Path,
    port: u16,
    token: &str,
) -> Option<FixAction> {
    let descriptors = match crate::core::hook_state::HookStateFile::load(ol_dir) {
        Ok(Some(state)) => hooks::health::tracked_descriptors(&state, hooks_dir),
        Ok(None) => Default::default(),
        Err(_) => Default::default(),
    };

    let health = hooks::health::inspect_directory(hooks_dir, &*agent.binding, &descriptors);
    if !health.needs_reinstall() {
        return None;
    }

    match hooks::install_hooks(&*agent.binding, port, token) {
        Ok(result) => {
            // A reinstall that skipped a file did NOT resolve that file's drift.
            // `write_all` leaves anything failing the ownership predicate where
            // it is — which is the right thing to do with a file the developer
            // owns, and exactly what a tampered script looks like. The action is
            // still reported, because nine backups and nine rewrites did happen;
            // what must not happen is a note that reads like the drift is gone.
            // `needs_reinstall()` will still be true on the next run, and the
            // operator deserves to know why rather than watch `--fix` appear to
            // succeed forever.
            // `left_alone`, not a count against an agent-named constant — the
            // install is the only thing that knows which paths it refused.
            let incomplete = !result.left_alone.is_empty();
            if incomplete {
                tracing::warn!(
                    rewrote = result.entries.len(),
                    left_alone = ?result.left_alone,
                    dir = %hooks_dir.display(),
                    "doctor --fix: hook file reinstall INCOMPLETE — a file we do not own holds \
                     a hook name; its drift is unresolved"
                );
            }
            Some(FixAction {
                ol_code: crate::error::ERR_HOOK_WRITE_FAILED.to_string(),
                kind: FixKind::HookReinstall,
                // The only thing naming WHICH agent this healed: `FixAction` has no
                // agent field and gains none.
                file: hooks_dir.to_path_buf(),
                backup: None,
                reversible: false,
                applied_at: Utc::now(),
                note: if incomplete {
                    // Name the paths. A count tells the operator something is
                    // wrong; the paths tell them which files to go and look at.
                    format!(
                        "INCOMPLETE: rewrote {} hook script(s) in {}, and left {} alone \
                         because we did not write them — their drift is NOT resolved. \
                         Inspect them by hand, or remove them and re-run: {}",
                        result.entries.len(),
                        crate::core::path_compat::display_path(hooks_dir),
                        result.left_alone.len(),
                        result
                            .left_alone
                            .iter()
                            .map(|p| crate::core::path_compat::display_path(p))
                            .collect::<Vec<_>>()
                            .join(", ")
                    )
                } else {
                    format!(
                        "rewrote {} hook script(s) in {} (each replaced script backed up beside \
                         it as <name>.bak; files we did not write were left alone)",
                        result.entries.len(),
                        hooks_dir.display()
                    )
                },
            })
        }
        Err(e) => {
            tracing::warn!(
                error = %e.message,
                code = e.code,
                "doctor --fix: hook file reinstall failed"
            );
            None
        }
    }
}

/// Re-stage the `openlatch-hook` binary into the canonical install
/// location (`<ol_dir>/bin/openlatch-hook[.exe]`) when missing.
///
/// Thin wrapper over [`hooks::staging::stage_hook_binary`], which `init` calls
/// too — the staging itself must be one implementation, or the "canonical
/// install location" is only canonical on whichever path last touched it.
///
/// A failure records nothing rather than propagating: `--fix` applies what it
/// can and the post-fix diagnostics still surface the missing-binary check, so
/// the user gets a remediation hint instead of an aborted repair run.
pub(crate) fn heal_binaries(ol_dir: &Path) -> Vec<FixAction> {
    let mut actions = Vec::new();

    match hooks::staging::stage_hook_binary(ol_dir) {
        Ok(hooks::staging::StageOutcome::AlreadyStaged { .. }) => {}
        Ok(hooks::staging::StageOutcome::Staged { target, source }) => {
            actions.push(FixAction {
                ol_code: crate::error::ERR_HOOK_BINARY_UNRESOLVABLE.to_string(),
                kind: FixKind::BinaryCopy,
                file: target.clone(),
                backup: None, // freshly staged — no prior file to preserve
                reversible: true,
                applied_at: Utc::now(),
                note: format!("staged {} from {}", target.display(), source.display()),
            });
        }
        Err(e) => {
            tracing::warn!(
                error = %e.message,
                code = e.code,
                "doctor --fix: cannot stage hook binary"
            );
        }
    }

    actions
}

/// Reinstall the OS supervisor when config says `mode=active` but the OS
/// artifact (plist / unit / Task Scheduler task) is missing or predates this
/// binary's [`crate::supervision::UNIT_VERSION`] — a stale unit can be the
/// very thing keeping the daemon down (a v3 systemd unit fails every start on
/// a host without `~/.claude`). No-op in every other state — keep the fix
/// surgical so `--fix` never silently re-opts a user back into persistence
/// they disabled.
pub(crate) fn heal_supervision(ol_dir: &Path) -> Vec<FixAction> {
    use crate::supervision::{select_supervisor, SupervisionMode};
    let mut actions = Vec::new();

    let cfg = match config::Config::load(None, None, false) {
        Ok(c) => c,
        Err(_) => return actions,
    };

    if !matches!(cfg.supervision.mode, SupervisionMode::Active) {
        return actions;
    }

    let Some(supervisor) = select_supervisor() else {
        return actions;
    };

    let status_ok = supervisor
        .status()
        .map(|s| s.installed && s.unit_current)
        .unwrap_or(false);
    if status_ok {
        return actions;
    }

    let exe_path =
        std::env::current_exe().unwrap_or_else(|_| std::path::PathBuf::from("openlatch"));
    if let Err(e) = supervisor.install(&exe_path) {
        tracing::warn!(error = %e.message, code = %e.code, "doctor --fix: supervisor reinstall failed");
        return actions;
    }

    let config_path = ol_dir.join("config.toml");
    let _ = config::persist_supervision_state(
        &config_path,
        &SupervisionMode::Active,
        &supervisor.kind(),
        None,
    );

    actions.push(FixAction {
        ol_code: crate::supervision::ERR_SUPERVISION_INSTALL_FAILED.to_string(),
        kind: FixKind::SupervisionInstall,
        file: std::path::PathBuf::new(),
        backup: None,
        reversible: false,
        applied_at: Utc::now(),
        note: "Reinstalled missing or outdated OS supervisor (config said active)".to_string(),
    });

    actions
}

/// Job (a) of [`heal_relay_ca_with`]: the CA exists but the user store does not trust it (a
/// headless init, a refusal, a removed entry) → 02's `crate::daemon::ensure_proxy_env_trust(..)`
/// (the ONE install and its D-29 gate; no second copy here), read back with `store.is_trusted`
/// (D-29's "doctor --fix retries"). `None` when there is no CA, it is already trusted, or the
/// reinstall attempt did not take — S3: one early-return chain in place of three nested
/// `if`/`if let` levels.
#[cfg(feature = "model-relay")]
fn reinstall_relay_ca_if_untrusted(
    ol_dir: &Path,
    cfg: &config::Config,
    detected: &[DetectedAgent],
    owner: bool,
    store: &dyn crate::model_relay::trust_store::TrustStore,
) -> Option<FixAction> {
    use crate::model_relay::ca;

    let info = ca::inspect(&ca::ca_dir(ol_dir))?;
    if store.is_trusted(&info.sha256_hex).unwrap_or(false) {
        return None;
    }
    let _ = crate::daemon::ensure_proxy_env_trust(cfg, detected, owner);
    if !store.is_trusted(&info.sha256_hex).unwrap_or(false) {
        return None;
    }
    Some(FixAction {
        ol_code: crate::error::ERR_MODEL_RELAY_CA_UNTRUSTED.to_string(),
        kind: FixKind::RelayCaTrust,
        file: ca::ca_pem_path(&ca::ca_dir(ol_dir)),
        backup: None,
        reversible: false,
        applied_at: Utc::now(),
        note: format!(
            "Relay certificate authority (SHA-256 {}) installed into your user trust store.",
            info.sha256_hex
        ),
    })
}

/// Trust and rotation for the relay's CA (I-2 plan 04, D-29/D-31). Two jobs, in order:
/// (a) [`reinstall_relay_ca_if_untrusted`];
/// (b) inside `CA_WARN_DAYS`, **or whenever `ca_lifecycle::prev_dir(ol_dir)` exists** (a stuck
///     old root to retry) → `ca_lifecycle::rotate(..)` (D-31) — but only when the daemon is
///     CONFIRMED stopped (C2): it holds the old CA in memory, and rotation removes that root
///     from the trust store, which would otherwise leave a live daemon serving leaves nothing
///     trusts any more.
///
/// `owner` is the predicate `ensure_proxy_env_trust` applies: a detected ProxyEnv binding whose
/// wiring `owns_wiring_for`, and `supervision::owns_machine_supervision()`. `owner == false` →
/// zero store calls, with ONE carve-out: removing our own stale root is allowed whenever
/// `ca.prev/` exists — `ca_lifecycle::retire_prev` only, no install, no rotation. Every path is
/// best-effort — `run_all_checks` afterwards reports whatever is still wrong.
#[cfg(feature = "model-relay")]
pub(crate) fn heal_relay_ca(
    ol_dir: &Path,
    detected: &[DetectedAgent],
    now: time::OffsetDateTime,
    daemon_confirmed_stopped: bool,
) -> Vec<FixAction> {
    use crate::hooks::binding::EndpointConvention;

    if !crate::supervision::owns_machine_supervision() {
        return Vec::new(); // isolated-instance trap 4
    }
    let Ok(cfg) = config::Config::load(None, None, false) else {
        return Vec::new();
    };
    let owner = crate::supervision::owns_machine_supervision()
        && detected.iter().any(|a| {
            a.binding
                .model_relay_wiring()
                .is_some_and(|w| matches!(w.endpoint, EndpointConvention::ProxyEnv { .. }))
                && crate::daemon::owns_wiring_for(&cfg, &*a.binding)
        });
    heal_relay_ca_with(
        ol_dir,
        &cfg,
        detected,
        owner,
        now,
        &*crate::model_relay::trust_store::store(),
        &|staging| prove_in_runtime(detected, staging),
        daemon_confirmed_stopped,
    )
}

/// The logic [`heal_relay_ca`] wraps: takes an injected store and prove closure so tests never
/// touch a real trust store or spawn a real runtime.
#[cfg(feature = "model-relay")]
#[allow(clippy::too_many_arguments)]
pub(crate) fn heal_relay_ca_with(
    ol_dir: &Path,
    cfg: &config::Config,
    detected: &[DetectedAgent],
    owner: bool,
    now: time::OffsetDateTime,
    store: &dyn crate::model_relay::trust_store::TrustStore,
    prove: &dyn Fn(&Path) -> Result<(), String>,
    daemon_confirmed_stopped: bool,
) -> Vec<FixAction> {
    use crate::model_relay::{ca, ca_lifecycle};

    let mut actions = Vec::new();

    if !owner {
        // The ca.prev carve-out (04-35), nothing else: a host whose last ProxyEnv agent
        // vanished still gets its own stale root retried, never a fresh install or rotation.
        let _ = ca_lifecycle::retire_prev(ol_dir, store);
        return actions;
    }

    // (a) trust.
    actions.extend(reinstall_relay_ca_if_untrusted(
        ol_dir, cfg, detected, owner, store,
    ));

    // (b) rotation — skipped (C2) when the daemon could not be confirmed stopped. A live daemon
    // never re-reads the CA (D-06), so it would keep serving the OLD root's leaves after
    // rotation removes that very root from the trust store underneath it.
    if !daemon_confirmed_stopped {
        // A note only when rotation would plausibly have run — the same two gates `rotate`
        // itself checks (a stuck previous root, or inside the warning window) — so an
        // untouched, healthy CA never earns a "skipped" line nobody asked for.
        let due = ca::inspect(&ca_lifecycle::prev_dir(ol_dir)).is_some()
            || ca::inspect(&ca::ca_dir(ol_dir))
                .is_some_and(|info| ca_lifecycle::days_left(&info, now) <= ca::CA_WARN_DAYS);
        if due {
            actions.push(FixAction {
                ol_code: crate::error::ERR_MODEL_RELAY_CA_UNTRUSTED.to_string(),
                kind: FixKind::RelayCaRotateSkipped,
                file: ca::ca_pem_path(&ca::ca_dir(ol_dir)),
                backup: None,
                reversible: false,
                applied_at: Utc::now(),
                note: "Relay certificate authority rotation is due but was skipped: the daemon \
                       could not be confirmed stopped, and rotating under a live daemon would \
                       leave it serving leaves the trust store no longer trusts. Stop \
                       `openlatch` and run `openlatch doctor --fix` again."
                    .to_string(),
            });
        }
        return actions;
    }

    // `rotate` itself now names step 5's stuck-old-root case (S1: `RotateOutcome::
    // PromotedButStuck`), so there is no before/after `ca::inspect` to compare here any more —
    // a plain I/O `Failed` and a promoted-but-stuck rotation are two different variants, not two
    // shapes of the same one.
    match ca_lifecycle::rotate(ol_dir, store, prove, now) {
        ca_lifecycle::RotateOutcome::NotDue => {}
        ca_lifecycle::RotateOutcome::Rotated { old_sha, new_sha } => {
            actions.push(FixAction {
                ol_code: crate::error::ERR_MODEL_RELAY_CA_UNTRUSTED.to_string(),
                kind: FixKind::RelayCaRotate,
                file: ca::ca_pem_path(&ca::ca_dir(ol_dir)),
                backup: None,
                reversible: false,
                applied_at: Utc::now(),
                note: format!(
                    "Relay certificate authority rotated (was {old_sha}, now {new_sha}). \
                     Restart any CLI agent launched before now. It read the previous \
                     certificate at start."
                ),
            });
        }
        ca_lifecycle::RotateOutcome::PromotedButStuck {
            old_sha,
            new_sha,
            why,
        } => {
            // The promotion completed but the old root's removal was refused — the live CA
            // already changed, so the restart remedy must still print and `touched_critical`
            // must still restart the daemon.
            actions.push(FixAction {
                ol_code: crate::error::ERR_MODEL_RELAY_CA_UNTRUSTED.to_string(),
                kind: FixKind::RelayCaRotate,
                file: ca::ca_pem_path(&ca::ca_dir(ol_dir)),
                backup: None,
                reversible: false,
                applied_at: Utc::now(),
                note: format!(
                    "Relay certificate authority rotated (was {old_sha}, now {new_sha}), but the \
                     previous certificate authority is still trusted — {why}"
                ),
            });
        }
        ca_lifecycle::RotateOutcome::InstallDeclined(why) => {
            tracing::warn!(
                reason = %why,
                "doctor --fix: the rotated certificate authority was declined by the trust store"
            );
        }
        ca_lifecycle::RotateOutcome::ProofFailed(_why) => {
            // `why` is never echoed: `prove_store`'s remedy names the LIVE CA's install
            // command, and the CA that failed was the staged one. It may still be on disk
            // (C1: `ca.next/` is kept when its removal from the store was refused), in which
            // case the next rotation attempt retires it before minting a fresh one.
            tracing::warn!(
                "doctor --fix: the new certificate authority could not be proven; nothing changed"
            );
        }
        ca_lifecycle::RotateOutcome::Failed(why) => {
            tracing::warn!(
                reason = %why,
                "doctor --fix: certificate authority rotation failed"
            );
        }
    }

    actions
}

/// The production `prove` closure [`heal_relay_ca`] hands to [`ca_lifecycle::rotate`]: a
/// current-thread runtime (precedent: `crate::cli::commands::update`'s update check), the
/// loaded config, and an in-process relay proving the staged CA against every ProxyEnv
/// binding's first intercept host.
#[cfg(feature = "model-relay")]
fn prove_in_runtime(detected: &[DetectedAgent], staging: &Path) -> Result<(), String> {
    use crate::hooks::binding::EndpointConvention;

    let targets: Vec<(crate::model_relay::wire_format::WireFormat, &'static str)> = detected
        .iter()
        .filter_map(|a| {
            let w = a.binding.model_relay_wiring()?;
            match w.endpoint {
                EndpointConvention::ProxyEnv {
                    intercept_hosts, ..
                } => intercept_hosts.first().map(|h| (w.wire_format, *h)),
                _ => None,
            }
        })
        .collect();
    if targets.is_empty() {
        return Ok(());
    }

    let rt = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .map_err(|e| e.to_string())?;
    rt.block_on(async {
        let cfg = config::Config::load(None, None, false).map_err(|e| e.message)?;
        let upstream = cfg.model_relay.upstream_for(targets[0].0);
        let upstream_url = reqwest::Url::parse(&upstream).map_err(|e| e.to_string())?;
        let state = crate::model_relay::ModelRelayState::new_with_egress(
            upstream_url,
            0,
            8,
            &[],
            &cfg.egress,
        );
        crate::model_relay::ca_lifecycle::prove_with_ephemeral_relay(
            &cfg,
            state,
            staging,
            &targets,
            &*crate::model_relay::trust_store::store(),
        )
        .await
    })
}

/// Copy `path` to a sibling `<filename>.bak`, returning the backup path.
///
/// Single-level backup — overwrites any prior `.bak`. Multi-level history
/// is intentionally not kept (disk cost outweighs value; the journal
/// itself records intent and timestamps).
pub(crate) fn backup_file(path: &Path) -> Result<PathBuf, OlError> {
    let bak = bak_path_for(path);
    std::fs::copy(path, &bak).map_err(|e| {
        OlError::new(
            crate::error::ERR_INVALID_CONFIG,
            format!(
                "cannot create backup '{}' for '{}': {e}",
                bak.display(),
                path.display()
            ),
        )
    })?;
    Ok(bak)
}

/// Compute the `.bak` sibling path for an arbitrary file path.
///
/// Appends `.bak` to the file name (preserving any existing extension):
/// `config.toml` → `config.toml.bak`, `daemon.token` → `daemon.token.bak`.
pub(crate) fn bak_path_for(path: &Path) -> PathBuf {
    let mut bak = path.to_path_buf();
    let new_name = match path.file_name() {
        Some(name) => format!("{}.bak", name.to_string_lossy()),
        None => "unknown.bak".to_string(),
    };
    bak.set_file_name(new_name);
    bak
}

/// Render the fix run as either a JSON object (for scripting) or a
/// before/after delta (for human consumption).
fn print_fix_results(
    journal: &Journal,
    journal_path: &Path,
    before: Option<&DoctorReport>,
    after: &DoctorReport,
    auto_rollback_triggered: bool,
    output: &OutputConfig,
) {
    let unresolved = after.unresolved();
    let unfixable: Vec<&str> = unresolved.iter().map(String::as_str).collect();

    if output.format == OutputFormat::Json {
        let actions_json: Vec<serde_json::Value> = journal
            .actions
            .iter()
            .map(|a| {
                serde_json::json!({
                    "ol_code": a.ol_code,
                    "kind": a.kind,
                    "file": a.file.display().to_string(),
                    "backup": a.backup.as_ref().map(|p| p.display().to_string()),
                    "reversible": a.reversible,
                    "applied_at": a.applied_at,
                    "note": a.note,
                })
            })
            .collect();
        let backups: Vec<String> = journal
            .actions
            .iter()
            .filter_map(|a| a.backup.as_ref().map(|p| p.display().to_string()))
            .collect();
        let exit_code = if after.all_pass() && !auto_rollback_triggered {
            0
        } else {
            1
        };
        output.print_json(&serde_json::json!({
            "command": "doctor_fix",
            "run_id": journal.run_id,
            "started_at": journal.started_at,
            "journal_path": journal_path.display().to_string(),
            "checks_before": before.map(|r| serde_json::json!({
                "pass": r.pass_count(),
                "fail": r.fail_count(),
            })),
            "checks_after": serde_json::json!({
                "pass": after.pass_count(),
                "fail": after.fail_count(),
            }),
            "fixes_applied": actions_json,
            "fixes_count": journal.actions.len(),
            "unfixable": unfixable,
            "backups": backups,
            "auto_rollback_triggered": auto_rollback_triggered,
            "exit_code": exit_code,
        }));
        return;
    }

    if output.quiet {
        return;
    }

    print_diagnostic_results(after, output);

    if auto_rollback_triggered {
        eprintln!();
        eprintln!("Fix attempted but daemon failed to restart — rolled back to pre-fix state.");
        eprintln!("  Run `openlatch doctor --rescue` to file a bug with diagnostics.");
        return;
    }

    if !journal.actions.is_empty() {
        eprintln!();
        eprintln!("Fixes applied ({}):", journal.actions.len());
        for action in &journal.actions {
            eprintln!("  • {} [{}]", action.note, action.ol_code);
        }
        let backups: Vec<String> = journal
            .actions
            .iter()
            .filter_map(|a| a.backup.as_ref().map(|p| p.display().to_string()))
            .collect();
        if !backups.is_empty() {
            eprintln!();
            eprintln!("Backups created: {}", backups.join(", "));
            eprintln!("Roll back with: openlatch doctor --restore");
        }
    }

    eprintln!();
    if after.all_pass() {
        eprintln!(
            "Summary: {} fix{} applied, 0 issues remaining.",
            journal.actions.len(),
            if journal.actions.len() == 1 { "" } else { "es" }
        );
    } else {
        eprintln!(
            "Summary: {} fix{} applied, {} issue{} remaining.",
            journal.actions.len(),
            if journal.actions.len() == 1 { "" } else { "es" },
            after.fail_count(),
            if after.fail_count() == 1 { "" } else { "s" }
        );
    }
}

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

    // Env vars are process-global and `cargo test` runs tests in parallel
    // threads of ONE process, so two tests mutating OPENLATCH_HOOK_BIN clobber
    // each other: whichever sets it second wins, and the first sees the wrong
    // value (or a removal) mid-run. This failed non-deterministically under the
    // default parallel runner while passing under --test-threads=1, which reads
    // as flake rather than a race. Same pattern as core::telemetry::consent and
    // core::config.
    // ONE lock per process-wide variable, not one per module. This used to be a
    // private mutex here, which was correct while it was the only writer in this
    // binary. It is not any more: the Codex install tests in `hooks::mod` mutate
    // the same `OPENLATCH_HOOK_BIN` under `staging::HOOK_BIN_ENV_LOCK`, and two
    // different mutexes guarding one variable serialise nothing — the exact shape
    // commit 696687b already had to fix once. Aliasing rather than deleting keeps
    // every `ENV_LOCK.lock()` site below reading the same, and makes the sharing a
    // single line rather than six.
    use crate::hooks::staging::HOOK_BIN_ENV_LOCK as ENV_LOCK;
    use tempfile::TempDir;

    fn empty_dir() -> TempDir {
        TempDir::new().expect("tempdir must be created")
    }

    // -----------------------------------------------------------------------
    // heal_relay_ca(_with) — I-2 plan 04 §2.2
    // -----------------------------------------------------------------------

    /// S5: the bespoke `RecordingStore` this used to declare is gone — every field and method it
    /// had (an ordered call log, a per-SHA removal-refusal set, `trust`/`trusted_directly`/
    /// `set_install_outcome`/`refuse_removal_of`/`allow_removal_of`) now lives on
    /// [`crate::model_relay::trust_store::test_support::FakeStore`] itself, so this fixture uses
    /// that directly. Never a real OS store.
    #[cfg(feature = "model-relay")]
    use crate::model_relay::trust_store::test_support::FakeStore;

    /// A ProxyEnv agent for the `heal_relay_ca_with` fixtures — `owns_wiring_for` reads
    /// `Config::defaults()`'s default port, so this fake needs nothing beyond the wiring itself.
    #[cfg(feature = "model-relay")]
    fn proxy_env_fake_agent() -> DetectedAgent {
        use crate::hooks::binding::test_support::proxy_env_wiring;
        use crate::hooks::binding::ProxyDelivery;
        const DELIVERY: &[ProxyDelivery] = &[ProxyDelivery::EnvFile {
            commands: &["fakecli"],
        }];
        DetectedAgent {
            kind: crate::hooks::AgentKind::ClaudeCode,
            binding: std::sync::Arc::new(crate::hooks::binding::test_support::FakeBinding {
                agent_type: "fake-relay-agent",
                display_name: "Fake",
                model_relay_wiring: Some(proxy_env_wiring(&["a.test"], DELIVERY)),
                ..Default::default()
            }),
        }
    }

    /// Relocates `OPENLATCH_DIR` to `dir` under the documented lock chain (this test never
    /// touches Claude Code/Codex/Cline seams, so `OPENLATCH_DIR_ENV_LOCK` is the only env lock
    /// needed before the trust-store guard, taken last). `ensure_proxy_env_trust` — reached
    /// through job (a) — reads `config::openlatch_dir()` directly, so the CA on disk at `dir`
    /// must be the same one `heal_relay_ca_with`'s own `ol_dir` parameter names.
    ///
    /// S4: field order is drop order for a struct (declaration order, first-to-last). Three
    /// constraints, together: the trust-store guard drops FIRST (it was acquired LAST, the
    /// documented LIFO order every other fixture in this crate follows); `_env` must drop
    /// BEFORE `_dir_lock` releases the lock; and `_ol_dir` must outlive `_env` (its path is what
    /// `_env` restores away from) — `EnvOverride` restores on unwind too, which the hand-rolled
    /// `set_var`/no-restore this replaced never did.
    #[cfg(feature = "model-relay")]
    struct RelayCaFixture {
        _trust_guard: crate::model_relay::trust_store::TrustStoreGuard,
        _env: crate::hooks::cline::EnvOverride,
        _ol_dir: TempDir,
        _dir_lock: std::sync::MutexGuard<'static, ()>,
        store: std::sync::Arc<FakeStore>,
    }

    #[cfg(feature = "model-relay")]
    impl RelayCaFixture {
        fn new() -> Self {
            let _dir_lock = crate::config::OPENLATCH_DIR_ENV_LOCK
                .lock()
                .unwrap_or_else(|e| e.into_inner());
            let ol_dir = TempDir::new().expect("tempdir");
            let _env = crate::hooks::cline::EnvOverride::apply([(
                "OPENLATCH_DIR",
                Some(ol_dir.path().as_os_str().to_os_string()),
            )]);
            let store = std::sync::Arc::new(FakeStore::default());
            let _trust_guard = crate::model_relay::trust_store::install_for_tests(store.clone());
            Self {
                _trust_guard,
                _env,
                _ol_dir: ol_dir,
                _dir_lock,
                store,
            }
        }

        fn ol_dir(&self) -> &Path {
            self._ol_dir.path()
        }
    }

    #[test]
    #[cfg(feature = "model-relay")]
    fn rotation_is_a_no_op_outside_the_warning_window() {
        let fx = RelayCaFixture::new();
        let ca_dir = crate::model_relay::ca::ca_dir(fx.ol_dir());
        let old = crate::model_relay::ca::LocalCa::generate_into(&ca_dir).expect("generate");
        fx.store.trust(&old.sha256_hex());
        let now = old.not_after() - time::Duration::days(60);
        let cfg = config::Config::defaults();
        let detected = [proxy_env_fake_agent()];

        let actions = heal_relay_ca_with(
            fx.ol_dir(),
            &cfg,
            &detected,
            true,
            now,
            &*fx.store,
            &|_| Ok(()),
            true,
        );

        assert_eq!(
            fx.store.calls(),
            vec![("is_trusted", old.sha256_hex())],
            "outside the window, only job (a)'s trust check may touch the store"
        );
        assert!(actions.is_empty(), "nothing to do outside the window");
    }

    #[test]
    #[cfg(feature = "model-relay")]
    fn an_untrusted_ca_is_reinstalled_by_fix() {
        let cfg = config::Config::defaults();

        // -- untrusted: install is called, and one RelayCaTrust action returned -----
        // Scoped so `fx`'s `OPENLATCH_DIR_ENV_LOCK` guard drops before the control below
        // takes it again — the mutex is not reentrant.
        {
            let fx = RelayCaFixture::new();
            let ca_dir = crate::model_relay::ca::ca_dir(fx.ol_dir());
            let old = crate::model_relay::ca::LocalCa::generate_into(&ca_dir).expect("generate");
            let now = old.not_after() - time::Duration::days(300); // well outside CA_WARN_DAYS
            let detected = [proxy_env_fake_agent()];

            let actions = heal_relay_ca_with(
                fx.ol_dir(),
                &cfg,
                &detected,
                true,
                now,
                &*fx.store,
                &|_| Ok(()),
                true,
            );

            assert_eq!(
                actions.len(),
                1,
                "the reinstall must be recorded: {actions:?}"
            );
            assert_eq!(actions[0].kind, FixKind::RelayCaTrust);
            assert!(fx
                .store
                .calls()
                .iter()
                .any(|(m, sha)| *m == "install" && sha == &old.sha256_hex()));
        }

        // -- control: already trusted, no install call, no action ------------------
        {
            let fx2 = RelayCaFixture::new();
            let ca_dir2 = crate::model_relay::ca::ca_dir(fx2.ol_dir());
            let old2 = crate::model_relay::ca::LocalCa::generate_into(&ca_dir2).expect("generate");
            fx2.store.trust(&old2.sha256_hex());
            let now2 = old2.not_after() - time::Duration::days(300);
            let detected2 = [proxy_env_fake_agent()];

            let actions2 = heal_relay_ca_with(
                fx2.ol_dir(),
                &cfg,
                &detected2,
                true,
                now2,
                &*fx2.store,
                &|_| Ok(()),
                true,
            );

            assert!(
                !fx2.store.calls().iter().any(|(m, _)| *m == "install"),
                "an already-trusted CA must never be reinstalled"
            );
            assert!(actions2.is_empty());
        }
    }

    #[test]
    #[cfg(feature = "model-relay")]
    fn heal_relay_ca_is_a_no_op_without_the_owner() {
        let cfg = config::Config::defaults();

        // -- no ca.prev: zero calls, no action --------------------------------------
        // Scoped so `fx`'s `OPENLATCH_DIR_ENV_LOCK` guard drops before the carve-out
        // case below takes it again — the mutex is not reentrant.
        {
            let fx = RelayCaFixture::new();
            let ca_dir = crate::model_relay::ca::ca_dir(fx.ol_dir());
            let old = crate::model_relay::ca::LocalCa::generate_into(&ca_dir).expect("generate");
            let now = old.not_after() - time::Duration::days(20);
            let detected = [proxy_env_fake_agent()];

            let actions = heal_relay_ca_with(
                fx.ol_dir(),
                &cfg,
                &detected,
                false,
                now,
                &*fx.store,
                &|_| Ok(()),
                true,
            );

            assert!(
                fx.store.calls().is_empty(),
                "no owner, no ca.prev — the store must never be touched: {:?}",
                fx.store.calls()
            );
            assert!(actions.is_empty());
        }

        // -- the ca.prev carve-out: retry the removal, nothing else -----------------
        {
            let fx2 = RelayCaFixture::new();
            let ca_dir2 = crate::model_relay::ca::ca_dir(fx2.ol_dir());
            let live = crate::model_relay::ca::LocalCa::generate_into(&ca_dir2).expect("generate");
            let prev_dir = crate::model_relay::ca_lifecycle::prev_dir(fx2.ol_dir());
            let prev = crate::model_relay::ca::LocalCa::generate_into(&prev_dir).expect("generate");
            fx2.store.trust(&prev.sha256_hex());
            let now2 = live.not_after() - time::Duration::days(20);
            let detected2 = [proxy_env_fake_agent()];

            let actions2 = heal_relay_ca_with(
                fx2.ol_dir(),
                &cfg,
                &detected2,
                false,
                now2,
                &*fx2.store,
                &|_| Ok(()),
                true,
            );

            assert_eq!(
                fx2.store.calls(),
                vec![
                    ("remove", prev.sha256_hex()),
                    ("is_trusted", prev.sha256_hex()),
                ],
                "the carve-out retries the stuck removal and nothing more"
            );
            assert!(!prev_dir.exists(), "ca.prev must be gone once retired");
            assert!(actions2.is_empty());
        }
    }

    #[test]
    #[cfg(feature = "model-relay")]
    fn rotation_promotes_only_after_install_and_proof() {
        let fx = RelayCaFixture::new();
        let ca_dir = crate::model_relay::ca::ca_dir(fx.ol_dir());
        let old = crate::model_relay::ca::LocalCa::generate_into(&ca_dir).expect("generate");
        fx.store.trust(&old.sha256_hex());
        let now = old.not_after() - time::Duration::days(20); // inside CA_WARN_DAYS, outside CA_RELEASE_DAYS
        let cfg = config::Config::defaults();
        let detected = [proxy_env_fake_agent()];

        let actions = heal_relay_ca_with(
            fx.ol_dir(),
            &cfg,
            &detected,
            true,
            now,
            &*fx.store,
            &|_| Ok(()),
            true,
        );

        let calls = fx.store.calls();
        let new_sha = calls
            .iter()
            .find(|(m, _)| *m == "install")
            .map(|(_, s)| s.clone())
            .expect("rotation must install the new CA");
        assert_eq!(
            calls,
            vec![
                ("is_trusted", old.sha256_hex()),
                ("install", new_sha.clone()),
                ("remove", old.sha256_hex()),
                ("is_trusted", old.sha256_hex()),
            ],
            "the exact rotation call order"
        );
        let now_info = crate::model_relay::ca::inspect(&ca_dir).expect("ca.pem must exist");
        assert_eq!(now_info.sha256_hex, new_sha);
        assert!(
            !crate::model_relay::ca_lifecycle::staging_dir(fx.ol_dir()).exists(),
            "ca.next must be gone after a clean rotation"
        );
        assert_eq!(
            actions
                .iter()
                .filter(|a| a.kind == FixKind::RelayCaRotate)
                .count(),
            1
        );
    }

    #[test]
    #[cfg(feature = "model-relay")]
    fn a_failed_proof_keeps_the_old_ca_and_takes_back_the_new_trust() {
        let fx = RelayCaFixture::new();
        let ca_dir = crate::model_relay::ca::ca_dir(fx.ol_dir());
        let old = crate::model_relay::ca::LocalCa::generate_into(&ca_dir).expect("generate");
        fx.store.trust(&old.sha256_hex());
        let now = old.not_after() - time::Duration::days(20);
        let cfg = config::Config::defaults();
        let detected = [proxy_env_fake_agent()];

        let actions = heal_relay_ca_with(
            fx.ol_dir(),
            &cfg,
            &detected,
            true,
            now,
            &*fx.store,
            &|_| Err("proof failed (fixture)".to_string()),
            true,
        );

        let calls = fx.store.calls();
        let new_sha = calls
            .iter()
            .find(|(m, _)| *m == "install")
            .map(|(_, s)| s.clone())
            .expect("the staged CA is still installed before proof runs");
        assert!(
            calls.contains(&("remove", new_sha.clone())),
            "a failed proof must take back only what THIS run added: {calls:?}"
        );
        assert!(
            !calls.contains(&("remove", old.sha256_hex())),
            "the old CA must never be touched on a failed proof: {calls:?}"
        );
        let now_info = crate::model_relay::ca::inspect(&ca_dir).expect("ca.pem must exist");
        assert_eq!(
            now_info.sha256_hex,
            old.sha256_hex(),
            "the old CA is still the live one"
        );
        assert!(!crate::model_relay::ca_lifecycle::staging_dir(fx.ol_dir()).exists());
        assert!(
            actions.is_empty(),
            "a failed proof takes no reportable action"
        );
    }

    #[test]
    #[cfg(feature = "model-relay")]
    fn a_declined_install_changes_nothing() {
        use crate::model_relay::trust_store::InstallOutcome;

        for outcome in [
            InstallOutcome::NoGuiSession,
            InstallOutcome::Refused("no".to_string()),
        ] {
            let fx = RelayCaFixture::new();
            let ca_dir = crate::model_relay::ca::ca_dir(fx.ol_dir());
            let old = crate::model_relay::ca::LocalCa::generate_into(&ca_dir).expect("generate");
            fx.store.trust(&old.sha256_hex()); // job (a) is a no-op; this run is about job (b)
            fx.store.set_install_outcome(outcome.clone());
            let now = old.not_after() - time::Duration::days(20);
            let cfg = config::Config::defaults();
            let detected = [proxy_env_fake_agent()];
            let prove_calls = std::sync::atomic::AtomicUsize::new(0);

            let actions = heal_relay_ca_with(
                fx.ol_dir(),
                &cfg,
                &detected,
                true,
                now,
                &*fx.store,
                &|_| {
                    prove_calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                    Ok(())
                },
                true,
            );

            assert_eq!(
                prove_calls.load(std::sync::atomic::Ordering::SeqCst),
                0,
                "a declined install must never reach the proof step, for {outcome:?}"
            );
            assert!(
                !fx.store.calls().iter().any(|(m, _)| *m == "remove"),
                "nothing was promoted, so nothing may be removed, for {outcome:?}"
            );
            let now_info = crate::model_relay::ca::inspect(&ca_dir).expect("ca.pem must exist");
            assert_eq!(
                now_info.sha256_hex,
                old.sha256_hex(),
                "the old CA is intact, for {outcome:?}"
            );
            assert!(actions.is_empty(), "no action, for {outcome:?}");
        }
    }

    #[test]
    #[cfg(feature = "model-relay")]
    fn a_refused_old_root_removal_keeps_ca_prev_and_the_next_run_retries_it() {
        let fx = RelayCaFixture::new();
        let ca_dir = crate::model_relay::ca::ca_dir(fx.ol_dir());
        let old = crate::model_relay::ca::LocalCa::generate_into(&ca_dir).expect("generate");
        fx.store.trust(&old.sha256_hex());
        fx.store.refuse_removal_of(&old.sha256_hex());
        let now = old.not_after() - time::Duration::days(20);
        let cfg = config::Config::defaults();
        let detected = [proxy_env_fake_agent()];

        // -- run 1: the promotion completes, but the old root is stuck --------------
        let actions = heal_relay_ca_with(
            fx.ol_dir(),
            &cfg,
            &detected,
            true,
            now,
            &*fx.store,
            &|_| Ok(()),
            true,
        );
        let calls = fx.store.calls();
        let new_sha = calls
            .iter()
            .find(|(m, _)| *m == "install")
            .map(|(_, s)| s.clone())
            .expect("the new CA is installed before the stuck removal");
        assert_eq!(
            calls,
            vec![
                ("is_trusted", old.sha256_hex()),
                ("install", new_sha.clone()),
                ("remove", old.sha256_hex()),
            ],
            "the refused remove short-circuits the read-back in the SAME expression"
        );
        assert_eq!(
            actions
                .iter()
                .filter(|a| a.kind == FixKind::RelayCaRotate)
                .count(),
            1,
            "the stuck-root case still reports one action, never silently"
        );
        assert!(
            actions[0].note.contains(old.sha256_hex().as_str())
                && actions[0].note.contains(new_sha.as_str())
        );
        let prev_dir = crate::model_relay::ca_lifecycle::prev_dir(fx.ol_dir());
        assert!(prev_dir.exists(), "ca.prev must be kept for the next run");
        let live_info = crate::model_relay::ca::inspect(&ca_dir).expect("ca.pem must exist");
        assert_eq!(
            live_info.sha256_hex, new_sha,
            "ca/ already holds the NEW CA"
        );
        assert!(
            fx.store.trusted_directly(&old.sha256_hex()),
            "the old root is still trusted"
        );
        assert!(
            fx.store.trusted_directly(&new_sha),
            "the new root is trusted"
        );

        // -- run 2: the store now accepts the removal; only ca.prev/ sends it to rotate --
        fx.store.allow_removal_of(&old.sha256_hex());
        let new_info =
            crate::model_relay::ca::inspect(&ca_dir).expect("ca.pem must exist after run 1");
        let now2 = new_info.not_after - time::Duration::days(60); // outside the window for the NEW CA
        let actions2 = heal_relay_ca_with(
            fx.ol_dir(),
            &cfg,
            &detected,
            true,
            now2,
            &*fx.store,
            &|_| Ok(()),
            true,
        );
        assert!(
            actions2.is_empty(),
            "job (a) sees the new CA already trusted; job (b) is NotDue outside its own window: {actions2:?}"
        );
        assert!(!prev_dir.exists(), "ca.prev must be gone once retired");
        assert!(
            !crate::model_relay::ca_lifecycle::staging_dir(fx.ol_dir()).exists(),
            "run 2 must mint nothing"
        );
        let final_info = crate::model_relay::ca::inspect(&ca_dir).expect("ca.pem must exist");
        assert_eq!(
            final_info.sha256_hex, new_sha,
            "run 2 rotates nothing further"
        );
    }

    /// C2 (adversarial review): a live daemon still holds the OLD CA in memory (D-06 reads it
    /// once per process), so rotating while `doctor --fix` failed to confirm it stopped would
    /// remove that very root from the trust store out from under it. Job (a) still runs; job
    /// (b) never reaches `rotate` at all — proven here with a `prove` closure that panics if
    /// called — and reports the skip so it is never silent.
    #[test]
    #[cfg(feature = "model-relay")]
    fn rotation_is_skipped_when_the_daemon_is_not_confirmed_stopped() {
        let fx = RelayCaFixture::new();
        let ca_dir = crate::model_relay::ca::ca_dir(fx.ol_dir());
        let old = crate::model_relay::ca::LocalCa::generate_into(&ca_dir).expect("generate");
        fx.store.trust(&old.sha256_hex()); // job (a) is a no-op; this run is about job (b)
        let cfg = config::Config::defaults();
        let detected = [proxy_env_fake_agent()];

        // -- inside the window: rotation is due, so the skip must be reported ------
        let now = old.not_after() - time::Duration::days(20);
        let actions = heal_relay_ca_with(
            fx.ol_dir(),
            &cfg,
            &detected,
            true,
            now,
            &*fx.store,
            &|_| panic!("a skipped rotation must never reach the proof step"),
            false, // daemon NOT confirmed stopped
        );
        assert!(
            !fx.store.calls().iter().any(|(m, _)| *m == "install"),
            "rotation must never mint or install a new CA while the daemon might still be \
             alive: {:?}",
            fx.store.calls()
        );
        assert_eq!(
            actions.len(),
            1,
            "the skip must be reported, never silently: {actions:?}"
        );
        assert_eq!(actions[0].kind, FixKind::RelayCaRotateSkipped);
        let now_info = crate::model_relay::ca::inspect(&ca_dir).expect("ca.pem must exist");
        assert_eq!(
            now_info.sha256_hex,
            old.sha256_hex(),
            "the old CA is untouched"
        );

        // -- control: outside the window, rotation was never due — nothing to skip --
        let far_now = old.not_after() - time::Duration::days(60);
        let actions2 = heal_relay_ca_with(
            fx.ol_dir(),
            &cfg,
            &detected,
            true,
            far_now,
            &*fx.store,
            &|_| panic!("must never prove outside the window either"),
            false,
        );
        assert!(
            actions2.is_empty(),
            "outside the window there was nothing rotation would have done: {actions2:?}"
        );
    }

    #[test]
    fn test_bak_path_for_appends_bak_suffix() {
        let p = Path::new("/tmp/config.toml");
        assert_eq!(bak_path_for(p), Path::new("/tmp/config.toml.bak"));
    }

    #[test]
    fn test_bak_path_for_handles_no_extension() {
        let p = Path::new("/tmp/daemon.token");
        assert_eq!(bak_path_for(p), Path::new("/tmp/daemon.token.bak"));
    }

    #[test]
    fn test_backup_file_round_trip() {
        let tmp = empty_dir();
        let src = tmp.path().join("config.toml");
        std::fs::write(&src, "port = 7443\n").unwrap();
        let bak = backup_file(&src).expect("backup must succeed");
        assert_eq!(bak, src.with_file_name("config.toml.bak"));
        assert_eq!(std::fs::read_to_string(&bak).unwrap(), "port = 7443\n");
    }

    #[test]
    fn test_heal_state_creates_config_when_missing() {
        let tmp = empty_dir();
        let actions = heal_state(tmp.path());
        let config_path = tmp.path().join("config.toml");
        assert!(config_path.exists(), "config.toml must be created");
        assert!(
            actions
                .iter()
                .any(|a| a.kind == FixKind::ConfigRewrite && a.backup.is_none()),
            "expected ConfigRewrite action with no backup (no prior file)"
        );
    }

    #[test]
    fn test_heal_state_rewrites_corrupt_config_with_backup() {
        let tmp = empty_dir();
        let config_path = tmp.path().join("config.toml");
        std::fs::write(&config_path, "this is not valid TOML {{{").unwrap();
        let actions = heal_state(tmp.path());
        let bak = config_path.with_file_name("config.toml.bak");
        assert!(bak.exists(), ".bak must be created for corrupt config");
        // After rewrite the config must parse
        let raw = std::fs::read_to_string(&config_path).unwrap();
        assert!(toml::from_str::<toml::Value>(&raw).is_ok());
        assert!(actions
            .iter()
            .any(|a| a.kind == FixKind::ConfigRewrite && a.backup.is_some()));
    }

    #[test]
    fn test_heal_state_regenerates_missing_token() {
        let tmp = empty_dir();
        let token_path = tmp.path().join("daemon.token");
        let actions = heal_state(tmp.path());
        assert!(token_path.exists(), "token must be regenerated");
        let token = std::fs::read_to_string(&token_path).unwrap();
        assert_eq!(token.trim().len(), 64, "token must be 64 hex chars");
        assert!(actions.iter().any(|a| a.kind == FixKind::TokenRegenerate));
    }

    #[test]
    fn test_heal_state_regenerates_empty_token_with_backup() {
        let tmp = empty_dir();
        let token_path = tmp.path().join("daemon.token");
        std::fs::write(&token_path, "").unwrap();
        let actions = heal_state(tmp.path());
        let bak = token_path.with_file_name("daemon.token.bak");
        assert!(bak.exists(), "empty token must be backed up");
        let token = std::fs::read_to_string(&token_path).unwrap();
        assert_eq!(token.trim().len(), 64);
        assert!(actions.iter().any(|a| a.kind == FixKind::TokenRegenerate));
    }

    #[test]
    fn test_heal_state_inserts_agent_id_into_existing_config() {
        let tmp = empty_dir();
        let config_path = tmp.path().join("config.toml");
        std::fs::write(&config_path, "[daemon]\nport = 7443\n").unwrap();
        let actions = heal_state(tmp.path());
        let raw = std::fs::read_to_string(&config_path).unwrap();
        assert!(raw.contains("agent_id"), "agent_id must be inserted");
        assert!(actions.iter().any(|a| a.kind == FixKind::AgentIdInsert));
    }

    #[test]
    fn test_heal_state_resets_corrupt_telemetry_json() {
        let tmp = empty_dir();
        let telem_path = tmp.path().join("telemetry.json");
        std::fs::write(&telem_path, "{ broken json").unwrap();
        let actions = heal_state(tmp.path());
        let raw = std::fs::read_to_string(&telem_path).unwrap();
        let parsed: serde_json::Value =
            serde_json::from_str(&raw).expect("telemetry must be valid JSON");
        assert_eq!(parsed.get("enabled"), Some(&serde_json::json!(false)));
        assert!(actions.iter().any(|a| a.kind == FixKind::TelemetryReset));
    }

    #[test]
    fn test_heal_state_removes_stale_pid_file() {
        let tmp = empty_dir();
        let pid_path = tmp.path().join("daemon.pid");
        // Use PID 0 — guaranteed not alive on any platform (kernel-reserved).
        std::fs::write(&pid_path, "0").unwrap();
        let actions = heal_state(tmp.path());
        assert!(!pid_path.exists(), "stale PID file must be removed");
        assert!(actions.iter().any(|a| a.kind == FixKind::PidStaleRemove));
    }

    #[test]
    fn test_heal_state_idempotent_on_clean_install() {
        let tmp = empty_dir();
        // First run brings the install up from scratch.
        let first = heal_state(tmp.path());
        assert!(!first.is_empty(), "first run must apply at least one fix");
        // Second run on the same dir should be a no-op (or no-mutation: only
        // agent_id may already be set after the first run).
        let second = heal_state(tmp.path());
        assert!(
            second.is_empty(),
            "second run on a healthy install must apply zero fixes (got {second:?})"
        );
    }

    #[test]
    fn test_heal_binaries_noop_when_target_exists() {
        let tmp = empty_dir();
        let bin_dir = tmp.path().join("bin");
        std::fs::create_dir_all(&bin_dir).unwrap();
        let bin_name = if cfg!(windows) {
            "openlatch-hook.exe"
        } else {
            "openlatch-hook"
        };
        std::fs::write(bin_dir.join(bin_name), b"existing").unwrap();
        let actions = heal_binaries(tmp.path());
        assert!(actions.is_empty(), "no action when target already exists");
    }

    #[test]
    fn test_heal_binaries_copies_from_env_override() {
        let tmp = empty_dir();
        let src_dir = empty_dir();
        let bin_name = if cfg!(windows) {
            "openlatch-hook.exe"
        } else {
            "openlatch-hook"
        };
        let src = src_dir.path().join(bin_name);
        std::fs::write(&src, b"hook bytes").unwrap();

        // Serialize against the other OPENLATCH_HOOK_BIN test — cargo does NOT
        // isolate env per test, they share one process.
        let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let prev = std::env::var("OPENLATCH_HOOK_BIN").ok();
        std::env::set_var("OPENLATCH_HOOK_BIN", &src);

        let actions = heal_binaries(tmp.path());

        if let Some(p) = prev {
            std::env::set_var("OPENLATCH_HOOK_BIN", p);
        } else {
            std::env::remove_var("OPENLATCH_HOOK_BIN");
        }

        let target = tmp.path().join("bin").join(bin_name);
        assert!(target.exists(), "binary must be staged");
        assert_eq!(std::fs::read(&target).unwrap(), b"hook bytes");
        assert!(actions.iter().any(|a| a.kind == FixKind::BinaryCopy));
    }

    #[test]
    fn test_heal_binaries_no_action_when_no_source_locatable() {
        let tmp = empty_dir();
        let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let prev = std::env::var("OPENLATCH_HOOK_BIN").ok();
        std::env::set_var("OPENLATCH_HOOK_BIN", "");
        let actions = heal_binaries(tmp.path());
        if let Some(p) = prev {
            std::env::set_var("OPENLATCH_HOOK_BIN", p);
        } else {
            std::env::remove_var("OPENLATCH_HOOK_BIN");
        }
        // We cannot assert strictly that actions is empty: the test runner
        // binary itself may sit next to an `openlatch-hook` artifact in the
        // target dir, in which case heal_binaries will (correctly) stage it.
        // We only assert the staged action, when present, points at the
        // tempdir target — never at a path outside.
        for a in &actions {
            assert!(a.file.starts_with(tmp.path()));
        }
    }

    #[test]
    fn test_journal_save_and_load_round_trip() {
        let tmp = empty_dir();
        let mut journal = Journal::new();
        journal.actions.push(FixAction {
            ol_code: crate::error::ERR_INVALID_CONFIG.to_string(),
            kind: FixKind::ConfigRewrite,
            file: tmp.path().join("config.toml"),
            backup: Some(tmp.path().join("config.toml.bak")),
            reversible: true,
            applied_at: Utc::now(),
            note: "test".to_string(),
        });
        journal.save(tmp.path()).expect("save must succeed");
        let loaded = Journal::load(tmp.path()).expect("load must succeed");
        assert_eq!(loaded.run_id, journal.run_id);
        assert_eq!(loaded.actions.len(), 1);
        assert_eq!(loaded.actions[0].kind, FixKind::ConfigRewrite);
    }

    #[test]
    fn test_journal_load_returns_no_journal_error_when_absent() {
        let tmp = empty_dir();
        let err = Journal::load(tmp.path()).expect_err("load must fail when absent");
        assert_eq!(err.code, crate::error::ERR_DOCTOR_RESTORE_NO_JOURNAL);
    }

    #[test]
    fn test_journal_load_returns_corrupt_error_when_unparsable() {
        let tmp = empty_dir();
        std::fs::write(tmp.path().join(JOURNAL_FILENAME), "{ broken").unwrap();
        let err = Journal::load(tmp.path()).expect_err("load must fail on bad JSON");
        assert_eq!(err.code, crate::error::ERR_DOCTOR_JOURNAL_CORRUPT);
    }

    /// The #165 repair gap, end to end.
    ///
    /// settings.json holds all the entries it is supposed to hold, so the old
    /// substring predicate declared the install healthy — while every command
    /// pointed at a binary that did not exist and every agent tool call died
    /// with `openlatch-hook: command not found`. `doctor` diagnosed it exactly
    /// (`ERR Hook binary missing` ×12) and `--fix` did nothing, which is what
    /// left the tamper-response path as the only repair tool on the machine.
    ///
    /// Also asserts the token is NOT rotated: `init` regenerates it
    /// unconditionally, and agent sessions already running hold the old value
    /// in their process env — sending an operator to `init` to fix a dead hook
    /// command costs them capture on every live session.
    #[test]
    fn heal_hooks_rewrites_a_command_that_points_at_a_missing_binary() {
        let ol = empty_dir();
        let claude = empty_dir();
        let src = empty_dir();

        // A real binary to stage from, reached via the documented override.
        let hook_src = src.path().join(crate::hooks::staging::hook_bin_name());
        std::fs::write(&hook_src, b"hook bytes").unwrap();

        // The token an already-running agent session is holding.
        std::fs::write(ol.path().join("daemon.token"), "live-session-token").unwrap();

        // settings.json as `init` left it on the broken machine: every entry
        // present, every command naming a binary that is not there.
        let settings_path = claude.path().join("settings.json");
        let dead = serde_json::json!({
            "env": { "OPENLATCH_TOKEN": "live-session-token", "OPENLATCH_PORT": "7443" },
            "hooks": {
                "PreToolUse": [{ "matcher": "*", "_openlatch": { "entry_id": "a" },
                    "hooks": [{ "type": "command", "command": "\"openlatch-hook\" --event PreToolUse" }] }],
                "UserPromptSubmit": [{ "matcher": "*", "_openlatch": { "entry_id": "b" },
                    "hooks": [{ "type": "command", "command": "\"openlatch-hook\" --event UserPromptSubmit" }] }],
                "Stop": [{ "matcher": "*", "_openlatch": { "entry_id": "c" },
                    "hooks": [{ "type": "command", "command": "\"openlatch-hook\" --event Stop" }] }],
            }
        });
        std::fs::write(&settings_path, serde_json::to_string_pretty(&dead).unwrap()).unwrap();

        // Lock order (daemon/mod.rs): OPENLATCH_DIR -> claude_code -> HOOK_BIN
        // -> codex_cli. This test writes `OPENLATCH_DIR` and took every lock
        // but that one, so it raced every other test that holds it.
        let _dir_env = crate::config::OPENLATCH_DIR_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let _env = crate::hooks::claude_code::CONFIG_DIR_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        // HOOK_BIN sits HERE, not at the top of the test: the order this
        // comment states is the one `hooks::staging::HOOK_BIN_ENV_LOCK`
        // documents, and taking HOOK_BIN before `OPENLATCH_DIR` inverted it
        // against every test that takes the two the documented way round —
        // an AB-BA deadlock waiting on a scheduling coincidence.
        let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        // `heal_hooks` resolves its own agents, so EVERY detector has to be
        // pointed inside this test's tempdirs — not just Claude Code's. Pointed
        // at a path that does not exist, `codex_cli::detect()` answers `None`
        // and the walk stays single-agent, which is what this test is about.
        // Without it the walk reaches the developer's real `~/.codex` and
        // `install_hooks` rewrites it. Codex's lock is taken last, everywhere.
        let _codex_env = crate::hooks::codex_cli::CONFIG_DIR_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        // This test WRITES the three Cline seams below, so it must hold the
        // seam lock against `hooks::cline`'s own tests and `cline_isolated()`.
        // Tail position, after Codex's, per the documented order.
        let _cline_env = crate::hooks::cline::SEAM_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let prev = (
            std::env::var("OPENLATCH_DIR").ok(),
            std::env::var("CLAUDE_CONFIG_DIR").ok(),
            std::env::var("OPENLATCH_HOOK_BIN").ok(),
            std::env::var(crate::hooks::codex_cli::CONFIG_DIR_ENV).ok(),
        );
        std::env::set_var("OPENLATCH_DIR", ol.path());
        std::env::set_var("CLAUDE_CONFIG_DIR", claude.path());
        std::env::set_var("OPENLATCH_HOOK_BIN", &hook_src);
        std::env::set_var(
            crate::hooks::codex_cli::CONFIG_DIR_ENV,
            ol.path().join("absent-codex"),
        );

        // The same argument, one agent further out. `doctor --fix` walks EVERY
        // detected agent, so every agent needs a seam — and Cline needs three.
        // `cline::absent_seams` owns which three and where they point, and its
        // doc carries what an incomplete triple leaks.
        //
        // Declared after the seam lock above so it is dropped before it, and
        // restored by `Drop` rather than by hand: a failing assertion below
        // must not leak a redirected seam into the next test in this binary.
        let _cline_seams = crate::hooks::cline::EnvOverride::absent_cline_seams(ol.path());

        let actions = heal_hooks(ol.path());

        let restore = |key: &str, v: Option<String>| match v {
            Some(v) => std::env::set_var(key, v),
            None => std::env::remove_var(key),
        };
        restore("OPENLATCH_DIR", prev.0);
        restore("CLAUDE_CONFIG_DIR", prev.1);
        restore("OPENLATCH_HOOK_BIN", prev.2);
        restore(crate::hooks::codex_cli::CONFIG_DIR_ENV, prev.3);

        assert!(
            actions.iter().any(|a| a.kind == FixKind::HookReinstall),
            "a dangling command must be repaired, not declared healthy"
        );

        // Read the settings back as JSON, not as text.
        //
        // Substring-matching a path into the serialized file passes on Unix and
        // cannot pass on Windows: `hook_src.display()` renders `C:\Users\…`
        // with single separators while the file holds `C:\\Users\\…`, because
        // JSON escapes every backslash. That one assertion kept `Windows
        // Checks` red on `main` for two releases while `heal_hooks` was doing
        // exactly the right thing. Decoding first also sidesteps 8.3 short
        // paths (`RUNNER~1`), which the runner's temp directory really does
        // produce.
        //
        // It is the stronger check too: every command is inspected rather than
        // the file merely containing the path somewhere.
        let settings: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(&settings_path).unwrap()).unwrap();
        let commands = hook_commands(&settings);
        assert!(
            !commands.is_empty(),
            "the repair must leave hook commands behind: {settings:#}"
        );
        for command in &commands {
            assert!(
                !command.starts_with("\"openlatch-hook\""),
                "the bare-name command must be gone: {command}"
            );
            assert!(
                command.contains(&hook_src.display().to_string()),
                "commands must now name an existing binary: {command}"
            );
        }
        assert_eq!(
            settings
                .pointer("/env/OPENLATCH_TOKEN")
                .and_then(serde_json::Value::as_str),
            Some("live-session-token"),
            "the token must NOT be rotated — running sessions still hold it"
        );
    }

    /// The Windows failure, made reproducible on any platform.
    ///
    /// `Windows Checks` was red on `main` for two releases over one assertion
    /// that substring-matched a raw path into the serialized settings file. It
    /// could not fail on Unix — there is no separator to escape — so nothing
    /// short of a Windows runner could catch it, and the PR gate does not run
    /// one.
    ///
    /// This pins the mechanism instead of the platform: a command carrying a
    /// path with backslashes is escaped by `serde_json`, so the text search
    /// misses while the decoded search hits. Reintroducing the substring form
    /// now fails here, on the machine of whoever writes it.
    #[test]
    fn a_windows_path_survives_the_json_round_trip_only_when_decoded() {
        let windows_path = r"C:\Users\RUNNER~1\AppData\Local\Temp\.tmpZBZOCa\openlatch-hook.exe";
        let settings = serde_json::json!({
            "hooks": {
                "PreToolUse": [{
                    "hooks": [{
                        "type": "command",
                        "command": format!("\"{windows_path}\" --event PreToolUse"),
                    }]
                }]
            }
        });
        let serialized = serde_json::to_string_pretty(&settings).unwrap();

        assert!(
            !serialized.contains(windows_path),
            "the premise: JSON escapes every separator, so the raw path is not \
             in the serialized text — this is exactly what the old assertion \
             searched for:\n{serialized}"
        );

        let parsed: serde_json::Value = serde_json::from_str(&serialized).unwrap();
        let commands = hook_commands(&parsed);
        assert_eq!(commands.len(), 1);
        assert!(
            commands[0].contains(windows_path),
            "decoded first, the path is found: {}",
            commands[0]
        );
    }

    /// Every `command` string under `hooks.<event>[].hooks[]`, decoded.
    ///
    /// Exists so assertions compare what an agent would actually execute rather
    /// than how `serde_json` chose to spell it — see the comment above.
    fn hook_commands(settings: &serde_json::Value) -> Vec<String> {
        settings
            .get("hooks")
            .and_then(serde_json::Value::as_object)
            .map(|events| {
                events
                    .values()
                    .filter_map(serde_json::Value::as_array)
                    .flatten()
                    .filter_map(|entry| entry.get("hooks")?.as_array())
                    .flatten()
                    .filter_map(|h| h.get("command")?.as_str())
                    .map(str::to_string)
                    .collect()
            })
            .unwrap_or_default()
    }

    /// The predicate must not churn a healthy install: `--fix` is expected to be
    /// safe to run repeatedly.
    #[test]
    fn heal_hooks_leaves_a_healthy_install_alone() {
        let ol = empty_dir();
        let claude = empty_dir();

        let staged_dir = ol.path().join("bin");
        std::fs::create_dir_all(&staged_dir).unwrap();
        let staged = staged_dir.join(crate::hooks::staging::hook_bin_name());
        std::fs::write(&staged, b"hook bytes").unwrap();

        std::fs::write(ol.path().join("daemon.token"), "tok").unwrap();

        let settings_path = claude.path().join("settings.json");
        let healthy = serde_json::json!({
            "hooks": {
                "PreToolUse": [{ "_openlatch": { "entry_id": "a" },
                    "hooks": [current_hook(&staged, "PreToolUse")] }],
                "UserPromptSubmit": [{ "_openlatch": { "entry_id": "b" },
                    "hooks": [current_hook(&staged, "UserPromptSubmit")] }],
                "Stop": [{ "_openlatch": { "entry_id": "c" },
                    "hooks": [current_hook(&staged, "Stop")] }],
            }
        });
        let before = serde_json::to_string_pretty(&healthy).unwrap();
        std::fs::write(&settings_path, &before).unwrap();

        // Lock order (daemon/mod.rs): OPENLATCH_DIR -> claude_code -> HOOK_BIN
        // -> codex_cli. This test writes `OPENLATCH_DIR` and took every lock
        // but that one, so it raced every other test that holds it.
        let _dir_env = crate::config::OPENLATCH_DIR_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let _env = crate::hooks::claude_code::CONFIG_DIR_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        // HOOK_BIN sits HERE, not at the top of the test: the order this
        // comment states is the one `hooks::staging::HOOK_BIN_ENV_LOCK`
        // documents, and taking HOOK_BIN before `OPENLATCH_DIR` inverted it
        // against every test that takes the two the documented way round —
        // an AB-BA deadlock waiting on a scheduling coincidence.
        let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        // See the sibling test: `heal_hooks` detects its own agents, so a
        // `CODEX_HOME` left pointing at the developer's real `~/.codex` makes
        // this "healthy install" walk reinstall hooks into it — which is both a
        // false failure here and a write nobody asked for.
        let _codex_env = crate::hooks::codex_cli::CONFIG_DIR_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        // This test WRITES the three Cline seams below, so it must hold the
        // seam lock against `hooks::cline`'s own tests and `cline_isolated()`.
        // Tail position, after Codex's, per the documented order.
        let _cline_env = crate::hooks::cline::SEAM_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let prev = (
            std::env::var("OPENLATCH_DIR").ok(),
            std::env::var("CLAUDE_CONFIG_DIR").ok(),
            std::env::var(crate::hooks::codex_cli::CONFIG_DIR_ENV).ok(),
        );
        std::env::set_var("OPENLATCH_DIR", ol.path());
        std::env::set_var("CLAUDE_CONFIG_DIR", claude.path());
        std::env::set_var(
            crate::hooks::codex_cli::CONFIG_DIR_ENV,
            ol.path().join("absent-codex"),
        );

        // The same argument, one agent further out. `doctor --fix` walks EVERY
        // detected agent, so every agent needs a seam — and Cline needs three.
        // `cline::absent_seams` owns which three and where they point, and its
        // doc carries what an incomplete triple leaks.
        //
        // Declared after the seam lock above so it is dropped before it, and
        // restored by `Drop` rather than by hand: a failing assertion below
        // must not leak a redirected seam into the next test in this binary.
        let _cline_seams = crate::hooks::cline::EnvOverride::absent_cline_seams(ol.path());

        let actions = heal_hooks(ol.path());

        match prev.0 {
            Some(v) => std::env::set_var("OPENLATCH_DIR", v),
            None => std::env::remove_var("OPENLATCH_DIR"),
        }
        match prev.1 {
            Some(v) => std::env::set_var("CLAUDE_CONFIG_DIR", v),
            None => std::env::remove_var("CLAUDE_CONFIG_DIR"),
        }
        match prev.2 {
            Some(v) => std::env::set_var(crate::hooks::codex_cli::CONFIG_DIR_ENV, v),
            None => std::env::remove_var(crate::hooks::codex_cli::CONFIG_DIR_ENV),
        }

        assert!(actions.is_empty(), "healthy install must not be rewritten");
        assert_eq!(std::fs::read_to_string(&settings_path).unwrap(), before);
    }

    // -----------------------------------------------------------------------
    // The seam: `heal_hooks_for` must reach every detected agent
    // -----------------------------------------------------------------------

    /// Redirects everything `heal_hooks_for` resolves from the environment into
    /// the test's own tempdirs, and restores it on unwind as well as on
    /// success: a failing assertion must not leak a redirected state directory
    /// into the next test in this binary.
    ///
    /// `OPENLATCH_SKIP_KEYRING` is not optional here. `install_hooks` resolves
    /// the HMAC key, and with no `hmac.key` in the (fresh) state directory that
    /// read reaches the OS keychain — which on macOS blocks on a GUI
    /// authorization dialog, hanging the run rather than failing it. Bypassing
    /// the keychain in tests is this repo's convention
    /// (`.claude/rules/credential-lookup.md`).
    ///
    /// **It takes the locks itself, and it takes BOTH.** This guard sets
    /// `OPENLATCH_DIR` as well as `OPENLATCH_HOOK_BIN`, and those two variables
    /// have two different locks on purpose —
    /// [`crate::hooks::staging::HOOK_BIN_ENV_LOCK`]'s own doc says so, and ends
    /// *"a test that sets both variables takes both locks"*. Its three callers
    /// took only the hook-binary one, so a `hooks::` test holding
    /// `OPENLATCH_DIR_ENV_LOCK` could repoint `$OPENLATCH_DIR` mid-`heal_hooks_for`;
    /// `install_hooks` then resolved a foreign state directory, returned `Err`
    /// for the second agent and pushed no `FixAction` — which is exactly
    /// `heal_hooks_repairs_every_detected_agent` failing on its *second* agent,
    /// intermittently, only under concurrency. Owning both guards here is what
    /// makes that unforgettable at a call site.
    ///
    /// Acquisition order is the documented one — `config::OPENLATCH_DIR_ENV_LOCK`
    /// then `HOOK_BIN_ENV_LOCK` — so this cannot deadlock against
    /// `hooks::mod`'s tests, which take the same two in the same order.
    struct HookEnvGuard {
        saved: Vec<(&'static str, Option<std::ffi::OsString>)>,
        // Field order IS drop order, and it runs after `Drop::drop` below: the
        // variables are restored while both locks are still held, so no other
        // test ever observes a half-restored environment. Released LIFO —
        // hook-binary first, then the directory lock.
        _hook_bin_lock: std::sync::MutexGuard<'static, ()>,
        _dir_lock: std::sync::MutexGuard<'static, ()>,
    }

    impl HookEnvGuard {
        fn set(ol_dir: &Path, hook_bin: &Path) -> Self {
            let dir_lock = crate::config::OPENLATCH_DIR_ENV_LOCK
                .lock()
                .unwrap_or_else(|e| e.into_inner());
            let hook_bin_lock = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());

            let pairs: [(&'static str, std::ffi::OsString); 3] = [
                ("OPENLATCH_DIR", ol_dir.as_os_str().to_owned()),
                ("OPENLATCH_HOOK_BIN", hook_bin.as_os_str().to_owned()),
                ("OPENLATCH_SKIP_KEYRING", std::ffi::OsString::from("1")),
            ];
            let saved = pairs
                .iter()
                .map(|(key, _)| (*key, std::env::var_os(key)))
                .collect();
            for (key, value) in pairs {
                std::env::set_var(key, value);
            }
            Self {
                saved,
                _hook_bin_lock: hook_bin_lock,
                _dir_lock: dir_lock,
            }
        }
    }

    impl Drop for HookEnvGuard {
        fn drop(&mut self) {
            for (key, value) in &self.saved {
                match value {
                    Some(v) => std::env::set_var(key, v),
                    None => std::env::remove_var(key),
                }
            }
        }
    }

    /// Two detected agents whose settings files the caller writes.
    ///
    /// The first is the real binding with its `pub` fields set under a tempdir
    /// — no `CLAUDE_CONFIG_DIR` and no config-dir lock, which is the whole
    /// point of taking the slice. The second is `FakeBinding`, the only way to
    /// reach a second `agent_type` on a build that detects one agent; adding an
    /// `AgentKind` variant or a second real binding to get one would put
    /// agent-two code in a unit whose premise is that there is none.
    use crate::hooks::binding::test_support::two_detected_agents as two_agents;

    use crate::hooks::binding::test_support::non_installable_agent;

    /// settings.json as `init` left it on the broken machine: every
    /// load-bearing entry present, every command naming a binary that is not
    /// there.
    fn write_dead_settings(path: &Path) {
        let dead = serde_json::json!({
            "env": { "OPENLATCH_TOKEN": "live-session-token", "OPENLATCH_PORT": "7443" },
            "hooks": {
                "PreToolUse": [{ "matcher": "*", "_openlatch": { "entry_id": "a" },
                    "hooks": [{ "type": "command", "command": "\"openlatch-hook\" --event PreToolUse" }] }],
                "UserPromptSubmit": [{ "matcher": "*", "_openlatch": { "entry_id": "b" },
                    "hooks": [{ "type": "command", "command": "\"openlatch-hook\" --event UserPromptSubmit" }] }],
                "Stop": [{ "matcher": "*", "_openlatch": { "entry_id": "c" },
                    "hooks": [{ "type": "command", "command": "\"openlatch-hook\" --event Stop" }] }],
            }
        });
        std::fs::write(path, serde_json::to_string_pretty(&dead).unwrap()).unwrap();
    }

    /// The same file in the state `install_hooks` leaves behind: every
    /// load-bearing entry present, every command naming the binary this install
    /// actually resolves to.
    /// A Claude Code hook handler exactly as `install_hooks` writes it today —
    /// anything else is a stale invocation, which `--fix` rightly rewrites.
    fn current_hook(bin: &Path, event: &str) -> serde_json::Value {
        let marker = crate::core::hook_state::marker::OpenlatchMarker::new("m".into());
        crate::hooks::claude_code::build_hook_entry(
            event,
            7443,
            crate::hooks::OPENLATCH_TOKEN_ENV,
            bin,
            &marker,
        )["hooks"][0]
            .clone()
    }

    fn write_healthy_settings(path: &Path, bin: &Path) {
        let healthy = serde_json::json!({
            "hooks": {
                "PreToolUse": [{ "_openlatch": { "entry_id": "a" },
                    "hooks": [current_hook(bin, "PreToolUse")] }],
                "UserPromptSubmit": [{ "_openlatch": { "entry_id": "b" },
                    "hooks": [current_hook(bin, "UserPromptSubmit")] }],
                "Stop": [{ "_openlatch": { "entry_id": "c" },
                    "hooks": [current_hook(bin, "Stop")] }],
            }
        });
        std::fs::write(path, serde_json::to_string_pretty(&healthy).unwrap()).unwrap();
    }

    /// Codex's liveness remedy for an untrusted hook is *"Run `openlatch doctor
    /// --fix`"*, and the hook file is perfectly healthy in that state — so the
    /// reinstall predicate alone would find nothing to do and the remedy would
    /// be a lie. `--fix` grants the trust itself.
    #[test]
    fn heal_hooks_trusts_a_healthy_but_untrusted_codex_install() {
        let ol = empty_dir();
        let src = empty_dir();
        let codex = empty_dir();

        let hook_src = src.path().join(crate::hooks::staging::hook_bin_name());
        std::fs::write(&hook_src, b"hook bytes").unwrap();
        std::fs::write(ol.path().join("daemon.token"), "tok").unwrap();
        let _env = HookEnvGuard::set(ol.path(), &hook_src);
        crate::hooks::staging::stage_hook_binary(ol.path()).expect("stage");

        let root = codex.path().to_path_buf();
        let binding = |listing: Option<Vec<crate::hooks::codex_cli::ListedHook>>| {
            crate::hooks::bindings::codex_cli::CodexCliBinding {
                codex_dir: root.clone(),
                hooks_path: root.join("hooks.json"),
                requirements_toml: None,
                hooks_list: std::sync::Arc::new(move |_| listing.clone()),
            }
        };
        // Installed while Codex could not be asked: a healthy file, no trust.
        crate::hooks::install_hooks(&binding(None), 7443, "tok").expect("install");
        let ours = crate::hooks::codex_cli::installed_handler(&root, "PreToolUse").expect("ours");
        let untrusted: crate::hooks::codex_cli::ListedHook =
            serde_json::from_value(serde_json::json!({
                "key": crate::hooks::codex_cli::trust_key(&root, "PreToolUse", &ours),
                "command": ours.command,
                "sourcePath": root.join("hooks.json"),
                "currentHash": "sha256:current",
                "trustStatus": "untrusted",
            }))
            .expect("listed hook");
        let before = std::fs::read_to_string(root.join("hooks.json")).unwrap();

        let detected = vec![DetectedAgent {
            kind: crate::hooks::AgentKind::CodexCli,
            binding: std::sync::Arc::new(binding(Some(vec![untrusted]))),
        }];
        let actions = heal_hooks_for(&detected, ol.path());

        assert_eq!(
            actions.iter().map(|a| &a.kind).collect::<Vec<_>>(),
            [&FixKind::HookTrustGrant],
            "a healthy file is not rewritten, and the trust is granted"
        );
        assert_eq!(
            std::fs::read_to_string(root.join("hooks.json")).unwrap(),
            before
        );
        let config = std::fs::read_to_string(root.join("config.toml")).expect("config.toml");
        assert!(
            config.contains("trusted_hash = \"sha256:current\""),
            "{config}"
        );
    }

    /// The Hooks check's own remedy is *"Run `openlatch doctor --fix` to
    /// reinstall them"*. On a host where a second agent is broken, that remedy
    /// has to be true.
    #[test]
    fn heal_hooks_repairs_every_detected_agent() {
        // No `ENV_LOCK` here: `HookEnvGuard` below takes it, together with
        // `OPENLATCH_DIR_ENV_LOCK`, and this mutex is not reentrant.

        let ol = empty_dir();
        let src = empty_dir();
        let agents = empty_dir();

        // A real binary to stage from, reached via the documented override.
        let hook_src = src.path().join(crate::hooks::staging::hook_bin_name());
        std::fs::write(&hook_src, b"hook bytes").unwrap();
        std::fs::write(ol.path().join("daemon.token"), "tok").unwrap();

        let _env = HookEnvGuard::set(ol.path(), &hook_src);

        let detected = two_agents(agents.path());
        for agent in &detected {
            write_dead_settings(&agent.settings_path());
        }

        let actions = heal_hooks_for(&detected, ol.path());

        let healed: Vec<PathBuf> = actions
            .iter()
            .filter(|a| a.kind == FixKind::HookReinstall)
            .map(|a| a.file.clone())
            .collect();
        assert_eq!(
            healed,
            detected
                .iter()
                .map(DetectedAgent::settings_path)
                .collect::<Vec<_>>(),
            "every dead agent must be repaired — `file` is what names which one"
        );
    }

    /// The `return` → `continue` conversion, and nothing else, decides this.
    ///
    /// The test above cannot: both its agents are dead, so the healthy branch
    /// is never reached and a bare `return` there is indistinguishable from a
    /// `continue`. Detection order is fixed with Claude Code first, so the
    /// realistic dual-agent host — Claude Code healthy, the second one broken —
    /// is precisely the case a bare `return` leaves broken forever.
    #[test]
    fn heal_hooks_skips_a_healthy_agent_without_abandoning_the_rest() {
        // No `ENV_LOCK` here: `HookEnvGuard` below takes it, together with
        // `OPENLATCH_DIR_ENV_LOCK`, and this mutex is not reentrant.

        let ol = empty_dir();
        let src = empty_dir();
        let agents = empty_dir();

        let hook_src = src.path().join(crate::hooks::staging::hook_bin_name());
        std::fs::write(&hook_src, b"hook bytes").unwrap();
        std::fs::write(ol.path().join("daemon.token"), "tok").unwrap();

        let _env = HookEnvGuard::set(ol.path(), &hook_src);

        let detected = two_agents(agents.path());
        write_healthy_settings(&detected[0].settings_path(), &hook_src);
        write_dead_settings(&detected[1].settings_path());

        // The fixture proves nothing unless the first agent really is healthy:
        // if `needs_reinstall` were true for it too, the branch this test
        // exists to pin would never be reached.
        assert!(
            !hooks::health::inspect_file(&detected[0].settings_path(), &*detected[0].binding)
                .expect("the healthy settings file must parse")
                .needs_reinstall(),
            "the first agent must start out healthy"
        );

        let actions = heal_hooks_for(&detected, ol.path());

        assert_eq!(
            actions.iter().map(|a| a.file.clone()).collect::<Vec<_>>(),
            vec![detected[1].settings_path()],
            "a healthy first agent must not end the walk — the broken one behind it \
             still needs its fix"
        );
    }

    /// `--fix` never reinstalls into an agent this build cannot write, however
    /// broken that agent's hook path looks — and repeating the run adds nothing.
    ///
    /// The defect this pins is not a failed write. `install_hooks` refuses on
    /// its own, so the reinstall would "succeed" writing nothing — but
    /// `backup_file` runs FIRST, so every `doctor --fix` on such a host copied
    /// a file it was never going to repair, and a `.bak` accumulated per run.
    /// Worse, `needs_reinstall` is permanently true for a path we do not own,
    /// so the fix could never converge: the diagnostic and its own fix would
    /// disagree forever.
    ///
    /// A dead installable agent shares the fixture as the positive control. It
    /// IS healed and it DOES gain a backup, so "no backup" cannot pass here by
    /// the run having done nothing at all.
    #[test]
    fn doctor_fix_does_not_reinstall_cline() {
        // No `ENV_LOCK` here: `HookEnvGuard` below takes it, together with
        // `OPENLATCH_DIR_ENV_LOCK`, and this mutex is not reentrant.

        let ol = empty_dir();
        let src = empty_dir();
        let agents = empty_dir();

        let hook_src = src.path().join(crate::hooks::staging::hook_bin_name());
        std::fs::write(&hook_src, b"hook bytes").unwrap();
        std::fs::write(ol.path().join("daemon.token"), "tok").unwrap();
        let _env = HookEnvGuard::set(ol.path(), &hook_src);

        // The shared fixture's second agent, re-declared as one with no
        // writable hook surface. Its settings file is written dead, so
        // `needs_reinstall` would be true and the loop WOULD reach
        // `backup_file` without the guard.
        let cline_dir = agents.path().join("cline");
        std::fs::create_dir_all(&cline_dir).unwrap();
        let detected = vec![
            two_agents(agents.path()).remove(0),
            non_installable_agent("cline", &cline_dir),
        ];
        let cline_settings = detected[1].settings_path();
        write_dead_settings(&detected[0].settings_path());
        write_dead_settings(&cline_settings);

        // Two runs: the accumulation is the symptom, so one run cannot show it.
        let first = heal_hooks_for(&detected, ol.path());
        let second = heal_hooks_for(&detected, ol.path());

        for (run, actions) in [("first", &first), ("second", &second)] {
            assert!(
                !actions.iter().any(|a| a.file == cline_settings),
                "the {run} --fix run must record no action for a non-installable \
                 agent, got {:?}",
                actions.iter().map(|a| a.file.clone()).collect::<Vec<_>>()
            );
        }

        let backups: Vec<PathBuf> = std::fs::read_dir(&cline_dir)
            .expect("the agent directory is readable")
            .filter_map(|e| e.ok().map(|e| e.path()))
            .filter(|p| p.extension().is_some_and(|x| x == "bak"))
            .collect();
        assert!(
            backups.is_empty(),
            "no `.bak` may be written beside a hook path this build never repairs, got {backups:?}"
        );

        // The control: the installable agent in the same two runs was healed
        // and did gain a backup, so the assertions above are about the guard,
        // not about a `--fix` that did nothing.
        assert_eq!(
            first
                .iter()
                .filter(|a| a.kind == FixKind::HookReinstall)
                .map(|a| a.file.clone())
                .collect::<Vec<_>>(),
            vec![detected[0].settings_path()],
            "the installable agent must still be repaired"
        );
        assert!(
            bak_path_for(&detected[0].settings_path()).exists(),
            "the control agent's backup proves `backup_file` is reachable in this fixture"
        );
    }
}