Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
58.6 KB
Raw Blame

Key files: Commands (2/6)

Subsystem index. Read only the entries relevant to your change. Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.

Doctor's embedding-dimension warning treats existing chunks as existing data even when every vector is missing. It directs the operator to a verified database backup and a brain-wide migration preview, followed only by explicitly approved total spending authorization; it never recommends forced reinitialization for that case. test/doctor.test.ts pins this recovery guidance.

  • src/commands/doctor/checks/chat-fallback.ts — chat_fallback_chain (OPS, registered after embedding_env_override so --only connects the brain, and in doctorReportRemote): the effective chain, its plane, shadowed values, providers and refusal behavior from src/core/ai/chat-fallback-planes.ts. An active, healthy chain is ok with the optional per-plane removal fix (never next: run); an unreadable plane value or a malformed / unknown-provider / no-chat entry warns with the removal fix, a missing credential with a credentials fix, an unpriced model under a user cap with noPricingFix. Remote (remote !== false): only that a chain is configured and its problem count, host_admin fix. Pinned by test/doctor-chat-fallback-chain.test.ts.

  • src/commands/doctor/checks/behavior-changes.ts — behavior_changes (META, after chat_fallback_chain): the behavior_changes disclosure read again (src/core/behavior-change-notice.ts): every change newer than the brain's baseline, labeled by release, whether or not the notice was shown; always ok; reads the baseline and markers without recording either, and reports which channels were shown.

  • src/commands/doctor/checks/ranking-extraction.ts — informational BRAIN check extraction_date_grounding, registered after timeline_history: fact extraction, synthesis, atoms and takes grounded by default, all off when the setting is false, and whether the chronicle prompt is opted in. Pinned by test/doctor-ranking-extraction.test.ts and the doctor registry/JSON goldens.

  • src/commands/doctor/checks/vector-plan.ts — vector_plan (#5824, OPS, wave check with operator resolution). Postgres only: EXPLAINs (no ANALYZE) the statement searchVector emits for the active embedding column with a zero vector through PostgresEngine.explainVectorSearch (same builder, scoped read transaction and scan settings) and warns when an HNSW-indexed column's plan does not use its HNSW index, naming the observed scans, whether the index exists and is valid (pg_index.indisvalid, with the create/reindex command), the 8 s candidate-budget risk and the legacy guard as rollback. Skipped on PGLite, on columns wider than the HNSW cap, and below 10,000 embedded chunks (pg_class.reltuples x pg_stats.null_frac, a bounded count when never analyzed). A configured legacy guard warns "active after restarting the owning service". Details carry a sampled stale-text fraction and point to gbrain embed --stale above 5%. Tested in test/e2e/vector-plan-real-column-postgres.test.ts (empty, small, ok, unused valid index, INVALID index, guard via env and config).

  • src/commands/doctor/checks/persistence-requests.ts — wave checks (OPS, registered in wave-checks.ts); persistence_terminal_failures (#6650) is in Managed sync bookkeeping. persistence_request_indexes (#5762) reports each request index missing, INVALID or building, naming gbrain repair request-indexes --apply, and 3+ consecutive dream postprocess deferrals (#6757). persistence_request_growth reports the request-table row count (a reltuples estimate on Postgres), each scope's admission rate over the last 7 days (the newest 10,000 admissions per scope, one bounded index read), lifetime IDs against persistence.limits.* and the projected exhaustion date within ten years; it warns under 90 days with the oneYearCapacity gbrain config set value and the doctor re-check. persistence_write_stall (#6176, host-only) reads running requests and warns when one has held its claim longer than persistence.max_claim_ms (claim-phase.ts; an owner that predates phase recording falls back to the request's age on the database clock), naming the stuck phase, the root, the claim age, the queued writes behind it and whether the request resumes on its own, with gbrain sources writer status --source <id> --json as the fix. persistence_session_timeouts (#6278, host-only) reads SHOW statement_timeout through the configured URL and warns session_timeouts_not_applied when it is 0 while resolveSessionTimeouts() configured one (a transaction-mode pooler dropped the startup parameter), naming the role-level fix. Tests: test/persistence-request-indexes.test.ts, test/e2e/persistence-request-indexes-postgres.test.ts, test/persistence-write-stall.test.ts, test/persistence-session-timeouts-check.test.ts.

  • src/commands/doctor/checks/{persistence-capacity,parked-effects}.ts — persistence_capacity (OPS) warns when a principal or the brain reaches 80% of permanent request IDs or receipt bytes (via capacityDiagnostics) and prints one gbrain config set <key> <value> per brain-wide key, using the largest value any scope needs for about one more year; transient caps never warn. parked_effects (BRAIN) reads the partial parked-effect index, counts exactly, samples 20, and names each parked page with its retry-effects ... --dry-run command. Both report exact/inspected/truncated details; an unreadable state is warn, never clean. Tests: test/persistence-capacity.test.ts, test/persistence-effect-parking.test.ts.

  • src/commands/doctor/checks/unbound-source.ts — unbound_source (#5254) counts live pages with pages.database_only_reason='unbound_source' and no recorded origin (blank source_path and source_uri) per source, via databaseOnlyPageSql (persistence/unbound-pages.ts), the SQL form of isDatabaseOnlyPage (#6536). A managed sync that records a page's origin, and a reconcile apply, clear the marker. While the source is unbound the count is ok and the message carries the filled sources writer status/writer claim bind command (database-only is the chosen mode); once the source has a binding it warns, because binding never materializes those pages into canonical files. Unreadable state warns. Registered on the persistence_capacity line in doctor.ts. Tests: e2e/unbound-source-postgres, unbound-source-6536.

  • src/commands/doctor/checks/revision-backfill.ts — revision_backfill (#5216, META, registered before search_mode): reads readRevisionBackfillStatus (column state, pages still without knowledge_revision, failed rows still pending with their page). ok when the column is NOT NULL; warn with the pending count and gbrain apply-migrations --force-schema as fix while any row is resumable (or only the NOT NULL step remains); failed rows are listed by page id, source:slug, attempt and error, and when only rows with spent attempts remain the fix is the read-only gbrain repair orphan-children preview. Tests: test/doctor-revision-backfill.test.ts.

  • src/commands/doctor/checks/extractor-facts.ts — extractor_facts_expired (#5731): counts conversation-extractor facts the pre-v0.60.11.0 projection expired, by class (evidenced, ambiguous; excluded reported but never a finding) through classifyExtractorFacts, and names gbrain repair extractor-facts (explicit-only, so the remediation plan and banner list it with its preview). Read-only; health unknown when the query fails.

  • src/commands/doctor/checks/atom-retirements.ts — atom_retirements_restorable (#7013, BRAIN, a WAVE_CHECKS entry with resolution: 'repair', host-only, cleared by the explicit-only atoms-restore, so remediation classifies it explicit_kind_required): counts the restorable rows of atomRetirementsSql per source; warn names the count, origins, oldest and newest retired_at, the end of the earliest purge hold (hold_until) and the read-only preview gbrain repair atoms-restore --source <id> --json as an agent fix; the apply is the user's call.

  • src/commands/doctor/checks/conversation-outcomes.ts — conversation_label_facts (wave check, host-only, resolution repair): bounded count (capped at 1000, reported as at least N) of the default set gbrain repair conversation-labels would retire; names the preview, never the apply. conversation_outcomes_stale (wave check, host-only, resolution operator): counts active conversation extraction outcomes stamped with an older extractor_version than CONVERSATION_EXTRACTOR_VERSION (outcomes are never reopened automatically) and names the --force --dry-run re-extract preview; outcomes older than the stamp are counted as unstamped and never warn. Bounded scan of the extractor rows, capped at 5000 (reported as at least N). Read-only.

  • src/commands/doctor/checks/captured-facts.ts — captured_facts_active (wave check, host-only): counts active capture-lane facts (hook:writeback, hook:compact, sweep:corpus) that classifyCapturedFacts classes as self-capture (evidenced) or paste candidates (ambiguous); excluded and unclassifiable are reported, never a finding. Names gbrain repair captured-facts (explicit-only) and says it counts facts while self_capture counts corpus files. Read-only; health unknown when the scan fails.

  • src/commands/doctor/checks/facts-redaction-marker.ts — facts_redaction_marker (wave check, host-only, #7125): counts active facts of active sources whose text holds [redacted (one scan of active facts) and names the explicit-only gbrain repair redacted-facts preview. Read-only; health unknown when the count fails.

  • src/commands/doctor/checks/loop-facts.ts — loop_facts_drift (#5869): counts closed commitment loops whose fact is still active and retirable (loopFactDrift) and names gbrain repair loop-facts (explicit-only). Read-only; health unknown when the query fails.

  • src/commands/doctor/checks/ontology-facts.ts — ontology_facts_fenced (#6264; wave check, host-only): counts ontology observations the pre-fix extract_facts fence step moved onto an entity page's Facts table, restorable ones by state (fenced, retired) plus excluded (withdrawn, consolidated, duplicate; never a finding), through classifyOntologyFacts, and names gbrain repair ontology-facts. Read-only; an inspection error reports health unknown.

  • src/commands/doctor/checks/auto-chronicle.ts — auto_chronicle, chronicle_config_invalid, chronicle_duplicate_events and auto_chronicle_default_on (#5876, #8972), registered after unlinked_facts, config-plane only (no provider calls). auto_chronicle: off by choice is ok with severity: info, readiness: disabled_by_choice; an invalid word warns auto_chronicle_invalid; when on it reads core/chronicle/ledger-stats.ts and warns judge_llm_unavailable (pending pages, no provider) or the top failure reason with that reason's fix, else reports ok with 24 h use of the daily limit, the largest writer's share, 7-day outcomes and spend, and gbrain dream --phase chronicle. Every warn carries a details.fix Action and fix_hint. chronicle_config_invalid warns on an out-of-range stored chronicle.* value. auto_chronicle_default_on is ok/info with ask_user and keep/opt-out decisions until gbrain config set auto_chronicle. Test: test/auto-chronicle-surfaces-5876.test.ts.

  • src/commands/doctor/checks/vector-coverage.ts — fact_take_vectors (#5188, #5885), registered after auto_chronicle: per unarchived source (honoring --source), active facts (eligibleFactEmbedding + staleFactEmbedding) and takes (countStaleTakes with the DB-plane model and width) with no vector for their current text, split into missing versus other-model, plus facts.partially_embedded (current vectors of facts over EMBED_MAX_CHARS, partiallyEmbeddedFact; reported, never re-embedded, #6975); warns with code stale_vectors and details.fix (gbrain embed --stale, or gbrain takes embed when takes.auto_embed is off; per-source gbrain embed --facts --stale --source <id> --dry-run --json). Keyless brains report applicable: false; a brain with no recorded model or width warns vectors_not_verified.

  • src/commands/doctor/checks/git-holds.ts + checks/frontmatter-repairable.ts + checks/frontmatter-hook.ts — the #5988 hold and frontmatter checks. git_held_files (wave, host-only, resolution: 'repair'): Git-source holds per source from readHeldCoverage (missing vs stale counts) and the first five paths from readGitHoldListing with each one's code and gitHoldFix step, the put_page read-only note, gbrain sources status <id> and each source's repair command from the hold router (holdRepairSteps: gbrain repair frontmatter --source <id>, gbrain repair fences --source <id> for invalid_fence holds, both for a mixed source; with fence holds the details add fences and auto_repair, and the banner line names the fence repair through the wave entry's bannerHow); fail once a source holds more than sync.hold_escalate_count; details.visibility_noncanonical counts held files and stored non-canonical private pages; connector holds stay on connector_held_items. frontmatter_repairable (emitted inline by the frontmatter_integrity entry from the same scanBrainSources walk, whose PerSourceReport.repairable counts files by repairable cause: recoverable YAML_PARSE, needs_interpretation, FRONTMATTER_COMMENT_VALUE on title/name/description/summary, NESTED_QUOTES, NULL_BYTES, MISSING_CLOSE, SLUG_MISMATCH); a deadline-partial scan sets details.partial; the doctor scan passes frontmatterOnly, so each file's head through its closing fence is validated when frontmatterScanHead proves the findings equal, else the whole file (test/brain-writer-frontmatter-scan-head.test.ts). Both list details.source_ids and belong to the explicit-only frontmatter kind, so remediation classifies them explicit_kind_required with --source <id> when one source is named. frontmatter_hook (wave, operator): gbrain pre-commit hooks older than FRONTMATTER_HOOK_VERSION, fix gbrain frontmatter install-hook --source <id> --force. frontmatterHoldsBannerNote (a POST_UPGRADE_NOTES entry) names sources whose unfinished managed cursor stopped on a failed content refusal: the next sync (or gbrain sync --source <id> --no-pull now) recovers them, plus the repair preview and the hook refresh. fenceHoldsBannerNote (a separate POST_UPGRADE_NOTES entry) names sources whose cursor stopped on a fence receipt (typed or legacy): the next sync recovers them with no command (gbrain sync --source <id> --no-pull now), the stored census's malformed fences and whether the next maintenance run repairs them, the read-only gbrain repair fences preview and the pause command gbrain config set fences.repair.enabled false; never an apply. Tests: test/doctor-frontmatter-holds.test.ts, test/persistence-sync-fence-holds.test.ts.

  • src/commands/doctor/wave-checks.ts — WAVE_CHECKS, the table of managed-persistence wave checks (stable id, resolution repair/operator/unsupported, count-free remote impact, operator instruction, count for banners, bannerHow when a finding's details change the banner's parenthetical, registration inline-in-doctor.ts or from this table). fence_integrity (#6188, repair, registered inline) counts details.total; its banner line says "repaired automatically by the next maintenance run" while one is active (from details.auto_repair), else why not, with gbrain repair fences as the preview; a fence-only git_held_files finding gets the same wording, a mixed one adds it to the frontmatter preview. runWaveChecks (ids for --only, #7343) turns a throwing check into an unknown finding; checkHealthUnknown reads details.health === 'unknown'. remoteWaveHandoff returns one line per remotely offered check with details.host_action {check_id, state ok/action_required/unknown, preview_command} and no paths, rows, SQL, emails or installation ids. Consumers: doctor.ts, report-remote.ts, remediate.ts, upgrade-banner.ts. Tests: test/recovery-layer.test.ts, test/e2e/recovery-layer.test.ts.

  • src/commands/doctor/remediate.ts — the --remediation-plan / --remediate CLI shell (re-exported from doctor.ts): per-step command (gbrain jobs submit … for job steps, gbrain repair <kind> --apply for repair steps; a repair step with llm_usd names its paid chat model spend, and any embedding part, in its fix and plan line), combinedRemediateCommand (with repair steps it ends --expect <plan_hash>, the same hash --remediation-plan --json reports as plan_hash), a Repair kinds whose preview failed block for repair_preview_failures (each {kind, code, message, why, fix}; such a kind is not planned, so a plan approved while it failed refuses preview_changed once it succeeds), REMEDIATE_HELP, --include-repairs/--no-embed/--resume handling, the resume command after budget exhaustion (repeats the recorded cap and consent), classifyWaveFindings (cleared / pending / consent_required / operator_required / explicit_kind_required / unsupported, from wave checks run before and after; details.partial is pending; an explicit-only kind's preview gets --source <id> via findingSource when the finding names one source; --remediation-plan runs the wave checks too and reports the same classification as findings) and remediationExitStatus (0 when no repairable finding remains and no step failed; 1 otherwise, on budget exhaustion or when a repair preview failed; 2 when the target is unreachable with no repair step, or a resume is refused), set through setCliExitVerdict; 3 when consent is required), set through setCliExitVerdict. Consent (agent operator wave C1) lives in doctor/remediate-consent.ts: the CLI connects probe-only (no migrations) and computes the plan; when anything would run it calls requireConsent (effects paid, plus destructive with --include-repairs, bound to a plan_hash over the brain id, job step ids, repair kinds and pending counts, and the parameters, and persisted with the approval). Non-TTY without authorization changes nothing and exits 3 with the consent payload; --json never implies consent; --yes without --max-usd runs under the derived cap (estimate ×1.5, floor $0.25; the default cap when unpriced), and derived-cap exhaustion prints the --max-usd resume command. Startup (migrations) completes only after consent. A --resume is bound by its checkpoint manifest, not a new plan hash. Pinned by test/doctor-remediate-consent.test.ts.

  • src/commands/doctor/checks/global-maintenance-stalled.ts — global_maintenance_stalled (GBRA-130 C-6, #6837): reports assessGlobalMaintenanceStall from src/core/minions/global-maintenance-stall.ts. Warns when autopilot.last_global_at is older than three global intervals (autopilot.global_floor_min, default 60 min) and autopilot-global-maintenance jobs ended failed/dead/cancelled since it or a phase streak is active, fails when it is older than seven days (or twice the warn age, if longer), and also warns when passes stamp past a phase whose fail: streak reached three passes. It also warns when passes stamp past a deferred streak whose count stopped shrinking (#7307). The message names the phase, its blocker key and back-off; fix is gbrain dream --phase <p> (paid consent) then gbrain autopilot --retry-global --phase <p>, or for a deferred streak gbrain dream retriage (paid consent, --dry-run --json preview), or gbrain jobs get <id> for the last failed job when no phase streak exists. Health score: warn -5, fail -20 (ops category; brain score and --target-score are unaffected). Pinned by test/pathological/a10-global-maintenance-stamp.test.ts.

  • src/commands/doctor/checks/global-maintenance-timeouts.ts — global_maintenance_timeouts (#4578): warns when the last three finished autopilot-global-maintenance jobs died at their deadline, or one phase was running in three consecutive job deaths (read from config autopilot.global_maintenance.progress), or (#6303) the last three finished dream patterns / synthesize subagent children (keyed by idempotency prefix) all died at their own timeout exceeded while the jobs completed, naming dream.<phase>.subagent_timeout_ms (details.child_timeouts). Details carry code, cause, fix (gbrain dream --phase <name>, else the deadline config key) and the docs/guides/troubleshooting.md#global-maintenance-timeouts anchor. Pinned by test/autopilot-global-maintenance-resume-4578.test.ts.

  • src/commands/doctor/checks/legacy-job-authority.ts — legacy_job_authority (#5157): the claim gate's population (UNREVIEWED_LIVE_JOBS_WHERE), split into authorizable SQL NULL and unsupported rows; terminal keyed SQL NULL rows are reported as ok. Live rows fail with the filled recovery. legacyJobAuthorityBannerNote feeds the banner. The same check counts queued paid jobs by spend basis (details.queued_spend) and warns, with the read-only fix gbrain jobs list --status waiting --json, when spend-authorized rows wait over 10 minutes while registered workers run (an un-upgraded worker is fenced off them); legacyDefaultSpendBannerNote names queued legacy_default rows after an upgrade. Tests: test/doctor-legacy-job-authority.test.ts, test/doctor-queued-spend.test.ts.

  • src/commands/doctor/upgrade-banner.ts — postUpgradeRecoveryBanner: runs the wave checks once and returns one [AGENT] Relay this to your operator block (brain, per-finding count and resolution, refined by the check's bannerHow, the read-only gbrain doctor --remediation-plan, ask before applying), never an applying command; empty for a clean brain. POST_UPGRADE_NOTES lets other subsystems add lines (fenceHoldsBannerNote among them). Test: test/post-upgrade-banner.test.ts.

  • src/commands/doctor/checks/{safe-index,self-capture,stale-embedding-effects}.ts — safe_index_pending (BRAIN: re-sealable pages below the safe-chunk fence, names gbrain repair safe-chunks; kept code/image pages are informational), self_capture (BRAIN, #5413: corpus .txt files whose session id matches a gbrain claude-cli scratch transcript are classified, ones with no harness transcript left are unclassifiable; classification is isClaudeCliSelfSessionId; details carry newest_capture_at, a capped sample and copy-paste quarantine commands into <corpus>.quarantine, and the message says new captures stopped (#5820) so only the existing files need one quarantine; never moves or deletes), stale_embedding_effects (OPS, #5629: committed writes with a queued embedding effect untouched for an hour; names each effect with its inspect command; reported as unsupported). Unreadable state is warn with details.health: 'unknown'. writer_version (checks/writer-version.ts, owned by the persistence entry) is registered in the same table as operator-required. Tests: test/doctor-self-capture.test.ts, test/recovery-layer.test.ts.

  • src/commands/doctor/checks/managed-sync-backlog.ts — #5984: lists unfinished managed sync cursors of live source incarnations with remaining entries, the last drain's pages/min and indexing ETA (persistence/sync-drain.ts readManagedSyncBacklog); warns when a cursor has not advanced for an hour, with its resume command. Tests: test/sync-drain.test.ts.

  • src/commands/doctor.ts — gbrain doctor [--json] [--fast] [--fix] [--dry-run] [--index-audit] [--no-migrate]: health checks. checkPostgresCancellationDriver (postgres_cancellation_driver) inspects a real reserved runtime owner through the shared cancellation helper: unsupported discard() is a typed local failure with a repair link, connection/deadline failure is a warning, and PGLite is exempt. The bounded reserve releases late arrivals and does not make general engine connect require cancellation, preserving broken-install diagnostics. --no-migrate keeps doctor observational: the CLI connects with probeOnly so a clean-or-behind schema is reported as-is instead of being auto-migrated before the checks run. The file is a façade carrying buildChecks (flag parse into a DoctorContext, then runDoctorRegistry), runDoctor and output rendering; the checks run as the ordered registry in src/commands/doctor/registry.ts (see that entry), the check-function library lives in bundles under src/commands/doctor/checks/ plus four tail-cluster modules under src/commands/doctor/ (see that entry), all re-exported here so the full surface is unchanged — structural guards pin its source text via test/helpers/doctor-source.ts, never by reading this file alone. Checks include jsonb_integrity + markdown_body_completeness (reliability), schema_version (fails loudly when version=0, routes to gbrain apply-migrations --yes; a version AHEAD of this client's LATEST_VERSION warns "upgrade this client"; and when the ledger reads current, a read-only detectMissingColumns diff from src/core/schema-verify.ts runs INSIDE the ledger-current branch — a PgBouncer-swallowed ALTER TABLE can advance config.version over a physically narrower table, so missing live columns downgrade the ok to a warn naming them with the gbrain init --migrate-only hint; diff failure is best-effort and the ledger ok stands; positional wiring pinned by test/doctor-schema-column-diff.test.ts), upgrade_errors (async checkUpgradeErrors(engine) over ~/.gbrain/upgrade-errors.jsonl: the warn downgrades to an EXPLICIT status-ok line — never silence — only when the past failure is provably superseded, i.e. the running binary is at/past the failed target version AND the schema verifies current via engine.getConfig('version'); a missing engine or unverifiable schema keeps the warn, fail-closed, because self-upgrade swaps the binary before post-upgrade runs migrations and the binary alone can lie; pinned by test/doctor-upgrade-errors.test.ts + test/doctor-upgrade-errors-stale.test.ts), queue_health (Postgres-only: stalled-forever active jobs started_at > 1h, waiting-depth-per-name > threshold default 10 via GBRAIN_QUEUE_WAITING_THRESHOLD, and dead-lettered subagent jobs with last_error matching the prompt_too_long classifier in last 24h), sync_failures ([CODE=N, ...] breakdown for unacked-warn + acked-ok; severity comes from the shared decideSyncFailureSeverity in src/core/sync-failure-ledger.ts so the LOCAL and REMOTE/thin-client doctor surfaces can never drift — a stuck bookmark escalates to FAIL once an OPEN failure has blocked past the staleness window or ≥10 files block, while already auto_skipped rows stay a visible WARN), rls_event_trigger (healthy evtenabled set is ('O','A') only; fix hint gbrain apply-migrations --force-retry 35), graph_coverage (short-circuits to ok when SELECT COUNT(*) FROM pages WHERE type IN ('entity','person','company','organization') returns 0; WARN hint is gbrain extract all), embedding_column_registry (probes each declared column via Postgres format_type(atttypid, atttypmod) to catch dim mismatch with a paste-ready gbrain config set embedding_columns '{...}' hint, probes HNSW index presence via pg_indexes, computes default-column population via COUNT(*) FILTER (WHERE <col> IS NOT NULL) / COUNT(*) warning below 90% except empty brains where chunk_count=0 short-circuits to ok; PGLite parity via executeRaw), and skill_brain_first (walks SKILL.md via autoDetectSkillsDirReadOnly, calls analyzeSkillBrainFirst() from src/core/skill-brain-first.ts per file with structured Check.issues[]; warn states missing_brain_first/brain_first_typo, ok states compliant_callout/compliant_phase/compliant_position/exempt_frontmatter/no_external; snapshot+diff audit at ~/.gbrain/audit/skill-brain-first-YYYY-Www.jsonl). --fix delegates inlined cross-cutting rules to > **Convention:** see [path](../path). callouts via src/core/dry-fix.ts (and MISSING_RULE_PATTERNS for the brain-first callout); --fix --dry-run previews. --index-audit (Postgres-only, informational, no auto-drop) reports zero-scan indexes from pg_stat_user_indexes. Every DB check runs under a progress phase; markdown_body_completeness runs under a 1s heartbeat. runDoctor uses autoDetectSkillsDirReadOnly (from src/core/repo-root.ts; install-path fallback so cd ~ && gbrain doctor finds bundled skills); --fix carries a D6 install-path safety gate that refuses auto-repair when detected.source === 'install_path' (would rewrite the bundled tree). The Lane D supervisor check (doctor/checks/supervisor-health.ts) consumes summarizeCrashes(events) from src/core/minions/handlers/supervisor-audit.ts (warn at >=1 real crash; ok message has clean_exits_24h=N; warn message has runtime=A oom=B unknown=C legacy=D per-cause breakdown) so OOM/runtime/unknown crashes are distinguishable from clean code=0 worker drains; cross-surface parity with gbrain jobs supervisor status is pinned by source-grep wiring assertions requiring the breakdown substrings on the doctor surface and in jobs.ts. checkSyncFreshness (exported, in runDoctor local + doctorReportRemote thin-client) is a staleness probe: warns at 24h, fails at 72h or never-synced; future-last_sync_at warns ("clock skew") instead of falling through ok; env overrides GBRAIN_SYNC_FRESHNESS_WARN_HOURS/GBRAIN_SYNC_FRESHNESS_FAIL_HOURS (invalid fall back with once-per-process stderr warn via _resolveSyncFreshnessHours); failure messages embed source.id so the printed gbrain sync --source <id> matches. A source holding a LIVE, non-expired per-source sync lock (inspectLock(engine, syncLockId(source.id)) from src/core/db-lock.ts) is reported as actively syncing (the message names the holder pid + host) and counted in synced_recently_count, NOT flagged stale — the live lock is the only honest in-progress signal (checkpoint banking can't distinguish in-progress from wedged: a blocked sync banks its files but writes no anchor). A blocked/failed sync's process has exited (no lock row) and a wedged holder stops refreshing (TTL lapses), so either falls through to the stale path and is never masked; the dynamic db-lock import is swallowed to a no-op on a stub engine or pre-lock-table brain, so this can only ADD an in-progress verdict, never suppress a real stale one. The in-progress note is appended to whatever verdict the buckets produce and is empty when nothing is syncing, so steady-state messages stay byte-for-byte unchanged. It has a localOnly-gated git short-circuit (runDoctor passes localOnly: true; doctorReportRemote runs in the HTTP MCP server src/commands/serve-http.ts and keeps default false so that path never walks DB-supplied local_path via subprocess — trust boundary). The local predicate mirrors sync's "do work?" gate (HEAD == last_commit AND working tree clean via requireCleanWorkingTree: 'ignore-untracked' so a quiet repo with only untracked dirs is unchanged not SEVERE, AND chunker_version === CURRENT); the inline SELECT carries last_commit + chunker_version + newest_content_at. The REMOTE path computes lag via lagFromContentMs(newest_content_at, lastSync, now) from the stored column, NO git subprocess; LOCAL fall-through and the < 0 clock-skew check stay on raw wall-clock. Three-bucket count math populates Check.details = {unchanged_count, synced_recently_count, stale_count} with the invariant sum === sources.length. checkCycleFreshness is DELIBERATELY NOT git-short-circuited or content-relativized (last_commit == HEAD can't answer "did the full cycle complete?"; a sync can succeed while later cycle phases fail; different axis last_full_cycle_at). Pinned by test/doctor.test.ts (incl. the IRON-RULE guard banning stale verb names, the sync_freshness boundary matrix, the D4 guard verifying git probes are NEVER called when localOnly is unset/false, the three-bucket invariant, and the untracked-folders / remote-never-shells-out trust-boundary cases). pglite_data_dir check: fs-only check that runs when a PGLite brain FAILS to connect (!fastMode && !engine && config.engine === 'pglite', placed after orphan_clones, before the DB-checks gate; pgliteDataDirEntry in doctor/checks/db-connection.ts): computePgliteDataDirCheck(dataDir, diagnosis) (exported pure fn, computeWorkerOomLoopCheck convention) maps the inspectPgliteDataDir verdict to a Check — corruption-likely/looks-healthy-but-unopenable/unsupported-layout → fail naming gbrain pglite-repair --dry-run/--yes or the rebuild path, live-lock/missing-dir → warn; all remediation_status: 'human_only' (Minion remediation needs the DB that is down). Escalates when ≥2 repair attempts failed inside 7 days (unclean-shutdown genesis still active → engine-switch pointer) and reports retained backup-dir inventory (orphan_clones disk-visibility class). Registered in doctor-categories.ts OPS_CHECK_NAMES. Pinned by test/doctor-pglite-datadir.test.ts. silent-failure checks: content_hash_duplicates (single GROUP BY over (source_id, content_hash) with FILTER aggregates — never N² — flagging hash groups that hold BOTH a bare and a path-prefixed slug, the wrong-import-root pattern; warn carries sample pairs + the pages delete → purge-deleted --older-than 0 remediation); undeclared_db_only_pages (per source with a local repo: markdown pages with no backing file outside every declared + derive-phase-default db_only prefix — the one check deliberately allowed to stat the repo; it finds each source's Git root once with sourceGitScope and passes it to resolveSourceLocalFilePath as gitScope; connector_database sources are skipped and counted in the message); db_only_collector_collision (configured recipe output_paths inside a declared db_only dir — auto-gitignore means sync AND import silently skip the collector's files; same warning fires in sync's manageGitignore at config-write time). All warn-level, engine-parity pinned by test/e2e/doctor-silent-death-parity.test.ts; units in test/doctor-silent-death-checks.test.ts. graph_signals_coverage check wired into both runDoctor (local) and doctorReportRemote (HTTP/JSON thin-client path). Reads search.graph_signals config first, falls back to mode default; silent ok when disabled. Computes inbound link coverage on the page set; warns at <10% with gbrain extract all fix hint; ok at ≥30% ("fire on most queries") and 10-29% ("fire occasionally"), each with the percentage embedded. Pinned by cases in test/doctor.test.ts. subagent_capability check (layer 3 of 3). Resolves subagent model config in runtime order (models.subagent > models.default > models.tier.subagent > built-in default) and warns when the selected model lacks native tool-loop capability (message names the bad value + paste-ready fix gbrain config set models.tier.subagent anthropic:claude-sonnet-4-6); also warns when models.default would sneak subagent into a non-Anthropic provider via tier inheritance. OK when subagent tier resolves to Anthropic. Tests in test/doctor.test.ts. computeWorkerOomLoopCheck(engine) is the single authoritative OOM-loop signal, unioning supervised summarizeCrashes(readRecentSupervisorEvents(24)).by_cause.rss_watchdog (cross-week read via readRecentSupervisorEvents so a Monday window can't lose Sunday) + bare-worker minion_jobs error_text='aborted: watchdog' count (Postgres-only; the same source queue_health subcheck 3 reads). Cap comes from the latest rss_watchdog_loop breaker alert's max_rss_mb, else resolveDefaultMaxRssMb() fallback. fail at breaker-tripped or oomKills≥5, warn at ≥1, null otherwise. computePoolReapHealthCheck(engine) is the Postgres-only pool_reap_health check reading readRecentPoolRecoveries(1) — fail when reconnect failures>0 (reconnect throwing is the actionable signal), warn at ≥10 reaps/hr (pooler thrash), null otherwise. Both registered by the supervisor registry entry after the supervisor block. The supervisor causeStr carries rss=N (see worker_oom_loop) and queue_health's watchdog message cross-references worker_oom_loop. DoctorReport.top_issues + the cause-ranked render header. worker_oom_loop + pool_reap_health registered under ops in doctor-categories.ts. Pinned by test/doctor-worker-oom-loop.test.ts, test/doctor-pool-reap-health.test.ts. supervisor_singleton check, a SEPARATE check from supervisor (same split precedent as the niceness check) so a singleton-divergence warn can't clobber the crash/liveness precedence. Runs only when a started supervisor event was seen in the last 24h and a live engine is available. Reads the queue-scoped DB lock row (gbrain_cycle_locks WHERE id = supervisorLockId(queue)) and compares the lock holder (holder_host:holder_pid) against the local pidfile holder via the pure classifySupervisorSingleton. mismatch → warn (a second supervisor may be running with a different --max-rss; message names both holders, the effective cap from the started event's max_rss_mb, and the fix gbrain jobs supervisor stop); single → ok (names holder + cap); no_lock → no check. PR #6463: pidfileHost (PID-file line 3) makes the same pid under a drifted hostname single → ok + host_label_drift; a two-line legacy file warns same_pid_host_label_differs; another pid keeps the warning emitted. Best-effort try/catch (silent skip on brains without the lock table). Registered under ops in doctor-categories.ts as supervisor_singleton. Pinned by test/supervisor-db-lock.test.ts + test/doctor.test.ts. checkBatchRetryHealth: batch_retry_health check surfacing Supavisor circuit-breaker incidents. Wired into both runDoctor (local) and doctorReportRemote (thin-client). Reads last 24h. States: ok (zero exhausted in 24h OR <3 from a single site), warn (>=3 same-site OR >=5 cross-site), fail (>=20 sustained breaker). Surfaces bad GBRAIN_BULK_* env at doctor startup. Corrupt-JSONL tolerant. Paste-ready fix hints in every warn/fail message. Also reads readRecentDbDisconnects(24) and appends Disconnect-call audit: N call(s) in 24h (most recent caller: <frame>). to ALL three message paths so connection-incident signal is greppable from one gbrain doctor --json call (module-import wrapped in try/catch so older brains without the audit file degrade silently). Pinned by test/doctor-batch-retry.test.ts (10 cases). three checks wired into runDoctor() and the JSON envelope, all warn-only with paste-ready fix hints. (1) checkSourceRoutingHealth(engine) scans up to 200 pages on federated brains and flags pages whose source_id doesn't match what resolveSourceWithTier() would have picked for their source_path; single-source brains short-circuit to ok; the 200-page cap is total across the brain so doctor stays under 5s. (2) checkOauthConfidentialHealth(engine) probes registered confidential clients for /token reachability. (3) checkAutopilotLockScope() (pure, no engine) compares the resolved lock path to $GBRAIN_HOME; warns when set but the lock lives elsewhere, with a PID-safe inspection hint (kill -0 <pid> before deletion). Pinned by test/doctor-v0_37_7_checks.test.ts. buildChecks(engine, args, dbSource, connectError?): Promise<Check[]> exported as a test seam; the optional connectError is the connect failure captured by the CLI's dead-DB fallback, which the null-engine path turns into a SYNTHESIZED classified connection fail entry (so checks[name=="connection"] exists in every failure shape — smoke-test branches on it). The connection check's failure path classifies via src/core/pg-access-classify.ts into a redacted message + details: {reason, transient, fix_hint} naming gbrain db-repair (deliberately NOT remediation[]/makeRemediationStep — that lane feeds --remediate, whose Minion jobs need the very DB that's down; applicator boundary: --remediate = brain-DATA quality with a live engine, db-repair = DB ACCESS engine-free). The URL-only pgbouncerPrepareCheck helper and the engine-free db_repair_recurrence check run BOTH before the connection check and in the dead-DB filesystem lane; pglite_scale (engine-fit, warn at ≥1000 pages on pglite) runs in the DB phase. computeDoctorReport(checks, extras?) accepts optional {engine, db_url_source} which land as additive DoctorReport.engine / DoctorReport.db_url_source JSON fields (schema_version stays 2). runDoctor is a thin wrapper: buildChecks → computeDoctorReport → render + process.exit. All 10 process.exit sites stay in the wrapper; the two early-return paths (no engine, connection failure) return partial check lists instead of inline exits (observable output identical). Pinned by test/doctor-behavioral.test.ts (13 cases: pure aggregation math over computeDoctorReport, orchestrator cases for --fast skip set + --json flag + no-engine partial path + snapshot of load-bearing check names) and test/doctor-cli-smoke.test.ts (1 subprocess case spawning bun run src/cli.ts doctor --json against a fresh PGLite tempdir, asserting schema_version=2 envelope, status enum, non-empty checks array — the render-path coverage buildChecks-only tests miss; quarantined .serial because PGLite write-locks don't play with parallel runners). three checks wired into runDoctor() and the JSON envelope: oversized_pages (warns on pages exceeding content_sanity.bytes_warn), scraper_junk_pages (warns on live DB pages matching any junk pattern that escaped ingest), and content_sanity_audit_recent (reads the last 7 days of audit events, aggregates by pattern+source). Default scans the 1000 most-recent pages; --content-audit opts into a full scan. All three warn-only with paste-ready fix hints (junk → gbrain sources audit <id> + git rm source-of-truth, oversize → split or accept). two checks wired into runDoctor() + the JSON envelope: quarantined_pages (counts pages carrying the quarantine marker via engine.executeRaw JSONB ? existence, works on PGLite + Postgres; warn-only with a gbrain quarantine list hint) and flagged_pages (counts content_flag pages — searchable but odd; warn-only). Both skip gracefully (status ok, "Skipped") on engines/brains where the probe errors. Pinned by test/doctor.test.ts. home_dir_in_worktree: filesystem check walking up from gbrainPath() toward $HOME looking for a .git directory (main repo) or .git file (linked worktree pointer; Conductor + git-worktrees topology). Walk terminates at $HOME so a .git above the user's home doesn't false-positive. Honors GBRAIN_HOME (appends .gbrain to the override). Warn (not fail) with worktree-root path + paste-ready fix pointing at GBRAIN_HOME override or moving the brain. --remediation-plan [--json] [--target-score N] prints what would run (stable id, idempotency_key, severity, est_seconds, est_usd_cost, depends_on); --remediate [--yes] [--target-score N] [--max-usd N] submits each plan step as a Minion job in dependency order, re-checking score between steps. --target-score N defaults to 90; refuses to start when target exceeds maxReachableScore() and lists what's missing. --max-usd N is the cron-safety guard — submission refuses when the plan's est_total_usd_cost exceeds the cap. JSON envelope adds a Check.remediation field (additive, schema_version unchanged). Pinned by tests in test/doctor.test.ts. 4 checks: abandoned_threads, calibration_freshness, grade_confidence_drift (mitigation surface; math ships later), voice_gate_health. Schema health is a two-check pair: schema_version resolves through schemaVersionHealth (src/core/schema-version-health.ts, shared with the remote doctor report; a DB AHEAD of the client warns with an upgrade-this-client hint rather than suggesting migrations), and on ledger-current brains a read-only schema_columns check diffs live columns against the expected schema (detectMissingColumns, dynamically imported inside the ledger-current branch — positional guard in test/doctor-schema-column-diff.test.ts) and warns naming the missing columns with the gbrain init --migrate-only hint. Size ceiling: scripts/module-size-limits.tsv (per-change raise history: git log -p on that file). The ceiling covers the façade: re-exports, Check/DoctorReport and report scoring, the buildChecks flag parse, runDoctor, output rendering and --locks; every check block lives in a registry entry under doctor/checks/* (refactor wave 1 W4 doctor), remediation in doctor/remediate.ts, wave checks in doctor/wave-checks.ts.

  • src/commands/doctor/check-fix.ts (+ heartbeat.ts, checks/harness-wiring.ts, checks/agent-contract.ts) — doctor speaks agent contract v1. Check carries optional fix (stored Action; computeDoctorReport renders it for the report's transport via finalizeCheckFixes, redacted on http), fix_unavailable_reason (check_errored, operator_judgement, no_safe_automatic_fix, unstructured for legacy prose-only warns), severity: 'info' and readiness_state; schema_version stays 2 and status stays ok | warn | fail. Capabilities that are off by choice or not applicable yet (keyless embeddings and their staleness/vector checks, opt-in takes, no serve running, 0 pages, never-cycled empty or <24 h sources, backup before 25 pages+facts or 7 days via backupCoachingDue) report ok + info with the enable command as fix; the report adds capped_by: ['embeddings_disabled'] and, when the connection check is present and not ok, unknown_scores: ['brain']. top_issues[] gain action (the rendered fix) beside the legacy fix string. checkError(name, what, err) is the one "Could not …" shape (a gbrain db-repair fix when the error classifies as DB access). gbrain doctor --only <check>[,…] [--json] (parseOnlyChecks, onlyNeedsEngine, CLI runDoctorOnly) runs only the entries that emit those names plus the connection lane, engine-free when every name is a filesystem check, else connectEngine({ probeOnly: true }); unknown names exit 2 with the valid list; a requested check that produced nothing reports info/not_applicable (or check_errored after an early stop). It is every doctor fix's verify. harness_wiring reads the gbrain registration from ~/.claude.json (+ receipt .mcp.json), Codex config.toml (the user config, then the receipt workspace's .codex/config.toml) and opencode.json; under --only harness_wiring it smoke-tests it (live serve lock owner → wired_running; else spawn the registered argv, 15 s, initialize + tools/list + recall; gbrain_status replies reported with their reason/fix); it writes nothing. #6453: with no PGLite lock, an HTTP registration gets a credential-free 3 s GET of /health (probeHttpRegistration): gbrain ok → wired_running + mcp_access: 'unverified'; refused loopback http: → http_serve_missing + fix; else http_serve_unreachable/http_serve_unhealthy, no fix. redactRegistrationUrl strips userinfo, query and fragment from every printed URL (test/harness-wiring-redaction-6453.test.ts). agent_contract reads the whole size-bounded log (readAgentContractEvents(Infinity), 7-day window) and warns on internal_error/suggestion-less envelopes, consent refusals, derived_cap_exhausted and json_document_missing, with the user-only consent.preapprove.* command as fix. throttleDoctorHeartbeat: piped doctor progress emits at most one heartbeat per 5 s. Tests: test/doctor-status-set.test.ts, test/doctor-harness-smoke.test.ts, test/doctor-day-zero.test.ts (keyless init then doctor: 0 WARN, health ≥ 90), test/doctor-remote-parity.test.ts (run_doctor and CLI agree per shared check; run_doctor renders fixes for its transport). harness_wiring with no registration drops each detected harness a plugin lane covers (enabledPluginLanes; all → ok plugin_lane_enabled, not smoke-tested) or whose receipt-recorded config it cannot read (#7422; all → info registration_recorded); the warning names the rest. Claude Code detection also honors CLAUDE_CONFIG_DIR.

  • src/commands/doctor/registry.ts + src/commands/doctor/context.ts — the doctor check registry (refactor wave 1, W4 doctor). DOCTOR_CHECK_REGISTRY lists 126 DoctorEntry records { name, emits, run(ctx) -> Promise<Check[] | STOP_DOCTOR> } in output order; runDoctorRegistry(ctx) runs them, returns the checks gathered so far on STOP_DOCTOR, and otherwise finishes the DB-checks progress phase. The run is one withGitListingCache scope (src/core/git-visible-files.ts), so entries that list the same source checkout (frontmatter scan, fence census, slug collisions) share one git ls-files per listing and one "not a git repository" verdict per directory (ls-files, discoverGitRoot, the census HEAD probe; any repository-changing sync-git.ts command or invalidateGitListingCache() drops the scope's memo: test/git-listing-memo.serial.test.ts). Execution groups: filesystem-first entries (the resolver-health entry applies --fix before it scans), the no-engine connection lane plus a STOP when --fast or no engine, the live connection entry plus a STOP when getStats failed, then the DB entries, which take the engine via connectedEngine(ctx). GBRA-541: the entries that emit LOST_WRITE_CHECKS (git_index_lag, db_ahead_of_git, strict_facts_outside_git, owner_host_stale, uncommitted_sync_deletions) sit right after the privacy check, before the full scans, so slow scans on a large brain cannot use up the budget first (test/doctor-entry-deadline-6803.test.ts). DoctorContext carries the parsed flags (jsonOutput, fastMode, doFix, dryRun, scope, orphanRatioSourceId, args), engine, dbSource, connectError, progress, the skills-dir resolution and the cross-entry values autoFixReport, schemaVersion, connectionFailed, each written by the entry that computes it. Entry modules (one run* function per former buildChecks block, moved verbatim): checks/skill-group.ts, local-runtime.ts, supervisor-health.ts, local-audits.ts, db-connection.ts (also pgbouncerPrepareCheck, classifiedConnectionCheck — a live serve owner warns with the exclusive two-step fix, a pglite_busy reason legacy_owner_unverified fails with details.reason and the refusal's ask_user preview fix, anything else is classified for db-repair — and the two STOP gates), schema-health.ts, embedding-health.ts, graph-health.ts, data-integrity.ts, content-quality.ts, knowledge-health.ts, queue-assets.ts, sync-search.ts; checks/legacy-token-grants.ts (F3) emits legacy_token_grant_shape (info: active tokens still on the JSONB-only grant shape, fix gbrain auth rescope --migrate-legacy) and legacy_token_grant_drift (warn: per-token drifted axes with the two adopt commands); checks/grant-new-ops.ts (D4) emits grant_new_ops_available (warn: active clients and tokens whose operation snapshot or stored surface keeps operations their scopes allow out of reach, with proven blockers apart from inferred grant age, per-grant names in details, and an ask_user fix whose rescope argv differs for tokens and clients; --operations all is a disclosed choice, never the fix; a grant missing only operations the owner approves by name stays ok, its message naming them with the by-name command); checks/upgrade-health.ts holds checkUpgradeErrors / checkSelfUpgradeHealth / upgradeErrorResolved (re-exported by the façade). A pre-gate entry declares the names it only emits with a connected engine in engineChecks (#6303), so onlyNeedsEngine connects for --only of them; test/doctor-only-engine-checks.test.ts is the drift guard. To add a check: add an entry in the topic module, place it in DOCTOR_CHECK_REGISTRY where its output belongs, and categorize every emitted name in src/core/doctor-categories.ts. Tests: test/doctor-registry.test.ts (category contract with FAIL/Why/Fix/See, emits[] equals the AST walk, STOP positions), test/doctor-mode-matrix.serial.test.ts (entries run, STOP point, engine calls and --fix mutations per mode), and the W0 goldens test/doctor-registry-golden.test.ts (the AST walker follows runDoctorRegistry into the registry), test/doctor-early-stop-golden.serial.test.ts, test/doctor-json-golden.test.ts.

  • src/commands/doctor/ — the doctor module directory behind the doctor.ts façade. checks/ holds the check functions, grouped by concern (core-health.ts, queue-jobs.ts, extraction-sync.ts (its sync_freshness check excludes sources disabled by isSyncDisabledConfig and adds --no-pull to its sync hint on a managed brain; a source whose root syncContentDirectory resolves to a gbrain content directory counts as content_directory_count (ok, hint gbrain import <dir> --source <id>), never a failing gbrain sync hint (#9471); content_hash_duplicates prescribes GBRAIN_SOURCE=<id> gbrain delete <bare-slug> --force per wrong-root pair, naming each source when pairs span several, and never a hard purge; cycle_freshness in consolidation-cycle.ts still monitors their maintenance; its atom_provenance_drift check scopes drift to page-bound atoms and splits it into source_changed / source_gone; atoms with no source_slug — transcript-origin source_path-only rows, hashed over a file, with page liveness unresolvable by slug — count as their own slug_unbound, outside the drift total and the WARN ratio), graph-embedding.ts, search-eval.ts, calibration.ts, consolidation-cycle.ts, pglite-worker.ts, routing-federation.ts (source_routing_health exempts zero-page skill-pack sources), verbs-reflex.ts, stale-mentions.ts, timeline-history.ts (timeline_history: database-only timeline rows, bounded to 2,000 pages / 10 s per run, cursor in config doctor.timeline_history.scan:<sources> so runs finish a pass (a clean pass stays ok until a newer row; doctor-timeline-history-cursor-5821.test.ts), exact-or-lower-bound counts (lower bound past 10,000 found pages), non-round-trippable rows informational, repair gbrain repair timeline; segmented pages counted apart (segmented_*), no repair advice), derived-visibility.ts (derived_visibility: atoms and synthesized concepts without explicit visibility or looser than their origin (an origin a rename moved counts through slug_rename_history, GST-2687), one exact aggregate, repair gbrain repair visibility), engine-fit.ts — the last carrying pglite_scale + the engine-free db_repair_recurrence over the db-repair receipts); schema-pack-checks.ts, report-remote.ts, bootstrap-checks.ts, and skill-checks.ts are the four tail-cluster modules (schema-pack checks, the remote/thin-client doctor report, bootstrap checks, skill checks). harness-hook-checks.ts (harnessHookCarrierChecks, called from bootstrap_harness_health) reads each receipt-named Claude Code hook carrier read-only: an event wired more than once by this install warns harness_hook_duplicates with a consented re-run carrying the install's --project/--no-capture choices, a lookalike it did not write warns harness_hook_unowned (operator judgement), an unparseable carrier warns naming the file, and entries the host stripped of their marker are an ok info row; plugin_lane_collision iterates enabledPluginLanes. multiSourceDriftCheck is the one local/remote multi_source_drift verdict: on a managed brain (managedPersistenceEnabled) its sync advice names --no-pull and drops --include-gitignored, unmanaged wording is unchanged, and any skipped source keeps it warn/not_verified. src/core/multi-source-drift.ts derives a git-root-pinned source's slug prefix from its git toplevel (realpaths, empty at the repo root) and skips only a source whose toplevel cannot be resolved (git_root_skipped). It drops every walked path sync would refuse (unsyncableReason(prefix + relPath): metafiles such as root AGENTS.md/CLAUDE.md, pruned dirs, malformed names) before probing, so a same-slug page on default is not reported for a file sync never imports (#6681). graph-health.ts graph_coverage, like onboard's link and timeline coverage, is ok (not applicable, with the count) below MIN_ENTITY_PAGES_FOR_COVERAGE (5) eligible entity pages. graph_coverage and orphan_ratio count the entity types the active schema pack declares (#4772, src/core/schema-pack/entity-types.ts, resolved per source: brain-wide for graph_coverage, the asked source for orphan_ratio --source); a pack that does not load makes graph_coverage a warn naming the pack (never the old hardcoded list) and orphan_ratio answers with an "entity count unknown" caveat instead of a vacuous ok. All are re-exported by the façade. Structural guards that pin doctor source text load it through test/helpers/doctor-source.ts: doctorSource() concatenates the façade plus every src/commands/doctor/**/*.ts (façade first, then sorted) so a module move can never take a pinned string out of a guard's sight; doctorFileSource(rel) reads one named file for positional/ordering assertions; the helper also feeds the doctor-source-helper detector in scripts/classify-tests.ts. facadeExpansion in scripts/generate-flag-registry.ts keeps this directory on the doctor command's flag-scan surface. Two read-only derived-data checks live beside them: timeline-orphans.ts (timeline_orphans, samples 500 pages for rows an earlier page version produced that the current text no longer does; fix is gbrain extract timeline --prune-orphans) and slug-collisions.ts (slug_collisions, walks each live source checkout with collectSyncableFiles and reports paths that map to one slug plus the indexed one; sources without a checkout are skipped). checks/graph-embedding.ts checkJunkEntityHubs (#6158) splits connector contact pages (frontmatter google_contact_id or a connector source kind) into details.connector_twins with their main-brain canonical_twin, never calls them extractor-minted or offers junk_hub_exempt, and carries fix_unavailable_reason: 'operator_judgement' while the defer-to-twin policy is open.

  • src/commands/doctor/checks/default-source-path.ts — the doctor-surface gathering wrapper: reads the default row, page counts (live + file-backed), sync.repo_path, the leak-guard collision and every other live source with a relative local_path (all named), then hands the verdict to assessDefaultSourcePath. Reads fallback inputs only for a null pointer; null on skip with no relative source.

  • src/commands/doctor/checks/fts-reindex.ts — ftsReindexIncompleteCheck(engine): the fts_reindex_incomplete check. Reads the fts.reindex_in_progress config row that reindex-search-vector sets before its trigger-language flip and clears only after both backfills finish; null (nothing pushed) when absent, fail naming the language and the resume command (GBRAIN_FTS_LANGUAGE=<lang> gbrain reindex-search-vector --yes) when set, because un-backfilled rows are unreachable by keyword search under the new configuration. Registered in doctor.ts inside the engine !== null lazy-import guard (skipped on --fast / DB-down); category brain. Pinned by test/doctor-fts-reindex-incomplete.test.ts.