Skip to main content

rustbrain_core/
doctor.rs

1//! Health checks for a project brain (`rustbrain doctor`).
2
3use crate::error::Result;
4use crate::query::PendingLink;
5use crate::storage::{Database, SCHEMA_VERSION};
6use crate::types::NodeType;
7use serde::{Deserialize, Serialize};
8use std::path::{Path, PathBuf};
9
10/// Severity of a doctor finding.
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
12#[serde(rename_all = "snake_case")]
13pub enum DoctorSeverity {
14    /// Informational.
15    Info,
16    /// Should be fixed soon.
17    Warn,
18    /// Broken or unusable state.
19    Error,
20}
21
22/// One line of doctor output.
23#[derive(Debug, Clone, Serialize, Deserialize)]
24pub struct DoctorFinding {
25    /// Severity.
26    pub severity: DoctorSeverity,
27    /// Stable machine code (e.g. `pending_links`).
28    pub code: String,
29    /// Human message.
30    pub message: String,
31}
32
33/// Full doctor report.
34#[derive(Debug, Clone, Serialize, Deserialize)]
35pub struct DoctorReport {
36    /// Workspace path examined.
37    pub workspace: PathBuf,
38    /// Brain directory.
39    pub brain_dir: PathBuf,
40    /// Whether `db.sqlite` exists.
41    pub db_exists: bool,
42    /// Whether `graph.mmap` exists.
43    pub mmap_exists: bool,
44    /// Schema version if readable.
45    pub schema_version: Option<u32>,
46    /// Total nodes.
47    pub nodes: usize,
48    /// Total edges.
49    pub edges: usize,
50    /// FTS rows.
51    pub fts_rows: usize,
52    /// Pending links.
53    pub pending_links: usize,
54    /// Symbol anchors.
55    pub symbol_anchors: usize,
56    /// Notes with no **explicit** edges (auto-links ignored).
57    pub orphan_notes: usize,
58    /// Breakdown by node type.
59    pub by_type: Vec<(String, usize)>,
60    /// Pending link samples (up to 50).
61    pub pending: Vec<PendingLink>,
62    /// Detailed orphan list when [`DoctorOptions::detail_orphans`] is set.
63    #[serde(default, skip_serializing_if = "Vec::is_empty")]
64    pub orphan_details: Vec<crate::autolink::OrphanNote>,
65    /// Findings.
66    pub findings: Vec<DoctorFinding>,
67    /// True when any finding is Error (or pending policy fail).
68    pub healthy: bool,
69}
70
71/// Options for [`run_doctor_with`].
72#[derive(Debug, Clone, Default)]
73pub struct DoctorOptions {
74    /// Include full orphan list + suggestions in the report.
75    pub detail_orphans: bool,
76}
77
78/// Run doctor against a workspace (opens DB if present).
79///
80/// Walks parent directories for `.brain/db.sqlite` (same as [`crate::Brain::open`]).
81pub fn run_doctor(workspace: &Path) -> Result<DoctorReport> {
82    run_doctor_with(workspace, &DoctorOptions::default())
83}
84
85/// Doctor with options (e.g. detailed orphan analysis).
86pub fn run_doctor_with(workspace: &Path, opts: &DoctorOptions) -> Result<DoctorReport> {
87    let start = workspace
88        .canonicalize()
89        .unwrap_or_else(|_| workspace.to_path_buf());
90
91    let (workspace, brain_dir) = if let Some(found) = crate::brain::find_brain_dir(&start) {
92        found
93    } else {
94        let brain_dir = start.join(".brain");
95        let mut findings = Vec::new();
96        findings.push(DoctorFinding {
97            severity: DoctorSeverity::Error,
98            code: "no_db".into(),
99            message: format!(
100                "no database at {} or parents — run `rustbrain setup --yes`",
101                brain_dir.display()
102            ),
103        });
104        return Ok(DoctorReport {
105            workspace: start,
106            brain_dir,
107            db_exists: false,
108            mmap_exists: false,
109            schema_version: None,
110            nodes: 0,
111            edges: 0,
112            fts_rows: 0,
113            pending_links: 0,
114            symbol_anchors: 0,
115            orphan_notes: 0,
116            by_type: vec![],
117            pending: vec![],
118            orphan_details: vec![],
119            healthy: false,
120            findings,
121        });
122    };
123
124    let db_path = brain_dir.join("db.sqlite");
125    let mmap_path = brain_dir.join("graph.mmap");
126    let mut findings = Vec::new();
127    let mmap_exists = mmap_path.is_file();
128
129    let db = Database::open(&db_path)?;
130    let nodes = db.count_nodes()?;
131    let edges = db.count_edges()?;
132    let fts_rows = db.count_fts_rows()?;
133    let pending_links = db.count_pending_links()?;
134    let symbol_anchors = db.count_symbol_anchors()?;
135    let by_type = db.count_nodes_by_type()?;
136    let pending = db.list_pending_links()?;
137    let schema_version = Some(SCHEMA_VERSION);
138
139    if !mmap_exists {
140        findings.push(DoctorFinding {
141            severity: DoctorSeverity::Warn,
142            code: "no_mmap".into(),
143            message: "graph.mmap missing — run `rustbrain sync` to bake CSR cache".into(),
144        });
145    }
146
147    if nodes == 0 {
148        findings.push(DoctorFinding {
149            severity: DoctorSeverity::Warn,
150            code: "empty_brain".into(),
151            message: "brain has zero nodes — add docs/ notes or run `rustbrain bootstrap --write` then sync"
152                .into(),
153        });
154    }
155
156    let note_count: usize = by_type
157        .iter()
158        .filter(|(t, _)| t != "symbol")
159        .map(|(_, c)| c)
160        .sum();
161    let symbol_count = by_type
162        .iter()
163        .find(|(t, _)| t == "symbol")
164        .map(|(_, c)| *c)
165        .unwrap_or(0);
166
167    if note_count == 0 && symbol_count > 0 {
168        findings.push(DoctorFinding {
169            severity: DoctorSeverity::Warn,
170            code: "symbols_only".into(),
171            message: format!(
172                "brain has {symbol_count} symbols but no notes — bootstrap or write Markdown under docs/"
173            ),
174        });
175    } else if note_count > 0 && symbol_count > note_count.saturating_mul(20) {
176        findings.push(DoctorFinding {
177            severity: DoctorSeverity::Info,
178            code: "symbol_flood".into(),
179            message: format!(
180                "symbol/note ratio high ({symbol_count} symbols / {note_count} notes) — default `query` is note-first; use `--with-symbols` when you need code"
181            ),
182        });
183    }
184
185    if pending_links > 0 {
186        findings.push(DoctorFinding {
187            severity: DoctorSeverity::Warn,
188            code: "pending_links".into(),
189            message: format!(
190                "{pending_links} unresolved WikiLink/symbol refs — `rustbrain links` to list; `links --apply --dry-run` if targets now exist; else create notes or fix links"
191            ),
192        });
193    }
194
195    if fts_rows != note_count + symbol_count && fts_rows != nodes {
196        // Soft check: FTS should track indexed content nodes
197        if fts_rows == 0 && nodes > 0 {
198            findings.push(DoctorFinding {
199                severity: DoctorSeverity::Error,
200                code: "fts_empty".into(),
201                message: "nodes exist but FTS is empty — re-run `rustbrain sync`".into(),
202            });
203        }
204    }
205
206    if !workspace.join("docs").is_dir() {
207        findings.push(DoctorFinding {
208            severity: DoctorSeverity::Info,
209            code: "no_docs_dir".into(),
210            message: "no docs/ directory — `rustbrain bootstrap --write` can scaffold one".into(),
211        });
212    }
213
214    let ignore = workspace.join(".rustbrainignore");
215    if !ignore.is_file() {
216        findings.push(DoctorFinding {
217            severity: DoctorSeverity::Info,
218            code: "no_ignore".into(),
219            message: "no .rustbrainignore — bootstrap can create one from .gitignore defaults"
220                .into(),
221        });
222    }
223
224    // --- README / harvest / knowledge density (info-level; never invent content) ---
225    assess_readme_and_harvest(&workspace, &db, &mut findings)?;
226    assess_changelog(&workspace, &db, &mut findings)?;
227    assess_knowledge_density(&workspace, &db, note_count, symbol_count, &mut findings)?;
228
229    let has_goal = by_type.iter().any(|(t, c)| t == NodeType::Goal.as_str() && *c > 0);
230    if nodes > 0 && !has_goal {
231        findings.push(DoctorFinding {
232            severity: DoctorSeverity::Info,
233            code: "no_goals".into(),
234            message: "no goal nodes yet — consider docs/goals/ or bootstrap from README".into(),
235        });
236    }
237
238    // ADR quality: TEMPLATE alone is not a real decision record.
239    let adr_ids = db.list_node_ids_by_type(NodeType::Adr.as_str())?;
240    let real_adrs = adr_ids
241        .iter()
242        .filter(|id| !id.to_lowercase().contains("template"))
243        .count();
244    if !adr_ids.is_empty() && real_adrs == 0 {
245        findings.push(DoctorFinding {
246            severity: DoctorSeverity::Info,
247            code: "adr_template_only".into(),
248            message: "only ADR template present — write real decisions under docs/adr/ (or `note new --type adr`)"
249                .into(),
250        });
251    } else if adr_ids.is_empty() && note_count > 0 {
252        findings.push(DoctorFinding {
253            severity: DoctorSeverity::Info,
254            code: "no_adrs".into(),
255            message: "no ADR notes yet — capture decisions with `rustbrain note new --type adr --title … --note …`"
256                .into(),
257        });
258    }
259
260    if !workspace.join("AGENTS.md").is_file() && nodes > 0 {
261        findings.push(DoctorFinding {
262            severity: DoctorSeverity::Info,
263            code: "no_agents_md".into(),
264            message: "no AGENTS.md — `rustbrain bootstrap --yes --write` can add the agent cookbook (or --no-agents-md to skip intentionally)"
265                .into(),
266        });
267    }
268
269    let orphan_list = crate::autolink::list_orphan_notes(&db)?;
270    let orphan_notes = orphan_list.len();
271    if orphan_notes > 0 {
272        findings.push(DoctorFinding {
273            severity: DoctorSeverity::Info,
274            code: "orphan_notes".into(),
275            message: format!(
276                "{orphan_notes} orphan note(s) (no explicit links) — run `rustbrain doctor --orphans` for details, or `rustbrain links --auto` to create soft auto-links"
277            ),
278        });
279    }
280
281    let orphan_details = if opts.detail_orphans {
282        orphan_list
283    } else {
284        vec![]
285    };
286
287    let healthy = !findings
288        .iter()
289        .any(|f| f.severity == DoctorSeverity::Error);
290
291    // "ok" only when nothing else to report (knowledge infos replace a bare ok).
292    if healthy && findings.is_empty() {
293        findings.push(DoctorFinding {
294            severity: DoctorSeverity::Info,
295            code: "ok".into(),
296            message: "brain looks healthy".into(),
297        });
298    }
299
300    Ok(DoctorReport {
301        workspace,
302        brain_dir,
303        db_exists: true,
304        mmap_exists,
305        schema_version,
306        nodes,
307        edges,
308        fts_rows,
309        pending_links,
310        symbol_anchors,
311        orphan_notes,
312        by_type,
313        pending,
314        orphan_details,
315        findings,
316        healthy,
317    })
318}
319
320/// Rough non-whitespace content length (chars).
321fn content_mass(s: &str) -> usize {
322    s.chars().filter(|c| !c.is_whitespace()).count()
323}
324
325/// Body-ish mass: strip common YAML frontmatter then count.
326fn body_mass(s: &str) -> usize {
327    let t = s.trim_start();
328    let body = if let Some(rest) = t.strip_prefix("---") {
329        if let Some(idx) = rest.find("\n---") {
330            rest[idx + 4..].trim()
331        } else {
332            t
333        }
334    } else {
335        t
336    };
337    content_mass(body)
338}
339
340fn file_body_mass(path: &Path) -> Option<usize> {
341    let text = std::fs::read_to_string(path).ok()?;
342    Some(body_mass(&text))
343}
344
345/// README / from-readme harvest quality (informational only).
346fn assess_readme_and_harvest(
347    workspace: &Path,
348    db: &Database,
349    findings: &mut Vec<DoctorFinding>,
350) -> Result<()> {
351    let readme_path = workspace.join("README.md");
352    let from_readme_path = workspace.join("docs/goals/from-readme.md");
353
354    if !readme_path.is_file() {
355        findings.push(DoctorFinding {
356            severity: DoctorSeverity::Info,
357            code: "no_readme".into(),
358            message: "no root README.md — bootstrap cannot harvest goals; context relies on docs/ notes, module map, and symbols. Optional: add a short README then `bootstrap --force` + sync"
359                .into(),
360        });
361        if !from_readme_path.is_file() {
362            findings.push(DoctorFinding {
363                severity: DoctorSeverity::Info,
364                code: "no_from_readme".into(),
365                message: "no docs/goals/from-readme.md (expected without README) — write goals under docs/goals/ or add README.md"
366                    .into(),
367            });
368        }
369        return Ok(());
370    }
371
372    // README present
373    let readme_text = std::fs::read_to_string(&readme_path).unwrap_or_default();
374    let readme_mass = body_mass(&readme_text);
375    let content_lines = readme_text
376        .lines()
377        .filter(|l| {
378            let t = l.trim();
379            !t.is_empty() && !t.starts_with('#')
380        })
381        .count();
382
383    // Sparse: very little prose (not a hard error — many valid tiny READMEs exist).
384    const SPARSE_MASS: usize = 120;
385    const SPARSE_LINES: usize = 3;
386    if readme_mass < SPARSE_MASS || content_lines < SPARSE_LINES {
387        findings.push(DoctorFinding {
388            severity: DoctorSeverity::Info,
389            code: "sparse_readme".into(),
390            message: format!(
391                "README.md is thin (~{readme_mass} non-ws chars, {content_lines} content lines) — from-readme harvest will mirror that; enrich README or write real docs/goals and ADRs for better context"
392            ),
393        });
394    }
395
396    if db.get_node("readme")?.is_none() {
397        findings.push(DoctorFinding {
398            severity: DoctorSeverity::Info,
399            code: "readme_not_indexed".into(),
400            message: "README.md exists but hub node `readme` missing — run `rustbrain sync`".into(),
401        });
402    }
403
404    if from_readme_path.is_file() {
405        let mass = file_body_mass(&from_readme_path).unwrap_or(0);
406        // Subtract typical boilerplate header roughly by threshold on body.
407        if mass < 180 {
408            findings.push(DoctorFinding {
409                severity: DoctorSeverity::Info,
410                code: "thin_from_readme".into(),
411                message: format!(
412                    "docs/goals/from-readme.md is thin (~{mass} non-ws chars) — harvest only copies README sections; expand README (Why/Features) or add hand-written goals/ADRs"
413                ),
414            });
415        }
416    } else if readme_mass >= SPARSE_MASS {
417        findings.push(DoctorFinding {
418            severity: DoctorSeverity::Info,
419            code: "no_from_readme".into(),
420            message: "README.md present but no docs/goals/from-readme.md — run `rustbrain bootstrap --yes --write` (or --force) then sync"
421                .into(),
422        });
423    }
424
425    Ok(())
426}
427
428/// Keep a Changelog / SemVer habit (Rust community standard for published crates).
429///
430/// Info-level only: absence is normal for apps and private tools; presence should
431/// be indexed as hub node `changelog` after sync.
432fn assess_changelog(
433    workspace: &Path,
434    db: &Database,
435    findings: &mut Vec<DoctorFinding>,
436) -> Result<()> {
437    let candidates = ["CHANGELOG.md", "CHANGES.md", "HISTORY.md"];
438    let path = candidates
439        .iter()
440        .map(|n| workspace.join(n))
441        .find(|p| p.is_file());
442
443    let Some(path) = path else {
444        // Soft suggestion for library-shaped trees (Cargo.toml present).
445        if workspace.join("Cargo.toml").is_file() {
446            findings.push(DoctorFinding {
447                severity: DoctorSeverity::Info,
448                code: "no_changelog".into(),
449                message: "no root CHANGELOG.md — Rust/crates.io convention is Keep a Changelog + SemVer; when present, rustbrain indexes it as hub `changelog` for release/status context. Optional for apps"
450                    .into(),
451            });
452        }
453        return Ok(());
454    };
455
456    let text = std::fs::read_to_string(&path).unwrap_or_default();
457    let mass = body_mass(&text);
458    let has_version_heading = text.lines().any(|l| {
459        let t = l.trim();
460        t.starts_with("## [") || t.starts_with("##[") || t.eq_ignore_ascii_case("## unreleased")
461    });
462
463    if mass < 80 {
464        findings.push(DoctorFinding {
465            severity: DoctorSeverity::Info,
466            code: "sparse_changelog".into(),
467            message: format!(
468                "{} is thin (~{mass} non-ws chars) — release context will be weak until you record shipped changes",
469                path.file_name().and_then(|n| n.to_str()).unwrap_or("CHANGELOG.md")
470            ),
471        });
472    } else if !has_version_heading {
473        findings.push(DoctorFinding {
474            severity: DoctorSeverity::Info,
475            code: "changelog_no_versions".into(),
476            message: "CHANGELOG present but no `## [x.y.z]` / Unreleased headings detected — Keep a Changelog format improves FTS and hub summaries"
477                .into(),
478        });
479    }
480
481    if db.get_node(crate::hubs::HUB_CHANGELOG)?.is_none() {
482        findings.push(DoctorFinding {
483            severity: DoctorSeverity::Info,
484            code: "changelog_not_indexed".into(),
485            message: "CHANGELOG.md exists but hub node `changelog` missing — run `rustbrain sync`"
486                .into(),
487        });
488    } else if let Some(node) = db.get_node(crate::hubs::HUB_CHANGELOG)? {
489        if let Some(sum) = &node.summary {
490            if !sum.is_empty() {
491                findings.push(DoctorFinding {
492                    severity: DoctorSeverity::Info,
493                    code: "changelog_latest".into(),
494                    message: format!("changelog hub indexed; latest section summary: {sum}"),
495                });
496            }
497        }
498    }
499
500    Ok(())
501}
502
503/// Detect bootstrap-scaffold-only brains vs hand-written knowledge.
504fn assess_knowledge_density(
505    workspace: &Path,
506    db: &Database,
507    note_count: usize,
508    symbol_count: usize,
509    findings: &mut Vec<DoctorFinding>,
510) -> Result<()> {
511    if note_count == 0 {
512        return Ok(());
513    }
514
515    // Collect note ids that look like hand-written project knowledge.
516    let mut substantive = 0usize;
517    let mut scaffoldish = 0usize;
518
519    for ty in [
520        NodeType::Goal,
521        NodeType::Adr,
522        NodeType::Concept,
523        NodeType::Analysis,
524        NodeType::EdgeCase,
525        NodeType::Reference,
526        NodeType::Alternative,
527        NodeType::Changelog,
528        NodeType::Plan,
529    ] {
530        let ids = db.list_node_ids_by_type(ty.as_str())?;
531        for id in ids {
532            if is_hard_scaffold_id(&id) {
533                scaffoldish += 1;
534                continue;
535            }
536            let mass = note_body_mass(workspace, db, &id)?;
537            // Rich README harvest counts as useful knowledge (still generated, but real prose).
538            if id_is_from_readme(&id) {
539                if mass >= 200 {
540                    substantive += 1;
541                } else {
542                    scaffoldish += 1;
543                }
544                continue;
545            }
546            if mass >= 80 {
547                substantive += 1;
548            } else {
549                scaffoldish += 1;
550            }
551        }
552    }
553
554    if substantive == 0 && (scaffoldish > 0 || symbol_count > 0) {
555        findings.push(DoctorFinding {
556            severity: DoctorSeverity::Info,
557            code: "scaffold_only".into(),
558            message: format!(
559                "notes look bootstrap-scaffold only (stubs/templates/thin harvest); no substantial goals/ADRs/concepts yet — use `note new` or edit docs/; symbols={symbol_count}"
560            ),
561        });
562    } else if substantive > 0 && symbol_count > substantive.saturating_mul(30) {
563        findings.push(DoctorFinding {
564            severity: DoctorSeverity::Info,
565            code: "knowledge_thin".into(),
566            message: format!(
567                "few substantial notes ({substantive}) vs many symbols ({symbol_count}) — context for *why* may be thin; capture decisions as ADRs"
568            ),
569        });
570    }
571
572    let _ = scaffoldish;
573    Ok(())
574}
575
576fn note_body_mass(workspace: &Path, db: &Database, id: &str) -> Result<usize> {
577    if let Some(c) = db.get_fts_content(id)? {
578        let m = body_mass(&c);
579        if m > 0 {
580            return Ok(m);
581        }
582    }
583    if let Some(node) = db.get_node(id)? {
584        if let Some(path) = node.file_path.as_ref() {
585            return Ok(file_body_mass(&workspace.join(path)).unwrap_or(0));
586        }
587    }
588    Ok(0)
589}
590
591fn id_is_from_readme(id: &str) -> bool {
592    let id = id.to_lowercase();
593    id == "docs/goals/from-readme" || id.contains("from-readme")
594}
595
596/// Pure scaffold: never counts as project knowledge by itself.
597fn is_hard_scaffold_id(id: &str) -> bool {
598    let id = id.to_lowercase();
599    id.contains("template")
600        || id == "docs/goals/readme"
601        || id.ends_with("bootstrap_checklist")
602        || id.contains("bootstrap-checklist")
603        || id.contains("bootstrap_checklist")
604        || id.contains("module-map.generated")
605        || id == "agents"
606        || id.ends_with("/agents")
607        || id == "readme" // root hub is inventory, not a decision record
608}
609
610impl DoctorReport {
611    /// Render a human-readable multi-line report.
612    pub fn to_text(&self) -> String {
613        let mut out = String::new();
614        out.push_str(&format!("rustbrain doctor — {}\n", self.workspace.display()));
615        out.push_str(&format!(
616            "  db: {}  mmap: {}  schema: {}\n",
617            if self.db_exists { "yes" } else { "NO" },
618            if self.mmap_exists { "yes" } else { "no" },
619            self.schema_version
620                .map(|v| v.to_string())
621                .unwrap_or_else(|| "-".into())
622        ));
623        out.push_str(&format!(
624            "  nodes={} edges={} fts={} pending={} symbols={}",
625            self.nodes, self.edges, self.fts_rows, self.pending_links, self.symbol_anchors
626        ));
627        if self.orphan_notes > 0 {
628            out.push_str(&format!(" orphans={}", self.orphan_notes));
629        }
630        out.push('\n');
631        if !self.by_type.is_empty() {
632            out.push_str("  by type: ");
633            let parts: Vec<_> = self
634                .by_type
635                .iter()
636                .map(|(t, c)| format!("{t}={c}"))
637                .collect();
638            out.push_str(&parts.join(" "));
639            out.push('\n');
640        }
641        out.push_str("\nfindings:\n");
642        for f in &self.findings {
643            let tag = match f.severity {
644                DoctorSeverity::Info => "info",
645                DoctorSeverity::Warn => "WARN",
646                DoctorSeverity::Error => "ERR ",
647            };
648            out.push_str(&format!("  [{tag}] {}: {}\n", f.code, f.message));
649        }
650        if !self.orphan_details.is_empty() {
651            out.push_str("\norphan notes (no explicit WikiLink/symbol edges; auto-links ignored):\n");
652            for o in &self.orphan_details {
653                let path = o.file_path.as_deref().unwrap_or("-");
654                out.push_str(&format!(
655                    "  • [{}] {} (id: {})\n    path: {}\n",
656                    o.node_type, o.title, o.id, path
657                ));
658                if o.suggestions.is_empty() {
659                    out.push_str("    suggestions: (none — add tags, matching filenames, or WikiLinks)\n");
660                } else {
661                    out.push_str("    suggestions:\n");
662                    for s in o.suggestions.iter().take(8) {
663                        let tp = s.target_path.as_deref().unwrap_or("-");
664                        out.push_str(&format!(
665                            "      - [{} w={:.2}] {} → {} ({})\n",
666                            s.relation_type, s.weight, s.reason, s.target_id, tp
667                        ));
668                    }
669                }
670            }
671            out.push_str(
672                "\n  apply soft links: `rustbrain links --auto`\n  one file: `rustbrain links --auto docs/goals/foo.md`\n",
673            );
674        }
675        if !self.pending.is_empty() {
676            out.push_str("\npending links (up to 50):\n");
677            for p in self.pending.iter().take(50) {
678                out.push_str(&format!(
679                    "  {} -[{}]-> {}\n",
680                    p.source_id, p.relation_type, p.raw_target
681                ));
682            }
683        }
684        out.push_str(&format!(
685            "\nstatus: {}\n",
686            if self.healthy { "OK" } else { "UNHEALTHY" }
687        ));
688        out
689    }
690}
691
692#[cfg(test)]
693mod tests {
694    use super::*;
695    use crate::brain::Brain;
696    use tempfile::tempdir;
697
698    #[test]
699    fn doctor_empty_workspace() {
700        let dir = tempdir().unwrap();
701        let report = run_doctor(dir.path()).unwrap();
702        assert!(!report.healthy);
703        assert!(report.findings.iter().any(|f| f.code == "no_db"));
704    }
705
706    #[test]
707    fn doctor_after_init_sync() {
708        let dir = tempdir().unwrap();
709        let docs = dir.path().join("docs");
710        std::fs::create_dir_all(&docs).unwrap();
711        std::fs::write(
712            docs.join("a.md"),
713            "---\nnode_type: concept\n---\n# A\nHello.\n",
714        )
715        .unwrap();
716        let mut brain = Brain::create(dir.path()).unwrap();
717        brain.sync().unwrap();
718        let report = run_doctor(dir.path()).unwrap();
719        assert!(report.db_exists);
720        assert!(report.nodes >= 1);
721        assert!(report.healthy || report.findings.iter().all(|f| f.severity != DoctorSeverity::Error));
722    }
723
724    #[test]
725    fn doctor_walks_parent_for_brain() {
726        let dir = tempdir().unwrap();
727        let root = dir.path();
728        let sub = root.join("src").join("nested");
729        std::fs::create_dir_all(&sub).unwrap();
730        let mut brain = Brain::create(root).unwrap();
731        brain.sync().unwrap();
732        let report = run_doctor(&sub).unwrap();
733        assert!(report.db_exists, "doctor should find parent .brain");
734        assert_eq!(
735            report.workspace.canonicalize().unwrap(),
736            root.canonicalize().unwrap()
737        );
738    }
739
740    #[test]
741    fn doctor_reports_no_readme() {
742        let dir = tempdir().unwrap();
743        let mut brain = Brain::create(dir.path()).unwrap();
744        brain.sync().unwrap();
745        let report = run_doctor(dir.path()).unwrap();
746        assert!(
747            report.findings.iter().any(|f| f.code == "no_readme"),
748            "findings={:?}",
749            report.findings
750        );
751        assert!(report.healthy);
752    }
753
754    #[test]
755    fn doctor_reports_sparse_readme() {
756        let dir = tempdir().unwrap();
757        std::fs::write(dir.path().join("README.md"), "# x\n\ntodo\n").unwrap();
758        let mut brain = Brain::create(dir.path()).unwrap();
759        brain.sync().unwrap();
760        let report = run_doctor(dir.path()).unwrap();
761        assert!(
762            report.findings.iter().any(|f| f.code == "sparse_readme"),
763            "findings={:?}",
764            report.findings
765        );
766    }
767
768    #[test]
769    fn doctor_counts_orphans_and_details() {
770        let dir = tempdir().unwrap();
771        std::fs::create_dir_all(dir.path().join("docs/concepts")).unwrap();
772        std::fs::write(
773            dir.path().join("docs/concepts/lonely.md"),
774            "---\nnode_type: concept\n---\n# Lonely\n\nNo links here.\n",
775        )
776        .unwrap();
777        let mut brain = Brain::create(dir.path()).unwrap();
778        brain.sync().unwrap();
779        let report = run_doctor(dir.path()).unwrap();
780        assert!(report.orphan_notes >= 1, "orphan_notes={}", report.orphan_notes);
781        assert!(report.findings.iter().any(|f| f.code == "orphan_notes"));
782
783        let detailed = run_doctor_with(
784            dir.path(),
785            &DoctorOptions {
786                detail_orphans: true,
787            },
788        )
789        .unwrap();
790        assert!(!detailed.orphan_details.is_empty());
791        assert!(detailed
792            .orphan_details
793            .iter()
794            .any(|o| o.id.contains("lonely")));
795    }
796
797    #[test]
798    fn doctor_scaffold_only_after_empty_bootstrap_ish() {
799        let dir = tempdir().unwrap();
800        // Minimal notes that look like stubs
801        std::fs::create_dir_all(dir.path().join("docs/adr")).unwrap();
802        std::fs::write(
803            dir.path().join("docs/adr/TEMPLATE.md"),
804            "---\nnode_type: adr\n---\n# ADR template\n\nProposed\n",
805        )
806        .unwrap();
807        let mut brain = Brain::create(dir.path()).unwrap();
808        brain.sync().unwrap();
809        let report = run_doctor(dir.path()).unwrap();
810        assert!(
811            report
812                .findings
813                .iter()
814                .any(|f| f.code == "scaffold_only" || f.code == "adr_template_only"),
815            "findings={:?}",
816            report.findings
817        );
818    }
819}