Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(doctor): harness_wiring consults the bootstrap registration record

garrytanb13b0d44573c
diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.md
index e51ec47529..e7f8ff169c 100644
--- a/docs/architecture/key-files/commands-2.md
+++ b/docs/architecture/key-files/commands-2.md
@@ -24,7 +24,7 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve
- `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`; connector holds stay on `connector_held_items`. `frontmatter_repairable` (registered inline: emitted 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): installed 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 recovers them, `gbrain sync --source <id> --no-pull` does it now, plus the repair preview and the hook refresh. `fenceHoldsBannerNote` (a separate `POST_UPGRADE_NOTES` entry, #6188 D7) names sources whose cursor stopped on a fence receipt (typed or the message an older gbrain stored): the next sync recovers them with no command, `gbrain sync --source <id> --no-pull` does it now, the malformed fences the stored census knows 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 applying command. 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` 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/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`.
@@ -40,7 +40,7 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve
- `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`, 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 every detected harness an enabled plugin lane covers (`enabledPluginLanes`): all covered → `ok`, `reason: plugin_lane_enabled` with the plugins, harnesses and a verify hint (plugin lanes are not smoke-tested); partly covered → the missing-registration warning for the uncovered harnesses only. Claude Code detection also honors `CLAUDE_CONFIG_DIR`.
+- `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 workspace `.mcp.json`), 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 67 `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)`. `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); `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 (the meat behind the `doctor.ts` façade). `checks/` holds the check-function library in bundles 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; `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, whose hash is over a file and whose page liveness cannot be resolved by slug — are reported as their own `slug_unbound` count and never enter the drift total or 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, 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, 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.
diff --git a/src/commands/doctor/checks/harness-wiring.ts b/src/commands/doctor/checks/harness-wiring.ts
index fae25e08fc..7689fd2087 100644
--- a/src/commands/doctor/checks/harness-wiring.ts
+++ b/src/commands/doctor/checks/harness-wiring.ts
@@ -34,7 +34,9 @@ import { verifiedStatusMarkers } from '../../../core/serve-http-status-marker.ts
import { agentProcessMarker } from '../../../core/interaction.ts';
import { resolveGbrainBin } from '../../../core/gbrain-bin.ts';
import { enabledPluginLanes } from '../../../core/bootstrap/plugin-lanes.ts';
-import { claudeConfigDir } from '../../../core/bootstrap/host-specs.ts';
+import { claudeConfigDir, opencodeProjectConfigPath } from '../../../core/bootstrap/host-specs.ts';
+import { readReceipt } from '../../../core/bootstrap/format.ts';
+import { resolveGbrainHome } from '../../../core/gbrain-home.ts';
import type { Action } from '../../../core/agent-output.ts';
import type { Check } from '../../doctor.ts';
import { checkError, doctorVerify, infoCheck } from '../check-fix.ts';
@@ -84,16 +86,24 @@ function stringRecord(v: unknown): Record<string, string> | undefined {
return out;
}
+/** #7422: the install receipt `gbrain bootstrap` keeps (its workspace and the registrations it made), or null. */
+function bootstrapReceipt(): ReturnType<typeof readReceipt> {
+ try { return readReceipt(resolveGbrainHome()); } catch { return null; }
+}
+
function claudeRegistration(name: string): HarnessRegistration | null {
const path = join(home(), '.claude.json');
const cfg = readJson(path) as { mcpServers?: Record<string, unknown>; projects?: Record<string, { mcpServers?: Record<string, unknown> }> } | null;
- if (!cfg) return null;
- const candidates = [cfg.mcpServers?.[name], ...Object.values(cfg.projects ?? {}).map((p) => p?.mcpServers?.[name])];
- const entry = candidates.find((c) => c && typeof c === 'object') as Record<string, unknown> | undefined;
- if (!entry) return null;
- if (typeof entry.url === 'string') return { harness: 'claude-code', source: path, kind: 'http', url: entry.url };
+ const ws = bootstrapReceipt()?.workspace_dir;
+ const projectPath = ws ? join(ws, '.mcp.json') : null;
+ const project = projectPath ? readJson(projectPath) as { mcpServers?: Record<string, unknown> } | null : null;
+ const candidates: Array<[string, unknown]> = [[path, cfg?.mcpServers?.[name]], ...Object.values(cfg?.projects ?? {}).map((p): [string, unknown] => [path, p?.mcpServers?.[name]])];
+ if (projectPath) candidates.push([projectPath, project?.mcpServers?.[name]]);
+ const [source, entry] = (candidates.find(([, c]) => c && typeof c === 'object') ?? []) as [string?, Record<string, unknown>?];
+ if (!source || !entry) return null;
+ if (typeof entry.url === 'string') return { harness: 'claude-code', source, kind: 'http', url: entry.url };
if (typeof entry.command !== 'string') return null;
- return { harness: 'claude-code', source: path, kind: 'stdio', command: entry.command, args: strings(entry.args) ?? [], env: stringRecord(entry.env) };
+ return { harness: 'claude-code', source, kind: 'stdio', command: entry.command, args: strings(entry.args) ?? [], env: stringRecord(entry.env) };
}
/** `[mcp_servers.<name>]` from Codex's config.toml: the `command`/`args`/`url`/`env` keys only. */
@@ -121,14 +131,17 @@ export function parseCodexRegistration(text: string, name: string, source: strin
return { harness: 'codex', source, kind: 'stdio', command, args: strings(parse(value('args'))) ?? [], env };
}
+const codexConfigPath = () => join(process.env.CODEX_HOME || join(home(), '.codex'), 'config.toml');
+const opencodeConfigPath = () => join(process.env.XDG_CONFIG_HOME || join(home(), '.config'), 'opencode', 'opencode.json');
+
function codexRegistration(name: string): HarnessRegistration | null {
- const path = join(process.env.CODEX_HOME || join(home(), '.codex'), 'config.toml');
+ const path = codexConfigPath();
if (!existsSync(path)) return null;
try { return parseCodexRegistration(readFileSync(path, 'utf8'), name, path); } catch { return null; }
}
function opencodeRegistration(name: string): HarnessRegistration | null {
- const path = join(process.env.XDG_CONFIG_HOME || join(home(), '.config'), 'opencode', 'opencode.json');
+ const path = opencodeConfigPath();
const cfg = readJson(path) as { mcp?: Record<string, Record<string, unknown>> } | null;
const entry = cfg?.mcp?.[name];
if (!entry) return null;
@@ -143,6 +156,27 @@ export function readHarnessRegistrations(name = 'gbrain'): HarnessRegistration[]
return [claudeRegistration(name), codexRegistration(name), opencodeRegistration(name)].filter((r): r is HarnessRegistration => r !== null);
}
+interface RecordedRegistration { harness: ReadinessHarness; scope: string; config: string }
+
+/**
+ * #7422: MCP registrations `gbrain bootstrap` recorded for these harnesses
+ * whose config file this process cannot read (a service running under
+ * another HOME, a permission): unverified here, not missing. A readable
+ * config without the registration is not listed (it was removed).
+ */
+function recordedUnreadableRegistrations(harnesses: readonly ReadinessHarness[]): RecordedRegistration[] {
+ const receipt = bootstrapReceipt();
+ if (!receipt) return [];
+ const configFor = (harness: ReadinessHarness, scope: string): string => harness === 'claude-code'
+ ? (scope === 'project' ? join(receipt.workspace_dir, '.mcp.json') : join(home(), '.claude.json'))
+ : harness === 'codex' ? codexConfigPath() : scope === 'project' ? opencodeProjectConfigPath(receipt.workspace_dir) : opencodeConfigPath();
+ const readable = (path: string) => { try { readFileSync(path); return true; } catch { return false; } };
+ return receipt.registrations
+ .filter((r) => harnesses.includes(r.host) && (r.detail?.split('+') ?? []).includes('mcp'))
+ .map((r) => ({ harness: r.host, scope: r.scope, config: configFor(r.host, r.scope) }))
+ .filter((r) => !readable(r.config));
+}
+
/** Harnesses installed on this machine: the active agent marker, else their config files. */
function detectedHarnesses(): ReadinessHarness[] {
const marker = agentProcessMarker();
@@ -354,7 +388,13 @@ export async function harnessWiringCheck(opts: { smoke: boolean }): Promise<Chec
if (regs.length === 0) {
const detected = detectedHarnesses();
const plugins = enabledPluginLanes('gbrain').filter((lane) => detected.includes(lane.harness));
- const harnesses = detected.filter((h) => !plugins.some((lane) => lane.harness === h));
+ const recorded = recordedUnreadableRegistrations(detected.filter((h) => !plugins.some((lane) => lane.harness === h)));
+ const harnesses = detected.filter((h) => !plugins.some((lane) => lane.harness === h) && !recorded.some((r) => r.harness === h));
+ if (detected.length > 0 && harnesses.length === 0 && recorded.length > 0) {
+ return infoCheck(NAME, `${recorded.map((r) => `${HARNESS_LABEL[r.harness]}: \`gbrain bootstrap\` recorded a gbrain MCP registration (${r.scope} scope)`).join('; ')}, `
+ + `but this process cannot read its config, so doctor did not verify it here. Verify it with \`gbrain doctor --only harness_wiring\` run as the user who runs the agent app.`,
+ 'unknown', undefined, { reason: 'registration_recorded', harnesses: recorded.map((r) => r.harness), registrations: recorded });
+ }
if (detected.length > 0 && harnesses.length === 0) {
return { name: NAME, status: 'ok',
message: `${plugins.map((p) => `${HARNESS_LABEL[p.harness]} gets gbrain from the enabled '${p.plugin}' plugin`).join('; ')}. Enabled is a config signal: doctor does not smoke-test plugin lanes, so verify by starting a new session in that app and checking that gbrain's tools (recall, remember) are listed.`,
diff --git a/test/doctor-harness-wiring-recorded-7422.test.ts b/test/doctor-harness-wiring-recorded-7422.test.ts
new file mode 100644
index 0000000000..5417bbe956
--- /dev/null
+++ b/test/doctor-harness-wiring-recorded-7422.test.ts
@@ -0,0 +1,120 @@
+/**
+ * #7422: `harness_wiring` warned "Claude Code is installed but has no gbrain
+ * MCP registration … has not been verified from this process" on a host whose
+ * registration `gbrain bootstrap` recorded: the check never read the
+ * project-scope `.mcp.json` bootstrap writes, and a registration in a config
+ * this process cannot see (a service under another HOME) read as missing.
+ *
+ * - A project-scope registration in the receipt workspace's `.mcp.json` is
+ * read like any other registration.
+ * - A recorded registration whose config this process cannot read reports ok
+ * (info) and says how to verify it, instead of a false warn.
+ * - No registration anywhere, a hooks-only record, or a recorded registration
+ * that its readable config no longer holds still warns.
+ *
+ * Hermetic temp HOME, GBRAIN_HOME, CODEX_HOME, CLAUDE_CONFIG_DIR and
+ * XDG_CONFIG_HOME; no serve is spawned (registration read only, smoke off).
+ */
+import { afterAll, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { harnessWiringCheck } from '../src/commands/doctor/checks/harness-wiring.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const roots: string[] = [];
+afterAll(() => { for (const r of roots) rmSync(r, { recursive: true, force: true }); });
+
+interface Box { root: string; home: string; ws: string; gbrainHome: string; env: Record<string, string | undefined> }
+
+/** A machine whose active agent is Claude Code (its process marker is set) and nothing is configured yet. */
+function box(): Box {
+ const root = mkdtempSync(join(tmpdir(), 'gb-hw-7422-'));
+ roots.push(root);
+ const home = join(root, 'home');
+ const ws = join(root, 'workspace');
+ mkdirSync(home, { recursive: true });
+ mkdirSync(ws, { recursive: true });
+ return {
+ root, home, ws, gbrainHome: join(root, 'gbrain-home', '.gbrain'),
+ env: {
+ HOME: home, GBRAIN_HOME: join(root, 'gbrain-home'), CODEX_HOME: join(root, 'codex'), CLAUDE_CONFIG_DIR: join(root, 'claude'), XDG_CONFIG_HOME: join(root, 'xdg'),
+ DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined,
+ CLAUDECODE: '1', CLAUDE_CODE_ENTRYPOINT: undefined, CODEX_SANDBOX: undefined, CODEX_CI: undefined, OPENCODE: undefined, OPENCODE_PID: undefined,
+ },
+ };
+}
+
+function receipt(b: Box, registrations: Array<{ host: string; scope: string; detail?: string }>): void {
+ mkdirSync(join(b.gbrainHome, 'bootstrap'), { recursive: true });
+ writeFileSync(join(b.gbrainHome, 'bootstrap', 'receipt.json'), JSON.stringify({
+ receipt_version: 1, workspace_dir: b.ws, source_id: 'source-a', agent_name: 'agent', created_at: new Date().toISOString(),
+ created_by: 'test', brain_created_by_bootstrap: false, created_paths: [], registrations,
+ }));
+}
+
+const STDIO = { type: 'stdio', command: '/opt/example/bin/gbrain', args: ['serve', '--surface', 'full'], env: { GBRAIN_SOURCE: 'source-a' } };
+const check = (b: Box) => withEnv(b.env, () => harnessWiringCheck({ smoke: false }));
+
+describe('#7422 harness_wiring consults the bootstrap registration record', () => {
+ test('a project-scope registration in the receipt workspace .mcp.json is read', async () => {
+ const b = box();
+ receipt(b, [{ host: 'claude-code', scope: 'project', detail: 'mcp+hooks' }]);
+ writeFileSync(join(b.ws, '.mcp.json'), JSON.stringify({ mcpServers: { gbrain: STDIO } }));
+ const c = await check(b);
+ expect(c.status).toBe('ok');
+ expect(c.details).toMatchObject({ reason: 'registration_unverified', harnesses: ['claude-code'] });
+ expect(c.message).toContain('Registered: Claude Code → /opt/example/bin/gbrain serve --surface full');
+ });
+
+ test('a recorded user-scope registration this process cannot read → ok info, not a false warn', async () => {
+ const b = box();
+ receipt(b, [{ host: 'claude-code', scope: 'user', detail: 'mcp+hooks' }]);
+ const c = await check(b);
+ expect(c.status).toBe('ok');
+ expect(c.severity).toBe('info');
+ expect(c.details).toMatchObject({ reason: 'registration_recorded', harnesses: ['claude-code'] });
+ expect(c.message).toContain('gbrain bootstrap');
+ expect(c.message).toContain('gbrain doctor --only harness_wiring');
+ expect(c.message).not.toContain('has no gbrain MCP registration');
+ });
+
+ test('a recorded project-scope registration whose workspace config this process cannot read → ok info', async () => {
+ const b = box();
+ receipt(b, [{ host: 'claude-code', scope: 'project', detail: 'mcp' }]);
+ rmSync(b.ws, { recursive: true, force: true });
+ const c = await check(b);
+ expect(c.status).toBe('ok');
+ expect(c.details).toMatchObject({ reason: 'registration_recorded' });
+ });
+
+ test('no registration anywhere still warns', async () => {
+ const b = box();
+ const c = await check(b);
+ expect(c.status).toBe('warn');
+ expect(c.message).toMatch(/^Claude Code is installed but has no gbrain MCP registration/);
+ });
+
+ test('a hooks-only record is not an MCP registration → warn', async () => {
+ const b = box();
+ receipt(b, [{ host: 'claude-code', scope: 'user', detail: 'hooks' }]);
+ expect((await check(b)).status).toBe('warn');
+ });
+
+ test('a record for another harness does not cover Claude Code → warn', async () => {
+ const b = box();
+ receipt(b, [{ host: 'codex', scope: 'user', detail: 'mcp' }]);
+ expect((await check(b)).status).toBe('warn');
+ });
+
+ test('a recorded registration its readable config no longer holds → warn', async () => {
+ const b = box();
+ receipt(b, [{ host: 'claude-code', scope: 'user', detail: 'mcp' }]);
+ writeFileSync(join(b.home, '.claude.json'), JSON.stringify({ mcpServers: { other: STDIO } }));
+ expect((await check(b)).status).toBe('warn');
+ const p = box();
+ receipt(p, [{ host: 'claude-code', scope: 'project', detail: 'mcp' }]);
+ writeFileSync(join(p.ws, '.mcp.json'), JSON.stringify({ mcpServers: {} }));
+ expect((await check(p)).status).toBe('warn');
+ });
+});