openlatch-client 0.5.2

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
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
/// Agent hook detection and installation.
///
/// Public API:
/// - [`detect_agents`] โ€” every AI agent installed on this machine
/// - [`detect_agent`] โ€” the first of them, for instance-scoped callers
/// - [`install_hooks`] โ€” write OpenLatch HTTP hook entries into the agent's config
/// - [`remove_hooks`] โ€” remove all OpenLatch-owned hook entries
///
/// # Module structure
///
/// - `claude_code` โ€” path detection and hook entry building for Claude Code
/// - `codex_cli` โ€” path detection for Codex CLI
/// - `jsonc` โ€” JSONC-preserving string surgery on `settings.json`
pub mod atomic;
pub mod binding;
pub mod bindings;
pub mod claude_code;
pub mod cline;
pub mod cline_plugin;
pub mod cline_providers;
pub mod codex_cli;
pub mod health;
pub mod hook_files;
pub mod jsonc;
pub mod model_relay_endpoints;
pub mod provider_endpoints;
pub mod staging;

use std::path::PathBuf;
use std::sync::Arc;

use crate::core::hook_state::hmac::compute_entry_hmac;
use crate::core::hook_state::key::HmacKeyStore;
use crate::core::hook_state::marker::OpenlatchMarker;
use crate::core::hook_state::{self, HookStateFile, StateEntry};
use crate::error::{OlError, ERR_HOOK_AGENT_NOT_FOUND, ERR_HOOK_BINARY_UNRESOLVABLE};
use crate::hooks::binding::{AgentBinding, HookSurface};

// ---------------------------------------------------------------------------
// Public types
// ---------------------------------------------------------------------------

/// A detected AI agent, paired with the binding that acts on it.
///
/// `kind` is what callers match on; `binding` is what they act through. The
/// binding already resolved every path, so a duplicated payload here would be a
/// second copy that can disagree with it. One field, one source.
#[derive(Clone)]
pub struct DetectedAgent {
    /// Which agent this is.
    pub kind: AgentKind,
    /// Everything the client needs in order to act on it.
    pub binding: Arc<dyn AgentBinding>,
}

/// The identity half of a [`DetectedAgent`].
///
/// `#[non_exhaustive]` has **no effect inside this crate** โ€” every match on it
/// here still breaks, usefully, when agent four lands. It is a semver
/// affordance for downstream consumers of the published lib, nothing more.
///
/// **Nothing in production reads a variant.** Every `AgentKind::` site in
/// `src/` outside this enum is a test fixture; the one production consumer is
/// the `Debug` impl below. It exists so the fixtures can say which agent they
/// mean, and it is the reason `two_detected_agents`' fake is not retargeted
/// onto a real agent's variant.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AgentKind {
    /// Claude Code.
    ClaudeCode,
    /// Codex CLI.
    CodexCli,
    /// Cline โ€” detected, and the one variant whose binding declares
    /// [`AgentBinding::installable`] is `false`. Last in detection order, so
    /// [`detect_agent`]'s "take the first" never hands a singular caller the
    /// agent this build writes nothing into.
    Cline,
}

impl DetectedAgent {
    /// The agent's config directory โ€” read from the binding, never duplicated.
    pub fn config_dir(&self) -> PathBuf {
        self.binding.config_dir()
    }

    /// The file this agent's hook registrations are written into.
    pub fn settings_path(&self) -> PathBuf {
        self.binding.hook_config_path()
    }

    /// **What shape** that surface is โ€” forwarded for the same reason
    /// [`installable`](Self::installable) is: a guard site that reaches past
    /// `DetectedAgent` into `.binding` for one half of its predicate and not
    /// the other is exactly how `doctor_rescue` came to hold
    /// `a.binding.installable() && a.settings_path().exists()`.
    pub fn hook_surface(&self) -> HookSurface {
        self.binding.hook_surface()
    }

    /// The CloudEvents `source` wire value, e.g. `"claude-code"`.
    pub fn agent_type(&self) -> &'static str {
        self.binding.agent_type()
    }

    /// Human-facing label, e.g. `"Claude Code"`. Feeds doctor's Environment
    /// line and init's detected-agent step.
    pub fn display_name(&self) -> &'static str {
        self.binding.display_name()
    }

    /// Whether this agent's hook surface can be written at all.
    ///
    /// Forwarded for the same reason the four above are: every guard site
    /// otherwise reaches past `DetectedAgent` into `.binding`, and
    /// `doctor_rescue`'s collection filter had one forwarded and one
    /// unforwarded call in a single expression
    /// (`a.binding.installable() && a.settings_path().exists()`).
    pub fn installable(&self) -> bool {
        self.binding.installable()
    }
}

// Hand-written: `Arc<dyn AgentBinding>` is not `Debug`. The kind and the
// resolved config directory are enough for a log line, and no more.
impl std::fmt::Debug for DetectedAgent {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DetectedAgent")
            .field("kind", &self.kind)
            .field("config_dir", &self.binding.config_dir())
            .finish()
    }
}

/// The result of a successful [`install_hooks`] call.
#[derive(Debug)]
pub struct HookInstallResult {
    /// Per-hook-event status showing whether the entry was added or replaced.
    pub entries: Vec<HookEntryStatus>,
    /// Paths this install refused to touch because the file there is not ours.
    ///
    /// Always empty for a [`HookSurface::ConfigFile`] agent: that arm writes one
    /// entry per event type and has no skip rule. Non-empty means the install
    /// did **not** land everywhere, which is a different fact from `Err` โ€” the
    /// call succeeded and left the developer's file alone, exactly as the
    /// collision rule requires.
    ///
    /// It is a field rather than something callers count because counting needs
    /// to know how many files were expected, which means naming the agent. Two
    /// callers had already reached for `CLINE_HOOK_FILES.len()` to answer it.
    pub left_alone: Vec<std::path::PathBuf>,
}

/// Status of a single hook event entry after installation.
#[derive(Debug)]
pub struct HookEntryStatus {
    /// The hook event type (e.g. `"PreToolUse"`, `"UserPromptSubmit"`, `"Stop"`).
    pub event_type: String,
    /// Whether the entry was newly added or replaced an existing OpenLatch entry.
    pub action: HookAction,
}

/// Whether a hook entry was newly created or replaced an existing one.
#[derive(Debug, Clone, PartialEq)]
pub enum HookAction {
    /// A new hook entry was appended to the array.
    Added,
    /// An existing OpenLatch-owned entry was replaced (idempotent re-install).
    Replaced,
}

/// Resolve the absolute path to the `openlatch-hook` binary that hook
/// configs should invoke.
///
/// Order of precedence:
///
/// 1. `OPENLATCH_HOOK_BIN` env var (override for tests, custom installs).
/// 2. `<openlatch_dir>/bin/openlatch-hook[.exe]` โ€” the canonical install
///    location, populated by [`staging::stage_hook_binary`], which `init` and
///    `doctor --fix` both call before writing any hook. Resolved through
///    [`crate::config::openlatch_dir`] so it honours `$OPENLATCH_DIR`, exactly
///    like the side that writes it.
/// 3. `openlatch-hook[.exe]` next to the current running binary (typical
///    during `cargo install` or portable tarball extractions).
/// 4. Bare `"openlatch-hook"` as a last resort โ€” relies on the hook
///    subprocess resolving it via `PATH`.
///
/// Step 4 is a path that may not exist, and writing it into a hook command is
/// what produced the #165 outage: `/bin/sh: openlatch-hook: command not found`
/// on every tool call, invisible because the hook fails open. [`install_hooks`]
/// therefore refuses any resolution that is not an existing file โ€” callers must
/// stage the binary first rather than let this fall through.
pub fn resolve_hook_binary_path() -> PathBuf {
    let bin_name = if cfg!(windows) {
        "openlatch-hook.exe"
    } else {
        "openlatch-hook"
    };

    if let Ok(override_path) = std::env::var("OPENLATCH_HOOK_BIN") {
        if !override_path.is_empty() {
            return PathBuf::from(override_path);
        }
    }

    // `config::openlatch_dir()`, not `home/.openlatch`: the staging side writes
    // into `<ol_dir>/bin`, and `<ol_dir>` honours `$OPENLATCH_DIR` (and resolves
    // under `%APPDATA%` on Windows). Hardcoding the home-relative path here made
    // the two disagree on any non-default directory โ€” the resolver looked in a
    // directory nothing had ever staged into, and fell through to the bare name.
    let candidate = crate::config::openlatch_dir().join("bin").join(bin_name);
    if candidate.exists() {
        return candidate;
    }

    if let Ok(current_exe) = std::env::current_exe() {
        if let Some(dir) = current_exe.parent() {
            let candidate = dir.join(bin_name);
            if candidate.exists() {
                return candidate;
            }
        }
    }

    PathBuf::from(bin_name)
}

// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------

/// Every AI agent installed on this machine, in detection order.
///
/// Plural is the primitive: callers that must act on the whole host iterate
/// this. Order is fixed (Claude Code first) and load-bearing.
pub fn detect_agents() -> Vec<DetectedAgent> {
    binding::detect_all()
}

/// The **first** detected agent.
///
/// For callers that own wiring for the *instance* rather than acting per
/// agent โ€” "which agent does this daemon instance own wiring for" is singular
/// by construction. Callers that must reach every agent use
/// [`detect_agents`].
///
/// # Errors
///
/// Returns `OL-1400` if no supported AI agent is detected.
pub fn detect_agent() -> Result<DetectedAgent, OlError> {
    detect_agents()
        .into_iter()
        .next()
        .ok_or_else(agent_not_found_err)
}

/// `OL-1400`, with a remedy naming **every** agent this build can detect.
///
/// The old text named Claude Code and only Claude Code, with a
/// `https://claude.ai/download` link. One URL cannot serve a list, and
/// `.with_docs` already carries the OL-1400 page where per-agent install
/// instructions belong.
pub(crate) fn agent_not_found_err() -> OlError {
    OlError::new(ERR_HOOK_AGENT_NOT_FOUND, "No AI agents detected")
        .with_suggestion(format!(
            "Install a supported agent ({}) and try again.",
            binding::DETECTABLE_AGENT_NAMES.join(", ")
        ))
        .with_docs("https://docs.openlatch.ai/errors/OL-1400")
}

/// Narrow `agents` to the ones the operator named with `--agent` (D-09).
///
/// **Coverage is the default**: an empty `wanted` returns every detected agent
/// untouched, so an operator who says nothing gets everything on the host
/// wired. Opting an agent *out* is the explicit act, not opting one in.
///
/// The three failure directions, and why they differ:
///
/// - **A name that is not an agent type at all** is a typo in the flag. It
///   fails, listing the valid wire values from
///   [`crate::generated::known_values::SCHEMA_AGENT_TYPES`] โ€” the schema
///   vocabulary, deliberately wider than the two agents this build can detect,
///   so the message distinguishes "not a thing" from "not here".
/// - **A valid name that is not on this host** fails too, naming it. It is
///   still a typo โ€” the operator believes they are covering an agent they are
///   not โ€” and quietly doing nothing is how somebody ends up trusting an
///   uncaptured host.
/// - **A detected agent nobody named** is skipped in silence. That is the flag
///   working, not a condition to report.
///
/// # Errors
///
/// `OL-1400` in both failing directions: the agent asked for is not one this
/// command can act on. No new code โ€” the existing one already means exactly
/// that, and its docs page is where per-agent install instructions live.
pub fn select_agents(
    agents: Vec<DetectedAgent>,
    wanted: &[String],
) -> Result<Vec<DetectedAgent>, OlError> {
    if wanted.is_empty() {
        return Ok(agents);
    }

    let known = crate::generated::known_values::SCHEMA_AGENT_TYPES;

    for name in wanted {
        if !known.contains(&name.as_str()) {
            return Err(OlError::new(
                ERR_HOOK_AGENT_NOT_FOUND,
                format!("Unknown agent type '{name}'"),
            )
            .with_suggestion(format!("Valid values: {}.", known.join(", ")))
            .with_docs("https://docs.openlatch.ai/errors/OL-1400"));
        }
        if !agents.iter().any(|a| a.agent_type() == name) {
            return Err(OlError::new(
                ERR_HOOK_AGENT_NOT_FOUND,
                format!("Agent '{name}' was not detected on this machine"),
            )
            .with_suggestion(format!(
                "Detected agents: {}. Omit --agent to cover every one of them.",
                if agents.is_empty() {
                    "none".to_string()
                } else {
                    agents
                        .iter()
                        .map(DetectedAgent::agent_type)
                        .collect::<Vec<_>>()
                        .join(", ")
                }
            ))
            .with_docs("https://docs.openlatch.ai/errors/OL-1400"));
        }
    }

    // Detection order, not flag order: `detect_all`'s declaration order is
    // load-bearing everywhere else, and `--agent codex-cli --agent claude-code`
    // must not reverse it.
    Ok(agents
        .into_iter()
        .filter(|a| wanted.iter().any(|w| w == a.agent_type()))
        .collect())
}

/// Env var name carrying the daemon bearer token to a hook subprocess.
///
/// Written into the agent's `env` block by [`install_hooks`] and removed by
/// [`remove_hooks`]. Declared here, once, because those two must agree on the
/// name: while each held its own local copy, install wrote two `env` keys that
/// uninstall did not know about, and `openlatch uninstall --purge` left the
/// token โ€” in plaintext โ€” in `settings.json`.
pub const OPENLATCH_TOKEN_ENV: &str = "OPENLATCH_TOKEN";

/// Env var name pinning the daemon port for a hook subprocess. Same
/// install/remove symmetry as [`OPENLATCH_TOKEN_ENV`].
pub const OPENLATCH_PORT_ENV: &str = "OPENLATCH_PORT";

/// Install OpenLatch HTTP hook entries into the agent's config.
///
/// Every event in `binding.hook_event_types()` is written. Re-running this
/// function is idempotent: existing OpenLatch entries are replaced rather than
/// duplicated. Hooks from other tools are never touched.
///
/// Both sentences hold for the other shape of surface too, in its own terms:
/// a [`HookSurface::Directory`] binding is handed to [`install_hook_files`],
/// which writes one executable shim per hook file, replaces only shims carrying
/// our ownership marker, and leaves a file the developer wrote exactly where it
/// is. What it writes is [`hook_files::CLINE_HOOK_FILES`] โ€” the writer's list,
/// since a directory surface registers by *file name* and there is no JSON
/// entry for an event type to key โ€” **plus**, for a binding that declares one,
/// the enforcement plugin at [`AgentBinding::plugin_surface`].
///
/// # Arguments
///
/// - `binding`: the agent binding to install into โ€” from
///   [`detect_agents`]/[`detect_agent`], or any other `AgentBinding`
/// - `port`: the daemon's listen port (written into each hook URL)
/// - `token`: the bearer token value โ€” for an agent whose
///   [`DaemonChannel`](binding::DaemonChannel) is `EnvVars`, only the *env var
///   name* reaches settings.json; the actual token is stored separately
///
/// # Errors
///
/// - `OL-1401` if settings.json cannot be read or written.
/// - `OL-1402` if settings.json contains malformed JSONC.
/// - `OL-1404` if [`resolve_hook_binary_path`] does not resolve to an existing
///   file. settings.json is left untouched: writing a command that cannot
///   resolve is worse than not writing one.
pub fn install_hooks(
    binding: &dyn AgentBinding,
    port: u16,
    token: &str,
) -> Result<HookInstallResult, OlError> {
    // THE BACKSTOP, and it is the first statement for a reason: everything
    // below this line writes. The callers are guarded too, but this function is
    // `pub` and documented as accepting *any* `AgentBinding`, so a caller that
    // forgets must still be unable to reach a write.
    //
    // Not an error. An operator who asked for coverage of the whole host did
    // not ask about this agent in particular, and failing here would take the
    // agents we *can* wire down with it. `--agent <non-installable>` is the
    // case where the operator did ask, and `init` answers that with
    // `OL-1407`.
    //
    // Built by hand: `HookInstallResult` is `#[derive(Debug)]` only โ€” there is
    // no `Default` to fall back on.
    if !binding.installable() {
        return Ok(HookInstallResult {
            entries: Vec::new(),
            left_alone: Vec::new(),
        });
    }

    let openlatch_dir = crate::config::openlatch_dir();
    let hook_bin = resolve_hook_binary_path();

    // The command we are about to write into every hook entry must point
    // at a binary that exists. `resolve_hook_binary_path()` ends in a
    // bare `"openlatch-hook"` that relies on the agent's PATH, and when
    // that name is not on it every hook on the machine dies with exit
    // 127 โ€” silently, because the hook fails open. Callers stage the
    // binary first (`hooks::staging::stage_hook_binary`); this is the
    // post-condition that makes "an install that cannot resolve its own
    // hook binary" impossible to write rather than merely unlikely.
    //
    // Above the surface `match`, and deliberately: BOTH arms hand this path to
    // the agent to execute, and `write_all` takes it as its `bin` parameter for
    // ten shell scripts that have no other way of finding the hook. Nothing
    // between the `installable()` guard and the `match` writes anything, so
    // hoisting the check changes no behaviour on the `ConfigFile` path.
    if !hook_bin.is_file() {
        return Err(OlError::new(
            ERR_HOOK_BINARY_UNRESOLVABLE,
            format!(
                "Refusing to install hooks: '{}' is not an existing file",
                hook_bin.display()
            ),
        )
        .with_suggestion(
            "Run 'openlatch doctor --fix' to stage the hook binary, or point \
             OPENLATCH_HOOK_BIN at an existing one.",
        ));
    }

    // The shape of the surface, not just its path. A `Directory` binding has
    // no file for `atomic_rewrite_jsonc` below to rewrite, and reaching it with
    // one would run a JSONC rewrite against a directory.
    //
    // **This is the one place a directory surface is resolved.** Everything the
    // file installer needs is a parameter โ€” it calls no resolver of its own โ€”
    // so the only route to a real Cline store on a developer's machine runs
    // through this line, under a binding that answered `installable()`.
    let settings_path = match binding.hook_surface() {
        HookSurface::ConfigFile(path) => path,
        HookSurface::Directory(dir) => {
            return install_hook_files(binding, &dir, &hook_bin, &openlatch_dir, port, token);
        }
    };
    let event_types = binding.hook_event_types();

    // The env-var pair, when this agent's channel is one. An agent on
    // `OpenlatchDirArg` gets no `env` key at all โ€” for Codex that is not a
    // preference but a hard requirement, since its hooks file is
    // `deny_unknown_fields`.
    let env_keys = match binding.daemon_channel() {
        binding::DaemonChannel::EnvVars {
            token: token_env,
            port: port_env,
        } => Some((token_env, port_env)),
        binding::DaemonChannel::OpenlatchDirArg => None,
    };

    let key_store = HmacKeyStore::new(&openlatch_dir);
    let hmac_key = key_store.load_or_create()?;

    let token_fp = crate::core::hook_state::key::key_fingerprint(token.as_bytes());
    let settings_path_hash = hook_state::hash_settings_path(&settings_path);

    let mut entries_with_markers: Vec<(String, serde_json::Value, String)> = Vec::new();
    for &et in event_types {
        let entry_id = uuid::Uuid::now_v7().to_string();
        let mut marker = OpenlatchMarker::new(entry_id.clone());

        let mut entry = binding.build_hook_entry(et, &hook_bin, port, &marker);

        let hmac_value = compute_entry_hmac(&entry, &hmac_key)?;
        marker = marker.with_hmac(hmac_value.clone());

        let marker_value = serde_json::to_value(&marker).expect("OpenlatchMarker serializes");
        entry["_openlatch"] = marker_value;

        entries_with_markers.push((et.to_string(), entry, entry_id));
    }

    let jsonc_entries: Vec<(String, serde_json::Value)> = entries_with_markers
        .iter()
        .map(|(et, entry, _)| (et.clone(), entry.clone()))
        .collect();

    let token_owned = token.to_string();
    let actions = std::cell::RefCell::new(Vec::new());

    atomic::atomic_rewrite_jsonc(&settings_path, |root| {
        let a = jsonc::insert_hook_entries_cst(root, &jsonc_entries)?;
        if let Some((token_env, port_env)) = env_keys {
            jsonc::set_env_var_cst(root, token_env, &token_owned)?;
            // Pin the port too, not just the token.
            //
            // The hook resolves its port as OPENLATCH_PORT (its own env,
            // populated by the agent from this settings block) ->
            // <openlatch_dir>/daemon.port -> 7443. OPENLATCH_DIR is
            // deliberately NOT in a hook entry's allowedEnvVars, so a
            // daemon on a non-default directory is unreachable by the
            // middle step: the hook reads the DEFAULT directory's port
            // file and connects to the wrong daemon, or none at all.
            // Because the hook fails open โ€” prints `{}`, exits 0, spools
            // to fallback.jsonl โ€” the whole install looks healthy while
            // every event is dropped.
            //
            // Writing the concrete port here removes the dependency on
            // directory discovery entirely. It is already declared in each
            // entry's allowedEnvVars, so it reaches the subprocess.
            jsonc::set_env_var_cst(root, port_env, &port.to_string())?;
        }
        *actions.borrow_mut() = a;
        Ok(())
    })?;

    let actions = actions.into_inner();

    let mut state =
        HookStateFile::load(&openlatch_dir)?.unwrap_or_else(|| HookStateFile::new("kid-01".into()));

    for (et, entry, entry_id) in &entries_with_markers {
        let hmac_val = entry["_openlatch"]["hmac"]
            .as_str()
            .map(str::to_string)
            .unwrap_or_default();

        state.upsert_entry(StateEntry {
            id: entry_id.clone(),
            agent: binding.agent_type().into(),
            settings_path_hash: settings_path_hash.clone(),
            hook_event: et.clone(),
            expected_entry_hmac: hmac_val,
            daemon_port_at_install: port,
            daemon_token_fp: token_fp.clone(),
            // A JSON-file agent has no script on disk to describe. The field
            // exists for the `HookSurface::Directory` arm, which records one
            // descriptor per script it wrote.
            descriptor: None,
            v: hook_state::STATE_ENTRY_VERSION,
        });
    }

    if let Err(e) = state.save(&openlatch_dir) {
        tracing::warn!(
            code = crate::error::ERR_STATE_FILE_WRITE_FAILED,
            error = %e,
            "failed to write hook state file โ€” hooks installed but state file out of sync"
        );
    }

    let entries = event_types
        .iter()
        .zip(actions)
        .map(|(&et, action)| HookEntryStatus {
            event_type: et.to_string(),
            action,
        })
        .collect();

    Ok(HookInstallResult {
        entries,
        // No skip rule on this arm โ€” every event type is written.
        left_alone: Vec::new(),
    })
}

/// [`install_hooks`] for a surface that is a **directory of hook scripts**.
///
/// Ten files rather than ten entries in one file, and the differences are the
/// whole reason this is a separate arm: there is no JSONC document to rewrite,
/// no `env` block to write, and the ownership marker lives *inside each script*
/// rather than in a `_openlatch` key beside it.
///
/// Everything it needs is a parameter. [`hook_files`] resolves nothing, and this
/// is the function that hands it the directory it may write into โ€” see
/// `install_hooks`' `match`.
///
/// # No token reaches this directory (D-09)
///
/// The `EnvVars` channel writes the daemon's bearer token **value** into the
/// agent's own config file. A directory surface has no such file and this arm
/// writes no token anywhere: each shim carries `--openlatch-dir` and finds the
/// port and the credential through the OpenLatch state directory, which is why
/// [`binding::DaemonChannel::OpenlatchDirArg`] is the only channel a directory
/// binding can honestly declare. `token` is read here for its **fingerprint**,
/// which goes into the state file under `$OPENLATCH_DIR` โ€” never into a script,
/// never into the agent's store. `no_token_reaches_the_hook_directory` is the
/// assertion.
///
/// # Collisions
///
/// [`hook_files::write_all`] owns the decision, per path: a file failing the
/// ownership predicate is the developer's and is left exactly as it is, with
/// the install continuing through the other nine, and one that passes is ours
/// and is backed up to `<name>.bak` before being rewritten. A skipped path
/// produces **no state row and no [`HookEntryStatus`]** โ€” an install that did
/// not write a file must not report one.
///
/// # The eleventh artefact
///
/// The ten capture and discard; the plugin is what can refuse. It is written
/// here rather than by [`hook_files::write_all`] because it shares almost
/// nothing with the ten โ€” a different root (the **store**, not the user-asset
/// root), mode `0644` rather than `0755` because Node imports it, and no hook
/// event to key a [`HookEntryStatus`] on. What it does share is the ownership
/// marker, and it shares [`hook_files::is_ours`] itself rather than a copy.
///
/// A binding that returns `None` from [`AgentBinding::plugin_surface`] gets
/// none, which is what keeps every directory-surface fixture โ€” and any future
/// directory agent with no plugin lane โ€” writing exactly ten files.
///
/// # Errors
///
/// - `OL-1401` if the directory or one of the scripts cannot be written.
fn install_hook_files(
    binding: &dyn AgentBinding,
    hooks_dir: &std::path::Path,
    hook_bin: &std::path::Path,
    openlatch_dir: &std::path::Path,
    port: u16,
    token: &str,
) -> Result<HookInstallResult, OlError> {
    // No pre-pass. `write_all` classified every path through `whatever_is_there`
    // on its way past and reports the answer as `WrittenHookFile::replaced`, so
    // a second walk stat'ing all ten would re-derive what it already knew โ€” and
    // could disagree with it.
    let report = hook_files::write_all(hooks_dir, hook_bin, openlatch_dir)?;
    let written = &report.written;

    let key_store = HmacKeyStore::new(openlatch_dir);
    let hmac_key = key_store.load_or_create()?;

    let token_fp = crate::core::hook_state::key::key_fingerprint(token.as_bytes());
    // The directory is what the whole set of rows is keyed to. The natural key
    // is `(agent, settings_path_hash, hook_event)` and `hook_event` already
    // separates the ten from one another, so hashing each file's own path would
    // only make the rows unfindable from the surface the binding reports.
    let settings_path_hash = hook_state::hash_settings_path(hooks_dir);

    let mut state =
        HookStateFile::load(openlatch_dir)?.unwrap_or_else(|| HookStateFile::new("kid-01".into()));

    for file in written {
        // The descriptor is what gets signed. There is no hook entry to HMAC
        // here โ€” the tamper-evident object a JSON agent carries in `_openlatch`
        // has no equivalent in a shell script โ€” and the descriptor is a JSON
        // object, so it goes through `compute_entry_hmac` exactly as an entry
        // does. Its `canonicalize_entry` rejects a non-object, which is the
        // reason `FileDescriptor` is a struct rather than a bare hash string.
        let descriptor = serde_json::to_value(&file.descriptor)
            .expect("FileDescriptor is a plain struct and serializes");
        let hmac_value = compute_entry_hmac(&descriptor, &hmac_key)?;

        state.upsert_entry(StateEntry {
            // The writer's id, never a fresh one: it is already written into
            // that file's marker line, and minting a second here would put two
            // different ids on one script.
            id: file.entry_id.clone(),
            agent: binding.agent_type().into(),
            settings_path_hash: settings_path_hash.clone(),
            hook_event: file.event.clone(),
            expected_entry_hmac: hmac_value,
            daemon_port_at_install: port,
            daemon_token_fp: token_fp.clone(),
            // The point of the row. An HMAC is not reversible, so health and
            // the reconciler cannot recover the body hash they should find on
            // disk from `expected_entry_hmac` โ€” it has to be stored.
            descriptor: Some(file.descriptor.clone()),
            v: hook_state::STATE_ENTRY_VERSION,
        });
    }

    let entries = report
        .written
        .iter()
        .map(|file| HookEntryStatus {
            action: if file.replaced {
                HookAction::Replaced
            } else {
                HookAction::Added
            },
            event_type: file.event.clone(),
        })
        .collect();

    let mut left_alone = report.left;

    // The ELEVENTH artefact, and the only one that can refuse a tool call.
    //
    // Beside the ten rather than inside `hook_files::write_all`, because it is
    // not one of them in any respect that matters: a different root (the store,
    // not the user-asset root), a different mode (0644 โ€” Node imports it), a
    // different lane (a verdict, where the ten discard one) and no hook event to
    // key a `HookEntryStatus` on. What it DOES share is the ownership marker,
    // and it shares the predicate itself rather than a copy of it.
    //
    // A binding that declares no plugin surface writes nothing here โ€” which is
    // what keeps the directory-surface fixtures, and any future directory agent
    // without a plugin lane, exactly as they were.
    //
    // A failure here is HELD rather than propagated. The ten are already on
    // disk and their rows are still unsaved at this point, so `?`-ing out would
    // lose the record of ten files that were written successfully because an
    // eleventh, under a different root, was not โ€” and a row that was never
    // written is a file the reconciler never verifies.
    let mut plugin_failure: Option<OlError> = None;
    if let Some(plugin_dir) = binding.plugin_surface() {
        match cline_plugin::install(&plugin_dir, openlatch_dir) {
            // One row, whether or not this run had anything to write. An
            // install that found the plugin already current still has to record
            // it, or a host whose state file was lost never gets the row back
            // and the reconciler stops watching the one artefact that enforces.
            Ok(cline_plugin::PluginWrite::Written { descriptor, .. })
            | Ok(cline_plugin::PluginWrite::AlreadyCurrent(descriptor)) => {
                if let Err(e) = record_plugin_entry(
                    &mut state,
                    binding,
                    &descriptor,
                    &hmac_key,
                    port,
                    &token_fp,
                ) {
                    plugin_failure = Some(e);
                }
            }
            // Reported through `left_alone`, the same channel a hook-file
            // collision uses: a path we refused to write is the one thing a
            // caller has to be told about, and re-deriving it would mean
            // stat-ing a file we deliberately did not read.
            //
            // No row either. The row is what authorises the reconciler to
            // rewrite this path without asking the file's own marker, so
            // recording one for a file we just refused to touch would hand heal
            // the developer's plugin on the next poll.
            Ok(cline_plugin::PluginWrite::LeftAlone(path)) => left_alone.push(path),
            Err(e) => plugin_failure = Some(e),
        }
    }

    // One save, after the eleventh artefact rather than before it โ€” otherwise
    // the plugin's row waits for the next install to reach disk and the
    // reconciler spends that whole time unable to see the file that enforces.
    if let Err(e) = state.save(openlatch_dir) {
        tracing::warn!(
            code = crate::error::ERR_STATE_FILE_WRITE_FAILED,
            error = %e,
            "failed to write hook state file โ€” hooks installed but state file out of sync"
        );
    }

    if let Some(e) = plugin_failure {
        return Err(e);
    }

    Ok(HookInstallResult {
        entries,
        left_alone,
    })
}

/// Record the enforcement plugin's **one** state row (plan 02 ยง3a).
///
/// Keyed on the triple the ten use โ€” `(agent, settings_path_hash, hook_event)`
/// โ€” built from the plugin's **file** path rather than its directory, because
/// the file is the artefact the reconciler reads and the directory is only the
/// id, and under [`cline_plugin::PLUGIN_ENTRY_EVENT`] rather than a hook name
/// the plugin does not have.
///
/// The row exists for exactly one reason: the reconciler needs a **stored**
/// expected hash. The self-describing marker proves a file is internally
/// consistent, not that it is what we would write today โ€” and a plugin
/// corrupted badly enough to break that marker fails the ownership predicate
/// outright, which is precisely the damage heal exists to repair.
///
/// The id is reused when a row is already there. The ten mint a fresh UUIDv7
/// per write because the id is embedded in each script's own marker line; the
/// plugin's marker carries none, so a new id per install would be pure churn โ€”
/// and the reconciler's per-entry circuit breaker keys on it, so churning it
/// would reset the breaker on every heal and let a plugin that cannot be
/// written spin forever.
fn record_plugin_entry(
    state: &mut HookStateFile,
    binding: &dyn AgentBinding,
    descriptor: &crate::core::hook_state::FileDescriptor,
    hmac_key: &[u8],
    port: u16,
    token_fp: &str,
) -> Result<(), OlError> {
    let agent = binding.agent_type();
    let settings_path_hash = hook_state::hash_settings_path(std::path::Path::new(&descriptor.path));

    let id = state
        .entries
        .iter()
        .find(|e| {
            e.agent == agent
                && e.settings_path_hash == settings_path_hash
                && e.hook_event == cline_plugin::PLUGIN_ENTRY_EVENT
        })
        .map_or_else(|| uuid::Uuid::now_v7().to_string(), |e| e.id.clone());

    // The descriptor is what gets signed, exactly as it is for the ten: a
    // plain JSON object through `compute_entry_hmac`, so the row's integrity at
    // rest goes through one path for every surface shape.
    let value =
        serde_json::to_value(descriptor).expect("FileDescriptor is a plain struct and serializes");
    let expected_entry_hmac = compute_entry_hmac(&value, hmac_key)?;

    state.upsert_entry(StateEntry {
        id,
        agent: agent.into(),
        settings_path_hash,
        hook_event: cline_plugin::PLUGIN_ENTRY_EVENT.into(),
        expected_entry_hmac,
        daemon_port_at_install: port,
        daemon_token_fp: token_fp.into(),
        descriptor: Some(descriptor.clone()),
        v: hook_state::STATE_ENTRY_VERSION,
    });

    Ok(())
}

/// Remove everything [`install_hooks`] wrote into the detected agent's config.
///
/// Two halves, both of them ours:
///
/// - hook entries carrying the OpenLatch ownership marker (either the legacy
///   `"_openlatch": true` boolean or the current tamper-evident object);
/// - the two `env` keys the binding's [`DaemonChannel`] names โ€” for an
///   `OpenlatchDirArg` agent there are none, because install wrote none.
///
/// Hooks and env vars belonging to other tools are never touched. The `env`
/// half is not a courtesy: it used to be missing, so `openlatch uninstall`
/// removed the hooks and left the bearer token in plaintext in `settings.json`
/// next to a port no daemon answers on โ€” `--purge` included, which is the one
/// command that promises to leave nothing behind. Uninstall is the inverse of
/// install or it is a half-uninstall.
///
/// # Errors
///
/// - `OL-1401` if settings.json cannot be read or written.
/// - `OL-1402` if settings.json contains malformed JSONC.
pub fn remove_hooks(binding: &dyn AgentBinding) -> Result<(), OlError> {
    // The same backstop as `install_hooks`, and it cannot be the same
    // statement: this function returns `Result<(), OlError>` and that one
    // returns `Result<HookInstallResult, OlError>`.
    //
    // Uninstall is a writer too โ€” it reaches `atomic_rewrite_jsonc` below. The
    // `exists()` early return that follows is NOT a substitute: a binding whose
    // hook path is a **directory** passes it, because `Path::exists()` is true
    // for a directory, and Cline's hook path is exactly that. The rewrite would
    // then run against a directory.
    //
    // Nothing we wrote can be there to remove, so succeeding without touching
    // anything is the honest answer, not a silent skip.
    if !binding.installable() {
        return Ok(());
    }

    // Same `match` as `install_hooks`, and for the sharper reason: the
    // `exists()` check below is TRUE for a directory, so a `Directory` binding
    // would sail past it into `atomic_rewrite_jsonc`.
    //
    // This arm lands in the SAME change as the installer, never after it. Once
    // a build has written ten scripts to a host, a build that can no longer
    // remove them orphans them there: `uninstall` skips a non-installable agent
    // before it ever reaches this function, so nothing would be left that takes
    // them off the developer's disk.
    let settings_path = match binding.hook_surface() {
        HookSurface::ConfigFile(path) => path,
        HookSurface::Directory(dir) => return remove_hook_files(binding, &dir),
    };
    if !settings_path.exists() {
        return Ok(());
    }

    // Ask the binding which keys install actually wrote, exactly as `install_hooks`
    // does โ€” same `match`, same source of truth. Hardcoding the two constants here
    // would make uninstall Claude-shaped in shared code: a second binding whose
    // `EnvVars` channel names different keys would leave its bearer token behind in
    // plaintext, and an `OpenlatchDirArg` agent has no `env` block to strip at all.
    // For Claude Code the channel answers exactly `OPENLATCH_TOKEN_ENV` /
    // `OPENLATCH_PORT_ENV`, so the bytes removed today are unchanged.
    let env_keys = match binding.daemon_channel() {
        binding::DaemonChannel::EnvVars {
            token: token_env,
            port: port_env,
        } => Some((token_env, port_env)),
        binding::DaemonChannel::OpenlatchDirArg => None,
    };

    atomic::atomic_rewrite_jsonc(&settings_path, |root| {
        jsonc::remove_owned_entries_cst(root)?;
        if let Some((token_env, port_env)) = env_keys {
            jsonc::remove_env_var_cst(root, token_env)?;
            jsonc::remove_env_var_cst(root, port_env)?;
        }
        Ok(())
    })?;

    Ok(())
}

/// [`remove_hooks`] for a surface that is a **directory of hook scripts**.
///
/// [`hook_files::remove_all`] confirms the ownership predicate per file โ€”
/// marker line **and** recomputed hash โ€” and removes only what satisfies it.
/// The enforcement plugin goes the same way, from the other root, in the same
/// arm that installed it: left behind, it keeps loading into every session and
/// pointing at a daemon that is no longer there.
/// There is no install id to compare against and no state file is consulted:
/// the self-describing hash is the whole predicate, which is what lets an
/// uninstall work on a host whose state file was lost, and what keeps a script
/// the developer wrote under one of the ten names off the removal list.
///
/// # A partial removal is a success
///
/// Deliberately, and the [`remove_hooks`] signature is what carries it:
/// `uninstall` gates the model-relay teardown on this returning `Ok`, so an
/// `Err` over a file we were never going to touch leaves the agent pointed at a
/// loopback port no daemon answers on. Files left in place are reported through
/// a warning per path from `remove_all`, plus the summary below so one line in
/// the log says how the removal as a whole came out.
fn remove_hook_files(
    binding: &dyn AgentBinding,
    hooks_dir: &std::path::Path,
) -> Result<(), OlError> {
    let report = hook_files::remove_all(hooks_dir)?;

    if !report.left.is_empty() {
        tracing::warn!(
            dir = %hooks_dir.display(),
            removed = report.removed.len(),
            left = report.left.len(),
            "left hook files we did not write in place; uninstall removed only our own"
        );
    }

    // The enforcement plugin, in the same arm that installed it. It lives under
    // a DIFFERENT root from the ten, so `remove_all` above cannot reach it and
    // an uninstall that stopped there would leave the one artefact that can
    // refuse a tool call still loading into every Cline session โ€” pointed at a
    // daemon that is no longer there.
    //
    // Same marker predicate as the ten: a plugin failing it is the developer's
    // and is left exactly where it is, reported and not removed.
    if let Some(plugin_dir) = binding.plugin_surface() {
        match cline_plugin::remove(&plugin_dir)? {
            cline_plugin::PluginRemoval::Removed(_) | cline_plugin::PluginRemoval::Nothing => {}
            cline_plugin::PluginRemoval::LeftAlone(path) => tracing::warn!(
                path = %path.display(),
                "left a plugin we did not write in place; uninstall removed only our own"
            ),
        }
        // The state row goes WITH the file (plan 02 ยง3a.3), and it is not
        // bookkeeping. The reconciler reads a missing file as drift and heals
        // it by reinstalling, so a row left behind re-creates the plugin on the
        // next 30-second poll โ€” an uninstall that silently undoes itself.
        //
        // Unconditional, including the path we just refused to remove: after an
        // uninstall we hold no claim on it at all, and the row is precisely
        // what would authorise heal to rewrite the developer's own file there.
        forget_plugin_entry(binding, &cline_plugin::entry_path(&plugin_dir));
    }

    Ok(())
}

/// Drop the enforcement plugin's state row, best effort.
///
/// Best effort and not a `Result`, for the reason stated above: `uninstall`
/// gates the model-relay teardown on `remove_hooks` returning `Ok`, and an
/// `Err` raised over the state file would leave the agent pointed at a loopback
/// port no daemon answers on. A row that could not be dropped is a warning; a
/// half-uninstalled agent is a broken machine.
fn forget_plugin_entry(binding: &dyn AgentBinding, entry_path: &std::path::Path) {
    let openlatch_dir = crate::config::openlatch_dir();
    let mut state = match HookStateFile::load(&openlatch_dir) {
        Ok(Some(state)) => state,
        // No state file is nothing to forget โ€” an uninstall on a host whose
        // state was lost still removed the artefact, which is what matters.
        Ok(None) => return,
        Err(e) => {
            tracing::warn!(
                error = %e,
                "uninstall: cannot read the hook state file to drop the plugin's row"
            );
            return;
        }
    };

    if !state.remove_entry(
        binding.agent_type(),
        &hook_state::hash_settings_path(entry_path),
        cline_plugin::PLUGIN_ENTRY_EVENT,
    ) {
        return;
    }

    if let Err(e) = state.save(&openlatch_dir) {
        tracing::warn!(
            code = crate::error::ERR_STATE_FILE_WRITE_FAILED,
            error = %e,
            "uninstall: the plugin is gone but its state row could not be dropped โ€” \
             the reconciler may re-create it"
        );
    }
}

// ---------------------------------------------------------------------------
// Model-relay config wiring (D-07 / D-01)
// ---------------------------------------------------------------------------

/// Env var name Claude Code reads for the model-provider base URL.
pub const ANTHROPIC_BASE_URL_ENV: &str = "ANTHROPIC_BASE_URL";
/// Env var name Claude Code reads for extra static request headers.
/// Newline-separated `Name: Value` entries (Anthropic SDK convention).
pub const ANTHROPIC_CUSTOM_HEADERS_ENV: &str = "ANTHROPIC_CUSTOM_HEADERS";
/// Both spellings of the agent's proxy-bypass variable.
///
/// Both, always. Node reads `NO_PROXY`; a great deal of tooling in the same process tree
/// reads `no_proxy`; and which one wins is not something this client gets to decide inside
/// somebody else's runtime. Writing one and not the other is a coin flip on whether the
/// bypass applies at all.
const NO_PROXY_ENV_KEYS: [&str; 2] = ["NO_PROXY", "no_proxy"];

/// The entries D-24 guarantees are present, in the order they are appended.
const LOOPBACK_BYPASS_ENTRIES: [&str; 2] = ["127.0.0.1", "localhost"];

/// Merge the loopback entries into an existing comma-separated bypass list.
///
/// Verified against a live Claude Code (2026-08): **it has no implicit loopback bypass.**
/// With a corporate `HTTPS_PROXY` in the environment and the model relay enabled, the
/// agent issues `CONNECT 127.0.0.1:7600` to the corporate proxy, which has no route to the
/// customer's own laptop and answers 502. Every model call on the host fails, and nothing
/// in any log looks like a proxy problem. This is the fix, and it has to live in the
/// agent's own environment because the agent is the process making the connection.
///
/// Additive-only, byte-for-byte, in the `merge_install_id_header` discipline: every
/// pre-existing entry survives in its original order and its original spelling. A customer
/// bypass list is a security control in its own right, and reordering or normalising it is
/// a change we have no mandate to make.
fn merge_loopback_entries(existing: Option<&str>) -> String {
    let mut entries: Vec<String> = existing
        .unwrap_or_default()
        .split(',')
        .map(str::trim)
        .filter(|e| !e.is_empty())
        .map(str::to_string)
        .collect();
    for wanted in LOOPBACK_BYPASS_ENTRIES {
        // Case-insensitive, because `LOCALHOST` and `localhost` are the same host and
        // appending a second spelling is noise the customer has to read past forever.
        if !entries.iter().any(|e| e.eq_ignore_ascii_case(wanted)) {
            entries.push(wanted.to_string());
        }
    }
    entries.join(",")
}

/// `true` when a single custom-header line declares the OpenLatch install-id
/// header (name compared case-insensitively).
///
/// The name is a parameter rather than a module constant: it is declared by the
/// agent's own [`ModelRelayWiring`](binding::ModelRelayWiring), so the writer, the
/// merger and the stripper cannot disagree with the binding about which header
/// is ours.
fn is_install_id_line(line: &str, header: &str) -> bool {
    line.split_once(':')
        .map(|(name, _)| name.trim().eq_ignore_ascii_case(header))
        .unwrap_or(false)
}

/// Merge our install-id line INTO an existing `ANTHROPIC_CUSTOM_HEADERS` value,
/// preserving every customer line and replacing only a prior install-id line.
/// Additive-only: corporate proxy/routing/auth headers survive untouched.
///
/// Reuses [`strip_install_id_header`] for the parse-and-drop-our-line pass, then
/// appends our current line. `kept.is_empty()` is byte-equivalent to the old
/// empty-Vec check: `strip_install_id_header` joins only non-blank customer
/// lines with `\n`, so its result is empty exactly when no customer line remains.
fn merge_install_id_header(existing: Option<&str>, header: &str, install_id: &str) -> String {
    let kept = existing
        .map(|value| strip_install_id_header(value, header))
        .unwrap_or_default();
    let our_line = format!("{header}: {install_id}");
    if kept.is_empty() {
        our_line
    } else {
        format!("{kept}\n{our_line}")
    }
}

/// Strip OUR install-id line(s) from an existing `ANTHROPIC_CUSTOM_HEADERS`
/// value, returning the remaining customer lines (possibly empty).
fn strip_install_id_header(existing: &str, header: &str) -> String {
    existing
        .split('\n')
        .filter(|line| !line.trim().is_empty() && !is_install_id_line(line, header))
        .collect::<Vec<_>>()
        .join("\n")
}

/// `true` when `value` is a loopback base URL OpenLatch would have written โ€”
/// host `127.0.0.1`, any port, http or https. A customer-set base URL pointing
/// anywhere else must be left untouched on disable.
///
/// `pub(crate)` because the `TomlProvider` convention asks the identical
/// question of a `[model_providers.<name>].base_url`
/// (`codex_cli::provider_table_is_ours`). One predicate, so the two conventions
/// cannot disagree about what "ours" means.
/// **Not proof of authorship.** A customer running Ollama, LM Studio or
/// llama.cpp names a `127.0.0.1` endpoint of their own, and this answers `true`
/// for it. Every caller that is deciding "may I rewrite or delete this?" must
/// pair it with the durable record in [`model_relay_endpoints`], which is
/// written before the value commits and therefore exists for exactly the
/// entries we wrote. Callers scoped to a provider name WE chose (Codex's
/// `[model_providers.<ours>]`) need no pairing: the customer has no entry
/// there to confuse with ours.
pub(crate) fn is_openlatch_loopback_base_url(value: &str) -> bool {
    reqwest::Url::parse(value.trim())
        .ok()
        .and_then(|u| u.host_str().map(|h| h == "127.0.0.1"))
        .unwrap_or(false)
}

/// The file this agent's model relay wiring is written into, when it has a request
/// plane at all.
///
/// **Not [`AgentBinding::hook_config_path`], and the difference is easy to
/// miss.** Claude Code's hooks and its `ANTHROPIC_BASE_URL` share one
/// `settings.json`; Codex's do not โ€” its hooks live in `hooks.json` and its
/// provider table in `config.toml`. Every log line, remedy and diagnostic that
/// names "the file we wired" names this one, so the two layers cannot drift
/// into naming a file the writer never touched.
/// How an operator points ONE session at an isolated listener by hand, in that
/// agent's own vocabulary.
///
/// Naming `ANTHROPIC_BASE_URL` at a Codex agent is the same defect as pointing
/// a Codex user at `api.anthropic.com`: an instruction they cannot act on,
/// printed by the subsystem that is supposed to explain itself.
///
/// Keyed on the **endpoint convention**, never on the agent's wire name, so a
/// third agent that arrives with a `TomlProvider` is answered correctly without
/// touching this function. It lives here rather than in the daemon because all
/// three surfaces that print the hint โ€” the daemon's log, `openlatch system
/// model-relay status` and `openlatch start` โ€” must say the same sentence, and
/// two of them are compiled without the `model-relay` feature.
pub fn isolated_wiring_hint(binding: &dyn AgentBinding, port: u16) -> String {
    match binding.model_relay_wiring().map(|w| w.endpoint) {
        Some(binding::EndpointConvention::EnvVars { base_url, .. }) => {
            format!("{base_url}=http://127.0.0.1:{port}")
        }
        Some(binding::EndpointConvention::TomlProvider { provider_name, .. }) => format!(
            "a [model_providers.{provider_name}] table with base_url = \"http://127.0.0.1:{port}/v1\""
        ),
        None => "this agent has no request plane".to_string(),
    }
}

pub fn model_relay_config_path(binding: &dyn AgentBinding) -> Option<PathBuf> {
    match binding.model_relay_wiring()?.endpoint {
        binding::EndpointConvention::EnvVars { .. } => Some(binding.hook_config_path()),
        binding::EndpointConvention::TomlProvider { .. } => {
            Some(codex_cli::config_toml_path(&binding.config_dir()))
        }
    }
}

/// Point the agent at the model-relay listener, in whatever way that agent
/// names its model provider.
///
/// **Only the process holding `port` may call this.** The daemon does, right
/// after [`crate::model_relay::bind_pinned`] returns `Ok` โ€” never before, and never
/// from a process that will not go on to serve that port. Writing the base URL
/// on the strength of an intention to bind is what pointed every agent on the
/// machine at a port nobody held.
///
/// The binding decides the convention, not this function:
///
/// - [`EndpointConvention::EnvVars`] โ€” the JSONC path on
///   [`AgentBinding::hook_config_path`]: the base URL, the install-id header and
///   D-24's `NO_PROXY` / `no_proxy` loopback merge, with the two variable names
///   read from the variant rather than from an `ANTHROPIC_*` literal.
/// - [`EndpointConvention::TomlProvider`] โ€” the format-preserving
///   `[model_providers.<name>]` write on the agent's `config.toml`. **A
///   different file from that agent's hooks file**; do not assume one path per
///   agent.
/// - No [`AgentBinding::model_relay_wiring`] at all โ€” nothing is written, and that
///   is not an error. An agent with no request plane is a question that does
///   not apply.
///
/// Both arms record the endpoint the agent named **before** us, so uninstall can
/// put it back ([`model_relay_endpoints`]). The record is taken **only when the
/// current value is not already ours**: on a re-install it already is, and
/// recording it would overwrite the customer's real prior with our own value.
///
/// D-01 ships the plain-`http://` base URL as the default (the HTTPS +
/// `NODE_EXTRA_CA_CERTS` fallback is specified in `model_relay::bind_pinned`'s
/// docs but conditional on the empirical loopback spike). `install_id` MUST be
/// PII-free โ€” it reaches the provider on every request (F-22); the existing
/// `agent_id` is used verbatim (no new persisted field is introduced).
///
/// # Errors
///
/// Propagates whatever the convention's writer reports โ€” a malformed agent
/// config, an unwritable file, or (`TomlProvider` only)
/// [`crate::error::ERR_MODEL_RELAY_FOREIGN_PROVIDER`] when a provider table of our
/// name exists and is somebody else's.
pub fn write_model_relay_config(
    binding: &dyn AgentBinding,
    port: u16,
    install_id: &str,
) -> Result<(), OlError> {
    let Some(wiring) = binding.model_relay_wiring() else {
        return Ok(());
    };
    let agent = binding.agent_type();
    match wiring.endpoint {
        binding::EndpointConvention::EnvVars { base_url, headers } => {
            let settings_path = binding.hook_config_path();
            let our_base_url = format!("http://127.0.0.1:{port}");
            atomic::atomic_rewrite_jsonc(&settings_path, |root| {
                // D-10 โ€” remember what the agent pointed at before us, but only
                // when that value is not already ours. A second install
                // otherwise records our own loopback URL and uninstall
                // "restores" a dead port.
                let current = jsonc::get_env_var_cst(root, base_url);
                // OURS ONLY WITH PROOF, exactly as the JsonProvider arm below.
                // A loopback address is not authorship: an operator who points
                // this agent at their own local gateway names one too, and
                // treating that as "our own previous install" discards the only
                // record of where they were pointed โ€” `record` is skipped, so
                // uninstall has nothing to restore and the relay has nothing to
                // forward to.
                let we_wired_it_before = model_relay_endpoints::peek(agent).is_some();
                let already_ours = we_wired_it_before
                    && current
                        .as_deref()
                        .map(is_openlatch_loopback_base_url)
                        .unwrap_or(false);
                if !already_ours {
                    // AND where the relay must forward this format, when the
                    // agent named somewhere. Same contract as the JsonProvider
                    // arm: the value we are about to overwrite is the only
                    // statement of where this agent's provider actually is.
                    if let Some(ref endpoint) = current {
                        model_relay_endpoints::record(
                            &upstream_record_key(wiring.wire_format),
                            Some(endpoint.clone()),
                        )?;
                    }
                    model_relay_endpoints::record(agent, current)?;
                }
                jsonc::set_env_var_cst(root, base_url, &our_base_url)?;
                // Additive-only: merge our install-id line into any pre-existing
                // custom-headers value (corporate proxy/routing/auth headers)
                // rather than clobbering the whole value.
                let existing = jsonc::get_env_var_cst(root, headers);
                let merged = merge_install_id_header(
                    existing.as_deref(),
                    wiring.install_id_header,
                    install_id,
                );
                jsonc::set_env_var_cst(root, headers, &merged)?;
                // D-24 โ€” the base URL above points the agent at a loopback
                // listener, and on a proxied estate the agent would tunnel to it
                // through the corporate proxy and get a 502. Both spellings,
                // merge-preserving. Never recorded and never restored: see
                // `remove_model_relay_config`.
                for key in NO_PROXY_ENV_KEYS {
                    let existing = jsonc::get_env_var_cst(root, key);
                    let merged = merge_loopback_entries(existing.as_deref());
                    jsonc::set_env_var_cst(root, key, &merged)?;
                }
                Ok(())
            })
        }
        binding::EndpointConvention::TomlProvider {
            provider_name,
            wire_api,
        } => {
            let config_toml = codex_cli::config_toml_path(&binding.config_dir());
            // RECORD BEFORE THE WRITE COMMITS. The obvious order โ€” write, then
            // record what it displaced โ€” has a window: if recording fails or
            // the process dies between the two, the customer's file points at
            // us with no restoration record, and the eventual uninstall reads
            // "nothing was here before" and deletes a setting they had. The
            // reverse window is harmless by comparison: a record with no write
            // is never consumed, because uninstall's ownership test sees a
            // provider table that is not ours and returns early.
            let prior = codex_cli::read_prior_provider(&config_toml, provider_name)?;
            if let codex_cli::Prior::Theirs(ref p) = prior {
                model_relay_endpoints::record(agent, p.clone())?;
            }
            let write = codex_cli::write_provider_table(
                &config_toml,
                provider_name,
                wire_api,
                wiring.install_id_header,
                port,
                install_id,
            );
            if write.is_err() && matches!(prior, codex_cli::Prior::Theirs(_)) {
                // Best effort: the write we recorded for did not happen, so the
                // record describes nothing. Leaving it is survivable (see
                // above); clearing it is tidier.
                model_relay_endpoints::forget(agent);
            }
            write.map(|_| ())
        }
    }
}

/// Remove the model-relay wiring, and put back whatever the agent named
/// before it.
///
/// Called by the daemon when it stops holding the pinned port (teardown), or
/// when it starts with the model relay disabled (reconciliation after a SIGKILL or
/// a config change); by `openlatch stop` as a net for the escalation paths where
/// the daemon never got to run its own teardown; and by `openlatch uninstall`.
///
/// **Idempotent, because it runs two or three times per uninstall.** Both arms
/// test ownership *before* consuming the record, so a second pass finds nothing
/// of ours, changes nothing, and cannot delete the pointer the first pass
/// restored.
///
/// Additive-safe reversal:
///
/// - The base URL / provider table is reclaimed ONLY while it still names our
///   loopback listener; a customer-set endpoint is left untouched.
/// - The custom-headers value loses only OUR install-id line(s); any customer
///   headers survive. If nothing remains, the key is dropped entirely.
/// - **`NO_PROXY` / `no_proxy` are deliberately left alone**, loopback entries included.
///   `127.0.0.1` and `localhost` carry no ownership marker: a customer whose bypass list
///   already named them, or who added them for their own tooling, is indistinguishable
///   from one who got them from us, and stripping the entries would break their setup to
///   tidy ours. Leaving a host's own loopback in its own bypass list costs nothing โ€” it is
///   the correct value for that host whether OpenLatch is installed or not. This is a
///   contract, not an oversight: `tests/cli_contract.rs` asserts the entries survive.
///   It follows that the bypass is never *recorded* either โ€” ยง2's record covers
///   the endpoint only.
///
/// A no-op when the file, the keys or the request plane are absent.
pub fn remove_model_relay_config(binding: &dyn AgentBinding) -> Result<(), OlError> {
    let Some(wiring) = binding.model_relay_wiring() else {
        return Ok(());
    };
    let agent = binding.agent_type();
    match wiring.endpoint {
        binding::EndpointConvention::EnvVars { base_url, headers } => {
            let settings_path = binding.hook_config_path();
            if !settings_path.exists() {
                return Ok(());
            }
            atomic::atomic_rewrite_jsonc(&settings_path, |root| {
                // Only reclaim the base URL if it is OUR loopback URL โ€” and ask
                // that BEFORE taking the record, or a second pass drops the
                // customer's recorded prior on the floor.
                if let Some(current) = jsonc::get_env_var_cst(root, base_url) {
                    if is_openlatch_loopback_base_url(&current) {
                        // D-10 โ€” put the customer's endpoint back.
                        //
                        // `Some(None)` is "they named none". `None` is "no
                        // record at all", which is an install that predates the
                        // record store โ€” and it removes the key too, because
                        // the daemon's stale-wiring reconciliation is exactly
                        // that case: a SIGKILLed daemon leaves a base URL on
                        // disk with no record, and the next start has to clear
                        // it or every session on the host dies on a dead port
                        // (`tests/model_relay_wiring.rs`'s
                        // `startup_clears_a_stale_base_url_when_the_model_relay_is_off`).
                        // The second-uninstall-pass hazard those two arms are
                        // otherwise told apart for is already closed one line
                        // up: the ownership test above is false once the key is
                        // gone or the customer's own value is back.
                        //
                        // A replace, never remove-then-add: `set_env_var_cst`
                        // leaves the key where the customer had it, with the
                        // comments around it.
                        // PEEK, not take. `take` deletes the entry first, so a
                        // rewrite that then failed at the rename would leave the
                        // agent pointed at us with its real prior endpoint gone
                        // for good. The record is cleared after the write lands.
                        match model_relay_endpoints::peek(agent) {
                            Some(Some(prior)) => jsonc::set_env_var_cst(root, base_url, &prior)?,
                            Some(None) | None => jsonc::remove_env_var_cst(root, base_url)?,
                        }
                    }
                }
                // Strip only our install-id line from the custom-headers value.
                if let Some(current) = jsonc::get_env_var_cst(root, headers) {
                    let remainder = strip_install_id_header(&current, wiring.install_id_header);
                    if remainder.trim().is_empty() {
                        jsonc::remove_env_var_cst(root, headers)?;
                    } else {
                        jsonc::set_env_var_cst(root, headers, &remainder)?;
                    }
                }
                Ok(())
            })?;
            // Cleared only now, after the atomic rewrite has landed. See the
            // `peek` comment above: consuming the record before the rename
            // would lose the customer's prior endpoint on a failed write.
            model_relay_endpoints::forget(agent);
            // And where the relay forwarded this format on the agent's behalf:
            // with the agent restored there is nothing left to forward for, and
            // a surviving record would keep routing the next install's traffic
            // to an endpoint the customer has since left.
            model_relay_endpoints::forget(&upstream_record_key(wiring.wire_format));
            Ok(())
        }
        binding::EndpointConvention::TomlProvider { provider_name, .. } => {
            let config_toml = codex_cli::config_toml_path(&binding.config_dir());
            // Ownership first, record second: `take` deletes the entry, and an
            // implementation that takes before it knows the table is ours drops
            // the customer's recorded prior on the second uninstall pass.
            let is_ours = std::fs::read_to_string(&config_toml)
                .ok()
                .and_then(|raw| raw.parse::<toml_edit::DocumentMut>().ok())
                .and_then(|doc| codex_cli::provider_table_is_ours(&doc, provider_name))
                == Some(true);
            if !is_ours {
                return Ok(());
            }
            // PEEK, then clear only once the rewrite has landed โ€” same reason
            // as the arm above: `take` would drop the customer's real prior on
            // a rename that failed.
            let result = codex_cli::remove_provider_table(
                &config_toml,
                provider_name,
                model_relay_endpoints::peek(agent),
            );
            if result.is_ok() {
                model_relay_endpoints::forget(agent);
            }
            result
        }
    }
}

/// The record naming where the relay must forward one wire format.
///
/// A different namespace from [`provider_record_key`] on purpose: that one
/// answers "what do I restore this agent's config to on uninstall", this one
/// answers "where does this format's traffic actually go". They happen to carry
/// the same string today โ€” the endpoint we replaced is both โ€” but they are
/// consumed by different subsystems at different times, and collapsing them
/// would make an uninstall's `forget` silently change the live forward path.
pub(crate) fn upstream_record_key(fmt: crate::model_relay::wire_format::WireFormat) -> String {
    format!("upstream:{}", fmt.as_str())
}

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

#[cfg(test)]
mod tests {

    /// **Zero regression.** Adding a third endpoint convention changed neither
    /// shipped binding's answer.
    ///
    /// Both are pinned as literals rather than compared to themselves: the
    /// failure this guards against is a new variant pulling one of them along โ€”
    /// an `EnvVars` that quietly became a `JsonProvider`, a `wire_api` that
    /// moved โ€” and a self-comparison would pass through all of it.
    #[test]
    #[cfg(feature = "model-relay")]
    fn claude_and_codex_wiring_unchanged() {
        use crate::hooks::binding::{AgentBinding, EndpointConvention};
        use crate::model_relay::wire_format::WireFormat;

        let root = tempfile::tempdir().expect("temp dir");
        let claude = crate::hooks::bindings::claude_code::ClaudeCodeBinding {
            claude_dir: root.path().to_path_buf(),
            settings_path: root.path().join("settings.json"),
        };
        let w = claude
            .model_relay_wiring()
            .expect("Claude Code has a request plane");
        assert_eq!(w.wire_format, WireFormat::AnthropicMessages);
        assert_eq!(w.install_id_header, "x-openlatch-install-id");
        assert!(
            matches!(
                w.endpoint,
                EndpointConvention::EnvVars {
                    base_url: "ANTHROPIC_BASE_URL",
                    headers: "ANTHROPIC_CUSTOM_HEADERS",
                }
            ),
            "Claude Code's two environment variable names, unchanged: {:?}",
            w.endpoint
        );

        let codex = crate::hooks::bindings::codex_cli::CodexCliBinding {
            codex_dir: root.path().to_path_buf(),
            hooks_path: root.path().join("hooks.json"),
            requirements_toml: None,
        };
        let w = codex
            .model_relay_wiring()
            .expect("Codex CLI has a request plane");
        assert_eq!(w.wire_format, WireFormat::OpenAiResponses);
        assert_eq!(w.install_id_header, "x-openlatch-install-id");
        assert!(
            matches!(
                w.endpoint,
                EndpointConvention::TomlProvider {
                    provider_name: "openlatch",
                    wire_api: "responses",
                }
            ),
            "Codex's provider table name and wire_api, unchanged: {:?}",
            w.endpoint
        );

        // And the file each one's wiring is written into is still its own.
        assert!(crate::hooks::model_relay_config_path(&claude)
            .expect("a wiring path")
            .ends_with("settings.json"));
        assert!(crate::hooks::model_relay_config_path(&codex)
            .expect("a wiring path")
            .ends_with("config.toml"));
    }

    /// D-24's merge, in isolation.
    #[test]
    fn loopback_entries_are_added_when_the_list_is_empty() {
        assert_eq!(super::merge_loopback_entries(None), "127.0.0.1,localhost");
        assert_eq!(
            super::merge_loopback_entries(Some("")),
            "127.0.0.1,localhost"
        );
    }

    /// A customer bypass list is a security control in its own right. Every entry keeps
    /// its place and its spelling.
    #[test]
    fn customer_entries_survive_byte_for_byte() {
        assert_eq!(
            super::merge_loopback_entries(Some("internal.corp,10.0.0.0/8,.corp.example")),
            "internal.corp,10.0.0.0/8,.corp.example,127.0.0.1,localhost"
        );
    }

    /// Idempotent, and case-insensitively so: re-running `init` must not grow the list by
    /// two entries every time, and `LOCALHOST` is the same host as `localhost`.
    #[test]
    fn the_merge_is_idempotent() {
        let once = super::merge_loopback_entries(Some("internal.corp"));
        let twice = super::merge_loopback_entries(Some(&once));
        assert_eq!(once, twice);
        assert_eq!(
            super::merge_loopback_entries(Some("LOCALHOST,internal.corp")),
            "LOCALHOST,internal.corp,127.0.0.1"
        );
    }

    /// Whitespace an operator left around their own entries is not a reason to add a
    /// duplicate.
    #[test]
    fn spacing_does_not_produce_duplicates() {
        assert_eq!(
            super::merge_loopback_entries(Some(" localhost , internal.corp ")),
            "localhost,internal.corp,127.0.0.1"
        );
    }

    /// Smoke-test detect_agent when ~/.claude/ does NOT exist.
    ///
    /// We override HOME so that dirs::home_dir() points to an empty tempdir,
    /// and clear every config-dir seam that would win over it.
    #[test]
    #[cfg(unix)]
    fn test_detect_agent_returns_ol_1400_when_no_claude_dir() {
        use super::detect_agent;
        use crate::error::ERR_HOOK_AGENT_NOT_FOUND;

        // Every config-dir seam must be controlled, and controlled exclusively:
        // each `detect` honours its own variable *over* $HOME, and other suites
        // set them concurrently. See `claude_code::CONFIG_DIR_ENV_LOCK`, and
        // `codex_cli::CONFIG_DIR_ENV_LOCK` โ€” taken last, the ordering rule for
        // every test that needs both. `$CODEX_HOME` joined this list when
        // `detect_agents` gained its Codex arm: redirecting `$HOME` alone hides
        // `~/.codex` but not an exported `CODEX_HOME`, and this assertion is
        // that NO agent is found.
        let _env = crate::hooks::claude_code::CONFIG_DIR_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let _codex_env = crate::hooks::codex_cli::CONFIG_DIR_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        // Cline's seam lock, taken last โ€” the tail of the crate's documented
        // order. It joined this test when `detect_all` gained its Cline arm,
        // for exactly the reason `$CODEX_HOME` joined it when the Codex arm
        // landed: redirecting `$HOME` hides `~/.cline`, but not an exported
        // `CLINE_DIR`, and this assertion is that NO agent is found. Without
        // the lock a sibling holding a store root that exists races it.
        let _cline_env = crate::hooks::cline::SEAM_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let cline_root = tempfile::tempdir().unwrap();
        // Declared after every lock, so it is dropped before them.
        let _cline_seams = crate::hooks::cline::EnvOverride::absent_cline_seams(cline_root.path());
        let dir = tempfile::tempdir().unwrap();
        let prev_claude = std::env::var(crate::hooks::claude_code::CONFIG_DIR_ENV).ok();
        let prev_codex = std::env::var(crate::hooks::codex_cli::CONFIG_DIR_ENV).ok();
        std::env::remove_var(crate::hooks::claude_code::CONFIG_DIR_ENV);
        std::env::remove_var(crate::hooks::codex_cli::CONFIG_DIR_ENV);
        // Override HOME so neither ~/.claude/ nor ~/.codex/ exists.
        std::env::set_var("HOME", dir.path());
        let result = detect_agent();
        std::env::remove_var("HOME");
        if let Some(v) = prev_claude {
            std::env::set_var(crate::hooks::claude_code::CONFIG_DIR_ENV, v);
        }
        if let Some(v) = prev_codex {
            std::env::set_var(crate::hooks::codex_cli::CONFIG_DIR_ENV, v);
        }

        let err = result.unwrap_err();
        assert_eq!(
            err.code, ERR_HOOK_AGENT_NOT_FOUND,
            "Expected OL-1400, got {}",
            err.code
        );
    }

    // -----------------------------------------------------------------------
    // Model relay config wiring โ€” additive-only guarantee (FIX 2)
    // -----------------------------------------------------------------------

    use super::{
        remove_model_relay_config, write_model_relay_config, ANTHROPIC_CUSTOM_HEADERS_ENV,
    };
    use crate::hooks::binding::test_support::FakeBinding;
    use crate::hooks::binding::{EndpointConvention, ModelRelayWiring};

    /// An `EnvVars` agent rooted at `dir`, carrying Claude Code's own two
    /// variable names and header โ€” the binding these tests drive shared code
    /// through, rather than a `ClaudeCodeBinding` under a config-dir env lock.
    fn envvars_agent(dir: &std::path::Path) -> FakeBinding {
        FakeBinding {
            agent_type: "claude-code",
            config_dir: dir.to_path_buf(),
            model_relay_wiring: Some(ModelRelayWiring {
                wire_format: crate::model_relay::wire_format::WireFormat::AnthropicMessages,
                endpoint: EndpointConvention::EnvVars {
                    base_url: super::ANTHROPIC_BASE_URL_ENV,
                    headers: super::ANTHROPIC_CUSTOM_HEADERS_ENV,
                },
                install_id_header: "x-openlatch-install-id",
            }),
            ..Default::default()
        }
    }

    /// Run `f` with `OPENLATCH_DIR` pointed at a tempdir, under **the** lock for
    /// that variable.
    ///
    /// Not optional hygiene: the writer records the endpoint the agent named
    /// before us into `$OPENLATCH_DIR/model-relay-endpoints.json`, so a test that
    /// left the variable alone would write the developer's real record.
    fn with_openlatch_dir<T>(f: impl FnOnce() -> T) -> T {
        let _guard = crate::config::OPENLATCH_DIR_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let tmp = tempfile::tempdir().expect("tempdir");
        let prev = std::env::var_os("OPENLATCH_DIR");
        std::env::set_var("OPENLATCH_DIR", tmp.path());
        let out = f();
        match prev {
            Some(v) => std::env::set_var("OPENLATCH_DIR", v),
            None => std::env::remove_var("OPENLATCH_DIR"),
        }
        out
    }

    /// Read a settings.json file back as plain JSON for assertions.
    fn read_env(path: &std::path::Path) -> serde_json::Value {
        let raw = std::fs::read_to_string(path).unwrap();
        serde_json::from_str(&raw).unwrap()
    }

    #[test]
    fn model_relay_enable_preserves_existing_custom_headers() {
        // (a) A customer already ships a corporate header; enable must append
        // our install-id line, keeping theirs.
        let dir = tempfile::tempdir().unwrap();
        let agent = envvars_agent(dir.path());
        let path = agent.hook_config_path();
        std::fs::write(
            &path,
            r#"{"env":{"ANTHROPIC_CUSTOM_HEADERS":"x-corp-proxy: foo"}}"#,
        )
        .unwrap();

        with_openlatch_dir(|| write_model_relay_config(&agent, 7600, "agt_x").unwrap());

        let v = read_env(&path);
        let headers = v["env"][ANTHROPIC_CUSTOM_HEADERS_ENV].as_str().unwrap();
        assert!(
            headers.contains("x-corp-proxy: foo"),
            "customer header must survive enable: {headers}"
        );
        assert!(
            headers.contains("x-openlatch-install-id: agt_x"),
            "our install-id line must be added: {headers}"
        );
        assert_eq!(v["env"]["ANTHROPIC_BASE_URL"], "http://127.0.0.1:7600");
    }

    #[test]
    fn model_relay_disable_keeps_customer_headers_and_drops_ours() {
        // (b) After enable, disable must remove ONLY our line โ€” the corporate
        // header (and the key itself) remain.
        let dir = tempfile::tempdir().unwrap();
        let agent = envvars_agent(dir.path());
        let path = agent.hook_config_path();
        std::fs::write(
            &path,
            r#"{"env":{"ANTHROPIC_CUSTOM_HEADERS":"x-corp-proxy: foo"}}"#,
        )
        .unwrap();

        with_openlatch_dir(|| {
            write_model_relay_config(&agent, 7600, "agt_x").unwrap();
            remove_model_relay_config(&agent).unwrap();
        });

        let v = read_env(&path);
        let headers = v["env"][ANTHROPIC_CUSTOM_HEADERS_ENV].as_str().unwrap();
        assert!(
            headers.contains("x-corp-proxy: foo"),
            "customer header must remain after disable: {headers}"
        );
        assert!(
            !headers.contains("x-openlatch-install-id"),
            "our install-id line must be gone: {headers}"
        );
        // Our loopback base URL was reclaimed.
        assert!(v["env"].get("ANTHROPIC_BASE_URL").is_none());
    }

    #[test]
    fn model_relay_disable_removes_headers_key_when_only_ours_existed() {
        // (c) When only our line existed, disable drops the key entirely.
        let dir = tempfile::tempdir().unwrap();
        let agent = envvars_agent(dir.path());
        let path = agent.hook_config_path();
        std::fs::write(&path, "{}").unwrap();

        with_openlatch_dir(|| {
            write_model_relay_config(&agent, 7600, "agt_x").unwrap();
            remove_model_relay_config(&agent).unwrap();
        });

        let v = read_env(&path);
        assert!(
            v["env"].get(ANTHROPIC_CUSTOM_HEADERS_ENV).is_none(),
            "an all-ours header value must be removed entirely: {v}"
        );
    }

    #[test]
    fn model_relay_disable_leaves_non_loopback_base_url_untouched() {
        // (d) A customer base URL pointing at a corporate gateway must survive
        // disable (we only reclaim our own 127.0.0.1 loopback URL).
        let dir = tempfile::tempdir().unwrap();
        let agent = envvars_agent(dir.path());
        let path = agent.hook_config_path();
        std::fs::write(
            &path,
            r#"{"env":{"ANTHROPIC_BASE_URL":"https://gateway.corp.example"}}"#,
        )
        .unwrap();

        with_openlatch_dir(|| remove_model_relay_config(&agent).unwrap());

        let v = read_env(&path);
        assert_eq!(
            v["env"]["ANTHROPIC_BASE_URL"], "https://gateway.corp.example",
            "a non-loopback base URL must be left untouched: {v}"
        );
    }

    /// **The existing-gap fix (D-10).** A customer whose Claude Code already
    /// pointed at a corporate gateway got that value clobbered on install and
    /// never got it back: the writer overwrote `ANTHROPIC_BASE_URL`
    /// unconditionally, and the remover only knew how to delete the key.
    ///
    /// Fails on the pre-D-10 code, which is the point.
    #[test]
    fn claude_model_relay_config_restores_a_prior_base_url() {
        let dir = tempfile::tempdir().unwrap();
        let agent = envvars_agent(dir.path());
        let path = agent.hook_config_path();
        std::fs::write(
            &path,
            r#"{"env":{"ANTHROPIC_BASE_URL":"https://gw.example"}}"#,
        )
        .unwrap();

        with_openlatch_dir(|| {
            write_model_relay_config(&agent, 7600, "agt_x").unwrap();
            assert_eq!(
                read_env(&path)["env"]["ANTHROPIC_BASE_URL"],
                "http://127.0.0.1:7600",
                "precondition: install really did point the agent at us"
            );
            remove_model_relay_config(&agent).unwrap();
        });

        assert_eq!(
            read_env(&path)["env"]["ANTHROPIC_BASE_URL"],
            "https://gw.example",
            "uninstall must put the customer's own gateway back"
        );
    }

    /// The re-install trap, on the `EnvVars` side. Two installs with no
    /// intervening uninstall: the second sees our own loopback URL on disk, and
    /// recording it would make uninstall "restore" a dead port.
    #[test]
    fn a_customers_own_loopback_base_url_is_theirs_not_ours() {
        // The `EnvVars` half of the ownership bug. `already_ours` was decided
        // by the ADDRESS alone, so an operator who points this agent at their
        // own local gateway had that value read as "our own previous install":
        // `record` was skipped, uninstall had nothing to put back, and the
        // relay had nothing to forward to.
        let dir = tempfile::tempdir().unwrap();
        let agent = envvars_agent(dir.path());
        let path = agent.hook_config_path();
        std::fs::write(
            &path,
            r#"{"env":{"ANTHROPIC_BASE_URL":"http://127.0.0.1:8787"}}"#,
        )
        .unwrap();

        let recorded = with_openlatch_dir(|| {
            write_model_relay_config(&agent, 7600, "agt_x").unwrap();
            // Where the relay must forward this format โ€” the endpoint we just
            // overwrote is the only statement of where that agent was pointed.
            let seen = super::model_relay_endpoints::peek(&super::upstream_record_key(
                crate::model_relay::wire_format::WireFormat::AnthropicMessages,
            ));
            remove_model_relay_config(&agent).unwrap();
            seen
        });

        assert_eq!(
            recorded,
            Some(Some("http://127.0.0.1:8787".to_string())),
            "a local endpoint we did not write is the customer's, and the relay needs it"
        );
        assert_eq!(
            read_env(&path)["env"]["ANTHROPIC_BASE_URL"],
            "http://127.0.0.1:8787",
            "and uninstall must put their own endpoint back"
        );
    }

    #[test]
    fn reinstall_keeps_the_first_installs_recorded_prior() {
        let dir = tempfile::tempdir().unwrap();
        let agent = envvars_agent(dir.path());
        let path = agent.hook_config_path();
        std::fs::write(
            &path,
            r#"{"env":{"ANTHROPIC_BASE_URL":"https://gw.example"}}"#,
        )
        .unwrap();

        with_openlatch_dir(|| {
            write_model_relay_config(&agent, 7600, "agt_x").unwrap();
            write_model_relay_config(&agent, 7600, "agt_x").unwrap();
            remove_model_relay_config(&agent).unwrap();
        });

        assert_eq!(
            read_env(&path)["env"]["ANTHROPIC_BASE_URL"],
            "https://gw.example",
            "the second install must not have overwritten the recorded prior"
        );
    }

    // -----------------------------------------------------------------------
    // Uninstall is the inverse of install โ€” the `env` half
    // -----------------------------------------------------------------------

    use super::{remove_hooks, AgentKind, DetectedAgent, OPENLATCH_PORT_ENV, OPENLATCH_TOKEN_ENV};

    /// A settings.json in the state `install_hooks` leaves behind: one owned
    /// hook entry, our two `env` keys, and a customer key beside them.
    fn installed_settings(dir: &std::path::Path) -> DetectedAgent {
        let settings_path = dir.join("settings.json");
        std::fs::write(
            &settings_path,
            r#"{
  "env": {
    "ANOTHER_TOOL_TOKEN": "keep-me",
    "OPENLATCH_TOKEN": "not-a-real-token",
    "OPENLATCH_PORT": "7443"
  },
  "hooks": {
    "Stop": [
      {"_openlatch": {"v": 1, "id": "x"}, "hooks": [{"type": "command", "command": "openlatch-hook"}]},
      {"hooks": [{"type": "command", "command": "sh other-tool.sh"}]}
    ]
  }
}"#,
        )
        .unwrap();
        DetectedAgent {
            kind: AgentKind::ClaudeCode,
            binding: std::sync::Arc::new(crate::hooks::bindings::claude_code::ClaudeCodeBinding {
                claude_dir: dir.to_path_buf(),
                settings_path,
            }),
        }
    }

    // -----------------------------------------------------------------------
    // The `env` block is written per DaemonChannel, not unconditionally
    // -----------------------------------------------------------------------

    /// Restores the variables `install_hooks` resolves its directories, its
    /// hook binary and its HMAC key from, on unwind as well as on success.
    ///
    /// It is save/restore only โ€” the mutual exclusion comes from the locks the
    /// caller holds. `CODEX_HOME` rides along here rather than in a guard of
    /// its own because it is absent from `daemon::identity::MANAGED`, so
    /// nothing else would put it back.
    struct EnvVars(Vec<(&'static str, Option<std::ffi::OsString>)>);

    impl EnvVars {
        fn set<const N: usize>(pairs: [(&'static str, &std::ffi::OsStr); N]) -> Self {
            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)
        }
    }

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

    /// Site 4 of the containment move: the top-level `env` block is now written
    /// only when the binding's channel is `DaemonChannel::EnvVars`. Claude Code
    /// answers exactly that, so the block it produces is byte-identical to the
    /// one an unconditional write produced โ€” an agent that cannot forward
    /// environment variables is the case that changed, and there is none in
    /// this build.
    #[test]
    fn env_channel_still_writes_the_env_block() {
        use crate::hooks::binding::AgentBinding;
        use crate::hooks::bindings::claude_code::ClaudeCodeBinding;

        // Three locks, in the crate's order โ€” `OPENLATCH_DIR` first, then
        // `$CLAUDE_CONFIG_DIR`, then the hook-binary trio.
        // `config::OPENLATCH_DIR_ENV_LOCK` is **the** lock for `OPENLATCH_DIR`,
        // and this test writes that variable: the model-relay-wiring tests above
        // hold it while they read the endpoint record back out of
        // `$OPENLATCH_DIR`, so without it this test's write lands under their
        // feet.
        let _dir_lock = crate::config::OPENLATCH_DIR_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let _lock = crate::hooks::claude_code::CONFIG_DIR_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let _bin_lock = crate::hooks::staging::HOOK_BIN_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        // Tail of the documented order, and taken because the block below now
        // redirects the three Cline seams too.
        let _cline_lock = crate::hooks::cline::SEAM_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());

        let ol = tempfile::tempdir().unwrap();
        let claude = tempfile::tempdir().unwrap();
        let staged = tempfile::tempdir().unwrap();
        // `install_hooks` refuses to write a command naming a path that is not
        // an existing file, so the fake binary has to really be there.
        let hook_bin = staged.path().join("openlatch-hook");
        std::fs::write(&hook_bin, b"#!/bin/sh\nexit 0\n").unwrap();
        let cline_root = tempfile::tempdir().unwrap();

        let _env = EnvVars::set([
            ("OPENLATCH_DIR", ol.path().as_os_str()),
            ("CLAUDE_CONFIG_DIR", claude.path().as_os_str()),
            ("OPENLATCH_HOOK_BIN", hook_bin.as_os_str()),
            // `HmacKeyStore::load_or_create` is file-first and falls through to
            // the OS keychain, which on a developer's machine raises a GUI
            // dialog and blocks the whole suite behind it.
            ("OPENLATCH_SKIP_KEYRING", std::ffi::OsStr::new("1")),
        ]);
        // Cline's three seams โ€” this fixture redirects the other agents' config
        // dirs and then *writes* through `install_hooks`, so leaving them alone
        // points that walk at `~/.cline/data/secrets.json`.
        // `cline::absent_seams` is the one definition of where they go, and
        // nothing it names is created: an existing directory would arm a
        // stat-based detector the day a Cline arm lands.
        let _cline_seams = crate::hooks::cline::EnvOverride::absent_cline_seams(cline_root.path());

        let binding = ClaudeCodeBinding {
            claude_dir: claude.path().to_path_buf(),
            settings_path: claude.path().join("settings.json"),
        };
        assert!(
            matches!(
                binding.daemon_channel(),
                super::binding::DaemonChannel::EnvVars { .. }
            ),
            "the premise of this test: Claude Code forwards named env vars"
        );

        super::install_hooks(&binding, 7443, "a-token").unwrap();

        let v = read_env(&binding.settings_path);
        assert_eq!(
            v["env"][OPENLATCH_TOKEN_ENV], "a-token",
            "an EnvVars channel still pins the token: {v}"
        );
        assert_eq!(
            v["env"][OPENLATCH_PORT_ENV], "7443",
            "and the port beside it: {v}"
        );
    }

    /// Uninstall used to remove the hook entries and stop there, leaving the
    /// bearer token โ€” in plaintext โ€” and a dead port in the agent's `env`
    /// block. `--purge`, the command that promises to leave nothing behind,
    /// left them too. Reported on a real machine after a purge.
    #[test]
    fn remove_hooks_takes_the_env_keys_install_wrote() {
        let dir = tempfile::tempdir().unwrap();
        let agent = installed_settings(dir.path());
        let settings_path = agent.settings_path();

        remove_hooks(&*agent.binding).unwrap();

        let v = read_env(&settings_path);
        for key in [OPENLATCH_TOKEN_ENV, OPENLATCH_PORT_ENV] {
            assert!(
                v["env"].get(key).is_none(),
                "install wrote {key}; uninstall must take it back: {v}"
            );
        }
    }

    /// The `env` block is shared. Only the two keys we wrote may go.
    #[test]
    fn remove_hooks_leaves_every_env_key_that_is_not_ours() {
        let dir = tempfile::tempdir().unwrap();
        let agent = installed_settings(dir.path());
        let settings_path = agent.settings_path();

        remove_hooks(&*agent.binding).unwrap();

        let v = read_env(&settings_path);
        assert_eq!(
            v["env"]["ANOTHER_TOOL_TOKEN"], "keep-me",
            "a key we never wrote must survive uninstall: {v}"
        );
        let stop = v["hooks"]["Stop"].as_array().unwrap();
        assert_eq!(stop.len(), 1, "only the owned entry may go: {v}");
        assert_eq!(stop[0]["hooks"][0]["command"], "sh other-tool.sh");
    }

    // -----------------------------------------------------------------------
    // Codex CLI: the hooks.json writer and its reversal
    // -----------------------------------------------------------------------

    /// One customer-owned `PostToolUse` group, exactly as a customer's own
    /// `hooks.json` carries one โ€” no `_openlatch` marker, no `openlatch-hook`
    /// in its command, so nothing in the writer may claim it.
    const CUSTOMER_GROUP: &str = r#"{"hooks":{"PostToolUse":[{"matcher":"","hooks":[{"type":"command","command":"echo mine","timeout":5}]}]}}"#;

    // `hook_config_path` is a trait method, and these tests hold the concrete
    // binding rather than a `dyn AgentBinding`.
    use crate::hooks::binding::AgentBinding as _;

    /// Everything an in-module install test must redirect, under the two locks
    /// that make it safe, with a real staged hook binary and a Codex CLI
    /// binding pointed at a temp `$CODEX_HOME`.
    ///
    /// Three of these redirections are not tidiness. `install_hooks` resolves
    /// `crate::config::openlatch_dir()` and then `HmacKeyStore::load_or_create`
    /// and a `HookStateFile` upsert under it, so a test that leaves
    /// `OPENLATCH_DIR` alone writes `agent: "codex-cli"` rows into the
    /// developer's โ€” and the CI runner's โ€” real `~/.openlatch/hook-state.json`,
    /// the file the live daemon's reconciler reads, and nothing fails.
    /// `OPENLATCH_SKIP_KEYRING` keeps the HMAC key off the OS keychain, whose
    /// dialog blocks the whole suite. And `OPENLATCH_HOOK_BIN` has to name a
    /// file that exists or `install_hooks` refuses with `OL-1404`.
    ///
    /// Lock order is `config::OPENLATCH_DIR_ENV_LOCK` then `HOOK_BIN_ENV_LOCK`
    /// then `codex_cli::CONFIG_DIR_ENV_LOCK`, everywhere: `OPENLATCH_DIR` has
    /// its own lock and it is taken first, and a config-directory lock is
    /// always taken last, or two tests deadlock by taking them in opposite
    /// orders.
    fn with_codex_install_env<T>(
        f: impl FnOnce(&crate::hooks::bindings::codex_cli::CodexCliBinding) -> T,
    ) -> T {
        use crate::hooks::bindings::codex_cli::CodexCliBinding;

        let _dir_lock = crate::config::OPENLATCH_DIR_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let _bin_lock = crate::hooks::staging::HOOK_BIN_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let _codex_lock = crate::hooks::codex_cli::CONFIG_DIR_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let _cline_lock = crate::hooks::cline::SEAM_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());

        let ol = tempfile::tempdir().unwrap();
        let codex = tempfile::tempdir().unwrap();
        let staged = tempfile::tempdir().unwrap();
        let hook_bin = staged.path().join("openlatch-hook");
        std::fs::write(&hook_bin, b"#!/bin/sh\nexit 0\n").unwrap();
        let cline_root = tempfile::tempdir().unwrap();

        // Declared after the locks so it is dropped BEFORE them: a failing
        // assertion must not release the lock while the variables are still
        // redirected. Cline's three seams follow, from `cline::absent_seams`,
        // for the reason given at the fixture above.
        let _env = EnvVars::set([
            ("OPENLATCH_DIR", ol.path().as_os_str()),
            ("OPENLATCH_HOOK_BIN", hook_bin.as_os_str()),
            ("OPENLATCH_SKIP_KEYRING", std::ffi::OsStr::new("1")),
            ("CODEX_HOME", codex.path().as_os_str()),
        ]);
        let _cline_seams = crate::hooks::cline::EnvOverride::absent_cline_seams(cline_root.path());

        let binding =
            CodexCliBinding::detect().expect("a $CODEX_HOME that exists must be detected");
        f(&binding)
    }

    /// The registration, asserted from the install side.
    ///
    /// Twelve event keys, `PreToolUse` among them, and that key is what makes
    /// Codex *enforced* rather than merely captured: `SHELL_TOOL_NAMES`
    /// contains `"Bash"`, `evaluate()` matches on `tool_name` whoever sent it,
    /// and Codex's shell tools report as `"Bash"`. It may only be written while
    /// `hook_output::codex_cli` can express a deny.
    #[test]
    fn install_writes_twelve_events() {
        with_codex_install_env(|binding| {
            super::install_hooks(binding, 7443, "a-token").expect("install must succeed");

            let v = read_env(&binding.hook_config_path());
            let hooks = v["hooks"].as_object().expect("a hooks object: {v}");
            assert_eq!(hooks.len(), 12, "twelve event keys: {v}");
            assert!(
                hooks.contains_key("PreToolUse"),
                "PreToolUse is the registration โ€” without it no Codex deny is ever \
                 evaluated: {v}"
            );

            // The matcher tiers, on disk. `PreToolUse` is the EXACT tier โ€”
            // split on `|`, compared with `==`, so `"Bash"` cannot capture a
            // future `"BashOutput"` โ€” and every other event takes `""`, which
            // matches all. Not `"Bash|apply_patch"`: `evaluate()` needs
            // `tool_input.command` and a patch has none.
            for (event, groups) in hooks {
                let group = &groups.as_array().unwrap()[0];
                let expected = if event == "PreToolUse" { "Bash" } else { "" };
                assert_eq!(
                    group["matcher"].as_str(),
                    Some(expected),
                    "{event} carries the wrong matcher: {group}"
                );
            }

            // Nothing at the TOP level but `hooks`: Codex's `HooksFile` is
            // `#[serde(deny_unknown_fields)]`, so one extra key there makes it
            // reject the customer's entire file. In particular no `env` block โ€”
            // this binding's channel is `OpenlatchDirArg` for that reason.
            let top: Vec<&String> = v.as_object().unwrap().keys().collect();
            assert_eq!(top, vec!["hooks"], "top level must carry only `hooks`: {v}");

            // Every entry carries an explicit timeout and the directory flag,
            // and none sets `async`. An omitted timeout inherits Codex's
            // 600-second default on the verdict path.
            for (event, groups) in hooks {
                let group = &groups.as_array().unwrap()[0];
                let handler = &group["hooks"][0];
                assert!(
                    handler["timeout"].is_number(),
                    "{event} has no explicit timeout: {group}"
                );
                assert!(
                    handler.get("async").is_none(),
                    "{event} sets async: {group}"
                );
                let command = handler["command"].as_str().unwrap();
                assert!(
                    command.contains("--openlatch-dir"),
                    "{event} must carry the directory the hook reads its port and \
                     token from: {command}"
                );
                assert!(
                    !command.contains("--event unknown"),
                    "{event} installed as `--event unknown` โ€” pascal_to_snake is \
                     missing an arm: {command}"
                );
            }
        });
    }

    /// A customer's own group survives an install and keeps index 0.
    ///
    /// Index is the assertion, not decoration: Codex keys hook trust on
    /// `"{source_path}:{event}:{group_index}:{handler_index}"`, so moving a
    /// customer's group re-arms `/hooks` review on hooks they already trusted.
    #[test]
    fn install_appends_and_preserves_a_customer_group() {
        with_codex_install_env(|binding| {
            let path = binding.hook_config_path();
            std::fs::write(&path, CUSTOMER_GROUP).unwrap();
            let seeded: serde_json::Value = serde_json::from_str(CUSTOMER_GROUP).unwrap();
            let theirs = seeded["hooks"]["PostToolUse"][0].clone();

            super::install_hooks(binding, 7443, "a-token").expect("install must succeed");

            let v = read_env(&path);
            let arr = v["hooks"]["PostToolUse"].as_array().unwrap();
            assert_eq!(arr.len(), 2, "ours is appended beside theirs: {v}");
            assert_eq!(
                arr[0], theirs,
                "the customer's group must be untouched: {v}"
            );
            assert!(
                arr[1].get("_openlatch").is_some(),
                "ours must be the appended one: {v}"
            );
        });
    }

    /// **The D-06 gate.** A re-install must not move a customer group that sits
    /// *after* ours.
    ///
    /// The customer group is added AFTER the first install on purpose. Seeding
    /// it first makes the test blind: remove-then-append leaves them at index 0
    /// either way, and index 0 is exactly where the old writer left them while
    /// silently shifting anything behind it.
    #[test]
    fn reinstall_does_not_move_a_later_customer_group() {
        with_codex_install_env(|binding| {
            let path = binding.hook_config_path();
            super::install_hooks(binding, 7443, "a-token").expect("first install");

            // The array is now [ours]. Append theirs, so it is [ours, theirs].
            let mut v = read_env(&path);
            v["hooks"]["PostToolUse"]
                .as_array_mut()
                .expect("PostToolUse is one of the twelve")
                .push(serde_json::json!({
                    "matcher": "",
                    "hooks": [{"type": "command", "command": "echo later", "timeout": 5}],
                }));
            std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();

            super::install_hooks(binding, 7443, "a-token").expect("re-install");

            let v = read_env(&path);
            let arr = v["hooks"]["PostToolUse"].as_array().unwrap();
            assert_eq!(arr.len(), 2, "a re-install replaces, never duplicates: {v}");
            assert!(
                arr[0].get("_openlatch").is_some(),
                "ours must be replaced IN PLACE at index 0: {v}"
            );
            assert_eq!(
                arr[1]["hooks"][0]["command"], "echo later",
                "the customer's later group must still be at index 1 โ€” \
                 remove-then-append would have moved it to 0: {v}"
            );
        });
    }

    /// Uninstall is the inverse of install: seed โ†’ install โ†’ uninstall gives
    /// the customer their file back.
    ///
    /// Install writes twelve event keys, eleven of which the seeded file never
    /// had. Removing only our *elements* leaves eleven `"SessionStart": []` keys
    /// behind โ€” a file we created still naming OpenLatch on every event โ€” so
    /// the key set is the sharpest assertion here.
    ///
    /// **Compared as JSON, not as bytes.** The file comes back through the
    /// JSONC CST serialiser, which leaves the whitespace its own insertion
    /// introduced, so a byte comparison would pin a formatting contract nothing
    /// specifies โ€” the same reason this plan's live acceptance diffs `jq -S`
    /// output rather than raw files. What must be identical is the customer's
    /// content and the shape around it, and that is what is asserted.
    #[test]
    fn uninstall_restores_the_seeded_file_byte_for_byte() {
        with_codex_install_env(|binding| {
            let path = binding.hook_config_path();
            std::fs::write(&path, CUSTOMER_GROUP).unwrap();
            let seeded: serde_json::Value = serde_json::from_str(CUSTOMER_GROUP).unwrap();

            super::install_hooks(binding, 7443, "a-token").expect("install must succeed");
            super::remove_hooks(binding).expect("uninstall must succeed");

            // THE CUSTOMER'S OWN GROUP MUST COME BACK AS ITS ORIGINAL TEXT.
            // A parsed comparison alone would pass over a silent reformat of
            // their content, which is the one mutation they would actually
            // notice in a file they wrote โ€” so assert their bytes directly.
            //
            // Not the WHOLE file, and the difference is worth stating because
            // this test's name reads like it. Removing our elements makes the
            // CST reflow the container around them: the file comes back as
            // `{"hooks":{\n    "PostToolUse":[โ€ฆ]\n  }}` where it was seeded
            // flat. Their group is untouched; the whitespace that held our
            // entries is not restored. Making it so would mean teaching the
            // shared JSONC writer to reproduce removed whitespace exactly โ€”
            // a formatting contract this plan deliberately does not specify,
            // and one Claude Code would inherit too. Verified empirically
            // rather than assumed: the strict assertion was written first and
            // failed on exactly that whitespace.
            let customer_group = CUSTOMER_GROUP
                .split_once("\"PostToolUse\":[")
                .and_then(|(_, rest)| rest.rsplit_once("]"))
                .map(|(group, _)| group)
                .expect("the seed's customer group");
            assert!(
                std::fs::read_to_string(&path)
                    .unwrap()
                    .contains(customer_group),
                "uninstall must give the customer's own group back as the exact text \
                 they wrote, not a reserialisation of it"
            );

            let restored = read_env(&path);
            assert_eq!(
                restored, seeded,
                "uninstall must give the customer their file back: every group they \
                 owned, no leftovers, and none of the ten event keys install added"
            );
            // Stated separately so a failure says which half broke: a `del` that
            // leaves ten empty arrays behind still fails the line above, but this
            // one names the reason.
            let keys: Vec<&String> = restored["hooks"].as_object().unwrap().keys().collect();
            assert_eq!(
                keys,
                vec!["PostToolUse"],
                "an event key we emptied must be pruned, not left holding []"
            );
        });
    }

    /// `--agent` semantics (D-09), on the two-agent fixture so no environment
    /// is involved.
    ///
    /// Coverage is the default and a detected-but-unnamed agent is skipped in
    /// silence โ€” that is the flag working. Both *failing* directions are
    /// failures on purpose: a name that is not an agent type is a typo, and a
    /// valid name that is not on this host is a typo too. Quietly wiring
    /// nothing is how somebody comes to believe they are covered.
    #[test]
    fn agent_flag_narrows_coverage_and_refuses_a_name_that_is_not_here() {
        let root = tempfile::tempdir().unwrap();
        let detected = crate::hooks::binding::test_support::two_detected_agents(root.path());
        let types = |v: Vec<DetectedAgent>| {
            v.iter()
                .map(DetectedAgent::agent_type)
                .collect::<Vec<&str>>()
        };

        assert_eq!(
            types(super::select_agents(detected.clone(), &[]).unwrap()),
            vec!["claude-code", "cursor"],
            "no --agent means every detected agent"
        );
        assert_eq!(
            types(super::select_agents(detected.clone(), &["cursor".to_string()]).unwrap()),
            vec!["cursor"],
            "a detected agent nobody named is skipped, silently"
        );
        assert_eq!(
            types(
                super::select_agents(
                    detected.clone(),
                    &["cursor".to_string(), "claude-code".to_string()],
                )
                .unwrap()
            ),
            vec!["claude-code", "cursor"],
            "detection order wins over flag order โ€” it is load-bearing elsewhere"
        );

        // A schema-valid agent this host does not have. `gemini-cli` is in
        // SCHEMA_AGENT_TYPES and is not one of the two this build detects.
        let err = super::select_agents(detected.clone(), &["gemini-cli".to_string()])
            .expect_err("a named-but-undetected agent must fail");
        assert_eq!(err.code, crate::error::ERR_HOOK_AGENT_NOT_FOUND);
        assert!(
            err.message.contains("gemini-cli"),
            "the error must NAME the agent, or the operator cannot see their typo: {}",
            err.message
        );

        // Not an agent type at all: a different message, listing what is.
        let err = super::select_agents(detected, &["claude_code".to_string()])
            .expect_err("an unknown agent type must fail");
        assert_eq!(err.code, crate::error::ERR_HOOK_AGENT_NOT_FOUND);
        assert!(
            err.suggestion
                .as_deref()
                .is_some_and(|s| s.contains("claude-code")),
            "the remedy must list the valid values: {err:?}"
        );
    }

    /// The unseeded branch: install then uninstall on a file that did not
    /// exist leaves `{}`, never a deleted file.
    ///
    /// Nothing records that we created it โ€” `StateEntry` carries no creation
    /// flag โ€” and deleting unconditionally would take a customer's own empty
    /// `hooks.json` with it. Every other case here seeds a file, so this branch
    /// is otherwise untested.
    #[test]
    fn uninstall_of_an_unseeded_file_leaves_an_empty_object() {
        with_codex_install_env(|binding| {
            let path = binding.hook_config_path();
            assert!(!path.exists(), "the fixture starts with no hooks.json");

            super::install_hooks(binding, 7443, "a-token").expect("install must succeed");
            super::remove_hooks(binding).expect("uninstall must succeed");

            assert_eq!(std::fs::read_to_string(&path).unwrap(), "{}");
        });
    }

    // -----------------------------------------------------------------------
    // DD-05 โ€” the guard lives in the primitives, not only at their callers
    // -----------------------------------------------------------------------

    /// `install_hooks` writes nothing for a binding that declares it cannot be
    /// installed into โ€” called **directly**, not through `init` or the
    /// reconciler.
    ///
    /// The primitive is the backstop that matters: it is `pub`, and its own
    /// docs say it accepts any `AgentBinding`. A guard that lives only at the
    /// six call sites is a guard the seventh caller does not have.
    ///
    /// Driven through `FakeBinding` rather than `ClineBinding` deliberately โ€”
    /// the guard is about `installable()`, not about Cline, and the fake keeps
    /// this assertion independent of Cline's path resolution.
    #[test]
    fn install_hooks_refuses_non_installable() {
        let _dir_lock = crate::config::OPENLATCH_DIR_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let _bin_lock = crate::hooks::staging::HOOK_BIN_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());

        let ol = tempfile::tempdir().unwrap();
        let agent = tempfile::tempdir().unwrap();
        let staged = tempfile::tempdir().unwrap();
        let hook_bin = staged.path().join("openlatch-hook");
        std::fs::write(&hook_bin, b"#!/bin/sh\nexit 0\n").unwrap();

        // A hook binary that really resolves, on purpose: without one the
        // install refuses at its binary post-condition anyway, and this test
        // would be green whether or not the guard exists.
        let _env = EnvVars::set([
            ("OPENLATCH_DIR", ol.path().as_os_str()),
            ("OPENLATCH_HOOK_BIN", hook_bin.as_os_str()),
            ("OPENLATCH_SKIP_KEYRING", std::ffi::OsStr::new("1")),
        ]);

        let refused = FakeBinding {
            config_dir: agent.path().join("refused"),
            installable: false,
            ..Default::default()
        };

        let result = super::install_hooks(&refused, 7443, "a-token")
            .expect("a non-installable agent is skipped, never an error");

        assert!(
            result.entries.is_empty(),
            "an install that registered nothing must say so, not report entries"
        );
        assert!(
            !refused.hook_config_path().exists(),
            "and it must not have created the settings file: {}",
            refused.hook_config_path().display()
        );
        // The HMAC key, the hook state file and the directory itself are all
        // created AFTER the guard. An empty `$OPENLATCH_DIR` is what proves the
        // guard is the first statement rather than a late filter โ€” and it is
        // the daemon bearer token, written into `env` at the same stage, that
        // makes the distinction matter.
        // `.expect`, not `.unwrap_or_default()`: a read_dir that failed would
        // otherwise hand the assertion below an empty vec and pass vacuously.
        let left_behind: Vec<std::ffi::OsString> = std::fs::read_dir(ol.path())
            .expect("the temp $OPENLATCH_DIR is readable")
            .map(|entry| entry.expect("a readable directory entry").file_name())
            .collect();
        assert!(
            left_behind.is_empty(),
            "a skipped install must not create an HMAC key or a state file: {left_behind:?}"
        );

        // The control, so none of the above can pass vacuously: the same
        // fixture, the same call, with the guard's one condition flipped.
        let writable = FakeBinding {
            config_dir: agent.path().join("writable"),
            installable: true,
            ..Default::default()
        };
        let wrote = super::install_hooks(&writable, 7443, "a-token").expect("install must succeed");
        assert!(
            !wrote.entries.is_empty() && writable.hook_config_path().exists(),
            "the fixture does write when it is installable โ€” otherwise the assertions \
             above prove nothing"
        );
    }

    /// `remove_hooks` is a writer too, and its own `exists()` early return does
    /// **not** stand in for the guard.
    ///
    /// The hazard is a hook path that exists and is a **directory**:
    /// `Path::exists()` is true for one, so the early return does not fire and
    /// `atomic_rewrite_jsonc` runs against it. Cline's `hook_config_path()` is
    /// exactly that โ€” the asset root's `Hooks/` directory.
    #[test]
    fn remove_hooks_refuses_non_installable() {
        let agent = tempfile::tempdir().unwrap();

        let refused = FakeBinding {
            config_dir: agent.path().to_path_buf(),
            installable: false,
            ..Default::default()
        };

        // The hazard, built on purpose.
        let hook_path = refused.hook_config_path();
        std::fs::create_dir_all(&hook_path).unwrap();
        let theirs = hook_path.join("their-hook");
        std::fs::write(&theirs, b"a file we have no business touching").unwrap();

        super::remove_hooks(&refused).expect("a non-installable agent is skipped, never an error");

        assert!(
            hook_path.is_dir(),
            "the directory must still be a directory"
        );
        assert_eq!(
            std::fs::read_to_string(&theirs).unwrap(),
            "a file we have no business touching",
            "and nothing inside it may be touched"
        );

        // The control: identical state, identical call, `installable()` flipped
        // โ€” and the rewrite now reaches a directory and fails. Without the
        // guard that is what uninstall does to a Cline host.
        let writable = FakeBinding {
            config_dir: agent.path().to_path_buf(),
            installable: true,
            ..Default::default()
        };
        let err = super::remove_hooks(&writable)
            .expect_err("the rewrite cannot read a directory as JSONC");
        assert_eq!(err.code, crate::error::ERR_HOOK_WRITE_FAILED);
    }

    // -----------------------------------------------------------------------
    // The `Directory` surface โ€” ten scripts on disk, not ten entries in a file
    // -----------------------------------------------------------------------

    /// A binding whose hook surface is a **directory**, pointed wherever the
    /// test puts it.
    ///
    /// Not `FakeBinding` with one more field: the point of this fixture is that
    /// it resolves nothing at all. Its directory is a `tempdir()` the test hands
    /// it, so the whole install path can be exercised with no seam, no `$HOME`
    /// and no route whatever to the real Cline store that exists on the machines
    /// this suite runs on.
    ///
    /// It mirrors `ClineBinding` in the one place that is load-bearing โ€”
    /// `OpenlatchDirArg`, so a bearer token has nowhere to go โ€” and nowhere
    /// else. In particular it declares **no** event types, which is how these
    /// tests show that the ten come from the writer's own list rather than from
    /// the binding.
    /// Field order is drop order in Rust, so the two environment guards come
    /// first and the four locks after them: a lock released while this test's
    /// variables were still set would hand the next taker our `$OPENLATCH_DIR`.
    /// The temp directories go last, because a directory removed after the
    /// locks are gone harms nothing.
    ///
    /// **All four locks, including the home lock**, and that one is not
    /// optional even though nothing here reads `$HOME`: Cline's own fixtures
    /// redirect the three seams under `claude_code::CONFIG_DIR_ENV_LOCK`
    /// (`cline::isolated`, whose doc says so), not under `SEAM_ENV_LOCK`. A
    /// fixture that redirects them while holding only the seam lock runs
    /// straight through the middle of `cline_isolated()`, and its victim fails
    /// with `require_seam`'s panic โ€” "CLINE_DIR unset" โ€” in a test that never
    /// mentions hooks.
    struct DirFixture {
        _env: EnvVars,
        _seams: crate::hooks::cline::EnvOverride,
        _dir_lock: std::sync::MutexGuard<'static, ()>,
        _home_lock: std::sync::MutexGuard<'static, ()>,
        _bin_lock: std::sync::MutexGuard<'static, ()>,
        _seam_lock: std::sync::MutexGuard<'static, ()>,
        ol: tempfile::TempDir,
        store: tempfile::TempDir,
        _staged: tempfile::TempDir,
        _cline_root: tempfile::TempDir,
        /// The staged absolute path every shim has to carry.
        hook_bin: std::path::PathBuf,
    }

    impl DirFixture {
        fn new() -> Self {
            // Locks first, in the crate's documented total order, and before a
            // single variable is written: the mutual exclusion is what makes the
            // writes safe, so a write above them is a race by construction.
            let dir_lock = crate::config::OPENLATCH_DIR_ENV_LOCK
                .lock()
                .unwrap_or_else(|e| e.into_inner());
            let home_lock = crate::hooks::claude_code::CONFIG_DIR_ENV_LOCK
                .lock()
                .unwrap_or_else(|e| e.into_inner());
            let bin_lock = crate::hooks::staging::HOOK_BIN_ENV_LOCK
                .lock()
                .unwrap_or_else(|e| e.into_inner());
            let seam_lock = crate::hooks::cline::SEAM_ENV_LOCK
                .lock()
                .unwrap_or_else(|e| e.into_inner());

            let ol = tempfile::tempdir().expect("a temp $OPENLATCH_DIR");
            let store = tempfile::tempdir().expect("a temp agent store");
            let staged = tempfile::tempdir().expect("a temp staging directory");
            let cline_root = tempfile::tempdir().expect("a temp seam root");

            // `install_hooks` refuses to write a command naming a path that is
            // not an existing file, and every shim carries that path verbatim,
            // so the fake binary has to really be there.
            let hook_bin = staged.path().join("openlatch-hook");
            std::fs::write(&hook_bin, b"#!/bin/sh\nexit 0\n").expect("a staged hook binary");

            let env = EnvVars::set([
                ("OPENLATCH_DIR", ol.path().as_os_str()),
                ("OPENLATCH_HOOK_BIN", hook_bin.as_os_str()),
                // `HmacKeyStore::load_or_create` is file-first and falls through
                // to the OS keychain, which on a developer's machine raises a
                // GUI dialog and blocks the whole suite behind it.
                ("OPENLATCH_SKIP_KEYRING", std::ffi::OsStr::new("1")),
            ]);
            // Nothing below resolves a Cline path โ€” the writer takes its
            // directory as a parameter and calls no resolver, which is this
            // module's structural guarantee. The seams are pinned anyway, at
            // paths under a temp root that are never created, so an edit that
            // one day *does* reach a resolver still cannot reach
            // `~/Documents/Cline` or `~/.cline`.
            let seams = crate::hooks::cline::EnvOverride::absent_cline_seams(cline_root.path());

            Self {
                _env: env,
                _seams: seams,
                _dir_lock: dir_lock,
                _home_lock: home_lock,
                _bin_lock: bin_lock,
                _seam_lock: seam_lock,
                ol,
                store,
                _staged: staged,
                _cline_root: cline_root,
                hook_bin,
            }
        }

        /// The directory the binding points at โ€” **never created here.** The
        /// installer has to create it, and a fixture that pre-created it would
        /// hide the day it stopped.
        fn hooks_dir(&self) -> std::path::PathBuf {
            self.store.path().join("Hooks")
        }

        /// `FakeBinding`, not a bespoke fixture.
        ///
        /// It grew `hook_surface_dir`, `hook_event_types`, `load_bearing_events`
        /// and `daemon_channel` for exactly this, and the reconciler's
        /// directory-surface test already builds one the same way. A second
        /// hand-written `impl AgentBinding` is thirteen methods kept in step
        /// with the trait for the sake of the four that differ.
        ///
        /// `hook_event_types` is `&[]` deliberately: the `Directory` arm takes
        /// its ten from `hook_files::CLINE_HOOK_FILES`, so a fixture that also
        /// declared ten would make it impossible to tell which list was used.
        ///
        /// `OpenlatchDirArg`, because D-09 forbids a daemon token reaching an
        /// agent's asset root โ€” the fixture has to model that, not the default.
        fn binding(&self) -> crate::hooks::binding::test_support::FakeBinding {
            crate::hooks::binding::test_support::FakeBinding {
                agent_type: "cline",
                display_name: "Directory Agent",
                hook_surface_dir: Some(self.hooks_dir()),
                hook_event_types: &[],
                load_bearing_events: &[],
                daemon_channel: Some(crate::hooks::binding::DaemonChannel::OpenlatchDirArg),
                ..Default::default()
            }
        }

        /// Where the enforcement plugin goes โ€” a directory under the **store**
        /// root, never beside the ten under the asset root.
        ///
        /// Never created here, for the same reason `hooks_dir` is not: the
        /// installer has to create it, and a fixture that pre-created it would
        /// hide the day it stopped.
        fn plugin_dir(&self) -> std::path::PathBuf {
            self.store.path().join("plugins").join("openlatch")
        }

        /// `binding()`, plus the plugin surface.
        ///
        /// A separate constructor rather than a field on `binding()`, so every
        /// test above this one keeps writing ten scripts and nothing else. An
        /// opt-in is what keeps the blast radius of arming the plugin installer
        /// at exactly the tests that asked for it.
        fn binding_with_plugin(&self) -> crate::hooks::binding::test_support::FakeBinding {
            crate::hooks::binding::test_support::FakeBinding {
                plugin_surface_dir: Some(self.plugin_dir()),
                ..self.binding()
            }
        }

        fn state(&self) -> crate::core::hook_state::HookStateFile {
            crate::core::hook_state::HookStateFile::load(self.ol.path())
                .expect("the state file parses")
                .expect("the install wrote a state file")
        }

        /// The file names in the hook directory, sorted.
        fn listing(&self) -> Vec<String> {
            let mut names: Vec<String> = std::fs::read_dir(self.hooks_dir())
                .expect("the installer created the hook directory")
                .map(|entry| {
                    entry
                        .expect("a readable directory entry")
                        .file_name()
                        .to_string_lossy()
                        .into_owned()
                })
                .collect();
            names.sort();
            names
        }
    }

    /// The ten file names this platform expects, sorted.
    fn expected_listing() -> Vec<String> {
        let mut names: Vec<String> = super::hook_files::CLINE_HOOK_FILES
            .iter()
            .map(|event| super::hook_files::hook_file_name(event))
            .collect();
        names.sort();
        names
    }

    /// The `Directory` arm writes ten executable shims where the `ConfigFile`
    /// arm writes ten entries into one JSON document.
    ///
    /// Each one has to be recognisable as ours from its own bytes, and each one
    /// has to name the **staged absolute** hook binary: a bare name on a PATH
    /// that does not carry it kills every hook with exit 127, silently, because
    /// the hook fails open.
    #[test]
    fn installing_a_directory_surface_writes_the_ten_scripts() {
        let fx = DirFixture::new();
        let hooks_dir = fx.hooks_dir();
        assert!(
            !hooks_dir.exists(),
            "the fixture must not pre-create the directory the installer is being asked to create"
        );

        let result =
            super::install_hooks(&fx.binding(), 7443, "a-token").expect("the directory arm writes");

        assert_eq!(
            fx.listing(),
            expected_listing(),
            "ten files, exactly these names, in THIS platform's shape"
        );

        for name in expected_listing() {
            let path = hooks_dir.join(&name);
            let body = std::fs::read_to_string(&path).expect("a readable shim");
            assert!(
                super::hook_files::is_ours(&body),
                "{name} has to be recognisable as ours from its own bytes, with no state \
                 file present: {body}"
            );
            assert!(
                body.contains(&fx.hook_bin.display().to_string()),
                "{name} must name the staged absolute binary, never a bare name: {body}"
            );
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                let mode = std::fs::metadata(&path)
                    .expect("a stat-able shim")
                    .permissions()
                    .mode()
                    & 0o777;
                assert_eq!(
                    mode, 0o755,
                    "{name} is executed by the agent; 0600 would be permission-denied on \
                     every event"
                );
            }
        }

        assert_eq!(
            result.entries.len(),
            10,
            "one status per file written: {:?}",
            result.entries
        );
        assert!(
            result
                .entries
                .iter()
                .all(|e| e.action == super::HookAction::Added),
            "a first install adds all ten: {:?}",
            result.entries
        );
        let mut reported: Vec<&str> = result
            .entries
            .iter()
            .map(|e| e.event_type.as_str())
            .collect();
        reported.sort_unstable();
        let mut want = super::hook_files::CLINE_HOOK_FILES;
        want.sort_unstable();
        assert_eq!(
            reported,
            want.to_vec(),
            "the statuses name the ten hook FILES โ€” and they came from the writer's list, \
             since this binding declares no event types at all"
        );
    }

    /// One `StateEntry` per script, carrying the descriptor.
    ///
    /// The descriptor is the point: an HMAC is not reversible, so neither health
    /// nor the reconciler can recover the body hash they should find on disk
    /// from `expected_entry_hmac`. It has to be stored โ€” and signed, through the
    /// same `compute_entry_hmac` a JSON entry goes through, which is why it is a
    /// JSON object rather than a bare hash string.
    #[test]
    fn each_installed_script_gets_a_state_row_carrying_its_descriptor() {
        let fx = DirFixture::new();
        super::install_hooks(&fx.binding(), 7443, "a-token").expect("the directory arm writes");

        let key = crate::core::hook_state::key::HmacKeyStore::new(fx.ol.path())
            .load_or_create()
            .expect("the install created an HMAC key");
        let surface_hash = crate::core::hook_state::hash_settings_path(&fx.hooks_dir());

        let state = fx.state();
        assert_eq!(state.entries.len(), 10, "one row per script");

        for row in &state.entries {
            assert_eq!(
                row.settings_path_hash, surface_hash,
                "the rows are keyed to the DIRECTORY, so the surface the binding reports \
                 finds all ten"
            );
            assert_eq!(row.v, crate::core::hook_state::STATE_ENTRY_VERSION);
            assert!(
                super::hook_files::CLINE_HOOK_FILES.contains(&row.hook_event.as_str()),
                "the row's event is the hook file name: {}",
                row.hook_event
            );

            let descriptor = row
                .descriptor
                .as_ref()
                .expect("a directory surface records what it wrote");
            let body = std::fs::read_to_string(&descriptor.path)
                .expect("the descriptor names a file that exists");
            assert_eq!(
                descriptor.sha256,
                super::hook_files::sha256_hex(&body),
                "the stored hash is the whole body, which is what a later read hashes"
            );
            assert_eq!(descriptor.mode, 0o755);
            assert!(
                body.contains(&row.id),
                "the marker line in the file and its state row must name the SAME uuid โ€” \
                 the writer mints it once, before the body can be hashed"
            );

            let signed = serde_json::to_value(descriptor).expect("a descriptor serializes");
            assert!(
                crate::core::hook_state::hmac::verify_entry_hmac(
                    &signed,
                    &row.expected_entry_hmac,
                    &key
                )
                .expect("the descriptor is a JSON object, so canonicalization succeeds"),
                "the HMAC has to be over the descriptor, or the row is not tamper-evident"
            );
        }
    }

    /// D-09, asserted rather than assumed: **no daemon token reaches the
    /// agent's store.**
    ///
    /// An `EnvVars` channel writes the bearer token's value into the agent's own
    /// config file. A directory surface has no such file and this arm writes no
    /// token anywhere โ€” each shim carries `--openlatch-dir` and finds the port
    /// and the credential through the OpenLatch state directory.
    #[test]
    fn no_token_reaches_the_hook_directory() {
        const TOKEN: &str = "a-daemon-bearer-token-nobody-may-copy";

        let fx = DirFixture::new();
        let binding = fx.binding();
        assert!(
            matches!(
                super::binding::AgentBinding::daemon_channel(&binding),
                super::binding::DaemonChannel::OpenlatchDirArg
            ),
            "the premise: a directory surface has no env block to carry a token"
        );

        super::install_hooks(&binding, 7443, TOKEN).expect("the directory arm writes");

        // The store holds the hook directory and nothing else โ€” no settings
        // file appeared beside it to hold what the scripts do not.
        let store_entries: Vec<String> = std::fs::read_dir(fx.store.path())
            .expect("a readable store")
            .map(|e| {
                e.expect("a readable entry")
                    .file_name()
                    .to_string_lossy()
                    .into_owned()
            })
            .collect();
        assert_eq!(store_entries, vec!["Hooks".to_string()]);

        for name in fx.listing() {
            let bytes = std::fs::read(fx.hooks_dir().join(&name)).expect("a readable shim");
            assert!(
                !String::from_utf8_lossy(&bytes).contains(TOKEN),
                "{name} carries the daemon's bearer token"
            );
        }

        // And none of that is vacuous: the install really ran, and really
        // recorded the token โ€” as a fingerprint, in `$OPENLATCH_DIR`.
        let state = fx.state();
        assert_eq!(state.entries.len(), 10);
        assert!(
            state
                .entries
                .iter()
                .all(|e| !e.daemon_token_fp.is_empty() && !e.daemon_token_fp.contains(TOKEN)),
            "the row keeps a fingerprint of the token, never the token"
        );
    }

    /// A file at one of the ten names that fails the ownership predicate is the
    /// developer's. It is never overwritten, the install continues with the
    /// other nine โ€” and it gets **no state row**, or the reconciler would
    /// later heal somebody else's script into one of ours.
    #[test]
    fn a_file_we_did_not_write_is_never_overwritten_by_install() {
        const THEIRS: &str = "#!/bin/sh\n# the developer's own PreToolUse hook\necho hi\n";

        let fx = DirFixture::new();
        let hooks_dir = fx.hooks_dir();
        std::fs::create_dir_all(&hooks_dir).expect("the developer's own hook directory");
        let name = super::hook_files::hook_file_name("PreToolUse");
        std::fs::write(hooks_dir.join(&name), THEIRS).expect("the developer's own hook");

        let result = super::install_hooks(&fx.binding(), 7443, "a-token")
            .expect("a collision is a decision about someone else's file, never a failure");

        assert_eq!(
            std::fs::read_to_string(hooks_dir.join(&name)).expect("still readable"),
            THEIRS,
            "never overwritten"
        );
        assert!(
            !hooks_dir.join(format!("{name}.bak")).exists(),
            "and never backed up either โ€” a backup is for a file of ours we are about to \
             rewrite"
        );
        assert_eq!(
            result.entries.len(),
            9,
            "the install continues with the other nine: {:?}",
            result.entries
        );
        assert!(
            !result.entries.iter().any(|e| e.event_type == "PreToolUse"),
            "an install that did not write a file must not report one: {:?}",
            result.entries
        );

        let state = fx.state();
        assert_eq!(state.entries.len(), 9);
        assert!(
            !state.entries.iter().any(|e| e.hook_event == "PreToolUse"),
            "no state row for a file we did not write"
        );
    }

    /// Re-installing is idempotent, and says so: ten `Replaced`, one `.bak` per
    /// script for `doctor --restore` to return to, and still ten rows rather
    /// than twenty.
    #[test]
    fn re_installing_replaces_our_own_and_leaves_a_backup() {
        let fx = DirFixture::new();
        let first = super::install_hooks(&fx.binding(), 7443, "a-token").expect("first install");
        assert!(first
            .entries
            .iter()
            .all(|e| e.action == super::HookAction::Added));

        let second = super::install_hooks(&fx.binding(), 7443, "a-token").expect("second install");
        assert_eq!(second.entries.len(), 10);
        assert!(
            second
                .entries
                .iter()
                .all(|e| e.action == super::HookAction::Replaced),
            "a re-install must not report ten fresh additions: {:?}",
            second.entries
        );

        for name in expected_listing() {
            let backup = fx.hooks_dir().join(format!("{name}.bak"));
            let body = std::fs::read_to_string(&backup)
                .unwrap_or_else(|e| panic!("{name} has no backup beside it: {e}"));
            assert!(
                super::hook_files::is_ours(&body),
                "the backup is the script we replaced, which was ours"
            );
        }

        assert_eq!(
            fx.state().entries.len(),
            10,
            "the rows are upserted on (agent, surface, event), never appended"
        );
    }

    /// Uninstall removes what carries our marker and nothing else, and a
    /// partial removal is an `Ok`.
    ///
    /// That last part is load-bearing: `uninstall` gates the model-relay
    /// teardown on this returning `Ok`, so an `Err` raised over a file we were
    /// never going to touch would leave the agent pointed at a loopback port no
    /// daemon answers on.
    #[test]
    fn uninstall_removes_our_scripts_and_only_ours() {
        const MINE_NOW: &str = "#!/bin/sh\n# I replaced yours\n";

        let fx = DirFixture::new();
        super::install_hooks(&fx.binding(), 7443, "a-token").expect("install");

        // A file of the developer's under a name that is not one of the tenโ€ฆ
        std::fs::write(fx.hooks_dir().join("MyOwn"), "# mine\n").expect("the developer's own hook");
        // โ€ฆand one of the ten, taken over by the developer after we installed:
        // the marker is gone, so the file is theirs now whatever its name is.
        let taken = super::hook_files::hook_file_name("PostToolUse");
        std::fs::write(fx.hooks_dir().join(&taken), MINE_NOW).expect("a hook taken over");

        super::remove_hooks(&fx.binding())
            .expect("a partial removal is an Ok โ€” the relay teardown is gated on it");

        assert_eq!(
            fx.listing(),
            {
                let mut want = vec!["MyOwn".to_string(), taken.clone()];
                want.sort();
                want
            },
            "our nine are gone; both of the developer's files are still there"
        );
        assert_eq!(
            std::fs::read_to_string(fx.hooks_dir().join(&taken)).expect("still readable"),
            MINE_NOW,
            "and the one under one of our names was not even modified"
        );

        super::remove_hooks(&fx.binding())
            .expect("removing again, with nothing of ours left, is still an Ok");
        assert_eq!(fx.listing().len(), 2, "and it took nothing on the way past");
    }

    // -----------------------------------------------------------------------
    // The eleventh artefact โ€” the enforcement plugin (plan 02 ยง3)
    // -----------------------------------------------------------------------

    /// The `Directory` arm writes the plugin **as well as** the ten, under a
    /// different root, in a different mode, recognisable by the same marker.
    ///
    /// Each clause is load-bearing. The wrong root is a file Cline never loads;
    /// the wrong mode claims an importable module is an executable; a second
    /// ownership scheme is a file uninstall and heal would each have to learn
    /// about separately.
    #[test]
    fn installing_a_directory_surface_writes_the_plugin_too() {
        let fx = DirFixture::new();
        let plugin_dir = fx.plugin_dir();
        assert!(
            !plugin_dir.exists(),
            "the fixture must not pre-create the directory the installer is being asked \
             to create"
        );

        super::install_hooks(&fx.binding_with_plugin(), 7443, "a-token")
            .expect("the directory arm writes");

        assert_eq!(
            fx.listing(),
            expected_listing(),
            "the plugin must not land among the ten, and must not displace one"
        );

        let entry = super::cline_plugin::entry_path(&plugin_dir);
        let body = std::fs::read_to_string(&entry).expect("a readable plugin");
        assert!(
            super::hook_files::is_ours(&body),
            "the plugin shares the ten's ownership predicate: {body}"
        );
        // The path is compared as the JavaScript literal the writer emits, not
        // as `display()`. On Windows those differ: `C:\Users\x` is written
        // `"C:\\Users\\x"`, because a lone backslash is an escape in JS and the
        // raw form would be a broken plugin rather than a cosmetic difference.
        // Asserting `display()` here passed on Unix and failed on Windows for a
        // file that was correct on both.
        let ol_dir_literal = serde_json::to_string(&fx.ol.path().display().to_string())
            .expect("a path renders as a JSON string");
        assert!(
            body.contains(&ol_dir_literal),
            "the plugin must carry the openlatch directory it talks to \
             as {ol_dir_literal}: {body}"
        );
        assert!(
            !body.contains("__OPENLATCH_DIR__"),
            "the template placeholder reached disk: {body}"
        );

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mode = std::fs::metadata(&entry)
                .expect("a stat-able plugin")
                .permissions()
                .mode()
                & 0o777;
            assert_eq!(mode, 0o644, "Node imports this file; it is never executed");
        }
    }

    /// No token reaches Cline's store either (D-09).
    ///
    /// `no_token_reaches_the_hook_directory` proves it for the asset root. The
    /// plugin is written into a second tree the agent owns, so the same claim
    /// has to be made again there โ€” the plugin carries a PATH and finds its
    /// credential through it, exactly as the ten shims do.
    #[test]
    fn no_token_reaches_the_plugin_directory() {
        const TOKEN: &str = "a-token-that-must-not-be-written";

        let fx = DirFixture::new();
        super::install_hooks(&fx.binding_with_plugin(), 7443, TOKEN).expect("install");

        let body = std::fs::read_to_string(super::cline_plugin::entry_path(&fx.plugin_dir()))
            .expect("a readable plugin");
        assert!(
            !body.contains(TOKEN),
            "the daemon's bearer token reached the agent's own store: {body}"
        );
    }

    /// A binding that declares no plugin surface gets no plugin โ€” anywhere.
    ///
    /// The blast-radius guard, and it is the reason `plugin_surface()` is
    /// `Option` and defaulted to `None`: every directory-surface fixture that
    /// predates the plugin keeps writing ten files and nothing else, and no
    /// future directory agent acquires one by inheritance.
    #[test]
    fn a_binding_with_no_plugin_surface_writes_no_plugin() {
        let fx = DirFixture::new();
        super::install_hooks(&fx.binding(), 7443, "a-token").expect("install");

        assert!(
            !fx.plugin_dir().exists(),
            "a binding that declared no plugin surface had one written for it"
        );
    }

    /// Uninstall is the inverse of install on this surface too: the plugin goes
    /// with the ten, from the other root.
    ///
    /// Left behind, it keeps loading into every Cline session and pointing at a
    /// daemon that is no longer there.
    #[test]
    fn uninstall_removes_the_plugin_as_well_as_the_ten() {
        let fx = DirFixture::new();
        super::install_hooks(&fx.binding_with_plugin(), 7443, "a-token").expect("install");
        assert!(super::cline_plugin::entry_path(&fx.plugin_dir()).exists());

        super::remove_hooks(&fx.binding_with_plugin()).expect("uninstall");

        assert!(
            !super::cline_plugin::entry_path(&fx.plugin_dir()).exists(),
            "the one artefact that can refuse a tool call outlived the uninstall"
        );
        assert_eq!(fx.listing(), Vec::<String>::new(), "and so did the ten");
    }

    /// The install records the plugin's one state row, and **uninstall drops it
    /// with the file** (plan 02 ยง3a.3).
    ///
    /// Not bookkeeping. The reconciler reads a missing file as drift and heals
    /// it by reinstalling, so a row left behind re-creates the plugin on the
    /// next 30-second poll โ€” an uninstall that silently undoes itself, with
    /// nothing else in either plan positioned to catch it.
    ///
    /// The key is asserted as well as the removal: the row hangs on the
    /// **file** path, because the directory name is only the plugin id and the
    /// file is what the reconciler reads.
    #[test]
    fn uninstall_drops_the_plugin_state_entry() {
        let fx = DirFixture::new();
        super::install_hooks(&fx.binding_with_plugin(), 7443, "a-token").expect("install");

        let entry = super::cline_plugin::entry_path(&fx.plugin_dir());
        let row = fx
            .state()
            .entries
            .into_iter()
            .find(|e| e.hook_event == super::cline_plugin::PLUGIN_ENTRY_EVENT)
            .expect("the install recorded a row for the plugin");

        assert_eq!(
            row.settings_path_hash,
            crate::core::hook_state::hash_settings_path(&entry),
            "the row must be keyed on the plugin FILE, not on the directory that names it"
        );
        let descriptor = row.descriptor.as_ref().expect("a stored descriptor");
        assert_eq!(descriptor.path, entry.to_string_lossy());
        assert_eq!(
            descriptor.sha256,
            super::hook_files::sha256_hex(
                &std::fs::read_to_string(&entry).expect("a readable plugin")
            ),
            "the stored hash is what heal compares against; a stale one heals forever"
        );
        assert_eq!(
            descriptor.mode, 0o644,
            "Node imports this file; 0755 would record an executable that is not one"
        );

        // The ten are keyed to the directory, so the plugin's row must not have
        // displaced one of theirs.
        assert_eq!(
            fx.state().entries.len(),
            super::hook_files::CLINE_HOOK_FILES.len() + 1,
            "eleven artefacts, eleven rows"
        );

        super::remove_hooks(&fx.binding_with_plugin()).expect("uninstall");

        assert!(
            fx.state()
                .entries
                .iter()
                .all(|e| e.hook_event != super::cline_plugin::PLUGIN_ENTRY_EVENT),
            "the plugin's row outlived its file; the next reconciler pass re-creates it"
        );
    }

    /// A plugin the developer wrote is never overwritten, and the install
    /// reports the path rather than swallowing it.
    #[test]
    fn a_plugin_we_did_not_write_is_never_overwritten_by_install() {
        const THEIRS: &str = "export default { name: 'mine' };\n";

        let fx = DirFixture::new();
        let entry = super::cline_plugin::entry_path(&fx.plugin_dir());
        std::fs::create_dir_all(fx.plugin_dir()).expect("the developer's own plugin directory");
        std::fs::write(&entry, THEIRS).expect("their plugin");

        let result = super::install_hooks(&fx.binding_with_plugin(), 7443, "a-token")
            .expect("a collision is not an error");

        assert_eq!(
            std::fs::read_to_string(&entry).expect("still readable"),
            THEIRS,
            "their plugin was rewritten"
        );
        assert!(
            result.left_alone.contains(&entry),
            "an install that refused to write a path must say which: {:?}",
            result.left_alone
        );
        assert_eq!(
            result.entries.len(),
            10,
            "the ten are unaffected by a collision on the eleventh"
        );

        super::remove_hooks(&fx.binding_with_plugin()).expect("uninstall");
        assert!(
            entry.exists(),
            "uninstall removed a plugin that is not ours"
        );
    }

    /// Uninstall against a directory that was never installed into does not
    /// create it.
    ///
    /// `write_all` creates the directory; `remove_all` must not. An uninstall
    /// that left an empty `Hooks/` behind in an agent store we never wrote to
    /// is litter at best, and on a host where the store itself is absent it is
    /// a directory tree conjured by the command that promises to leave nothing.
    #[test]
    fn uninstall_never_creates_the_hook_directory() {
        let fx = DirFixture::new();
        assert!(!fx.hooks_dir().exists(), "nothing was installed");

        super::remove_hooks(&fx.binding()).expect("nothing to remove is not a failure");

        assert!(
            !fx.hooks_dir().exists(),
            "uninstall must not conjure the directory it was asked to clean"
        );
    }
}