openlatch-client 0.6.3

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
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
/// Byte-identical uninstall for a binding that opts in (Cursor).
pub mod agent_backup;
/// 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;
/// Cline.app (bundle `bot.cline.app`): detection, and (feature `model-relay`) its hub (06).
pub mod cline_app;
/// The pinned Cline plugin-sandbox bootstrap tree, materialised under `<ol_dir>` (Cline I-5).
pub mod cline_bootstrap;
/// Which Cline hosts are installed, their JS runtime and embedded `@cline/core` version (Cline I-5).
pub mod cline_hosts;
pub mod cline_plugin;
pub mod cline_providers;
/// Per-host JS runtime wrappers and the headless plugin probe (Cline I-5).
pub mod cline_runtime;
pub mod codex_cli;
pub mod created_hook_files;
/// Cursor: the one root resolver (`OPENLATCH_CURSOR_DIR`, else `~/.cursor`) and detection.
pub mod cursor;
/// The two shapes of a hook entry — nested and flat — read in one place.
pub mod entry_shape;
pub mod health;
pub mod hook_files;
pub mod hook_trust_grants;
pub mod jsonc;
pub mod model_relay_endpoints;
pub mod provider_endpoints;
/// The per-command wrapper for a shell-launched `ProxyEnv` agent (I-2 D-27/D-28/D-38).
pub mod proxy_env_file;
/// The settings-key sink for a `ProxyEnv` agent's own JSON/JSONC setting (I-2 D-25/D-33/D-34).
pub mod proxy_settings;
/// The machine-global shell-profile line that sources the proxy wrapper (I-2, new).
pub mod shell_profile;
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,
    /// Cursor — the IDE and the CLI share one `~/.cursor/hooks.json`.
    Cursor,
    /// 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);

    // Where the ownership marker goes. A sidecar binding's file carries none:
    // the HMAC is taken over the entry as written and lives in the state row
    // only, and ownership is the exact command signature (`entry_shape`).
    let sidecar = binding.marker_placement() == binding::MarkerPlacement::Sidecar;

    let mut entries_with_markers: Vec<(String, serde_json::Value, String, 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)?;
        if !sidecar {
            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, hmac_value));
    }

    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());
    // Asked before the rewrite brings it into existence: a file we create is
    // one uninstall may delete again, once it holds nothing (#325 D4).
    let existed = settings_path.exists();

    let agent = binding.agent_type();
    let root_defaults = binding.file_root_defaults();
    let byte_identical = binding.byte_identical_restore();
    // Before the first write, so a crash between the rewrite and the record
    // below still leaves the original behind.
    let snapshot_taken = byte_identical
        && agent_backup::snapshot_before_first_write(&openlatch_dir, agent, &settings_path)?;

    let rewrite = atomic::atomic_rewrite_jsonc_returning(&settings_path, |root| {
        // The guard first: nothing is written into a format this build does
        // not know.
        jsonc::check_root_defaults(root, root_defaults, &settings_path)?;
        jsonc::set_root_defaults_cst(root, root_defaults);
        let a = if sidecar {
            jsonc::insert_hook_entries_cst_owned_by(root, &jsonc_entries, &|el| {
                entry_shape::is_sidecar_owned_node(el, agent)
            })?
        } else {
            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(())
    });
    // A refused write (the version guard, unparseable input) leaves no snapshot
    // of its own behind: the next install must snapshot the file as it is then.
    let rewrite = match rewrite {
        Ok(rewrite) => rewrite,
        Err(e) => {
            if snapshot_taken {
                let _ = agent_backup::retire(&openlatch_dir, agent, &settings_path);
            }
            return Err(e);
        }
    };

    // From the exact text written, never a re-read. Bookkeeping: a failure
    // costs only the exact restore, and uninstall then removes our entries by
    // CST instead.
    if byte_identical {
        if let Err(e) = agent_backup::record_last_write(
            &openlatch_dir,
            agent,
            &settings_path,
            rewrite.before.as_deref(),
            &rewrite.after,
        ) {
            tracing::warn!(
                path = %settings_path.display(),
                error = %e,
                "hooks installed, but the byte-identical restore point could not be recorded"
            );
        }
    }

    let actions = actions.into_inner();

    // Bookkeeping, not the install: a failure costs only the empty file's
    // deletion at uninstall, and the file is then kept — the safe side.
    if !existed {
        if let Err(e) = created_hook_files::record(&openlatch_dir, &settings_path) {
            tracing::warn!(
                path = %settings_path.display(),
                error = %e,
                "hooks installed, but the file's creation could not be recorded"
            );
        }
    }

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

    // The HMAC computed above — the same value the in-entry marker carries,
    // and for a sidecar binding the only copy there is.
    for (et, _, entry_id, hmac_val) in &entries_with_markers {
        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.clone(),
            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: crate::core::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();

    // An agent that runs no hook until it is trusted gets that trust now, from
    // the same call that wrote the hooks — so `init`, `doctor --fix` and the
    // reconciler's heal all leave an install that runs. A grant that could not
    // be made does not fail the install: the hooks are written, and `doctor`
    // reports the missing trust with its remedy.
    match binding.trust_own_hooks(binding::TrustOccasion::Install) {
        Ok(0) => {}
        Ok(granted) => tracing::info!(
            agent = binding.agent_type(),
            granted,
            "trusted the installed hooks in the agent's own config"
        ),
        Err(e) => tracing::warn!(
            agent = binding.agent_type(),
            error = %e,
            "hooks installed, but the agent's trust could not be granted"
        ),
    }

    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: crate::core::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),
        }

        // The pinned bootstrap tree Cline's other hosts need to load that plugin (Cline I-5).
        // Pure file I/O under `openlatch_dir` — no detection, no process: the reconciler's
        // drift-heal reaches this path. Not deliverable is logged, never a failed install.
        if let Err(e) = cline_bootstrap::materialise(openlatch_dir) {
            tracing::warn!(
                code = e.code,
                error = %e,
                "the Cline plugin bootstrap tree was not materialised — the plugin cannot be delivered to Cline.app or VS Code"
            );
        }
    }

    // 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),
    };

    let openlatch_dir = crate::config::openlatch_dir();
    let agent = binding.agent_type();
    let byte_identical = binding.byte_identical_restore();

    // Byte-identical first, for a binding that opts in: when the file is still
    // exactly our last write, the pre-install bytes go back and nothing below
    // runs. Any other answer falls through to the CST removal.
    if byte_identical {
        match agent_backup::restore_if_unchanged(&openlatch_dir, agent, &settings_path) {
            Ok(agent_backup::RestoreOutcome::RestoredExact)
            | Ok(agent_backup::RestoreOutcome::DeletedCreated) => {
                // The same tail as the CST path, where `delete_if_created_and_empty`
                // is what clears the created-file record.
                forget_surface(binding, &settings_path);
                if let Err(e) = created_hook_files::forget(&openlatch_dir, &settings_path) {
                    tracing::warn!(
                        path = %settings_path.display(),
                        error = %e,
                        "could not clear the created-file record"
                    );
                }
                revoke_trust_best_effort(binding);
                return Ok(());
            }
            Ok(_) => {}
            Err(e) => tracing::warn!(
                path = %settings_path.display(),
                error = %e,
                "the byte-identical restore failed; removing OpenLatch's entries instead"
            ),
        }
    }

    if !settings_path.exists() {
        if byte_identical {
            retire_snapshot(&openlatch_dir, agent, &settings_path);
        }
        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,
    };

    let sidecar = binding.marker_placement() == binding::MarkerPlacement::Sidecar;
    let root_defaults = binding.file_root_defaults();
    atomic::atomic_rewrite_jsonc(&settings_path, |root| {
        jsonc::check_root_defaults(root, root_defaults, &settings_path)?;
        if sidecar {
            // The predicate install replaced with — this binding's exact
            // signature, never another agent's entry or a developer's wrapper.
            jsonc::remove_owned_entries_cst_by(root, &|el| {
                entry_shape::is_sidecar_owned_node(el, agent)
            })?;
        } else {
            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(())
    })?;

    // The rows go with the entries (#325). Left behind, they are what the
    // reconciler reads as "tracked but missing", and it reinstalls every hook
    // this function just removed on the next daemon start.
    forget_surface(binding, &settings_path);

    // The trust install granted, taken back once the hooks it named are gone.
    revoke_trust_best_effort(binding);

    if root_defaults.is_empty() {
        delete_if_created_and_empty(&openlatch_dir, &settings_path);
    } else {
        delete_if_created_and_only_defaults(&openlatch_dir, &settings_path, root_defaults);
    }
    // Retired whichever way this went, so the next install snapshots the file
    // as it is then — a later uninstall must never restore bytes older than
    // the developer's edits.
    if byte_identical {
        retire_snapshot(&openlatch_dir, agent, &settings_path);
    }

    Ok(())
}

/// Take back the trust install granted, once the hooks it named are gone.
/// Left behind it would be harmless, and it would also be untidy in a file the
/// customer reads — so a failure here is reported, not fatal.
fn revoke_trust_best_effort(binding: &dyn AgentBinding) {
    if let Err(e) = binding.revoke_own_hook_trust() {
        tracing::warn!(
            agent = binding.agent_type(),
            error = %e,
            "hooks removed, but the trust OpenLatch granted could not be taken back"
        );
    }
}

/// [`agent_backup::retire`], best effort: a snapshot left behind costs a stale
/// restore point, and an `Err` here would gate the rest of `uninstall`.
fn retire_snapshot(openlatch_dir: &std::path::Path, agent: &str, path: &std::path::Path) {
    if let Err(e) = agent_backup::retire(openlatch_dir, agent, path) {
        tracing::warn!(
            path = %path.display(),
            error = %e,
            "could not retire the byte-identical restore point"
        );
    }
}

/// [`delete_if_created_and_empty`] for a binding whose file root carries
/// defaults (Cursor's `"version": 1`): a file we created is deleted once it
/// holds exactly those defaults and no hook — `hooks` absent or `{}`.
///
/// Strict JSON, deliberately: a comment is something, exactly as it is for
/// the `{}` rule, and a file carrying one is kept.
fn delete_if_created_and_only_defaults(
    openlatch_dir: &std::path::Path,
    path: &std::path::Path,
    defaults: &[(&str, i64)],
) {
    delete_if_created_and(openlatch_dir, path, |raw| {
        let Ok(serde_json::Value::Object(root)) = serde_json::from_str(raw) else {
            return false;
        };
        root.iter().all(|(key, value)| {
            if key == "hooks" {
                return value.as_object().is_some_and(serde_json::Map::is_empty);
            }
            defaults
                .iter()
                .any(|(k, v)| k == key && value.as_i64() == Some(*v))
        }) && defaults.iter().all(|(k, _)| root.contains_key(*k))
    });
}

/// Delete a hook file install created, once removal has left it holding
/// nothing (#325 D4) — Codex's `hooks.json` reduced to `{}`, which nobody
/// asked for.
///
/// "Nothing" is literal: the file must be `{}` and whitespace. A comment is
/// something — a customer who annotated a file we created has made it theirs
/// — and so is any key. Either way the file is kept, and so is its record, so a
/// later uninstall that finds it empty can still delete it. A file that existed
/// before install is never deleted, whatever it holds.
fn delete_if_created_and_empty(openlatch_dir: &std::path::Path, path: &std::path::Path) {
    delete_if_created_and(openlatch_dir, path, |raw| {
        raw.chars().filter(|c| !c.is_whitespace()).eq("{}".chars())
    });
}

/// The tail both deletion rules share: a file install recorded as created,
/// whose contents `is_empty` accepts, is deleted and its record cleared. A
/// file that was not created, cannot be read, or holds something is kept.
fn delete_if_created_and(
    openlatch_dir: &std::path::Path,
    path: &std::path::Path,
    is_empty: impl FnOnce(&str) -> bool,
) {
    if !created_hook_files::is_recorded(openlatch_dir, path) {
        return;
    }
    if !std::fs::read_to_string(path).is_ok_and(|raw| is_empty(&raw)) {
        return;
    }
    if let Err(e) = std::fs::remove_file(path) {
        tracing::warn!(path = %path.display(), error = %e, "could not delete an emptied hook file");
        return;
    }
    if let Err(e) = created_hook_files::forget(openlatch_dir, path) {
        tracing::warn!(path = %path.display(), error = %e, "could not clear the created-file record");
    }
}

/// [`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)?;
    // The ten rows, for the reason the plugin's goes below.
    forget_surface(binding, 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_surface(binding, &cline_plugin::entry_path(&plugin_dir));
    }

    Ok(())
}

/// Drop every state row `binding` holds under one surface (a hook file, the
/// hook directory, or the plugin's entry file), best effort.
///
/// Best effort and not a `Result`: `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_surface(binding: &dyn AgentBinding, surface: &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 its rows"
            );
            return;
        }
    };

    if !state.remove_surface(
        binding.agent_type(),
        &hook_state::hash_settings_path(surface),
    ) {
        return;
    }

    if let Err(e) = state.save(&openlatch_dir) {
        tracing::warn!(
            code = crate::error::ERR_STATE_FILE_WRITE_FAILED,
            error = %e,
            "uninstall: the hooks are gone but their state rows could not be dropped — \
             the reconciler may re-create them"
        );
    }
}

// ---------------------------------------------------------------------------
// 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();
    entries.extend(
        loopback_entries_to_add(existing)
            .into_iter()
            .map(str::to_string),
    );
    entries.join(",")
}

/// The loopback entries [`merge_loopback_entries`] appends to `existing` — what
/// the wiring records as ours, so removal takes back exactly these.
fn loopback_entries_to_add(existing: Option<&str>) -> Vec<&'static str> {
    let entries: Vec<&str> = existing
        .unwrap_or_default()
        .split(',')
        .map(str::trim)
        .collect();
    LOOPBACK_BYPASS_ENTRIES
        .into_iter()
        // Case-insensitive, because `LOCALHOST` and `localhost` are the same host and
        // appending a second spelling is noise the customer has to read past forever.
        .filter(|wanted| !entries.iter().any(|e| e.eq_ignore_ascii_case(wanted)))
        .collect()
}

/// Take `ours` back out of a comma-separated bypass list: one occurrence of each,
/// compared as written. Every other entry keeps its position and its spelling.
fn strip_loopback_entries(current: &str, ours: &[String]) -> String {
    let mut to_remove: Vec<&str> = ours.iter().map(String::as_str).collect();
    current
        .split(',')
        .filter(
            |entry| match to_remove.iter().position(|ours| *ours == entry.trim()) {
                Some(i) => {
                    to_remove.remove(i);
                    false
                }
                None => true,
            },
        )
        .collect::<Vec<_>>()
        .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\""
        ),
        Some(binding::EndpointConvention::ProxyEnv { .. }) => {
            let ca_pem = crate::model_relay::ca::ca_pem_path(&crate::model_relay::ca::ca_dir(
                &crate::config::openlatch_dir(),
            ));
            format!(
                "HTTPS_PROXY=http://127.0.0.1:{port} NODE_EXTRA_CA_CERTS={} for a shell-launched \
                 session (an editor-hosted one also needs that CA in the user trust store)",
                ca_pem.display()
            )
        }
        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()))
        }
        // Every log line names ONE path; the first delivery's is the one that means something.
        binding::EndpointConvention::ProxyEnv { delivery, .. } => match delivery.first() {
            Some(binding::ProxyDelivery::SettingsKey { file, .. }) => file(),
            Some(binding::ProxyDelivery::EnvFile { .. }) | None => {
                Some(proxy_env_file::env_sh_path(&crate::config::openlatch_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.
/// Nor while a record is on file: a re-write after the wiring was deleted or
/// repointed (the wiring supervisor's drift heal) keeps the prior it has.
///
/// 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.
/// One `SettingsKey` delivery of `write_model_relay_config`'s `ProxyEnv` arm, extracted so that
/// loop stays shallow. Returns whether the delivery counts as delivered; every skip reason (a
/// missing file, a settings-only write failure, a foreign or unparseable value) is pushed onto
/// `skipped` instead of returned, exactly as it was written inline. Any other error still
/// propagates, as `?` did before this was its own function.
fn deliver_settings_key(
    agent: &str,
    file: fn() -> Option<std::path::PathBuf>,
    key: &str,
    url: &str,
    skipped: &mut Vec<String>,
) -> Result<bool, OlError> {
    let Some(path) = file() else {
        skipped.push(format!(
            "{key}: {}",
            crate::model_relay::preflight::SETTINGS_NO_FILE
        ));
        return Ok(false);
    };
    match proxy_settings::write_proxy_key(&path, key, url, agent) {
        // A missing settings directory or a file that kept changing: a
        // skip, not an abort, so a later EnvFile delivery still lands. The
        // message is exactly SETTINGS_NO_FILE or SETTINGS_CONTENDED, the
        // phrases plan 04 matches.
        Err(e) if e.code == crate::error::ERR_MODEL_RELAY_SETTINGS => {
            skipped.push(format!("{key}: {}", e.message));
            Ok(false)
        }
        Err(e) => Err(e), // any other error still propagates, as `?` did
        Ok(proxy_settings::KeyWrite::Written | proxy_settings::KeyWrite::AlreadyOurs) => Ok(true),
        Ok(proxy_settings::KeyWrite::Foreign(v)) => {
            // D-34: never overwritten. The value is NOT logged — it can
            // carry credentials.
            tracing::warn!(
                code = crate::error::ERR_MODEL_RELAY_SETTINGS,
                agent,
                key,
                path = %path.display(),
                "the agent's proxy setting names a proxy OpenLatch did not \
                 write — left untouched; that surface is not captured. Move \
                 that proxy into OpenLatch's [proxy] config"
            );
            let _ = v;
            // The shared phrase: plan 04's settings_remedy matches on it.
            skipped.push(format!(
                "{key}: {}",
                crate::model_relay::preflight::SETTINGS_FOREIGN
            ));
            Ok(false)
        }
        Ok(proxy_settings::KeyWrite::Unparseable(why)) => {
            tracing::warn!(
                code = crate::error::ERR_MODEL_RELAY_SETTINGS,
                agent,
                key,
                path = %path.display(),
                reason = %why,
                "the agent's settings file is not valid JSONC — left \
                 untouched; that surface is not captured"
            );
            skipped.push(format!("{key}: {why}"));
            Ok(false)
        }
    }
}

pub fn write_model_relay_config(
    binding: &dyn AgentBinding,
    port: u16,
    install_id: &str,
) -> Result<(), OlError> {
    write_model_relay_config_trusting(binding, port, install_id, true)
}

/// [`write_model_relay_config`] with the trust lane spelled out. `store_trusted = false` is an
/// isolated instance that proved only the env-trusted chain (`NODE_EXTRA_CA_CERTS`): it writes the
/// `EnvFile` deliveries and skips every `SettingsKey`, whose editor trusts only the OS store.
pub fn write_model_relay_config_trusting(
    binding: &dyn AgentBinding,
    port: u16,
    install_id: &str,
    store_trusted: bool,
) -> 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.
                //
                // And the record, once taken, is the prior for as long as it
                // lives, whatever the file now holds. A re-wire after the base
                // URL was deleted or repointed (the supervisor's drift heal)
                // must not record the tampered value: uninstall would then
                // "restore" it.
                let we_wired_it_before = model_relay_endpoints::peek(agent).is_some();
                if !we_wired_it_before {
                    // 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. What we append is recorded (first value
                // wins), so `remove_model_relay_config` takes back exactly that.
                for key in NO_PROXY_ENV_KEYS {
                    let existing = jsonc::get_env_var_cst(root, key);
                    model_relay_endpoints::record_no_proxy(
                        agent,
                        key,
                        model_relay_endpoints::NoProxyAdded {
                            created: existing.is_none(),
                            entries: loopback_entries_to_add(existing.as_deref())
                                .into_iter()
                                .map(str::to_string)
                                .collect(),
                        },
                    )?;
                    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.
            //
            // A record already on file is the prior, and the ledger's word that
            // the table of our name is ours: a re-wire after `model_provider`
            // was removed or the table repointed keeps the record and
            // overwrites the table, rather than recording the tampered value or
            // refusing the table as foreign.
            let recorded = model_relay_endpoints::peek(agent).is_some();
            let prior = codex_cli::read_prior_provider(&config_toml, provider_name)?;
            let mut record_now = false;
            if let (false, codex_cli::Prior::Theirs(p)) = (recorded, &prior) {
                model_relay_endpoints::record(agent, p.clone())?;
                record_now = true;
            }
            let write = codex_cli::write_provider_table_as(
                &config_toml,
                provider_name,
                wire_api,
                wiring.install_id_header,
                port,
                install_id,
                recorded,
            );
            if write.is_err() && record_now {
                // 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(|_| ())
        }
        binding::EndpointConvention::ProxyEnv {
            intercept_hosts,
            delivery,
        } => {
            // A binding bug, surfaced here rather than as an agent that is silently unwired.
            if intercept_hosts.is_empty() || delivery.is_empty() {
                return Err(OlError::new(
                    crate::error::ERR_MODEL_RELAY_IO,
                    format!("{agent}: ProxyEnv declares no intercept host or no delivery"),
                ));
            }
            let ol = crate::config::openlatch_dir();
            let ca_pem = crate::model_relay::ca::ca_pem_path(&crate::model_relay::ca::ca_dir(&ol));
            // The daemon's D-09r gate makes this unreachable there; kept for every other
            // caller.
            if !ca_pem.is_file() {
                return Err(OlError::new(
                    crate::error::ERR_MODEL_RELAY_IO,
                    format!(
                        "{agent}: {} does not exist — the relay has not created its CA",
                        ca_pem.display()
                    ),
                ));
            }
            let url = format!("http://127.0.0.1:{port}");
            let (mut delivered, mut skipped, mut wrapper) = (0usize, Vec::<String>::new(), false);
            for d in delivery {
                match d {
                    binding::ProxyDelivery::SettingsKey { key, .. } if !store_trusted => {
                        skipped.push(format!("{key}: {SETTINGS_KEY_ISOLATED_SKIP}"));
                    }
                    binding::ProxyDelivery::SettingsKey { file, key } => {
                        if deliver_settings_key(agent, *file, key, &url, &mut skipped)? {
                            delivered += 1;
                        }
                    }
                    binding::ProxyDelivery::EnvFile { commands, defaults } => {
                        proxy_env_file::write_block(
                            agent,
                            commands,
                            defaults,
                            &url,
                            &ca_pem,
                            &proxy_env_file::relay_no_proxy(port),
                        )?;
                        delivered += 1;
                        wrapper = true;
                    }
                }
            }
            if wrapper {
                proxy_env_file::set_live(true)?; // AFTER the block: a marker never precedes its wrapper
            }
            if delivered == 0 {
                return Err(OlError::new(
                    crate::error::ERR_MODEL_RELAY_SETTINGS,
                    format!(
                        "{}{}",
                        crate::model_relay::preflight::SETTINGS_REASON_MARKER,
                        skipped.join("; ")
                    ),
                ));
                // The daemon wrapper's Err arm turns this into Verdict::Failed(e.message), so
                // the message becomes the PreflightFailed reason verbatim; the marker is what
                // plan 04's settings arm matches (INDEX contract).
            }
            Ok(())
        }
    }
}

/// Why a `SettingsKey` is not delivered from an isolated instance. Shared with `doctor`'s row.
pub(crate) const SETTINGS_KEY_ISOLATED_SKIP: &str =
    "not delivered from an isolated instance (VS Code trusts only the OS store)";

/// I-4 D-40/D-43 (amended): whether `binding` has an interception plane — its model-relay wiring is
/// `ProxyEnv`. While true, its non-loopback slots are never rewritten and are handed back.
pub(crate) fn declares_proxy_env(binding: &dyn AgentBinding) -> bool {
    binding
        .model_relay_wiring()
        .is_some_and(|w| w.endpoint.is_proxy_env())
}

/// I-4 D-44: whether one delivery points at the relay right now. A `SettingsKey` is live when its
/// file holds exactly our value (`proxy_settings::observe_key == Observed::Ours`). An `EnvFile` is
/// live when its wrapper is (`proxy_env_file::live_proxy_url(agent).is_some()`).
fn delivery_is_live(agent: &str, d: &binding::ProxyDelivery) -> bool {
    match d {
        binding::ProxyDelivery::SettingsKey { file, key } => file().is_some_and(|p| {
            matches!(
                proxy_settings::observe_key(&p, key, agent),
                Ok(proxy_settings::Observed::Ours(_))
            )
        }),
        binding::ProxyDelivery::EnvFile { .. } => proxy_env_file::live_proxy_url(agent).is_some(),
    }
}

/// `env.<name>` of a JSONC settings file, as the agent reads it. `Ok(None)` when the file or the
/// key is absent; `Err` when the file is there and cannot be read or parsed.
fn read_env_var(settings_path: &std::path::Path, name: &str) -> Result<Option<String>, OlError> {
    let raw = match std::fs::read_to_string(settings_path) {
        Ok(raw) => raw,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
        Err(e) => {
            return Err(OlError::new(
                crate::error::ERR_MODEL_RELAY_IO,
                format!("cannot read {}: {e}", settings_path.display()),
            ))
        }
    };
    let parsed = jsonc::parse_settings_value(&raw)?;
    Ok(parsed
        .get("env")
        .and_then(|env| env.get(name))
        .and_then(serde_json::Value::as_str)
        .map(str::to_string))
}

/// Read `env.ANTHROPIC_BASE_URL` from the agent settings, but only when it is
/// OUR loopback URL — a customer's corporate gateway is not our wiring and must
/// not be reported as such.
pub(crate) fn read_model_relay_base_url(settings_path: &std::path::Path) -> Option<String> {
    let url = read_env_var(settings_path, "ANTHROPIC_BASE_URL").ok()??;
    is_openlatch_loopback_base_url(&url).then_some(url)
}

/// How an agent's relay wiring stands on disk, against what the endpoint ledger says this
/// install wrote. Asked by the daemon's wiring supervisor — the one writer — on every pass over
/// an agent it believes is wired; a drift is reported as `tamper_detected` and re-wired.
#[derive(Debug, Clone)]
pub enum WiringDrift {
    /// Everything we wrote is still there, naming our listener.
    Intact,
    /// The ledger holds nothing of ours for this agent: the wiring was handed back (`uninstall`,
    /// `stop`, the relay switched off), not lost. Never tamper.
    Released,
    /// Something we wrote is gone. The deltas are field paths, never values.
    Unwired(Vec<crate::core::cloud::tamper::FieldDelta>),
    /// Something we wrote now names something else — another URL, another provider, another
    /// port. Wins over [`Self::Unwired`] when both are seen.
    Modified(Vec<crate::core::cloud::tamper::FieldDelta>),
}

/// [`WiringDrift`] for `binding`, whose wiring names the relay on `port`. One reader per
/// [`binding::EndpointConvention`], each the one its writer and `read_agent_wiring` already use.
///
/// The ledger is the authority on what is ours. `EnvVars` and `TomlProvider` record every wiring
/// under the agent's name before the write commits and forget it only once a removal has landed;
/// `ProxyEnv` settings keys carry their own records. So a value the ledger does not claim is
/// never drift — the one gap is a `ProxyEnv` agent with no settings-key record at all (the
/// wrapper alone), whose wrapper a concurrent `uninstall` removes without a record to say so.
/// That window closes with `uninstall`'s own stop of the daemon, whose teardown releases again.
///
/// The shell-profile line is not read here: whether it is ours to write is the daemon's
/// machine-global question (`daemon::profile_line_wanted`), so the daemon adds it.
pub fn wiring_on_disk(binding: &dyn AgentBinding, port: u16) -> WiringDrift {
    use crate::core::cloud::tamper::FieldDelta;

    let Some(wiring) = binding.model_relay_wiring() else {
        return WiringDrift::Released;
    };
    let agent = binding.agent_type();
    let ours = format!("http://127.0.0.1:{port}");
    let mut deltas: Vec<FieldDelta> = Vec::new();
    let mut note = |field: String, change: &str| {
        deltas.push(FieldDelta {
            field,
            change: change.to_string(),
        })
    };
    match wiring.endpoint {
        binding::EndpointConvention::EnvVars { base_url, headers } => {
            if model_relay_endpoints::peek(agent).is_none() {
                return WiringDrift::Released;
            }
            let path = binding.hook_config_path();
            match read_env_var(&path, base_url) {
                Ok(Some(v)) if v.trim() == ours => {}
                Ok(Some(_)) | Err(_) => note(format!("env.{base_url}"), "modified"),
                Ok(None) => note(format!("env.{base_url}"), "removed"),
            }
            let header_is_ours = |v: &str| {
                v.split('\n')
                    .any(|line| is_install_id_line(line, wiring.install_id_header))
            };
            match read_env_var(&path, headers) {
                Ok(Some(v)) if header_is_ours(&v) => {}
                // The base URL above already said so for an unreadable file.
                Err(_) => {}
                Ok(_) => note(format!("env.{headers}"), "removed"),
            }
        }
        binding::EndpointConvention::TomlProvider { provider_name, .. } => {
            if model_relay_endpoints::peek(agent).is_none() {
                return WiringDrift::Released;
            }
            let path = codex_cli::config_toml_path(&binding.config_dir());
            match codex_cli::read_prior_provider(&path, provider_name) {
                Ok(codex_cli::Prior::Ours) => {}
                Ok(codex_cli::Prior::Theirs(None)) => note("model_provider".to_string(), "removed"),
                Ok(codex_cli::Prior::Theirs(Some(_))) | Err(_) => {
                    note("model_provider".to_string(), "modified")
                }
            }
            let field = format!("model_providers.{provider_name}.base_url");
            let doc = std::fs::read_to_string(&path)
                .ok()
                .and_then(|raw| raw.parse::<toml_edit::DocumentMut>().ok());
            match doc
                .as_ref()
                .and_then(|d| codex_cli::provider_base_url(d, provider_name))
            {
                Some(v) if v.trim() == format!("{ours}/v1") => {}
                Some(_) => note(field, "modified"),
                None => note(field, "removed"),
            }
        }
        binding::EndpointConvention::ProxyEnv { delivery, .. } => {
            let Ok((owned, handed_back)) = proxy_settings::owned_keys(agent) else {
                // An unreadable ledger proves nothing either way.
                return WiringDrift::Intact;
            };
            if handed_back {
                return WiringDrift::Released;
            }
            for (file, key) in owned {
                match proxy_settings::observe_key(&file, &key, agent) {
                    Ok(proxy_settings::Observed::Ours(v)) if v == ours => {}
                    Ok(proxy_settings::Observed::Unset(_) | proxy_settings::Observed::NoFile) => {
                        note(key, "removed")
                    }
                    Ok(_) => note(key, "modified"),
                    Err(_) => {}
                }
            }
            if delivery
                .iter()
                .any(|d| matches!(d, binding::ProxyDelivery::EnvFile { .. }))
            {
                match proxy_env_file::live_proxy_url(agent) {
                    Some(v) if v == ours => {}
                    Some(_) => note("env.sh.HTTPS_PROXY".to_string(), "modified"),
                    None => note(format!("env.sh.{agent}"), "removed"),
                }
            }
        }
    }
    if deltas.is_empty() {
        WiringDrift::Intact
    } else if deltas.iter().any(|d| d.change == "modified") {
        WiringDrift::Modified(deltas)
    } else {
        WiringDrift::Unwired(deltas)
    }
}

/// I-4 D-44: whether an editor surface of `binding` is pointed at the relay right now — some
/// `ProxyDelivery::SettingsKey` of its `ProxyEnv` wiring that `delivery_is_live`. 02 writes a value
/// only after the full proof and releases it on stop, relay-off, refusal and expiry, so "ours on disk"
/// is "proven and live". `false` for every other convention, and for an unreadable file.
pub(crate) fn editor_proxy_written(binding: &dyn AgentBinding) -> bool {
    let Some(binding::EndpointConvention::ProxyEnv { delivery, .. }) =
        binding.model_relay_wiring().map(|w| w.endpoint)
    else {
        return false;
    };
    delivery.iter().any(|d| {
        matches!(d, binding::ProxyDelivery::SettingsKey { .. })
            && delivery_is_live(binding.agent_type(), d)
    })
}

/// Take back every proxy value this install wrote for `binding`: every settings key the ledger
/// holds for the agent (by RECORD, not by declaration — a `file()` that moved since the write is
/// still restored), the agent's wrapper block, and the marker when no wrapper remains.
/// Attempts every step even when one fails; returns the first error.
pub fn release_proxy_env(
    binding: &dyn AgentBinding,
    by: model_relay_endpoints::ReleasedBy,
) -> Result<(), OlError> {
    let agent = binding.agent_type();
    let mut first: Option<OlError> = None;
    let mut keep_first = |r: Result<(), OlError>| {
        if let Err(e) = r {
            if first.is_none() {
                first = Some(e);
            }
        }
    };
    let prefix = format!("{}{agent}:", proxy_settings::RECORD_PREFIX);
    match model_relay_endpoints::endpoint_records(&prefix) {
        Err(e) => keep_first(Err(e)),
        Ok(recs) => {
            for (rk, rec) in recs.into_iter().filter(|(_, r)| r.is_live()) {
                let Some((key, _)) = rk[prefix.len()..].split_once('@') else {
                    continue;
                };
                keep_first(proxy_settings::release_proxy_key(&rec.file, key, agent, by).map(drop));
            }
        }
    }
    // ALWAYS runs: the agent's open-shell wrappers go direct now.
    keep_first(proxy_env_file::remove_block(agent).map(drop));
    if !proxy_env_file::has_blocks() {
        keep_first(proxy_env_file::set_live(false));
    }
    first.map_or(Ok(()), Err)
}

/// 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` lose only the loopback entries the wiring recorded
///   appending.** `127.0.0.1` and `localhost` carry no ownership marker of their own —
///   a customer whose list already named them is indistinguishable, in the file, from
///   one who got them from us — so ownership comes from the record the writer took
///   before merging, never from the value. Every other entry keeps its position and
///   spelling; a variable we created and that is now empty is removed; one that existed
///   before us is kept, even empty. A record written before this was tracked says
///   nothing about the entries, and the variable is then left exactly as it is.
///   `tests/cli_contract.rs` pins both halves.
///
/// 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)?;
                    }
                }
                // D-24 reversed: only what the writer recorded appending.
                for (key, added) in model_relay_endpoints::peek_no_proxy(agent) {
                    let Some(current) = jsonc::get_env_var_cst(root, &key) else {
                        continue;
                    };
                    let remainder = strip_loopback_entries(&current, &added.entries);
                    if remainder.trim().is_empty() && added.created {
                        jsonc::remove_env_var_cst(root, &key)?;
                    } else if remainder != current {
                        jsonc::set_env_var_cst(root, &key, &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));
            // The hooks may already be gone, and these were the last keys in a
            // file install created: uninstall runs this after `remove_hooks`.
            delete_if_created_and_empty(&crate::config::openlatch_dir(), &settings_path);
            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
        }
        binding::EndpointConvention::ProxyEnv { .. } => {
            release_proxy_env(binding, model_relay_endpoints::ReleasedBy::Teardown)
        }
    }
}

/// 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())
}

/// The pieces a Cursor install test must redirect, under the locks that make
/// it safe, in the crate's order: `OPENLATCH_DIR` first, the hook binary next.
/// The Cursor binding is constructed rather than detected, so no Cursor seam is
/// written and no config-dir lock is needed.
///
/// Shared by this module's tests and the reconciler's: `f` runs with the
/// binding and the redirected `OPENLATCH_DIR`, nothing installed yet.
#[cfg(test)]
pub(crate) fn with_cursor_install_env<T>(
    f: impl FnOnce(&bindings::cursor::CursorBinding, &std::path::Path) -> T,
) -> T {
    let _dir_lock = crate::config::OPENLATCH_DIR_ENV_LOCK
        .lock()
        .unwrap_or_else(|e| e.into_inner());
    let _bin_lock = staging::HOOK_BIN_ENV_LOCK
        .lock()
        .unwrap_or_else(|e| e.into_inner());

    let ol = tempfile::tempdir().unwrap();
    let cursor = 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 _env = cline::EnvOverride::apply([
        ("OPENLATCH_DIR", Some(ol.path().as_os_str().to_owned())),
        ("OPENLATCH_HOOK_BIN", Some(hook_bin.as_os_str().to_owned())),
        ("OPENLATCH_SKIP_KEYRING", Some("1".into())),
    ]);
    let binding = bindings::cursor::CursorBinding {
        root: cursor.path().to_path_buf(),
        hooks_path: cursor.path().join("hooks.json"),
    };
    f(&binding, ol.path())
}

// ---------------------------------------------------------------------------
// 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,
            hooks_list: std::sync::Arc::new(|_| 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}"
        );
    }

    /// D-24 reversed: install then remove gives the customer's bypass list back
    /// byte for byte, and a variable the wiring created goes with it.
    #[test]
    fn no_proxy_round_trip_takes_back_only_our_entries() {
        let dir = tempfile::tempdir().unwrap();
        let agent = envvars_agent(dir.path());
        let path = agent.hook_config_path();
        std::fs::write(&path, r#"{"env":{"NO_PROXY":"internal.corp"}}"#).unwrap();

        with_openlatch_dir(|| {
            write_model_relay_config(&agent, 7600, "agt_x").unwrap();
            let wired = read_env(&path);
            assert_eq!(
                wired["env"]["NO_PROXY"],
                "internal.corp,127.0.0.1,localhost"
            );
            assert_eq!(wired["env"]["no_proxy"], "127.0.0.1,localhost");
            // A re-wire must not claim the entries it finds as newly added.
            write_model_relay_config(&agent, 7600, "agt_x").unwrap();
            remove_model_relay_config(&agent).unwrap();
        });

        let v = read_env(&path);
        assert_eq!(v["env"]["NO_PROXY"], "internal.corp", "{v}");
        assert!(v["env"].get("no_proxy").is_none(), "we created it: {v}");
    }

    /// A customer who already listed loopback keeps it: nothing was appended,
    /// so nothing is taken.
    #[test]
    fn no_proxy_entries_the_customer_already_had_survive() {
        let dir = tempfile::tempdir().unwrap();
        let agent = envvars_agent(dir.path());
        let path = agent.hook_config_path();
        let seeded = "localhost,internal.corp,127.0.0.1";
        std::fs::write(
            &path,
            format!(r#"{{"env":{{"NO_PROXY":"{seeded}","no_proxy":""}}}}"#),
        )
        .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_eq!(v["env"]["NO_PROXY"], seeded, "{v}");
        assert_eq!(v["env"]["no_proxy"], "", "existed before us, kept: {v}");
    }

    /// A record from before the bypass was tracked leaves the variable alone.
    #[test]
    fn a_legacy_record_leaves_no_proxy_untouched() {
        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:7600","NO_PROXY":"127.0.0.1,localhost"}}"#,
        )
        .unwrap();

        with_openlatch_dir(|| {
            super::model_relay_endpoints::record(agent.agent_type(), None).unwrap();
            remove_model_relay_config(&agent).unwrap();
        });

        let v = read_env(&path);
        assert_eq!(v["env"]["NO_PROXY"], "127.0.0.1,localhost", "{v}");
        assert!(v["env"].get("ANTHROPIC_BASE_URL").is_none(), "{v}");
    }

    #[test]
    fn strip_loopback_entries_keeps_every_other_entry_as_written() {
        let ours = vec!["127.0.0.1".to_string(), "localhost".to_string()];
        assert_eq!(
            super::strip_loopback_entries("a.corp, 127.0.0.1 ,b.corp,localhost", &ours),
            "a.corp,b.corp"
        );
        // One occurrence each: a customer's own duplicate survives.
        assert_eq!(
            super::strip_loopback_entries("localhost,localhost", &ours[1..]),
            "localhost"
        );
        assert_eq!(
            super::strip_loopback_entries("127.0.0.1,localhost", &ours),
            ""
        );
    }

    #[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}"
        );
    }

    /// #325 D4: a hook file install created is deleted once uninstall has
    /// emptied it; one that existed before is kept, even as `{}`; and a created
    /// file that picked up someone else's hook is kept with its record.
    #[test]
    fn uninstall_deletes_only_a_hook_file_it_created_and_emptied() {
        use crate::hooks::bindings::claude_code::ClaudeCodeBinding;

        // Same locks, same order, same seams as `env_channel_still_writes_the_env_block`.
        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());
        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();
        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()),
            ("OPENLATCH_SKIP_KEYRING", std::ffi::OsStr::new("1")),
        ]);
        let _cline_seams = crate::hooks::cline::EnvOverride::absent_cline_seams(cline_root.path());

        let binding_at = |name: &str| {
            let dir = claude.path().join(name);
            std::fs::create_dir_all(&dir).unwrap();
            ClaudeCodeBinding {
                settings_path: dir.join("settings.json"),
                claude_dir: dir,
            }
        };

        // Created by install, emptied by uninstall: gone, record and all.
        let created = binding_at("created");
        super::install_hooks(&created, 7443, "a-token").unwrap();
        assert!(super::created_hook_files::is_recorded(
            ol.path(),
            &created.settings_path
        ));
        remove_hooks(&created).unwrap();
        assert!(
            !created.settings_path.exists(),
            "we created it, and it is empty"
        );
        assert!(!super::created_hook_files::is_recorded(
            ol.path(),
            &created.settings_path
        ));

        // There before install, as `{}`: kept.
        let theirs = binding_at("theirs");
        std::fs::write(&theirs.settings_path, "{}").unwrap();
        super::install_hooks(&theirs, 7443, "a-token").unwrap();
        remove_hooks(&theirs).unwrap();
        assert_eq!(
            std::fs::read_to_string(&theirs.settings_path)
                .unwrap()
                .split_whitespace()
                .collect::<String>(),
            "{}",
            "a file that existed before us is never deleted"
        );

        // Created by install, then someone else's hook added: kept, record kept.
        let shared = binding_at("shared");
        super::install_hooks(&shared, 7443, "a-token").unwrap();
        let mut v = read_env(&shared.settings_path);
        v["hooks"]["Stop"]
            .as_array_mut()
            .expect("our Stop entry")
            .push(serde_json::json!({"hooks": [{"type": "command", "command": "sh other.sh"}]}));
        std::fs::write(&shared.settings_path, v.to_string()).unwrap();
        remove_hooks(&shared).unwrap();
        assert!(
            shared.settings_path.exists(),
            "a foreign hook keeps the file"
        );
        assert!(super::created_hook_files::is_recorded(
            ol.path(),
            &shared.settings_path
        ));
    }

    /// An install made by 0.5.7 or earlier wrote Claude Code's hooks as a
    /// quoted shell string, which PowerShell cannot parse. Re-running install
    /// (`init`, `doctor --fix`) must REPLACE each of those marked entries with
    /// the exec form — one entry per event, not the old one plus a new one —
    /// and leave the result healthy by the same predicate doctor uses.
    #[test]
    fn install_replaces_a_legacy_quoted_entry_with_exec_form() {
        use crate::hooks::binding::AgentBinding;
        use crate::hooks::bindings::claude_code::ClaudeCodeBinding;

        // The same locks, in the same order, as the test above.
        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());
        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();
        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()),
            ("OPENLATCH_SKIP_KEYRING", std::ffi::OsStr::new("1")),
        ]);
        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"),
        };

        // Every event as 0.5.7 wrote it: marked, and a quoted shell string.
        let mut hooks = serde_json::Map::new();
        for event in binding.hook_event_types() {
            let wire = crate::hooks::claude_code::pascal_to_snake(event);
            hooks.insert(
                (*event).to_string(),
                serde_json::json!([{
                    "_openlatch": { "v": 1, "id": format!("legacy-{event}") },
                    "hooks": [{
                        "type": "command",
                        "command": format!(
                            "\"{}\" --agent claude-code --event {wire}",
                            hook_bin.display()
                        ),
                        "timeout": 10
                    }]
                }]),
            );
        }
        let legacy = serde_json::json!({ "hooks": hooks });
        std::fs::write(&binding.settings_path, legacy.to_string()).unwrap();
        assert!(
            !crate::hooks::health::inspect(&legacy, &binding).is_healthy(),
            "the premise: doctor calls the legacy form unhealthy"
        );

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

        let v = read_env(&binding.settings_path);
        for event in binding.hook_event_types() {
            let entries = v["hooks"][event].as_array().unwrap();
            assert_eq!(entries.len(), 1, "{event} replaced, not duplicated: {v}");
            let hook = &entries[0]["hooks"][0];
            assert_eq!(hook["command"], hook_bin.display().to_string(), "{event}");
            assert_eq!(hook["args"][0], "--agent", "{event} is exec form: {hook}");
        }
        assert!(crate::hooks::health::inspect(&v, &binding).is_healthy());
    }

    /// 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 rows go with the entries (#325 A2): a row left behind is what the
    /// reconciler reads as "tracked but missing", and it reinstalls on the next
    /// daemon start what uninstall just removed. Another file's rows stay.
    #[test]
    fn remove_hooks_drops_the_state_rows_of_the_file_it_cleaned() {
        let _guard = crate::config::OPENLATCH_DIR_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let state_dir = tempfile::tempdir().unwrap();
        let prev = std::env::var_os("OPENLATCH_DIR");
        std::env::set_var("OPENLATCH_DIR", state_dir.path());

        let dir = tempfile::tempdir().unwrap();
        let agent = installed_settings(dir.path());
        let row = |id: &str, path: &std::path::Path| crate::core::hook_state::StateEntry {
            id: id.into(),
            agent: "claude-code".into(),
            settings_path_hash: crate::core::hook_state::hash_settings_path(path),
            hook_event: "Stop".into(),
            expected_entry_hmac: String::new(),
            daemon_port_at_install: 7443,
            daemon_token_fp: "fp".into(),
            descriptor: None,
            v: crate::core::hook_state::STATE_ENTRY_VERSION,
        };
        let mut state = crate::core::hook_state::HookStateFile::new("kid-01".into());
        state.upsert_entry(row("ours", &agent.settings_path()));
        state.upsert_entry(row("elsewhere", &dir.path().join("other.json")));
        state.save(state_dir.path()).unwrap();

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

        let left: Vec<String> = crate::core::hook_state::HookStateFile::load(state_dir.path())
            .unwrap()
            .unwrap()
            .entries
            .into_iter()
            .map(|e| e.id)
            .collect();
        match prev {
            Some(v) => std::env::set_var("OPENLATCH_DIR", v),
            None => std::env::remove_var("OPENLATCH_DIR"),
        }
        assert_eq!(left, ["elsewhere"]);
    }

    /// 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", "codex-cli"],
            "no --agent means every detected agent"
        );
        assert_eq!(
            types(super::select_agents(detected.clone(), &["codex-cli".to_string()]).unwrap()),
            vec!["codex-cli"],
            "a detected agent nobody named is skipped, silently"
        );
        assert_eq!(
            types(
                super::select_agents(
                    detected.clone(),
                    &["codex-cli".to_string(), "claude-code".to_string()],
                )
                .unwrap()
            ),
            vec!["claude-code", "codex-cli"],
            "detection order wins over flag order — it is load-bearing elsewhere"
        );

        // A schema-valid agent this host does not have. `cline` is in
        // SCHEMA_AGENT_TYPES and is not one of the two this fixture detects.
        let err = super::select_agents(detected.clone(), &["cline".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("cline"),
            "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 (#325 D4): install then uninstall on a `hooks.json`
    /// that did not exist deletes it, rather than leaving a `{}` nobody asked
    /// for.
    ///
    /// Only because install recorded creating it (`created_hook_files`):
    /// 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_deletes_the_file_it_created() {
        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");
            assert!(path.exists(), "install created it");
            super::remove_hooks(binding).expect("uninstall must succeed");

            assert!(!path.exists(), "we created it, and uninstall emptied it");
        });
    }

    // -----------------------------------------------------------------------
    // 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"
        );
    }

    // -----------------------------------------------------------------------
    // I-2 plan 02: the `ProxyEnv` convention's consumer arms
    // -----------------------------------------------------------------------

    /// The path every `SettingsKey` delivery in this section points at — inside the locked
    /// temp `OPENLATCH_DIR` (`with_openlatch_dir`), so a plain `fn` pointer (the shape
    /// `ProxyDelivery::SettingsKey` requires) needs no lock of its own.
    #[cfg(feature = "model-relay")]
    fn proxy_env_settings_path() -> std::path::PathBuf {
        crate::config::openlatch_dir()
            .join("fake-agent")
            .join("settings.json")
    }

    #[cfg(feature = "model-relay")]
    fn proxy_env_settings_file() -> Option<std::path::PathBuf> {
        Some(proxy_env_settings_path())
    }

    #[test]
    #[cfg(feature = "model-relay")]
    fn proxy_env_write_then_remove_round_trip() {
        use crate::hooks::binding::test_support::{proxy_env_wiring, FakeBinding};
        use crate::hooks::binding::ProxyDelivery;

        with_openlatch_dir(|| {
            let ol = crate::config::openlatch_dir();
            crate::model_relay::ca::LocalCa::load_or_generate(&crate::model_relay::ca::ca_dir(&ol))
                .expect("a CA");

            let settings_path = proxy_env_settings_path();
            std::fs::create_dir_all(settings_path.parent().unwrap()).unwrap();
            let seed = "{\n  \"a\": 1,\n}\n";
            std::fs::write(&settings_path, seed).unwrap();

            const DELIVERY: &[ProxyDelivery] = &[
                ProxyDelivery::SettingsKey {
                    file: proxy_env_settings_file,
                    key: "fake.proxy",
                },
                ProxyDelivery::EnvFile {
                    commands: &["fakecli"],
                    defaults: &[],
                },
            ];
            let agent = FakeBinding {
                agent_type: "fake-a",
                model_relay_wiring: Some(proxy_env_wiring(&["a.test"], DELIVERY)),
                ..Default::default()
            };

            write_model_relay_config(&agent, 7600, "agt_x").expect("write");
            let after_write = std::fs::read_to_string(&settings_path).unwrap();
            assert!(after_write.contains("fake.proxy"), "{after_write}");
            assert!(crate::hooks::proxy_env_file::env_sh_path(&ol).exists());
            assert!(crate::hooks::proxy_env_file::live_marker_path(&ol).exists());

            remove_model_relay_config(&agent).expect("remove");
            assert_eq!(std::fs::read_to_string(&settings_path).unwrap(), seed);
            assert!(!crate::hooks::proxy_env_file::env_sh_path(&ol).exists());
            assert!(!crate::hooks::proxy_env_file::env_ps1_path(&ol).exists());
            assert!(!crate::hooks::proxy_env_file::live_marker_path(&ol).exists());
        });
    }

    #[test]
    #[cfg(feature = "model-relay")]
    fn proxy_env_without_a_ca_writes_nothing() {
        use crate::hooks::binding::test_support::{proxy_env_wiring, FakeBinding};
        use crate::hooks::binding::ProxyDelivery;

        with_openlatch_dir(|| {
            let ol = crate::config::openlatch_dir();
            // Deliberately no CA generated: `crate::model_relay::ca::ca_dir(&ol)` is never
            // touched.
            const DELIVERY: &[ProxyDelivery] = &[
                ProxyDelivery::SettingsKey {
                    file: proxy_env_settings_file,
                    key: "fake.proxy",
                },
                ProxyDelivery::EnvFile {
                    commands: &["fakecli"],
                    defaults: &[],
                },
            ];
            let agent = FakeBinding {
                agent_type: "fake-a",
                model_relay_wiring: Some(proxy_env_wiring(&["a.test"], DELIVERY)),
                ..Default::default()
            };

            let err = write_model_relay_config(&agent, 7600, "agt_x").expect_err("no CA on disk");
            assert_eq!(err.code, crate::error::ERR_MODEL_RELAY_IO);
            assert!(!crate::hooks::proxy_env_file::env_sh_path(&ol).exists());
            assert!(!proxy_env_settings_path().exists());
        });
    }

    #[test]
    #[cfg(feature = "model-relay")]
    fn proxy_env_with_no_host_or_no_delivery_is_refused() {
        use crate::hooks::binding::test_support::FakeBinding;
        use crate::hooks::binding::{EndpointConvention, ModelRelayWiring, ProxyDelivery};

        with_openlatch_dir(|| {
            const NON_EMPTY_DELIVERY: &[ProxyDelivery] = &[ProxyDelivery::EnvFile {
                commands: &["fakecli"],
                defaults: &[],
            }];
            let no_host = FakeBinding {
                agent_type: "fake-a",
                model_relay_wiring: Some(ModelRelayWiring {
                    wire_format: crate::model_relay::wire_format::WireFormat::AnthropicMessages,
                    endpoint: EndpointConvention::ProxyEnv {
                        intercept_hosts: &[],
                        delivery: NON_EMPTY_DELIVERY,
                    },
                    install_id_header: "x-openlatch-install-id",
                }),
                ..Default::default()
            };
            let err =
                write_model_relay_config(&no_host, 7600, "agt_x").expect_err("no intercept host");
            assert_eq!(err.code, crate::error::ERR_MODEL_RELAY_IO);

            let no_delivery = FakeBinding {
                agent_type: "fake-a",
                model_relay_wiring: Some(ModelRelayWiring {
                    wire_format: crate::model_relay::wire_format::WireFormat::AnthropicMessages,
                    endpoint: EndpointConvention::ProxyEnv {
                        intercept_hosts: &["a.test"],
                        delivery: &[],
                    },
                    install_id_header: "x-openlatch-install-id",
                }),
                ..Default::default()
            };
            let err =
                write_model_relay_config(&no_delivery, 7600, "agt_x").expect_err("no delivery");
            assert_eq!(err.code, crate::error::ERR_MODEL_RELAY_IO);
        });
    }

    #[test]
    #[cfg(feature = "model-relay")]
    fn proxy_env_foreign_settings_key_leaves_the_wrapper_delivered() {
        use crate::hooks::binding::test_support::{proxy_env_wiring, FakeBinding};
        use crate::hooks::binding::ProxyDelivery;

        with_openlatch_dir(|| {
            let ol = crate::config::openlatch_dir();
            crate::model_relay::ca::LocalCa::load_or_generate(&crate::model_relay::ca::ca_dir(&ol))
                .expect("a CA");
            let settings_path = proxy_env_settings_path();
            std::fs::create_dir_all(settings_path.parent().unwrap()).unwrap();
            let foreign = "{\n  \"fake.proxy\": \"http://corp:3128\"\n}\n";
            std::fs::write(&settings_path, foreign).unwrap();

            // (a) A mixed delivery: the foreign key is skipped, the wrapper still lands, and
            // the overall result is Ok — deliveries are independent.
            const MIXED: &[ProxyDelivery] = &[
                ProxyDelivery::SettingsKey {
                    file: proxy_env_settings_file,
                    key: "fake.proxy",
                },
                ProxyDelivery::EnvFile {
                    commands: &["fakecli"],
                    defaults: &[],
                },
            ];
            let agent = FakeBinding {
                agent_type: "fake-a",
                model_relay_wiring: Some(proxy_env_wiring(&["a.test"], MIXED)),
                ..Default::default()
            };
            write_model_relay_config(&agent, 7600, "agt_x")
                .expect("a live EnvFile delivery must still succeed");
            assert_eq!(
                std::fs::read_to_string(&settings_path).unwrap(),
                foreign,
                "the foreign value must never be touched"
            );
            assert!(crate::hooks::proxy_env_file::env_sh_path(&ol).exists());
            remove_model_relay_config(&agent).expect("remove");

            // (b) A LONE SettingsKey, foreign: nothing was delivered, and the call fails with
            // the settings marker plan 04 matches, never naming the foreign value.
            const LONE: &[ProxyDelivery] = &[ProxyDelivery::SettingsKey {
                file: proxy_env_settings_file,
                key: "fake.proxy",
            }];
            let lone_agent = FakeBinding {
                agent_type: "fake-a",
                model_relay_wiring: Some(proxy_env_wiring(&["a.test"], LONE)),
                ..Default::default()
            };
            let err = write_model_relay_config(&lone_agent, 7600, "agt_x")
                .expect_err("everything skipped must fail");
            assert_eq!(err.code, crate::error::ERR_MODEL_RELAY_SETTINGS);
            assert!(err
                .message
                .starts_with(crate::model_relay::preflight::SETTINGS_REASON_MARKER));
            assert!(err
                .message
                .contains(crate::model_relay::preflight::SETTINGS_FOREIGN));
            assert!(!err.message.contains("corp:3128"), "{}", err.message);
        });
    }

    #[test]
    #[cfg(feature = "model-relay")]
    fn proxy_env_env_trust_only_writes_the_wrapper_and_never_the_settings_key() {
        use crate::hooks::binding::test_support::{proxy_env_wiring, FakeBinding};
        use crate::hooks::binding::ProxyDelivery;

        with_openlatch_dir(|| {
            let ol = crate::config::openlatch_dir();
            crate::model_relay::ca::LocalCa::load_or_generate(&crate::model_relay::ca::ca_dir(&ol))
                .expect("a CA");
            let settings_path = proxy_env_settings_path();
            std::fs::create_dir_all(settings_path.parent().unwrap()).unwrap();
            let seed = "{\n  \"a\": 1,\n}\n";
            std::fs::write(&settings_path, seed).unwrap();

            // (a) Mixed: the wrapper and its marker land; the settings file is byte-identical.
            const MIXED: &[ProxyDelivery] = &[
                ProxyDelivery::SettingsKey {
                    file: proxy_env_settings_file,
                    key: "fake.proxy",
                },
                ProxyDelivery::EnvFile {
                    commands: &["fakecli"],
                    defaults: &[],
                },
            ];
            let agent = FakeBinding {
                agent_type: "fake-a",
                model_relay_wiring: Some(proxy_env_wiring(&["a.test"], MIXED)),
                ..Default::default()
            };
            crate::hooks::write_model_relay_config_trusting(&agent, 7600, "agt_x", false)
                .expect("the env-trusted delivery must still succeed");
            assert_eq!(std::fs::read_to_string(&settings_path).unwrap(), seed);
            assert!(crate::hooks::proxy_env_file::env_sh_path(&ol).exists());
            assert!(crate::hooks::proxy_env_file::live_marker_path(&ol).exists());
            remove_model_relay_config(&agent).expect("remove");

            // (b) SettingsKey only: nothing deliverable, so the binding stays unwired.
            const LONE: &[ProxyDelivery] = &[ProxyDelivery::SettingsKey {
                file: proxy_env_settings_file,
                key: "fake.proxy",
            }];
            let lone_agent = FakeBinding {
                agent_type: "fake-a",
                model_relay_wiring: Some(proxy_env_wiring(&["a.test"], LONE)),
                ..Default::default()
            };
            let err =
                crate::hooks::write_model_relay_config_trusting(&lone_agent, 7600, "agt_x", false)
                    .expect_err("a store-only binding has nothing to deliver");
            assert!(err
                .message
                .starts_with(crate::model_relay::preflight::SETTINGS_REASON_MARKER));
            assert!(err
                .message
                .contains(crate::hooks::SETTINGS_KEY_ISOLATED_SKIP));
            assert_eq!(std::fs::read_to_string(&settings_path).unwrap(), seed);
        });
    }

    #[test]
    #[cfg(feature = "model-relay")]
    fn proxy_env_hint_and_config_path_speak_the_convention() {
        use crate::hooks::binding::test_support::{proxy_env_wiring, FakeBinding};
        use crate::hooks::binding::ProxyDelivery;

        with_openlatch_dir(|| {
            const DELIVERY: &[ProxyDelivery] = &[
                ProxyDelivery::SettingsKey {
                    file: proxy_env_settings_file,
                    key: "fake.proxy",
                },
                ProxyDelivery::EnvFile {
                    commands: &["fakecli"],
                    defaults: &[],
                },
            ];
            let agent = FakeBinding {
                agent_type: "fake-a",
                model_relay_wiring: Some(proxy_env_wiring(&["a.test"], DELIVERY)),
                ..Default::default()
            };

            let hint = crate::hooks::isolated_wiring_hint(&agent, 7600);
            assert!(hint.contains("HTTPS_PROXY=http://127.0.0.1:7600"), "{hint}");
            assert!(hint.contains("NODE_EXTRA_CA_CERTS="), "{hint}");

            let path = crate::hooks::model_relay_config_path(&agent).expect("a path");
            assert_eq!(path, proxy_env_settings_path(), "the first delivery's file");
        });
    }

    /// I-4 D-44 / D-40: `editor_proxy_written` reads the file; `declares_proxy_env` never does.
    #[test]
    #[cfg(feature = "model-relay")]
    fn editor_proxy_written_needs_our_value_in_a_settings_key() {
        use crate::hooks::binding::test_support::{proxy_env_wiring, FakeBinding};
        use crate::hooks::binding::{EndpointConvention, ModelRelayWiring, ProxyDelivery};
        use crate::hooks::model_relay_endpoints::ReleasedBy;
        use crate::model_relay::wire_format::WireFormat;

        fn fake_file() -> Option<std::path::PathBuf> {
            Some(
                crate::config::openlatch_dir()
                    .join("fake-editor")
                    .join("settings.json"),
            )
        }
        const DELIVERY: &[ProxyDelivery] = &[ProxyDelivery::SettingsKey {
            file: fake_file,
            key: "fake.proxy",
        }];

        with_openlatch_dir(|| {
            let proxy = FakeBinding {
                agent_type: "fake-a",
                model_relay_wiring: Some(proxy_env_wiring(&["a.test"], DELIVERY)),
                ..Default::default()
            };
            let env_vars = FakeBinding {
                agent_type: "fake-b",
                model_relay_wiring: Some(ModelRelayWiring {
                    wire_format: WireFormat::AnthropicMessages,
                    endpoint: EndpointConvention::EnvVars {
                        base_url: "FAKE_BASE_URL",
                        headers: "FAKE_HEADERS",
                    },
                    install_id_header: "x-openlatch-install-id",
                }),
                ..Default::default()
            };
            let none = FakeBinding::default();
            let path = fake_file().expect("path");

            assert!(!crate::hooks::editor_proxy_written(&proxy), "no file");
            assert!(crate::hooks::declares_proxy_env(&proxy));

            std::fs::create_dir_all(path.parent().expect("parent")).expect("mkdir");
            std::fs::write(&path, "{\"fake.proxy\": \"http://corp:3128\"}\n").expect("foreign");
            assert!(
                !crate::hooks::editor_proxy_written(&proxy),
                "a foreign value"
            );
            assert!(crate::hooks::declares_proxy_env(&proxy));

            std::fs::write(&path, "{}\n").expect("seed");
            crate::hooks::proxy_settings::write_proxy_key(
                &path,
                "fake.proxy",
                "http://127.0.0.1:7600",
                "fake-a",
            )
            .expect("write");
            assert!(crate::hooks::editor_proxy_written(&proxy), "our value");
            assert!(crate::hooks::declares_proxy_env(&proxy));

            crate::hooks::proxy_settings::release_proxy_key(
                &path,
                "fake.proxy",
                "fake-a",
                ReleasedBy::Teardown,
            )
            .expect("release");
            assert!(!crate::hooks::editor_proxy_written(&proxy), "released");
            assert!(crate::hooks::declares_proxy_env(&proxy));

            assert!(!crate::hooks::editor_proxy_written(&env_vars));
            assert!(!crate::hooks::declares_proxy_env(&env_vars));
            assert!(!crate::hooks::declares_proxy_env(&none));
        });
    }

    // -----------------------------------------------------------------------
    // Cursor: the sidecar marker, the root defaults and byte-identical restore
    // -----------------------------------------------------------------------

    /// The seeded file of the plan's acceptance block: one developer hook on
    /// `stop`, `version` AFTER `hooks`, a trailing newline.
    const CURSOR_SEED: &str =
        "{\"hooks\":{\"stop\":[{\"command\":\"echo mine\"}]},\"version\":1}\n";

    fn ours_on(v: &serde_json::Value, event: &str) -> usize {
        v["hooks"][event].as_array().map_or(0, |entries| {
            entries
                .iter()
                .filter(|e| crate::hooks::entry_shape::is_sidecar_owned_entry(e, "cursor"))
                .count()
        })
    }

    #[test]
    fn cursor_install_writes_version_and_record_only_events() {
        super::with_cursor_install_env(|binding, ol| {
            crate::hooks::install_hooks(binding, 7443, "a-token").expect("install");
            let raw = std::fs::read_to_string(&binding.hooks_path).unwrap();
            assert!(!raw.contains("_openlatch"), "no marker anywhere: {raw}");
            assert!(!raw.contains("matcher"), "no matcher anywhere: {raw}");
            assert!(
                !raw.contains("a-token"),
                "no token value in the file: {raw}"
            );

            let v: serde_json::Value = serde_json::from_str(&raw).unwrap();
            let mut keys: Vec<&String> = v.as_object().unwrap().keys().collect();
            keys.sort();
            assert_eq!(keys, ["hooks", "version"], "{raw}");
            assert_eq!(v["version"], 1);
            // Read on the raw text: `serde_json::Map` sorts its keys.
            assert!(
                raw.find("\"version\"") < raw.find("\"hooks\""),
                "version first, then hooks: {raw}"
            );

            let mut events: Vec<&String> = v["hooks"].as_object().unwrap().keys().collect();
            events.sort();
            assert_eq!(
                events,
                [
                    "postToolUse",
                    "postToolUseFailure",
                    "preCompact",
                    "sessionEnd",
                    "sessionStart",
                    "stop",
                    "subagentStop"
                ]
            );
            for deciding in [
                "preToolUse",
                "beforeShellExecution",
                "beforeMCPExecution",
                "beforeSubmitPrompt",
            ] {
                assert!(
                    v["hooks"].get(deciding).is_none(),
                    "{deciding} installed early"
                );
            }
            for event in &events {
                assert_eq!(ours_on(&v, event), 1, "{event}: {raw}");
            }

            // The HMAC lives in the state row, over the entry as written.
            let state = crate::core::hook_state::HookStateFile::load(ol)
                .unwrap()
                .unwrap();
            let key = crate::core::hook_state::key::HmacKeyStore::new(ol)
                .load_or_create()
                .unwrap();
            let rows: Vec<_> = state
                .entries
                .iter()
                .filter(|e| e.agent == "cursor")
                .collect();
            assert_eq!(rows.len(), 7);
            for row in rows {
                let entry = &v["hooks"][&row.hook_event][0];
                assert_eq!(
                    crate::core::hook_state::hmac::compute_entry_hmac(entry, &key).unwrap(),
                    row.expected_entry_hmac,
                    "{}",
                    row.hook_event
                );
            }
        });
    }

    #[test]
    fn cursor_reinstall_replaces_not_duplicates() {
        super::with_cursor_install_env(|binding, _| {
            std::fs::write(&binding.hooks_path, CURSOR_SEED).unwrap();
            crate::hooks::install_hooks(binding, 7443, "a-token").expect("install");
            crate::hooks::install_hooks(binding, 7443, "a-token").expect("reinstall");
            let v = read_env(&binding.hooks_path);
            for event in v["hooks"].as_object().unwrap().keys() {
                assert_eq!(ours_on(&v, event), 1, "{event} duplicated: {v}");
            }
            let stop = v["hooks"]["stop"].as_array().unwrap();
            assert_eq!(
                stop[0]["command"], "echo mine",
                "the developer's hook keeps index 0"
            );
            assert_eq!(stop.len(), 2);
        });
    }

    #[test]
    fn cursor_uninstall_is_byte_identical_seeded() {
        super::with_cursor_install_env(|binding, _| {
            std::fs::write(&binding.hooks_path, CURSOR_SEED).unwrap();
            crate::hooks::install_hooks(binding, 7443, "a-token").expect("install");
            assert_ne!(
                std::fs::read_to_string(&binding.hooks_path).unwrap(),
                CURSOR_SEED
            );

            crate::hooks::remove_hooks(binding).expect("uninstall");
            assert_eq!(
                std::fs::read(&binding.hooks_path).unwrap(),
                CURSOR_SEED.as_bytes(),
                "byte for byte"
            );
        });
    }

    #[test]
    fn cursor_uninstall_is_byte_identical_unseeded_deletes() {
        super::with_cursor_install_env(|binding, ol| {
            crate::hooks::install_hooks(binding, 7443, "a-token").expect("install");
            assert!(crate::hooks::created_hook_files::is_recorded(
                ol,
                &binding.hooks_path
            ));
            crate::hooks::remove_hooks(binding).expect("uninstall");
            assert!(!binding.hooks_path.exists(), "a file we created is gone");
            assert!(!crate::hooks::created_hook_files::is_recorded(
                ol,
                &binding.hooks_path
            ));
            let state = crate::core::hook_state::HookStateFile::load(ol)
                .unwrap()
                .unwrap();
            assert!(
                state.entries.iter().all(|e| e.agent != "cursor"),
                "rows forgotten"
            );
        });
    }

    #[test]
    fn cursor_uninstall_is_byte_identical_user_edit_falls_back_to_cst() {
        super::with_cursor_install_env(|binding, _| {
            std::fs::write(&binding.hooks_path, CURSOR_SEED).unwrap();
            crate::hooks::install_hooks(binding, 7443, "a-token").expect("install");
            // The developer adds a hook of their own after ours.
            let mut v = read_env(&binding.hooks_path);
            v["hooks"]["sessionEnd"]
                .as_array_mut()
                .unwrap()
                .push(serde_json::json!({"command": "echo bye"}));
            std::fs::write(&binding.hooks_path, v.to_string()).unwrap();

            crate::hooks::remove_hooks(binding).expect("uninstall");
            let after = read_env(&binding.hooks_path);
            let events: Vec<&String> = after["hooks"].as_object().unwrap().keys().collect();
            assert_eq!(events, ["sessionEnd", "stop"], "only ours went: {after}");
            assert_eq!(after["hooks"]["sessionEnd"][0]["command"], "echo bye");
            assert_eq!(after["hooks"]["stop"][0]["command"], "echo mine");
            assert_eq!(after["version"], 1);
        });
    }

    /// A later OpenLatch write (a re-run of `init`, `doctor --fix`, a heal) over
    /// a user edit must never bless it: uninstall restores the edit, not the
    /// bytes from before the first install.
    #[test]
    fn install_edit_heal_uninstall_keeps_the_edit() {
        super::with_cursor_install_env(|binding, _| {
            std::fs::write(&binding.hooks_path, CURSOR_SEED).unwrap();
            crate::hooks::install_hooks(binding, 7443, "a-token").expect("install");

            let mut v = read_env(&binding.hooks_path);
            v["hooks"]["stop"][0]["command"] = serde_json::json!("echo edited");
            std::fs::write(&binding.hooks_path, v.to_string()).unwrap();
            let edited = std::fs::read_to_string(&binding.hooks_path).unwrap();

            crate::hooks::install_hooks(binding, 7443, "a-token").expect("heal");
            crate::hooks::remove_hooks(binding).expect("uninstall");

            assert_eq!(
                std::fs::read_to_string(&binding.hooks_path).unwrap(),
                edited
            );
        });
    }

    #[test]
    fn restore_path_forgets_the_created_record() {
        super::with_cursor_install_env(|binding, ol| {
            crate::hooks::install_hooks(binding, 7443, "a-token").expect("install");
            crate::hooks::remove_hooks(binding).expect("uninstall");
            assert!(!binding.hooks_path.exists());

            // The developer creates an empty file of their own afterwards.
            let theirs = "{\"version\":1,\"hooks\":{}}";
            std::fs::write(&binding.hooks_path, theirs).unwrap();
            assert!(!crate::hooks::created_hook_files::is_recorded(
                ol,
                &binding.hooks_path
            ));
            crate::hooks::remove_hooks(binding).expect("second uninstall");
            assert_eq!(
                std::fs::read_to_string(&binding.hooks_path).unwrap(),
                theirs,
                "a file we did not create survives"
            );
        });
    }

    #[test]
    fn a_user_wrapper_mentioning_openlatch_hook_is_never_claimed() {
        super::with_cursor_install_env(|binding, _| {
            let seed = r#"{"version":1,"hooks":{"stop":[{"command":"my-wrapper --then openlatch-hook"},{"command":"\"/x/openlatch-hook\" --agent codex-cli --event stop"}]}}"#;
            std::fs::write(&binding.hooks_path, seed).unwrap();
            crate::hooks::install_hooks(binding, 7443, "a-token").expect("install");

            let v = read_env(&binding.hooks_path);
            let stop = v["hooks"]["stop"].as_array().unwrap();
            assert_eq!(
                stop.len(),
                3,
                "both foreign entries kept, ours appended: {v}"
            );
            assert_eq!(stop[0]["command"], "my-wrapper --then openlatch-hook");

            // Uninstall (a user edit falls to CST removal) removes ours alone.
            let mut edited = v.clone();
            edited["hooks"]["sessionEnd"]
                .as_array_mut()
                .unwrap()
                .push(serde_json::json!({"command": "echo edit"}));
            std::fs::write(&binding.hooks_path, edited.to_string()).unwrap();
            crate::hooks::remove_hooks(binding).expect("uninstall");
            let after = read_env(&binding.hooks_path);
            let stop = after["hooks"]["stop"].as_array().unwrap();
            assert_eq!(stop.len(), 2, "{after}");
            assert_eq!(stop[0]["command"], "my-wrapper --then openlatch-hook");
        });
    }

    #[test]
    fn a_non_1_version_is_refused() {
        super::with_cursor_install_env(|binding, _| {
            let seed = "{\"version\":2,\"hooks\":{}}";
            std::fs::write(&binding.hooks_path, seed).unwrap();
            let err = crate::hooks::install_hooks(binding, 7443, "a-token")
                .expect_err("version 2 is refused");
            assert_eq!(err.code, crate::error::ERR_CURSOR_HOOK_FILE_MALFORMED);
            assert_eq!(std::fs::read_to_string(&binding.hooks_path).unwrap(), seed);

            std::fs::write(&binding.hooks_path, "{ not json").unwrap();
            assert!(
                crate::hooks::install_hooks(binding, 7443, "a-token").is_err(),
                "unparseable is refused"
            );
            assert_eq!(
                std::fs::read_to_string(&binding.hooks_path).unwrap(),
                "{ not json"
            );

            // The refusals left no snapshot: the developer fixes the file, and
            // uninstall restores THAT, not the refused bytes.
            let fixed = "{\"version\":1,\"hooks\":{\"stop\":[{\"command\":\"echo mine\"}]}}\n";
            std::fs::write(&binding.hooks_path, fixed).unwrap();
            crate::hooks::install_hooks(binding, 7443, "a-token").expect("install");
            crate::hooks::remove_hooks(binding).expect("uninstall");
            assert_eq!(std::fs::read_to_string(&binding.hooks_path).unwrap(), fixed);
        });
    }

    /// Shared-code regression: the byte output of an install into seeded Claude
    /// Code and Codex CLI files, with per-install values (marker id, timestamp,
    /// HMAC) and temp paths masked, pinned against the bytes the code produced
    /// BEFORE the sidecar, root defaults and byte-identical restore existed.
    #[cfg(unix)]
    #[test]
    fn claude_and_codex_install_bytes_unchanged() {
        use crate::hooks::bindings::claude_code::ClaudeCodeBinding;
        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 ol = tempfile::tempdir().unwrap();
        let agents = 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 _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 claude_dir = agents.path().join("claude");
        let codex_dir = agents.path().join("codex");
        std::fs::create_dir_all(&claude_dir).unwrap();
        std::fs::create_dir_all(&codex_dir).unwrap();
        let claude = ClaudeCodeBinding {
            claude_dir: claude_dir.clone(),
            settings_path: claude_dir.join("settings.json"),
        };
        let codex = CodexCliBinding {
            codex_dir: codex_dir.clone(),
            hooks_path: codex_dir.join("hooks.json"),
            requirements_toml: None,
            hooks_list: std::sync::Arc::new(|_| None),
        };
        std::fs::write(
            &claude.settings_path,
            "{\n  // mine\n  \"hooks\": {\"Stop\": [{\"matcher\": \"\", \"hooks\": [{\"type\": \"command\", \"command\": \"echo mine\"}]}]}\n}\n",
        )
        .unwrap();
        std::fs::write(&codex.hooks_path, CUSTOMER_GROUP).unwrap();

        crate::hooks::install_hooks(&claude, 7443, "a-token").unwrap();
        crate::hooks::install_hooks(&codex, 7443, "a-token").unwrap();

        let mask = |path: &std::path::Path| -> String {
            let mut text = std::fs::read_to_string(path).unwrap();
            let v = crate::hooks::jsonc::parse_settings_value(&text).unwrap();
            let mut dynamic: Vec<String> = Vec::new();
            for entries in v["hooks"].as_object().unwrap().values() {
                for entry in entries.as_array().unwrap() {
                    for key in ["id", "installed_at", "hmac"] {
                        if let Some(value) = entry["_openlatch"][key].as_str() {
                            dynamic.push(value.to_string());
                        }
                    }
                }
            }
            for value in dynamic {
                text = text.replace(&value, "<DYN>");
            }
            text.replace(&hook_bin.display().to_string(), "<BIN>")
                .replace(&ol.path().display().to_string(), "<OL>")
        };
        let claude_bytes = mask(&claude.settings_path);
        let codex_bytes = mask(&codex.hooks_path);

        assert_eq!(
            claude_bytes, EXPECTED_CLAUDE_BYTES,
            "Claude Code bytes moved"
        );
        assert_eq!(codex_bytes, EXPECTED_CODEX_BYTES, "Codex CLI bytes moved");
    }

    /// Captured from `main` at d9d59d3, before this change, with the masking above.
    #[cfg(unix)] // its only reader, `claude_and_codex_install_bytes_unchanged`, is Unix-only
    const EXPECTED_CLAUDE_BYTES: &str = r####"{
  // mine
  "hooks": {
    "Stop": [{"matcher": "", "hooks": [{"type": "command", "command": "echo mine"}]},
      {
        "_openlatch": {
          "hmac": "<DYN>",
          "id": "<DYN>",
          "installed_at": "<DYN>",
          "v": 1
        },
        "hooks": [
          {
            "allowedEnvVars": ["OPENLATCH_TOKEN", "OPENLATCH_PORT"],
            "args": ["--agent", "claude-code", "--event", "stop"],
            "command": "<BIN>",
            "timeout": 10,
            "type": "command"
          }
        ]
      }],
    "PreToolUse": [
      {
        "_openlatch": {
          "hmac": "<DYN>",
          "id": "<DYN>",
          "installed_at": "<DYN>",
          "v": 1
        },
        "hooks": [
          {
            "allowedEnvVars": ["OPENLATCH_TOKEN", "OPENLATCH_PORT"],
            "args": ["--agent", "claude-code", "--event", "pre_tool_use"],
            "command": "<BIN>",
            "timeout": 900,
            "type": "command"
          }
        ],
        "matcher": ""
      }
    ],
    "PostToolUse": [
      {
        "_openlatch": {
          "hmac": "<DYN>",
          "id": "<DYN>",
          "installed_at": "<DYN>",
          "v": 1
        },
        "hooks": [
          {
            "allowedEnvVars": ["OPENLATCH_TOKEN", "OPENLATCH_PORT"],
            "args": ["--agent", "claude-code", "--event", "post_tool_use"],
            "command": "<BIN>",
            "timeout": 10,
            "type": "command"
          }
        ]
      }
    ],
    "PostToolUseFailure": [
      {
        "_openlatch": {
          "hmac": "<DYN>",
          "id": "<DYN>",
          "installed_at": "<DYN>",
          "v": 1
        },
        "hooks": [
          {
            "allowedEnvVars": ["OPENLATCH_TOKEN", "OPENLATCH_PORT"],
            "args": ["--agent", "claude-code", "--event", "post_tool_use_failure"],
            "command": "<BIN>",
            "timeout": 10,
            "type": "command"
          }
        ]
      }
    ],
    "UserPromptSubmit": [
      {
        "_openlatch": {
          "hmac": "<DYN>",
          "id": "<DYN>",
          "installed_at": "<DYN>",
          "v": 1
        },
        "hooks": [
          {
            "allowedEnvVars": ["OPENLATCH_TOKEN", "OPENLATCH_PORT"],
            "args": ["--agent", "claude-code", "--event", "user_prompt_submit"],
            "command": "<BIN>",
            "timeout": 10,
            "type": "command"
          }
        ]
      }
    ],
    "Notification": [
      {
        "_openlatch": {
          "hmac": "<DYN>",
          "id": "<DYN>",
          "installed_at": "<DYN>",
          "v": 1
        },
        "hooks": [
          {
            "allowedEnvVars": ["OPENLATCH_TOKEN", "OPENLATCH_PORT"],
            "args": ["--agent", "claude-code", "--event", "notification"],
            "command": "<BIN>",
            "timeout": 10,
            "type": "command"
          }
        ]
      }
    ],
    "SubagentStop": [
      {
        "_openlatch": {
          "hmac": "<DYN>",
          "id": "<DYN>",
          "installed_at": "<DYN>",
          "v": 1
        },
        "hooks": [
          {
            "allowedEnvVars": ["OPENLATCH_TOKEN", "OPENLATCH_PORT"],
            "args": ["--agent", "claude-code", "--event", "subagent_stop"],
            "command": "<BIN>",
            "timeout": 10,
            "type": "command"
          }
        ]
      }
    ],
    "PreCompact": [
      {
        "_openlatch": {
          "hmac": "<DYN>",
          "id": "<DYN>",
          "installed_at": "<DYN>",
          "v": 1
        },
        "hooks": [
          {
            "allowedEnvVars": ["OPENLATCH_TOKEN", "OPENLATCH_PORT"],
            "args": ["--agent", "claude-code", "--event", "pre_compact"],
            "command": "<BIN>",
            "timeout": 10,
            "type": "command"
          }
        ]
      }
    ],
    "SessionStart": [
      {
        "_openlatch": {
          "hmac": "<DYN>",
          "id": "<DYN>",
          "installed_at": "<DYN>",
          "v": 1
        },
        "hooks": [
          {
            "allowedEnvVars": ["OPENLATCH_TOKEN", "OPENLATCH_PORT"],
            "args": ["--agent", "claude-code", "--event", "session_start"],
            "command": "<BIN>",
            "timeout": 10,
            "type": "command"
          }
        ]
      }
    ],
    "SessionEnd": [
      {
        "_openlatch": {
          "hmac": "<DYN>",
          "id": "<DYN>",
          "installed_at": "<DYN>",
          "v": 1
        },
        "hooks": [
          {
            "allowedEnvVars": ["OPENLATCH_TOKEN", "OPENLATCH_PORT"],
            "args": ["--agent", "claude-code", "--event", "session_end"],
            "command": "<BIN>",
            "timeout": 10,
            "type": "command"
          }
        ]
      }
    ],
    "ConfigChange": [
      {
        "_openlatch": {
          "hmac": "<DYN>",
          "id": "<DYN>",
          "installed_at": "<DYN>",
          "v": 1
        },
        "hooks": [
          {
            "allowedEnvVars": ["OPENLATCH_TOKEN", "OPENLATCH_PORT"],
            "args": ["--agent", "claude-code", "--event", "config_change"],
            "command": "<BIN>",
            "timeout": 10,
            "type": "command"
          }
        ]
      }
    ],
    "InstructionsLoaded": [
      {
        "_openlatch": {
          "hmac": "<DYN>",
          "id": "<DYN>",
          "installed_at": "<DYN>",
          "v": 1
        },
        "hooks": [
          {
            "allowedEnvVars": ["OPENLATCH_TOKEN", "OPENLATCH_PORT"],
            "args": ["--agent", "claude-code", "--event", "instructions_loaded"],
            "command": "<BIN>",
            "timeout": 10,
            "type": "command"
          }
        ]
      }
    ],
    "FileChanged": [
      {
        "_openlatch": {
          "hmac": "<DYN>",
          "id": "<DYN>",
          "installed_at": "<DYN>",
          "v": 1
        },
        "hooks": [
          {
            "allowedEnvVars": ["OPENLATCH_TOKEN", "OPENLATCH_PORT"],
            "args": ["--agent", "claude-code", "--event", "file_changed"],
            "command": "<BIN>",
            "timeout": 10,
            "type": "command"
          }
        ]
      }
    ]
  },
  "env": {
    "OPENLATCH_TOKEN": "a-token",
    "OPENLATCH_PORT": "7443"
  }
}
"####;

    /// Captured from `main` at d9d59d3, before this change, with the masking above.
    #[cfg(unix)] // its only reader, `claude_and_codex_install_bytes_unchanged`, is Unix-only
    const EXPECTED_CODEX_BYTES: &str = r####"{"hooks":{
    "PostToolUse":[{"matcher":"","hooks":[{"type":"command","command":"echo mine","timeout":5}]},
      {
        "_openlatch": {
          "hmac": "<DYN>",
          "id": "<DYN>",
          "installed_at": "<DYN>",
          "v": 1
        },
        "hooks": [
          {
            "command": "\"<BIN>\" --agent codex-cli --event post_tool_use --openlatch-dir \"<OL>\"",
            "timeout": 10,
            "type": "command"
          }
        ],
        "matcher": ""
      }],
    "PreToolUse": [
      {
        "_openlatch": {
          "hmac": "<DYN>",
          "id": "<DYN>",
          "installed_at": "<DYN>",
          "v": 1
        },
        "hooks": [
          {
            "command": "\"<BIN>\" --agent codex-cli --event pre_tool_use --openlatch-dir \"<OL>\"",
            "timeout": 900,
            "type": "command"
          }
        ],
        "matcher": "Bash"
      }
    ],
    "PermissionRequest": [
      {
        "_openlatch": {
          "hmac": "<DYN>",
          "id": "<DYN>",
          "installed_at": "<DYN>",
          "v": 1
        },
        "hooks": [
          {
            "command": "\"<BIN>\" --agent codex-cli --event permission_request --openlatch-dir \"<OL>\"",
            "timeout": 10,
            "type": "command"
          }
        ],
        "matcher": ""
      }
    ],
    "UserPromptSubmit": [
      {
        "_openlatch": {
          "hmac": "<DYN>",
          "id": "<DYN>",
          "installed_at": "<DYN>",
          "v": 1
        },
        "hooks": [
          {
            "command": "\"<BIN>\" --agent codex-cli --event user_prompt_submit --openlatch-dir \"<OL>\"",
            "timeout": 10,
            "type": "command"
          }
        ],
        "matcher": ""
      }
    ],
    "SessionStart": [
      {
        "_openlatch": {
          "hmac": "<DYN>",
          "id": "<DYN>",
          "installed_at": "<DYN>",
          "v": 1
        },
        "hooks": [
          {
            "command": "\"<BIN>\" --agent codex-cli --event session_start --openlatch-dir \"<OL>\"",
            "timeout": 10,
            "type": "command"
          }
        ],
        "matcher": ""
      }
    ],
    "SessionEnd": [
      {
        "_openlatch": {
          "hmac": "<DYN>",
          "id": "<DYN>",
          "installed_at": "<DYN>",
          "v": 1
        },
        "hooks": [
          {
            "command": "\"<BIN>\" --agent codex-cli --event session_end --openlatch-dir \"<OL>\"",
            "timeout": 3,
            "type": "command"
          }
        ],
        "matcher": ""
      }
    ],
    "PreCompact": [
      {
        "_openlatch": {
          "hmac": "<DYN>",
          "id": "<DYN>",
          "installed_at": "<DYN>",
          "v": 1
        },
        "hooks": [
          {
            "command": "\"<BIN>\" --agent codex-cli --event pre_compact --openlatch-dir \"<OL>\"",
            "timeout": 10,
            "type": "command"
          }
        ],
        "matcher": ""
      }
    ],
    "PostCompact": [
      {
        "_openlatch": {
          "hmac": "<DYN>",
          "id": "<DYN>",
          "installed_at": "<DYN>",
          "v": 1
        },
        "hooks": [
          {
            "command": "\"<BIN>\" --agent codex-cli --event post_compact --openlatch-dir \"<OL>\"",
            "timeout": 10,
            "type": "command"
          }
        ],
        "matcher": ""
      }
    ],
    "Stop": [
      {
        "_openlatch": {
          "hmac": "<DYN>",
          "id": "<DYN>",
          "installed_at": "<DYN>",
          "v": 1
        },
        "hooks": [
          {
            "command": "\"<BIN>\" --agent codex-cli --event stop --openlatch-dir \"<OL>\"",
            "timeout": 10,
            "type": "command"
          }
        ],
        "matcher": ""
      }
    ],
    "SubagentStop": [
      {
        "_openlatch": {
          "hmac": "<DYN>",
          "id": "<DYN>",
          "installed_at": "<DYN>",
          "v": 1
        },
        "hooks": [
          {
            "command": "\"<BIN>\" --agent codex-cli --event subagent_stop --openlatch-dir \"<OL>\"",
            "timeout": 10,
            "type": "command"
          }
        ],
        "matcher": ""
      }
    ],
    "SubagentStart": [
      {
        "_openlatch": {
          "hmac": "<DYN>",
          "id": "<DYN>",
          "installed_at": "<DYN>",
          "v": 1
        },
        "hooks": [
          {
            "command": "\"<BIN>\" --agent codex-cli --event subagent_start --openlatch-dir \"<OL>\"",
            "timeout": 10,
            "type": "command"
          }
        ],
        "matcher": ""
      }
    ],
    "Interrupt": [
      {
        "_openlatch": {
          "hmac": "<DYN>",
          "id": "<DYN>",
          "installed_at": "<DYN>",
          "v": 1
        },
        "hooks": [
          {
            "command": "\"<BIN>\" --agent codex-cli --event interrupt --openlatch-dir \"<OL>\"",
            "timeout": 3,
            "type": "command"
          }
        ],
        "matcher": ""
      }
    ]
  }}"####;
}