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
/// `openlatch doctor` command handler.
///
/// Runs diagnostic checks and reports results.
/// All path references use `config::openlatch_dir()` per PLAT-02.
///
/// `--fix`, `--restore`, and `--rescue` dispatch to sibling modules
/// (`doctor_fix`, `doctor_restore`, `doctor_rescue`). The shared
/// `run_all_checks` helper returns a structured `DoctorReport` so those
/// modules can re-run diagnostics for before/after deltas without
/// duplicating ~600 LOC of probe logic.
use crate::cli::commands::lifecycle;
use crate::cli::commands::{doctor_fix, doctor_rescue, doctor_restore};
use crate::cli::output::{OutputConfig, OutputFormat};
use crate::cli::DoctorArgs;
use crate::config;
use crate::error::OlError;
use crate::hooks;

/// How a single doctor check came out.
///
/// The middle tier exists because "not the ideal state" and "something is
/// broken" were being reported identically, and the ones that were merely
/// suboptimal — no OS supervisor on a host that cannot have one, drift right
/// after an auto-update — trained people to read every cross as noise. A `Warn`
/// is visible and does not count toward the exit code.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum CheckStatus {
    Pass,
    Warn,
    Fail,
}

/// A single doctor check result.
#[derive(Clone)]
pub(crate) struct DoctorCheck {
    pub status: CheckStatus,
    pub message: String,
}

impl DoctorCheck {
    pub(crate) fn pass(message: impl Into<String>) -> Self {
        Self {
            status: CheckStatus::Pass,
            message: message.into(),
        }
    }

    pub(crate) fn warn(message: impl Into<String>) -> Self {
        Self {
            status: CheckStatus::Warn,
            message: message.into(),
        }
    }

    pub(crate) fn fail(message: impl Into<String>) -> Self {
        Self {
            status: CheckStatus::Fail,
            message: message.into(),
        }
    }

    /// `true` for anything that is not a failure — `Warn` included.
    pub(crate) fn is_pass(&self) -> bool {
        self.status != CheckStatus::Fail
    }
}

/// Aggregate diagnostic snapshot returned by [`run_all_checks`].
///
/// Carries enough state for `--fix` and `--rescue` flows to inspect
/// daemon liveness and the originally-configured port without re-probing.
#[allow(dead_code)] // fields consumed by doctor_fix / doctor_rescue (steps 4–7)
pub(crate) struct DoctorReport {
    pub checks: Vec<DoctorCheck>,
    pub issues: Vec<String>,
    pub daemon_alive: bool,
    pub daemon_uptime_secs: Option<u64>,
    pub port: u16,
}

#[allow(dead_code)] // methods consumed by doctor_fix (step 4) for before/after deltas
impl DoctorReport {
    /// Convenience: `true` when no check failed. Warnings do not disqualify.
    pub(crate) fn all_pass(&self) -> bool {
        self.checks.iter().all(DoctorCheck::is_pass)
    }

    /// Number of failing checks. Warnings are deliberately not counted — they
    /// feed the exit code nowhere, which is the point of the tier.
    pub(crate) fn fail_count(&self) -> usize {
        self.checks
            .iter()
            .filter(|c| c.status == CheckStatus::Fail)
            .count()
    }
}

/// Run the `openlatch doctor` command.
///
/// Default invocation (no flags): runs diagnostic checks and reports results.
/// `--fix`, `--restore`, `--rescue` dispatch to the matching sibling module.
/// Combined `--fix --rescue` and `--restore --rescue` are allowed —
/// rescue runs first to snapshot pre-fix state.
///
/// # Errors
///
/// Returns an error only if a fix/restore/rescue helper itself fails —
/// individual diagnostic check failures are reported, not returned.
pub fn run_doctor(args: &DoctorArgs, output: &OutputConfig) -> Result<(), OlError> {
    // Hidden self-test: deliberately panic to exercise the Sentry pipeline.
    // Used once per release during smoke validation — see brainstorm
    // Decision 14. Panics after crash-report init has already completed
    // at the top of main(), so the panic hook is live.
    if args.trigger_panic {
        panic!("openlatch crash-report validation panic");
    }

    // Combined-flag composition: rescue first to capture pre-fix state.
    if args.rescue && args.fix {
        doctor_rescue::run(args, output, /* fix_applied_after = */ true)?;
        return doctor_fix::run(args, output);
    }
    if args.rescue && args.restore {
        doctor_rescue::run(args, output, false)?;
        return doctor_restore::run(args, output);
    }
    if args.fix {
        return doctor_fix::run(args, output);
    }
    if args.restore {
        return doctor_restore::run(args, output);
    }
    if args.rescue {
        return doctor_rescue::run(args, output, false);
    }

    crate::cli::header::print(output, &["doctor"]);
    if output.format == OutputFormat::Human && !output.quiet {
        eprintln!();
    }

    let report = run_all_checks(output)?;
    print_diagnostic_results(&report, output);
    Ok(())
}

/// Run every diagnostic check and assemble a [`DoctorReport`].
///
/// Pure read-only — never mutates state. Reusable by `doctor_fix` (for
/// before/after deltas) and `doctor_rescue` (for the bundled health
/// snapshot).
pub(crate) fn run_all_checks(_output: &OutputConfig) -> Result<DoctorReport, OlError> {
    let cfg = config::Config::load(None, None, false)?;
    let ol_dir = config::openlatch_dir();

    let mut issues: Vec<String> = Vec::new();
    let mut checks: Vec<DoctorCheck> = Vec::new();

    // Check 1: Agent detection
    match hooks::detect_agent() {
        Ok(agent) => {
            let label = match &agent {
                hooks::DetectedAgent::ClaudeCode { claude_dir, .. } => {
                    format!("Claude Code ({})", claude_dir.display())
                }
            };
            checks.push(DoctorCheck::pass(format!("Agent detected: {label}")));
        }
        Err(e) => {
            let msg = format!("Agent not found: {} ({})", e.message, e.code);
            checks.push(DoctorCheck::fail(msg.clone()));
            issues.push("No AI agent detected. Install Claude Code to use OpenLatch.".to_string());
        }
    }

    // Check 2: Config file exists and is parseable (PLAT-02: OS-aware path)
    let config_path = ol_dir.join("config.toml");
    if config_path.exists() {
        match config::Config::load(None, None, false) {
            Ok(_) => {
                checks.push(DoctorCheck::pass(format!(
                    "Config file: {}",
                    config_path.display()
                )));
            }
            Err(e) => {
                checks.push(DoctorCheck::fail(format!(
                    "Config file invalid: {} ({})",
                    e.message, e.code
                )));
                issues.push(format!(
                    "Config file '{}' has errors. Delete and re-run 'openlatch init'.",
                    config_path.display()
                ));
            }
        }
    } else {
        checks.push(DoctorCheck::fail(format!(
            "Config file missing: {}",
            config_path.display()
        )));
        issues.push("Config file missing. Run 'openlatch init' to create it.".to_string());
    }

    // Check 2b: Crash report consent state (panic reporting to Sentry).
    // Diagnostic only — never a fail condition. Reports the resolved state so
    // users can verify their opt-out (`SENTRY_DISABLED=1` or
    // `[crashreport] enabled = false`) actually landed.
    #[cfg(feature = "crash-report")]
    {
        let resolved = crate::crash_report::current_state(&ol_dir);
        let label = match resolved.decided_by {
            crate::crash_report::consent::DecidedBy::SentryDisabledEnv => {
                "off (SENTRY_DISABLED env)"
            }
            crate::crash_report::consent::DecidedBy::NoBakedDsn => "off (no DSN baked)",
            crate::crash_report::consent::DecidedBy::ConfigFile => {
                if resolved.enabled() {
                    "on (config.toml)"
                } else {
                    "off (config.toml)"
                }
            }
            crate::crash_report::consent::DecidedBy::DefaultEnabled => "on (default)",
        };
        checks.push(DoctorCheck::pass(format!("Crash reporting: {label}")));
    }
    #[cfg(not(feature = "crash-report"))]
    {
        checks.push(DoctorCheck::pass(
            "Crash reporting: not compiled in".to_string(),
        ));
    }

    // Check 3: Auth token exists and non-empty (PLAT-02: OS-aware path)
    let token_path = ol_dir.join("daemon.token");
    let mut daemon_token: Option<String> = None;
    if token_path.exists() {
        match std::fs::read_to_string(&token_path) {
            Ok(content) if !content.trim().is_empty() => {
                daemon_token = Some(content.trim().to_string());
                checks.push(DoctorCheck::pass(format!(
                    "Auth token: {} (valid)",
                    token_path.display()
                )));
            }
            Ok(_) => {
                checks.push(DoctorCheck::fail(format!(
                    "Auth token empty: {}",
                    token_path.display()
                )));
                issues.push("Auth token is empty. Run 'openlatch init' to regenerate.".to_string());
            }
            Err(e) => {
                checks.push(DoctorCheck::fail(format!(
                    "Auth token unreadable: {}{e}",
                    token_path.display()
                )));
                issues.push(format!(
                    "Cannot read token file '{}'. Check file permissions.",
                    token_path.display()
                ));
            }
        }
    } else {
        checks.push(DoctorCheck::fail(format!(
            "Auth token missing: {}",
            token_path.display()
        )));
        issues.push("Auth token missing. Run 'openlatch init' to generate one.".to_string());
    }

    // Check 4: Daemon reachable via /health
    let pid = lifecycle::read_pid_file();
    let daemon_alive = pid.map(lifecycle::is_process_alive).unwrap_or(false);

    // The PID comes from <dir>/daemon.pid, the port from config/env — two
    // independent sources that are only equal by convention. <dir>/daemon.port
    // records the port the daemon in THIS directory actually bound, so a
    // disagreement means the /health probe below is answered by some OTHER
    // daemon while we report the local PID next to it.
    //
    // Seen in practice with two instances up: `OPENLATCH_PORT=7543` with
    // OPENLATCH_DIR left at the default made doctor print "running on port
    // 7543 (PID 1115226)" — but 1115226 was on 7443, and 7543 belonged to an
    // entirely different process. Every downstream check then compared against
    // an instance the operator was not looking at.
    let bound_port = config::read_port_file();
    if let (true, Some(bound)) = (daemon_alive, bound_port) {
        if bound != cfg.port {
            checks.push(DoctorCheck::fail(format!(
                "Daemon identity: daemon.port says this instance is on {bound}, but the configured port is {}",
                cfg.port
            )));
            issues.push(format!(
                "PID {} belongs to the daemon on port {bound}; port {} is served by a different process. Checks below describe that other instance — re-run with OPENLATCH_DIR set to the instance you mean.",
                pid.unwrap_or(0),
                cfg.port
            ));
        }
    }

    // Hoisted out of the block below: the hook-port cross-check needs to know
    // whether anything answered, so it can skip a comparison against a port no
    // daemon is serving instead of calling it a match.
    let mut daemon_reachable = false;
    if daemon_alive {
        let url = format!("http://127.0.0.1:{}/health", cfg.port);
        // Keep the body, not just the status: `/health` carries the version the
        // daemon is actually serving, which is the only way to see an upgrade
        // that landed on disk without reaching the running process.
        let health: Option<serde_json::Value> = reqwest::blocking::get(&url)
            .ok()
            .filter(|r| r.status().is_success())
            .and_then(|r| r.json().ok());
        let reachable = health.is_some();
        daemon_reachable = reachable;
        if reachable {
            // Only claim the PID and the port describe one process when
            // daemon.port agrees (or is absent, i.e. nothing to contradict).
            let same_instance = bound_port.map(|b| b == cfg.port).unwrap_or(true);
            if same_instance {
                checks.push(DoctorCheck::pass(format!(
                    "Daemon: running on port {} (PID {})",
                    cfg.port,
                    pid.unwrap()
                )));
            } else {
                checks.push(DoctorCheck::pass(format!(
                    "Daemon: port {} is serving (PID unknown — local daemon.pid {} is on port {})",
                    cfg.port,
                    pid.unwrap(),
                    bound_port.unwrap()
                )));
            }

            // An upgrade that reached the disk but not the process. Every other
            // signal on the machine looks healthy here — the package manager
            // succeeded, the binary on disk really is new, and this daemon
            // answers 200 — so nothing but this comparison catches it. On a
            // security client it means a fix the user installed is not running.
            if let Some(running) = health
                .as_ref()
                .and_then(|h| h.get("version"))
                .and_then(|v| v.as_str())
            {
                let installed = env!("OPENLATCH_VERSION");
                if running != installed {
                    checks.push(DoctorCheck::warn(format!(
                        "Daemon binary: serving {running}, {installed} installed on disk"
                    )));
                    issues.push(format!(
                        "The daemon is still serving {running} while {installed} sits on disk — \
                         an upgrade landed but never took effect (a package manager replaces the \
                         binary; it does not restart the process). Run 'openlatch restart'."
                    ));
                }
            }
        } else {
            checks.push(DoctorCheck::fail(format!(
                "Daemon: process alive (PID {}) but /health unreachable on port {}",
                pid.unwrap(),
                cfg.port
            )));
            issues.push(format!(
                "Daemon process exists but /health on port {} doesn't respond. Try 'openlatch restart'.",
                cfg.port
            ));
        }
    } else {
        checks.push(DoctorCheck::fail(format!(
            "Daemon: not running (port {})",
            cfg.port
        )));
        issues.push("Daemon is not running. Run 'openlatch start' to start it.".to_string());
    }

    // Check 4b: Cloud reachability.
    // When the daemon is running we query its own /metrics endpoint for the
    // cloud_status it actually observes — this catches misconfigured URLs or
    // dropped events that the doctor process itself would never see (because it
    // reads its own env, which may differ from the env the daemon was started with).
    // When the daemon is down we fall back to a direct cloud ping from this process.
    let mut daemon_uptime_secs: Option<u64> = None;
    if daemon_alive {
        let metrics_url = format!("http://127.0.0.1:{}/metrics", cfg.port);
        match reqwest::blocking::get(&metrics_url).and_then(|r| r.json::<serde_json::Value>()) {
            Ok(m) => {
                daemon_uptime_secs = m.get("uptime_secs").and_then(|v| v.as_u64());
                let status = m
                    .get("cloud_status")
                    .and_then(|v| v.as_str())
                    .unwrap_or("unknown");
                let drops = m
                    .get("cloud_drop_count")
                    .and_then(|v| v.as_u64())
                    .unwrap_or(0);
                let api_url = m
                    .get("cloud_api_url")
                    .and_then(|v| v.as_str())
                    .unwrap_or("");
                match status {
                    "connected" => {
                        checks.push(DoctorCheck::pass(format!("Cloud: connected ({api_url})")));
                    }
                    "network_error" => {
                        let msg =
                            format!("Cloud: network errors — {drops} event(s) dropped ({api_url})");
                        checks.push(DoctorCheck::fail(msg.clone()));
                        issues.push(format!(
                            "Daemon cannot reach cloud at {api_url}. Check OPENLATCH_API_URL and network connectivity."
                        ));
                    }
                    "auth_error" => {
                        let msg = format!("Cloud: auth error — credential rejected ({api_url})");
                        checks.push(DoctorCheck::fail(msg));
                        issues.push(
                            "Run 'openlatch auth login' to refresh the cloud credential."
                                .to_string(),
                        );
                    }
                    "no_credential" => {
                        let msg = format!("Cloud: no credential — forwarding paused ({api_url})");
                        checks.push(DoctorCheck::fail(msg));
                        issues.push(
                            "Run 'openlatch auth login' to store an API key, or set \
                             [cloud] enabled = false in config.toml."
                                .to_string(),
                        );
                    }
                    "not_configured" => {
                        checks.push(DoctorCheck::pass(
                            "Cloud: disabled in daemon config".to_string(),
                        ));
                    }
                    other => {
                        checks.push(DoctorCheck::fail(format!(
                            "Cloud: unknown status '{other}'"
                        )));
                    }
                }
            }
            Err(_) => {
                checks.push(DoctorCheck::fail(
                    "Cloud: could not read daemon /metrics — daemon may be unhealthy".to_string(),
                ));
            }
        }
    } else if cfg.cloud.enabled {
        match tokio::runtime::Runtime::new() {
            Ok(rt) => {
                let (pass, message) = rt.block_on(check_cloud(&cfg.cloud.api_url));
                if pass {
                    checks.push(DoctorCheck::pass(message));
                } else {
                    checks.push(DoctorCheck::fail(message.clone()));
                    if message.contains("not authenticated") {
                        issues.push("Run 'openlatch auth login' to enable cloud sync.".to_string());
                    } else {
                        issues.push(format!(
                            "Cloud unreachable or credential rejected at {}. Check network connectivity or re-run 'openlatch auth login'.",
                            cfg.cloud.api_url
                        ));
                    }
                }
            }
            Err(_) => {
                checks.push(DoctorCheck::fail(
                    "Cloud: check skipped (runtime init failed)".to_string(),
                ));
            }
        }
    } else {
        checks.push(DoctorCheck::pass("Cloud: disabled in config".to_string()));
    }

    // Check 5: Hooks installed in settings.json
    if let Ok(agent) = hooks::detect_agent() {
        let settings_path = match &agent {
            hooks::DetectedAgent::ClaudeCode { settings_path, .. } => settings_path.clone(),
        };

        if settings_path.exists() {
            // Parsed, not substring-matched. `content.contains("Stop")` is true
            // for a settings.json whose only OpenLatch entry is `SubagentStop`,
            // or whose `Stop` array holds somebody else's hook — the marker and
            // the event were never checked on the same entry. The same laxity
            // in `doctor --fix` is what let it declare 12 dead hook commands
            // healthy.
            match crate::hooks::health::inspect_file(&settings_path) {
                Ok(health) => {
                    if health.missing_events.is_empty() {
                        checks.push(DoctorCheck::pass(format!(
                            "Hooks: all entries present in {}",
                            settings_path.display()
                        )));
                    } else {
                        for hook in &health.missing_events {
                            checks.push(DoctorCheck::fail(format!(
                                "Hooks: {hook} missing from {}",
                                settings_path.display()
                            )));
                        }
                        issues.push(format!(
                            "Missing hooks: {}. Run 'openlatch doctor --fix' to reinstall them (it keeps the current token, so running agent sessions keep capturing).",
                            health.missing_events.join(", ")
                        ));
                    }
                }
                Err(e) => {
                    checks.push(DoctorCheck::fail(format!(
                        "Hooks: cannot read {}{}",
                        settings_path.display(),
                        e.message
                    )));
                    issues.push(format!(
                        "Cannot read settings file '{}'. Check permissions.",
                        settings_path.display()
                    ));
                }
            }

            // Check 6: Hook command sanity — binary path exists + matches
            // resolve_hook_binary_path(), and settings.json OPENLATCH_TOKEN
            // matches daemon.token on disk. Catches stale post-reinstall state
            // where the daemon loaded a fresh token but settings.json still
            // carries the old one, or a drifted binary path after `cargo install`.
            check_hook_binding(
                &settings_path,
                daemon_token.as_deref(),
                cfg.port,
                daemon_reachable,
                &mut checks,
                &mut issues,
            );

            // Check 6a: the model-boundary invariant — wired iff someone is
            // listening. Reads the same settings.json, so it belongs here rather
            // than re-detecting the agent.
            #[cfg(feature = "boundary")]
            check_boundary_wiring(&cfg, &settings_path, &mut checks, &mut issues);
        } else {
            checks.push(DoctorCheck::fail(format!(
                "Hooks: settings.json not found at {}",
                settings_path.display()
            )));
            issues.push(
                "settings.json not found. Run 'openlatch init' to install hooks.".to_string(),
            );
        }
    }

    // Check 6b: Supervision state. Persistence is a security property — a
    // wrongly-advertised supervisor is worse than no supervisor, so we treat the
    // (Active, not-installed) drift as a fail condition that --fix can heal.
    check_supervision_state(&cfg, &mut checks, &mut issues);

    // Check 7: Fallback log activity while daemon has been alive. The hook
    // binary only writes to fallback.jsonl when the daemon POST fails — so
    // any entry newer than the daemon's start time proves the hook can't
    // reach its own daemon (token mismatch, wrong port, IPv6-only loopback).
    check_fallback_activity(
        &ol_dir,
        daemon_alive,
        daemon_uptime_secs,
        &mut checks,
        &mut issues,
    );

    // Check 8: Auto-update install-state drift. We warn (not fail) when
    // an npm-installed daemon has been auto-updated (actual_binary_version
    // != npm_reported_version) and the divergence is older than 30 days
    // — that's the signal the auto-update path is healthy and only
    // surfacing the cosmetic drift, but if drift sits stale it is also
    // the first sign auto-update has stopped firing.
    check_auto_update_drift(&cfg, &mut checks, &mut issues);

    Ok(DoctorReport {
        checks,
        issues,
        daemon_alive,
        daemon_uptime_secs,
        port: cfg.port,
    })
}

/// Render a [`DoctorReport`] using the configured output format.
///
/// JSON mode emits `{checks, issues, issue_count}` for parity with the
/// pre-refactor schema. Human mode prints checkmark/cross lines plus a
/// summary footer.
pub(crate) fn print_diagnostic_results(report: &DoctorReport, output: &OutputConfig) {
    if output.format == OutputFormat::Json {
        let checks_json: Vec<serde_json::Value> = report
            .checks
            .iter()
            .map(|c| {
                serde_json::json!({
                    // `pass` keeps its pre-tier meaning — "not a failure" — so
                    // existing consumers gating on it do not start failing on
                    // warnings. `status` carries the new detail.
                    "pass": c.is_pass(),
                    "status": match c.status {
                        CheckStatus::Pass => "pass",
                        CheckStatus::Warn => "warn",
                        CheckStatus::Fail => "fail",
                    },
                    "message": c.message,
                })
            })
            .collect();
        output.print_json(&serde_json::json!({
            "checks": checks_json,
            "issues": report.issues,
            "issue_count": report.issues.len(),
        }));
    } else if !output.quiet {
        for check in &report.checks {
            let mark = match check.status {
                CheckStatus::Pass => crate::cli::color::checkmark(output.color),
                CheckStatus::Warn => crate::cli::color::warning_mark(output.color),
                CheckStatus::Fail => crate::cli::color::cross(output.color),
            };
            eprintln!("{mark} {}", check.message);
        }

        eprintln!();
        if report.issues.is_empty() {
            eprintln!("All checks passed.");
            return;
        }

        // Print the explanations, rather than building them and throwing them
        // away. Every issue string is written to be the actionable half of its
        // check — the check says what is wrong, the issue says what to do — and
        // for the entire life of this command only the first half reached the
        // user, under a blanket "run 'openlatch init'" that was frequently the
        // wrong advice.
        let n = report.issues.len();
        eprintln!("{n} issue{} found:", if n == 1 { "" } else { "s" });
        for issue in &report.issues {
            eprintln!();
            eprintln!("  {issue}");
        }

        if let Some(next) = suggested_next_step(report) {
            eprintln!();
            eprintln!("Next: {next}");
        }
    }
}

/// The one command most likely to move the user forward, derived from the issues
/// actually present.
///
/// Replaces a hardcoded "Run 'openlatch init' to fix hook installation", which
/// was printed for every issue including the many that `init` does not touch. A
/// suggestion that is wrong most of the time is worse than none, so this returns
/// `None` when the issues do not point anywhere in particular — the per-issue
/// lines above already carry their own instructions.
fn suggested_next_step(report: &DoctorReport) -> Option<&'static str> {
    let mentions = |needle: &str| report.issues.iter().any(|i| i.contains(needle));

    if mentions("openlatch init") {
        Some("run 'openlatch init' to repair the hook installation")
    } else if mentions("openlatch start") || mentions("openlatch stop") {
        Some("run 'openlatch start' to bring the daemon back up")
    } else if mentions("openlatch supervision install") {
        Some("run 'openlatch supervision install' to make the daemon survive a reboot")
    } else if report.fail_count() > 0 {
        Some("run 'openlatch doctor --fix' to attempt an automatic repair")
    } else {
        None
    }
}

/// Probe the cloud by loading the stored API key and calling
/// `GET /api/v1/users/me` via the same validator used by `openlatch auth status`.
/// Returns (pass, human-readable message).
async fn check_cloud(api_url: &str) -> (bool, String) {
    use secrecy::ExposeSecret;

    let store = crate::core::auth::KeyringCredentialStore::new();
    let file_store = crate::cli::commands::auth::make_file_store();

    let key = match crate::core::auth::retrieve_credential(
        &store as &dyn crate::core::auth::CredentialStore,
        &file_store as &dyn crate::core::auth::CredentialStore,
    ) {
        Ok(k) => k,
        Err(_) => return (false, "Cloud: not authenticated".to_string()),
    };

    let key_str = key.expose_secret().to_string();
    let result = crate::cli::commands::auth::validate_online_full(&key_str, api_url).await;

    if result.online {
        let org = if result.org_name.is_empty() {
            String::new()
        } else {
            format!(" — org {}", result.org_name)
        };
        (true, format!("Cloud: reachable ({api_url}){org}"))
    } else {
        (
            false,
            format!("Cloud: unreachable or credential rejected ({api_url})"),
        )
    }
}

/// Verify the hook command in settings.json still points at a usable binary,
/// that the bearer token the hook subprocess will receive matches the one the
/// daemon has loaded, and that the hook will resolve the port this daemon is
/// actually listening on.
fn check_hook_binding(
    settings_path: &std::path::Path,
    daemon_token: Option<&str>,
    daemon_port: u16,
    daemon_reachable: bool,
    checks: &mut Vec<DoctorCheck>,
    issues: &mut Vec<String>,
) {
    let raw = match std::fs::read_to_string(settings_path) {
        Ok(s) => s,
        // Read-error is already reported by Check 5; don't double-count.
        Err(_) => return,
    };
    let parsed = match crate::hooks::jsonc::parse_settings_value(&raw) {
        Ok(v) => v,
        Err(e) => {
            checks.push(DoctorCheck::fail(format!(
                "Hook config: cannot parse settings.json ({})",
                e.code
            )));
            return;
        }
    };

    let health = crate::hooks::health::inspect(&parsed);
    if health.commands == 0 {
        // No _openlatch entries — Check 5 already flagged this path.
        return;
    }
    let expected_bin = &health.expected_bin;

    if health.missing_bin.is_empty() && health.drifted_bin.is_empty() {
        checks.push(DoctorCheck::pass(format!(
            "Hook binary: {} (referenced by settings.json)",
            expected_bin.display()
        )));
    }
    // The remediation is `doctor --fix`, not `init`.
    //
    // `init` regenerates the daemon token unconditionally. Agent sessions
    // already running hold the previous `OPENLATCH_TOKEN` in their process env,
    // so after the rotation their hooks authenticate with a stale token and get
    // rejected — silently, because the hook fails open and spools to
    // fallback.jsonl. Sending an operator to `init` to repair a dangling hook
    // command therefore costs them capture on every session currently running.
    // `doctor --fix` reinstalls with the token already on disk.
    if !health.missing_bin.is_empty() {
        checks.push(DoctorCheck::fail(format!(
            "Hook binary missing: {}",
            health.missing_bin.join(", ")
        )));
        issues.push(
            "Hook command points at a binary that does not exist. Run 'openlatch doctor --fix' to stage the binary and rewrite the hook command (it keeps the current token, so running agent sessions keep capturing)."
                .to_string(),
        );
    }
    if !health.drifted_bin.is_empty() {
        checks.push(DoctorCheck::fail(format!(
            "Hook binary drift: settings.json uses {}, current install is {}",
            health.drifted_bin.join(", "),
            expected_bin.display()
        )));
        issues.push(
            "Hook command points at a stale binary. Run 'openlatch doctor --fix' to re-link settings.json to the current install."
                .to_string(),
        );
    }

    // Token cross-check — settings.json env.OPENLATCH_TOKEN vs daemon.token.
    if let Some(token) = daemon_token {
        let settings_token = parsed
            .get("env")
            .and_then(|e| e.get("OPENLATCH_TOKEN"))
            .and_then(|v| v.as_str());
        match settings_token {
            Some(t) if t == token => {
                checks.push(DoctorCheck::pass(
                    "Hook token: settings.json env matches daemon.token".to_string(),
                ));
            }
            Some(_) => {
                checks.push(DoctorCheck::fail(
                    "Hook token: settings.json OPENLATCH_TOKEN does not match daemon.token"
                        .to_string(),
                ));
                issues.push(
                    "Hook subprocess will be rejected with 401. Run 'openlatch init' to re-sync the token."
                        .to_string(),
                );
            }
            None => {
                checks.push(DoctorCheck::fail(
                    "Hook token: OPENLATCH_TOKEN not set in settings.json env".to_string(),
                ));
                issues.push(
                    "Hook subprocess will not receive OPENLATCH_TOKEN. Run 'openlatch init' to install it."
                        .to_string(),
                );
            }
        }
    }

    // Port cross-check — settings.json env.OPENLATCH_PORT vs the port the
    // daemon is actually listening on.
    //
    // The hook resolves its port as: OPENLATCH_PORT (its own env, populated by
    // the agent from settings.json) -> <openlatch_dir>/daemon.port -> 7443.
    // `openlatch init` writes OPENLATCH_TOKEN but NOT OPENLATCH_PORT, and
    // OPENLATCH_DIR is not in the hook entry's allowedEnvVars, so a daemon on
    // a non-default OPENLATCH_DIR is invisible to the hook: it reads the
    // DEFAULT dir's daemon.port and silently talks to the wrong daemon (or
    // none). Because the hook fails open — prints `{}`, exits 0, spools to
    // fallback.jsonl — nothing surfaces the breakage. Without this check
    // doctor reported "All checks passed" while no event ever reached the
    // daemon.
    let settings_port = parsed
        .get("env")
        .and_then(|e| e.get("OPENLATCH_PORT"))
        // Accept both "7543" and 7543 — hand-edited settings use either.
        .and_then(|v| {
            v.as_str()
                .and_then(|s| s.trim().parse::<u16>().ok())
                .or_else(|| v.as_u64().and_then(|n| u16::try_from(n).ok()))
        });

    let dir_is_default = std::env::var("OPENLATCH_DIR")
        .ok()
        .filter(|d| !d.is_empty())
        .is_none();

    match settings_port {
        // `0` is never a port a hook can reach. It got into settings.json
        // because `OPENLATCH_PORT` parsed as any u16, the daemon then bound an
        // ephemeral port, and `install_hooks` pinned the configured `0` into
        // all 12 entries. Both sides then held `0` and this check reported
        // `OK  Hook port: settings.json env matches daemon port (0)` directly
        // under `ERR Daemon: not running (port 0)` — a green line on a config
        // where no event can ever reach a daemon, which is precisely the
        // silent breakage the check exists to catch. Equality is not health.
        Some(p) if p < config::MIN_USER_PORT || daemon_port < config::MIN_USER_PORT => {
            checks.push(DoctorCheck::fail(format!(
                "Hook port: {p} in settings.json / {daemon_port} configured — not a usable port"
            )));
            issues.push(format!(
                "OPENLATCH_PORT must be between {} and {}. Re-run 'openlatch init' with a valid OPENLATCH_PORT (or unset it to probe automatically).",
                config::MIN_USER_PORT,
                u16::MAX
            ));
        }
        // A match against a port nobody is serving proves nothing. Say what we
        // actually verified rather than borrowing the confidence of a real
        // round trip.
        Some(p) if p == daemon_port && !daemon_reachable => {
            checks.push(DoctorCheck::warn(format!(
                "Hook port: settings.json env matches the configured port ({daemon_port}), but no daemon answered"
            )));
        }
        Some(p) if p == daemon_port => {
            checks.push(DoctorCheck::pass(format!(
                "Hook port: settings.json env matches daemon port ({daemon_port})"
            )));
        }
        Some(p) => {
            checks.push(DoctorCheck::fail(format!(
                "Hook port: settings.json OPENLATCH_PORT is {p}, daemon is on {daemon_port}"
            )));
            issues.push(format!(
                "Hook subprocess will connect to port {p} and fail open silently. Set OPENLATCH_PORT to {daemon_port} in the agent's settings env."
            ));
        }
        // Unset is fine on a default install: the hook falls back to
        // <default dir>/daemon.port, which IS this daemon's port file.
        None if dir_is_default => {
            checks.push(DoctorCheck::pass(format!(
                "Hook port: resolved from daemon.port ({daemon_port})"
            )));
        }
        None => {
            checks.push(DoctorCheck::fail(
                "Hook port: OPENLATCH_PORT not set in settings.json env, but OPENLATCH_DIR is non-default"
                    .to_string(),
            ));
            issues.push(format!(
                "The hook cannot see OPENLATCH_DIR, so it reads the default directory's daemon.port instead of this instance's and fails open silently. Set OPENLATCH_PORT to {daemon_port} in the agent's settings env."
            ));
        }
    }
}

/// Probe the OS-native supervisor and compare its actual state against
/// `config.supervision`. The comparison catches drift in both directions:
/// the user manually deleted the plist/task/unit, OR the config was never
/// updated but the supervisor is still alive.
fn check_supervision_state(
    cfg: &config::Config,
    checks: &mut Vec<DoctorCheck>,
    issues: &mut Vec<String>,
) {
    use crate::supervision::{select_supervisor, SupervisionMode, SupervisorKind};
    let configured_backend = match cfg.supervision.backend {
        SupervisorKind::Launchd => "launchd",
        SupervisorKind::Systemd => "systemd",
        SupervisorKind::TaskScheduler => "task_scheduler",
        SupervisorKind::None => "none",
    };

    match (&cfg.supervision.mode, select_supervisor()) {
        (SupervisionMode::Active, Some(sup)) => match sup.status() {
            // Registered, running, but generated by an older release — the
            // restart semantics on disk are that release's, not this one's.
            // Reported, never silently rewritten: an OS-registered unit is not
            // something `doctor` should replace without being asked.
            Ok(s) if s.installed && s.running && !s.unit_current => {
                checks.push(DoctorCheck::fail(format!(
                    "Supervision: running an outdated unit ({configured_backend}, {})",
                    s.description
                )));
                issues.push(
                    "The installed supervisor unit predates this client's restart semantics \
                     (it may still use the old never-fires restart policy). Run 'openlatch \
                     supervision install' to regenerate it."
                        .to_string(),
                );
            }
            Ok(s) if s.installed && s.running => {
                checks.push(DoctorCheck::pass(format!(
                    "Supervision: active ({configured_backend}, {})",
                    s.description
                )));
            }
            Ok(s) if s.installed => {
                checks.push(DoctorCheck::fail(format!(
                    "Supervision: installed but supervisor not running ({configured_backend})"
                )));
                issues.push(
                    "Supervisor is registered but not running. Check OS logs or run \
                     'openlatch supervision install' to rebuild the artifact."
                        .to_string(),
                );
            }
            Ok(_) => {
                checks.push(DoctorCheck::fail(format!(
                    "Supervision: config says active but OS artifact is missing ({configured_backend})"
                )));
                issues.push(
                    "Supervisor drifted — OS artifact deleted while config still expects it. \
                     Run 'openlatch supervision install' (or 'openlatch doctor --fix')."
                        .to_string(),
                );
            }
            Err(e) => {
                checks.push(DoctorCheck::fail(format!(
                    "Supervision: cannot query supervisor ({}) — {}",
                    e.code, e.message
                )));
            }
        },
        // Deferred is never a choice — an install tried to register a
        // supervisor and could not. Warn: the user did not ask for this, and it
        // is also not something broken that a repair pass can heal blind.
        (SupervisionMode::Deferred, _) => {
            let reason = cfg
                .supervision
                .disabled_reason
                .as_deref()
                .unwrap_or("unknown");
            checks.push(DoctorCheck::warn(format!(
                "Supervision: deferred — {reason}"
            )));
            issues.push(format!(
                "Supervision was deferred ({reason}), so nothing will restart the daemon after \
                 a crash or a reboot — you did not choose this. Run 'openlatch supervision \
                 install' once the underlying condition is resolved (headless session, missing \
                 systemd, and so on). ({})",
                crate::error::ERR_NO_SUPERVISOR
            ));
        }
        (SupervisionMode::Disabled, _) => {
            let reason = cfg
                .supervision
                .disabled_reason
                .as_deref()
                .unwrap_or("user_opt_out");
            if crate::supervision::absence_is_deliberate(Some(reason)) {
                // You asked for no supervisor. Reporting that back as a problem
                // is how a diagnostic teaches people to stop reading it.
                checks.push(DoctorCheck::pass(format!(
                    "Supervision: disabled ({reason}) — as requested"
                )));
            } else {
                checks.push(DoctorCheck::warn(format!(
                    "Supervision: disabled ({reason})"
                )));
                issues.push(format!(
                    "Supervision is off for a reason you did not choose ({reason}), so nothing \
                     will restart the daemon after a crash or a reboot. Run 'openlatch \
                     supervision install' if this machine can support one. ({})",
                    crate::error::ERR_NO_SUPERVISOR
                ));
            }
        }
        (SupervisionMode::Active, None) => {
            checks.push(DoctorCheck::fail(
                "Supervision: config says active but no supervisor is available on this OS"
                    .to_string(),
            ));
            issues.push(
                "Supervisor unsupported on this OS. Run 'openlatch supervision disable' to \
                 clear the stale state."
                    .to_string(),
            );
        }
    }
}

/// The model-boundary invariant, made observable: `ANTHROPIC_BASE_URL` is in the
/// agent's settings.json IF AND ONLY IF a listener holds the pinned port.
///
/// Both halves are worth reporting and they fail very differently:
///
/// - **Wired, nothing listening** — every Claude Code session on this machine
///   dies on ECONNREFUSED. This is the bug the ownership move exists to prevent;
///   seeing it now means a daemon was SIGKILLed and neither `openlatch stop` nor
///   a subsequent start has reconciled it. A failure.
/// - **Wired, someone ELSE listening** — the agent is sending its provider
///   credential to a process that is not us. A failure, and the more urgent one.
/// - **Listening, not wired** — agents talk straight to the provider. Nothing
///   breaks; nothing is captured either. A warning.
#[cfg(feature = "boundary")]
fn check_boundary_wiring(
    cfg: &config::Config,
    settings_path: &std::path::Path,
    checks: &mut Vec<DoctorCheck>,
    issues: &mut Vec<String>,
) {
    use crate::cli::commands::boundary::{
        classify_boundary, read_boundary_base_url, BoundaryState,
    };

    let port = cfg.boundary.port;
    let wired = read_boundary_base_url(settings_path);
    let url = wired.as_deref().unwrap_or_default();

    match classify_boundary(cfg, wired.as_deref()) {
        // Switched off on purpose. Agents connect to the provider directly and
        // the port belongs to whoever wants it — reporting on ownership here is
        // how `status` came to raise a security alarm on a safe config.
        BoundaryState::Disabled => {
            checks.push(DoctorCheck::pass(
                "Model boundary: disabled in config — agents connect to the provider directly"
                    .to_string(),
            ));
        }
        // An isolated instance (non-default port) deliberately does not write
        // the machine-global agent config, so "wired" and "listening" are not
        // supposed to line up here — checking the invariant would report a
        // designed state as a defect.
        BoundaryState::Isolated => {
            checks.push(DoctorCheck::pass(format!(
                "Model boundary: isolated instance on port {port}{} is not managed by it",
                settings_path.display()
            )));
        }
        BoundaryState::Wired => {
            checks.push(DoctorCheck::pass(format!(
                "Model boundary: agent wired to {url} and the listener is up"
            )));
        }
        BoundaryState::WiredButDown => {
            checks.push(DoctorCheck::fail(format!(
                "Model boundary: agent is wired to {url} but nothing is listening there"
            )));
            issues.push(format!(
                "Every agent on this machine is pointed at 127.0.0.1:{port} and no listener \
                 holds it — model calls will fail with ECONNREFUSED. Run 'openlatch start' to \
                 bring the boundary back up, or 'openlatch stop' to clear the wiring and go \
                 direct."
            ));
        }
        BoundaryState::WiredToForeign => {
            checks.push(DoctorCheck::fail(format!(
                "Model boundary: agent is wired to {url}, held by a process that is NOT OpenLatch"
            )));
            issues.push(format!(
                "127.0.0.1:{port} is occupied by something else while the agent config points \
                 at it — your provider API key is being sent to that process. Identify it \
                 (lsof -i :{port}), stop it, then run 'openlatch restart'. ({})",
                crate::error::ERR_BOUNDARY_PORT_FOREIGN
            ));
        }
        BoundaryState::PreflightFailed(why) => {
            checks.push(DoctorCheck::warn(format!(
                "Model boundary: listener is up but its preflight failed — {why}"
            )));
            issues.push(format!(
                "The boundary on 127.0.0.1:{port} cannot reach the provider, so the agent \
                 was deliberately left unwired: model calls go direct and keep working, \
                 but nothing is captured. Fix reachability to https://api.anthropic.com \
                 (proxy, VPN, TLS interception), then run 'openlatch restart' — the daemon \
                 re-wires itself as soon as the check passes. ({})",
                crate::error::ERR_BOUNDARY_PREFLIGHT_FAILED
            ));
        }
        BoundaryState::PreflightPending => {
            checks.push(DoctorCheck::warn(
                "Model boundary: listener is up, its preflight has not finished yet".to_string(),
            ));
            issues.push(format!(
                "The boundary on 127.0.0.1:{port} is still verifying it can reach the \
                 provider; the agent is wired only once it can. Re-run 'openlatch doctor' \
                 in a moment."
            ));
        }
        BoundaryState::UpUnwired => {
            checks.push(DoctorCheck::warn(
                "Model boundary: listener is up but the agent is not wired to it".to_string(),
            ));
            issues.push(format!(
                "The boundary is listening on 127.0.0.1:{port} but the agent has no \
                 ANTHROPIC_BASE_URL pointing at it, so model calls bypass it entirely and \
                 nothing is captured. Run 'openlatch restart' to re-wire."
            ));
        }
        BoundaryState::Down => {
            checks.push(DoctorCheck::pass(
                "Model boundary: not wired, nothing listening — consistent".to_string(),
            ));
        }
        // Not our port and not our wiring: someone else's process on 7600 is
        // their business, and the agent is not pointed at it. Worth saying out
        // loud, because it is also the reason the next `openlatch start` will
        // refuse to come up.
        BoundaryState::ForeignIdle => {
            checks.push(DoctorCheck::pass(format!(
                "Model boundary: not wired; 127.0.0.1:{port} is held by another process"
            )));
        }
    }
}

/// Flag fallback.jsonl as a problem when any of its bytes were written after
/// the currently-running daemon started. That's the on-disk trace of a hook
/// subprocess failing to reach its own daemon.
fn check_fallback_activity(
    ol_dir: &std::path::Path,
    daemon_alive: bool,
    daemon_uptime_secs: Option<u64>,
    checks: &mut Vec<DoctorCheck>,
    issues: &mut Vec<String>,
) {
    if !daemon_alive {
        // Without a live daemon there's no "since daemon start" reference
        // point, and any fallback activity is expected (daemon is down).
        return;
    }
    let Some(uptime) = daemon_uptime_secs else {
        return;
    };
    let fallback_path = ol_dir.join("logs").join("fallback.jsonl");
    if !fallback_path.exists() {
        checks.push(DoctorCheck::pass(
            "Hook fallback log: no offline events recorded".to_string(),
        ));
        return;
    }

    let meta = match std::fs::metadata(&fallback_path) {
        Ok(m) => m,
        Err(e) => {
            checks.push(DoctorCheck::fail(format!(
                "Hook fallback log: cannot stat {}{e}",
                fallback_path.display()
            )));
            return;
        }
    };
    let mtime = match meta.modified() {
        Ok(t) => t,
        Err(_) => return,
    };
    let daemon_start = std::time::SystemTime::now()
        .checked_sub(std::time::Duration::from_secs(uptime))
        .unwrap_or(std::time::UNIX_EPOCH);

    if mtime > daemon_start {
        let age_secs = mtime
            .duration_since(daemon_start)
            .map(|d| d.as_secs())
            .unwrap_or(0);
        checks.push(DoctorCheck::fail(format!(
            "Hook fallback log: {} written {age_secs}s after daemon start — hook subprocess is not reaching the daemon",
            fallback_path.display()
        )));
        issues.push(
            "Hook binary is writing to fallback.jsonl while the daemon is up. \
             Likely causes: token mismatch, wrong port, or stale settings.json. \
             Run 'openlatch doctor' above for Hook token/binary checks, then 'openlatch init' to repair."
                .to_string(),
        );
    } else {
        checks.push(DoctorCheck::pass(format!(
            "Hook fallback log: quiet since daemon start ({})",
            fallback_path.display()
        )));
    }
}

/// Auto-update install-state drift check (P2 § 6).
///
/// Warns (not fails) when:
/// 1. install-state.json reports `install_method == npm`, AND
/// 2. `actual_binary_version != npm_reported_version`, AND
/// 3. `last_updated_at` is more than 30 days in the past, AND
/// 4. `auto_update == true` in config.
///
/// The 30-day threshold is the canary: if auto-update is supposedly on
/// but no apply has happened in a month, the worker is likely silently
/// broken — and the user is exposed.
fn check_auto_update_drift(
    cfg: &config::Config,
    checks: &mut Vec<DoctorCheck>,
    issues: &mut Vec<String>,
) {
    use crate::install_state::{InstallMethod, InstallState};
    let state = InstallState::load_or_default();
    let (Some(actual), Some(npm)) = (
        state.actual_binary_version.as_deref(),
        state.npm_reported_version.as_deref(),
    ) else {
        // Nothing to compare yet — fresh install, or no auto-update has
        // ever applied. Quiet pass.
        checks.push(DoctorCheck::pass(
            "Auto-update: no drift recorded".to_string(),
        ));
        return;
    };
    if !matches!(state.install_method, InstallMethod::Npm) {
        // Drift detection is only meaningful for npm-managed installs.
        return;
    }
    if actual == npm {
        checks.push(DoctorCheck::pass(format!(
            "Auto-update: in sync (npm={npm}, binary={actual})"
        )));
        return;
    }

    let last_update = state.last_updated_at.as_deref();
    let stale_drift = last_update
        .and_then(|ts| chrono::DateTime::parse_from_rfc3339(ts).ok())
        .map(|t| (chrono::Utc::now() - t.with_timezone(&chrono::Utc)).num_days() > 30)
        .unwrap_or(false);

    if stale_drift && cfg.update.auto_update {
        checks.push(DoctorCheck::fail(format!(
            "Auto-update: drift unchanged for >30d (npm={npm}, binary={actual}, last={})",
            last_update.unwrap_or("?")
        )));
        issues.push(format!(
            "Auto-update appears stalled. The binary is at {actual} but npm last installed {npm} \
             over 30 days ago. Run `npm install -g @openlatch/client@{actual}` to resync, then \
             check the daemon log for `target=update` errors."
        ));
    } else {
        // Drift exists but is fresh — that's the *expected* state right
        // after an auto-update.
        checks.push(DoctorCheck::pass(format!(
            "Auto-update: drift detected (binary {actual} > npm {npm}) — run `npm install -g @openlatch/client@{actual}` to sync"
        )));
    }
}