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
/// `openlatch status` command handler.
///
/// Displays daemon status in a compact dashboard format (D-06 when running, D-07 when stopped).
/// All path references use `config::openlatch_dir()` per PLAT-02.
///
/// SECURITY (T-05-01-01, T-02-09): Never include API key value in status output.
/// Cloud fields show state information only — credentials are never exposed.
use crate::cli::commands::lifecycle;
use crate::cli::output::{OutputConfig, OutputFormat};
use crate::config;
use crate::error::OlError;

/// Run the `openlatch status` command.
///
/// Per D-06: compact dashboard when running.
/// Per D-07: stopped format with last-seen info when daemon is not running.
///
/// # Errors
///
/// Returns an error if config cannot be loaded.
pub fn run_status(output: &OutputConfig) -> Result<(), OlError> {
    let version = env!("OPENLATCH_VERSION");
    let cfg = config::Config::load(None, None, false)?;

    // Check if daemon is running
    let pid_opt = lifecycle::read_pid_file();
    let is_running = pid_opt.map(lifecycle::is_process_alive).unwrap_or(false);

    if is_running {
        let pid = pid_opt.unwrap();
        show_running_status(version, cfg.port, pid, output, &cfg.cloud.api_url)?;
    } else {
        show_stopped_status(version, output)?;
    }

    Ok(())
}

/// Display compact dashboard when daemon is running (D-06).
fn show_running_status(
    version: &str,
    port: u16,
    pid: u32,
    output: &OutputConfig,
    cloud_api_url: &str,
) -> Result<(), OlError> {
    // Try to get metrics from daemon
    let health = fetch_health(port);
    let metrics = fetch_metrics(port);

    let uptime_str = health
        .as_ref()
        .and_then(|h| h.get("uptime_secs"))
        .and_then(|v| v.as_u64())
        .map(format_uptime)
        .unwrap_or_else(|| "unknown".to_string());

    let agent_str = health
        .as_ref()
        .and_then(|h| h.get("agent"))
        .and_then(|v| v.as_str())
        .unwrap_or("Claude Code")
        .to_string();

    // What the daemon actually runs, which a package upgrade can leave behind
    // the binary this command was launched from.
    let stale_daemon = stale_daemon_line(
        version,
        health
            .as_ref()
            .and_then(|h| h.get("version"))
            .and_then(|v| v.as_str()),
    );

    let update_available = metrics
        .as_ref()
        .and_then(|m| m.get("update_available"))
        .and_then(|v| v.as_str())
        .map(|s| s.to_string());

    let total_events = metrics
        .as_ref()
        .and_then(|m| m.get("events_processed"))
        .and_then(|v| v.as_u64())
        .unwrap_or(0);

    // PLAT-02: Use config::openlatch_dir() for all path access
    let log_path = config::openlatch_dir().join("logs").join(format!(
        "events-{}.jsonl",
        chrono::Local::now().format("%Y-%m-%d")
    ));

    // Cloud metrics from daemon /metrics endpoint
    let cloud_status_daemon = metrics
        .as_ref()
        .and_then(|m| m.get("cloud_status"))
        .and_then(|v| v.as_str())
        .unwrap_or("not_configured")
        .to_string();

    let cloud_forwarded_count = metrics
        .as_ref()
        .and_then(|m| m.get("cloud_forwarded_count"))
        .and_then(|v| v.as_u64())
        .unwrap_or(0);

    let cloud_last_sync_secs = metrics
        .as_ref()
        .and_then(|m| m.get("cloud_last_sync_secs"))
        .and_then(|v| v.as_u64())
        .unwrap_or(0);

    // D-01: Prefer the daemon's own cloud_status — it is the authoritative
    // signal for whether POSTs to /api/v1/events/ingest are succeeding. Fall
    // through to a live /api/v1/users/me probe only when the daemon has no
    // active cloud worker ("not_configured") or hasn't loaded a credential
    // yet ("no_credential") but one now exists on disk (e.g. the user ran
    // `openlatch auth login` after the daemon started).
    // SECURITY (T-05-01-02): API key is used only in Authorization header, never logged or printed.
    let live_cloud_status = match cloud_status_daemon.as_str() {
        "not_configured" | "no_credential" => {
            if check_credential_configured() == "not_configured" {
                "not_configured".to_string()
            } else {
                probe_cloud_status(cloud_api_url).to_string()
            }
        }
        _ => cloud_status_daemon.clone(),
    };

    let cloud_last_sync_relative = format_relative_secs(cloud_last_sync_secs);

    let supervision_line = supervision_summary_line();

    let install_state = crate::install_state::InstallState::load_or_default();

    // Model-boundary state (Acceptance #7). Classified LIVE, through the SAME
    // classifier `doctor` uses, so the two commands cannot contradict each
    // other about the same boundary.
    //
    // This used to read port ownership alone and never consult
    // `boundary.enabled`, which is how `status` came to print
    // `FAILED (port held by a non-OpenLatch process — agents misconfigured/exposed)`
    // on a machine where the boundary was switched off in config and no agent
    // was wired to that port at all — a security-shaped alarm on a
    // deliberately safe configuration.
    #[cfg(feature = "boundary")]
    let (boundary_port, boundary_state): (Option<u16>, &'static str) = {
        let cfg = config::Config::load(None, None, false).ok();
        let port = cfg
            .as_ref()
            .map_or_else(crate::boundary::resolve_boundary_port, |c| c.boundary.port);
        let state = match cfg {
            Some(cfg) => {
                let wired = crate::hooks::detect_agent()
                    .ok()
                    .and_then(|agent| match agent {
                        crate::hooks::DetectedAgent::ClaudeCode { settings_path, .. } => {
                            crate::cli::commands::boundary::read_boundary_base_url(&settings_path)
                        }
                    });
                crate::cli::commands::boundary::classify_boundary(&cfg, wired.as_deref()).label()
            }
            None => "down",
        };
        (Some(port), state)
    };
    #[cfg(not(feature = "boundary"))]
    let (boundary_port, boundary_state): (Option<u16>, &'static str) = (None, "down");

    // Supervised in-process subsystems. `/health` answers 200 even while
    // degraded (it is a liveness probe), so the only way a user sees a cloud
    // worker that keeps panicking or a boundary that cannot bind is if `status`
    // reads the body and says so.
    let degraded_subsystems = degraded_subsystems_from_health(health.as_ref());

    if output.format == OutputFormat::Json {
        // SECURITY (T-02-09, T-05-01-01): No API key value in output
        let json = serde_json::json!({
            "status": "running",
            "version": version,
            "port": port,
            "pid": pid,
            "uptime": uptime_str,
            "events": total_events,
            "log_path": log_path.to_string_lossy(),
            "update_available": update_available,
            "cloud_status": live_cloud_status,
            "cloud_forwarded_count": cloud_forwarded_count,
            "cloud_last_sync": cloud_last_sync_relative,
            "cloud_api_url": cloud_api_url,
            "supervision": supervision_json(),
            "install_state": install_state_json(&install_state),
            // The version the daemon is actually serving, and whether it has
            // fallen behind the installed binary. Scripted callers gate a
            // restart on this rather than diffing two version strings
            // themselves.
            "daemon_version": health
                .as_ref()
                .and_then(|h| h.get("version"))
                .and_then(|v| v.as_str()),
            "daemon_stale": stale_daemon.is_some(),
            "boundary": {
                "port": boundary_port,
                "state": boundary_state,
                "up": boundary_state == "up",
            },
            "health_status": health
                .as_ref()
                .and_then(|h| h.get("status"))
                .and_then(|v| v.as_str())
                .unwrap_or("unknown"),
            "subsystems": health
                .as_ref()
                .and_then(|h| h.get("subsystems"))
                .cloned()
                .unwrap_or(serde_json::Value::Null),
        });
        output.print_json(&json);
    } else if !output.quiet {
        crate::cli::header::print(output, &["running", &format!("uptime {uptime_str}")]);
        eprintln!("  Port:     {port}");
        eprintln!("  Agent:    {agent_str}");
        eprintln!("  Events:   {total_events}");
        eprintln!("  Log:      {}", log_path.display());
        // UPDT-03: Show update suggestion when newer version is available
        if let Some(ref latest) = update_available {
            eprintln!("  Update:   v{latest} available (run: npx openlatch@latest)");
        }
        // Auto-update drift surfacing — only shown when we have a
        // non-default install state. Most installs that haven't gone
        // through the auto-update path show nothing here.
        for line in install_state_human_lines(&install_state) {
            eprintln!("  {line}");
        }
        // An upgrade that landed on disk but not in the running process. Shown
        // next to the install-state drift lines because it is the same class of
        // problem seen from the other side.
        if let Some(ref line) = stale_daemon {
            eprintln!("  {line}");
        }
        // Cloud section (D-02, D-04)
        if live_cloud_status == "not_configured" {
            eprintln!("  Cloud:    not configured");
            eprintln!("            Run 'openlatch auth login' to enable cloud sync");
        } else {
            eprintln!("  Cloud:    {live_cloud_status} ({cloud_api_url})");
            eprintln!(
                "  Synced:   {cloud_forwarded_count} events, last {cloud_last_sync_relative}"
            );
        }
        eprintln!("  Supervision: {supervision_line}");
        if let Some(bp) = boundary_port {
            // Only the genuinely dangerous state gets the alarm wording: an
            // agent wired at a port a foreign process holds is sending its
            // provider credential there. A foreign process on a port nothing is
            // wired to is not that.
            let label = if boundary_state == "failed" {
                "FAILED (agent wired to a port held by a non-OpenLatch process — credential exposed)"
            } else {
                boundary_state
            };
            eprintln!("  Boundary:    {label} (port {bp})");
        }
        // One line per degraded subsystem — nothing at all when everything is
        // running, which is the overwhelmingly common case.
        for line in &degraded_subsystems {
            eprintln!("  Subsystem:   {line}");
        }
    }

    Ok(())
}

/// Render `/health`'s `subsystems` map into one human line per **degraded**
/// subsystem. Pure — no I/O — so it is unit-testable without a daemon.
///
/// Keyed off the daemon's own `"degraded": true` flag rather than re-deriving
/// it from the state string: a one-shot task legitimately sits in `stopped`
/// forever and must not be reported as a problem. A body from an older daemon
/// with no `subsystems` key simply yields nothing.
fn degraded_subsystems_from_health(health: Option<&serde_json::Value>) -> Vec<String> {
    let Some(subsystems) = health
        .and_then(|h| h.get("subsystems"))
        .and_then(|v| v.as_object())
    else {
        return Vec::new();
    };

    let mut lines: Vec<String> = subsystems
        .iter()
        .filter(|(_, entry)| {
            entry
                .get("degraded")
                .and_then(|v| v.as_bool())
                .unwrap_or(false)
        })
        .map(|(name, entry)| {
            let state = entry
                .get("state")
                .and_then(|v| v.as_str())
                .unwrap_or("unknown");
            let restarts = entry.get("restarts").and_then(|v| v.as_u64()).unwrap_or(0);
            let mut line = format!("{name}: {state} ({restarts} restarts)");
            if let Some(err) = entry.get("last_error").and_then(|v| v.as_str()) {
                line.push_str(&format!("{err}"));
            }
            line
        })
        .collect();
    // serde_json preserves insertion order, but sort anyway so the output does
    // not depend on the daemon's registration sequence.
    lines.sort();
    lines
}

/// Display stopped status with last-seen info (D-07).
fn show_stopped_status(version: &str, output: &OutputConfig) -> Result<(), OlError> {
    // Try to read last shutdown from daemon.log
    let (last_seen, last_events) = read_last_session_info();

    // D-03: When daemon is stopped, check credential presence only — no live probe.
    // SECURITY (T-05-01-01): Never expose the key value, only its presence.
    let cloud_status = check_credential_configured();

    let supervision_line = supervision_summary_line();

    if output.format == OutputFormat::Json {
        let json = serde_json::json!({
            "status": "stopped",
            "version": version,
            "last_seen": last_seen,
            "last_session_events": last_events,
            "cloud_status": cloud_status,
            "supervision": supervision_json(),
        });
        output.print_json(&json);
    } else if !output.quiet {
        crate::cli::header::print(output, &["stopped"]);
        if let Some(ref ts) = last_seen {
            let relative = format_relative_time(ts);
            eprintln!("  Last seen:  {ts} ({relative} ago)");
        } else {
            eprintln!("  Last seen:  never");
        }
        eprintln!("  Events:     {last_events} in last session");
        eprintln!("  Suggestion: Run 'openlatch start' to resume");
        // Cloud section (D-03, D-04)
        if cloud_status == "not_configured" {
            eprintln!("  Cloud:    not configured");
            eprintln!("            Run 'openlatch auth login' to enable cloud sync");
        } else {
            eprintln!("  Cloud:    configured (not running)");
        }
        eprintln!("  Supervision: {supervision_line}");
    }

    Ok(())
}

/// Build a human-readable supervision summary line.
///
/// Probes the OS supervisor when the config says `active`. It used to render
/// `cfg.supervision.mode` alone and nothing else, which meant `(active)`
/// asserted "someone once ran `supervision install`" while reading as "the
/// supervisor is up". Every broken state — crash-looping, masked, stopped,
/// running a stale unit — displayed as healthy, and that is how a unit
/// restarting 130 times in five minutes went unnoticed while `status` said
/// `systemd (active)` throughout.
///
/// Costs one `systemctl is-active` fork, and only in the `active` branch.
/// `status` already forks for the cloud probe and the boundary port-ownership
/// check, so this is not a new class of cost. `deferred` / `disabled` never
/// probe: no artifact is supposed to be installed, and `doctor` owns the
/// converse drift ("config says disabled, a unit is still running").
fn supervision_summary_line() -> String {
    let Ok(cfg) = config::Config::load(None, None, false) else {
        return "unknown".to_string();
    };
    let observed = probe_supervisor_if_active(&cfg.supervision);
    render_supervision_line(&cfg.supervision, observed.as_ref())
}

/// Probe the OS supervisor, but only when the config claims it is active.
///
/// `Some(Err(()))` is the "config says active, this OS has no supervisor at
/// all" case — distinct from `Some(Ok(status))` (we asked and got an answer)
/// and from `None` (we had no reason to ask).
type ObservedSupervisor = Result<crate::supervision::SupervisorStatus, ()>;

fn probe_supervisor_if_active(
    cfg: &crate::supervision::SupervisionConfig,
) -> Option<ObservedSupervisor> {
    use crate::supervision::{select_supervisor, SupervisionMode};
    if cfg.mode != SupervisionMode::Active {
        return None;
    }
    Some(match select_supervisor() {
        Some(sup) => sup.status().map_err(|_| ()),
        None => Err(()),
    })
}

/// Render the supervision line from the configured intent and the observed
/// reality, as two separate facts.
///
/// Pure, so every branch is testable without a supervisor on the machine —
/// which is the point: the branches that matter are the ones that only occur
/// on a broken host.
fn render_supervision_line(
    cfg: &crate::supervision::SupervisionConfig,
    observed: Option<&ObservedSupervisor>,
) -> String {
    use crate::supervision::{SupervisionMode, SupervisorKind};
    let backend = match cfg.backend {
        SupervisorKind::Launchd => "launchd",
        SupervisorKind::Systemd => "systemd",
        SupervisorKind::TaskScheduler => "task_scheduler",
        SupervisorKind::None => "none",
    };
    match cfg.mode {
        SupervisionMode::Active => match observed {
            // Configured and confirmed. The common case, and the only one that
            // still reads exactly as it did before.
            Some(Ok(s)) if s.installed && s.running && s.unit_current => {
                format!("{backend} (active)")
            }
            Some(Ok(s)) if s.installed && s.running => {
                format!("{backend} (active, outdated unit — run 'openlatch supervision install')")
            }
            // Registered but not up: crash-looping, masked, or stopped. The
            // description carries the supervisor's own word for it
            // (`activating`, `failed`, `inactive`).
            Some(Ok(s)) if s.installed => {
                format!(
                    "{backend} (configured active, NOT running — {})",
                    s.description
                )
            }
            Some(Ok(_)) => format!(
                "{backend} (configured active, unit missing — run 'openlatch supervision install')"
            ),
            Some(Err(())) => {
                format!("{backend} (configured active, no supervisor available on this OS)")
            }
            None => format!("{backend} (active)"),
        },
        SupervisionMode::Deferred => {
            let reason = cfg.disabled_reason.clone().unwrap_or_default();
            if reason.is_empty() {
                format!("{backend} (deferred)")
            } else {
                format!("{backend} (deferred — {reason})")
            }
        }
        SupervisionMode::Disabled => {
            let reason = cfg
                .disabled_reason
                .clone()
                .unwrap_or_else(|| "user_opt_out".to_string());
            format!("disabled ({reason})")
        }
    }
}

/// JSON representation of the supervision state for `status --json`.
///
/// `mode` / `backend` / `disabled_reason` are the configured intent and keep
/// their meaning. `installed` / `running` / `unit_current` / `description` are
/// the observed reality, present only when there was a supervisor to ask —
/// same keys `openlatch supervision status --json` already emits, so the two
/// commands describe supervision with one vocabulary. Purely additive: no
/// existing key changed shape.
fn supervision_json() -> serde_json::Value {
    use crate::supervision::{SupervisionMode, SupervisorKind};
    let cfg = match config::Config::load(None, None, false) {
        Ok(c) => c,
        Err(_) => return serde_json::json!(null),
    };
    let backend = match cfg.supervision.backend {
        SupervisorKind::Launchd => "launchd",
        SupervisorKind::Systemd => "systemd",
        SupervisorKind::TaskScheduler => "task_scheduler",
        SupervisorKind::None => "none",
    };
    let mode = match cfg.supervision.mode {
        SupervisionMode::Active => "active",
        SupervisionMode::Deferred => "deferred",
        SupervisionMode::Disabled => "disabled",
    };
    let mut out = serde_json::json!({
        "mode": mode,
        "backend": backend,
        "disabled_reason": cfg.supervision.disabled_reason,
    });
    if let Some(Ok(s)) = probe_supervisor_if_active(&cfg.supervision) {
        out["installed"] = serde_json::json!(s.installed);
        out["running"] = serde_json::json!(s.running);
        out["unit_current"] = serde_json::json!(s.unit_current);
        out["description"] = serde_json::json!(s.description);
    }
    out
}

#[cfg(test)]
mod stale_daemon_tests {
    use super::stale_daemon_line;

    #[test]
    fn matching_versions_say_nothing() {
        assert_eq!(stale_daemon_line("0.1.16", Some("0.1.16")), None);
    }

    /// The npm-upgrade shape: the package manager replaced the binary, the
    /// daemon kept the inode it started from. Everything else on the machine
    /// reports success, so this line is the only signal the user gets.
    #[test]
    fn a_daemon_left_behind_by_an_upgrade_is_reported_with_its_remedy() {
        let line = stale_daemon_line("0.1.16", Some("0.1.15")).expect("must report");
        assert!(line.contains("0.1.15"), "must name what is running: {line}");
        assert!(
            line.contains("0.1.16"),
            "must name what is installed: {line}"
        );
        assert!(
            line.contains("openlatch restart"),
            "a warning without the remedy is not actionable: {line}"
        );
    }

    /// An unreachable or older daemon that reports no version at all must not
    /// be accused of being stale — absence of evidence is not a mismatch.
    #[test]
    fn a_daemon_that_reports_no_version_is_not_called_stale() {
        assert_eq!(stale_daemon_line("0.1.16", None), None);
    }
}

#[cfg(test)]
mod supervision_line_tests {
    use super::*;
    use crate::supervision::{
        SupervisionConfig, SupervisionMode, SupervisorKind, SupervisorStatus,
    };

    fn active() -> SupervisionConfig {
        SupervisionConfig {
            mode: SupervisionMode::Active,
            backend: SupervisorKind::Systemd,
            disabled_reason: None,
        }
    }

    fn observed(
        installed: bool,
        running: bool,
        unit_current: bool,
        desc: &str,
    ) -> ObservedSupervisor {
        Ok(SupervisorStatus {
            installed,
            running,
            unit_current,
            description: desc.into(),
        })
    }

    /// Configured, registered, up, current — the only state that may read as a
    /// bare "(active)".
    #[test]
    fn healthy_renders_unchanged() {
        let o = observed(true, true, true, "systemd-user (Restart=always active)");
        assert_eq!(
            render_supervision_line(&active(), Some(&o)),
            "systemd (active)"
        );
    }

    /// The regression this whole change exists for: a unit restart-looping
    /// reported `systemd (active)` while `doctor` correctly reported an error.
    /// It must now say so, and carry systemd's own word for the state.
    #[test]
    fn restart_looping_is_not_reported_as_active() {
        let o = observed(
            true,
            false,
            true,
            "systemd-user (unit present, state: activating)",
        );
        let line = render_supervision_line(&active(), Some(&o));
        assert!(line.contains("NOT running"), "{line}");
        assert!(line.contains("activating"), "{line}");
        assert_ne!(line, "systemd (active)");
    }

    #[test]
    fn stale_unit_is_flagged_with_the_remedy() {
        let o = observed(true, true, false, "systemd-user (running an outdated unit)");
        let line = render_supervision_line(&active(), Some(&o));
        assert!(line.contains("outdated unit"), "{line}");
        assert!(line.contains("supervision install"), "{line}");
    }

    #[test]
    fn missing_unit_is_flagged_with_the_remedy() {
        let o = observed(false, false, false, "not installed");
        let line = render_supervision_line(&active(), Some(&o));
        assert!(line.contains("unit missing"), "{line}");
        assert!(line.contains("supervision install"), "{line}");
    }

    #[test]
    fn active_without_a_supervisor_on_this_os_says_so() {
        let line = render_supervision_line(&active(), Some(&Err(())));
        assert!(line.contains("no supervisor available"), "{line}");
    }

    /// `deferred` / `disabled` describe an intent with no artifact to observe,
    /// so they never probe and their rendering is untouched.
    #[test]
    fn non_active_modes_are_unchanged_and_never_probe() {
        let deferred = SupervisionConfig {
            mode: SupervisionMode::Deferred,
            backend: SupervisorKind::Systemd,
            disabled_reason: Some("headless_install_no_gui".into()),
        };
        assert_eq!(
            render_supervision_line(&deferred, None),
            "systemd (deferred — headless_install_no_gui)"
        );
        assert!(probe_supervisor_if_active(&deferred).is_none());

        let disabled = SupervisionConfig {
            mode: SupervisionMode::Disabled,
            backend: SupervisorKind::None,
            disabled_reason: Some("user_opt_out".into()),
        };
        assert_eq!(
            render_supervision_line(&disabled, None),
            "disabled (user_opt_out)"
        );
        assert!(probe_supervisor_if_active(&disabled).is_none());
    }
}

/// Check if an API key credential is configured (D-03: config-only, no live probe).
///
/// Returns "configured" if any credential is present, "not_configured" otherwise.
/// SECURITY (T-05-01-01): Never exposes the key value.
fn check_credential_configured() -> &'static str {
    let store = crate::core::auth::KeyringCredentialStore::new();
    let openlatch_dir = config::openlatch_dir();
    let agent_id = config::Config::load(None, None, false)
        .ok()
        .and_then(|c| c.agent_id)
        .unwrap_or_default();
    let file_store = crate::core::auth::FileCredentialStore::new(
        openlatch_dir.join("credentials.enc"),
        agent_id,
    );

    if crate::core::auth::retrieve_credential(
        &store as &dyn crate::core::auth::CredentialStore,
        &file_store as &dyn crate::core::auth::CredentialStore,
    )
    .is_ok()
    {
        "configured"
    } else {
        "not_configured"
    }
}

/// Probe the cloud API to determine live connection status (D-01).
///
/// Performs a GET to `{api_url}/api/v1/users/me` with Bearer auth.
/// Returns: "connected" (200), "auth_error" (401/403), "disconnected" (other/timeout).
///
/// SECURITY (T-05-01-02): The API key is only placed in the Authorization header.
/// It is never stored in a variable that gets logged, printed, or returned.
/// T-05-01-03: 3-second timeout prevents status from hanging.
fn probe_cloud_status(api_url: &str) -> &'static str {
    use secrecy::ExposeSecret;

    // Retrieve credential using the fallback chain
    let store = crate::core::auth::KeyringCredentialStore::new();
    let openlatch_dir = config::openlatch_dir();
    let agent_id = config::Config::load(None, None, false)
        .ok()
        .and_then(|c| c.agent_id)
        .unwrap_or_default();
    let file_store = crate::core::auth::FileCredentialStore::new(
        openlatch_dir.join("credentials.enc"),
        agent_id,
    );

    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 "not_configured",
    };

    // T-05-01-03: 3-second timeout to prevent status hanging when cloud is unreachable
    // WR-06: use_rustls_tls() enforces rustls-only TLS per security-constraints.md
    let client = match reqwest::blocking::Client::builder()
        .timeout(std::time::Duration::from_secs(3))
        .use_rustls_tls()
        .build()
    {
        Ok(c) => c,
        Err(_) => return "disconnected",
    };

    // WR-02: Strip trailing slash to prevent double-slash URLs.
    let base = api_url.trim_end_matches('/');
    let url = format!("{base}/api/v1/users/me");

    // SECURITY (T-05-01-02): expose_secret() only in header construction — never logged
    let result = client.get(&url).bearer_auth(key.expose_secret()).send();

    match result {
        Ok(resp) if resp.status().is_success() => "connected",
        Ok(resp)
            if resp.status() == reqwest::StatusCode::UNAUTHORIZED
                || resp.status() == reqwest::StatusCode::FORBIDDEN =>
        {
            "auth_error"
        }
        // T-05-01-04: malformed JSON or any other response → disconnected, never panic
        _ => "disconnected",
    }
}

/// Format a Unix epoch timestamp (seconds) as a relative time string.
///
/// Returns "never" when `epoch_secs` is 0.
/// Otherwise returns "{N}s ago", "{N}m ago", "{N}h ago", or "{N}d ago".
fn format_relative_secs(epoch_secs: u64) -> String {
    use std::time::{SystemTime, UNIX_EPOCH};
    let now_secs = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs();

    format_relative_secs_at(epoch_secs, now_secs)
}

/// `format_relative_secs` with the clock injected.
///
/// The wrapper above reads the clock, so a test that derives `past` from its
/// own `SystemTime::now()` reads it a SECOND time inside the call. Crossing a
/// one-second boundary between the two reads turns "12s ago" into "13s ago" —
/// rare uninstrumented, common under cargo-tarpaulin's ptrace overhead, which
/// is where it was caught. Tests pin `now_secs` and call this directly.
fn format_relative_secs_at(epoch_secs: u64, now_secs: u64) -> String {
    if epoch_secs == 0 {
        return "never".to_string();
    }

    let elapsed = now_secs.saturating_sub(epoch_secs);

    if elapsed < 60 {
        format!("{elapsed}s ago")
    } else if elapsed < 3600 {
        format!("{}m ago", elapsed / 60)
    } else if elapsed < 86400 {
        format!("{}h ago", elapsed / 3600)
    } else {
        format!("{}d ago", elapsed / 86400)
    }
}

/// Fetch health data from the daemon's /health endpoint.
fn fetch_health(port: u16) -> Option<serde_json::Value> {
    let url = format!("http://127.0.0.1:{port}/health");
    // WR-06: use_rustls_tls() enforces rustls-only TLS per security-constraints.md
    let client = reqwest::blocking::Client::builder()
        .timeout(std::time::Duration::from_secs(2))
        .use_rustls_tls()
        .build()
        .ok()?;
    let resp = client.get(&url).send().ok()?;
    if resp.status().is_success() {
        resp.json().ok()
    } else {
        None
    }
}

/// Fetch metrics from the daemon's /metrics endpoint.
fn fetch_metrics(port: u16) -> Option<serde_json::Value> {
    let url = format!("http://127.0.0.1:{port}/metrics");
    // WR-06: use_rustls_tls() enforces rustls-only TLS per security-constraints.md
    let client = reqwest::blocking::Client::builder()
        .timeout(std::time::Duration::from_secs(2))
        .use_rustls_tls()
        .build()
        .ok()?;
    let resp = client.get(&url).send().ok()?;
    if resp.status().is_success() {
        resp.json().ok()
    } else {
        None
    }
}

/// Read the last session info from daemon.log.
///
/// Returns (last_seen_timestamp, event_count).
fn read_last_session_info() -> (Option<String>, u64) {
    // PLAT-02: Use config::openlatch_dir() for path access
    let log_path = config::openlatch_dir().join("daemon.log");
    let Ok(content) = std::fs::read_to_string(&log_path) else {
        return (None, 0);
    };

    let mut last_seen = None;
    let mut last_events = 0u64;

    // Look for shutdown log entry with event count
    for line in content.lines().rev() {
        if let Ok(entry) = serde_json::from_str::<serde_json::Value>(line) {
            if entry
                .get("message")
                .and_then(|m| m.as_str())
                .map(|m| m.contains("daemon stopped") || m.contains("shutdown"))
                .unwrap_or(false)
            {
                last_seen = entry
                    .get("timestamp")
                    .and_then(|t| t.as_str())
                    .map(|s| s.to_string());
                last_events = entry.get("events").and_then(|e| e.as_u64()).unwrap_or(0);
                break;
            }
        }
    }

    (last_seen, last_events)
}

/// Format uptime in seconds to a human-readable string.
fn format_uptime(secs: u64) -> String {
    if secs < 60 {
        format!("{secs}s")
    } else if secs < 3600 {
        format!("{}m {}s", secs / 60, secs % 60)
    } else {
        format!("{}h {}m", secs / 3600, (secs % 3600) / 60)
    }
}

/// Format a timestamp string as a relative time ("5 minutes").
fn format_relative_time(ts: &str) -> String {
    // Parse RFC 3339 or ISO 8601 timestamp
    if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(ts) {
        let now = chrono::Utc::now();
        let duration = now.signed_duration_since(dt.with_timezone(&chrono::Utc));
        let secs = duration.num_seconds();
        if secs < 60 {
            return format!("{secs} seconds");
        } else if secs < 3600 {
            return format!("{} minutes", secs / 60);
        } else if secs < 86400 {
            return format!("{} hours", secs / 3600);
        } else {
            return format!("{} days", secs / 86400);
        }
    }
    "unknown time".to_string()
}

// ---------------------------------------------------------------------------
// Auto-update install-state surfacing (P2 §6 drift display)
// ---------------------------------------------------------------------------

fn install_state_json(state: &crate::install_state::InstallState) -> serde_json::Value {
    let drift_detected = matches!(
        (
            &state.actual_binary_version,
            &state.npm_reported_version,
            state.install_method,
        ),
        (Some(actual), Some(npm), crate::install_state::InstallMethod::Npm) if actual != npm
    );
    serde_json::json!({
        "install_method": serde_json::to_value(state.install_method).unwrap_or(serde_json::Value::Null),
        "actual_binary_version": state.actual_binary_version,
        "npm_reported_version": state.npm_reported_version,
        "last_updated_at": state.last_updated_at,
        "last_check_at": state.last_check_at,
        "drift_detected": drift_detected,
    })
}

/// The daemon is serving a binary that is no longer the one on disk.
///
/// A package upgrade — `npm update`, Homebrew, the curl installer, an MDM push
/// — replaces the binary underneath a daemon that goes on running the inode it
/// started from. The new code is installed and simply not in effect, and
/// nothing on the machine says so: the package manager reports success, the
/// binary on disk is genuinely new, and `/health` answers 200 the whole time.
/// For a security client that is the worst shape a failure can take, because
/// the update a user installed to fix something never took.
///
/// `install_state`'s drift check is the *opposite* case — the binary was
/// self-replaced by the auto-updater and npm's metadata lagged behind. That one
/// compares two on-disk facts; this one compares disk against memory.
///
/// Pure, so both branches are testable without a running daemon.
fn stale_daemon_line(cli_version: &str, daemon_version: Option<&str>) -> Option<String> {
    let running = daemon_version?;
    if running == cli_version {
        return None;
    }
    Some(format!(
        "Daemon:   serving {running} but {cli_version} is installed — \
         the update is not in effect (run: openlatch restart)"
    ))
}

/// Lines describing install state for the human dashboard. Returns an
/// empty Vec when there is nothing meaningful to surface (a fresh
/// install with no recorded auto-update activity).
fn install_state_human_lines(state: &crate::install_state::InstallState) -> Vec<String> {
    use crate::install_state::InstallMethod;
    let mut lines = Vec::new();
    if let Some(actual) = state.actual_binary_version.as_deref() {
        let suffix = match state.last_updated_at.as_deref() {
            Some(ts) => format!(" (last updated {ts})"),
            None => String::new(),
        };
        lines.push(format!("Binary:   {actual}{suffix}"));
    }
    if matches!(state.install_method, InstallMethod::Npm) {
        match (
            state.npm_reported_version.as_deref(),
            state.actual_binary_version.as_deref(),
        ) {
            (Some(npm), Some(actual)) if npm != actual => {
                lines.push(format!(
                    "npm:      {npm} ⚠ drift — run `npm install -g @openlatch/client@{actual}` to sync"
                ));
            }
            (Some(npm), _) => {
                lines.push(format!("npm:      {npm}"));
            }
            _ => {}
        }
    }
    lines
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    /// A fixed instant, so every relative-format case below is pure
    /// arithmetic with no clock read at all. 2026-01-01T00:00:00Z.
    const NOW: u64 = 1_767_225_600;

    #[test]
    fn test_format_relative_secs_zero_returns_never() {
        // Keeps covering the public wrapper: the zero case short-circuits
        // before any elapsed-time maths, so it cannot race.
        assert_eq!(format_relative_secs(0), "never");
        assert_eq!(format_relative_secs_at(0, NOW), "never");
    }

    /// Only the daemon's own `degraded` flag produces a line. A one-shot task
    /// legitimately parks in `stopped` forever, and reporting that as a problem
    /// would train the user to ignore the section entirely.
    #[test]
    fn degraded_subsystems_reports_only_flagged_entries() {
        let health = serde_json::json!({
            "status": "degraded",
            "subsystems": {
                "cloud-worker": {"state": "running", "restarts": 0},
                "update-check": {"state": "stopped", "restarts": 0},
                "boundary": {
                    "state": "restarting",
                    "restarts": 3,
                    "degraded": true,
                    "last_error": "boundary listener could not bind pinned loopback port 7600",
                },
            },
        });

        let lines = degraded_subsystems_from_health(Some(&health));
        assert_eq!(lines.len(), 1, "got {lines:?}");
        assert!(
            lines[0].starts_with("boundary: restarting (3 restarts)"),
            "{}",
            lines[0]
        );
        assert!(lines[0].contains("could not bind"), "{}", lines[0]);
    }

    /// A healthy daemon prints nothing, and so does a daemon too old to know
    /// what `subsystems` means — `status` must not invent a problem either way.
    #[test]
    fn degraded_subsystems_is_empty_when_healthy_or_absent() {
        let healthy = serde_json::json!({
            "status": "ok",
            "subsystems": {"cloud-worker": {"state": "running", "restarts": 0}},
        });
        assert!(degraded_subsystems_from_health(Some(&healthy)).is_empty());

        let legacy = serde_json::json!({"status": "ok", "version": "0.1.0"});
        assert!(degraded_subsystems_from_health(Some(&legacy)).is_empty());
        assert!(degraded_subsystems_from_health(None).is_empty());
    }

    // Pure mapping test (no network): the shared classification maps onto the
    // dashboard's boundary-state vocabulary. The classifier itself — including
    // "disabled in config is not FAILED" — is tested in `commands::boundary`.
    //
    // `"failed"` is reserved for the one genuinely dangerous state: an agent
    // wired at a port a foreign process holds, i.e. the provider credential is
    // going there. A foreign process on a port nothing is wired to is not that,
    // and reporting it as such is what raised a security alarm on a machine
    // whose boundary was deliberately switched off.
    #[cfg(feature = "boundary")]
    #[test]
    fn boundary_state_maps_onto_dashboard_vocabulary() {
        use crate::cli::commands::boundary::BoundaryState;
        assert_eq!(BoundaryState::Wired.label(), "up");
        assert_eq!(BoundaryState::WiredToForeign.label(), "failed");
        assert_eq!(BoundaryState::Disabled.label(), "disabled");
        assert_eq!(BoundaryState::ForeignIdle.label(), "down");
        assert_eq!(BoundaryState::Down.label(), "down");
        assert_ne!(
            BoundaryState::ForeignIdle.label(),
            "failed",
            "a foreign process on an unwired port is not an exposure"
        );
    }

    #[test]
    fn test_format_relative_secs_12_returns_12s_ago() {
        assert_eq!(format_relative_secs_at(NOW - 12, NOW), "12s ago");
    }

    #[test]
    fn test_format_relative_secs_90_returns_1m_ago() {
        assert_eq!(format_relative_secs_at(NOW - 90, NOW), "1m ago");
    }

    #[test]
    fn test_format_relative_secs_3700_returns_1h_ago() {
        assert_eq!(format_relative_secs_at(NOW - 3700, NOW), "1h ago");
    }
}