openlatch-client 0.3.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
/// Configuration loading for OpenLatch daemon.
///
/// Implements the full precedence chain per CONF-03:
/// CLI flags > env vars (`OPENLATCH_*`) > `~/.openlatch/config.toml` > defaults
///
/// The default config file uses a commented-template style (D-10) with only the
/// pinned port written as an active value (D-11).
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use serde::Deserialize;

use crate::boundary::wire_format::WireFormat;
use crate::error::{OlError, ERR_INVALID_CONFIG, ERR_PORT_IN_USE};

// ---------------------------------------------------------------------------
// Update check configuration
// ---------------------------------------------------------------------------

/// Configuration for the version update check + auto-update path.
///
/// Override via env vars:
/// - `OPENLATCH_UPDATE_CHECK=false` disables the startup check.
/// - `OPENLATCH_NPM_REGISTRY=https://...` overrides the registry origin
///   (used by the E2E orchestrator's fake-registry server; the default
///   points at the public npm registry).
/// - `OPENLATCH_UPDATE_DOWNLOAD_TIMEOUT_SECS` overrides the per-tarball
///   download timeout.
#[derive(Debug, Clone)]
pub struct UpdateConfig {
    /// Whether to check for a newer version on daemon start. Default: true.
    pub check: bool,
    /// Origin of the npm registry — manifest + tarball both fetched from
    /// here. Default: `https://registry.npmjs.org`.
    pub registry_origin: String,
    /// Per-request HTTP timeout when downloading the platform tarball.
    /// Default: 60 seconds (tarballs are ~5–10 MB).
    pub download_timeout_secs: u64,
    /// Whether the background auto-update worker is enabled. Default
    /// `true` — silent auto-update is the baseline; users opt out by
    /// setting this to `false` in `~/.openlatch/config.toml` or via
    /// `OPENLATCH_AUTO_UPDATE=false`.
    pub auto_update: bool,
    /// How often the auto-update worker polls the registry. Default 6 h.
    /// Override via `OPENLATCH_UPDATE_CHECK_INTERVAL_SECS` for E2E tests.
    pub check_interval_secs: u64,
    /// Quiet-window length: a non-critical update is deferred until at
    /// least N seconds have elapsed since the last hook AND no hook is
    /// in flight. Critical-severity updates bypass this gate. Default
    /// 60 s. Override via `OPENLATCH_UPDATE_QUIET_WINDOW_SECS`.
    pub quiet_window_secs: u64,
    /// Hard cap on cumulative deferral. Once an update has been pending
    /// for this long, the worker applies it regardless of activity.
    /// Default 24 h. Override via `OPENLATCH_UPDATE_MAX_DEFER_SECS`.
    pub max_defer_secs: u64,
}

impl Default for UpdateConfig {
    fn default() -> Self {
        Self {
            check: true,
            registry_origin: "https://registry.npmjs.org".into(),
            download_timeout_secs: 60,
            // Auto-update is on by default. The deferral logic
            // (quiet window + in-flight check) protects active sessions
            // from being interrupted; the supervisor-restart-loop
            // rollback catches a bad release. CI environments and
            // `cargo install`-managed binaries are auto-detected and
            // skip the worker.
            auto_update: true,
            check_interval_secs: 6 * 60 * 60,
            // 60 s of hook silence before a non-critical apply fires.
            // Critical-severity updates bypass deferral.
            quiet_window_secs: 60,
            max_defer_secs: 24 * 60 * 60,
        }
    }
}

// ---------------------------------------------------------------------------
// Cloud forwarding configuration (D-12)
// ---------------------------------------------------------------------------

/// Runtime-resolved configuration for cloud event forwarding.
///
/// Populated from the `[cloud]` section in `config.toml` with env var overrides:
/// - `OPENLATCH_CLOUD_ENABLED` — overrides `enabled`
/// - `OPENLATCH_API_URL` — overrides `api_url`
///
/// `OPENLATCH_API_KEY` is NOT handled here — it is a credential managed by
/// `CredentialStore` in `src/core/auth/`.
#[derive(Debug, Clone)]
pub struct CloudConfig {
    /// Always `true`. Retained as a field so the shape of `Config` is stable
    /// for the handful of call sites that read it, but nothing sets it to
    /// `false` any more.
    ///
    /// **Forwarding is not optional.** A client that captures events and sends
    /// them nowhere is a log rotator; the platform is the product. The switch
    /// existed, defaulted to on, and was documented here as "Default: false"
    /// while the `Default` impl said `true` and a test asserted `true` — three
    /// sources, two answers, for a flag whose only real use was silently
    /// disarming a host.
    ///
    /// `[cloud] enabled` and `OPENLATCH_CLOUD_ENABLED` are still *parsed*, so
    /// no existing `config.toml` stops loading; a `false` is logged once and
    /// ignored. To stop talking to a platform, point `[cloud] api_url`
    /// somewhere else — the parameters of forwarding stay entirely
    /// configurable, only its existence does not.
    pub enabled: bool,
    /// Cloud API base URL. Default: "https://app.openlatch.ai".
    ///
    /// Callers prepend their own `/api/v1/...` path segments, so this value is
    /// the bare origin (or, in dev setups, the Vite dev server origin). The
    /// prior default mistakenly included `/api`, which produced a duplicated
    /// `/api/api/v1/...` path and caused every request to 404.
    pub api_url: String,
    /// TCP connect timeout in milliseconds. Default: 5000.
    pub timeout_connect_ms: u64,
    /// Total request timeout in milliseconds. Default: 10000.
    pub timeout_total_ms: u64,
    /// Delay before the single retry on network error or 5xx, in milliseconds.
    /// Default: 2000.
    pub retry_delay_ms: u64,
    /// Bounded channel size for async event forwarding. Default: 1000.
    pub channel_size: usize,
    /// How often the cloud worker re-reads the credential from the provider,
    /// in milliseconds. Default: 60_000 (60 s). E2E tests override this via
    /// `OPENLATCH_CLOUD_CREDENTIAL_POLL_MS` so the hot-reload path is
    /// observable without a real-time 60 s wait.
    pub credential_poll_interval_ms: u64,
    /// Whether to spool failed POSTs to a durable outbox and replay them
    /// when the cloud is reachable again. Default: true. Disable via
    /// `OPENLATCH_CLOUD_OUTBOX_ENABLED=false` if the environment cannot
    /// afford the additional disk I/O. Events are still logged locally to
    /// the audit JSONL whether the outbox is enabled or not.
    pub outbox_enabled: bool,
    /// Maximum size of `~/.openlatch/outbox.jsonl` before drop-oldest eviction
    /// kicks in. Default: 104_857_600 (100 MB). Setting to 0 disables the
    /// cap entirely (NOT recommended — can fill the partition during a
    /// prolonged outage).
    pub outbox_max_bytes: u64,
    /// Maximum size of the **unreplayed window** of
    /// `~/.openlatch/logs/fallback.jsonl` — not of the file. Default:
    /// 52_428_800 (50 MB). Setting to 0 disables the cap entirely.
    ///
    /// Drop-oldest is implemented by advancing the persisted read offset, never
    /// by rewriting the file, so the evicted prefix stays on disk. It is
    /// reclaimed only when a daemon drains the file completely (`remove_file`
    /// in `daemon::fallback_replay`). While no daemon comes to drain it — the
    /// case this cap exists for — the file itself grows without bound: a
    /// five-day outage measured 135 MB on disk with the 50 MB unread window
    /// being held correctly throughout.
    ///
    /// Daemon-side only. The hook compiles in its own 50 MB constant because it
    /// cannot read `config.toml` within its cold-start budget, so lowering this
    /// has no effect during an outage.
    pub fallback_max_bytes: u64,
    /// Maximum number of events the cloud worker accumulates before flushing
    /// the batch. Default: 50. Clamped to `1..=100` at load time: the platform
    /// hard-rejects batches larger than 100, and 0 would leave the accumulator
    /// with no reachable size trigger. Setting it to 1 restores the historical
    /// one-request-per-event behaviour.
    pub batch_max_events: usize,
    /// Maximum time the cloud worker waits before flushing a partial batch, in
    /// milliseconds. Default: 5000. The deadline is anchored to the *first*
    /// event buffered and is not reset by subsequent ones, so this value bounds
    /// forwarding latency rather than merely spacing out flushes.
    pub batch_max_wait_ms: u64,
}

/// Log — once per process — that a config or env switch asking to disable cloud
/// forwarding was read and ignored.
///
/// Once, because `Config::load` runs several times in a single CLI invocation
/// and a per-load warning would bury the command's actual output.
fn warn_ignored_cloud_switch(source: &str) {
    use std::sync::atomic::{AtomicBool, Ordering};
    static WARNED: AtomicBool = AtomicBool::new(false);
    if WARNED.swap(true, Ordering::Relaxed) {
        return;
    }
    tracing::warn!(
        code = ERR_INVALID_CONFIG,
        source = source,
        "cloud forwarding can no longer be disabled — {source} was ignored. Point [cloud] \
         api_url elsewhere if you need to change where events go."
    );
}

impl Default for CloudConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            api_url: "https://app.openlatch.ai".into(),
            timeout_connect_ms: 5000,
            timeout_total_ms: 10000,
            retry_delay_ms: 2000,
            channel_size: 1000,
            credential_poll_interval_ms: 60_000,
            outbox_enabled: true,
            outbox_max_bytes: 104_857_600,
            fallback_max_bytes: 52_428_800,
            batch_max_events: 50,
            batch_max_wait_ms: 5000,
        }
    }
}

// ---------------------------------------------------------------------------
// Configuration plane monitoring (Phase 1)
// ---------------------------------------------------------------------------

/// How file content is forwarded to the cloud — privacy-filtered (default),
/// hash-only (enterprise), or unfiltered (E2E test only, refused unless
/// `OPENLATCH_TESTING=true`).
#[derive(Debug, Clone, Copy, Default, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ContentForwardMode {
    #[default]
    Filtered,
    HashOnly,
    FullUnfiltered,
}

/// Configuration for the configuration-plane inventory monitor.
///
/// Override via env vars (all start with `OPENLATCH_INVENTORY_`):
/// - `..._ENABLED` — toggle the monitor entirely (default: true).
/// - `..._PERIODIC_RESCAN_HOURS` — periodic rescan cadence (default: 12).
/// - `..._DEBOUNCE_MS` — FS-watcher debounce window (default: 500).
/// - `..._MAX_INLINE_BYTES` — max content forwarded inline (default: 64 KB).
/// - `..._CONTENT_FORWARD` — `filtered` / `hash_only` / `full_unfiltered`.
/// - `..._PROJECT_AUTO_DETECT` — walk-up project root detection (default: true).
/// - `..._CACHE_MAX_ENTRIES` — `ContentHashCache` capacity (default: 4096).
#[derive(Debug, Clone)]
pub struct InventoryMonitorConfig {
    pub enabled: bool,
    pub periodic_rescan_interval_hours: u64,
    pub watcher_debounce_ms: u64,
    pub max_inline_content_bytes: u64,
    pub content_forward: ContentForwardMode,
    pub project_scope_auto_detect: bool,
    pub cache_max_entries: usize,
}

impl Default for InventoryMonitorConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            periodic_rescan_interval_hours: 12,
            watcher_debounce_ms: 500,
            max_inline_content_bytes: 65_536,
            content_forward: ContentForwardMode::Filtered,
            project_scope_auto_detect: true,
            cache_max_entries: 4096,
        }
    }
}

// ---------------------------------------------------------------------------
// Policy bundle sync
// ---------------------------------------------------------------------------

/// Configuration for the local policy engine — bundle polling and evaluation.
///
/// Populated from the `[policy]` section of `config.toml` with env var
/// overrides:
/// - `OPENLATCH_POLICY_ENABLED` — overrides `enabled`
/// - `OPENLATCH_POLICY_POLL_INTERVAL_SECS` — overrides `poll_interval_secs`
/// - `OPENLATCH_POLICY_STALE_WARN_SECS` — overrides `stale_warn_after_secs`
#[derive(Debug, Clone)]
pub struct PolicyConfig {
    /// Whether the client participates in policy at all.
    ///
    /// **Ships `true` — secure-by-default.** Policy polling and on-host
    /// evaluation are on out of the box; opt out with `[policy] enabled = false`
    /// in `config.toml` or `OPENLATCH_POLICY_ENABLED=false`. (The first release
    /// shipped `false` so it could not change any host's behaviour; the canary
    /// having passed, the default is now on.)
    ///
    /// `enabled = false` is a **complete off switch, not observe mode**: the
    /// poller does not run, nothing is fetched, and any resident bundle is
    /// **not** consulted — the daemon returns `allow` exactly as it does
    /// today. The on-disk bundle is left in place, so re-enabling does not
    /// require a re-download.
    ///
    /// Not to be confused with the bundle's own `enforcement_enabled`, which
    /// is the server-side kill switch: that one downgrades every rule to
    /// observe while still recording shadow verdicts. This one stops the
    /// client participating.
    pub enabled: bool,
    /// Base interval between bundle polls, in seconds. Default: 300.
    ///
    /// The poller applies ±10% jitter to every interval so a fleet on a fixed
    /// timer does not become a synchronized thundering herd against a single
    /// origin. The value configured here is the centre of that band, not the
    /// exact sleep.
    pub poll_interval_secs: u64,
    /// Log `OL-1213` once no successful poll has happened for this many
    /// seconds. Default: 86400 (24 h).
    ///
    /// Measured from the last successful **poll** (connectivity), not from the
    /// bundle's `built_at` (policy age) — otherwise a healthy organization
    /// whose rules simply never change would warn forever. A `304` counts as a
    /// successful poll. Staleness is a warning only: the resident bundle keeps
    /// enforcing.
    pub stale_warn_after_secs: u64,
}

impl Default for PolicyConfig {
    fn default() -> Self {
        Self {
            // Secure-by-default: policy polling + evaluation are on out of the
            // box. Opt out with `[policy] enabled = false` or
            // OPENLATCH_POLICY_ENABLED=false. See the field doc.
            enabled: true,
            poll_interval_secs: 300,
            stale_warn_after_secs: 86_400,
        }
    }
}

// ---------------------------------------------------------------------------
// Model-boundary listener
// ---------------------------------------------------------------------------

/// Configuration for the model-boundary listener (the loopback proxy that
/// captures model-call economics and attribution).
///
/// Populated from the `[boundary]` section of `config.toml` with the env
/// overrides `OPENLATCH_BOUNDARY_ENABLED` and
/// `OPENLATCH_BOUNDARY_TRANSFORMS_ACT`.
#[derive(Debug, Clone)]
pub struct BoundaryConfig {
    /// Whether the daemon binds the pinned loopback boundary port and routes
    /// the agent through it.
    ///
    /// **Ships `true` — secure-by-default.** The proxy is on out of the box; the
    /// daemon writes `ANTHROPIC_BASE_URL` so the agent routes model calls
    /// through the listener.
    ///
    /// This is the only switch, because binding the port and writing the agent
    /// config are no longer separable: the daemon writes `ANTHROPIC_BASE_URL`
    /// once a preflight probe has proven the listener can reach the provider
    /// (`boundary::preflight`), and removes it when either stops being true, so
    /// the config can never name a listener that does not exist — or one that
    /// exists and cannot forward. `false` here
    /// (or `OPENLATCH_BOUNDARY_ENABLED=false`) means neither happens, and a
    /// daemon starting that way also clears any wiring it finds left behind.
    /// `openlatch init --no-boundary` does the same for one install.
    ///
    /// Accepted implication: while the agent's `ANTHROPIC_BASE_URL` points at
    /// the listener, Claude Code Remote Control is disabled. Stopping the daemon
    /// restores it, since the wiring goes with the listener.
    pub enabled: bool,

    /// The loopback port the boundary listener binds. Defaults to
    /// [`DEFAULT_BOUNDARY_PORT`](crate::boundary::DEFAULT_BOUNDARY_PORT).
    ///
    /// **This became configurable only once the daemon took sole ownership of
    /// the agent wiring.** It was a compile-time constant with deliberately no
    /// override, because `init` wrote `ANTHROPIC_BASE_URL` and the supervised
    /// daemon bound the port — two processes in different environments (a shell
    /// variable set at `init` is not inherited by a launchd/systemd start after
    /// a reboot), so any runtime override could make the written value and the
    /// bound value disagree. One process now does both, deriving what it writes
    /// from the bind that just succeeded, so they cannot disagree whatever this
    /// is set to. D-25 still holds: the port is never *silently re-probed* onto
    /// a different one: an explicitly configured port is not a re-probe.
    ///
    /// Whether an **acting** `prefix_reorder` (L-0) rule may rewrite the
    /// forwarded request body.
    ///
    /// **Ships `false`.** The opposite default from [`BoundaryConfig::enabled`],
    /// and deliberately so: `enabled` decides whether OpenLatch *sees* the
    /// traffic, this decides whether it *changes* it. Model Boundary **D-28**
    /// exempts L-0 alone from the D-26 mode coercion — an L-0 rule authored
    /// `enforce` may act — and makes this flag one of its four conditions, so
    /// a fleet that has not deliberately turned it on forwards byte-identically
    /// to the pre-D-28 build.
    ///
    /// It gates **only L-0**. `history_trim` (L-1) and `prompt_edit` (L-2) are
    /// still rewritten to `observe` at bundle load whatever this is set to —
    /// they are removal levers, still D-26/ABE-D14-blocked, and no value here
    /// reaches them.
    ///
    /// Off is not merely "do not act": it is a **zero-cost** path. The request
    /// body is not retained past observation and the mutation step never runs,
    /// so an instance with this off does exactly the work it did before.
    pub transforms_act: bool,

    /// Whether the boundary resolves the request's session with the **prioritized
    /// selector cascade** instead of the single most-recently-active pick (D-29).
    ///
    /// **Ships `false`**, on the same reasoning as [`BoundaryConfig::transforms_act`]:
    /// a fleet that has not deliberately turned it on attributes exactly as the
    /// pre-cascade build did. Off, `resolve_session` runs the pre-cascade path
    /// byte-for-byte and the request-side signals are never derived at all.
    ///
    /// **A non-default port makes the instance isolated**: the daemon binds it
    /// but does NOT write `~/.claude/settings.json`, and does not clear it
    /// either. That file is machine-global and the canonical daemon on the
    /// default port owns it — a second instance writing it would take the wiring
    /// out from under the first, reintroducing the two-owner divergence in a new
    /// shape. An isolated instance prints the `ANTHROPIC_BASE_URL` to export
    /// instead, so exactly the sessions launched with it are routed through it.
    pub port: u16,

    /// The provider origins the listener forwards to, **one per wire format**,
    /// keyed by [`WireFormat::as_str`]. Read through
    /// [`BoundaryConfig::upstream_for`], never indexed directly.
    ///
    /// Exists because the wiring is now gated on a real round trip to this
    /// origin (`boundary::preflight`), and a gate that can only ever be aimed at
    /// `api.anthropic.com` cannot be exercised without the public internet —
    /// which would make the hermetic wiring tests network-dependent and the
    /// end-to-end harness unable to prove the gate at all.
    ///
    /// It is NOT a general-purpose gateway setting: a value that is not the
    /// first-party API means every model call and every credential on this host
    /// goes to whatever it names. Left at the default unless a test, a local
    /// harness, or a deliberate operator says otherwise.
    ///
    /// **Empty by default, and that is load-bearing.** The built-in per-format
    /// upstream lives in [`WireFormat::default_upstream`] and is applied as the
    /// last step of [`BoundaryConfig::upstream_for`]; materializing Anthropic's
    /// into this map would make that step unreachable and resolve every
    /// unconfigured format — Codex included — to `api.anthropic.com`.
    ///
    /// `[boundary] upstream` still accepts the bare string it always did: a
    /// scalar lands as the `anthropic-messages` entry, so an existing
    /// corporate-gateway setting keeps its exact meaning.
    pub upstream: BTreeMap<String, String>,

    /// Override for "may this instance write the agent's `ANTHROPIC_BASE_URL`?"
    /// `None` — the default — derives it from the port.
    ///
    /// Exists for the isolated instance: own `OPENLATCH_DIR`, own
    /// `$CLAUDE_CONFIG_DIR`, own ports. Such an instance binds its listener and
    /// then, under the port rule alone, refuses to wire its *own throwaway*
    /// agent config — so every sandbox session needed `ANTHROPIC_BASE_URL`
    /// exported by hand, which is exactly the manual step that makes a
    /// development loop unpleasant enough to skip.
    ///
    /// Explicit rather than inferred, and see
    /// [`BoundaryConfig::owns_agent_wiring`] for why: `$CLAUDE_CONFIG_DIR` is
    /// also how someone relocates their single real agent config, so treating
    /// its presence as "this file is nobody else's" would be wrong on exactly
    /// the hosts where being wrong costs the most.
    ///
    /// `olbox` (`tools/sandbox`) exports this for every sandbox it creates; on
    /// a normal install nothing sets it. It is a supported client seam, not a
    /// hook for that tool — anyone running a second instance with its own agent
    /// config sets it the same way, by hand or otherwise.
    /// Config: `[boundary] own_agent_wiring`. Env:
    /// `OPENLATCH_BOUNDARY_OWN_WIRING`.
    pub own_agent_wiring: Option<bool>,
}

impl Default for BoundaryConfig {
    fn default() -> Self {
        // Secure-by-default: the proxy is on. Opt out via config/env/flag.
        Self {
            enabled: true,
            // D-28 condition: acting ships OFF. Seeing traffic is
            // secure-by-default; changing it is opt-in.
            transforms_act: false,
            port: crate::boundary::default_boundary_port(),
            // EMPTY, deliberately: the built-in defaults belong to
            // `WireFormat::default_upstream()`, which `upstream_for` applies
            // last. A materialized `anthropic-messages` entry here would exist
            // on every stock install and make that step unreachable.
            upstream: BTreeMap::new(),
            own_agent_wiring: None,
        }
    }
}

impl BoundaryConfig {
    /// May this instance write the agent's `ANTHROPIC_BASE_URL`?
    ///
    /// Default: only the canonical daemon, identified by the default boundary
    /// port. `~/.claude/settings.json` is machine-global and has exactly one
    /// owner; a second daemon writing it would take the wiring out from under
    /// the first, which is the two-owner divergence the ownership move removed.
    ///
    /// [`BoundaryConfig::own_agent_wiring`] overrides that for an instance
    /// whose agent config is genuinely its own — a sandbox. The override is
    /// **explicit and never inferred**. Inferring it from "`$CLAUDE_CONFIG_DIR`
    /// is set" is the obvious shortcut and it is wrong: that variable is also
    /// how an operator relocates their *one real* agent config, and how the
    /// wiring tests stand in for it. Under inference, a host that relocates it
    /// globally would hand ownership of one shared file to every daemon that
    /// came along.
    ///
    /// The override is refused when the agent config it would write **is** the
    /// machine-global one. Opting in is a decision about your own sandbox; it
    /// is not a way to seize `~/.claude/settings.json` from a non-default port.
    pub fn owns_agent_wiring(&self) -> bool {
        match self.own_agent_wiring {
            // Belt and braces: an explicit `true` still may not reach the
            // machine-global file from a non-default port.
            Some(true) => {
                self.port == crate::boundary::default_boundary_port()
                    || !crate::hooks::claude_code::config_is_machine_global()
            }
            Some(false) => false,
            None => self.port == crate::boundary::default_boundary_port(),
        }
    }

    /// The configured upstream for one wire format, as a **string**.
    ///
    /// Three steps, and this is the only place the precedence exists:
    ///
    /// 1. an entry for **this** format — use it;
    /// 2. for [`WireFormat::Unknown`] **only**, the `anthropic-messages` entry —
    ///    use it;
    /// 3. otherwise the format's own [`WireFormat::default_upstream`].
    ///
    /// **Step 2 is scoped to `Unknown` and the scope is the whole point.** Today
    /// one base serves every route, so a host with `upstream = "https://gw"`
    /// forwards `GET /v1/models` and `POST /v1/messages/count_tokens` to the
    /// gateway too; step 2 is what preserves that. Widening it to captured
    /// formats would resolve `openai-responses` to the customer's *Anthropic*
    /// gateway — a cross-provider misroute of their prompts.
    ///
    /// **This function does not parse.** It returns the configured string
    /// verbatim or the built-in default string; the `String` → `Url` parse, its
    /// warning and its per-format fallback have exactly one owner,
    /// `BoundaryState::with_upstream_map`. Two owners is how the fallbacks
    /// drifted apart last time.
    pub fn upstream_for(&self, fmt: WireFormat) -> String {
        if let Some(v) = self.upstream.get(fmt.as_str()) {
            return v.clone();
        }
        if matches!(fmt, WireFormat::Unknown) {
            if let Some(v) = self.upstream.get(WireFormat::AnthropicMessages.as_str()) {
                return v.clone();
            }
        }
        fmt.default_upstream().to_string()
    }
}

// ---------------------------------------------------------------------------
// Platform-aware home directory
// ---------------------------------------------------------------------------

/// Serializes every unit test that writes the process-wide `OPENLATCH_DIR`.
///
/// **The** lock for that variable, not another one beside it. Two mutexes do
/// not exclude each other: a module holding its own `ENV_LOCK` while another
/// module holds this one leaves both free to set the one process-wide variable
/// at the same time, and each then redirects the other's config writes. So a
/// test that pokes `OPENLATCH_DIR` takes this, and a module-private lock keeps
/// only its other duties.
///
/// **Lock order**, so two tests cannot deadlock by taking these in opposite
/// orders: this one → `hooks::claude_code::CONFIG_DIR_ENV_LOCK` →
/// `hooks::staging::HOOK_BIN_ENV_LOCK` → `hooks::codex_cli::CONFIG_DIR_ENV_LOCK`.
/// `OPENLATCH_DIR` is taken first; a config-directory lock is always last.
///
/// Scope, stated so the gap is not mistaken for coverage: this module's own
/// tests, `cli::commands::doctor_fix` and `boundary::retention` also write
/// `OPENLATCH_DIR` in unit tests, in this same binary, and still do not take
/// this lock. That race pre-dates this static and closing it is a repo-wide
/// test refactor — not something to do silently from a unit that only needed
/// to stop *adding* to it. What did have to move are the writers this unit's
/// own tests demonstrably collide with: `hooks::tests`' install fixtures and
/// `cli::commands::lifecycle`'s two.
///
/// `#[cfg(test)]` because an ungated `pub(crate)` static read only from tests
/// is dead code, and CI runs clippy with `-D warnings`.
#[cfg(test)]
pub(crate) static OPENLATCH_DIR_ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

/// Returns the platform-appropriate openlatch data directory.
///
/// Resolution order:
/// 1. `OPENLATCH_DIR` env var — absolute path override (used by E2E tests and
///    users who need a non-default location; non-empty values only).
/// 2. Platform default:
///    - Unix/macOS: `~/.openlatch`
///    - Windows: `%APPDATA%\openlatch` (falls back to `~\openlatch` if
///      `%APPDATA%` is unavailable). On Windows this reads `FOLDERID_RoamingAppData`
///      via `SHGetKnownFolderPath` — which ignores the `APPDATA` env var —
///      so `OPENLATCH_DIR` is the supported redirection mechanism.
pub fn openlatch_dir() -> PathBuf {
    if let Ok(dir) = std::env::var("OPENLATCH_DIR") {
        if !dir.is_empty() {
            return PathBuf::from(dir);
        }
    }
    default_openlatch_dir()
}

/// Step 2 of [`openlatch_dir`] on its own: where the state directory lives when
/// nothing redirects it.
///
/// Split out so a caller can ask whether *this* install is the machine's
/// default one — the question anything machine-global has to answer before it
/// acts on behalf of "the install". `uninstall --purge` is one: the OS keychain
/// holds a single `openlatch` credential per machine however many state
/// directories sit beside it, so a purge run from a sandbox must not take the
/// real install's key with it.
pub fn default_openlatch_dir() -> PathBuf {
    #[cfg(windows)]
    {
        dirs::data_dir()
            .unwrap_or_else(|| dirs::home_dir().expect("home directory must exist"))
            .join("openlatch")
    }
    #[cfg(not(windows))]
    {
        dirs::home_dir()
            .expect("home directory must exist")
            .join(".openlatch")
    }
}

// Parse a boolean environment variable using the project convention:
// "true" or "1" is true; anything else (including "false", "0", empty)
// is false. Returns None when the variable is unset so callers can
// fall through to a TOML or default value.
fn env_bool(name: &str) -> Option<bool> {
    std::env::var(name)
        .ok()
        .map(|v| matches!(v.as_str(), "true" | "1"))
}

/// Return the `agent_id` from `~/.openlatch/config.toml` without the full
/// TOML parse pipeline. Line-grep only — returns `None` if the file is
/// missing, malformed, or has no `agent_id` line. Used by startup paths
/// (CLI init_telemetry, cloud worker drain) where triggering a full
/// `Config::load` would be heavier than needed and more brittle if the
/// config file is partially written during first install.
pub fn sniff_agent_id(openlatch_dir: &Path) -> Option<String> {
    std::fs::read_to_string(openlatch_dir.join("config.toml"))
        .ok()
        .and_then(|raw| {
            raw.lines()
                .find_map(|l| {
                    let l = l.trim();
                    l.strip_prefix("agent_id")
                        .and_then(|rest| rest.split('=').nth(1))
                        .map(|v| v.trim().trim_matches('"').to_string())
                })
                .filter(|s| s.starts_with("agt_"))
        })
}

// ---------------------------------------------------------------------------
// Config struct (public, runtime-resolved)
// ---------------------------------------------------------------------------

/// Resolved runtime configuration for the OpenLatch daemon.
///
/// This struct is constructed by [`Config::load`] from the full precedence chain:
/// CLI flags > env vars > config.toml > defaults.
#[derive(Debug, Clone)]
pub struct Config {
    /// TCP port for the local daemon (default: 7443).
    pub port: u16,
    /// Directory for audit and daemon logs.
    pub log_dir: PathBuf,
    /// Tracing log level (default: "info").
    pub log_level: String,
    /// Audit log retention in days (default: 30).
    pub retention_days: u32,
    /// Additional regex patterns for secret masking (additive to built-ins, per D-03).
    pub extra_patterns: Vec<String>,
    /// When true, daemon runs in foreground without forking.
    pub foreground: bool,
    /// Update check configuration (UPDT-01 through UPDT-04).
    pub update: UpdateConfig,
    /// Cloud forwarding configuration (CONF-01, D-12).
    pub cloud: CloudConfig,
    /// Persistent machine identifier (D-11). Generated once at init via ensure_agent_id().
    /// Format: `agt_<uuid_simple>` (e.g., "agt_550e8400e29b41d4a716446655440000").
    /// None if not yet initialized.
    pub agent_id: Option<String>,
    /// Supervision state: OS-native auto-restart for the daemon (launchd / systemd
    /// user / Task Scheduler). Populated from the `[supervision]` section in
    /// config.toml, persisted by `persist_supervision_state`.
    pub supervision: crate::supervision::SupervisionConfig,
    /// Configuration plane monitor — captures AI agent config-file changes,
    /// hashes them, and forwards to cloud via the existing rail. Populated
    /// from the `[inventory_monitor]` section of `config.toml`.
    pub inventory_monitor: InventoryMonitorConfig,
    /// Local policy engine — bundle polling and on-host evaluation. Populated
    /// from the `[policy]` section of `config.toml`. Ships enabled (opt-out).
    pub policy: PolicyConfig,
    /// Model-boundary listener — the loopback proxy for model-call economics +
    /// attribution. Populated from the `[boundary]` section of `config.toml`.
    /// Ships enabled (opt-out).
    pub boundary: BoundaryConfig,
    /// The resolved egress route: which proxy every non-loopback request goes
    /// through, how it authenticates, what it trusts and what it bypasses.
    ///
    /// Resolved from the `[proxy]` section plus the environment, and unlike the
    /// other sections it is settled at the very END of [`Config::load`] — see
    /// the call site for why the port numbers have to be final first.
    pub egress: crate::core::egress::EgressConfig,
}

impl Config {
    /// Return sensible defaults for all config fields.
    pub fn defaults() -> Self {
        Self {
            port: 7443,
            log_dir: openlatch_dir().join("logs"),
            log_level: "info".into(),
            retention_days: 30,
            extra_patterns: vec![],
            foreground: false,
            update: UpdateConfig::default(),
            cloud: CloudConfig::default(),
            agent_id: None,
            supervision: crate::supervision::SupervisionConfig::default(),
            inventory_monitor: InventoryMonitorConfig::default(),
            policy: PolicyConfig::default(),
            boundary: BoundaryConfig::default(),
            // Defaults read nothing: no file, no environment, no proxy. The
            // route is discovered only by `load`, which is the one place that
            // knows the final listener ports.
            egress: crate::core::egress::EgressConfig::direct(),
        }
    }

    /// Load configuration from the full precedence chain.
    ///
    /// Precedence order (highest to lowest):
    /// 1. CLI flags (`cli_*` parameters — `Some(value)` overrides)
    /// 2. Environment variables (`OPENLATCH_PORT`, `OPENLATCH_HOST`, `OPENLATCH_LOG_DIR`,
    ///    `OPENLATCH_LOG`, `OPENLATCH_RETENTION_DAYS`)
    /// 3. `~/.openlatch/config.toml` (parsed, partial overrides)
    /// 4. Compile-time defaults
    ///
    /// # Errors
    ///
    /// Returns [`OlError`] if the config file exists but cannot be parsed as valid TOML.
    pub fn load(
        cli_port: Option<u16>,
        cli_log_level: Option<String>,
        cli_foreground: bool,
    ) -> Result<Self, OlError> {
        let mut cfg = Self::defaults();

        // Held aside rather than merged with the rest of the file: the `[proxy]`
        // block is resolved at the very end of this function, once both listener
        // ports are final. See the resolve call below.
        let mut proxy_toml: Option<crate::core::egress::ProxyToml> = None;

        // Layer 3: config.toml
        let config_path = openlatch_dir().join("config.toml");
        if config_path.exists() {
            let raw = std::fs::read_to_string(&config_path).map_err(|e| {
                OlError::new(ERR_INVALID_CONFIG, format!("Cannot read config file: {e}"))
                    .with_suggestion("Check that the file is readable and not corrupted.")
            })?;
            let toml_cfg: TomlConfig = toml::from_str(&raw).map_err(|e| {
                OlError::new(
                    ERR_INVALID_CONFIG,
                    format!("Invalid TOML in config file: {e}"),
                )
                .with_suggestion("Check your config.toml for syntax errors.")
                .with_docs("https://docs.openlatch.ai/configuration")
            })?;
            proxy_toml = toml_cfg.proxy;
            if let Some(daemon) = toml_cfg.daemon {
                if let Some(port) = daemon.port {
                    cfg.port = port;
                }
                if let Some(ref mid) = daemon.agent_id {
                    cfg.agent_id = Some(mid.clone());
                }
            }
            if let Some(logging) = toml_cfg.logging {
                if let Some(level) = logging.level {
                    cfg.log_level = level;
                }
                if let Some(dir) = logging.dir {
                    cfg.log_dir = PathBuf::from(dir);
                }
                if let Some(days) = logging.retention_days {
                    cfg.retention_days = days;
                }
            }
            if let Some(privacy) = toml_cfg.privacy {
                if let Some(patterns) = privacy.extra_patterns {
                    cfg.extra_patterns = patterns;
                }
            }
            if let Some(update) = toml_cfg.update {
                if let Some(check) = update.check {
                    cfg.update.check = check;
                }
                if let Some(origin) = update.registry_origin {
                    cfg.update.registry_origin = origin;
                }
                if let Some(secs) = update.download_timeout_secs {
                    cfg.update.download_timeout_secs = secs;
                }
                if let Some(v) = update.auto_update {
                    cfg.update.auto_update = v;
                }
                if let Some(v) = update.check_interval_secs {
                    cfg.update.check_interval_secs = v;
                }
                if let Some(v) = update.quiet_window_secs {
                    cfg.update.quiet_window_secs = v;
                }
                if let Some(v) = update.max_defer_secs {
                    cfg.update.max_defer_secs = v;
                }
            }
            if let Some(sup) = toml_cfg.supervision {
                use crate::supervision::{SupervisionMode, SupervisorKind};
                if let Some(mode) = sup.mode.as_deref() {
                    cfg.supervision.mode = match mode {
                        "active" => SupervisionMode::Active,
                        "deferred" => SupervisionMode::Deferred,
                        _ => SupervisionMode::Disabled,
                    };
                }
                if let Some(backend) = sup.backend.as_deref() {
                    cfg.supervision.backend = match backend {
                        "launchd" => SupervisorKind::Launchd,
                        "systemd" => SupervisorKind::Systemd,
                        "task_scheduler" => SupervisorKind::TaskScheduler,
                        _ => SupervisorKind::None,
                    };
                }
                cfg.supervision.disabled_reason = sup.disabled_reason;
            }
            if let Some(inv) = toml_cfg.inventory_monitor {
                if let Some(v) = inv.enabled {
                    cfg.inventory_monitor.enabled = v;
                }
                if let Some(v) = inv.periodic_rescan_interval_hours {
                    cfg.inventory_monitor.periodic_rescan_interval_hours = v;
                }
                if let Some(v) = inv.watcher_debounce_ms {
                    cfg.inventory_monitor.watcher_debounce_ms = v;
                }
                if let Some(v) = inv.max_inline_content_bytes {
                    cfg.inventory_monitor.max_inline_content_bytes = v;
                }
                if let Some(v) = inv.content_forward {
                    cfg.inventory_monitor.content_forward = v;
                }
                if let Some(v) = inv.project_scope_auto_detect {
                    cfg.inventory_monitor.project_scope_auto_detect = v;
                }
                if let Some(v) = inv.cache_max_entries {
                    cfg.inventory_monitor.cache_max_entries = v;
                }
            }
            if let Some(cloud) = toml_cfg.cloud {
                // `[cloud] enabled` is parsed and ignored. See the field doc on
                // `CloudConfig::enabled`: forwarding to the platform is what the
                // client is for, and there is no supported way to switch it
                // off. The key is still accepted so an existing config.toml
                // carrying it keeps loading — it just no longer decides
                // anything.
                if cloud.enabled == Some(false) {
                    warn_ignored_cloud_switch("[cloud] enabled = false");
                }
                if let Some(v) = cloud.api_url {
                    cfg.cloud.api_url = v;
                }
                if let Some(v) = cloud.timeout_connect_ms {
                    cfg.cloud.timeout_connect_ms = v;
                }
                if let Some(v) = cloud.timeout_total_ms {
                    cfg.cloud.timeout_total_ms = v;
                }
                if let Some(v) = cloud.retry_delay_ms {
                    cfg.cloud.retry_delay_ms = v;
                }
                if let Some(v) = cloud.channel_size {
                    cfg.cloud.channel_size = v;
                }
                if let Some(v) = cloud.credential_poll_interval_ms {
                    cfg.cloud.credential_poll_interval_ms = v;
                }
                if let Some(v) = cloud.outbox_enabled {
                    cfg.cloud.outbox_enabled = v;
                }
                if let Some(v) = cloud.outbox_max_bytes {
                    cfg.cloud.outbox_max_bytes = v;
                }
                if let Some(v) = cloud.fallback_max_bytes {
                    cfg.cloud.fallback_max_bytes = v;
                }
                if let Some(v) = cloud.batch_max_events {
                    cfg.cloud.batch_max_events = v;
                }
                if let Some(v) = cloud.batch_max_wait_ms {
                    cfg.cloud.batch_max_wait_ms = v;
                }
            }
            if let Some(policy) = toml_cfg.policy {
                if let Some(v) = policy.enabled {
                    cfg.policy.enabled = v;
                }
                if let Some(v) = policy.poll_interval_secs {
                    cfg.policy.poll_interval_secs = v;
                }
                if let Some(v) = policy.stale_warn_after_secs {
                    cfg.policy.stale_warn_after_secs = v;
                }
            }
            if let Some(boundary) = toml_cfg.boundary {
                if let Some(v) = boundary.enabled {
                    cfg.boundary.enabled = v;
                }
                if let Some(v) = boundary.transforms_act {
                    cfg.boundary.transforms_act = v;
                }
                if let Some(v) = boundary.port {
                    cfg.boundary.port = v;
                }
                if let Some(v) = boundary.upstream {
                    match v {
                        // The shape every install written before the per-format
                        // map contains. It has always meant "the upstream Claude
                        // traffic goes to", so that is exactly the entry it sets.
                        UpstreamToml::One(s) => {
                            cfg.boundary
                                .upstream
                                .insert(WireFormat::AnthropicMessages.as_str().to_string(), s);
                        }
                        // The raw keys exist HERE and nowhere downstream, so this
                        // is the only place a typo can be named. `upstream_for`
                        // would drop `anthropic_messages = "…"` (underscore)
                        // silently, and `collect_unknown_config_keys` does not
                        // recurse into `[boundary.upstream]`.
                        UpstreamToml::Map(m) => {
                            for key in m.keys() {
                                if !WireFormat::ALL.iter().any(|f| f.as_str() == key) {
                                    tracing::warn!(
                                        key = %key,
                                        "[boundary.upstream] key names no known wire format and \
                                         is ignored — expected one of anthropic-messages, \
                                         openai-responses, unknown"
                                    );
                                }
                            }
                            cfg.boundary.upstream = m;
                        }
                    }
                }
                if let Some(v) = boundary.own_agent_wiring {
                    cfg.boundary.own_agent_wiring = Some(v);
                }
            }
        }

        // Layer 2: env vars
        if let Ok(val) = std::env::var("OPENLATCH_PORT") {
            cfg.port = parse_port_env(&val)?;
        }
        if let Ok(val) = std::env::var("OPENLATCH_LOG_DIR") {
            cfg.log_dir = PathBuf::from(val);
        }
        if let Ok(val) = std::env::var("OPENLATCH_LOG") {
            cfg.log_level = val;
        }
        if let Ok(val) = std::env::var("OPENLATCH_RETENTION_DAYS") {
            cfg.retention_days = val.parse::<u32>().map_err(|_| {
                OlError::new(
                    ERR_INVALID_CONFIG,
                    format!("OPENLATCH_RETENTION_DAYS is not a valid integer: '{val}'"),
                )
                .with_suggestion("Set OPENLATCH_RETENTION_DAYS to a positive integer.")
            })?;
        }
        // UPDT-04: env var override for update check
        if let Ok(val) = std::env::var("OPENLATCH_UPDATE_CHECK") {
            if val == "false" || val == "0" {
                cfg.update.check = false;
            }
        }
        // P2 auto-update: registry origin + download timeout.
        if let Ok(val) = std::env::var("OPENLATCH_NPM_REGISTRY") {
            if !val.is_empty() {
                cfg.update.registry_origin = val;
            }
        }
        if let Ok(val) = std::env::var("OPENLATCH_UPDATE_DOWNLOAD_TIMEOUT_SECS") {
            if let Ok(secs) = val.parse::<u64>() {
                cfg.update.download_timeout_secs = secs;
            }
        }
        // Auto-update worker knobs. The E2E suite uses these to
        // squeeze the 6 h cadence down to single-digit seconds; users
        // can also opt out of auto-update entirely from a containerised
        // environment without writing a config file.
        if let Some(v) = env_bool("OPENLATCH_AUTO_UPDATE") {
            cfg.update.auto_update = v;
        }
        if let Ok(val) = std::env::var("OPENLATCH_UPDATE_CHECK_INTERVAL_SECS") {
            if let Ok(secs) = val.parse::<u64>() {
                cfg.update.check_interval_secs = secs;
            }
        }
        if let Ok(val) = std::env::var("OPENLATCH_UPDATE_QUIET_WINDOW_SECS") {
            if let Ok(secs) = val.parse::<u64>() {
                cfg.update.quiet_window_secs = secs;
            }
        }
        if let Ok(val) = std::env::var("OPENLATCH_UPDATE_MAX_DEFER_SECS") {
            if let Ok(secs) = val.parse::<u64>() {
                cfg.update.max_defer_secs = secs;
            }
        }
        // CONF-02: cloud env var overrides
        if env_bool("OPENLATCH_CLOUD_ENABLED") == Some(false) {
            warn_ignored_cloud_switch("OPENLATCH_CLOUD_ENABLED=false");
        }
        if let Ok(val) = std::env::var("OPENLATCH_API_URL") {
            cfg.cloud.api_url = val;
        }
        if let Ok(val) = std::env::var("OPENLATCH_CLOUD_CREDENTIAL_POLL_MS") {
            cfg.cloud.credential_poll_interval_ms = val.parse::<u64>().map_err(|_| {
                OlError::new(
                    ERR_INVALID_CONFIG,
                    format!("OPENLATCH_CLOUD_CREDENTIAL_POLL_MS is not a valid integer: '{val}'"),
                )
                .with_suggestion(
                    "Set OPENLATCH_CLOUD_CREDENTIAL_POLL_MS to a positive integer (ms).",
                )
            })?;
        }
        if let Some(v) = env_bool("OPENLATCH_CLOUD_OUTBOX_ENABLED") {
            cfg.cloud.outbox_enabled = v;
        }
        if let Ok(val) = std::env::var("OPENLATCH_CLOUD_OUTBOX_MAX_BYTES") {
            cfg.cloud.outbox_max_bytes = val.parse::<u64>().map_err(|_| {
                OlError::new(
                    ERR_INVALID_CONFIG,
                    format!("OPENLATCH_CLOUD_OUTBOX_MAX_BYTES is not a valid integer: '{val}'"),
                )
                .with_suggestion(
                    "Set OPENLATCH_CLOUD_OUTBOX_MAX_BYTES to a non-negative byte count (0 disables the cap).",
                )
            })?;
        }
        if let Ok(val) = std::env::var("OPENLATCH_CLOUD_FALLBACK_MAX_BYTES") {
            cfg.cloud.fallback_max_bytes = val.parse::<u64>().map_err(|_| {
                OlError::new(
                    ERR_INVALID_CONFIG,
                    format!("OPENLATCH_CLOUD_FALLBACK_MAX_BYTES is not a valid integer: '{val}'"),
                )
                .with_suggestion(
                    "Set OPENLATCH_CLOUD_FALLBACK_MAX_BYTES to a non-negative byte count (0 disables the cap).",
                )
            })?;
        }
        if let Ok(val) = std::env::var("OPENLATCH_CLOUD_BATCH_MAX_EVENTS") {
            cfg.cloud.batch_max_events = val.parse::<usize>().map_err(|_| {
                OlError::new(
                    ERR_INVALID_CONFIG,
                    format!("OPENLATCH_CLOUD_BATCH_MAX_EVENTS is not a valid integer: '{val}'"),
                )
                .with_suggestion(
                    "Set OPENLATCH_CLOUD_BATCH_MAX_EVENTS to an integer between 1 and 100 (values outside that range are clamped).",
                )
            })?;
        }
        if let Ok(val) = std::env::var("OPENLATCH_CLOUD_BATCH_MAX_WAIT_MS") {
            cfg.cloud.batch_max_wait_ms = val.parse::<u64>().map_err(|_| {
                OlError::new(
                    ERR_INVALID_CONFIG,
                    format!("OPENLATCH_CLOUD_BATCH_MAX_WAIT_MS is not a valid integer: '{val}'"),
                )
                .with_suggestion(
                    "Set OPENLATCH_CLOUD_BATCH_MAX_WAIT_MS to a positive integer (ms).",
                )
            })?;
        }

        // Inventory monitor env-var overrides.
        if let Some(v) = env_bool("OPENLATCH_INVENTORY_ENABLED") {
            cfg.inventory_monitor.enabled = v;
        }
        if let Ok(val) = std::env::var("OPENLATCH_INVENTORY_PERIODIC_RESCAN_HOURS") {
            if let Ok(n) = val.parse::<u64>() {
                cfg.inventory_monitor.periodic_rescan_interval_hours = n;
            }
        }
        if let Ok(val) = std::env::var("OPENLATCH_INVENTORY_DEBOUNCE_MS") {
            if let Ok(n) = val.parse::<u64>() {
                cfg.inventory_monitor.watcher_debounce_ms = n;
            }
        }
        if let Ok(val) = std::env::var("OPENLATCH_INVENTORY_MAX_INLINE_BYTES") {
            if let Ok(n) = val.parse::<u64>() {
                cfg.inventory_monitor.max_inline_content_bytes = n;
            }
        }
        if let Ok(val) = std::env::var("OPENLATCH_INVENTORY_CONTENT_FORWARD") {
            cfg.inventory_monitor.content_forward = match val.as_str() {
                "filtered" => ContentForwardMode::Filtered,
                "hash_only" => ContentForwardMode::HashOnly,
                "full_unfiltered" => ContentForwardMode::FullUnfiltered,
                _ => cfg.inventory_monitor.content_forward,
            };
        }
        if let Some(v) = env_bool("OPENLATCH_INVENTORY_PROJECT_AUTO_DETECT") {
            cfg.inventory_monitor.project_scope_auto_detect = v;
        }
        if let Ok(val) = std::env::var("OPENLATCH_INVENTORY_CACHE_MAX_ENTRIES") {
            if let Ok(n) = val.parse::<usize>() {
                cfg.inventory_monitor.cache_max_entries = n;
            }
        }

        // Policy engine env-var overrides.
        //
        // `enabled` goes through the shared `env_bool` helper, whose semantics
        // are not the obvious ones: "true" or "1" is true and ANY OTHER
        // non-empty value is false — so `OPENLATCH_POLICY_ENABLED=yes`
        // silently disables policy rather than erroring. That is the
        // established behaviour for every other boolean in this file and is
        // matched deliberately rather than special-cased here.
        if let Some(v) = env_bool("OPENLATCH_POLICY_ENABLED") {
            cfg.policy.enabled = v;
        }
        if let Ok(val) = std::env::var("OPENLATCH_POLICY_POLL_INTERVAL_SECS") {
            cfg.policy.poll_interval_secs = val.parse::<u64>().map_err(|_| {
                OlError::new(
                    ERR_INVALID_CONFIG,
                    format!("OPENLATCH_POLICY_POLL_INTERVAL_SECS is not a valid integer: '{val}'"),
                )
                .with_suggestion(
                    "Set OPENLATCH_POLICY_POLL_INTERVAL_SECS to a positive integer (seconds).",
                )
            })?;
        }
        if let Ok(val) = std::env::var("OPENLATCH_POLICY_STALE_WARN_SECS") {
            cfg.policy.stale_warn_after_secs = val.parse::<u64>().map_err(|_| {
                OlError::new(
                    ERR_INVALID_CONFIG,
                    format!("OPENLATCH_POLICY_STALE_WARN_SECS is not a valid integer: '{val}'"),
                )
                .with_suggestion(
                    "Set OPENLATCH_POLICY_STALE_WARN_SECS to a positive integer (seconds).",
                )
            })?;
        }

        // Model-boundary env-var override. Same `env_bool` semantics as every
        // other boolean here: "true"/"1" is true, any other non-empty value is
        // false (so `OPENLATCH_BOUNDARY_ENABLED=yes` disables the proxy).
        if let Some(v) = env_bool("OPENLATCH_BOUNDARY_ENABLED") {
            cfg.boundary.enabled = v;
        }
        if let Some(v) = env_bool("OPENLATCH_BOUNDARY_TRANSFORMS_ACT") {
            cfg.boundary.transforms_act = v;
        }
        if let Ok(val) = std::env::var("OPENLATCH_BOUNDARY_PORT") {
            cfg.boundary.port = val.parse::<u16>().map_err(|_| {
                OlError::new(
                    ERR_INVALID_CONFIG,
                    format!("OPENLATCH_BOUNDARY_PORT is not a valid port: '{val}'"),
                )
                .with_suggestion(
                    "Set OPENLATCH_BOUNDARY_PORT to a port number (1-65535), or unset it to use \
                     the default 7600. A non-default port makes the instance isolated: it does \
                     not write ~/.claude/settings.json.",
                )
            })?;
        }
        // Test / local-harness seam for the forward target. Every model call and
        // every provider credential on this host goes wherever this points, so
        // it is validated here — a typo that silently fell back to the default
        // would make a harness look like it was proving something it was not.
        if let Some(v) = env_bool("OPENLATCH_BOUNDARY_OWN_WIRING") {
            cfg.boundary.own_agent_wiring = Some(v);
        }
        if let Ok(val) = std::env::var("OPENLATCH_BOUNDARY_UPSTREAM") {
            if !val.trim().is_empty() {
                reqwest::Url::parse(val.trim()).map_err(|_| {
                    OlError::new(
                        ERR_INVALID_CONFIG,
                        format!("OPENLATCH_BOUNDARY_UPSTREAM is not a valid URL: '{val}'"),
                    )
                    .with_suggestion(
                        "Set it to an absolute origin such as http://127.0.0.1:8080, or unset it \
                         to forward to https://api.anthropic.com.",
                    )
                })?;
                // One override, for the one format that had it — it keeps its
                // current meaning and sets the `anthropic-messages` entry.
                cfg.boundary.upstream.insert(
                    WireFormat::AnthropicMessages.as_str().to_string(),
                    val.trim().to_string(),
                );
            }
        }

        // Layer 1: CLI flags (highest priority)
        if let Some(port) = cli_port {
            cfg.port = port;
        }
        if let Some(level) = cli_log_level {
            cfg.log_level = level;
        }
        if cli_foreground {
            cfg.foreground = true;
        }

        // Clamp the cloud batch size to what the platform will actually accept.
        // `POST /api/v1/events/ingest` hard-rejects batches larger than 100, and
        // a value of 0 would leave the worker's accumulator with no reachable
        // size trigger — it would only ever flush on the timer. Clamping here
        // (after every layer) means the worker can trust the value unchecked.
        cfg.cloud.batch_max_events = cfg.cloud.batch_max_events.clamp(1, 100);

        // Resolve the egress route LAST, for the same reason the clamp above is
        // last: it needs a value no later layer can still change. The resolver
        // refuses a proxy url aimed at this client's own daemon or boundary
        // listener — forwarding to ourselves is an infinite loop dressed as a
        // configuration — and a guard that ran inside the toml merge would be
        // comparing against ports that the env and CLI layers had yet to touch.
        //
        // The `?` is deliberate (D-9): an unreachable proxy is a network state
        // the daemon reports and keeps running through, but a `[proxy]` block it
        // cannot parse is a bug in the input, and starting anyway would only
        // move the failure to the first request.
        cfg.egress = crate::core::egress::EgressConfig::resolve(
            proxy_toml.as_ref(),
            &crate::core::egress::ProcessEnv,
            cfg.port,
            cfg.boundary.port,
        )?;

        // The proxy password is deliberately NOT loaded here. It is the one `[proxy]` value
        // that never appears in this file, and reading it means touching the OS keychain —
        // blocking I/O that can raise a macOS authorization dialog, which has no business
        // running inside a config parser that every command calls.
        //
        // The daemon gets it from `egress::resolve_auth`, which runs the full ladder (env,
        // keychain, encrypted file) once in the serve path before the first outbound client
        // is built. A CLI command that must itself authenticate to a proxy has to call the
        // same function; none does today.

        Ok(cfg)
    }
}

// ---------------------------------------------------------------------------
// TOML intermediate structs (all fields optional — partial overrides)
// ---------------------------------------------------------------------------

#[derive(Debug, Deserialize)]
struct TomlConfig {
    #[serde(default)]
    daemon: Option<DaemonToml>,
    #[serde(default)]
    logging: Option<LoggingToml>,
    #[serde(default)]
    privacy: Option<PrivacyToml>,
    #[serde(default)]
    update: Option<UpdateToml>,
    #[serde(default)]
    cloud: Option<CloudToml>,
    #[serde(default)]
    supervision: Option<SupervisionToml>,
    #[serde(default)]
    inventory_monitor: Option<InventoryMonitorToml>,
    #[serde(default)]
    policy: Option<PolicyToml>,
    #[serde(default)]
    boundary: Option<BoundaryToml>,
    /// The `[proxy]` block. Unlike every other section here, the mirror struct
    /// is not declared in this file: `core::egress` owns the field list, the
    /// precedence ladder that reads it and the validation that rejects it, so a
    /// second copy here would be a second thing to keep in step.
    #[serde(default)]
    proxy: Option<crate::core::egress::ProxyToml>,
}

#[derive(Debug, Deserialize)]
struct DaemonToml {
    port: Option<u16>,
    agent_id: Option<String>,
}

#[derive(Debug, Deserialize)]
struct CloudToml {
    enabled: Option<bool>,
    api_url: Option<String>,
    timeout_connect_ms: Option<u64>,
    timeout_total_ms: Option<u64>,
    retry_delay_ms: Option<u64>,
    channel_size: Option<usize>,
    credential_poll_interval_ms: Option<u64>,
    outbox_enabled: Option<bool>,
    outbox_max_bytes: Option<u64>,
    fallback_max_bytes: Option<u64>,
    batch_max_events: Option<usize>,
    batch_max_wait_ms: Option<u64>,
}

#[derive(Debug, Deserialize)]
struct LoggingToml {
    level: Option<String>,
    dir: Option<String>,
    retention_days: Option<u32>,
}

#[derive(Debug, Deserialize)]
struct PrivacyToml {
    extra_patterns: Option<Vec<String>>,
}

#[derive(Debug, Deserialize)]
struct UpdateToml {
    check: Option<bool>,
    registry_origin: Option<String>,
    download_timeout_secs: Option<u64>,
    auto_update: Option<bool>,
    check_interval_secs: Option<u64>,
    quiet_window_secs: Option<u64>,
    max_defer_secs: Option<u64>,
}

#[derive(Debug, Deserialize)]
struct SupervisionToml {
    mode: Option<String>,
    backend: Option<String>,
    disabled_reason: Option<String>,
}

#[derive(Debug, Deserialize)]
struct PolicyToml {
    enabled: Option<bool>,
    poll_interval_secs: Option<u64>,
    stale_warn_after_secs: Option<u64>,
}

#[derive(Debug, Deserialize)]
struct BoundaryToml {
    enabled: Option<bool>,
    transforms_act: Option<bool>,
    port: Option<u16>,
    upstream: Option<UpstreamToml>,
    own_agent_wiring: Option<bool>,
}

/// `[boundary] upstream` on disk — **both** shapes deserialize.
///
/// Untagged so a customer's existing scalar keeps working untouched, which
/// matters more here than anywhere else in the config: the boundary is the
/// subsystem where a startup failure takes every session on the machine down.
#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum UpstreamToml {
    /// `upstream = "https://api.anthropic.com"` — the `anthropic-messages`
    /// entry. What every install written before the map contains.
    One(String),
    /// ```toml
    /// [boundary.upstream]
    /// anthropic-messages = "https://gw.example"
    /// openai-responses   = "https://api.openai.com"
    /// ```
    Map(BTreeMap<String, String>),
}

#[derive(Debug, Deserialize)]
struct InventoryMonitorToml {
    enabled: Option<bool>,
    periodic_rescan_interval_hours: Option<u64>,
    watcher_debounce_ms: Option<u64>,
    max_inline_content_bytes: Option<u64>,
    content_forward: Option<ContentForwardMode>,
    project_scope_auto_detect: Option<bool>,
    cache_max_entries: Option<usize>,
}

// ---------------------------------------------------------------------------
// Unknown-key detection (warn on typo'd config keys)
// ---------------------------------------------------------------------------

/// Known configuration sections and their allowed keys.
///
/// serde's default `Deserialize` silently drops unrecognized fields, so a typo
/// like `[policy] enable = true` (correct: `enabled`) is ignored with no
/// feedback. This table drives [`collect_unknown_config_keys`]; keep it in
/// lock-step with the `*Toml` structs above.
const KNOWN_CONFIG_SECTIONS: &[(&str, &[&str])] = &[
    ("daemon", &["port", "agent_id"]),
    ("logging", &["level", "dir", "retention_days"]),
    ("privacy", &["extra_patterns"]),
    (
        "update",
        &[
            "check",
            "registry_origin",
            "download_timeout_secs",
            "auto_update",
            "check_interval_secs",
            "quiet_window_secs",
            "max_defer_secs",
        ],
    ),
    (
        "cloud",
        &[
            "enabled",
            "api_url",
            "timeout_connect_ms",
            "timeout_total_ms",
            "retry_delay_ms",
            "channel_size",
            "credential_poll_interval_ms",
            "outbox_enabled",
            "outbox_max_bytes",
            "fallback_max_bytes",
            "batch_max_events",
            "batch_max_wait_ms",
        ],
    ),
    ("supervision", &["mode", "backend", "disabled_reason"]),
    (
        "inventory_monitor",
        &[
            "enabled",
            "periodic_rescan_interval_hours",
            "watcher_debounce_ms",
            "max_inline_content_bytes",
            "content_forward",
            "project_scope_auto_detect",
            "cache_max_entries",
        ],
    ),
    (
        "policy",
        &["enabled", "poll_interval_secs", "stale_warn_after_secs"],
    ),
    (
        "boundary",
        &[
            "enabled",
            "transforms_act",
            "port",
            "upstream",
            // Parsed by `BoundaryToml` and honoured by `load` since the
            // isolated-instance seam landed; it was missing here, so a config
            // that set it was warned about a key that was working.
            "own_agent_wiring",
        ],
    ),
    // The one section whose key list is not written out here: `core::egress`
    // declares the `[proxy]` fields, and borrowing its array is what keeps the
    // allowlist from drifting away from the struct the way `boundary` did.
    ("proxy", crate::core::egress::PROXY_TOML_KEYS),
];

/// Collect unrecognized keys from a raw `config.toml` string.
///
/// Performs a second, lenient pass over the raw TOML and returns the dotted
/// paths of any top-level section — or per-section key — not present in
/// [`KNOWN_CONFIG_SECTIONS`], so the caller can warn the user about keys that
/// serde would otherwise silently ignore.
///
/// Returns an empty vec when `raw` is not valid TOML (the caller surfaces the
/// real parse error via its own typed path) or contains no unknown keys.
/// Order follows the document order preserved by the TOML parser.
pub(crate) fn collect_unknown_config_keys(raw: &str) -> Vec<String> {
    let Ok(table) = raw.parse::<toml::Table>() else {
        return Vec::new();
    };
    let mut unknown = Vec::new();
    for (section, value) in &table {
        let Some((_, allowed)) = KNOWN_CONFIG_SECTIONS
            .iter()
            .find(|(name, _)| name == section)
        else {
            unknown.push(section.clone());
            continue;
        };
        if let Some(sub) = value.as_table() {
            for key in sub.keys() {
                if !allowed.contains(&key.as_str()) {
                    unknown.push(format!("{section}.{key}"));
                }
            }
        }
    }
    unknown
}

/// Read `~/.openlatch/config.toml` (if present) and return any unrecognized
/// keys.
///
/// Thin disk wrapper over [`collect_unknown_config_keys`] for callers (e.g. the
/// `start` command) that want to warn the user about typo'd config keys.
/// Returns an empty vec when the file is absent or unreadable.
pub fn unknown_config_keys_on_disk() -> Vec<String> {
    match std::fs::read_to_string(openlatch_dir().join("config.toml")) {
        Ok(raw) => collect_unknown_config_keys(&raw),
        Err(_) => Vec::new(),
    }
}

// ---------------------------------------------------------------------------
// Default config template (D-10 / D-11)
// ---------------------------------------------------------------------------

/// Generate the default config.toml content.
///
/// Per D-10: commented template style — all sections present, every field commented.
/// Per D-11: only the pinned `port` value is written as an active (uncommented) line.
pub fn generate_default_config_toml(port: u16) -> String {
    format!(
        r#"# OpenLatch Configuration
# Uncomment and modify values to customize behavior.

[daemon]
port = {port}
# SECURITY: bind address is always 127.0.0.1 — not configurable
# agent_id is generated by 'openlatch init'

[logging]
# level = "info"
# dir = "~/.openlatch/logs"
# retention_days = 30

[privacy]
# Extra regex patterns for secret masking (additive to built-ins).
# Each entry is a regex string applied to JSON string values.
# extra_patterns = ["CUSTOM_SECRET_[A-Z0-9]{{32}}"]

# [update]
# check = true  # Set to false to disable update checks on daemon start

# [cloud]
# enabled = true
# api_url = "https://app.openlatch.ai"
# timeout_connect_ms = 5000
# timeout_total_ms = 10000
# retry_delay_ms = 2000
# channel_size = 1000
# batch_max_events = 50          # events per cloud POST (clamped to 1..=100; 1 = one POST per event)
# batch_max_wait_ms = 5000       # flush a partial batch this long after its FIRST event
# outbox_max_bytes = 104857600   # 100 MB cap on outbox.jsonl (drop-oldest)
# fallback_max_bytes = 52428800  # 50 MB cap on the UNREPLAYED window of fallback.jsonl, not on the
#                                # file: drop-oldest advances the read offset instead of rewriting.
#                                # The dead prefix is reclaimed only when a daemon fully drains the
#                                # file, so across a long outage the file on disk grows past this.
#                                # Daemon-side only — the hook uses a compiled-in 50 MB while the
#                                # daemon is down, which is exactly when this cap would matter.

# [proxy]
# How every outbound byte leaves this host — the cloud rail above included.
# With the section absent the client resolves the route itself: the OPENLATCH_*
# variables, then the standard https_proxy / HTTP_PROXY pair, then the OS proxy
# settings, then a direct connection. Set keys here only to override that.
# A malformed value fails startup rather than quietly going direct: an
# unreachable proxy is a network state to report, but a config the client cannot
# parse is a bug in the input.
# mode = "auto"                 # "auto" walks the ladder above; "manual" uses exactly what
#                               # is configured here and is never overwritten by discovery;
#                               # "direct" never proxies at all.
# url = ""                      # http:// https:// socks5:// or socks5h://. It must NOT carry
#                               # a username or password — this file is plaintext on disk, and
#                               # a url with userinfo is refused at startup. Credentials go in
#                               # OPENLATCH_PROXY or the `openlatch init` prompt, which put
#                               # them in the OS credential store.
# username = ""                 # username for Basic; the password lives in the credential store
# auth = "auto"                 # "auto" answers whatever scheme the proxy offers. "none",
#                               # "basic" or "negotiate" (Kerberos/SPNEGO) pin it. NTLM is
#                               # deliberately not supported.
# no_proxy = ""                 # additive bypass list, Go grammar:
#                               # ".corp.example,10.0.0.0/8,localhost:8080". Loopback always
#                               # bypasses and needs no entry here.
# pac_url = ""                  # explicit PAC URL. Not supported on Linux.
# ca_bundle = ""                # PEM bundle merged on top of the OS trust store, for a proxy
#                               # that terminates TLS. Read and checked at startup, so a
#                               # missing file or a DER-encoded one fails there rather than at
#                               # the first request.
# allow_direct = true           # false means the ladder never ends at a direct connection: with
#                               # no usable proxy the request fails instead of leaving the host
#                               # unproxied. A non-loopback no_proxy entry is then refused too,
#                               # since it is exactly the bypass the flag exists to forbid.
# source = "manual"             # provenance of the active route, written by `openlatch proxy
#                               # set` and by init: "manual" | "env" | "windows" | "macos" |
#                               # "gnome" | "pac" | "wpad". "manual" is what keeps a hand-set
#                               # route from being replaced by discovery or self-heal.
# spn = ""                      # Kerberos SPN override, e.g. "HTTP/proxy.corp.example". Only
#                               # read when auth resolves to negotiate.
# http1_only = false            # force HTTP/1.1 for inspection proxies that mishandle HTTP/2

# [policy]
# Local policy evaluation. On by default (secure-by-default). `enabled = false`
# is a complete off switch: no bundle is fetched and any bundle already on disk
# is not consulted — the daemon returns allow exactly as it does with this
# section absent. The on-disk bundle is left in place, so re-enabling does not
# re-download.
# enabled = true
# poll_interval_secs = 300        # +/-10% jitter is applied to every interval
# stale_warn_after_secs = 86400   # warn (OL-1213) after this long with no successful poll

# [boundary]
# Model-boundary listener — the loopback proxy for model-call economics +
# attribution. On by default (secure-by-default). Set `enabled = false` to skip
# binding the pinned loopback port and leave the agent connected directly to the
# provider. While enabled, the daemon points the agent at the listener via
# ANTHROPIC_BASE_URL — but only after a synthetic request has proven the listener
# can actually reach the provider through it — and removes it again when it stops
# or when that stops being true. So Claude Code Remote Control is disabled exactly
# while the boundary is up AND working. Opt out here, or per-install via
# `openlatch init --no-boundary`.
# enabled = true
# transforms_act = false        # allow an ACTING prefix_reorder (L-0) rule to rewrite the
#                               # forwarded request — inject cache_control breakpoints, or
#                               # move a volatile block after the stable ones. OFF by
#                               # default (Model Boundary D-28): `enabled` decides whether
#                               # OpenLatch sees the traffic, this decides whether it
#                               # changes it. Gates L-0 ONLY — history_trim and prompt_edit
#                               # stay held at `observe` whatever this is set to. On any
#                               # validation failure, error or panic the ORIGINAL bytes are
#                               # forwarded, so the worst case is the behaviour you get
#                               # with this off.
# port = 7600                   # a NON-default port makes this instance isolated:
#                               # it binds and serves but never writes or clears
#                               # ~/.claude/settings.json (that file belongs to the
#                               # daemon on the default port). Route sessions to it
#                               # with ANTHROPIC_BASE_URL=http://127.0.0.1:<port>.
# upstream = "https://api.anthropic.com"
#                               # where the listener forwards. Every model call and
#                               # every provider credential on this host goes here,
#                               # so change it only for a local harness or a
#                               # deliberate gateway. Env: OPENLATCH_BOUNDARY_UPSTREAM.
#                               # It sets the Anthropic destination; to move
#                               # Codex's too, use the table form instead:
#                               #   [boundary.upstream]
#                               #   openai-responses = "https://gw.example/v1"
#                               # A value carrying a path is the API root, so a
#                               # request's own /v1 is dropped rather than
#                               # doubled. Codex on a ChatGPT plan reaches a
#                               # different origin with no key here — setting
#                               # openai-responses overrides BOTH plans.

# [supervision]
# OS-native auto-restart (launchd / systemd-user / Task Scheduler).
# Managed by `openlatch init` and `openlatch supervision {{install|uninstall|enable|disable}}`.
# mode = "disabled"           # "active" | "deferred" | "disabled"
# backend = "none"            # "launchd" | "systemd" | "task_scheduler" | "none"
# disabled_reason = "user_opt_out"
"#
    )
}

/// Ensure the openlatch config directory and config.toml exist.
///
/// Creates `~/.openlatch/` if missing, writes `config.toml` with the default
/// template if missing, then returns the path to `config.toml`.
///
/// # Errors
///
/// Returns [`OlError`] if the directory or file cannot be created.
pub fn ensure_config(port: u16) -> Result<PathBuf, OlError> {
    let dir = openlatch_dir();
    std::fs::create_dir_all(&dir).map_err(|e| {
        OlError::new(
            ERR_INVALID_CONFIG,
            format!("Cannot create config directory '{}': {e}", dir.display()),
        )
        .with_suggestion("Check that you have write permission to your home directory.")
    })?;

    let config_path = dir.join("config.toml");
    if !config_path.exists() {
        let content = generate_default_config_toml(port);
        std::fs::write(&config_path, content).map_err(|e| {
            OlError::new(
                ERR_INVALID_CONFIG,
                format!("Cannot write config file '{}': {e}", config_path.display()),
            )
            .with_suggestion("Check that you have write permission to ~/.openlatch/.")
        })?;
    }

    Ok(config_path)
}

// ---------------------------------------------------------------------------
// Token generation and management (SEC-01)
// ---------------------------------------------------------------------------

/// Generate a cryptographically random 64-character hex token.
///
/// Uses two UUIDv4 values (each 16 bytes of OS CSPRNG entropy via `getrandom`)
/// concatenated to produce 32 bytes = 64 hex characters. No additional
/// dependencies are needed since `uuid` with the `v4` feature already pulls
/// in `getrandom` which maps to the OS CSPRNG on all platforms.
///
/// # Security
///
/// The resulting string is suitable as a bearer token for daemon authentication.
/// The `uuid` crate uses `getrandom` internally, which calls `BCryptGenRandom`
/// on Windows and `getrandom(2)` / `/dev/urandom` on Unix.
pub fn generate_token() -> String {
    let a = uuid::Uuid::new_v4();
    let b = uuid::Uuid::new_v4();
    format!("{}{}", a.simple(), b.simple())
}

/// Ensure a daemon bearer token exists at `{dir}/daemon.token`.
///
/// If the token file already exists, reads and returns the existing token.
/// If it does not exist, generates a new token, writes it to the file with
/// restricted permissions (mode 0600 on Unix), and returns the new token.
///
/// # Errors
///
/// Returns [`OlError`] if the token file cannot be read or written.
///
/// # Security (SEC-01)
///
/// The token file is set to mode 0600 on Unix (user read/write only).
/// On Windows, the file is written to the user's AppData directory which is
/// already restricted to the current user by default ACLs.
pub fn ensure_token(dir: &Path) -> Result<String, OlError> {
    let token_path = dir.join("daemon.token");

    if token_path.exists() {
        // Read existing token
        let token = std::fs::read_to_string(&token_path).map_err(|e| {
            OlError::new(
                crate::error::ERR_INVALID_CONFIG,
                format!("Cannot read token file '{}': {e}", token_path.display()),
            )
            .with_suggestion("Check that the file exists and is readable.")
        })?;
        return Ok(token.trim().to_string());
    }

    // Generate and write new token — ensure parent directory exists first
    let token = generate_token();
    if let Some(parent) = token_path.parent() {
        std::fs::create_dir_all(parent).map_err(|e| {
            OlError::new(
                crate::error::ERR_INVALID_CONFIG,
                format!("Cannot create directory '{}': {e}", parent.display()),
            )
            .with_suggestion("Check that you have write permission to the parent directory.")
        })?;
    }
    std::fs::write(&token_path, &token).map_err(|e| {
        OlError::new(
            crate::error::ERR_INVALID_CONFIG,
            format!("Cannot write token file '{}': {e}", token_path.display()),
        )
        .with_suggestion("Check that you have write permission to the openlatch directory.")
    })?;

    // SECURITY: restrict the token file to its owner on every platform.
    //
    // This used to be Unix-only, on the rationale that AppData is already
    // ACL-restricted — true of the default directory, false as soon as
    // `OPENLATCH_DIR` moves the token somewhere with an inherited `Users` ACE.
    crate::fs_secure::restrict_to_owner(&token_path).map_err(|e| {
        OlError::new(
            crate::error::ERR_INVALID_CONFIG,
            format!("Cannot set permissions on token file: {e}"),
        )
        .with_suggestion("Check that you have permission to modify file attributes.")
    })?;

    Ok(token)
}

// ---------------------------------------------------------------------------
// Agent ID generation and management (D-11, CONF-03)
// ---------------------------------------------------------------------------

/// Ensure a machine identifier exists in `[daemon].agent_id` within `config_path`.
///
/// On first call: generates `agt_<uuid_simple>`, inserts it into the config file
/// (preserving all other content), and returns the new ID.
///
/// On subsequent calls: reads the existing ID and returns it unchanged (idempotent).
///
/// # Format
///
/// `agt_` prefix + 32 lowercase hex digits (UUID v4 simple format, no hyphens).
/// Example: `agt_550e8400e29b41d4a716446655440000`
///
/// # Errors
///
/// Returns [`OlError`] if the config file cannot be read or written.
pub fn ensure_agent_id(config_path: &Path) -> Result<String, OlError> {
    // Read and parse the existing file
    let raw = std::fs::read_to_string(config_path).map_err(|e| {
        OlError::new(
            crate::error::ERR_INVALID_CONFIG,
            format!("Cannot read config file '{}': {e}", config_path.display()),
        )
        .with_suggestion("Check that the file exists and is readable.")
    })?;

    let toml_cfg: TomlConfig = toml::from_str(&raw).map_err(|e| {
        OlError::new(
            crate::error::ERR_INVALID_CONFIG,
            format!("Invalid TOML in config file: {e}"),
        )
        .with_suggestion("Check your config.toml for syntax errors.")
    })?;

    // If agent_id already exists, return it (idempotent)
    if let Some(ref daemon) = toml_cfg.daemon {
        if let Some(ref existing_id) = daemon.agent_id {
            return Ok(existing_id.clone());
        }
    }

    // Generate new agent_id
    let new_id = format!("agt_{}", uuid::Uuid::new_v4().simple());

    // Insert agent_id into the raw config string, preserving all other content.
    // Strategy: find [daemon] section, insert agent_id line after port line (or
    // after [daemon] header if no port line is present). If no [daemon] section,
    // append one.
    let updated_raw = insert_agent_id_into_toml(&raw, &new_id);

    std::fs::write(config_path, &updated_raw).map_err(|e| {
        OlError::new(
            crate::error::ERR_INVALID_CONFIG,
            format!("Cannot write config file '{}': {e}", config_path.display()),
        )
        .with_suggestion("Check that you have write permission to ~/.openlatch/.")
    })?;

    Ok(new_id)
}

/// Insert `agent_id = "..."` into TOML raw string, preserving all other content.
///
/// Finds the `[daemon]` section and inserts the agent_id line after the `port =`
/// line (or directly after `[daemon]` if no port line exists). If no `[daemon]`
/// section exists, appends one to the end.
fn insert_agent_id_into_toml(raw: &str, agent_id: &str) -> String {
    let agent_id_line = format!("agent_id = \"{agent_id}\"");

    // Find [daemon] section — look for a line that is exactly "[daemon]"
    let daemon_header_pos = raw
        .lines()
        .enumerate()
        .find(|(_, line)| line.trim() == "[daemon]")
        .map(|(idx, _)| idx);

    match daemon_header_pos {
        Some(daemon_idx) => {
            // [daemon] section found — find the best insertion point
            // Look for the last non-empty, non-comment line within the [daemon] section
            // (before the next section header or end of file)
            let lines: Vec<&str> = raw.lines().collect();
            let insert_after = find_insert_position(&lines, daemon_idx);

            // Rebuild the string with the new line inserted
            let mut result = String::with_capacity(raw.len() + agent_id_line.len() + 1);
            for (i, line) in lines.iter().enumerate() {
                result.push_str(line);
                result.push('\n');
                if i == insert_after {
                    result.push_str(&agent_id_line);
                    result.push('\n');
                }
            }
            result
        }
        None => {
            // No [daemon] section — append one
            let mut result = raw.to_string();
            if !result.ends_with('\n') {
                result.push('\n');
            }
            result.push_str("\n[daemon]\n");
            result.push_str(&agent_id_line);
            result.push('\n');
            result
        }
    }
}

/// Find the line index after which to insert agent_id within a [daemon] section.
///
/// Prefers inserting after `port = ...` if present; otherwise inserts after the
/// `[daemon]` header line itself.
fn find_insert_position(lines: &[&str], daemon_header_idx: usize) -> usize {
    // Walk forward from [daemon] header to find port line or next section
    let mut best = daemon_header_idx;
    for (i, line) in lines.iter().enumerate().skip(daemon_header_idx + 1) {
        let trimmed = line.trim();
        // Stop at next section header
        if trimmed.starts_with('[') {
            break;
        }
        // Track port line as best insertion point
        if trimmed.starts_with("port") {
            best = i;
            break;
        }
    }
    best
}

// ---------------------------------------------------------------------------
// Supervision state persistence
// ---------------------------------------------------------------------------

/// Persist supervision state into the `[supervision]` section of `config.toml`.
///
/// Updates (or creates) the section atomically via write-tmp + rename. Existing
/// content outside `[supervision]` is preserved.
///
/// # Arguments
///
/// - `config_path`: absolute path to `~/.openlatch/config.toml`.
/// - `mode`: `active`, `deferred`, or `disabled`.
/// - `backend`: `launchd`, `systemd`, `task_scheduler`, or `none`.
/// - `disabled_reason`: free-form reason (e.g., `user_opt_out`,
///   `foreground_session`, `headless_install_no_gui`).
pub fn persist_supervision_state(
    config_path: &Path,
    mode: &crate::supervision::SupervisionMode,
    backend: &crate::supervision::SupervisorKind,
    disabled_reason: Option<&str>,
) -> Result<(), OlError> {
    let mode_str = match mode {
        crate::supervision::SupervisionMode::Active => "active",
        crate::supervision::SupervisionMode::Deferred => "deferred",
        crate::supervision::SupervisionMode::Disabled => "disabled",
    };
    let backend_str = match backend {
        crate::supervision::SupervisorKind::Launchd => "launchd",
        crate::supervision::SupervisorKind::Systemd => "systemd",
        crate::supervision::SupervisorKind::TaskScheduler => "task_scheduler",
        crate::supervision::SupervisorKind::None => "none",
    };

    // Ensure config.toml exists so we have something to edit.
    if !config_path.exists() {
        if let Some(parent) = config_path.parent() {
            std::fs::create_dir_all(parent).map_err(|e| {
                OlError::new(
                    ERR_INVALID_CONFIG,
                    format!("Cannot create config directory: {e}"),
                )
            })?;
        }
        std::fs::write(config_path, "").map_err(|e| {
            OlError::new(
                ERR_INVALID_CONFIG,
                format!("Cannot create config file: {e}"),
            )
        })?;
    }

    let raw = std::fs::read_to_string(config_path).map_err(|e| {
        OlError::new(
            ERR_INVALID_CONFIG,
            format!("Cannot read config file '{}': {e}", config_path.display()),
        )
    })?;

    let new_raw = rewrite_supervision_section(&raw, mode_str, backend_str, disabled_reason);

    // Atomic write: tmp + rename.
    let tmp_path = config_path.with_extension("toml.tmp");
    std::fs::write(&tmp_path, &new_raw)
        .map_err(|e| OlError::new(ERR_INVALID_CONFIG, format!("Cannot write config tmp: {e}")))?;
    std::fs::rename(&tmp_path, config_path)
        .map_err(|e| OlError::new(ERR_INVALID_CONFIG, format!("Cannot rename config tmp: {e}")))?;

    Ok(())
}

/// Rewrite (or insert) the `[supervision]` section of a TOML string.
///
/// Finds an existing `[supervision]` header (preserving both commented and
/// uncommented forms) and replaces the block up to the next section header.
/// If absent, appends a fresh section.
fn rewrite_supervision_section(
    raw: &str,
    mode: &str,
    backend: &str,
    disabled_reason: Option<&str>,
) -> String {
    let mut block = String::new();
    block.push_str("[supervision]\n");
    block.push_str(&format!("mode = \"{mode}\"\n"));
    block.push_str(&format!("backend = \"{backend}\"\n"));
    if let Some(reason) = disabled_reason {
        block.push_str(&format!("disabled_reason = \"{reason}\"\n"));
    }

    let lines: Vec<&str> = raw.lines().collect();
    let mut header_idx: Option<usize> = None;
    for (i, line) in lines.iter().enumerate() {
        let trimmed = line.trim();
        if trimmed == "[supervision]" || trimmed == "# [supervision]" {
            header_idx = Some(i);
            break;
        }
    }

    match header_idx {
        Some(start) => {
            // Find the next section header (uncommented) to know where to stop.
            let mut end = lines.len();
            for (i, line) in lines.iter().enumerate().skip(start + 1) {
                let trimmed = line.trim();
                if trimmed.starts_with('[') && !trimmed.starts_with("[supervision]") {
                    end = i;
                    break;
                }
            }
            let mut result = String::new();
            for line in lines.iter().take(start) {
                result.push_str(line);
                result.push('\n');
            }
            result.push_str(&block);
            for line in lines.iter().skip(end) {
                result.push_str(line);
                result.push('\n');
            }
            result
        }
        None => {
            let mut result = raw.to_string();
            if !result.is_empty() && !result.ends_with('\n') {
                result.push('\n');
            }
            if !result.is_empty() {
                result.push('\n');
            }
            result.push_str(&block);
            result
        }
    }
}

/// Persist `[cloud] api_url` into `config.toml`, preserving everything else.
///
/// The default template ships every `[cloud]` field commented out, which means
/// an untouched install silently forwards to the compiled-in production origin
/// — there was previously no command that could point the client at a
/// self-hosted or local platform, only a hand edit or an `OPENLATCH_API_URL`
/// export that vanishes with the shell. `openlatch init --api-url` writes it
/// once, here.
///
/// Surgical by design, exactly like [`ensure_agent_id`] and
/// [`persist_supervision_state`]: the `[cloud]` section is the only thing
/// touched, and every other section — including hand-written
/// `[privacy] extra_patterns` — survives verbatim. Written atomically via
/// tmp + rename.
pub fn persist_api_url(config_path: &Path, api_url: &str) -> Result<(), OlError> {
    let raw = std::fs::read_to_string(config_path).map_err(|e| {
        OlError::new(
            ERR_INVALID_CONFIG,
            format!("Cannot read config file '{}': {e}", config_path.display()),
        )
        .with_suggestion("Run 'openlatch init' first to create it.")
    })?;

    let new_raw = set_cloud_api_url(&raw, api_url);

    let tmp_path = config_path.with_extension("toml.tmp");
    std::fs::write(&tmp_path, &new_raw)
        .map_err(|e| OlError::new(ERR_INVALID_CONFIG, format!("Cannot write config tmp: {e}")))?;
    std::fs::rename(&tmp_path, config_path)
        .map_err(|e| OlError::new(ERR_INVALID_CONFIG, format!("Cannot rename config tmp: {e}")))?;

    Ok(())
}

/// Set `api_url` inside the `[cloud]` section of a TOML string.
///
/// Three cases, in order:
///
/// 1. An active `[cloud]` section exists — replace an existing active
///    `api_url` line in it, or insert one directly under the header.
/// 2. Only the commented `# [cloud]` template block exists — activate the
///    header and the `api_url` line in place, leaving the rest of the block
///    commented so the template still documents the other knobs.
/// 3. Neither exists — append a fresh `[cloud]` section.
fn set_cloud_api_url(raw: &str, api_url: &str) -> String {
    set_section_key(raw, "cloud", "api_url", &format!("\"{api_url}\""))
}

/// Set `key = value` inside `[section]` of a TOML string, preserving comments
/// and the shipped template's layout.
///
/// Three cases, in order:
///
/// 1. An active `[section]` exists — replace an existing active `key` line in
///    it, or insert one directly under the header.
/// 2. Only the commented `# [section]` template block exists — activate the
///    header and the `key` line in place, leaving the rest of the block
///    commented so the template still documents the other knobs.
/// 3. Neither exists — append a fresh `[section]`.
///
/// `value` is inserted verbatim, so string values must arrive already quoted.
fn set_section_key(raw: &str, section: &str, key: &str, value: &str) -> String {
    let is_key = |line: &str| {
        line.trim()
            .trim_start_matches('#')
            .trim_start()
            .starts_with(key)
    };

    let header = format!("[{section}]");
    let commented_header = format!("# [{section}]");
    let key_line = format!("{key} = {value}");
    let lines: Vec<&str> = raw.lines().collect();

    // An ACTIVE header wins over the commented template, wherever each sits.
    //
    // Taking the first match of either kind meant that a config carrying both
    // — the shipped template's `# [boundary]` near the top and a real
    // `[boundary]` appended later, which is what hand-editing produces — got
    // the template uncommented while the real section stayed put. The file then
    // held two `[boundary]` headers and every subsequent load died on TOML's
    // duplicate-key error, from a command whose whole job was to flip one
    // boolean.
    let Some(start) = lines
        .iter()
        .position(|l| l.trim() == header)
        .or_else(|| lines.iter().position(|l| l.trim() == commented_header))
    else {
        // Case 3 — append a fresh section.
        let mut result = raw.to_string();
        if !result.is_empty() && !result.ends_with('\n') {
            result.push('\n');
        }
        result.push('\n');
        result.push_str(&header);
        result.push('\n');
        result.push_str(&key_line);
        result.push('\n');
        return result;
    };

    // The body runs to the next ACTIVE section header. A commented
    // `# [policy]` must not end it: in the shipped template the entire tail is
    // commented, so honouring commented headers would truncate at the first.
    let end = lines
        .iter()
        .enumerate()
        .skip(start + 1)
        .find(|(_, l)| {
            let t = l.trim();
            t.starts_with('[') && t != header
        })
        .map_or(lines.len(), |(i, _)| i);

    let body = &lines[start + 1..end];
    let mut out: Vec<String> = lines[..start].iter().map(|l| (*l).to_string()).collect();
    out.push(header);
    if !body.iter().any(|l| is_key(l)) {
        out.push(key_line.clone());
    }
    let mut written = false;
    for line in body {
        if is_key(line) {
            // Replace the first occurrence; drop any later one, which would
            // otherwise shadow ours under TOML's last-key-wins parsing.
            if !written {
                out.push(key_line.clone());
                written = true;
            }
            continue;
        }
        out.push((*line).to_string());
    }
    out.extend(lines[end..].iter().map(|l| (*l).to_string()));

    let mut result = out.join("\n");
    result.push('\n');
    result
}

/// Persist `[boundary] enabled` to `config.toml`.
///
/// `init --no-boundary` used to be read in exactly one place — inside the
/// `--foreground` branch — while the background paths, which are the default,
/// passed no boundary intent at all. The spawned daemon read `[boundary]
/// enabled` from config and bound anyway, then wrote `ANTHROPIC_BASE_URL` into
/// settings.json. The documented opt-out ("keep the agent connected directly to
/// the provider") therefore did nothing unless you also passed `--foreground`.
///
/// The opt-out is persisted rather than passed down because a one-shot flag
/// cannot hold: `init` installs OS supervision by default, so the supervisor
/// would restart a daemon that binds the boundary at the next boot regardless.
/// Config is the only place the intent survives.
///
/// # Errors
///
/// Returns `OL-1300` if the config file cannot be read, written, or replaced.
pub fn persist_boundary_enabled(config_path: &Path, enabled: bool) -> Result<(), OlError> {
    let raw = std::fs::read_to_string(config_path).map_err(|e| {
        OlError::new(
            ERR_INVALID_CONFIG,
            format!("Cannot read config file '{}': {e}", config_path.display()),
        )
        .with_suggestion("Run 'openlatch init' first to create it.")
    })?;

    let new_raw = set_section_key(&raw, "boundary", "enabled", &enabled.to_string());

    let tmp_path = config_path.with_extension("toml.tmp");
    std::fs::write(&tmp_path, &new_raw)
        .map_err(|e| OlError::new(ERR_INVALID_CONFIG, format!("Cannot write config tmp: {e}")))?;
    std::fs::rename(&tmp_path, config_path)
        .map_err(|e| OlError::new(ERR_INVALID_CONFIG, format!("Cannot rename config tmp: {e}")))?;

    Ok(())
}

/// Persist a batch of `[proxy]` keys into `config.toml`, preserving everything else.
///
/// The first multi-key persister in this file, and the first one that can *remove* a key.
/// Both are forced by the frozen contract rather than chosen: a proxy write is never one
/// key (`url` and `source` always move together; the prompt writes `mode` and `source`),
/// and the static→PAC transition has to leave `url` **absent** — a PAC-sourced route is
/// re-evaluated per destination, so a stale concrete `url` left behind would be used as a
/// static route by the next process that read it.
///
/// `sets` values arrive **pre-quoted**, exactly like [`set_section_key`]: the caller knows
/// which of its values are TOML strings and which are bare booleans.
///
/// One read, one write: every key is applied to an in-memory string and the file is
/// replaced once, atomically via tmp + rename. Applying them one file-write at a time
/// would leave `url` written and `source` not if the process died between them, which is
/// the one intermediate state that misattributes provenance.
///
/// # Errors
///
/// Returns `OL-1300` if the config file cannot be read, written, or replaced.
pub fn persist_proxy_config(
    config_path: &Path,
    sets: &[(&str, String)],
    removes: &[&str],
) -> Result<(), OlError> {
    let raw = std::fs::read_to_string(config_path).map_err(|e| {
        OlError::new(
            ERR_INVALID_CONFIG,
            format!("Cannot read config file '{}': {e}", config_path.display()),
        )
        .with_suggestion("Run 'openlatch init' first to create it.")
    })?;

    let mut new_raw = raw;
    for (key, value) in sets {
        new_raw = set_section_key(&new_raw, "proxy", key, value);
    }
    for key in removes {
        new_raw = remove_section_key(&new_raw, "proxy", key);
    }

    let tmp_path = config_path.with_extension("toml.tmp");
    std::fs::write(&tmp_path, &new_raw)
        .map_err(|e| OlError::new(ERR_INVALID_CONFIG, format!("Cannot write config tmp: {e}")))?;
    std::fs::rename(&tmp_path, config_path)
        .map_err(|e| OlError::new(ERR_INVALID_CONFIG, format!("Cannot rename config tmp: {e}")))?;

    Ok(())
}

/// Delete every active `key = …` line from `[section]`, leaving the rest byte-for-byte.
///
/// The removal sibling of [`set_section_key`], and deliberately its mirror image: same
/// active-header-wins rule, same "a commented `# [policy]` does not end the body" rule,
/// same trailing newline. A key that is absent, or a section that does not exist, is a
/// no-op rather than an error — removal is idempotent by nature, and `proxy clear` runs
/// on configs that never had a `url`.
///
/// **Commented lines survive.** The shipped template documents `[proxy]`'s knobs as
/// comments; deleting `# url = "..."` would silently strip the documentation the operator
/// reads to set it again.
fn remove_section_key(raw: &str, section: &str, key: &str) -> String {
    let header = format!("[{section}]");
    let lines: Vec<&str> = raw.lines().collect();

    // Only an ACTIVE header can hold an active key. A purely commented template block has
    // nothing to remove, and uncommenting it here to delete a line would be a strange way
    // to spend a write.
    let Some(start) = lines.iter().position(|l| l.trim() == header) else {
        return raw.to_string();
    };

    let end = lines
        .iter()
        .enumerate()
        .skip(start + 1)
        .find(|(_, l)| {
            let t = l.trim();
            t.starts_with('[') && t != header
        })
        .map_or(lines.len(), |(i, _)| i);

    let is_active_key = |line: &str| {
        let t = line.trim();
        if t.starts_with('#') {
            return false;
        }
        match t.split_once('=') {
            Some((name, _)) => name.trim() == key,
            None => false,
        }
    };

    let mut out: Vec<String> = Vec::with_capacity(lines.len());
    for (i, line) in lines.iter().enumerate() {
        if i > start && i < end && is_active_key(line) {
            continue;
        }
        out.push((*line).to_string());
    }

    let mut result = out.join("\n");
    result.push('\n');
    result
}

// ---------------------------------------------------------------------------
// Port probing and port file (PRD: probe 7443-7543 on first init)
// ---------------------------------------------------------------------------

/// Default port range start for probing.
pub const PORT_RANGE_START: u16 = 7443;
/// Default port range end for probing (inclusive).
pub const PORT_RANGE_END: u16 = 7543;

/// Lowest port `OPENLATCH_PORT` will accept — the top of the privileged range.
pub const MIN_USER_PORT: u16 = 1024;

/// Parse an `OPENLATCH_PORT` value, enforcing the range the error message has
/// always advertised.
///
/// The parse used to be a bare `u16::from_str`, so `0` passed while the
/// suggestion on the very same code path promised "an integer between 1024 and
/// 65535". `0` is not a harmless out-of-range value: the daemon binds an
/// ephemeral port, `daemon.port` and all 12 hook entries are rewritten with
/// `0`, and `doctor`'s cross-check then compares `0` against `0` and reports
/// OK. Worse, `OPENLATCH_PORT` lives in the agent's settings.json `env` block,
/// so every `openlatch` command run from inside an agent session inherits it —
/// a bad value poisons the very CLI you would use to fix it.
///
/// # Errors
///
/// Returns `OL-1300` for anything that is not an integer in `1024..=65535`.
pub fn parse_port_env(value: &str) -> Result<u16, OlError> {
    let invalid = || {
        OlError::new(
            ERR_INVALID_CONFIG,
            format!("OPENLATCH_PORT is not a valid port number: '{value}'"),
        )
        .with_suggestion(format!(
            "Set OPENLATCH_PORT to an integer between {MIN_USER_PORT} and {}.",
            u16::MAX
        ))
    };
    let port: u16 = value.trim().parse().map_err(|_| invalid())?;
    if port < MIN_USER_PORT {
        return Err(invalid());
    }
    Ok(port)
}

/// Probe ports in the given range, returning the first available port.
///
/// Uses a sync `std::net::TcpListener` bind-and-drop to test availability.
/// Safe to call before any async runtime is started.
///
/// # Errors
///
/// Returns `OL-1500` if no port in the range is free.
pub fn probe_free_port(start: u16, end: u16) -> Result<u16, OlError> {
    for port in start..=end {
        if std::net::TcpListener::bind(("127.0.0.1", port)).is_ok() {
            return Ok(port);
        }
    }
    Err(OlError::new(
        ERR_PORT_IN_USE,
        format!("No free port found in range {start}-{end}"),
    )
    .with_suggestion(format!(
        "Free a port in the {start}-{end} range, or set OPENLATCH_PORT to a specific port."
    ))
    .with_docs("https://docs.openlatch.ai/errors/OL-1500"))
}

/// Write the daemon's port number to `~/.openlatch/daemon.port`.
///
/// Plain text file containing just the port number. Readable by the hook binary
/// without TOML parsing.
pub fn write_port_file(port: u16) -> Result<(), OlError> {
    let path = openlatch_dir().join("daemon.port");
    std::fs::write(&path, port.to_string()).map_err(|e| {
        OlError::new(
            ERR_INVALID_CONFIG,
            format!("Cannot write port file '{}': {e}", path.display()),
        )
    })?;
    Ok(())
}

/// Read the daemon's port from `~/.openlatch/daemon.port`.
///
/// Returns `None` if the file doesn't exist or can't be parsed.
pub fn read_port_file() -> Option<u16> {
    let path = openlatch_dir().join("daemon.port");
    std::fs::read_to_string(path)
        .ok()?
        .trim()
        .parse::<u16>()
        .ok()
}

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

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

    #[test]
    fn test_config_defaults_values() {
        // Test 1: Config::defaults() returns expected values
        let cfg = Config::defaults();
        assert_eq!(cfg.port, 7443, "Default port must be 7443");
        assert_eq!(cfg.log_level, "info", "Default log level must be info");
        assert_eq!(cfg.retention_days, 30, "Default retention must be 30 days");
    }

    #[test]
    fn test_config_loads_from_toml_file() {
        // Test 2: Config loads from a TOML file in a temp directory
        let tmp = TempDir::new().unwrap();
        let config_path = tmp.path().join("config.toml");
        std::fs::write(
            &config_path,
            r#"
[daemon]
port = 8080
"#,
        )
        .unwrap();

        // Write a minimal config to the openlatch dir location by overriding
        // via env var (since Config::load reads from openlatch_dir())
        // We'll test the TOML parsing logic directly via env override
        // and by placing the file at the expected path.

        // Directly test the TOML parse path:
        let raw = std::fs::read_to_string(&config_path).unwrap();
        let toml_cfg: TomlConfig = toml::from_str(&raw).unwrap();
        let daemon = toml_cfg.daemon.unwrap();
        assert_eq!(daemon.port, Some(8080));
    }

    /// `OPENLATCH_PORT=0` used to parse, and the damage was not confined to a
    /// bad value: the daemon bound an ephemeral port, `install_hooks` pinned
    /// `"0"` into all 12 hook entries, and `doctor` then compared `0` against
    /// `0` and reported OK. Because the var lives in the agent's settings.json
    /// `env` block, every `openlatch` command run from inside a session
    /// inherited it — the CLI you would use to fix it was poisoned too.
    #[test]
    fn parse_port_env_rejects_zero_and_the_privileged_range() {
        for bad in ["0", "1", "1023", "-1", "70000", "", "  ", "7443x"] {
            let err = parse_port_env(bad)
                .expect_err("must reject {bad}: the suggestion promises 1024..=65535");
            assert_eq!(err.code, ERR_INVALID_CONFIG, "input {bad:?}");
        }
    }

    #[test]
    fn parse_port_env_accepts_the_range_it_advertises() {
        assert_eq!(parse_port_env("1024").unwrap(), 1024);
        assert_eq!(parse_port_env("7443").unwrap(), PORT_RANGE_START);
        assert_eq!(parse_port_env(" 7543 ").unwrap(), PORT_RANGE_END);
        assert_eq!(parse_port_env("65535").unwrap(), u16::MAX);
    }

    /// `--no-boundary` has to survive being read back, because that is the only
    /// way the opt-out reaches the background daemon — and the OS supervisor's
    /// restart after it.
    #[test]
    fn persist_boundary_enabled_activates_the_commented_template_block() {
        let dir = TempDir::new().unwrap();
        let config_path = dir.path().join("config.toml");
        // The shipped template ships the whole section commented out.
        std::fs::write(
            &config_path,
            "[daemon]\nport = 7443\n\n# [boundary]\n# Model-boundary listener.\n# enabled = true\n# port = 7600\n",
        )
        .unwrap();

        persist_boundary_enabled(&config_path, false).unwrap();

        let raw = std::fs::read_to_string(&config_path).unwrap();
        let parsed: TomlConfig = toml::from_str(&raw).expect("still valid TOML");
        assert_eq!(parsed.boundary.unwrap().enabled, Some(false));
        // The rest of the template stays commented so it keeps documenting the
        // other knobs.
        assert!(raw.contains("# port = 7600"), "template preserved: {raw}");
    }

    #[test]
    fn wiring_ownership_is_explicit_never_inferred_from_the_agent_dir() {
        // The rule an isolated instance depends on, and the shortcut it must
        // not take. `$CLAUDE_CONFIG_DIR` is also how someone relocates their
        // single real agent config — inferring ownership from its presence
        // would hand one shared file to every daemon on such a host.
        let default_port = crate::boundary::default_boundary_port();

        let canonical = BoundaryConfig::default();
        assert!(
            canonical.owns_agent_wiring(),
            "the daemon on the default port is the canonical owner"
        );

        let isolated = BoundaryConfig {
            port: default_port.wrapping_add(1),
            ..BoundaryConfig::default()
        };
        assert!(
            !isolated.owns_agent_wiring(),
            "a non-default port does not own the machine-global config"
        );

        let opted_out = BoundaryConfig {
            own_agent_wiring: Some(false),
            ..BoundaryConfig::default()
        };
        assert!(
            !opted_out.owns_agent_wiring(),
            "an explicit false wins even on the default port"
        );
    }

    #[test]
    fn cloud_cannot_be_switched_off_from_config() {
        // D-6 / AC-CLOUD-01. The key still parses — an existing config.toml
        // carrying it must keep loading — but it decides nothing. A client that
        // captures events and forwards them nowhere is a log rotator.
        let dir = tempfile::tempdir().unwrap();
        let config_path = dir.path().join("config.toml");
        std::fs::write(
            &config_path,
            "[daemon]\nport = 7443\n\n[cloud]\nenabled = false\napi_url = \"http://example.test\"\n",
        )
        .unwrap();

        let _guard = BATCH_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let previous = std::env::var("OPENLATCH_DIR").ok();
        std::env::set_var("OPENLATCH_DIR", dir.path());
        let loaded = Config::load(None, None, false);
        match previous {
            Some(v) => std::env::set_var("OPENLATCH_DIR", v),
            None => std::env::remove_var("OPENLATCH_DIR"),
        }

        let cfg = loaded.expect("a config with the retired key must still load");
        assert!(
            cfg.cloud.enabled,
            "[cloud] enabled = false must be ignored, not honoured"
        );
        assert_eq!(
            cfg.cloud.api_url, "http://example.test",
            "the rest of the [cloud] block still applies"
        );
    }

    #[test]
    fn persist_boundary_enabled_updates_the_active_block_not_the_template() {
        // The shape a hand-edit leaves behind: the shipped commented template
        // AND a real section appended below it. Activating the template would
        // produce two `[boundary]` headers and a config that no longer parses.
        let dir = tempfile::tempdir().unwrap();
        let config_path = dir.path().join("config.toml");
        std::fs::write(
            &config_path,
            "[daemon]\nport = 7443\n\n# [boundary]\n# enabled = true\n\n[boundary]\nenabled = false\n",
        )
        .unwrap();

        persist_boundary_enabled(&config_path, true).unwrap();

        let raw = std::fs::read_to_string(&config_path).unwrap();
        assert_eq!(
            raw.lines().filter(|l| l.trim() == "[boundary]").count(),
            1,
            "exactly one active [boundary] header must survive:\n{raw}"
        );
        let parsed: toml::Value = toml::from_str(&raw).expect("config must still parse");
        assert_eq!(
            parsed["boundary"]["enabled"].as_bool(),
            Some(true),
            "the active block is the one that was updated:\n{raw}"
        );
    }

    #[test]
    fn persist_boundary_enabled_replaces_an_active_value() {
        let dir = TempDir::new().unwrap();
        let config_path = dir.path().join("config.toml");
        std::fs::write(&config_path, "[boundary]\nenabled = true\nport = 7600\n").unwrap();

        persist_boundary_enabled(&config_path, false).unwrap();

        let raw = std::fs::read_to_string(&config_path).unwrap();
        let parsed: TomlConfig = toml::from_str(&raw).unwrap();
        let boundary = parsed.boundary.unwrap();
        assert_eq!(boundary.enabled, Some(false));
        assert_eq!(boundary.port, Some(7600), "unrelated keys survive");
    }

    // ---- persist_proxy_config (Proxy Support I-2) --------------------------

    #[test]
    fn persist_proxy_config_writes_a_whole_route_in_one_pass() {
        let dir = TempDir::new().unwrap();
        let config_path = dir.path().join("config.toml");
        std::fs::write(&config_path, "[daemon]\nport = 7443\n").unwrap();

        persist_proxy_config(
            &config_path,
            &[
                ("url", "\"http://proxy.corp:8080\"".to_string()),
                ("source", "\"windows\"".to_string()),
            ],
            &[],
        )
        .unwrap();

        let raw = std::fs::read_to_string(&config_path).unwrap();
        let parsed: TomlConfig = toml::from_str(&raw).unwrap();
        let proxy = parsed.proxy.unwrap();
        assert_eq!(proxy.url.as_deref(), Some("http://proxy.corp:8080"));
        assert_eq!(proxy.source.as_deref(), Some("windows"));
        assert_eq!(
            parsed.daemon.and_then(|d| d.port),
            Some(7443),
            "a neighbouring section must survive"
        );
    }

    /// The static→PAC transition, and the reason a removal primitive had to exist at all.
    ///
    /// A PAC route materialises no URL — the script answers per destination — so a
    /// concrete `url` left over from a previous static win is read by the very next
    /// process as a static route, and the script is never consulted again.
    #[test]
    fn persist_proxy_config_removes_a_stale_url_on_the_pac_transition() {
        let dir = TempDir::new().unwrap();
        let config_path = dir.path().join("config.toml");
        std::fs::write(
            &config_path,
            "[proxy]\nurl = \"http://old-static:8080\"\nsource = \"windows\"\nno_proxy = \"internal.corp\"\n",
        )
        .unwrap();

        persist_proxy_config(
            &config_path,
            &[("source", "\"wpad\"".to_string())],
            &["url"],
        )
        .unwrap();

        let raw = std::fs::read_to_string(&config_path).unwrap();
        assert!(
            !raw.contains("url = \"http://old-static"),
            "the stale route must be gone, not merely overwritten:\n{raw}"
        );
        let parsed: TomlConfig = toml::from_str(&raw).unwrap();
        let proxy = parsed.proxy.unwrap();
        assert_eq!(proxy.url, None, "the key must be ABSENT, not empty");
        assert_eq!(proxy.source.as_deref(), Some("wpad"));
        assert_eq!(
            proxy.no_proxy.as_deref(),
            Some("internal.corp"),
            "an unrelated key in the same section survives"
        );
    }

    /// `proxy clear`: direct, and nothing left pointing anywhere.
    #[test]
    fn persist_proxy_config_clears_a_route_completely() {
        let dir = TempDir::new().unwrap();
        let config_path = dir.path().join("config.toml");
        std::fs::write(
            &config_path,
            "[proxy]\nmode = \"manual\"\nurl = \"http://p:8080\"\nsource = \"manual\"\nusername = \"svc\"\n",
        )
        .unwrap();

        persist_proxy_config(
            &config_path,
            &[("mode", "\"direct\"".to_string())],
            &["url", "source", "pac_url", "username"],
        )
        .unwrap();

        let parsed: TomlConfig =
            toml::from_str(&std::fs::read_to_string(&config_path).unwrap()).unwrap();
        let proxy = parsed.proxy.unwrap();
        assert_eq!(proxy.mode.as_deref(), Some("direct"));
        assert_eq!(proxy.url, None);
        assert_eq!(proxy.source, None);
        assert_eq!(proxy.username, None);
    }

    /// Removing a key that is not there, from a section that is not there, is a no-op.
    /// `proxy clear` runs on configs that never had a route.
    #[test]
    fn removing_an_absent_key_changes_nothing() {
        let raw = "[daemon]\nport = 7443\n";
        assert_eq!(remove_section_key(raw, "proxy", "url"), raw);
        assert_eq!(
            remove_section_key("[proxy]\nsource = \"env\"\n", "proxy", "url"),
            "[proxy]\nsource = \"env\"\n"
        );
    }

    /// The shipped template documents `[proxy]`'s knobs as comments. Deleting
    /// `# url = "..."` would strip the documentation an operator reads to set it again.
    #[test]
    fn removal_leaves_commented_lines_alone() {
        let raw = "[proxy]\n# url = \"http://proxy.corp:8080\"\nurl = \"http://real:8080\"\n";
        let out = remove_section_key(raw, "proxy", "url");
        assert!(
            out.contains("# url = "),
            "the template comment is documentation, not a value:\n{out}"
        );
        assert!(
            !out.contains("\nurl = "),
            "the active value must be gone:\n{out}"
        );
    }

    /// A removal must stop at the section boundary. `url` exists in more than one section's
    /// vocabulary, and taking the wrong one out is a silent reconfiguration.
    #[test]
    fn removal_stops_at_the_next_section() {
        let raw = "[proxy]\nurl = \"http://p:8080\"\n\n[cloud]\napi_url = \"https://app.openlatch.ai\"\nurl = \"keep\"\n";
        let out = remove_section_key(raw, "proxy", "url");
        assert!(out.contains("url = \"keep\""), "{out}");
        assert!(!out.contains("http://p:8080"), "{out}");
    }

    #[test]
    fn test_config_cli_port_overrides_default() {
        // Not setting env is only half of thread-safety: `Config::load` READS the same
        // variables the mutating tests write, so a reader without the lock can observe a
        // neighbour's value mid-test. That is how this test failed in CI with
        // "OPENLATCH_CLOUD_BATCH_MAX_EVENTS is not a valid integer: 'fifty'" -- a string it
        // never set and does not care about.
        let _guard = BATCH_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let cfg = Config::load(Some(9000), None, false)
            .expect("Config::load should succeed with valid CLI port");
        assert_eq!(cfg.port, 9000, "CLI port should override default");
    }

    #[test]
    fn test_generate_token_produces_64_char_hex() {
        // Test 4: generate_token() produces a 32-byte hex string (64 chars)
        let token = generate_token();
        assert_eq!(
            token.len(),
            64,
            "Token must be 64 characters (32 bytes hex-encoded), got: {token}"
        );
        assert!(
            token.chars().all(|c| c.is_ascii_hexdigit()),
            "Token must be hex-encoded, got: {token}"
        );
    }

    #[test]
    fn test_ensure_token_creates_and_returns_token() {
        // Test 5: ensure_token() creates token file and returns token; second call reads existing
        let tmp = TempDir::new().unwrap();

        // First call: creates the file
        let token1 = ensure_token(tmp.path()).expect("First ensure_token call should succeed");
        assert_eq!(token1.len(), 64, "Generated token must be 64 chars");
        assert!(
            tmp.path().join("daemon.token").exists(),
            "Token file must be created"
        );

        // Second call: reads the existing file
        let token2 = ensure_token(tmp.path()).expect("Second ensure_token call should succeed");
        assert_eq!(token1, token2, "Second call must return the same token");
    }

    #[cfg(unix)]
    #[test]
    fn test_ensure_token_file_has_mode_0600() {
        // Test 6: On Unix, token file has mode 0o600
        use std::os::unix::fs::PermissionsExt;

        let tmp = TempDir::new().unwrap();
        ensure_token(tmp.path()).expect("ensure_token should succeed");

        let token_path = tmp.path().join("daemon.token");
        let metadata = std::fs::metadata(&token_path).unwrap();
        let mode = metadata.permissions().mode() & 0o777;
        assert_eq!(mode, 0o600, "Token file must have mode 0600, got: {mode:o}");
    }

    #[test]
    fn test_generate_default_config_toml_format() {
        // Test 7: generate_default_config_toml() contains "# [daemon]" (commented sections)
        // and "port = 7443" as the only uncommented value
        let content = generate_default_config_toml(7443);

        assert!(
            content.contains("port = 7443"),
            "Must contain active port line: {content}"
        );
        // The [daemon] section header is present (active)
        assert!(
            content.contains("[daemon]"),
            "Must contain [daemon] section: {content}"
        );
        // All other fields are commented
        assert!(
            content.contains("# level ="),
            "level must be commented out: {content}"
        );
        assert!(
            content.contains("# retention_days ="),
            "retention_days must be commented: {content}"
        );
    }

    #[test]
    fn test_config_extra_patterns_defaults_empty() {
        // Test 8: Config::extra_patterns field exists and defaults to empty vec
        let cfg = Config::defaults();
        assert!(
            cfg.extra_patterns.is_empty(),
            "Default extra_patterns must be empty"
        );
    }

    #[test]
    fn test_probe_free_port_finds_available_port() {
        // Probe a range — at least one port should be free on any test machine
        let port = probe_free_port(PORT_RANGE_START, PORT_RANGE_END)
            .expect("should find at least one free port");
        assert!((PORT_RANGE_START..=PORT_RANGE_END).contains(&port));
    }

    #[test]
    fn test_probe_free_port_skips_occupied_port() {
        // Bind a port, then probe a range starting at that port — should skip it
        let listener =
            std::net::TcpListener::bind(("127.0.0.1", 0)).expect("should bind to random port");
        let occupied = listener.local_addr().unwrap().port();

        // Probe a 1-port range with the occupied port — must fail
        let result = probe_free_port(occupied, occupied);
        assert!(
            result.is_err(),
            "must fail when only port in range is occupied"
        );

        // Probe a 2-port range — should find the next one
        if occupied < 65535 {
            let result = probe_free_port(occupied, occupied + 1);
            assert!(result.is_ok(), "should find next port after occupied one");
            assert_eq!(result.unwrap(), occupied + 1);
        }
    }

    #[test]
    fn test_write_and_read_port_file_round_trip() {
        let tmp = TempDir::new().unwrap();
        let port_path = tmp.path().join("daemon.port");

        // Write port file to temp location (test the format, not the path logic)
        std::fs::write(&port_path, "8080").unwrap();
        let content = std::fs::read_to_string(&port_path).unwrap();
        assert_eq!(content.trim().parse::<u16>().unwrap(), 8080);
    }

    // ---------------------------------------------------------------------------
    // Task 2: agent_id tests (TDD RED → GREEN)
    // ---------------------------------------------------------------------------

    #[test]
    fn test_ensure_agent_id_creates_agt_prefixed_id() {
        // ensure_agent_id() creates agent_id starting with "agt_" followed by 32 hex chars
        let tmp = TempDir::new().unwrap();
        let config_path = tmp.path().join("config.toml");
        std::fs::write(&config_path, "[daemon]\nport = 7443\n").unwrap();

        let mid = ensure_agent_id(&config_path).expect("ensure_agent_id should succeed");
        assert!(
            mid.starts_with("agt_"),
            "agent_id must start with 'agt_': {mid}"
        );
        let hex_part = &mid[4..]; // "agt_" is 4 chars
        assert_eq!(
            hex_part.len(),
            32,
            "hex part must be 32 chars (UUID simple): {mid}"
        );
        assert!(
            hex_part.chars().all(|c| c.is_ascii_hexdigit()),
            "hex part must be hex digits: {mid}"
        );
    }

    #[test]
    fn test_ensure_agent_id_is_idempotent() {
        // Second call to ensure_agent_id() returns the same value
        let tmp = TempDir::new().unwrap();
        let config_path = tmp.path().join("config.toml");
        std::fs::write(&config_path, "[daemon]\nport = 7443\n").unwrap();

        let mid1 = ensure_agent_id(&config_path).expect("first call should succeed");
        let mid2 = ensure_agent_id(&config_path).expect("second call should succeed");
        assert_eq!(mid1, mid2, "ensure_agent_id must be idempotent");
    }

    #[test]
    fn test_ensure_agent_id_preserves_port_value() {
        // ensure_agent_id() does not overwrite existing port in [daemon]
        let tmp = TempDir::new().unwrap();
        let config_path = tmp.path().join("config.toml");
        std::fs::write(&config_path, "[daemon]\nport = 8888\n").unwrap();

        ensure_agent_id(&config_path).expect("ensure_agent_id should succeed");

        let raw = std::fs::read_to_string(&config_path).unwrap();
        assert!(
            raw.contains("port = 8888"),
            "port must be preserved after ensure_agent_id: {raw}"
        );
    }

    #[test]
    fn test_config_reads_agent_id_from_daemon_section() {
        // Config struct has agent_id field; TOML [daemon].agent_id is parsed
        let toml_str = r#"
[daemon]
port = 7443
agent_id = "agt_abcdef1234567890abcdef1234567890"
"#;
        let toml_cfg: TomlConfig = toml::from_str(toml_str).unwrap();
        let daemon = toml_cfg.daemon.unwrap();
        assert_eq!(
            daemon.agent_id.as_deref(),
            Some("agt_abcdef1234567890abcdef1234567890")
        );
    }

    // ---------------------------------------------------------------------------
    // Task 1: CloudConfig tests (TDD RED → GREEN)
    // ---------------------------------------------------------------------------

    #[test]
    fn test_cloud_config_default_values() {
        // CloudConfig::default() must return all specified defaults
        let cfg = CloudConfig::default();
        assert!(cfg.enabled, "cloud.enabled default must be true");
        assert_eq!(
            cfg.api_url, "https://app.openlatch.ai",
            "cloud.api_url default must be https://app.openlatch.ai (callers append /api/v1/...)"
        );
        assert_eq!(
            cfg.timeout_connect_ms, 5000,
            "cloud.timeout_connect_ms default must be 5000"
        );
        assert_eq!(
            cfg.timeout_total_ms, 10000,
            "cloud.timeout_total_ms default must be 10000"
        );
        assert_eq!(
            cfg.retry_delay_ms, 2000,
            "cloud.retry_delay_ms default must be 2000"
        );
        assert_eq!(
            cfg.channel_size, 1000,
            "cloud.channel_size default must be 1000"
        );
    }

    #[test]
    fn test_config_defaults_includes_cloud_config() {
        // Config::defaults() must include a cloud field with CloudConfig defaults
        let cfg = Config::defaults();
        assert!(cfg.cloud.enabled);
        assert_eq!(cfg.cloud.api_url, "https://app.openlatch.ai");
        assert_eq!(cfg.cloud.timeout_connect_ms, 5000);
        assert_eq!(cfg.cloud.timeout_total_ms, 10000);
        assert_eq!(cfg.cloud.retry_delay_ms, 2000);
        assert_eq!(cfg.cloud.channel_size, 1000);
    }

    #[test]
    fn test_config_load_no_cloud_section_returns_defaults() {
        // Shares the lock with the env-mutating cloud tests: this reads via
        // `Config::load`, and a reader of shared mutable state needs the same lock as the
        // writers.
        let _guard = BATCH_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        // Config::load() with no [cloud] section must return CloudConfig default values
        // Parse TOML with only daemon section — no cloud section
        let toml_str = r#"
[daemon]
port = 7443
"#;
        let toml_cfg: TomlConfig = toml::from_str(toml_str).unwrap();
        assert!(
            toml_cfg.cloud.is_none(),
            "TomlConfig.cloud must be None when [cloud] is absent"
        );
    }

    #[test]
    fn test_config_load_parses_all_cloud_fields() {
        // Shares the lock with the env-mutating cloud tests: this reads via
        // `Config::load`, and a reader of shared mutable state needs the same lock as the
        // writers.
        let _guard = BATCH_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        // Config::load() must parse all 7 cloud fields from [cloud] TOML section
        let toml_str = r#"
[cloud]
enabled = true
api_url = "https://custom.openlatch.ai"
timeout_connect_ms = 3000
timeout_total_ms = 8000
retry_delay_ms = 1000
channel_size = 500
"#;
        let toml_cfg: TomlConfig = toml::from_str(toml_str).unwrap();
        let cloud = toml_cfg.cloud.unwrap();
        assert_eq!(cloud.enabled, Some(true));
        assert_eq!(
            cloud.api_url.as_deref(),
            Some("https://custom.openlatch.ai")
        );
        assert_eq!(cloud.timeout_connect_ms, Some(3000));
        assert_eq!(cloud.timeout_total_ms, Some(8000));
        assert_eq!(cloud.retry_delay_ms, Some(1000));
        assert_eq!(cloud.channel_size, Some(500));
    }

    #[test]
    fn test_config_load_partial_cloud_section_merges_with_defaults() {
        // Partial [cloud] section: only provided fields overridden, rest stay at defaults
        let toml_str = r#"
[cloud]
enabled = true
api_url = "https://staging.openlatch.ai"
"#;
        let toml_cfg: TomlConfig = toml::from_str(toml_str).unwrap();
        let cloud = toml_cfg.cloud.unwrap();
        // Provided fields must be Some
        assert_eq!(cloud.enabled, Some(true));
        assert_eq!(
            cloud.api_url.as_deref(),
            Some("https://staging.openlatch.ai")
        );
        // Unprovided fields must be None (merging with defaults happens in Config::load)
        assert!(cloud.timeout_connect_ms.is_none());
    }

    // ---------------------------------------------------------------------------
    // PolicyConfig tests
    // ---------------------------------------------------------------------------

    #[test]
    fn test_policy_config_default_values() {
        let cfg = PolicyConfig::default();
        assert!(
            cfg.enabled,
            "policy.enabled MUST ship true — secure-by-default (opt out via config/env)"
        );
        assert_eq!(
            cfg.poll_interval_secs, 300,
            "policy.poll_interval_secs default must be 300"
        );
        assert_eq!(
            cfg.stale_warn_after_secs, 86_400,
            "policy.stale_warn_after_secs default must be 86400 (24 h)"
        );
    }

    #[test]
    fn test_config_defaults_includes_policy_config() {
        let cfg = Config::defaults();
        assert!(cfg.policy.enabled);
        assert_eq!(cfg.policy.poll_interval_secs, 300);
        assert_eq!(cfg.policy.stale_warn_after_secs, 86_400);
    }

    #[test]
    fn test_boundary_config_default_is_enabled() {
        // Secure-by-default: the model-boundary proxy ships on. Opt out via
        // `[boundary] enabled = false`, OPENLATCH_BOUNDARY_ENABLED=false, or
        // `openlatch init --no-boundary`.
        assert!(
            BoundaryConfig::default().enabled,
            "boundary.enabled MUST ship true — secure-by-default"
        );
        assert!(
            Config::defaults().boundary.enabled,
            "Config::defaults() must carry the enabled boundary default"
        );
    }

    #[test]
    fn test_config_load_no_policy_section_returns_defaults() {
        let toml_str = r#"
[daemon]
port = 7443
"#;
        let toml_cfg: TomlConfig = toml::from_str(toml_str).unwrap();
        assert!(
            toml_cfg.policy.is_none(),
            "TomlConfig.policy must be None when [policy] is absent"
        );
    }

    #[test]
    fn test_config_load_parses_all_policy_fields() {
        let toml_str = r#"
[policy]
enabled = true
poll_interval_secs = 60
stale_warn_after_secs = 3600
"#;
        let toml_cfg: TomlConfig = toml::from_str(toml_str).unwrap();
        let policy = toml_cfg.policy.unwrap();
        assert_eq!(policy.enabled, Some(true));
        assert_eq!(policy.poll_interval_secs, Some(60));
        assert_eq!(policy.stale_warn_after_secs, Some(3600));
    }

    #[test]
    fn test_config_load_partial_policy_section_merges_with_defaults() {
        let toml_str = r#"
[policy]
enabled = true
"#;
        let toml_cfg: TomlConfig = toml::from_str(toml_str).unwrap();
        let policy = toml_cfg.policy.unwrap();
        assert_eq!(policy.enabled, Some(true));
        // Unprovided fields stay None — merging with defaults happens in Config::load.
        assert!(policy.poll_interval_secs.is_none());
        assert!(policy.stale_warn_after_secs.is_none());
    }

    #[test]
    fn test_generate_default_config_toml_contains_policy_section() {
        let content = generate_default_config_toml(7443);
        assert!(
            content.contains("# [policy]"),
            "Must contain commented [policy] header: {content}"
        );
        assert!(
            content.contains("# enabled = true"),
            "Must document that policy ships enabled (secure-by-default): {content}"
        );
        assert!(
            content.contains("# poll_interval_secs = 300"),
            "Must contain commented poll_interval_secs line: {content}"
        );
        assert!(
            content.contains("# stale_warn_after_secs = 86400"),
            "Must contain commented stale_warn_after_secs line: {content}"
        );
    }

    #[test]
    fn test_generate_default_config_toml_contains_boundary_section() {
        let content = generate_default_config_toml(7443);
        assert!(
            content.contains("# [boundary]"),
            "Must contain commented [boundary] header: {content}"
        );
        assert!(
            content.contains("# enabled = true"),
            "Must document that the boundary ships enabled (secure-by-default): {content}"
        );
    }

    #[test]
    fn test_supervision_toml_round_trip() {
        let toml_str = r#"
[supervision]
mode = "active"
backend = "launchd"
disabled_reason = "user_opt_out"
"#;
        let toml_cfg: TomlConfig = toml::from_str(toml_str).unwrap();
        let sup = toml_cfg.supervision.unwrap();
        assert_eq!(sup.mode.as_deref(), Some("active"));
        assert_eq!(sup.backend.as_deref(), Some("launchd"));
        assert_eq!(sup.disabled_reason.as_deref(), Some("user_opt_out"));
    }

    /// The shipped template's only active line is `port`; `[cloud]` arrives
    /// fully commented. Activating it must not disturb the surrounding
    /// documentation, and must actually parse back as the requested URL.
    #[test]
    fn test_set_cloud_api_url_activates_commented_template_block() {
        let raw = generate_default_config_toml(7443);
        let out = set_cloud_api_url(&raw, "http://127.0.0.1:5183");

        let parsed: TomlConfig = toml::from_str(&out).expect("template stays valid TOML");
        assert_eq!(
            parsed.cloud.and_then(|c| c.api_url).as_deref(),
            Some("http://127.0.0.1:5183")
        );
        assert!(
            !out.contains("# api_url = \"https://app.openlatch.ai\""),
            "the commented production URL must be replaced, not left to confuse"
        );
        // The rest of the block stays commented documentation.
        assert!(out.contains("# batch_max_events = 50"));
        assert!(out.contains("# [policy]"));
        assert!(out.contains("port = 7443"));
    }

    #[test]
    fn test_set_cloud_api_url_replaces_active_value_and_keeps_other_sections() {
        let raw = "[daemon]\nport = 7443\n\n[cloud]\nenabled = true\napi_url = \"https://app.openlatch.ai\"\n\n[privacy]\nextra_patterns = [\"KEEP_ME\"]\n";
        let out = set_cloud_api_url(raw, "http://localhost:5173");

        let parsed: TomlConfig = toml::from_str(&out).unwrap();
        let cloud = parsed.cloud.unwrap();
        assert_eq!(cloud.api_url.as_deref(), Some("http://localhost:5173"));
        assert_eq!(cloud.enabled, Some(true), "sibling keys survive");
        assert_eq!(
            parsed.privacy.unwrap().extra_patterns.unwrap(),
            vec!["KEEP_ME".to_string()],
            "hand-written sections are never collateral"
        );
        assert!(!out.contains("app.openlatch.ai"));
    }

    #[test]
    fn test_set_cloud_api_url_appends_when_section_absent() {
        let raw = "[daemon]\nport = 7443\n";
        let out = set_cloud_api_url(raw, "http://127.0.0.1:5183");
        let parsed: TomlConfig = toml::from_str(&out).unwrap();
        assert_eq!(
            parsed.cloud.and_then(|c| c.api_url).as_deref(),
            Some("http://127.0.0.1:5183")
        );
        assert_eq!(parsed.daemon.unwrap().port, Some(7443));
    }

    /// Applying it twice must not accumulate `api_url` lines — TOML's
    /// last-key-wins would hide the duplicate until someone edited the file by
    /// hand and picked the wrong one.
    #[test]
    fn test_set_cloud_api_url_is_idempotent() {
        let once = set_cloud_api_url(&generate_default_config_toml(7443), "http://a.test");
        let twice = set_cloud_api_url(&once, "http://b.test");
        assert_eq!(twice.matches("api_url").count(), 1);
        let parsed: TomlConfig = toml::from_str(&twice).unwrap();
        assert_eq!(
            parsed.cloud.and_then(|c| c.api_url).as_deref(),
            Some("http://b.test")
        );
    }

    /// The commented values in the shipped template are a hand-typed mirror of
    /// the compiled defaults — nothing structural keeps the two in step, so a
    /// changed default silently turns the template into documentation that
    /// lies. Uncomment the template's `key = value` lines and assert they
    /// round-trip to `Config::defaults()`.
    ///
    /// Scope note: `[daemon]`, `[privacy]` and `[supervision]` are excluded
    /// deliberately — their commented lines are EXAMPLES (`extra_patterns`,
    /// `disabled_reason = "user_opt_out"`), not defaults. `[logging] dir` is
    /// excluded for a different reason: the template writes the tilde form
    /// `~/.openlatch/logs`, and the loader does not expand `~` — it would
    /// become a literal directory named `~`.
    #[test]
    fn test_template_comments_match_compiled_defaults() {
        const ASSERTED_SECTIONS: [&str; 4] = ["logging", "update", "cloud", "policy"];

        let template = generate_default_config_toml(7443);
        let mut uncommented = String::new();
        let mut in_asserted_section = false;
        for line in template.lines() {
            let trimmed = line.trim();
            let bare = trimmed.trim_start_matches('#').trim();
            if bare.starts_with('[') && bare.ends_with(']') {
                let name = bare.trim_matches(|c| c == '[' || c == ']');
                in_asserted_section = ASSERTED_SECTIONS.contains(&name);
                if in_asserted_section {
                    uncommented.push_str(bare);
                    uncommented.push('\n');
                }
                continue;
            }
            // Only `key = value` lines. Prose is skipped by requiring the
            // left-hand side to be a bare TOML key — the `[policy]` blurb
            // ("`enabled = false` is a complete off switch") otherwise reads
            // as an assignment.
            let is_key_line = bare.split_once(" = ").is_some_and(|(key, _)| {
                !key.is_empty() && key.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
            });
            if in_asserted_section && is_key_line {
                uncommented.push_str(bare);
                uncommented.push('\n');
            }
        }

        let parsed: TomlConfig = toml::from_str(&uncommented).unwrap_or_else(|e| {
            panic!("uncommented template must be valid TOML: {e}\n{uncommented}")
        });
        let defaults = Config::defaults();

        let logging = parsed.logging.expect("[logging] present in template");
        assert_eq!(logging.level.as_deref(), Some(defaults.log_level.as_str()));
        assert_eq!(logging.retention_days, Some(defaults.retention_days));

        let update = parsed.update.expect("[update] present in template");
        assert_eq!(update.check, Some(defaults.update.check));

        let cloud = parsed.cloud.expect("[cloud] present in template");
        assert_eq!(cloud.enabled, Some(defaults.cloud.enabled));
        assert_eq!(
            cloud.api_url.as_deref(),
            Some(defaults.cloud.api_url.as_str())
        );
        assert_eq!(
            cloud.timeout_connect_ms,
            Some(defaults.cloud.timeout_connect_ms)
        );
        assert_eq!(
            cloud.timeout_total_ms,
            Some(defaults.cloud.timeout_total_ms)
        );
        assert_eq!(cloud.retry_delay_ms, Some(defaults.cloud.retry_delay_ms));
        assert_eq!(cloud.channel_size, Some(defaults.cloud.channel_size));
        assert_eq!(
            cloud.batch_max_events,
            Some(defaults.cloud.batch_max_events)
        );
        assert_eq!(
            cloud.batch_max_wait_ms,
            Some(defaults.cloud.batch_max_wait_ms)
        );
        assert_eq!(
            cloud.outbox_max_bytes,
            Some(defaults.cloud.outbox_max_bytes)
        );
        assert_eq!(
            cloud.fallback_max_bytes,
            Some(defaults.cloud.fallback_max_bytes)
        );

        let policy = parsed.policy.expect("[policy] present in template");
        assert_eq!(policy.enabled, Some(defaults.policy.enabled));
        assert_eq!(
            policy.poll_interval_secs,
            Some(defaults.policy.poll_interval_secs)
        );
        assert_eq!(
            policy.stale_warn_after_secs,
            Some(defaults.policy.stale_warn_after_secs)
        );
    }

    #[test]
    fn test_rewrite_supervision_section_appends_when_absent() {
        let raw = "[daemon]\nport = 7443\n";
        let out = rewrite_supervision_section(raw, "active", "launchd", None);
        assert!(out.contains("[supervision]"));
        assert!(out.contains("mode = \"active\""));
        assert!(out.contains("backend = \"launchd\""));
        assert!(!out.contains("disabled_reason"));
        assert!(out.contains("[daemon]"));
        assert!(out.contains("port = 7443"));
    }

    #[test]
    fn test_rewrite_supervision_section_replaces_existing() {
        let raw = "[daemon]\nport = 7443\n\n[supervision]\nmode = \"disabled\"\nbackend = \"none\"\ndisabled_reason = \"user_opt_out\"\n\n[cloud]\nenabled = false\n";
        let out = rewrite_supervision_section(raw, "active", "task_scheduler", None);
        assert!(out.contains("mode = \"active\""));
        assert!(out.contains("backend = \"task_scheduler\""));
        // Old reason removed since we passed None.
        assert!(!out.contains("user_opt_out"));
        // Other sections preserved.
        assert!(out.contains("[cloud]"));
        assert!(out.contains("enabled = false"));
    }

    #[test]
    fn test_rewrite_supervision_section_replaces_commented_header() {
        let raw = "[daemon]\nport = 7443\n\n# [supervision]\n# mode = \"disabled\"\n";
        let out = rewrite_supervision_section(raw, "active", "launchd", Some("ok"));
        assert!(out.contains("[supervision]"));
        assert!(out.contains("mode = \"active\""));
        // Commented template replaced, not duplicated.
        assert_eq!(out.matches("[supervision]").count(), 1);
    }

    #[test]
    fn test_persist_supervision_state_writes_to_disk() {
        use crate::supervision::{SupervisionMode, SupervisorKind};
        let tmp = TempDir::new().unwrap();
        let config_path = tmp.path().join("config.toml");
        std::fs::write(&config_path, "[daemon]\nport = 7443\n").unwrap();

        persist_supervision_state(
            &config_path,
            &SupervisionMode::Active,
            &SupervisorKind::Launchd,
            None,
        )
        .expect("persist should succeed");

        let raw = std::fs::read_to_string(&config_path).unwrap();
        assert!(raw.contains("[supervision]"));
        assert!(raw.contains("mode = \"active\""));
        assert!(raw.contains("backend = \"launchd\""));
    }

    #[test]
    fn test_generate_default_config_toml_contains_supervision_template() {
        let content = generate_default_config_toml(7443);
        assert!(
            content.contains("# [supervision]"),
            "Must contain commented [supervision] header: {content}"
        );
        assert!(
            content.contains("# mode = \"disabled\""),
            "Must contain commented mode line: {content}"
        );
    }

    #[test]
    fn test_generate_default_config_toml_contains_cloud_section() {
        // generate_default_config_toml() must contain commented [cloud] section
        let content = generate_default_config_toml(7443);
        assert!(
            content.contains("# [cloud]"),
            "Must contain commented [cloud] header: {content}"
        );
        assert!(
            content.contains("# enabled = true"),
            "Must contain commented enabled line: {content}"
        );
        assert!(
            content.contains("# api_url = \"https://app.openlatch.ai\""),
            "Must contain commented api_url line: {content}"
        );
        assert!(
            content.contains("# timeout_connect_ms = 5000"),
            "Must contain commented timeout_connect_ms line: {content}"
        );
        assert!(
            content.contains("# timeout_total_ms = 10000"),
            "Must contain commented timeout_total_ms line: {content}"
        );
        assert!(
            content.contains("# retry_delay_ms = 2000"),
            "Must contain commented retry_delay_ms line: {content}"
        );
        assert!(
            content.contains("# channel_size = 1000"),
            "Must contain commented channel_size line: {content}"
        );
        assert!(
            content.contains("# batch_max_events = 50"),
            "Must contain commented batch_max_events line: {content}"
        );
        assert!(
            content.contains("# batch_max_wait_ms = 5000"),
            "Must contain commented batch_max_wait_ms line: {content}"
        );
    }

    /// Serialises the tests below: they mutate process-global env vars and
    /// `Config::load` reads them, so two of them running concurrently would
    /// observe each other's values.
    static BATCH_ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

    /// Set both batching env vars, run `Config::load`, and always unset them
    /// again — even if the assertion inside `check` panics, because the
    /// `Mutex` guard is poisoned but the vars would otherwise leak into every
    /// other test in this binary.
    fn with_batch_env<T>(
        max_events: Option<&str>,
        max_wait_ms: Option<&str>,
        check: impl FnOnce(Config) -> T,
    ) -> T {
        let _guard = BATCH_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        match max_events {
            Some(v) => std::env::set_var("OPENLATCH_CLOUD_BATCH_MAX_EVENTS", v),
            None => std::env::remove_var("OPENLATCH_CLOUD_BATCH_MAX_EVENTS"),
        }
        match max_wait_ms {
            Some(v) => std::env::set_var("OPENLATCH_CLOUD_BATCH_MAX_WAIT_MS", v),
            None => std::env::remove_var("OPENLATCH_CLOUD_BATCH_MAX_WAIT_MS"),
        }
        let cfg = Config::load(None, None, false).expect("Config::load should succeed");
        std::env::remove_var("OPENLATCH_CLOUD_BATCH_MAX_EVENTS");
        std::env::remove_var("OPENLATCH_CLOUD_BATCH_MAX_WAIT_MS");
        check(cfg)
    }

    #[test]
    fn test_cloud_batch_defaults() {
        let cfg = Config::defaults();
        assert_eq!(
            cfg.cloud.batch_max_events, 50,
            "Default batch_max_events must be 50"
        );
        assert_eq!(
            cfg.cloud.batch_max_wait_ms, 5000,
            "Default batch_max_wait_ms must be 5000"
        );
    }

    #[test]
    fn test_cloud_batch_env_overrides() {
        with_batch_env(Some("25"), Some("750"), |cfg| {
            assert_eq!(
                cfg.cloud.batch_max_events, 25,
                "OPENLATCH_CLOUD_BATCH_MAX_EVENTS must override the default"
            );
            assert_eq!(
                cfg.cloud.batch_max_wait_ms, 750,
                "OPENLATCH_CLOUD_BATCH_MAX_WAIT_MS must override the default"
            );
        });
    }

    #[test]
    fn test_cloud_batch_max_events_clamped_at_load() {
        // 0 would leave the accumulator with no reachable size trigger.
        with_batch_env(Some("0"), None, |cfg| {
            assert_eq!(
                cfg.cloud.batch_max_events, 1,
                "batch_max_events = 0 must clamp up to 1"
            );
        });
        // The platform hard-rejects batches larger than 100.
        with_batch_env(Some("101"), None, |cfg| {
            assert_eq!(
                cfg.cloud.batch_max_events, 100,
                "batch_max_events = 101 must clamp down to 100"
            );
        });
    }

    #[test]
    fn test_cloud_batch_max_events_rejects_non_integer() {
        let _guard = BATCH_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        std::env::set_var("OPENLATCH_CLOUD_BATCH_MAX_EVENTS", "fifty");
        let err = Config::load(None, None, false).expect_err("non-integer must be rejected");
        std::env::remove_var("OPENLATCH_CLOUD_BATCH_MAX_EVENTS");
        assert_eq!(err.code, ERR_INVALID_CONFIG);
    }

    // -----------------------------------------------------------------------
    // [proxy] — the egress route
    // -----------------------------------------------------------------------

    /// Write a `config.toml` into a throwaway state directory and load it.
    ///
    /// The scrubbing is not defensive tidiness: the `OPENLATCH_*` proxy
    /// variables are precedence tier 2 and `config.toml` is tier 3, so a
    /// developer machine (or a CI runner) that exports one would decide what
    /// these tests observe instead of the file under test. Everything is put
    /// back afterwards, and `BATCH_ENV_LOCK` keeps the mutation off the other
    /// env-reading tests in this binary.
    fn with_proxy_config<T>(body: &str, check: impl FnOnce(Result<Config, OlError>) -> T) -> T {
        const SCRUBBED: &[&str] = &[
            "OPENLATCH_DIR",
            "OPENLATCH_PROXY",
            "OPENLATCH_PROXY_MODE",
            "OPENLATCH_PROXY_AUTH",
            "OPENLATCH_PROXY_PAC_URL",
            "OPENLATCH_PROXY_SPN",
            "OPENLATCH_NO_PROXY",
            "OPENLATCH_CA_BUNDLE",
        ];

        let dir = TempDir::new().unwrap();
        std::fs::write(dir.path().join("config.toml"), body).unwrap();

        let _guard = BATCH_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let saved: Vec<(&str, Option<String>)> = SCRUBBED
            .iter()
            .map(|key| (*key, std::env::var(key).ok()))
            .collect();
        for key in SCRUBBED {
            std::env::remove_var(key);
        }
        std::env::set_var("OPENLATCH_DIR", dir.path());

        let loaded = Config::load(None, None, false);

        for (key, previous) in saved {
            match previous {
                Some(v) => std::env::set_var(key, v),
                None => std::env::remove_var(key),
            }
        }
        check(loaded)
    }

    #[test]
    fn proxy_section_reaches_the_resolved_egress_config() {
        use crate::core::egress::{ProxyAuth, ProxyMode, ProxySource};

        // All eleven keys, so the section proves it parses as a whole rather
        // than one field at a time. `pac_url` and `ca_bundle` are present but
        // empty: an empty value resolves to None, and a real ca_bundle would
        // have to exist on disk to survive startup validation.
        let cfg = with_proxy_config(
            r#"
[daemon]
port = 7443

[proxy]
mode = "manual"
url = "http://proxy.corp.example:3128"
username = "svc-openlatch"
auth = "basic"
no_proxy = ".corp.example"
pac_url = ""
ca_bundle = ""
allow_direct = true
source = "manual"
spn = "HTTP/proxy.corp.example"
http1_only = true
"#,
            |loaded| loaded.expect("a well-formed [proxy] block must load"),
        );

        assert_eq!(cfg.egress.mode, ProxyMode::Manual);
        assert_eq!(
            cfg.egress.url.as_deref(),
            Some("http://proxy.corp.example:3128")
        );
        assert_eq!(cfg.egress.username.as_deref(), Some("svc-openlatch"));
        assert_eq!(cfg.egress.auth, ProxyAuth::Basic);
        assert_eq!(cfg.egress.source, Some(ProxySource::Manual));
        assert_eq!(cfg.egress.spn.as_deref(), Some("HTTP/proxy.corp.example"));
        assert!(cfg.egress.http1_only, "http1_only must survive the merge");
        assert!(cfg.egress.allow_direct);
        assert!(
            cfg.egress.no_proxy.matches("api.corp.example", 443),
            "the operator's bypass list must reach the matcher"
        );
        assert!(
            !cfg.egress.no_proxy.matches("api.openlatch.ai", 443),
            "and must not swallow everything else"
        );
    }

    #[test]
    fn no_proxy_section_leaves_the_egress_route_direct() {
        // The common case: a config.toml with no [proxy] block at all. Nothing
        // here asserts what the ambient environment does — only that the
        // absent section is not itself an error.
        let cfg = with_proxy_config("[daemon]\nport = 7443\n", |loaded| {
            loaded.expect("a config with no [proxy] section must load")
        });
        assert!(cfg.egress.allow_direct, "the default never forbids direct");
    }

    #[test]
    fn malformed_proxy_url_fails_startup() {
        // D-9: a config error is a bug in the input, so it fails at boot rather
        // than degrading to a direct connection nobody asked for.
        let err = with_proxy_config(
            "[daemon]\nport = 7443\n\n[proxy]\nurl = \"proxy.corp.example:3128\"\n",
            |loaded| loaded.expect_err("a url with no scheme must be rejected"),
        );
        assert_eq!(err.code, crate::error::ERR_PROXY_CONFIG_INVALID);
    }

    #[test]
    fn unknown_proxy_key_is_flagged() {
        // The allowlist borrows `PROXY_TOML_KEYS`, so this also proves the
        // borrow reached the table.
        let raw = "[proxy]\nurl = \"http://proxy.corp.example:3128\"\nno_proxy_list = \".corp\"\n";
        assert_eq!(
            collect_unknown_config_keys(raw),
            vec!["proxy.no_proxy_list"]
        );
    }

    #[test]
    fn a_retired_attribution_cascade_key_is_reported_not_silently_ignored() {
        // The cascade became unconditional, so the key does nothing. Serde would
        // drop it without a word; the allowlist is what tells the operator their
        // `attribution_cascade = false` is no longer switching anything off.
        let raw = "[boundary]\nenabled = true\nattribution_cascade = false\n";
        assert_eq!(
            collect_unknown_config_keys(raw),
            vec!["boundary.attribution_cascade".to_string()],
            "a config that still sets the retired key must be told it is inert"
        );
    }

    #[test]
    fn boundary_own_agent_wiring_is_not_an_unknown_key() {
        // Regression: the key parsed and took effect while the checker reported
        // it as a typo, so the one config that used it was told to remove it.
        let raw = "[boundary]\nenabled = true\nown_agent_wiring = true\n";
        assert!(
            collect_unknown_config_keys(raw).is_empty(),
            "own_agent_wiring is honoured by load and must be in the allowlist"
        );
    }

    #[test]
    fn test_generate_default_config_toml_contains_proxy_section() {
        let content = generate_default_config_toml(7443);
        assert!(
            content.contains("# [proxy]"),
            "Must contain commented [proxy] header: {content}"
        );
        assert!(
            content.contains("# mode = \"auto\""),
            "Must document the default mode: {content}"
        );
        assert!(
            content.contains("# allow_direct = true"),
            "Must document that the ladder may end at a direct connection: {content}"
        );
    }

    #[test]
    fn test_unknown_config_key_is_flagged() {
        // The reported typo: `[policy] enable` instead of `enabled`.
        let raw = "[policy]\nenable = true\npoll_interval_secs = 60\n";
        assert_eq!(collect_unknown_config_keys(raw), vec!["policy.enable"]);
    }

    #[test]
    fn test_unknown_top_level_section_is_flagged() {
        let raw = "[nope]\nfoo = 1\n";
        assert_eq!(collect_unknown_config_keys(raw), vec!["nope"]);
    }

    #[test]
    fn test_all_known_keys_produce_no_warnings() {
        // A fully-specified, all-known-keys config must be clean — guards the
        // KNOWN_CONFIG_SECTIONS table against drift from the *Toml structs.
        let raw = "\
[daemon]
port = 7443
agent_id = \"a\"
[logging]
level = \"info\"
dir = \"/tmp\"
retention_days = 30
[privacy]
extra_patterns = []
[update]
check = true
registry_origin = \"o\"
download_timeout_secs = 1
auto_update = false
check_interval_secs = 1
quiet_window_secs = 1
max_defer_secs = 1
[cloud]
enabled = true
api_url = \"u\"
timeout_connect_ms = 1
timeout_total_ms = 1
retry_delay_ms = 1
channel_size = 1
credential_poll_interval_ms = 1
outbox_enabled = true
outbox_max_bytes = 1
fallback_max_bytes = 1
batch_max_events = 1
batch_max_wait_ms = 1
[supervision]
mode = \"m\"
backend = \"b\"
disabled_reason = \"r\"
[inventory_monitor]
enabled = true
periodic_rescan_interval_hours = 1
watcher_debounce_ms = 1
max_inline_content_bytes = 1
content_forward = \"metadata_only\"
project_scope_auto_detect = true
cache_max_entries = 1
[policy]
enabled = true
poll_interval_secs = 1
stale_warn_after_secs = 1
[boundary]
enabled = true
";
        assert!(
            collect_unknown_config_keys(raw).is_empty(),
            "known keys must not be flagged: {:?}",
            collect_unknown_config_keys(raw)
        );
    }

    #[test]
    fn test_invalid_toml_returns_no_keys() {
        // Malformed TOML is the caller's typed-error path, not ours.
        assert!(collect_unknown_config_keys("this is not = = toml").is_empty());
    }
    // -----------------------------------------------------------------------
    // `[boundary] upstream` — both shapes, and the three-step precedence
    // -----------------------------------------------------------------------

    /// Load a `config.toml` body through the real precedence chain.
    ///
    /// Scrubs the two env vars that would otherwise decide the answer instead
    /// of the file under test — `OPENLATCH_DIR` points `load` at the temp dir,
    /// and `OPENLATCH_BOUNDARY_UPSTREAM` is precedence tier 2, above the file.
    /// `BATCH_ENV_LOCK` keeps the mutation off the other env-reading tests.
    fn load_boundary_config(body: &str) -> Result<Config, OlError> {
        const SCRUBBED: &[&str] = &["OPENLATCH_DIR", "OPENLATCH_BOUNDARY_UPSTREAM"];
        let dir = TempDir::new().unwrap();
        std::fs::write(dir.path().join("config.toml"), body).unwrap();

        let _guard = BATCH_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let saved: Vec<(&str, Option<String>)> = SCRUBBED
            .iter()
            .map(|key| (*key, std::env::var(key).ok()))
            .collect();
        for key in SCRUBBED {
            std::env::remove_var(key);
        }
        std::env::set_var("OPENLATCH_DIR", dir.path());

        let loaded = Config::load(None, None, false);

        for (key, previous) in saved {
            match previous {
                Some(v) => std::env::set_var(key, v),
                None => std::env::remove_var(key),
            }
        }
        loaded
    }

    /// The non-breaking guarantee (D-04). A scalar is what every install
    /// written before the per-format map contains, and it has always meant "the
    /// upstream Claude traffic goes to" — so it keeps meaning exactly that, and
    /// does NOT silently become Codex's upstream.
    #[test]
    fn upstream_scalar_still_parses_as_the_anthropic_entry() {
        let cfg = load_boundary_config("[boundary]\nupstream = \"https://gw.example\"\n")
            .expect("a scalar upstream must still load");

        // Step 1 — the configured entry wins for its own format.
        assert_eq!(
            cfg.boundary.upstream_for(WireFormat::AnthropicMessages),
            "https://gw.example"
        );
        // Step 3 — a captured format the customer did not configure takes its
        // OWN built-in default. This is the assertion that reds if step 2 is
        // left unscoped, and the misroute it prevents would send Codex prompts
        // to the customer's Anthropic gateway.
        assert_eq!(
            cfg.boundary.upstream_for(WireFormat::OpenAiResponses),
            crate::boundary::wire_format::OPENAI_BASE
        );
        // Step 2 — an UNCAPTURED route still resolves to the configured base,
        // which is today's behaviour for `GET /v1/models` and friends.
        assert_eq!(
            cfg.boundary.upstream_for(WireFormat::Unknown),
            "https://gw.example"
        );
    }

    /// The table form, and it resolves both formats independently.
    #[test]
    fn upstream_map_parses_per_format() {
        let cfg = load_boundary_config(
            "[boundary.upstream]\n\
             anthropic-messages = \"https://a.example\"\n\
             openai-responses = \"https://o.example\"\n",
        )
        .expect("a table upstream must load");

        assert_eq!(
            cfg.boundary.upstream_for(WireFormat::AnthropicMessages),
            "https://a.example"
        );
        assert_eq!(
            cfg.boundary.upstream_for(WireFormat::OpenAiResponses),
            "https://o.example"
        );
        assert_eq!(
            cfg.boundary.upstream_for(WireFormat::Unknown),
            "https://a.example",
            "step 2: an uncaptured route follows the anthropic-messages entry"
        );
    }

    /// A stock install configures nothing, so every format takes its own
    /// built-in default — which is only reachable because the map's `Default`
    /// is EMPTY. Materializing Anthropic's into it would make step 3 unreachable
    /// and resolve Codex to `api.anthropic.com` on every stock host.
    #[test]
    fn a_stock_install_resolves_every_format_to_its_own_default() {
        let cfg = BoundaryConfig::default();
        assert!(cfg.upstream.is_empty(), "the default map must be EMPTY");
        assert_eq!(
            cfg.upstream_for(WireFormat::AnthropicMessages),
            crate::boundary::ANTHROPIC_BASE
        );
        assert_eq!(
            cfg.upstream_for(WireFormat::OpenAiResponses),
            crate::boundary::wire_format::OPENAI_BASE
        );
        assert_eq!(
            cfg.upstream_for(WireFormat::Unknown),
            crate::boundary::ANTHROPIC_BASE
        );
    }

    /// The typo `collect_unknown_config_keys` cannot see.
    ///
    /// It does not recurse into `[boundary.upstream]` — `upstream` is itself an
    /// allowed key — so a hyphen written as an underscore would be dropped in
    /// silence. The warning lives at the merge arm because that is the only
    /// place the RAW keys exist: the builder downstream is handed a map the
    /// daemon composed from `WireFormat::ALL` and can never see a typo.
    #[test]
    fn unknown_upstream_key_warns() {
        let (cfg, logs) = crate::core::policy::test_support::capture_logs(|| {
            load_boundary_config(
                "[boundary.upstream]\n\
                 anthropic_messages = \"https://typo.example\"\n\
                 openai-responses = \"https://o.example\"\n",
            )
            .expect("an unknown key must not fail the load")
        });

        assert!(
            logs.contains("anthropic_messages"),
            "the warning must NAME the key that was ignored, got: {logs}"
        );
        // Named, ignored, and the rest of the table still applies.
        assert_eq!(
            cfg.boundary.upstream_for(WireFormat::AnthropicMessages),
            crate::boundary::ANTHROPIC_BASE,
            "the typo'd key configures nothing"
        );
        assert_eq!(
            cfg.boundary.upstream_for(WireFormat::OpenAiResponses),
            "https://o.example"
        );
        // EXACTLY ONE warning: the known key beside it must not produce one.
        // (The message body itself lists the valid names, so a bare
        // `!logs.contains("openai-responses")` would read its own remedy text.)
        assert_eq!(
            logs.matches("names no known wire format").count(),
            1,
            "a KNOWN key must not be warned about, got: {logs}"
        );
    }
}