memd 0.61.0

Local memory CLI for AI agents with hybrid retrieval
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
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
//! `memd doctor` — diagnose host wiring and per-repo scope.
//!
//! Reports whether the user's machine is set up for the
//! "clone → it just works in any repo" UX:
//!
//! - `memd` binary discoverable + version
//! - Data directory present (and chunk count if readable)
//! - Global agent rules wired: Claude Code (`~/.claude/CLAUDE.md`),
//!   Codex (`~/.codex/AGENTS.md`), Cursor (`~/.cursor/rules/*.mdc`)
//! - Claude Code `SessionStart` hook wired in `~/.claude/settings.json`
//! - Current project scope (`.memd/project_scope.json`) if cwd is a
//!   memd-aware repo
//!
//! Always exits 0 — `doctor` is informational. Use `--format json`
//! for machine-readable output suitable for `--quiet` checks.

use std::path::{Path, PathBuf};

use serde_json::{json, Value};

use super::args::ExportFormat;
use crate::error::Result;
use crate::store::Store;
use crate::types::TenantId;

/// Marker the installer drops into agent rule files. Identical
/// substring is used by both `~/.claude/CLAUDE.md` and
/// `~/.codex/AGENTS.md`, so a single grep covers both surfaces.
const ENFORCEMENT_MARKER: &str = "memd-enforcement:start";

/// Marker used inside the wired `SessionStart` hook command.
const SESSION_HOOK_MARKER: &str = "memd session-start";
const PROJECT_DRIFT_LOW_CHUNK_THRESHOLD: usize = 2;
const PROJECT_DRIFT_MIN_DOMINANT_CHUNKS: usize = 10;
const PROJECT_DRIFT_DOMINANCE_RATIO: usize = 5;
const PROJECT_DRIFT_SCAN_LIMIT: usize = 5_000;
const PROJECT_DRIFT_PAGE_SIZE: usize = 500;

#[derive(Debug, Clone)]
pub(super) struct DoctorOptions {
    pub(super) project_dir: PathBuf,
    pub(super) format: ExportFormat,
}

/// Run the doctor command. Returns the structured report as JSON; the
/// CLI dispatcher renders it according to `options.format`.
pub(super) async fn run_doctor<S: Store>(store: &S, options: DoctorOptions) -> Result<Value> {
    let mut report = collect_report(&options.project_dir);
    if let Some(scope) = report.get_mut("project_scope") {
        enrich_project_scope_memory(store, scope).await;
    }
    match options.format {
        ExportFormat::Json => {
            println!("{}", serde_json::to_string_pretty(&report)?);
        }
        ExportFormat::Jsonl => {
            println!("{}", serde_json::to_string(&report)?);
        }
        ExportFormat::Markdown => {
            print!("{}", render_text(&report));
        }
    }
    Ok(report)
}

fn collect_report(project_dir: &Path) -> Value {
    let binary = check_binary();
    let data_dir = check_data_dir();
    let claude_rules = check_rules_file(home_path(".claude/CLAUDE.md").as_deref());
    let codex_rules = check_rules_file(home_path(".codex/AGENTS.md").as_deref());
    let cursor_rules = check_cursor_rules();
    let session_hook = check_session_hook();
    let project_scope = check_project_scope(project_dir);

    json!({
        "binary": binary,
        "data_dir": data_dir,
        "global_rules": {
            "claude_md": claude_rules,
            "codex_agents_md": codex_rules,
            "cursor_rules_mdc": cursor_rules,
        },
        "session_start_hook": session_hook,
        "project_scope": project_scope,
    })
}

fn check_binary() -> Value {
    let exe = std::env::current_exe().ok();
    let on_path = find_on_path("memd");
    let version = env!("CARGO_PKG_VERSION");
    // "ok" means `memd` is discoverable via PATH — that's what
    // matters for SessionStart hooks and skill invocations. Knowing
    // the current process's exe is informational only.
    json!({
        "ok": on_path.is_some(),
        "current_exe": exe.as_ref().map(|p| p.display().to_string()),
        "on_path": on_path.as_ref().map(|p| p.display().to_string()),
        "version": version,
    })
}

/// Walk `$PATH` for an executable named `name`. Returns the first
/// match. Unix-only executable bit check; on other platforms any
/// regular file with the name counts.
fn find_on_path(name: &str) -> Option<PathBuf> {
    let path_var = std::env::var_os("PATH")?;
    for dir in std::env::split_paths(&path_var) {
        let candidate = dir.join(name);
        if !candidate.is_file() {
            continue;
        }
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            match candidate.metadata() {
                Ok(meta) if meta.permissions().mode() & 0o111 != 0 => return Some(candidate),
                _ => continue,
            }
        }
        #[cfg(not(unix))]
        {
            return Some(candidate);
        }
    }
    None
}

fn check_data_dir() -> Value {
    let path = dirs::home_dir().map(|h| h.join(".memd").join("data"));
    let exists = path.as_ref().map(|p| p.exists()).unwrap_or(false);
    let tenant_count = path.as_ref().map(|p| count_tenant_dirs(p)).unwrap_or(0);
    json!({
        "ok": exists,
        "path": path.as_ref().map(|p| p.display().to_string()),
        "tenant_count": tenant_count,
    })
}

fn count_tenant_dirs(data_dir: &Path) -> usize {
    let tenants = data_dir.join("tenants");
    let Ok(entries) = std::fs::read_dir(&tenants) else {
        return 0;
    };
    entries
        .flatten()
        .filter(|e| e.file_type().map(|t| t.is_dir()).unwrap_or(false))
        .count()
}

fn check_rules_file(path: Option<&Path>) -> Value {
    let Some(path) = path else {
        return json!({"ok": false, "reason": "no home dir"});
    };
    if !path.exists() {
        return json!({
            "ok": false,
            "path": path.display().to_string(),
            "reason": "file missing",
        });
    }
    let contents = std::fs::read_to_string(path).unwrap_or_default();
    let wired = contents.contains(ENFORCEMENT_MARKER);
    json!({
        "ok": wired,
        "path": path.display().to_string(),
        "reason": if wired { Value::Null } else { json!("memd-enforcement block missing") },
    })
}

fn check_cursor_rules() -> Value {
    let Some(home) = dirs::home_dir() else {
        return json!({"ok": false, "reason": "no home dir"});
    };
    let dir = home.join(".cursor").join("rules");
    let path = dir.join("memd.mdc");
    if path.exists() {
        return json!({
            "ok": true,
            "path": path.display().to_string(),
        });
    }
    // Fall back: any .mdc rule that references memd counts as
    // "wired" so users with custom Cursor setups aren't flagged.
    if let Ok(entries) = std::fs::read_dir(&dir) {
        for entry in entries.flatten() {
            let p = entry.path();
            if p.extension().and_then(|s| s.to_str()) != Some("mdc") {
                continue;
            }
            if let Ok(text) = std::fs::read_to_string(&p) {
                if text.to_lowercase().contains("memd") {
                    return json!({
                        "ok": true,
                        "path": p.display().to_string(),
                        "note": "matched a non-default .mdc referencing memd",
                    });
                }
            }
        }
    }
    json!({
        "ok": false,
        "path": path.display().to_string(),
        "reason": "no memd Cursor rule found",
    })
}

fn check_session_hook() -> Value {
    let Some(home) = dirs::home_dir() else {
        return json!({"ok": false, "reason": "no home dir"});
    };
    let path = home.join(".claude").join("settings.json");
    if !path.exists() {
        return json!({
            "ok": false,
            "path": path.display().to_string(),
            "reason": "settings.json missing",
        });
    }
    let contents = std::fs::read_to_string(&path).unwrap_or_default();
    // Parse the JSON and walk to `hooks.SessionStart[].hooks[].command`
    // before substring-matching — that's the only place a *real*
    // SessionStart hook lives. Substring-matching the whole file
    // would false-positive on stale comments or unrelated keys.
    let wired = match serde_json::from_str::<Value>(&contents) {
        Ok(parsed) => session_start_hook_wired(&parsed),
        Err(_) => {
            return json!({
                "ok": false,
                "path": path.display().to_string(),
                "reason": "settings.json is not valid JSON",
            });
        }
    };
    json!({
        "ok": wired,
        "path": path.display().to_string(),
        "reason": if wired { Value::Null } else { json!("SessionStart hook for memd missing") },
    })
}

/// Returns true if `settings` contains a `hooks.SessionStart[].hooks[].command`
/// entry whose command string mentions `memd session-start`.
fn session_start_hook_wired(settings: &Value) -> bool {
    settings
        .get("hooks")
        .and_then(|h| h.get("SessionStart"))
        .and_then(|s| s.as_array())
        .map(|groups| {
            groups.iter().any(|group| {
                group
                    .get("hooks")
                    .and_then(|inner| inner.as_array())
                    .map(|hooks| {
                        hooks.iter().any(|h| {
                            h.get("command")
                                .and_then(|c| c.as_str())
                                .map(|s| s.contains(SESSION_HOOK_MARKER))
                                .unwrap_or(false)
                        })
                    })
                    .unwrap_or(false)
            })
        })
        .unwrap_or(false)
}

fn check_project_scope(project_dir: &Path) -> Value {
    let scope_path = project_dir.join(".memd").join("project_scope.json");
    if !scope_path.exists() {
        return json!({
            "ok": false,
            "path": scope_path.display().to_string(),
            "reason": "no project scope (will be auto-created on next session-start)",
        });
    }
    let text = std::fs::read_to_string(&scope_path).unwrap_or_default();
    let parsed: Option<Value> = serde_json::from_str(&text).ok();
    let Some(parsed) = parsed else {
        return json!({
            "ok": false,
            "path": scope_path.display().to_string(),
            "reason": "malformed JSON",
        });
    };
    json!({
        "ok": true,
        "path": scope_path.display().to_string(),
        "tenant_id": parsed.get("tenant_id"),
        "project_id": parsed.get("project_id"),
    })
}

async fn enrich_project_scope_memory<S: Store>(store: &S, project_scope: &mut Value) {
    let Some(scope) = project_scope.as_object_mut() else {
        return;
    };
    if !scope
        .get("ok")
        .and_then(|value| value.as_bool())
        .unwrap_or(false)
    {
        return;
    }

    let tenant_id = scope
        .get("tenant_id")
        .and_then(|value| value.as_str())
        .unwrap_or_default();
    let project_id = scope.get("project_id").and_then(|value| value.as_str());
    let Some(project_id) = project_id.filter(|value| !value.trim().is_empty()) else {
        return;
    };
    let Ok(tenant) = TenantId::new(tenant_id) else {
        scope.insert(
            "memory".to_string(),
            json!({"ok": false, "reason": "invalid tenant_id in project scope"}),
        );
        return;
    };

    let counts = match project_counts_for_tenant(store, &tenant).await {
        Ok(counts) => counts,
        Err(err) => {
            scope.insert(
                "memory".to_string(),
                json!({"ok": false, "reason": format!("could not inspect project memory: {err}")}),
            );
            return;
        }
    };
    let configured_chunks = counts
        .iter()
        .find_map(|(candidate, count)| (candidate.as_deref() == Some(project_id)).then_some(*count))
        .unwrap_or(0);
    let normalized = normalize_project_id_for_drift(project_id);
    let similar = counts
        .into_iter()
        .filter_map(|(candidate, count)| {
            let candidate = candidate?;
            if candidate == project_id {
                return None;
            }
            if normalize_project_id_for_drift(&candidate) != normalized {
                return None;
            }
            Some(json!({
                "project_id": candidate,
                "active_chunks": count,
                "normalized_id": normalized,
            }))
        })
        .collect::<Vec<_>>();
    let dominant_similar_chunks = similar
        .iter()
        .filter_map(|entry| entry.get("active_chunks").and_then(|value| value.as_u64()))
        .max()
        .unwrap_or(0) as usize;

    let mut memory = json!({
        "ok": true,
        "configured_project_active_chunks": configured_chunks,
        "similar_project_ids": similar,
    });
    let has_similar_project_ids = !memory["similar_project_ids"]
        .as_array()
        .map(Vec::is_empty)
        .unwrap_or(true);
    let similar_dominates_configured = dominant_similar_chunks >= PROJECT_DRIFT_MIN_DOMINANT_CHUNKS
        && dominant_similar_chunks
            > configured_chunks.saturating_mul(PROJECT_DRIFT_DOMINANCE_RATIO);
    if has_similar_project_ids
        && (configured_chunks <= PROJECT_DRIFT_LOW_CHUNK_THRESHOLD || similar_dominates_configured)
    {
        let variants = memory["similar_project_ids"]
            .as_array()
            .into_iter()
            .flatten()
            .filter_map(|entry| entry.get("project_id").and_then(|value| value.as_str()))
            .collect::<Vec<_>>()
            .join(", ");
        memory["ok"] = json!(false);
        memory["warning"] = json!(format!(
            "configured project_id `{project_id}` has {configured_chunks} active chunks, but similar project_id(s) exist: {variants}"
        ));
        scope.insert("ok".to_string(), json!(false));
        scope.insert(
            "reason".to_string(),
            json!("configured project_id has little/no memory but similar project IDs exist"),
        );
    }
    scope.insert("memory".to_string(), memory);
}

async fn project_counts_for_tenant<S: Store>(
    store: &S,
    tenant: &TenantId,
) -> crate::error::Result<Vec<(Option<String>, usize)>> {
    if let Some(persistent) = store.as_persistent() {
        return persistent.metadata().project_counts(tenant, 1_000);
    }
    let scanned = scan_project_counts_for_tenant(store, tenant).await?;
    if !scanned.is_empty() {
        return Ok(scanned);
    }
    project_counts_from_default_metadata(tenant, 1_000)
}

async fn scan_project_counts_for_tenant<S: Store>(
    store: &S,
    tenant: &TenantId,
) -> crate::error::Result<Vec<(Option<String>, usize)>> {
    let mut counts = std::collections::BTreeMap::<Option<String>, usize>::new();
    let mut offset = 0usize;
    while offset < PROJECT_DRIFT_SCAN_LIMIT {
        let limit = PROJECT_DRIFT_PAGE_SIZE.min(PROJECT_DRIFT_SCAN_LIMIT - offset);
        let chunks = store.list_chunks(tenant, limit, offset).await?;
        if chunks.is_empty() {
            break;
        }
        offset = offset.saturating_add(limit);
        for chunk in chunks {
            *counts
                .entry(chunk.project_id.as_option().map(str::to_string))
                .or_insert(0) += 1;
        }
    }
    Ok(counts.into_iter().collect())
}

fn project_counts_from_default_metadata(
    tenant: &TenantId,
    limit: usize,
) -> crate::error::Result<Vec<(Option<String>, usize)>> {
    if limit == 0 {
        return Ok(Vec::new());
    }
    let Some(path) =
        dirs::home_dir().map(|home| home.join(".memd").join("data").join("metadata.db"))
    else {
        return Ok(Vec::new());
    };
    if !path.exists() {
        return Ok(Vec::new());
    }

    let conn =
        rusqlite::Connection::open_with_flags(path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)?;
    let mut stmt = conn.prepare(
        "SELECT project_id, COUNT(*) AS active_chunks
         FROM chunks
         WHERE tenant_id = ?1 AND status != 'deleted'
         GROUP BY project_id
         ORDER BY active_chunks DESC
         LIMIT ?2",
    )?;
    let rows = stmt.query_map(rusqlite::params![tenant.as_str(), limit as i64], |row| {
        let project_id: Option<String> = row.get(0)?;
        let count: i64 = row.get(1)?;
        Ok((project_id, count.max(0) as usize))
    })?;

    let mut results = Vec::new();
    for row in rows {
        results.push(row?);
    }
    Ok(results)
}

fn normalize_project_id_for_drift(project_id: &str) -> String {
    project_id
        .chars()
        .filter(|ch| ch.is_ascii_alphanumeric())
        .flat_map(|ch| ch.to_lowercase())
        .collect()
}

fn home_path(suffix: &str) -> Option<PathBuf> {
    dirs::home_dir().map(|h| h.join(suffix))
}

/// Render a human-readable report. One line per check; `[ok]` /
/// `[--]` prefixes are stable so users can grep them.
fn render_text(report: &Value) -> String {
    let mut out = String::new();
    out.push_str("memd doctor\n");
    out.push_str("===========\n");

    push_line(&mut out, "binary on PATH", &report["binary"], |v| {
        let on_path = v
            .get("on_path")
            .and_then(|p| p.as_str())
            .unwrap_or("not found");
        let current = v.get("current_exe").and_then(|p| p.as_str()).unwrap_or("?");
        let version = v.get("version").and_then(|p| p.as_str()).unwrap_or("?");
        format!("{on_path} (v{version}; current_exe={current})")
    });
    push_line(&mut out, "data dir", &report["data_dir"], |v| {
        format!(
            "{} ({} tenants)",
            v.get("path").and_then(|p| p.as_str()).unwrap_or("?"),
            v.get("tenant_count").and_then(|p| p.as_u64()).unwrap_or(0),
        )
    });
    let rules = &report["global_rules"];
    push_line(
        &mut out,
        "Claude CLAUDE.md",
        &rules["claude_md"],
        path_or_reason,
    );
    push_line(
        &mut out,
        "Codex AGENTS.md",
        &rules["codex_agents_md"],
        path_or_reason,
    );
    push_line(
        &mut out,
        "Cursor rule",
        &rules["cursor_rules_mdc"],
        path_or_reason,
    );
    push_line(
        &mut out,
        "Claude SessionStart hook",
        &report["session_start_hook"],
        path_or_reason,
    );
    push_line(&mut out, "project scope", &report["project_scope"], |v| {
        if v.get("ok").and_then(|b| b.as_bool()).unwrap_or(false) {
            let mut detail = format!(
                "tenant={} project={}",
                v.get("tenant_id").and_then(|p| p.as_str()).unwrap_or("?"),
                v.get("project_id").and_then(|p| p.as_str()).unwrap_or("?"),
            );
            if let Some(count) = v
                .get("memory")
                .and_then(|m| m.get("configured_project_active_chunks"))
                .and_then(|count| count.as_u64())
            {
                detail.push_str(&format!(" chunks={count}"));
            }
            detail
        } else if let Some(memory_warning) = v
            .get("memory")
            .and_then(|m| m.get("warning"))
            .and_then(|warning| warning.as_str())
        {
            memory_warning.to_string()
        } else {
            path_or_reason(v)
        }
    });

    out
}

fn path_or_reason(v: &Value) -> String {
    if let Some(reason) = v.get("reason").and_then(|r| r.as_str()) {
        return reason.to_string();
    }
    v.get("path")
        .and_then(|p| p.as_str())
        .unwrap_or("?")
        .to_string()
}

fn push_line<F: Fn(&Value) -> String>(out: &mut String, label: &str, v: &Value, detail: F) {
    let ok = v.get("ok").and_then(|b| b.as_bool()).unwrap_or(false);
    let tag = if ok { "[ok]" } else { "[--]" };
    out.push_str(&format!("{tag} {label}: {}\n", detail(v)));
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{ChunkType, MemoryChunk, MemoryStore, ProjectId, Store, TenantId};
    use tempfile::tempdir;

    #[test]
    fn report_includes_all_sections() {
        let dir = tempdir().unwrap();
        let report = collect_report(dir.path());
        for key in [
            "binary",
            "data_dir",
            "global_rules",
            "session_start_hook",
            "project_scope",
        ] {
            assert!(
                report.get(key).is_some(),
                "report missing key: {key} (got {report})"
            );
        }
        for key in ["claude_md", "codex_agents_md", "cursor_rules_mdc"] {
            assert!(
                report["global_rules"].get(key).is_some(),
                "global_rules missing key: {key}"
            );
        }
    }

    #[test]
    fn project_scope_reports_ok_for_valid_file() {
        let dir = tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join(".memd")).unwrap();
        std::fs::write(
            dir.path().join(".memd/project_scope.json"),
            r#"{"tenant_id":"alice","project_id":"demo"}"#,
        )
        .unwrap();
        let v = check_project_scope(dir.path());
        assert_eq!(v["ok"], true);
        assert_eq!(v["tenant_id"], "alice");
        assert_eq!(v["project_id"], "demo");
    }

    #[test]
    fn project_scope_reports_missing_with_helpful_reason() {
        let dir = tempdir().unwrap();
        let v = check_project_scope(dir.path());
        assert_eq!(v["ok"], false);
        let reason = v["reason"].as_str().unwrap_or("");
        assert!(reason.contains("auto-created"), "reason was: {reason}");
    }

    #[test]
    fn project_scope_reports_malformed_json() {
        let dir = tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join(".memd")).unwrap();
        std::fs::write(dir.path().join(".memd/project_scope.json"), "{not json").unwrap();
        let v = check_project_scope(dir.path());
        assert_eq!(v["ok"], false);
        assert_eq!(v["reason"], "malformed JSON");
    }

    #[test]
    fn project_id_drift_normalization_ignores_separators() {
        assert_eq!(
            normalize_project_id_for_drift("bester_hosting"),
            normalize_project_id_for_drift("bester-hosting")
        );
        assert_ne!(
            normalize_project_id_for_drift("bester_hosting"),
            normalize_project_id_for_drift("bester-hosting-old")
        );
    }

    #[tokio::test]
    async fn project_scope_warns_on_similar_project_id_with_no_memory() {
        let dir = tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join(".memd")).unwrap();
        std::fs::write(
            dir.path().join(".memd/project_scope.json"),
            r#"{"tenant_id":"fschulz","project_id":"bester_hosting"}"#,
        )
        .unwrap();
        let store = MemoryStore::new();
        let tenant = TenantId::new("fschulz").unwrap();
        store
            .add(
                MemoryChunk::new(
                    tenant,
                    "Useful gateway restore lesson under the hyphenated project id.",
                    ChunkType::Summary,
                )
                .with_project(ProjectId::from("bester-hosting")),
            )
            .await
            .unwrap();

        let mut v = check_project_scope(dir.path());
        enrich_project_scope_memory(&store, &mut v).await;

        assert_eq!(v["ok"], false);
        assert_eq!(
            v["reason"],
            "configured project_id has little/no memory but similar project IDs exist"
        );
        assert_eq!(v["memory"]["configured_project_active_chunks"], 0);
        assert_eq!(
            v["memory"]["similar_project_ids"][0]["project_id"],
            "bester-hosting"
        );
        assert!(v["memory"]["warning"]
            .as_str()
            .unwrap_or_default()
            .contains("bester_hosting"));
    }

    #[tokio::test]
    async fn project_scope_warns_when_similar_project_id_dominates_existing_memory() {
        let dir = tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join(".memd")).unwrap();
        std::fs::write(
            dir.path().join(".memd/project_scope.json"),
            r#"{"tenant_id":"fschulz","project_id":"bester_hosting"}"#,
        )
        .unwrap();
        let store = MemoryStore::new();
        let tenant = TenantId::new("fschulz").unwrap();
        for index in 0..8 {
            store
                .add(
                    MemoryChunk::new(
                        tenant.clone(),
                        format!("Low-volume underscore project record {index}."),
                        ChunkType::Summary,
                    )
                    .with_project(ProjectId::from("bester_hosting")),
                )
                .await
                .unwrap();
        }
        for index in 0..50 {
            store
                .add(
                    MemoryChunk::new(
                        tenant.clone(),
                        format!("Dominant hyphenated project record {index}."),
                        ChunkType::Summary,
                    )
                    .with_project(ProjectId::from("bester-hosting")),
                )
                .await
                .unwrap();
        }

        let mut v = check_project_scope(dir.path());
        enrich_project_scope_memory(&store, &mut v).await;

        assert_eq!(v["ok"], false);
        assert_eq!(v["memory"]["configured_project_active_chunks"], 8);
        assert_eq!(
            v["memory"]["similar_project_ids"][0]["project_id"],
            "bester-hosting"
        );
    }

    #[tokio::test]
    async fn project_scope_does_not_warn_for_unrelated_project_names() {
        let dir = tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join(".memd")).unwrap();
        std::fs::write(
            dir.path().join(".memd/project_scope.json"),
            r#"{"tenant_id":"fschulz","project_id":"bester_hosting"}"#,
        )
        .unwrap();
        let store = MemoryStore::new();
        let tenant = TenantId::new("fschulz").unwrap();
        store
            .add(
                MemoryChunk::new(tenant, "Unrelated memory.", ChunkType::Summary)
                    .with_project(ProjectId::from("bester-hosting-old")),
            )
            .await
            .unwrap();

        let mut v = check_project_scope(dir.path());
        enrich_project_scope_memory(&store, &mut v).await;

        assert_eq!(v["ok"], true);
        assert_eq!(v["memory"]["configured_project_active_chunks"], 0);
        assert_eq!(
            v["memory"]["similar_project_ids"].as_array().unwrap().len(),
            0
        );
    }

    #[test]
    fn render_text_emits_stable_ok_dash_prefixes() {
        let dir = tempdir().unwrap();
        let report = collect_report(dir.path());
        let text = render_text(&report);
        // Each check produces a single line; `[ok]` or `[--]` is the
        // grep contract for human consumers and screen-scrapers.
        let lines = text
            .lines()
            .filter(|l| l.starts_with("[ok]") || l.starts_with("[--]"))
            .count();
        assert_eq!(lines, 7, "expected 7 status lines, got:\n{text}");
    }

    #[test]
    fn session_start_hook_wired_detects_real_hook_shape() {
        let wired = json!({
            "hooks": {
                "SessionStart": [
                    {"hooks": [{"type": "command", "command": "memd session-start --project-dir ."}]}
                ]
            }
        });
        assert!(session_start_hook_wired(&wired));

        // String appears outside the SessionStart hook chain → not wired.
        let stale = json!({
            "comment": "old config used to have memd session-start",
            "hooks": {"PreToolUse": []}
        });
        assert!(!session_start_hook_wired(&stale));

        // SessionStart array present but no memd command in any inner hook.
        let unrelated = json!({
            "hooks": {
                "SessionStart": [
                    {"hooks": [{"type": "command", "command": "echo hello"}]}
                ]
            }
        });
        assert!(!session_start_hook_wired(&unrelated));

        // Empty settings shouldn't false-positive.
        assert!(!session_start_hook_wired(&json!({})));
    }

    #[test]
    fn check_binary_reports_path_discoverability_and_current_exe() {
        let v = check_binary();
        // Always present (Option may be null but key exists).
        assert!(v.get("current_exe").is_some());
        assert!(v.get("on_path").is_some());
        assert_eq!(v["version"], env!("CARGO_PKG_VERSION"));
        // `ok` reflects on_path, not current_exe.
        let expected_ok = v["on_path"].as_str().is_some();
        assert_eq!(v["ok"].as_bool().unwrap_or(false), expected_ok);
    }
}