openlatch-client 0.3.3

OpenLatch runtime enforcement node — the capture-and-enforce adapter that evaluates every covered action against a coding agent's Autonomy Zone before it runs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
/// `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, FileCredentialStore, KeyringCredentialStore};
use crate::cli::commands::lifecycle;
use crate::cli::commands::proxy;
use crate::cli::output::{OutputConfig, OutputFormat};
use crate::cli::AuthLoginArgs;
use crate::cli::InitArgs;
use crate::config;
use crate::error::{OlError, ERR_INVALID_CONFIG, 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;
use std::io::{BufRead, Write};

/// Run the `openlatch init` command.
///
/// Detects the AI agent, regenerates the auth token, writes hooks, and starts the daemon.
/// Prints step-by-step checkmark output in human mode (D-01 through D-05).
/// In JSON mode, emits a single JSON object.
///
/// # 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);
    }

    // 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 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
        });
        match lifecycle::reclaim_ports(&pre_cfg, output) {
            Ok(outcome) => {
                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
            }
            Err(e) => {
                output.print_error(&e);
                return Err(e);
            }
        }
    };

    // 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 = match hooks::select_agents(agents, &args.agent) {
        Ok(v) => v,
        Err(e) => {
            output.print_error(&e);
            return Err(e);
        }
    };
    if agents.is_empty() {
        let e = hooks::agent_not_found_err();
        output.print_error(&e);
        return Err(e);
    }
    for a in &agents {
        output.print_step(&format!("Detected agent: {}", agent_label(a)));
    }

    // 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)?;

    // 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-boundary` 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 boundary intent at all: the spawned daemon read `[boundary]
    // 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_boundary {
        config::persist_boundary_enabled(&config_path, false)?;
        output.print_substep(
            "Model boundary 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.
                ledger.unwind(output);
                return Err(e);
            }
        }
    };

    // 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.
    let (auth_success, org_name) = run_auth_for_init(output)?;

    // Step 4.5: Telemetry consent (moved before hooks for foreground mode).
    handle_telemetry_consent(args, output, &ol_dir)?;

    // 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.
    match hooks::staging::stage_hook_binary(&ol_dir) {
        Ok(outcome) => {
            output.print_step(&format!("Hook binary at {}", outcome.target().display()));
        }
        Err(e) => {
            output.print_error(&e);
            return Err(e);
        }
    }

    // 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.
    //
    // 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 line, and unwinding here would delete the
    // token and config a successfully wired agent now depends on.
    let mut installed: Vec<(&hooks::DetectedAgent, hooks::HookInstallResult)> = Vec::new();
    let mut install_failures: Vec<OlError> = Vec::new();

    for a in &agents {
        match hooks::install_hooks(&*a.binding, cfg.port, &new_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_info(&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() {
        let e = install_failures
            .into_iter()
            .next()
            .unwrap_or_else(hooks::agent_not_found_err);
        output.print_error(&e);
        return Err(e);
    }

    // NOTE: `init` deliberately does NOT write the model-boundary 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.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.
    let (supervision_backend_label, supervision_mode_label, supervision_deferred_reason) =
        run_supervision_install_for_init(args, &config_path, output);

    // 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",
    );
    let (port, pid) = if start_plan == DaemonStartPlan::Skip {
        output.print_step("Skipped daemon start (--no-start)");
        (cfg.port, 0u32)
    } else if start_plan == DaemonStartPlan::SupervisorOwned {
        // The supervisor already started a daemon, a few lines above:
        // `systemctl enable --now` and launchd's `RunAtLoad` both 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,
                );
                output.print_error(&e);
                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"
                ));
                if output.format == OutputFormat::Human && !output.quiet {
                    eprintln!("  Check `openlatch status` shortly, or the newest ~/.openlatch/logs/daemon.log.<date>.");
                }
                (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 {
        // 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 boundary 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_boundary` is deliberately NOT consulted here any more: it was
        // persisted into config above, so `cfg.boundary.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 = "boundary")]
        let spawn_boundary = cfg.boundary.enabled;
        #[cfg(not(feature = "boundary"))]
        let spawn_boundary = false;
        run_daemon_foreground(cfg.port, &new_token, spawn_boundary)?;
        (cfg.port, std::process::id())
    } else {
        start_and_prove(cfg.port, &new_token, output)?
    };

    // Step 5.5: The model boundary must be proven, not assumed.
    //
    // Everything above can succeed against a boundary 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 = "boundary")]
    verify_boundary_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);
        if output.format == OutputFormat::Human && !output.quiet {
            eprintln!("  Events will be forwarded automatically");
        }
    }

    // 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.
    // A boundary switched off in config, by nobody in this invocation, is the
    // one state an operator can look straight at and not register: the install
    // succeeds, every step prints a checkmark, and the section warning scrolls
    // past with the others. It stayed unnoticed on a real machine for two days
    // while every model call bypassed OpenLatch. It gets a banner.
    #[cfg(feature = "boundary")]
    if !cfg.boundary.enabled && !args.no_boundary {
        warn_boundary_disabled_in_config(&config_path, output);
    }

    let install_report = build_install_report(args, output);
    let today = chrono::Local::now().format("%Y-%m-%d");
    let log_path = config::openlatch_dir()
        .join("logs")
        .join(format!("events-{today}.jsonl"));
    let fully_live = install_report
        .as_ref()
        .map(|r| r.overall() == crate::cli::report::Overall::Healthy)
        .unwrap_or(false);

    if output.format == OutputFormat::Human && !output.quiet {
        eprintln!();
        if let Some(report) = &install_report {
            report.render(output);
        }
        if args.no_start {
            eprintln!("Setup complete. Run `openlatch start` to launch the daemon.");
        } else {
            eprintln!("Ready. Events will appear in: {}", log_path.display());
        }
        if fully_live {
            print_init_success_banner(output.color);
        }
    }

    // The exit status is the report's, not a constant. An install that leaves
    // the model boundary switched off, or supervision disabled, exits 7 — it
    // succeeded at what it was asked to do and the machine is still not doing
    // everything it can, and a script has to be able to tell.
    if let Some(report) = &install_report {
        report.record_verdict();
    }

    // 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
            // boundary was off and whose daemon was somebody else's process.
            "status": install_report
                .as_ref()
                .map(|r| r.overall().key())
                .unwrap_or("unknown"),
            "exit_code": install_report.as_ref().map(|r| r.exit_code()).unwrap_or(0),
            "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
            // boundary 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 boundary 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 --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 = cfg.egress.clone();
    overrides.apply(&mut egress_cfg)?;
    proxy::refuse_linux_pac(&egress_cfg)?;

    let persisted_source = 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(())
}

/// 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(Debug, Clone, Default)]
struct GateReport {
    source: Option<String>,
    url_masked: Option<String>,
    prompted: bool,
}

/// 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()?;

    // `Config::load` attached the stored proxy password already.
    let base = cfg.egress.clone();

    // 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");
    let persisted = 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.
    let has_writes = !outcome.sets.is_empty() || !outcome.removes.is_empty();
    if has_writes && config_path.exists() {
        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,
    })
}

/// 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 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;
    }
    output.print_error(&failure.error);
    if headless {
        eprintln!("  {hint}");
    }
    for attempt in &failure.attempts {
        if attempt.was_probed() {
            eprintln!("  {}", attempt.trace_line());
        }
    }
}

/// 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)
///
/// Returns `(auth_success, org_name)`. On auth failure (401/403), propagates error.
fn run_auth_for_init(output: &OutputConfig) -> 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() {
            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)
    // 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: both `systemctl enable --now` and launchd's `RunAtLoad` 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 = match lifecycle::spawn_daemon_tracked(port, token) {
        Ok(s) => s,
        Err(e) => {
            output.print_error(&e);
            return Err(e);
        }
    };
    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) => {
            let e = lifecycle::start_failure_error(failure, port);
            output.print_error(&e);
            Err(e)
        }
    }
}

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"
            ));
            if output.format == OutputFormat::Human && !output.quiet {
                eprintln!(
                    "  Disable with `openlatch 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
            ));
            if output.format == OutputFormat::Human && !output.quiet {
                eprintln!("  {}", e.message);
                eprintln!(
                    "  Init will continue; run `openlatch 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_boundary: bool) -> Result<(), 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();

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

    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 boundary 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-BND-PORT).
        match crate::daemon::start_server(
            cfg.clone(),
            token_owned,
            Some(credential_store),
            spawn_boundary,
        )
        .await
        {
            Ok((uptime_secs, events)) => {
                eprintln!(
                    "openlatch daemon stopped \u{2022} uptime {} \u{2022} {} events processed",
                    crate::daemon::format_uptime(uptime_secs),
                    events
                );
            }
            Err(e) => {
                tracing::error!(error = %e, "daemon exited with error");
                eprintln!("Error: daemon exited unexpectedly: {e}");
            }
        }

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

    #[cfg(feature = "crash-report")]
    crate::crash_report::flush(std::time::Duration::from_secs(2));

    Ok(())
}

/// 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 TTY → show notice, read line, default Y
///
/// I11: writes `telemetry.json` BEFORE any event capture happens elsewhere.
fn handle_telemetry_consent(
    args: &InitArgs,
    output: &OutputConfig,
    ol_dir: &std::path::Path,
) -> Result<(), 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(());
    }
    if args.telemetry {
        telemetry_config::write_consent(&consent_path, true)?;
        output.print_step("Telemetry: enabled (--telemetry)");
        return Ok(());
    }

    // 2. Existing decision — leave it alone.
    if consent_path.exists() {
        return Ok(());
    }

    // 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)?;
        if output.format == OutputFormat::Human && !output.quiet {
            eprintln!(
                "ℹ Telemetry is off in non-interactive mode. Enable with `openlatch telemetry enable`."
            );
        }
        return Ok(());
    }

    // 4. Interactive prompt.
    print_telemetry_notice();
    let enabled = read_consent_answer();
    telemetry_config::write_consent(&consent_path, enabled)?;
    if enabled {
        output.print_step("Telemetry: enabled — thanks for helping shape OpenLatch.");
    } else {
        output.print_step("Telemetry: disabled — enable later with `openlatch telemetry enable`.");
    }
    Ok(())
}

/// Final banner shown when `openlatch init` completes fully and the daemon
/// is actively forwarding events to the cloud.
fn print_init_success_banner(color: bool) {
    use crate::cli::color as c;
    let check = c::checkmark(color);
    let headline = c::bold(
        "OpenLatch is now capturing activity from your AI agents",
        color,
    );
    let url = c::bold("https://app.openlatch.ai", color);
    let rule = c::dim(
        "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
        color,
    );
    let lines = [
        String::new(),
        rule.clone(),
        format!("  {check} {headline}"),
        String::new(),
        "  Nothing else to do — OpenLatch runs in the background,".to_string(),
        "  capturing what your agents do so you can see and".to_string(),
        "  control it from the console.".to_string(),
        String::new(),
        "  Explore agent activity, inventory, and the audit trail:".to_string(),
        format!("  {url}"),
        rule,
    ];
    for line in lines {
        eprintln!("{line}");
    }
    let _ = std::io::stderr().flush();
}

fn print_telemetry_notice() {
    let lines = [
        "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
        "  Help shape OpenLatch",
        "",
        "  OpenLatch is early, and anonymous usage data is how we",
        "  learn which agents, detections, and workflows matter",
        "  most to the people we protect.",
        "",
        "  What we collect:",
        "    ✓ Command names (e.g. `init`, `status`) and durations",
        "    ✓ Which AI agents you use",
        "    ✓ Error codes and daemon health signals",
        "    ✓ Aggregated hook volume (counts only, every 5 min)",
        "",
        "  What we NEVER collect:",
        "    ✗ File contents, source code, or prompts",
        "    ✗ Environment variables, tokens, or secrets",
        "    ✗ Command arguments or flag values",
        "    ✗ IP addresses, hostnames, usernames",
        "",
        "  Turn it off anytime: openlatch telemetry disable",
        "",
        "  Share anonymous usage data to help improve OpenLatch? [Y/n]",
        "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
    ];
    for line in lines {
        eprintln!("{line}");
    }
    let _ = std::io::stderr().flush();
}

fn read_consent_answer() -> bool {
    let mut buf = String::new();
    let stdin = std::io::stdin();
    let _ = stdin.lock().read_line(&mut buf);
    let answer = buf.trim().to_ascii_lowercase();
    // Default Y on empty input. Only explicit "n"/"no" declines.
    !matches!(answer.as_str(), "n" | "no")
}

/// 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 = "boundary")]
const PREFLIGHT_VERDICT_WAIT: std::time::Duration = std::time::Duration::from_secs(15);

/// Read the daemon's boundary 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 boundary 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 = "boundary")]
fn verify_boundary_preflight(
    args: &InitArgs,
    cfg: &config::Config,
    start_plan: DaemonStartPlan,
    output: &OutputConfig,
) -> Result<(), OlError> {
    // Nothing to verify: no daemon was started, the boundary 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.boundary.enabled
        || args.no_boundary
        || !cfg.boundary.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 boundary 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::boundary::wire_format::WireFormat)> =
        crate::hooks::detect_agents()
            .iter()
            .filter_map(|a| {
                a.binding
                    .boundary_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() {
        return Ok(());
    }

    let port = cfg.boundary.port;
    let deadline = std::time::Instant::now() + PREFLIGHT_VERDICT_WAIT;
    let url = format!("http://127.0.0.1:{port}/admin/boundary/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 boundary verified — agents routed via http://127.0.0.1:{port}"
                    ));
                    return Ok(());
                }
                WaitRule::Err {
                    agent,
                    upstream,
                    reason,
                } => {
                    let err = OlError::new(
                        crate::error::ERR_BOUNDARY_PREFLIGHT_FAILED,
                        format!("Model boundary 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-BND-PREFLIGHT");
                    output.print_error(&err);
                    return Err(err);
                }
                // Not every plane has a verdict yet.
                WaitRule::Wait => {}
            }
        }

        if std::time::Instant::now() >= deadline {
            output.print_substep(
                "Model boundary: 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));
    }
}

/// What the preflight poll should do next.
#[cfg(feature = "boundary")]
#[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 = "boundary")]
fn preflight_wait_rule(
    body: &serde_json::Value,
    planes: &[(&'static str, crate::boundary::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") => {
                return WaitRule::Err {
                    agent,
                    upstream: cfg.boundary.upstream_for(*fmt),
                    reason: body
                        .get("preflight_error")
                        .and_then(|v| v.get(agent))
                        .and_then(|v| v.as_str())
                        .unwrap_or("the boundary could not complete a request to the provider")
                        .to_string(),
                };
            }
            // Absent, `pending`, or a value we do not recognise.
            _ => all_ok = false,
        }
    }
    if all_ok {
        WaitRule::Ok
    } else {
        WaitRule::Wait
    }
}

/// Say, unmissably, that this install routes nothing through OpenLatch.
///
/// Only for the case nobody asked for in this invocation. `--no-boundary` gets
/// a one-line acknowledgement instead: someone who just typed the flag does not
/// need a banner telling them what they typed.
#[cfg(feature = "boundary")]
fn warn_boundary_disabled_in_config(config_path: &std::path::Path, output: &OutputConfig) {
    if output.format != OutputFormat::Human || output.quiet {
        return;
    }
    let line = crate::cli::color::bold(
        "  MODEL BOUNDARY OFF — model calls do not pass through OpenLatch  ",
        output.color,
    );
    eprintln!();
    eprintln!("{}", crate::cli::color::red(&"=".repeat(66), output.color));
    eprintln!("{line}");
    eprintln!("{}", crate::cli::color::red(&"=".repeat(66), output.color));
    eprintln!("  Nothing is captured and no policy is enforced on model traffic.");
    eprintln!(
        "  Set by  : {} — [boundary] enabled = false",
        config_path.display()
    );
    eprintln!("  Undo by : openlatch boundary enable");
    eprintln!();
}

/// 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> {
    use crate::cli::report::{Check, Section};

    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::Boundary,
            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::*;

    /// `init` must not call the boundary 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 = "boundary")]
    #[test]
    fn verify_boundary_preflight_waits_for_every_agent() {
        use crate::boundary::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.boundary.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"
        );
    }
}