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    ] {
528        let ids = db.list_node_ids_by_type(ty.as_str())?;
529        for id in ids {
530            if is_hard_scaffold_id(&id) {
531                scaffoldish += 1;
532                continue;
533            }
534            let mass = note_body_mass(workspace, db, &id)?;
535            // Rich README harvest counts as useful knowledge (still generated, but real prose).
536            if id_is_from_readme(&id) {
537                if mass >= 200 {
538                    substantive += 1;
539                } else {
540                    scaffoldish += 1;
541                }
542                continue;
543            }
544            if mass >= 80 {
545                substantive += 1;
546            } else {
547                scaffoldish += 1;
548            }
549        }
550    }
551
552    if substantive == 0 && (scaffoldish > 0 || symbol_count > 0) {
553        findings.push(DoctorFinding {
554            severity: DoctorSeverity::Info,
555            code: "scaffold_only".into(),
556            message: format!(
557                "notes look bootstrap-scaffold only (stubs/templates/thin harvest); no substantial goals/ADRs/concepts yet — use `note new` or edit docs/; symbols={symbol_count}"
558            ),
559        });
560    } else if substantive > 0 && symbol_count > substantive.saturating_mul(30) {
561        findings.push(DoctorFinding {
562            severity: DoctorSeverity::Info,
563            code: "knowledge_thin".into(),
564            message: format!(
565                "few substantial notes ({substantive}) vs many symbols ({symbol_count}) — context for *why* may be thin; capture decisions as ADRs"
566            ),
567        });
568    }
569
570    let _ = scaffoldish;
571    Ok(())
572}
573
574fn note_body_mass(workspace: &Path, db: &Database, id: &str) -> Result<usize> {
575    if let Some(c) = db.get_fts_content(id)? {
576        let m = body_mass(&c);
577        if m > 0 {
578            return Ok(m);
579        }
580    }
581    if let Some(node) = db.get_node(id)? {
582        if let Some(path) = node.file_path.as_ref() {
583            return Ok(file_body_mass(&workspace.join(path)).unwrap_or(0));
584        }
585    }
586    Ok(0)
587}
588
589fn id_is_from_readme(id: &str) -> bool {
590    let id = id.to_lowercase();
591    id == "docs/goals/from-readme" || id.contains("from-readme")
592}
593
594/// Pure scaffold: never counts as project knowledge by itself.
595fn is_hard_scaffold_id(id: &str) -> bool {
596    let id = id.to_lowercase();
597    id.contains("template")
598        || id == "docs/goals/readme"
599        || id.ends_with("bootstrap_checklist")
600        || id.contains("bootstrap-checklist")
601        || id.contains("bootstrap_checklist")
602        || id.contains("module-map.generated")
603        || id == "agents"
604        || id.ends_with("/agents")
605        || id == "readme" // root hub is inventory, not a decision record
606}
607
608impl DoctorReport {
609    /// Render a human-readable multi-line report.
610    pub fn to_text(&self) -> String {
611        let mut out = String::new();
612        out.push_str(&format!("rustbrain doctor — {}\n", self.workspace.display()));
613        out.push_str(&format!(
614            "  db: {}  mmap: {}  schema: {}\n",
615            if self.db_exists { "yes" } else { "NO" },
616            if self.mmap_exists { "yes" } else { "no" },
617            self.schema_version
618                .map(|v| v.to_string())
619                .unwrap_or_else(|| "-".into())
620        ));
621        out.push_str(&format!(
622            "  nodes={} edges={} fts={} pending={} symbols={}",
623            self.nodes, self.edges, self.fts_rows, self.pending_links, self.symbol_anchors
624        ));
625        if self.orphan_notes > 0 {
626            out.push_str(&format!(" orphans={}", self.orphan_notes));
627        }
628        out.push('\n');
629        if !self.by_type.is_empty() {
630            out.push_str("  by type: ");
631            let parts: Vec<_> = self
632                .by_type
633                .iter()
634                .map(|(t, c)| format!("{t}={c}"))
635                .collect();
636            out.push_str(&parts.join(" "));
637            out.push('\n');
638        }
639        out.push_str("\nfindings:\n");
640        for f in &self.findings {
641            let tag = match f.severity {
642                DoctorSeverity::Info => "info",
643                DoctorSeverity::Warn => "WARN",
644                DoctorSeverity::Error => "ERR ",
645            };
646            out.push_str(&format!("  [{tag}] {}: {}\n", f.code, f.message));
647        }
648        if !self.orphan_details.is_empty() {
649            out.push_str("\norphan notes (no explicit WikiLink/symbol edges; auto-links ignored):\n");
650            for o in &self.orphan_details {
651                let path = o.file_path.as_deref().unwrap_or("-");
652                out.push_str(&format!(
653                    "  • [{}] {} (id: {})\n    path: {}\n",
654                    o.node_type, o.title, o.id, path
655                ));
656                if o.suggestions.is_empty() {
657                    out.push_str("    suggestions: (none — add tags, matching filenames, or WikiLinks)\n");
658                } else {
659                    out.push_str("    suggestions:\n");
660                    for s in o.suggestions.iter().take(8) {
661                        let tp = s.target_path.as_deref().unwrap_or("-");
662                        out.push_str(&format!(
663                            "      - [{} w={:.2}] {} → {} ({})\n",
664                            s.relation_type, s.weight, s.reason, s.target_id, tp
665                        ));
666                    }
667                }
668            }
669            out.push_str(
670                "\n  apply soft links: `rustbrain links --auto`\n  one file: `rustbrain links --auto docs/goals/foo.md`\n",
671            );
672        }
673        if !self.pending.is_empty() {
674            out.push_str("\npending links (up to 50):\n");
675            for p in self.pending.iter().take(50) {
676                out.push_str(&format!(
677                    "  {} -[{}]-> {}\n",
678                    p.source_id, p.relation_type, p.raw_target
679                ));
680            }
681        }
682        out.push_str(&format!(
683            "\nstatus: {}\n",
684            if self.healthy { "OK" } else { "UNHEALTHY" }
685        ));
686        out
687    }
688}
689
690#[cfg(test)]
691mod tests {
692    use super::*;
693    use crate::brain::Brain;
694    use tempfile::tempdir;
695
696    #[test]
697    fn doctor_empty_workspace() {
698        let dir = tempdir().unwrap();
699        let report = run_doctor(dir.path()).unwrap();
700        assert!(!report.healthy);
701        assert!(report.findings.iter().any(|f| f.code == "no_db"));
702    }
703
704    #[test]
705    fn doctor_after_init_sync() {
706        let dir = tempdir().unwrap();
707        let docs = dir.path().join("docs");
708        std::fs::create_dir_all(&docs).unwrap();
709        std::fs::write(
710            docs.join("a.md"),
711            "---\nnode_type: concept\n---\n# A\nHello.\n",
712        )
713        .unwrap();
714        let mut brain = Brain::create(dir.path()).unwrap();
715        brain.sync().unwrap();
716        let report = run_doctor(dir.path()).unwrap();
717        assert!(report.db_exists);
718        assert!(report.nodes >= 1);
719        assert!(report.healthy || report.findings.iter().all(|f| f.severity != DoctorSeverity::Error));
720    }
721
722    #[test]
723    fn doctor_walks_parent_for_brain() {
724        let dir = tempdir().unwrap();
725        let root = dir.path();
726        let sub = root.join("src").join("nested");
727        std::fs::create_dir_all(&sub).unwrap();
728        let mut brain = Brain::create(root).unwrap();
729        brain.sync().unwrap();
730        let report = run_doctor(&sub).unwrap();
731        assert!(report.db_exists, "doctor should find parent .brain");
732        assert_eq!(
733            report.workspace.canonicalize().unwrap(),
734            root.canonicalize().unwrap()
735        );
736    }
737
738    #[test]
739    fn doctor_reports_no_readme() {
740        let dir = tempdir().unwrap();
741        let mut brain = Brain::create(dir.path()).unwrap();
742        brain.sync().unwrap();
743        let report = run_doctor(dir.path()).unwrap();
744        assert!(
745            report.findings.iter().any(|f| f.code == "no_readme"),
746            "findings={:?}",
747            report.findings
748        );
749        assert!(report.healthy);
750    }
751
752    #[test]
753    fn doctor_reports_sparse_readme() {
754        let dir = tempdir().unwrap();
755        std::fs::write(dir.path().join("README.md"), "# x\n\ntodo\n").unwrap();
756        let mut brain = Brain::create(dir.path()).unwrap();
757        brain.sync().unwrap();
758        let report = run_doctor(dir.path()).unwrap();
759        assert!(
760            report.findings.iter().any(|f| f.code == "sparse_readme"),
761            "findings={:?}",
762            report.findings
763        );
764    }
765
766    #[test]
767    fn doctor_counts_orphans_and_details() {
768        let dir = tempdir().unwrap();
769        std::fs::create_dir_all(dir.path().join("docs/concepts")).unwrap();
770        std::fs::write(
771            dir.path().join("docs/concepts/lonely.md"),
772            "---\nnode_type: concept\n---\n# Lonely\n\nNo links here.\n",
773        )
774        .unwrap();
775        let mut brain = Brain::create(dir.path()).unwrap();
776        brain.sync().unwrap();
777        let report = run_doctor(dir.path()).unwrap();
778        assert!(report.orphan_notes >= 1, "orphan_notes={}", report.orphan_notes);
779        assert!(report.findings.iter().any(|f| f.code == "orphan_notes"));
780
781        let detailed = run_doctor_with(
782            dir.path(),
783            &DoctorOptions {
784                detail_orphans: true,
785            },
786        )
787        .unwrap();
788        assert!(!detailed.orphan_details.is_empty());
789        assert!(detailed
790            .orphan_details
791            .iter()
792            .any(|o| o.id.contains("lonely")));
793    }
794
795    #[test]
796    fn doctor_scaffold_only_after_empty_bootstrap_ish() {
797        let dir = tempdir().unwrap();
798        // Minimal notes that look like stubs
799        std::fs::create_dir_all(dir.path().join("docs/adr")).unwrap();
800        std::fs::write(
801            dir.path().join("docs/adr/TEMPLATE.md"),
802            "---\nnode_type: adr\n---\n# ADR template\n\nProposed\n",
803        )
804        .unwrap();
805        let mut brain = Brain::create(dir.path()).unwrap();
806        brain.sync().unwrap();
807        let report = run_doctor(dir.path()).unwrap();
808        assert!(
809            report
810                .findings
811                .iter()
812                .any(|f| f.code == "scaffold_only" || f.code == "adr_template_only"),
813            "findings={:?}",
814            report.findings
815        );
816    }
817}