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-attack5d5841bcbe0b
diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.md
index 90d395b23c..8c32651d5e 100644
--- a/docs/architecture/key-files/commands-2.md
+++ b/docs/architecture/key-files/commands-2.md
@@ -40,7 +40,7 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve
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`.
-- `src/commands/doctor/registry.ts` + `src/commands/doctor/context.ts` — the doctor check registry (refactor wave 1, W4 doctor). `DOCTOR_CHECK_REGISTRY` lists 67 `DoctorEntry` records `{ name, emits, run(ctx) -> Promise<Check[] | STOP_DOCTOR> }` in output order; `runDoctorRegistry(ctx)` runs them, returns the checks gathered so far on `STOP_DOCTOR`, and otherwise finishes the DB-checks progress phase. Execution groups: filesystem-first entries (the resolver-health entry applies `--fix` before it scans), the no-engine connection lane plus a STOP when `--fast` or no engine, the live connection entry plus a STOP when `getStats` failed, then the DB entries, which take the engine via `connectedEngine(ctx)`. `DoctorContext` carries the parsed flags (`jsonOutput`, `fastMode`, `doFix`, `dryRun`, `scope`, `orphanRatioSourceId`, `args`), `engine`, `dbSource`, `connectError`, `progress`, the skills-dir resolution and the cross-entry values `autoFixReport`, `schemaVersion`, `connectionFailed`, each written by the entry that computes it. Entry modules (one `run*` function per former `buildChecks` block, moved verbatim): `checks/skill-group.ts`, `local-runtime.ts`, `supervisor-health.ts`, `local-audits.ts`, `db-connection.ts` (also `pgbouncerPrepareCheck`, `classifiedConnectionCheck` and the two STOP gates), `schema-health.ts`, `embedding-health.ts`, `graph-health.ts`, `data-integrity.ts`, `content-quality.ts`, `knowledge-health.ts`, `queue-assets.ts`, `sync-search.ts`; `checks/legacy-token-grants.ts` (F3) emits `legacy_token_grant_shape` (info: active tokens still on the JSONB-only grant shape, fix `gbrain auth rescope --migrate-legacy`) and `legacy_token_grant_drift` (warn: per-token drifted axes with the two adopt commands); `checks/grant-new-ops.ts` (D4) emits `grant_new_ops_available` (warn: active clients and tokens whose operation snapshot or stored surface keeps operations their scopes allow out of reach, with proven blockers apart from inferred grant age, per-grant names in details, and an ask_user fix whose rescope argv differs for tokens and clients; `--operations all` is a disclosed choice, never the fix); `checks/upgrade-health.ts` holds `checkUpgradeErrors` / `checkSelfUpgradeHealth` / `upgradeErrorResolved` (re-exported by the façade). To add a check: add an entry in the topic module, place it in `DOCTOR_CHECK_REGISTRY` where its output belongs, and categorize every emitted name in `src/core/doctor-categories.ts`. Tests: `test/doctor-registry.test.ts` (category contract with FAIL/Why/Fix/See, `emits[]` equals the AST walk, STOP positions), `test/doctor-mode-matrix.serial.test.ts` (entries run, STOP point, engine calls and `--fix` mutations per mode), and the W0 goldens `test/doctor-registry-golden.test.ts` (the AST walker follows `runDoctorRegistry` into the registry), `test/doctor-early-stop-golden.serial.test.ts`, `test/doctor-json-golden.test.ts`.
+- `src/commands/doctor/registry.ts` + `src/commands/doctor/context.ts` — the doctor check registry (refactor wave 1, W4 doctor). `DOCTOR_CHECK_REGISTRY` lists 67 `DoctorEntry` records `{ name, emits, run(ctx) -> Promise<Check[] | STOP_DOCTOR> }` in output order; `runDoctorRegistry(ctx)` runs them, returns the checks gathered so far on `STOP_DOCTOR`, and otherwise finishes the DB-checks progress phase. The run is one `withGitListingCache` scope (`src/core/git-visible-files.ts`), so entries that list the same source checkout (frontmatter scan, fence census, slug collisions) share one `git ls-files` per listing. Execution groups: filesystem-first entries (the resolver-health entry applies `--fix` before it scans), the no-engine connection lane plus a STOP when `--fast` or no engine, the live connection entry plus a STOP when `getStats` failed, then the DB entries, which take the engine via `connectedEngine(ctx)`. `DoctorContext` carries the parsed flags (`jsonOutput`, `fastMode`, `doFix`, `dryRun`, `scope`, `orphanRatioSourceId`, `args`), `engine`, `dbSource`, `connectError`, `progress`, the skills-dir resolution and the cross-entry values `autoFixReport`, `schemaVersion`, `connectionFailed`, each written by the entry that computes it. Entry modules (one `run*` function per former `buildChecks` block, moved verbatim): `checks/skill-group.ts`, `local-runtime.ts`, `supervisor-health.ts`, `local-audits.ts`, `db-connection.ts` (also `pgbouncerPrepareCheck`, `classifiedConnectionCheck` and the two STOP gates), `schema-health.ts`, `embedding-health.ts`, `graph-health.ts`, `data-integrity.ts`, `content-quality.ts`, `knowledge-health.ts`, `queue-assets.ts`, `sync-search.ts`; `checks/legacy-token-grants.ts` (F3) emits `legacy_token_grant_shape` (info: active tokens still on the JSONB-only grant shape, fix `gbrain auth rescope --migrate-legacy`) and `legacy_token_grant_drift` (warn: per-token drifted axes with the two adopt commands); `checks/grant-new-ops.ts` (D4) emits `grant_new_ops_available` (warn: active clients and tokens whose operation snapshot or stored surface keeps operations their scopes allow out of reach, with proven blockers apart from inferred grant age, per-grant names in details, and an ask_user fix whose rescope argv differs for tokens and clients; `--operations all` is a disclosed choice, never the fix); `checks/upgrade-health.ts` holds `checkUpgradeErrors` / `checkSelfUpgradeHealth` / `upgradeErrorResolved` (re-exported by the façade). To add a check: add an entry in the topic module, place it in `DOCTOR_CHECK_REGISTRY` where its output belongs, and categorize every emitted name in `src/core/doctor-categories.ts`. Tests: `test/doctor-registry.test.ts` (category contract with FAIL/Why/Fix/See, `emits[]` equals the AST walk, STOP positions), `test/doctor-mode-matrix.serial.test.ts` (entries run, STOP point, engine calls and `--fix` mutations per mode), and the W0 goldens `test/doctor-registry-golden.test.ts` (the AST walker follows `runDoctorRegistry` into the registry), `test/doctor-early-stop-golden.serial.test.ts`, `test/doctor-json-golden.test.ts`.
- `src/commands/doctor/checks/git-convergence.ts` — `git_convergence` (#5063, brain category, after `sync_freshness`): for every non-archived filesystem source root plus `sync.repo_path` (connector sources skipped), `git status --porcelain -z` and `rev-list --left-right --count @{u}...HEAD` against the local upstream ref, never a fetch, each call bounded at 5 s and at most 50 roots. Commits not on the upstream warn after 6 h and fail after 24 h (oldest unpushed commit time); uncommitted changes warn once the oldest changed file is older than 6 h; behind is reported, not judged. Emits nothing when no probed root has an upstream. `bootstrap-checks.ts` `bootstrap_push_health` also warns, instead of `ok`, when a recent successful push leaves the receipt workspace ahead of `origin/<branch>`. `scripts/smoke-test.sh` accepts a configured database URL (`engine status` `db_url_source`) and trusts doctor `embedding_provider` over raw OpenAI/Voyage keys. Tests: `doctor-git-convergence-5063.test.ts`, `bootstrap-doctor-checks.test.ts`, `smoke-test-worker.test.ts`.
- `src/commands/doctor/` — the doctor module directory (the meat behind the `doctor.ts` façade). `checks/` holds the check-function library in bundles grouped by concern (`core-health.ts`, `queue-jobs.ts`, `extraction-sync.ts` (its `sync_freshness` check excludes sources disabled by `isSyncDisabledConfig` and adds `--no-pull` to its sync hint on a managed brain; `content_hash_duplicates` prescribes `GBRAIN_SOURCE=<id> gbrain delete <bare-slug> --force` per wrong-root pair, naming each source when pairs span several, and never a hard purge; `cycle_freshness` in `consolidation-cycle.ts` still monitors their maintenance; its `atom_provenance_drift` check scopes drift to page-bound atoms and splits it into `source_changed` / `source_gone`; atoms with no `source_slug` — transcript-origin `source_path`-only rows, whose hash is over a file and whose page liveness cannot be resolved by slug — are reported as their own `slug_unbound` count and never enter the drift total or the WARN ratio), `graph-embedding.ts`, `search-eval.ts`, `calibration.ts`, `consolidation-cycle.ts`, `pglite-worker.ts`, `routing-federation.ts` (`source_routing_health` exempts zero-page skill-pack sources), `verbs-reflex.ts`, `stale-mentions.ts`, `timeline-history.ts` (`timeline_history`: database-only timeline rows, bounded to 2,000 pages / 10 s per run with a cursor kept in config `doctor.timeline_history.scan:<sources>` so successive runs finish a pass (a clean finished pass stays `ok` until a newer timeline row; `doctor-timeline-history-cursor-5821.test.ts`), exact-or-lower-bound counts, kept non-round-trippable rows informational, repair `gbrain repair timeline`), `derived-visibility.ts` (`derived_visibility`: atoms and synthesized concepts without explicit visibility or looser than their origin, one exact aggregate, repair `gbrain repair visibility`), `engine-fit.ts` — the last carrying `pglite_scale` + the engine-free `db_repair_recurrence` over the db-repair receipts); `schema-pack-checks.ts`, `report-remote.ts`, `bootstrap-checks.ts`, and `skill-checks.ts` are the four tail-cluster modules (schema-pack checks, the remote/thin-client doctor report, bootstrap checks, skill checks). `harness-hook-checks.ts` (`harnessHookCarrierChecks`, called from `bootstrap_harness_health`) reads each receipt-named Claude Code hook carrier read-only: an event wired more than once by this install warns `harness_hook_duplicates` with a consented re-run carrying the install's `--project`/`--no-capture` choices, a lookalike it did not write warns `harness_hook_unowned` (operator judgement), an unparseable carrier warns naming the file, and entries the host stripped of their marker are an `ok` info row; `plugin_lane_collision` iterates `enabledPluginLanes`. `multiSourceDriftCheck` is the one local/remote `multi_source_drift` verdict: on a managed brain (`managedPersistenceEnabled`) its sync advice names `--no-pull` and drops `--include-gitignored`, unmanaged wording is unchanged, and any skipped source keeps it warn/not_verified. `src/core/multi-source-drift.ts` derives a `git-root`-pinned source's slug prefix from its git toplevel (realpaths, empty at the repo root) and skips only a source whose toplevel cannot be resolved (`git_root_skipped`). `graph-health.ts` `graph_coverage`, like onboard's link and timeline coverage, is `ok` (not applicable, with the count) below `MIN_ENTITY_PAGES_FOR_COVERAGE` (5) eligible entity pages. All are re-exported by the façade. Structural guards that pin doctor source text load it through `test/helpers/doctor-source.ts`: `doctorSource()` concatenates the façade plus every `src/commands/doctor/**/*.ts` (façade first, then sorted) so a module move can never take a pinned string out of a guard's sight; `doctorFileSource(rel)` reads one named file for positional/ordering assertions; the helper also feeds the `doctor-source-helper` detector in `scripts/classify-tests.ts`. `facadeExpansion` in `scripts/generate-flag-registry.ts` keeps this directory on the doctor command's flag-scan surface. Two read-only derived-data checks live beside them: `timeline-orphans.ts` (`timeline_orphans`, samples 500 pages for rows an earlier page version produced that the current text no longer does; fix is `gbrain extract timeline --prune-orphans`) and `slug-collisions.ts` (`slug_collisions`, walks each live source checkout with `collectSyncableFiles` and reports paths that map to one slug plus the indexed one; sources without a checkout are skipped). `checks/graph-embedding.ts` `checkJunkEntityHubs` (#6158) splits connector contact pages (frontmatter `google_contact_id` or a connector source kind) into `details.connector_twins` with their main-brain `canonical_twin`, never calls them extractor-minted or offers `junk_hub_exempt`, and carries `fix_unavailable_reason: 'operator_judgement'` while the defer-to-twin policy is open.
diff --git a/docs/architecture/key-files/commands-4.md b/docs/architecture/key-files/commands-4.md
index fc4ad5c36a..2a1ec9d093 100644
--- a/docs/architecture/key-files/commands-4.md
+++ b/docs/architecture/key-files/commands-4.md
@@ -7,7 +7,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/graph-query.ts` — `gbrain graph-query <slug> [--type T] [--depth N] [--direction in|out|both] [--source <id>] [--include-foreign]`: typed-edge relationship traversal (renders indented tree). The local walk is scoped to the resolved source (`--source` / `GBRAIN_SOURCE` / `.gbrain-source` / path match / brain default via `resolveSourceId`, the same scalar scope the `traverse_graph` op gets from `sourceScopeOpts`); an explicit `--source` that fails to resolve throws. `--include-foreign` (or `--source __all__`) drops the scope so the walk spans every source. The foreign-edge footer (`N edges to foreign-source pages hidden; pass --include-foreign`) prints only when the walk was actually scoped, so cross-source edges never disappear silently and the footer never describes a filter that did not apply. The local path uses `engine.traversePathsDetailed` and prints a stderr note when the walk hit `TRAVERSE_PATH_ROW_CAP` (shallowest edges kept; lower `--depth` or narrow with `--type`/`--direction`); the thin-client path goes through the `traverse_graph` op, which has no `source_id` param (the server scopes the walk to the caller's grant): an explicit `--source` there is rejected with exit 1 (same policy + wording as `applyThinClientSourceScope`, never silently dropped) and `--include-foreign` prints a stderr note that it is not forwarded. `--hop <link_type>:<object|subject>` (repeatable, 1-3) runs a typed chain through `runRelationalChain` locally or `traverse_graph` `hops` on a thin client; it is refused with `--type`/`--depth`/`--direction`, a malformed hop names the fix, and a host that ignored `hops` (older gbrain, detected via `ignoredRemoteParams` or a non-chain response) is refused with the upgrade message. Pinned by `test/graph-query.test.ts` (local) + `test/graph-query-thin-client-source-flag.serial.test.ts` (thin client; mocks `isThinClient` + `callRemoteTool`).
-- `src/commands/import.ts` — `gbrain import <path> [--source-id <id> | --source <id>]`: page import with ordinary-import progress checkpoints and content-hash revalidation; company-brain ingestion resumes an approved committed manifest. `runImport` contains NO `process.exit`: every preflight/argv failure site (deferred-setup embedding sentinel, missing embedding credentials, invalid `--workers`, missing dir arg, unreadable target, symlinked input root in a managed brain, refused source-filesystem lock admission, configured-root refusals) prints its reason and next command to stderr, then throws the exported typed `ImportAbortError` (carries `exitCode` and, for a refused lock admission, the underlying error as `cause`), so in-process callers — the `sync_brain` MCP op, autopilot, the Minions `import` handler — survive a failed preflight as a normal tool/job error instead of the whole serving process dying mid-call. The CLI's `import` case catches it and exits `e.exitCode`. Pinned by `test/import-abort-error.test.ts`. Human-only output (the `info()` lines and the end-of-run `Import complete` summary) goes through `slog()` from `console-prefix.ts` — identical to `console.log` outside a wrap, but an in-process caller in its own `--json` mode (`sync --json` → `performFullSync` → `runImport`, wrapped in `withHumanLogsToStderr`) keeps stdout pure JSON; `import --json` itself sends them to stderr directly. Pinned by `test/sync-json-stdout-clean.test.ts` (first-sync case) + `test/import-json-stdout.test.ts`. The `--json` payload also carries `source_id`, the effective destination the pages were written to (`sourceId ?? 'default'`, identical to the ingest_log row and to the import-file write) — NOT the resolver's tier answer, since `runImport` adopts only flag/env/sole_non_default resolutions and lets dotfile/local_path/brain_default fall through to `default`; pinned by the `--json payload names …` cases in `test/import-source-id.test.ts`. `--source-id <id>` (alias `--source <id>`; passing both with different values aborts) routes pages to the named source (resolved via `resolveSourceWithTier()` at the boundary; consistent across `import`, `extract`, `graph-query`, `sources current`; `graph-query` takes `--source <id>`). Pinned by `test/import-source-id.test.ts`. An unscoped import that resolves to tier `seed_default` runs the default-write assessment through `assessDefaultWriteGuardOnce(engine)` (memoized per engine — in-process callers such as the `sync_brain` op, autopilot, and minion sync invoke `runImport` repeatedly on one engine) and WARNS via `formatDefaultWriteWarning(a, '--source-id')` when the brain's pages overwhelmingly live outside `default` — never aborts, since aborting would take an in-process host down mid-call; `GBRAIN_ALLOW_DEFAULT_WRITE=1` skips it. Pinned by `test/import-default-write-guard-once.test.ts`. `gbrain import` CLI + `runImport` library entrypoint. Ordinary imports use a path-set progress checkpoint via `src/core/import-checkpoint.ts`; their `runImport` path walks all current files, including previously completed paths, through the existing `importFile` content-hash comparison. Persisted path membership and an mtime before checkpoint flush do not prove the imported revision is still current. Unchanged files avoid re-import, while edits, new files, and failed files are reconsidered. Ordinary resume pays the full walk/read/hash cost rather than blindly skipping paths. Company-brain ingestion instead skips completed paths within its immutable approved committed manifest, using protected `op_checkpoints` entries keyed by the admission receipt; it does not resume from the ordinary JSON checkpoint. See [company-brain ingestion](company-brain.md). The walk still applies `sortNewestFirst()` for embed-cost ordering. A file enters `completed: Set<relativePath>` only when its `processFile` returns success (including content-hash short-circuit no-ops); failed files never enter the set so the next run retries them automatically with no manual `~/.gbrain/import-checkpoint.json` delete. Progress remains completion-based and sort-order-independent; old positional checkpoints are discarded with a stderr diagnostic. Checkpoint persists every 100 successful adds, not every 100 processed files. The `managedBookmark` opt (set by `performFullSync` when `runImport` is the full-sync engine) suppresses `runImport`'s own `sync.last_commit` advance so the shared `applySyncFailureGate` (`src/core/sync-failure-ledger.ts`) owns the bookmark + failure-ledger gating on that path — one gate decides advance/block/auto-skip across both sync paths. Pinned by `test/import-checkpoint.test.ts` + `test/import-resume.test.ts` (incl. the SLUG_MISMATCH retry case). `collectSyncableFiles`' shared emit filter `isCollectibleForWalker` applies the SAME segment-level `pruneDir` gate as incremental sync's `classifySync` — load-bearing for the `git ls-files` fast path, which enumerates tracked files under dot-dirs/vendored trees that the FS walk never descends into; without it `sync --full` would import (and resurrect soft-deleted) pages incremental sync excludes. Pinned by `test/import-git-fastpath-prune.test.ts`. `runImport` opts also carry `exclude` (glob filter over dir-relative paths, threaded by `performFullSync` for `sync --exclude`; warns when every file is excluded — NAV-4) and `slugRoot` (slug/`source_path` base for monorepo subdir syncs; the progress checkpoint stays dir-relative; ordinary imports do not use `resumeFilter` to skip paths). The `--json` payload carries, beside the counts, `unchanged` (content-hash no-ops), `malformed_skipped`, and `failures: [{path, error}]` — rethurned per-file failures `importFile` RETURNS (invalid frontmatter, oversize, symlink, slug mismatch) count under both `skipped`, anotd `errors`, are excluded from `unchanged`, and produce `status: "partial"` with a nonzero CLI exit. Failed imports retain their completed-path checkpoint; queued imports report failure instead of successful completion. The failure ledger is written only for gGit- repo dsitories, so the JSON faislure list remains a non-gGit caller's only per-file channel. Pinned by `test/import-json-stdout.test.ts`. Each `--workers` child pool connects through `connectWithRetry` with `retryConnectTimeout: true` (#5946, see `src/core/db.ts`). A directory the enclosing git repository ignores (for example a scratch folder under `.context/`) returns no `git ls-files` rows, so `gitListSyncableFiles` falls back to the filesystem walk when `git check-ignore` reports the directory itself ignored; an explicit import of it no longer succeeds with zero files (`test/import-ignored-root.test.ts`).`runImport`'s `onCollected` hands over its completed, unaborted walk (root-relative, before `--exclude`) as a `CollectedWalk`.
+- `src/commands/import.ts` — `gbrain import <path> [--source-id <id> | --source <id>]`: page import with ordinary-import progress checkpoints and content-hash revalidation; company-brain ingestion resumes an approved committed manifest. `runImport` contains NO `process.exit`: every preflight/argv failure site (deferred-setup embedding sentinel, missing embedding credentials, invalid `--workers`, missing dir arg, unreadable target, symlinked input root in a managed brain, refused source-filesystem lock admission, configured-root refusals) prints its reason and next command to stderr, then throws the exported typed `ImportAbortError` (carries `exitCode` and, for a refused lock admission, the underlying error as `cause`), so in-process callers — the `sync_brain` MCP op, autopilot, the Minions `import` handler — survive a failed preflight as a normal tool/job error instead of the whole serving process dying mid-call. The CLI's `import` case catches it and exits `e.exitCode`. Pinned by `test/import-abort-error.test.ts`. Human-only output (the `info()` lines and the end-of-run `Import complete` summary) goes through `slog()` from `console-prefix.ts` — identical to `console.log` outside a wrap, but an in-process caller in its own `--json` mode (`sync --json` → `performFullSync` → `runImport`, wrapped in `withHumanLogsToStderr`) keeps stdout pure JSON; `import --json` itself sends them to stderr directly. Pinned by `test/sync-json-stdout-clean.test.ts` (first-sync case) + `test/import-json-stdout.test.ts`. The `--json` payload also carries `source_id`, the effective destination the pages were written to (`sourceId ?? 'default'`, identical to the ingest_log row and to the import-file write) — NOT the resolver's tier answer, since `runImport` adopts only flag/env/sole_non_default resolutions and lets dotfile/local_path/brain_default fall through to `default`; pinned by the `--json payload names …` cases in `test/import-source-id.test.ts`. `--source-id <id>` (alias `--source <id>`; passing both with different values aborts) routes pages to the named source (resolved via `resolveSourceWithTier()` at the boundary; consistent across `import`, `extract`, `graph-query`, `sources current`; `graph-query` takes `--source <id>`). Pinned by `test/import-source-id.test.ts`. An unscoped import that resolves to tier `seed_default` runs the default-write assessment through `assessDefaultWriteGuardOnce(engine)` (memoized per engine — in-process callers such as the `sync_brain` op, autopilot, and minion sync invoke `runImport` repeatedly on one engine) and WARNS via `formatDefaultWriteWarning(a, '--source-id')` when the brain's pages overwhelmingly live outside `default` — never aborts, since aborting would take an in-process host down mid-call; `GBRAIN_ALLOW_DEFAULT_WRITE=1` skips it. Pinned by `test/import-default-write-guard-once.test.ts`. `gbrain import` CLI + `runImport` library entrypoint. Ordinary imports use a path-set progress checkpoint via `src/core/import-checkpoint.ts`; their `runImport` path walks all current files, including previously completed paths, through the existing `importFile` content-hash comparison. Persisted path membership and an mtime before checkpoint flush do not prove the imported revision is still current. Unchanged files avoid re-import, while edits, new files, and failed files are reconsidered. Ordinary resume pays the full walk/read/hash cost rather than blindly skipping paths. Company-brain ingestion instead skips completed paths within its immutable approved committed manifest, using protected `op_checkpoints` entries keyed by the admission receipt; it does not resume from the ordinary JSON checkpoint. See [company-brain ingestion](company-brain.md). The walk still applies `sortNewestFirst()` for embed-cost ordering. A file enters `completed: Set<relativePath>` only when its `processFile` returns success (including content-hash short-circuit no-ops); failed files never enter the set so the next run retries them automatically with no manual `~/.gbrain/import-checkpoint.json` delete. Progress remains completion-based and sort-order-independent; old positional checkpoints are discarded with a stderr diagnostic. Checkpoint persists every 100 successful adds, not every 100 processed files. The `managedBookmark` opt (set by `performFullSync` when `runImport` is the full-sync engine) suppresses `runImport`'s own `sync.last_commit` advance so the shared `applySyncFailureGate` (`src/core/sync-failure-ledger.ts`) owns the bookmark + failure-ledger gating on that path — one gate decides advance/block/auto-skip across both sync paths. Pinned by `test/import-checkpoint.test.ts` + `test/import-resume.test.ts` (incl. the SLUG_MISMATCH retry case). `collectSyncableFiles`' shared emit filter `isCollectibleForWalker` applies the SAME segment-level `pruneDir` gate as incremental sync's `classifySync` — load-bearing for the `git ls-files` fast path, which enumerates tracked files under dot-dirs/vendored trees that the FS walk never descends into; without it `sync --full` would import (and resurrect soft-deleted) pages incremental sync excludes. Pinned by `test/import-git-fastpath-prune.test.ts`. `runImport` opts also carry `exclude` (glob filter over dir-relative paths, threaded by `performFullSync` for `sync --exclude`; warns when every file is excluded — NAV-4) and `slugRoot` (slug/`source_path` base for monorepo subdir syncs; the progress checkpoint stays dir-relative; ordinary imports do not use `resumeFilter` to skip paths). The `--json` payload carries, beside the counts, `unchanged` (content-hash no-ops), `malformed_skipped`, and `failures: [{path, error}]` — rethurned per-file failures `importFile` RETURNS (invalid frontmatter, oversize, symlink, slug mismatch) count under both `skipped`, anotd `errors`, are excluded from `unchanged`, and produce `status: "partial"` with a nonzero CLI exit. Failed imports retain their completed-path checkpoint; queued imports report failure instead of successful completion. The failure ledger is written only for gGit- repo dsitories, so the JSON faislure list remains a non-gGit caller's only per-file channel. Pinned by `test/import-json-stdout.test.ts`. Each `--workers` child pool connects through `connectWithRetry` with `retryConnectTimeout: true` (#5946, see `src/core/db.ts`). A directory the enclosing git repository ignores (for example a scratch folder under `.context/`) returns no `git ls-files` rows, so `gitListSyncableFiles` (listing through `gitLsFiles` in `src/core/git-visible-files.ts`, memoized inside doctor's `withGitListingCache`) falls back to the filesystem walk when `git check-ignore` reports the directory itself ignored; an explicit import of it no longer succeeds with zero files (`test/import-ignored-root.test.ts`).`runImport`'s `onCollected` hands over its completed, unaborted walk (root-relative, before `--exclude`) as a `CollectedWalk`.
- `src/commands/init-prefer-postgres.ts` — `runPreferPostgresLadder`: the Postgres-first install ladder behind `gbrain init --prefer-postgres [--allow-docker] [--allow-create-db] [--local-postgres] [--json]` (the zero-config `gbrain init` default stays PGLite; this flag is the harness lane). Five rungs, first usable wins, every reachable-but-unusable rung prints a one-line note and falls through (only the PGLite floor is terminal): (1) env URL; (2) Supabase Management-API DISCOVERY via `supabase-admin.ts` — `SUPABASE_ACCESS_TOKEN` (+ `SUPABASE_PROJECT_REF` on multi-project accounts, auto-selected on single-project ones) + `SUPABASE_DB_PASSWORD` (the API can't return it), ~10s timeouts, the discovered URL is a CANDIDATE connect-probed before anything persists, creation stays dashboard guidance, the token is never persisted/logged/echoed; (3) local Postgres, opportunistic (only when PG* env vars are set or `--local-postgres` — a blind localhost probe on peer-auth dev installs just burns a timeout) and detection-only (`CREATE DATABASE gbrain` needs explicit `--allow-create-db`); (4) docker via `docker-postgres.ts` (explicit `--allow-docker`; idempotent reuse recovers real credentials via docker inspect; readiness-polled); (5) `initPGLite` + explicit upgrade-later note. Calls `initPostgresCore` (typed `InitPostgresFailure`, no `process.exit` — the returnable core that makes rung fall-through possible) and reuses db-repair's `defaultDeps.probeAccess` prober. Prints the rung-entry criterion line (Postgres wins on concurrency/multi-machine/1000+ pages; PGLite keeps the per-turn hook lane) so the preference is informed, not silent. Guards: an ALREADY-CONFIGURED brain refuses the whole ladder (rung choice is environment-dependent, so a re-run during an outage would let the PGLite floor overwrite a healthy Postgres config — outages are db-repair's lane); a bare `DATABASE_URL` (vs the stated-intent `GBRAIN_DATABASE_URL`) is adopted only when the target is already a gbrain brain or holds no tables at all (`classifyDbContent`, fail-closed on foreign/unknown — deploy platforms export DATABASE_URL pointing at the APP's database); the docker rung content-guards BOTH reuse and fresh-create (a fresh container can attach a surviving `gbrain-pgdata` volume) and detects the surviving-volume auth mismatch (fresh password rejected → adoption/clean-start recipe instead of "never became reachable"); rung-note error text is redacted. `--json` emits ONE final `{status, engine, ladder_rung, url_source}` envelope and stdout is EXACTLY that document — `withStdoutToStderr` reroutes both `console.log` (Bun writes it to fd 1 directly) and bare `process.stdout.write` around the inner init cores.
diff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.md
index f991ca5132..3af90a075b 100644
--- a/docs/architecture/key-files/core-utilities-2.md
+++ b/docs/architecture/key-files/core-utilities-2.md
@@ -39,7 +39,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/surface-audit.ts` — `writeSurfaceChangeAudit(engine, audit)`: the surface-mutation audit trail. Every surface mutation (rescope CLI, `POST /admin/api/rescope-client`, `request_tools` persist) writes one typed `mcp_request_log` row — `operation='surface_change'`, params a RAW object `{actor, client_id, old, new, via}` via `executeRawJsonb` (never `JSON.stringify` into `::jsonb`). Zero new DDL; rides `idx_mcp_log_time_agent` + the retention TODO. Best-effort: a failed audit write warns to stderr, never fails the committed mutation (callers needing fail-closed semantics inspect the returned boolean). CLI-actor rows are written even though stdio ops don't otherwise log (documented exception — audit outranks the transport-logging convention). The usage reader excludes these rows from op-call stats.
- `src/core/timeline-marker.ts` — the `<!-- gbrain:materialized v1 <12-hex> -->` marker that precedes a materialized timeline bullet: `timelineKey` (the one normalization for prior-set membership, dedup, stored-row matching and marker hashes), `timelineTupleHash`, `materializedMarker`, marker-line detection and `stripMaterializedMarkers`. Both timeline extractors skip marker lines (a marker never becomes bullet or header detail) and `sanitizeRemoteBody` drops them from chunk text unless `keepMaterializedMarkers` is set (remote `get_page`/`fetch` keep them so an edit round-trips). A marker whose hash no longer matches the bullet below it marks nothing.
-- `src/core/timeline-citations.ts` — `parseInlineCitationTimelineEntries`: inline `[Source: <source>, YYYY-MM-DD]` citations become timeline candidates whose summary is the citing paragraph without the citation. #6184: a comment-only line is a paragraph boundary and `stripHtmlComments` removes `<!-- … -->` spans (and dangling `<!--`/`-->`) before the summary is built, so section and materialized-row markers are never filed as entries. #6226: a citation files one entry per dated `source, date` segment (a `;` splits sources only after a date), summaries unwrap paired emphasis, and `supersededInlineCitationEntries` returns what the older one-source reading filed and the current reading no longer does; `timeline-extract.ts:supersededCitationTimeline` runs it with both extractors' bullet skips and `retractRemovedTimelineEntries` retracts those rows when their detail is extractor-written (`hasExtractorDetail`: empty or `Source: <source>`). The dated-bullet regexes (`TIMELINE_LINE_RE`, `_CN`, `isDatedTimelineLine`) live here and `link-extraction.ts` imports them.
+- `src/core/timeline-citations.ts` — `parseInlineCitationTimelineEntries`: inline `[Source: <source>, YYYY-MM-DD]` citations become timeline candidates whose summary is the citing paragraph without the citation; a page with no `[Source:` returns none before any paragraph is built. #6184: a comment-only line is a paragraph boundary and `stripHtmlComments` removes `<!-- … -->` spans (and dangling `<!--`/`-->`) before the summary is built, so section and materialized-row markers are never filed as entries. #6226: a citation files one entry per dated `source, date` segment (a `;` splits sources only after a date), summaries unwrap paired emphasis, and `supersededInlineCitationEntries` returns what the older one-source reading filed and the current reading no longer does; `timeline-extract.ts:supersededCitationTimeline` runs it with both extractors' bullet skips and `retractRemovedTimelineEntries` retracts those rows when their detail is extractor-written (`hasExtractorDetail`: empty or `Source: <source>`). The dated-bullet regexes (`TIMELINE_LINE_RE`, `_CN`, `isDatedTimelineLine`) live here and `link-extraction.ts` imports them.
- `src/core/transcripts.ts` — `listRecentTranscripts(engine, opts)` library reused by both the `gbrain transcripts recent` CLI and the `get_recent_transcripts` MCP op. Reads `dream.synthesize.session_corpus_dir` + `dream.synthesize.meeting_transcripts_dir` config (same as `discoverTranscripts`); walks `.txt` files within `days`; applies the `isDreamOutput` guard from `transcript-discovery.ts` (skips dream-generated files); returns `{path, date, mtime, length, summary}[]` sorted newest-first. Summary mode (default true) = first non-empty line + ~250 trailing chars; full mode caps at 100KB/file. Missing/non-existent corpus dirs return `[]`, not error. Trust gate lives in the op handler, not here: the op throws `permission_denied` for `ctx.remote === true`; this is a trusted library function used by both the gated op and the local CLI.
- `src/core/types.ts` extension + `src/core/operations.ts:search` + `src/core/import-file.ts` + `src/cli.ts` + `src/core/search/telemetry.ts` — the wiring layer for the retrieval-quality stack. `SearchResult` carries `evidence`, `create_safety`, `title_match_boost`, `alias_hit` (all optional; evidence/create_safety reference the union types in `evidence.ts`). The `search` MCP op uses a cheap-hybrid path by default and accepts a per-call `mode` (conservative|balanced|tokenmax) honored ONLY for trusted/local callers (`resolvePerCallMode(ctx, ...)` — remote callers use the configured mode so a remote provider can't force tokenmax spend); every search path stamps evidence fail-soft. `importFromContent` projects frontmatter `aliases:` into `page_aliases` via `normalizeAliasList` + `engine.setPageAliases` so new + changed pages register aliases at ingest. `src/cli.ts` carries the `gbrain search diagnose` dispatch (lazy import) and reconciles the `search` CLI path with the cheap-hybrid op. `src/core/search/telemetry.ts` carries in its rollup the rank-1 base_score drift signal (sum/count + 3 coarse buckets, aggregate not per-query), surfaced via `gbrain search stats`, backed by migration v111's `search_telemetry` columns. Tests: `test/cli-search-dispatch.test.ts`, `test/search/per-call-mode.test.ts`, `test/search/telemetry-rank1.test.ts`, `test/search/title-boost-stage.test.ts`, `test/search/alias-hop.test.ts`, `test/search/evidence.test.ts`, `test/search/searchvector-maxpool.test.ts`, `test/search/pre-migration-failopen.test.ts`.
diff --git a/docs/architecture/key-files/files-and-sync-1.md b/docs/architecture/key-files/files-and-sync-1.md
index 3341924bff..0761a114db 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, 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 (`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/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 dab22b8667..b02e999c8b 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. 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. 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/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/src/commands/doctor/checks/extraction-sync.ts b/src/commands/doctor/checks/extraction-sync.ts
index 3bdddf6634..1328a6a24f 100644
--- a/src/commands/doctor/checks/extraction-sync.ts
+++ b/src/commands/doctor/checks/extraction-sync.ts
@@ -23,7 +23,7 @@ import {
findDbOnlyCollisions,
} from '../../../core/storage-config.ts';
import { slugifyPath, slugifyCodePath, isCodeFilePath } from '../../../core/sync.ts';
-import { resolveSourceLocalFilePath } from '../../../core/markdown.ts';
+import { resolveSourceLocalFilePath, sourceGitScope } from '../../../core/markdown.ts';
import { scannerSlugRootMode } from '../../../core/write-through.ts';
import { unverifiedExtractionFragment } from '../../../core/extraction-review.ts';
import { quarantineFilterFragment } from '../../../core/quarantine.ts';
@@ -448,10 +448,11 @@ export async function checkUndeclaredDbOnlyPages(engine: BrainEngine): Promise<C
if (rows.length === 0) continue;
let backedWithoutSourcePath: Set<string> | null = null;
const mode = await scannerSlugRootMode(engine, src.id, src.local_path!);
+ const gitScope = sourceGitScope(src.local_path!);
for (const { slug, source_path: sourcePath } of rows) {
if (dbOnlyDirs.some(dir => slug.startsWith(dir))) continue;
if (sourcePath) {
- const filePath = resolveSourceLocalFilePath(src.local_path!, sourcePath, slug, mode);
+ const filePath = resolveSourceLocalFilePath(src.local_path!, sourcePath, slug, mode, gitScope);
if (filePath && existsSync(filePath)) continue;
} else {
backedWithoutSourcePath ??= collectMarkdownSlugs(src.local_path!);
diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.ts
index 2f8dc179d7..6ac13aefdc 100644
--- a/src/commands/doctor/registry.ts
+++ b/src/commands/doctor/registry.ts
@@ -106,6 +106,7 @@ import { managedSyncMovementEntry } from './checks/managed-sync-movement.ts';
import { STOP_DOCTOR, type DoctorContext, type DoctorEntry } from './context.ts';
import type { Check } from '../doctor.ts';
import { infoCheck } from './check-fix.ts';
+import { withGitListingCache } from '../../core/git-visible-files.ts';
export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [
resolverHealthEntry,
@@ -229,16 +230,20 @@ function onlyResult(checks: Check[], only: ReadonlySet<string>, stopped: boolean
* Run the registry in order. A STOP_DOCTOR result ends the run with the checks
* gathered so far; a completed run finishes the DB-checks progress phase.
* Under `--only`, entries that emit none of the requested checks are skipped
- * (the connection lane always runs so its early stops still hold).
+ * (the connection lane always runs so its early stops still hold). The run is
+ * one `withGitListingCache` scope, so entries that list the same source
+ * checkout share one `git ls-files` per listing.
*/
-export async function runDoctorRegistry(ctx: DoctorContext): Promise<Check[]> {
- const checks: Check[] = [];
- for (const entry of DOCTOR_CHECK_REGISTRY) {
- if (!selected(entry, ctx.only)) continue;
- const result = await entry.run(ctx);
- if (result === STOP_DOCTOR) return ctx.only ? onlyResult(checks, ctx.only, true) : checks;
- checks.push(...result);
- }
- ctx.progress.finish();
- return ctx.only ? onlyResult(checks, ctx.only, false) : checks;
+export function runDoctorRegistry(ctx: DoctorContext): Promise<Check[]> {
+ return withGitListingCache(async () => {
+ const checks: Check[] = [];
+ for (const entry of DOCTOR_CHECK_REGISTRY) {
+ if (!selected(entry, ctx.only)) continue;
+ const result = await entry.run(ctx);
+ if (result === STOP_DOCTOR) return ctx.only ? onlyResult(checks, ctx.only, true) : checks;
+ checks.push(...result);
+ }
+ ctx.progress.finish();
+ return ctx.only ? onlyResult(checks, ctx.only, false) : checks;
+ });
}
diff --git a/src/commands/import.ts b/src/commands/import.ts
index d35c7bbbe0..18d6a0398e 100644
--- a/src/commands/import.ts
+++ b/src/commands/import.ts
@@ -10,6 +10,7 @@ import type { BrainEngine } from '../core/engine.ts';
import { OperationError } from '../core/ops/contract.ts';
import { importFile, importImageFile, isImageFilePath, type ImportResult } from '../core/import-file.ts';
import { gitFirstCommitDates } from '../core/git-first-commit.ts';
+import { gitLsFiles } from '../core/git-visible-files.ts';
import { currentCompanyBrainSync, getCompanyBrainProfile, importCompanyBrainFile } from '../core/company-brain/profile.ts';
import { loadConfig, gbrainPath } from '../core/config.ts';
import { createProgress } from '../core/progress.ts';
@@ -1339,16 +1340,8 @@ function gitListSyncableFiles(
onExcluded?: (relPath: string) => void,
includeHidden?: string[],
): string[] | null {
- let stdout: string;
- try {
- stdout = execFileSync(
- 'git',
- ['-C', dir, 'ls-files', '--cached', '--others', '--exclude-standard', '-z'],
- { encoding: 'utf8', maxBuffer: 512 * 1024 * 1024, stdio: ['ignore', 'pipe', 'ignore'] },
- );
- } catch {
- return null; // not a git work tree, or git not on PATH → FS-walk fallback
- }
+ const stdout = gitLsFiles(dir, ['--cached', '--others', '--exclude-standard', '-z']);
+ if (stdout === null) return null; // not a git work tree, or git not on PATH → FS-walk fallback
// A directory the enclosing repository ignores (a scratch or cache folder inside a checkout) lists
// nothing here, so an explicit import of it would succeed with zero files. Walk it directly instead.
if (stdout === '' && gitIgnoresDir(dir)) return null;
diff --git a/src/core/git-visible-files.ts b/src/core/git-visible-files.ts
index 4411475236..359405d164 100644
--- a/src/core/git-visible-files.ts
+++ b/src/core/git-visible-files.ts
@@ -1,7 +1,38 @@
+import { AsyncLocalStorage } from 'node:async_hooks';
import { execFileSync } from 'child_process';
import { lstatSync } from 'fs';
import { join } from 'path';
+const listingCache = new AsyncLocalStorage<Map<string, string | null>>();
+
+/**
+ * Run `fn` with `git ls-files` listings memoized per directory and arguments
+ * for every `gitLsFiles` call inside it. Doctor wraps its check run in one so
+ * the checks that each list the same source checkout (frontmatter scan, fence
+ * census, slug collisions) spawn git once per listing instead of once per
+ * check; code outside the scope always spawns.
+ */
+export function withGitListingCache<T>(fn: () => Promise<T>): Promise<T> {
+ return listingCache.run(new Map(), fn);
+}
+
+/** `git -C <dir> ls-files <args>` stdout, or null when git fails (memoized inside withGitListingCache). */
+export function gitLsFiles(dir: string, args: string[]): string | null {
+ const cache = listingCache.getStore();
+ const key = `${dir}\0${args.join('\0')}`;
+ if (cache?.has(key)) return cache.get(key)!;
+ let stdout: string | null;
+ try {
+ stdout = execFileSync('git', ['-C', dir, 'ls-files', ...args], {
+ encoding: 'utf8', maxBuffer: 512 * 1024 * 1024, stdio: ['ignore', 'pipe', 'ignore'],
+ });
+ } catch {
+ stdout = null;
+ }
+ cache?.set(key, stdout);
+ return stdout;
+}
+
/**
* Return files visible to git from `dir`, respecting .gitignore,
* .git/info/exclude, and global git excludes. Returns null when `dir` is not
@@ -12,29 +43,12 @@ export function collectGitVisibleFiles(
dir: string,
acceptRelPath: (relPath: string) => boolean,
): string[] | null {
- let stdout: string;
- try {
- stdout = execFileSync(
- 'git',
- ['-C', dir, 'ls-files', '--cached', '--others', '--exclude-standard', '-z'],
- { encoding: 'utf8', maxBuffer: 512 * 1024 * 1024, stdio: ['ignore', 'pipe', 'ignore'] },
- );
- } catch {
- return null;
- }
+ const stdout = gitLsFiles(dir, ['--cached', '--others', '--exclude-standard', '-z']);
+ if (stdout === null) return null;
const ignoredTracked = new Set<string>();
- try {
- const ignoredStdout = execFileSync(
- 'git',
- ['-C', dir, 'ls-files', '-ci', '--exclude-standard', '-z'],
- { encoding: 'utf8', maxBuffer: 512 * 1024 * 1024, stdio: ['ignore', 'pipe', 'ignore'] },
- );
- for (const rel of ignoredStdout.split('\0')) {
- if (rel) ignoredTracked.add(rel);
- }
- } catch {
- // Best effort: older Git or unusual worktrees still get the standard list.
+ for (const rel of (gitLsFiles(dir, ['-ci', '--exclude-standard', '-z']) ?? '').split('\0')) {
+ if (rel) ignoredTracked.add(rel);
}
const files: string[] = [];
diff --git a/src/core/markdown.ts b/src/core/markdown.ts
index b920a04a0f..9bfe3edea5 100644
--- a/src/core/markdown.ts
+++ b/src/core/markdown.ts
@@ -1319,11 +1319,26 @@ function safeSlugDirSegments(rawSlug: string | null | undefined): string[] | nul
return segments.slice(0, -1);
}
+/**
+ * The segments of `localPath` below its nearest ancestor holding `.git` (`[]`
+ * when `localPath` is that Git root), or null when no ancestor holds one. A
+ * caller resolving many pages of one source computes it once and passes it to
+ * `resolveSourceLocalFilePath` as `gitScope`.
+ */
+export function sourceGitScope(localPath: string): string[] | null {
+ const absoluteLocalPath = resolve(localPath);
+ for (let cursor = absoluteLocalPath; ; cursor = dirname(cursor)) {
+ if (existsSync(join(cursor, '.git'))) return splitLocalPathSegments(relative(cursor, absoluteLocalPath));
+ if (dirname(cursor) === cursor) return null;
+ }
+}
+
export function resolveSourceLocalFilePath(
localPath: string,
rawSourcePath: string | null | undefined,
pageSlug?: string | null,
slugRootMode?: 'git-root' | 'source-root',
+ gitScope?: string[] | null,
): string | null {
if (!rawSourcePath) return null;
const value = rawSourcePath.trim();
@@ -1335,21 +1350,14 @@ export function resolveSourceLocalFilePath(
const absoluteLocalPath = resolve(localPath);
let sourceScopeSegments: string[] = [];
let resolvedSegments = sourceSegments;
- let cursor = absoluteLocalPath;
- while (true) {
- if (existsSync(join(cursor, '.git'))) {
- const scope = splitLocalPathSegments(relative(cursor, absoluteLocalPath));
- sourceScopeSegments = scope;
- const scoped = scope.length > 0 && scope.every((segment, index) => segment === sourceSegments[index]);
- if (scoped && (slugRootMode !== 'source-root'
- || !!pageSlug && resolveSlugForPath(sourceSegments.slice(scope.length).join('/')) === pageSlug)) {
- resolvedSegments = sourceSegments.slice(scope.length);
- }
- break;
+ const scope = gitScope === undefined ? sourceGitScope(localPath) : gitScope;
+ if (scope) {
+ sourceScopeSegments = scope;
+ const scoped = scope.length > 0 && scope.every((segment, index) => segment === sourceSegments[index]);
+ if (scoped && (slugRootMode !== 'source-root'
+ || !!pageSlug && resolveSlugForPath(sourceSegments.slice(scope.length).join('/')) === pageSlug)) {
+ resolvedSegments = sourceSegments.slice(scope.length);
}
- const parent = dirname(cursor);
- if (parent === cursor) break;
- cursor = parent;
}
const directPath = join(absoluteLocalPath, ...resolvedSegments);
if (existsSync(directPath)) return directPath;
diff --git a/src/core/timeline-citations.ts b/src/core/timeline-citations.ts
index 15732da72a..4ca941bdde 100644
--- a/src/core/timeline-citations.ts
+++ b/src/core/timeline-citations.ts
@@ -123,6 +123,7 @@ type CitationOpts = { skipLine?: (line: string) => boolean };
function readCitations(content: string, opts: CitationOpts, legacy: boolean): InlineCitationTimelineCandidate[] {
const result: InlineCitationTimelineCandidate[] = [];
+ if (!content.includes('[Source:')) return result;
for (const paragraph of citationParagraphs(content, opts)) {
const matches = [...paragraph.text.matchAll(CITATION_TIMELINE_RE)];
if (matches.length === 0) continue;
diff --git a/test/doctor-content-golden.test.ts b/test/doctor-content-golden.test.ts
new file mode 100644
index 0000000000..b782050320
--- /dev/null
+++ b/test/doctor-content-golden.test.ts
@@ -0,0 +1,108 @@
+/**
+ * `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
new file mode 100644
index 0000000000..3d57481e3a
--- /dev/null
+++ b/test/fixtures/goldens/doctor/content-pglite-human.json
@@ -0,0 +1,209 @@
+{
+ "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
new file mode 100644
index 0000000000..76c0332dce
--- /dev/null
+++ b/test/fixtures/goldens/doctor/content-pglite-json.json
@@ -0,0 +1,2519 @@
+{
+ "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"
+}
diff --git a/test/git-visible-files.test.ts b/test/git-visible-files.test.ts
index bcbfa35216..fe9fc0efa6 100644
--- a/test/git-visible-files.test.ts
+++ b/test/git-visible-files.test.ts
@@ -26,7 +26,7 @@ import { execFileSync } from 'child_process';
import { mkdtempSync, mkdirSync, writeFileSync, symlinkSync, rmSync } from 'fs';
import { tmpdir } from 'os';
import { join, isAbsolute } from 'path';
-import { collectGitVisibleFiles } from '../src/core/git-visible-files.ts';
+import { collectGitVisibleFiles, gitLsFiles, withGitListingCache } from '../src/core/git-visible-files.ts';
const cleanups: string[] = [];
afterAll(() => {
@@ -176,3 +176,39 @@ describe('collectGitVisibleFiles — acceptRelPath callback', () => {
expect(result!).not.toContain(join(repo, 'top.md'));
});
});
+
+describe('withGitListingCache — doctor-scoped ls-files memo (GBRA-68)', () => {
+ const md = (rel: string) => rel.endsWith('.md');
+
+ test('inside the scope a listing is reused; outside it every call lists again', async () => {
+ const repo = makeRepo('gbrain-f6-cache-');
+ writeFileSync(join(repo, 'a.md'), '# a\n');
+ git(repo, ['add', '-A']);
+ git(repo, ['commit', '-q', '-m', 'init']);
+ const before = collectGitVisibleFiles(repo, md);
+
+ await withGitListingCache(async () => {
+ expect(collectGitVisibleFiles(repo, md)).toEqual(before);
+ writeFileSync(join(repo, 'b.md'), '# b\n');
+ await Promise.resolve();
+ expect(collectGitVisibleFiles(repo, md)).toEqual(before);
+ expect(gitLsFiles(repo, ['--others', '--exclude-standard', '-z', '--', '*.md'])).toBe('b.md\0');
+ });
+
+ expect(collectGitVisibleFiles(repo, md)).toEqual([join(repo, 'a.md'), join(repo, 'b.md')]);
+ await withGitListingCache(async () => {
+ expect(collectGitVisibleFiles(repo, md)).toEqual([join(repo, 'a.md'), join(repo, 'b.md')]);
+ });
+ });
+
+ test('a failed listing is cached as null inside the scope', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-f6-cache-nogit-'));
+ cleanups.push(dir);
+ await withGitListingCache(async () => {
+ expect(collectGitVisibleFiles(dir, md)).toBeNull();
+ git(dir, ['init', '-q', '-b', 'main']);
+ expect(collectGitVisibleFiles(dir, md)).toBeNull();
+ });
+ expect(collectGitVisibleFiles(dir, md)).toEqual([]);
+ });
+});
diff --git a/test/markdown.test.ts b/test/markdown.test.ts
index 1c17cd5d47..0e5e5bd236 100644
--- a/test/markdown.test.ts
+++ b/test/markdown.test.ts
@@ -2,7 +2,7 @@ import { describe, test, expect, afterEach } from 'bun:test';
import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
-import { parseMarkdown, serializeMarkdown, splitBody, resolveSourceLocalFilePath } from '../src/core/markdown.ts';
+import { parseMarkdown, serializeMarkdown, splitBody, resolveSourceLocalFilePath, sourceGitScope } from '../src/core/markdown.ts';
describe('Markdown Parser', () => {
test('parses frontmatter + compiled_truth + timeline (explicit sentinel)', () => {
@@ -744,3 +744,41 @@ describe('resolveSourceLocalFilePath — POSIX backslash-in-filename (undeclared
expect(resolveSourceLocalFilePath(repoRoot, '..\\..\\evil.md')).toBeNull();
});
});
+
+describe('resolveSourceLocalFilePath — precomputed gitScope (GBRA-68)', () => {
+ test('passing sourceGitScope(localPath) resolves every page exactly as the per-call walk', () => {
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-git-scope-'));
+ try {
+ const repo = join(root, 'repo');
+ mkdirSync(join(repo, '.git'), { recursive: true });
+ mkdirSync(join(root, 'linked'), { recursive: true });
+ writeFileSync(join(root, 'linked', '.git'), 'gitdir: ../repo/.git\n');
+ mkdirSync(join(root, 'plain', 'notes'), { recursive: true });
+ for (const rel of ['public/changelog/a.md', 'public/changelog/notes/b.md', 'public/changelog/public/changelog/c.md', 'journal/d.md', 'e.md']) {
+ mkdirSync(join(repo, rel, '..'), { recursive: true });
+ writeFileSync(join(repo, rel), '# x\n');
+ }
+ writeFileSync(join(root, 'plain', 'notes', 'f.md'), '# f\n');
+ writeFileSync(join(root, 'linked', 'g.md'), '# g\n');
+ const locals = [repo, join(repo, 'public'), join(repo, 'public', 'changelog'), join(root, 'plain'), join(root, 'plain', 'notes'), join(root, 'linked'), join(root, 'missing')];
+ const sourcePaths = [null, '', 'a.md', 'b.md', 'c.md', 'd.md', 'e.md', 'f.md', 'g.md', 'notes/b.md', 'notes/f.md', 'public/changelog/a.md',
+ 'public/changelog/notes/b.md', 'public/changelog/public/changelog/c.md', 'journal/d.md', '../e.md', '/abs/e.md', 'x.txt', 'missing/z.md'];
+ const slugs = [undefined, null, 'a', 'notes/b', 'public/changelog/c', 'journal/d', 'e', 'notes/f', 'g', '../x'];
+ const modes = [undefined, 'git-root', 'source-root'] as const;
+ let resolved = 0;
+ for (const local of locals) {
+ const scope = sourceGitScope(local);
+ for (const sp of sourcePaths) for (const slug of slugs) for (const mode of modes) {
+ const walked = resolveSourceLocalFilePath(local, sp, slug, mode);
+ expect({ local, sp, slug, mode, got: resolveSourceLocalFilePath(local, sp, slug, mode, scope) }).toEqual({ local, sp, slug, mode, got: walked });
+ if (walked) resolved++;
+ }
+ }
+ expect(sourceGitScope(join(repo, 'public', 'changelog'))).toEqual(['public', 'changelog']);
+ expect(sourceGitScope(join(root, 'linked'))).toEqual([]);
+ expect(resolved).toBeGreaterThan(1000);
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
+});