openlatch-client 0.3.3

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

use crate::cli::output::OutputConfig;
use crate::cli::StartArgs;
use crate::config;
use crate::error::{
    OlError, ERR_ALREADY_RUNNING, ERR_DAEMON_START_FAILED, ERR_DAEMON_STOP_FAILED,
    ERR_INVALID_CONFIG, ERR_PORT_IN_USE,
};

/// Resolve and emit the observability-subsystem status line to daemon.log.
///
/// Called once per daemon start, right after `log_startup`. Records whether
/// telemetry + crash reports are active and which rule decided each — so
/// operators grepping daemon.log can confirm at a glance whether events and
/// panics will be sent upstream. Never logs the PostHog key or Sentry DSN.
pub(crate) fn log_observability_status_from_env() {
    let dir = config::openlatch_dir();

    let telemetry_consent = crate::telemetry::consent::resolve(&dir.join("telemetry.json"));
    let baked_key_present = crate::telemetry::network::key_is_present();
    let telemetry_enabled = telemetry_consent.enabled() && baked_key_present;
    let telemetry_decided_by = if !baked_key_present {
        "NoBakedKey".to_string()
    } else {
        format!("{:?}", telemetry_consent.decided_by)
    };

    #[cfg(feature = "crash-report")]
    let (crash_report_enabled, crash_report_decided_by) = {
        let resolved = crate::crash_report::current_state(&dir);
        (resolved.enabled(), format!("{:?}", resolved.decided_by))
    };
    #[cfg(not(feature = "crash-report"))]
    let (crash_report_enabled, crash_report_decided_by) = (false, "BuildExcluded".to_string());

    crate::logging::daemon_log::log_observability_status(
        telemetry_enabled,
        &telemetry_decided_by,
        crash_report_enabled,
        &crash_report_decided_by,
    );
}

/// Run the `openlatch start` command.
///
/// Starts the daemon in the background, or in foreground if `--foreground` is set.
/// Idempotent: if the daemon is already running, exits 0 with a message.
///
/// # Errors
///
/// Returns an error if the daemon fails to spawn.
/// Stop the daemon through the OS supervisor, when one owns its lifecycle.
///
/// `true` means the supervisor accepted the stop and the process is gone; the
/// caller must NOT then reach for the process itself. `false` means no
/// supervisor owns the daemon, or it refused — the caller falls back to its
/// own stop path.
///
/// Exists because "stop the daemon" is written four times across the CLI
/// (`run_stop`, `doctor --fix`, `doctor --restore`, and the update path) and
/// every one of them was killing a process the supervisor would resurrect two
/// seconds later.
pub(crate) fn stop_via_supervisor() -> bool {
    let Ok(cfg) = config::Config::load(None, None, false) else {
        return false;
    };
    let Some(sup) = crate::supervision::lifecycle_owner(&cfg.supervision) else {
        return false;
    };
    if let Err(e) = sup.stop() {
        tracing::warn!(
            error = %e.message, code = e.code,
            "supervisor refused the stop; falling back to stopping the process directly"
        );
        return false;
    }
    if let Some(pid) = read_pid_file() {
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
        while std::time::Instant::now() < deadline && is_process_alive(pid) {
            std::thread::sleep(std::time::Duration::from_millis(100));
        }
    }
    true
}

/// Start the daemon through the OS supervisor, when one owns its lifecycle.
///
/// `true` means the supervisor started it and `/health` answered. `false`
/// means the caller still has to start the daemon itself.
pub(crate) fn start_via_supervisor(port: u16) -> bool {
    let Ok(cfg) = config::Config::load(None, None, false) else {
        return false;
    };
    let Some(sup) = crate::supervision::lifecycle_owner(&cfg.supervision) else {
        return false;
    };
    if let Err(e) = sup.start() {
        tracing::warn!(
            error = %e.message, code = e.code,
            "supervisor refused the start; falling back to spawning the daemon directly"
        );
        return false;
    }
    wait_for_health(port, 10)
}

/// Is this a plain "start the daemon as configured" request — the only shape a
/// supervisor can serve?
///
/// The supervisor starts its unit, and its unit has fixed arguments. Every flag
/// below asks for something the unit cannot express, so honouring it means
/// starting the daemon here:
///
/// - `--foreground`: the caller wants the daemon in *this* terminal, tied to
///   this shell's lifetime. Handing that to a background supervisor would
///   return immediately and leave nothing attached.
/// - `--port` / `--boundary-port`: one-shot overrides. The unit would silently
///   start on the configured port instead, and the caller would never know the
///   flag was dropped.
pub(crate) fn request_is_plain_start(args: &StartArgs) -> bool {
    !args.foreground && args.port.is_none() && args.boundary_port.is_none()
}

pub fn run_start(args: &StartArgs, output: &OutputConfig) -> Result<(), OlError> {
    // `--boundary-port` is an alias for the env override rather than a fourth
    // positional on `Config::load` (42 call sites) or a parameter threaded
    // through `spawn_daemon_background` → `run_daemon_foreground` → a re-`load`
    // in the child. Setting it here covers all three readers at once: this
    // process's load below, the foreground path's own re-load, and the
    // background child, which inherits the environment. Done before any thread
    // that could read it exists.
    if let Some(p) = args.boundary_port {
        std::env::set_var("OPENLATCH_BOUNDARY_PORT", p.to_string());
    }

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

    // Warn on typo'd / unrecognized config keys that serde silently ignores
    // (e.g. `[policy] enable` instead of `enabled`). Surfaced here because the
    // CLI installs no tracing subscriber, so a `tracing::warn!` at load time
    // would no-op; `output` writes to the user's terminal.
    for key in config::unknown_config_keys_on_disk() {
        output.print_info(&format!(
            "Warning: ignoring unrecognized config key '{key}' in config.toml"
        ));
    }

    // Hand the start to the OS supervisor when it owns the daemon's lifecycle.
    // Spawning here instead would put a second, unsupervised daemon next to the
    // supervised one, racing it for the port.
    if request_is_plain_start(args) {
        // Before delegating: this process is the CLI, outside the unit's
        // sandbox, so it is the one that can replace a stale artifact. Once the
        // start is handed to the supervisor we do not come back here.
        migrate_supervisor_artifact_if_stale(&cfg);
        if let Some(sup) = crate::supervision::lifecycle_owner(&cfg.supervision) {
            match sup.start() {
                Ok(()) => {
                    if wait_for_health(cfg.port, 10) {
                        let pid = read_pid_file().unwrap_or(0);
                        output.print_step(&format!(
                            "Daemon started on port {} (PID {pid}, supervised)",
                            cfg.port
                        ));
                        return Ok(());
                    }
                    return Err(OlError::new(
                        ERR_DAEMON_START_FAILED,
                        format!(
                            "Supervisor accepted the start but nothing answered /health on port {} within 10s",
                            cfg.port
                        ),
                    )
                    .with_suggestion(
                        "Ask the supervisor what happened — `systemctl --user status openlatch.service` \
                         (Linux), `launchctl print gui/$UID/ai.openlatch.client` (macOS) — and check \
                         the newest ~/.openlatch/logs/daemon.log.<date>.",
                    )
                    .with_docs("https://docs.openlatch.ai/errors/OL-1502"));
                }
                // The config claims `active` but the supervisor will not drive
                // the unit — deleted by hand, no user DBus session, a masked
                // unit. Fall through and start the daemon directly rather than
                // fail: an operator asking for a daemon should get one.
                Err(e) => {
                    tracing::warn!(
                        error = %e.message, code = e.code,
                        "supervisor refused the start; starting the daemon directly"
                    );
                }
            }
        }
    }

    // Idempotency + duplicate-spawn guard.
    //
    // The pid file alone is NOT authoritative: it can be stale (the daemon
    // crashed without cleanup) or missing (never written, or manually removed)
    // right next to a live daemon. Decide in three steps so a `start` next to a
    // running daemon never spawns a second one that would just fail to bind the
    // port and leave the user confused.
    match read_pid_file() {
        // pid file present + process alive → already running.
        Some(pid) if is_process_alive(pid) => {
            // Two callers, two contracts.
            //
            // Background `openlatch start` is fire-and-forget and documented
            // idempotent: "make sure a daemon is running" is satisfied, exit 0.
            //
            // `--foreground` promises that THIS process *is* the daemon. A
            // supervisor that reads exit 0 from a supervised foreground process
            // concludes the job ran to completion — when in fact it did nothing
            // at all. Paired with `Restart=always` that is an unbounded restart
            // loop against a perfectly healthy daemon, which is exactly what
            // happened: 130 restarts in five minutes, every one of them a
            // 30 ms no-op reporting success. Exit 5 (`OL-1501`) is the code
            // `RestartPreventExitStatus=5` keys off.
            if args.foreground {
                return Err(OlError::new(
                    ERR_ALREADY_RUNNING,
                    format!(
                        "A daemon is already running (PID {pid}); refusing to run a second one \
                         in the foreground"
                    ),
                )
                .with_suggestion(
                    "Run `openlatch stop` first, or `openlatch restart` to cycle it. Under an OS \
                     supervisor the running daemon is the supervised one — leave it be.",
                )
                .with_docs("https://docs.openlatch.ai/errors/OL-1501"));
            }
            output.print_info(&format!("Daemon is already running (PID {pid})"));
            return Ok(());
        }
        // pid file present + process dead → stale file; clear it and continue.
        Some(pid) => {
            let _ = std::fs::remove_file(config::openlatch_dir().join("daemon.pid"));
            output.print_info(&format!("Cleared stale PID file (PID {pid} not running)"));
        }
        // No pid file → fall through to the health probe below.
        None => {}
    }

    // Even with no live pid file, a daemon may still be answering /health on the
    // port (the stale/missing-pid-next-to-a-live-daemon case). Refuse rather than
    // spawn a duplicate that would fail to bind the port.
    if check_health(cfg.port) {
        return Err(OlError::new(
            ERR_ALREADY_RUNNING,
            format!(
                "A daemon is already answering on port {}; refusing to start a duplicate",
                cfg.port
            ),
        )
        .with_suggestion("Run `openlatch stop` first, or `openlatch restart` to cycle it.")
        .with_docs("https://docs.openlatch.ai/errors/OL-1501"));
    }

    let token = load_or_generate_token()?;

    // Pre-flight the pinned boundary port.
    //
    // The daemon refuses to start when it cannot bind it — that refusal is what
    // keeps the agent config from naming a listener that never came up. But the
    // background path spawns a child, waits 5 s for `/health`, and then reports
    // a timeout: the real cause (OL-BND-PORT, with the process holding the port
    // and how to find it) lands only in `daemon.log`, and the user is sent to a
    // file to learn something we already know here. Probing first turns the most
    // likely new failure into a precise message, immediately.
    //
    // Advisory, not authoritative: the child does the binding that counts, and a
    // port taken in the gap between this probe and that bind still fails the
    // start — just with the generic message this exists to avoid.
    #[cfg(feature = "boundary")]
    if cfg.boundary.enabled {
        let boundary_port = cfg.boundary.port;
        if let Err(e) = std::net::TcpListener::bind(("127.0.0.1", boundary_port)) {
            return Err(OlError::port_occupied(boundary_port, e));
        }
        // Say it in both modes. The daemon logs the same thing, but in
        // background mode that log is the only place it appears — and "why is
        // my agent not going through this?" is the obvious next question.
        if !cfg.boundary.owns_agent_wiring() {
            output.print_info(&format!(
                "Isolated boundary instance on 127.0.0.1:{boundary_port} — the agent config is \
                 left untouched. Route a session through it with:\n    \
                 ANTHROPIC_BASE_URL=http://127.0.0.1:{boundary_port} claude"
            ));
        }
    }

    if args.foreground {
        run_daemon_foreground(cfg.port, &token)?;
    } else {
        let pid = spawn_daemon_background(cfg.port, &token)?;
        if !wait_for_health(cfg.port, 5) {
            return Err(OlError::new(
                ERR_DAEMON_START_FAILED,
                format!("Daemon spawned (PID {pid}) but health check failed within 5s"),
            )
            // `~/.openlatch/logs/daemon.log` does not exist: the appender is
            // `rolling::daily(log_dir, "daemon.log")`, which only ever writes
            // date-suffixed files. Sending a user to the unsuffixed path sends
            // them to a missing file at the one moment they need the log.
            .with_suggestion(
                "Check the newest ~/.openlatch/logs/daemon.log.<date> for errors \
                 (the log rotates daily, so there is no unsuffixed daemon.log).",
            )
            .with_docs("https://docs.openlatch.ai/errors/OL-1502"));
        }
        output.print_step(&format!("Daemon started on port {} (PID {pid})", cfg.port));
    }

    Ok(())
}

/// Run the `openlatch stop` command.
///
/// Sends a graceful shutdown request to the daemon via POST /shutdown.
/// Idempotent: if the daemon is not running, exits 0 with a message.
///
/// # Errors
///
/// Returns an error if the shutdown request fails.
pub fn run_stop(output: &OutputConfig) -> Result<(), OlError> {
    // Ask the supervisor FIRST — before the pid-file check, not after it.
    //
    // `POST /shutdown` exits the daemon cleanly, and a supervisor reads a clean
    // exit as a death like any other: `Restart=always` had the daemon back in
    // two seconds while this command printed "Daemon stopped". The stop has to
    // be recorded by whoever owns the restart policy or it is not a stop.
    //
    // Before the pid-file check because a unit that is crash-looping or
    // mid-`activating` has no live pid file, and that is precisely a state a
    // user needs `openlatch stop` to end.
    if stop_via_supervisor() {
        let _ = std::fs::remove_file(config::openlatch_dir().join("daemon.pid"));
        announce_unwire(unwire_boundary_after_death(), output);
        output.print_step("Daemon stopped (supervised)");
        if output.format == crate::cli::output::OutputFormat::Human && !output.quiet {
            eprintln!(
                "  It will start again at the next login. Run `openlatch supervision disable` \
                 to prevent that."
            );
        }
        return Ok(());
    }

    let Some(pid) = read_pid_file() else {
        output.print_info("Daemon is not running");
        announce_unwire(unwire_boundary_after_death(), output);
        return Ok(());
    };

    if !is_process_alive(pid) {
        output.print_info("Daemon is not running");
        // Clean up stale PID file
        let _ = std::fs::remove_file(config::openlatch_dir().join("daemon.pid"));
        announce_unwire(unwire_boundary_after_death(), output);
        return Ok(());
    }

    // Load config to get the port
    let cfg = config::Config::load(None, None, false)?;

    // Prefer graceful shutdown via POST /shutdown endpoint (works cross-platform, DAEM-14)
    let token = load_or_generate_token().unwrap_or_default();
    if send_shutdown_request(cfg.port, &token) {
        // Wait for process to exit (poll PID file deletion, 5s timeout)
        let start = std::time::Instant::now();
        while start.elapsed() < std::time::Duration::from_secs(5) {
            if !is_process_alive(pid) {
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(200));
        }
    }

    // Clean up PID file if process is gone
    if !is_process_alive(pid) {
        let _ = std::fs::remove_file(config::openlatch_dir().join("daemon.pid"));
        announce_unwire(unwire_boundary_after_death(), output);
        output.print_step("Daemon stopped");
        return Ok(());
    }

    // Graceful shutdown didn't work — escalate to SIGTERM (catchable).
    force_kill(pid);
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(3);
    while std::time::Instant::now() < deadline && is_process_alive(pid) {
        std::thread::sleep(std::time::Duration::from_millis(100));
    }

    // Still alive after SIGTERM — a hung daemon that ignores or is slow to honor
    // it. Escalate to SIGKILL (uncatchable), which the previous code never did:
    // it stopped at SIGTERM, so a wedged daemon dead-ended at OL-1300 "process
    // still running". On Windows `force_kill` already used `taskkill /F` (a hard,
    // uncatchable terminate), so this repeat is a belt-and-suspenders reap.
    if is_process_alive(pid) {
        force_kill_hard(pid);
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
        while std::time::Instant::now() < deadline && is_process_alive(pid) {
            std::thread::sleep(std::time::Duration::from_millis(100));
        }
    }

    if is_process_alive(pid) {
        // Surviving SIGKILL means the process is stuck in an uninterruptible
        // kernel wait (D state) — effectively unreachable. Report with the
        // correct Daemon-decade code, not the config-error OL-1300 this path
        // used to mis-emit.
        return Err(OlError::new(
            ERR_DAEMON_STOP_FAILED,
            format!("Failed to stop daemon (pid {pid}); process still running after SIGKILL"),
        )
        .with_suggestion("Kill the process manually and remove ~/.openlatch/daemon.pid.")
        .with_docs("https://docs.openlatch.ai/errors/OL-1507"));
    }

    let _ = std::fs::remove_file(config::openlatch_dir().join("daemon.pid"));
    announce_unwire(unwire_boundary_after_death(), output);
    output.print_step("Daemon stopped");
    Ok(())
}

/// Tell the user their agent config just changed.
///
/// Stopping the daemon removes `ANTHROPIC_BASE_URL` from the agent's
/// settings.json — a visible, machine-global edit to a file they did not name,
/// and the documented way back to Claude Code Remote Control. It happened in
/// silence, so the one command that flips that behaviour never said it had.
fn announce_unwire(removed: bool, output: &OutputConfig) {
    if removed {
        output.print_step(
            "Boundary wiring removed from the agent config — model calls now go direct",
        );
    }
}

/// Net for the agent wiring, called from every `run_stop` path that has just
/// established the daemon is not running.
///
/// The daemon removes `ANTHROPIC_BASE_URL` itself on any graceful teardown. It
/// cannot on SIGKILL — which `run_stop` itself escalates to — so the process
/// that did the killing finishes the job. This is also the documented way back
/// to Remote Control: stop the daemon and the wiring goes with it.
///
/// **Gated on the port actually being free.** "The daemon I was tracking is
/// gone" is not the same claim as "nothing holds the pinned port": a second
/// daemon under a different `OPENLATCH_DIR`, or one started outside this pid
/// file, may still be serving it, and its wiring is honest. Probing ownership
/// makes the net exactly as wide as the invariant and never wider — the same
/// question `openlatch doctor` asks, answered the same way.
fn unwire_boundary_after_death() -> bool {
    #[cfg(feature = "boundary")]
    {
        use crate::cli::commands::boundary::{verify_port_ownership, PortOwnership};

        let Ok(cfg) = config::Config::load(None, None, false) else {
            return false;
        };
        // An isolated instance never wrote the machine-global config, so it has
        // no business clearing it — the canonical daemon's wiring is not ours to
        // revoke.
        if !cfg.boundary.owns_agent_wiring() {
            return false;
        }
        let port = cfg.boundary.port;
        if verify_port_ownership(port) == PortOwnership::Owned {
            // Someone else's live boundary. The config naming it is correct.
            return false;
        }
        unwire_all(crate::hooks::detect_agents().into_iter().map(|a| a.binding))
    }
    #[cfg(not(feature = "boundary"))]
    false
}

/// Remove OpenLatch's boundary wiring from each agent's config, and report
/// whether wiring **existed and was removed**.
///
/// Bindings rather than bare paths: the warning below names *which* agent
/// failed to unwire, and on a multi-agent host that field is the only thing
/// telling an operator where to look. The binding also carries the agent's
/// endpoint convention, which is what decides *which file* holds the wiring —
/// and it keeps the helper injectable, so a test hands it fakes and needs no
/// detector.
///
/// The probe runs first and its result is not sufficient on its own:
/// [`crate::hooks::remove_boundary_config`] returns `Ok(())` both when the file
/// is absent and when nothing OpenLatch-owned was in it, so only a removal that
/// actually succeeded on wiring that actually existed counts.
///
/// One agent's failure never ends the walk. `stop` is teardown: leaving a later
/// agent pointed at a listener that no longer exists is the failure mode this
/// whole function exists to prevent, and a warning about the first agent is no
/// reason to inflict it on the second.
#[cfg(feature = "boundary")]
fn unwire_all(
    agents: impl IntoIterator<Item = std::sync::Arc<dyn crate::hooks::binding::AgentBinding>>,
) -> bool {
    let mut was_wired = false;
    for binding in agents {
        // Probe first: the removal's `Ok(())` is not evidence that wiring was
        // ever there, so only the pair "it was wired" AND "the removal
        // succeeded" flips the flag the caller prints a step for.
        // THE convention reader, not `read_boundary_base_url`: that leaf is
        // EnvVars-only, so `stop` would report `was_wired = false` for a Codex
        // agent it had just unwired — a teardown that silently under-reports
        // what it did.
        let wired = crate::cli::commands::boundary::read_agent_wiring(&*binding).is_some();
        match crate::hooks::remove_boundary_config(&*binding) {
            Ok(()) if wired => was_wired = true,
            Err(e) => tracing::warn!(
                code = %e.code,
                error = %e.message,
                agent = binding.agent_type(),
                "could not remove the agent's boundary wiring after stop"
            ),
            _ => {}
        }
    }
    was_wired
}

/// Run the `openlatch restart` command.
///
/// Stops the daemon, waits for it to exit, then starts it again.
/// Per Pitfall 4 from RESEARCH.md: waits for stop to complete before starting.
///
/// # Errors
///
/// Returns an error if start fails.
pub fn run_restart(output: &OutputConfig) -> Result<(), OlError> {
    // One supervisor-mediated cycle rather than stop-then-start.
    //
    // Done as two steps under a supervisor, the stop is undone by
    // `Restart=always` before `run_start` gets to run — the daemon does come
    // back, but the supervisor restarted it, not this command, and `run_start`
    // then finds a daemon already running and reports success for work it never
    // did. `systemctl restart` / `launchctl kickstart -k` close that window.
    if let Ok(cfg) = config::Config::load(None, None, false) {
        // Same reason as `run_start`: the CLI is unsandboxed and the daemon is
        // not, so a stale artifact can only be replaced from here. `restart` is
        // also what `status` and `doctor` tell a user to run after an upgrade,
        // which makes it the one gesture that fixes both halves.
        migrate_supervisor_artifact_if_stale(&cfg);
        if let Some(sup) = crate::supervision::lifecycle_owner(&cfg.supervision) {
            match sup.restart() {
                Ok(()) => {
                    if wait_for_health(cfg.port, 10) {
                        let pid = read_pid_file().unwrap_or(0);
                        output.print_step(&format!(
                            "Daemon restarted on port {} (PID {pid}, supervised)",
                            cfg.port
                        ));
                        return Ok(());
                    }
                    return Err(OlError::new(
                        ERR_DAEMON_START_FAILED,
                        format!(
                            "Supervisor accepted the restart but nothing answered /health on port {} within 10s",
                            cfg.port
                        ),
                    )
                    .with_suggestion(
                        "Ask the supervisor what happened — `systemctl --user status openlatch.service` \
                         (Linux), `launchctl print gui/$UID/ai.openlatch.client` (macOS) — and check \
                         the newest ~/.openlatch/logs/daemon.log.<date>.",
                    )
                    .with_docs("https://docs.openlatch.ai/errors/OL-1502"));
                }
                Err(e) => {
                    tracing::warn!(
                        error = %e.message, code = e.code,
                        "supervisor refused the restart; cycling the daemon directly"
                    );
                }
            }
        }
    }

    // Stop — ignore "not running" case
    run_stop(output)?;

    // Wait until PID file is gone or health check fails before starting
    let timeout = std::time::Duration::from_secs(5);
    let start = std::time::Instant::now();
    let cfg = config::Config::load(None, None, false)?;

    while start.elapsed() < timeout {
        let pid_file_gone = read_pid_file().is_none();
        let health_down = !check_health(cfg.port);
        if pid_file_gone || health_down {
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(200));
    }

    let start_args = StartArgs {
        foreground: false,
        port: None,
        // Restart keeps whatever the config says; it does not re-assert a
        // one-shot `--boundary-port` from the run it is restarting.
        boundary_port: None,
    };
    run_start(&start_args, output)
}

/// Spawn the daemon as a detached background process.
///
/// Gets the path to the current executable and re-executes with `daemon start --foreground`.
///
/// Platform-specific detachment:
/// - Unix: `setsid()` in a `pre_exec` hook — a new session AND a new process
///   group, with **no controlling terminal**
/// - Windows: `CREATE_NO_WINDOW` suppresses the console window
///
/// Writes PID to `config::openlatch_dir().join("daemon.pid")` per PLAT-02.
///
/// # Errors
///
/// Returns an error if the child process cannot be spawned or PID file cannot be written.
pub fn spawn_daemon_background(port: u16, token: &str) -> Result<u32, OlError> {
    let exe = std::env::current_exe().map_err(|e| {
        OlError::new(
            ERR_INVALID_CONFIG,
            format!("Cannot locate current executable: {e}"),
        )
    })?;

    #[cfg(unix)]
    let child = {
        use std::os::unix::process::CommandExt;
        let mut cmd = std::process::Command::new(&exe);
        cmd.args([
            "daemon",
            "start",
            "--foreground",
            "--port",
            &port.to_string(),
        ])
        .env("OPENLATCH_TOKEN", token)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null());

        // Real daemonization. `process_group(0)` — what this used to do — gives
        // a new process group but keeps the parent's CONTROLLING TERMINAL, so
        // closing that terminal still delivers SIGHUP to the daemon. `setsid()`
        // makes the child a session leader with no controlling terminal at all,
        // which is the only way a background daemon genuinely outlives the shell
        // that started it.
        //
        // SAFETY: `pre_exec` runs in the forked child between `fork` and `exec`,
        // where only async-signal-safe calls are permitted. `setsid(2)` is on
        // POSIX's async-signal-safe list; it allocates nothing and takes no
        // locks. It fails only with EPERM when the caller is already a process
        // group leader — harmless here (we then keep the parent's session, i.e.
        // exactly the old behaviour), so the error is deliberately not fatal.
        unsafe {
            cmd.pre_exec(|| {
                libc::setsid();
                Ok(())
            });
        }

        cmd.spawn().map_err(|e| {
            OlError::new(
                ERR_INVALID_CONFIG,
                format!("Failed to spawn daemon process: {e}"),
            )
            .with_suggestion("Check that the openlatch binary is executable.")
        })?
    };

    #[cfg(windows)]
    let child = {
        use std::os::windows::process::CommandExt;
        // CREATE_NO_WINDOW: suppress console window for background daemon
        // CREATE_NEW_PROCESS_GROUP: detach from parent so daemon survives parent exit
        const CREATE_NO_WINDOW: u32 = 0x0800_0000;
        const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
        std::process::Command::new(&exe)
            .args([
                "daemon",
                "start",
                "--foreground",
                "--port",
                &port.to_string(),
            ])
            .env("OPENLATCH_TOKEN", token)
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .creation_flags(CREATE_NO_WINDOW | CREATE_NEW_PROCESS_GROUP)
            .spawn()
            .map_err(|e| {
                OlError::new(
                    ERR_INVALID_CONFIG,
                    format!("Failed to spawn daemon process: {e}"),
                )
                .with_suggestion("Check that the openlatch binary is executable.")
            })?
    };

    let pid = child.id();

    // PID file is written by the child process in run_daemon_foreground(),
    // not here — writing it here causes the child's idempotency check to
    // see its own PID and exit immediately.

    Ok(pid)
}

/// Read the daemon PID from the PID file.
///
/// Returns `None` if the file doesn't exist or can't be parsed.
pub(crate) fn read_pid_file() -> Option<u32> {
    let pid_path = config::openlatch_dir().join("daemon.pid");
    let content = std::fs::read_to_string(&pid_path).ok()?;
    content.trim().parse::<u32>().ok()
}

/// Check whether a process with the given PID is alive.
///
/// Uses OS-appropriate process existence checks.
/// Per T-02-06: verifies the process exists, not just the PID file.
pub(crate) fn is_process_alive(pid: u32) -> bool {
    // PID 0 is kernel-reserved on every platform and never a valid daemon PID.
    // On Unix, `kill(0, 0)` would additionally target the caller's process group
    // rather than probe PID 0 — guard so stale-PID detection stays correct.
    if pid == 0 {
        return false;
    }

    #[cfg(unix)]
    {
        // send signal 0 — tests process existence without actually sending a signal
        let result = unsafe { libc::kill(pid as libc::pid_t, 0) };
        result == 0
    }

    #[cfg(windows)]
    {
        // Use OpenProcess to check if the process exists
        let handle = unsafe {
            winapi::um::processthreadsapi::OpenProcess(
                winapi::um::winnt::PROCESS_QUERY_INFORMATION,
                0,
                pid,
            )
        };
        if handle.is_null() {
            return false;
        }
        let mut exit_code: u32 = 0;
        let alive = unsafe {
            winapi::um::processthreadsapi::GetExitCodeProcess(handle, &mut exit_code) != 0
                && exit_code == winapi::um::minwinbase::STILL_ACTIVE
        };
        unsafe { winapi::um::handleapi::CloseHandle(handle) };
        alive
    }

    // Fallback for non-unix, non-windows (should not happen in practice)
    #[cfg(not(any(unix, windows)))]
    {
        let _ = pid;
        false
    }
}

/// Send a graceful shutdown request to the daemon via POST /shutdown.
///
/// Returns true if the request was sent successfully.
pub(crate) fn send_shutdown_request(port: u16, token: &str) -> bool {
    let url = format!("http://127.0.0.1:{port}/shutdown");
    let client = crate::egress::blocking_client_builder()
        .timeout(std::time::Duration::from_secs(2))
        .build();

    match client {
        Ok(c) => c
            .post(&url)
            .header("Authorization", format!("Bearer {token}"))
            .send()
            .map(|r| r.status().is_success() || r.status() == reqwest::StatusCode::GONE)
            .unwrap_or(false),
        Err(_) => false,
    }
}

/// Force-kill the daemon process as a last resort when graceful shutdown fails.
pub(crate) fn force_kill(pid: u32) {
    #[cfg(unix)]
    unsafe {
        libc::kill(pid as libc::pid_t, libc::SIGTERM);
    }

    #[cfg(windows)]
    {
        let _ = std::process::Command::new("taskkill")
            .args(["/F", "/T", "/PID", &pid.to_string()])
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status();
    }
}

/// Last-resort hard kill when [`force_kill`]'s SIGTERM did not stop the daemon.
///
/// Unix: SIGKILL — uncatchable, un-blockable; the only signal a hung daemon
/// cannot ignore. Windows: `taskkill /F` is already a forced, uncatchable
/// terminate (the same call [`force_kill`] makes), repeated here to give the OS
/// a second chance to reap a stuck process tree.
pub(crate) fn force_kill_hard(pid: u32) {
    #[cfg(unix)]
    unsafe {
        libc::kill(pid as libc::pid_t, libc::SIGKILL);
    }

    #[cfg(windows)]
    {
        let _ = std::process::Command::new("taskkill")
            .args(["/F", "/T", "/PID", &pid.to_string()])
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status();
    }
}

/// Probe `GET /health` once, with a hard 2 s ceiling.
///
/// The timeout is not decoration. A bare `reqwest::blocking::get` has **no**
/// timeout, and a process that merely holds the port — accepting the TCP
/// handshake from the listen backlog and then saying nothing — makes the
/// request hang forever. That turned `openlatch start` next to a squatted port
/// into an indefinite hang instead of the OL-1500 it should report. 2 s matches
/// the ceiling [`send_shutdown_request`] already uses on the same loopback.
fn probe_health_once(port: u16) -> bool {
    let url = format!("http://127.0.0.1:{port}/health");
    crate::egress::blocking_client_builder()
        .timeout(std::time::Duration::from_secs(2))
        .build()
        .ok()
        .and_then(|c| c.get(&url).send().ok())
        .map(|r| r.status().is_success())
        .unwrap_or(false)
}

/// Wait for the daemon's /health endpoint to return 200.
///
/// Returns true if health check passed within the timeout, false otherwise.
pub(crate) fn wait_for_health(port: u16, timeout_secs: u64) -> bool {
    let start = std::time::Instant::now();
    let timeout = std::time::Duration::from_secs(timeout_secs);

    while start.elapsed() < timeout {
        if probe_health_once(port) {
            return true;
        }
        std::thread::sleep(std::time::Duration::from_millis(200));
    }
    false
}

/// Check if the daemon's /health endpoint is reachable (single bounded attempt).
pub(crate) fn check_health(port: u16) -> bool {
    probe_health_once(port)
}

/// Build the credential store chain (keyring -> env -> file) for the daemon
/// to hand to the cloud worker.
pub(crate) fn build_credential_store() -> std::sync::Arc<dyn crate::auth::CredentialStore> {
    let agent_id = config::Config::load(None, None, false)
        .ok()
        .and_then(|c| c.agent_id)
        .unwrap_or_default();
    let keyring = Box::new(crate::auth::KeyringCredentialStore::new());
    let file = Box::new(crate::auth::FileCredentialStore::new(
        config::openlatch_dir().join("credentials.enc"),
        agent_id,
    ));
    std::sync::Arc::new(crate::auth::FallbackCredentialStore::new(keyring, file))
}

/// Load the daemon token or generate a new one if missing.
fn load_or_generate_token() -> Result<String, OlError> {
    let ol_dir = config::openlatch_dir();
    config::ensure_token(&ol_dir)
}

/// Regenerate the supervisor artifact when the installed one predates this
/// binary.
///
/// Package upgrades replace the binary and leave the unit exactly as it was:
/// npm's `postinstall`, Homebrew and the curl installer all know how to write
/// files and nothing at all about the OS supervisor. The artifact therefore
/// keeps whatever semantics it was generated with, however old — and a v2 unit
/// (no `RestartPreventExitStatus=5`) in front of a binary that exits 5 on
/// already-running is an unbounded restart loop, which
/// `StartLimitIntervalSec=0` guarantees nobody will be told about. This machine
/// reached 550 restarts in that configuration.
///
/// # This must not be called from the daemon
///
/// It was, and it could never have worked. The generated unit sandboxes the
/// process it starts:
///
/// ```ini
/// ProtectHome=read-only
/// ReadWritePaths={home}/.openlatch {home}/.claude
/// ```
///
/// `~/.config/systemd/user` is in neither path, so a daemon running under its
/// own unit gets `EROFS` writing the file it is trying to replace — on the only
/// platform where the loop this fixes actually happens. The write is only
/// reachable from an **unsandboxed** process, which means the CLI: `openlatch
/// start` and `openlatch restart` as typed by a user or a fleet tool.
///
/// Widening `ReadWritePaths` to cover the unit directory would trade the bug
/// for a worse one — an enforcement daemon that can rewrite its own startup
/// unit is an enforcement daemon that can persist itself once compromised, and
/// that sandbox is exactly what denies it today.
///
/// # What this does not cover
///
/// A boot. systemd starts the daemon directly, no CLI is involved, and the
/// process it starts is the sandboxed one — so an upgraded host that is only
/// ever rebooted keeps its old unit. That case is surfaced rather than fixed:
/// `status` and `doctor` both report an outdated unit and name `openlatch
/// supervision install`.
///
/// `current_exe()` is valid on this path for the same reason it was on the old
/// one — the CLI process was just exec'd from the binary on disk, so it cannot
/// resolve to the deleted inode an upgrade leaves behind a long-running daemon.
///
/// Is the installed artifact one this binary should replace?
///
/// Registered, and not the generation we produce today. Deliberately **not**
/// gated on `running`.
///
/// That gate was correct at the call site this migration used to have — a
/// daemon starting itself must not hand a stopped service an `enable --now`
/// and get a second daemon. From `run_start` / `run_restart` it is exactly
/// backwards: the caller is asking for a daemon, so starting one is the point.
///
/// Worse, it excluded the case the migration exists for. `SupervisorStatus`
/// derives `running` from `systemctl is-active`, which answers `activating`
/// with exit 3 for a unit in `Restart=always` auto-restart — so throughout the
/// 550-restart loop the gate read `running: false` and skipped the one rewrite
/// that ends it. Measured, not inferred: a looping unit reports `activating`,
/// exit 3.
///
/// With the loop, the rewrite now lands: v3 unit → `daemon-reload` →
/// `enable --now` → `ExecStart` refuses with exit 5 → `RestartPreventExitStatus=5`
/// stops the restarting and the unit settles in `failed`, where an operator can
/// finally see it.
///
/// Pure, so the states that only occur on a broken host are testable.
fn artifact_needs_migration(status: &crate::supervision::SupervisorStatus) -> bool {
    status.installed && !status.unit_current
}

fn migrate_supervisor_artifact_if_stale(cfg: &config::Config) {
    let Some(sup) = crate::supervision::lifecycle_owner(&cfg.supervision) else {
        return;
    };
    let Ok(status) = sup.status() else { return };
    if !artifact_needs_migration(&status) {
        return;
    }
    let Ok(exe) = std::env::current_exe() else {
        return;
    };
    match sup.install(&exe) {
        Ok(()) => tracing::info!(
            exe = %exe.display(),
            "supervisor artifact predated this binary; regenerated it — effective at the next start"
        ),
        Err(e) => tracing::warn!(
            error = %e.message, code = e.code,
            "could not regenerate the stale supervisor artifact; it keeps its previous semantics"
        ),
    }
}

/// Start the daemon in foreground mode (blocking call).
///
/// Creates a tokio runtime and runs the daemon server directly.
fn run_daemon_foreground(port: u16, token: &str) -> Result<(), OlError> {
    // Set by the `rt.block_on` closure below when `start_server` returns an
    // Err. Hoisted out of the closure so the error survives to become this
    // function's return value — and therefore the process's exit code.
    let mut serve_error: Option<String> = None;
    // D-11: self-heal old installs whose config.toml pre-dates the
    // agent_id field. Idempotent — if already present, reads and returns
    // the existing ID without touching the file.
    let config_path = config::openlatch_dir().join("config.toml");
    if config_path.exists() {
        let _ = config::ensure_agent_id(&config_path);
    }

    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 BEFORE any tokio work runs.
    // Reached via `daemon start --foreground` re-invoking the same binary,
    // so main()'s earlier `enrich_cli_scope` tagged us as "cli" — this
    // overwrites it so panics in daemon bootstrap carry the correct tag.
    #[cfg(feature = "crash-report")]
    crate::crash_report::enrich_daemon_scope(cfg.port, pid);

    rt.block_on({
        let serve_error = &mut serve_error;
        async move {
            use crate::daemon;
            use crate::envelope;
            use crate::logging;
            use crate::privacy;

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

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

            // Resolve `[proxy] auth = "auto"` and the proxy password ONCE, here, before the
            // first outbound client is built. `build_client` is called from several tasks
            // below and is deliberately synchronous and pure, so the probe and the keychain
            // read cannot live in it -- they would run per client, on runtime threads.
            //
            // Cost when no proxy is configured, which is the overwhelmingly common case:
            // nothing. `resolve_auth` returns immediately without touching the network or
            // the keychain. When one IS configured, a failure here is a warning and a
            // buildable client, never a refusal to start.
            {
                let credentials = crate::egress::ProxyCredentialFile::new(
                    config::openlatch_dir().join(crate::egress::PROXY_CREDENTIALS_FILE),
                    cfg.agent_id.clone().unwrap_or_default(),
                );
                let api_url = cfg.cloud.api_url.clone();
                cfg.egress =
                    crate::egress::resolve_auth(cfg.egress, Some(&api_url), Some(&credentials))
                        .await;
                if let Some(resolved) = cfg.egress.resolved.as_ref() {
                    if let Some(warning) = resolved.warning.as_deref() {
                        tracing::warn!(
                            code = crate::error::ERR_PROXY_AUTH_FAILED,
                            proxy = ?cfg.egress.masked_url(),
                            "{warning}"
                        );
                    }
                }
            }

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

            // Daemon foreground has no parent `OutputConfig` — construct a minimal
            // human-mode config so the header honors TTY color detection.
            let header_output = crate::cli::output::OutputConfig {
                format: crate::cli::output::OutputFormat::Human,
                verbose: false,
                debug: false,
                quiet: false,
                color: std::io::IsTerminal::is_terminal(&std::io::stderr()),
            };
            crate::cli::header::print(
                &header_output,
                &[
                    &format!("listening 127.0.0.1:{}", cfg.port),
                    &format!("pid {pid}"),
                ],
            );

            // Model-boundary listener (plan 01 forward + plan 02 measurement) is
            // co-launched INSIDE `start_server`/`serve_with_listener` when
            // `spawn_boundary = true`, so it shares this daemon's session registry
            // (attribution) and cloud rail (economics emission) directly. It inherits
            // the daemon's OS supervision (a daemon crash restarts both) and binds the
            // pinned loopback port, never re-probed (D-25).
            //
            // `start_server` also owns the agent's `ANTHROPIC_BASE_URL` from here
            // on: written once the bind succeeds, removed when this process
            // stops, cleared at startup when the boundary is off. An occupied
            // port therefore fails this start (OL-BND-PORT) rather than leaving
            // the config pointing at a listener that never came up.
            //
            // The flag follows `[boundary] enabled` (secure-by-default true; opt
            // out via config or OPENLATCH_BOUNDARY_ENABLED).
            let credential_store = build_credential_store();
            let spawn_boundary = cfg.boundary.enabled;
            log_if_unsupervised(&cfg);
            match 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",
                        daemon::format_uptime(uptime_secs),
                        events
                    );
                }
                Err(e) => {
                    tracing::error!(error = %e, "daemon exited with error");
                    eprintln!("Error: daemon exited unexpectedly: {e}");
                    // Recorded, not swallowed. This branch used to fall through to
                    // `Ok(())`, so a daemon that died from a serve error exited 0 —
                    // and systemd's `Restart=on-failure` / launchd's
                    // `KeepAlive{SuccessfulExit=false}` both read 0 as "it meant to
                    // stop" and never restarted it. A supervised daemon that
                    // crashes has to exit non-zero or supervision is theatre.
                    *serve_error = Some(e.to_string());
                }
            }

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

    // Flush pending Sentry events before the process winds down. Covers
    // panics captured in the final few ms of the server loop where the
    // guard's Drop might otherwise race OS process teardown.
    #[cfg(feature = "crash-report")]
    crate::crash_report::flush(std::time::Duration::from_secs(2));

    // Exit-code contract (.claude/rules/error-handling.md) is preserved: a
    // graceful stop still returns Ok → 0, SIGINT still ends at 130. Only the
    // genuine-error branch becomes non-zero, which is the whole point.
    match serve_error {
        None => Ok(()),
        Some(message) => Err(OlError::new(
            ERR_DAEMON_START_FAILED,
            format!("Daemon exited unexpectedly: {message}"),
        )
        .with_suggestion(
            "Check the newest ~/.openlatch/logs/daemon.log.<date> for the failure that \
             preceded it (the log rotates daily, so there is no unsuffixed daemon.log).",
        )
        .with_docs("https://docs.openlatch.ai/errors/OL-1502")),
    }
}

/// Record the OL-1513 condition in `daemon.log`: this daemon is running with no
/// OS supervisor behind it, and nobody asked for that.
///
/// The in-process supervisor (`core::supervision::task`) keeps subsystems alive
/// but cannot resurrect the process itself, so a crash or a reboot ends the
/// daemon until a human notices. That is worth a line in the log when the
/// machine landed there (`unsupported_os`, a deferred install) — and worth
/// nothing at all when the user typed `--no-persistence`, `--foreground`, or
/// `--no-start`, which is what [`absence_is_deliberate`] separates.
///
/// Log only, and never an automatic install: `--foreground` is a deliberate dev
/// choice and hijacking it into registering a launchd/systemd unit would be a
/// surprise with persistent side effects.
///
/// [`absence_is_deliberate`]: crate::supervision::absence_is_deliberate
fn log_if_unsupervised(cfg: &config::Config) {
    use crate::supervision::{absence_is_deliberate, SupervisionMode};
    if cfg.supervision.mode == SupervisionMode::Active {
        return;
    }
    if absence_is_deliberate(cfg.supervision.disabled_reason.as_deref()) {
        return;
    }
    tracing::warn!(
        code = crate::error::ERR_NO_SUPERVISOR,
        supervision_mode = ?cfg.supervision.mode,
        reason = cfg.supervision.disabled_reason.as_deref().unwrap_or("unknown"),
        "No OS supervisor is installed and none was declined — nothing will restart this \
         daemon after a crash or a reboot. Run `openlatch supervision install`."
    );
}

#[cfg(test)]
mod tests {
    /// A start is not a start because something answered — the child has to be
    /// alive.
    ///
    /// This is the check whose absence produced "Daemon started on port 7443
    /// (PID 4185510)" for a process that had already exited: the old code
    /// spawned, slept, probed `/health` once and never looked at the child, so
    /// a 200 from whatever else held the port read as success.
    #[test]
    fn a_child_that_died_is_not_a_started_daemon() {
        let dir = tempfile::tempdir().unwrap();
        let log_path = dir.path().join("daemon-spawn.log");
        std::fs::write(&log_path, "Error: A daemon is already running (OL-1501)\n").unwrap();

        // Any process that exits immediately stands in for a daemon that
        // refused to start.
        #[cfg(unix)]
        let mut child = std::process::Command::new("/bin/sh")
            .args(["-c", "exit 5"])
            .spawn()
            .expect("spawn");
        #[cfg(windows)]
        let mut child = std::process::Command::new("cmd")
            .args(["/C", "exit 5"])
            .spawn()
            .expect("spawn");

        // Wait for the fact this test needs instead of guessing that 300 ms is
        // enough for every Windows runner to publish the child's exit status.
        let status = child.wait().expect("wait for child refusal");
        assert_eq!(status.code(), Some(5), "the fixture must refuse its start");
        let mut spawned = SpawnedDaemon::from_child_for_test(child, log_path);

        // A port nothing is on, so `/health` can never rescue the verdict.
        let verdict = verify_started_daemon(&mut spawned, 17969, 2);
        match verdict {
            Err(StartFailure::ChildDied { log, .. }) => {
                assert!(
                    log.iter().any(|l| l.contains("OL-1501")),
                    "the child's own words must reach the caller, not /dev/null: {log:?}"
                );
            }
            other => panic!("a dead child must be reported as such, got {other:?}"),
        }
    }

    /// Every failure shape has to say something an operator can act on.
    #[test]
    fn every_start_failure_names_a_next_step() {
        let cases = [
            StartFailure::ChildDied {
                status: "exit status: 5".into(),
                log: vec!["Error: A daemon is already running".into()],
            },
            StartFailure::NoHealth,
            StartFailure::ForeignPid {
                answering: 42,
                expected: 43,
            },
            StartFailure::VersionMismatch {
                serving: "0.1.16".into(),
                expected: "0.1.18".into(),
            },
        ];
        for case in cases {
            let err = start_failure_error(case.clone(), 7443);
            assert!(err.suggestion.is_some(), "{case:?} must carry a suggestion");
            assert!(!err.message.is_empty(), "{case:?} must say what happened");
        }
    }

    use super::*;

    /// Serializes this module's own env-mutating tests against each other.
    ///
    /// **Not** the lock for `OPENLATCH_DIR`: that variable has one lock,
    /// [`crate::config::OPENLATCH_DIR_ENV_LOCK`], and the two tests below take
    /// that as well. A second mutex serialises nothing against the first — two
    /// modules holding two different locks can both set the one process-wide
    /// variable and each redirect the other's config writes.
    static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

    fn quiet_output() -> OutputConfig {
        OutputConfig {
            format: crate::cli::output::OutputFormat::Human,
            verbose: false,
            debug: false,
            quiet: true,
            color: false,
        }
    }

    /// The force path must escalate SIGTERM → SIGKILL.
    ///
    /// Before this fix, `run_stop`'s force path stopped at SIGTERM
    /// (`force_kill`), so a daemon that ignores SIGTERM dead-ended at OL-1300
    /// "process still running". Spawn a child that traps and ignores SIGTERM,
    /// prove `force_kill` (SIGTERM) does NOT stop it, then prove
    /// `force_kill_hard` (SIGKILL) does — the exact escalation `run_stop` now
    /// performs.
    #[cfg(unix)]
    #[test]
    fn force_kill_hard_escalates_to_sigkill_on_sigterm_ignoring_process() {
        use std::time::{Duration, Instant};

        // `trap '' TERM` makes the shell ignore SIGTERM; it then sleeps well past
        // the test's lifetime. All stdio is null so nothing leaks to test output.
        let mut child = std::process::Command::new("sh")
            .args(["-c", "trap '' TERM; sleep 30"])
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .spawn()
            .expect("spawn SIGTERM-ignoring child");
        let pid = child.id();

        assert!(
            is_process_alive(pid),
            "child must be alive right after spawn"
        );

        // SIGTERM (the old force path) is ignored — the child survives it.
        force_kill(pid);
        std::thread::sleep(Duration::from_millis(500));
        assert!(
            is_process_alive(pid),
            "child ignores SIGTERM — force_kill alone must NOT stop it (the OL-1300 bug)"
        );

        // SIGKILL (the new escalation) is uncatchable — the child dies. Reap it
        // first so it is not left a zombie, which `kill(pid, 0)` still reports as
        // alive; after the wait, `is_process_alive` observes the true death.
        force_kill_hard(pid);
        let status = child.wait().expect("wait on killed child");
        assert!(
            !status.success(),
            "a SIGKILL'd process must not report a success exit"
        );

        let deadline = Instant::now() + Duration::from_secs(2);
        while Instant::now() < deadline && is_process_alive(pid) {
            std::thread::sleep(Duration::from_millis(50));
        }
        assert!(
            !is_process_alive(pid),
            "SIGKILL must terminate a SIGTERM-ignoring process"
        );
    }

    /// The two contracts of "already running", which used to be one.
    ///
    /// Background `start` is documented idempotent — "make sure a daemon is
    /// running" is satisfied, exit 0. `--foreground` promises this process IS
    /// the daemon, so exiting 0 without becoming one tells a supervisor the job
    /// completed successfully. Under `Restart=always` that is an unbounded
    /// restart loop against a healthy daemon.
    ///
    /// Uses the current process's own PID: `is_process_alive` is true for it by
    /// construction, so the test drives the pid-file branch without spawning
    /// anything.
    #[test]
    fn foreground_refuses_when_already_running_but_background_stays_idempotent() {
        let _env = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let _dir_env = crate::config::OPENLATCH_DIR_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let tmp = tempfile::tempdir().expect("tempdir");
        std::env::set_var("OPENLATCH_DIR", tmp.path());
        std::fs::write(
            tmp.path().join("daemon.pid"),
            std::process::id().to_string(),
        )
        .expect("write pid file");

        let foreground = run_start(
            &StartArgs {
                foreground: true,
                // An explicit port keeps `request_is_plain_start` false, so the
                // supervisor delegation never runs and this exercises the
                // pid-file branch on any host.
                port: Some(59_411),
                boundary_port: None,
            },
            &quiet_output(),
        );
        let background = run_start(
            &StartArgs {
                foreground: false,
                port: Some(59_411),
                boundary_port: None,
            },
            &quiet_output(),
        );

        std::env::remove_var("OPENLATCH_DIR");

        let err = foreground.expect_err("--foreground must refuse a second daemon");
        assert_eq!(
            err.code, ERR_ALREADY_RUNNING,
            "the foreground refusal must carry OL-1501, got {}",
            err.code
        );
        assert_eq!(
            err.exit_code(),
            5,
            "OL-1501 must exit 5 — RestartPreventExitStatus=5 keys off it"
        );
        assert!(
            background.is_ok(),
            "background start must stay idempotent (exit 0), got {background:?}"
        );
    }

    /// The state the old gate skipped, and the whole reason the migration
    /// exists: a unit restart-looping against a healthy daemon.
    ///
    /// `systemctl is-active` answers `activating` with exit 3 while a unit is
    /// in `Restart=always` auto-restart, so `SupervisorStatus::running` is
    /// `false` for the entire loop. Gating on it meant the one rewrite that
    /// ends the loop was skipped precisely while the loop ran — and the remedy
    /// `status` and `doctor` print (`openlatch restart`) walked into the same
    /// early return.
    #[test]
    fn a_looping_unit_is_migrated_even_though_it_reads_as_not_running() {
        let looping = crate::supervision::SupervisorStatus {
            installed: true,
            // `activating` → is-active exits 3 → not "running".
            running: false,
            unit_current: false,
            description: "systemd-user (unit present, state: activating)".into(),
        };
        assert!(
            artifact_needs_migration(&looping),
            "a looping unit reads as not-running; gating on that skipped the fix"
        );
    }

    /// The two states that must NOT trigger a rewrite: nothing registered to
    /// replace, and an artifact already at this generation.
    #[test]
    fn nothing_to_migrate_is_left_alone() {
        let absent = crate::supervision::SupervisorStatus {
            installed: false,
            running: false,
            unit_current: false,
            description: "not installed".into(),
        };
        assert!(!artifact_needs_migration(&absent));

        let current = crate::supervision::SupervisorStatus {
            installed: true,
            running: true,
            unit_current: true,
            description: "systemd-user (Restart=always active)".into(),
        };
        assert!(
            !artifact_needs_migration(&current),
            "a current artifact must not be rewritten on every start"
        );
    }

    /// A supervisor's unit has fixed arguments, so only a plain "start the
    /// daemon as configured" request can be handed to it. Every flag below
    /// asks for something the unit cannot express — delegating would silently
    /// drop it.
    #[test]
    fn only_a_plain_start_is_delegated_to_the_supervisor() {
        let plain = StartArgs {
            foreground: false,
            port: None,
            boundary_port: None,
        };
        assert!(request_is_plain_start(&plain));
        assert!(!request_is_plain_start(&StartArgs {
            foreground: true,
            ..plain
        }));
        assert!(!request_is_plain_start(&StartArgs {
            port: Some(7444),
            ..plain
        }));
        assert!(!request_is_plain_start(&StartArgs {
            boundary_port: Some(7600),
            ..plain
        }));
    }

    /// `run_start` must refuse to spawn a duplicate when a daemon is already
    /// answering `/health` on the port — even with no live PID file (the
    /// stale/missing-pid-next-to-a-live-daemon case).
    ///
    /// Stands up a minimal HTTP `/health` responder on an ephemeral port,
    /// isolates `OPENLATCH_DIR` to an empty temp dir (so `read_pid_file()`
    /// returns `None` and the refusal path reaches the health probe), and
    /// asserts the OL-1501 refusal. Never touches the real `~/.openlatch` or
    /// port 7443.
    #[test]
    fn run_start_refuses_when_health_answers_without_pid_file() {
        use std::io::{Read, Write};
        use std::sync::atomic::{AtomicBool, Ordering};
        use std::sync::Arc;
        use std::time::Duration;

        let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind ephemeral port");
        let port = listener.local_addr().unwrap().port();
        listener
            .set_nonblocking(true)
            .expect("set listener non-blocking");

        let stop = Arc::new(AtomicBool::new(false));
        let stop_thread = stop.clone();
        let responder = std::thread::spawn(move || {
            while !stop_thread.load(Ordering::Relaxed) {
                match listener.accept() {
                    Ok((mut stream, _)) => {
                        // Drain the request (best-effort) then answer a bare 200.
                        let mut buf = [0u8; 1024];
                        let _ = stream.read(&mut buf);
                        let _ = stream.write_all(
                            b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
                        );
                        let _ = stream.flush();
                    }
                    Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {
                        std::thread::sleep(Duration::from_millis(10));
                    }
                    Err(_) => break,
                }
            }
        });

        let _env = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let _dir_env = crate::config::OPENLATCH_DIR_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let tmp = tempfile::tempdir().expect("tempdir");
        std::env::set_var("OPENLATCH_DIR", tmp.path());

        let args = StartArgs {
            foreground: false,
            port: Some(port),
            boundary_port: None,
        };
        let result = run_start(&args, &quiet_output());

        std::env::remove_var("OPENLATCH_DIR");
        stop.store(true, Ordering::Relaxed);
        let _ = responder.join();

        let err = result.expect_err("start must refuse when a daemon answers /health");
        assert_eq!(
            err.code, ERR_ALREADY_RUNNING,
            "duplicate refusal must carry OL-1501, got {}",
            err.code
        );
    }

    /// `openlatch stop` must tear down EVERY wired agent, not just the first.
    ///
    /// The daemon removes `ANTHROPIC_BASE_URL` itself on a graceful teardown;
    /// after a SIGKILL this helper is the only thing that does. Stopping at the
    /// first agent leaves every later one pointed at a loopback port nobody
    /// holds — every model call on that agent fails, and nothing says why.
    #[cfg(feature = "boundary")]
    #[test]
    fn stop_tears_down_every_wired_agent() {
        let tmp = tempfile::tempdir().unwrap();

        // Bindings, not literal paths: `remove_boundary_config` dispatches on
        // the agent's endpoint convention, so an agent that declares none is
        // skipped entirely and a fixture without one would assert nothing.
        let mut agents: Vec<std::sync::Arc<dyn crate::hooks::binding::AgentBinding>> = Vec::new();
        for (agent_type, dir_name) in [("claude-code", "claude"), ("cursor", "cursor")] {
            let dir = tmp.path().join(dir_name);
            std::fs::create_dir_all(&dir).unwrap();
            std::fs::write(
                dir.join("settings.json"),
                r#"{"env": {"ANTHROPIC_BASE_URL": "http://127.0.0.1:7600"}}"#,
            )
            .unwrap();
            agents.push(std::sync::Arc::new(
                crate::hooks::binding::test_support::FakeBinding {
                    agent_type,
                    config_dir: dir,
                    boundary_wiring: Some(crate::hooks::binding::BoundaryWiring {
                        wire_format: crate::boundary::wire_format::WireFormat::AnthropicMessages,
                        endpoint: crate::hooks::binding::EndpointConvention::EnvVars {
                            base_url: crate::hooks::ANTHROPIC_BASE_URL_ENV,
                            headers: crate::hooks::ANTHROPIC_CUSTOM_HEADERS_ENV,
                        },
                        install_id_header: "x-openlatch-install-id",
                    }),
                    ..Default::default()
                },
            ));
        }

        // The fixture only proves something if both files really are wired
        // before the call — an unwired file is trivially "unwired" after.
        for binding in &agents {
            assert!(
                crate::cli::commands::boundary::read_boundary_base_url(&binding.hook_config_path())
                    .is_some(),
                "{} must start out wired",
                binding.agent_type()
            );
        }

        let was_wired = unwire_all(agents.clone());

        assert!(
            was_wired,
            "wiring existed and was removed, so the caller must be told to print the step"
        );
        for binding in &agents {
            assert!(
                crate::cli::commands::boundary::read_boundary_base_url(&binding.hook_config_path())
                    .is_none(),
                "{} is still wired after stop",
                binding.agent_type()
            );
        }
    }
}

// ---------------------------------------------------------------------------
// Reclaim — taking sole ownership of the ports before an install
// ---------------------------------------------------------------------------

/// What [`reclaim_ports`] did.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ReclaimAction {
    /// Nothing held either port.
    Nothing,
    /// An OpenLatch daemon was stopped and its ports released.
    Stopped,
    /// An OpenLatch daemon ignored the graceful shutdown and was killed.
    ForceKilled,
}

/// Who held the port, for the line `init` prints about the process it replaced.
///
/// "No zombie process from X hours ago" is only verifiable if X is printed, so
/// the age and the executable path are part of the outcome rather than a debug
/// log nobody reads.
#[derive(Debug, Clone, Default)]
pub struct ReclaimedIdentity {
    pub pid: Option<u32>,
    pub version: Option<String>,
    pub uptime_secs: Option<u64>,
    pub exe: Option<String>,
}

impl ReclaimedIdentity {
    /// `PID 625897, v0.1.16-dev.2, up 40h, from /path/to/openlatch`
    pub fn describe(&self) -> String {
        let mut parts = Vec::new();
        if let Some(pid) = self.pid {
            parts.push(format!("PID {pid}"));
        }
        if let Some(v) = &self.version {
            parts.push(format!("v{v}"));
        }
        if let Some(secs) = self.uptime_secs {
            parts.push(format!("up {}", approx_duration(secs)));
        }
        if let Some(exe) = &self.exe {
            parts.push(format!("from {exe}"));
        }
        if parts.is_empty() {
            "an unidentified daemon".to_string()
        } else {
            parts.join(", ")
        }
    }
}

/// Outcome of a reclaim pass.
#[derive(Debug, Clone)]
pub struct ReclaimOutcome {
    pub action: ReclaimAction,
    pub identity: ReclaimedIdentity,
}

/// Seconds as a coarse human duration. Deliberately approximate — the point is
/// "this thing is ancient", not an exact interval.
fn approx_duration(secs: u64) -> String {
    match secs {
        0..=90 => format!("{secs}s"),
        91..=5400 => format!("{}m", secs / 60),
        5401..=172_800 => format!("{}h", secs / 3600),
        _ => format!("{}d", secs / 86_400),
    }
}

/// Best-effort path of a running process's executable.
///
/// Linux only for now: `/proc/<pid>/exe`. Everywhere else this returns `None`
/// and the caller simply prints one fewer fact — an approximation is worse than
/// an omission in a line an operator uses to identify a process.
fn process_exe(pid: u32) -> Option<String> {
    #[cfg(target_os = "linux")]
    {
        std::fs::read_link(format!("/proc/{pid}/exe"))
            .ok()
            .map(|p| p.display().to_string())
    }
    #[cfg(not(target_os = "linux"))]
    {
        let _ = pid;
        None
    }
}

/// Is anything accepting connections on this loopback port?
pub(crate) fn port_is_held(port: u16) -> bool {
    std::net::TcpListener::bind(("127.0.0.1", port)).is_err()
}

/// Block until the port is free, or the deadline passes. Returns `true` if free.
fn wait_for_port_free(port: u16, timeout_secs: u64) -> bool {
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(timeout_secs);
    while std::time::Instant::now() < deadline {
        if !port_is_held(port) {
            return true;
        }
        std::thread::sleep(std::time::Duration::from_millis(150));
    }
    !port_is_held(port)
}

/// Ask the daemon on `port` who it is. `None` when nothing there speaks our
/// `/health`.
fn identify_daemon(port: u16) -> Option<ReclaimedIdentity> {
    let body: serde_json::Value = crate::egress::blocking_client()
        .get(format!("http://127.0.0.1:{port}/health"))
        .timeout(std::time::Duration::from_secs(2))
        .send()
        .ok()
        .filter(|r| r.status().is_success())?
        .json()
        .ok()?;
    // A JSON 200 from something that is not us is not an identification.
    body.get("version")?;
    let pid = body
        .get("pid")
        .and_then(|v| v.as_u64())
        .and_then(|v| u32::try_from(v).ok())
        // Pre-`pid`-field daemons: fall back to the pid file, which is right
        // whenever there is only one instance — the case this fallback covers.
        .or_else(read_pid_file);
    Some(ReclaimedIdentity {
        pid,
        version: body
            .get("version")
            .and_then(|v| v.as_str())
            .map(str::to_string),
        uptime_secs: body.get("uptime_secs").and_then(|v| v.as_u64()),
        exe: pid.and_then(process_exe),
    })
}

/// Take sole ownership of the daemon port and the boundary port before an
/// install writes anything.
///
/// **This is the step whose absence made `openlatch init` a no-op.** `init`
/// spawned a daemon unconditionally; the child lost the bind race, printed
/// `OL-1501` to a `/dev/null` stderr and exited; `wait_for_health` then got its
/// 200 from the *old* process and `init` reported success. A daemon from a
/// deleted worktree served this machine for forty hours across three installs
/// that all claimed to have replaced it.
///
/// The holder is identified **by the port**, never by `daemon.pid` alone: that
/// zombie's path, binary name and version all differed from the installation
/// being run, and the port was the only thing that still pointed at it.
///
/// # Errors
///
/// `OL-1500` when a port stays held by something that is not an OpenLatch
/// daemon, or by one that survived SIGKILL. Refusing here is the point: an
/// install that cannot own its ports has not happened.
pub fn reclaim_ports(
    cfg: &config::Config,
    output: &OutputConfig,
) -> Result<ReclaimOutcome, OlError> {
    let mut outcome = ReclaimOutcome {
        action: ReclaimAction::Nothing,
        identity: ReclaimedIdentity::default(),
    };

    let daemon_held = port_is_held(cfg.port);
    let stale_pid = read_pid_file().filter(|p| is_process_alive(*p));

    if daemon_held || stale_pid.is_some() {
        match identify_daemon(cfg.port) {
            Some(identity) => {
                output.print_substep(&format!("Reclaiming daemon ({})", identity.describe()));
                outcome.identity = identity;
            }
            None if daemon_held => {
                // Something holds the port and does not answer as us. Killing it
                // is not ours to do.
                return Err(OlError::new(
                    ERR_PORT_IN_USE,
                    format!(
                        "127.0.0.1:{} is held by a process that is not an OpenLatch daemon",
                        cfg.port
                    ),
                )
                .with_suggestion(format!(
                    "Identify it with `lsof -i :{}` (or `ss -tlnp | grep :{}`) and stop it, \
                     or point this install elsewhere with OPENLATCH_PORT.",
                    cfg.port, cfg.port
                ))
                .with_docs("https://docs.openlatch.ai/errors/OL-1500"));
            }
            // A live pid file with a free port: a daemon that is starting, or a
            // process that no longer serves. `run_stop` reaps it either way.
            None => {
                outcome.identity = ReclaimedIdentity {
                    pid: stale_pid,
                    exe: stale_pid.and_then(process_exe),
                    ..Default::default()
                };
            }
        }

        // `run_stop` owns the ordinary escalation — supervisor, then
        // POST /shutdown, then SIGTERM, then SIGKILL — and re-implementing any
        // rung of it here would be a second, subtly different stop path.
        run_stop(output)?;
        let mut forced = false;

        // `run_stop` finds its target through `daemon.pid`, and the daemon we
        // have to end is precisely the one that file may not name: a process
        // whose pid file was overwritten by a later start, deleted by a
        // half-finished uninstall, or never written where this install can see
        // it. `run_stop` then prints "Daemon is not running" and returns
        // happily while the port stays held.
        //
        // The port answered `/health` a moment ago, so we have its PID from a
        // source that cannot be stale. Escalate on that.
        if port_is_held(cfg.port) {
            if let Some(pid) = outcome.identity.pid.filter(|p| is_process_alive(*p)) {
                forced = true;
                output.print_substep(&format!(
                    "PID {pid} holds the port but is not the daemon on record — stopping it directly"
                ));
                let token = load_or_generate_token().unwrap_or_default();
                if send_shutdown_request(cfg.port, &token) {
                    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
                    while std::time::Instant::now() < deadline && is_process_alive(pid) {
                        std::thread::sleep(std::time::Duration::from_millis(150));
                    }
                }
                if is_process_alive(pid) {
                    force_kill(pid);
                    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(3);
                    while std::time::Instant::now() < deadline && is_process_alive(pid) {
                        std::thread::sleep(std::time::Duration::from_millis(100));
                    }
                }
                if is_process_alive(pid) {
                    force_kill_hard(pid);
                }
            }
        }

        if !wait_for_port_free(cfg.port, 10) {
            return Err(OlError::new(
                ERR_PORT_IN_USE,
                format!(
                    "127.0.0.1:{} is still held 10s after stopping the daemon that held it",
                    cfg.port
                ),
            )
            .with_suggestion(format!(
                "Something else took the port. Identify it with `lsof -i :{}` (or \
                 `ss -tlnp | grep :{}`) and stop it.",
                cfg.port, cfg.port
            ))
            .with_docs("https://docs.openlatch.ai/errors/OL-1500"));
        }
        // The pid file may name a process this reclaim never touched; the fact
        // that matters is whether *we* had to escalate past the graceful stop.
        outcome.action = if forced {
            ReclaimAction::ForceKilled
        } else {
            ReclaimAction::Stopped
        };
    }

    // The boundary port matters as much as the daemon port: the daemon refuses
    // to come up without it, and the failure lands in a log file rather than in
    // front of the operator. Checked here so the message names the port and the
    // way to find its holder.
    #[cfg(feature = "boundary")]
    if cfg.boundary.enabled && port_is_held(cfg.boundary.port) {
        // The daemon we just stopped may still be releasing it.
        if !wait_for_port_free(cfg.boundary.port, 5) {
            return Err(OlError::new(
                crate::error::ERR_BOUNDARY_PORT_FOREIGN,
                format!(
                    "the model boundary's port 127.0.0.1:{} is held by another process",
                    cfg.boundary.port
                ),
            )
            .with_suggestion(format!(
                "Identify it with `lsof -i :{}` and stop it, or run `openlatch init \
                 --no-boundary` to install without the model boundary.",
                cfg.boundary.port
            ))
            .with_docs("https://docs.openlatch.ai/errors/OL-BND-FOREIGN"));
        }
    }

    Ok(outcome)
}

// ---------------------------------------------------------------------------
// Spawning with evidence
// ---------------------------------------------------------------------------

/// A background daemon this process started, kept long enough to prove it came
/// up — or to say why it did not.
pub struct SpawnedDaemon {
    pub pid: u32,
    child: std::process::Child,
    log_path: std::path::PathBuf,
}

impl SpawnedDaemon {
    /// The child's exit status if it has already exited, without blocking.
    ///
    /// A daemon that dies immediately is the normal shape of every start
    /// failure — port taken, token unreadable, boundary refusing to bind — and
    /// for the life of this command nobody looked. `wait_for_health` then
    /// answered from whatever else was on the port.
    pub fn exited(&mut self) -> Option<std::process::ExitStatus> {
        self.child.try_wait().ok().flatten()
    }

    /// The last few lines the child wrote before dying, for the error message.
    pub fn stderr_tail(&self, lines: usize) -> Vec<String> {
        let Ok(content) = std::fs::read_to_string(&self.log_path) else {
            return Vec::new();
        };
        content
            .lines()
            .filter(|l| !l.trim().is_empty())
            .rev()
            .take(lines)
            .map(str::to_string)
            .collect::<Vec<_>>()
            .into_iter()
            .rev()
            .collect()
    }

    pub fn log_path(&self) -> &std::path::Path {
        &self.log_path
    }

    /// Wrap an arbitrary child, so a test can present the shape a failed start
    /// takes without needing a real daemon to fail.
    #[cfg(test)]
    fn from_child_for_test(child: std::process::Child, log_path: std::path::PathBuf) -> Self {
        Self {
            pid: child.id(),
            child,
            log_path,
        }
    }
}

/// Spawn the daemon and keep the handle, so the caller can tell "it is starting"
/// apart from "it is already dead".
///
/// Unlike [`spawn_daemon_background`], the child's stderr goes to
/// `~/.openlatch/logs/daemon-spawn.log` rather than `/dev/null`. Discarding it
/// is what turned an `OL-1501` refusal into a silent success: the one sentence
/// that explained the failure was written to a file descriptor pointing at
/// nothing.
pub fn spawn_daemon_tracked(port: u16, token: &str) -> Result<SpawnedDaemon, OlError> {
    let exe = std::env::current_exe().map_err(|e| {
        OlError::new(
            ERR_INVALID_CONFIG,
            format!("Cannot locate current executable: {e}"),
        )
    })?;

    let log_dir = config::openlatch_dir().join("logs");
    let _ = std::fs::create_dir_all(&log_dir);
    let log_path = log_dir.join("daemon-spawn.log");
    // Truncated per spawn: this file answers "why did the start I just ran
    // fail", and a growing log makes the answer harder to find, not easier.
    let stderr_sink = std::fs::File::create(&log_path).map_err(|e| {
        OlError::new(
            ERR_INVALID_CONFIG,
            format!("Cannot open {}: {e}", log_path.display()),
        )
    })?;

    let mut cmd = std::process::Command::new(&exe);
    cmd.args([
        "daemon",
        "start",
        "--foreground",
        "--port",
        &port.to_string(),
    ])
    .env("OPENLATCH_TOKEN", token)
    .stdin(Stdio::null())
    .stdout(Stdio::null())
    .stderr(Stdio::from(stderr_sink));

    #[cfg(unix)]
    {
        use std::os::unix::process::CommandExt;
        // See `spawn_daemon_background` for why this is `setsid` and not
        // `process_group(0)`, and why the EPERM case is deliberately ignored.
        //
        // SAFETY: `pre_exec` runs in the forked child between `fork` and
        // `exec`, where only async-signal-safe calls are permitted. `setsid(2)`
        // is on POSIX's async-signal-safe list.
        unsafe {
            cmd.pre_exec(|| {
                libc::setsid();
                Ok(())
            });
        }
    }
    #[cfg(windows)]
    {
        use std::os::windows::process::CommandExt;
        const CREATE_NO_WINDOW: u32 = 0x0800_0000;
        const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
        cmd.creation_flags(CREATE_NO_WINDOW | CREATE_NEW_PROCESS_GROUP);
    }

    let child = cmd.spawn().map_err(|e| {
        OlError::new(
            ERR_INVALID_CONFIG,
            format!("Failed to spawn daemon process: {e}"),
        )
        .with_suggestion("Check that the openlatch binary is executable.")
    })?;

    Ok(SpawnedDaemon {
        pid: child.id(),
        log_path,
        child,
    })
}

/// Why a freshly-spawned daemon cannot be called started.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StartFailure {
    /// The child process exited before serving.
    ChildDied { status: String, log: Vec<String> },
    /// Nothing answered `/health` within the deadline.
    NoHealth,
    /// Something answers, but it is not the process we started.
    ForeignPid { answering: u32, expected: u32 },
    /// The process on the port serves a different build than the one we ran.
    VersionMismatch { serving: String, expected: String },
}

/// Prove the daemon on `port` is the one just spawned.
///
/// Three facts have to agree, and each one alone has been observed lying:
/// `/health` answering (an *older* daemon answers just as well), the PID
/// (a pid file survives the process that wrote it), and the version (a start
/// that silently lost the race leaves the previous build serving). Checking one
/// of the three is what "Daemon started on port 7443 (PID 4185510)" meant while
/// PID 4185510 no longer existed.
pub fn verify_started_daemon(
    spawned: &mut SpawnedDaemon,
    port: u16,
    timeout_secs: u64,
) -> Result<(), StartFailure> {
    let expected_version = env!("OPENLATCH_VERSION");
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(timeout_secs);

    loop {
        if let Some(status) = spawned.exited() {
            return Err(StartFailure::ChildDied {
                status: status.to_string(),
                log: spawned.stderr_tail(20),
            });
        }
        if let Some(identity) = identify_daemon(port) {
            let serving = identity.version.unwrap_or_default();
            if serving != expected_version {
                return Err(StartFailure::VersionMismatch {
                    serving,
                    expected: expected_version.to_string(),
                });
            }
            match identity.pid {
                Some(pid) if pid == spawned.pid => return Ok(()),
                // Pre-`pid`-field daemon, or a pid file that has not landed
                // yet. The version already matched, which is the fact that
                // catches a stale process; keep waiting for the PID rather than
                // failing on a race we created.
                Some(pid) if std::time::Instant::now() >= deadline => {
                    return Err(StartFailure::ForeignPid {
                        answering: pid,
                        expected: spawned.pid,
                    })
                }
                None if std::time::Instant::now() >= deadline => return Ok(()),
                _ => {}
            }
        }
        if std::time::Instant::now() >= deadline {
            return Err(StartFailure::NoHealth);
        }
        std::thread::sleep(std::time::Duration::from_millis(150));
    }
}

/// Turn a [`StartFailure`] into the error the operator sees.
pub fn start_failure_error(failure: StartFailure, port: u16) -> OlError {
    match failure {
        StartFailure::ChildDied { status, log } => {
            let detail = if log.is_empty() {
                String::new()
            } else {
                format!("\n\n  The daemon said:\n    {}", log.join("\n    "))
            };
            OlError::new(
                ERR_DAEMON_START_FAILED,
                format!("The daemon exited immediately ({status}){detail}"),
            )
            .with_suggestion(
                "The full output is in ~/.openlatch/logs/daemon-spawn.log; the daemon's own \
                 log is the newest ~/.openlatch/logs/daemon.log.<date>.",
            )
            .with_docs("https://docs.openlatch.ai/errors/OL-1502")
        }
        StartFailure::NoHealth => OlError::new(
            ERR_DAEMON_START_FAILED,
            format!("Nothing answered /health on port {port}"),
        )
        .with_suggestion(
            "Check ~/.openlatch/logs/daemon-spawn.log and the newest \
             ~/.openlatch/logs/daemon.log.<date> (the log rotates daily, so there is no \
             unsuffixed daemon.log).",
        )
        .with_docs("https://docs.openlatch.ai/errors/OL-1502"),
        StartFailure::ForeignPid {
            answering,
            expected,
        } => OlError::new(
            ERR_DAEMON_START_FAILED,
            format!(
                "Port {port} is served by PID {answering}, not the daemon just started (PID {expected})"
            ),
        )
        .with_suggestion("Run `openlatch stop`, then `openlatch init` again.")
        .with_docs("https://docs.openlatch.ai/errors/OL-1502"),
        StartFailure::VersionMismatch { serving, expected } => OlError::new(
            ERR_DAEMON_START_FAILED,
            format!(
                "Port {port} is served by version {serving}, but this binary is {expected}\
                 an older daemon still owns the port"
            ),
        )
        .with_suggestion("Run `openlatch stop`, confirm the port is free, then `openlatch init` again.")
        .with_docs("https://docs.openlatch.ai/errors/OL-1502"),
    }
}

/// Prove the daemon on `port` is running this build, without having spawned it.
///
/// The supervised path has no child handle — `systemctl enable --now` and
/// launchd's `RunAtLoad` start the unit — so the PID cannot be predicted. The
/// version still can, and it is the fact that catches the failure that matters:
/// an older daemon holding the port while the install reports success.
pub fn verify_running_daemon(port: u16, timeout_secs: u64) -> Result<u32, StartFailure> {
    let expected_version = env!("OPENLATCH_VERSION");
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(timeout_secs);
    let mut last_seen: Option<String> = None;

    loop {
        if let Some(identity) = identify_daemon(port) {
            let serving = identity.version.clone().unwrap_or_default();
            if serving == expected_version {
                return Ok(identity.pid.unwrap_or(0));
            }
            last_seen = Some(serving);
        }
        if std::time::Instant::now() >= deadline {
            return Err(match last_seen {
                Some(serving) => StartFailure::VersionMismatch {
                    serving,
                    expected: expected_version.to_string(),
                },
                None => StartFailure::NoHealth,
            });
        }
        std::thread::sleep(std::time::Duration::from_millis(200));
    }
}