Garry's Opinionated OpenClaw/Hermes Agent Brain
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 afterembedding_env_overrideso--onlyconnects the brain, and indoctorReportRemote): the effective chain, its plane, shadowed values, providers and refusal behavior fromsrc/core/ai/chat-fallback-planes.ts. An active, healthy chain isokwith the optional per-plane removal fix (nevernext: run); an unreadable plane value or a malformed / unknown-provider / no-chat entry warns with the removal fix, a missing credential with acredentialsfix, an unpriced model under a user cap withnoPricingFix. Remote (remote !== false): only that a chain is configured and its problem count,host_adminfix. Pinned bytest/doctor-chat-fallback-chain.test.ts.src/commands/doctor/checks/behavior-changes.ts—behavior_changes(META, afterchat_fallback_chain): thebehavior_changesdisclosure 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; alwaysok; reads the baseline and markers without recording either, and reports which channels were shown.src/commands/doctor/checks/ranking-extraction.ts— informational BRAIN checkextraction_date_grounding, registered aftertimeline_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 bytest/doctor-ranking-extraction.test.tsand 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 statementsearchVectoremits for the active embedding column with a zero vector throughPostgresEngine.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.reltuplesxpg_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 togbrain embed --staleabove 5%. Tested intest/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 inwave-checks.ts);persistence_terminal_failures(#6650) is in Managed sync bookkeeping.persistence_request_indexes(#5762) reports each request index missing, INVALID or building, naminggbrain repair request-indexes --apply, and 3+ consecutive dream postprocess deferrals (#6757).persistence_request_growthreports the request-table row count (areltuplesestimate 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 againstpersistence.limits.*and the projected exhaustion date within ten years; it warns under 90 days with theoneYearCapacitygbrain config setvalue and the doctor re-check.persistence_write_stall(#6176, host-only) reads running requests and warns when one has held its claim longer thanpersistence.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, withgbrain sources writer status --source <id> --jsonas the fix.persistence_session_timeouts(#6278, host-only) readsSHOW statement_timeoutthrough the configured URL and warnssession_timeouts_not_appliedwhen it is0whileresolveSessionTimeouts()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 (viacapacityDiagnostics) and prints onegbrain 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 itsretry-effects ... --dry-runcommand. Both reportexact/inspected/truncateddetails; 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 withpages.database_only_reason='unbound_source'and no recorded origin (blanksource_pathandsource_uri) per source, viadatabaseOnlyPageSql(persistence/unbound-pages.ts), the SQL form ofisDatabaseOnlyPage(#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 filledsources writer status/writer claimbind 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 thepersistence_capacityline indoctor.ts. Tests:e2e/unbound-source-postgres,unbound-source-6536.src/commands/doctor/checks/revision-backfill.ts—revision_backfill(#5216, META, registered beforesearch_mode): readsreadRevisionBackfillStatus(column state, pages still withoutknowledge_revision, failed rows still pending with their page). ok when the column is NOT NULL; warn with the pending count andgbrain apply-migrations --force-schemaasfixwhile 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 thefixis the read-onlygbrain repair orphan-childrenpreview. 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;excludedreported but never a finding) throughclassifyExtractorFacts, and namesgbrain 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, aWAVE_CHECKSentry withresolution: 'repair', host-only, cleared by the explicit-onlyatoms-restore, so remediation classifies itexplicit_kind_required): counts therestorablerows ofatomRetirementsSqlper source;warnnames the count, origins, oldest and newestretired_at, the end of the earliest purge hold (hold_until) and the read-only previewgbrain repair atoms-restore --source <id> --jsonas an agentfix; the apply is the user's call.src/commands/doctor/checks/conversation-outcomes.ts—conversation_label_facts(wave check, host-only, resolutionrepair): bounded count (capped at 1000, reported as at least N) of the default setgbrain repair conversation-labelswould retire; names the preview, never the apply.conversation_outcomes_stale(wave check, host-only, resolutionoperator): counts active conversation extraction outcomes stamped with an olderextractor_versionthanCONVERSATION_EXTRACTOR_VERSION(outcomes are never reopened automatically) and names the--force --dry-runre-extract preview; outcomes older than the stamp are counted asunstampedand 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) thatclassifyCapturedFactsclasses as self-capture (evidenced) or paste candidates (ambiguous);excludedandunclassifiableare reported, never a finding. Namesgbrain repair captured-facts(explicit-only) and says it counts facts whileself_capturecounts 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-onlygbrain repair redacted-factspreview. 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 namesgbrain 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-fixextract_factsfence step moved onto an entity page's Facts table, restorable ones by state (fenced,retired) plusexcluded(withdrawn, consolidated, duplicate; never a finding), throughclassifyOntologyFacts, and namesgbrain 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_eventsandauto_chronicle_default_on(#5876, #8972), registered afterunlinked_facts, config-plane only (no provider calls).auto_chronicle: off by choice is ok withseverity: info,readiness: disabled_by_choice; an invalid word warnsauto_chronicle_invalid; when on it readscore/chronicle/ledger-stats.tsand warnsjudge_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, andgbrain dream --phase chronicle. Every warn carries adetails.fixAction andfix_hint.chronicle_config_invalidwarns on an out-of-range storedchronicle.*value.auto_chronicle_default_onis ok/info withask_userand keep/opt-out decisions untilgbrain 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 afterauto_chronicle: per unarchived source (honoring--source), active facts (eligibleFactEmbedding+staleFactEmbedding) and takes (countStaleTakeswith the DB-plane model and width) with no vector for their current text, split into missing versus other-model, plusfacts.partially_embedded(current vectors of facts overEMBED_MAX_CHARS,partiallyEmbeddedFact; reported, never re-embedded, #6975); warns with codestale_vectorsanddetails.fix(gbrain embed --stale, orgbrain takes embedwhentakes.auto_embedis off; per-sourcegbrain embed --facts --stale --source <id> --dry-run --json). Keyless brains reportapplicable: false; a brain with no recorded model or width warnsvectors_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 fromreadHeldCoverage(missing vs stale counts) and the first five paths fromreadGitHoldListingwith each one's code andgitHoldFixstep, 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>forinvalid_fenceholds, both for a mixed source; with fence holds the details addfencesandauto_repair, and the banner line names the fence repair through the wave entry'sbannerHow);failonce a source holds more thansync.hold_escalate_count;details.visibility_noncanonicalcounts held files and stored non-canonical private pages; connector holds stay onconnector_held_items.frontmatter_repairable(emitted inline by thefrontmatter_integrityentry from the samescanBrainSourceswalk, whosePerSourceReport.repairablecounts files by repairable cause: recoverableYAML_PARSE,needs_interpretation,FRONTMATTER_COMMENT_VALUEon title/name/description/summary,NESTED_QUOTES,NULL_BYTES,MISSING_CLOSE,SLUG_MISMATCH); a deadline-partial scan setsdetails.partial; the doctor scan passesfrontmatterOnly, so each file's head through its closing fence is validated whenfrontmatterScanHeadproves the findings equal, else the whole file (test/brain-writer-frontmatter-scan-head.test.ts). Both listdetails.source_idsand belong to the explicit-onlyfrontmatterkind, so remediation classifies themexplicit_kind_requiredwith--source <id>when one source is named.frontmatter_hook(wave, operator): gbrain pre-commit hooks older thanFRONTMATTER_HOOK_VERSION, fixgbrain frontmatter install-hook --source <id> --force.frontmatterHoldsBannerNote(aPOST_UPGRADE_NOTESentry) names sources whose unfinished managed cursor stopped on a failed content refusal: the next sync (orgbrain sync --source <id> --no-pullnow) recovers them, plus the repair preview and the hook refresh.fenceHoldsBannerNote(a separatePOST_UPGRADE_NOTESentry) 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-pullnow), the stored census's malformed fences and whether the next maintenance run repairs them, the read-onlygbrain repair fencespreview and the pause commandgbrain 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,resolutionrepair/operator/unsupported, count-free remoteimpact, operatorinstruction,countfor banners,bannerHowwhen a finding's details change the banner's parenthetical,registrationinline-in-doctor.ts or from this table).fence_integrity(#6188,repair, registered inline) countsdetails.total; its banner line says "repaired automatically by the next maintenance run" while one is active (fromdetails.auto_repair), else why not, withgbrain repair fencesas the preview; a fence-onlygit_held_filesfinding gets the same wording, a mixed one adds it to the frontmatter preview.runWaveChecks(idsfor--only, #7343) turns a throwing check into anunknownfinding;checkHealthUnknownreadsdetails.health === 'unknown'.remoteWaveHandoffreturns one line per remotely offered check withdetails.host_action{check_id,stateok/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/--remediateCLI shell (re-exported from doctor.ts): per-stepcommand(gbrain jobs submit …for job steps,gbrain repair <kind> --applyfor repair steps; a repair step withllm_usdnames 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 --jsonreports asplan_hash), aRepair kinds whose preview failedblock forrepair_preview_failures(each{kind, code, message, why, fix}; such a kind is not planned, so a plan approved while it failed refusespreview_changedonce it succeeds),REMEDIATE_HELP,--include-repairs/--no-embed/--resumehandling, 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.partialis pending; an explicit-only kind's preview gets--source <id>viafindingSourcewhen the finding names one source;--remediation-planruns the wave checks too and reports the same classification asfindings) andremediationExitStatus(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 throughsetCliExitVerdict; 3 when consent is required), set throughsetCliExitVerdict. Consent (agent operator wave C1) lives indoctor/remediate-consent.ts: the CLI connects probe-only (no migrations) and computes the plan; when anything would run it callsrequireConsent(effectspaid, plusdestructivewith--include-repairs, bound to aplan_hashover 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;--jsonnever implies consent;--yeswithout--max-usdruns under the derived cap (estimate ×1.5, floor $0.25; the default cap when unpriced), and derived-cap exhaustion prints the--max-usdresume command. Startup (migrations) completes only after consent. A--resumeis bound by its checkpoint manifest, not a new plan hash. Pinned bytest/doctor-remediate-consent.test.ts.src/commands/doctor/checks/global-maintenance-stalled.ts—global_maintenance_stalled(GBRA-130 C-6, #6837): reportsassessGlobalMaintenanceStallfromsrc/core/minions/global-maintenance-stall.ts. Warns whenautopilot.last_global_atis older than three global intervals (autopilot.global_floor_min, default 60 min) andautopilot-global-maintenancejobs 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 whosefail:streak reached three passes. It also warns when passes stamp past adeferredstreak whose count stopped shrinking (#7307). The message names the phase, its blocker key and back-off;fixisgbrain dream --phase <p>(paid consent) thengbrain autopilot --retry-global --phase <p>, or for adeferredstreakgbrain dream retriage(paid consent,--dry-run --jsonpreview), orgbrain 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-scoreare unaffected). Pinned bytest/pathological/a10-global-maintenance-stamp.test.ts.src/commands/doctor/checks/global-maintenance-timeouts.ts—global_maintenance_timeouts(#4578): warns when the last three finishedautopilot-global-maintenancejobs died at their deadline, or one phase was running in three consecutive job deaths (read from configautopilot.global_maintenance.progress), or (#6303) the last three finished dreampatterns/synthesizesubagent children (keyed by idempotency prefix) all died at their owntimeout exceededwhile the jobs completed, namingdream.<phase>.subagent_timeout_ms(details.child_timeouts). Details carrycode,cause,fix(gbrain dream --phase <name>, else the deadline config key) and thedocs/guides/troubleshooting.md#global-maintenance-timeoutsanchor. Pinned bytest/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 asok. Live rowsfailwith the filled recovery.legacyJobAuthorityBannerNotefeeds the banner. The same check counts queued paid jobs by spend basis (details.queued_spend) and warns, with the read-only fixgbrain 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);legacyDefaultSpendBannerNotenames queuedlegacy_defaultrows 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 operatorblock (brain, per-finding count and resolution, refined by the check'sbannerHow, the read-onlygbrain doctor --remediation-plan, ask before applying), never an applying command; empty for a clean brain.POST_UPGRADE_NOTESlets other subsystems add lines (fenceHoldsBannerNoteamong 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, namesgbrain repair safe-chunks; kept code/image pages are informational),self_capture(BRAIN, #5413: corpus.txtfiles whose session id matches a gbrain claude-cli scratch transcript are classified, ones with no harness transcript left are unclassifiable; classification isisClaudeCliSelfSessionId; details carrynewest_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 withdetails.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.tsreadManagedSyncBacklog); 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: unsupporteddiscard()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-migratekeeps doctor observational: the CLI connects withprobeOnlyso a clean-or-behind schema is reported as-is instead of being auto-migrated before the checks run. The file is a façade carryingbuildChecks(flag parse into aDoctorContext, thenrunDoctorRegistry),runDoctorand output rendering; the checks run as the ordered registry insrc/commands/doctor/registry.ts(see that entry), the check-function library lives in bundles undersrc/commands/doctor/checks/plus four tail-cluster modules undersrc/commands/doctor/(see that entry), all re-exported here so the full surface is unchanged — structural guards pin its source text viatest/helpers/doctor-source.ts, never by reading this file alone. Checks includejsonb_integrity+markdown_body_completeness(reliability),schema_version(fails loudly whenversion=0, routes togbrain apply-migrations --yes; a version AHEAD of this client'sLATEST_VERSIONwarns "upgrade this client"; and when the ledger reads current, a read-onlydetectMissingColumnsdiff fromsrc/core/schema-verify.tsruns INSIDE the ledger-current branch — a PgBouncer-swallowed ALTER TABLE can advanceconfig.versionover a physically narrower table, so missing live columns downgrade the ok to a warn naming them with thegbrain init --migrate-onlyhint; diff failure is best-effort and the ledger ok stands; positional wiring pinned bytest/doctor-schema-column-diff.test.ts),upgrade_errors(asynccheckUpgradeErrors(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 viaengine.getConfig('version'); a missing engine or unverifiable schema keeps the warn, fail-closed, becauseself-upgradeswaps the binary beforepost-upgraderuns migrations and the binary alone can lie; pinned bytest/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 viaGBRAIN_QUEUE_WAITING_THRESHOLD, and dead-lettered subagent jobs withlast_errormatching theprompt_too_longclassifier in last 24h),sync_failures([CODE=N, ...]breakdown for unacked-warn + acked-ok; severity comes from the shareddecideSyncFailureSeverityinsrc/core/sync-failure-ledger.tsso 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 alreadyauto_skippedrows stay a visible WARN),rls_event_trigger(healthyevtenabledset is('O','A')only; fix hintgbrain apply-migrations --force-retry 35),graph_coverage(short-circuits to ok whenSELECT COUNT(*) FROM pages WHERE type IN ('entity','person','company','organization')returns 0; WARN hint isgbrain extract all),embedding_column_registry(probes each declared column via Postgresformat_type(atttypid, atttypmod)to catch dim mismatch with a paste-readygbrain config set embedding_columns '{...}'hint, probes HNSW index presence viapg_indexes, computes default-column population viaCOUNT(*) FILTER (WHERE <col> IS NOT NULL) / COUNT(*)warning below 90% except empty brains where chunk_count=0 short-circuits to ok; PGLite parity viaexecuteRaw), andskill_brain_first(walks SKILL.md viaautoDetectSkillsDirReadOnly, callsanalyzeSkillBrainFirst()fromsrc/core/skill-brain-first.tsper file with structuredCheck.issues[]; warn statesmissing_brain_first/brain_first_typo, ok statescompliant_callout/compliant_phase/compliant_position/exempt_frontmatter/no_external; snapshot+diff audit at~/.gbrain/audit/skill-brain-first-YYYY-Www.jsonl).--fixdelegates inlined cross-cutting rules to> **Convention:** see [path](../path).callouts viasrc/core/dry-fix.ts(and MISSING_RULE_PATTERNS for the brain-first callout);--fix --dry-runpreviews.--index-audit(Postgres-only, informational, no auto-drop) reports zero-scan indexes frompg_stat_user_indexes. Every DB check runs under a progress phase;markdown_body_completenessruns under a 1s heartbeat.runDoctorusesautoDetectSkillsDirReadOnly(fromsrc/core/repo-root.ts; install-path fallback socd ~ && gbrain doctorfinds bundled skills);--fixcarries a D6 install-path safety gate that refuses auto-repair whendetected.source === 'install_path'(would rewrite the bundled tree). The Lane D supervisor check (doctor/checks/supervisor-health.ts) consumessummarizeCrashes(events)fromsrc/core/minions/handlers/supervisor-audit.ts(warn at>=1real crash; ok message hasclean_exits_24h=N; warn message hasruntime=A oom=B unknown=C legacy=Dper-cause breakdown) so OOM/runtime/unknown crashes are distinguishable from clean code=0 worker drains; cross-surface parity withgbrain jobs supervisor statusis pinned by source-grep wiring assertions requiring the breakdown substrings on the doctor surface and injobs.ts.checkSyncFreshness(exported, inrunDoctorlocal +doctorReportRemotethin-client) is a staleness probe: warns at 24h, fails at 72h or never-synced; future-last_sync_atwarns ("clock skew") instead of falling through ok; env overridesGBRAIN_SYNC_FRESHNESS_WARN_HOURS/GBRAIN_SYNC_FRESHNESS_FAIL_HOURS(invalid fall back with once-per-process stderr warn via_resolveSyncFreshnessHours); failure messages embedsource.idso the printedgbrain sync --source <id>matches. A source holding a LIVE, non-expired per-source sync lock (inspectLock(engine, syncLockId(source.id))fromsrc/core/db-lock.ts) is reported as actively syncing (the message names the holder pid + host) and counted insynced_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 dynamicdb-lockimport 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 alocalOnly-gated git short-circuit (runDoctorpasseslocalOnly: true;doctorReportRemoteruns in the HTTP MCP serversrc/commands/serve-http.tsand keeps defaultfalseso that path never walks DB-suppliedlocal_pathvia subprocess — trust boundary). The local predicate mirrors sync's "do work?" gate (HEAD ==last_commitAND working tree clean viarequireCleanWorkingTree: 'ignore-untracked'so a quiet repo with only untracked dirs isunchangednot SEVERE, ANDchunker_version === CURRENT); the inline SELECT carrieslast_commit + chunker_version + newest_content_at. The REMOTE path computes lag vialagFromContentMs(newest_content_at, lastSync, now)from the stored column, NO git subprocess; LOCAL fall-through and the< 0clock-skew check stay on raw wall-clock. Three-bucket count math populatesCheck.details = {unchanged_count, synced_recently_count, stale_count}with the invariantsum === sources.length.checkCycleFreshnessis DELIBERATELY NOT git-short-circuited or content-relativized (last_commit == HEADcan't answer "did the full cycle complete?"; a sync can succeed while later cycle phases fail; different axislast_full_cycle_at). Pinned bytest/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 whenlocalOnlyis unset/false, the three-bucket invariant, and the untracked-folders / remote-never-shells-out trust-boundary cases).pglite_data_dircheck: fs-only check that runs when a PGLite brain FAILS to connect (!fastMode && !engine && config.engine === 'pglite', placed afterorphan_clones, before the DB-checks gate;pgliteDataDirEntryindoctor/checks/db-connection.ts):computePgliteDataDirCheck(dataDir, diagnosis)(exported pure fn,computeWorkerOomLoopCheckconvention) maps theinspectPgliteDataDirverdict to a Check — corruption-likely/looks-healthy-but-unopenable/unsupported-layout →failnaminggbrain pglite-repair --dry-run/--yesor the rebuild path, live-lock/missing-dir →warn; allremediation_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 indoctor-categories.tsOPS_CHECK_NAMES. Pinned bytest/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 + thepages delete→purge-deleted --older-than 0remediation);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 withsourceGitScopeand passes it toresolveSourceLocalFilePathasgitScope;connector_databasesources are skipped and counted in the message);db_only_collector_collision(configured recipeoutput_pathsinside a declared db_only dir — auto-gitignore means sync AND import silently skip the collector's files; same warning fires in sync'smanageGitignoreat config-write time). All warn-level, engine-parity pinned bytest/e2e/doctor-silent-death-parity.test.ts; units intest/doctor-silent-death-checks.test.ts.graph_signals_coveragecheck wired into bothrunDoctor(local) anddoctorReportRemote(HTTP/JSON thin-client path). Readssearch.graph_signalsconfig first, falls back to mode default; silentokwhen disabled. Computes inbound link coverage on the page set; warns at <10% withgbrain extract allfix hint;okat ≥30% ("fire on most queries") and 10-29% ("fire occasionally"), each with the percentage embedded. Pinned by cases intest/doctor.test.ts.subagent_capabilitycheck (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 fixgbrain config set models.tier.subagent anthropic:claude-sonnet-4-6); also warns whenmodels.defaultwould sneaksubagentinto a non-Anthropic provider via tier inheritance. OK when subagent tier resolves to Anthropic. Tests intest/doctor.test.ts.computeWorkerOomLoopCheck(engine)is the single authoritative OOM-loop signal, unioning supervisedsummarizeCrashes(readRecentSupervisorEvents(24)).by_cause.rss_watchdog(cross-week read viareadRecentSupervisorEventsso a Monday window can't lose Sunday) + bare-workerminion_jobs error_text='aborted: watchdog'count (Postgres-only; the same sourcequeue_healthsubcheck 3 reads). Cap comes from the latestrss_watchdog_loopbreaker alert'smax_rss_mb, elseresolveDefaultMaxRssMb()fallback. fail at breaker-tripped or oomKills≥5, warn at ≥1, null otherwise.computePoolReapHealthCheck(engine)is the Postgres-onlypool_reap_healthcheck readingreadRecentPoolRecoveries(1)— fail when reconnect failures>0 (reconnect throwing is the actionable signal), warn at ≥10 reaps/hr (pooler thrash), null otherwise. Both registered by thesupervisorregistry entry after thesupervisorblock. ThesupervisorcauseStr carriesrss=N (see worker_oom_loop)andqueue_health's watchdog message cross-referencesworker_oom_loop.DoctorReport.top_issues+ the cause-ranked render header.worker_oom_loop+pool_reap_healthregistered under ops indoctor-categories.ts. Pinned bytest/doctor-worker-oom-loop.test.ts,test/doctor-pool-reap-health.test.ts.supervisor_singletoncheck, a SEPARATE check fromsupervisor(same split precedent as the niceness check) so a singleton-divergence warn can't clobber the crash/liveness precedence. Runs only when astartedsupervisor 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 pureclassifySupervisorSingleton.mismatch→ warn (a second supervisor may be running with a different--max-rss; message names both holders, the effective cap from thestartedevent'smax_rss_mb, and the fixgbrain 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 hostnamesingle→ok+host_label_drift; a two-line legacy file warnssame_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 indoctor-categories.tsassupervisor_singleton. Pinned bytest/supervisor-db-lock.test.ts+test/doctor.test.ts.checkBatchRetryHealth:batch_retry_healthcheck surfacing Supavisor circuit-breaker incidents. Wired into bothrunDoctor(local) anddoctorReportRemote(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 badGBRAIN_BULK_*env at doctor startup. Corrupt-JSONL tolerant. Paste-ready fix hints in every warn/fail message. Also readsreadRecentDbDisconnects(24)and appendsDisconnect-call audit: N call(s) in 24h (most recent caller: <frame>).to ALL three message paths so connection-incident signal is greppable from onegbrain doctor --jsoncall (module-import wrapped in try/catch so older brains without the audit file degrade silently). Pinned bytest/doctor-batch-retry.test.ts(10 cases). three checks wired intorunDoctor()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 whosesource_iddoesn't match whatresolveSourceWithTier()would have picked for theirsource_path; single-source brains short-circuit took; the 200-page cap is total across the brain so doctor stays under 5s. (2)checkOauthConfidentialHealth(engine)probes registered confidential clients for/tokenreachability. (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 bytest/doctor-v0_37_7_checks.test.ts.buildChecks(engine, args, dbSource, connectError?): Promise<Check[]>exported as a test seam; the optionalconnectErroris the connect failure captured by the CLI's dead-DB fallback, which the null-engine path turns into a SYNTHESIZED classifiedconnectionfail entry (sochecks[name=="connection"]exists in every failure shape — smoke-test branches on it). Theconnectioncheck's failure path classifies viasrc/core/pg-access-classify.tsinto a redacted message +details: {reason, transient, fix_hint}naminggbrain db-repair(deliberately NOTremediation[]/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-onlypgbouncerPrepareCheckhelper and the engine-freedb_repair_recurrencecheck 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 additiveDoctorReport.engine/DoctorReport.db_url_sourceJSON fields (schema_version stays 2).runDoctoris a thin wrapper:buildChecks → computeDoctorReport → render + process.exit. All 10process.exitsites 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 bytest/doctor-behavioral.test.ts(13 cases: pure aggregation math overcomputeDoctorReport, orchestrator cases for--fastskip set +--jsonflag + no-engine partial path + snapshot of load-bearing check names) andtest/doctor-cli-smoke.test.ts(1 subprocess case spawningbun run src/cli.ts doctor --jsonagainst a fresh PGLite tempdir, asserting schema_version=2 envelope, status enum, non-empty checks array — the render-path coverage buildChecks-only tests miss; quarantined.serialbecause PGLite write-locks don't play with parallel runners). three checks wired intorunDoctor()and the JSON envelope:oversized_pages(warns on pages exceedingcontent_sanity.bytes_warn),scraper_junk_pages(warns on live DB pages matching any junk pattern that escaped ingest), andcontent_sanity_audit_recent(reads the last 7 days of audit events, aggregates by pattern+source). Default scans the 1000 most-recent pages;--content-auditopts into a full scan. All three warn-only with paste-ready fix hints (junk →gbrain sources audit <id>+git rmsource-of-truth, oversize → split or accept). two checks wired intorunDoctor()+ the JSON envelope:quarantined_pages(counts pages carrying thequarantinemarker viaengine.executeRawJSONB?existence, works on PGLite + Postgres; warn-only with agbrain quarantine listhint) andflagged_pages(countscontent_flagpages — searchable but odd; warn-only). Both skip gracefully (status ok, "Skipped") on engines/brains where the probe errors. Pinned bytest/doctor.test.ts.home_dir_in_worktree: filesystem check walking up fromgbrainPath()toward$HOMElooking for a.gitdirectory (main repo) or.gitfile (linked worktree pointer; Conductor + git-worktrees topology). Walk terminates at$HOMEso a.gitabove the user's home doesn't false-positive. HonorsGBRAIN_HOME(appends.gbrainto the override). Warn (not fail) with worktree-root path + paste-ready fix pointing atGBRAIN_HOMEoverride or moving the brain.--remediation-plan [--json] [--target-score N]prints what would run (stableid,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 Ndefaults to 90; refuses to start when target exceedsmaxReachableScore()and lists what's missing.--max-usd Nis the cron-safety guard — submission refuses when the plan'sest_total_usd_costexceeds the cap. JSON envelope adds aCheck.remediationfield (additive, schema_version unchanged). Pinned by tests intest/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_versionresolves throughschemaVersionHealth(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-onlyschema_columnscheck diffs live columns against the expected schema (detectMissingColumns, dynamically imported inside the ledger-current branch — positional guard intest/doctor-schema-column-diff.test.ts) and warns naming the missing columns with thegbrain init --migrate-onlyhint. Size ceiling:scripts/module-size-limits.tsv(per-change raise history:git log -pon that file). The ceiling covers the façade: re-exports,Check/DoctorReportand report scoring, thebuildChecksflag parse,runDoctor, output rendering and--locks; every check block lives in a registry entry underdoctor/checks/*(refactor wave 1 W4 doctor), remediation indoctor/remediate.ts, wave checks indoctor/wave-checks.ts.src/commands/doctor/check-fix.ts(+heartbeat.ts,checks/harness-wiring.ts,checks/agent-contract.ts) — doctor speaks agent contract v1.Checkcarries optionalfix(storedAction;computeDoctorReportrenders it for the report's transport viafinalizeCheckFixes, redacted on http),fix_unavailable_reason(check_errored,operator_judgement,no_safe_automatic_fix,unstructuredfor legacy prose-only warns),severity: 'info'andreadiness_state;schema_versionstays 2 and status staysok | 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 viabackupCoachingDue) reportok+infowith the enable command asfix; the report addscapped_by: ['embeddings_disabled']and, when theconnectioncheck is present and not ok,unknown_scores: ['brain'].top_issues[]gainaction(the rendered fix) beside the legacyfixstring.checkError(name, what, err)is the one "Could not …" shape (agbrain db-repairfix when the error classifies as DB access).gbrain doctor --only <check>[,…] [--json](parseOnlyChecks,onlyNeedsEngine, CLIrunDoctorOnly) runs only the entries that emit those names plus the connection lane, engine-free when every name is a filesystem check, elseconnectEngine({ probeOnly: true }); unknown names exit 2 with the valid list; a requested check that produced nothing reportsinfo/not_applicable(orcheck_erroredafter an early stop). It is every doctor fix'sverify.harness_wiringreads the gbrain registration from~/.claude.json(+ receipt.mcp.json), Codexconfig.toml(the user config, then the receipt workspace's.codex/config.toml) andopencode.json; under--only harness_wiringit smoke-tests it (live serve lock owner →wired_running; else spawn the registered argv, 15 s, initialize + tools/list +recall;gbrain_statusreplies 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): gbrainok→wired_running+mcp_access: 'unverified'; refused loopbackhttp:→http_serve_missing+ fix; elsehttp_serve_unreachable/http_serve_unhealthy, no fix.redactRegistrationUrlstrips userinfo, query and fragment from every printed URL (test/harness-wiring-redaction-6453.test.ts).agent_contractreads the whole size-bounded log (readAgentContractEvents(Infinity), 7-day window) and warns oninternal_error/suggestion-less envelopes, consent refusals,derived_cap_exhaustedandjson_document_missing, with the user-onlyconsent.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_wiringwith no registration drops each detected harness a plugin lane covers (enabledPluginLanes; all →okplugin_lane_enabled, not smoke-tested) or whose receipt-recorded config it cannot read (#7422; all →inforegistration_recorded); the warning names the rest. Claude Code detection also honorsCLAUDE_CONFIG_DIR.src/commands/doctor/registry.ts+src/commands/doctor/context.ts— the doctor check registry (refactor wave 1, W4 doctor).DOCTOR_CHECK_REGISTRYlists 126DoctorEntryrecords{ name, emits, run(ctx) -> Promise<Check[] | STOP_DOCTOR> }in output order;runDoctorRegistry(ctx)runs them, returns the checks gathered so far onSTOP_DOCTOR, and otherwise finishes the DB-checks progress phase. The run is onewithGitListingCachescope (src/core/git-visible-files.ts), so entries that list the same source checkout (frontmatter scan, fence census, slug collisions) share onegit ls-filesper listing and one "not a git repository" verdict per directory (ls-files,discoverGitRoot, the census HEAD probe; any repository-changingsync-git.tscommand orinvalidateGitListingCache()drops the scope's memo:test/git-listing-memo.serial.test.ts). Execution groups: filesystem-first entries (the resolver-health entry applies--fixbefore it scans), the no-engine connection lane plus a STOP when--fastor no engine, the live connection entry plus a STOP whengetStatsfailed, then the DB entries, which take the engine viaconnectedEngine(ctx). GBRA-541: the entries that emitLOST_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).DoctorContextcarries the parsed flags (jsonOutput,fastMode,doFix,dryRun,scope,orphanRatioSourceId,args),engine,dbSource,connectError,progress, the skills-dir resolution and the cross-entry valuesautoFixReport,schemaVersion,connectionFailed, each written by the entry that computes it. Entry modules (onerun*function per formerbuildChecksblock, moved verbatim):checks/skill-group.ts,local-runtime.ts,supervisor-health.ts,local-audits.ts,db-connection.ts(alsopgbouncerPrepareCheck,classifiedConnectionCheck— a live serve owner warns with the exclusive two-step fix, apglite_busyreasonlegacy_owner_unverifiedfails with details.reason and the refusal's ask_user preview fix, anything else is classified fordb-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) emitslegacy_token_grant_shape(info: active tokens still on the JSONB-only grant shape, fixgbrain auth rescope --migrate-legacy) andlegacy_token_grant_drift(warn: per-token drifted axes with the two adopt commands);checks/grant-new-ops.ts(D4) emitsgrant_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 allis a disclosed choice, never the fix; a grant missing only operations the owner approves by name staysok, its message naming them with the by-name command);checks/upgrade-health.tsholdscheckUpgradeErrors/checkSelfUpgradeHealth/upgradeErrorResolved(re-exported by the façade). A pre-gate entry declares the names it only emits with a connected engine inengineChecks(#6303), soonlyNeedsEngineconnects for--onlyof them;test/doctor-only-engine-checks.test.tsis the drift guard. To add a check: add an entry in the topic module, place it inDOCTOR_CHECK_REGISTRYwhere its output belongs, and categorize every emitted name insrc/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--fixmutations per mode), and the W0 goldenstest/doctor-registry-golden.test.ts(the AST walker followsrunDoctorRegistryinto the registry),test/doctor-early-stop-golden.serial.test.ts,test/doctor-json-golden.test.ts.src/commands/doctor/— the doctor module directory behind thedoctor.tsfaçade.checks/holds the check functions, grouped by concern (core-health.ts,queue-jobs.ts,extraction-sync.ts(itssync_freshnesscheck excludes sources disabled byisSyncDisabledConfigand adds--no-pullto its sync hint on a managed brain; a source whose rootsyncContentDirectoryresolves to a gbrain content directory counts ascontent_directory_count(ok, hintgbrain import <dir> --source <id>), never a failinggbrain synchint (#9471);content_hash_duplicatesprescribesGBRAIN_SOURCE=<id> gbrain delete <bare-slug> --forceper wrong-root pair, naming each source when pairs span several, and never a hard purge;cycle_freshnessinconsolidation-cycle.tsstill monitors their maintenance; itsatom_provenance_driftcheck scopes drift to page-bound atoms and splits it intosource_changed/source_gone; atoms with nosource_slug— transcript-originsource_path-only rows, hashed over a file, with page liveness unresolvable by slug — count as their ownslug_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_healthexempts 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 configdoctor.timeline_history.scan:<sources>so runs finish a pass (a clean pass staysokuntil 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, repairgbrain 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 throughslug_rename_history, GST-2687), one exact aggregate, repairgbrain repair visibility),engine-fit.ts— the last carryingpglite_scale+ the engine-freedb_repair_recurrenceover the db-repair receipts);schema-pack-checks.ts,report-remote.ts,bootstrap-checks.ts, andskill-checks.tsare the four tail-cluster modules (schema-pack checks, the remote/thin-client doctor report, bootstrap checks, skill checks).harness-hook-checks.ts(harnessHookCarrierChecks, called frombootstrap_harness_health) reads each receipt-named Claude Code hook carrier read-only: an event wired more than once by this install warnsharness_hook_duplicateswith a consented re-run carrying the install's--project/--no-capturechoices, a lookalike it did not write warnsharness_hook_unowned(operator judgement), an unparseable carrier warns naming the file, and entries the host stripped of their marker are anokinfo row;plugin_lane_collisioniteratesenabledPluginLanes.multiSourceDriftCheckis the one local/remotemulti_source_driftverdict: on a managed brain (managedPersistenceEnabled) its sync advice names--no-pulland drops--include-gitignored, unmanaged wording is unchanged, and any skipped source keeps it warn/not_verified.src/core/multi-source-drift.tsderives agit-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 rootAGENTS.md/CLAUDE.md, pruned dirs, malformed names) before probing, so a same-slug page ondefaultis not reported for a file sync never imports (#6681).graph-health.tsgraph_coverage, like onboard's link and timeline coverage, isok(not applicable, with the count) belowMIN_ENTITY_PAGES_FOR_COVERAGE(5) eligible entity pages.graph_coverageandorphan_ratiocount the entity types the active schema pack declares (#4772,src/core/schema-pack/entity-types.ts, resolved per source: brain-wide forgraph_coverage, the asked source fororphan_ratio --source); a pack that does not load makesgraph_coveragea warn naming the pack (never the old hardcoded list) andorphan_ratioanswers 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 throughtest/helpers/doctor-source.ts:doctorSource()concatenates the façade plus everysrc/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 thedoctor-source-helperdetector inscripts/classify-tests.ts.facadeExpansioninscripts/generate-flag-registry.tskeeps 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 isgbrain extract timeline --prune-orphans) andslug-collisions.ts(slug_collisions, walks each live source checkout withcollectSyncableFilesand reports paths that map to one slug plus the indexed one; sources without a checkout are skipped).checks/graph-embedding.tscheckJunkEntityHubs(#6158) splits connector contact pages (frontmattergoogle_contact_idor a connector source kind) intodetails.connector_twinswith their main-braincanonical_twin, never calls them extractor-minted or offersjunk_hub_exempt, and carriesfix_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 thedefaultrow, page counts (live + file-backed),sync.repo_path, the leak-guard collision and every other live source with a relativelocal_path(all named), then hands the verdict toassessDefaultSourcePath. Reads fallback inputs only for a null pointer; null on skip with no relative source.src/commands/doctor/checks/fts-reindex.ts—ftsReindexIncompleteCheck(engine): thefts_reindex_incompletecheck. Reads thefts.reindex_in_progressconfig row thatreindex-search-vectorsets before its trigger-language flip and clears only after both backfills finish; null (nothing pushed) when absent,failnaming 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 theengine !== nulllazy-import guard (skipped on--fast/ DB-down); categorybrain. Pinned bytest/doctor-fts-reindex-incomplete.test.ts.