openlatch-client 0.6.1

OpenLatch runtime enforcement node — the capture-and-enforce adapter that evaluates every covered action against a coding agent's Autonomy Zone before it runs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
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
/// `openlatch init` command handler.
///
/// Runs the full initialization flow:
/// 1. Detect AI agent (D-01)
/// 2. Regenerate auth token (D-02)
/// 3. Write hooks to settings.json (D-03, D-04)
///    3.5. Auth flow — browser or env var validation (D-06, D-07, D-09)
/// 4. Start the daemon (D-05)
///    4.5. Show cloud sync status (D-08)
///
/// In JSON mode, emits a single JSON object at the end instead of step-by-step output.
use crate::auth::{
    retrieve_credential, store_credential, CredentialStore, FileCredentialStore,
    KeyringCredentialStore,
};
use crate::cli::commands::lifecycle;
use crate::cli::commands::proxy;
use crate::cli::output::{OutputConfig, OutputFormat};
use crate::cli::report::{Check, Report, Resolution, Section, SetupVerdict, State};
use crate::cli::ui;
use crate::cli::AuthLoginArgs;
use crate::cli::InitArgs;
use crate::config;
use crate::error::{OlError, ERR_INVALID_CONFIG, ERR_NO_CREDENTIALS, ERR_PORT_IN_USE};
use crate::hooks;
use crate::hooks::DetectedAgent;
use crate::telemetry::{self, config as telemetry_config, consent_file_path, Event};
use secrecy::ExposeSecret;

/// Stages on `init`'s rail — see [`run_stages`].
const STAGES: usize = 6;

/// How long Final checks waits for a check that settles by itself (a first
/// policy bundle, a relay preflight) before reporting it as still in flight.
const SETTLE_WAIT: std::time::Duration = std::time::Duration::from_secs(10);

/// Run the `openlatch init` command.
///
/// Detects the AI agent, regenerates the auth token, writes hooks, and starts the daemon.
/// In human mode the run is a rail of six customer-language stages ending in one result
/// card (`crate::cli::ui`); engineering detail is logged and shown only with `--verbose`.
/// In JSON mode, emits a single JSON object.
///
/// The exit status is the customer verdict: 0 live · 7 needs attention · 3 no supported
/// agent to connect · 1 (or the error's own code) not live.
///
/// # Errors
///
/// Returns an error at the first failing step. No rollback is performed (D-03).
pub fn run_init(args: &InitArgs, output: &OutputConfig) -> Result<(), OlError> {
    crate::cli::header::print(output, &["init"]);

    // [A] --dry-run is the FIRST thing this function does, before the `create_dir_all`
    // calls below. On a fresh host those calls create `~/.openlatch`, and "a dry run
    // touches no disk" has to be literally true or it is not worth saying.
    if args.dry_run {
        return run_dry_run(args, output);
    }

    // Held for the whole run: `OutputConfig`'s helpers route through the rail while it
    // lives. The error is reported here, before the guard drops, so it lands on the stage
    // that failed rather than under a closed rail.
    let _rail = ui::install(output, "init", STAGES);
    ui::intro("Setting up this machine");
    let result = run_stages(args, output);
    if let Err(e) = &result {
        report_not_live(e, output);
    }
    result
}

/// Close the rail on an error: the failed stage, then the red card.
///
/// Returns the error unchanged to `main`, which does not print it again
/// (`ui::error_reported`) and exits with its code.
fn report_not_live(error: &OlError, output: &OutputConfig) {
    if !ui::is_active() {
        return;
    }
    if !ui::error_reported(error) {
        output.print_error(error);
    }
    ui::outro("Stopped.");
    let log = ui::log_path().map(|p| p.display().to_string());
    let footer = log_footer(log.as_deref());
    ui::card(&ui::Card {
        verdict: ui::Verdict::NotLive,
        title: "OpenLatch couldn't finish setting up".into(),
        rows: vec![ui::Row::new("What happened", error.message.clone())],
        sections: vec![
            ui::Section::new(
                "Try this",
                vec![error
                    .suggestion
                    .clone()
                    .unwrap_or_else(|| "Run `openlatch init` again.".into())],
            ),
            ui::Section::new(
                "Need help",
                vec!["Share the log below with your IT team or OpenLatch.".into()],
            ),
        ],
        footer,
    });
    let mut fields = vec![("code", error.code)];
    if let Some(log) = &log {
        fields.push(("log", log));
    }
    ui::result(ui::Verdict::NotLive, error.exit_code(), &fields);
}

/// No supported agent on this machine: an amber outcome, not an error.
///
/// OpenLatch is installed and has nothing to connect yet. On a rail that is the amber
/// card; under `--json` / `--quiet` the `OL-1400` error is printed exactly as before.
/// Either way the exit status is 3 (not found), so a script or an MDM retries later
/// rather than recording a failed install.
fn report_no_agent(output: &OutputConfig) {
    if !ui::is_active() {
        output.print_error(&hooks::agent_not_found_err());
        return;
    }
    ui::halt("no AI agent found");
    ui::outro("Paused: one thing to do first.");
    ui::card(&ui::Card {
        verdict: ui::Verdict::NoAgent,
        title: "No AI agent to connect on this machine yet".into(),
        rows: vec![
            ui::Row::new(
                "Looked for",
                hooks::binding::DETECTABLE_AGENT_NAMES.join(" · "),
            ),
            ui::Row::new("Status", "installed, not active yet"),
        ],
        sections: vec![ui::Section::new(
            "To finish",
            vec!["Install one of them, then run `openlatch init` again.".into()],
        )],
        footer: footer_lines(),
    });
    ui::result(ui::Verdict::NoAgent, EXIT_NO_AGENT, &[]);
}

/// `init`'s exit status when there is no supported agent to connect: 3, "not found".
const EXIT_NO_AGENT: i32 = 3;

/// The exit status for a customer verdict: 0 live · 7 needs attention · 1 not live.
fn verdict_exit_code(verdict: SetupVerdict) -> i32 {
    match verdict {
        SetupVerdict::Live => 0,
        SetupVerdict::NeedsAttention => crate::cli::report::EXIT_DEGRADED,
        SetupVerdict::NotLive => 1,
    }
}

/// What the result card says about this run, beyond the report.
struct CardFacts<'a> {
    org: &'a str,
    /// `(wire type, display name)` of every agent this run connected.
    agents: &'a [(&'static str, &'static str)],
    /// How OpenLatch runs now: `in the background · starts at login`.
    runs: &'a str,
    no_start: bool,
    /// Where the user sees what their agents do.
    console_url: &'a str,
}

/// Final checks: the install report, given a few seconds to settle.
///
/// A first policy bundle or a relay preflight still in flight
/// ([`Resolution::SelfResolving`]) is re-checked every second for up to [`SETTLE_WAIT`],
/// so a machine a moment away from fully in sync is reported as in sync. Only while
/// nothing else holds the verdict back — waiting cannot turn an amber or red card green.
fn final_checks(args: &InitArgs, output: &OutputConfig) -> Option<Report> {
    let mut report = build_install_report(args, output)?;
    let deadline = std::time::Instant::now() + SETTLE_WAIT;
    while let Some(section) = settling(&report) {
        if std::time::Instant::now() >= deadline {
            break;
        }
        ui::progress(if section == Section::Policy {
            "Waiting for first policies"
        } else {
            "Waiting for the model relay check"
        });
        std::thread::sleep(std::time::Duration::from_secs(1));
        match build_install_report(args, output) {
            Some(next) => report = next,
            None => break,
        }
    }
    Some(report)
}

/// The section of the first check still settling by itself, when that is all that
/// stands between this report and a fully green one.
fn settling(report: &Report) -> Option<Section> {
    if report.setup_verdict() != SetupVerdict::Live {
        return None;
    }
    report
        .checks()
        .iter()
        .find(|c| c.state.is_warning() && c.resolution == Resolution::SelfResolving)
        .map(|c| c.section)
}

/// Close Final checks and the rail, then draw the card and the `result=` line.
fn report_verdict(report: &Report, facts: &CardFacts<'_>, exit_code: i32) {
    let verdict = report.setup_verdict();
    let failed: Vec<&Check> = report
        .checks()
        .iter()
        .filter(|c| c.state.is_failure())
        .collect();
    match verdict {
        SetupVerdict::Live => ui::done("all checks passed"),
        SetupVerdict::NeedsAttention => ui::attention(&things(attention_items(report).len())),
        SetupVerdict::NotLive => ui::failed(&format!(
            "{} failed",
            count(failed.len(), "check", "checks")
        )),
    }
    ui::outro(if verdict == SetupVerdict::NotLive {
        "Stopped."
    } else {
        "Done."
    });
    ui::card(&install_card(report, facts));

    let agents = facts
        .agents
        .iter()
        .map(|(wire, _)| *wire)
        .collect::<Vec<_>>()
        .join(",");
    let log = ui::log_path().map(|p| p.display().to_string());
    // A field is written only when there is something in it: a cloud that could not be
    // asked for the organization's name leaves `org` out rather than `org=""`.
    let mut fields: Vec<(&str, &str)> = [("org", facts.org), ("agents", agents.as_str())]
        .into_iter()
        .filter(|(_, v)| !v.is_empty())
        .collect();
    if verdict == SetupVerdict::NotLive {
        if let Some(code) = failed.iter().find_map(|c| c.code) {
            fields.push(("code", code));
        }
        if let Some(log) = &log {
            fields.push(("log", log));
        }
    }
    ui::result(card_verdict(verdict), exit_code, &fields);
}

fn card_verdict(verdict: SetupVerdict) -> ui::Verdict {
    match verdict {
        SetupVerdict::Live => ui::Verdict::Live,
        SetupVerdict::NeedsAttention => ui::Verdict::NeedsAttention,
        SetupVerdict::NotLive => ui::Verdict::NotLive,
    }
}

/// The warnings that ask something of the user, in report order.
///
/// An `Unknown` row is left out when the section it waits on is itself on the list —
/// one outage, one item. One whose blocker asks nothing of the user (a healthy section
/// it still cannot see past) stays, or the amber card would name nothing to do.
fn attention_items(report: &Report) -> Vec<&Check> {
    let needs_user = |c: &Check| c.state.is_warning() && c.resolution == Resolution::NeedsUser;
    let blocking: Vec<Section> = report
        .checks()
        .iter()
        .filter(|c| needs_user(c) && !matches!(c.state, State::Unknown(_)))
        .map(|c| c.section)
        .collect();
    report
        .checks()
        .iter()
        .filter(|c| match c.state {
            State::Unknown(blocker) => needs_user(c) && !blocking.contains(&blocker),
            _ => needs_user(c),
        })
        .collect()
}

/// `1 check`, `2 checks`.
fn count(n: usize, one: &str, many: &str) -> String {
    format!("{n} {}", if n == 1 { one } else { many })
}

/// `one thing left to do`, `2 things left to do` — Final checks' result.
fn things(n: usize) -> String {
    if n <= 1 {
        "one thing left to do".to_string()
    } else {
        format!("{n} things left to do")
    }
}

/// `one thing needs you`, `2 things need you` — the amber card's title.
fn needs(n: usize) -> String {
    if n <= 1 {
        "one thing needs you".to_string()
    } else {
        format!("{n} things need you")
    }
}

/// The result card for a run that got as far as Final checks.
fn install_card(report: &Report, facts: &CardFacts<'_>) -> ui::Card {
    let verdict = report.setup_verdict();
    let mut rows = Vec::new();
    if verdict != SetupVerdict::NotLive {
        if !facts.org.is_empty() {
            rows.push(ui::Row::new("Organization", facts.org));
        }
        let label = if facts.agents.len() == 1 {
            "Agent"
        } else {
            "Agents"
        };
        for (i, (wire, name)) in facts.agents.iter().enumerate() {
            rows.push(ui::Row::new(if i == 0 { label } else { "" }, *name));
            rows.push(ui::Row::more(coverage_line(report, wire)));
        }
    }
    let mut footer = footer_lines();

    match verdict {
        SetupVerdict::Live => {
            rows.push(match report.section_state(Section::Policy) {
                State::Ok => ui::Row::new("Policies", "in sync"),
                State::Pending => ui::Row::new("Policies", "first sync in progress")
                    .with_tail("· applies on arrival"),
                _ => ui::Row::new("Policies", "not in sync yet"),
            });
            rows.push(ui::Row::new("Runs", facts.runs));
            let names: Vec<&str> = facts.agents.iter().map(|(_, n)| *n).collect();
            ui::Card {
                verdict: ui::Verdict::Live,
                title: "OpenLatch is live on this machine".into(),
                rows,
                sections: vec![ui::Section::new(
                    "Next",
                    vec![
                        format!("Keep using {} as usual.", words(&names)),
                        format!("See what they do at `{}`", facts.console_url),
                    ],
                )],
                footer,
            }
        }
        SetupVerdict::NeedsAttention => {
            let items = attention_items(report);
            let mut next: Vec<String> = Vec::new();
            for check in &items {
                rows.push(ui::Row::new(check.section.title(), check.headline.clone()));
                if let Some(remedy) = check.remedy.as_ref().filter(|r| !next.contains(r)) {
                    next.push(remedy.clone());
                }
            }
            if next.is_empty() {
                next.push("Run `openlatch doctor` for the details.".into());
            }
            let state = if facts.no_start { "set up" } else { "running" };
            ui::Card {
                verdict: ui::Verdict::NeedsAttention,
                title: format!("OpenLatch is {state} — {}", needs(items.len())),
                rows,
                sections: vec![ui::Section::new("Next", next)],
                footer,
            }
        }
        SetupVerdict::NotLive => {
            let mut fixes: Vec<String> = Vec::new();
            for (i, check) in report
                .checks()
                .iter()
                .filter(|c| c.state.is_failure())
                .enumerate()
            {
                rows.push(ui::Row::new(
                    if i == 0 { "What happened" } else { "" },
                    format!("{}: {}", check.section.title(), check.headline),
                ));
                if let Some(remedy) = check.remedy.as_ref().filter(|r| !fixes.contains(r)) {
                    fixes.push(remedy.clone());
                }
            }
            if fixes.is_empty() {
                fixes.push("Run `openlatch init` again.".into());
            }
            footer = log_footer(ui::log_path().map(|p| p.display().to_string()).as_deref());
            ui::Card {
                verdict: ui::Verdict::NotLive,
                title: "OpenLatch couldn't finish setting up".into(),
                rows,
                sections: vec![
                    ui::Section::new("Try this", fixes),
                    ui::Section::new(
                        "Need help",
                        vec!["Share the log below with your IT team or OpenLatch.".into()],
                    ),
                ],
                footer,
            }
        }
    }
}

/// `actions controlled · model calls observed` — what OpenLatch covers for one agent.
fn coverage_line(report: &Report, agent: &str) -> String {
    let actions = if report.agent_section_state(agent, Section::Hooks) == Some(State::Ok) {
        "actions controlled"
    } else {
        "actions not controlled yet"
    };
    let calls = if report.agent_section_state(agent, Section::ModelRelay) == Some(State::Ok) {
        "model calls observed"
    } else {
        "model calls not observed"
    };
    format!("{actions} · {calls}")
}

/// The line under a not-live card: where the log is, for support.
fn log_footer(log: Option<&str>) -> Vec<String> {
    log.map(|log| vec![format!("Log  {log}")])
        .unwrap_or_default()
}

/// The dim lines under a live or amber card.
fn footer_lines() -> Vec<String> {
    let mut footer =
        vec!["Check anytime `openlatch status`   ·   Full diagnostics `openlatch doctor`".into()];
    // Set by the install scripts when the shell that ran them will not resolve
    // `openlatch` until it is restarted (`powershell -c "irm … | iex"`, `curl … | sh`).
    if std::env::var_os("OPENLATCH_INSTALL_PATH_HINT").is_some_and(|v| !v.is_empty()) {
        footer.push("Open a new terminal to use the `openlatch` command.".into());
    }
    footer
}

/// `A`, `A and B`, `A, B and C`.
fn words(names: &[&str]) -> String {
    match names {
        [] => String::new(),
        [one] => (*one).to_string(),
        [head @ .., last] => format!("{} and {last}", head.join(", ")),
    }
}

/// The body of `init`, one rail stage after another:
///
/// | # | Stage | Wraps |
/// | - | ----- | ----- |
/// | 1 | Checking this machine | egress gates, reclaim, agent detection, token, port, config |
/// | 2 | Signing in | [`run_auth_for_init`] |
/// | 3 | Usage data | [`handle_telemetry_consent`] |
/// | 4 | Connecting <agents> | hook staging, [`install_for_agents`] |
/// | 5 | Starting OpenLatch | supervision, daemon start, relay preflight, cloud sync |
/// | 6 | Running final checks | [`build_install_report`] + the settle wait |
///
/// With no rail installed (`--json`, `--quiet`) every `ui::` call is a no-op.
fn run_stages(args: &InitArgs, output: &OutputConfig) -> Result<(), OlError> {
    ui::stage_named(
        "Check this machine",
        "Checking this machine",
        "Checked this machine",
    );

    // Everything this run creates, so a failed egress gate can leave the host exactly as it
    // found it. See `InitLedger` for why the gate is the one step D-03 is amended for.
    let mut ledger = InitLedger::default();

    // Ensure the openlatch directory exists
    let ol_dir = config::openlatch_dir();
    ledger.create_dir(&ol_dir).map_err(|e| {
        OlError::new(
            ERR_INVALID_CONFIG,
            format!(
                "Cannot create openlatch directory '{}': {e}",
                ol_dir.display()
            ),
        )
        .with_suggestion("Check that you have write permission to your home directory.")
    })?;
    ledger.create_dir(&ol_dir.join("logs")).map_err(|e| {
        OlError::new(
            ERR_INVALID_CONFIG,
            format!("Cannot create logs directory: {e}"),
        )
    })?;

    // [B] The RE-INIT gate — before `reclaim_ports` below, and therefore before the token
    // rotation and every config write.
    //
    // A re-init over a working install must never take that install down over a network
    // condition: reclaiming the ports stops the daemon, and a daemon stopped by a run that
    // then fails leaves the host with no resident bundle enforcing anything. The predicate
    // is the presence of `config.toml`, which is what "an install is already here" means
    // everywhere else in this file.
    //
    // On failure this returns and nothing else has happened. The prior daemon is still
    // serving, still holding its bundle, and still denying what it denied a second ago.
    let config_path = config::openlatch_dir().join("config.toml");
    let re_init = config_path.exists();
    let mut re_init_report = if re_init {
        // `--api-url` is probed as an in-memory override: `persist_api_url` runs much
        // later, so on this run the file still names the old platform, and probing that
        // would gate on the reachability of an origin this install is leaving behind.
        run_egress_gate(args, args.api_url.as_deref(), output)?
    } else {
        GateReport::default()
    };

    // Step 0: Reclaim the ports.
    //
    // `init` is a complete reinstall: when it returns 0, the daemon serving
    // this machine is the one THIS binary started. That guarantee needs a step
    // that ends whatever was running before, and there wasn't one — `init`
    // spawned a daemon unconditionally, the child lost the bind race and exited
    // with `OL-1501` into a `/dev/null` stderr, and the health probe got its
    // 200 from the process already there. A daemon built in a since-deleted
    // worktree served this machine for forty hours across three installs that
    // each reported success.
    //
    // Before the token rotation a few lines below, deliberately: stopping the
    // old daemon gracefully means asking it over HTTP with the token it is
    // holding, which is the one on disk right now.
    //
    // Ports come from the pre-rotation config; the port-probing block below may
    // still move `cfg.port`, and reclaiming a port we are about to abandon is
    // both harmless and correct — it is the port a previous install pinned.
    let reclaim = {
        let pre_cfg = config::Config::load(None, None, false).unwrap_or_else(|_| {
            let mut c = config::Config::defaults();
            c.port = config::read_port_file().unwrap_or(c.port);
            c
        });
        let outcome = lifecycle::reclaim_ports(&pre_cfg, output)?;
        match outcome.action {
            lifecycle::ReclaimAction::Nothing => output.print_step("No prior daemon to reclaim"),
            lifecycle::ReclaimAction::Stopped => output.print_step(&format!(
                "Reclaimed daemon ({})",
                outcome.identity.describe()
            )),
            lifecycle::ReclaimAction::ForceKilled => output.print_step(&format!(
                "Force-killed unresponsive daemon ({})",
                outcome.identity.describe()
            )),
        }
        outcome
    };

    // Step 1: Detect agents (D-01).
    //
    // PLURAL. `init` used to wire `detect_agent()` — the FIRST agent — and
    // detection order is fixed with Claude Code first, so on a host carrying
    // both, Codex CLI's hooks file was never written at all: binding, writer
    // and manifest block all correct, and all unreached. Coverage is the
    // default; `--agent` is how an operator narrows it.
    let agents = hooks::detect_agents();
    let agents = hooks::select_agents(agents, &args.agent)?;
    if agents.is_empty() {
        report_no_agent(output);
        crate::cli::report::record_exit_code(EXIT_NO_AGENT);
        return Ok(());
    }
    for a in &agents {
        output.print_step(&format!("Detected agent: {}", agent_label(a)));
    }
    let found: Vec<&str> = agents.iter().map(DetectedAgent::display_name).collect();

    // Step 2: Regenerate token (D-02 — always regenerate)
    // Check if token file already existed to display the right message
    let token_path = ol_dir.join("daemon.token");
    let token_existed = token_path.exists();

    // Always regenerate: write a fresh token
    let new_token = config::generate_token();
    if !token_existed {
        ledger.record_file(&token_path);
    }
    std::fs::write(&token_path, &new_token).map_err(|e| {
        OlError::new(
            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.
    crate::fs_secure::restrict_to_owner(&token_path).map_err(|e| {
        OlError::new(
            ERR_INVALID_CONFIG,
            format!("Cannot set permissions on token file: {e}"),
        )
    })?;

    let token_action = if token_existed {
        "(regenerated existing)"
    } else {
        "(new)"
    };
    output.print_step(&format!("Generated auth token {token_action}"));

    // Step 3: Resolve port + write config (no hooks yet — see Step 7).
    //
    // Port probing: on first init (no config.toml) or --reconfig, probe 7443-7543
    // for a free port. On normal re-init, use the pinned port from existing config.
    // `config_path` was bound above, before the re-init gate that keys on its existence.
    let needs_port_probe = !config_path.exists() || args.reconfig;

    let port = if needs_port_probe {
        if args.reconfig {
            // Stop running daemon before rebinding (if any)
            let _ = lifecycle::run_stop(output);
            // Remove stale port file
            let _ = std::fs::remove_file(config::openlatch_dir().join("daemon.port"));
            // Remove old config so ensure_config writes fresh
            let _ = std::fs::remove_file(&config_path);
        }
        // An explicit OPENLATCH_PORT outranks probing. Probing picks a
        // default when the operator has expressed no preference; it is not an
        // override. Passing the probe result down as `cli_port` gave it
        // CLI-flag precedence, so `OPENLATCH_PORT=7599 openlatch init` pinned
        // 7443 and silently discarded the request — while probe_free_port's
        // own failure text tells the operator to "set OPENLATCH_PORT to a
        // specific port". init has no --port flag, so this env var is the only
        // way to express the intent at all.
        //
        // --reconfig still applies: it discards the previous pin above, then
        // lands on whatever the operator asked for here.
        let requested = std::env::var("OPENLATCH_PORT")
            .ok()
            .filter(|v| !v.trim().is_empty())
            .map(|v| config::parse_port_env(&v))
            .transpose()?;

        let selected = match requested {
            Some(p) => {
                // Fail loudly rather than probing past it. Silently binding a
                // different port is what produces a daemon and a settings.json
                // that disagree, and the hook fails open when they do.
                if std::net::TcpListener::bind(("127.0.0.1", p)).is_err() {
                    return Err(OlError::new(
                        ERR_PORT_IN_USE,
                        format!("OPENLATCH_PORT={p} is already in use"),
                    )
                    .with_suggestion(format!(
                        "Free port {p}, choose another via OPENLATCH_PORT, or unset it to probe {}-{} automatically.",
                        config::PORT_RANGE_START,
                        config::PORT_RANGE_END
                    ))
                    .with_docs("https://docs.openlatch.ai/errors/OL-1500"));
                }
                output.print_substep(&format!("Selected port {p} (from OPENLATCH_PORT)"));
                p
            }
            None => {
                let probed =
                    config::probe_free_port(config::PORT_RANGE_START, config::PORT_RANGE_END)?;
                output.print_substep(&format!("Selected port {probed} (first available)"));
                probed
            }
        };
        // Write config.toml with the selected port
        let config_existed = config_path.exists();
        config::ensure_config(selected)?;
        if !config_existed {
            ledger.record_file(&config_path);
        }
        // Write daemon.port file for hook binary discovery
        let port_file = config::openlatch_dir().join("daemon.port");
        let port_file_existed = port_file.exists();
        config::write_port_file(selected)?;
        if !port_file_existed {
            ledger.record_file(&port_file);
        }
        selected
    } else {
        config::Config::load(None, None, false)?.port
    };

    // D-11: ensure [daemon].agent_id is present before anything reads the
    // config. Without this, re-running `openlatch init` on an install that
    // predates the agent_id field leaves it blank and the daemon silently
    // forwards `agent_id = ""` to cloud on every event.
    config::ensure_agent_id(&config_path)?;

    // The `[proxy]` write `--reconfig` deferred, now that there is a file to put it in and
    // an agent_id to key the credential store by. Without this the gate would resolve,
    // probe and even prompt for a route, and then hand the daemon a config that has none.
    if let Some(outcome) = re_init_report.deferred.take() {
        proxy::persist_outcome(&config_path, &outcome, output)?;
    }

    // Must land before the auth flow below: `auth login` opens the browser at
    // `cloud.api_url`, so a --api-url applied afterwards would authenticate
    // against the wrong platform on the very run that set it.
    if let Some(api_url) = &args.api_url {
        config::persist_api_url(&config_path, api_url)?;
        output.print_substep(&format!("Cloud API URL set to {api_url}"));
    }

    // `--no-model-relay` must hold on every path, so it lands in config BEFORE the
    // config is loaded below.
    //
    // It used to be read in exactly one place — inside the `--foreground`
    // branch of the daemon start. The background paths, which are the default,
    // passed no model relay intent at all: the spawned daemon read `[model_relay]
    // enabled` from config, bound the port, and wrote `ANTHROPIC_BASE_URL` into
    // settings.json. So the documented opt-out did nothing unless you also
    // passed `--foreground`, and with live agent sessions on the machine the
    // flag read as a safety measure while being none.
    //
    // Persisted rather than passed down: `init` installs OS supervision by
    // default, so a one-shot flag would be undone by the supervisor's next
    // start. Config is the only place the intent survives.
    if args.no_model_relay {
        config::persist_model_relay_enabled(&config_path, false)?;
        output.print_substep(
            "Model relay disabled in config — agents connect to the provider directly",
        );
    }

    let cfg = config::Config::load(Some(port), None, false)?;

    // [C] The FRESH gate — after the config and ports resolved (so the probe targets the
    // right `api_url`), and BEFORE the auth flow.
    //
    // The order is not a preference. `run_auth_for_init` is itself a cloud consumer: on a
    // host with no credential it falls through to `run_login`, which binds a callback
    // server and waits up to 300 seconds for a browser. A gate placed after it would let
    // the hero case — a headless, proxied, fresh install — block for five minutes and then
    // fail with an auth error that says nothing about a proxy. The probe needs no
    // credential of its own: `/api/v1/health` is unauthenticated.
    //
    // `settings.json` is still untouched at this line (hooks land further down), so a
    // failure here leaves the agent's own config byte-identical.
    let gate_report = if re_init {
        // Already run above, before anything destructive. Re-running it would spend a
        // second round of probes to learn what the first one settled.
        re_init_report
    } else {
        match run_egress_gate(args, args.api_url.as_deref(), output) {
            Ok(report) => report,
            Err(e) => {
                // D-8: a fresh install that cannot reach the platform leaves NOTHING. Not
                // a token, not a config, not a port file, and not a directory this run
                // created — an install that is not enforcing must not look like one.
                // The rail's transcript included: after the ledger it moves to the temp
                // directory, taking the directories it created with it, so the log the
                // card points at survives the rollback.
                ledger.unwind(output);
                ui::take_back_log();
                return Err(e);
            }
        }
    };
    ui::done(&format!("found {}", words(&found)));

    // Step 4: Auth flow (D-06, D-07, D-09).
    // Runs BEFORE hook installation so a canceled / failed auth leaves no
    // broken hooks pointing at a half-configured daemon.
    ui::stage_named("Sign in", "Signing in", "Signed in");
    let (auth_success, org_name) = run_auth_for_init(output, args.yes)?;
    ui::done(&org_name);

    // Step 4.5: Telemetry consent (moved before hooks for foreground mode).
    ui::stage("Usage data", "Usage data");
    let consent = handle_telemetry_consent(args, output, &ol_dir)?;
    ui::done(consent);

    let connecting: Vec<&str> = agents
        .iter()
        .filter(|a| a.installable())
        .map(DetectedAgent::display_name)
        .collect();
    let (name, running) = match connecting.as_slice() {
        [one] => (format!("Connect {one}"), format!("Connecting {one}")),
        _ => (
            "Connect your agents".to_string(),
            "Connecting your agents".to_string(),
        ),
    };
    ui::stage_named(
        &name,
        &running,
        &format!("Connected {}", words(&connecting)),
    );

    // Step 4.55: Stage the hook binary into `<ol_dir>/bin/` BEFORE writing any
    // hook command.
    //
    // `resolve_hook_binary_path()` has always documented this directory as "the
    // canonical install location populated by `openlatch init` on the first
    // run", and nothing populated it — the only staging in the tree lived in
    // `doctor --fix`. On a machine whose `openlatch` had no `openlatch-hook`
    // sibling, the resolver fell through to a bare name, `init` wrote it into
    // all 12 entries, and every tool call in every session died with
    // `openlatch-hook: command not found` — invisibly, because the hook fails
    // open. Failing here is the point: an install that cannot resolve its own
    // hook binary is not a successful install, and settings.json is still
    // untouched at this line.
    let staged = hooks::staging::stage_hook_binary(&ol_dir)?;
    output.print_step(&format!("Hook binary at {}", staged.target().display()));

    // Step 4.6: Install hooks BEFORE daemon start. This is critical for
    // --foreground mode where run_daemon_foreground blocks forever — hooks
    // must be installed before the daemon starts so the reconciler finds them.
    let installed = install_for_agents(&agents, cfg.port, &new_token, output)?;
    let connected: Vec<&str> = installed.iter().map(|(a, _)| a.display_name()).collect();
    if connected.len() < connecting.len() {
        // One wired agent is an install; the rest were each reported as a note above.
        ui::relabel(&format!("Connected {}", words(&connected)));
    }
    ui::done("actions now go through OpenLatch");

    // NOTE: `init` deliberately does NOT write the model-relay wiring.
    //
    // It used to, right here, before anything had bound the pinned port — and
    // `init --foreground` then started a daemon that never bound it, so
    // `ANTHROPIC_BASE_URL` pointed every Claude Code session on the machine at a
    // port nobody held. The write now belongs to the daemon, which does it after
    // its bind succeeds and undoes it when it stops (`daemon::serve_with_listener`).
    // `init` starts the daemon a few lines below; that is what wires the agent.

    // Step 4.65: the model relay CA in the user's own trust store (I-2 D-19/D-29). Only when a
    // detected agent declares the intercepting convention; never from an isolated instance.
    // Supervision may start the daemon (Step 4.7, right after), and the daemon's first tick must
    // find the CA already trusted, or it answers `Failed` and `init`'s preflight wait reports it.
    #[cfg(feature = "model-relay")]
    if cfg.model_relay.enabled && !args.no_model_relay {
        use crate::model_relay::trust_store::{install_command, InstallOutcome};
        let ca_pem = crate::model_relay::ca::ca_pem_path(&crate::model_relay::ca::ca_dir(&ol_dir));
        match crate::daemon::ensure_proxy_env_trust(&cfg, &agents, crate::supervision::owns_machine_supervision())
        {
            None => {}
            Some(InstallOutcome::Installed) => output.print_substep(
                "Trusted the OpenLatch model relay CA in your user trust store",
            ),
            Some(InstallOutcome::AlreadyTrusted) => {
                output.print_substep("The OpenLatch model relay CA is already trusted")
            }
            Some(InstallOutcome::NoGuiSession) => output.print_note(&format!(
                "{}: no desktop session can answer the trust prompt, so intercepted model calls \
                 are not captured yet. Run `openlatch doctor --fix` from a desktop terminal, or: {}",
                crate::error::ERR_MODEL_RELAY_CA_UNTRUSTED,
                install_command(&ca_pem)
            )),
            Some(InstallOutcome::Refused(why)) => output.print_note(&format!(
                "{}: the model relay CA was not trusted ({why}), so intercepted model calls are \
                 not captured. Run `openlatch doctor --fix`, or: {}",
                crate::error::ERR_MODEL_RELAY_CA_UNTRUSTED,
                install_command(&ca_pem)
            )),
        }
    }

    // Step 4.7: Install OS-native supervision (launchd / systemd-user / Task Scheduler).
    // Default-on: absence of --no-persistence means install. Skipped when the user
    // explicitly asked for a foreground session, --no-start, or --no-persistence.
    ui::stage_named("Start OpenLatch", "Starting OpenLatch", "Started OpenLatch");
    let (supervision_backend_label, supervision_mode_label, supervision_deferred_reason) =
        run_supervision_install_for_init(args, &config_path, output);
    let at_login = if supervision_mode_label == "active" {
        "starts at login"
    } else if args.no_persistence {
        "won't restart at login (--no-persistence)"
    } else {
        "won't restart at login"
    };

    // Step 5: Start daemon (D-05) — skip if --no-start
    let start_plan = plan_daemon_start(
        args.no_start,
        args.foreground,
        supervision_mode_label == "active",
    );
    // Set when the foreground daemon below was stopped by a signal rather than by itself.
    // Nothing above the daemon can set it, and nothing below it may report as though the
    // daemon were still up.
    let mut interrupted = false;
    // The card's `Runs` row and Starting OpenLatch's result.
    let mut runs = format!("in the background · {at_login}");
    let (port, pid) = if start_plan == DaemonStartPlan::Skip {
        output.print_step("Skipped daemon start (--no-start)");
        runs = "not started (--no-start)".to_string();
        (cfg.port, 0u32)
    } else if start_plan == DaemonStartPlan::SupervisorOwned {
        // The supervisor already started a daemon, a few lines above:
        // `systemctl enable --now`, launchd's `RunAtLoad` and Task Scheduler's
        // `/Run` after `/Create` all start the unit at INSTALL time. Spawning
        // one here as well is what produced the 130-restart loop — two daemons
        // racing for port 7443, and whichever lost exited 0 straight into
        // `Restart=always`. There is one owner, and from here `init` only
        // waits for it.
        // Version-matched, not merely reachable. A supervised unit that failed
        // to restart leaves the PREVIOUS daemon answering /health, and waiting
        // for a 200 accepts it — which is how an install that changed nothing
        // reported a fresh start.
        match lifecycle::verify_running_daemon(cfg.port, 10) {
            Ok(pid) => {
                output.print_step(&format!(
                    "Daemon started on port {} (PID {pid}, supervised, v{})",
                    cfg.port,
                    env!("OPENLATCH_VERSION")
                ));
                (cfg.port, pid)
            }
            Err(lifecycle::StartFailure::VersionMismatch { serving, expected }) => {
                // Someone else's daemon owns the port. Spawning a second one
                // would be the two-owner bug in a new costume.
                let e = lifecycle::start_failure_error(
                    lifecycle::StartFailure::VersionMismatch { serving, expected },
                    cfg.port,
                );
                return Err(e);
            }
            Err(_)
                if lifecycle::read_pid_file()
                    .filter(|p| lifecycle::is_process_alive(*p))
                    .is_some() =>
            {
                // A supervised daemon exists and is simply not serving yet.
                // Spawning a second one here would not help: whatever is
                // keeping that process from answering would stop a fresh one
                // too.
                let pid = lifecycle::read_pid_file().unwrap_or(0);
                output.print_step(&format!(
                    "Daemon starting under supervision (PID {pid}) — not yet answering /health"
                ));
                output.print_info(
                    "  Check `openlatch status` shortly, or the newest ~/.openlatch/logs/daemon.log.<date>.",
                );
                runs = format!("starting in the background · {at_login}");
                (cfg.port, pid)
            }
            Err(_) => {
                // Nothing is running and nothing is starting: the supervisor
                // accepted the install but demonstrably started nothing. THIS
                // is the case the direct spawn exists for.
                tracing::warn!(
                    "supervision reported active but no daemon came up; starting one directly"
                );
                start_and_prove(cfg.port, &new_token, output)?
            }
        }
    } else if args.foreground {
        // Where the install report would have been. This shell belongs to the daemon from
        // the next line until it stops, so Step 6 can only ever run once the thing it wants
        // to measure is gone — there is no moment on this path at which a trailing report
        // would be true. The check still exists; it just has to be run from somewhere else.
        output.print_notice(
            "Run `openlatch doctor` in another shell to check this install while it is up",
        );
        // Foreground mode: start inline (blocking). We print the step first, then call.
        output.print_step(&format!(
            "Starting daemon on port {} (foreground)",
            cfg.port
        ));
        // The foreground daemon IS the daemon — there is no background one
        // behind it — so it must bind the model relay and own the agent wiring,
        // exactly like `openlatch start`. Passing `false` here is what made
        // `init --foreground` deterministically break every Claude Code session
        // on the machine.
        //
        // `args.no_model_relay` is deliberately NOT consulted here any more: it was
        // persisted into config above, so `cfg.model_relay.enabled` already carries
        // it. One source of truth is the point — this branch reading the flag
        // while the background branches did not is exactly how the opt-out came
        // to hold on one path out of three.
        #[cfg(feature = "model-relay")]
        let spawn_model_relay = cfg.model_relay.enabled;
        #[cfg(not(feature = "model-relay"))]
        let spawn_model_relay = false;
        // The rail ends here: from the next line this terminal is the daemon's.
        ui::done("running in this terminal");
        ui::outro("Running in the foreground · Ctrl+C to stop");
        // A hand-over to an updated binary leaves the daemon restarting, and the
        // report would measure that gap: it is skipped as an interrupt's is.
        interrupted = run_daemon_foreground(cfg.port, &new_token, spawn_model_relay)?
            != lifecycle::Stopped::Exited;
        (cfg.port, std::process::id())
    } else {
        start_and_prove(cfg.port, &new_token, output)?
    };

    // Step 5.5: The model relay must be proven, not assumed.
    //
    // Everything above can succeed against a model relay that binds its port and
    // cannot forward a single byte, and that install is worse than no install:
    // `ANTHROPIC_BASE_URL` would point every Claude Code session on the machine
    // at a listener that answers 502. The daemon gates the write on a real round
    // trip; this reads its verdict and refuses to report success without one.
    #[cfg(feature = "model-relay")]
    verify_model_relay_preflight(args, &cfg, start_plan, output)?;

    // Step 4.5: Show cloud sync status (D-08)
    if auth_success {
        let cloud_msg = if org_name.is_empty() {
            "Cloud sync: enabled".to_string()
        } else {
            format!("Cloud sync: connected (org: {org_name})")
        };
        output.print_step(&cloud_msg);
        output.print_info("  Events will be forwarded automatically");
    }
    if start_plan == DaemonStartPlan::Skip {
        ui::relabel("Set up OpenLatch");
        ui::done("not started (--no-start)");
    } else {
        ui::done(runs.replacen("in the background", "running", 1).as_str());
    }

    // Step 6: Report what the install actually produced.
    //
    // Every line above says what `init` *did*; none of them says what is
    // *true* afterwards, and the gap between the two is where this command
    // spent two days claiming success on a machine it had not touched. The
    // report is measured after the fact, by the same code `openlatch doctor`
    // runs, so the two can never drift into disagreeing about the same host.
    //
    // It measures the host with the same detectors `openlatch doctor` uses, and after
    // an interrupt it would be measuring a daemon the operator stopped a second ago: every
    // section behind it reads `waiting on: Daemon`, and the verdict comes out `BROKEN` on an
    // install that is fine. That report describes the keystroke, not the machine — the same
    // reasoning `build_install_report` already applies to `--no-start`, which is why this
    // does not try to relabel the sections: with the daemon deliberately gone there is no
    // question left for them to answer.
    //
    // Only the report. The model relay preflight and the cloud-sync line above ran while the
    // daemon was still up and are statements about what the install did, not about what is
    // true now.
    //
    // The foreground path closed its rail before the daemon took the terminal, so it gets
    // no stage and no card — only the verdict, for the exit status and `--json`.
    let on_rail = start_plan != DaemonStartPlan::Foreground;
    if on_rail {
        ui::stage_named("Final checks", "Running final checks", "Final checks");
    }
    let install_report = if interrupted {
        None
    } else {
        final_checks(args, output)
    };
    let today = chrono::Local::now().format("%Y-%m-%d");
    let log_path = config::openlatch_dir()
        .join("logs")
        .join(format!("events-{today}.jsonl"));

    // The exit status is the customer verdict, not a constant and not doctor's: a
    // warning that is a known coverage limit or settles by itself leaves the machine
    // live (0); one the user has to act on is 7; any failure is 1. A model relay
    // switched off in config by nobody in this invocation is such a warning — it lands
    // on the amber card, where it cannot scroll past.
    let verdict = install_report.as_ref().map(Report::setup_verdict);
    let exit_code = verdict.map_or(0, verdict_exit_code);
    if let Some(report) = &install_report {
        crate::cli::report::record_exit_code(exit_code);
        if on_rail {
            let wired: Vec<(&'static str, &'static str)> = installed
                .iter()
                .map(|(a, _)| (a.agent_type(), a.display_name()))
                .collect();
            let api_url = cfg.cloud.api_url.clone();
            let facts = CardFacts {
                org: &org_name,
                agents: &wired,
                runs: &runs,
                no_start: args.no_start,
                console_url: &api_url,
            };
            report_verdict(report, &facts, exit_code);
        }
    }

    // Telemetry: emit cli_initialized after the install completes successfully.
    //
    // One event per agent, each carrying that agent's own entry count. A
    // single event naming the first agent would report a one-agent install on
    // a host where two were wired.
    for (a, result) in &installed {
        telemetry::capture_global(Event::cli_initialized(
            a.agent_type(),
            result.entries.len(),
            !token_existed,
        ));
    }
    telemetry::capture_global(Event::supervision_installed(
        supervision_backend_label,
        supervision_mode_label,
        supervision_deferred_reason.as_deref(),
    ));

    // JSON output mode: emit single JSON object
    if output.format == OutputFormat::Json {
        // N agents, not one. The singular `"agent"` and the flat `"hooks"`
        // event-name list are both gone: they described one install, and one
        // install is now the special case. Each element carries its own
        // settings path, entry count and event names, so support tooling can
        // tell which agent got what rather than inferring it.
        let agents_json: Vec<serde_json::Value> = installed
            .iter()
            .map(|(a, result)| {
                serde_json::json!({
                    "agent": a.agent_type(),
                    "settings_path": a.settings_path().to_string_lossy(),
                    "entries": result.entries.len(),
                    "events": result
                        .entries
                        .iter()
                        .map(|e| e.event_type.as_str())
                        .collect::<Vec<_>>(),
                })
            })
            .collect();

        let cloud_status = if auth_success {
            "connected"
        } else {
            "not_configured"
        };
        let json = serde_json::json!({
            // Derived, never a constant. `"status": "ok"` was hardcoded here,
            // so `init --json` reported a healthy install on a host whose
            // model relay was off and whose daemon was somebody else's process.
            "status": install_report
                .as_ref()
                .map(|r| r.overall().key())
                .unwrap_or("unknown"),
            // The process's own exit status: the customer verdict below, not doctor's.
            "exit_code": exit_code,
            // Additive: `live` | `attention` | `not_live`, the `result=` vocabulary.
            "verdict": verdict.map(SetupVerdict::key),
            "reclaimed": {
                "action": match reclaim.action {
                    lifecycle::ReclaimAction::Nothing => "nothing",
                    lifecycle::ReclaimAction::Stopped => "stopped",
                    lifecycle::ReclaimAction::ForceKilled => "force_killed",
                },
                "pid": reclaim.identity.pid,
                "version": reclaim.identity.version,
                "uptime_secs": reclaim.identity.uptime_secs,
                "exe": reclaim.identity.exe,
            },
            // The eleven sections, identical in shape to `doctor --json`. The
            // model relay in particular had no representation here at all, which
            // is why a scripted install could not tell that the one subsystem
            // it cared about had not come up.
            "report": install_report.as_ref().map(crate::cli::report::Report::to_json),
            "agents": agents_json,
            "port": port,
            "pid": pid,
            "log_path": log_path.to_string_lossy(),
            "token_action": token_action,
            "daemon_started": !args.no_start,
            "cloud_status": cloud_status,
            "org_name": org_name,
            "supervision": {
                "mode": supervision_mode_label,
                "backend": supervision_backend_label,
                "disabled_reason": supervision_deferred_reason,
            },
            // The frozen `init --json` success shape. `prompted` is what tells a scripted
            // install whether a human had to intervene — the zero-question install is the
            // product claim, and this field is how it is measured rather than asserted.
            "proxy": {
                "source": gate_report.source,
                "url_masked": gate_report.url_masked,
                "prompted": gate_report.prompted,
            },
        });
        output.print_json(&json);
    }

    Ok(())
}

// ---------------------------------------------------------------------------
// The egress gate (Proxy Support I-2 — F-06, F-08, F-17)
// ---------------------------------------------------------------------------

/// One artifact `init` created on THIS run, and can therefore take back.
///
/// The list is short on purpose: it holds only what can exist before the fresh gate fires.
/// Hooks, supervision, the daemon and the model relay wiring never appear, because all of them
/// install *after* the gate — D-03's "no rollback" stands for every failure past it.
#[derive(Debug, Clone)]
enum InitArtifact {
    /// A file this run wrote where there was none.
    File(std::path::PathBuf),
    /// A directory `create_dir_all` brought into existence. Removed non-recursively and
    /// last, so a directory that acquired other content keeps it.
    Directory(std::path::PathBuf),
}

/// What `init` created before the gate ran, so a failed gate can leave nothing behind.
///
/// **A deliberate, scoped amendment to D-03 ("init performs no rollback").** The egress gate
/// is the one step whose failure contract demands one: D-8 says a fresh install that cannot
/// reach the platform leaves *nothing running*, and a fresh install with no policy bundle is
/// not an install — it is a host carrying a token and a config and enforcing nothing, which
/// reads as a successful install to every later command that looks at it.
///
/// Only artifacts recorded here are ever deleted. A `config.toml` that existed before this
/// process started never enters the ledger, so no code path can reach it — pre-existing
/// state is structurally untouchable rather than untouched by convention. Unwind order
/// mirrors `run_uninstall`'s: files first, directories last.
#[derive(Default)]
struct InitLedger {
    created: Vec<InitArtifact>,
}

impl InitLedger {
    /// Record a file this run created. Called immediately after the write succeeds, and
    /// only when the path did not exist beforehand.
    fn record_file(&mut self, path: &std::path::Path) {
        self.created.push(InitArtifact::File(path.to_path_buf()));
    }

    /// `create_dir_all`, recording the path only when it really did create it.
    fn create_dir(&mut self, path: &std::path::Path) -> std::io::Result<()> {
        let existed = path.exists();
        std::fs::create_dir_all(path)?;
        if !existed {
            self.created
                .push(InitArtifact::Directory(path.to_path_buf()));
        }
        Ok(())
    }

    /// Delete everything this run created, best effort.
    ///
    /// Every failure is swallowed: unwind runs on the way out of an already-failing
    /// command, and a second error stacked on the first tells the operator nothing they can
    /// act on. Directories go through `remove_dir`, never `remove_dir_all` — a directory
    /// that gained content this ledger does not know about keeps it, and the empty case
    /// (the only one we create) still cleans up.
    fn unwind(&self, output: &OutputConfig) {
        if self.created.is_empty() {
            return;
        }
        let mut dirs = Vec::new();
        for artifact in &self.created {
            match artifact {
                InitArtifact::File(p) => {
                    let _ = std::fs::remove_file(p);
                }
                InitArtifact::Directory(p) => dirs.push(p),
            }
        }
        // Deepest first, so `logs/` is gone before `~/.openlatch` is tried.
        dirs.sort_by_key(|p| std::cmp::Reverse(p.components().count()));
        for dir in dirs {
            let _ = std::fs::remove_dir(dir);
        }
        output.print_substep("Rolled back — this host is as `init` found it");
    }
}

/// `init`'s install loop — every detected agent, one write each.
///
/// Lifted out of [`run_init`] for one reason: the skip below is otherwise only
/// reachable through a full `init`, which needs a credential, a reachable
/// platform and a daemon. A guard nobody can test is a guard nobody can prove.
///
/// **ONE INSTALL PER AGENT, and a failure does not abort the loop.** A Codex CLI
/// failure must not leave Claude Code unwired on a host that had both: partial
/// coverage beats none, and every failure is reported. Nothing here unwinds the
/// `InitLedger` either — the ledger exists for the egress gate, which ran long
/// before this point, and unwinding here would delete the token and config a
/// successfully wired agent now depends on.
///
/// # Errors
///
/// Only when the loop wired **nothing**: one wired agent is an install. See
/// [`nothing_installed_err`] for which of the two codes comes back.
fn install_for_agents<'a>(
    agents: &'a [DetectedAgent],
    port: u16,
    token: &str,
    output: &OutputConfig,
) -> Result<Vec<(&'a DetectedAgent, hooks::HookInstallResult)>, OlError> {
    let mut installed: Vec<(&DetectedAgent, hooks::HookInstallResult)> = Vec::new();
    let mut install_failures: Vec<OlError> = Vec::new();
    let mut skipped_non_installable: Vec<&'static str> = Vec::new();

    for a in agents {
        // Skipped BEFORE `install_hooks`, not left to it. The primitive is the
        // backstop and refuses too — but it refuses by returning `Ok` with zero
        // entries, and `Ok` is exactly what the arm below counts as installed.
        // Routing a non-installable agent through it would print "Hooks written
        // to …" about a path this build has never touched and push the agent
        // onto `installed`. "We wrote nothing" and "we wired the agent" must not
        // be the same value, and `HookInstallResult` cannot tell them apart.
        if !a.installable() {
            output.print_notice(&format!(
                "Skipping {} — detected, but this build writes no hooks into it.",
                a.display_name()
            ));
            skipped_non_installable.push(a.display_name());
            continue;
        }

        match hooks::install_hooks(&*a.binding, port, token) {
            Ok(result) => {
                output.print_step(&format!("Hooks written to {}", a.settings_path().display()));
                for entry in &result.entries {
                    let action_label = match entry.action {
                        hooks::HookAction::Added => "added",
                        hooks::HookAction::Replaced => "replaced",
                    };
                    output.print_substep(&format!("{} ({})", entry.event_type, action_label));
                }
                installed.push((a, result));
            }
            Err(e) => {
                output.print_notice(&format!(
                    "Warning: could not write hooks for {}: {} ({})",
                    a.display_name(),
                    e.message,
                    e.code
                ));
                install_failures.push(e);
            }
        }
    }

    // Non-zero only when EVERY agent failed. One wired agent is an install; the
    // failures were printed above and `doctor` is what reports the residual
    // state.
    if installed.is_empty() {
        return Err(install_failures
            .into_iter()
            .next()
            .unwrap_or_else(|| nothing_installed_err(&skipped_non_installable)));
    }

    Ok(installed)
}

/// The error `init` reports when the install loop wired nothing at all.
///
/// Two different facts end here, and they must not be told as one. "No agent"
/// is `OL-1400` — install one and try again. "Every agent we could see
/// declares no writable hook surface" is `OL-1407`: the agent IS here, we DID
/// see it, and this build writes no hooks into it. `OL-1400`'s remedy — install
/// the agent — is actively wrong advice in that state.
///
/// **This distinction is the whole test.** On a build without it,
/// `openlatch init --agent cline` *already* exits non-zero, because
/// [`hooks::select_agents`] rejects an undetected name with
/// `ERR_HOOK_AGENT_NOT_FOUND`. So an assertion that only checks "non-zero"
/// passes against a tree that has none of this — the CODE is the assertion.
///
/// `install_failures` wins when there is one: a real write failure on one agent
/// is a more actionable answer than the skip of another.
fn nothing_installed_err(skipped_non_installable: &[&'static str]) -> OlError {
    if skipped_non_installable.is_empty() {
        return hooks::agent_not_found_err();
    }
    OlError::new(
        crate::error::ERR_HOOK_AGENT_NOT_INSTALLABLE,
        format!(
            "No hooks were installed: {} detected, and this build writes no hooks into {}",
            skipped_non_installable.join(", "),
            if skipped_non_installable.len() == 1 {
                "it"
            } else {
                "any of them"
            }
        ),
    )
    .with_suggestion(
        "Omit --agent to cover every agent on this host, or name one this build can install into."
            .to_string(),
    )
    .with_docs("https://docs.openlatch.ai/errors/OL-1407")
}

/// `init --dry-run` — say what would happen to the egress route, and touch nothing.
///
/// **Runs before every mutating step, the `create_dir_all` calls included.** On a fresh host
/// those calls create `~/.openlatch`, and a dry run that leaves a directory behind has not
/// told the truth about touching no disk. The distinction matters most to the people most
/// likely to reach for the flag: an operator evaluating the installer on a locked-down build
/// host before they are allowed to run it for real.
///
/// The network *is* reached — "would this install find a route?" is the whole question — and
/// nothing is written whatever the answer.
///
/// # Errors
///
/// Propagates a `[proxy]` block that does not parse, a `--proxy` carrying userinfo, and a
/// `pac_url` on Linux. All three are input defects the operator can see and fix, and
/// surfacing them without side effects is what a dry run is for.
fn run_dry_run(args: &InitArgs, output: &OutputConfig) -> Result<(), OlError> {
    let config_path = config::openlatch_dir().join("config.toml");
    let cfg = config::Config::load(None, None, false)?;
    let api_url = args
        .api_url
        .clone()
        .unwrap_or_else(|| cfg.cloud.api_url.clone());

    let overrides = proxy::ProxyOverrides::from_init(args);
    overrides.validate()?;
    let mut egress_cfg = outgoing_egress(args, &cfg)?;
    overrides.apply(&mut egress_cfg)?;
    proxy::refuse_linux_pac(&egress_cfg)?;

    // A dry run's whole claim is "this is what the real run would do", so it reads the file
    // exactly as far as the real run would: on `--reconfig`, not at all.
    let persisted_source = if args.reconfig {
        None
    } else {
        proxy::PersistedProxy::read(&config_path).source
    };
    let probe_ok = probe_current_route(&api_url, &egress_cfg);

    // Three actions, each a statement about `[proxy]` and nothing else:
    //   keep     — `init` would write nothing there
    //   persist  — `init` would record the working route it found outside the file
    //   discover — `init` would go looking, because nothing it already has works
    let (action, source) = if persisted_source.as_deref() == Some("manual") {
        // Never re-decided, working or not: automation does not overwrite a human (D-7).
        ("keep", persisted_source.clone())
    } else if probe_ok {
        match &persisted_source {
            Some(s) => ("keep", Some(s.clone())),
            None if egress_cfg.has_proxy() => ("persist", Some("env".to_string())),
            None => ("keep", None),
        }
    } else {
        ("discover", None)
    };

    if output.format == OutputFormat::Json {
        let mut proxy_doc = serde_json::json!({ "action": action });
        if let Some(s) = &source {
            proxy_doc["source"] = serde_json::json!(s);
        }
        output.print_json(&serde_json::json!({
            "status": "ok",
            "dry_run": true,
            "api_url": api_url,
            "proxy": proxy_doc,
        }));
    } else {
        output.print_step("Dry run — nothing was written");
        output.print_substep(&format!("api_url   {api_url}"));
        match &source {
            Some(s) => output.print_substep(&format!("proxy     {action} (source: {s})")),
            None => output.print_substep(&format!("proxy     {action}")),
        }
    }
    Ok(())
}

/// The egress route as this run will **leave** it, which is not always the one it found.
///
/// `--reconfig` deletes `config.toml` a few steps into `run_init` and writes a fresh one
/// from the default template, so on that run the `[proxy]` block is not this install's
/// route — it is the route of the install being replaced. Reading it made `init` open with
///
/// ```text
/// ✓ proxy via http://127.0.0.1:3128 (manual)
/// ```
///
/// on a host that, forty seconds later, answered `openlatch system proxy status` with `direct — no
/// proxy set`. The wrong line was the visible half; the dangerous half is that the *probe*
/// used that route too, so a host whose only path to the platform was that proxy passed the
/// gate and then ran with a config that had none.
///
/// Resolving with no `[proxy]` block is exactly the post-reset world: tier 2 and the
/// discovery ladder — the environment and the OS settings — survive the rewrite, and the
/// file does not. It is the same rule `--api-url` is already applied under a few lines up:
/// probe what this run leaves behind, never what it is leaving.
///
/// `Config::load` attached the stored proxy password on the other path; here there is no
/// persisted authority to attach one to.
///
/// # Errors
///
/// A `[proxy]` block or `OPENLATCH_PROXY*` variable that does not parse (D-9).
fn outgoing_egress(
    args: &InitArgs,
    cfg: &config::Config,
) -> Result<crate::egress::EgressConfig, OlError> {
    if !args.reconfig {
        return Ok(cfg.egress.clone());
    }
    crate::egress::EgressConfig::resolve(
        None,
        &crate::egress::ProcessEnv,
        cfg.port,
        cfg.model_relay.port,
    )
}

/// One read-only probe of the route as it currently resolves.
fn probe_current_route(api_url: &str, egress_cfg: &crate::egress::EgressConfig) -> bool {
    use crate::egress::CandidateProbe;
    let Ok(probe) = crate::egress::HealthProbe::new(api_url, egress_cfg.clone()) else {
        return false;
    };
    let via = egress_cfg
        .url
        .as_deref()
        .filter(|_| egress_cfg.mode != crate::egress::ProxyMode::Direct)
        .and_then(|u| reqwest::Url::parse(u).ok());
    probe.probe(via.as_ref()).is_ok()
}

/// What the gate decided, for `init --json`'s success document.
#[derive(Default)]
struct GateReport {
    source: Option<String>,
    url_masked: Option<String>,
    prompted: bool,
    /// The route the gate settled on, carried only when the caller still owes it a write.
    /// `--reconfig` deletes the file the gate would have written into, so its outcome is
    /// persisted by `run_init` once the fresh one exists.
    deferred: Option<proxy::GateOutcome>,
}

/// Run the egress gate: resolve, probe, discover, and — when someone is there — prompt.
///
/// The placement of each call site is the contract:
///
/// - **Re-init** runs before `reclaim_ports`, so a failure leaves the prior daemon running
///   and its resident bundle enforcing. A network condition must never take down a working
///   installation (D-8, fail-static).
/// - **Fresh** runs before `run_auth_for_init`, because the auth flow is itself a cloud
///   consumer: on a host with no credential it binds a callback server and waits up to 300
///   seconds for a browser. A gate after it would let the hero case — a headless, proxied,
///   fresh install — block for five minutes and then die with an auth error naming nothing
///   about the proxy.
///
/// `api_url_override` carries `--api-url` as an **in-memory** override. `persist_api_url`
/// runs later in `run_init`, so on the very run that changes the platform origin the file
/// still names the old one, and probing that would measure the reachability of a platform
/// this install is leaving.
///
/// # Errors
///
/// `OL-1220` / `OL-1221` when nothing reached the platform. What that means is the caller's
/// decision: the re-init path returns untouched, the fresh path unwinds its ledger first.
fn run_egress_gate(
    args: &InitArgs,
    api_url_override: Option<&str>,
    output: &OutputConfig,
) -> Result<GateReport, OlError> {
    let cfg = config::Config::load(None, None, false)?;
    let api_url = api_url_override
        .map(str::to_string)
        .unwrap_or_else(|| cfg.cloud.api_url.clone());

    let overrides = proxy::ProxyOverrides::from_init(args);
    // Before any step runs: argv is world-readable, so a `--proxy` carrying a credential is
    // refused here rather than at the point it would be used.
    overrides.validate()?;

    let base = outgoing_egress(args, &cfg)?;

    // The interactivity gate, evaluated once. `--yes` forces headless semantics even on a
    // terminal, which is the only way to script an install from an interactive shell.
    let mut terminal = crate::cli::prompt::TerminalPrompter::new(api_url.clone());
    let prompter: Option<&mut dyn crate::cli::prompt::Prompter> =
        if crate::cli::prompt::interactive(output, args.yes) {
            Some(&mut terminal)
        } else {
            None
        };

    let config_path = config::openlatch_dir().join("config.toml");
    // Same rule: on `--reconfig` nothing in the file survives, so nothing in it is "already
    // recorded". Reading it would make the gate skip the one write that gives the fresh
    // config a route at all — that idempotency check is what made the old bug silent.
    let persisted = if args.reconfig {
        proxy::PersistedProxy::default()
    } else {
        proxy::PersistedProxy::read(&config_path)
    };

    let outcome = match proxy::run_gate(&api_url, base, &overrides, &persisted, prompter, output) {
        Ok(o) => o,
        Err(failure) => {
            report_gate_failure(&failure, &api_url, args, output);
            return Err(failure.error);
        }
    };

    // The ONE write the re-init path allows, and it is surgical: `[proxy]` keys only, never
    // the ports and never the token. Everything destructive is still ahead of this line.
    //
    // `config_path.exists()` is a real condition, not belt-and-braces: on the fresh path the
    // file was created a few steps up, but the re-init gate runs before anything writes, so a
    // host with no config at all reaches this line with nothing to persist into.
    //
    // `--reconfig` is the one run that must NOT write here: the file this would write into
    // is deleted a few steps down. The outcome rides back to `run_init` instead and is
    // persisted into the fresh `config.toml`, after `ensure_agent_id` — which is also the
    // correct moment for `captured`, since the credential store is keyed by the agent_id
    // this run mints, not the one it replaced.
    let has_writes = !outcome.sets.is_empty() || !outcome.removes.is_empty();
    if has_writes && config_path.exists() && !args.reconfig {
        proxy::persist_outcome(&config_path, &outcome, output)?;
    }

    let probed = outcome.attempts.iter().filter(|a| a.was_probed()).count();
    proxy::emit_proxy_configured(&outcome.config, probed, None);

    let route = outcome
        .config
        .url
        .as_deref()
        .map(crate::egress::mask_userinfo);
    match (outcome.source_str(), &route) {
        (Some(source), Some(url)) => output.print_step(&format!("proxy via {url} ({source})")),
        (Some(source), None) => {
            output.print_step(&format!("Cloud reachable (proxy source: {source})"));
        }
        (None, _) => output.print_step("Cloud reachable (direct)"),
    }

    Ok(GateReport {
        source: outcome.source_str().map(str::to_string),
        url_masked: route,
        prompted: outcome.prompted,
        deferred: (has_writes && args.reconfig).then_some(outcome),
    })
}

/// Print the failed gate's candidate report.
///
/// **JSON on clean stdout, human lines on stderr** — the pip `--report -` split. A script
/// that ran `init --json` behind a proxy it could not reach must be able to parse the
/// document naming every route that was tried, without a log line landing in the middle of
/// it. The message names `--yes` when the run was headless, because "it did not ask" is the
/// single most confusing part of a headless failure (the rustup pattern).
fn report_gate_failure(
    failure: &proxy::GateFailure,
    api_url: &str,
    args: &InitArgs,
    output: &OutputConfig,
) {
    let headless = !crate::cli::prompt::interactive(output, args.yes);
    let hint = if headless {
        "No terminal to prompt on (or `--yes` was passed), so no proxy was requested. Set one \
         with `openlatch init --proxy <url>` or `openlatch system proxy set <url>`, or run \
         `openlatch init` interactively without `--yes`."
            .to_string()
    } else {
        failure.error.suggestion.clone().unwrap_or_default()
    };

    if output.format == OutputFormat::Json {
        output.print_json(&serde_json::json!({
            "status": "failed",
            "exit_code": 1,
            "api_url": api_url,
            "error": { "code": failure.error.code, "message": failure.error.message },
            "message": hint,
            "candidates": proxy::candidates_json(&failure.attempts),
        }));
        return;
    }
    // Printed here rather than by `main`, because the hints below must follow
    // it; `print_error` marks it reported so `main` does not print it again.
    output.print_error(&failure.error);
    if headless {
        output.print_note(&format!("  {hint}"));
    }
    for attempt in &failure.attempts {
        if attempt.was_probed() {
            output.print_note(&format!("  {}", attempt.trace_line()));
        }
    }
}

/// Keep an `OPENLATCH_API_KEY` enrolment key in the store browser login writes.
///
/// The daemon does not inherit the shell that ran `init`: systemd, launchd and
/// Task Scheduler start it with their own environment. A key that lives only in
/// the variable authenticates `init` and nothing after it, and the supervised
/// daemon reports `OL-1600` "No credential". That is the managed-rollout path
/// (MDM, config management, image bake), where the key is always supplied this
/// way.
///
/// Written on every run, so a re-init with a different key replaces the old
/// one. A failed write is reported, not fatal: `init` itself still holds the
/// key, and a daemon it spawns directly inherits it.
fn persist_env_key(
    key: &str,
    primary: &dyn CredentialStore,
    fallback: &dyn CredentialStore,
    output: &OutputConfig,
) {
    let secret = secrecy::SecretString::from(key.to_string());
    if let Err(e) = store_credential(primary, fallback, secret) {
        output.print_notice(&format!(
            "Could not store the API key for the daemon ({}): {}",
            e.code, e.message
        ));
    }
}

/// No credential, and nobody at a terminal to sign in through the browser.
fn sign_in_needs_a_terminal(app_url: &str) -> OlError {
    OlError::new(
        ERR_NO_CREDENTIALS,
        "no API key found, and no terminal to finish a browser sign-in on",
    )
    .with_suggestion(format!(
        "Create an API key at {app_url} and re-run with it in OPENLATCH_API_KEY, or run \
         `openlatch init` from a terminal without `--yes` to sign in through the browser."
    ))
}

/// Run the auth flow for `openlatch init` (Step 3.5).
///
/// Priority order:
/// 1. `OPENLATCH_API_KEY` env var (D-09) — validate online, fail-open on network error
/// 2. Existing credential in keychain/file — re-validate, re-trigger if invalid (D-07)
/// 3. No credential — run browser auth flow (D-06), when someone is there to finish it
///
/// Returns `(auth_success, org_name)`. On auth failure (401/403), propagates error.
fn run_auth_for_init(output: &OutputConfig, yes: bool) -> Result<(bool, String), OlError> {
    let keyring = KeyringCredentialStore::new();
    let cfg = config::Config::load(None, None, false).ok();
    let agent_id = cfg
        .as_ref()
        .and_then(|c| c.agent_id.clone())
        .unwrap_or_default();
    let file_store =
        FileCredentialStore::new(config::openlatch_dir().join("credentials.enc"), agent_id);

    // WR-03: read api_url from config so staging/custom environments are respected
    let api_url = cfg
        .as_ref()
        .map(|c| c.cloud.api_url.clone())
        .unwrap_or_else(|| "https://app.openlatch.ai".to_string());
    // Same config, same reason: the three validation calls below are the only outbound
    // requests `init` makes, and they take the host's proxy route like everything else.
    let egress = cfg
        .as_ref()
        .map(|c| c.egress.clone())
        .unwrap_or_else(crate::egress::EgressConfig::direct);

    // WR-05: Create a single Tokio runtime here and reuse it for all async validation
    // calls in this function. Previously each code path created its own Runtime::new(),
    // which is harmless today (sync call site) but would panic if run_init is ever called
    // from an async context (e.g. tests or a future TUI).
    //
    // NOTE: run_login (Path 3) creates its own runtime internally. That is safe here
    // because it is called from sync code after this runtime's block_on() has returned —
    // there is no nesting at runtime.
    let rt = tokio::runtime::Runtime::new().map_err(|e| {
        OlError::new(
            ERR_INVALID_CONFIG,
            format!("Failed to create async runtime: {e}"),
        )
    })?;

    // Path 1: OPENLATCH_API_KEY env var (D-09)
    if let Ok(val) = std::env::var("OPENLATCH_API_KEY") {
        if !val.is_empty() {
            persist_env_key(&val, &keyring, &file_store, output);
            let (online, org_name, _org_id) = rt.block_on(
                crate::cli::commands::auth::validate_online(&val, &api_url, &egress),
            );
            if online {
                let msg = if org_name.is_empty() {
                    "Authenticated via env var".to_string()
                } else {
                    format!("Authenticated via env var (org: {org_name})")
                };
                output.print_step(&msg);
                return Ok((true, org_name));
            }
            // Network error → fail-open (Pitfall 4): proceed with key stored
            output.print_step("Authenticated via env var (cloud offline - validation skipped)");
            return Ok((true, String::new()));
        }
    }

    // Path 2: Check existing credential (D-07)
    if let Ok(existing_key) = retrieve_credential(&keyring, &file_store) {
        let key_str = existing_key.expose_secret().to_string();
        let v = rt.block_on(crate::cli::commands::auth::validate_online_full(
            &key_str, &api_url, &egress,
        ));
        if v.online {
            let msg = if v.org_name.is_empty() {
                "Authenticated".to_string()
            } else {
                format!("Authenticated (org: {})", v.org_name)
            };
            output.print_step(&msg);
            return Ok((true, v.org_name));
        }
        if !v.rejected {
            // Cloud unreachable — fail-open, keep existing credential
            output.print_step("Authenticated (cloud offline - using stored credentials)");
            return Ok((true, String::new()));
        }
        // Server rejected the credential (401/403) — re-trigger auth
        output.print_substep("Existing credentials invalid, re-authenticating...");
    }

    // Path 3: Run browser auth flow (D-06) — only with a human at a terminal to finish it.
    // Headless (no terminal, `--yes`, `--json`, `--quiet`) nobody is going to open the link,
    // and waiting out the 300 s callback timer turns a missing key into a five-minute hang
    // that ends in the same failure. A terminal with no browser keeps the flow: the link is
    // printed, and it can be opened on another machine.
    if !crate::cli::prompt::interactive(output, yes) {
        return Err(sign_in_needs_a_terminal(
            &crate::cli::commands::auth::resolve_app_url(),
        ));
    }

    // run_login creates its own runtime internally — safe here because it is called
    // from sync code (the rt.block_on() above has already returned).
    let login_args = AuthLoginArgs { no_browser: false };
    crate::cli::commands::auth::run_login(&login_args, output)?;

    // After successful login, retrieve the newly stored credential to get org info
    if let Ok(key) = retrieve_credential(&keyring, &file_store) {
        let key_str = key.expose_secret().to_string();
        let (_, org_name, _) = rt.block_on(crate::cli::commands::auth::validate_online(
            &key_str, &api_url, &egress,
        ));
        return Ok((true, org_name));
    }

    Ok((true, String::new()))
}

/// Install the OS supervisor and persist the resulting state into config.toml.
///
/// Returns `(backend_label, mode_label, deferred_reason)` for downstream
/// telemetry and JSON output. All errors are non-fatal — init always
/// continues so users are never locked out of setup by a platform quirk
/// (headless macOS CI, Alpine without systemd, Windows schtasks permissions).
/// Who starts the daemon at the end of `init`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum DaemonStartPlan {
    /// `--no-start` — nothing starts.
    Skip,
    /// `--foreground` — this process becomes the daemon.
    Foreground,
    /// Supervision installed successfully, which means a daemon is ALREADY
    /// starting: `systemctl enable --now`, launchd's `RunAtLoad` and Task
    /// Scheduler's `/Run` after `/Create` all start the unit at install time.
    /// `init` waits for it instead of spawning.
    SupervisorOwned,
    /// Nobody else owns the daemon — `init` spawns it itself.
    SpawnBackground,
}

/// Decide who starts the daemon. Pure, so the ordering is testable without a
/// systemd on the machine.
///
/// The order is the whole content of the function. `--no-start` and
/// `--foreground` are explicit user requests and win over everything;
/// `supervision_active` is a fact about the machine and only decides the
/// remaining case. (`run_supervision_install_for_init` already declines to
/// install under either flag, so the last two arguments cannot both be
/// meaningful — the ordering here makes that independent of that function.)
/// Start a background daemon and prove it is the one now serving.
///
/// The three facts [`lifecycle::verify_started_daemon`] insists on — the child
/// is still alive, the port answers with our version, and the PID matches —
/// are what separate this from the old code, which spawned, slept, probed
/// `/health` once, ignored the answer, and printed "Daemon started on port
/// 7443 (PID N)" for a process that had already exited.
fn start_and_prove(port: u16, token: &str, output: &OutputConfig) -> Result<(u16, u32), OlError> {
    let mut spawned = lifecycle::spawn_daemon_tracked(port, token)?;
    match lifecycle::verify_started_daemon(&mut spawned, port, 10) {
        Ok(()) => {
            output.print_step(&format!(
                "Daemon started on port {port} (PID {}, v{})",
                spawned.pid,
                env!("OPENLATCH_VERSION")
            ));
            Ok((port, spawned.pid))
        }
        Err(failure) => Err(lifecycle::start_failure_error(failure, port)),
    }
}

pub(crate) fn plan_daemon_start(
    no_start: bool,
    foreground: bool,
    supervision_active: bool,
) -> DaemonStartPlan {
    if no_start {
        DaemonStartPlan::Skip
    } else if foreground {
        DaemonStartPlan::Foreground
    } else if supervision_active {
        DaemonStartPlan::SupervisorOwned
    } else {
        DaemonStartPlan::SpawnBackground
    }
}

fn run_supervision_install_for_init(
    args: &InitArgs,
    config_path: &std::path::Path,
    output: &OutputConfig,
) -> (&'static str, &'static str, Option<String>) {
    use crate::supervision::{select_supervisor, SupervisionMode, SupervisorKind};

    // Skip cases: foreground is explicitly ephemeral; no_start means the user
    // doesn't want the daemon running right now (so don't register auto-start);
    // no_persistence is the explicit opt-out.
    let skip_reason: Option<&'static str> = if args.foreground {
        Some("foreground_session")
    } else if args.no_start {
        Some("no_start")
    } else if args.no_persistence {
        Some("user_opt_out")
    } else if !crate::supervision::unreproducible_environment().is_empty() {
        // Persistence is default-on, so an `init` inside a sandbox would
        // otherwise install a machine-global unit pointed at the machine's real
        // install. Skipped, not failed: the flag was never typed, and the rest
        // of the install is perfectly good without it.
        Some("isolated_instance")
    } else {
        None
    };

    if let Some(reason) = skip_reason {
        let _ = config::persist_supervision_state(
            config_path,
            &SupervisionMode::Disabled,
            &SupervisorKind::None,
            Some(reason),
        );
        let msg = match reason {
            "user_opt_out" => "Supervision: skipped (--no-persistence)",
            "isolated_instance" => {
                "Supervision: not applicable — an isolated instance is not machine-global"
            }
            "foreground_session" => "Supervision: skipped (foreground session)",
            "no_start" => "Supervision: skipped (--no-start)",
            _ => "Supervision: skipped",
        };
        output.print_step(msg);
        return ("none", "disabled", Some(reason.to_string()));
    }

    let Some(supervisor) = select_supervisor() else {
        let reason = "unsupported_os";
        let _ = config::persist_supervision_state(
            config_path,
            &SupervisionMode::Deferred,
            &SupervisorKind::None,
            Some(reason),
        );
        output
            .print_step("Supervision: deferred (no supported supervisor detected on this system)");
        return ("none", "deferred", Some(reason.to_string()));
    };

    let exe_path =
        std::env::current_exe().unwrap_or_else(|_| std::path::PathBuf::from("openlatch"));
    let backend = supervisor.kind();
    let backend_label: &'static str = match backend {
        SupervisorKind::Launchd => "launchd",
        SupervisorKind::Systemd => "systemd",
        SupervisorKind::TaskScheduler => "task_scheduler",
        SupervisorKind::None => "none",
    };

    match supervisor.install(&exe_path) {
        Ok(()) => {
            let _ = config::persist_supervision_state(
                config_path,
                &SupervisionMode::Active,
                &backend,
                None,
            );
            output.print_step(&format!(
                "Supervision installed ({backend_label}) — daemon will auto-start on login"
            ));
            output.print_info(
                "  Disable with `openlatch system supervision disable` or run `openlatch init --no-persistence`.",
            );
            (backend_label, "active", None)
        }
        Err(e) => {
            let reason_text = format!("{} ({})", e.message, e.code);
            let _ = config::persist_supervision_state(
                config_path,
                &SupervisionMode::Deferred,
                &backend,
                Some(&reason_text),
            );
            output.print_step(&format!(
                "Supervision: deferred — {backend_label} install failed ({})",
                e.code
            ));
            output.print_info(&format!("  {}", e.message));
            output.print_info(
                "  Init will continue; run `openlatch system supervision install` to retry after the issue is resolved.",
            );
            (backend_label, "deferred", Some(reason_text))
        }
    }
}

/// Get a human-readable agent label with path for display.
fn agent_label(agent: &DetectedAgent) -> String {
    format!(
        "{} ({})",
        agent.display_name(),
        agent.config_dir().display()
    )
}

/// Start the daemon in foreground mode (blocking).
///
/// This creates a tokio runtime and starts the daemon server directly.
fn run_daemon_foreground(
    port: u16,
    token: &str,
    spawn_model_relay: bool,
) -> Result<lifecycle::Stopped, OlError> {
    let mut cfg = config::Config::load(Some(port), None, true)?;
    cfg.foreground = true;

    let rt = tokio::runtime::Runtime::new().map_err(|e| {
        OlError::new(
            ERR_INVALID_CONFIG,
            format!("Failed to create async runtime: {e}"),
        )
    })?;

    let token_owned = token.to_string();
    let pid = std::process::id();
    let supervised = lifecycle::supervisor_owns_this_daemon(&cfg.supervision);

    // Tag this process as the daemon for crash reports. See sibling copy in
    // lifecycle.rs::run_daemon_foreground for rationale.
    #[cfg(feature = "crash-report")]
    crate::telemetry::crash::set_daemon_scope(cfg.port, pid);

    let restart_into = rt.block_on(async move {
        use crate::envelope;
        use crate::logging;
        use crate::privacy;

        let _guard = logging::daemon_log::init_daemon_logging(&cfg.log_dir, true);

        if let Ok(deleted) = logging::cleanup_old_logs(&cfg.log_dir, cfg.retention_days) {
            if deleted > 0 {
                tracing::info!(deleted = deleted, "cleaned up old log files");
            }
        }

        privacy::init_filter(&cfg.extra_patterns);

        // Write PID file so status/stop can find us
        let pid_path = config::openlatch_dir().join("daemon.pid");
        if let Err(e) = std::fs::write(&pid_path, pid.to_string()) {
            tracing::warn!(error = %e, "failed to write PID file");
        }

        logging::daemon_log::log_startup(
            env!("CARGO_PKG_VERSION"),
            cfg.port,
            pid,
            envelope::os_string(),
            envelope::arch_string(),
        );
        crate::cli::commands::lifecycle::log_observability_status_from_env();

        let credential_store = crate::cli::commands::lifecycle::build_credential_store();
        // `--foreground` makes this process the long-lived daemon, not a setup
        // helper: it binds the pinned model relay port and owns the agent's
        // `ANTHROPIC_BASE_URL` for as long as it runs. An occupied port fails
        // the start rather than degrading it (OL-RELAY-PORT).
        let restart_into = match crate::daemon::start_server(
            cfg.clone(),
            token_owned,
            Some(credential_store),
            spawn_model_relay,
        )
        .await
        {
            Ok(served) => {
                eprintln!(
                    "openlatch daemon stopped \u{2022} uptime {} \u{2022} {} events processed",
                    crate::daemon::format_uptime(served.uptime_secs),
                    served.events
                );
                served.restart_into
            }
            Err(e) => {
                tracing::error!(error = %e, "daemon exited with error");
                eprintln!("Error: daemon exited unexpectedly: {e}");
                None
            }
        };

        // Clean up PID file on exit
        let _ = std::fs::remove_file(&pid_path);
        restart_into
    });

    // No crash-report flush here, deliberately: the panic path POSTs synchronously,
    // so nothing is buffered at exit. The client this replaced batched in the
    // background, which is what a flush existed to drain.

    // An auto-update drained this daemon: hand over to the new binary as a
    // plain daemon. Replaying `init` would rerun the whole setup. The runtime
    // goes first, so none of its tasks still holds a port the new daemon binds
    // (see the sibling in `lifecycle::run_daemon_foreground`).
    if let Some(exe) = restart_into {
        rt.shutdown_timeout(std::time::Duration::from_secs(5));
        return lifecycle::hand_over(&exe, port, token, supervised);
    }

    Ok(lifecycle::Stopped::observe())
}

/// First-run telemetry consent prompt.
///
/// Order of precedence (per `.brainstorms/...telemetry.md §4.5`):
/// 1. `--telemetry` / `--no-telemetry` flag → write decision, no prompt
/// 2. Existing `telemetry.json` → respect it, no prompt (idempotent)
/// 3. Non-interactive (no TTY, CI, `--quiet`, JSON mode) → write disabled + one-liner
/// 4. Interactive → the rail's `Usage data` select (keys on a live console,
///    a `[Y/n]` line otherwise), default Yes
///
/// I11: writes `telemetry.json` BEFORE any event capture happens elsewhere.
///
/// Returns the Usage data stage's result, in the words the rail shows.
fn handle_telemetry_consent(
    args: &InitArgs,
    output: &OutputConfig,
    ol_dir: &std::path::Path,
) -> Result<&'static str, OlError> {
    let consent_path = consent_file_path(ol_dir);

    // 1. Explicit flags win.
    if args.no_telemetry {
        telemetry_config::write_consent(&consent_path, false)?;
        output.print_step("Telemetry: disabled (--no-telemetry)");
        return Ok("off (--no-telemetry)");
    }
    if args.telemetry {
        telemetry_config::write_consent(&consent_path, true)?;
        output.print_step("Telemetry: enabled (--telemetry)");
        return Ok("sharing anonymous usage data (--telemetry)");
    }

    // 2. Existing decision — leave it alone.
    if consent_path.exists() {
        let sharing = telemetry_config::read_consent(&consent_path)
            .ok()
            .flatten()
            .is_some_and(|c| c.enabled);
        return Ok(if sharing {
            "unchanged (sharing)"
        } else {
            "unchanged (not sharing)"
        });
    }

    // 3. Non-interactive: default disabled, print one-liner.
    //
    // `--yes` belongs in this predicate, not only in the proxy prompt's: without it,
    // `openlatch init --yes` on a terminal sails past every egress question and then stops
    // dead at the consent prompt, which is the opposite of what the flag promises. One
    // meaning for "do not ask me anything", one place it is decided.
    let interactive = crate::cli::prompt::interactive(output, args.yes);
    if !interactive {
        telemetry_config::write_consent(&consent_path, false)?;
        output.print_info(
            "ℹ Telemetry is off in non-interactive mode. Enable with `openlatch system telemetry enable`.",
        );
        return Ok("off (no terminal to ask)");
    }

    // 4. Interactive prompt, drawn by the rail as the stage's active block.
    let question = consent_question();
    let outcome = ui::select(&question).unwrap_or_else(|| ask_without_rail(&question));
    let (sharing, result) = consent_result(&outcome);
    telemetry_config::write_consent(&consent_path, sharing)?;
    if !matches!(outcome, ui::SelectOutcome::Answered(_)) {
        ui::note("Turn it on anytime: `openlatch system telemetry enable`");
    }
    output.print_step(&format!("Usage data: {result}"));
    Ok(result)
}

/// The consent question: the block the rail draws under `◆  Usage data`.
fn consent_question() -> ui::Select<'static> {
    ui::Select {
        title: "Usage data",
        question: "Share anonymous usage data to help improve OpenLatch?",
        lines: &[
            "Command names, agent types, error codes and counts. Never prompts,",
            "code, secrets, or anything that identifies you. Off anytime.",
        ],
        yes: "Yes, share",
        no: "No thanks",
        default_yes: true,
        timeout: Some(CONSENT_PROMPT_BUDGET),
    }
}

/// With no rail installed, ask on a plain line prompt on stderr.
fn ask_without_rail(question: &ui::Select<'_>) -> ui::SelectOutcome {
    let caps = ui::Caps::new(ui::Mode::Plain, false, false, 80);
    ui::Rail::new(caps, ui::Out::Term(console::Term::stderr()), None, 0).select(question)
}

/// What the consent bit is, and the words the rail's `Usage data` line shows.
///
/// Only an actual yes enables it: a question nobody answered is not
/// permission — the same reading the non-interactive branch of
/// [`handle_telemetry_consent`] applies when it finds no terminal to ask. Each
/// way of not answering keeps its own words, because they are different facts:
/// input that closed is not an answer that could not be read, and neither is
/// the budget running out.
fn consent_result(outcome: &ui::SelectOutcome) -> (bool, &'static str) {
    use ui::SelectOutcome as O;
    match outcome {
        O::Answered(true) => (true, "sharing anonymous usage data"),
        O::Answered(false) => (false, "not sharing"),
        O::Eof => (false, "no answer (input closed) — usage data stays off"),
        O::ReadError(_) => (false, "couldn't read your answer — usage data stays off"),
        O::TimedOut => (false, "no answer in time — usage data stays off"),
        O::Unrecognized => (false, "answer not recognized — usage data stays off"),
    }
}

/// How long the line prompt waits for a human before giving up.
///
/// The line path runs where stdin only LOOKS like a terminal as often as where
/// someone is typing ([`crate::cli::prompt::interactive`] can ask no more than
/// that), so it is bounded; running out is reported as its own outcome. The
/// key path is not bounded: it runs only on a live console, and the budget
/// expiring while the person was still in the browser is how an answer used to
/// be lost.
const CONSENT_PROMPT_BUDGET: std::time::Duration = std::time::Duration::from_secs(120);

/// Wait for the daemon's /health endpoint to return 200, up to `timeout_secs`.
///
/// Returns `true` if health check passed within the timeout, `false` otherwise.
/// How long `init` waits for the daemon's wiring supervisor to reach a verdict.
///
/// Its first probe has a 5 s budget of its own and runs the moment the listener
/// is bound, so this is that plus room for a cold start on a slow machine.
#[cfg(feature = "model-relay")]
const PREFLIGHT_VERDICT_WAIT: std::time::Duration = std::time::Duration::from_secs(15);

/// Read the daemon's model relay preflight verdict and fail the install on a proven
/// failure.
///
/// Three outcomes, deliberately not two:
///
/// - **`ok`** — the agent is wired to a listener that demonstrably reaches the
///   provider. Say so and move on.
/// - **`failed`** — the model relay bound its port and could NOT complete a round
///   trip. The daemon has already left the agent unwired, so sessions work; but
///   nothing is captured and the operator must know, so `init` exits non-zero.
///   Hooks, daemon and supervision all stay installed — none of them depend on
///   the proxy, and tearing them down would turn one degraded subsystem into no
///   install at all.
/// - **no verdict inside the budget** — a warning, never a failure. "We could
///   not tell in 15 s" is not evidence of breakage, the supervisor keeps
///   probing, and it will not wire anything until it is green. Failing here
///   would cost slow machines their install for nothing.
#[cfg(feature = "model-relay")]
fn verify_model_relay_preflight(
    args: &InitArgs,
    cfg: &config::Config,
    start_plan: DaemonStartPlan,
    output: &OutputConfig,
) -> Result<(), OlError> {
    // Nothing to verify: no daemon was started, the model relay is off, this is an
    // isolated instance that never wires the machine-global agent config, or
    // the foreground path — where the daemon IS this process and we only reach
    // here after it has already shut down.
    if start_plan == DaemonStartPlan::Skip
        || args.foreground
        || !cfg.model_relay.enabled
        || args.no_model_relay
        || !cfg.model_relay.owns_agent_wiring()
    {
        return Ok(());
    }

    // Every request plane on this host, and the format each is probed in. The
    // verdict map is keyed by agent, so "is the model relay verified" is a
    // question about all of them: probes run sequentially, so the map can hold
    // `claude-code: ok` while `codex-cli` is still absent, and a loop that
    // returned on the first `ok` would exit `init` before the second agent was
    // ever written.
    let planes: Vec<(&'static str, crate::model_relay::wire_format::WireFormat)> =
        crate::hooks::detect_agents()
            .iter()
            .filter_map(|a| {
                a.binding
                    .model_relay_wiring()
                    .map(|w| (a.agent_type(), w.wire_format))
            })
            .collect();
    // No agent on this host has a request plane: there is nothing to verify,
    // and waiting fifteen seconds to say so would be a lie either way.
    if !planes.is_empty() {
        wait_for_request_planes(cfg, &planes, output)?;
    }
    wait_for_provider_endpoints(cfg, output);
    Ok(())
}

/// Poll the daemon until every request plane has a preflight verdict; see
/// [`verify_model_relay_preflight`].
#[cfg(feature = "model-relay")]
fn wait_for_request_planes(
    cfg: &config::Config,
    planes: &[(&'static str, crate::model_relay::wire_format::WireFormat)],
    output: &OutputConfig,
) -> Result<(), OlError> {
    let port = cfg.model_relay.port;
    let deadline = std::time::Instant::now() + PREFLIGHT_VERDICT_WAIT;
    let url = format!("http://127.0.0.1:{port}/admin/model-relay/status");

    loop {
        let status = crate::egress::blocking_client_builder()
            .timeout(std::time::Duration::from_secs(2))
            .build()
            .ok()
            .and_then(|c| c.get(&url).send().ok())
            .and_then(|r| r.json::<serde_json::Value>().ok());

        if let Some(body) = status {
            match preflight_wait_rule(&body, planes, cfg) {
                WaitRule::Ok => {
                    output.print_step(&format!(
                        "Model relay verified — agents routed via http://127.0.0.1:{port}"
                    ));
                    return Ok(());
                }
                WaitRule::Err {
                    agent,
                    upstream,
                    reason,
                } => {
                    let err = OlError::new(
                        crate::error::ERR_MODEL_RELAY_PREFLIGHT_FAILED,
                        format!("Model relay check failed for {agent}: {reason}"),
                    )
                    .with_suggestion(format!(
                        "{agent}'s request plane is absent: its settings were left untouched, so \
                         its sessions connect straight to the provider and keep working — but \
                         nothing is captured. Check network reachability to {upstream} (proxy, \
                         VPN, TLS interception), then run `openlatch restart`. Run `openlatch \
                         doctor` for the full picture."
                    ))
                    .with_docs("https://docs.openlatch.ai/errors/OL-RELAY-PREFLIGHT");
                    return Err(err);
                }
                // Not every plane has a verdict yet.
                WaitRule::Wait => {}
            }
        }

        if std::time::Instant::now() >= deadline {
            output.print_substep(
                "Model relay: no verdict yet — the daemon is still checking it. \
                 Run `openlatch doctor` in a moment to confirm.",
            );
            return Ok(());
        }
        std::thread::sleep(std::time::Duration::from_millis(250));
    }
}

/// Wait for the daemon's first pass over the provider slots (Cline's
/// providers), so the report that follows says where each one stands rather
/// than "not wired yet".
///
/// Never a failure, and silent when it settles: a slot waiting for the editor
/// to restart is what a fresh install looks like, and a slot the daemon could
/// not wire is in the report with its code.
#[cfg(feature = "model-relay")]
fn wait_for_provider_endpoints(cfg: &config::Config, output: &OutputConfig) {
    use crate::cli::commands::model_relay::{endpoint_rows_for, verify_endpoint_ownership};

    let agents = crate::hooks::detect_agents();
    if !agents
        .iter()
        .any(|a| a.binding.provider_endpoints().is_some())
    {
        return;
    }
    let deadline = std::time::Instant::now() + PREFLIGHT_VERDICT_WAIT;
    loop {
        if endpoints_settled(&endpoint_rows_for(cfg, &agents, &verify_endpoint_ownership)) {
            return;
        }
        if std::time::Instant::now() >= deadline {
            output.print_substep(
                "Provider endpoints: the daemon is still wiring them. \
                 Run `openlatch doctor` in a moment to confirm.",
            );
            return;
        }
        std::thread::sleep(std::time::Duration::from_millis(500));
    }
}

/// Whether the daemon has had its pass over every slot: none is still waiting
/// to be wired, and none names a port the daemon has not bound yet.
#[cfg(feature = "model-relay")]
fn endpoints_settled(rows: &[crate::cli::commands::model_relay::EndpointRow]) -> bool {
    use crate::cli::commands::model_relay::EndpointState;
    rows.iter()
        .all(|r| !matches!(r.state, EndpointState::Unwired | EndpointState::Down))
}

/// What the preflight poll should do next.
#[cfg(feature = "model-relay")]
#[derive(Debug, PartialEq, Eq)]
enum WaitRule {
    /// Every request plane on this host reported `ok`.
    Ok,
    /// One of them reported `failed`. Carries which, the upstream ITS format is
    /// checked against, and the reason verbatim.
    Err {
        agent: &'static str,
        upstream: String,
        reason: String,
    },
    /// At least one plane has no verdict yet, and none has failed. Keep polling.
    Wait,
}

/// The wait rule, as a pure function of the status body and the host's planes.
///
/// Extracted so it can be tested without a daemon: the loop above needs a live
/// listener, this needs a `serde_json::Value`.
///
/// Three rules, and two engineers would otherwise write two loops:
///
/// - `Ok` **only** when EVERY plane reports `ok`. Probes run sequentially, so a
///   rule that returned on the first `ok` would exit `init` before a later
///   agent's endpoint was written.
/// - Any `failed` → `Err`, naming that agent and the upstream its own format is
///   checked against. Naming Anthropic's host at a Codex failure is the
///   Claude-shaped assumption this whole unit removes.
/// - Absent or `pending` → keep polling. Absent is the state between the
///   supervisor seeding an agent and its first probe returning.
#[cfg(feature = "model-relay")]
fn preflight_wait_rule(
    body: &serde_json::Value,
    planes: &[(&'static str, crate::model_relay::wire_format::WireFormat)],
    cfg: &config::Config,
) -> WaitRule {
    let verdicts = body.get("preflight");
    let mut all_ok = true;
    for (agent, fmt) in planes {
        match verdicts.and_then(|v| v.get(agent)).and_then(|v| v.as_str()) {
            Some("ok") => {}
            Some("failed") => {
                let reason = body
                    .get("preflight_error")
                    .and_then(|v| v.get(agent))
                    .and_then(|v| v.as_str())
                    .unwrap_or("the model relay could not complete a request to the provider")
                    .to_string();
                // I-4 (plan 05 §8): a CA or settings refusal is a coverage limit doctor already
                // renders (OL-RELAY-CA / OL-RELAY-SETTINGS), never fatal to `init` (D-19). The
                // plane is settled either way — it neither fails `init` nor keeps the wait open.
                if reason.starts_with(crate::model_relay::preflight::CA_REASON_MARKER)
                    || reason.starts_with(crate::model_relay::preflight::SETTINGS_REASON_MARKER)
                {
                    continue;
                }
                return WaitRule::Err {
                    agent,
                    upstream: cfg.model_relay.upstream_for(*fmt),
                    reason,
                };
            }
            // Absent, `pending`, or a value we do not recognise.
            _ => all_ok = false,
        }
    }
    if all_ok {
        WaitRule::Ok
    } else {
        WaitRule::Wait
    }
}

/// Measure the install that just happened, using the same detectors `openlatch
/// doctor` uses.
///
/// Sharing the detectors rather than re-deriving them is the point: two
/// commands that answer "is this host healthy?" with separately-written code
/// eventually disagree, and the operator has no way to know which one is
/// right.
///
/// Returns `None` only when the config cannot be loaded at all — at which point
/// the failure has already been reported by the step that hit it, and inventing
/// an eleven-section report about a machine we cannot read would be worse than
/// printing none.
fn build_install_report(
    args: &InitArgs,
    output: &OutputConfig,
) -> Option<crate::cli::report::Report> {
    let mut report = crate::cli::commands::doctor::run_all_checks(output)
        .ok()?
        .report;

    // `--no-start` leaves the daemon down on purpose. Reporting that as a
    // failure describes the flag, not the machine — and it would make every
    // scripted `init --no-start` exit non-zero.
    if args.no_start {
        report.replace_section(
            Section::Daemon,
            Check::off(Section::Daemon, "Not started at your request (--no-start)")
                .code(crate::error::ERR_DAEMON_START_FAILED)
                .source("--no-start")
                .remedy("Run `openlatch start` when you want it up."),
        );
        // Everything behind the daemon is unknowable rather than broken.
        for section in [
            Section::Hooks,
            Section::ModelRelay,
            Section::Cloud,
            Section::Policy,
            Section::Inventory,
            Section::Integrity,
        ] {
            report.replace_section(section, Check::unknown(section, Section::Daemon));
        }
    }

    Some(report)
}

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

    /// The bug: `init` installed supervision (which starts a daemon via
    /// `enable --now` / `RunAtLoad`) and then spawned a second daemon
    /// unconditionally. Both raced for the port; the loser exited 0 into
    /// `Restart=always`. With a supervisor active there must be exactly one
    /// owner, and it is not `init`.
    #[test]
    fn active_supervision_means_init_does_not_spawn() {
        assert_eq!(
            plan_daemon_start(false, false, true),
            DaemonStartPlan::SupervisorOwned
        );
    }

    #[test]
    fn without_supervision_init_still_spawns() {
        assert_eq!(
            plan_daemon_start(false, false, false),
            DaemonStartPlan::SpawnBackground
        );
    }

    /// Explicit user requests outrank the machine's supervision state — and
    /// stay outranking it even if a future change lets supervision install
    /// under these flags.
    #[test]
    fn explicit_flags_win_over_supervision() {
        assert_eq!(plan_daemon_start(true, false, true), DaemonStartPlan::Skip);
        assert_eq!(
            plan_daemon_start(false, true, true),
            DaemonStartPlan::Foreground
        );
        // --no-start beats --foreground: nothing starts at all.
        assert_eq!(plan_daemon_start(true, true, true), DaemonStartPlan::Skip);
    }
}

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

    /// The headless no-key failure names both ways out: a key through the environment, or a
    /// terminal to sign in on.
    #[test]
    fn a_headless_sign_in_names_the_key_and_where_to_get_one() {
        let e = sign_in_needs_a_terminal("https://app.example.test");
        assert_eq!(e.code, ERR_NO_CREDENTIALS);
        let suggestion = e.suggestion.unwrap_or_default();
        assert!(suggestion.contains("OPENLATCH_API_KEY"), "{suggestion}");
        assert!(
            suggestion.contains("https://app.example.test"),
            "{suggestion}"
        );
        assert!(suggestion.contains("--yes"), "{suggestion}");
    }

    /// Enter on an empty line takes the `[Y/n]` default the prompt shows, and
    /// only an explicit refusal declines.
    #[test]
    fn consent_line_takes_the_printed_default() {
        let default_yes = consent_question().default_yes;
        for accepted in ["", "\n", "  \r\n", "y", "Y", "yes", "YES"] {
            assert_eq!(
                ui::select::parse_answer(accepted, default_yes),
                Some(true),
                "{accepted:?} should take the [Y/n] default"
            );
        }
        for declined in ["n", "N", "no", "NO", "  no  ", "No\r\n"] {
            assert_eq!(
                ui::select::parse_answer(declined, default_yes),
                Some(false),
                "{declined:?} should decline"
            );
        }
    }

    /// The consent bit written to disk. Every way of not answering lands on
    /// the same side as a refusal: a prompt nobody answered is not permission,
    /// and the non-interactive branch of `handle_telemetry_consent` already
    /// writes `false` for exactly that situation.
    #[test]
    fn only_an_actual_yes_enables_telemetry() {
        use ui::SelectOutcome as O;
        let failure = ui::select::ReadFailure {
            kind: std::io::ErrorKind::InvalidInput,
            os_code: Some(6),
        };
        assert!(consent_result(&O::Answered(true)).0);
        for outcome in [
            O::Answered(false),
            O::Eof,
            O::ReadError(failure),
            O::TimedOut,
            O::Unrecognized,
        ] {
            assert!(!consent_result(&outcome).0, "{outcome:?} must not enable");
        }
    }

    /// Each outcome says what happened: a read error is never reported as
    /// nobody answering, and a non-answer never as a decision.
    #[test]
    fn consent_outcomes_keep_their_own_words() {
        use ui::SelectOutcome as O;
        let failure = ui::select::ReadFailure {
            kind: std::io::ErrorKind::InvalidInput,
            os_code: Some(6),
        };
        let words = |o: O| consent_result(&o).1;
        assert_eq!(words(O::Answered(true)), "sharing anonymous usage data");
        assert_eq!(words(O::Answered(false)), "not sharing");
        assert!(words(O::ReadError(failure)).starts_with("couldn't read your answer"));
        assert!(words(O::Eof).contains("input closed"));
        assert!(words(O::TimedOut).contains("in time"));
        let all = [O::Eof, O::ReadError(failure), O::TimedOut, O::Unrecognized];
        for o in all {
            let w = words(o);
            assert!(w.ends_with("usage data stays off"), "{w}");
            assert!(!w.contains("nothing answered"), "{w}");
        }
    }

    /// EOF is not an empty line. The two arrive as different values precisely
    /// so that a closed stdin cannot be read as assent.
    #[test]
    fn eof_is_not_the_printed_default() {
        use ui::select::{ask_line, LineRead};
        let default_yes = consent_question().default_yes;
        let once = |read: LineRead| {
            let mut read = Some(read);
            ask_line(
                default_yes,
                None,
                move |_| read.take().expect("one read"),
                || {},
            )
        };
        assert_eq!(
            once(LineRead::Line("\n".into())),
            ui::SelectOutcome::Answered(true)
        );
        let eof = once(LineRead::Eof);
        assert_eq!(eof, ui::SelectOutcome::Eof);
        assert!(!consent_result(&eof).0);
    }

    /// Init waits out the daemon's first pass over the provider slots, and a
    /// slot waiting for the editor to restart is a settled — never failed —
    /// outcome.
    #[cfg(feature = "model-relay")]
    #[test]
    fn init_waits_for_provider_slots_and_pending_is_settled() {
        use crate::cli::commands::model_relay::{EndpointRow, EndpointState};
        use crate::hooks::cline_providers::UncoveredReason;
        let row = |state| EndpointRow {
            agent: "cline",
            key: "cline:gs:shared:ollamaBaseUrl".into(),
            label: "ollama (ollamaBaseUrl)".into(),
            file: None,
            port: Some(7601),
            state,
        };
        assert!(endpoints_settled(&[]));
        assert!(endpoints_settled(&[
            row(EndpointState::NextStart),
            row(EndpointState::Active),
            row(EndpointState::Uncovered(UncoveredReason::SignedHost)),
            row(EndpointState::Verdict {
                code: crate::error::ERR_MODEL_RELAY_PREFLIGHT_FAILED,
                detail: "offline".into(),
            }),
        ]));
        assert!(!endpoints_settled(&[
            row(EndpointState::NextStart),
            row(EndpointState::Unwired)
        ]));
        assert!(
            !endpoints_settled(&[row(EndpointState::Down)]),
            "a recorded port the daemon has not bound yet"
        );
    }

    /// `init` must not call the model relay verified until EVERY request plane on
    /// the host has one, and must name the right agent — and the right
    /// upstream — when one fails.
    ///
    /// The rule is a pure function on purpose: the loop around it needs a live
    /// daemon, and this needs a `serde_json::Value`.
    ///
    /// The failure it exists to catch is silent. `body.get("preflight")` is an
    /// OBJECT now, so a reader that calls `.as_str()` on it gets `None` on every
    /// host, falls to the "still pending" arm, and burns the full
    /// `PREFLIGHT_VERDICT_WAIT` printing "no verdict yet" on a perfectly healthy
    /// install — with no compile error anywhere.
    #[cfg(feature = "model-relay")]
    #[test]
    fn verify_model_relay_preflight_waits_for_every_agent() {
        use crate::model_relay::wire_format::WireFormat;

        let mut cfg = config::Config::defaults();
        // A dead upstream for the Responses format, so the Err arm has
        // something specific to name — and something that is provably not
        // Anthropic's host.
        cfg.model_relay.upstream.insert(
            WireFormat::OpenAiResponses.as_str().to_string(),
            "http://127.0.0.1:9".to_string(),
        );
        let planes = [
            ("claude-code", WireFormat::AnthropicMessages),
            ("codex-cli", WireFormat::OpenAiResponses),
        ];

        // One plane green, the other with no entry at all — the state between
        // the supervisor seeding an agent and its first probe returning. Probes
        // run sequentially, so a rule that returned on the first `ok` would
        // exit `init` before the Codex endpoint was ever written.
        let pending = serde_json::json!({
            "preflight": { "claude-code": "ok" },
            "preflight_error": { "claude-code": null },
        });
        assert_eq!(
            preflight_wait_rule(&pending, &planes, &cfg),
            WaitRule::Wait,
            "one green plane is not the host's answer while another has no verdict"
        );

        // Explicitly `pending` reads the same way as absent.
        let still_pending = serde_json::json!({
            "preflight": { "claude-code": "ok", "codex-cli": "pending" },
        });
        assert_eq!(
            preflight_wait_rule(&still_pending, &planes, &cfg),
            WaitRule::Wait
        );

        // A failure names WHICH plane and the upstream ITS OWN format is
        // checked against. Naming Anthropic's host at a Codex probe failure is
        // the Claude-shaped assumption this unit exists to remove.
        let failed = serde_json::json!({
            "preflight": { "claude-code": "ok", "codex-cli": "failed" },
            "preflight_error": { "claude-code": null, "codex-cli": "could not reach it" },
        });
        match preflight_wait_rule(&failed, &planes, &cfg) {
            WaitRule::Err {
                agent,
                upstream,
                reason,
            } => {
                assert_eq!(agent, "codex-cli");
                assert_eq!(upstream, "http://127.0.0.1:9");
                assert!(
                    !upstream.contains("anthropic"),
                    "the upstream named must be the failing format's, not Anthropic's"
                );
                assert_eq!(reason, "could not reach it");
            }
            other => panic!("a failed plane must fail the install, got {other:?}"),
        }

        // Every plane green is the only shape that stops the poll successfully.
        let all_ok = serde_json::json!({
            "preflight": { "claude-code": "ok", "codex-cli": "ok" },
        });
        assert_eq!(preflight_wait_rule(&all_ok, &planes, &cfg), WaitRule::Ok);

        // And a scalar body — the shape this endpoint used to emit — must NOT
        // read as green. It is the silent-regression case: `.get(agent)` on a
        // string returns `None`, which is "no verdict", which keeps polling.
        let legacy = serde_json::json!({ "preflight": "ok" });
        assert_eq!(
            preflight_wait_rule(&legacy, &planes, &cfg),
            WaitRule::Wait,
            "a per-agent reader must not accept a scalar verdict as everyone's"
        );
    }

    // -----------------------------------------------------------------------
    // The install loop's one skip: an agent this build writes no hooks into
    // -----------------------------------------------------------------------

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

    /// Silent output — these tests are about return values and the filesystem,
    /// and `quiet` is what keeps `print_info`/`print_step` off the test log.
    fn silent_output() -> OutputConfig {
        OutputConfig {
            format: OutputFormat::Human,
            verbose: false,
            debug: false,
            quiet: true,
            color: false,
        }
    }

    /// The loop skips a non-installable agent *before* `install_hooks`, so
    /// nothing is written and the agent is never counted as installed.
    ///
    /// The filesystem assertion is the load-bearing half. `install_hooks` is
    /// what creates the settings file and its parent, mints the HMAC key and
    /// writes the daemon bearer token — reaching it and relying on its own
    /// refusal would already be too late for a build that ever loosened it. An
    /// empty directory proves the call never happened.
    ///
    /// The `Err` proves the second half: an `Ok` with zero entries is
    /// indistinguishable from a successful install at this call site, which is
    /// why the skip is here and not only in the primitive.
    #[test]
    fn init_skips_non_installable() {
        let dir = tempfile::tempdir().expect("temp dir");
        // The helper creates nothing under `dir` — its `hook_config_path()` is
        // `<dir>/settings.json` and no one writes it — so anything appearing
        // there was written by the code under test.
        let agents = vec![non_installable_agent("cline", dir.path())];

        let err = install_for_agents(&agents, 7590, "test-token", &silent_output())
            .expect_err("nothing was installed, so the loop reports a failure");

        assert_eq!(
            err.code,
            crate::error::ERR_HOOK_AGENT_NOT_INSTALLABLE,
            "the skip is what failed the install, not a missing agent"
        );
        assert_eq!(
            std::fs::read_dir(dir.path())
                .expect("the asset root is readable")
                .count(),
            0,
            "install_hooks was never reached: it creates the settings file, its \
             parent, the HMAC key and the token, and none of them may exist"
        );
    }

    /// A lone non-installable selection refuses with its OWN code.
    ///
    /// `openlatch init --agent cline` already exits non-zero on a build with
    /// none of this — `select_agents` rejects an undetected name with
    /// `ERR_HOOK_AGENT_NOT_FOUND` — so "non-zero" is a vacuous assertion and
    /// the code is the real one. The second half is what makes even that
    /// non-vacuous: the same function still answers `OL-1400` when there was
    /// genuinely no agent, so the two facts are distinguished rather than one
    /// of them being hardcoded.
    #[test]
    fn init_agent_cline_alone_refuses_with_its_own_code() {
        let dir = tempfile::tempdir().expect("temp dir");
        let agents = vec![non_installable_agent("cline", dir.path())];

        let err = install_for_agents(&agents, 7590, "test-token", &silent_output())
            .expect_err("a lone non-installable selection installs nothing");

        assert_eq!(err.code, crate::error::ERR_HOOK_AGENT_NOT_INSTALLABLE);
        assert_ne!(
            err.code,
            crate::error::ERR_HOOK_AGENT_NOT_FOUND,
            "the agent WAS found — telling the operator to install it is wrong advice"
        );
        assert!(
            err.message.contains("Cline"),
            "the refusal must name the agent it refused: {}",
            err.message
        );

        assert_eq!(
            nothing_installed_err(&[]).code,
            crate::error::ERR_HOOK_AGENT_NOT_FOUND,
            "a host with no agent at all is still OL-1400 — the codes are two \
             different facts, not one constant"
        );
    }

    /// I-4 plan 05 §8 (D-19): a CA or settings refusal is a coverage limit doctor renders, never a
    /// failed `init`. Every other failure still fails it.
    #[test]
    fn a_ca_or_settings_refusal_settles_the_wait_without_failing_init() {
        use crate::model_relay::preflight::{CA_REASON_MARKER, SETTINGS_REASON_MARKER};
        use crate::model_relay::wire_format::WireFormat;

        let cfg = config::Config::defaults();
        let planes = [
            ("claude-code", WireFormat::AnthropicMessages),
            ("cline", WireFormat::OpenAiChatCompletions),
        ];
        let failed = |reason: &str| {
            serde_json::json!({
                "preflight": { "claude-code": "ok", "cline": "failed" },
                "preflight_error": { "claude-code": null, "cline": reason },
            })
        };
        for marker in [CA_REASON_MARKER, SETTINGS_REASON_MARKER] {
            assert_eq!(
                preflight_wait_rule(
                    &failed(&format!("{marker}the store refused")),
                    &planes,
                    &cfg
                ),
                WaitRule::Ok,
                "{marker}: settled, not failed"
            );
        }
        match preflight_wait_rule(&failed("could not reach it"), &planes, &cfg) {
            WaitRule::Err { agent, .. } => assert_eq!(agent, "cline"),
            other => panic!("any other failure still fails init, got {other:?}"),
        }
        let pending = serde_json::json!({
            "preflight": { "claude-code": "ok", "cline": "pending" },
        });
        assert_eq!(preflight_wait_rule(&pending, &planes, &cfg), WaitRule::Wait);
    }
}

/// The customer verdict, the card it draws and the plain-mode transcript it leaves —
/// everything after the report is measured, driven on an in-memory rail.
#[cfg(test)]
mod rail_tests {
    use super::*;
    use crate::cli::ui::{Caps, Mode, Rail, INSTALL_LOCK};
    use std::sync::{Arc, Mutex};

    fn lock() -> std::sync::MutexGuard<'static, ()> {
        INSTALL_LOCK
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
    }

    /// A plain (no-TTY) rail of six stages on a buffer.
    fn plain_rail() -> (Rail, Arc<Mutex<Vec<String>>>) {
        Rail::buffer(Caps::new(Mode::Plain, false, false, 80), STAGES)
    }

    fn screen(s: &Arc<Mutex<Vec<String>>>) -> Vec<String> {
        s.lock().unwrap().clone()
    }

    /// Every section, green, for one agent on the command and request planes.
    fn green() -> Report {
        let mut report = Report::new();
        for section in Section::ALL {
            let check = Check::ok(section, "fine");
            let check = if matches!(section, Section::Hooks | Section::ModelRelay) {
                check.agent("claude-code")
            } else {
                check
            };
            report.push(check);
        }
        report
    }

    fn with(mut report: Report, check: Check) -> Report {
        report.replace_section(check.section, check);
        report
    }

    fn relay_uncovered() -> Check {
        Check::off(Section::ModelRelay, "Cline's model calls are not relayed")
            .code("OL-RELAY-UNCOVERED")
            .remedy("None — a known coverage limit.")
            .resolution(Resolution::NothingToDo)
    }

    fn first_bundle_pending() -> Check {
        Check::pending(Section::Policy, "Waiting for the first policy bundle")
            .code("OL-1210")
            .remedy("Nothing to do — it applies on arrival.")
            .resolution(Resolution::SelfResolving)
    }

    fn relay_off() -> Check {
        Check::off(Section::ModelRelay, "Model relay is switched off in config")
            .code("OL-RELAY-OFF")
            .remedy("Run `openlatch system model-relay enable`.")
    }

    fn daemon_failed() -> Check {
        Check::failed(
            Section::Daemon,
            "The service stopped right after it started",
        )
        .code("OL-1502")
        .remedy("Run `openlatch init` again.")
    }

    const AGENTS: &[(&str, &str)] = &[("claude-code", "Claude Code")];

    fn facts() -> CardFacts<'static> {
        CardFacts {
            org: "Acme Corp",
            agents: AGENTS,
            runs: "in the background · starts at login",
            no_start: false,
            console_url: "https://app.openlatch.ai",
        }
    }

    #[test]
    fn setup_verdict_maps_to_the_exit_table() {
        assert_eq!(verdict_exit_code(SetupVerdict::Live), 0);
        assert_eq!(
            verdict_exit_code(SetupVerdict::NeedsAttention),
            crate::cli::report::EXIT_DEGRADED
        );
        assert_eq!(verdict_exit_code(SetupVerdict::NotLive), 1);
        assert_eq!(EXIT_NO_AGENT, 3, "no agent is `not found`, never a failure");

        // Resolution decides init's exit, never doctor's.
        let limit = with(green(), relay_uncovered());
        assert_eq!(limit.exit_code(), crate::cli::report::EXIT_DEGRADED);
        assert_eq!(verdict_exit_code(limit.setup_verdict()), 0);
        let off = with(green(), relay_off());
        assert_eq!(verdict_exit_code(off.setup_verdict()), 7);
        let broken = with(off, daemon_failed());
        assert_eq!(verdict_exit_code(broken.setup_verdict()), 1);
    }

    #[test]
    fn live_card_names_agents_their_coverage_and_policies() {
        let report = with(green(), first_bundle_pending());
        let card = install_card(&report, &facts());
        assert_eq!(card.verdict, ui::Verdict::Live);
        assert_eq!(card.title, "OpenLatch is live on this machine");
        let rows: Vec<(&str, &str)> = card
            .rows
            .iter()
            .map(|r| (r.label.as_str(), r.value.as_str()))
            .collect();
        assert_eq!(
            rows,
            vec![
                ("Organization", "Acme Corp"),
                ("Agent", "Claude Code"),
                ("", "actions controlled · model calls observed"),
                ("Policies", "first sync in progress"),
                ("Runs", "in the background · starts at login"),
            ]
        );
        assert_eq!(
            card.sections[0].lines,
            vec![
                "Keep using Claude Code as usual.".to_string(),
                "See what they do at `https://app.openlatch.ai`".to_string(),
            ]
        );
        assert!(card.footer[0].contains("`openlatch doctor`"));
    }

    #[test]
    fn a_known_coverage_limit_is_a_coverage_line_not_a_task() {
        let report = with(green(), relay_uncovered());
        let card = install_card(&report, &facts());
        assert_eq!(card.verdict, ui::Verdict::Live);
        assert!(card
            .rows
            .iter()
            .any(|r| r.value == "actions controlled · model calls not observed"));
    }

    #[test]
    fn attention_card_lists_what_needs_the_user_and_its_remedy() {
        let report = with(green(), relay_off());
        let card = install_card(&report, &facts());
        assert_eq!(card.verdict, ui::Verdict::NeedsAttention);
        assert_eq!(card.title, "OpenLatch is running — one thing needs you");
        assert!(card.rows.iter().any(
            |r| r.label == "Model Relay" && r.value == "Model relay is switched off in config"
        ));
        assert_eq!(
            card.sections[0].lines,
            vec!["Run `openlatch system model-relay enable`.".to_string()]
        );

        let mut no_start = facts();
        no_start.no_start = true;
        let card = install_card(&report, &no_start);
        assert_eq!(card.title, "OpenLatch is set up — one thing needs you");
    }

    #[test]
    fn not_live_card_says_what_happened_and_what_to_try() {
        let report = with(green(), daemon_failed());
        let card = install_card(&report, &facts());
        assert_eq!(card.verdict, ui::Verdict::NotLive);
        assert_eq!(card.title, "OpenLatch couldn't finish setting up");
        assert_eq!(card.rows[0].label, "What happened");
        assert_eq!(
            card.rows[0].value,
            "Daemon: The service stopped right after it started"
        );
        let labels: Vec<&str> = card.sections.iter().map(|s| s.label.as_str()).collect();
        assert_eq!(labels, vec!["Try this", "Need help"]);
    }

    #[test]
    fn an_unknown_waiting_on_a_healthy_section_is_still_named() {
        let blocked = Check::unknown(Section::Policy, Section::Cloud)
            .headline("policy_bundle compatibility unknown")
            .code("OL-TEST")
            .remedy("Fix Cloud first.");
        let report = with(green(), blocked);
        assert_eq!(report.setup_verdict(), SetupVerdict::NeedsAttention);
        let items = attention_items(&report);
        assert_eq!(items.len(), 1);
        assert_eq!(items[0].section, Section::Policy);

        // With its blocker on the list, one outage stays one item.
        let mut report = report;
        report.replace_section(
            Section::Cloud,
            Check::off(Section::Cloud, "Cloud is off")
                .code("OL-TEST")
                .remedy("Turn it on."),
        );
        report.push(
            Check::unknown(Section::Policy, Section::Cloud)
                .code("OL-TEST")
                .remedy("Fix Cloud first."),
        );
        let sections: Vec<Section> = attention_items(&report).iter().map(|c| c.section).collect();
        assert_eq!(sections, vec![Section::Cloud]);
    }

    #[test]
    fn settle_waits_only_on_a_self_resolving_check_of_an_otherwise_live_run() {
        assert_eq!(settling(&green()), None);
        assert_eq!(
            settling(&with(green(), first_bundle_pending())),
            Some(Section::Policy)
        );
        // Waiting cannot turn an amber card green, so it does not wait.
        let amber = with(with(green(), first_bundle_pending()), relay_off());
        assert_eq!(settling(&amber), None);
    }

    #[test]
    fn plain_transcript_of_a_live_run() {
        let _l = lock();
        let (rail, s) = plain_rail();
        {
            let _guard = ui::install_rail(rail).expect("installs");
            ui::intro("Setting up this machine");
            ui::stage("Checking this machine", "Checked this machine");
            ui::detail("Reclaimed daemon (PID 42)");
            ui::done("found Claude Code");
            ui::stage("Signing in", "Signed in");
            ui::done("Acme Corp");
            ui::stage("Usage data", "Usage data");
            ui::done("not sharing");
            ui::stage("Connecting Claude Code", "Connected Claude Code");
            ui::done("actions now go through OpenLatch");
            ui::stage("Starting OpenLatch", "Started OpenLatch");
            ui::done("running · starts at login");
            ui::stage("Running final checks", "Final checks");
            report_verdict(&green(), &facts(), 0);
        }
        let lines = screen(&s);
        assert_eq!(
            lines[..9],
            [
                "Setting up this machine",
                "[1/6] Checked this machine - found Claude Code",
                "[2/6] Signed in - Acme Corp",
                "[3/6] Usage data - not sharing",
                "[4/6] Connected Claude Code - actions now go through OpenLatch",
                "[5/6] Started OpenLatch - running - starts at login",
                "[6/6] Final checks - all checks passed",
                "Done.",
                "",
            ]
        );
        assert_eq!(lines[9], "   +  OpenLatch is live on this machine");
        assert_eq!(
            lines.last().map(String::as_str),
            Some("result=live org=\"Acme Corp\" agents=claude-code exit=0")
        );
        assert!(lines.iter().all(|l| l.is_ascii()), "{lines:#?}");
        assert!(
            !lines.iter().any(|l| l.contains("Reclaimed")),
            "detail stays out of plain output without --verbose"
        );
    }

    #[test]
    fn plain_transcript_with_no_agent() {
        let _l = lock();
        let (rail, s) = plain_rail();
        {
            let _guard = ui::install_rail(rail).expect("installs");
            ui::intro("Setting up this machine");
            ui::stage("Checking this machine", "Checked this machine");
            report_no_agent(&silent());
        }
        let lines = screen(&s);
        assert_eq!(lines[1], "[1/6] Checked this machine - no AI agent found");
        assert_eq!(lines[2], "Paused: one thing to do first.");
        assert!(lines
            .iter()
            .any(|l| l.contains("No AI agent to connect on this machine yet")));
        assert!(lines
            .iter()
            .any(|l| l.contains("Looked for     Claude Code - Codex CLI - Cline")));
        assert_eq!(
            lines.last().map(String::as_str),
            Some("result=attention reason=no-agent exit=3")
        );
    }

    #[test]
    fn plain_transcript_of_a_failed_stage() {
        let _l = lock();
        let (rail, s) = plain_rail();
        let error = OlError::new("OL-1502", "The service stopped right after it started")
            .with_suggestion("Run `openlatch init` again.");
        {
            let _guard = ui::install_rail(rail).expect("installs");
            ui::stage("Starting OpenLatch", "Started OpenLatch");
            report_not_live(&error, &silent());
        }
        let lines = screen(&s);
        assert_eq!(
            lines[..4],
            [
                "[1/6] Starting OpenLatch - failed",
                "      The service stopped right after it started (OL-1502)",
                "      Run openlatch init again.",
                "Stopped.",
            ]
        );
        assert!(ui::error_reported(&error), "main must not print it again");
        assert_eq!(
            lines.last().map(String::as_str),
            Some("result=not_live code=OL-1502 exit=1")
        );
    }

    /// Human output with nothing printed outside the rail.
    fn silent() -> OutputConfig {
        OutputConfig {
            format: OutputFormat::Human,
            verbose: false,
            debug: false,
            quiet: false,
            color: false,
        }
    }

    #[test]
    fn words_joins_names_the_way_a_sentence_does() {
        assert_eq!(words(&[]), "");
        assert_eq!(words(&["Cline"]), "Cline");
        assert_eq!(words(&["Claude Code", "Cline"]), "Claude Code and Cline");
        assert_eq!(
            words(&["Claude Code", "Codex CLI", "Cline"]),
            "Claude Code, Codex CLI and Cline"
        );
    }
}

#[cfg(test)]
mod env_key_tests {
    use super::*;
    use crate::auth::memory::InMemoryCredentialStore;
    use secrecy::SecretString;

    fn silent_output() -> OutputConfig {
        OutputConfig {
            format: OutputFormat::Human,
            verbose: false,
            debug: false,
            quiet: true,
            color: false,
        }
    }

    /// A store that takes nothing — no keychain, and a file it cannot write.
    struct RefusingStore;

    impl CredentialStore for RefusingStore {
        fn store(&self, _key: SecretString) -> Result<(), OlError> {
            Err(OlError::new("OL-TEST", "store unavailable"))
        }
        fn retrieve(&self) -> Result<SecretString, OlError> {
            Err(OlError::new("OL-TEST", "store unavailable"))
        }
        fn delete(&self) -> Result<(), OlError> {
            Ok(())
        }
    }

    #[test]
    fn an_env_key_lands_in_the_store_browser_login_uses() {
        let primary = InMemoryCredentialStore::new();
        let fallback = InMemoryCredentialStore::new();
        persist_env_key("olk_first", &primary, &fallback, &silent_output());
        assert_eq!(primary.retrieve().unwrap().expose_secret(), "olk_first");
    }

    #[test]
    fn a_re_init_with_a_different_key_replaces_the_stored_one() {
        let primary = InMemoryCredentialStore::new();
        let fallback = InMemoryCredentialStore::new();
        persist_env_key("olk_first", &primary, &fallback, &silent_output());
        persist_env_key("olk_second", &primary, &fallback, &silent_output());
        assert_eq!(primary.retrieve().unwrap().expose_secret(), "olk_second");
    }

    #[test]
    fn with_no_keychain_the_key_goes_to_the_fallback_store() {
        let fallback = InMemoryCredentialStore::new();
        persist_env_key("olk_first", &RefusingStore, &fallback, &silent_output());
        assert_eq!(fallback.retrieve().unwrap().expose_secret(), "olk_first");
    }

    /// Both stores refusing is reported, not fatal, and the report built from
    /// the stores' errors never carries the key.
    #[test]
    fn a_failed_write_does_not_fail_init_or_echo_the_key() {
        persist_env_key(
            "olk_secret_value",
            &RefusingStore,
            &RefusingStore,
            &silent_output(),
        );
        let e = store_credential(
            &RefusingStore,
            &RefusingStore,
            SecretString::from("olk_secret_value".to_string()),
        )
        .unwrap_err();
        assert!(!e.message.contains("olk_secret_value"), "{}", e.message);
    }
}