trusty-memory 0.26.2

MCP server (stdio + Unix socket) for trusty-memory
Documentation
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
//! Handler for `trusty-memory doctor`.
//!
//! Why: GH #62 — when the launchd-managed daemon misbehaves (silent EROFS on
//! fastembed model download, stale plist without `FASTEMBED_CACHE_PATH`,
//! daemon not bound, etc.), operators currently have to grep through
//! `~/Library/LaunchAgents`, `~/.cache/fastembed`, and the lock file by hand
//! to figure out what's wrong. `doctor` runs the same checks in one shot and
//! prints a human-readable pass/fail report so the user can act immediately.
//! What: a one-shot CLI command that runs five checks:
//!   1. fastembed cache directory exists and is readable
//!   2. launchd plist exists at `~/Library/LaunchAgents/com.trusty.memory.plist`
//!      and contains the `FASTEMBED_CACHE_PATH` env var (macOS only)
//!   3. The HTTP daemon responds to `GET /health` on its configured port
//!   4. No obvious stale palace lock sidecar files (`*.lock`) under the data dir
//!   5. No Tier S standing rule is overdue for re-affirmation (#4890, `tier_s`)
//!   6. Every MCP-client registration launches `trusty-memory serve` (#5265,
//!      `mcp_registration`)
//!
//! Each check prints a ✅ or ❌ line. The command exits 0 if all critical
//! checks pass, 1 otherwise.
//!
//! Test: `fastembed_cache_check_reports_missing_dir` and
//! `plist_check_detects_missing_env_var` cover the helpers; the full
//! orchestrator is exercised manually via
//! `cargo run -p trusty-memory -- doctor`.

mod audit;
mod checks;
mod mcp_registration;
mod tier_s;

use audit::audit_palaces;
pub use audit::{PalaceAuditEntry, PalaceAuditStatus};
#[cfg(target_os = "macos")]
use checks::check_launchd_plist;
use checks::{
    check_daemon_health, check_fastembed_cache, check_kg_redb_size, check_stale_palace_locks,
};
use mcp_registration::check_mcp_registrations;
use tier_s::check_tier_s_reaffirmation;

use anyhow::Result;
use colored::Colorize;

use crate::project_root::PERSONAL_PALACE;

/// Outcome of a single doctor check.
///
/// Why: keeps the orchestrator able to count failures without re-parsing
/// strings, while preserving the human-readable message for printing.
/// What: a tiny enum-with-message: `Pass` for green checks, `Warn` for
/// non-critical issues (don't flip exit code), `Fail` for actionable
/// failures (flip exit code to 1).
/// Test: not directly — exercised via the per-check unit tests.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) enum CheckStatus {
    Pass,
    Warn,
    Fail,
    /// The probe could not determine the answer (issue #4005).
    ///
    /// Why: this is the missing third state, and the whole reason #4005 and
    /// #4001 are the same bug in opposite directions. A probe that times out
    /// has learned NOTHING — the daemon may be perfectly healthy and merely
    /// slow (which is exactly what happened on 2026-07-26, when `/health`
    /// missed a 2 s budget while MCP calls against the same daemon succeeded).
    /// Rendering that as `Fail` is a false negative; rendering it as `Pass`
    /// would be a false positive. Neither is honest, so it gets its own state.
    /// The rule this variant encodes: a health check must report what it
    /// actually observed, and "could not determine" must never render as
    /// healthy.
    /// Test: `indeterminate_probe_renders_as_unknown_not_pass`.
    Unknown,
}

/// A single doctor check result.
///
/// Why: the orchestrator collects every result before printing so the
/// summary line ("N checks passed, M failed") is accurate.
/// What: bundles the status with a human-readable label and optional detail
/// (file path, error message, etc.).
/// Test: covered transitively by the helper tests.
#[derive(Debug, Clone)]
pub(super) struct CheckResult {
    pub(super) status: CheckStatus,
    label: String,
    detail: Option<String>,
}

impl CheckResult {
    pub(super) fn pass(label: impl Into<String>, detail: impl Into<String>) -> Self {
        Self {
            status: CheckStatus::Pass,
            label: label.into(),
            detail: Some(detail.into()),
        }
    }
    pub(super) fn warn(label: impl Into<String>, detail: impl Into<String>) -> Self {
        Self {
            status: CheckStatus::Warn,
            label: label.into(),
            detail: Some(detail.into()),
        }
    }
    pub(super) fn fail(label: impl Into<String>, detail: impl Into<String>) -> Self {
        Self {
            status: CheckStatus::Fail,
            label: label.into(),
            detail: Some(detail.into()),
        }
    }

    /// Build an "could not determine" result (issue #4005).
    ///
    /// Why: see [`CheckStatus::Unknown`]. Callers reach for this when the probe
    /// itself failed to produce evidence — a timeout, an unparseable body —
    /// rather than when it produced evidence of a problem.
    /// What: a [`CheckStatus::Unknown`] result carrying the reason.
    /// Test: `indeterminate_probe_renders_as_unknown_not_pass`.
    pub(super) fn unknown(label: impl Into<String>, detail: impl Into<String>) -> Self {
        Self {
            status: CheckStatus::Unknown,
            label: label.into(),
            detail: Some(detail.into()),
        }
    }

    pub(super) fn print(&self) {
        let glyph = match self.status {
            CheckStatus::Pass => "✅".to_string(),
            CheckStatus::Warn => "⚠️ ".to_string(),
            CheckStatus::Fail => "❌".to_string(),
            // Deliberately NOT a green/✅ glyph: an indeterminate probe must
            // never read as healthy at a glance (issue #4005).
            CheckStatus::Unknown => "❔".to_string(),
        };
        let label = match self.status {
            CheckStatus::Pass => self.label.green().to_string(),
            CheckStatus::Warn => self.label.yellow().to_string(),
            CheckStatus::Fail => self.label.red().to_string(),
            CheckStatus::Unknown => self.label.yellow().to_string(),
        };
        match &self.detail {
            Some(d) => println!("{glyph} {label} — {}", d.dimmed()),
            None => println!("{glyph} {label}"),
        }
    }
}

/// Entry point for `trusty-memory doctor --fix-palaces [--fix]`.
///
/// Why: issue #88 — users with many accumulated palaces (e.g. 89 from
/// account-recovery) need a way to see which ones are orphaned without
/// destructive auto-cleanup. This command provides the read-only audit view
/// (default) and prints rename suggestions when `--fix` is also given.
/// Actual renaming is deliberately deferred to a future PR to avoid data
/// loss during this first conservative implementation.
/// What: resolves the palace registry directory (same logic as daemon startup),
/// calls `audit_palaces`, prints a table, and exits 0. The `--fix` flag
/// adds "rename suggested: X → personal" lines for every `Orphaned` entry
/// but does NOT mutate the filesystem.
/// Test: `doctor_fix_palaces_lists_orphaned_dry_run`.
pub async fn handle_doctor_fix_palaces(suggest_fix: bool) -> Result<()> {
    let data_dir = match trusty_common::resolve_data_dir("trusty-memory") {
        Ok(d) => d,
        Err(e) => {
            eprintln!("{} could not resolve data directory: {e:#}", "✗".red());
            return Ok(());
        }
    };
    let registry_dir = crate::resolve_palace_registry_dir(data_dir);

    println!(
        "{} Auditing palaces under {}\n",
        "·".dimmed(),
        registry_dir.display()
    );

    let entries = audit_palaces(&registry_dir);
    if entries.is_empty() {
        println!("{} No palace directories found.", "·".dimmed());
        return Ok(());
    }

    let mut ok_count = 0usize;
    let mut orphaned_count = 0usize;
    let mut empty_count = 0usize;

    for entry in &entries {
        match entry.status {
            PalaceAuditStatus::Ok => {
                ok_count += 1;
                println!(
                    "✅  {} — {}",
                    entry.id.green(),
                    "project palace ok".dimmed()
                );
            }
            PalaceAuditStatus::Orphaned => {
                orphaned_count += 1;
                println!(
                    "⚠️   {} — {}",
                    entry.id.yellow(),
                    "orphaned (no matching project directory found on disk)".dimmed()
                );
                if suggest_fix {
                    println!(
                        "   {} rename suggested: {} → {}",
                        "→".dimmed(),
                        entry.id.yellow(),
                        PERSONAL_PALACE.cyan()
                    );
                }
            }
            PalaceAuditStatus::Empty => {
                empty_count += 1;
                println!(
                    "❌  {} — {}",
                    entry.id.red(),
                    "empty (no palace.json; directory may be a leftover)".dimmed()
                );
            }
        }
    }

    println!();
    println!(
        "{} palace audit: {} ok, {} orphaned, {} empty.",
        "·".dimmed(),
        ok_count,
        orphaned_count,
        empty_count
    );

    if orphaned_count > 0 && !suggest_fix {
        println!(
            "{} Run with {} to see rename suggestions (no filesystem changes made).",
            "·".dimmed(),
            "--fix-palaces --fix".cyan()
        );
    }
    if suggest_fix && orphaned_count > 0 {
        println!(
            "{} Rename suggestions printed above (dry-run — no filesystem changes made).",
            "·".dimmed()
        );
    }

    Ok(())
}

/// Entry point for `trusty-memory doctor`.
///
/// Why: a single command for operators to triage daemon health without
/// having to remember four separate diagnostic incantations.
/// What: runs each check, prints the ✅/❌ line, and exits 0 (all pass) or
/// 1 (any `Fail` or `Unknown`, #4001). `Warn` results print but do not flip the
/// exit code.
/// Test: orchestrator is process-level; the verdict is `checks::summarize`'s,
/// unit-tested in `checks_tests.rs`.
pub async fn handle_doctor() -> Result<()> {
    println!("{} Running trusty-memory diagnostics…\n", "·".dimmed());

    let mut results: Vec<CheckResult> = Vec::new();

    // Check 1: fastembed cache.
    results.push(check_fastembed_cache());

    // Check 2: launchd plist (macOS only).
    #[cfg(target_os = "macos")]
    {
        results.push(check_launchd_plist());
    }
    #[cfg(not(target_os = "macos"))]
    {
        results.push(CheckResult::warn(
            "launchd plist".to_string(),
            "skipped (not macOS)".to_string(),
        ));
    }

    // Check 3: HTTP daemon health.
    results.push(check_daemon_health().await);

    // Check 4: stale palace locks.
    results.push(check_stale_palace_locks());

    // #6652: kg.redb only ever grows; surface the biggest one before it is a
    // slow-write symptom the operator has to trace by hand.
    results.push(check_kg_redb_size());

    // Check 5 (#4890): Tier S facts overdue for re-affirmation. Report only.
    results.push(check_tier_s_reaffirmation().await);

    // Check 6 (#5265): what each MCP client will actually launch. One verdict
    // per client, so a broken Codex registration cannot hide behind a healthy
    // Claude one.
    results.extend(check_mcp_registrations(
        crate::commands::setup::MCP_SERVER_KEY,
    ));

    for r in &results {
        r.print();
    }

    // #4005 gave indeterminate checks their own column; #4001 stops them
    // ending the run green, since a timed-out probe has not passed.
    let summary = checks::summarize(&results);

    println!();
    if summary.healthy {
        println!("{} {}", "✓".green(), summary.line);
        Ok(())
    } else {
        eprintln!("{} {}", "✗".red(), summary.line);
        std::process::exit(1);
    }
}

#[cfg(test)]
mod tests {
    use super::audit::scan_project_dirs_for_pin;
    #[cfg(target_os = "macos")]
    use super::checks::plist_contains_fastembed_cache_path;
    use super::checks::{fastembed_cache_has_models, find_lock_files};
    use super::*;

    /// Why: when the cache directory genuinely doesn't exist, doctor must
    /// flag it as a `Fail` so the user knows to run `setup` — silently
    /// passing here is the whole bug GH #62 protects against.
    /// What: builds a path under a tempdir that we deliberately do not
    /// create, calls the helper with a fake `FASTEMBED_CACHE_PATH`, and
    /// asserts the result is `Fail`.
    /// Test: pure, no network.
    #[test]
    fn fastembed_cache_check_reports_missing_dir() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let missing = tmp.path().join("does_not_exist");
        // SAFETY: serial test — no other thread is reading the env var.
        // We don't set FASTEMBED_CACHE_DIR (which would take precedence)
        // and instead exercise FASTEMBED_CACHE_PATH so the resolver
        // returns our specific missing path.
        unsafe {
            std::env::remove_var("FASTEMBED_CACHE_DIR");
            std::env::set_var("FASTEMBED_CACHE_PATH", &missing);
        }
        let result = check_fastembed_cache();
        unsafe {
            std::env::remove_var("FASTEMBED_CACHE_PATH");
        }
        assert_eq!(result.status, CheckStatus::Fail, "got: {:?}", result);
    }

    /// Why: detecting model files (vs an empty cache) is what distinguishes
    /// "pre-warmed" from "first request will pay the download cost". The
    /// helper has to differentiate the two.
    /// What: creates an empty dir, asserts `Ok(false)`; writes a file,
    /// asserts `Ok(true)`.
    /// Test: pure filesystem.
    #[test]
    fn fastembed_cache_has_models_detects_entries() {
        let tmp = tempfile::tempdir().expect("tempdir");
        assert!(!fastembed_cache_has_models(tmp.path()).unwrap());
        std::fs::write(tmp.path().join("model.onnx"), b"x").unwrap();
        assert!(fastembed_cache_has_models(tmp.path()).unwrap());
    }

    /// Why: the plist check is the most operationally important diagnostic
    /// — it's the difference between "the daemon will work" and "the
    /// daemon will EROFS on first embed". Both branches must be covered.
    /// What: writes a plist *without* the key and asserts `Ok(false)`;
    /// writes a plist *with* the key and asserts `Ok(true)`.
    /// Test: pure filesystem.
    #[cfg(target_os = "macos")]
    #[test]
    fn plist_check_detects_missing_env_var() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let no_key = tmp.path().join("no_key.plist");
        std::fs::write(&no_key, "<plist><dict></dict></plist>").unwrap();
        assert!(
            !plist_contains_fastembed_cache_path(&no_key).unwrap(),
            "plist without env var must report false"
        );

        let with_key = tmp.path().join("with_key.plist");
        std::fs::write(
            &with_key,
            "<plist><dict><key>FASTEMBED_CACHE_PATH</key><string>/x</string></dict></plist>",
        )
        .unwrap();
        assert!(
            plist_contains_fastembed_cache_path(&with_key).unwrap(),
            "plist with env var must report true"
        );
    }

    /// Why: `audit_palaces` is the core of the `--fix-palaces` audit; it must
    /// correctly classify palaces as `Ok`, `Orphaned`, and `Empty` so the
    /// presenter can display actionable information.
    /// What: build a mock registry under a tempdir with three palace
    /// directories: one matching the `personal` sentinel (Ok), one with a
    /// `palace.json` and no matching project directory (Orphaned), and one
    /// with no `palace.json` at all (Empty). Assert the audit returns three
    /// entries with the correct statuses.
    /// Test: pure filesystem.
    #[test]
    fn find_orphaned_palaces_lists_non_matching_and_empty() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let registry = tmp.path();

        // `personal` → always Ok.
        let personal = registry.join("personal");
        std::fs::create_dir_all(&personal).unwrap();
        std::fs::write(personal.join("palace.json"), b"{}").unwrap();

        // `orphaned-proj` → has palace.json but no matching project on disk.
        let orphaned = registry.join("orphaned-proj-xyzzy");
        std::fs::create_dir_all(&orphaned).unwrap();
        std::fs::write(orphaned.join("palace.json"), b"{}").unwrap();

        // `empty-palace` → no palace.json.
        let empty = registry.join("empty-palace");
        std::fs::create_dir_all(&empty).unwrap();

        let entries = audit_palaces(registry);

        let personal_entry = entries.iter().find(|e| e.id == "personal");
        assert!(personal_entry.is_some(), "personal must appear in audit");
        assert_eq!(
            personal_entry.unwrap().status,
            PalaceAuditStatus::Ok,
            "personal must be Ok"
        );

        let orphaned_entry = entries.iter().find(|e| e.id == "orphaned-proj-xyzzy");
        assert!(orphaned_entry.is_some(), "orphaned entry must appear");
        assert_eq!(
            orphaned_entry.unwrap().status,
            PalaceAuditStatus::Orphaned,
            "orphaned-proj-xyzzy must be Orphaned"
        );

        let empty_entry = entries.iter().find(|e| e.id == "empty-palace");
        assert!(empty_entry.is_some(), "empty entry must appear");
        assert_eq!(
            empty_entry.unwrap().status,
            PalaceAuditStatus::Empty,
            "empty-palace must be Empty"
        );
    }

    /// Why: Change 3 — a palace whose name is claimed by a pin file in a
    /// scanned project directory must be classified `Ok`, not `Orphaned`, even
    /// when the directory name no longer matches the palace id (e.g. after a
    /// drive reorg / rename).
    /// What: create a mock registry with a palace named `my-old-name`; create
    /// a fake "Projects" search dir with a project that has a pin file claiming
    /// `palace: my-old-name`; pass that search dir to `scan_project_dirs_for_pin`
    /// and assert it returns `true`. Also assert that `audit_palaces` with the
    /// scanned search dirs classifies the palace as `Ok`.
    /// Test: pure filesystem.
    #[test]
    fn audit_palaces_ok_when_pin_file_claims_it() {
        use crate::project_root::{write_project_pin, ProjectPin};
        let tmp = tempfile::tempdir().expect("tempdir");

        // Set up a fake "Projects" directory with a project that has a pin.
        let projects_dir = tmp.path().join("Projects");
        let project_dir = projects_dir.join("moved-project");
        std::fs::create_dir_all(&project_dir).unwrap();
        let pin = ProjectPin::new("my-old-name".to_string());
        write_project_pin(&project_dir, &pin).expect("write pin");

        // scan_project_dirs_for_pin must return true for the pinned id.
        assert!(
            scan_project_dirs_for_pin(std::slice::from_ref(&projects_dir), "my-old-name"),
            "scan must find the pin file that claims my-old-name"
        );
        // Must return false for an unrelated id.
        assert!(
            !scan_project_dirs_for_pin(std::slice::from_ref(&projects_dir), "some-other-palace"),
            "scan must not match a palace id not claimed by any pin"
        );
    }

    /// Why: `scan_project_dirs_for_pin` must not falsely claim a match when
    /// the pin file's `palace` field differs from the audit id.
    /// What: create a project with a pin for `alpha`; assert scan for `beta`
    /// returns false.
    /// Test: pure filesystem.
    #[test]
    fn scan_project_dirs_returns_false_for_mismatch() {
        use crate::project_root::{write_project_pin, ProjectPin};
        let tmp = tempfile::tempdir().expect("tempdir");
        let projects_dir = tmp.path().join("Projects");
        let project_dir = projects_dir.join("some-project");
        std::fs::create_dir_all(&project_dir).unwrap();
        let pin = ProjectPin::new("alpha".to_string());
        write_project_pin(&project_dir, &pin).expect("write pin");
        assert!(
            !scan_project_dirs_for_pin(&[projects_dir], "beta"),
            "mismatch must return false"
        );
    }

    /// Why: stale `.lock` files are the canonical "palace won't open"
    /// symptom; the scanner must report them so `doctor` can hint at the
    /// remediation.
    /// What: lays out a tiny `palace/kg.redb.lock` tree under a tempdir
    /// and asserts the scanner picks it up.
    /// Test: pure filesystem.
    #[test]
    fn find_lock_files_returns_paths() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let palace = tmp.path().join("palace_a");
        std::fs::create_dir_all(&palace).unwrap();
        let lock = palace.join("kg.redb.lock");
        std::fs::write(&lock, b"").unwrap();
        // Also drop a non-lock file to ensure it is ignored.
        std::fs::write(palace.join("kg.redb"), b"").unwrap();

        let found = find_lock_files(tmp.path());
        assert!(
            found.iter().any(|p| p == &lock),
            "expected to find {} in {:?}",
            lock.display(),
            found
        );
        assert_eq!(
            found.len(),
            1,
            "non-lock files must be ignored: {:?}",
            found
        );
    }

    // -----------------------------------------------------------------------
    // check_daemon_health against nothing (#475, reshaped by #6286)
    // -----------------------------------------------------------------------

    /// Why: #475 was about a STALE `http_addr` file — the check reported
    /// "daemon not running" while a live daemon sat on a port the file did not
    /// name, so it grew a fallback that walked 7070..=7079. #6286 removed both
    /// the file and the port range: the socket path is derived, so caller and
    /// daemon compute the same one and there is nothing to be stale. What
    /// survives is the case underneath — nothing is serving — and it must
    /// report a `Fail` whose message an operator can act on rather than
    /// panicking or naming a start command that does not exist.
    ///
    /// The two tests that used to sit here (`…_with_stale_addr_and_no_listener`
    /// and `…_when_no_addr_file_and_no_listener`) differed only in whether they
    /// pre-wrote a stale file. With no file in the design they are one test.
    ///
    /// `Pass` and `Unknown` stay acceptable outcomes: `TRUSTY_DATA_DIR_OVERRIDE`
    /// redirects the derived path into a tempdir, but a developer machine can
    /// still have a real daemon whose socket the override happens not to hide,
    /// and #4001 made "live but progress unobservable" an honest `Unknown`
    /// rather than a claimed pass.
    /// Test: itself.
    #[tokio::test]
    async fn check_daemon_health_fails_cleanly_with_no_listener() {
        // Serialise on the process-wide env-var lock so concurrent tests that
        // also mutate TRUSTY_DATA_DIR_OVERRIDE do not interleave.
        let _guard = super::super::env_test_lock().lock().await;

        let tmp = tempfile::tempdir().expect("tempdir");
        // The override sets the BASE dir; `resolve_data_dir` appends
        // "trusty-memory" to it.
        std::fs::create_dir_all(tmp.path().join("trusty-memory")).expect("create data dir");

        // SAFETY: serialised by env_test_lock above.
        unsafe {
            std::env::set_var("TRUSTY_DATA_DIR_OVERRIDE", tmp.path());
        }
        let result = check_daemon_health().await;
        unsafe {
            std::env::remove_var("TRUSTY_DATA_DIR_OVERRIDE");
        }
        drop(_guard);

        assert!(
            matches!(
                result.status,
                CheckStatus::Fail | CheckStatus::Pass | CheckStatus::Unknown
            ),
            "unexpected status {:?}",
            result.status,
        );
        if result.status == CheckStatus::Fail {
            let detail = result.detail.as_deref().unwrap_or("");
            assert!(
                detail.contains("no daemon") || detail.contains("unreachable"),
                "a Fail must say the daemon is not there: {detail:?}"
            );
            assert!(
                detail.contains("service start"),
                "a Fail must name the command that fixes it: {detail:?}"
            );
        }
    }

    // ---- Issues #4001 / #4005: interpret what the daemon reported ----

    use super::checks::interpret_health_body;

    fn interpret(body: serde_json::Value) -> CheckResult {
        interpret_health_body(
            "HTTP daemon".to_string(),
            "http://x/health",
            200,
            Some(&body),
        )
    }

    /// Why (issue #4001): `trusty-memory doctor` reported HEALTHY throughout
    /// the #3992 hang because a 2xx was the entire test. A daemon reporting a
    /// wedged pool must fail even though the HTTP layer is perfectly fine.
    /// What: asserts `Fail` plus a message naming the wedge and its age.
    /// Test: itself.
    #[test]
    fn wedged_body_is_fail() {
        let r = interpret(serde_json::json!({
            "status": "ok",
            "daemon_state": "ready",
            "worker": {"in_flight": 6, "oldest_age_secs": 1800, "wedged": true},
        }));
        assert_eq!(r.status, CheckStatus::Fail);
        let d = r.detail.as_deref().unwrap_or("");
        assert!(d.contains("WEDGED"), "must name the wedge: {d}");
        assert!(d.contains("1800"), "must carry the observed age: {d}");
    }

    /// Why (issue #4005): post-restart warm-up is a normal transient state.
    /// Reporting it as a hard failure is the false negative; reporting it as a
    /// clean pass would hide that recall is on its fallback path.
    /// What: asserts `Warn`.
    /// Test: itself.
    #[test]
    fn warming_body_is_warn() {
        let r = interpret(serde_json::json!({
            "status": "ok",
            "daemon_state": "warming",
            "worker": {"in_flight": 0, "wedged": false, "stall_tracking_ok": true},
        }));
        assert_eq!(r.status, CheckStatus::Warn);
        assert!(r.detail.as_deref().unwrap_or("").contains("WARMING"));
    }

    /// Why (the unifying principle): doctor must never claim health it did not
    /// observe. A 2xx whose body cannot be read tells us the listener is up
    /// and nothing else.
    /// What: asserts an absent body is `Unknown`, explicitly not `Pass`.
    /// Test: itself.
    #[test]
    fn indeterminate_probe_renders_as_unknown_not_pass() {
        let r = interpret_health_body("HTTP daemon".to_string(), "http://x/health", 200, None);
        assert_eq!(r.status, CheckStatus::Unknown);
        assert_ne!(r.status, CheckStatus::Pass, "unknown must never be healthy");
        assert!(r.detail.as_deref().unwrap_or("").contains("UNKNOWN"));
    }

    /// Why (issue #4001, forward-compatibility): a daemon predating the worker
    /// block gives doctor no observation to base a pass on.
    /// What: asserts a body with no `worker` key is `Unknown`.
    /// Test: itself.
    #[test]
    fn body_without_worker_block_is_unknown() {
        let r = interpret(serde_json::json!({"status": "ok", "daemon_state": "ready"}));
        assert_eq!(r.status, CheckStatus::Unknown);
    }

    /// Why: the fix must still let a genuinely healthy daemon pass, or it
    /// would trade one false verdict for another.
    /// What: asserts a ready daemon with a quiet pool is `Pass`.
    /// Test: itself.
    #[test]
    fn healthy_body_is_pass() {
        let r = interpret(serde_json::json!({
            "status": "ok",
            "daemon_state": "ready",
            "worker": {
                "in_flight": 2,
                "oldest_age_secs": 1,
                "wedged": false,
                "stall_tracking_ok": true,
            },
        }));
        assert_eq!(r.status, CheckStatus::Pass);
    }

    /// Why (issue #71 preserved): the deep-probe degraded signal must survive
    /// the new worker-block logic rather than being masked by it.
    /// What: asserts a degraded round-trip still warns.
    /// Test: itself.
    #[test]
    fn degraded_body_is_warn() {
        let r = interpret(serde_json::json!({
            "status": "degraded",
            "detail": "store failed: disk full",
            "daemon_state": "ready",
            "worker": {"in_flight": 0, "wedged": false, "stall_tracking_ok": true},
        }));
        assert_eq!(r.status, CheckStatus::Warn);
        assert!(r.detail.as_deref().unwrap_or("").contains("disk full"));
    }

    /// Why (#6652): the thresholds are the whole check — an operator acts on
    /// "warn at 100 MB, fail at 500 MB" and on the command the message names.
    /// Pinning them here keeps a later tweak deliberate, and needs no
    /// filesystem.
    #[test]
    fn kg_redb_size_verdict_matches_the_thresholds() {
        use super::CheckStatus;
        use checks::kg_redb_verdict;

        let pass = kg_redb_verdict("kg.redb size".into(), "small", 10 * 1024 * 1024);
        assert!(matches!(pass.status, CheckStatus::Pass), "{pass:?}");

        let warn = kg_redb_verdict("kg.redb size".into(), "mid", 120 * 1024 * 1024);
        assert!(matches!(warn.status, CheckStatus::Warn), "{warn:?}");
        assert!(
            warn.detail
                .as_deref()
                .unwrap_or("")
                .contains("palace stats mid"),
            "the warning must name the command to run: {warn:?}"
        );

        let fail = kg_redb_verdict("kg.redb size".into(), "huge", 600 * 1024 * 1024);
        assert!(matches!(fail.status, CheckStatus::Fail), "{fail:?}");
        assert!(
            fail.detail
                .as_deref()
                .unwrap_or("")
                .contains("palace compact huge"),
            "the failure must name the command to run: {fail:?}"
        );
        assert!(
            fail.detail
                .as_deref()
                .unwrap_or("")
                .contains("disk, not data"),
            "a large store still serves every read; say so: {fail:?}"
        );
    }
}