Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(doctor): revision_backfill reports the page revision backfill with a resume command that works (#5216)

garrytan5e9b481c0adb
diff --git a/TODOS.md b/TODOS.md
index 20131ec15c..3f6fd77c4c 100644
--- a/TODOS.md
+++ b/TODOS.md
@@ -124,7 +124,7 @@ Spec: `docs/designs/AGENT_OPERATOR_WAVE.md` (Deferred list). Contract: `docs/pro
**What:** facts without a fence row number are invisible to the fence reconciler. **Fix:** the cycle fences them after GBRA-35's facts writeback (now on master). **Effort:** M. **Priority:** P2 (Foundations 2).
- [x] **P2 — One-shot repair for supersession chains broken on managed brains (#5886).** **Completed** — `gbrain repair take-supersession` (preview, then `--apply`) relinks each struck take from journal, stored-pointer or forced fence-structure evidence and reports ambiguous pages with the manual edit.
**What:** v0.60.36.0 writes the supersession pointer on the old take row; chains written before it keep `superseded_by` NULL on managed brains. **Fix:** a `gbrain repair` kind that rebuilds the pointers from the fence. **Effort:** S. **Priority:** P2.
-- [ ] **P2 — Doctor check for pages still waiting on their revision backfill (#5216).**
+- [x] **P2 — Doctor check for pages still waiting on their revision backfill (#5216).** **Completed** — doctor `revision_backfill` warns with the pending count, the failed rows by page and `gbrain apply-migrations --force-schema`, which resumes the backfill (managed brains included).
**What:** the backfill is resumable and reports progress on upgrade, but a brain whose backfill keeps stopping on a failing row has no standing doctor signal. **Effort:** S. **Priority:** P2.
- [x] **P2 — Scale harness gaps (`bun run test:scale`).** Shipped in v0.60.37.0 (F4c scale tier).
**What:** the report-only harness lacks injected query vectors, populated facts and takes, a source-scoped grant query, a cold-process first query, concurrent receipt-bearing writers, the Postgres engine and the 10k/20k/50k CI tiers. At 10k pages the per-page import cost of the last 10% is about 8x the first 10% (gate 1.5). **Effort:** L. **Priority:** P2 (Foundations 1, F4).
diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.md
index 09263e3a75..87d3d04d65 100644
--- a/docs/architecture/key-files/commands-2.md
+++ b/docs/architecture/key-files/commands-2.md
@@ -9,6 +9,7 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve
- `src/commands/doctor/checks/persistence-requests.ts` — two wave checks (OPS, registered in `wave-checks.ts`). `persistence_request_indexes` (#5762) reports each managed sync request index missing, INVALID or still building (with progress) and names `gbrain repair request-indexes --apply`. `persistence_request_growth` reports the request-table row count (a `reltuples` estimate on Postgres), each scope's admission rate over the last 7 days (the newest 10,000 admissions per scope, one bounded index read), lifetime IDs against `persistence.limits.*` and the projected exhaustion date within ten years; it warns under 90 days with the `oneYearCapacity` `gbrain config set` value and the doctor re-check. Tests: `test/persistence-request-indexes.test.ts`, `test/e2e/persistence-request-indexes-postgres.test.ts`.
- `src/commands/doctor/checks/{persistence-capacity,parked-effects}.ts` — `persistence_capacity` (OPS) warns when a principal or the brain reaches 80% of permanent request IDs or receipt bytes (via `capacityDiagnostics`) and prints one `gbrain config set <key> <value>` per brain-wide key, using the largest value any scope needs for about one more year; transient caps never warn. `parked_effects` (BRAIN) reads the partial parked-effect index, counts exactly, samples 20, and names each parked page with its `retry-effects ... --dry-run` command. Both report `exact`/`inspected`/`truncated` details; an unreadable state is warn, never clean. Tests: `test/persistence-capacity.test.ts`, `test/persistence-effect-parking.test.ts`.
- `src/commands/doctor/checks/unbound-source.ts` — `unbound_source` (#5254) counts live pages with `pages.database_only_reason='unbound_source'` per source. While the source is unbound the count is ok and the message carries the filled `sources writer status`/`writer claim` bind command (database-only is the chosen mode); once the source has a binding it warns, because binding never materializes those pages into canonical files. Unreadable state warns. Registered on the `persistence_capacity` line in `doctor.ts`. Test: `test/e2e/unbound-source-postgres.test.ts`.
+- `src/commands/doctor/checks/revision-backfill.ts` — `revision_backfill` (#5216, META, registered before `search_mode`): reads `readRevisionBackfillStatus` (column state, pages still without `knowledge_revision`, failed rows still pending with their page). ok when the column is NOT NULL; warn with the pending count and `gbrain apply-migrations --force-schema` as `fix` while any row is resumable (or only the NOT NULL step remains); failed rows are listed by page id, `source:slug`, attempt and error, and when only rows with spent attempts remain the `fix` is the read-only `gbrain repair orphan-children` preview. Tests: `test/doctor-revision-backfill.test.ts`.
- `src/commands/doctor/checks/extractor-facts.ts` — `extractor_facts_expired` (#5731): counts conversation-extractor facts the pre-v0.60.11.0 projection expired, by class (`evidenced`, `ambiguous`; `excluded` reported but never a finding) through `classifyExtractorFacts`, and names `gbrain repair extractor-facts` (explicit-only, so the remediation plan and banner list it with its preview). Read-only; health unknown when the query fails.
- `src/commands/doctor/checks/captured-facts.ts` — `captured_facts_active` (wave check, host-only): counts active capture-lane facts (`hook:writeback`, `hook:compact`, `sweep:corpus`) that `classifyCapturedFacts` classes as self-capture (`evidenced`) or paste candidates (`ambiguous`); `excluded` and `unclassifiable` are reported, never a finding. Names `gbrain repair captured-facts` (explicit-only) and says it counts facts while `self_capture` counts corpus files. Read-only; health unknown when the scan fails.
- `src/commands/doctor/checks/loop-facts.ts` — `loop_facts_drift` (#5869): counts closed commitment loops whose fact is still active and retirable (`loopFactDrift`) and names `gbrain repair loop-facts` (explicit-only). Read-only; health unknown when the query fails.
diff --git a/docs/architecture/key-files/engines-1.md b/docs/architecture/key-files/engines-1.md
index 450ccf0dee..dbfad9437e 100644
--- a/docs/architecture/key-files/engines-1.md
+++ b/docs/architecture/key-files/engines-1.md
@@ -29,7 +29,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/engine.ts` — Pluggable engine interface (BrainEngine). `clampSearchLimit(limit, default, cap)` takes an explicit cap so per-operation caps can be tighter than `MAX_SEARCH_LIMIT`. Exports `LinkBatchInput`/`TimelineBatchInput` for the bulk-insert API (`addLinksBatch`/`addTimelineEntriesBatch`). `readonly kind: 'postgres' | 'pglite'` discriminator lets `src/core/migrate.ts` and others branch without `instanceof` + dynamic imports. Methods: `batchLoadEmotionalInputs(slugs?)` (CTE-shaped read with per-table aggregates so page × N tags × M takes never produces N×M rows), `setEmotionalWeightBatch(rows)` (`UPDATE FROM unnest($1::text[],$2::text[],$3::real[])` composite-keyed on `(slug, source_id)`), `getRecentSalience(opts)`, `findAnomalies(opts)`. `PageFilters` has `sort?: 'updated_desc'|'updated_asc'|'created_desc'|'slug'` + `PAGE_SORT_SQL` whitelist consumed by both engines. `listAllPageRefs(): Promise<Array<{slug, source_id}>>` ordered by `(source_id, slug)` — cheap cross-source enumeration instead of a `getAllSlugs()→getPage(slug)` N+1 (which would silently default to `source_id='default'`); parity across postgres-engine.ts + pglite-engine.ts; Pinned by `test/e2e/multi-source-bug-class.test.ts`. `SearchOpts`+`PageFilters` add `sourceIds?: string[]` (federated read axis; both engines apply `WHERE source_id = ANY($N::text[])` when set, preserve scalar `sourceId` fast path when unset); `traverseGraph(slug, depth, opts?)` and `traversePaths(slug, opts?)` accept `opts.sourceId`/`opts.sourceIds`. `traversePathsDetailed(slug, opts?)` returns `{ paths: GraphPath[], truncated }` — the final SELECT of the path-enumerating recursive CTE is bounded at `TRAVERSE_PATH_ROW_CAP + 1` rows on both engines (the probe row signals overflow; `ORDER BY depth` means the deepest edges are dropped, so a truncated result is still the complete shallow neighbourhood; the cap counts raw rows before the in-memory edge dedup, so `paths.length` alone cannot reveal truncation) and `traversePaths` is its `.paths` projection. Each `GraphPath` carries `from_source_id`/`to_source_id` and the edge dedup keys on page ids; each `traverseGraph` `GraphNode` carries `source_id` (DISTINCT per page), so the same slug in two sources stays two edges or nodes. `resolveSlugWithAliasDetailed(slug, sourceOrSources)` returns `{ canonical_slug, source_id } | null` — the winning alias row AND its owning source under the same scope/precedence rules (`ORDER BY array_position(scope, source_id), id`; null when nothing matches or the `slug_aliases` table does not exist yet); `resolveSlugWithAlias` is its canonical-slug projection (falls back to the input slug). A consumer that goes on to read the canonical page must scope that read to `source_id`. The by-slug read methods carry the same federated axis: `getTags`/`getLinks`/`getBacklinks`/`getChunks` opts and `TimelineOpts` (consumed by `getTimeline`) accept `sourceIds?: string[]` taking precedence over the scalar `sourceId` (`source_id = ANY($::text[])` scoping the slug→page-id lookup); `getChunks` falls back to the `'default'` source when neither is set (importCodeFile's incremental-embedding reuse relies on it) and SELECTs an explicit non-vector column list — embedding vectors never ride the payload since rowToChunk discards them (`getChunksWithEmbeddings` stays scalar-only by design: engine-internal, zero remote-reachable callers); the link reads (`getLinks`/`getBacklinks`) scope ALL THREE endpoints (from/to/origin) on the federated branch while the scalar branch scopes only the near endpoint for trusted internal cross-source callers. `traverseGraph` opts has `frontierCap?: number` (per-iteration recursive-CTE cap, approx per-BFS-layer); return type `Promise<GraphNode[]>` for MCP wire stability; export `TraverseGraphOpts`; Postgres uses parenthesized `LIMIT N ORDER BY (slug, id)` inside the recursive term, PGLite mirrors with positional params; Pinned by `test/regressions/v0_36_frontier_cap.test.ts`. Phantom-redirect methods: `refreshPageBody(slug, sourceId, compiled_truth, timeline, content_hash)` narrow-UPDATEs three columns + updated_at, skipping soft-deleted rows (content_hash refresh required so `gbrain sync` sees the canonical as unchanged after fence merge); `migrateFactsToCanonical(phantomSlug, canonicalSlug, sourceId)` UPDATEs `entity_slug`+`source_markdown_slug` on every active fact row keyed on the phantom, preserving embedding/validUntil/kind/status/source_session/confidence and offsetting `row_num` past the canonical page's current MAX(row_num) (all rows incl. expired — the partial `idx_facts_fence_key` only excludes NULL; NULL stays NULL) so overlapping fence rows never collide; parity at `test/phantom-redirect-engine-parity.test.ts`. `getAdjacencyBoosts(pageIds): Promise<Map<number, AdjacencyRow>>` powers the per-query graph-signals stage — one SQL query returning inbound-link counts among top-K plus a cross-source count (links from differing `source_id`); `COALESCE(p.source_id,'default')` null safety, `HAVING >= 1`, cross-source CASE-WHEN excludes the target's own source; parity SQL across both engines; `SearchResult` gains optional `base_score`, `backlink_boost`, `salience_boost`, `recency_boost`, `exact_match_boost`, `graph_adjacency_boost`, `graph_cross_source_boost`, `session_demote_factor`, `reranker_delta` + internal staging fields; Pinned by `test/e2e/graph-signals-engine.test.ts`. Two REQUIRED methods: `deletePages(slugs, {sourceId}): Promise<string[]>` (single-batch primitive returning slugs actually deleted) and `resolveSlugsByPaths(paths, {sourceId}): Promise<Map<path,slug>>` (batch path→slug lookup); `sourceId` REQUIRED on both at the type level (asymmetric with single-row `deletePage` which keeps optional/'default'); both short-circuit on empty input and throw when `> DELETE_BATCH_SIZE`. `softDeletePages(slugs, {sourceId}): Promise<string[]>` is the batch soft-delete twin, mirroring `deletePages`' contract exactly (required `sourceId`, `> DELETE_BATCH_SIZE` throws, empty input short-circuits, caller owns chunking + decompose-to-one-element-batches on failure): one `UPDATE … SET deleted_at = now() … AND deleted_at IS NULL … RETURNING slug` round-trip returning only the slugs that actually flipped active→soft-deleted — the `deleted_at IS NULL` predicate is load-bearing so a re-run never refreshes an already-soft-deleted row's 72h purge clock — and NOTHING cascades (chunks/links/timeline stay behind the read-side `deleted_at` filters; the autopilot purge phase hard-deletes after 72h; a re-import within the window revives via `putPage`'s upsert; `deletePage`/`deletePages` remain the purge/teardown primitives). `getStats(opts?)` / `getHealth(opts?)` take an optional `{sourceId?, sourceIds?}` scope (same shape as `sourceScopeOpts` output): omitted = brain-wide; scoped = EVERY counter/coverage/degree confines to the grant, including derived-table counts via their page joins, and link-derived numbers count only edges with BOTH endpoints in scope — so an excluded source's numbers can't be recovered by subtraction. Consumer is the remote-caller ladder in `src/core/ops/admin.ts`; `getHealth` is a one-line delegation to `src/core/engine-sql/health.ts`. Embedding-signature stale-detection quartet: `countStaleChunks(opts?)` gains optional `signature?: string` widening the stale predicate from `embedding IS NULL` to ALSO include chunks whose JOINed page `embedding_signature IS NOT NULL AND <> $signature` (NULL signature is GRANDFATHERED, never counted; omit `signature` for the legacy NULL-only count); `sumStaleChunkChars(opts?: {sourceId?, signature?}): Promise<number>` = `SUM(LENGTH(chunk_text))` over stale chunks (same predicate + embed_skip filter + optional sourceId scope), used by `gbrain sync --all` cost preview via `estimateCostFromChars`; `setPageEmbeddingSignature(slug, {sourceId?, signature})` stamps `pages.embedding_signature` after a page's chunks (re)embed, idempotent no-op when page absent; `invalidateStaleSignatureEmbeddings({signature, sourceId?}): Promise<number>` NULLs `embedding`+`embedded_at` on every chunk whose page signature is set AND differs, returning the count, called BEFORE `listStaleChunks` so signature-drift pages flow through the NULL-embedding keyset cursor unchanged (NULL never invalidated). Widens `findOrphanPages(opts?: {sourceId?, sourceIds?})` (candidate-side scoping only; inbound links counted from any source). Pinned by `test/sum-stale-chunk-chars.test.ts`, `test/embedding-signature-stale.test.ts`, `test/e2e/engine-parity.test.ts`. Free-text alias layer: `resolveAliases(aliasNorms, opts?): Promise<Map<string, Array<{slug, source_id}>>>` (READ; maps each normalized alias to declaring `(slug, source_id)` pairs, source-scoped) and `setPageAliases(slug, sourceId, aliasNorms)` (WRITE; replaces the full alias set, delete-then-insert, empty clears, idempotent on the unique triple), called by the `importFromContent` ingest projection and the `reindex --aliases` backfill; parity across both engines, Pinned by `test/search/page-aliases-engine.test.ts`. `searchVector` in both engines injects the shared `buildBestPerPagePoolCte` per-page max-pool so a page surfaces on its strongest chunk. `executeRawDirect(sql, params?, opts?)` is the lock-hot-path sibling of `executeRaw`: same single-statement contract, but routes to the direct session-mode pool when dual-pool is active (Postgres/Supabase port 5432) so a long-held lock heartbeat survives the transaction pooler's per-transaction connection recycling; PGLite delegates straight to `executeRaw` (no pooler). Both engines implement it; the Minion lock path (`claim`/`renewLock`) is the consumer. `reconnect(ctx?: {error?})` is a REQUIRED lifecycle method on BOTH engines: it recovers a dropped connection using the config captured at the last `connect()`, so callers (autopilot health probe, `batchRetry`) never `disconnect()` + bare `connect()` (which loses the config and throws `database_url undefined` forever, and opens a null-connection window). PostgresEngine rebuilds its pool with a `_reconnecting` reentrancy guard and emits pool-recovery audit; PGLite is single-writer in-process so it just restores the saved data dir for parity. Plus two interface members: (1) optional `findDuplicatePage?(sourceId, {hash, frontmatterId?}): Promise<{slug, id} | null>` (identity precedence is content_hash OR frontmatter->>'id', both with `deleted_at IS NULL`); (2) `resolveSlugs(partial, opts?)` extended with `{sourceId?, sourceIds?}` so the MCP fuzzy `get_page` path scopes by source (field names match `sourceScopeOpts(ctx)` output so handlers spread directly; no opts gives the unscoped behavior). Plus a stable tiebreaker `ORDER BY score DESC, page_id ASC, chunk_id ASC` in `searchVector` in both engines: on a score tie (basis-vector eval fixtures) older `page_id` wins, so a new index on `pages` cannot flip ranking on tied scores.
-- `src/core/migrate.ts` — schema-migration runner. Re-exports `MIGRATIONS` from the generated registry `src/core/schema-migrations/registry.generated.ts`; each migration is one file `src/core/schema-migrations/v<NNN>-<name>.ts` (the source of truth for schema DDL history), with the `Migration` type in `schema-migrations/types.ts` and shared handler helpers (`migrationNotice`, `dropInvalidConcurrentIndex`, the fresh-install quiet flag) in `schema-migrations/helpers.ts`, a leaf that never imports `migrate.ts`. `Migration` carries `sqlFor?: { postgres?, pglite? }` (engine-specific SQL overrides `sql`) and `transaction?: boolean` (false for `CREATE INDEX CONCURRENTLY`, which Postgres refuses in a transaction; ignored on PGLite). Key migrations: v14 (handler branches on `engine.kind` for CONCURRENTLY-on-Postgres with invalid-remnant pre-drop via `pg_index.indisvalid`, plain `CREATE INDEX` on PGLite); v15 (`minion_jobs.max_stalled` default 1→5 + backfill non-terminal rows); v24 `rls_backfill_missing_tables` (`sqlFor: { pglite: '' }` no-op — PGLite has no RLS engine, targets subagent tables absent from pglite-schema.ts); v30 `dream_verdicts (file_path TEXT, content_hash TEXT, worth_processing BOOL, reasons JSONB, judged_at TIMESTAMPTZ, PK(file_path, content_hash))` (RLS-enabled under BYPASSRLS; synthesize reads/writes to avoid re-judging); v35 auto-RLS event trigger `auto_rls_on_create_table` fires on `ddl_command_end` for `WHEN TAG IN ('CREATE TABLE','CREATE TABLE AS','SELECT INTO')` running `ALTER TABLE … ENABLE ROW LEVEL SECURITY` on new `public.*` tables (no FORCE) + one-time backfill on every existing `public.*` base table whose comment doesn't match `^GBRAIN:RLS_EXEMPT\s+reason=\S.{3,}` (per-table failure aborts the offending CREATE TABLE; no EXCEPTION wrap; PGLite no-op via `sqlFor.pglite: ''`; breaking change: intentionally-RLS-off public tables need the GBRAIN:RLS_EXEMPT comment before upgrade); v40 `pages_emotional_weight` (`pages.emotional_weight REAL NOT NULL DEFAULT 0.0`, column-only metadata-only); v46 `mcp_request_log_params_jsonb_normalize` (`UPDATE ... SET params = params::text::jsonb WHERE jsonb_typeof(params) = 'string'`, idempotent); v60-v65 six-migration chain wiring source-scoping into `oauth_clients` — v60 (`oauth_clients_source_id_fk`: `source_id TEXT` NULL→`'default'` backfill + FK to `sources(id) ON DELETE SET NULL`), v61 (`federated_read TEXT[] NOT NULL DEFAULT '{}'`), v62 (explicit-CASE backfill so `source_id IS NULL` → `'{}'`), v63 (fail-loud check every row's source_id is in its federated_read array), v64 (FK flipped to `ON DELETE RESTRICT`), v65 (GIN index for array-containment); v68 `eval_candidates_embedding_column` (`eval_candidates.embedding_column TEXT NULL` per-row provenance for `gbrain eval replay` to reproduce the same retrieval space; NULL-tolerant); v108 `pages_embedding_signature` (`pages.embedding_signature TEXT NULL` = `<provider:model>:<dims>` stamped via `setPageEmbeddingSignature`; GRANDFATHER — stale predicate is `embedding_signature IS NOT NULL AND embedding_signature <> $current` so NULL is NEVER stale and upgrade never re-embeds the whole corpus; no index; metadata-only); v109 `sources_newest_content_at` (`sources.newest_content_at TIMESTAMPTZ` durable newest-COMMIT HEAD committer time written by `writeSyncAnchor`, read by the REMOTE staleness path instead of shelling to git; fresh-install column in `src/schema.sql`, generated into both blobs, plus a bootstrap probe); v110 `page_aliases` (`(id, source_id, alias_norm, slug, ...)` with `UNIQUE (source_id, alias_norm, slug)` + lookup indexes on `(source_id, alias_norm)` and `(source_id, slug)`; `alias_norm` is `normalizeAlias()` output so WRITE/READ key on the same form; also in `src/core/pglite-schema.ts`); v111 `search_telemetry_rank1_columns` (`ADD COLUMN IF NOT EXISTS` on both engines: `sum_rank1_score`, `count_rank1`, three buckets `rank1_lt_solid`/`rank1_solid`/`rank1_high` on `search_telemetry` — aggregate not per-query rows so rank-1 median drift is bounded-growth; ALTERs right after v57 which created the table); v114 `links_link_source_check_kebab_regex` (opens `link_source` from the closed allowlist to a kebab-case format gate `^[a-z][a-z0-9]*(-[a-z0-9]+)*$` + `char_length<=64`; Postgres branch uses `NOT VALID` + `VALIDATE CONSTRAINT` with `transaction:false`, PGLite plain DROP+ADD; existing built-ins all satisfy the regex so VALIDATE never fails on existing data); v116 `code_edges_source_backfill_and_callee_index` (idempotent: backfills NULL `code_edges_symbol`/`code_edges_chunk` `source_id` from each edge's `from_chunk` page — a NULL never matches a scoped `AND source_id = …` filter, so scoped `code-callers`/`code-callees` would return 0 rows on multi-source brains — plus plain `CREATE INDEX` on `from_symbol_qualified` for both edge tables, which had no index and seq-scanned per BFS node); v129 `dream_verdicts_triage_v1_columns` (additive `ADD COLUMN IF NOT EXISTS` widening `dream_verdicts` into a scored triage record — `score`, `content_type`, `segments`, `entities`, `model`, `triage_version`; legacy rows keep `score` NULL and read as cache misses, re-judged once; no backfill, no index; same SQL on both engines since `dream_verdicts` is migration-created on PGLite too, so the columns take the COLUMN_EXEMPTIONS route in `test/schema-bootstrap-coverage.test.ts` rather than bootstrap probes); v143 `dream_verdicts_ttl` (30-day `expires_at` TTL: nullable `ADD COLUMN` + `SET DEFAULT` run BEFORE the `judged_at`-derived backfill — statement order is load-bearing so a legacy writer racing the upgrade window picks up the default instead of inserting a NULL that would fail `SET NOT NULL` on every retry; on Postgres the schema blob's `dream_verdicts_expires_idx` forward-references the column, so `forward-reference-bootstrap.ts` probes + ALTERs it before the blob replays, and both engines' `getDreamVerdict` read predicate is NULL-tolerant — `expires_at IS NULL OR expires_at > now()` — so a pre-backfill row reads as a hit instead of silently re-judging the corpus). Three shape-keyed self-heals run on EVERY `runMigrations` pass, including the no-pending early-return path, because a merge-renumbered migration or a drifted restore can leave the version counter past a schema change while the live shape stays old: `repairTimelineDedupIndex` (`timeline_dedup_index`, see `timeline-dedup-repair.ts`) and `repairPagesUpsertArbiter` (`pages_source_slug_key`, see `pages-upsert-arbiter.ts`) are not version-gated at all; `repairLinkSourceCheck` (`links_link_source_check`, see `link-source-check-repair.ts`) runs only when the ledger is already >= `LINK_SOURCE_GATE_MIGRATION_VERSION` (114), because below it the pending loop replays v114 itself (running the repair first would rewrite the constraint twice, and a pre-v11 brain has no `link_source` column). All three are best-effort + idempotent; `doctor` surfaces each drift independently. `retry-matcher.ts` and `timeline-dedup-repair.ts` are static dependencies because `runMigrations()` executes from live engine initialization; the engine dynamic-import guard scans this file with both engine implementations. v95: `pages_dedup_partial_index` adds `CREATE INDEX pages_dedup_idx ON pages (source_id, content_hash) WHERE deleted_at IS NULL`. Postgres uses `CREATE INDEX CONCURRENTLY` with `transaction: false` + pre-drops any invalid remnant; PGLite uses plain `CREATE INDEX`. Powers `findDuplicatePage` hot path (O(log n) instead of O(n)). v74 `mcp_spend_log` uses BTREE on `(client_id, created_at)` + `(token_name, created_at)` — `date_trunc('day', TIMESTAMPTZ)` is NOT IMMUTABLE so can't appear in index expressions; a `created_at` range scan covers the per-day rollup. v75 `embedding_multimodal_column` is column-only (no HNSW index — deferred to post-reindex per pgvector best practice). Every pass (including one with nothing pending) ends with `page-state/revision-backfill-schema.ts:resumePageRevisionBackfill` while `pages.knowledge_revision` is nullable (#5216): the page-state schema adds `sources.incarnation` and `pages.knowledge_revision` nullable with a separate default (no volatile-default table rewrite on replay; an empty `pages` is constrained at once), rows are backfilled in committed id batches with a config cursor (`page_state.revision_backfill`), a failing row is isolated and retried at most three passes, and the column becomes NOT NULL via CHECK NOT VALID → VALIDATE → SET NOT NULL. The revision trigger handles a NULL old revision without reading bodies; snapshots report such a row's revision as `backfill_pending` and `assertPageRevision` refuses revision-bound writes with `revision_backfill_pending` (`page-revision-backfill-5216.test.ts`).
+- `src/core/migrate.ts` — schema-migration runner. Re-exports `MIGRATIONS` from the generated registry `src/core/schema-migrations/registry.generated.ts`; each migration is one file `src/core/schema-migrations/v<NNN>-<name>.ts` (the source of truth for schema DDL history), with the `Migration` type in `schema-migrations/types.ts` and shared handler helpers (`migrationNotice`, `dropInvalidConcurrentIndex`, the fresh-install quiet flag) in `schema-migrations/helpers.ts`, a leaf that never imports `migrate.ts`. `Migration` carries `sqlFor?: { postgres?, pglite? }` (engine-specific SQL overrides `sql`) and `transaction?: boolean` (false for `CREATE INDEX CONCURRENTLY`, which Postgres refuses in a transaction; ignored on PGLite). Key migrations: v14 (handler branches on `engine.kind` for CONCURRENTLY-on-Postgres with invalid-remnant pre-drop via `pg_index.indisvalid`, plain `CREATE INDEX` on PGLite); v15 (`minion_jobs.max_stalled` default 1→5 + backfill non-terminal rows); v24 `rls_backfill_missing_tables` (`sqlFor: { pglite: '' }` no-op — PGLite has no RLS engine, targets subagent tables absent from pglite-schema.ts); v30 `dream_verdicts (file_path TEXT, content_hash TEXT, worth_processing BOOL, reasons JSONB, judged_at TIMESTAMPTZ, PK(file_path, content_hash))` (RLS-enabled under BYPASSRLS; synthesize reads/writes to avoid re-judging); v35 auto-RLS event trigger `auto_rls_on_create_table` fires on `ddl_command_end` for `WHEN TAG IN ('CREATE TABLE','CREATE TABLE AS','SELECT INTO')` running `ALTER TABLE … ENABLE ROW LEVEL SECURITY` on new `public.*` tables (no FORCE) + one-time backfill on every existing `public.*` base table whose comment doesn't match `^GBRAIN:RLS_EXEMPT\s+reason=\S.{3,}` (per-table failure aborts the offending CREATE TABLE; no EXCEPTION wrap; PGLite no-op via `sqlFor.pglite: ''`; breaking change: intentionally-RLS-off public tables need the GBRAIN:RLS_EXEMPT comment before upgrade); v40 `pages_emotional_weight` (`pages.emotional_weight REAL NOT NULL DEFAULT 0.0`, column-only metadata-only); v46 `mcp_request_log_params_jsonb_normalize` (`UPDATE ... SET params = params::text::jsonb WHERE jsonb_typeof(params) = 'string'`, idempotent); v60-v65 six-migration chain wiring source-scoping into `oauth_clients` — v60 (`oauth_clients_source_id_fk`: `source_id TEXT` NULL→`'default'` backfill + FK to `sources(id) ON DELETE SET NULL`), v61 (`federated_read TEXT[] NOT NULL DEFAULT '{}'`), v62 (explicit-CASE backfill so `source_id IS NULL` → `'{}'`), v63 (fail-loud check every row's source_id is in its federated_read array), v64 (FK flipped to `ON DELETE RESTRICT`), v65 (GIN index for array-containment); v68 `eval_candidates_embedding_column` (`eval_candidates.embedding_column TEXT NULL` per-row provenance for `gbrain eval replay` to reproduce the same retrieval space; NULL-tolerant); v108 `pages_embedding_signature` (`pages.embedding_signature TEXT NULL` = `<provider:model>:<dims>` stamped via `setPageEmbeddingSignature`; GRANDFATHER — stale predicate is `embedding_signature IS NOT NULL AND embedding_signature <> $current` so NULL is NEVER stale and upgrade never re-embeds the whole corpus; no index; metadata-only); v109 `sources_newest_content_at` (`sources.newest_content_at TIMESTAMPTZ` durable newest-COMMIT HEAD committer time written by `writeSyncAnchor`, read by the REMOTE staleness path instead of shelling to git; fresh-install column in `src/schema.sql`, generated into both blobs, plus a bootstrap probe); v110 `page_aliases` (`(id, source_id, alias_norm, slug, ...)` with `UNIQUE (source_id, alias_norm, slug)` + lookup indexes on `(source_id, alias_norm)` and `(source_id, slug)`; `alias_norm` is `normalizeAlias()` output so WRITE/READ key on the same form; also in `src/core/pglite-schema.ts`); v111 `search_telemetry_rank1_columns` (`ADD COLUMN IF NOT EXISTS` on both engines: `sum_rank1_score`, `count_rank1`, three buckets `rank1_lt_solid`/`rank1_solid`/`rank1_high` on `search_telemetry` — aggregate not per-query rows so rank-1 median drift is bounded-growth; ALTERs right after v57 which created the table); v114 `links_link_source_check_kebab_regex` (opens `link_source` from the closed allowlist to a kebab-case format gate `^[a-z][a-z0-9]*(-[a-z0-9]+)*$` + `char_length<=64`; Postgres branch uses `NOT VALID` + `VALIDATE CONSTRAINT` with `transaction:false`, PGLite plain DROP+ADD; existing built-ins all satisfy the regex so VALIDATE never fails on existing data); v116 `code_edges_source_backfill_and_callee_index` (idempotent: backfills NULL `code_edges_symbol`/`code_edges_chunk` `source_id` from each edge's `from_chunk` page — a NULL never matches a scoped `AND source_id = …` filter, so scoped `code-callers`/`code-callees` would return 0 rows on multi-source brains — plus plain `CREATE INDEX` on `from_symbol_qualified` for both edge tables, which had no index and seq-scanned per BFS node); v129 `dream_verdicts_triage_v1_columns` (additive `ADD COLUMN IF NOT EXISTS` widening `dream_verdicts` into a scored triage record — `score`, `content_type`, `segments`, `entities`, `model`, `triage_version`; legacy rows keep `score` NULL and read as cache misses, re-judged once; no backfill, no index; same SQL on both engines since `dream_verdicts` is migration-created on PGLite too, so the columns take the COLUMN_EXEMPTIONS route in `test/schema-bootstrap-coverage.test.ts` rather than bootstrap probes); v143 `dream_verdicts_ttl` (30-day `expires_at` TTL: nullable `ADD COLUMN` + `SET DEFAULT` run BEFORE the `judged_at`-derived backfill — statement order is load-bearing so a legacy writer racing the upgrade window picks up the default instead of inserting a NULL that would fail `SET NOT NULL` on every retry; on Postgres the schema blob's `dream_verdicts_expires_idx` forward-references the column, so `forward-reference-bootstrap.ts` probes + ALTERs it before the blob replays, and both engines' `getDreamVerdict` read predicate is NULL-tolerant — `expires_at IS NULL OR expires_at > now()` — so a pre-backfill row reads as a hit instead of silently re-judging the corpus). Three shape-keyed self-heals run on EVERY `runMigrations` pass, including the no-pending early-return path, because a merge-renumbered migration or a drifted restore can leave the version counter past a schema change while the live shape stays old: `repairTimelineDedupIndex` (`timeline_dedup_index`, see `timeline-dedup-repair.ts`) and `repairPagesUpsertArbiter` (`pages_source_slug_key`, see `pages-upsert-arbiter.ts`) are not version-gated at all; `repairLinkSourceCheck` (`links_link_source_check`, see `link-source-check-repair.ts`) runs only when the ledger is already >= `LINK_SOURCE_GATE_MIGRATION_VERSION` (114), because below it the pending loop replays v114 itself (running the repair first would rewrite the constraint twice, and a pre-v11 brain has no `link_source` column). All three are best-effort + idempotent; `doctor` surfaces each drift independently. `retry-matcher.ts` and `timeline-dedup-repair.ts` are static dependencies because `runMigrations()` executes from live engine initialization; the engine dynamic-import guard scans this file with both engine implementations. v95: `pages_dedup_partial_index` adds `CREATE INDEX pages_dedup_idx ON pages (source_id, content_hash) WHERE deleted_at IS NULL`. Postgres uses `CREATE INDEX CONCURRENTLY` with `transaction: false` + pre-drops any invalid remnant; PGLite uses plain `CREATE INDEX`. Powers `findDuplicatePage` hot path (O(log n) instead of O(n)). v74 `mcp_spend_log` uses BTREE on `(client_id, created_at)` + `(token_name, created_at)` — `date_trunc('day', TIMESTAMPTZ)` is NOT IMMUTABLE so can't appear in index expressions; a `created_at` range scan covers the per-day rollup. v75 `embedding_multimodal_column` is column-only (no HNSW index — deferred to post-reindex per pgvector best practice). Every pass (including one with nothing pending) ends with `page-state/revision-backfill-schema.ts:resumePageRevisionBackfill` while `pages.knowledge_revision` is nullable (#5216): the page-state schema adds `sources.incarnation` and `pages.knowledge_revision` nullable with a separate default (no volatile-default table rewrite on replay; an empty `pages` is constrained at once), rows are backfilled in committed id batches with a config cursor (`page_state.revision_backfill`), a failing row is isolated and retried at most three passes, each update grants only its rows' sources to the managed writer guard (`gbrain.write_sources`, transaction-local), and the column becomes NOT NULL via CHECK NOT VALID → VALIDATE → SET NOT NULL. With the schema version current no ordinary command runs a pass, so `gbrain apply-migrations --force-schema` (`REVISION_BACKFILL_RESUME_COMMAND`) resumes it; `readRevisionBackfillStatus` feeds doctor `revision_backfill` (`src/commands/doctor/checks/revision-backfill.ts`: ok when NOT NULL, warn with the pending count, the failed rows by page and the resume command, or the `repair orphan-children` preview when only spent rows remain). The revision trigger handles a NULL old revision without reading bodies; snapshots report such a row's revision as `backfill_pending` and `assertPageRevision` refuses revision-bound writes with `revision_backfill_pending` (`page-revision-backfill-5216.test.ts`).
Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). The runner (ordering, retry, verify, repair-handler hooks and the static helper imports engine-live paths require) has a plain ratchet ceiling; migrations no longer live in this file.
- `src/core/pglite-embedded-assets.ts` + `src/core/pglite-embedded-asset-paths.ts` — PGLite runtime-asset supply for every run mode (compiled binary, source checkout, bun-global install). `pglite-embedded-asset-paths.ts` is the bundler ANCHOR: five literal `with { type: 'file' }` imports of the wasm/data/extension-tarball assets via repo-relative node_modules paths (the package's `exports` map hides `./dist/*`) — keep the specifiers literal and byte-stable, an expression or indirection silently stops the bytes embedding and the compiled binary falls into the Bun-vfs ENOENT failure. `resolvePgliteAssetPaths()` in `pglite-embedded-assets.ts` is the tiered resolver: tier 1 dynamically `import()`s the anchor (the rejection under a hoisted install — bun-global upgrades dedupe `@electric-sql/pglite` to the global root, making the anchor's specifiers unresolvable — is EXPECTED and routes to tier 2, which is why the anchor is not a static import); tier 2 derives the dist dir via module resolution of `@electric-sql/pglite` (`import.meta.resolve` then `createRequire` — the SAME specifier the engine imports, so assets can never come from a different pglite copy than the loaded JS); tier 3 throws one actionable error naming everything tried, with the canonical GitHub reinstall command (never the npm-registry name, which is squatted — see the README install warning). `getEmbeddedPgliteOptions()` memoizes one build per process and hands PGLite compiled `WebAssembly.Module`s + fs-bundle Blob + materialized extension tarballs via `PGliteOptions`. Pinned by `test/pglite-embedded-assets.test.ts` + `test/pglite-hoisted-install.serial.test.ts` (real `bun add -g`-shaped hoisted layout).
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index fa4de464d9..d33a438f3f 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -374,7 +374,9 @@ The preview also reads every page body and lists the rows it cannot read
rows. Recover them from a backup, or create a fresh brain and sync it again
from its source files. Until then, a write that names the revision of a page
the upgrade could not backfill is refused with `revision_backfill_pending`;
-`gbrain apply-migrations --yes` resumes that backfill and prints its progress.
+doctor's `revision_backfill` check names those pages, and
+`gbrain apply-migrations --force-schema` resumes the backfill for the rest and
+prints its progress.
### Timeline history scan coverage
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index a7bcc998ab..232f8c7c04 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -80,7 +80,7 @@ a receipt can report has a row here.
| `writer_pool_capacity` | `writer_pool_capacity` | The canonical owner has no free publication slot right now; the write stays queued. | Wait and poll the receipt (`gbrain write-request <id>`). If it persists, check `gbrain sources writer status <source>`. |
| `revision_required` | `revision_required` | The operation must be bound to a revision you reviewed (for example `--if-version` or `expected_revision`), and none was given. | Preview first, then repeat with the revision the preview printed. |
| `revision_conflict` | `revision_conflict` | The page changed after the revision this write was bound to. Nothing was overwritten. | Re-read the page, merge your change, and save with the new revision. |
-| `revision_backfill_pending` | `revision_backfill_pending` | The page was written before page revisions existed (an upgrade from below schema v150) and the resumable revision backfill has not reached it, so it has no revision to bind to. Its revision reads as `backfill_pending`, never a UUID. Nothing was written. | Resume the backfill with `gbrain apply-migrations --yes` (it prints its progress). If it reports rows it could not update, run `gbrain repair orphan-children` to preview orphaned child rows and torn page bodies ([orphan children](repair.md#orphan-children)). |
+| <a id="revision-backfill"></a>`revision_backfill_pending` | `revision_backfill_pending` | The page was written before page revisions existed (an upgrade from below schema v150) and the resumable revision backfill has not reached it, so it has no revision to bind to. Its revision reads as `backfill_pending`, never a UUID. Nothing was written. `gbrain doctor` reports the backfill as `revision_backfill` with the pending count and any failed rows by page. | Resume the backfill on the brain host with `gbrain apply-migrations --force-schema` (it prints its progress; `--yes` alone does not resume it once the schema is current). Rows that used all three attempts are no longer retried: run `gbrain repair orphan-children` to preview orphaned child rows and torn page bodies ([orphan children](repair.md#orphan-children)). |
| `idempotency_conflict` | `idempotency_conflict` | The `request_id` was already used for a different target, content or protocol. | Use a new `request_id` for a different write; reuse an ID only to replay the same write. |
| <a id="write_pending"></a>`write_pending` | `write_pending` (CLI exit 10) | The write was accepted but has not committed yet. It keeps its request ID and may still commit. The CLI exits 10, not 1; a lost acknowledgment with no receipt is `submission_status: "unknown"` and exits 1. See [CLI exit status for writes](../protocol/MEMORY_VERBS_v1.md#cli-exit-status-for-writes). | Poll `gbrain call get_write_request '{"request_id":"<id>"}'`, or repeat the same command with the same `--request-id` and a longer `--wait <seconds>`. Scripts that only need the write admitted pass `--accept-pending` (or `GBRAIN_ACCEPT_PENDING=1`) to exit 0. |
| <a id="invalid_write_wait"></a>`invalid_write_wait` | `invalid_write_wait` | `GBRAIN_WRITE_WAIT_MS` or `persistence.write_wait_ms` is not a whole number of milliseconds from 0 to 600000. Nothing was written. | `unset GBRAIN_WRITE_WAIT_MS` (or set it to e.g. `30000`), or `gbrain config set persistence.write_wait_ms 30000`. |
diff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.ts
index 8147e5015b..bc072d5af5 100644
--- a/scripts/e2e-test-map.ts
+++ b/scripts/e2e-test-map.ts
@@ -30,7 +30,8 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
"src/commands/reindex.ts": ["test/e2e/reindex-auto-workers-5181.test.ts"],
// Fix wave 8, Lane G: deferred ANN build after the embedding re-embed (#5088).
// Fix wave 8, Lane G: page revision rollout (#5216).
- "src/core/page-state/revision-backfill-schema.ts": ["test/e2e/page-revision-rollout-5216-postgres.test.ts"],
+ "src/core/page-state/revision-backfill-schema.ts": ["test/e2e/page-revision-rollout-5216-postgres.test.ts", "test/e2e/doctor-revision-backfill-postgres.test.ts"],
+ "src/commands/doctor/checks/revision-backfill.ts": ["test/e2e/doctor-revision-backfill-postgres.test.ts", "test/e2e/doctor-json-golden.test.ts"],
"src/core/embedding-ann-build.ts": ["test/e2e/migrate-embeddings-ann-build-5088-postgres.test.ts", "test/e2e/migrate-embeddings-postgres.test.ts"],
// FOUNDATIONS 1 F4a: get_health SQL aggregate, shared orphan policy, op memo.
"src/core/engine-sql/health.ts": ["test/e2e/engine-sql-health-parity.test.ts", "test/e2e/health-parity-postgres.test.ts", "test/e2e/get-health-embedding-column-postgres.test.ts"],
diff --git a/src/commands/doctor/checks/revision-backfill.ts b/src/commands/doctor/checks/revision-backfill.ts
new file mode 100644
index 0000000000..26e084ffe2
--- /dev/null
+++ b/src/commands/doctor/checks/revision-backfill.ts
@@ -0,0 +1,64 @@
+/**
+ * revision_backfill (#5216): pages written before page revisions existed wait
+ * for the resumable `pages.knowledge_revision` backfill; until a page has its
+ * revision, a write that names one is refused with `revision_backfill_pending`.
+ * ok when the column is NOT NULL (backfill finished, or a fresh install).
+ * Otherwise warns with the pending count and the command that resumes the
+ * pass; failed rows are named with their page, attempt count and error, and
+ * rows whose attempts are spent point at the torn-page preview instead, since
+ * the resume command no longer retries them. Read-only.
+ */
+import {
+ readRevisionBackfillStatus,
+ REVISION_BACKFILL_MAX_ATTEMPTS,
+ REVISION_BACKFILL_RESUME_COMMAND,
+} from '../../../core/page-state/revision-backfill-schema.ts';
+import type { Check } from '../../doctor.ts';
+import { agentFix, checkError } from '../check-fix.ts';
+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
+
+const DOCS = 'docs/guides/write-refusals.md#revision-backfill';
+const LISTED = 5;
+
+async function runRevisionBackfill(ctx: DoctorContext): Promise<Check[]> {
+ const engine = connectedEngine(ctx);
+ const checks: Check[] = [];
+ try {
+ const status = await readRevisionBackfillStatus(engine);
+ if (status.column !== 'nullable') {
+ checks.push({ name: 'revision_backfill', status: 'ok', details: { column: status.column, pending: 0, failed: [] },
+ message: status.column === 'not_null' ? 'Every page has its revision; the page revision backfill is complete.'
+ : 'This schema predates page revisions; the backfill starts with the migration that adds them.' });
+ return checks;
+ }
+ const spent = status.failed.filter(f => f.attempts >= REVISION_BACKFILL_MAX_ATTEMPTS);
+ const resumable = status.pending - spent.length;
+ const details = { column: status.column, pending: status.pending, resumable, failed: status.failed,
+ resume_command: REVISION_BACKFILL_RESUME_COMMAND, docs: DOCS };
+ const listed = (rows: typeof status.failed) => rows.slice(0, LISTED)
+ .map(f => `page id ${f.id} (${f.source_id}:${f.slug}, attempt ${f.attempts} of ${REVISION_BACKFILL_MAX_ATTEMPTS}: ${f.error})`).join('; ')
+ + (rows.length > LISTED ? `; +${rows.length - LISTED} more` : '');
+ const parts = [
+ status.pending === 0
+ ? 'Every page has a revision, but the page revision backfill has not finished making the column NOT NULL.'
+ : `${status.pending} page(s) still have no revision; the page revision backfill is incomplete, and a write that names their revision is refused with revision_backfill_pending.`,
+ ...(status.failed.length ? [`${status.failed.length} row(s) failed: ${listed(status.failed)}.`] : []),
+ ...(spent.length ? [`${spent.length} of them used all ${REVISION_BACKFILL_MAX_ATTEMPTS} attempts, so resuming no longer retries them; `
+ + 'the usual cause is a torn page body. Preview with gbrain repair orphan-children (torn_pages lists them) and recover those pages from a backup or a re-sync.'] : []),
+ ...(resumable > 0 || status.pending === 0 ? [`Resume the backfill on the brain host: ${REVISION_BACKFILL_RESUME_COMMAND} (it prints its progress).`] : []),
+ ];
+ const fix = resumable > 0 || status.pending === 0
+ ? agentFix(REVISION_BACKFILL_RESUME_COMMAND.split(' '),
+ 'Re-runs the schema migration pass on the brain host, which resumes the page revision backfill and prints its progress; it changes no page content.',
+ 'revision_backfill', { requires_exclusive: true, docs: DOCS })
+ : agentFix(['gbrain', 'repair', 'orphan-children'],
+ 'Previews orphaned child rows and lists torn page bodies (torn_pages) without changing anything.', 'revision_backfill',
+ { docs: 'docs/guides/repair.md#orphan-children' });
+ checks.push({ name: 'revision_backfill', status: 'warn', message: parts.join(' '), fix, details });
+ } catch (err) {
+ checks.push(checkError('revision_backfill', 'read the page revision backfill state', err));
+ }
+ return checks;
+}
+
+export const revisionBackfillEntry: DoctorEntry = { name: 'revision_backfill', emits: ['revision_backfill'], run: runRevisionBackfill };
diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.ts
index 1c00a016da..5c6acdd78a 100644
--- a/src/commands/doctor/registry.ts
+++ b/src/commands/doctor/registry.ts
@@ -88,6 +88,7 @@ import { factTakeVectorsEntry } from './checks/vector-coverage.ts';
import { decideHealthEntry } from './checks/decide.ts';
import { unlinkedFactsEntry } from './checks/unlinked-facts.ts';
import { plannerStatsEntry } from './checks/planner-stats.ts';
+import { revisionBackfillEntry } from './checks/revision-backfill.ts';
import { harnessWiringDoctorEntry } from './checks/harness-wiring.ts';
import { agentContractEntry } from './checks/agent-contract.ts';
import { STOP_DOCTOR, type DoctorContext, type DoctorEntry } from './context.ts';
@@ -156,6 +157,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [
factsDrainEntry,
factTakeVectorsEntry,
plannerStatsEntry,
+ revisionBackfillEntry,
searchModeEntry,
];
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index 053875ed9b..06d079fe9e 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -294,6 +294,8 @@ export const META_CHECK_NAMES: ReadonlySet<string> = new Set([
// coherence healed by `gbrain apply-migrations` (sibling of
// timeline_dedup_index / schema_version).
'pages_upsert_arbiter',
+ // #5216: the resumable pages.knowledge_revision backfill (resumed by apply-migrations --force-schema).
+ 'revision_backfill',
'schema_columns',
'schema_pack_active',
'schema_pack_consistency',
diff --git a/src/core/page-state/revision-backfill-schema.ts b/src/core/page-state/revision-backfill-schema.ts
index 94e7c92e71..31ebb2f2ea 100644
--- a/src/core/page-state/revision-backfill-schema.ts
+++ b/src/core/page-state/revision-backfill-schema.ts
@@ -9,7 +9,7 @@
* config row `page_state.revision_backfill`, so an interrupted pass resumes and
* never reassigns a revision it already gave. A batch that fails is retried row
* by row; a row that still fails (for example a torn TOAST value) is isolated,
- * reported and retried on at most MAX_ATTEMPTS later passes, never forever;
+ * reported and retried on at most REVISION_BACKFILL_MAX_ATTEMPTS later passes, never forever;
* once its attempts are spent, later passes stay quiet.
* When no NULL row remains the column becomes NOT NULL through a CHECK added
* NOT VALID, validated without blocking writes, then SET NOT NULL and dropped,
@@ -18,11 +18,13 @@
import type { BrainEngine } from '../engine.ts';
export const REVISION_BACKFILL_STATE_KEY = 'page_state.revision_backfill';
-export const REVISION_BACKFILL_RESUME_COMMAND = 'gbrain apply-migrations --yes';
-const MAX_ATTEMPTS = 3;
+/** Re-runs the schema migration pass, which resumes this backfill even when no migration is pending. */
+export const REVISION_BACKFILL_RESUME_COMMAND = 'gbrain apply-migrations --force-schema';
+/** Passes a failing row is retried on before later passes stop retrying it. */
+export const REVISION_BACKFILL_MAX_ATTEMPTS = 3;
const CHECK_NAME = 'pages_knowledge_revision_backfilled';
-interface FailedRow { id: number; attempts: number; error: string }
+export interface FailedRow { id: number; attempts: number; error: string }
interface BackfillState { cursor: number; backfilled: number; failed: FailedRow[] }
export interface RevisionBackfillResult {
@@ -39,8 +41,45 @@ async function readState(engine: BrainEngine): Promise<BackfillState> {
return { cursor: 0, backfilled: 0, failed: [] };
}
-async function assignRow(engine: BrainEngine, id: number): Promise<void> {
- await engine.executeRaw('UPDATE pages SET knowledge_revision = gen_random_uuid() WHERE id = $1 AND knowledge_revision IS NULL', [id]);
+/**
+ * Assign revisions to the given rows in one statement. A managed brain's
+ * writer guard refuses a revision change outside a source capability, so the
+ * statement grants exactly the rows' sources (`gbrain.write_sources`,
+ * transaction-local, as schema migration v191 does) before any row updates;
+ * no content column changes.
+ */
+export interface RevisionBackfillStatus {
+ /** `absent`: pre-v150 schema; `not_null`: the backfill finished; `nullable`: it has not. */
+ column: 'absent' | 'not_null' | 'nullable';
+ /** Live and deleted page rows that still have no revision. */
+ pending: number;
+ /** Rows the backfill reported failing that still have no revision, with their page. */
+ failed: Array<FailedRow & { source_id: string; slug: string }>;
+}
+
+/** Read-only: where the backfill stands, for `gbrain doctor`. */
+export async function readRevisionBackfillStatus(engine: BrainEngine): Promise<RevisionBackfillStatus> {
+ const column = await engine.executeRaw<{ notnull: boolean }>(
+ `SELECT attnotnull AS notnull FROM pg_attribute
+ WHERE attrelid = to_regclass('pages') AND attname = 'knowledge_revision' AND NOT attisdropped`);
+ if (column.length === 0) return { column: 'absent', pending: 0, failed: [] };
+ if (column[0]!.notnull) return { column: 'not_null', pending: 0, failed: [] };
+ const [{ n }] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM pages WHERE knowledge_revision IS NULL');
+ const state = await readState(engine);
+ const pages = state.failed.length === 0 ? [] : await engine.executeRaw<{ id: number; source_id: string; slug: string }>(
+ 'SELECT id, source_id, slug FROM pages WHERE id = ANY($1::bigint[]) AND knowledge_revision IS NULL', [state.failed.map(f => f.id)]);
+ const byId = new Map(pages.map(p => [Number(p.id), p]));
+ const failed = state.failed.filter(f => byId.has(f.id)).map(f => ({ ...f, source_id: byId.get(f.id)!.source_id, slug: byId.get(f.id)!.slug }));
+ return { column: 'nullable', pending: Number(n), failed };
+}
+
+async function assignRows(engine: BrainEngine, ids: number[]): Promise<void> {
+ await engine.executeRaw(
+ `UPDATE pages SET knowledge_revision = gen_random_uuid()
+ WHERE id = ANY($1::bigint[]) AND knowledge_revision IS NULL
+ AND set_config('gbrain.write_sources',
+ (SELECT COALESCE(jsonb_agg(DISTINCT p.source_id), '[]'::jsonb)::text FROM pages p WHERE p.id = ANY($1::bigint[])), true) IS NOT NULL`,
+ [ids]);
}
export async function resumePageRevisionBackfill(
@@ -66,11 +105,11 @@ export async function resumePageRevisionBackfill(
announced = true;
}
try {
- await engine.executeRaw('UPDATE pages SET knowledge_revision = gen_random_uuid() WHERE id = ANY($1::bigint[]) AND knowledge_revision IS NULL', [ids]);
+ await assignRows(engine, ids);
state.backfilled += ids.length;
} catch {
for (const id of ids) {
- try { await assignRow(engine, id); state.backfilled++; }
+ try { await assignRows(engine, [id]); state.backfilled++; }
catch (error) {
state.failed.push({ id, attempts: 1, error: (error instanceof Error ? error.message : String(error)).slice(0, 200) });
}
@@ -86,9 +125,9 @@ export async function resumePageRevisionBackfill(
for (const row of state.failed) {
const [still] = await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE id = $1 AND knowledge_revision IS NULL', [row.id]);
if (!still) continue;
- if (row.attempts >= MAX_ATTEMPTS) { failed.push(row); continue; }
+ if (row.attempts >= REVISION_BACKFILL_MAX_ATTEMPTS) { failed.push(row); continue; }
retried = true;
- try { await assignRow(engine, row.id); state.backfilled++; }
+ try { await assignRows(engine, [row.id]); state.backfilled++; }
catch (error) { failed.push({ id: row.id, attempts: row.attempts + 1, error: (error instanceof Error ? error.message : String(error)).slice(0, 200) }); }
}
state.failed = failed;
diff --git a/test/doctor-revision-backfill-journey.serial.test.ts b/test/doctor-revision-backfill-journey.serial.test.ts
new file mode 100644
index 0000000000..dcd73ac887
--- /dev/null
+++ b/test/doctor-revision-backfill-journey.serial.test.ts
@@ -0,0 +1,70 @@
+/**
+ * #5216 follow-up journey: the command doctor `revision_backfill` prints
+ * actually finishes the page revision backfill.
+ *
+ * Protects: on a brain created by `gbrain init` (managed) whose pages still
+ * wait for their revision with the schema version current, doctor warns with
+ * `gbrain apply-migrations --force-schema`; `gbrain apply-migrations --yes`
+ * alone leaves the backfill where it was; the printed command completes it
+ * and doctor clears.
+ * Fails when: doctor has no revision_backfill check, prints a command that
+ * does not resume the backfill, or the backfill fails its rows on the managed
+ * writer guard.
+ * Why existing coverage misses it: the backfill tests call
+ * resumePageRevisionBackfill in-process; none runs the printed command.
+ * Seams: none; the real CLI against a PGLite brain in a temporary home.
+ * Serial: it opens the CLI's PGLite data directory in-process between CLI runs.
+ */
+import { expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { Check } from '../src/commands/doctor.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runCli } from './helpers/cli-spawn.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const SLUGS = ['notes/rev-a', 'notes/rev-b', 'notes/rev-c'];
+
+test('journey: on a CLI-created brain, the command doctor prints finishes the backfill and doctor clears', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-revision-journey-'));
+ try {
+ const init = await runCli(['init', '--pglite', '--no-embedding'], { home, timeoutMs: 120_000 });
+ expect(init.exitCode).toBe(0);
+ // The setup migrations gbrain init leaves pending re-run the schema pass; finish them first, as an upgraded brain has.
+ expect((await runCli(['apply-migrations', '--yes', '--no-autopilot-install'], { home, timeoutMs: 120_000 })).exitCode).toBe(0);
+ await withEnv({ GBRAIN_HOME: home }, async () => {
+ const engine = new PGLiteEngine();
+ await engine.connect({ database_path: join(home, '.gbrain', 'brain.pglite') });
+ try {
+ const [{ enabled }] = await engine.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain');
+ expect(enabled).toBe(true);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled = false');
+ for (const slug of SLUGS) await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `Body of ${slug}.` }, { sourceId: 'default' });
+ await engine.executeRaw('UPDATE persistence_brain SET enabled = true');
+ await engine.executeRaw('ALTER TABLE pages ALTER COLUMN knowledge_revision DROP NOT NULL');
+ await engine.executeRaw('ALTER TABLE pages DISABLE TRIGGER USER');
+ await engine.executeRaw('UPDATE pages SET knowledge_revision = NULL WHERE slug = ANY($1::text[])', [SLUGS]);
+ await engine.executeRaw('ALTER TABLE pages ENABLE TRIGGER USER');
+ } finally { await engine.disconnect(); }
+ });
+
+ const doctor = async () => {
+ const out = await runCli(['doctor', '--only', 'revision_backfill', '--json'], { home, timeoutMs: 120_000 });
+ const report = JSON.parse(out.stdout) as { checks: Check[] };
+ return report.checks.find(c => c.name === 'revision_backfill')!;
+ };
+ const before = await doctor();
+ expect(before.status).toBe('warn');
+ expect((before.fix as { command?: string }).command).toBe('gbrain apply-migrations --force-schema');
+
+ const plain = await runCli(['apply-migrations', '--yes', '--no-autopilot-install'], { home, timeoutMs: 120_000 });
+ expect(plain.exitCode).toBe(0);
+ expect((await doctor()).status).toBe('warn');
+
+ const resumed = await runCli(['apply-migrations', '--force-schema'], { home, timeoutMs: 120_000 });
+ expect(resumed.exitCode).toBe(0);
+ expect(resumed.stderr).toContain('page revision backfill complete: 3 row(s)');
+ expect((await doctor()).status).toBe('ok');
+ } finally { rmSync(home, { recursive: true, force: true }); }
+}, 300_000);
diff --git a/test/doctor-revision-backfill.test.ts b/test/doctor-revision-backfill.test.ts
new file mode 100644
index 0000000000..6b87d05eda
--- /dev/null
+++ b/test/doctor-revision-backfill.test.ts
@@ -0,0 +1,135 @@
+/**
+ * #5216 follow-up: doctor `revision_backfill` and the command that resumes
+ * the page revision backfill.
+ *
+ * Protects: doctor reports ok once `pages.knowledge_revision` is NOT NULL;
+ * warns with the pending count and `gbrain apply-migrations --force-schema`
+ * while pages still wait for their revision; names failed rows by page id,
+ * source:slug, attempt and error, and points at the torn-page preview when
+ * only rows with spent attempts remain. The backfill completes on a managed
+ * brain instead of failing every row on the managed writer guard.
+ * Fails when: the check is missing or silent, when it names a command that
+ * does not resume the backfill once the schema version is current (`--yes`
+ * alone), or when the backfill's revision update is refused with
+ * writer_coordinator_required on a managed brain.
+ * Why existing coverage misses it: page-revision-backfill-5216.test.ts drives
+ * resumePageRevisionBackfill directly on an unmanaged brain; nothing reports
+ * the state or runs the printed resume command.
+ * Seams: none; real PGLite (and Postgres through the e2e registration), the
+ * shared `managedBrain`. The CLI journey is test/doctor-revision-backfill-journey.serial.test.ts.
+ */
+import { describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { revisionBackfillEntry } from '../src/commands/doctor/checks/revision-backfill.ts';
+import type { DoctorContext } from '../src/commands/doctor/context.ts';
+import type { Check } from '../src/commands/doctor.ts';
+import { categorizeCheck } from '../src/core/doctor-categories.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { REVISION_BACKFILL_STATE_KEY, resumePageRevisionBackfill } from '../src/core/page-state/revision-backfill-schema.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const SLUGS = ['notes/rev-a', 'notes/rev-b', 'notes/rev-c'];
+
+/** Pages written before page revisions existed: the column nullable, their revisions NULL. */
+async function awaitingRevisions(engine: BrainEngine, slugs: string[]): Promise<void> {
+ await engine.executeRaw('ALTER TABLE pages ALTER COLUMN knowledge_revision DROP NOT NULL');
+ await engine.executeRaw('ALTER TABLE pages DISABLE TRIGGER USER');
+ await engine.executeRaw('UPDATE pages SET knowledge_revision = NULL WHERE slug = ANY($1::text[])', [slugs]);
+ await engine.executeRaw('ALTER TABLE pages ENABLE TRIGGER USER');
+}
+
+async function check(engine: BrainEngine): Promise<Check> {
+ const [result] = await revisionBackfillEntry.run({ engine } as unknown as DoctorContext) as Check[];
+ expect(result.name).toBe('revision_backfill');
+ return result;
+}
+
+async function unmanagedBrain(databaseUrl: string | undefined, run: (engine: BrainEngine) => Promise<void>): Promise<void> {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-revision-backfill-'));
+ try {
+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {
+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);
+ try {
+ for (const slug of SLUGS) await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `Body of ${slug}.` }, { sourceId: 'default' });
+ await run(engine);
+ } finally { await close(); }
+ });
+ } finally { rmSync(home, { recursive: true, force: true }); }
+}
+
+for (const backend of testBackends()) {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+
+ describe(`${backend}: revision_backfill doctor check`, () => {
+ test('ok when every page has its revision', async () => {
+ await unmanagedBrain(databaseUrl, async engine => {
+ const result = await check(engine);
+ expect(result).toMatchObject({ status: 'ok', details: { column: 'not_null', pending: 0 } });
+ expect(categorizeCheck('revision_backfill')).toBe('meta');
+ });
+ }, 120_000);
+
+ test('warns with the pending count and the resume command while pages wait for their revision', async () => {
+ await unmanagedBrain(databaseUrl, async engine => {
+ await awaitingRevisions(engine, SLUGS);
+ const result = await check(engine);
+ expect(result.status).toBe('warn');
+ expect(result.message).toContain('3 page(s) still have no revision');
+ expect(result.message).toContain('gbrain apply-migrations --force-schema');
+ expect(result.fix).toMatchObject({ argv: ['gbrain', 'apply-migrations', '--force-schema'], actor: 'agent',
+ verify: { argv: ['gbrain', 'doctor', '--only', 'revision_backfill', '--json'] } });
+ expect(result.details).toMatchObject({ column: 'nullable', pending: 3, resumable: 3, failed: [] });
+
+ expect((await resumePageRevisionBackfill(engine, { log: () => {} })).status).toBe('complete');
+ expect((await check(engine)).status).toBe('ok');
+ });
+ }, 120_000);
+
+ test('names failed rows by page; only spent rows left points at the torn-page preview', async () => {
+ await unmanagedBrain(databaseUrl, async engine => {
+ await awaitingRevisions(engine, SLUGS.slice(0, 2));
+ const ids = Object.fromEntries((await engine.executeRaw<{ id: number; slug: string }>(
+ 'SELECT id, slug FROM pages WHERE slug = ANY($1::text[])', [SLUGS])).map(r => [r.slug, Number(r.id)]));
+ const error = 'unexpected chunk number 21 (expected 1) for toast value 141869';
+ await engine.setConfig(REVISION_BACKFILL_STATE_KEY, JSON.stringify({ cursor: ids['notes/rev-c'], backfilled: 1, failed: [
+ { id: ids['notes/rev-a'], attempts: 1, error }, { id: ids['notes/rev-b'], attempts: 3, error }] }));
+ const both = await check(engine);
+ expect(both.status).toBe('warn');
+ expect(both.message).toContain(`page id ${ids['notes/rev-a']} (default:notes/rev-a, attempt 1 of 3: ${error})`);
+ expect(both.message).toContain(`page id ${ids['notes/rev-b']} (default:notes/rev-b, attempt 3 of 3: ${error})`);
+ expect(both.message).toContain('1 of them used all 3 attempts');
+ expect(both.fix).toMatchObject({ argv: ['gbrain', 'apply-migrations', '--force-schema'] });
+ expect(both.details).toMatchObject({ pending: 2, resumable: 1 });
+
+ await engine.executeRaw("UPDATE pages SET knowledge_revision = gen_random_uuid() WHERE slug = 'notes/rev-a'");
+ const spent = await check(engine);
+ expect(spent.status).toBe('warn');
+ expect(spent.message).not.toContain('apply-migrations');
+ expect(spent.message).toContain('gbrain repair orphan-children');
+ expect(spent.fix).toMatchObject({ argv: ['gbrain', 'repair', 'orphan-children'] });
+ expect(spent.details).toMatchObject({ pending: 1, resumable: 0, failed: [expect.objectContaining({ slug: 'notes/rev-b', attempts: 3 })] });
+ });
+ }, 120_000);
+ });
+
+ test(`${backend}: managed: the backfill assigns revisions under the writer guard instead of failing every row`, async () => {
+ await managedBrain(async ({ engine, ctx }) => {
+ for (const slug of SLUGS) {
+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug, content: `---\ntype: note\ntitle: ${slug}\n---\nBody of ${slug}.\n`, request_id: randomUUID() } });
+ }
+ await awaitingRevisions(engine, SLUGS);
+ const result = await resumePageRevisionBackfill(engine, { log: () => {} });
+ expect(result).toMatchObject({ status: 'complete', failed: [] });
+ const rows = await engine.executeRaw<{ r: string | null }>('SELECT knowledge_revision::text AS r FROM pages WHERE slug = ANY($1::text[])', [SLUGS]);
+ expect(rows.every(row => /^[0-9a-f-]{36}$/.test(row.r ?? ''))).toBe(true);
+ expect((await check(engine)).status).toBe('ok');
+ }, { databaseUrl });
+ }, 120_000);
+}
diff --git a/test/e2e/doctor-revision-backfill-postgres.test.ts b/test/e2e/doctor-revision-backfill-postgres.test.ts
new file mode 100644
index 0000000000..95d281c19d
--- /dev/null
+++ b/test/e2e/doctor-revision-backfill-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../doctor-revision-backfill.test.ts'));
diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.json
index 7eda06d330..40520fd63a 100644
--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json
+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json
@@ -1541,6 +1541,17 @@
"name": "planner_stats_stale",
"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": "ops",
"message": "Mode: conservative (no per-key overrides — mode bundle is canonical).",
diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.json
index cf50c1c43f..af60675b21 100644
--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json
+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json
@@ -1618,6 +1618,17 @@
"name": "planner_stats_stale",
"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": "ops",
"message": "Mode: conservative (no per-key overrides — mode bundle is canonical).",
diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.json
index 316ef797f6..7cb72a0489 100644
--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json
+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json
@@ -1608,6 +1608,17 @@
"name": "planner_stats_stale",
"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": "ops",
"message": "Mode: conservative (no per-key overrides — mode bundle is canonical).",
diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.json
index 560d566cef..79c076c000 100644
--- a/test/fixtures/goldens/doctor/registry-build-checks.json
+++ b/test/fixtures/goldens/doctor/registry-build-checks.json
@@ -633,6 +633,10 @@
"category": "ops",
"name": "planner_stats_stale"
},
+ {
+ "category": "meta",
+ "name": "revision_backfill"
+ },
{
"category": "ops",
"name": "chat_fallback_chain_inert"