Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(doctor): memoize git ls-files per run, skip citation parse without [Source:, one .git walk per source

time-attackfa22c25aa60b
diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.md
index 8c32651d5e..cb7079cf88 100644
--- a/docs/architecture/key-files/commands-2.md
+++ b/docs/architecture/key-files/commands-2.md
@@ -36,7 +36,7 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve
- `src/commands/doctor/checks/managed-sync-backlog.ts` — #5984: lists unfinished managed sync cursors with remaining entries, the last drain's pages/min and indexing ETA (`persistence/sync-drain.ts` `readManagedSyncBacklog`); warns when a cursor has not advanced for an hour, with its resume command. Tests: `test/sync-drain.test.ts`.
- `src/commands/doctor/checks/sync-failures.ts` — reads managed durable cursor/receipt state even when its compatibility ledger is absent. An unavailable read is unknown/warn, not healthy; local findings carry diagnostics and remote findings contain only source-scoped aggregates. Legacy remediation stays separate from explicit managed retry. Failures on archived sources (which sync refuses) are left out of the count and severity and only reported as an ignored total. Tests: `test/persistence-sync-failures.serial.test.ts`, `test/doctor-report-remote.serial.test.ts`, `test/doctor-sync-failures-archived.test.ts`.
-- `src/commands/doctor.ts` — `gbrain doctor [--json] [--fast] [--fix] [--dry-run] [--index-audit] [--no-migrate]`: health checks. `checkPostgresCancellationDriver` (`postgres_cancellation_driver`) inspects a real reserved runtime owner through the shared cancellation helper: unsupported `discard()` is a typed local failure with a repair link, connection/deadline failure is a warning, and PGLite is exempt. The bounded reserve releases late arrivals and does not make general engine connect require cancellation, preserving broken-install diagnostics. `--no-migrate` keeps doctor observational: the CLI connects with `probeOnly` so a clean-or-behind schema is reported as-is instead of being auto-migrated before the checks run. The file is a façade carrying `buildChecks` (flag parse into a `DoctorContext`, then `runDoctorRegistry`), `runDoctor` and output rendering; the checks run as the ordered registry in `src/commands/doctor/registry.ts` (see that entry), the check-function library lives in bundles under `src/commands/doctor/checks/` plus four tail-cluster modules under `src/commands/doctor/` (see that entry), all re-exported here so the full surface is unchanged — structural guards pin its source text via `test/helpers/doctor-source.ts`, never by reading this file alone. Checks include `jsonb_integrity` + `markdown_body_completeness` (reliability), `schema_version` (fails loudly when `version=0`, routes to `gbrain apply-migrations --yes`; a version AHEAD of this client's `LATEST_VERSION` warns "upgrade this client"; and when the ledger reads current, a read-only `detectMissingColumns` diff from `src/core/schema-verify.ts` runs INSIDE the ledger-current branch — a PgBouncer-swallowed ALTER TABLE can advance `config.version` over a physically narrower table, so missing live columns downgrade the ok to a warn naming them with the `gbrain init --migrate-only` hint; diff failure is best-effort and the ledger ok stands; positional wiring pinned by `test/doctor-schema-column-diff.test.ts`), `upgrade_errors` (async `checkUpgradeErrors(engine)` over `~/.gbrain/upgrade-errors.jsonl`: the warn downgrades to an EXPLICIT status-ok line — never silence — only when the past failure is provably superseded, i.e. the running binary is at/past the failed target version AND the schema verifies current via `engine.getConfig('version')`; a missing engine or unverifiable schema keeps the warn, fail-closed, because `self-upgrade` swaps the binary before `post-upgrade` runs migrations and the binary alone can lie; pinned by `test/doctor-upgrade-errors.test.ts` + `test/doctor-upgrade-errors-stale.test.ts`), `queue_health` (Postgres-only: stalled-forever active jobs started_at > 1h, waiting-depth-per-name > threshold default 10 via `GBRAIN_QUEUE_WAITING_THRESHOLD`, and dead-lettered subagent jobs with `last_error` matching the `prompt_too_long` classifier in last 24h), `sync_failures` (`[CODE=N, ...]` breakdown for unacked-warn + acked-ok; severity comes from the shared `decideSyncFailureSeverity` in `src/core/sync-failure-ledger.ts` so the LOCAL and REMOTE/thin-client doctor surfaces can never drift — a stuck bookmark escalates to FAIL once an OPEN failure has blocked past the staleness window or ≥10 files block, while already `auto_skipped` rows stay a visible WARN), `rls_event_trigger` (healthy `evtenabled` set is `('O','A')` only; fix hint `gbrain apply-migrations --force-retry 35`), `graph_coverage` (short-circuits to ok when `SELECT COUNT(*) FROM pages WHERE type IN ('entity','person','company','organization')` returns 0; WARN hint is `gbrain extract all`), `embedding_column_registry` (probes each declared column via Postgres `format_type(atttypid, atttypmod)` to catch dim mismatch with a paste-ready `gbrain config set embedding_columns '{...}'` hint, probes HNSW index presence via `pg_indexes`, computes default-column population via `COUNT(*) FILTER (WHERE <col> IS NOT NULL) / COUNT(*)` warning below 90% except empty brains where chunk_count=0 short-circuits to ok; PGLite parity via `executeRaw`), and `skill_brain_first` (walks SKILL.md via `autoDetectSkillsDirReadOnly`, calls `analyzeSkillBrainFirst()` from `src/core/skill-brain-first.ts` per file with structured `Check.issues[]`; warn states `missing_brain_first`/`brain_first_typo`, ok states `compliant_callout`/`compliant_phase`/`compliant_position`/`exempt_frontmatter`/`no_external`; snapshot+diff audit at `~/.gbrain/audit/skill-brain-first-YYYY-Www.jsonl`). `--fix` delegates inlined cross-cutting rules to `> **Convention:** see [path](../path).` callouts via `src/core/dry-fix.ts` (and MISSING_RULE_PATTERNS for the brain-first callout); `--fix --dry-run` previews. `--index-audit` (Postgres-only, informational, no auto-drop) reports zero-scan indexes from `pg_stat_user_indexes`. Every DB check runs under a progress phase; `markdown_body_completeness` runs under a 1s heartbeat. `runDoctor` uses `autoDetectSkillsDirReadOnly` (from `src/core/repo-root.ts`; install-path fallback so `cd ~ && gbrain doctor` finds bundled skills); `--fix` carries a D6 install-path safety gate that refuses auto-repair when `detected.source === 'install_path'` (would rewrite the bundled tree). The Lane D supervisor check (`doctor/checks/supervisor-health.ts`) consumes `summarizeCrashes(events)` from `src/core/minions/handlers/supervisor-audit.ts` (warn at `>=1` real crash; ok message has `clean_exits_24h=N`; warn message has `runtime=A oom=B unknown=C legacy=D` per-cause breakdown) so OOM/runtime/unknown crashes are distinguishable from clean code=0 worker drains; cross-surface parity with `gbrain jobs supervisor status` is pinned by source-grep wiring assertions requiring the breakdown substrings on the doctor surface and in `jobs.ts`. `checkSyncFreshness` (exported, in `runDoctor` local + `doctorReportRemote` thin-client) is a staleness probe: warns at 24h, fails at 72h or never-synced; future-`last_sync_at` warns ("clock skew") instead of falling through ok; env overrides `GBRAIN_SYNC_FRESHNESS_WARN_HOURS`/`GBRAIN_SYNC_FRESHNESS_FAIL_HOURS` (invalid fall back with once-per-process stderr warn via `_resolveSyncFreshnessHours`); failure messages embed `source.id` so the printed `gbrain sync --source <id>` matches. A source holding a LIVE, non-expired per-source sync lock (`inspectLock(engine, syncLockId(source.id))` from `src/core/db-lock.ts`) is reported as actively syncing (the message names the holder pid + host) and counted in `synced_recently_count`, NOT flagged stale — the live lock is the only honest in-progress signal (checkpoint banking can't distinguish in-progress from wedged: a blocked sync banks its files but writes no anchor). A blocked/failed sync's process has exited (no lock row) and a wedged holder stops refreshing (TTL lapses), so either falls through to the stale path and is never masked; the dynamic `db-lock` import is swallowed to a no-op on a stub engine or pre-lock-table brain, so this can only ADD an in-progress verdict, never suppress a real stale one. The in-progress note is appended to whatever verdict the buckets produce and is empty when nothing is syncing, so steady-state messages stay byte-for-byte unchanged. It has a `localOnly`-gated git short-circuit (`runDoctor` passes `localOnly: true`; `doctorReportRemote` runs in the HTTP MCP server `src/commands/serve-http.ts` and keeps default `false` so that path never walks DB-supplied `local_path` via subprocess — trust boundary). The local predicate mirrors sync's "do work?" gate (HEAD == `last_commit` AND working tree clean via `requireCleanWorkingTree: 'ignore-untracked'` so a quiet repo with only untracked dirs is `unchanged` not SEVERE, AND `chunker_version === CURRENT`); the inline SELECT carries `last_commit + chunker_version + newest_content_at`. The REMOTE path computes lag via `lagFromContentMs(newest_content_at, lastSync, now)` from the stored column, NO git subprocess; LOCAL fall-through and the `< 0` clock-skew check stay on raw wall-clock. Three-bucket count math populates `Check.details = {unchanged_count, synced_recently_count, stale_count}` with the invariant `sum === sources.length`. `checkCycleFreshness` is DELIBERATELY NOT git-short-circuited or content-relativized (`last_commit == HEAD` can't answer "did the full cycle complete?"; a sync can succeed while later cycle phases fail; different axis `last_full_cycle_at`). Pinned by `test/doctor.test.ts` (incl. the IRON-RULE guard banning stale verb names, the sync_freshness boundary matrix, the D4 guard verifying git probes are NEVER called when `localOnly` is unset/false, the three-bucket invariant, and the untracked-folders / remote-never-shells-out trust-boundary cases). `pglite_data_dir` check: fs-only check that runs when a PGLite brain FAILS to connect (`!fastMode && !engine && config.engine === 'pglite'`, placed after `orphan_clones`, before the DB-checks gate; `pgliteDataDirEntry` in `doctor/checks/db-connection.ts`): `computePgliteDataDirCheck(dataDir, diagnosis)` (exported pure fn, `computeWorkerOomLoopCheck` convention) maps the `inspectPgliteDataDir` verdict to a Check — corruption-likely/looks-healthy-but-unopenable/unsupported-layout → `fail` naming `gbrain pglite-repair --dry-run`/`--yes` or the rebuild path, live-lock/missing-dir → `warn`; all `remediation_status: 'human_only'` (Minion remediation needs the DB that is down). Escalates when ≥2 repair attempts failed inside 7 days (unclean-shutdown genesis still active → engine-switch pointer) and reports retained backup-dir inventory (orphan_clones disk-visibility class). Registered in `doctor-categories.ts` OPS_CHECK_NAMES. Pinned by `test/doctor-pglite-datadir.test.ts`. silent-failure checks: `content_hash_duplicates` (single GROUP BY over `(source_id, content_hash)` with FILTER aggregates — never N² — flagging hash groups that hold BOTH a bare and a path-prefixed slug, the wrong-import-root pattern; warn carries sample pairs + the `pages delete` → `purge-deleted --older-than 0` remediation); `undeclared_db_only_pages` (per source with a local repo: markdown pages with no backing file outside every declared + derive-phase-default db_only prefix — the one check deliberately allowed to stat the repo; `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 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.
+- `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 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. `agent_contract` reads `readAgentContractEvents()` (7 days) 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`.
diff --git a/docs/architecture/key-files/files-and-sync-1.md b/docs/architecture/key-files/files-and-sync-1.md
index 0761a114db..3341924bff 100644
--- a/docs/architecture/key-files/files-and-sync-1.md
+++ b/docs/architecture/key-files/files-and-sync-1.md
@@ -33,7 +33,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/link-source-check-repair.ts` — schema-drift self-heal for the `links_link_source_check` CHECK constraint (third instance of the `timeline-dedup-repair.ts` / `pages-upsert-arbiter.ts` class). Migration v114 opened `link_source` from a closed allowlist to the kebab-case gate; the migrator trusts the version ledger, so a brain stamped >= 114 whose live constraint reverted to the pre-v114 allowlist (drifted restore, manual DDL) rejects every kebab provenance write (`atom-provenance`, `concept-provenance`) while the ledger reads current. `LINK_SOURCE_KEBAB_RE` is the ONE exported copy of the regex (a drift-guard test pins it to the literal in migrate.ts v114, `schema.sql`, `pglite-schema.ts`). `checkLinkSourceCheck(engine)` probes `pg_constraint` (`pg_get_constraintdef` + `convalidated`) and classifies the drift as `absent` / `wrong_def` / `not_validated` (read-only; powers the `links_link_source_check` doctor check in `doctor/checks/core-health.ts`, whose severity follows what writes do: only `wrong_def` rejects kebab writes → fail; `absent` / `not_validated` still accept them → warn). `repairLinkSourceCheck(engine)` first COUNTs rows that fail the gate and returns `reason: 'violations'` WITHOUT any DDL when there are any (the prior constraint survives; rows are never touched; a brain with a bad row never pays for a failing ALTER at every engine open), then restores v114's definition mirroring the migration's engine split: Postgres runs DROP + `ADD ... NOT VALID` in one `engine.transaction` (atomic, no scan) and `VALIDATE CONSTRAINT` as a separate `engine.runMigration` outside it (SHARE UPDATE EXCLUSIVE, never a plain ADD's ACCESS EXCLUSIVE + full-table scan), with a `not_validated` drift getting the VALIDATE only; PGLite keeps the one-shot DROP+ADD transaction. A DDL failure re-counts violators (a row written between probe and ALTER) and rethrows when there are none. `LINK_SOURCE_GATE_MIGRATION_VERSION` (114) is the ledger gate `runMigrations` applies before calling it. Pinned by `test/link-source-check-repair.test.ts` (PGLite, incl. a recording-engine assertion that violators trigger no DDL and that a sub-114 ledger never probes) and the DATABASE_URL-gated `test/e2e/link-source-check-repair-postgres.test.ts` (two-phase DDL sequence on real Postgres).
-- `src/core/markdown.ts` — Frontmatter parsing + body splitter. `coerceFrontmatterString(v)` coerces a non-string `title`/`slug`/`type` to a deterministic string at parse time so a YAML-typed value never reaches `.toLowerCase()` and throws (`title: 2024-06-01` parses as a `Date`, `title: 1458` as a number, and a throw would block the sync bookmark from advancing); a `Date` becomes its UTC ISO date (`2024-06-01`, machine-independent and matching the on-disk token, unlike `String(date)`), `null`/`undefined` become `''`, everything else uses `String()`. `splitBody` requires an explicit timeline sentinel (`<!-- timeline -->`, `--- timeline ---`, or `---` immediately before `## Timeline`/`## History`). Plain `---` in body text is a markdown horizontal rule, not a separator. `inferType` auto-types `/wiki/analysis/` → analysis, `/wiki/guides/` → guide, `/wiki/hardware/` → hardware, `/wiki/architecture/` → architecture, `/writing/` → writing (plus existing people/companies/deals/etc heuristics). `resolveSourceLocalFilePath` maps Git-root-relative `pages.source_path` values into a source whose `local_path` scopes a repo subdirectory; it finds the Git root with filesystem checks only (`sourceGitScope`; a caller resolving many pages of one source, such as doctor's `undeclared_db_only_pages`, computes it once and passes it as `gitScope`), strips the exact root-relative scope, rejects unsafe/non-markdown paths, and when given a slug it tolerates historical basename-relative `source_path` rows by checking the slug directory only after the direct path is absent. It leaves write containment to the caller. After its pre-quote pass, a block the strict parse refuses goes to `recoverFrontmatter`; only `quote` recoveries are applied. Under `validate`, YAML_PARSE stays in `errors` (location-only message, `recoverable` plus a content-free `recovery` record), advisories go to `warnings` (`FRONTMATTER_RECOVERED`, `FRONTMATTER_COMMENT_VALUE`), and `recovery` carries interpretive, protected-key and identity-key findings. `HOLD_CODES` and `classifyImportHold(parsed, ctx)` define the ingestion hold set once; `isFrontmatterHoldMessage` recognizes its exact messages. Tests: `test/frontmatter-recovery.test.ts`.
+- `src/core/markdown.ts` — Frontmatter parsing + body splitter. `coerceFrontmatterString(v)` coerces a non-string `title`/`slug`/`type` to a deterministic string at parse time so a YAML-typed value never reaches `.toLowerCase()` and throws (`title: 2024-06-01` parses as a `Date`, `title: 1458` as a number, and a throw would block the sync bookmark from advancing); a `Date` becomes its UTC ISO date (`2024-06-01`, machine-independent and matching the on-disk token, unlike `String(date)`), `null`/`undefined` become `''`, everything else uses `String()`. `splitBody` requires an explicit timeline sentinel (`<!-- timeline -->`, `--- timeline ---`, or `---` immediately before `## Timeline`/`## History`). Plain `---` in body text is a markdown horizontal rule, not a separator. `inferType` auto-types `/wiki/analysis/` → analysis, `/wiki/guides/` → guide, `/wiki/hardware/` → hardware, `/wiki/architecture/` → architecture, `/writing/` → writing (plus existing people/companies/deals/etc heuristics). `resolveSourceLocalFilePath` maps Git-root-relative `pages.source_path` values into a source whose `local_path` scopes a repo subdirectory; it finds the Git root with filesystem checks only, strips the exact root-relative scope, rejects unsafe/non-markdown paths, and when given a slug it tolerates historical basename-relative `source_path` rows by checking the slug directory only after the direct path is absent. It leaves write containment to the caller. After its pre-quote pass, a block the strict parse refuses goes to `recoverFrontmatter`; only `quote` recoveries are applied. Under `validate`, YAML_PARSE stays in `errors` (location-only message, `recoverable` plus a content-free `recovery` record), advisories go to `warnings` (`FRONTMATTER_RECOVERED`, `FRONTMATTER_COMMENT_VALUE`), and `recovery` carries interpretive, protected-key and identity-key findings. `HOLD_CODES` and `classifyImportHold(parsed, ctx)` define the ingestion hold set once; `isFrontmatterHoldMessage` recognizes its exact messages. Tests: `test/frontmatter-recovery.test.ts`.
- `src/core/quarantine.ts` — the two frontmatter markers the content-quality gate writes, sibling of `src/core/embed-skip.ts` (same JSONB-object marker and `?` existence check on both engines; no migration). `quarantine` (key `QUARANTINE_KEY`) HIDES: set ONLY for high-confidence junk, writes zero chunks, excluded from search via `quarantineFilterFragment(pageAlias)` / `QUARANTINE_FILTER_FRAGMENT` (the `p`-aliased constant), the single source of truth `buildVisibilityClause` calls so the search filter and marker key can't drift. `content_flag` (key `CONTENT_FLAG_KEY`) WARNS, does NOT hide: set for fuzzy markup-heavy / oversize, page stays searchable, marker is READ INTO search/get_page output — deliberately NO SQL filter fragment. Three markers, three reasons: `embed_skip` = oversized-but-clean, `quarantine` = junk hidden, `content_flag` = odd-examine-still-here; a page can carry more than one (oversize → embed_skip + content_flag:oversized) and each clears independently. Exports `buildQuarantineMarker` / `isQuarantined` / `filterOutQuarantined`, `buildContentFlagMarker` / `getContentFlag` / `hasContentFlag`, plus the two key constants. Pinned by `test/quarantine.test.ts`. #6259: [quarantine cluster](quarantine.md). A quarantined page is skipped by every derived-data scan (stale listing via the engine-sql stale predicate, NER, meeting timeline projection, file walks via `quarantinedSlugs`, DB walks, the managed link derivation) and is not in the `links_extraction_lag` denominator. Pinned by `test/quarantine-extraction.test.ts`.
diff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.md
index b02e999c8b..dab22b8667 100644
--- a/docs/architecture/key-files/graph-and-facts.md
+++ b/docs/architecture/key-files/graph-and-facts.md
@@ -78,7 +78,7 @@ rejection of serve-only flags before a brain opens.
- `src/core/context/delta-cursor.ts` — pure helpers for delta's per-arm cursor: the opaque base64url `cursor` (`{v:1, p:[since, slug], f:[created_at, id]}`, validated like `since`), microsecond ISO normalization and the one-microsecond clamp, `nextPagesPos`/`nextFactsPos` (delivered prefix, `now() - 2 s` horizon `DELTA_COMMIT_LAG_MS`, the facts cursor computed from raw rows so a duplicate cluster split by a budget cut loses nothing), `resolveDeltaStart` and `legacyDeltaCursor`. `test/delta-cursor-integrity.test.ts`.
- `src/core/ops/facts.ts` — shared fact/memory operations, including `recall` and the `delta` cursor. `context_pack` and `delta` `facts[]` carry recall's `fact_id` and `provenance` (the stored `facts.source`), read in one batched `withProvenance` lookup by the delivered ids, so hot memory and MCP `_meta` stay unchanged; remote callers get provenance through the same redaction as the fact text, and it never enters `text` (#6146, `test/context-pack-fact-traceability.test.ts`). Recall keeps source/visibility and fact filters before per-arm candidate limits. Its default/explicit `facts_first` packing preserves the frozen memory-verb contract, including the positive sub-one budget quirk. Optional `query_first` packs the ranked page prefix first only with a nonblank query and positive finite budget; floor-zero and exhausted remainders explicitly return empty arms rather than call the unbounded zero-budget packer. Neither arm skips oversized prefix items or truncates. No-query and inactive-budget paths keep legacy behavior. Only policy-supplied calls add `budget_packing` effective-policy/reason and candidate/kept/dropped/estimated-used accounting. Counter sums match the frozen fields. Do not change the global packer or fact relevance to implement this policy. Delta rejects calendar-invalid ISO dates and years outside 0001-9999 (on the parsed UTC value) before normalization across fractional-second forms, while preserving valid six-digit microsecond cursors. Delta's per-arm cursor (contributor audit wave P0): the start position resolves `cursor` > `since` (whole tuple, slug only when supplied) > the session row; each arm advances through its delivered prefix only (`src/core/context/delta-cursor.ts`), an arm that failed or never finished holds, the conservative legacy `next_cursor.since`/`slug` never passes the oldest undelivered fact, and a legacy caller at an unpageable same-timestamp boundary is refused with `delta_cursor_upgrade_required`. Incomplete wakes emit `delta_incomplete` (`fix.next: wait`, `report` on the third consecutive wake, counted atomically in `session_context_state.degraded_wakes` with an in-process fallback when the store is down); a failed state read refuses with `unavailable`/`session_state` instead of re-initializing at now. `test/recall-budget-policy.test.ts` pins recall behavior; `test/ambient-recall.test.ts` pins delta cursor validation; `test/delta-cursor-integrity.test.ts` (both engines) pins every no-advance path, the facts drain, legacy safety and the commit-visibility bound.
-- `src/core/markdown-code.ts` — `stripCodeBlocks` masks fenced and inline code while preserving every CR/LF and UTF-16 code-unit offset. Plain text up to the next backtick, newline or (with `onHtmlComment`) `<` is copied as one slice, not one character at a time; `test/strip-code-blocks-equivalence.test.ts` fuzzes it against the per-character implementation. Citation paragraphs and later link references retain their original boundaries, including after an unclosed fence. `parseTimelineEntries` in `src/core/link-extraction.ts` groups the optional dash with its trailing whitespace so leading whitespace does not trigger overlapping repetition. Existing date and delimiter rules remain unchanged. Standalone backtick and tilde fences require valid closing markers; historical inline triple-backtick spans remain masked. Pinned through real FS/DB link and timeline consumers by `test/timeline-parser-regression.test.ts`; its adversarial whitespace workload runs in a timeout-bounded child process. #6133: inline spans pair backtick runs of equal length (CommonMark), found read-only by `fence-scan.ts` `scanMarkdownCode`/`inlineCodeEndAt` over a view where a bare CR is a space (so a span may still cross one), so a double-backtick span and a span holding a single backtick are masked whole and a backslash-escaped backtick opens nothing; the lint `placeholder-date` rule (`src/commands/lint.ts`) runs over the masked text, so placeholders in inline code no longer fire (`test/lint-3958.test.ts`, `test/timeline-parser-regression.test.ts`).
+- `src/core/markdown-code.ts` — `stripCodeBlocks` masks fenced and inline code while preserving every CR/LF and UTF-16 code-unit offset. Citation paragraphs and later link references retain their original boundaries, including after an unclosed fence. `parseTimelineEntries` in `src/core/link-extraction.ts` groups the optional dash with its trailing whitespace so leading whitespace does not trigger overlapping repetition. Existing date and delimiter rules remain unchanged. Standalone backtick and tilde fences require valid closing markers; historical inline triple-backtick spans remain masked. Pinned through real FS/DB link and timeline consumers by `test/timeline-parser-regression.test.ts`; its adversarial whitespace workload runs in a timeout-bounded child process. #6133: inline spans pair backtick runs of equal length (CommonMark), found read-only by `fence-scan.ts` `scanMarkdownCode`/`inlineCodeEndAt` over a view where a bare CR is a space (so a span may still cross one), so a double-backtick span and a span holding a single backtick are masked whole and a backslash-escaped backtick opens nothing; the lint `placeholder-date` rule (`src/commands/lint.ts`) runs over the masked text, so placeholders in inline code no longer fire (`test/lint-3958.test.ts`, `test/timeline-parser-regression.test.ts`).
- `src/core/check-resolvable.ts` — Resolver validation: reachability, MECE overlap, DRY checks, structured fix objects. `CROSS_CUTTING_PATTERNS.conventions` is an array (notability gate accepts `conventions/quality.md` and `_brain-filing-rules.md`). `extractTriggers()` delegates to the shared SKILL.md parser, so MECE gap detection and the trigger index agree on block lists, single-line flow sequences, wrapped flow sequences, and CRLF input. `extractDelegationTargets()` parses `> **Convention:**`, `> **Filing rule:**`, and inline backtick references. DRY suppression is proximity-based via `DRY_PROXIMITY_LINES = 40`. `parseResolverEntries` accepts BOTH the markdown table AND a compact list format (`- **skill-name**: trigger1 | trigger2 | trigger3` or `- skill-name: trigger1 | trigger2`); shapes can mix in one file, folded by the multi-resolver merge. Skill name MUST be kebab-lowercase (regex `[a-z][a-z0-9-]+`) so prose bullets like `- **Note**:`/`- **Convention**:`/`- **TODO**:` don't false-match as skill rows. `skillPath` is ALWAYS derived as `skills/<name>/SKILL.md`: an optional `→ \`skills/path\`` (or ASCII `->`) suffix is stripped from the trigger but NOT honored as the path — two consumers (`routing-eval.ts:skillSlugFromPath`, the manifest lookup) assume the convention; use the table format for non-conventional paths. Multi-trigger rows fan out to one entry per trigger sharing the same `skillPath`; `checkResolvable` dedupes so the reachability count counts each skill once. Pinned by `test/check-resolvable.test.ts` (resolver shapes plus trigger array syntax cases) + `test/check-resolvable-openclaw-compact.test.ts` (8 cases over `test/fixtures/openclaw-compact-resolver/` and `test/fixtures/openclaw-mixed-merge/`). Tutorial: `docs/guides/scaling-skills.md` (three-tier scaling: ~300-skill agent to ~4K tokens/turn from ~25K). `checkResolvable(skillsDir, opts?)` takes an optional `skillsDirSource` (the detection tier from `autoDetectSkillsDir`, threaded by both callers: doctor.ts and the check-resolvable command; an explicit `--skills-dir` passes `null`). An `unreachable` issue downgrades from `error` to `warning` only when ALL hold: the directory was found via the ungated `cwd_walk_up` tier, no resolver file contributes rows (no `RESOLVER.md`; a generic `AGENTS.md` with zero table rows counts as absent), unreachable skills outnumber reachable ones, and no `manifest.json` exists on disk. This keeps a foreign tool's `skills/` dir walked up to from cwd from being scored as a broken gbrain skillpack, while a real skillpack (RESOLVER.md present, higher-confidence tier, dense trigger coverage, or any manifest.json, even a corrupted one) stays strict. A foreign dir with zero `triggers:` and no resolver file still hard-fails via the `missing_file` branch (separate follow-up).
diff --git a/test/doctor-content-golden.test.ts b/test/doctor-content-golden.test.ts
deleted file mode 100644
index b782050320..0000000000
--- a/test/doctor-content-golden.test.ts
+++ /dev/null
@@ -1,108 +0,0 @@
-/**
- * `gbrain doctor` goldens on a PGLite brain with content (GBRA-68).
- *
- * The W0 doctor goldens (test/doctor-json-golden.test.ts) run on an empty
- * brain, so the content-reading checks (frontmatter scan, timeline history
- * and orphans, link resolution, fence census, slug collisions, undeclared
- * DB-only pages) never see a page. This golden imports a small synthetic Git
- * source whose pages exercise fenced and inline code, HTML comments, inline
- * citations, timeline bullets, bare wikilinks, CRLF lines and a broken
- * frontmatter file left untracked after the import, then pins `doctor --json`
- * and the human `doctor` output plus their exit codes. Captured on master before the doctor CPU fixes
- * (stripCodeBlocks run copying, the citation reader's no-citation exit, the
- * doctor-scoped `git ls-files` memo), so those fixes must reproduce it.
- *
- * Same hermetic env and normalizer as the W0 goldens; every capture runs
- * twice from independent fresh homes and must normalize identically.
- */
-import { afterAll, describe, expect, test } from 'bun:test';
-import { execFileSync } from 'node:child_process';
-import { mkdirSync, writeFileSync } from 'node:fs';
-import { dirname, join } from 'node:path';
-import { defineNormalizer, expectGolden, expectNormalizerStable } from './helpers/golden.ts';
-import { doctorJsonNormalizer, makeDoctorHome, networkAttempts, runGbrain, type DoctorHome, type GbrainRun } from './helpers/doctor-json-golden.ts';
-
-const DOCTOR = doctorJsonNormalizer();
-const homes: DoctorHome[] = [];
-afterAll(() => {
- for (const h of homes) h.cleanup();
-});
-
-const PAGES: Record<string, string> = {
- 'people/alice-example.md': [
- '---', 'title: Alice Example', 'type: person', '---',
- '# Alice Example', '',
- 'Alice works with [[acme-example]] and [[bob-example]]. Inline `[[not-a-link]]` stays code.', '',
- 'Alice joined Acme in March. [Source: Meeting notes, 2024-03-05]', '',
- '```ts', 'const s = "[Source: Fenced, 2024-01-01]"; // [[fenced-link]]', '```', '',
- '<!-- [Source: Hidden, 2024-01-02] -->', '',
- '## Timeline', '',
- '- **2024-03-05** | Joined Acme [Source: Email, 2024-03-05]',
- '- **2024-04-10** | Promoted', '',
- ].join('\n'),
- 'companies/acme-example.md': [
- '---', 'title: Acme Example', 'type: company', '---',
- '# Acme Example', '',
- '~~~', '[[tilde-fenced]] [Source: Tilde, 2024-01-03]', '~~~', '',
- 'Acme raised a round. [Source: Press, 2024-02-01; Filing, 2024-02-03]', '',
- 'An unclosed `backtick keeps [[alice-example]] live.', '',
- 'Double ``code with `inner` [[x]]`` span, then *emphasis* [Source: Blog, 2024-02-20].', '',
- ].join('\n'),
- 'notes/plain.md': [
- '---', 'title: Plain', '---',
- 'Mentions [[alice-example]], [[acme-example]], [[people/alice-example]] and [[carol-example]].', '',
- '- **2024-05-01** | Plain bullet without a citation', '',
- ].join('\n'),
- 'notes/crlf.md': ['---', 'title: Crlf', '---', 'Line one [[acme-example]]', '', 'Cited. [Source: Call, 2024-06-01]', '```', '[[in-fence]]', '```', ''].join('\r\n'),
- 'notes/unterminated-fence.md': ['---', 'title: Unterminated', '---', 'Before [[acme-example]].', '', '````md', '[Source: Never, 2024-07-01]', '```', 'still fenced [[x]]', ''].join('\n'),
-};
-
-/** Written after the import (which refuses it), untracked, so only the filesystem checks see it. */
-const BROKEN_PAGE = ['---', 'title: [unclosed', 'tags: a: b', '---', 'Body with [[alice-example]].', ''].join('\n');
-
-const FIXED_DATE = '2024-01-01T00:00:00Z';
-
-function writeSource(dir: string): void {
- for (const [rel, body] of Object.entries(PAGES)) {
- mkdirSync(join(dir, dirname(rel)), { recursive: true });
- writeFileSync(join(dir, rel), body);
- }
- const env = { ...process.env, GIT_AUTHOR_DATE: FIXED_DATE, GIT_COMMITTER_DATE: FIXED_DATE, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1' };
- const git = (...args: string[]) => execFileSync('git', ['-C', dir, '-c', 'user.name=fixture', '-c', '[email protected]', ...args], { env, stdio: 'ignore' });
- git('init', '-q', '-b', 'main');
- git('add', '-A');
- git('commit', '-q', '-m', 'fixture');
-}
-
-type Captures = Record<string, GbrainRun>;
-const ALL = defineNormalizer<Captures>(DOCTOR.name, (c) => Object.fromEntries(Object.entries(c).map(([k, v]) => [k, DOCTOR.apply(v)])));
-
-async function capture(): Promise<Captures> {
- const h = makeDoctorHome('doctor-content-golden');
- homes.push(h);
- const src = join(h.home, 'notes-src');
- writeSource(src);
- for (const args of [
- ['init', '--pglite', '--no-embedding'],
- ['sources', 'add', 'notes', '--path', src, '--federated', '--force'],
- ['import', src, '--no-embed', '--source-id', 'notes'],
- ['extract', 'all', '--source', 'db'],
- ]) {
- const run = await runGbrain(h, args);
- if (run.exitCode !== 0) throw new Error(`gbrain ${args.join(' ')} failed (${run.exitCode}): ${run.stderr}`);
- }
- writeFileSync(join(src, 'notes', 'broken-frontmatter.md'), BROKEN_PAGE);
- const json = await runGbrain(h, ['doctor', '--json', '--skills-dir', h.skillsDir]);
- const human = await runGbrain(h, ['doctor', '--skills-dir', h.skillsDir]);
- expect(networkAttempts(h)).toEqual([]);
- return { json, human };
-}
-
-describe('gbrain doctor goldens on a brain with content (PGLite)', () => {
- test('doctor --json and human doctor match the master capture', async () => {
- const c = await expectNormalizerStable(capture, ALL);
- expect(c.json.json).not.toBeNull();
- expectGolden('doctor/content-pglite-json', c.json, DOCTOR);
- expectGolden('doctor/content-pglite-human', c.human, DOCTOR);
- }, 300_000);
-});
diff --git a/test/fixtures/goldens/doctor/content-pglite-human.json b/test/fixtures/goldens/doctor/content-pglite-human.json
deleted file mode 100644
index 3d57481e3a..0000000000
--- a/test/fixtures/goldens/doctor/content-pglite-human.json
+++ /dev/null
@@ -1,209 +0,0 @@
-{
- "golden": {
- "args": [
- "doctor",
- "--skills-dir",
- "<home>/skills"
- ],
- "exit_code": 1,
- "report": null,
- "stderr": [
- "[doctor.db_checks] start",
- "[doctor.db_checks] done"
- ],
- "stdout": [
- "GBrain Health Check",
- "===================",
- "Top issues (ranked by cause):",
- " [FAIL] sync_freshness → Source 'notes' has never been synced. Run `gbrain sync --source <id> --no-pull` for each stale source. 1 writer-owned canonical content source(s): upstream sync is not applicable; see canonical_content_writes for publication status",
- " [WARN] brain_score → gbrain doctor --remediation-plan --json --brain host",
- " [WARN] frontmatter_integrity → gbrain repair frontmatter --source notes --brain host",
- " [WARN] frontmatter_repairable → gbrain repair frontmatter --source notes --brain host",
- " [WARN] link_resolution_opportunity → 6 of 8 bare wikilinks (75%) would resolve to 2 distinct page(s) under global_basename mode. Enable with: gbrain config set link_resolution.global_basename true",
- " +1 more — see full list below",
- " [OK] resolver_health: 1 skills, all reachable",
- " [INFO] retrieval_reflex_health: pglite — serve IPC socket not present; enabled but NO resolve path exists right now: the IPC socket is only bound by a running `gbrain serve` (stdio or --http) — until one is up, hooks/reflex degrade to no_serve on this brain (host capability may still supply pointers; policy skill carries otherwise) — policy skill not installed; run `gbrain integrations install retrieval-reflex --target <host-repo>`",
- " [OK] volunteer_channels: no push-context activity in 7 days — if a hook adapter is installed, confirm its registration landed and the harness session was RESTARTED (hooks snapshot at session start); a serve older than this build logs NOTHING for the hook lane — restart serve on the new build to activate the feedback loop",
- " [OK] memory_verbs_usage: no verb calls recorded yet (sidecar appears on first remember/recall/entity/synthesize/forget)",
- " [OK] skill_conformance: 1/1 skills pass",
- " [OK] skill_brain_first: 1 skill(s) compliant or exempt",
- " [OK] skills_manifest_integrity: No skills.lock.json in <home>/skills — integrity check not applicable",
- " [WARN] skill_currency: 64 new built-in skill(s) available that this workspace hasn't installed: academic-verify, archive-crawler, article-enrichment, ask-user, blog-ingest, book-mirror, brain-ingest-gate, brain-link-discipline, … +56 more. Add them with `gbrain skillpack sync`.",
- " [OK] skill_preconditions: no installed skills declare preconditions",
- " [OK] memorable_relay_health: memorable relay off (default)",
- " [OK] memory_writeback: ambient writeback off (default): Stop-hook turn capture is off, but the compaction harvest and SessionEnd transcripts still extract (installing the harness hooks opted into them; stop them: gbrain config set memory.auto_writeback off). Enable: gbrain config set memory.auto_writeback salient",
- " [OK] connectors: No chat connectors configured (optional).",
- " [OK] dream_paid_loop: No dream key died 3+ times in 24h",
- " [INFO] minions_migration: 5 setup migration(s) not run yet on this new brain (pending_fresh_install: 0.11.0, 0.14.0, 0.22.4, 0.28.0, 0.53.0). Expected after gbrain init, not a failed upgrade.",
- " [OK] self_upgrade_health: mode=notify",
- " [OK] bun_runtime: Bun <bun-version> (minimum 1.4.0)",
- " [OK] nightly_quality_probe_health: disabled (opt-in). Enable with: gbrain config set autopilot.nightly_quality_probe.enabled true",
- " [OK] extract_health: no extractions in last 7 days",
- " [OK] conversation_facts_backlog: disabled (opt-in). Enable with: gbrain config set cycle.conversation_facts_backfill.enabled true",
- " [OK] extract_atoms_backlog: no pages awaiting atom extraction",
- " [OK] atom_provenance_drift: no atoms to check",
- " [OK] conversation_format_coverage: No conversation-type pages — coverage check not applicable",
- " [OK] progressive_batch_audit_health: No progressive-batch operations in the last 7 days",
- " [OK] conversation_parser_probe_health: disabled (opt-in; default-on only for search.mode=tokenmax). Enable with: `gbrain config set autopilot.conversation_parser_probe.enabled true`",
- " [OK] home_dir_in_worktree: gbrain home is outside any enclosing git worktree.",
- " [OK] default_source_local_path: default source local_path is set: <home>/.gbrain/content/<uuid>/default",
- " [OK] multi_source_drift: No cross-source slug drift detected.",
- " [OK] embedding_key_source: No embedding key is set here (VOYAGE_API_KEY or voyage_api_key). No environment variable overrides a different config-plane provider key. This check sees only the environment `gbrain doctor` runs in; a daemon (gbrain serve, autopilot) has its own, and reports a mismatch in its log with a startup warning or embedding_auth_failed.",
- " [INFO] harness_wiring: No agent harness was detected. Wire one when the user picks an agent app.",
- " [OK] agent_contract: No agent dead ends in the last 7 days (0 non-success event(s) logged).",
- " [OK] connection: Connected, 5 pages",
- " [OK] pgvector: Extension installed",
- " [OK] pages_upsert_arbiter: pages has the UNIQUE(source_id, slug) upsert arbiter",
- " [OK] text_projection_readiness: Visible text projections match their canonical revisions.",
- " [OK] persistence_capacity: Managed write capacity is below 80% of every cumulative limit.",
- " [OK] parked_effects: No Git or withdrawal effect is parked.",
- " [OK] worktree_refresh_stuck: No worktree refresh is stuck.",
- " [OK] managed_guard_schema_drift: Guarded tables carry only the columns gbrain creates.",
- " [OK] publication_refusals: No write was refused by a database guard in the last 7 days.",
- " [OK] links_link_source_check: links_link_source_check has the v114 kebab-case gate",
- " [OK] pglite_scale: PGLite at 5 pages — comfortable below the 1000-page threshold",
- " [OK] rls: Skipped (PGLite — no PostgREST exposure, RLS not applicable)",
- " [OK] schema_version: Version <latest> (latest: <latest>)",
- " [OK] schema_columns: 1001 column(s) verified against live schema",
- " [OK] rls_event_trigger: Skipped (PGLite — no event trigger support)",
- " [INFO] embeddings: Not applicable: embeddings are disabled on this brain (keyword search keeps working).",
- " [INFO] embedding_provider: Not probed: embeddings are disabled on this brain by choice (keyword search keeps working).",
- " [OK] embedding_column_registry: Registry healthy: 1 columns (embedding_image); primary embeddings disabled",
- " [OK] embedding_env_override: no embedding env overrides set",
- " [OK] embedding_migration_state: no embedding migration in flight",
- " [OK] chat_fallback_chain: No chat_fallback_chain is set: every chat call uses only its own model.",
- " [OK] behavior_changes: Nothing to disclose: this brain is a fresh install at v<version>, after every disclosed behavior change, so the one-time behavior-change notice does not apply.",
- " [OK] graph_coverage: Only 2 eligible entity pages (< 5) — coverage ratio not meaningful at this scale",
- " [WARN] brain_score: Brain score 36/100 (embed 0/35, links 5/25, timeline density (entity and event pages) 15/15, orphans 6/15, dead-links 10/10)",
- " Fix: gbrain doctor --remediation-plan --json --brain host",
- " [OK] orphan_ratio: Vacuous: 2 entity pages (<100). Orphan ratio not meaningful at this scale.",
- " [OK] stale_mentions: No by-mention links in this brain.",
- " [OK] timeline_orphans: No orphaned timeline rows across 4 page(s).",
- " [OK] slug_collisions: No slug collisions across 2 source checkout(s).",
- " [OK] timeline_history: Every timeline row has a bullet in its page (4 page(s) inspected).",
- " [OK] derived_visibility: Every extracted atom and synthesized concept carries an explicit visibility no looser than its origin.",
- " [OK] safe_index_pending: Every re-sealable page is at the safe-chunk index version.",
- " [OK] credential_projection_pending: No page waits for the credential-safe re-chunk.",
- " [OK] connector_checkpoints: No orphan connector checkpoint rows older than 7 days.",
- " [OK] persistence_request_indexes: Managed sync request indexes are valid.",
- " [OK] persistence_request_growth: 6 request row(s); no scope exhausts its lifetime request IDs within 90 days at its last-7-day rate.",
- " [OK] persistence_write_stall: No write request has held its claim longer than persistence.max_claim_ms (600000 ms).",
- " [OK] persistence_session_timeouts: PGLite has no session to time out.",
- " [OK] connector_held_items: No connector items are held.",
- " [OK] git_held_files: No Git source files are held.",
- " [OK] frontmatter_hook: No outdated gbrain frontmatter pre-commit hook is installed.",
- " [OK] orphan_persistence_bindings: Every persistence source binding belongs to an existing source.",
- " [OK] unbound_source: No page was written database-only to an unbound source.",
- " [OK] writer_version: Every writer that admitted or published a request in the last 7 days is v0.60.5.0 or newer.",
- " [OK] self_capture: No session corpus is configured; nothing to classify.",
- " [OK] vector_plan: Skipped: PGLite runs vector search in-process; the plan check applies to Postgres brains.",
- " [OK] stale_embedding_effects: No committed write has a stale queued or failed embedding effect.",
- " [OK] google_file_modes: No group- or world-readable gbrain files under Google source directories outside ~/.gbrain.",
- " [OK] extractor_facts_expired: No conversation-extractor fact is left expired by the pre-v0.60.11.0 projection.",
- " [OK] conversation_label_facts: No conversation fact carries the pre-fix meeting-label signature (a 1970-01-01 segment on a label page).",
- " [OK] conversation_outcomes_stale: No conversation extraction outcome predates extractor version 1.",
- " [OK] captured_facts_active: No active fact from a gbrain self-capture or paste candidate remains. This counts facts in the database; the self_capture check counts corpus files.",
- " [OK] loop_facts_drift: Every closed commitment loop has its fact retired.",
- " [OK] ontology_facts_fenced: No ontology observation is held by a page's Facts table.",
- " [OK] extraction_date_grounding: Relative dates resolve against each source's observation date in fact extraction, dream synthesis, extract_atoms and propose_takes (the default). life chronicle events keep their current prompt unless extraction.date_grounding is set to true. Facts extracted before this was on keep their original wording; re-extract a source only with the user's consent (gbrain extract-conversation-facts --source-id <id> --dry-run previews it).",
- " [OK] integrity: Sampled 5 pages; no bare-tweet phrases or external links.",
- " [OK] jsonb_integrity: All JSONB columns store objects/arrays",
- " [OK] takes_weight_grid: No takes yet",
- " [OK] child_table_orphans: All FK-child tables clean (10 tables checked)",
- " [OK] raw_provenance: All synthesized pages carry a raw trace or explicit exemption",
- " [OK] source_config_shape: All source config values are JSON objects",
- " [OK] whoknows_health: whoknows eval fixture present (10 queries). Run `gbrain eval whoknows test/fixtures/whoknows-eval.jsonl` to grade.",
- " [OK] cross_modal_modality_backfill: All image-asset chunks have modality=image",
- " [OK] unified_multimodal_coverage: search.unified_multimodal is off; coverage check N/A",
- " [OK] markdown_body_completeness: No truncated bodies detected",
- " [OK] oversized_pages: No pages exceed 500000 bytes (excluding embed_skip pages, which already took the accepted non-embeddable remediation)",
- " [OK] scraper_junk_pages: No junk-pattern hits in 5 recent page(s) (use --content-audit for full scan)",
- " [OK] content_sanity_audit_recent: No content-sanity events in last 7 days (audit JSONL is local to this host; share GBRAIN_AUDIT_DIR for multi-host visibility)",
- " [OK] quarantined_pages: No quarantined pages",
- " [OK] flagged_pages: No flagged pages",
- " [OK] unverified_extractions: No stale unverified extraction stubs",
- " [WARN] frontmatter_integrity: 1 frontmatter issue(s). notes: 1 (YAML_PARSE=1). Fix: gbrain repair frontmatter --source <id> previews the line fix for every file it can repair (and names the manual fix for the rest, such as a missing opening ---); on an unmanaged checkout gbrain frontmatter validate <source-path> --fix applies the same safe fixes",
- " Fix: gbrain repair frontmatter --source notes --brain host",
- " [WARN] frontmatter_repairable: 1 file(s) have frontmatter gbrain repair frontmatter can fix: notes: 1 (needs_interpretation=1). Preview with gbrain repair frontmatter --source notes (writes nothing; add --include-ambiguous for interpretations after the safe pass).",
- " Fix: gbrain repair frontmatter --source notes --brain host",
- " [OK] eval_capture: No capture failures in the last 24h",
- " [OK] contradictions: No probe runs in the last 7 days. Run `gbrain eval suspected-contradictions --query \"...\" --top-k 5` to populate.",
- " [OK] facts_extraction_health: Automatic fact extraction not configured (keyless) — memory comes from agent-authored `## Facts` fences and the `remember` verb. One optional key enables automatic extraction (OpenAI or Anthropic).",
- " [OK] effective_date_health: Sample of last 1000 pages clean (no fallback-with-parseable-fm-date, no future-dated, no pre-1990)",
- " [OK] salience_health: Skipped (no pages have emotional_weight > 0; either fresh install or recompute hasn't run yet)",
- " [OK] queue_health: PGLite: no jobs waiting for a worker.",
- " [OK] subagent_capability: Subagent tier resolves to default (claude-sonnet-4-6) — full tool-loop capability",
- " [OK] facts_health: facts_health(default): 0 active, 0 today, 0 this week, 0 consolidated, top entities —",
- " [OK] global_maintenance_timeouts: Brain-wide maintenance jobs are finishing within their deadline.",
- " [OK] legacy_job_authority: No queued job predates submission authority.",
- " [OK] legacy_token_grant_shape: Every active legacy token uses the unified grant columns. The permissions mirror for older gbrain binaries is kept until 2026-11-04.",
- " [OK] legacy_token_grant_drift: No legacy token grant has drifted from its permissions mirror.",
- " [OK] legacy_token_null_scope: Every active legacy token has explicit scopes.",
- " [OK] grant_new_ops_available: Every active client and token can call the operations its scopes allow.",
- " [OK] image_assets: No image assets indexed yet",
- " [OK] ocr_health: OCR not in use (or no images ingested with OCR opt-in)",
- " [FAIL] sync_freshness: Source 'notes' has never been synced. Run `gbrain sync --source <id> --no-pull` for each stale source. 1 writer-owned canonical content source(s): upstream sync is not applicable; see canonical_content_writes for publication status",
- " [OK] canonical_content_writes: 1 writer-owned content source(s); no pending canonical publication or recovery.",
- " [INFO] backup_coverage: Not urgent yet: the brain holds 5 page(s)+fact(s) and is under 7 days old (backup coaching starts at 25 items or 7 days). 2 knowledge asset(s) lack verified recovery: default (not_a_git_repo), notes (no git remote). A source repo with a pushed git remote restores its Markdown files only, never DB-only pages, facts, config or credentials. Run `gbrain backup status` for each asset's fix command.",
- " [OK] sync_consolidation: 2 active sources on a managed brain. Recommended cron on the owner host, every 15 minutes: `gbrain sync --all --no-pull --hard-deadline 13m`. Managed sync never pulls: for each checkout that tracks a remote, chain `gbrain sources refresh <id>;` in front of it to take upstream commits. Keep the deadline under the interval: managed sync takes no per-source lock, so a tick that outlives the interval would overlap the next one.",
- " [OK] links_extraction_lag: Extraction lag not applicable (5 pages — too few to assess)",
- " [INFO] cycle_freshness: No full cycle yet for 'default', 'notes': they hold no pages or only pages from the last 24h, so there is nothing to consolidate yet.",
- " [OK] content_hash_duplicates: No same-source content-hash duplicate groups",
- " [OK] code_chunk_metadata: All code-page chunks carry symbol metadata",
- " [OK] undeclared_db_only_pages: Every DB page is file-backed or under a declared/default db_only path (derive-phase defaults: life/events/ atoms/ concepts/ extracts/ dream-cycle-summaries/).",
- " [OK] db_only_collector_collision: No configured collectors declare output paths",
- " [OK] decide_health: System One is off (every decide slot is off; nothing is sent).",
- " [OK] unlinked_facts: No active facts yet; nothing to link.",
- " [OK] edge_validity: relationships: none yet; read policy on; contradiction mode propose (default)",
- " [OK] auto_chronicle: auto_chronicle is on (default). Last 24 h: 0 of 200 automatic extraction calls. Last 7 days: 0 extracted, 0 failed, 0 skipped; $0.00 known spend. 0 page(s) pending. No chat provider is configured, so nothing will be extracted until one is.",
- " [OK] chronicle_config_invalid: chronicle.* settings are valid.",
- " [INFO] auto_chronicle_default_on: Automatic event extraction is on by default and the user has not confirmed it yet. Each eligible new or changed meeting, conversation or calendar page gets one paid chat call (cap $0.25 per page; at most 200 calls per day, so at most $50.00 per day for a priced model; an unpriced model has no cap), and page text goes to the configured chat provider. Relay this to the user, then run `gbrain config set auto_chronicle true` to keep it or `gbrain config set auto_chronicle false` to opt out.",
- " [OK] facts_drain: No facts-absorb jobs are queued (no run recorded yet).",
- " [INFO] fact_take_vectors: Not applicable: embeddings are disabled on this brain (keyword search keeps working).",
- " [OK] planner_stats_stale: Planner statistics are fresh on 6 hot tables.",
- " [OK] retrieval_feedback_health: Retrieval feedback is off; rankings do not learn from ratings. Turn it on with: gbrain config set feedback.enabled true",
- " [OK] revision_backfill: Every page has its revision; the page revision backfill is complete.",
- " [OK] core_memory: Core memory is off (opt-in). If the user wants a profile loaded in every session: gbrain config set memory.core.enabled true, then gbrain core init.",
- " [OK] managed_sync_not_moving: No managed sync is pending.",
- " [OK] two_consumers_on_host: PGLite admits one process; no consumer heartbeat rows are kept.",
- " [OK] consumers_without_heartbeat: PGLite admits one process; no consumer heartbeat rows are kept.",
- " [OK] host_identity_mismatch: This process's host identity (<home>/.gbrain/persistence/host.json) owns every binding this filesystem holds.",
- " [OK] fence_integrity: No malformed facts or takes fence is held, stored or waiting in a checkout (2 source(s) scanned).",
- " [OK] search_mode: Mode: conservative (no per-key overrides — mode bundle is canonical).",
- " [OK] hidden_by_search_policy: No pages hidden by search-exclude policy.",
- " [OK] eval_drift: No retrieval-affecting files changed in working tree.",
- " [OK] reranker_health: Reranker disabled — no failures expected",
- " [OK] batch_retry_health: No exhausted batch retries in last 24h.",
- " [OK] wedged_queue: PGLite — no queue to check",
- " [OK] orphaned_private_queue: No orphaned private queues",
- " [OK] autopilot_fanout_concurrency: PGLite — single-writer, fan-out is 1",
- " [OK] google_oauth: no Google accounts connected (gbrain google connect to start)",
- " [OK] graph_signals_coverage: graph_signals disabled — coverage not checked",
- " [OK] junk_entity_hubs: No junk entity hubs (pages with <=2 chunks and >1000 edges)",
- " [OK] brainstorm_health: Migration v79 applied; tracking enabled. Calibration profile not yet generated — brainstorm/lsd will run unbiased until enough takes are resolved.",
- " [WARN] link_resolution_opportunity: 6 of 8 bare wikilinks (75%) would resolve to 2 distinct page(s) under global_basename mode. Enable with: gbrain config set link_resolution.global_basename true",
- " [OK] embedding_width_consistency: Embeddings disabled — no active embedding width to reconcile.",
- " [OK] facts_embedding_width_consistency: Skipped on PGLite (single bundled pgvector version).",
- " [OK] source_routing_health: Multi-source brain (1 non-default source(s)); all populated",
- " [OK] oauth_confidential_client_health: No OAuth clients registered",
- " [OK] oauth_client_scope_health: Scoped-client grants consistent (no dangling federated reads, no orphaned workspace sources, no privileged self-registered clients)",
- " [OK] autopilot_lock_scope: Lock path: <home>/.gbrain/autopilot.lock",
- " [OK] stale_locks: No stale locks (no rows with ttl_expires_at < NOW())",
- " [OK] cycle_phase_scope: Phase taxonomy: 12 source-scoped, 13 brain-global, 2 mixed. Source-safe: [lint, backlinks, sync, extract, extract_facts, extract_atoms, recompute_emotional_weight, consolidate, propose_takes, conversation_facts_backfill, enrich_thin, schema-suggest]. Brain-global: [fence_repair, resolve_symbol_edges, synthesize_concepts, grade_takes, calibration_profile, edge_contradictions, drift, chronicle, facts_drain, skillopt, embed, orphans, purge]. Mixed: [synthesize, patterns].",
- " [INFO] embed_staleness: Not applicable: embeddings are disabled on this brain by choice, so chunks have no vectors by design (keyword search keeps working).",
- " [OK] entity_link_coverage: Only 2 entity pages (< 5) — coverage ratio not meaningful at this scale",
- " [OK] timeline_coverage: Only 2 entity pages (< 5) — coverage ratio not meaningful at this scale",
- " [INFO] takes_count: 0 takes (takes.bootstrap_enabled is false; opt in to enable)",
- " [OK] pack_upgrade_available: Active pack [email protected]+a50a67b9 is current (no successor declared)",
- " [OK] type_proliferation: 3 distinct typed values (pack declares 20)",
- " [OK] dangling_aliases: No dangling aliases",
- "Brain checks: 60/100 (category penalty)",
- "Skill checks: 95/100",
- "Ops checks: 100/100",
- "Meta checks: 100/100",
- "Weighted brain score: [WARN] Brain score 36/100 (embed 0/35, links 5/25, timeline density (entity and event pages) 15/15, orphans 6/15, dead-links 10/10)",
- "Overall health score: 55/100. Failed checks found."
- ]
- },
- "normalizer": "doctor-json-v1"
-}
diff --git a/test/fixtures/goldens/doctor/content-pglite-json.json b/test/fixtures/goldens/doctor/content-pglite-json.json
deleted file mode 100644
index 76c0332dce..0000000000
--- a/test/fixtures/goldens/doctor/content-pglite-json.json
+++ /dev/null
@@ -1,2519 +0,0 @@
-{
- "golden": {
- "args": [
- "doctor",
- "--json",
- "--skills-dir",
- "<home>/skills"
- ],
- "exit_code": 1,
- "report": {
- "brain_checks_score": 60,
- "capped_by": [
- "embeddings_disabled"
- ],
- "category_scores": {
- "brain": 60,
- "meta": 100,
- "ops": 100,
- "skill": 95
- },
- "checks": [
- {
- "category": "skill",
- "message": "1 skills, all reachable",
- "name": "resolver_health",
- "status": "ok"
- },
- {
- "category": "skill",
- "details": {
- "enabled": true,
- "engine": "pglite",
- "fired_recently": false,
- "last_fired": null,
- "path": "pglite — serve IPC socket not present",
- "policy_skill_installed": false
- },
- "fix": {
- "actor": "user",
- "consent": [
- "persistent_install"
- ],
- "docs": "https://github.com/garrytan/gbrain/blob/master/docs/protocol/MEMORY_VERBS_v1.md#install-the-4-command-quickstart",
- "next": "report",
- "requires_exclusive": false,
- "user_message": "Which agent app should get gbrain memory? The install guide has a one-line command for each.",
- "why": "Register `<absolute path to gbrain> serve --surface full` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
- },
- "message": "pglite — serve IPC socket not present; enabled but NO resolve path exists right now: the IPC socket is only bound by a running `gbrain serve` (stdio or --http) — until one is up, hooks/reflex degrade to no_serve on this brain (host capability may still supply pointers; policy skill carries otherwise) — policy skill not installed; run `gbrain integrations install retrieval-reflex --target <host-repo>`",
- "name": "retrieval_reflex_health",
- "readiness_state": "not_applicable",
- "severity": "info",
- "status": "ok"
- },
- {
- "category": "skill",
- "details": {
- "channels": {},
- "window_days": 7
- },
- "message": "no push-context activity in 7 days — if a hook adapter is installed, confirm its registration landed and the harness session was RESTARTED (hooks snapshot at session start); a serve older than this build logs NOTHING for the hook lane — restart serve on the new build to activate the feedback loop",
- "name": "volunteer_channels",
- "status": "ok"
- },
- {
- "category": "skill",
- "message": "no verb calls recorded yet (sidecar appears on first remember/recall/entity/synthesize/forget)",
- "name": "memory_verbs_usage",
- "status": "ok"
- },
- {
- "category": "skill",
- "message": "1/1 skills pass",
- "name": "skill_conformance",
- "status": "ok"
- },
- {
- "category": "skill",
- "message": "1 skill(s) compliant or exempt",
- "name": "skill_brain_first",
- "status": "ok"
- },
- {
- "category": "skill",
- "message": "No skills.lock.json in <home>/skills — integrity check not applicable",
- "name": "skills_manifest_integrity",
- "status": "ok"
- },
- {
- "category": "skill",
- "details": {
- "drifted": [],
- "new": [
- "academic-verify",
- "archive-crawler",
- "article-enrichment",
- "ask-user",
- "blog-ingest",
- "book-mirror",
- "brain-ingest-gate",
- "brain-link-discipline",
- "brain-ops",
- "brain-pdf",
- "brain-taxonomist",
- "briefing",
- "bulk-ingestion",
- "capture",
- "chat-connectors",
- "citation-fixer",
- "citation-graph-ingest",
- "cold-start",
- "company-brainify",
- "concept-synthesis",
- "context-audit",
- "conversation-archive",
- "correction-pipeline",
- "cron-scheduler",
- "cross-modal-review",
- "daily-task-manager",
- "daily-task-prep",
- "data-loss-gate",
- "data-research",
- "draft-in-voice",
- "eiirp",
- "enrich",
- "fact-check",
- "functional-area-resolver",
- "gbrain-advisor",
- "google-loops",
- "idea-ingest",
- "idea-lineage",
- "ingest",
- "maintain",
- "mcp-access",
- "measure-before-you-fix",
- "media-ingest",
- "meeting-ingestion",
- "minion-orchestrator",
- "perplexity-research",
- "publish",
- "query",
- "repo-architecture",
- "reports",
- "research-compendium",
- "resolve-before-asking",
- "signal-detector",
- "skill-autobench",
- "skill-creator",
- "skillify",
- "skillpack-check",
- "skillpack-harvest",
- "soul-audit",
- "strategic-reading",
- "testing",
- "two-tier-extraction",
- "voice-note-ingest",
- "webhook-transforms"
- ]
- },
- "fix_unavailable_reason": "unstructured",
- "message": "64 new built-in skill(s) available that this workspace hasn't installed: academic-verify, archive-crawler, article-enrichment, ask-user, blog-ingest, book-mirror, brain-ingest-gate, brain-link-discipline, … +56 more. Add them with `gbrain skillpack sync`.",
- "name": "skill_currency",
- "status": "warn"
- },
- {
- "category": "skill",
- "message": "no installed skills declare preconditions",
- "name": "skill_preconditions",
- "status": "ok"
- },
- {
- "category": "ops",
- "details": {
- "enabled": false,
- "out_of_band_settable": true,
- "reason": "disabled"
- },
- "message": "memorable relay off (default)",
- "name": "memorable_relay_health",
- "status": "ok"
- },
- {
- "category": "brain",
- "details": {
- "audience": "personal",
- "audience_reasons": [
- "no shared declaration; 0 non-automation client(s) active in 30d"
- ],
- "backstop_visibility": "private",
- "capture_lanes": {
- "compact": "extract",
- "session_end": "extract",
- "writeback": "retire"
- },
- "counters_note": "local, append-only, loss-tolerant observability over the last 7d — never a source of truth",
- "cross_lane_duplicates_7d": 0,
- "instruction_visibility": "world",
- "mode": "off",
- "mode_valid": true,
- "near_duplicates_shadow_7d": 0,
- "nudge_shown": false,
- "transient_ttl": "3d",
- "ttl_valid": true,
- "visibility_note": "world = readable by agents authorized on THIS brain, not the public internet"
- },
- "message": "ambient writeback off (default): Stop-hook turn capture is off, but the compaction harvest and SessionEnd transcripts still extract (installing the harness hooks opted into them; stop them: gbrain config set memory.auto_writeback off). Enable: gbrain config set memory.auto_writeback salient",
- "name": "memory_writeback",
- "status": "ok"
- },
- {
- "category": "ops",
- "message": "No chat connectors configured (optional).",
- "name": "connectors",
- "status": "ok"
- },
- {
- "category": "ops",
- "details": {
- "breaker_enabled": true,
- "count_exact": true,
- "inspected_keys": 0,
- "keys": [],
- "threshold": 3
- },
- "message": "No dream key died 3+ times in 24h",
- "name": "dream_paid_loop",
- "status": "ok"
- },
- {
- "category": "meta",
- "details": {
- "pending_fresh_install": [
- "0.11.0",
- "0.14.0",
- "0.22.4",
- "0.28.0",
- "0.53.0"
- ]
- },
- "fix": {
- "actor": "agent",
- "argv": [
- "gbrain",
- "apply-migrations",
- "--yes",
- "--no-autopilot-install"
- ],
- "command": "gbrain apply-migrations --yes --no-autopilot-install",
- "consent": [],
- "next": "run",
- "requires_exclusive": true,
- "verify": {
- "argv": [
- "gbrain",
- "doctor",
- "--only",
- "minions_migration",
- "--json",
- "--brain",
- "host"
- ]
- },
- "why": "Runs the setup migrations gbrain init left pending (preferences, host-work notes, shared-skill checkpoints) on the brain host, without installing background services."
- },
- "message": "5 setup migration(s) not run yet on this new brain (pending_fresh_install: 0.11.0, 0.14.0, 0.22.4, 0.28.0, 0.53.0). Expected after gbrain init, not a failed upgrade.",
- "name": "minions_migration",
- "severity": "info",
- "status": "ok"
- },
- {
- "category": "ops",
- "message": "mode=notify",
- "name": "self_upgrade_health",
- "status": "ok"
- },
- {
- "category": "ops",
- "message": "Bun <bun-version> (minimum 1.4.0)",
- "name": "bun_runtime",
- "status": "ok"
- },
- {
- "category": "brain",
- "message": "disabled (opt-in). Enable with: gbrain config set autopilot.nightly_quality_probe.enabled true",
- "name": "nightly_quality_probe_health",
- "status": "ok"
- },
- {
- "category": "brain",
- "details": {
- "kinds": [],
- "schema_version": 1
- },
- "message": "no extractions in last 7 days",
- "name": "extract_health",
- "status": "ok"
- },
- {
- "category": "brain",
- "message": "disabled (opt-in). Enable with: gbrain config set cycle.conversation_facts_backfill.enabled true",
- "name": "conversation_facts_backlog",
- "status": "ok"
- },
- {
- "category": "brain",
- "details": {
- "backlog": 0,
- "known_approximation": "page backlog only; transcript corpus not counted",
- "pack_declares_phase": false
- },
- "message": "no pages awaiting atom extraction",
- "name": "extract_atoms_backlog",
- "status": "ok"
- },
- {
- "category": "brain",
- "details": {
- "drift_pct": 0,
- "drifted": 0,
- "slug_unbound": 0,
- "source_changed": 0,
- "source_gone": 0,
- "total_atoms": 0
- },
- "message": "no atoms to check",
- "name": "atom_provenance_drift",
- "status": "ok"
- },
- {
- "category": "brain",
- "message": "No conversation-type pages — coverage check not applicable",
- "name": "conversation_format_coverage",
- "status": "ok"
- },
- {
- "category": "ops",
- "message": "No progressive-batch operations in the last 7 days",
- "name": "progressive_batch_audit_health",
- "status": "ok"
- },
- {
- "category": "brain",
- "message": "disabled (opt-in; default-on only for search.mode=tokenmax). Enable with: `gbrain config set autopilot.conversation_parser_probe.enabled true`",
- "name": "conversation_parser_probe_health",
- "status": "ok"
- },
- {
- "category": "ops",
- "message": "gbrain home is outside any enclosing git worktree.",
- "name": "home_dir_in_worktree",
- "status": "ok"
- },
- {
- "category": "meta",
- "message": "default source local_path is set: <home>/.gbrain/content/<uuid>/default",
- "name": "default_source_local_path",
- "status": "ok"
- },
- {
- "category": "meta",
- "details": {
- "docs": "docs/guides/troubleshooting.md#not-verified-doctor-checks",
- "git_root_skipped": [],
- "limit": 10000,
- "timeout_ms": "<volatile>",
- "unreadable_sources": [],
- "walk_truncated": false
- },
- "message": "No cross-source slug drift detected.",
- "name": "multi_source_drift",
- "status": "ok"
- },
- {
- "category": "brain",
- "details": {
- "docs": "docs/guides/repair.md#embedding-key-source",
- "embedding_key": {
- "config_key": "voyage_api_key",
- "kind": "missing",
- "variable": "VOYAGE_API_KEY"
- },
- "embedding_model": "voyage:voyage-4",
- "shadows": []
- },
- "message": "No embedding key is set here (VOYAGE_API_KEY or voyage_api_key). No environment variable overrides a different config-plane provider key. This check sees only the environment `gbrain doctor` runs in; a daemon (gbrain serve, autopilot) has its own, and reports a mismatch in its log with a startup warning or embedding_auth_failed.",
- "name": "embedding_key_source",
- "status": "ok"
- },
- {
- "category": "ops",
- "details": {
- "reason": "no_harness_detected"
- },
- "fix": {
- "actor": "user",
- "consent": [
- "persistent_install"
- ],
- "docs": "https://github.com/garrytan/gbrain/blob/master/docs/protocol/MEMORY_VERBS_v1.md#install-the-4-command-quickstart",
- "next": "report",
- "requires_exclusive": false,
- "user_message": "Which agent app should get gbrain memory? The install guide has a one-line command for each.",
- "why": "Register `<absolute path to gbrain> serve --surface full` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
- },
- "message": "No agent harness was detected. Wire one when the user picks an agent app.",
- "name": "harness_wiring",
- "readiness_state": "missing",
- "severity": "info",
- "status": "ok"
- },
- {
- "category": "meta",
- "details": {
- "consent_refused": 0,
- "derived_cap_exhausted": 0,
- "events": 0,
- "internal_errors": 0,
- "json_document_missing": 0,
- "window_days": 7
- },
- "message": "No agent dead ends in the last 7 days (0 non-success event(s) logged).",
- "name": "agent_contract",
- "status": "ok"
- },
- {
- "category": "ops",
- "message": "Connected, 5 pages",
- "name": "connection",
- "status": "ok"
- },
- {
- "category": "ops",
- "message": "Extension installed",
- "name": "pgvector",
- "status": "ok"
- },
- {
- "category": "meta",
- "message": "pages has the UNIQUE(source_id, slug) upsert arbiter",
- "name": "pages_upsert_arbiter",
- "status": "ok"
- },
- {
- "category": "brain",
- "details": {
- "readiness": "ready",
- "ready": true
- },
- "message": "Visible text projections match their canonical revisions.",
- "name": "text_projection_readiness",
- "status": "ok"
- },
- {
- "category": "ops",
- "details": {
- "commands": [],
- "exact": true,
- "inspected": 2,
- "resources": [],
- "truncated": false
- },
- "message": "Managed write capacity is below 80% of every cumulative limit.",
- "name": "persistence_capacity",
- "status": "ok"
- },
- {
- "category": "brain",
- "details": {
- "effects": [],
- "exact": true,
- "inspected": 0,
- "parked_effects": 0,
- "truncated": false
- },
- "message": "No Git or withdrawal effect is parked.",
- "name": "parked_effects",
- "status": "ok"
- },
- {
- "category": "ops",
- "details": {
- "refreshes": []
- },
- "message": "No worktree refresh is stuck.",
- "name": "worktree_refresh_stuck",
- "status": "ok"
- },
- {
- "category": "ops",
- "details": {
- "extra_columns": [],
- "page_child_source_columns": [],
- "runbook": "docs/guides/write-refusals.md#managed-guard-page-children"
- },
- "message": "Guarded tables carry only the columns gbrain creates.",
- "name": "managed_guard_schema_drift",
- "status": "ok"
- },
- {
- "category": "ops",
- "details": {
- "guard_refusals": 0,
- "runbook": "docs/guides/write-refusals.md#managed-guard-page-children",
- "trigger_refusals": 0,
- "unclassified_p0001": 0,
- "window_days": 7
- },
- "message": "No write was refused by a database guard in the last 7 days.",
- "name": "publication_refusals",
- "status": "ok"
- },
- {
- "category": "meta",
- "message": "links_link_source_check has the v114 kebab-case gate",
- "name": "links_link_source_check",
- "status": "ok"
- },
- {
- "category": "ops",
- "message": "PGLite at 5 pages — comfortable below the 1000-page threshold",
- "name": "pglite_scale",
- "status": "ok"
- },
- {
- "category": "ops",
- "message": "Skipped (PGLite — no PostgREST exposure, RLS not applicable)",
- "name": "rls",
- "status": "ok"
- },
- {
- "category": "meta",
- "message": "Version <latest> (latest: <latest>)",
- "name": "schema_version",
- "status": "ok"
- },
- {
- "category": "meta",
- "message": "1001 column(s) verified against live schema",
- "name": "schema_columns",
- "status": "ok"
- },
- {
- "category": "ops",
- "message": "Skipped (PGLite — no event trigger support)",
- "name": "rls_event_trigger",
- "status": "ok"
- },
- {
- "category": "brain",
- "fix": {
- "actor": "user",
- "argv": [
- "gbrain",
- "init",
- "--force",
- "--embedding-model",
- "voyage:voyage-4",
- "--embedding-dimensions",
- "1024",
- "--path",
- "<home>/.gbrain/brain.pglite"
- ],
- "command": "gbrain init --force --embedding-model voyage:voyage-4 --embedding-dimensions 1024 --path <home>/.gbrain/brain.pglite",
- "consent": [
- "credentials",
- "paid"
- ],
- "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/search-modes.md",
- "inputs": [
- {
- "how": "Ask the user for an API key for Voyage AI; store it with `gbrain config set voyage_api_key <key>` (every gbrain process reads it), or export VOYAGE_API_KEY in the environment of every gbrain process. Then run the command.",
- "name": "VOYAGE_API_KEY"
- }
- ],
- "next": "tell_user_to_run",
- "requires_exclusive": true,
- "user_message": "Semantic search needs an embedding API key. Voyage AI works with this brain; if you add a key (VOYAGE_API_KEY), I can turn it on. Embedding costs a little per page; your notes and facts stay as they are.",
- "verify": {
- "argv": [
- "gbrain",
- "doctor",
- "--only",
- "embeddings",
- "--json",
- "--brain",
- "host"
- ]
- },
- "why": "Embeddings are off, so search is keyword-only, and no configured embedding key fits this brain. Once the key is set this turns on voyage:voyage-4 (1024d) for the PGLite brain at <home>/.gbrain/brain.pglite. Pages, facts and keyword search are kept; existing chunks and facts are queued for vectors, which `gbrain embed --stale` (or the next maintenance cycle) fills."
- },
- "message": "Not applicable: embeddings are disabled on this brain (keyword search keeps working).",
- "name": "embeddings",
- "readiness_state": "disabled_by_choice",
- "severity": "info",
- "status": "ok"
- },
- {
- "category": "brain",
- "fix": {
- "actor": "user",
- "argv": [
- "gbrain",
- "init",
- "--force",
- "--embedding-model",
- "voyage:voyage-4",
- "--embedding-dimensions",
- "1024",
- "--path",
- "<home>/.gbrain/brain.pglite"
- ],
- "command": "gbrain init --force --embedding-model voyage:voyage-4 --embedding-dimensions 1024 --path <home>/.gbrain/brain.pglite",
- "consent": [
- "credentials",
- "paid"
- ],
- "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/search-modes.md",
- "inputs": [
- {
- "how": "Ask the user for an API key for Voyage AI; store it with `gbrain config set voyage_api_key <key>` (every gbrain process reads it), or export VOYAGE_API_KEY in the environment of every gbrain process. Then run the command.",
- "name": "VOYAGE_API_KEY"
- }
- ],
- "next": "tell_user_to_run",
- "requires_exclusive": true,
- "user_message": "Semantic search needs an embedding API key. Voyage AI works with this brain; if you add a key (VOYAGE_API_KEY), I can turn it on. Embedding costs a little per page; your notes and facts stay as they are.",
- "verify": {
- "argv": [
- "gbrain",
- "doctor",
- "--only",
- "embeddings",
- "--json",
- "--brain",
- "host"
- ]
- },
- "why": "Embeddings are off, so search is keyword-only, and no configured embedding key fits this brain. Once the key is set this turns on voyage:voyage-4 (1024d) for the PGLite brain at <home>/.gbrain/brain.pglite. Pages, facts and keyword search are kept; existing chunks and facts are queued for vectors, which `gbrain embed --stale` (or the next maintenance cycle) fills."
- },
- "message": "Not probed: embeddings are disabled on this brain by choice (keyword search keeps working).",
- "name": "embedding_provider",
- "readiness_state": "disabled_by_choice",
- "severity": "info",
- "status": "ok"
- },
- {
- "category": "brain",
- "message": "Registry healthy: 1 columns (embedding_image); primary embeddings disabled",
- "name": "embedding_column_registry",
- "status": "ok"
- },
- {
- "category": "brain",
- "message": "no embedding env overrides set",
- "name": "embedding_env_override",
- "status": "ok"
- },
- {
- "category": "brain",
- "message": "no embedding migration in flight",
- "name": "embedding_migration_state",
- "status": "ok"
- },
- {
- "category": "ops",
- "message": "No chat_fallback_chain is set: every chat call uses only its own model.",
- "name": "chat_fallback_chain",
- "status": "ok"
- },
- {
- "category": "meta",
- "message": "Nothing to disclose: this brain is a fresh install at v<version>, after every disclosed behavior change, so the one-time behavior-change notice does not apply.",
- "name": "behavior_changes",
- "status": "ok"
- },
- {
- "category": "brain",
- "message": "Only 2 eligible entity pages (< 5) — coverage ratio not meaningful at this scale",
- "name": "graph_coverage",
- "status": "ok"
- },
- {
- "category": "brain",
- "fix": {
- "actor": "agent",
- "argv": [
- "gbrain",
- "doctor",
- "--remediation-plan",
- "--json",
- "--brain",
- "host"
- ],
- "command": "gbrain doctor --remediation-plan --json --brain host",
- "consent": [],
- "next": "run",
- "requires_exclusive": false,
- "verify": {
- "argv": [
- "gbrain",
- "doctor",
- "--only",
- "brain_score",
- "--json",
- "--brain",
- "host"
- ]
- },
- "why": "The plan lists which steps raise each score component, what they cost and the reachable maximum; it changes nothing."
- },
- "message": "Brain score 36/100 (embed 0/35, links 5/25, timeline density (entity and event pages) 15/15, orphans 6/15, dead-links 10/10)",
- "name": "brain_score",
- "status": "warn"
- },
- {
- "category": "brain",
- "message": "Vacuous: 2 entity pages (<100). Orphan ratio not meaningful at this scale.",
- "name": "orphan_ratio",
- "status": "ok"
- },
- {
- "category": "brain",
- "message": "No by-mention links in this brain.",
- "name": "stale_mentions",
- "status": "ok"
- },
- {
- "category": "brain",
- "message": "No orphaned timeline rows across 4 page(s).",
- "name": "timeline_orphans",
- "status": "ok"
- },
- {
- "category": "brain",
- "message": "No slug collisions across 2 source checkout(s).",
- "name": "slug_collisions",
- "status": "ok"
- },
- {
- "category": "brain",
- "details": {
- "count": "exact",
- "kept_unrenderable_rows": 0,
- "materializable_rows": 0,
- "pages_affected": 0,
- "pages_inspected": 4,
- "repair": "timeline",
- "truncated": false
- },
- "message": "Every timeline row has a bullet in its page (4 page(s) inspected).",
- "name": "timeline_history",
- "status": "ok"
- },
- {
- "category": "brain",
- "details": {
- "count": "exact",
- "looser_atoms": 0,
- "looser_concepts": 0,
- "repair": "visibility",
- "truncated": false,
- "unstamped_atoms": 0,
- "unstamped_concepts": 0
- },
- "message": "Every extracted atom and synthesized concept carries an explicit visibility no looser than its origin.",
- "name": "derived_visibility",
- "status": "ok"
- },
- {
- "category": "brain",
- "details": {
- "count": "exact",
- "kept_pages": 0,
- "pages_pending": 0,
- "repair": "safe-chunks",
- "truncated": false
- },
- "message": "Every re-sealable page is at the safe-chunk index version.",
- "name": "safe_index_pending",
- "status": "ok"
- },
- {
- "category": "brain",
- "details": {
- "count": "exact",
- "kept_pages": 0,
- "pages_pending": 0,
- "truncated": false
- },
- "message": "No page waits for the credential-safe re-chunk.",
- "name": "credential_projection_pending",
- "status": "ok"
- },
- {
- "category": "brain",
- "details": {
- "checkpoints": 0,
- "count": 0,
- "docs": "docs/guides/repair.md#connector-checkpoints",
- "repair": "connector-checkpoints",
- "retries": 0,
- "truncated": false
- },
- "message": "No orphan connector checkpoint rows older than 7 days.",
- "name": "connector_checkpoints",
- "status": "ok"
- },
- {
- "category": "ops",
- "details": {
- "command": "gbrain repair request-indexes --apply",
- "count": 0,
- "docs": "docs/guides/repair.md#request-indexes",
- "indexes": [
- {
- "name": "persistence_requests_sync_run_open",
- "state": "valid"
- },
- {
- "name": "persistence_requests_sync_run_committed",
- "state": "valid"
- }
- ],
- "repair": "request-indexes"
- },
- "message": "Managed sync request indexes are valid.",
- "name": "persistence_request_indexes",
- "status": "ok"
- },
- {
- "category": "ops",
- "details": {
- "commands": [],
- "docs": "docs/guides/repair.md#request-growth",
- "rows": 6,
- "rows_exact": true,
- "scopes": [
- {
- "admissions_in_window": 6,
- "config_key": "persistence.limits.brain_lifetime_ids",
- "days_to_exhaustion": null,
- "exhaustion_date": null,
- "lifetime_ids": 7,
- "limit": 1000000,
- "per_day": 1,
- "scope": "brain",
- "window_days": 7
- },
- {
- "admissions_in_window": 6,
- "config_key": "persistence.limits.principal_lifetime_ids",
- "days_to_exhaustion": null,
- "exhaustion_date": null,
- "lifetime_ids": 7,
- "limit": 250000,
- "per_day": 1,
- "scope": "principal:local_cli:<uuid>",
- "window_days": 7
- }
- ],
- "verify": "gbrain doctor --json (check persistence_request_growth)",
- "window_days": 7
- },
- "message": "6 request row(s); no scope exhausts its lifetime request IDs within 90 days at its last-7-day rate.",
- "name": "persistence_request_growth",
- "status": "ok"
- },
- {
- "category": "ops",
- "details": {
- "config_key": "persistence.max_claim_ms",
- "count": 0,
- "docs": "docs/guides/troubleshooting.md#persistence-write-stall",
- "max_claim_ms": "<volatile>",
- "preparation_policy": {
- "maintenance_preparation_ms": "<volatile>",
- "max_preparation_attempts": 2,
- "preparation_ceiling_ms": "<volatile>",
- "sync_preparation_ms": "<volatile>"
- },
- "stalls": []
- },
- "message": "No write request has held its claim longer than persistence.max_claim_ms (600000 ms).",
- "name": "persistence_write_stall",
- "status": "ok"
- },
- {
- "category": "ops",
- "details": {
- "applied": null,
- "configured": "5min",
- "docs": "docs/guides/troubleshooting.md#session-timeouts-not-applied"
- },
- "message": "PGLite has no session to time out.",
- "name": "persistence_session_timeouts",
- "status": "ok"
- },
- {
- "category": "brain",
- "details": {
- "docs": "docs/guides/repair.md#connector-held-items",
- "held": 0,
- "sources": []
- },
- "message": "No connector items are held.",
- "name": "connector_held_items",
- "status": "ok"
- },
- {
- "category": "brain",
- "details": {
- "docs": "docs/guides/repair.md#held-files",
- "escalate_count": 50,
- "held": 0,
- "source_ids": [],
- "sources": []
- },
- "message": "No Git source files are held.",
- "name": "git_held_files",
- "status": "ok"
- },
- {
- "category": "ops",
- "details": {
- "count": 0,
- "docs": "docs/guides/repair.md#held-files",
- "hooks": []
- },
- "message": "No outdated gbrain frontmatter pre-commit hook is installed.",
- "name": "frontmatter_hook",
- "status": "ok"
- },
- {
- "category": "brain",
- "details": {
- "bindings": [],
- "count": 0,
- "docs": "docs/guides/repair.md#orphan-bindings",
- "repair": "orphan-bindings",
- "truncated": false
- },
- "message": "Every persistence source binding belongs to an existing source.",
- "name": "orphan_persistence_bindings",
- "status": "ok"
- },
- {
- "category": "brain",
- "details": {
- "sources": [],
- "total": 0
- },
- "message": "No page was written database-only to an unbound source.",
- "name": "unbound_source",
- "status": "ok"
- },
- {
- "category": "ops",
- "details": {
- "count": 0,
- "floor": "0.60.5.0",
- "hosts": [],
- "observed": [
- {
- "host_id": "<uuid>",
- "last_seen": "<ts>",
- "principal": "local_cli:<uuid>",
- "role": "consumer",
- "version": "<version>"
- },
- {
- "host_id": "<uuid>",
- "last_seen": "<ts>",
- "principal": "local_cli:<uuid>",
- "role": "admitter",
- "version": "<version>"
- }
- ],
- "truncated": false,
- "window_days": 7
- },
- "message": "Every writer that admitted or published a request in the last 7 days is v0.60.5.0 or newer.",
- "name": "writer_version",
- "status": "ok"
- },
- {
- "category": "brain",
- "details": {
- "classified": 0,
- "count": "exact",
- "truncated": false,
- "unclassifiable": 0
- },
- "message": "No session corpus is configured; nothing to classify.",
- "name": "self_capture",
- "status": "ok"
- },
- {
- "category": "ops",
- "details": {
- "outcome": "skipped",
- "reason": "pglite"
- },
- "message": "Skipped: PGLite runs vector search in-process; the plan check applies to Postgres brains.",
- "name": "vector_plan",
- "status": "ok"
- },
- {
- "category": "ops",
- "details": {
- "command": "gbrain repair embedding-effects",
- "count": "exact",
- "docs": "docs/guides/repair.md#stale-queued-embedding-effects",
- "effects": [],
- "failed_effects": 0,
- "repair": "embedding-effects",
- "resolution": "repairable",
- "retry_queued_effects": 0,
- "stale_effects": 0,
- "truncated": false
- },
- "message": "No committed write has a stale queued or failed embedding effect.",
- "name": "stale_embedding_effects",
- "status": "ok"
- },
- {
- "category": "ops",
- "details": {
- "count": 0,
- "docs": "docs/guides/google-connect.md",
- "repair": "google-file-modes",
- "sources": []
- },
- "message": "No group- or world-readable gbrain files under Google source directories outside ~/.gbrain.",
- "name": "google_file_modes",
- "status": "ok"
- },
- {
- "category": "brain",
- "details": {
- "ambiguous": 0,
- "docs": "docs/guides/repair.md#explicit-only-repair-kinds",
- "evidenced": 0,
- "excluded": 0,
- "repair": "extractor-facts"
- },
- "message": "No conversation-extractor fact is left expired by the pre-v0.60.11.0 projection.",
- "name": "extractor_facts_expired",
- "status": "ok"
- },
- {
- "category": "brain",
- "details": {
- "capped": false,
- "docs": "docs/guides/repair.md#conversation-labels",
- "evidenced": 0,
- "repair": "conversation-labels"
- },
- "message": "No conversation fact carries the pre-fix meeting-label signature (a 1970-01-01 segment on a label page).",
- "name": "conversation_label_facts",
- "status": "ok"
- },
- {
- "category": "brain",
- "details": {
- "capped": false,
- "docs": "docs/guides/repair.md#conversation-labels",
- "extractor_version": 1,
- "sample": [],
- "scanned": 0,
- "stale": 0,
- "unstamped": 0
- },
- "message": "No conversation extraction outcome predates extractor version 1.",
- "name": "conversation_outcomes_stale",
- "status": "ok"
- },
- {
- "category": "brain",
- "details": {
- "ambiguous": 0,
- "docs": "docs/guides/repair.md#explicit-only-repair-kinds",
- "evidenced": 0,
- "excluded": 0,
- "repair": "captured-facts",
- "unclassifiable": 0
- },
- "message": "No active fact from a gbrain self-capture or paste candidate remains. This counts facts in the database; the self_capture check counts corpus files.",
- "name": "captured_facts_active",
- "status": "ok"
- },
- {
- "category": "brain",
- "details": {
- "docs": "docs/guides/repair.md#explicit-only-repair-kinds",
- "drifted": 0,
- "repair": "loop-facts"
- },
- "message": "Every closed commitment loop has its fact retired.",
- "name": "loop_facts_drift",
- "status": "ok"
- },
- {
- "category": "brain",
- "details": {
- "docs": "docs/guides/repair.md#explicit-only-repair-kinds",
- "excluded": 0,
- "fenced": 0,
- "repair": "ontology-facts",
- "retired": 0
- },
- "message": "No ontology observation is held by a page's Facts table.",
- "name": "ontology_facts_fenced",
- "status": "ok"
- },
- {
- "category": "brain",
- "message": "Relative dates resolve against each source's observation date in fact extraction, dream synthesis, extract_atoms and propose_takes (the default). life chronicle events keep their current prompt unless extraction.date_grounding is set to true. Facts extracted before this was on keep their original wording; re-extract a source only with the user's consent (gbrain extract-conversation-facts --source-id <id> --dry-run previews it).",
- "name": "extraction_date_grounding",
- "status": "ok"
- },
- {
- "category": "brain",
- "message": "Sampled 5 pages; no bare-tweet phrases or external links.",
- "name": "integrity",
- "status": "ok"
- },
- {
- "category": "brain",
- "message": "All JSONB columns store objects/arrays",
- "name": "jsonb_integrity",
- "status": "ok"
- },
- {
- "category": "brain",
- "message": "No takes yet",
- "name": "takes_weight_grid",
- "status": "ok"
- },
- {
- "category": "brain",
- "message": "All FK-child tables clean (10 tables checked)",
- "name": "child_table_orphans",
- "status": "ok"
- },
- {
- "category": "brain",
- "message": "All synthesized pages carry a raw trace or explicit exemption",
- "name": "raw_provenance",
- "status": "ok"
- },
- {
- "category": "brain",
- "message": "All source config values are JSON objects",
- "name": "source_config_shape",
- "status": "ok"
- },
- {
- "category": "skill",
- "message": "whoknows eval fixture present (10 queries). Run `gbrain eval whoknows test/fixtures/whoknows-eval.jsonl` to grade.",
- "name": "whoknows_health",
- "status": "ok"
- },
- {
- "category": "brain",
- "message": "All image-asset chunks have modality=image",
- "name": "cross_modal_modality_backfill",
- "status": "ok"
- },
- {
- "category": "brain",
- "message": "search.unified_multimodal is off; coverage check N/A",
- "name": "unified_multimodal_coverage",
- "status": "ok"
- },
- {
- "category": "brain",
- "message": "No truncated bodies detected",
- "name": "markdown_body_completeness",
- "status": "ok"
- },
- {
- "category": "brain",
- "message": "No pages exceed 500000 bytes (excluding embed_skip pages, which already took the accepted non-embeddable remediation)",
- "name": "oversized_pages",
- "status": "ok"
- },
- {
- "category": "brain",
- "message": "No junk-pattern hits in 5 recent page(s) (use --content-audit for full scan)",
- "name": "scraper_junk_pages",
- "status": "ok"
- },
- {
- "category": "brain",
- "message": "No content-sanity events in last 7 days (audit JSONL is local to this host; share GBRAIN_AUDIT_DIR for multi-host visibility)",
- "name": "content_sanity_audit_recent",
- "status": "ok"
- },
- {
- "category": "brain",
- "message": "No quarantined pages",
- "name": "quarantined_pages",
- "status": "ok"
- },
- {
- "category": "brain",
- "message": "No flagged pages",
- "name": "flagged_pages",
- "status": "ok"
- },
- {
- "category": "brain",
- "details": {
- "count": 0,
- "days": 7,
- "source_id": null
- },
- "message": "No stale unverified extraction stubs",
- "name": "unverified_extractions",
- "status": "ok"
- },
- {
- "category": "brain",
- "fix": {
- "actor": "agent",
- "argv": [
- "gbrain",
- "repair",
- "frontmatter",
- "--source",
- "notes",
- "--brain",
- "host"
- ],
- "command": "gbrain repair frontmatter --source notes --brain host",
- "consent": [],
- "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/repair.md#frontmatter",
- "next": "run",
- "requires_exclusive": false,
- "verify": {
- "argv": [
- "gbrain",
- "doctor",
- "--only",
- "frontmatter_integrity",
- "--json",
- "--brain",
- "host"
- ]
- },
- "why": "Previews the line fix for each file the repair can fix and names the manual fix for the rest; it writes nothing."
- },
- "message": "1 frontmatter issue(s). notes: 1 (YAML_PARSE=1). Fix: gbrain repair frontmatter --source <id> previews the line fix for every file it can repair (and names the manual fix for the rest, such as a missing opening ---); on an unmanaged checkout gbrain frontmatter validate <source-path> --fix applies the same safe fixes",
- "name": "frontmatter_integrity",
- "status": "warn"
- },
- {
- "category": "brain",
- "details": {
- "docs": "docs/guides/repair.md#frontmatter",
- "partial": false,
- "repairable": 1,
- "source_ids": [
- "notes"
- ],
- "sources": [
- {
- "by_code": {
- "needs_interpretation": 1
- },
- "files": 1,
- "preview": "gbrain repair frontmatter --source notes",
- "sample_paths": [
- "notes/broken-frontmatter.md"
- ],
- "source_id": "notes",
- "status": "scanned"
- }
- ],
- "unscanned": []
- },
- "fix": {
- "actor": "agent",
- "argv": [
- "gbrain",
- "repair",
- "frontmatter",
- "--source",
- "notes",
- "--brain",
- "host"
- ],
- "command": "gbrain repair frontmatter --source notes --brain host",
- "consent": [],
- "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/repair.md#frontmatter",
- "next": "run",
- "requires_exclusive": false,
- "verify": {
- "argv": [
- "gbrain",
- "doctor",
- "--only",
- "frontmatter_repairable",
- "--json",
- "--brain",
- "host"
- ]
- },
- "why": "Previews the minimal line fix per file (safe quoting first; interpretations only with --include-ambiguous) and prints the hash-bound apply command; it writes nothing."
- },
- "message": "1 file(s) have frontmatter gbrain repair frontmatter can fix: notes: 1 (needs_interpretation=1). Preview with gbrain repair frontmatter --source notes (writes nothing; add --include-ambiguous for interpretations after the safe pass).",
- "name": "frontmatter_repairable",
- "status": "warn"
- },
- {
- "category": "meta",
- "message": "No capture failures in the last 24h",
- "name": "eval_capture",
- "status": "ok"
- },
- {
- "category": "brain",
- "message": "No probe runs in the last 7 days. Run `gbrain eval suspected-contradictions --query \"...\" --top-k 5` to populate.",
- "name": "contradictions",
- "status": "ok"
- },
- {
- "category": "brain",
- "message": "Automatic fact extraction not configured (keyless) — memory comes from agent-authored `## Facts` fences and the `remember` verb. One optional key enables automatic extraction (OpenAI or Anthropic).",
- "name": "facts_extraction_health",
- "status": "ok"
- },
- {
- "category": "brain",
- "message": "Sample of last 1000 pages clean (no fallback-with-parseable-fm-date, no future-dated, no pre-1990)",
- "name": "effective_date_health",
- "status": "ok"
- },
- {
- "category": "brain",
- "message": "Skipped (no pages have emotional_weight > 0; either fresh install or recompute hasn't run yet)",
- "name": "salience_health",
- "status": "ok"
- },
- {
- "category": "ops",
- "details": {
- "by_queue": {},
- "depth": 0,
- "engine": "pglite",
- "worker_alive": true
- },
- "message": "PGLite: no jobs waiting for a worker.",
- "name": "queue_health",
- "status": "ok"
- },
- {
- "category": "ops",
- "message": "Subagent tier resolves to default (claude-sonnet-4-6) — full tool-loop capability",
- "name": "subagent_capability",
- "status": "ok"
- },
- {
- "category": "brain",
- "message": "facts_health(default): 0 active, 0 today, 0 this week, 0 consolidated, top entities —",
- "name": "facts_health",
- "status": "ok"
- },
- {
- "category": "ops",
- "message": "Brain-wide maintenance jobs are finishing within their deadline.",
- "name": "global_maintenance_timeouts",
- "status": "ok"
- },
- {
- "category": "ops",
- "details": {
- "active_ids": [],
- "authorizable": {},
- "authorizable_total": 0,
- "docs": "docs/guides/repair.md#legacy-job-authority",
- "live": 0,
- "queued_spend": {
- "by_basis": {},
- "long_waiting": 0,
- "long_waiting_ids": []
- },
- "terminal_keyed": {},
- "terminal_keyed_total": 0,
- "unsupported": 0,
- "unsupported_ids": []
- },
- "message": "No queued job predates submission authority.",
- "name": "legacy_job_authority",
- "status": "ok"
- },
- {
- "category": "ops",
- "details": {
- "convertible_count": 0,
- "docs": "docs/mcp/ADMIN.md#legacy-token-grants",
- "legacy_shape_count": 0,
- "malformed": [],
- "mirror_window_ends": "2026-11-04"
- },
- "message": "Every active legacy token uses the unified grant columns. The permissions mirror for older gbrain binaries is kept until 2026-11-04.",
- "name": "legacy_token_grant_shape",
- "status": "ok"
- },
- {
- "category": "ops",
- "details": {
- "docs": "docs/mcp/ADMIN.md#legacy-token-grants",
- "drift": [],
- "mirror_window_ends": "2026-11-04"
- },
- "message": "No legacy token grant has drifted from its permissions mirror.",
- "name": "legacy_token_grant_drift",
- "status": "ok"
- },
- {
- "category": "ops",
- "details": {
- "docs": "docs/mcp/ADMIN.md#tokens-without-scopes",
- "null_scope_count": 0,
- "tokens": []
- },
- "message": "Every active legacy token has explicit scopes.",
- "name": "legacy_token_null_scope",
- "status": "ok"
- },
- {
- "category": "ops",
- "details": {
- "docs": "docs/mcp/ADMIN.md#grants-that-cannot-reach-new-operations",
- "grants": [],
- "server_surface": "full"
- },
- "message": "Every active client and token can call the operations its scopes allow.",
- "name": "grant_new_ops_available",
- "status": "ok"
- },
- {
- "category": "brain",
- "message": "No image assets indexed yet",
- "name": "image_assets",
- "status": "ok"
- },
- {
- "category": "brain",
- "message": "OCR not in use (or no images ingested with OCR opt-in)",
- "name": "ocr_health",
- "status": "ok"
- },
- {
- "category": "brain",
- "details": {
- "stale_count": 1,
- "synced_recently_count": 0,
- "unchanged_count": 0,
- "writer_owned_count": 1
- },
- "fix_unavailable_reason": "unstructured",
- "message": "Source 'notes' has never been synced. Run `gbrain sync --source <id> --no-pull` for each stale source. 1 writer-owned canonical content source(s): upstream sync is not applicable; see canonical_content_writes for publication status",
- "name": "sync_freshness",
- "status": "fail"
- },
- {
- "category": "ops",
- "details": {
- "pending_count": 0,
- "recovering_count": 0,
- "writer_owned_count": 1
- },
- "message": "1 writer-owned content source(s); no pending canonical publication or recovery.",
- "name": "canonical_content_writes",
- "status": "ok"
- },
- {
- "category": "ops",
- "details": {
- "cache_age": "under an hour ago",
- "checked_at": "<ts>",
- "computed_by": "doctor",
- "degraded": false,
- "recovery_scope": "Git evidence covers committed repository files only; not a full database backup. DB-only pages, facts, configuration and credentials need a separate backup and restore drill.",
- "totals": {
- "assets": 2,
- "configured_repos": 0,
- "failing": 0,
- "no_remote": 1,
- "pages_at_risk": 0,
- "recoverable_repos": 0,
- "unpushed": 0
- }
- },
- "fix": {
- "actor": "agent",
- "argv": [
- "gbrain",
- "export",
- "--source",
- "default",
- "--dir",
- "<BACKUP_DIR>/default",
- "--brain",
- "host"
- ],
- "command": "gbrain export --source default --dir '<BACKUP_DIR>/default' --brain host",
- "consent": [],
- "docs": "https://github.com/garrytan/gbrain/blob/master/docs/operations/backup-check.md",
- "inputs": [
- {
- "how": "Ask the user where backups should live (a directory outside the brain, ideally synced or on another disk).",
- "name": "BACKUP_DIR"
- }
- ],
- "next": "run",
- "requires_exclusive": false,
- "verify": {
- "argv": [
- "gbrain",
- "doctor",
- "--only",
- "backup_coverage",
- "--json",
- "--brain",
- "host"
- ]
- },
- "why": "Writes a Markdown copy of 'default' (pages and facts) to a directory outside the brain so it survives losing the database."
- },
- "message": "Not urgent yet: the brain holds 5 page(s)+fact(s) and is under 7 days old (backup coaching starts at 25 items or 7 days). 2 knowledge asset(s) lack verified recovery: default (not_a_git_repo), notes (no git remote). A source repo with a pushed git remote restores its Markdown files only, never DB-only pages, facts, config or credentials. Run `gbrain backup status` for each asset's fix command.",
- "name": "backup_coverage",
- "readiness_state": "degraded",
- "severity": "info",
- "status": "ok"
- },
- {
- "category": "ops",
- "message": "2 active sources on a managed brain. Recommended cron on the owner host, every 15 minutes: `gbrain sync --all --no-pull --hard-deadline 13m`. Managed sync never pulls: for each checkout that tracks a remote, chain `gbrain sources refresh <id>;` in front of it to take upstream commits. Keep the deadline under the interval: managed sync takes no per-source lock, so a tick that outlives the interval would overlap the next one.",
- "name": "sync_consolidation",
- "status": "ok"
- },
- {
- "category": "brain",
- "message": "Extraction lag not applicable (5 pages — too few to assess)",
- "name": "links_extraction_lag",
- "status": "ok"
- },
- {
- "category": "brain",
- "message": "No full cycle yet for 'default', 'notes': they hold no pages or only pages from the last 24h, so there is nothing to consolidate yet.",
- "name": "cycle_freshness",
- "readiness_state": "not_applicable",
- "severity": "info",
- "status": "ok"
- },
- {
- "category": "brain",
- "message": "No same-source content-hash duplicate groups",
- "name": "content_hash_duplicates",
- "status": "ok"
- },
- {
- "category": "brain",
- "message": "All code-page chunks carry symbol metadata",
- "name": "code_chunk_metadata",
- "status": "ok"
- },
- {
- "category": "brain",
- "message": "Every DB page is file-backed or under a declared/default db_only path (derive-phase defaults: life/events/ atoms/ concepts/ extracts/ dream-cycle-summaries/).",
- "name": "undeclared_db_only_pages",
- "status": "ok"
- },
- {
- "category": "ops",
- "message": "No configured collectors declare output paths",
- "name": "db_only_collector_collision",
- "status": "ok"
- },
- {
- "category": "ops",
- "message": "System One is off (every decide slot is off; nothing is sent).",
- "name": "decide_health",
- "status": "ok"
- },
- {
- "category": "brain",
- "details": {
- "fix": "preview links: gbrain facts relink --dry-run",
- "inferred_7d": {
- "mention": 0,
- "page": 0
- },
- "new_7d": {
- "facts": 0,
- "no_subject": 0,
- "unlinked": 0
- },
- "no_subject": 0,
- "origins": [],
- "relinked_7d": {},
- "sources": 2,
- "window": {
- "active": 0,
- "capped": false,
- "fence_owned": 0,
- "unlinked": 0
- }
- },
- "message": "No active facts yet; nothing to link.",
- "name": "unlinked_facts",
- "status": "ok"
- },
- {
- "category": "brain",
- "details": {
- "contradiction_mode": "propose (default)",
- "lagging": 0,
- "proposals": {
- "applied": 0,
- "proposed": 0,
- "undated": 0
- },
- "read_policy": "on",
- "relationships": {},
- "stale_assertions": []
- },
- "message": "relationships: none yet; read policy on; contradiction mode propose (default)",
- "name": "edge_validity",
- "status": "ok"
- },
- {
- "category": "brain",
- "details": {
- "auto_calls_24h": 0,
- "chat_available": false,
- "daily_limit": 200,
- "docs": "docs/guides/life-chronicle.md",
- "enabled": true,
- "job_budget_usd": 0.25,
- "last_7d": {
- "extracted": 0,
- "failed": 0,
- "failedReasons": {},
- "reasons": {},
- "skipped": 0
- },
- "ledger_available": true,
- "pending": 0,
- "principals_24h": [],
- "readiness": "missing",
- "run_now": [
- "gbrain",
- "dream",
- "--phase",
- "chronicle"
- ],
- "severity": "info",
- "source": "default",
- "spend_7d": {
- "incompleteRecords": 0,
- "knownUsd": 0,
- "unpricedCalls": 0
- }
- },
- "message": "auto_chronicle is on (default). Last 24 h: 0 of 200 automatic extraction calls. Last 7 days: 0 extracted, 0 failed, 0 skipped; $0.00 known spend. 0 page(s) pending. No chat provider is configured, so nothing will be extracted until one is.",
- "name": "auto_chronicle",
- "readiness_state": "missing",
- "status": "ok"
- },
- {
- "category": "brain",
- "message": "chronicle.* settings are valid.",
- "name": "chronicle_config_invalid",
- "status": "ok"
- },
- {
- "category": "brain",
- "details": {
- "ask_user": true,
- "code": "auto_chronicle_default_on",
- "decisions": [
- {
- "argv": [
- "gbrain",
- "config",
- "set",
- "auto_chronicle",
- "true"
- ],
- "fix": {
- "actor": "agent",
- "argv": [
- "gbrain",
- "config",
- "set",
- "auto_chronicle",
- "true"
- ],
- "consent": [
- "paid",
- "egress"
- ],
- "requires_exclusive": false,
- "user_message": "Automatic event extraction is on: each new or changed meeting, conversation or calendar page gets one paid chat call. Keep it on, or turn it off?",
- "verify": {
- "argv": [
- "gbrain",
- "doctor",
- "--only",
- "auto_chronicle_default_on",
- "--json"
- ]
- },
- "why": "Keeping automatic extraction records that the user accepted one paid chat call per eligible page; page text goes to the chat provider."
- },
- "id": "keep",
- "label": "Keep automatic extraction on"
- },
- {
- "argv": [
- "gbrain",
- "config",
- "set",
- "auto_chronicle",
- "false"
- ],
- "fix": {
- "actor": "agent",
- "argv": [
- "gbrain",
- "config",
- "set",
- "auto_chronicle",
- "false"
- ],
- "consent": [],
- "requires_exclusive": false,
- "verify": {
- "argv": [
- "gbrain",
- "doctor",
- "--only",
- "auto_chronicle_default_on",
- "--json"
- ]
- },
- "why": "Turns automatic extraction off; history stays available on request with chronicle-backfill."
- },
- "id": "opt_out",
- "label": "Turn automatic extraction off"
- }
- ],
- "default": "keep",
- "docs": "docs/guides/life-chronicle.md",
- "fix": {
- "actor": "agent",
- "argv": [
- "gbrain",
- "config",
- "set",
- "auto_chronicle",
- "true"
- ],
- "consent": [
- "paid",
- "egress"
- ],
- "requires_exclusive": false,
- "user_message": "Automatic event extraction is on: each new or changed meeting, conversation or calendar page gets one paid chat call. Keep it on, or turn it off?",
- "verify": {
- "argv": [
- "gbrain",
- "doctor",
- "--only",
- "auto_chronicle_default_on",
- "--json"
- ]
- },
- "why": "Keeping automatic extraction records that the user accepted one paid chat call per eligible page; page text goes to the chat provider."
- },
- "severity": "info"
- },
- "fix": {
- "actor": "agent",
- "argv": [
- "gbrain",
- "config",
- "set",
- "auto_chronicle",
- "true",
- "--brain",
- "host"
- ],
- "command": "gbrain config set auto_chronicle true --brain host",
- "consent": [
- "paid",
- "egress"
- ],
- "next": "ask_user",
- "requires_exclusive": false,
- "user_message": "Automatic event extraction is on: each new or changed meeting, conversation or calendar page gets one paid chat call. Keep it on, or turn it off?",
- "verify": {
- "argv": [
- "gbrain",
- "doctor",
- "--only",
- "auto_chronicle_default_on",
- "--json",
- "--brain",
- "host"
- ]
- },
- "why": "Keeping automatic extraction records that the user accepted one paid chat call per eligible page; page text goes to the chat provider."
- },
- "message": "Automatic event extraction is on by default and the user has not confirmed it yet. Each eligible new or changed meeting, conversation or calendar page gets one paid chat call (cap $0.25 per page; at most 200 calls per day, so at most $50.00 per day for a priced model; an unpriced model has no cap), and page text goes to the configured chat provider. Relay this to the user, then run `gbrain config set auto_chronicle true` to keep it or `gbrain config set auto_chronicle false` to opt out.",
- "name": "auto_chronicle_default_on",
- "readiness_state": "ok",
- "severity": "info",
- "status": "ok"
- },
- {
- "category": "brain",
- "details": {
- "backlog": {
- "active": 0,
- "delayed": 0,
- "waiting": 0
- },
- "budget_usd": 1,
- "daily_budget_usd": 5,
- "daily_spent_usd": 0,
- "docs": "docs/guides/facts-drain.md",
- "enabled": true,
- "health": "idle",
- "last_run": null,
- "max_jobs": 50
- },
- "message": "No facts-absorb jobs are queued (no run recorded yet).",
- "name": "facts_drain",
- "status": "ok"
- },
- {
- "category": "brain",
- "details": {
- "applicable": false
- },
- "message": "Not applicable: embeddings are disabled on this brain (keyword search keeps working).",
- "name": "fact_take_vectors",
- "readiness_state": "disabled_by_choice",
- "severity": "info",
- "status": "ok"
- },
- {
- "category": "ops",
- "details": {
- "auto_analyze": true,
- "checked": [
- "pages",
- "links",
- "facts",
- "takes",
- "content_chunks",
- "timeline_entries"
- ],
- "engine": "pglite",
- "fix": "gbrain repair planner-stats --apply",
- "stale": []
- },
- "message": "Planner statistics are fresh on 6 hot tables.",
- "name": "planner_stats_stale",
- "status": "ok"
- },
- {
- "category": "meta",
- "details": {
- "answers_recorded": 0,
- "docs": "docs/guides/retrieval-feedback.md",
- "enabled": false,
- "implicit": false,
- "influence": 0.1,
- "last_rating_at": null,
- "learn": true,
- "ratings_cited": 0,
- "ratings_explicit": 0,
- "top_client_share_7d": null,
- "weights": 0,
- "weights_off_neutral": 0
- },
- "message": "Retrieval feedback is off; rankings do not learn from ratings. Turn it on with: gbrain config set feedback.enabled true",
- "name": "retrieval_feedback_health",
- "status": "ok"
- },
- {
- "category": "meta",
- "details": {
- "column": "not_null",
- "failed": [],
- "pending": 0
- },
- "message": "Every page has its revision; the page revision backfill is complete.",
- "name": "revision_backfill",
- "status": "ok"
- },
- {
- "category": "brain",
- "details": {
- "bad_config": [],
- "chars_limit": 4000,
- "chars_used": 0,
- "compiled": [],
- "docs": "docs/guides/core-memory.md",
- "enabled": false,
- "pages": 0
- },
- "message": "Core memory is off (opt-in). If the user wants a profile loaded in every session: gbrain config set memory.core.enabled true, then gbrain core init.",
- "name": "core_memory",
- "status": "ok"
- },
- {
- "category": "ops",
- "details": {
- "count": 0,
- "docs": "docs/guides/troubleshooting.md#managed-sync-not-moving",
- "parked": 0,
- "sources": []
- },
- "message": "No managed sync is pending.",
- "name": "managed_sync_not_moving",
- "status": "ok"
- },
- {
- "category": "ops",
- "details": {
- "consumers": [],
- "count": 0,
- "docs": "docs/guides/troubleshooting.md#two-consumers-on-host"
- },
- "message": "PGLite admits one process; no consumer heartbeat rows are kept.",
- "name": "two_consumers_on_host",
- "status": "ok"
- },
- {
- "category": "ops",
- "details": {
- "count": 0,
- "docs": "docs/guides/troubleshooting.md#two-consumers-on-host",
- "owners": []
- },
- "message": "PGLite admits one process; no consumer heartbeat rows are kept.",
- "name": "consumers_without_heartbeat",
- "status": "ok"
- },
- {
- "category": "ops",
- "details": {
- "count": 0,
- "docs": "docs/guides/troubleshooting.md#host-identity-mismatch",
- "host_id": "<uuid>",
- "host_json_path": "<home>/.gbrain/persistence/host.json",
- "mismatches": []
- },
- "message": "This process's host identity (<home>/.gbrain/persistence/host.json) owns every binding this filesystem holds.",
- "name": "host_identity_mismatch",
- "status": "ok"
- },
- {
- "category": "brain",
- "details": {
- "docs": "docs/guides/write-refusals.md#invalid_fence",
- "model_repair": {
- "max_usd_per_day": 1,
- "max_usd_per_page": 0.3,
- "reserved_today_usd": 0,
- "spent_today_usd": 0
- },
- "partial": false,
- "partial_sources": [],
- "sources": [
- {
- "by_tier": {
- "deterministic": 0,
- "llm": 0,
- "manual": 0,
- "resolver": 0,
- "total": 0
- },
- "files": {
- "deterministic": 0,
- "llm": 0,
- "manual": 0,
- "resolver": 0,
- "total": 0
- },
- "holds": {
- "deterministic": 0,
- "llm": 0,
- "manual": 0,
- "resolver": 0,
- "total": 0
- },
- "oldest_hold_at": null,
- "pages": {
- "deterministic": 0,
- "llm": 0,
- "manual": 0,
- "resolver": 0,
- "total": 0
- },
- "sample": [],
- "scan": {
- "backfill_done": true,
- "checked_at": "<ts>",
- "complete": true,
- "fresh_at": "<ts>",
- "walking": false
- },
- "source_id": "default",
- "total": 0
- },
- {
- "by_tier": {
- "deterministic": 0,
- "llm": 0,
- "manual": 0,
- "resolver": 0,
- "total": 0
- },
- "files": {
- "deterministic": 0,
- "llm": 0,
- "manual": 0,
- "resolver": 0,
- "total": 0
- },
- "holds": {
- "deterministic": 0,
- "llm": 0,
- "manual": 0,
- "resolver": 0,
- "total": 0
- },
- "oldest_hold_at": null,
- "pages": {
- "deterministic": 0,
- "llm": 0,
- "manual": 0,
- "resolver": 0,
- "total": 0
- },
- "sample": [],
- "scan": {
- "backfill_done": true,
- "checked_at": "<ts>",
- "complete": true,
- "fresh_at": "<ts>",
- "walking": false
- },
- "source_id": "notes",
- "total": 0
- }
- ],
- "timeout_ms": "<volatile>",
- "total": 0,
- "trend": [
- {
- "by_day": [],
- "normalized_7d": 0,
- "source_id": "default",
- "top_writers": []
- },
- {
- "by_day": [],
- "normalized_7d": 0,
- "source_id": "notes",
- "top_writers": []
- }
- ],
- "uncommitted_repairs": 0,
- "unrenderable_legacy_facts": {
- "complete": true,
- "pages": [],
- "total": 0
- },
- "warn_at_normalized_7d": 20
- },
- "message": "No malformed facts or takes fence is held, stored or waiting in a checkout (2 source(s) scanned).",
- "name": "fence_integrity",
- "status": "ok"
- },
- {
- "category": "ops",
- "message": "Mode: conservative (no per-key overrides — mode bundle is canonical).",
- "name": "search_mode",
- "status": "ok"
- },
- {
- "category": "brain",
- "details": {
- "counts": {},
- "prefixes": [
- "test/",
- "attachments/",
- ".raw/"
- ]
- },
- "message": "No pages hidden by search-exclude policy.",
- "name": "hidden_by_search_policy",
- "status": "ok"
- },
- {
- "category": "brain",
- "message": "No retrieval-affecting files changed in working tree.",
- "name": "eval_drift",
- "status": "ok"
- },
- {
- "category": "ops",
- "message": "Reranker disabled — no failures expected",
- "name": "reranker_health",
- "status": "ok"
- },
- {
- "category": "ops",
- "message": "No exhausted batch retries in last 24h.",
- "name": "batch_retry_health",
- "status": "ok"
- },
- {
- "category": "ops",
- "message": "PGLite — no queue to check",
- "name": "wedged_queue",
- "status": "ok"
- },
- {
- "category": "ops",
- "message": "No orphaned private queues",
- "name": "orphaned_private_queue",
- "status": "ok"
- },
- {
- "category": "ops",
- "message": "PGLite — single-writer, fan-out is 1",
- "name": "autopilot_fanout_concurrency",
- "status": "ok"
- },
- {
- "category": "ops",
- "message": "no Google accounts connected (gbrain google connect to start)",
- "name": "google_oauth",
- "status": "ok"
- },
- {
- "category": "brain",
- "message": "graph_signals disabled — coverage not checked",
- "name": "graph_signals_coverage",
- "status": "ok"
- },
- {
- "category": "brain",
- "message": "No junk entity hubs (pages with <=2 chunks and >1000 edges)",
- "name": "junk_entity_hubs",
- "status": "ok"
- },
- {
- "category": "ops",
- "message": "Migration v79 applied; tracking enabled. Calibration profile not yet generated — brainstorm/lsd will run unbiased until enough takes are resolved.",
- "name": "brainstorm_health",
- "status": "ok"
- },
- {
- "category": "brain",
- "fix_unavailable_reason": "unstructured",
- "message": "6 of 8 bare wikilinks (75%) would resolve to 2 distinct page(s) under global_basename mode. Enable with: gbrain config set link_resolution.global_basename true",
- "name": "link_resolution_opportunity",
- "status": "warn"
- },
- {
- "category": "brain",
- "message": "Embeddings disabled — no active embedding width to reconcile.",
- "name": "embedding_width_consistency",
- "status": "ok"
- },
- {
- "category": "brain",
- "message": "Skipped on PGLite (single bundled pgvector version).",
- "name": "facts_embedding_width_consistency",
- "status": "ok"
- },
- {
- "category": "brain",
- "message": "Multi-source brain (1 non-default source(s)); all populated",
- "name": "source_routing_health",
- "status": "ok"
- },
- {
- "category": "ops",
- "message": "No OAuth clients registered",
- "name": "oauth_confidential_client_health",
- "status": "ok"
- },
- {
- "category": "ops",
- "message": "Scoped-client grants consistent (no dangling federated reads, no orphaned workspace sources, no privileged self-registered clients)",
- "name": "oauth_client_scope_health",
- "status": "ok"
- },
- {
- "category": "ops",
- "message": "Lock path: <home>/.gbrain/autopilot.lock",
- "name": "autopilot_lock_scope",
- "status": "ok"
- },
- {
- "category": "ops",
- "message": "No stale locks (no rows with ttl_expires_at < NOW())",
- "name": "stale_locks",
- "status": "ok"
- },
- {
- "category": "meta",
- "details": {
- "counts": {
- "global": 13,
- "mixed": 2,
- "source": 12
- },
- "phase_scope_map": {
- "backlinks": "source",
- "calibration_profile": "global",
- "chronicle": "global",
- "consolidate": "source",
- "conversation_facts_backfill": "source",
- "drift": "global",
- "edge_contradictions": "global",
- "embed": "global",
- "enrich_thin": "source",
- "extract": "source",
- "extract_atoms": "source",
- "extract_facts": "source",
- "facts_drain": "global",
- "fence_repair": "global",
- "grade_takes": "global",
- "lint": "source",
- "orphans": "global",
- "patterns": "mixed",
- "propose_takes": "source",
- "purge": "global",
- "recompute_emotional_weight": "source",
- "resolve_symbol_edges": "global",
- "schema-suggest": "source",
- "skillopt": "global",
- "sync": "source",
- "synthesize": "mixed",
- "synthesize_concepts": "global"
- }
- },
- "message": "Phase taxonomy: 12 source-scoped, 13 brain-global, 2 mixed. Source-safe: [lint, backlinks, sync, extract, extract_facts, extract_atoms, recompute_emotional_weight, consolidate, propose_takes, conversation_facts_backfill, enrich_thin, schema-suggest]. Brain-global: [fence_repair, resolve_symbol_edges, synthesize_concepts, grade_takes, calibration_profile, edge_contradictions, drift, chronicle, facts_drain, skillopt, embed, orphans, purge]. Mixed: [synthesize, patterns].",
- "name": "cycle_phase_scope",
- "status": "ok"
- },
- {
- "category": "brain",
- "fix": {
- "actor": "user",
- "argv": [
- "gbrain",
- "init",
- "--force",
- "--embedding-model",
- "voyage:voyage-4",
- "--embedding-dimensions",
- "1024",
- "--path",
- "<home>/.gbrain/brain.pglite"
- ],
- "command": "gbrain init --force --embedding-model voyage:voyage-4 --embedding-dimensions 1024 --path <home>/.gbrain/brain.pglite",
- "consent": [
- "credentials",
- "paid"
- ],
- "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/search-modes.md",
- "inputs": [
- {
- "how": "Ask the user for an API key for Voyage AI; store it with `gbrain config set voyage_api_key <key>` (every gbrain process reads it), or export VOYAGE_API_KEY in the environment of every gbrain process. Then run the command.",
- "name": "VOYAGE_API_KEY"
- }
- ],
- "next": "tell_user_to_run",
- "requires_exclusive": true,
- "user_message": "Semantic search needs an embedding API key. Voyage AI works with this brain; if you add a key (VOYAGE_API_KEY), I can turn it on. Embedding costs a little per page; your notes and facts stay as they are.",
- "verify": {
- "argv": [
- "gbrain",
- "doctor",
- "--only",
- "embeddings",
- "--json",
- "--brain",
- "host"
- ]
- },
- "why": "Embeddings are off, so search is keyword-only, and no configured embedding key fits this brain. Once the key is set this turns on voyage:voyage-4 (1024d) for the PGLite brain at <home>/.gbrain/brain.pglite. Pages, facts and keyword search are kept; existing chunks and facts are queued for vectors, which `gbrain embed --stale` (or the next maintenance cycle) fills."
- },
- "message": "Not applicable: embeddings are disabled on this brain by choice, so chunks have no vectors by design (keyword search keeps working).",
- "name": "embed_staleness",
- "readiness_state": "disabled_by_choice",
- "severity": "info",
- "status": "ok"
- },
- {
- "category": "brain",
- "message": "Only 2 entity pages (< 5) — coverage ratio not meaningful at this scale",
- "name": "entity_link_coverage",
- "status": "ok"
- },
- {
- "category": "brain",
- "message": "Only 2 entity pages (< 5) — coverage ratio not meaningful at this scale",
- "name": "timeline_coverage",
- "status": "ok"
- },
- {
- "category": "brain",
- "fix": {
- "actor": "agent",
- "argv": [
- "gbrain",
- "config",
- "set",
- "takes.bootstrap_enabled",
- "true",
- "--brain",
- "host"
- ],
- "command": "gbrain config set takes.bootstrap_enabled true --brain host",
- "consent": [
- "paid"
- ],
- "next": "ask_user",
- "requires_exclusive": false,
- "user_message": "gbrain can extract typed claims (\"takes\") from your pages so it can track calibration over time. It uses a paid chat model (roughly $5 once). Turn it on?",
- "verify": {
- "argv": [
- "gbrain",
- "doctor",
- "--only",
- "takes_count",
- "--json",
- "--brain",
- "host"
- ]
- },
- "why": "Takes (typed claims) are opt-in. Enabling the bootstrap lets maintenance extract them from existing pages with a chat model (about $5 on a typical brain), which feeds calibration."
- },
- "message": "0 takes (takes.bootstrap_enabled is false; opt in to enable)",
- "name": "takes_count",
- "readiness_state": "disabled_by_choice",
- "severity": "info",
- "status": "ok"
- },
- {
- "category": "meta",
- "message": "Active pack [email protected]+a50a67b9 is current (no successor declared)",
- "name": "pack_upgrade_available",
- "status": "ok"
- },
- {
- "category": "meta",
- "message": "3 distinct typed values (pack declares 20)",
- "name": "type_proliferation",
- "status": "ok"
- },
- {
- "category": "brain",
- "message": "No dangling aliases",
- "name": "dangling_aliases",
- "status": "ok"
- }
- ],
- "db_url_source": null,
- "engine": "pglite",
- "health_score": 55,
- "schema_version": 2,
- "status": "unhealthy",
- "top_issues": [
- {
- "fix": "Source 'notes' has never been synced. Run `gbrain sync --source <id> --no-pull` for each stale source. 1 writer-owned canonical content source(s): upstream sync is not applicable; see canonical_content_writes for publication status",
- "name": "sync_freshness",
- "status": "fail",
- "tier": "root"
- },
- {
- "action": {
- "actor": "agent",
- "argv": [
- "gbrain",
- "doctor",
- "--remediation-plan",
- "--json",
- "--brain",
- "host"
- ],
- "command": "gbrain doctor --remediation-plan --json --brain host",
- "consent": [],
- "next": "run",
- "requires_exclusive": false,
- "verify": {
- "argv": [
- "gbrain",
- "doctor",
- "--only",
- "brain_score",
- "--json",
- "--brain",
- "host"
- ]
- },
- "why": "The plan lists which steps raise each score component, what they cost and the reachable maximum; it changes nothing."
- },
- "fix": "Brain score 36/100 (embed 0/35, links 5/25, timeline density (entity and event pages) 15/15, orphans 6/15, dead-links 10/10)",
- "name": "brain_score",
- "status": "warn",
- "tier": "symptom"
- },
- {
- "action": {
- "actor": "agent",
- "argv": [
- "gbrain",
- "repair",
- "frontmatter",
- "--source",
- "notes",
- "--brain",
- "host"
- ],
- "command": "gbrain repair frontmatter --source notes --brain host",
- "consent": [],
- "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/repair.md#frontmatter",
- "next": "run",
- "requires_exclusive": false,
- "verify": {
- "argv": [
- "gbrain",
- "doctor",
- "--only",
- "frontmatter_integrity",
- "--json",
- "--brain",
- "host"
- ]
- },
- "why": "Previews the line fix for each file the repair can fix and names the manual fix for the rest; it writes nothing."
- },
- "fix": "1 frontmatter issue(s). notes: 1 (YAML_PARSE=1). Fix: gbrain repair frontmatter --source <id> previews the line fix for every file it can repair (and names the manual fix for the rest, such as a missing opening ---); on an unmanaged checkout gbrain frontmatter validate <source-path> --fix applies the same safe fixes",
- "name": "frontmatter_integrity",
- "status": "warn",
- "tier": "symptom"
- },
- {
- "action": {
- "actor": "agent",
- "argv": [
- "gbrain",
- "repair",
- "frontmatter",
- "--source",
- "notes",
- "--brain",
- "host"
- ],
- "command": "gbrain repair frontmatter --source notes --brain host",
- "consent": [],
- "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/repair.md#frontmatter",
- "next": "run",
- "requires_exclusive": false,
- "verify": {
- "argv": [
- "gbrain",
- "doctor",
- "--only",
- "frontmatter_repairable",
- "--json",
- "--brain",
- "host"
- ]
- },
- "why": "Previews the minimal line fix per file (safe quoting first; interpretations only with --include-ambiguous) and prints the hash-bound apply command; it writes nothing."
- },
- "fix": "1 file(s) have frontmatter gbrain repair frontmatter can fix: notes: 1 (needs_interpretation=1). Preview with gbrain repair frontmatter --source notes (writes nothing; add --include-ambiguous for interpretations after the safe pass).",
- "name": "frontmatter_repairable",
- "status": "warn",
- "tier": "symptom"
- },
- {
- "fix": "6 of 8 bare wikilinks (75%) would resolve to 2 distinct page(s) under global_basename mode. Enable with: gbrain config set link_resolution.global_basename true",
- "name": "link_resolution_opportunity",
- "status": "warn",
- "tier": "symptom"
- },
- {
- "fix": "64 new built-in skill(s) available that this workspace hasn't installed: academic-verify, archive-crawler, article-enrichment, ask-user, blog-ingest, book-mirror, brain-ingest-gate, brain-link-discipline, … +56 more. Add them with `gbrain skillpack sync`.",
- "name": "skill_currency",
- "status": "warn",
- "tier": "symptom"
- }
- ]
- },
- "stderr": [
- "[backup] checked 2 asset(s): 1 without a git remote (computed_by=doctor)"
- ],
- "stdout": "<json>"
- },
- "normalizer": "doctor-json-v1"
-}