Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

docs(key-files): doctor hot-check speedups (head-only frontmatter scan, batched timeline reads, census order, git verdict memo)

time-attackcf474e8e08a4
diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.md
index cb7079cf88..474ec92169 100644
--- a/docs/architecture/key-files/commands-2.md
+++ b/docs/architecture/key-files/commands-2.md
@@ -22,7 +22,7 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve
- `src/commands/doctor/checks/auto-chronicle.ts` — `auto_chronicle`, `chronicle_config_invalid` and `auto_chronicle_default_on` (#5876), registered after `unlinked_facts`, config-plane only (no provider calls). `auto_chronicle`: off by choice is ok with `severity: info`, `readiness: disabled_by_choice`; an invalid word warns `auto_chronicle_invalid`; when on it reads `core/chronicle/ledger-stats.ts` and warns `judge_llm_unavailable` (pending pages, no chat provider) or the top failure reason with that reason's fix, else reports ok with 24 h use of the daily limit, the largest writer's share, 7-day outcomes and spend, and `gbrain dream --phase chronicle`. Every warn carries `details.fix` (an Action: argv/consent/actor) and `fix_hint`. `chronicle_config_invalid` warns on an out-of-range stored `chronicle.*` value. `auto_chronicle_default_on` is ok/info with `ask_user` and keep/opt-out decisions until `gbrain config set auto_chronicle` acknowledges. Test: `test/auto-chronicle-surfaces-5876.test.ts`.
- `src/commands/doctor/checks/vector-coverage.ts` — `fact_take_vectors` (#5188, #5885), registered after `auto_chronicle`: per unarchived source (honoring `--source`), active facts (`eligibleFactEmbedding` + `staleFactEmbedding`) and takes (`countStaleTakes` with the DB-plane model and width) with no vector for their current text, split into missing versus other-model; warns with code `stale_vectors` and `details.fix` (`gbrain embed --stale`, or `gbrain takes embed` when `takes.auto_embed` is off; per-source `gbrain embed --facts --stale --source <id> --dry-run --json`). Keyless brains report `applicable: false`; a brain with no recorded model or width warns `vectors_not_verified`.
-- `src/commands/doctor/checks/git-holds.ts` + `checks/frontmatter-repairable.ts` + `checks/frontmatter-hook.ts` — the #5988 hold and frontmatter checks. `git_held_files` (wave, host-only, `resolution: 'repair'`): Git-source holds per source from `readHeldCoverage` (missing vs stale counts) and the first five paths from `readGitHoldListing` with each one's code and `gitHoldFix` step, the put_page read-only note, `gbrain sources status <id>` and each source's repair command from the hold router (`holdRepairSteps`: `gbrain repair frontmatter --source <id>`, `gbrain repair fences --source <id>` for `invalid_fence` holds, both for a mixed source; with fence holds the details add `fences` and `auto_repair`, and the banner line names the fence repair through the wave entry's `bannerHow`); `fail` once a source holds more than `sync.hold_escalate_count`; connector holds stay on `connector_held_items`. `frontmatter_repairable` (registered inline: emitted by the `frontmatter_integrity` entry from the same `scanBrainSources` walk, whose `PerSourceReport.repairable` counts files by repairable cause: recoverable `YAML_PARSE`, `needs_interpretation`, `FRONTMATTER_COMMENT_VALUE` on title/name/description/summary, `NESTED_QUOTES`, `NULL_BYTES`, `MISSING_CLOSE`, `SLUG_MISMATCH`); a deadline-partial scan sets `details.partial`. Both list `details.source_ids` and belong to the explicit-only `frontmatter` kind, so remediation classifies them `explicit_kind_required` with `--source <id>` when one source is named. `frontmatter_hook` (wave, operator): installed gbrain pre-commit hooks older than `FRONTMATTER_HOOK_VERSION`, fix `gbrain frontmatter install-hook --source <id> --force`. `frontmatterHoldsBannerNote` (a `POST_UPGRADE_NOTES` entry) names sources whose unfinished managed cursor stopped on a failed content refusal: the next sync recovers them, `gbrain sync --source <id> --no-pull` does it now, plus the repair preview and the hook refresh. `fenceHoldsBannerNote` (a separate `POST_UPGRADE_NOTES` entry, #6188 D7) names sources whose cursor stopped on a fence receipt (typed or the message an older gbrain stored): the next sync recovers them with no command, `gbrain sync --source <id> --no-pull` does it now, the malformed fences the stored census knows and whether the next maintenance run repairs them, the read-only `gbrain repair fences` preview and the pause command `gbrain config set fences.repair.enabled false`; never an applying command. Tests: `test/doctor-frontmatter-holds.test.ts`, `test/persistence-sync-fence-holds.test.ts`.
+- `src/commands/doctor/checks/git-holds.ts` + `checks/frontmatter-repairable.ts` + `checks/frontmatter-hook.ts` — the #5988 hold and frontmatter checks. `git_held_files` (wave, host-only, `resolution: 'repair'`): Git-source holds per source from `readHeldCoverage` (missing vs stale counts) and the first five paths from `readGitHoldListing` with each one's code and `gitHoldFix` step, the put_page read-only note, `gbrain sources status <id>` and each source's repair command from the hold router (`holdRepairSteps`: `gbrain repair frontmatter --source <id>`, `gbrain repair fences --source <id>` for `invalid_fence` holds, both for a mixed source; with fence holds the details add `fences` and `auto_repair`, and the banner line names the fence repair through the wave entry's `bannerHow`); `fail` once a source holds more than `sync.hold_escalate_count`; connector holds stay on `connector_held_items`. `frontmatter_repairable` (registered inline: emitted by the `frontmatter_integrity` entry from the same `scanBrainSources` walk, whose `PerSourceReport.repairable` counts files by repairable cause: recoverable `YAML_PARSE`, `needs_interpretation`, `FRONTMATTER_COMMENT_VALUE` on title/name/description/summary, `NESTED_QUOTES`, `NULL_BYTES`, `MISSING_CLOSE`, `SLUG_MISMATCH`); a deadline-partial scan sets `details.partial`; the doctor scan passes `frontmatterOnly`, so each file's head through its closing fence is validated when `frontmatterScanHead` proves the findings equal, else the whole file (`test/brain-writer-frontmatter-scan-head.test.ts`). Both list `details.source_ids` and belong to the explicit-only `frontmatter` kind, so remediation classifies them `explicit_kind_required` with `--source <id>` when one source is named. `frontmatter_hook` (wave, operator): installed gbrain pre-commit hooks older than `FRONTMATTER_HOOK_VERSION`, fix `gbrain frontmatter install-hook --source <id> --force`. `frontmatterHoldsBannerNote` (a `POST_UPGRADE_NOTES` entry) names sources whose unfinished managed cursor stopped on a failed content refusal: the next sync recovers them, `gbrain sync --source <id> --no-pull` does it now, plus the repair preview and the hook refresh. `fenceHoldsBannerNote` (a separate `POST_UPGRADE_NOTES` entry, #6188 D7) names sources whose cursor stopped on a fence receipt (typed or the message an older gbrain stored): the next sync recovers them with no command, `gbrain sync --source <id> --no-pull` does it now, the malformed fences the stored census knows and whether the next maintenance run repairs them, the read-only `gbrain repair fences` preview and the pause command `gbrain config set fences.repair.enabled false`; never an applying command. Tests: `test/doctor-frontmatter-holds.test.ts`, `test/persistence-sync-fence-holds.test.ts`.
- `src/commands/doctor/wave-checks.ts` — `WAVE_CHECKS`, the table of managed-persistence wave checks (stable id, `resolution` `repair`/`operator`/`unsupported`, count-free remote `impact`, operator `instruction`, `count` for banners, `bannerHow` when a finding's details change the banner's parenthetical, `registration` inline-in-doctor.ts or from this table). `fence_integrity` (#6188, `repair`, registered inline) counts `details.total`; its banner line says "repaired automatically by the next maintenance run" while one is active (from `details.auto_repair`), else why not, with `gbrain repair fences` as the preview; a fence-only `git_held_files` finding gets the same wording, a mixed one adds it to the frontmatter preview. `runWaveChecks` turns a throwing check into an `unknown` finding; `checkHealthUnknown` reads `details.health === 'unknown'`. `remoteWaveHandoff` returns one line per remotely offered check with `details.host_action` {`check_id`, `state` ok/action_required/unknown, `preview_command`} and no paths, rows, SQL, emails or installation ids. Consumers: doctor.ts, `report-remote.ts`, `remediate.ts`, `upgrade-banner.ts`. Tests: `test/recovery-layer.test.ts`, `test/e2e/recovery-layer.test.ts`.
- `src/commands/doctor/remediate.ts` — the `--remediation-plan` / `--remediate` CLI shell (re-exported from doctor.ts): per-step `command` (`gbrain jobs submit …` for job steps, `gbrain repair <kind> --apply` for repair steps; a repair step with `llm_usd` names its paid chat model spend, and any embedding part, in its fix and plan line), `combinedRemediateCommand` (with repair steps it ends `--expect <plan_hash>`, the same hash `--remediation-plan --json` reports as `plan_hash`), a `Repair kinds whose preview failed` block for `repair_preview_failures` (each `{kind, code, message, why, fix}`; such a kind is not planned, so a plan approved while it failed refuses `preview_changed` once it succeeds), `REMEDIATE_HELP`, `--include-repairs`/`--no-embed`/`--resume` handling, the resume command after budget exhaustion (repeats the recorded cap and consent), `classifyWaveFindings` (cleared / pending / consent_required / operator_required / explicit_kind_required / unsupported, from wave checks run before and after; `details.partial` is pending; an explicit-only kind's preview gets `--source <id>` via `findingSource` when the finding names one source; `--remediation-plan` runs the wave checks too and reports the same classification as `findings`) and `remediationExitStatus` (0 when no repairable finding remains and no step failed; 1 otherwise, on budget exhaustion or when a repair preview failed; 2 when the target is unreachable with no repair step, or a resume is refused), set through `setCliExitVerdict`; 3 when consent is required), set through `setCliExitVerdict`. Consent (agent operator wave C1) lives in `doctor/remediate-consent.ts`: the CLI connects probe-only (no migrations) and computes the plan; when anything would run it calls `requireConsent` (effects `paid`, plus `destructive` with `--include-repairs`, bound to a `plan_hash` over the brain id, job step ids, repair kinds and pending counts, and the parameters, and persisted with the approval). Non-TTY without authorization changes nothing and exits 3 with the consent payload; `--json` never implies consent; `--yes` without `--max-usd` runs under the derived cap (estimate ×1.5, floor $0.25; the default cap when unpriced), and derived-cap exhaustion prints the `--max-usd` resume command. Startup (migrations) completes only after consent. A `--resume` is bound by its checkpoint manifest, not a new plan hash. Pinned by `test/doctor-remediate-consent.test.ts`.
@@ -40,7 +40,7 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve
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. 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/registry.ts` + `src/commands/doctor/context.ts` — the doctor check registry (refactor wave 1, W4 doctor). `DOCTOR_CHECK_REGISTRY` lists 67 `DoctorEntry` records `{ name, emits, run(ctx) -> Promise<Check[] | STOP_DOCTOR> }` in output order; `runDoctorRegistry(ctx)` runs them, returns the checks gathered so far on `STOP_DOCTOR`, and otherwise finishes the DB-checks progress phase. The run is one `withGitListingCache` scope (`src/core/git-visible-files.ts`), so entries that list the same source checkout (frontmatter scan, fence census, slug collisions) share one `git ls-files` per listing and one "not a git repository" verdict per directory (`ls-files`, `discoverGitRoot`, the census HEAD probe; it lapses when a `.git` marker changes, and any repository-changing `sync-git.ts` command drops the scope's memo: `test/git-listing-memo.test.ts`). Execution groups: filesystem-first entries (the resolver-health entry applies `--fix` before it scans), the no-engine connection lane plus a STOP when `--fast` or no engine, the live connection entry plus a STOP when `getStats` failed, then the DB entries, which take the engine via `connectedEngine(ctx)`. `DoctorContext` carries the parsed flags (`jsonOutput`, `fastMode`, `doFix`, `dryRun`, `scope`, `orphanRatioSourceId`, `args`), `engine`, `dbSource`, `connectError`, `progress`, the skills-dir resolution and the cross-entry values `autoFixReport`, `schemaVersion`, `connectionFailed`, each written by the entry that computes it. Entry modules (one `run*` function per former `buildChecks` block, moved verbatim): `checks/skill-group.ts`, `local-runtime.ts`, `supervisor-health.ts`, `local-audits.ts`, `db-connection.ts` (also `pgbouncerPrepareCheck`, `classifiedConnectionCheck` 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/core-persistence-continued.md b/docs/architecture/key-files/core-persistence-continued.md
index 69a91f739d..7768c3277b 100644
--- a/docs/architecture/key-files/core-persistence-continued.md
+++ b/docs/architecture/key-files/core-persistence-continued.md
@@ -13,7 +13,7 @@ Managed connector ingestion, connector item holds, sync checkpoint validation an
- `src/core/fence-repair/{validate,validate-cells,page-checks}.ts` — #6188 the one gate every tier's output passes before a write: (a) compiles, (e) row count and containment, (b) claims, (c) existing row numbers, (d) visibility only tightens, (f) per-row cell preservation with rule-produced changes only, (g) nothing the privacy boundary hid is shown; gates (b), (c), (e) and (f) read the raw-row view. Before rows pair with after rows by primary-fence occurrence; when `ctx.issues` carries a `merge_fences` fix for a section and kind (#6377) the pairing is the merge mapping re-derived from the before page (`mergePlans`; a named merge the before page does not admit fails (e)): (e) requires the after count to equal the kept count and each dropped row to equal its kept row as written (`rowKey`), (b), (d) and (f) run per mapped row, (c) skips dropped rows and numbers used twice across every before fence, and (f) compares a merged row that carries `superseded by #N` as if written with the after number of its own before fence's row N (`withFollowedRef`); any other reference change is a changed cell. `isFenceFixedPoint` is E14. `page-checks.ts` holds `strictFailures` (gate a, the projection's three checks) and `exposedLines` (gate g). Tests: `test/fence-repair-validate.test.ts`, `test/fence-repair-merge.test.ts`.
- `src/core/fence-repair/{tier1,import-step,config,report}.ts` — #6188 Tier 1 on every write path. `fenceStep(page, ctx, { normalize })` is the step the coordinated screen, `importFromContent` and the append verbs share: no work beyond a marker substring check for a page with no fence, one shared scan when the fences compile, and `normalized` only when the validator passes and the output is a fixed point; otherwise `residual` with issues and the refusal location (`fenceIssuesWire` is the D18 `fence_issues` shape). `import-step.ts`: `applyImportFences` runs inside `importFromContent` before the remote hidden-row merge and withdrawal preservation (E7), reusing the screen's verdict unless hidden rows or a planned `renumber` need the database (stored rows load only then); `normalizeTargetFences` normalizes an append verb's target page or throws `target_fence_malformed` for a residual in its own fence kind; `normalizePageFences` serves synthesize verify. `config.ts`: `fences.normalize` (default on, read only when there is something to fix) and the model-repair caps `fences.repair.max_usd_per_page` (0.05) and `fences.repair.max_usd_per_day` (1.00), validated at `config set` as non-negative USD (0 = no model spend) and read by `readFenceRepairCaps` (stored value = a user cap). `report.ts`: the one `fences_normalized` shape (count, by_class, writers, sample paths for local callers, coaching fix), the `fence_normalized` coaching notice and the per-file import tally (`fence_issues` for lenient imports). Tests: `test/fence-write-verbs.test.ts`, `test/persistence-sync-fence-holds.test.ts`, `test/fence-normalize-overhead.slow.test.ts`.
- `src/core/fence-repair/hold-fix.ts` — #6188 (D16, D17, E35, Codex CEO #7) what an `invalid_fence` sync hold tells an agent (the OWNER list routes `owner_unavailable`, `owner_cli_required` and the #6278 owner conditions `host_mismatch`, `transfer_in_progress`, `clone_in_progress`, `incarnation_changed`, `local_path_missing`, `coordination_path_missing` to state `owner`). `readFenceAutoRepair` (two reads: `fences.repair.enabled`, `fences.repair.llm` and `autopilot.last_global_at` from `config`, plus the last completed `autopilot-global-maintenance` job) says whether the maintenance run repairs fences by itself (active within `FENCE_MAINTENANCE_ACTIVE_MS`, 24 h). `fenceHoldStatus` derives the state from the reason table and `meta.fence_repair`: `auto` (no action needed, the read-only preview), `apply` (preview, then apply), `manual` (manual-only reason, gate rejection or a model failure the run does not retry: the preview names the edit, then the sync), `paid` (`budget_exhausted`, `llm_disabled`, `no_pricing`: the exact config or `pricing set` command with consent `paid`), `owner` (the owner-host command, actor `host_admin`). `fenceHoldFix` is the local fix (`gbrain repair fences --source <id> --only <path>`), `fenceHoldRelay` the remote one (`tell_user_to_run`, no path), `fenceHoldLocation` the D16 object, `fenceFileLine` the file line of a section line. Location only. Tests: `test/fence-hold-surfaces.test.ts`, `test/sync-hold-surfaces.test.ts`.
-- `src/core/fence-repair/{census,census-store}.ts` — #6188 the fence census: discovery only, nothing repairs. `runFenceCensus(engine, { sourceIds, deadline, now })` advances per source (an even share of the deadline each): the stored-page scan (a one-time keyset backfill over `pages.id`, then incremental passes over `updated_at >= watermark`, where each new watermark is the previous pass's start minus the oldest open writer transaction in `pg_stat_activity` and `LATE_COMMIT_GRACE_MS`, so a transaction that committed after a later pass is still read) and, for a checkout, the working-tree walk (a full first walk of `isFrontmatterScannablePath` files via `collectGitVisibleFiles`/`walkDir`, then only `git diff <walked commit>` files, untracked files newer than the last walk, mtime for non-Git sources, and every stored file candidate). Both resume from cursors saved after every batch; a deadline leaves the census `partial`. `judgeFences` runs the coordinated `fenceStep` (normalization on): `deterministic` when Tier 1 fixes it, else the highest `FENCE_REASONS` tier of its residual reasons (`reasonTier`; manual-only or page-dependent counts as manual). `listFenceCandidates` dedupes by page slug across `invalid_fence` holds, stored pages and files (bucket hold > page > file; held-file tier from the walked file, else the hold reason), each bound to the judged bytes (page sha256/`updated_at`/`content_hash`, file sha256/mtime, hold `upstream_version`); `summarizeFenceCensus` counts per source by bucket and tier with the oldest hold and scan state. `census-store.ts`: `op_checkpoints` rows `fence-candidate` (one per source incarnation and slug, `page`/`file` parts), `fence-scan` (cursors and last census) and `fence-trend` (one row per sync run, keyed by run id: a managed run's total is rewritten in the same transaction as each cursor step that changes it, so the trend never differs from the cursor, and a legacy run writes its total when it ends; plus one row per normalized page write via `recordPublicationFenceTrend`, which the coordinator and group publication call inside the publication transaction and which skips per-file sync outcomes); candidate and scan rows survive the 7-day purge while their incarnation lives, trend rows age out. Location only: tiers, reasons, rows, columns, slugs and paths, never a cell value. Tests: `test/fence-census.test.ts` (+ `test/e2e/fence-census-postgres.test.ts`), `test/doctor-fence-integrity.test.ts`.
+- `src/core/fence-repair/{census,census-store}.ts` — #6188 the fence census: discovery only, nothing repairs. `runFenceCensus(engine, { sourceIds, deadline, now })` advances per source (an even share of the deadline each): the stored-page scan (a one-time keyset backfill over `pages.id`, then incremental passes over `updated_at >= watermark` ordered by `pages.updated_at, pages.id`, the indexed column the keyset compares, not the text alias, where each new watermark is the previous pass's start minus the oldest open writer transaction in `pg_stat_activity` and `LATE_COMMIT_GRACE_MS`, so a transaction that committed after a later pass is still read) and, for a checkout, the working-tree walk (a full first walk of `isFrontmatterScannablePath` files via `collectGitVisibleFiles`/`walkDir`, then only `git diff <walked commit>` files, untracked files newer than the last walk, mtime for non-Git sources, and every stored file candidate). Both resume from cursors saved after every batch; a deadline leaves the census `partial`. `judgeFences` runs the coordinated `fenceStep` (normalization on): `deterministic` when Tier 1 fixes it, else the highest `FENCE_REASONS` tier of its residual reasons (`reasonTier`; manual-only or page-dependent counts as manual). `listFenceCandidates` dedupes by page slug across `invalid_fence` holds, stored pages and files (bucket hold > page > file; held-file tier from the walked file, else the hold reason), each bound to the judged bytes (page sha256/`updated_at`/`content_hash`, file sha256/mtime, hold `upstream_version`); `summarizeFenceCensus` counts per source by bucket and tier with the oldest hold and scan state. `census-store.ts`: `op_checkpoints` rows `fence-candidate` (one per source incarnation and slug, `page`/`file` parts), `fence-scan` (cursors and last census) and `fence-trend` (one row per sync run, keyed by run id: a managed run's total is rewritten in the same transaction as each cursor step that changes it, so the trend never differs from the cursor, and a legacy run writes its total when it ends; plus one row per normalized page write via `recordPublicationFenceTrend`, which the coordinator and group publication call inside the publication transaction and which skips per-file sync outcomes); candidate and scan rows survive the 7-day purge while their incarnation lives, trend rows age out. Location only: tiers, reasons, rows, columns, slugs and paths, never a cell value. Tests: `test/fence-census.test.ts` (+ `test/e2e/fence-census-postgres.test.ts`), `test/doctor-fence-integrity.test.ts`, `test/doctor-hot-checks-golden.test.ts` (+ e2e twin: full doctor --json on a fixture hitting every fence, frontmatter and timeline finding).
- `src/core/fence-repair/{llm,repair-tiers}.ts` — #6188 Tier 2 and Tier 3 for one candidate. `analyzeFences`: Tier 1 (`safeNormalizeFences`, stored rows loaded only for `renumber`), Tier 2 (`resolveStrictEntityReference` without the same-name arm per `holder_unresolved` cell, only `people/`/`companies/` slugs, private pages excluded on a world page; hits feed `verifiedHolders`), then `proposal` (validated by gates (a)-(g) and a fixed point), `llm` (only `TIER3_REASONS` residuals left; a fence with stray text lines or no end marker is not eligible) or `manual`. `llm.ts`: `tier3Requests` (per fence: the header line and the residual rows, every row for a fence-level issue), `buildTier3Prompt` (schema, vocabulary, reason codes, page visibility, and rule 8: answer `HOLD` when a row has more than one reasonable reading; pinned by a prompt-bytes digest and `FENCE_REPAIR_PROMPT_VERSION`, 2), the layout (wide when the header names a wide column or, headerless, a row as written is wider than the narrow layout), `tier3TokenBudget` (the table's size plus `TIER3_REASONING_TOKENS` for a model whose reasoning the call cannot switch off, raised to the gateway's thinking headroom where the route has no switch: the estimate reserves what the gateway sends), `callTier3` (gateway `chat`, no tools, no fallback, thinking off; `llm_unavailable` when the provider throws, `llm_refused`, `llm_truncated` for any stop but a normal end, `llm_declined` for HOLD, `llm_malformed`/`llm_empty` from `extractSingleTable`, a wrong row count is a gate (e) failure), `spliceTier3` (rebuilds only that fence: canonical header, then every row in order with the sent rows replaced). `runTier3` claims the attempt (a rejected memo returns its verdict), checks the per-page cap and the run allowance, reserves on the daily ledger before each call (a refusal stops the run), settles actual tokens (an answerless call at its estimate), normalizes and validates the spliced page against the bytes as read, and re-asks once with the failed gate letter and rows only after a structural failure (gate (a) or (e)); any other gate or a HOLD is final and consumes the memo. `TIER3_REASONS` is the reason table's screen reasons of tier `llm`. Tests: `test/fence-repair-llm.test.ts`, `test/repair-fences.test.ts`.
- `src/core/fence-repair/llm-tail.ts` — #6377 (Lane A3) the Tier 3 request kind `tail`: when a fence has no end marker and lines follow its last row on a world-visible page, the model sees only the fence's begin line, header, every row and the trailing lines to the section end (never the rest of the page) and answers one JSON object `{"tail": "prose" | "rows" | "unsure"}` through the same gateway call, caps, daily ledger and attempt memo as the row requests (memo key: the fence region's sha256 + model + prompt version, so an unchanged tail never costs twice and a transient `llm_unavailable` does not consume it). `prose` makes the close previewable under the `tail_exposure_approval` reason (the preview prints the exact exposed lines and the hash binds them; unattended runs record `needs_human` with the paragraph and the `gbrain repair content --only <path> --apply --expect <hash>` command); `rows` and `unsure` render `unclosed_ambiguous_tail` (manual, the exact edit). On a private page the model is never called: `structure.ts` closes the fence after the last row deterministically (`trailing_lines` on the receipt), because the privacy boundary hides nothing from anyone there. Tests: `test/fence-repair-llm.test.ts`.
- `src/core/fence-repair/stray-cells.ts` — #6188 Tier 1 `stray_empty_cell` (`strayCellPass`, run by `normalizeFences` after the structural pass): in a balanced primary fence with a canonical header, a row with more cells than the layout loses empty cells (slot removed, every other byte kept) only when exactly one distinct deletion leaves every validated column valid; otherwise it stays `extra_cells`, now manual. In a fence with no header, `headerlessMisfit` reads a row that starts with a row number by position: a `kind` cell that is not a kind word is `claim_split`, a row wider than any layout with an invalid validated column is `extra_cells` (after the same empty-cell removal), and `content.ts` holds both as manual, so a claim an unescaped `|` cut never reaches Tier 3. `rules.ts` `kindWord` keeps facts `kind_map` to a kind word (at most three words, no sentence punctuation, link or strikethrough); other text is `claim_split` (manual), never a kind note. Tests: `test/fence-repair-normalize.test.ts`.
diff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.md
index 0842f32424..07a4aacd56 100644
--- a/docs/architecture/key-files/core-utilities-2.md
+++ b/docs/architecture/key-files/core-utilities-2.md
@@ -4,7 +4,7 @@ Memory trust tiers and read eligibility (#5575, the trust and eligibility direct
[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
-- `src/core/repair/` — `gbrain repair` core. `core.ts`: `resolveRepairScope` (default every active source; prints brain and source ids), `runRepair` (dry run unless `apply`; each item is one revision-bound `put_page` with a deterministic request id (replayed while pending, a new attempt id after a terminal failure), re-decided against current state just before it is applied; a cursor in `op_checkpoints` keyed by kind + scope resumes an interrupted or `--limit` run and is cleared when a scan completes; the same row carries the run id (written before the first applied item and passed to `apply` as `runId`), so a resumed run keeps the id that any authorization it granted is bound to; a kind may return a named per-item outcome (`RepairItemOutcome`), tallied in `outcomes` and `outcome_items`; a `spends: 'llm'` kind's plan reports `llm` (its paid-model estimate, null for an unpriced model under a user-set cap, and what is left under its own daily cap), and its result's `cost` adds `llm_usd` (the estimate on a dry run, the actual spend summed from each item's `llm_usd` on an apply) and `llm_cap_remaining_usd` (the smaller of the daily cap and the run allowance, less the spend), keys other kinds never carry; `maxLlmUsd` is the run's paid-model allowance: each item's `apply` gets what is left as `llmAllowanceUsd`, and once it is used up, or an item's own `llm_usd` estimate exceeds what is left, the run stops `budget_exhausted` before that item, naming spent and allowance, and rerunning the apply command resumes it (a dry run sums the per-item estimates of the items it would apply, so `--limit` lowers it); the core opens no budget tracker; `deadline` (epoch ms) stops the run with `time_budget` before the next item; an item outcome's `stop` ends the run after that item with its reason, message and fix; a kind's `report` hook adds `repaired`, `remaining`, `verification` (or refines `stopped`) once the run ends, and a plan's `scan` is copied to the result; stops before crossing 90% of the brain or principal lifetime-ID / receipt-byte caps with the `gbrain config set` value that finishes; a held writer stops with `gbrain sources writer status <source>`). `timeline.ts`: `scanTimelineHistory` (bounded id-order scan shared with the doctor) and the materialize kind. `visibility.ts`: `planVisibilityRepair`, the tighten-only atom/concept backfill (atoms from `effectiveVisibility` of their origin, concepts from the strictest input over provenance edges and atoms' `concepts:`; no-lineage concepts are counted and left alone). `safe-chunks.ts`: a `publication: 'projection'` kind (no admission, zero lifetime-ID and receipt cost, no capacity stop) that re-seals markdown and code pages below the safe-chunk fence through `resealSafeChunks`, then embeds their NULL chunks unless `--no-embed`; code pages without a recorded path and other page kinds are residuals. The pending count is reported only by the doctor check `safe_index_pending`, which the post-upgrade recovery banner uses. `contextual-mode.ts`: a `publication: 'projection'` kind (#5621) that stamps `contextual_retrieval_mode` + `corpus_generation` on sealed live markdown pages with a NULL mode through `resolveImportContextualMode` (`src/core/import-contextual-mode.ts`, the resolver `importFromContent` also uses, strict source-row read), then under the page guard clears only vectors whose recorded embedding input the stamped convention no longer accepts (the #5553 rule) and re-embeds that page once unless `--no-embed`; unsealed pages are the `unsealed_projection` residual. `connector-checkpoints.ts`: a `publication: 'projection'` bookkeeping kind (#5686, `embeds: false`) that deletes connector checkpoint rows and retry pointers no registered source can load and that are older than 7 days, keeping rows a non-terminal request or recorded pending set references; brain-wide. `request-indexes.ts`: a `publication: 'projection'` brain-wide kind (#5762, `embeds: false`) that builds a missing managed sync request index or drops an INVALID one and rebuilds it through `buildIndexOnline` (`src/core/schema-migrations/helpers.ts`: CONCURRENTLY on Postgres under the session's startup timeouts with no session SET, inline on PGLite, the result re-checked for validity, an index another session is still building is left alone); it clears `persistence_request_indexes`. `orphan-bindings.ts`: a projection bookkeeping kind (#5732) over `persistence/orphan-bindings.ts` that deletes persistence source bindings of a removed source or an earlier incarnation, brain-wide, keeping one a pending request of that incarnation references. `embedding-effects.ts`: a projection kind (#5629/#5734, `embeds: 'effect'`) over `persistence/embedding-settlement.ts`; each stale queued or failed embedding effect of a committed write is `reconciled` (the effect projection verifier passes), `superseded` (page deleted, or a newer revision of the same page owns its own effect), `retry_queued` (stale queued re-queued for the owner; failed granted the retry-effects allowance; an exhausted allowance gets one new bounded cycle under `embeddingGrantId(runId, effect)`, which a resumed run replays) or `blocked` with a reason; every change is a compare-and-set on state, attempts, execution token and recovery, and a changed candidate is `changed_since_preview`. Retry items count the whole retry budget in the embedding estimate. `registry.ts`: `REPAIR_REGISTRY` (one entry per `REPAIR_KINDS` name in `--all` order: handler, help summary, `embeds` — `effect` when the publication's embedding effect re-embeds each page outside the run, `inline` when the kind embeds in-process and honors `--no-embed`, `none` for bookkeeping kinds — `spends: 'llm'` for a kind that may call a paid chat model, and the doctor `checks` it clears), `repairMayEmbed` (embedding spend under the flags) and `repairMaySpend` (that or `spends: 'llm'`), `repairForCheck`, `repairApplyCommand` and `repairRunner`, the one trusted local runner that both `gbrain repair` and doctor remediation use (an applying runner resolves the CLI write wait once, before any kind runs, and puts it on the ctx as `writeWaitMs`, so every publication waits like other CLI writes and a malformed `GBRAIN_WRITE_WAIT_MS` refuses before a checkpoint; a preview never reads it) (its `run` takes `maxLlmUsd`; `repairRunner` and `repairSpec` take an optional `registry` of stub specs for tests, and production callers use the registered kinds); a new kind plugs in by adding its name to `REPAIR_KINDS` and one registry entry. A kind with `explicit_only` (`stale-atoms`, `extractor-facts`; the `extractor-facts.ts` stub refuses with `unavailable` until its fix wave 5 lane lands) runs only when named: `AUTO_REPAIR_REGISTRY` is the `--all`, no-kind and remediation set, `explicitRepairNotices` lists the rest as `explicit_kind_required` with `repairPreviewCommand`, and `runRepair` refuses an unnamed explicit-only kind (`explicitKindRequired`), so a supplied remediation step cannot run one. Explicit-only kinds and kinds with `preview_bound` (`fences`, which is not explicit-only and so also runs from `--all`, the remediation run and the maintenance cycle with a bare `--apply`) accept `--expect <hash>`; only explicit-only kinds accept `--include-ambiguous`; `--only`/`--skip`/`--slug` selections, `--no-llm` and `--max-usd` (only `spends: 'llm'` kinds; it only lowers their cap) are passed to `plan` as `RepairPlanOptions` and printed in the apply command; a plan's `preview_hash` is appended to its apply command, and its `listing` (every previewed item with its class) is printed by the dry run. `stale-atoms.ts` (#5770): live page-bound atoms (never `imported_from`, never `source_path`-only) whose source page is gone (`origin_gone`) or whose stripped 16-character `source_hash` differs from a source page that already completed an extraction at its current hash (`origin_changed`; managed evidence is the completed `managed-atoms` checkpoint via `managedAtomCompletedSql`, unmanaged evidence a non-managed atom at that hash). The preview saves the set with `saveApprovedSet`; `--apply --expect <hash>` loads it (`preview_changed` otherwise; `--apply` alone refuses with the filled commands), rechecks each atom (revision, class, origin, evidence) and reports `retired`, `changed_since_preview` or `file_conflict` (an uncoordinated edit of the atom file; its attempt-aware `repairRequestId` lets a later apply retry once the file is fixed). An approved set applies only under the source selection it was previewed with, and the apply's resume cursor is keyed by its approval hash. Managed brains admit one `managed_maintenance_retire_stale_atoms` request per atom bound to its revision (`prepareStaleAtomRetirement`, rechecked under the atom and origin page locks, no live origin needed); unmanaged brains soft-delete in one locked transaction. Both stamp `retired_by: stale-atoms`/`retired_at` and bump the origin page's `managed-atoms-generation` (clearing its page state and completed checkpoints, keeping the current hash for `origin_changed`), so a restored page is extracted again and `publishManagedAtoms` restores the retired atoms. Tests: `test/repair-explicit-only.test.ts`, `test/repair-stale-atoms.test.ts` and `test/journey-atoms-sync-race.test.ts` (PGLite and Postgres). Tests: `test/repair-command.test.ts`, `test/derived-visibility-repair.test.ts`, `test/safe-chunk-reseal.test.ts` (PGLite and Postgres), `test/repair-contextual-mode-5621.serial.test.ts` (PGLite and Postgres), `test/repair-flags.test.ts`, `test/persistence-request-indexes.test.ts`. `attribution-backfill.ts` (Foundations 1, F1b): an automatic `publication: 'projection'` bookkeeping kind (`embeds: 'none'`, no doctor check) that fills NULL write attribution only where exactly one committed request proves it: `pages.revision_*` and `page_versions.write_*` from the page mutation (or fenced `remember`) whose `outcome.revision` is the row's `knowledge_revision` (skipped, duplicate and observe-only requests prove nothing), and `facts.write_*` from the `remember` whose `outcome.id` names the fact with status `inserted` or `superseded`. The preview proofs and each batch run inside a short transaction with `enable_nestloop` off (the journal join on the outcome key has no index, and fresh attribution columns have no statistics), restoring the caller's setting before it ends. Items are batches of up to 1,000 ids per table in (table, id) cursor order; each batch re-runs the proof under `lockPageKeys` for its pages and commits on its own, so an interrupted run resumes after the last committed batch. Unproven NULL rows are the `unrecorded_<table>` residuals. Test: `test/write-attribution-read.test.ts`. `google-file-modes.ts`: an explicit-only (`explicit_only: true`), `publication: 'projection'` filesystem-only kind (`embeds: false`, no admission, no request ids) that plans one item per loose entry from `scanGoogleFileModes` (cursor phase = source index; the item carries root, relative path, kind and old mode) and applies `tightenGoogleEntry` (outcomes `tightened`, `already_private`, `skipped` with a reason); symlink, foreign-owner and wrong-type entries are `skipped_*` residuals. It is last in `REPAIR_KINDS`, so `--all` runs it after `embedding-effects`; registry check `google_file_modes`. Every run re-scans, so a rerun after `--limit` picks up exactly what is still loose.
+- `src/core/repair/` — `gbrain repair` core. `core.ts`: `resolveRepairScope` (default every active source; prints brain and source ids), `runRepair` (dry run unless `apply`; each item is one revision-bound `put_page` with a deterministic request id (replayed while pending, a new attempt id after a terminal failure), re-decided against current state just before it is applied; a cursor in `op_checkpoints` keyed by kind + scope resumes an interrupted or `--limit` run and is cleared when a scan completes; the same row carries the run id (written before the first applied item and passed to `apply` as `runId`), so a resumed run keeps the id that any authorization it granted is bound to; a kind may return a named per-item outcome (`RepairItemOutcome`), tallied in `outcomes` and `outcome_items`; a `spends: 'llm'` kind's plan reports `llm` (its paid-model estimate, null for an unpriced model under a user-set cap, and what is left under its own daily cap), and its result's `cost` adds `llm_usd` (the estimate on a dry run, the actual spend summed from each item's `llm_usd` on an apply) and `llm_cap_remaining_usd` (the smaller of the daily cap and the run allowance, less the spend), keys other kinds never carry; `maxLlmUsd` is the run's paid-model allowance: each item's `apply` gets what is left as `llmAllowanceUsd`, and once it is used up, or an item's own `llm_usd` estimate exceeds what is left, the run stops `budget_exhausted` before that item, naming spent and allowance, and rerunning the apply command resumes it (a dry run sums the per-item estimates of the items it would apply, so `--limit` lowers it); the core opens no budget tracker; `deadline` (epoch ms) stops the run with `time_budget` before the next item; an item outcome's `stop` ends the run after that item with its reason, message and fix; a kind's `report` hook adds `repaired`, `remaining`, `verification` (or refines `stopped`) once the run ends, and a plan's `scan` is copied to the result; stops before crossing 90% of the brain or principal lifetime-ID / receipt-byte caps with the `gbrain config set` value that finishes; a held writer stops with `gbrain sources writer status <source>`). `timeline.ts`: `scanTimelineHistory` (bounded id-order scan shared with the doctor; one stored-row read per page batch for the retraction check) and the materialize kind. `visibility.ts`: `planVisibilityRepair`, the tighten-only atom/concept backfill (atoms from `effectiveVisibility` of their origin, concepts from the strictest input over provenance edges and atoms' `concepts:`; no-lineage concepts are counted and left alone). `safe-chunks.ts`: a `publication: 'projection'` kind (no admission, zero lifetime-ID and receipt cost, no capacity stop) that re-seals markdown and code pages below the safe-chunk fence through `resealSafeChunks`, then embeds their NULL chunks unless `--no-embed`; code pages without a recorded path and other page kinds are residuals. The pending count is reported only by the doctor check `safe_index_pending`, which the post-upgrade recovery banner uses. `contextual-mode.ts`: a `publication: 'projection'` kind (#5621) that stamps `contextual_retrieval_mode` + `corpus_generation` on sealed live markdown pages with a NULL mode through `resolveImportContextualMode` (`src/core/import-contextual-mode.ts`, the resolver `importFromContent` also uses, strict source-row read), then under the page guard clears only vectors whose recorded embedding input the stamped convention no longer accepts (the #5553 rule) and re-embeds that page once unless `--no-embed`; unsealed pages are the `unsealed_projection` residual. `connector-checkpoints.ts`: a `publication: 'projection'` bookkeeping kind (#5686, `embeds: false`) that deletes connector checkpoint rows and retry pointers no registered source can load and that are older than 7 days, keeping rows a non-terminal request or recorded pending set references; brain-wide. `request-indexes.ts`: a `publication: 'projection'` brain-wide kind (#5762, `embeds: false`) that builds a missing managed sync request index or drops an INVALID one and rebuilds it through `buildIndexOnline` (`src/core/schema-migrations/helpers.ts`: CONCURRENTLY on Postgres under the session's startup timeouts with no session SET, inline on PGLite, the result re-checked for validity, an index another session is still building is left alone); it clears `persistence_request_indexes`. `orphan-bindings.ts`: a projection bookkeeping kind (#5732) over `persistence/orphan-bindings.ts` that deletes persistence source bindings of a removed source or an earlier incarnation, brain-wide, keeping one a pending request of that incarnation references. `embedding-effects.ts`: a projection kind (#5629/#5734, `embeds: 'effect'`) over `persistence/embedding-settlement.ts`; each stale queued or failed embedding effect of a committed write is `reconciled` (the effect projection verifier passes), `superseded` (page deleted, or a newer revision of the same page owns its own effect), `retry_queued` (stale queued re-queued for the owner; failed granted the retry-effects allowance; an exhausted allowance gets one new bounded cycle under `embeddingGrantId(runId, effect)`, which a resumed run replays) or `blocked` with a reason; every change is a compare-and-set on state, attempts, execution token and recovery, and a changed candidate is `changed_since_preview`. Retry items count the whole retry budget in the embedding estimate. `registry.ts`: `REPAIR_REGISTRY` (one entry per `REPAIR_KINDS` name in `--all` order: handler, help summary, `embeds` — `effect` when the publication's embedding effect re-embeds each page outside the run, `inline` when the kind embeds in-process and honors `--no-embed`, `none` for bookkeeping kinds — `spends: 'llm'` for a kind that may call a paid chat model, and the doctor `checks` it clears), `repairMayEmbed` (embedding spend under the flags) and `repairMaySpend` (that or `spends: 'llm'`), `repairForCheck`, `repairApplyCommand` and `repairRunner`, the one trusted local runner that both `gbrain repair` and doctor remediation use (an applying runner resolves the CLI write wait once, before any kind runs, and puts it on the ctx as `writeWaitMs`, so every publication waits like other CLI writes and a malformed `GBRAIN_WRITE_WAIT_MS` refuses before a checkpoint; a preview never reads it) (its `run` takes `maxLlmUsd`; `repairRunner` and `repairSpec` take an optional `registry` of stub specs for tests, and production callers use the registered kinds); a new kind plugs in by adding its name to `REPAIR_KINDS` and one registry entry. A kind with `explicit_only` (`stale-atoms`, `extractor-facts`; the `extractor-facts.ts` stub refuses with `unavailable` until its fix wave 5 lane lands) runs only when named: `AUTO_REPAIR_REGISTRY` is the `--all`, no-kind and remediation set, `explicitRepairNotices` lists the rest as `explicit_kind_required` with `repairPreviewCommand`, and `runRepair` refuses an unnamed explicit-only kind (`explicitKindRequired`), so a supplied remediation step cannot run one. Explicit-only kinds and kinds with `preview_bound` (`fences`, which is not explicit-only and so also runs from `--all`, the remediation run and the maintenance cycle with a bare `--apply`) accept `--expect <hash>`; only explicit-only kinds accept `--include-ambiguous`; `--only`/`--skip`/`--slug` selections, `--no-llm` and `--max-usd` (only `spends: 'llm'` kinds; it only lowers their cap) are passed to `plan` as `RepairPlanOptions` and printed in the apply command; a plan's `preview_hash` is appended to its apply command, and its `listing` (every previewed item with its class) is printed by the dry run. `stale-atoms.ts` (#5770): live page-bound atoms (never `imported_from`, never `source_path`-only) whose source page is gone (`origin_gone`) or whose stripped 16-character `source_hash` differs from a source page that already completed an extraction at its current hash (`origin_changed`; managed evidence is the completed `managed-atoms` checkpoint via `managedAtomCompletedSql`, unmanaged evidence a non-managed atom at that hash). The preview saves the set with `saveApprovedSet`; `--apply --expect <hash>` loads it (`preview_changed` otherwise; `--apply` alone refuses with the filled commands), rechecks each atom (revision, class, origin, evidence) and reports `retired`, `changed_since_preview` or `file_conflict` (an uncoordinated edit of the atom file; its attempt-aware `repairRequestId` lets a later apply retry once the file is fixed). An approved set applies only under the source selection it was previewed with, and the apply's resume cursor is keyed by its approval hash. Managed brains admit one `managed_maintenance_retire_stale_atoms` request per atom bound to its revision (`prepareStaleAtomRetirement`, rechecked under the atom and origin page locks, no live origin needed); unmanaged brains soft-delete in one locked transaction. Both stamp `retired_by: stale-atoms`/`retired_at` and bump the origin page's `managed-atoms-generation` (clearing its page state and completed checkpoints, keeping the current hash for `origin_changed`), so a restored page is extracted again and `publishManagedAtoms` restores the retired atoms. Tests: `test/repair-explicit-only.test.ts`, `test/repair-stale-atoms.test.ts` and `test/journey-atoms-sync-race.test.ts` (PGLite and Postgres). Tests: `test/repair-command.test.ts`, `test/derived-visibility-repair.test.ts`, `test/safe-chunk-reseal.test.ts` (PGLite and Postgres), `test/repair-contextual-mode-5621.serial.test.ts` (PGLite and Postgres), `test/repair-flags.test.ts`, `test/persistence-request-indexes.test.ts`. `attribution-backfill.ts` (Foundations 1, F1b): an automatic `publication: 'projection'` bookkeeping kind (`embeds: 'none'`, no doctor check) that fills NULL write attribution only where exactly one committed request proves it: `pages.revision_*` and `page_versions.write_*` from the page mutation (or fenced `remember`) whose `outcome.revision` is the row's `knowledge_revision` (skipped, duplicate and observe-only requests prove nothing), and `facts.write_*` from the `remember` whose `outcome.id` names the fact with status `inserted` or `superseded`. The preview proofs and each batch run inside a short transaction with `enable_nestloop` off (the journal join on the outcome key has no index, and fresh attribution columns have no statistics), restoring the caller's setting before it ends. Items are batches of up to 1,000 ids per table in (table, id) cursor order; each batch re-runs the proof under `lockPageKeys` for its pages and commits on its own, so an interrupted run resumes after the last committed batch. Unproven NULL rows are the `unrecorded_<table>` residuals. Test: `test/write-attribution-read.test.ts`. `google-file-modes.ts`: an explicit-only (`explicit_only: true`), `publication: 'projection'` filesystem-only kind (`embeds: false`, no admission, no request ids) that plans one item per loose entry from `scanGoogleFileModes` (cursor phase = source index; the item carries root, relative path, kind and old mode) and applies `tightenGoogleEntry` (outcomes `tightened`, `already_private`, `skipped` with a reason); symlink, foreign-owner and wrong-type entries are `skipped_*` residuals. It is last in `REPAIR_KINDS`, so `--all` runs it after `embedding-effects`; registry check `google_file_modes`. Every run re-scans, so a rerun after `--limit` picks up exactly what is still loose.
- `src/core/rerank-audit.ts` — failure-only JSONL audit at `~/.gbrain/audit/rerank-failures-YYYY-Www.jsonl` (ISO-week rotation, mirrors `src/core/audit-slug-fallback.ts`). Exports `logRerankFailure({reason, model, query_hash, doc_count, error_summary})` + `readRecentRerankFailures(days)`. The `no_key` reason is written ONCE per process per model by the gateway itself (not per query by `applyReranker`): the provider key is absent, so calls are skipped without HTTP and results pass through unreranked; `auth` means key present but rejected. Deliberately no `logRerankSuccess`: writing once per tokenmax search is hot-path I/O churn AND success events leak query volume + timing into a local audit file. `gbrain doctor`'s `reranker_health` check (`doctor/checks/calibration.ts`) resolves enablement + model through `resolveSearchMode(loadSearchModeConfig)` — the plane search reranks with — and `rerankerReadiness` before reading the audit: readiness is evaluated against the DB-merged config plane (`loadConfigWithEngine`, so DB-plane provider keys and `provider_base_urls` self-host overrides count, exactly like the gateway the CLI configures): a brain with NO embedding provider (`isAvailable('embedding')` false on a configured gateway) is `ok` even when not ready — search runs keyword-only there and never reaches `applyReranker`, so there is nothing to fix; otherwise enabled-but-not-ready (key absent / unknown model) warns with the paste-ready fix; only audit rows for the RESOLVED model count (rows for any other model never make the live default warn or send the operator to verify the wrong key); `no_key` skip rows are informational once ready (those processes ran unreranked; a long-lived worker started before the key was added keeps skipping until restarted) and never outlive the fix as a warn; then the auth / payload / budget / transient / unknown ladders on the non-skip rows; disabled → ok (with an enable hint when the default is ready). Query text SHA-256-prefix-hashed (8 hex chars) for privacy. `GBRAIN_AUDIT_DIR` env override honored via the shared `resolveAuditDir()`.
- `src/core/repair/extractor-facts.ts` — `gbrain repair extractor-facts` (#5731), explicit-only and preview-bound. `classifyExtractorFacts` (read-only; also the doctor check's count) takes conversation-extractor facts with `expired_at` set and `row_num` NULL and classes each: `excluded` (page missing or deleted, `superseded_by` set, withdrawn, an active same-text fact on the page, or an earlier same-text candidate), `ambiguous` (unmanaged brain; no committed request of the page with `completed_at = expired_at`, compared in SQL as microsecond UTC text, which only a same-transaction completion satisfies on Postgres; a consumer at or above v0.60.11.0; or the page has ever held fence-projected facts) or `evidenced`. The preview lists every candidate, hashes them with the selection (`--include-ambiguous`) and saves one approved item per page (with its request id) through `preview-approval.ts`; the apply loads only that set, replays a still-pending request with the ctx's CLI write wait, skips pages whose request already committed or whose facts are active again, and restores each still-identical fact with a fresh `row_num` above the page's facts and fence rows. Managed brains publish one database-only `managed_maintenance_restore_extractor_facts` request per page (`submitDatabaseMaintenanceIntent`, dispatched by `prepareMaintenanceMutation` to `prepareExtractorFactsRestore`, which reclassifies under the page lock); unmanaged brains run the same restore in one locked transaction. Previews warn, naming the host, when a consumer older than this release published after `writer_version_cutoff`. On PGLite `now()` has millisecond resolution, so the same-transaction rule is millisecond-exact there.
- `src/core/repair/conversation-labels.ts` — `gbrain repair conversation-labels`, explicit-only, preview-bound and destructive (consent payload from the registry's `consentText`). `classifyLabelFacts` (read-only) takes active per-segment extractor facts (`source` exactly `cli:extract-conversation-facts`) on live pages with a bold `METADATA_LABELS` line and classes each `excluded` (page outcome stamped with `extractor_version`, withdrawn, superseded, named by another fact's `superseded_by`, referenced by `open_loops.fact_id`), `evidenced` (context carries `segment 1970-01-01`) or `ambiguous`. The preview decides each page's outcome with the current parser at no cost (`non_extractable`, `awaiting_reextraction`, `cleaned`), hashes it all, saves one approved item per page and prints the capped hand-off (`extract-conversation-facts --slugs … --dry-run`, then `--max-cost-usd`). The apply expires the approved ids still as previewed (appending `retired: conversation-labels <hash>` to the context), expires the completion marker and writes the stamped not-extractable outcome for a page still at the previewed parser input; approved pages apply in batches of `LABEL_BATCH_PAGES` (25): one database-only `managed_maintenance_conversation_label_retire` request per batch on `LABELS_ANCHOR_SLUG` on a managed brain (`prepareConversationLabelRetirement`, every page key locked, each page rechecked), one transaction per batch otherwise. No model calls. `countLabelFacts` is doctor `conversation_label_facts`' bounded count. Pinned by `test/repair-conversation-labels.test.ts` (+ Postgres arm) and `test/conversation-facts-retained-history.test.ts`.