openlatch-client 0.1.18

OpenLatch runtime enforcement node — the capture-and-enforce client for the AI Operations Platform
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
/// 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,
};

/// 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"));
        unwire_boundary_after_death();
        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");
        unwire_boundary_after_death();
        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"));
        unwire_boundary_after_death();
        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"));
        unwire_boundary_after_death();
        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"));
    unwire_boundary_after_death();
    output.print_step("Daemon stopped");
    Ok(())
}

/// 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() {
    #[cfg(feature = "boundary")]
    {
        use crate::cli::commands::boundary::{verify_port_ownership, PortOwnership};

        let Ok(cfg) = config::Config::load(None, None, false) else {
            return;
        };
        // 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;
        }
        let port = cfg.boundary.port;
        if verify_port_ownership(port) == PortOwnership::Owned {
            // Someone else's live boundary. The config naming it is correct.
            return;
        }
        let Ok(crate::hooks::DetectedAgent::ClaudeCode { settings_path, .. }) =
            crate::hooks::detect_agent()
        else {
            return;
        };
        if let Err(e) = crate::hooks::remove_boundary_config(&settings_path) {
            tracing::warn!(
                code = %e.code,
                error = %e.message,
                "could not remove the agent's boundary wiring after stop"
            );
        }
    }
}

/// 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 = reqwest::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");
    reqwest::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 _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);

            // 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 {
    use super::*;

    /// Serializes the two `OPENLATCH_DIR`-mutating tests below against each other.
    /// Process-global env can only be poked by one at a time.
    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 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 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
        );
    }
}