Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(migrate): batch v221 and the other published backfills before their migration (#7108)
garrytanbc135bec68cf
diff --git a/docs/architecture/key-files/engines-1.md b/docs/architecture/key-files/engines-1.mdindex 0da51cdc63..954a5b1ab6 100644--- a/docs/architecture/key-files/engines-1.md+++ b/docs/architecture/key-files/engines-1.md@@ -30,6 +30,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/migrate-pending.ts` — `hasPendingMigrations` (re-exported by `migrate.ts`): one `version` read against the generated `schema-migrations/latest.generated.ts`, so a connect never loads the migration registry.- `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`, `buildIndexOnline` with its best-effort `analyzeAfterIndexBuild` (a failed ANALYZE warns with the repair command and never fails the build of a valid index), 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`).+- `src/core/migration-preludes.ts` — #7108 runner-side preludes for published migrations whose SQL rewrites a large table in one transaction (published migration files never change; restamp refuses an edit). `runMigrationPrelude(engine, version)` runs right before that migration's SQL inside the runner's retry wrapper: `batchedUpdate` repeats the migration's own SET and predicate over id-ordered batches (5,000 rows, `__setBackfillBatchRowsForTests`), each its own transaction with the migration statement budget and the schema lock timeout, so progress is the data itself and a rerun resumes; a column the migration adds first is added first, in the migration's column order (fresh and upgraded ordinals stay equal). Preludes: v011 legacy `links.link_source` (skipped below PG15, where the migration refuses), v028 chunk keyword vectors, v033 request-log agent names, v116 code-edge `source_id`, v161 the partial pages index via `buildIndexOnline` (the migration caps its own build at 30 s), v221 `embedding_pending_since` (v221's active-column choice; the first stamping batch writes `embedding_pending_since_backfilled_at` in its transaction). The migration SQL then runs unchanged and finds nothing left. Pinned by `test/e2e/migration-v221-batched-backfill-7108.test.ts`. Migrations that cannot be moved here are listed in docs/guides/troubleshooting.md#migration-statement-timeout.+- `src/core/migration-timeout.ts` — #7108 the migration statement budget (`migrationStatementTimeoutMs`, default 10 min; `setMigrationStatementTimeoutMs` from operator-only `gbrain apply-migrations --statement-timeout <minutes>`, 0 removes it) and the timed-out-migration record (config `schema_migration_timeout`: version, name, idle blocker pids, gbrain release): `runMigrations` writes it on a 57014 or a statement-timeout retry exhaustion and deletes it after a pass reaches head. `migrationTimeoutAdvice` is the one fix both apply-migrations (`migrations_pending` still_behind) and doctor `schema_version` show: another release recorded it → rerun; a blocker → ask_user, end it, rerun; nothing blocking → ask_user, one run with `--statement-timeout 120`.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 squatted npm name; README install warning). `getEmbeddedPgliteOptions()` memoizes one build per process and hands PGLite compiled `WebAssembly.Module`s + fs-bundle Blob + `vector`/`pg_trgm` extensions via `PGliteOptions` (the tarballs are gunzipped and untarred in memory, and `lazyExtension` writes their files into PGLite's filesystem in the extension's `init`, after the backend starts, so postgres loads each `.so` on first use instead of PGLite preloading both on every open, about 30 ms; `readExtensionFiles` refuses any entry that is not a file or directory), plus `startParams` = PGLite's defaults then `PGLITE_START_PARAM_OVERRIDES` (no parallel maintenance workers, `max_wal_size=8GB`: an HNSW build fits the WASM heap, its WAL under the checkpoint trigger). `withSharedBuffers` appends `-c shared_buffers=<size>` when `EngineConfig.pglite_shared_buffers` is set: `connectEngineForServe` sets `ONE_SHOT_READ_SHARED_BUFFERS` (32MB) for a one-shot read-scope CLI process (shared op path, `gbrain call <read op>`, `search`, `sources list`), because the backend zero-fills the whole pool at start (about 55 ms for the 128MB default) and one read never fills it; serve and writes keep the default. The package itself is a type-only import plus one lazy `await import('@electric-sql/pglite')` inside `build()` after the resolver ran: the module must load without the package, or a missing install dies with the raw "Cannot find module" before the tier-3 sentence (#6512). Pinned by `test/pglite-embedded-assets.test.ts` + `test/pglite-hoisted-install.test.ts` (`bun add -g`-shaped hoisted layout, spawned with `bun --no-install` so script auto-install cannot mask a missing package).diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 026a2d93e3..43f2e7f3db 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -2465,7 +2465,7 @@ More: [docs/guides/shared-brain-skills.md#migrate-an-existing-brain](../../docs/| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable ||---|---|---|---|---|---|---|-| Schema migrations are behind (or could not be confirmed at head), or an orchestrator migration is wedged, so the command did not report success. | apply-migrations reasons: not_applied: the run had no --yes (or --non-interactive), so it did not apply the schema migrations; the fix applies them with --yes. still_behind: an authorized run tried them and they did not apply; another --yes repeats the failure, so run `gbrain doctor --json` and report. schema_unreadable: the schema version could not be read back after the orchestrators ran, so the run cannot confirm it reached head; report it. wedged: an orchestrator migration ended partial three or more times in a row, so runs skip it until a person fixes the cause and clears it with --force-retry. Each failure names the migrations still pending. schema_behind (#6904): a managed write was refused at admission because the brain schema is below the version this build needs. Not retryable as is (class caller): the same write refuses until the migrations are applied; nothing was admitted, so the request_id was not consumed and the same request_id commits once the schema is migrated (a replay of an already accepted id still reconciles). | schema_behind: apply them with `gbrain apply-migrations --yes` as the database role that owns the gbrain tables (the brain host operator when this connection does not own them), then resubmit the write with the same request_id. not_applied: apply them with `gbrain apply-migrations --yes`. still_behind or schema_unreadable: run `gbrain doctor --json` and report it to the user; another --yes repeats the failure. wedged: ask the user, read the migration's partial rows in the brain home's migrations/completed.jsonl (phases[].detail, if present; apply-migrations prints the resolved path), fix the cause, then `gbrain apply-migrations --force-retry <version>` and `gbrain apply-migrations --yes`. | agent | `repeat the read that failed` | 1 | no |+| Schema migrations are behind (or could not be confirmed at head), or an orchestrator migration is wedged, so the command did not report success. | apply-migrations reasons: not_applied: the run had no --yes (or --non-interactive), so it did not apply the schema migrations; the fix applies them with --yes. still_behind: an authorized run tried them and they did not apply; another --yes repeats the failure, so run `gbrain doctor --json` and report; when a migration ran out of its statement budget (#7108) the error names it and its fix depends on the case: recorded by another gbrain release (rerun), an idle-in-transaction blocker (end it once the user agrees, rerun) or nothing blocking (once the user agrees, one run with --statement-timeout). schema_unreadable: the schema version could not be read back after the orchestrators ran, so the run cannot confirm it reached head; report it. wedged: an orchestrator migration ended partial three or more times in a row, so runs skip it until a person fixes the cause and clears it with --force-retry. Each failure names the migrations still pending. schema_behind (#6904): a managed write was refused at admission because the brain schema is below the version this build needs. Not retryable as is (class caller): the same write refuses until the migrations are applied; nothing was admitted, so the request_id was not consumed and the same request_id commits once the schema is migrated (a replay of an already accepted id still reconciles). | schema_behind: apply them with `gbrain apply-migrations --yes` as the database role that owns the gbrain tables (the brain host operator when this connection does not own them), then resubmit the write with the same request_id. not_applied: apply them with `gbrain apply-migrations --yes`. still_behind or schema_unreadable: run `gbrain doctor --json` and report it to the user; another --yes repeats the failure (a still_behind that names a timed-out migration carries its own fix: follow it). See docs/guides/troubleshooting.md#migration-statement-timeout. wedged: ask the user, read the migration's partial rows in the brain home's migrations/completed.jsonl (phases[].detail, if present; apply-migrations prints the resolved path), fix the cause, then `gbrain apply-migrations --force-retry <version>` and `gbrain apply-migrations --yes`. | agent | `repeat the read that failed` | 1 | no |Reasons: `not_applied`, `still_behind`, `schema_unreadable`, `wedged`, `schema_behind`.diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.mdindex ed8bcc01cd..87aac53ed0 100644--- a/docs/guides/troubleshooting.md+++ b/docs/guides/troubleshooting.md@@ -25,6 +25,7 @@| Facts extraction or embedding reports `(cause=AIConfigError model_not_found)` or `gbrain models doctor` says `model_not_found` while the key is valid | the provider refused the model, not the key (a 404, or a 403 "project does not have access to model"): the fix text names the config key that selected the model when the gateway knows it ("Selected via models.tier.reasoning. Fix: gbrain config set …"; an env var or config.json pin says what to clear); otherwise check the model id with `gbrain models`, enable the model for the project in the provider console or set another model (`gbrain config set models.facts <provider:model>`) | user (provider console); agent for the config change, after the user agrees | none | `gbrain models doctor` reports the model `ok` || Doctor `links_extraction_lag` or sync says "N page(s) have un-extracted edges" | `gbrain extract --stale --dry-run --json`, then on the host `gbrain extract --stale --catch-up [--source-id <id>]` | user above 120 s, else agent | none | dry run: `actionable: 0` || Doctor `links_extraction_lag` says "N page(s) failed link extraction 3 runs in a row and are held", or `extract --stale` lists failed pages | Read each page's code (`unknown_source`: the page's source row is gone; restore the source or delete the page), fix the cause, then `gbrain extract --stale [--source-id <id>] --retry-held` | agent | none | `gbrain extract --stale --dry-run --json`: `held: 0` |+| `gbrain apply-migrations --yes` or `gbrain upgrade` stops with `Migration <N> … exhausted retries` / SQLSTATE 57014 and the schema stays behind (`migrations_pending`, reason `still_behind`) | upgrade first (#7108: long backfills run in committed batches), then follow the error's or doctor `schema_version`'s `fix` ([migration statement timeout](#migration-statement-timeout)) | agent; a longer `--statement-timeout` or ending a blocking session only after the user agrees | none for a rerun | `gbrain doctor --only schema_version --json` || A gbrain call failed with a code you don't recognize | follow `fix.next` ([protocol](../protocol/AGENT_OPERATOR_v1.md)); `gbrain errors <code>` | agent | as the fix's `consent` | the fix's `verify` || A graph read omits a relationship you know existed, or says someone still works somewhere they left | the default read returns relationships true today: repeat with `status: "all"` or `as_of`; to record an end, add a dated timeline line (`Ended works_at [[companies/x]]`) or `add_link ... valid_until` ([temporal edges](temporal-edges.md)) | agent | none | `gbrain doctor --only edge_validity --json` || A command exited 3 (`confirmation_required`) | relay `user_message`; run `fix.command` only after the user agrees | agent, after the user agrees | the payload's `effects` | the fix's `verify` |@@ -92,602 +93,3 @@<a id="ipc-path-too-long"></a>**Hooks get no context on Windows, the serve log says `ipc_path_too_long`, or doctor warns `ipc_socket_path`?** Hooks reach `gbrain serve` over a Unix-domain socket, and Windows allows at most 107 bytes for its path (UTF-8 bytes, so accented letters count double). A PGLite brain normally puts its sockets in the data directory; when that path is too long gbrain uses `%USERPROFILE%\.gbrain\run\<kind>-<hash>.sock` instead, still guarded by the data directory's `.gbrain-ipc-secret`, and hooks find it the same way. `ipc_path_too_long` means even the profile path is too long. The serve log and `gbrain doctor --only ipc_socket_path --json` print the path, its byte count and the limit. Fix it by moving the brain: stop serve, move the data directory to a short path such as `C:\gbrain\brain.pglite`, run `gbrain config set database_path C:\gbrain\brain.pglite`, then restart serve. **Say to your agent:** *"My hooks can't reach gbrain serve on Windows; check the IPC socket path."*<a id="held-files"></a>**Sync held a file (`Held <path>: invalid_frontmatter …`, doctor `git_held_files`, `get_page` shows `file_held`)?** The sync succeeded; only that file waits, and its page (if any) keeps its last good revision and refuses `put_page` until the file is repaired. Run `gbrain sources status <id>`, preview `gbrain repair frontmatter --source <id>`, and after the user agrees run the printed apply. A source a broken file blocked before upgrading recovers on its next sync (`gbrain sync --source <id> --no-pull` does it now). See [held files](repair.md#held-files).--<a id="held-fence-files"></a>**Sync held a file because of its facts or takes fence (`Held <path>: invalid_fence …`)?** Managed sync succeeded; only that file waits. The hold names the fence, section, row numbers, columns and reason, never a cell, and most holds clear by themselves: the maintenance run's `fence_repair` phase repairs the fence on the owner host and commits the file. To see the plan or do it now, run `gbrain repair fences --source <id>` (a read-only preview with no model call), then the apply command it prints; applying needs no extra consent. Model repair spends only within `fences.repair.max_usd_per_page` and `fences.repair.max_usd_per_day`; raising them, or pausing automatic repair with `gbrain config set fences.repair.enabled false`, is the user's call. A hold whose reason is `manual` needs a person: read the page (`gbrain get --source <id> -- <slug>`), edit only that fence in the file (not the frontmatter; `gbrain repair frontmatter` does not touch fences), commit, and run `gbrain sync --source <id> --no-pull`. A `prepare_time` hold was refused against stored rows (for example a takes row number a stored take already uses): fix it as its `fence.reason` says, and after a database-side fix run `gbrain sources retry-held <id>`. A source a fence blocked before upgrading recovers on its next sync. A fence with one obvious meaning is never held: sync rewrites it losslessly, commits the file and reports `fences_normalized`; a `fence_normalized` notice on a write means re-read the page before editing it. `gbrain doctor --only fence_integrity` counts every malformed fence still waiting (held, stored or unsynced) by tier. See [fence holds](write-refusals.md#invalid_fence), [fence repair](repair.md#fences) and the [fence format](fence-format.md).--<a id="concurrent-write-hold"></a>**Sync held a file with `concurrent_write`?** A Git edit raced a database-only write; nothing was overwritten. Preview `gbrain sources reconcile <id> <slug> --preview`, let the user choose, then `gbrain sources retry-held <id>`. See [concurrent_write](write-refusals.md#concurrent_write).--<a id="worktree-dirty-hold"></a>**Sync held a file with `worktree_dirty`?** The working tree holds uncommitted bytes for the file that match neither the pinned commit nor the page (an agent mid-edit on a live checkout), so sync held it instead of overwriting the edit and kept going; nothing is lost and the run finished. Commit the file (or restore it), then `gbrain sync unblock --source <id> --apply` re-screens every held file that is now committed and prints the sync to run; a later commit that changes the file re-screens it on its own. A file held three times is reported `needs_human` by `gbrain sync status`: find out what keeps editing it. Bytes committed at HEAD past the pinned target are imported as HEAD has them, never held. See [worktree_dirty](write-refusals.md#worktree_dirty) and the [sync unblock runbook](sync-unblock-runbook.md).--<a id="catch-up-stuck"></a>**Managed catch-up stuck (one write `running` for minutes while the rest waits), held N files as `preparation_stalled`, or the drain stopped with `preparation_abandoned`, `preparation_systemic` or `write_capacity`?** Every managed write's *preparation* has a deadline (`persistence.sync_preparation_ms`, default 120 s, for sync members; `persistence.maintenance_preparation_ms`, default 120 s, for maintenance writes; a hard ceiling `persistence.preparation_ceiling_ms`, default 600 s; `persistence.max_preparation_attempts`, default 2; all behind the `preparation_deadlines` write switch), so one stuck write is cut off at its budget, but a cut-off preparation that ignores cancellation keeps its root blocked until the ceiling (600 s from the claim's start), when the owner frees the root and the next claim holds the entry; the rest of the source keeps publishing meanwhile, and a sync beside such an owner prints `stalled <N>s on <step>` with the owner's pid and kind from the allowance to the ceiling instead of stopping. One wedge therefore costs up to ten minutes and one held file, never the run. The runbook branches on what you see; every command below is read-only unless it says otherwise, and the files themselves are never the problem in this branch. Start every branch with `gbrain doctor --only serve_build_drift --json`: on a warning, restart serve and its workers on this build first (see [serve build drift](#serve-build-drift)) and stop there until it reads ok.--1. **While it is stuck.** The progress line prints `stalled <N>s on <step>` instead of an ETA. Run `gbrain sources writer status --source <id> --json`: the blocked request's `claim.stall` names the step (`origin_check`, `knowledge_publication`, …), `waiting_on` (`git`, `fs`, `db`, `pool`, or an honest `unknown`), `step_age_ms`, the budget, and the owner process (kind, pid, gbrain version). An owner whose version predates this release never gives up: upgrade it and restart it (`gbrain serve`, the jobs worker or autopilot; the drain's own process ends with the drain). Otherwise wait out the budget: the write is released, retried once, then held. A release does not always free the root: a preparation that ignores cancellation holds its root barrier until the ceiling, and `writer status --json` ends the claim in a `claim.next` that says so (`claim_running` with `retry_after_ms` to the ceiling, or `claim_overdue` as `tell_user_to_run` naming the owner pid once the ceiling has passed or the owner reads `restart_required`).-2. **Held files (`preparation_stalled`).** `gbrain sources status <id> --json` lists them with the step each stalled on; no `gbrain repair` applies. After the cause is fixed (or gbrain upgraded), run `gbrain sources retry-held <id>` and then the same sync with the same options, which the hold's `fix` and `retry-held` print, for example `gbrain sync --source <id> --no-pull --no-embed`. If that sync still has a backlog, it finishes the backlog and then re-screens the scheduled files in the same run. Verify with `gbrain sources status <id> --json` (the held count drops) and `gbrain doctor --only git_held_files --json`. A held deletion keeps its page until that retry. A stalled hold also re-screens by itself when the gbrain version changes.-3. **The drain stopped `preparation_abandoned` (exit 0).** A preparation in the sync's own process was still running past its allowance (its budget plus 30 s) and cannot be cancelled in-process, so the sync exited to end it; `drain.stall.step` says where. Rerun `next.command` (`safe_to_loop` is true): the next pass holds the entry if it stalls again.-4. **The drain stopped `preparation_systemic` (exit 1).** Too many writes stalled in one run (more than `GBRAIN_SYNC_HOLD_ESCALATE_COUNT` / `GBRAIN_SYNC_HOLD_ESCALATE_PCT` of the run's screened imports, or five in a row with no page committed between), so the run stopped with one diagnostic instead of holding every file. `breaker` carries the rule, the counts and the last step. Inspect the writer as in step 1, fix the cause, then rerun the same sync: it re-freezes the stopped entry with a fresh request and re-screens the files that run held.-5. **The drain stopped `write_capacity` (exit 1).** Other writers' requests held the sync writer's outstanding-request cap (`persistence.limits.principal_outstanding`, default 100; on one host the CLI sync shares the `local_cli` principal with fact-fence adoption and `dream`) for the whole 30 s window, so the sync could not admit its next write. It waited and printed `waiting for write capacity (N outstanding of M)` first; nothing failed and the cursor is intact. `gbrain sources writer status --source <id> --json` lists the outstanding requests. Let them finish, or raise the cap (`gbrain config set persistence.limits.principal_outstanding 200`), then rerun the same sync. Reference: [drain stops](write-refusals.md#drain-write-capacity).-6. **A `put_page`, `remember` or maintenance write finished `preparation_stalled`.** Nothing is held: the receipt names the step. Read the writer as in step 1, then resubmit a foreground write under a new `request_id`; the next maintenance run submits its write again.-7. **A manual fence defect among the holds** (`invalid_fence`, reason `manual`, or `repeated_marker`) is a different branch: see [held fence files](#held-fence-files). `gbrain sources status` keeps the kinds apart and routes each to its own command.--Turning the `preparation_deadlines` switch off (`gbrain config set persistence.preparation_deadlines false`) restores the previous behaviour exactly: no deadlines on sync or maintenance writes, no attempt counter, no `preparation_stalled` holds. See [`preparation_stalled`](write-refusals.md#preparation_stalled), [managed sync drain stops](write-refusals.md#managed-sync-drain-stops) and the [timing knobs](live-sync.md#catching-up-a-large-backlog-on-managed-postgres).--<a id="held-connector-items"></a>**A Google or GitHub item is held after repeated failures (doctor `connector_held_items`, `gbrain waiting` says coverage is partial)?** Run `gbrain sources status <id>`, fix the cause, then after the user agrees run `gbrain sources retry-held <id>` and `gbrain sync --source <id>`. See [held items](google-connect.md#held-items).--<a id="retry-other-options"></a>**A sync (or the deprecated `--retry-failed` alias) lists failures that "belong to a run with different sync options"?** A managed retry resumes only the cursor its own options select; each other failure gets one line with its class and the command that settles it. `resumable (replay …)`: an unfinished run holds it, and the command resumes that run under its recorded options. `resumable (fresh discovery, not a replay …)`: no run holds it any more; the command starts a new run from HEAD under the failed run's options, which clears the failure when it completes. For a failure recorded before runs kept their options, the options are recovered only when an option set reproduces its cursor key exactly. `safely orphaned`: nothing current can resume it; preview `gbrain repair managed-sync-orphans --source <id>` and apply with the hash it prints. `unresolved`: its options were never recorded and nothing selects it; the line says what has to finish first (a request still in flight, or a current run whose completion lets the orphan repair retire it).--<a id="checkpoint-validation-timeout"></a>**A managed sync is blocked with `checkpoint_validation_timeout`?** Run the printed commands on the brain host: `gbrain repair request-indexes --apply` when an index is missing or INVALID, then the printed `gbrain sync --source <id> --no-pull …`. Doctor's `persistence_request_growth` warns before lifetime request IDs run out.--<a id="pglite-aborted"></a>**PGLite crashes at startup with `RuntimeError: Aborted()` (often right after a macOS upgrade)?** Not a macOS incompatibility — the OS-upgrade reboot killed gbrain mid-write and tore the data dir's WAL. gbrain repairs this automatically on the next command (data preserved, backup kept); if auto-repair is disabled or skipped, run `gbrain pglite-repair --dry-run` to diagnose and `gbrain pglite-repair --yes` to repair in place. Full recovery ladder (repair → rebuild → engine switch) in [`docs/ENGINES.md` — Troubleshooting: startup abort](../ENGINES.md#troubleshooting-startup-abort-runtimeerror-aborted) and [`docs/INSTALL.md`](../INSTALL.md#pglite-crashes-at-startup-runtimeerror-aborted).--<a id="embedding-dimensions"></a>**`gbrain import` fails with `expected N dimensions, not M`?** Run `gbrain doctor`. It will print the exact `gbrain config set ...` or `gbrain migrate embeddings` command to repair the mismatch (`migrate embeddings` re-embeds through the provider: effect `paid`, ask the user first). You should not need to delete `~/.gbrain`. Fresh `gbrain init --pglite` auto-detects your embedding provider from API keys: set `VOYAGE_API_KEY` (or `OPENAI_API_KEY` / another provider key) in the environment — or in `~/.gbrain/config.json`, which init also reads — before running init, or pass `--embedding-model <provider>:<model>` explicitly. With multiple keys set, init fires an interactive picker (non-TTY auto-picks the Voyage default when its key is present). With no keys at all, init continues keyless (keyword-only search) with a loud notice; add a key later and re-run `gbrain init --force --embedding-model voyage:voyage-4` to enable embeddings (effects: `credentials` and `paid`, since every page is embedded through the provider; it needs the brain's writer lock, so stop a running `gbrain serve` first; pages and facts are kept), or pass `--no-embedding` up front to make keyless explicit. `gbrain config get embedding_disabled` reports whether embedding is off and which plane says so (the config file and the database setting; `true` on either turns it off); `gbrain config set embedding_disabled true|false` and `gbrain config unset embedding_disabled` change both, and the `init --force --embedding-model` enable path clears both. See [`docs/integrations/embedding-providers.md`](../integrations/embedding-providers.md) for the full provider matrix and [`docs/operations/headless-install.md`](../operations/headless-install.md) for Docker/CI sequencing.--<a id="embed-backfill-skipped"></a>**A sync job or `embed-backfill` job reports `embed_backfill_skipped` (reason `embedding_disabled`)?** Nothing is wrong: the brain is keyless by choice (`embedding_disabled`), so sync queues no embed-backfill and a backfill already queued ends on its first attempt without reading a page. Search stays keyword-only. The notice appears once per brain state (the first skip after the brain became keyless); its fix is the optional step that turns embedding on and names the provider key it needs (effects `credentials` and `paid`: ask the user first).--**`gbrain doctor` warns `default_source_local_path`?** Your `default` source has no `local_path` AND that null pointer is provably breaking write-through (the repo fallback is another source's own working tree, or file-backed default pages have no resolvable root). A null `local_path` on its own is the designed fallback topology and reports ok. The repair is a pointer update, never a file move: `gbrain sources set-path default <path>` prints the prior value before changing it and refuses a path that nests inside or swallows another source's tree (exit 6; `--force` bypasses). **Say to your agent:** *"Run a brain health check and fix what you find"* — the maintain skill runs `gbrain doctor` and applies the printed repair.--**A Gmail, Calendar or GitHub connector source still has an old `local_path`?** Connector sources sync from their provider, so autopilot ignores their `local_path`: once a connector has synced (or tried to) at least once, autopilot syncs it on every interval and runs its database phases with no checkout. A connector that has never synced stays idle until you run `gbrain sync --source <id>` once; autopilot prints that command the first time it skips one. To remove the stale pointer, run `gbrain sources set-path <id> --clear` (connector sources only; it refuses a filesystem source and a connector bound to a canonical owner). `config.syncEnabled=false` still opts a source out. **Say to your agent:** *"My Gmail source points at an old folder. Clear it and keep it syncing."*--<a id="write-refused"></a>**A save, sync or background effect was refused with a named reason?** Reasons such as `file_database_drift`, `ambiguous_source_path`, `physical_root_device_changed`, `cursor_processing_options_conflict`, `take_row_collision`, `invalid_source_uri`, `queue_capacity` and parked effects (`targets_parked`, doctor `parked_effects`) each come with a recovery step in the error's `suggestion`. [Write refusal reasons](write-refusals.md) explains each one and its recovery. **Say to your agent:** *"My save was refused. Explain the reason and show me the fix before you run it."*--<a id="doctor-residue"></a>**`gbrain doctor` warns `timeline_history`, `derived_visibility`, or unsealed pages under `contextual_retrieval_coverage`?** Preview the fix with `gbrain repair`, then apply one kind at a time with `gbrain repair <kind> --apply` on the brain host. See [repair residual damage](repair.md).--<a id="extract-health-halts"></a>**Doctor warns `extract_health` with "kind(s) with halt rate > 10%" after the cause was already fixed?** The check is a rate over the last 7 days, not a list of open faults: `halt_count` and `round_completed_count` are 7-day sums from the extraction rollup (one row per kind per day), so halts recorded before a fix keep the rate up until their days leave the window. Read each kind's age before acting: `last halt today` (or `1d ago`) means the extractor is still halting, while `last halt 5d ago` on a kind that has run since means the halts are history. `gbrain doctor --only extract_health --json` gives the same per kind in `details.kinds[]`: `halt_rate`, `last_halt_age_days`, `top_halt_reason` and every reason with its count in `halt_reasons`; runs that stopped at an expected budget or deadline cap count in `expected_limit_count`, not as halts. Fix the reason that is still current, then let the window age out: expiry is how a repaired cause clears, and there is no acknowledgement or reset command. A halt with `last_halt_age_days` at 0 after the fix means the cause is not fixed. **Say to your agent:** *"Is extract_health warning about current halts or old ones?"*--**`gbrain doctor` warns `timeline_orphans`?** Timeline rows from an earlier version of a page are still in the database after the dated bullet was edited or deleted. Preview with `gbrain extract timeline --prune-orphans --dry-run`, then remove them with `gbrain extract timeline --prune-orphans` (add `--source-id <id>` to limit it). Rows no page version ever produced, such as enrichment and meeting fan-out, are kept.--**A doctor check says "Not verified"?** <a id="not-verified-doctor-checks"></a>The check could not read its input, so it reports `warn` instead of `ok`; `gbrain doctor --json` carries `details.code: "not_verified"` and the underlying reason in `details.reason`. Fix the cause, then re-run `gbrain doctor`:--| Check | What it could not read | Fix |-| --- | --- | --- |-| `multi_source_drift` | a source's `local_path` root or a directory below it (`details.unreadable_sources`), the walk hit its bound (`details.limit` files / `details.timeout_ms`), or, for a source whose slugs are pinned to its git root, where `local_path` sits in its git work tree (`details.git_root_skipped`) | fix the path or permissions (`gbrain sources status`); for a large source re-run with `GBRAIN_DRIFT_LIMIT=<files> GBRAIN_DRIFT_TIMEOUT_MS=<ms> gbrain doctor`; for a git-root source, check that `git -C <local_path> rev-parse --show-prefix` succeeds (a checkout git can read and that it trusts) |-| `embed_staleness` | the stale-chunk count (the embed worker's own predicate) | the reason names the database error; re-run `gbrain doctor` once it is fixed |-| `schema_pack_consistency`, `schema_pack_source_drift` | the pages or config query, or a source's active schema pack | `gbrain schema lint --with-db` runs the same classification locally; `gbrain schema active` debugs pack resolution |--`bootstrap_push_health` and `gbrain bootstrap status` report only the push record of the workspace named by this machine's bootstrap receipt; another workspace's stale or failed push is listed as such (a warn naming that workspace), never as this workspace's state. `reranker_health` auth warnings are audit-log history (`details.live_probe_performed: false`), not a live check of the key. These warns can appear while every other check reads green; each one names a check that did not run.--<a id="git-convergence"></a>**`gbrain doctor` warns or fails `git_convergence`, or `bootstrap_push_health` warns that a workspace is ahead?** A Git checkout the brain syncs from (a source's `local_path` or `sync.repo_path`) has commits its upstream does not have, or uncommitted changes, so the system of record on the remote is behind the brain (#5063). Commits not on the upstream warn after 6 hours and fail after 24; uncommitted changes older than 6 hours warn. Doctor compares with the local `@{u}` ref and never fetches, so it is only as fresh as the last fetch; checkouts without an upstream and connector sources are skipped. Commit and push the checkout (`gbrain sources push --path <root>` for a bootstrap workspace; otherwise commit your files with `gbrain git commit-push -m "<msg>" -- <paths>` and publish waiting commits with `gbrain git commit-push --push-only`, see [shared-checkout git](shared-checkout-git.md#outcomes)). `bootstrap_push_health` no longer reports `ok` on a recent successful push while the workspace still has commits not on origin.--<a id="tracked-ownership-marker"></a>**`gbrain doctor` warns `tracked_ownership_marker`, or `gbrain sources push` / `bootstrap verify` refuses a `.gbrain-owner*.json` or `.gbrain-bootstrap.lock/` path?** An ownership marker (`.gbrain-owner.json`, the `.gbrain-owner-<hash>.json` reservation beside a root, a `.gbrain-owner.json.<uuid>.tmp` staging file) or the bootstrap lock directory was committed to a source checkout (#5186). These files are this machine's claim on the checkout, never brain content, and must not reach a remote. Since this fix gbrain appends their patterns to the checkout's `.git/info/exclude` whenever it stamps or adopts a root, the bootstrap `.gitignore` template lists them, and the push deny list refuses a tracked one while an untracked one is excluded from the commit (`excludedUntracked`). None of that un-tracks a file already in the index: run the `git -C <root> rm --cached <paths>` the check prints (the files stay on disk, gbrain keeps reading them), commit, push, then `gbrain doctor --only tracked_ownership_marker --json`. A root stamped before this fix gains the exclude rule on its next stamp or transfer; until then the deny list is the backstop, and `bootstrap verify`'s `deny_globs` treats a merely-on-disk marker as fine. If a marker already reached a remote, rotate it the same way you would any published credential: the token alone is not remote authority (the reservation that proves ownership lives outside the root), but treat the history as exposed.--**`brain_score` shows a low "timeline density (entity and event pages)"?** The 15-point timeline component grades only linkable pages whose type's active-pack primitive is `entity` or `temporal` (people, companies, meetings, emails, events…); reference documents such as notes, writing and guides have no events and are not graded, so do not stamp "page created" rows onto them. Types the pack does not declare are still graded. Raise the score by giving those entity and event pages real timeline entries (`gbrain extract timeline`).--**`gbrain doctor` warns `slug_collisions`, or sync prints slug collisions?** Two or more files in a source map to the same page slug (for example `notes/Foo Bar.md` and `notes/foo-bar.md`), and only one is indexed. Rename all but one file in each group, commit, then sync.--<a id="session-timeouts-not-applied"></a>**Doctor warns `persistence_session_timeouts` with `session_timeouts_not_applied`?** gbrain sets `statement_timeout` (`GBRAIN_STATEMENT_TIMEOUT`, default 5min) and `idle_in_transaction_session_timeout` as connection startup parameters, and a transaction-mode pooler (PgBouncer with `ignore_startup_parameters`, Supavisor) drops them: `SHOW statement_timeout` through the configured URL reads `0`, so a statement outside a transaction has no server-side bound and a relation lock held in another session (a migration's `ALTER TABLE pages` queued behind a long transaction, for example) holds it for as long as the lock lasts. Managed write *preparation* reads are not affected since v0.60.108: they run under a transaction-local `statement_timeout` of the write's remaining preparation budget, so a lock-blocked read ends at the budget and the member is released `preparation_deadline` with no statement left on the server (#6278). For every other autocommit statement, set the default on the role instead of the connection: `ALTER ROLE <gbrain role> SET statement_timeout = '5min'` (read-only to check: `gbrain doctor --only persistence_session_timeouts --json`). Setting `GBRAIN_STATEMENT_TIMEOUT` has no effect through such a pooler.--<a id="managed-sync-blocked"></a>**A managed sync run is blocked (doctor `managed_sync_blocked`, a freshness `sync` job ended `dead`, or get_brain_health reports `sync_blocked`)?** The source's unfinished run stopped on a page request that did not commit and recorded the stop, so it resumes nothing by itself while the other sources keep syncing (#6858: one source stopped for 21 hours while every freshness job reported `completed`). Such a job now ends `dead`: its error names the stop and the run's `next` command, and `gbrain jobs get <id> --json` carries `outcome`, `drain` and `next` in its progress. Doctor warns as soon as a run is blocked and fails once it has been blocked for more than an hour; get_brain_health turns to `attention` past the same hour, with a count band and no source names. A sync pass that stopped before it finished (in discovery, path `<discovery>`, or on one file) counts as blocked too, until a later sync of the source succeeds. Run `gbrain sync status --source <id> --json` (read-only): it names the page, its fault class and its exit. Clear the cause it names and run the step it prints; the next freshness job resumes the run once the cause is gone. A page publication that `gbrain repair stuck-recovery --keep disk` abandoned is not a blocker: the next plain sync retries that page after the rest of its run, imports it when the kept file is committed, and holds it `worktree_dirty` otherwise.--<a id="managed-sync-not-moving"></a>**The catch-up is parked (`sources status --json` says `data_moving: false`, doctor warns `managed_sync_not_moving`, `gbrain sources writer movement` exited 1), or the drain stopped `drain_stalled` with `cause: owner_wedged_here`?** Liveness is not movement: `/health` can be ok, the pid alive and `sync_running: true` while no page has committed for weeks. A managed source is *not moving* when an unfinished `managed-sync` cursor has had neither a committed `managed_sync_*` receipt nor a head step advance for longer than `persistence.preparation_ceiling_ms` (600 s) while a drain or a full consumer is live on the owner host; with nothing live it is `movement_state: parked` (a cursor left between cron runs; informational, not scored). A parked cursor whose write queue still holds admitted requests while no consumer runs and nothing has moved for longer than that ceiling is stranded: nothing will ever drain it, so doctor `managed_sync_not_moving` fails (#6552, #6712 PR 2) and its fix is the resume sync with the cursor's stored options (`gbrain sync --source <id> …`), which consumes the queue itself; `details.stranded` counts such sources. When the sync backlog itself cannot be read, every surface says `movement_state: unknown` (`unknown.reason: backlog_read_failed`) instead of `nothing_pending`: doctor warns with `details.health: unknown`, `sources status` prints a `movement UNKNOWN` line, and `gbrain sources writer movement` exits 1 with code `movement_unknown` (`--warn-only` exits 0); rerun the movement command, and run `gbrain doctor --json` if the read keeps failing. Every surface routes to the same two read-only calls, so the agent reaches the owner, the step and the next action without SQL:--1. `gbrain sources status <id> --json`: `data_moving`, `not_moving_since`, `movement_state` and, beside `data_moving: false`, the exact `gbrain sources writer status --source <id> --json` to run next. Doctor's `managed_sync_not_moving` fix is that same command.-2. `gbrain sources writer status --source <id> --json`: every running claim ends in one `claim.next` envelope (`code` `claim_running`, `claim_overdue` or `claim_lapsed`). `claim_running` carries `retry_after_ms` and a `run` of the same status command while the owner is inside its allowance (the owner's own budget will cut the write; nothing to do but rerun after the delay), `tell_user_to_run` naming the owner `kind` and pid past the ceiling or when the owner reads `restart_required` (restart that process), `run` the printed resume command for a lapsed claim. `host.consumers` lists the processes on this host holding a consumer (pid, kind, mode `full|waiter_only`, started_at, the pool gauge), so a second consumer is visible in the same call.-3. After the restart (or after waiting out the ceiling), `gbrain sources retry-held <id>` re-screens the entry the owner held and prints the sync to run; `gbrain sources writer movement <id>` then waits one window and exits 0 only when a page committed (`moved`) or nothing is pending (`current`). See the [transcript](#managed-sync-wedge-transcript) below for what each step prints.--A `drain_stalled` stop with `cause: owner_wedged_here` is the same situation seen from the sync CLI: a live owner on this host holds the head write past the ceiling or its heartbeat row reads wedged. Before the ceiling the stop is loop-safe (`next.safe_to_loop: true`, `retry_after_ms` set); past it the stop names the pid to restart. Reference: [drain stops](write-refusals.md#drain-stalled).--<a id="two-consumers-on-host"></a>**Doctor warns `two_consumers_on_host`?** Two resident gbrain processes on this host (`serve`, `sync`, `jobs`, `autopilot`, `mcp`) have each run a *full* persistence consumer for more than 30 s, so both claim writes on the same roots. One full consumer per host is a preference, not a fenced role: a `serve` always starts full; every other resident kind probes the `persistence_consumers` heartbeat table at start and on every tick and runs *waiter-only* (it submits and waits, claims nothing) while a live, full, not-wedged consumer of this host exists, promoting itself when that row lapses (60 s), reads wedged or stops being full. Two processes that start within one renewal of each other can both start full, and a sync CLI that took its consumer before the `serve` started keeps it for that run; doctor lists both until one exits. Rows younger than 30 s and short-lived kinds (`put`, `import`, `dream`, `cycle`, `sources`, `cli`) are listed, never warned. `gbrain sources writer status --json` shows them under `host.consumers` (read-only); let the shorter-lived process finish, or restart it so it defers. With `persistence.single_consumer` off (`gbrain config set persistence.single_consumer false`, or `GBRAIN_SINGLE_CONSUMER=0`) every process keeps its own consumer as before and the warning describes the configured behavior. `gbrain sync --no-delegate` keeps that one run's own consumer on either engine.--<a id="consumers-without-heartbeat"></a>**Doctor warns `consumers_without_heartbeat`?** A running claim on this host is stamped by a process (`claim_phase.owner`: kind, pid, gbrain version) that has no `persistence_consumers` row. Every full consumer on this release renews its row every 10 s, so an owner without one runs a gbrain release from before the heartbeat table: it never defers to the resident consumer and the host runs two full consumers until it is upgraded. The check names the pid, kind and version from the stamp; upgrade and restart that process (after the user agrees). A new sync CLI beside an older `serve` says so on its start line (`owner row missing: older serve or no serve; running own consumer`).--<a id="serve-build-drift"></a>**Doctor warns `serve_build_drift` ("serve is running an older build than this checkout; restart serve and workers")?** Upgrading or pulling the checkout does not restart the processes already running from it. Every live consumer on this host writes its gbrain version into its `persistence_consumers` heartbeat row, and the check compares the live `serve`, `sync`, `jobs`, `autopilot` and `mcp` rows with this binary's version in one read. Until they restart, one-shot commands from the checkout (`gbrain sync`, `bun run src/cli.ts …`) run newer code against an older consumer. The check prints the restart for the serve: `systemctl --user restart gbrain-serve.service` or `launchctl kickstart -k gui/<uid>/com.gbrain.serve` when that service is installed, otherwise the pid to stop and start again the way it was launched. Restart each other listed process (the jobs worker, autopilot) the same way, after the user agrees; nothing restarts automatically. A serve older than the heartbeat table writes no row, so this check reads ok beside it and [`consumers_without_heartbeat`](#consumers-without-heartbeat) names it once it holds claims. A serve newer than this checkout is reported, not warned: upgrade the checkout before running one-shot commands from it. Verify with `gbrain doctor --only serve_build_drift --json`; on PGLite there is one process and the check reads ok.--<a id="host-identity-mismatch"></a>**Doctor warns `host_identity_mismatch`, or fence repair, chronicle and other maintenance jobs have reported `owner_unavailable` with reason `host_mismatch` for days?** Host identity is a file, `host.json` under the persistence home (`GBRAIN_HOME`, else `$HOME/.gbrain`). A job worker or container launched with a different `HOME` or without `GBRAIN_HOME` mints a new identity after every restart and sees the binding as another host's, so its writes never reach the owner while every health signal stays green. Doctor flags it when this process's identity differs from the binding owner's and the owner's checkout resolves on this filesystem (same machine id or volume), or, for a container without a stable machine id, when the checkout is present at the binding's path and this `host.json` was minted after the binding under a different `HOME`/`GBRAIN_HOME`. The check names both files, the environment each was minted under (`minted_under: {home, gbrain_home, hostname, machine_id}`; `unknown` for a file minted before it was recorded) and the one-line fix: set `GBRAIN_HOME` on that process's supervisor to the owner's home (the printed value; config appends `.gbrain` itself) and restart it. Nothing re-derives or rewrites an existing `host.json`: re-owning the binding would break every other host sharing the brain. Verify with `gbrain doctor --only host_identity_mismatch --json`.--<a id="managed-sync-wedge-transcript"></a>**What the agent sees while a catch-up is wedged, step by step.** The brain is `default`, the owner is a `gbrain serve` with pid 4121, the sync CLI runs beside it, and the head write of a 16-member bulk group has been `preparing` with nothing in flight at the database. Output is abbreviated to the fields that decide the next step.--```text-$ gbrain sync --source default --no-pull --no-embed-[sync] managed catch-up: 13627 entries frozen, 13412 remaining; publishing in bulk groups (each page keeps its own request).-[sync] 215/13627 processed · stalled 160s on import_screen (waiting on db) · allowed 2m30s · owner serve pid 4121-[sync] 215/13627 processed · stalled 430s on import_screen (waiting on db) · allowed 2m30s · owner serve pid 4121-Managed sync blocked: 215 entries this run (215 written, 0 waived), 13412 remaining.- Oldest unfinished request 01J9W6Y5D0X7K2Q8R4T1V3B9ZC (running), step=import_screen, waiting_on=db, cause=owner_wedged_here, owner serve pid 4121; claimable here: no.- Next: gbrain sync --source default --no-pull --no-embed (safe to rerun in a loop)- Why: The head write is held by gbrain serve (pid 4121) on this host, parked at step import_screen for 430s. Its budget frees the root by the 600 s ceiling (170 s from now) and the next pass holds the entry; rerun then. If it is still held after the ceiling, restart pid 4121.--$ gbrain sources status default --json-{ "id": "default", "managed_sync": { "index": 215, "total": 13627, "held": 0 }, "sync_running": true,- "data_moving": false, "not_moving_since": "2026-10-08T15:02:11Z", "movement_state": "not_moving",- "next": { "command": "gbrain sources writer status --source default --json",- "why": "No page of this source committed and the head write's step did not advance for 11 min while a consumer is live on its owner host." } }--$ gbrain doctor --only managed_sync_not_moving --json-{ "name": "managed_sync_not_moving", "status": "warn",- "message": "Source default has 13412 unfinished entries and a live consumer on this host, but no page committed and no step advanced for 11 min.",- "details": { "source_id": "default", "data_moving": false, "not_moving_since": "2026-10-08T15:02:11Z", "movement_state": "not_moving" },- "fix": { "command": "gbrain sources writer status --source default --json", "next": "run", "actor": "agent", "consent": [] } }--$ gbrain sources writer status --source default --json-{ "host": { "consumers": [- { "pid": 4121, "kind": "serve", "mode": "full", "started_at": "2026-10-08T14:50:03Z", "pool": { "checked_out": 10, "max": 10, "waiters": 3 } },- { "pid": 4388, "kind": "sync", "mode": "waiter_only", "started_at": "2026-10-08T14:51:20Z" } ] },- "blockers": [ { "request_id": "01J9W6Y5D0X7K2Q8R4T1V3B9ZC", "operation": "managed_sync_import", "state": "running",- "claim": { "phase": "preparing", "step": "import_screen", "step_age_ms": 661000, "waiting_on": "pool",- "owner": { "kind": "serve", "pid": 4121, "build": "0.60.113.0" }, "pool": { "checked_out": 10, "max": 10, "waiters": 3 },- "stall": { "reason": "preparation_overdue", "step": "import_screen", "budget_ms": 120000 } },- "next": { "code": "claim_overdue", "retry_after_ms": 0, "fix": { "next": "tell_user_to_run", "actor": "host_admin", "consent": [],- "user_message": "gbrain serve (pid 4121) has held this write at import_screen for 11 min, past the 600 s ceiling, waiting on its connection pool (10 of 10 checked out, 3 waiting). Restart that serve.",- "why": "The owner's budget cut the write at 120 s, but the preparation ignored cancellation and still holds its root barrier; only the owner process can release it now.",- "verify": { "argv": ["gbrain", "sources", "writer", "status", "--source", "default", "--json"] } } } } ],- "data_moving": false, "not_moving_since": "2026-10-08T15:02:11Z", "sync_running": true }--# after the operator restarted pid 4121:-$ gbrain sources retry-held default-Re-screening 1 held entry of source default. Run: gbrain sync --source default --no-pull --no-embed-$ gbrain sources writer movement default-Judging movement for 300 s (preparation budget 120 s + 60 s, floored at 300 s)...-default: moved (3 pages committed, head advanced import_screen -> knowledge_publication). Exit 0.-```--Two calls, no SQL: the doctor or `sources status` row names the command, and `writer status` ends in the action. A `data_moving: false` that returns after the restart means a different owner is wedged or the same one wedged again: the same two calls name it.--<a id="persistence-write-stall"></a>**A managed write stays `running` and later writes queue behind it, or doctor warns `persistence_write_stall`?** The owner keeps renewing a hung claim; doctor warns past `persistence.max_claim_ms` (default 600000) and names the request, root, age, phase and, for a preparation, its step and what it waited on. A claim released and taken again every few seconds never ages that far, so doctor also warns about a running request at least `persistence.max_claim_ms` old when no request on its root (its worktree, or for a database-only request the source's other database-only requests) reached a terminal state within that window (#6635); each stall carries `request_age_ms` and the message uses the larger age. A write stuck *preparing* is released at its deadline and finally held or failed `preparation_stalled` on its own: see [catch-up stuck](#catch-up-stuck). A write stuck *publishing*, or one whose owner predates the deadlines, still needs the owner restarted: run `gbrain sources writer status --source <id> --json` (read-only), then restart the `gbrain serve` that owns the root and attach that output when reporting it.--<a id="terminal-write-failures"></a>**Doctor warns `persistence_terminal_failures`, or `gbrain sync status` reports terminal write failures?** Every write leaves a receipt, and a receipt that ended `failed`, `conflict` or `cancelled` stays in `persistence_requests` until compaction. gbrain reads them at query time and sorts each one into a category with a class, safe actions, whether a person decides, and a structured fix (nothing new is stored). Most rows need no action, so the check separates three things:--- **Active blockers** hold work now: a receipt still holding a publication recovery record (it blocks every queued write on its root), or a receipt that blocks a managed sync's checkpoint. Doctor warns whenever one exists, whatever the trend, and its `fix.command` is the next step (for a recovery record, `gbrain sync --source <id> --no-pull`, which runs the owner pass that clears it; a `recovery_blocked` record names the file to inspect instead).-- **Unresolved rows** are terminal receipts in the window (`persistence.terminal_failures.window_days`, default 7, never longer than `persistence.receipt_retention_days`) that no later write superseded. Doctor warns when any of them is a gbrain-defect class (`owner_exception`, `database_refusal`, `writer_guard`, `outside_fence`, `gbrain_defect`): report those with the receipt ids. The rest are ordinary refusals the caller already received (`caller_conflict`, `caller_refusal`, `operator_cancelled`) or sync faults a rerun retries. A `schema_missing` row (#6904) is a write that met a missing table or column: when the schema is behind, its fix is `gbrain apply-migrations --yes` as the database role that owns the gbrain tables, then resubmit; at head, it asks the user and points at doctor's `schema_missing_tables` check and the `gbrain repair missing-tables` preview.-- **Historical rows** do not block: a later write superseded them (`superseded`, `already_written`, `duplicate`), or they came from a build older than the release that fixed their cause (sync knock-on cancels before 0.60.216.0, the `Publication failed (P0001)` refusal before 0.60.40.0). Doctor counts them and never warns on them.--A spike warns only on its own: when at least `persistence.terminal_failures.spike_min` (default 25) receipts ended in the last 24 h and that is more than `persistence.terminal_failures.spike_factor` (default 3) times the median of the 7 days before. When most of those receipts were written by a gbrain build older than the release that fixed their class, the warning says an older write owner is still producing them and names the build; its fix is the read-only `gbrain sources writer status --source <id> --json` that names the owner, so upgrade or restart that process. A `file_database_drift` row is the page-drift class: [file drift](repair.md#file-drift) resolves it with `gbrain repair file-drift`. A read that does not finish within its deadline (5 s per statement, 2 s to get a connection) reports `unknown`, never a clean pile; rerun it.--```bash-gbrain doctor --only persistence_terminal_failures --json # blockers, unresolved, historical, the fix-gbrain sync status --source <id> # the same summary for one source, with BLOCKING lines-gbrain sources writer failures <id> --group-by category # groups on code + origin + category, each with its drill-down-gbrain sources writer failures <id> --category owner_exception --code storage_error --origin owner_exception --json-gbrain write-request <request> --json # one receipt: write_error_reason, suggestion, diagnosis.fix-```--All five are read-only. `sources writer failures` prints a table, or one JSON document with `--json`; a full page ends with `truncated` and the exact next command (`--before <cursor>`), and `--state all` adds the resolved and historical rows. A receipt whose code and origin do not say what happened (most often an old `storage_error` compacted without its message) is `diagnosis_required`: its fix is the read-only `gbrain sources writer status --source <id> --json`, and nothing is guessed. With `gbrain serve --http`, the admin-only `/metrics` carries the same counts per source (`gbrain_writer_terminal_failures_active_blockers`, `_unresolved`, `_historical`, `_new_24h`, `_defects`, and `_known 0` when the read timed out), from one aggregate shared by every scrape for 60 s; the public `/health` never does. To tune the thresholds:--```bash-gbrain config set persistence.terminal_failures.window_days 14-gbrain config set persistence.terminal_failures.spike_factor 3-gbrain config set persistence.terminal_failures.spike_min 25-```--Refused writes a caller never saw land (`lost_caller_writes`) have their own repair: [failed writes](repair.md#failed-writes). Why a single write was refused: [write refusals](write-refusals.md).--<a id="owner-unavailable"></a>**`fence_repair`, chronicle, fact-fence adoption or another maintenance step refused `owner_unavailable`?** A managed source publishes only through the host that owns its checkout, and the refusal's `reason` says which condition this is; the fix is always the read-only `gbrain sources writer status --source <id> --json`, and nothing claims or transfers ownership to get a step through.--| `reason` | What it means | Next |-|---|---|---|-| `host_mismatch` | Another host id owns the checkout. The message prints both ids' first 8 characters and, to a local caller, the `host.json` this process read (`<GBRAIN_HOME>/.gbrain/persistence/host.json`). A maintenance worker (launchd, cron, autopilot) started with a different `GBRAIN_HOME` or user than the shell that ran the sync reads a different identity file and is, to the brain, a different host. `retryable: false`: a retry from the same environment cannot change the answer. | Run the step on the owner host writer status names, or make both environments use one `GBRAIN_HOME`. Never copy or regenerate `host.json`: a new identity orphans the ownership and pending writes recorded for the old one. |-| `transfer_in_progress` | The worktree is `draining`: a writer transfer was prepared and not yet accepted or cancelled. | `fix.next` is `wait`: retry after 30 s; the status read shows the state. A transfer prepared more than 30 minutes ago never ends on its own, so its refusal reads `ask_user` and names both exits: `gbrain sources writer transfer accept` on the successor, or `gbrain sources writer transfer cancel <source> --expected-epoch <n>` on the owner host (`--dry-run` previews; the worktree returns to active at the same epoch and the prepared manifest is cleared). A drain an older release prepared records no time and keeps the wait, whose `why` names the cancel. |-| `clone_in_progress` | The worktree is `recovering`: a topology clone or reclone is in progress. | `wait`: retry after 30 s; it is `active` when the clone finishes. |-| `binding_missing` | The source has no canonical worktree binding at all. | Claiming a checkout is the host administrator's decision. |-| `incarnation_changed` | The binding belongs to an earlier incarnation of the source (removed and re-added, or restored). | Re-bind the checkout on the brain host. |-| `local_path_missing` | This host owns the worktree but has no checkout path registered. | Register the checkout again on the brain host. |-| `coordination_path_missing` | This host's registration has no coordination directory. | Repair the registration on the brain host. |-| `not_sent`, `outcome_unknown` | The local owner's IPC lane did not take the write, or lost its acknowledgment. | `gbrain sources writer status --probe --json`; for `outcome_unknown` read the receipt (`gbrain write-request -- <id>`) before resubmitting. |--A running sync is not one of these: `gbrain repair fences` now runs during a catch-up for every candidate the sync does not still name ([fence repair during a sync](repair.md#fence-repair-during-a-sync)), and a candidate it does name is `sync_in_progress`, not `owner_unavailable`.--<a id="write-capacity"></a>**Managed writes refused with `queue_capacity`, or doctor warns `persistence_capacity`?** A per-principal or per-brain write-journal limit (`persistence.limits.*`) is full (`queue_capacity`), or doctor sees lifetime request IDs or receipt bytes at 80% or more (`persistence_capacity`). For the cumulative limits (lifetime request IDs and receipt bytes), the warning and the refusal print a `gbrain config set persistence.limits.<limit> <value>` sized for about one more year; run it on the brain host, then retry with the same request ID. For outstanding-request or queued-byte limits, let outstanding writes finish and check `gbrain sources writer status`. Receipt compaction age is `persistence.receipt_retention_days` (default 30). Limits and defaults: [bounded admission and retention](concurrent-writes.md#bounded-admission-and-retention).--<a id="doctor-ops-tier"></a>**`gbrain doctor` is slow on a large brain, or you need to see what is wrong in seconds?** Run `gbrain doctor --tier ops --json`: only the operator sections (write capacity, unresolved write failures, a managed sync cursor that stopped moving, [receipt compaction](repair.md#receipt-compaction) freshness, a serve on an older build, schema-pack consistency, embedding state) under a 4000 ms deadline (`--budget-ms <n>`). A section the deadline cut off reads unknown (`details.health: "unknown"`, `reason: "budget"`, `exact: false`), never clear; the report says `complete: false` and lists it in `unknown_sections`; rerun it with `gbrain doctor --only <name> --json`. On PGLite, serve-only sections read `not_applicable` and the report stays complete. The default doctor runs the same sections first and bounds each check and a plain `--json` run ([doctor budgets](repair.md#doctor-budgets)); above `doctor.orphan_ratio.full_scan_max_pages` pages (default 50000) it samples `orphan_ratio`, and `--tier deep` scans fully. From a thin client, `gbrain doctor --tier ops` (or `--only persistence_capacity`) asks the serve: an admin token gets the ops report, a read token the `get_brain_health` bands (no raw counts), and a serve that predates the ops tier refuses `doctor_tier_unavailable` (run it on the brain host, or upgrade and restart the serve). Agents without a shell call MCP `get_brain_health` (read) or `run_doctor` with `tier: "ops"` (admin).--<a id="dream-paid-loop"></a>**Dream keeps skipping one transcript, or doctor warns `dream_paid_loop`?** A dream key died `dream.breaker.max_dead_submissions` times (default 3) in 24 hours and is refused so it stops billing you. Fix the cause, then `gbrain dream reset-key --list` and `gbrain dream reset-key '<key>'`. See [the paid-loop breaker](../operations/spend-controls.md#dream-paid-loop-breaker-dreambreakermax_dead_submissions).--**Hourly cron sync keeps timing out on a federated brain?** Switch your-cron to a per-source loop with shell `timeout(1)` doing the OS-level kill-and gbrain self-terminating gracefully half-a-minute earlier:--```bash-gbrain sync --break-lock --all --max-age 1800-for src in $(gbrain sources list --json | jq -r '.[].id'); do- timeout 600 gbrain sync --source "$src" --timeout 540 || true-done-```--When `--timeout` fires mid-import, `gbrain sync` exits 0 with status-`partial` and `last_commit` UNCHANGED — the next run re-walks the same-diff and `content_hash` short-circuits already-imported files. The-`--max-age 1800` first command self-heals any wedged-but-alive locks-left by a hung previous run, keyed on the lock's last refresh time-(NOT when it was acquired) so healthy long-running holders are safe by-construction. Scope note: the extract + embed phases still run to-completion once started; `--timeout` interrupts the import walk only.--**Dream cycle silently losing wiki links on Supabase?** The engine-self-retries every bulk batch write (`addLinksBatch` /-`addTimelineEntriesBatch` / `upsertChunks`) on Supavisor pooler blips,-with a 12s worst-case wait that covers the full 5-10s circuit-breaker-recovery window. `gbrain doctor` surfaces incidents via the-`batch_retry_health` check (reads the last 24h of-`~/.gbrain/audit/batch-retry-YYYY-Www.jsonl`). To tune for an unusually-slow pooler:--```bash-# Defaults: 3 retries, base 1s, max 10s, decorrelated jitter.-# Override per operator without a release:-export GBRAIN_BULK_MAX_RETRIES=5 # int >= 0; 0 disables retries-export GBRAIN_BULK_RETRY_BASE_MS=2000 # int > 0-export GBRAIN_BULK_RETRY_MAX_MS=15000 # int >= base-```--Bad values surface at `gbrain doctor` startup with a paste-ready fix-(not at first-retry mid-cycle). PGLite-only installs pay zero cost — the-retry wrap is engine-level, but PGLite has no pooler so retries never-fire in practice.--**Dream cycle losing ~150 link rows per run with `'No database-connection: connect() has not been called'` errors in the log?** The-retry layer self-heals on a nulled-out database singleton: a-`reconnect` callback on `withRetry` rebuilds the connection between-attempts, and `PostgresEngine.batchRetry` injects `() => this.reconnect()`-so engine-level batch writes survive a mid-cycle disconnect by something-else in the same process. `gbrain capture` does not trail a-`'No database connection'` stderr line from a background facts:absorb-worker firing after CLI exit, because op dispatch awaits-`getFactsQueue().drainPending({timeout: 1000})` before-`engine.disconnect()`. To find which code path is still calling-disconnect mid-process, run `gbrain doctor --json | jq '.checks[] |-select(.id=="batch_retry_health")'`; the check surfaces the-24h disconnect-call count and the most-recent caller frame from the-`~/.gbrain/audit/db-disconnect-YYYY-Www.jsonl` audit.--<a id="outdated-build"></a>**`gbrain brainstorm` returning `judge_failed: true` with 0 scored-ideas?** You are on an outdated build. Upgrade with `gbrain upgrade`-(it also runs any pending migrations; no config change is needed), then-confirm with `gbrain --version` and `gbrain doctor --json`. Current builds size the-judge's output cap to the idea count instead of truncating mid-JSON-past ~40 ideas, and slash-form model ids (`gbrain brainstorm---judge-model anthropic/claude-sonnet-4-6 --max-cost 5`) resolve-pricing the same as the colon form instead of failing with-`BudgetExhausted reason=no_pricing`.--**`gbrain reindex --markdown` wiped your auto/dream/signal-detector-tags?** Run `gbrain upgrade`. Tag reconciliation is add-only: re-import-and `reindex --markdown` ADD current frontmatter tags and never delete,-so enrichment tags written to the DB (auto-tag, dream synthesize,-signal-detector) survive a re-chunk. The reindex DB-only fallback also-reconstructs the full markdown (frontmatter + body + timeline) before-re-chunking, so a page with no on-disk source keeps its frontmatter,-title, and timeline instead of getting overwritten with empty-frontmatter. Trade-off: removing a tag from a page's frontmatter does-not remove it from the DB on the next sync (frontmatter-tag removal-needs a provenance column, deferred).--**`gbrain sync` wedges on a large brain (no progress, high CPU)?**-Three tools. First, name the stalling file:--```bash-GBRAIN_SYNC_TRACE=1 gbrain sync --no-pull --no-embed --yes-```--The last `[sync] begin import: <path>` line with no following completion-is the file being processed when the hang hit. Second, if you suspect a-schema-pack `inference.regex` with catastrophic backtracking, complete-the sync with the pack disabled and re-run extraction later:--```bash-gbrain sync --no-schema-pack --no-pull --no-embed --yes-```--`gbrain schema lint` warns on the classic nested-quantifier ReDoS-shapes (`(a+)+`, `(a*)*`, …) in pack regexes, and the runtime caps-inference-regex input length (override via `GBRAIN_MAX_REGEX_INPUT_CHARS`).-Third, on a PGLite brain with a live `gbrain serve` (your agent's MCP-server), `gbrain sync` delegates through authenticated local IPC to the-owner, whether it serves HTTP or stdio. If the client exits, accepted page-requests can finish; repeat the same options to resume the managed sync-cursor. Embeds defer to the owner's background work. See-[`docs/architecture/serve-sync-concurrency.md`](../architecture/serve-sync-concurrency.md)-for supported flags, managed-mode limits and the full triage.--**`gbrain init --migrate-only` / a schema migration fails on Windows-with `getaddrinfo ENOTFOUND`?** Run `gbrain upgrade`. Schema bring-up-runs its phases in-process rather than spawning a child `gbrain init---migrate-only` per phase; a spawned child is what dies on-Windows + bun + Supabase pooler with a DNS-resolution failure even-though the parent connects fine, and running in-process removes the-spawn entirely. The grandfather migration runs as a chunked bulk SQL-pass (keyed on the page PK, soft-delete-filtered, source-safe) and-completes in seconds on an 80K-page PGLite brain.--<a id="ghost-pages"></a>**A write refuses `source_changed` with "The canonical file was removed outside coordinated publication." (`canonical_file_missing`), or doctor `ghost_pages` warns?** The page is a ghost: its canonical file is gone on the owner host but the database page is live, so every write refuses and no sync can import a file that is not there. On the owner host, list them with `gbrain pages ghosts --source <id>` (read-only). For each, the user decides: to keep the page, restore its file at the recorded path (from Git or a backup; gbrain has no automated file restore) and run `gbrain sync --source <id>`; to remove it, preview `gbrain repair ghost-pages --source <id>`, show the user the list, and after they agree run the printed `--apply --expect <hash> --yes`. Removed pages are purged after 72 h; `gbrain restore <slug> --force` undoes one until then. Off the owner host it refuses `not_owner_host`; on an unreadable checkout `ghost_storage_unknown`; when ghosts are more than half of the source's file-backed pages `ghost_mass_delete_refused` (check the checkout first). See [ghost pages](repair.md#ghost-pages). **Say to your agent:** *"Which pages lost their files? Show me the list before you remove anything."*--<a id="maintenance-write-drift"></a>**Writes to the same pages keep refusing `source_changed` with `file_database_drift`, or doctor `maintenance_write_drift` warns?** Each of those pages has a canonical file that differs from its database copy, usually from an edit outside a coordinated write, so every coordinated write to it refuses and leaves a conflict receipt. Maintenance now checks the file first: `synthesize_concepts` skips a drifted concept before any model call (the phase warns and names the commands below) and other maintenance writes refuse before admission, so the pile stops growing. To list the pages, run `gbrain sources reconcile <id> --brain host --audit --conflicts` (read-only; receipts per slug, whether the file still differs, its drift class and producer; MCP `list_write_conflicts` gives remote readers the database-derived part). Then preview `gbrain repair file-drift --source <id> --all-drifted --prefer file` (add `--class <name>` when the preview reports mixed classes, narrow it with `--only '<path glob>'` / `--skip '<path glob>'` over the canonical file paths, or pick pages with `--slug`), show the user the per-page `exceptions`, and after they agree run the printed `--apply --expect <hash>` command exactly as printed. For derived pages under one directory, such as regenerated concepts: (6) preview `gbrain repair file-drift --source default --all-drifted --only 'concepts/**' --prefer database`, show the user the count and the exceptions, and after they agree run the apply command it prints, which applies exactly the previewed pages. To keep resolving such a directory with the database copy from now on, the user can declare it under `storage:` `keep_db:` in the source's gbrain.yml; the owner host's serve, jobs or autopilot consumer then reconciles drifted pages there at most 10 every 10 minutes, and doctor echoes the policy with its matched count and receipt cost ([keep_db](repair.md#file-drift-keep-db)). `--keep` is refused here: use `--prefer database` or `--prefer file`. See [file drift](repair.md#file-drift). **Say to your agent:** *"Which pages keep refusing source_changed? Preview resolving them and show me before you apply."*--<a id="embedding-identity-unqualified"></a>**`facts-absorb` dies with `embedding_configuration` ("records its embedding model without a provider") while `gbrain config get embedding_model` shows a valid `provider:model`, or doctor `embedding_identity_unqualified` warns?** The brain's database `config` row `embedding_model` holds a bare model name from an older install (for example `text-embedding-3-small`), and managed fact extraction reads only that row. `gbrain config set` cannot change it. The doctor check prints the preview with the configured model filled in: run `gbrain migrate embeddings --to <provider:model> --dry-run` (read-only), show the user the cost, and only after they approve run it without `--dry-run`, with `--yes --max-cost-usd <cap>`. It re-embeds active facts even when the model is unchanged, so it is a paid step. When no model is configured outside the database, the check asks for the provider-qualified id instead. **Say to your agent:** *"Why did facts extraction stop with an embedding configuration error?"*--## Embedding state--**Symptom.** Doctor `embedding_state` warns, `get_brain_health` reports-`unsearchable` above zero, or a page you know exists never shows up in search.--**Say to your agent:** *"Which pages can search not see, and why?"* The agent-runs `gbrain pages unsearchable --source <id> --json` (read-only) and follows-each row's `fix`.--Every chunk, and every live page with no chunk row, is in exactly one state,-derived from the rows against the active embedding column (no stored status):--| State | What it means | Exit (each row's `fix`) |-|---|---|---|-| `embedded` | The chunk has a vector in the active column. | None. |-| `pending` | The embed job will embed it (no vector, page live, no `embed_skip`). Doctor `embeddings` ages this backlog and owns its warning. | `gbrain embed --stale --catch-up --source <id> --yes` (paid; preview with `--dry-run`). On a brain keyless by choice keyword search reads these chunks and they do not count as unsearchable. |-| `keyword_only` | The page carries `embed_skip`: the import gate found its body over `content_sanity.bytes_block` (info, by design; its chunks still feed keyword search and are never purged). Removing the marker alone is undone on the next import. | A marker under the current `bytes_block` (written by an older release under its 500 KB default): `gbrain reindex --oversized --source <id>` clears it for free. Otherwise split the page, or, after the operator approves, `gbrain config set content_sanity.bytes_block <bytes>` then `gbrain sync --source <id> --full`, which re-imports and embeds it. |-| `quarantined` | The content-quality gate hid the page as junk; it has no searchable chunks. Doctor `quarantined_pages` owns its warning. | Review with `gbrain quarantine list --json`; clear a false positive with `gbrain quarantine clear <slug> --source-id <id> --force` (the owner's call). |-| `empty` | A live page with no body text: nothing to index. | Write content to it, or delete the stub (`gbrain delete <slug> --source <id> --force`, restorable) after the user agrees. |-| `deleted_page_chunks` | Chunks of a soft-deleted page. Search never reads them; the purge lifecycle removes them after 72 h (info until then, a warning past it, code `deleted_page_chunks_overdue`). | `gbrain pages purge-deleted --dry-run --json`, then `gbrain pages purge-deleted --yes` once the user agrees (brain-wide, irreversible). |-| `chunkless_healable` | A live page with body text but no chunk rows (written without the chunking step). Doctor warns on a keyed brain (code `chunkless_pages_healable`). | `gbrain embed --stale --catch-up --source <id> --yes` chunks and embeds it (paid). |--`unsearchable` sums `pending`, `quarantined`, `empty` and `chunkless_healable`;-`keyword_only` and `deleted_page_chunks` never count. The doctor's ops tier-reads only index-backed counts: vector-less chunks through the partial index-`WHERE <active column> IS NULL` (`content_chunks_stale_idx` for the default-`embedding` column), gated and deleted pages through their indexes, and-`embedded` as a planner estimate (`basis: estimated`); it omits `empty` and-`chunkless_healable` (`unsearchable_complete: false`). A registry-routed brain-whose active column has no such index reports `unknown` there (code-`embedding_state_unknown`, never a slow scan); the standard tier-(`gbrain doctor --only embedding_state --json`) counts every state exactly.-Pending chunks written by a binary older than the pending-age stamp carry no-age: `details.unstamped_pending` gives their count, this writer's version and-a `created_at` lower bound, and never warns on its own.--## Hybrid search returns only keyword hits--**Symptom.** On a large Postgres brain, `gbrain query` answers look keyword-only,-search metadata carries `vector_candidates_incomplete`, or each query takes about-8 seconds. The vector arm ran out of its 8 s candidate budget, usually because-the planner chose a sequential scan over the HNSW index (`idx_chunks_embedding`).--**Say to your agent:** *"Check whether vector search is using its index"* — the-agent runs `gbrain doctor` and reads the `vector_plan` check.--`gbrain doctor` reports `vector_plan` (Postgres only):--- `ok`: the statement vector search sends uses the HNSW index.-- skipped: PGLite, a column wider than pgvector's HNSW cap (exact scan by- design), or fewer than 10,000 embedded chunks (a sequential scan is right- for a small brain).-- warn, index unused: the message names the plan the planner chose and whether- the HNSW index exists and is valid. Fix in this order: upgrade gbrain on the- brain host (`gbrain upgrade`) and rerun `gbrain doctor`; if the index is- missing or INVALID, run the `CREATE INDEX CONCURRENTLY` / `REINDEX INDEX- CONCURRENTLY` command doctor prints.-- warn, stale text above 5%: run `gbrain embed --stale` so chunks edited after- embedding get fresh vectors.-- warn, legacy guard: see below.--**Legacy guard (temporary rollback).** Vector search checks content freshness-outside the HNSW candidate scan. `search.vector_legacy_guard` restores the older-statement, which checked freshness inside the scan. Use it only when vector-search is slower or returns different results than before your upgrade, and-report the regression:--1. The setting belongs to the process that runs searches on the brain host- (`gbrain serve`, autopilot, job workers), never to a thin client.-2. Set it with `gbrain config set search.vector_legacy_guard true`, or export- `GBRAIN_VECTOR_LEGACY_GUARD=1` in that service's environment (the variable- wins over the config key).-3. Restart the owning service. It reads the setting once at its first search and- prints `[gbrain] vector legacy guard active` to stderr.-4. Confirm with `gbrain doctor`: `vector_plan` warns "legacy guard configured …- active after restarting the owning service".-5. Remove it once the regression is fixed: `gbrain config set- search.vector_legacy_guard false` (or unset the variable) and restart again.--**Filtered vector results changed (#6132).** HNSW scans use `relaxed_order`; restore with `gbrain config set search.hnsw_iterative_scan strict_order`, then restart serve.--The guard is temporary. The release that retires it prints a one-time notice-when the inert setting is still present.--## Keyword search times out on a large Postgres brain--**Symptom.** On a large Postgres brain (hundreds of thousands of pages), a-broad `gbrain search` or `gbrain query` with common words takes about 8-seconds and comes back with only vector hits; search metadata carries-`keyword_arm_failed`, and the server log says `canceling statement due to-statement timeout` (SQLSTATE 57014). The strict keyword statement ranks every-matching chunk before its `LIMIT`, so its cost grows with how common the terms-are, and the commonest terms cannot finish inside the keyword statement bound.-An arm that timed out is not evidence of absence: the pages exist, the arm-could not rank them in time.--**Say to your agent:** *"Check whether keyword search is hitting its time-limit"* — the agent runs `gbrain doctor` and reads the `keyword_plan` check.--`gbrain doctor` reports `keyword_plan` (Postgres only):--- `ok`: the brain's commonest keyword term (from the planner's statistics for- `content_chunks.search_vector`) is counted inside half of the bound; the- message shows the plan the planner chose for it.-- skipped: PGLite (no statement timeout), fewer than 10,000 chunks, or no- planner statistics yet (run `ANALYZE content_chunks` on the brain host, or- let the next sync refresh them).-- warn, `canary_timed_out` or `canary_slow`: the commonest term's bounded count- did not finish in 2 s, or took more than half of the bound. Broad queries on- this brain will hit the bound. One canary term is not workload coverage, and- a timed-out count is never "no matches".--**The bound is an operator knob.** `search.keyword_statement_timeout_ms`-(integer milliseconds, default 8000, range 1000 to 60000) is the-transaction-local `statement_timeout` the Postgres engine sets around every-keyword, keyword-count, keyword-page, title and CJK search statement. A remote-caller cannot change it, and `gbrain config set` refuses a value outside the-range (exit 2, nothing written). It is read once per connection, so:--1. Set it on the brain host: `gbrain config set search.keyword_statement_timeout_ms 20000`- (or `search.keyword_statement_timeout_ms` under `search` in the config file,- which wins over the database value).-2. Restart the process that runs searches (`gbrain serve`, autopilot, job- workers); the next CLI command picks it up by itself.-3. Confirm with `gbrain doctor --only keyword_plan --json`: `details.timeout_ms`- shows the value in effect.--A longer bound buys time, not a cheaper statement: a query whose terms match-most of the corpus still reads and ranks every match, so prefer narrowing with-`--source-id` (MCP `source_id`) or `match: "keyword"` paging, and follow-[#6495](https://github.com/garrytan/gbrain/issues/6495) for the bounded-candidate set that will answer broad terms from a capped set instead of-failing open.--**A timed-out keyword search is skipped for 10 minutes.** After hybrid search's-keyword statement hits the bound, a serving process (`gbrain serve`, an MCP-session) skips that exact statement for-`search.keyword_timeout_negative_cache_seconds` (integer seconds, default 600,-range 0 to 86400, 0 turns it off) instead of holding a backend for the whole-bound again. The skipped search answers from the vector arm at once and its-metadata carries `keyword_arm_failed` with reason `skipped_after_timeout`-(error code `keyword_skipped_after_timeout` in `gbrain errors`). The skip-covers the same statement only: the same terms with the same source scope,-types, dates, slug filters, visibility and trust floor of the caller, and the-same keyword bound. A narrower query (another `--source-id`, `--types`,-`--since`) still runs keyword search, another brain is never affected, and-the skip ends by itself when the entry expires, so a brief contention spike-recovers without anyone acting. A call with `use_cache: false` runs the-statement anyway.--Limits: the cache lives in the serving process's memory, so a one-shot CLI-command (`gbrain search …`) starts with an empty cache and gains nothing from-it, and a restart clears it. The TTL is read on the first timeout after the-process starts; a changed value takes effect after a restart. Each timeout-writes one counter row (`search.keyword_timeout_stats`: timeouts, skips counted-since the previous timeout, last timeout time), never one per search, and-`gbrain doctor --only keyword_plan --json` reports it under-`details.negative_cache`. Postgres only: PGLite has no keyword statement-timeout.--## Global maintenance timeouts--**Doctor warns `global_maintenance_timeouts`, or late maintenance phases-(orphans, purge, the brain-wide embed) never seem to run?** On a large brain-one `autopilot-global-maintenance` job may not fit every phase before its-deadline (30 minutes by default). Each job stops starting phases that its-deadline would cut off and the next job resumes at that phase, so one pass can-span several jobs; the resume point is the config row-`autopilot.global_maintenance.progress`. A phase that was running when a job-died is skipped for the rest of that pass so the others still run, and doctor-warns once it has killed three jobs in a row (or the last three jobs all died-at the deadline).--1. Run the named phase in the foreground, without the job deadline:- `gbrain dream --phase <name>` (for example `gbrain dream --phase embed`).-2. Give the job more time if your brain needs it:- `gbrain config set autopilot.global_maintenance_timeout_ms 3600000`, or set- `GBRAIN_GLOBAL_MAINTENANCE_TIMEOUT_MS` in the autopilot service environment- (the variable wins over the config key; values below 60000 are ignored).- Unset both to return to the default.-3. Confirm with `gbrain doctor`: `global_maintenance_timeouts` is `ok` after the- next job finishes within its deadline.--Doctor also warns when the last three dream `patterns` or `synthesize`-subagent children died at their own subagent timeout, even though each-maintenance job completed (the phase records a partial result). Raise that-child's timeout with `gbrain config set dream.<phase>.subagent_timeout_ms <ms>`;-`gbrain dream --phase <phase>` reruns it and spends model tokens, so ask the-user first. The warning clears once that phase's next child completes.--## Global maintenance stalled--**Doctor reports `global_maintenance_stalled`, or `gbrain autopilot --status`-exits 1 with a `Global maintenance:` line?** A brain-wide maintenance pass-stamps `autopilot.last_global_at` only when no phase blocked it. Each blocking-phase keeps a streak in `autopilot.global_maintenance.progress`, keyed by why-it blocked: `fail:<code>` (the phase failed), `budget`, `child:<outcome>` or-`deferred`. After a phase fails with the same code in three passes in a row,-later passes stamp past it (the job result lists it under-`pass_completed_with_failing_phase`) and the phase backs off: it is skipped-for two global intervals, then four, up to a day. Budget, deferral and child-blockers never let a pass stamp past them; child failures back off too.--Doctor warns when the stamp is older than three global intervals-(`autopilot.global_floor_min`, 60 minutes by default) while maintenance jobs-failed or a phase streak is active, fails once it is a week old, and also-warns while passes stamp past a phase that keeps failing. The message names-the phase, its blocker key and back-off, or the last failed job.--1. Run the named phase in the foreground to see its error:- `gbrain dream --phase <name>`. LLM and embedding phases spend tokens, so- ask the user first. With no phase named, read the failed job:- `gbrain jobs get <id>`.-2. Fix the cause the error names, then end the back-off so the next pass- runs the phase again: `gbrain autopilot --retry-global --phase <name>`- (without `--phase`, every backed-off phase). The streak count stays, so a- phase that still fails backs off again. Upgrading gbrain drops every- streak, and a phase that fails for a different reason starts a new one.-3. Confirm with `gbrain doctor --only global_maintenance_stalled`: it is `ok`- after a pass completes with the phase passing.--## auto_chronicle has no effect--**Say to your agent:** *"Why aren't my meetings showing up as timeline events?"*--Automatic event extraction is on by default. See the-[Life Chronicle guide](life-chronicle.md) for what qualifies, the cost, the-three-step check, and the skip codes. `gbrain doctor` reports it as the-`auto_chronicle` check. To turn it off, run-`gbrain config set auto_chronicle false`.--## Upstream rewritten--<a id="upstream-rewritten"></a>--**Say to your agent:** *"My brain repo's remote was force-pushed and sync keeps saying the pull failed. Fix it without losing anything."*--A classic source that syncs with pull fast-forwards its checkout to the-upstream. When that is impossible, the sync still imports local HEAD (nothing-is blocked) and records what it found; the sync result (`upstream` in-`gbrain sync --json`), `gbrain sources status <id> --json` and doctor-`sync_failures` report it with the next step. It is never a sync-failure ledger-row, and the next pull that fast-forwards (or finds nothing to do) clears it.-Before every fetch the sync records the upstream commit the checkout contains,-so the cases are told apart:--- `upstream_rewritten`: the upstream commit the checkout last contained is not in- the new upstream history, so someone force-pushed. A merge would bring back- the commits that push removed, so the fix is a reset after the user agrees:- preview `gbrain sources reset-upstream <id> --expect-local <sha> --expect-upstream <sha> --dry-run`- (doctor prints the exact command), then run it without `--dry-run` and- `gbrain sync --source <id>`.-- `upstream_unknown`: the checkout and upstream diverged and nothing usable was- recorded (the first pull after an upgrade, after an earlier fetch already- brought the rewrite in). Same fix; the preview names any local commit that- was never on the upstream.-- `upstream_diverged`: the checkout has its own commits and the upstream moved- forward normally. Run `gbrain git commit-push --pull --path <checkout>`, then- `gbrain sync --source <id>`.--Nothing is classified while a rebase, merge, cherry-pick or revert is in-progress in the checkout. `reset-upstream` takes the checkout's commit lock-and changes nothing (`reset_upstream_refused`) when HEAD or the upstream moved-since the command was printed (`expect_mismatch`: sync again for a fresh-command), when tracked files have uncommitted edits (`dirty_tree`), or when a-local commit was never on the upstream (`local_commits`: it names them and the-backup ref a reset would create; push or re-apply them first). Otherwise it-keeps the old HEAD under `refs/gbrain/backup/<UTC stamp>-<sha>`, runs-`git reset --keep` to the upstream and verifies HEAD before it reports-`reset`. To get the old history back: `git log <backup ref>`.--## Sync freshness: no successful sync recorded--<a id="sync-freshness-no-successful-sync"></a>--**Say to your agent:** *"Doctor says my source was never synced, but a sync keeps running. What's going on?"*--A sync stamps a source's `last_sync_at` only when it succeeds, so a source whose-syncs keep ending `partial` or failing has none, however many pages it imported.-`gbrain doctor` keeps freshness and sync outcome apart for such a source:--- **First sync running** (`warn`, code `sync_first_run_in_progress`): the source- holds a live sync lock inside the staleness ceiling. Running is not fresh, and- a second sync only contends for the lock, so the fix is to wait and re-run- `gbrain doctor --only sync_freshness --json`. A lock held past the ceiling- reads as wedged (`fail`) with its `--break-lock` command.-- **No successful sync recorded** (`fail`, code `sync_no_successful_sync`): no- sync is running. The message names the last attempt, read-only from the newest- `sync` job and (on a managed brain) `gbrain sync status`: its time, result- (`failed`, `completed (partial)`, a managed error code) and held files, or- `no attempt recorded`. `details.no_successful_sync[]` carries each source's- `reason` and `fix`:- - `attempt_queued`: a sync job is queued or running; wait.- - `holds_pending`: files are held; inspect them with- `gbrain sync status --source <id> --json` and follow its `next`.- - `last_attempt_unsuccessful`: read the job (`gbrain jobs get <id> --json`)- or the managed failure, then retry.- - `no_attempt`: run `gbrain sync --source <id>` (`--no-pull` on a managed brain).diff --git a/llms-full.txt b/llms-full.txtindex 8295138d78..06c10fcc19 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -10399,6 +10399,7 @@ Source: https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/tro| Facts extraction or embedding reports `(cause=AIConfigError model_not_found)` or `gbrain models doctor` says `model_not_found` while the key is valid | the provider refused the model, not the key (a 404, or a 403 "project does not have access to model"): the fix text names the config key that selected the model when the gateway knows it ("Selected via models.tier.reasoning. Fix: gbrain config set …"; an env var or config.json pin says what to clear); otherwise check the model id with `gbrain models`, enable the model for the project in the provider console or set another model (`gbrain config set models.facts <provider:model>`) | user (provider console); agent for the config change, after the user agrees | none | `gbrain models doctor` reports the model `ok` || Doctor `links_extraction_lag` or sync says "N page(s) have un-extracted edges" | `gbrain extract --stale --dry-run --json`, then on the host `gbrain extract --stale --catch-up [--source-id <id>]` | user above 120 s, else agent | none | dry run: `actionable: 0` || Doctor `links_extraction_lag` says "N page(s) failed link extraction 3 runs in a row and are held", or `extract --stale` lists failed pages | Read each page's code (`unknown_source`: the page's source row is gone; restore the source or delete the page), fix the cause, then `gbrain extract --stale [--source-id <id>] --retry-held` | agent | none | `gbrain extract --stale --dry-run --json`: `held: 0` |+| `gbrain apply-migrations --yes` or `gbrain upgrade` stops with `Migration <N> … exhausted retries` / SQLSTATE 57014 and the schema stays behind (`migrations_pending`, reason `still_behind`) | upgrade first (#7108: long backfills run in committed batches), then follow the error's or doctor `schema_version`'s `fix` ([migration statement timeout](#migration-statement-timeout)) | agent; a longer `--statement-timeout` or ending a blocking session only after the user agrees | none for a rerun | `gbrain doctor --only schema_version --json` || A gbrain call failed with a code you don't recognize | follow `fix.next` ([protocol](../protocol/AGENT_OPERATOR_v1.md)); `gbrain errors <code>` | agent | as the fix's `consent` | the fix's `verify` || A graph read omits a relationship you know existed, or says someone still works somewhere they left | the default read returns relationships true today: repeat with `status: "all"` or `as_of`; to record an end, add a dated timeline line (`Ended works_at [[companies/x]]`) or `add_link ... valid_until` ([temporal edges](temporal-edges.md)) | agent | none | `gbrain doctor --only edge_validity --json` || A command exited 3 (`confirmation_required`) | relay `user_message`; run `fix.command` only after the user agrees | agent, after the user agrees | the payload's `effects` | the fix's `verify` |@@ -10467,605 +10468,6 @@ Source: https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/tro<a id="held-files"></a>**Sync held a file (`Held <path>: invalid_frontmatter …`, doctor `git_held_files`, `get_page` shows `file_held`)?** The sync succeeded; only that file waits, and its page (if any) keeps its last good revision and refuses `put_page` until the file is repaired. Run `gbrain sources status <id>`, preview `gbrain repair frontmatter --source <id>`, and after the user agrees run the printed apply. A source a broken file blocked before upgrading recovers on its next sync (`gbrain sync --source <id> --no-pull` does it now). See [held files](repair.md#held-files).-<a id="held-fence-files"></a>**Sync held a file because of its facts or takes fence (`Held <path>: invalid_fence …`)?** Managed sync succeeded; only that file waits. The hold names the fence, section, row numbers, columns and reason, never a cell, and most holds clear by themselves: the maintenance run's `fence_repair` phase repairs the fence on the owner host and commits the file. To see the plan or do it now, run `gbrain repair fences --source <id>` (a read-only preview with no model call), then the apply command it prints; applying needs no extra consent. Model repair spends only within `fences.repair.max_usd_per_page` and `fences.repair.max_usd_per_day`; raising them, or pausing automatic repair with `gbrain config set fences.repair.enabled false`, is the user's call. A hold whose reason is `manual` needs a person: read the page (`gbrain get --source <id> -- <slug>`), edit only that fence in the file (not the frontmatter; `gbrain repair frontmatter` does not touch fences), commit, and run `gbrain sync --source <id> --no-pull`. A `prepare_time` hold was refused against stored rows (for example a takes row number a stored take already uses): fix it as its `fence.reason` says, and after a database-side fix run `gbrain sources retry-held <id>`. A source a fence blocked before upgrading recovers on its next sync. A fence with one obvious meaning is never held: sync rewrites it losslessly, commits the file and reports `fences_normalized`; a `fence_normalized` notice on a write means re-read the page before editing it. `gbrain doctor --only fence_integrity` counts every malformed fence still waiting (held, stored or unsynced) by tier. See [fence holds](write-refusals.md#invalid_fence), [fence repair](repair.md#fences) and the [fence format](fence-format.md).--<a id="concurrent-write-hold"></a>**Sync held a file with `concurrent_write`?** A Git edit raced a database-only write; nothing was overwritten. Preview `gbrain sources reconcile <id> <slug> --preview`, let the user choose, then `gbrain sources retry-held <id>`. See [concurrent_write](write-refusals.md#concurrent_write).--<a id="worktree-dirty-hold"></a>**Sync held a file with `worktree_dirty`?** The working tree holds uncommitted bytes for the file that match neither the pinned commit nor the page (an agent mid-edit on a live checkout), so sync held it instead of overwriting the edit and kept going; nothing is lost and the run finished. Commit the file (or restore it), then `gbrain sync unblock --source <id> --apply` re-screens every held file that is now committed and prints the sync to run; a later commit that changes the file re-screens it on its own. A file held three times is reported `needs_human` by `gbrain sync status`: find out what keeps editing it. Bytes committed at HEAD past the pinned target are imported as HEAD has them, never held. See [worktree_dirty](write-refusals.md#worktree_dirty) and the [sync unblock runbook](sync-unblock-runbook.md).--<a id="catch-up-stuck"></a>**Managed catch-up stuck (one write `running` for minutes while the rest waits), held N files as `preparation_stalled`, or the drain stopped with `preparation_abandoned`, `preparation_systemic` or `write_capacity`?** Every managed write's *preparation* has a deadline (`persistence.sync_preparation_ms`, default 120 s, for sync members; `persistence.maintenance_preparation_ms`, default 120 s, for maintenance writes; a hard ceiling `persistence.preparation_ceiling_ms`, default 600 s; `persistence.max_preparation_attempts`, default 2; all behind the `preparation_deadlines` write switch), so one stuck write is cut off at its budget, but a cut-off preparation that ignores cancellation keeps its root blocked until the ceiling (600 s from the claim's start), when the owner frees the root and the next claim holds the entry; the rest of the source keeps publishing meanwhile, and a sync beside such an owner prints `stalled <N>s on <step>` with the owner's pid and kind from the allowance to the ceiling instead of stopping. One wedge therefore costs up to ten minutes and one held file, never the run. The runbook branches on what you see; every command below is read-only unless it says otherwise, and the files themselves are never the problem in this branch. Start every branch with `gbrain doctor --only serve_build_drift --json`: on a warning, restart serve and its workers on this build first (see [serve build drift](#serve-build-drift)) and stop there until it reads ok.--1. **While it is stuck.** The progress line prints `stalled <N>s on <step>` instead of an ETA. Run `gbrain sources writer status --source <id> --json`: the blocked request's `claim.stall` names the step (`origin_check`, `knowledge_publication`, …), `waiting_on` (`git`, `fs`, `db`, `pool`, or an honest `unknown`), `step_age_ms`, the budget, and the owner process (kind, pid, gbrain version). An owner whose version predates this release never gives up: upgrade it and restart it (`gbrain serve`, the jobs worker or autopilot; the drain's own process ends with the drain). Otherwise wait out the budget: the write is released, retried once, then held. A release does not always free the root: a preparation that ignores cancellation holds its root barrier until the ceiling, and `writer status --json` ends the claim in a `claim.next` that says so (`claim_running` with `retry_after_ms` to the ceiling, or `claim_overdue` as `tell_user_to_run` naming the owner pid once the ceiling has passed or the owner reads `restart_required`).-2. **Held files (`preparation_stalled`).** `gbrain sources status <id> --json` lists them with the step each stalled on; no `gbrain repair` applies. After the cause is fixed (or gbrain upgraded), run `gbrain sources retry-held <id>` and then the same sync with the same options, which the hold's `fix` and `retry-held` print, for example `gbrain sync --source <id> --no-pull --no-embed`. If that sync still has a backlog, it finishes the backlog and then re-screens the scheduled files in the same run. Verify with `gbrain sources status <id> --json` (the held count drops) and `gbrain doctor --only git_held_files --json`. A held deletion keeps its page until that retry. A stalled hold also re-screens by itself when the gbrain version changes.-3. **The drain stopped `preparation_abandoned` (exit 0).** A preparation in the sync's own process was still running past its allowance (its budget plus 30 s) and cannot be cancelled in-process, so the sync exited to end it; `drain.stall.step` says where. Rerun `next.command` (`safe_to_loop` is true): the next pass holds the entry if it stalls again.-4. **The drain stopped `preparation_systemic` (exit 1).** Too many writes stalled in one run (more than `GBRAIN_SYNC_HOLD_ESCALATE_COUNT` / `GBRAIN_SYNC_HOLD_ESCALATE_PCT` of the run's screened imports, or five in a row with no page committed between), so the run stopped with one diagnostic instead of holding every file. `breaker` carries the rule, the counts and the last step. Inspect the writer as in step 1, fix the cause, then rerun the same sync: it re-freezes the stopped entry with a fresh request and re-screens the files that run held.-5. **The drain stopped `write_capacity` (exit 1).** Other writers' requests held the sync writer's outstanding-request cap (`persistence.limits.principal_outstanding`, default 100; on one host the CLI sync shares the `local_cli` principal with fact-fence adoption and `dream`) for the whole 30 s window, so the sync could not admit its next write. It waited and printed `waiting for write capacity (N outstanding of M)` first; nothing failed and the cursor is intact. `gbrain sources writer status --source <id> --json` lists the outstanding requests. Let them finish, or raise the cap (`gbrain config set persistence.limits.principal_outstanding 200`), then rerun the same sync. Reference: [drain stops](write-refusals.md#drain-write-capacity).-6. **A `put_page`, `remember` or maintenance write finished `preparation_stalled`.** Nothing is held: the receipt names the step. Read the writer as in step 1, then resubmit a foreground write under a new `request_id`; the next maintenance run submits its write again.-7. **A manual fence defect among the holds** (`invalid_fence`, reason `manual`, or `repeated_marker`) is a different branch: see [held fence files](#held-fence-files). `gbrain sources status` keeps the kinds apart and routes each to its own command.--Turning the `preparation_deadlines` switch off (`gbrain config set persistence.preparation_deadlines false`) restores the previous behaviour exactly: no deadlines on sync or maintenance writes, no attempt counter, no `preparation_stalled` holds. See [`preparation_stalled`](write-refusals.md#preparation_stalled), [managed sync drain stops](write-refusals.md#managed-sync-drain-stops) and the [timing knobs](live-sync.md#catching-up-a-large-backlog-on-managed-postgres).--<a id="held-connector-items"></a>**A Google or GitHub item is held after repeated failures (doctor `connector_held_items`, `gbrain waiting` says coverage is partial)?** Run `gbrain sources status <id>`, fix the cause, then after the user agrees run `gbrain sources retry-held <id>` and `gbrain sync --source <id>`. See [held items](google-connect.md#held-items).--<a id="retry-other-options"></a>**A sync (or the deprecated `--retry-failed` alias) lists failures that "belong to a run with different sync options"?** A managed retry resumes only the cursor its own options select; each other failure gets one line with its class and the command that settles it. `resumable (replay …)`: an unfinished run holds it, and the command resumes that run under its recorded options. `resumable (fresh discovery, not a replay …)`: no run holds it any more; the command starts a new run from HEAD under the failed run's options, which clears the failure when it completes. For a failure recorded before runs kept their options, the options are recovered only when an option set reproduces its cursor key exactly. `safely orphaned`: nothing current can resume it; preview `gbrain repair managed-sync-orphans --source <id>` and apply with the hash it prints. `unresolved`: its options were never recorded and nothing selects it; the line says what has to finish first (a request still in flight, or a current run whose completion lets the orphan repair retire it).--<a id="checkpoint-validation-timeout"></a>**A managed sync is blocked with `checkpoint_validation_timeout`?** Run the printed commands on the brain host: `gbrain repair request-indexes --apply` when an index is missing or INVALID, then the printed `gbrain sync --source <id> --no-pull …`. Doctor's `persistence_request_growth` warns before lifetime request IDs run out.--<a id="pglite-aborted"></a>**PGLite crashes at startup with `RuntimeError: Aborted()` (often right after a macOS upgrade)?** Not a macOS incompatibility — the OS-upgrade reboot killed gbrain mid-write and tore the data dir's WAL. gbrain repairs this automatically on the next command (data preserved, backup kept); if auto-repair is disabled or skipped, run `gbrain pglite-repair --dry-run` to diagnose and `gbrain pglite-repair --yes` to repair in place. Full recovery ladder (repair → rebuild → engine switch) in [`docs/ENGINES.md` — Troubleshooting: startup abort](../ENGINES.md#troubleshooting-startup-abort-runtimeerror-aborted) and [`docs/INSTALL.md`](../INSTALL.md#pglite-crashes-at-startup-runtimeerror-aborted).--<a id="embedding-dimensions"></a>**`gbrain import` fails with `expected N dimensions, not M`?** Run `gbrain doctor`. It will print the exact `gbrain config set ...` or `gbrain migrate embeddings` command to repair the mismatch (`migrate embeddings` re-embeds through the provider: effect `paid`, ask the user first). You should not need to delete `~/.gbrain`. Fresh `gbrain init --pglite` auto-detects your embedding provider from API keys: set `VOYAGE_API_KEY` (or `OPENAI_API_KEY` / another provider key) in the environment — or in `~/.gbrain/config.json`, which init also reads — before running init, or pass `--embedding-model <provider>:<model>` explicitly. With multiple keys set, init fires an interactive picker (non-TTY auto-picks the Voyage default when its key is present). With no keys at all, init continues keyless (keyword-only search) with a loud notice; add a key later and re-run `gbrain init --force --embedding-model voyage:voyage-4` to enable embeddings (effects: `credentials` and `paid`, since every page is embedded through the provider; it needs the brain's writer lock, so stop a running `gbrain serve` first; pages and facts are kept), or pass `--no-embedding` up front to make keyless explicit. `gbrain config get embedding_disabled` reports whether embedding is off and which plane says so (the config file and the database setting; `true` on either turns it off); `gbrain config set embedding_disabled true|false` and `gbrain config unset embedding_disabled` change both, and the `init --force --embedding-model` enable path clears both. See [`docs/integrations/embedding-providers.md`](../integrations/embedding-providers.md) for the full provider matrix and [`docs/operations/headless-install.md`](../operations/headless-install.md) for Docker/CI sequencing.--<a id="embed-backfill-skipped"></a>**A sync job or `embed-backfill` job reports `embed_backfill_skipped` (reason `embedding_disabled`)?** Nothing is wrong: the brain is keyless by choice (`embedding_disabled`), so sync queues no embed-backfill and a backfill already queued ends on its first attempt without reading a page. Search stays keyword-only. The notice appears once per brain state (the first skip after the brain became keyless); its fix is the optional step that turns embedding on and names the provider key it needs (effects `credentials` and `paid`: ask the user first).--**`gbrain doctor` warns `default_source_local_path`?** Your `default` source has no `local_path` AND that null pointer is provably breaking write-through (the repo fallback is another source's own working tree, or file-backed default pages have no resolvable root). A null `local_path` on its own is the designed fallback topology and reports ok. The repair is a pointer update, never a file move: `gbrain sources set-path default <path>` prints the prior value before changing it and refuses a path that nests inside or swallows another source's tree (exit 6; `--force` bypasses). **Say to your agent:** *"Run a brain health check and fix what you find"* — the maintain skill runs `gbrain doctor` and applies the printed repair.--**A Gmail, Calendar or GitHub connector source still has an old `local_path`?** Connector sources sync from their provider, so autopilot ignores their `local_path`: once a connector has synced (or tried to) at least once, autopilot syncs it on every interval and runs its database phases with no checkout. A connector that has never synced stays idle until you run `gbrain sync --source <id>` once; autopilot prints that command the first time it skips one. To remove the stale pointer, run `gbrain sources set-path <id> --clear` (connector sources only; it refuses a filesystem source and a connector bound to a canonical owner). `config.syncEnabled=false` still opts a source out. **Say to your agent:** *"My Gmail source points at an old folder. Clear it and keep it syncing."*--<a id="write-refused"></a>**A save, sync or background effect was refused with a named reason?** Reasons such as `file_database_drift`, `ambiguous_source_path`, `physical_root_device_changed`, `cursor_processing_options_conflict`, `take_row_collision`, `invalid_source_uri`, `queue_capacity` and parked effects (`targets_parked`, doctor `parked_effects`) each come with a recovery step in the error's `suggestion`. [Write refusal reasons](write-refusals.md) explains each one and its recovery. **Say to your agent:** *"My save was refused. Explain the reason and show me the fix before you run it."*--<a id="doctor-residue"></a>**`gbrain doctor` warns `timeline_history`, `derived_visibility`, or unsealed pages under `contextual_retrieval_coverage`?** Preview the fix with `gbrain repair`, then apply one kind at a time with `gbrain repair <kind> --apply` on the brain host. See [repair residual damage](repair.md).--<a id="extract-health-halts"></a>**Doctor warns `extract_health` with "kind(s) with halt rate > 10%" after the cause was already fixed?** The check is a rate over the last 7 days, not a list of open faults: `halt_count` and `round_completed_count` are 7-day sums from the extraction rollup (one row per kind per day), so halts recorded before a fix keep the rate up until their days leave the window. Read each kind's age before acting: `last halt today` (or `1d ago`) means the extractor is still halting, while `last halt 5d ago` on a kind that has run since means the halts are history. `gbrain doctor --only extract_health --json` gives the same per kind in `details.kinds[]`: `halt_rate`, `last_halt_age_days`, `top_halt_reason` and every reason with its count in `halt_reasons`; runs that stopped at an expected budget or deadline cap count in `expected_limit_count`, not as halts. Fix the reason that is still current, then let the window age out: expiry is how a repaired cause clears, and there is no acknowledgement or reset command. A halt with `last_halt_age_days` at 0 after the fix means the cause is not fixed. **Say to your agent:** *"Is extract_health warning about current halts or old ones?"*--**`gbrain doctor` warns `timeline_orphans`?** Timeline rows from an earlier version of a page are still in the database after the dated bullet was edited or deleted. Preview with `gbrain extract timeline --prune-orphans --dry-run`, then remove them with `gbrain extract timeline --prune-orphans` (add `--source-id <id>` to limit it). Rows no page version ever produced, such as enrichment and meeting fan-out, are kept.--**A doctor check says "Not verified"?** <a id="not-verified-doctor-checks"></a>The check could not read its input, so it reports `warn` instead of `ok`; `gbrain doctor --json` carries `details.code: "not_verified"` and the underlying reason in `details.reason`. Fix the cause, then re-run `gbrain doctor`:--| Check | What it could not read | Fix |-| --- | --- | --- |-| `multi_source_drift` | a source's `local_path` root or a directory below it (`details.unreadable_sources`), the walk hit its bound (`details.limit` files / `details.timeout_ms`), or, for a source whose slugs are pinned to its git root, where `local_path` sits in its git work tree (`details.git_root_skipped`) | fix the path or permissions (`gbrain sources status`); for a large source re-run with `GBRAIN_DRIFT_LIMIT=<files> GBRAIN_DRIFT_TIMEOUT_MS=<ms> gbrain doctor`; for a git-root source, check that `git -C <local_path> rev-parse --show-prefix` succeeds (a checkout git can read and that it trusts) |-| `embed_staleness` | the stale-chunk count (the embed worker's own predicate) | the reason names the database error; re-run `gbrain doctor` once it is fixed |-| `schema_pack_consistency`, `schema_pack_source_drift` | the pages or config query, or a source's active schema pack | `gbrain schema lint --with-db` runs the same classification locally; `gbrain schema active` debugs pack resolution |--`bootstrap_push_health` and `gbrain bootstrap status` report only the push record of the workspace named by this machine's bootstrap receipt; another workspace's stale or failed push is listed as such (a warn naming that workspace), never as this workspace's state. `reranker_health` auth warnings are audit-log history (`details.live_probe_performed: false`), not a live check of the key. These warns can appear while every other check reads green; each one names a check that did not run.--<a id="git-convergence"></a>**`gbrain doctor` warns or fails `git_convergence`, or `bootstrap_push_health` warns that a workspace is ahead?** A Git checkout the brain syncs from (a source's `local_path` or `sync.repo_path`) has commits its upstream does not have, or uncommitted changes, so the system of record on the remote is behind the brain (#5063). Commits not on the upstream warn after 6 hours and fail after 24; uncommitted changes older than 6 hours warn. Doctor compares with the local `@{u}` ref and never fetches, so it is only as fresh as the last fetch; checkouts without an upstream and connector sources are skipped. Commit and push the checkout (`gbrain sources push --path <root>` for a bootstrap workspace; otherwise commit your files with `gbrain git commit-push -m "<msg>" -- <paths>` and publish waiting commits with `gbrain git commit-push --push-only`, see [shared-checkout git](shared-checkout-git.md#outcomes)). `bootstrap_push_health` no longer reports `ok` on a recent successful push while the workspace still has commits not on origin.--<a id="tracked-ownership-marker"></a>**`gbrain doctor` warns `tracked_ownership_marker`, or `gbrain sources push` / `bootstrap verify` refuses a `.gbrain-owner*.json` or `.gbrain-bootstrap.lock/` path?** An ownership marker (`.gbrain-owner.json`, the `.gbrain-owner-<hash>.json` reservation beside a root, a `.gbrain-owner.json.<uuid>.tmp` staging file) or the bootstrap lock directory was committed to a source checkout (#5186). These files are this machine's claim on the checkout, never brain content, and must not reach a remote. Since this fix gbrain appends their patterns to the checkout's `.git/info/exclude` whenever it stamps or adopts a root, the bootstrap `.gitignore` template lists them, and the push deny list refuses a tracked one while an untracked one is excluded from the commit (`excludedUntracked`). None of that un-tracks a file already in the index: run the `git -C <root> rm --cached <paths>` the check prints (the files stay on disk, gbrain keeps reading them), commit, push, then `gbrain doctor --only tracked_ownership_marker --json`. A root stamped before this fix gains the exclude rule on its next stamp or transfer; until then the deny list is the backstop, and `bootstrap verify`'s `deny_globs` treats a merely-on-disk marker as fine. If a marker already reached a remote, rotate it the same way you would any published credential: the token alone is not remote authority (the reservation that proves ownership lives outside the root), but treat the history as exposed.--**`brain_score` shows a low "timeline density (entity and event pages)"?** The 15-point timeline component grades only linkable pages whose type's active-pack primitive is `entity` or `temporal` (people, companies, meetings, emails, events…); reference documents such as notes, writing and guides have no events and are not graded, so do not stamp "page created" rows onto them. Types the pack does not declare are still graded. Raise the score by giving those entity and event pages real timeline entries (`gbrain extract timeline`).--**`gbrain doctor` warns `slug_collisions`, or sync prints slug collisions?** Two or more files in a source map to the same page slug (for example `notes/Foo Bar.md` and `notes/foo-bar.md`), and only one is indexed. Rename all but one file in each group, commit, then sync.--<a id="session-timeouts-not-applied"></a>**Doctor warns `persistence_session_timeouts` with `session_timeouts_not_applied`?** gbrain sets `statement_timeout` (`GBRAIN_STATEMENT_TIMEOUT`, default 5min) and `idle_in_transaction_session_timeout` as connection startup parameters, and a transaction-mode pooler (PgBouncer with `ignore_startup_parameters`, Supavisor) drops them: `SHOW statement_timeout` through the configured URL reads `0`, so a statement outside a transaction has no server-side bound and a relation lock held in another session (a migration's `ALTER TABLE pages` queued behind a long transaction, for example) holds it for as long as the lock lasts. Managed write *preparation* reads are not affected since v0.60.108: they run under a transaction-local `statement_timeout` of the write's remaining preparation budget, so a lock-blocked read ends at the budget and the member is released `preparation_deadline` with no statement left on the server (#6278). For every other autocommit statement, set the default on the role instead of the connection: `ALTER ROLE <gbrain role> SET statement_timeout = '5min'` (read-only to check: `gbrain doctor --only persistence_session_timeouts --json`). Setting `GBRAIN_STATEMENT_TIMEOUT` has no effect through such a pooler.--<a id="managed-sync-blocked"></a>**A managed sync run is blocked (doctor `managed_sync_blocked`, a freshness `sync` job ended `dead`, or get_brain_health reports `sync_blocked`)?** The source's unfinished run stopped on a page request that did not commit and recorded the stop, so it resumes nothing by itself while the other sources keep syncing (#6858: one source stopped for 21 hours while every freshness job reported `completed`). Such a job now ends `dead`: its error names the stop and the run's `next` command, and `gbrain jobs get <id> --json` carries `outcome`, `drain` and `next` in its progress. Doctor warns as soon as a run is blocked and fails once it has been blocked for more than an hour; get_brain_health turns to `attention` past the same hour, with a count band and no source names. A sync pass that stopped before it finished (in discovery, path `<discovery>`, or on one file) counts as blocked too, until a later sync of the source succeeds. Run `gbrain sync status --source <id> --json` (read-only): it names the page, its fault class and its exit. Clear the cause it names and run the step it prints; the next freshness job resumes the run once the cause is gone. A page publication that `gbrain repair stuck-recovery --keep disk` abandoned is not a blocker: the next plain sync retries that page after the rest of its run, imports it when the kept file is committed, and holds it `worktree_dirty` otherwise.--<a id="managed-sync-not-moving"></a>**The catch-up is parked (`sources status --json` says `data_moving: false`, doctor warns `managed_sync_not_moving`, `gbrain sources writer movement` exited 1), or the drain stopped `drain_stalled` with `cause: owner_wedged_here`?** Liveness is not movement: `/health` can be ok, the pid alive and `sync_running: true` while no page has committed for weeks. A managed source is *not moving* when an unfinished `managed-sync` cursor has had neither a committed `managed_sync_*` receipt nor a head step advance for longer than `persistence.preparation_ceiling_ms` (600 s) while a drain or a full consumer is live on the owner host; with nothing live it is `movement_state: parked` (a cursor left between cron runs; informational, not scored). A parked cursor whose write queue still holds admitted requests while no consumer runs and nothing has moved for longer than that ceiling is stranded: nothing will ever drain it, so doctor `managed_sync_not_moving` fails (#6552, #6712 PR 2) and its fix is the resume sync with the cursor's stored options (`gbrain sync --source <id> …`), which consumes the queue itself; `details.stranded` counts such sources. When the sync backlog itself cannot be read, every surface says `movement_state: unknown` (`unknown.reason: backlog_read_failed`) instead of `nothing_pending`: doctor warns with `details.health: unknown`, `sources status` prints a `movement UNKNOWN` line, and `gbrain sources writer movement` exits 1 with code `movement_unknown` (`--warn-only` exits 0); rerun the movement command, and run `gbrain doctor --json` if the read keeps failing. Every surface routes to the same two read-only calls, so the agent reaches the owner, the step and the next action without SQL:--1. `gbrain sources status <id> --json`: `data_moving`, `not_moving_since`, `movement_state` and, beside `data_moving: false`, the exact `gbrain sources writer status --source <id> --json` to run next. Doctor's `managed_sync_not_moving` fix is that same command.-2. `gbrain sources writer status --source <id> --json`: every running claim ends in one `claim.next` envelope (`code` `claim_running`, `claim_overdue` or `claim_lapsed`). `claim_running` carries `retry_after_ms` and a `run` of the same status command while the owner is inside its allowance (the owner's own budget will cut the write; nothing to do but rerun after the delay), `tell_user_to_run` naming the owner `kind` and pid past the ceiling or when the owner reads `restart_required` (restart that process), `run` the printed resume command for a lapsed claim. `host.consumers` lists the processes on this host holding a consumer (pid, kind, mode `full|waiter_only`, started_at, the pool gauge), so a second consumer is visible in the same call.-3. After the restart (or after waiting out the ceiling), `gbrain sources retry-held <id>` re-screens the entry the owner held and prints the sync to run; `gbrain sources writer movement <id>` then waits one window and exits 0 only when a page committed (`moved`) or nothing is pending (`current`). See the [transcript](#managed-sync-wedge-transcript) below for what each step prints.--A `drain_stalled` stop with `cause: owner_wedged_here` is the same situation seen from the sync CLI: a live owner on this host holds the head write past the ceiling or its heartbeat row reads wedged. Before the ceiling the stop is loop-safe (`next.safe_to_loop: true`, `retry_after_ms` set); past it the stop names the pid to restart. Reference: [drain stops](write-refusals.md#drain-stalled).--<a id="two-consumers-on-host"></a>**Doctor warns `two_consumers_on_host`?** Two resident gbrain processes on this host (`serve`, `sync`, `jobs`, `autopilot`, `mcp`) have each run a *full* persistence consumer for more than 30 s, so both claim writes on the same roots. One full consumer per host is a preference, not a fenced role: a `serve` always starts full; every other resident kind probes the `persistence_consumers` heartbeat table at start and on every tick and runs *waiter-only* (it submits and waits, claims nothing) while a live, full, not-wedged consumer of this host exists, promoting itself when that row lapses (60 s), reads wedged or stops being full. Two processes that start within one renewal of each other can both start full, and a sync CLI that took its consumer before the `serve` started keeps it for that run; doctor lists both until one exits. Rows younger than 30 s and short-lived kinds (`put`, `import`, `dream`, `cycle`, `sources`, `cli`) are listed, never warned. `gbrain sources writer status --json` shows them under `host.consumers` (read-only); let the shorter-lived process finish, or restart it so it defers. With `persistence.single_consumer` off (`gbrain config set persistence.single_consumer false`, or `GBRAIN_SINGLE_CONSUMER=0`) every process keeps its own consumer as before and the warning describes the configured behavior. `gbrain sync --no-delegate` keeps that one run's own consumer on either engine.--<a id="consumers-without-heartbeat"></a>**Doctor warns `consumers_without_heartbeat`?** A running claim on this host is stamped by a process (`claim_phase.owner`: kind, pid, gbrain version) that has no `persistence_consumers` row. Every full consumer on this release renews its row every 10 s, so an owner without one runs a gbrain release from before the heartbeat table: it never defers to the resident consumer and the host runs two full consumers until it is upgraded. The check names the pid, kind and version from the stamp; upgrade and restart that process (after the user agrees). A new sync CLI beside an older `serve` says so on its start line (`owner row missing: older serve or no serve; running own consumer`).--<a id="serve-build-drift"></a>**Doctor warns `serve_build_drift` ("serve is running an older build than this checkout; restart serve and workers")?** Upgrading or pulling the checkout does not restart the processes already running from it. Every live consumer on this host writes its gbrain version into its `persistence_consumers` heartbeat row, and the check compares the live `serve`, `sync`, `jobs`, `autopilot` and `mcp` rows with this binary's version in one read. Until they restart, one-shot commands from the checkout (`gbrain sync`, `bun run src/cli.ts …`) run newer code against an older consumer. The check prints the restart for the serve: `systemctl --user restart gbrain-serve.service` or `launchctl kickstart -k gui/<uid>/com.gbrain.serve` when that service is installed, otherwise the pid to stop and start again the way it was launched. Restart each other listed process (the jobs worker, autopilot) the same way, after the user agrees; nothing restarts automatically. A serve older than the heartbeat table writes no row, so this check reads ok beside it and [`consumers_without_heartbeat`](#consumers-without-heartbeat) names it once it holds claims. A serve newer than this checkout is reported, not warned: upgrade the checkout before running one-shot commands from it. Verify with `gbrain doctor --only serve_build_drift --json`; on PGLite there is one process and the check reads ok.--<a id="host-identity-mismatch"></a>**Doctor warns `host_identity_mismatch`, or fence repair, chronicle and other maintenance jobs have reported `owner_unavailable` with reason `host_mismatch` for days?** Host identity is a file, `host.json` under the persistence home (`GBRAIN_HOME`, else `$HOME/.gbrain`). A job worker or container launched with a different `HOME` or without `GBRAIN_HOME` mints a new identity after every restart and sees the binding as another host's, so its writes never reach the owner while every health signal stays green. Doctor flags it when this process's identity differs from the binding owner's and the owner's checkout resolves on this filesystem (same machine id or volume), or, for a container without a stable machine id, when the checkout is present at the binding's path and this `host.json` was minted after the binding under a different `HOME`/`GBRAIN_HOME`. The check names both files, the environment each was minted under (`minted_under: {home, gbrain_home, hostname, machine_id}`; `unknown` for a file minted before it was recorded) and the one-line fix: set `GBRAIN_HOME` on that process's supervisor to the owner's home (the printed value; config appends `.gbrain` itself) and restart it. Nothing re-derives or rewrites an existing `host.json`: re-owning the binding would break every other host sharing the brain. Verify with `gbrain doctor --only host_identity_mismatch --json`.--<a id="managed-sync-wedge-transcript"></a>**What the agent sees while a catch-up is wedged, step by step.** The brain is `default`, the owner is a `gbrain serve` with pid 4121, the sync CLI runs beside it, and the head write of a 16-member bulk group has been `preparing` with nothing in flight at the database. Output is abbreviated to the fields that decide the next step.--```text-$ gbrain sync --source default --no-pull --no-embed-[sync] managed catch-up: 13627 entries frozen, 13412 remaining; publishing in bulk groups (each page keeps its own request).-[sync] 215/13627 processed · stalled 160s on import_screen (waiting on db) · allowed 2m30s · owner serve pid 4121-[sync] 215/13627 processed · stalled 430s on import_screen (waiting on db) · allowed 2m30s · owner serve pid 4121-Managed sync blocked: 215 entries this run (215 written, 0 waived), 13412 remaining.- Oldest unfinished request 01J9W6Y5D0X7K2Q8R4T1V3B9ZC (running), step=import_screen, waiting_on=db, cause=owner_wedged_here, owner serve pid 4121; claimable here: no.- Next: gbrain sync --source default --no-pull --no-embed (safe to rerun in a loop)- Why: The head write is held by gbrain serve (pid 4121) on this host, parked at step import_screen for 430s. Its budget frees the root by the 600 s ceiling (170 s from now) and the next pass holds the entry; rerun then. If it is still held after the ceiling, restart pid 4121.--$ gbrain sources status default --json-{ "id": "default", "managed_sync": { "index": 215, "total": 13627, "held": 0 }, "sync_running": true,- "data_moving": false, "not_moving_since": "2026-10-08T15:02:11Z", "movement_state": "not_moving",- "next": { "command": "gbrain sources writer status --source default --json",- "why": "No page of this source committed and the head write's step did not advance for 11 min while a consumer is live on its owner host." } }--$ gbrain doctor --only managed_sync_not_moving --json-{ "name": "managed_sync_not_moving", "status": "warn",- "message": "Source default has 13412 unfinished entries and a live consumer on this host, but no page committed and no step advanced for 11 min.",- "details": { "source_id": "default", "data_moving": false, "not_moving_since": "2026-10-08T15:02:11Z", "movement_state": "not_moving" },- "fix": { "command": "gbrain sources writer status --source default --json", "next": "run", "actor": "agent", "consent": [] } }--$ gbrain sources writer status --source default --json-{ "host": { "consumers": [- { "pid": 4121, "kind": "serve", "mode": "full", "started_at": "2026-10-08T14:50:03Z", "pool": { "checked_out": 10, "max": 10, "waiters": 3 } },- { "pid": 4388, "kind": "sync", "mode": "waiter_only", "started_at": "2026-10-08T14:51:20Z" } ] },- "blockers": [ { "request_id": "01J9W6Y5D0X7K2Q8R4T1V3B9ZC", "operation": "managed_sync_import", "state": "running",- "claim": { "phase": "preparing", "step": "import_screen", "step_age_ms": 661000, "waiting_on": "pool",- "owner": { "kind": "serve", "pid": 4121, "build": "0.60.113.0" }, "pool": { "checked_out": 10, "max": 10, "waiters": 3 },- "stall": { "reason": "preparation_overdue", "step": "import_screen", "budget_ms": 120000 } },- "next": { "code": "claim_overdue", "retry_after_ms": 0, "fix": { "next": "tell_user_to_run", "actor": "host_admin", "consent": [],- "user_message": "gbrain serve (pid 4121) has held this write at import_screen for 11 min, past the 600 s ceiling, waiting on its connection pool (10 of 10 checked out, 3 waiting). Restart that serve.",- "why": "The owner's budget cut the write at 120 s, but the preparation ignored cancellation and still holds its root barrier; only the owner process can release it now.",- "verify": { "argv": ["gbrain", "sources", "writer", "status", "--source", "default", "--json"] } } } } ],- "data_moving": false, "not_moving_since": "2026-10-08T15:02:11Z", "sync_running": true }--# after the operator restarted pid 4121:-$ gbrain sources retry-held default-Re-screening 1 held entry of source default. Run: gbrain sync --source default --no-pull --no-embed-$ gbrain sources writer movement default-Judging movement for 300 s (preparation budget 120 s + 60 s, floored at 300 s)...-default: moved (3 pages committed, head advanced import_screen -> knowledge_publication). Exit 0.-```--Two calls, no SQL: the doctor or `sources status` row names the command, and `writer status` ends in the action. A `data_moving: false` that returns after the restart means a different owner is wedged or the same one wedged again: the same two calls name it.--<a id="persistence-write-stall"></a>**A managed write stays `running` and later writes queue behind it, or doctor warns `persistence_write_stall`?** The owner keeps renewing a hung claim; doctor warns past `persistence.max_claim_ms` (default 600000) and names the request, root, age, phase and, for a preparation, its step and what it waited on. A claim released and taken again every few seconds never ages that far, so doctor also warns about a running request at least `persistence.max_claim_ms` old when no request on its root (its worktree, or for a database-only request the source's other database-only requests) reached a terminal state within that window (#6635); each stall carries `request_age_ms` and the message uses the larger age. A write stuck *preparing* is released at its deadline and finally held or failed `preparation_stalled` on its own: see [catch-up stuck](#catch-up-stuck). A write stuck *publishing*, or one whose owner predates the deadlines, still needs the owner restarted: run `gbrain sources writer status --source <id> --json` (read-only), then restart the `gbrain serve` that owns the root and attach that output when reporting it.--<a id="terminal-write-failures"></a>**Doctor warns `persistence_terminal_failures`, or `gbrain sync status` reports terminal write failures?** Every write leaves a receipt, and a receipt that ended `failed`, `conflict` or `cancelled` stays in `persistence_requests` until compaction. gbrain reads them at query time and sorts each one into a category with a class, safe actions, whether a person decides, and a structured fix (nothing new is stored). Most rows need no action, so the check separates three things:--- **Active blockers** hold work now: a receipt still holding a publication recovery record (it blocks every queued write on its root), or a receipt that blocks a managed sync's checkpoint. Doctor warns whenever one exists, whatever the trend, and its `fix.command` is the next step (for a recovery record, `gbrain sync --source <id> --no-pull`, which runs the owner pass that clears it; a `recovery_blocked` record names the file to inspect instead).-- **Unresolved rows** are terminal receipts in the window (`persistence.terminal_failures.window_days`, default 7, never longer than `persistence.receipt_retention_days`) that no later write superseded. Doctor warns when any of them is a gbrain-defect class (`owner_exception`, `database_refusal`, `writer_guard`, `outside_fence`, `gbrain_defect`): report those with the receipt ids. The rest are ordinary refusals the caller already received (`caller_conflict`, `caller_refusal`, `operator_cancelled`) or sync faults a rerun retries. A `schema_missing` row (#6904) is a write that met a missing table or column: when the schema is behind, its fix is `gbrain apply-migrations --yes` as the database role that owns the gbrain tables, then resubmit; at head, it asks the user and points at doctor's `schema_missing_tables` check and the `gbrain repair missing-tables` preview.-- **Historical rows** do not block: a later write superseded them (`superseded`, `already_written`, `duplicate`), or they came from a build older than the release that fixed their cause (sync knock-on cancels before 0.60.216.0, the `Publication failed (P0001)` refusal before 0.60.40.0). Doctor counts them and never warns on them.--A spike warns only on its own: when at least `persistence.terminal_failures.spike_min` (default 25) receipts ended in the last 24 h and that is more than `persistence.terminal_failures.spike_factor` (default 3) times the median of the 7 days before. When most of those receipts were written by a gbrain build older than the release that fixed their class, the warning says an older write owner is still producing them and names the build; its fix is the read-only `gbrain sources writer status --source <id> --json` that names the owner, so upgrade or restart that process. A `file_database_drift` row is the page-drift class: [file drift](repair.md#file-drift) resolves it with `gbrain repair file-drift`. A read that does not finish within its deadline (5 s per statement, 2 s to get a connection) reports `unknown`, never a clean pile; rerun it.--```bash-gbrain doctor --only persistence_terminal_failures --json # blockers, unresolved, historical, the fix-gbrain sync status --source <id> # the same summary for one source, with BLOCKING lines-gbrain sources writer failures <id> --group-by category # groups on code + origin + category, each with its drill-down-gbrain sources writer failures <id> --category owner_exception --code storage_error --origin owner_exception --json-gbrain write-request <request> --json # one receipt: write_error_reason, suggestion, diagnosis.fix-```--All five are read-only. `sources writer failures` prints a table, or one JSON document with `--json`; a full page ends with `truncated` and the exact next command (`--before <cursor>`), and `--state all` adds the resolved and historical rows. A receipt whose code and origin do not say what happened (most often an old `storage_error` compacted without its message) is `diagnosis_required`: its fix is the read-only `gbrain sources writer status --source <id> --json`, and nothing is guessed. With `gbrain serve --http`, the admin-only `/metrics` carries the same counts per source (`gbrain_writer_terminal_failures_active_blockers`, `_unresolved`, `_historical`, `_new_24h`, `_defects`, and `_known 0` when the read timed out), from one aggregate shared by every scrape for 60 s; the public `/health` never does. To tune the thresholds:--```bash-gbrain config set persistence.terminal_failures.window_days 14-gbrain config set persistence.terminal_failures.spike_factor 3-gbrain config set persistence.terminal_failures.spike_min 25-```--Refused writes a caller never saw land (`lost_caller_writes`) have their own repair: [failed writes](repair.md#failed-writes). Why a single write was refused: [write refusals](write-refusals.md).--<a id="owner-unavailable"></a>**`fence_repair`, chronicle, fact-fence adoption or another maintenance step refused `owner_unavailable`?** A managed source publishes only through the host that owns its checkout, and the refusal's `reason` says which condition this is; the fix is always the read-only `gbrain sources writer status --source <id> --json`, and nothing claims or transfers ownership to get a step through.--| `reason` | What it means | Next |-|---|---|---|-| `host_mismatch` | Another host id owns the checkout. The message prints both ids' first 8 characters and, to a local caller, the `host.json` this process read (`<GBRAIN_HOME>/.gbrain/persistence/host.json`). A maintenance worker (launchd, cron, autopilot) started with a different `GBRAIN_HOME` or user than the shell that ran the sync reads a different identity file and is, to the brain, a different host. `retryable: false`: a retry from the same environment cannot change the answer. | Run the step on the owner host writer status names, or make both environments use one `GBRAIN_HOME`. Never copy or regenerate `host.json`: a new identity orphans the ownership and pending writes recorded for the old one. |-| `transfer_in_progress` | The worktree is `draining`: a writer transfer was prepared and not yet accepted or cancelled. | `fix.next` is `wait`: retry after 30 s; the status read shows the state. A transfer prepared more than 30 minutes ago never ends on its own, so its refusal reads `ask_user` and names both exits: `gbrain sources writer transfer accept` on the successor, or `gbrain sources writer transfer cancel <source> --expected-epoch <n>` on the owner host (`--dry-run` previews; the worktree returns to active at the same epoch and the prepared manifest is cleared). A drain an older release prepared records no time and keeps the wait, whose `why` names the cancel. |-| `clone_in_progress` | The worktree is `recovering`: a topology clone or reclone is in progress. | `wait`: retry after 30 s; it is `active` when the clone finishes. |-| `binding_missing` | The source has no canonical worktree binding at all. | Claiming a checkout is the host administrator's decision. |-| `incarnation_changed` | The binding belongs to an earlier incarnation of the source (removed and re-added, or restored). | Re-bind the checkout on the brain host. |-| `local_path_missing` | This host owns the worktree but has no checkout path registered. | Register the checkout again on the brain host. |-| `coordination_path_missing` | This host's registration has no coordination directory. | Repair the registration on the brain host. |-| `not_sent`, `outcome_unknown` | The local owner's IPC lane did not take the write, or lost its acknowledgment. | `gbrain sources writer status --probe --json`; for `outcome_unknown` read the receipt (`gbrain write-request -- <id>`) before resubmitting. |--A running sync is not one of these: `gbrain repair fences` now runs during a catch-up for every candidate the sync does not still name ([fence repair during a sync](repair.md#fence-repair-during-a-sync)), and a candidate it does name is `sync_in_progress`, not `owner_unavailable`.--<a id="write-capacity"></a>**Managed writes refused with `queue_capacity`, or doctor warns `persistence_capacity`?** A per-principal or per-brain write-journal limit (`persistence.limits.*`) is full (`queue_capacity`), or doctor sees lifetime request IDs or receipt bytes at 80% or more (`persistence_capacity`). For the cumulative limits (lifetime request IDs and receipt bytes), the warning and the refusal print a `gbrain config set persistence.limits.<limit> <value>` sized for about one more year; run it on the brain host, then retry with the same request ID. For outstanding-request or queued-byte limits, let outstanding writes finish and check `gbrain sources writer status`. Receipt compaction age is `persistence.receipt_retention_days` (default 30). Limits and defaults: [bounded admission and retention](concurrent-writes.md#bounded-admission-and-retention).--<a id="doctor-ops-tier"></a>**`gbrain doctor` is slow on a large brain, or you need to see what is wrong in seconds?** Run `gbrain doctor --tier ops --json`: only the operator sections (write capacity, unresolved write failures, a managed sync cursor that stopped moving, [receipt compaction](repair.md#receipt-compaction) freshness, a serve on an older build, schema-pack consistency, embedding state) under a 4000 ms deadline (`--budget-ms <n>`). A section the deadline cut off reads unknown (`details.health: "unknown"`, `reason: "budget"`, `exact: false`), never clear; the report says `complete: false` and lists it in `unknown_sections`; rerun it with `gbrain doctor --only <name> --json`. On PGLite, serve-only sections read `not_applicable` and the report stays complete. The default doctor runs the same sections first and bounds each check and a plain `--json` run ([doctor budgets](repair.md#doctor-budgets)); above `doctor.orphan_ratio.full_scan_max_pages` pages (default 50000) it samples `orphan_ratio`, and `--tier deep` scans fully. From a thin client, `gbrain doctor --tier ops` (or `--only persistence_capacity`) asks the serve: an admin token gets the ops report, a read token the `get_brain_health` bands (no raw counts), and a serve that predates the ops tier refuses `doctor_tier_unavailable` (run it on the brain host, or upgrade and restart the serve). Agents without a shell call MCP `get_brain_health` (read) or `run_doctor` with `tier: "ops"` (admin).--<a id="dream-paid-loop"></a>**Dream keeps skipping one transcript, or doctor warns `dream_paid_loop`?** A dream key died `dream.breaker.max_dead_submissions` times (default 3) in 24 hours and is refused so it stops billing you. Fix the cause, then `gbrain dream reset-key --list` and `gbrain dream reset-key '<key>'`. See [the paid-loop breaker](../operations/spend-controls.md#dream-paid-loop-breaker-dreambreakermax_dead_submissions).--**Hourly cron sync keeps timing out on a federated brain?** Switch your-cron to a per-source loop with shell `timeout(1)` doing the OS-level kill-and gbrain self-terminating gracefully half-a-minute earlier:--```bash-gbrain sync --break-lock --all --max-age 1800-for src in $(gbrain sources list --json | jq -r '.[].id'); do- timeout 600 gbrain sync --source "$src" --timeout 540 || true-done-```--When `--timeout` fires mid-import, `gbrain sync` exits 0 with status-`partial` and `last_commit` UNCHANGED — the next run re-walks the same-diff and `content_hash` short-circuits already-imported files. The-`--max-age 1800` first command self-heals any wedged-but-alive locks-left by a hung previous run, keyed on the lock's last refresh time-(NOT when it was acquired) so healthy long-running holders are safe by-construction. Scope note: the extract + embed phases still run to-completion once started; `--timeout` interrupts the import walk only.--**Dream cycle silently losing wiki links on Supabase?** The engine-self-retries every bulk batch write (`addLinksBatch` /-`addTimelineEntriesBatch` / `upsertChunks`) on Supavisor pooler blips,-with a 12s worst-case wait that covers the full 5-10s circuit-breaker-recovery window. `gbrain doctor` surfaces incidents via the-`batch_retry_health` check (reads the last 24h of-`~/.gbrain/audit/batch-retry-YYYY-Www.jsonl`). To tune for an unusually-slow pooler:--```bash-# Defaults: 3 retries, base 1s, max 10s, decorrelated jitter.-# Override per operator without a release:-export GBRAIN_BULK_MAX_RETRIES=5 # int >= 0; 0 disables retries-export GBRAIN_BULK_RETRY_BASE_MS=2000 # int > 0-export GBRAIN_BULK_RETRY_MAX_MS=15000 # int >= base-```--Bad values surface at `gbrain doctor` startup with a paste-ready fix-(not at first-retry mid-cycle). PGLite-only installs pay zero cost — the-retry wrap is engine-level, but PGLite has no pooler so retries never-fire in practice.--**Dream cycle losing ~150 link rows per run with `'No database-connection: connect() has not been called'` errors in the log?** The-retry layer self-heals on a nulled-out database singleton: a-`reconnect` callback on `withRetry` rebuilds the connection between-attempts, and `PostgresEngine.batchRetry` injects `() => this.reconnect()`-so engine-level batch writes survive a mid-cycle disconnect by something-else in the same process. `gbrain capture` does not trail a-`'No database connection'` stderr line from a background facts:absorb-worker firing after CLI exit, because op dispatch awaits-`getFactsQueue().drainPending({timeout: 1000})` before-`engine.disconnect()`. To find which code path is still calling-disconnect mid-process, run `gbrain doctor --json | jq '.checks[] |-select(.id=="batch_retry_health")'`; the check surfaces the-24h disconnect-call count and the most-recent caller frame from the-`~/.gbrain/audit/db-disconnect-YYYY-Www.jsonl` audit.--<a id="outdated-build"></a>**`gbrain brainstorm` returning `judge_failed: true` with 0 scored-ideas?** You are on an outdated build. Upgrade with `gbrain upgrade`-(it also runs any pending migrations; no config change is needed), then-confirm with `gbrain --version` and `gbrain doctor --json`. Current builds size the-judge's output cap to the idea count instead of truncating mid-JSON-past ~40 ideas, and slash-form model ids (`gbrain brainstorm---judge-model anthropic/claude-sonnet-4-6 --max-cost 5`) resolve-pricing the same as the colon form instead of failing with-`BudgetExhausted reason=no_pricing`.--**`gbrain reindex --markdown` wiped your auto/dream/signal-detector-tags?** Run `gbrain upgrade`. Tag reconciliation is add-only: re-import-and `reindex --markdown` ADD current frontmatter tags and never delete,-so enrichment tags written to the DB (auto-tag, dream synthesize,-signal-detector) survive a re-chunk. The reindex DB-only fallback also-reconstructs the full markdown (frontmatter + body + timeline) before-re-chunking, so a page with no on-disk source keeps its frontmatter,-title, and timeline instead of getting overwritten with empty-frontmatter. Trade-off: removing a tag from a page's frontmatter does-not remove it from the DB on the next sync (frontmatter-tag removal-needs a provenance column, deferred).--**`gbrain sync` wedges on a large brain (no progress, high CPU)?**-Three tools. First, name the stalling file:--```bash-GBRAIN_SYNC_TRACE=1 gbrain sync --no-pull --no-embed --yes-```--The last `[sync] begin import: <path>` line with no following completion-is the file being processed when the hang hit. Second, if you suspect a-schema-pack `inference.regex` with catastrophic backtracking, complete-the sync with the pack disabled and re-run extraction later:--```bash-gbrain sync --no-schema-pack --no-pull --no-embed --yes-```--`gbrain schema lint` warns on the classic nested-quantifier ReDoS-shapes (`(a+)+`, `(a*)*`, …) in pack regexes, and the runtime caps-inference-regex input length (override via `GBRAIN_MAX_REGEX_INPUT_CHARS`).-Third, on a PGLite brain with a live `gbrain serve` (your agent's MCP-server), `gbrain sync` delegates through authenticated local IPC to the-owner, whether it serves HTTP or stdio. If the client exits, accepted page-requests can finish; repeat the same options to resume the managed sync-cursor. Embeds defer to the owner's background work. See-[`docs/architecture/serve-sync-concurrency.md`](../architecture/serve-sync-concurrency.md)-for supported flags, managed-mode limits and the full triage.--**`gbrain init --migrate-only` / a schema migration fails on Windows-with `getaddrinfo ENOTFOUND`?** Run `gbrain upgrade`. Schema bring-up-runs its phases in-process rather than spawning a child `gbrain init---migrate-only` per phase; a spawned child is what dies on-Windows + bun + Supabase pooler with a DNS-resolution failure even-though the parent connects fine, and running in-process removes the-spawn entirely. The grandfather migration runs as a chunked bulk SQL-pass (keyed on the page PK, soft-delete-filtered, source-safe) and-completes in seconds on an 80K-page PGLite brain.--<a id="ghost-pages"></a>**A write refuses `source_changed` with "The canonical file was removed outside coordinated publication." (`canonical_file_missing`), or doctor `ghost_pages` warns?** The page is a ghost: its canonical file is gone on the owner host but the database page is live, so every write refuses and no sync can import a file that is not there. On the owner host, list them with `gbrain pages ghosts --source <id>` (read-only). For each, the user decides: to keep the page, restore its file at the recorded path (from Git or a backup; gbrain has no automated file restore) and run `gbrain sync --source <id>`; to remove it, preview `gbrain repair ghost-pages --source <id>`, show the user the list, and after they agree run the printed `--apply --expect <hash> --yes`. Removed pages are purged after 72 h; `gbrain restore <slug> --force` undoes one until then. Off the owner host it refuses `not_owner_host`; on an unreadable checkout `ghost_storage_unknown`; when ghosts are more than half of the source's file-backed pages `ghost_mass_delete_refused` (check the checkout first). See [ghost pages](repair.md#ghost-pages). **Say to your agent:** *"Which pages lost their files? Show me the list before you remove anything."*--<a id="maintenance-write-drift"></a>**Writes to the same pages keep refusing `source_changed` with `file_database_drift`, or doctor `maintenance_write_drift` warns?** Each of those pages has a canonical file that differs from its database copy, usually from an edit outside a coordinated write, so every coordinated write to it refuses and leaves a conflict receipt. Maintenance now checks the file first: `synthesize_concepts` skips a drifted concept before any model call (the phase warns and names the commands below) and other maintenance writes refuse before admission, so the pile stops growing. To list the pages, run `gbrain sources reconcile <id> --brain host --audit --conflicts` (read-only; receipts per slug, whether the file still differs, its drift class and producer; MCP `list_write_conflicts` gives remote readers the database-derived part). Then preview `gbrain repair file-drift --source <id> --all-drifted --prefer file` (add `--class <name>` when the preview reports mixed classes, narrow it with `--only '<path glob>'` / `--skip '<path glob>'` over the canonical file paths, or pick pages with `--slug`), show the user the per-page `exceptions`, and after they agree run the printed `--apply --expect <hash>` command exactly as printed. For derived pages under one directory, such as regenerated concepts: (6) preview `gbrain repair file-drift --source default --all-drifted --only 'concepts/**' --prefer database`, show the user the count and the exceptions, and after they agree run the apply command it prints, which applies exactly the previewed pages. To keep resolving such a directory with the database copy from now on, the user can declare it under `storage:` `keep_db:` in the source's gbrain.yml; the owner host's serve, jobs or autopilot consumer then reconciles drifted pages there at most 10 every 10 minutes, and doctor echoes the policy with its matched count and receipt cost ([keep_db](repair.md#file-drift-keep-db)). `--keep` is refused here: use `--prefer database` or `--prefer file`. See [file drift](repair.md#file-drift). **Say to your agent:** *"Which pages keep refusing source_changed? Preview resolving them and show me before you apply."*--<a id="embedding-identity-unqualified"></a>**`facts-absorb` dies with `embedding_configuration` ("records its embedding model without a provider") while `gbrain config get embedding_model` shows a valid `provider:model`, or doctor `embedding_identity_unqualified` warns?** The brain's database `config` row `embedding_model` holds a bare model name from an older install (for example `text-embedding-3-small`), and managed fact extraction reads only that row. `gbrain config set` cannot change it. The doctor check prints the preview with the configured model filled in: run `gbrain migrate embeddings --to <provider:model> --dry-run` (read-only), show the user the cost, and only after they approve run it without `--dry-run`, with `--yes --max-cost-usd <cap>`. It re-embeds active facts even when the model is unchanged, so it is a paid step. When no model is configured outside the database, the check asks for the provider-qualified id instead. **Say to your agent:** *"Why did facts extraction stop with an embedding configuration error?"*--## Embedding state--**Symptom.** Doctor `embedding_state` warns, `get_brain_health` reports-`unsearchable` above zero, or a page you know exists never shows up in search.--**Say to your agent:** *"Which pages can search not see, and why?"* The agent-runs `gbrain pages unsearchable --source <id> --json` (read-only) and follows-each row's `fix`.--Every chunk, and every live page with no chunk row, is in exactly one state,-derived from the rows against the active embedding column (no stored status):--| State | What it means | Exit (each row's `fix`) |-|---|---|---|-| `embedded` | The chunk has a vector in the active column. | None. |-| `pending` | The embed job will embed it (no vector, page live, no `embed_skip`). Doctor `embeddings` ages this backlog and owns its warning. | `gbrain embed --stale --catch-up --source <id> --yes` (paid; preview with `--dry-run`). On a brain keyless by choice keyword search reads these chunks and they do not count as unsearchable. |-| `keyword_only` | The page carries `embed_skip`: the import gate found its body over `content_sanity.bytes_block` (info, by design; its chunks still feed keyword search and are never purged). Removing the marker alone is undone on the next import. | A marker under the current `bytes_block` (written by an older release under its 500 KB default): `gbrain reindex --oversized --source <id>` clears it for free. Otherwise split the page, or, after the operator approves, `gbrain config set content_sanity.bytes_block <bytes>` then `gbrain sync --source <id> --full`, which re-imports and embeds it. |-| `quarantined` | The content-quality gate hid the page as junk; it has no searchable chunks. Doctor `quarantined_pages` owns its warning. | Review with `gbrain quarantine list --json`; clear a false positive with `gbrain quarantine clear <slug> --source-id <id> --force` (the owner's call). |-| `empty` | A live page with no body text: nothing to index. | Write content to it, or delete the stub (`gbrain delete <slug> --source <id> --force`, restorable) after the user agrees. |-| `deleted_page_chunks` | Chunks of a soft-deleted page. Search never reads them; the purge lifecycle removes them after 72 h (info until then, a warning past it, code `deleted_page_chunks_overdue`). | `gbrain pages purge-deleted --dry-run --json`, then `gbrain pages purge-deleted --yes` once the user agrees (brain-wide, irreversible). |-| `chunkless_healable` | A live page with body text but no chunk rows (written without the chunking step). Doctor warns on a keyed brain (code `chunkless_pages_healable`). | `gbrain embed --stale --catch-up --source <id> --yes` chunks and embeds it (paid). |--`unsearchable` sums `pending`, `quarantined`, `empty` and `chunkless_healable`;-`keyword_only` and `deleted_page_chunks` never count. The doctor's ops tier-reads only index-backed counts: vector-less chunks through the partial index-`WHERE <active column> IS NULL` (`content_chunks_stale_idx` for the default-`embedding` column), gated and deleted pages through their indexes, and-`embedded` as a planner estimate (`basis: estimated`); it omits `empty` and-`chunkless_healable` (`unsearchable_complete: false`). A registry-routed brain-whose active column has no such index reports `unknown` there (code-`embedding_state_unknown`, never a slow scan); the standard tier-(`gbrain doctor --only embedding_state --json`) counts every state exactly.-Pending chunks written by a binary older than the pending-age stamp carry no-age: `details.unstamped_pending` gives their count, this writer's version and-a `created_at` lower bound, and never warns on its own.--## Hybrid search returns only keyword hits--**Symptom.** On a large Postgres brain, `gbrain query` answers look keyword-only,-search metadata carries `vector_candidates_incomplete`, or each query takes about-8 seconds. The vector arm ran out of its 8 s candidate budget, usually because-the planner chose a sequential scan over the HNSW index (`idx_chunks_embedding`).--**Say to your agent:** *"Check whether vector search is using its index"* — the-agent runs `gbrain doctor` and reads the `vector_plan` check.--`gbrain doctor` reports `vector_plan` (Postgres only):--- `ok`: the statement vector search sends uses the HNSW index.-- skipped: PGLite, a column wider than pgvector's HNSW cap (exact scan by- design), or fewer than 10,000 embedded chunks (a sequential scan is right- for a small brain).-- warn, index unused: the message names the plan the planner chose and whether- the HNSW index exists and is valid. Fix in this order: upgrade gbrain on the- brain host (`gbrain upgrade`) and rerun `gbrain doctor`; if the index is- missing or INVALID, run the `CREATE INDEX CONCURRENTLY` / `REINDEX INDEX- CONCURRENTLY` command doctor prints.-- warn, stale text above 5%: run `gbrain embed --stale` so chunks edited after- embedding get fresh vectors.-- warn, legacy guard: see below.--**Legacy guard (temporary rollback).** Vector search checks content freshness-outside the HNSW candidate scan. `search.vector_legacy_guard` restores the older-statement, which checked freshness inside the scan. Use it only when vector-search is slower or returns different results than before your upgrade, and-report the regression:--1. The setting belongs to the process that runs searches on the brain host- (`gbrain serve`, autopilot, job workers), never to a thin client.-2. Set it with `gbrain config set search.vector_legacy_guard true`, or export- `GBRAIN_VECTOR_LEGACY_GUARD=1` in that service's environment (the variable- wins over the config key).-3. Restart the owning service. It reads the setting once at its first search and- prints `[gbrain] vector legacy guard active` to stderr.-4. Confirm with `gbrain doctor`: `vector_plan` warns "legacy guard configured …- active after restarting the owning service".-5. Remove it once the regression is fixed: `gbrain config set- search.vector_legacy_guard false` (or unset the variable) and restart again.--**Filtered vector results changed (#6132).** HNSW scans use `relaxed_order`; restore with `gbrain config set search.hnsw_iterative_scan strict_order`, then restart serve.--The guard is temporary. The release that retires it prints a one-time notice-when the inert setting is still present.--## Keyword search times out on a large Postgres brain--**Symptom.** On a large Postgres brain (hundreds of thousands of pages), a-broad `gbrain search` or `gbrain query` with common words takes about 8-seconds and comes back with only vector hits; search metadata carries-`keyword_arm_failed`, and the server log says `canceling statement due to-statement timeout` (SQLSTATE 57014). The strict keyword statement ranks every-matching chunk before its `LIMIT`, so its cost grows with how common the terms-are, and the commonest terms cannot finish inside the keyword statement bound.-An arm that timed out is not evidence of absence: the pages exist, the arm-could not rank them in time.--**Say to your agent:** *"Check whether keyword search is hitting its time-limit"* — the agent runs `gbrain doctor` and reads the `keyword_plan` check.--`gbrain doctor` reports `keyword_plan` (Postgres only):--- `ok`: the brain's commonest keyword term (from the planner's statistics for- `content_chunks.search_vector`) is counted inside half of the bound; the- message shows the plan the planner chose for it.-- skipped: PGLite (no statement timeout), fewer than 10,000 chunks, or no- planner statistics yet (run `ANALYZE content_chunks` on the brain host, or- let the next sync refresh them).-- warn, `canary_timed_out` or `canary_slow`: the commonest term's bounded count- did not finish in 2 s, or took more than half of the bound. Broad queries on- this brain will hit the bound. One canary term is not workload coverage, and- a timed-out count is never "no matches".--**The bound is an operator knob.** `search.keyword_statement_timeout_ms`-(integer milliseconds, default 8000, range 1000 to 60000) is the-transaction-local `statement_timeout` the Postgres engine sets around every-keyword, keyword-count, keyword-page, title and CJK search statement. A remote-caller cannot change it, and `gbrain config set` refuses a value outside the-range (exit 2, nothing written). It is read once per connection, so:--1. Set it on the brain host: `gbrain config set search.keyword_statement_timeout_ms 20000`- (or `search.keyword_statement_timeout_ms` under `search` in the config file,- which wins over the database value).-2. Restart the process that runs searches (`gbrain serve`, autopilot, job- workers); the next CLI command picks it up by itself.-3. Confirm with `gbrain doctor --only keyword_plan --json`: `details.timeout_ms`- shows the value in effect.--A longer bound buys time, not a cheaper statement: a query whose terms match-most of the corpus still reads and ranks every match, so prefer narrowing with-`--source-id` (MCP `source_id`) or `match: "keyword"` paging, and follow-[#6495](https://github.com/garrytan/gbrain/issues/6495) for the bounded-candidate set that will answer broad terms from a capped set instead of-failing open.--**A timed-out keyword search is skipped for 10 minutes.** After hybrid search's-keyword statement hits the bound, a serving process (`gbrain serve`, an MCP-session) skips that exact statement for-`search.keyword_timeout_negative_cache_seconds` (integer seconds, default 600,-range 0 to 86400, 0 turns it off) instead of holding a backend for the whole-bound again. The skipped search answers from the vector arm at once and its-metadata carries `keyword_arm_failed` with reason `skipped_after_timeout`-(error code `keyword_skipped_after_timeout` in `gbrain errors`). The skip-covers the same statement only: the same terms with the same source scope,-types, dates, slug filters, visibility and trust floor of the caller, and the-same keyword bound. A narrower query (another `--source-id`, `--types`,-`--since`) still runs keyword search, another brain is never affected, and-the skip ends by itself when the entry expires, so a brief contention spike-recovers without anyone acting. A call with `use_cache: false` runs the-statement anyway.--Limits: the cache lives in the serving process's memory, so a one-shot CLI-command (`gbrain search …`) starts with an empty cache and gains nothing from-it, and a restart clears it. The TTL is read on the first timeout after the-process starts; a changed value takes effect after a restart. Each timeout-writes one counter row (`search.keyword_timeout_stats`: timeouts, skips counted-since the previous timeout, last timeout time), never one per search, and-`gbrain doctor --only keyword_plan --json` reports it under-`details.negative_cache`. Postgres only: PGLite has no keyword statement-timeout.--## Global maintenance timeouts--**Doctor warns `global_maintenance_timeouts`, or late maintenance phases-(orphans, purge, the brain-wide embed) never seem to run?** On a large brain-one `autopilot-global-maintenance` job may not fit every phase before its-deadline (30 minutes by default). Each job stops starting phases that its-deadline would cut off and the next job resumes at that phase, so one pass can-span several jobs; the resume point is the config row-`autopilot.global_maintenance.progress`. A phase that was running when a job-died is skipped for the rest of that pass so the others still run, and doctor-warns once it has killed three jobs in a row (or the last three jobs all died-at the deadline).--1. Run the named phase in the foreground, without the job deadline:- `gbrain dream --phase <name>` (for example `gbrain dream --phase embed`).-2. Give the job more time if your brain needs it:- `gbrain config set autopilot.global_maintenance_timeout_ms 3600000`, or set- `GBRAIN_GLOBAL_MAINTENANCE_TIMEOUT_MS` in the autopilot service environment- (the variable wins over the config key; values below 60000 are ignored).- Unset both to return to the default.-3. Confirm with `gbrain doctor`: `global_maintenance_timeouts` is `ok` after the- next job finishes within its deadline.--Doctor also warns when the last three dream `patterns` or `synthesize`-subagent children died at their own subagent timeout, even though each-maintenance job completed (the phase records a partial result). Raise that-child's timeout with `gbrain config set dream.<phase>.subagent_timeout_ms <ms>`;-`gbrain dream --phase <phase>` reruns it and spends model tokens, so ask the-user first. The warning clears once that phase's next child completes.--## Global maintenance stalled--**Doctor reports `global_maintenance_stalled`, or `gbrain autopilot --status`-exits 1 with a `Global maintenance:` line?** A brain-wide maintenance pass-stamps `autopilot.last_global_at` only when no phase blocked it. Each blocking-phase keeps a streak in `autopilot.global_maintenance.progress`, keyed by why-it blocked: `fail:<code>` (the phase failed), `budget`, `child:<outcome>` or-`deferred`. After a phase fails with the same code in three passes in a row,-later passes stamp past it (the job result lists it under-`pass_completed_with_failing_phase`) and the phase backs off: it is skipped-for two global intervals, then four, up to a day. Budget, deferral and child-blockers never let a pass stamp past them; child failures back off too.--Doctor warns when the stamp is older than three global intervals-(`autopilot.global_floor_min`, 60 minutes by default) while maintenance jobs-failed or a phase streak is active, fails once it is a week old, and also-warns while passes stamp past a phase that keeps failing. The message names-the phase, its blocker key and back-off, or the last failed job.--1. Run the named phase in the foreground to see its error:- `gbrain dream --phase <name>`. LLM and embedding phases spend tokens, so- ask the user first. With no phase named, read the failed job:- `gbrain jobs get <id>`.-2. Fix the cause the error names, then end the back-off so the next pass- runs the phase again: `gbrain autopilot --retry-global --phase <name>`- (without `--phase`, every backed-off phase). The streak count stays, so a- phase that still fails backs off again. Upgrading gbrain drops every- streak, and a phase that fails for a different reason starts a new one.-3. Confirm with `gbrain doctor --only global_maintenance_stalled`: it is `ok`- after a pass completes with the phase passing.--## auto_chronicle has no effect--**Say to your agent:** *"Why aren't my meetings showing up as timeline events?"*--Automatic event extraction is on by default. See the-[Life Chronicle guide](life-chronicle.md) for what qualifies, the cost, the-three-step check, and the skip codes. `gbrain doctor` reports it as the-`auto_chronicle` check. To turn it off, run-`gbrain config set auto_chronicle false`.--## Upstream rewritten--<a id="upstream-rewritten"></a>--**Say to your agent:** *"My brain repo's remote was force-pushed and sync keeps saying the pull failed. Fix it without losing anything."*--A classic source that syncs with pull fast-forwards its checkout to the-upstream. When that is impossible, the sync still imports local HEAD (nothing-is blocked) and records what it found; the sync result (`upstream` in-`gbrain sync --json`), `gbrain sources status <id> --json` and doctor-`sync_failures` report it with the next step. It is never a sync-failure ledger-row, and the next pull that fast-forwards (or finds nothing to do) clears it.-Before every fetch the sync records the upstream commit the checkout contains,-so the cases are told apart:--- `upstream_rewritten`: the upstream commit the checkout last contained is not in- the new upstream history, so someone force-pushed. A merge would bring back- the commits that push removed, so the fix is a reset after the user agrees:- preview `gbrain sources reset-upstream <id> --expect-local <sha> --expect-upstream <sha> --dry-run`- (doctor prints the exact command), then run it without `--dry-run` and- `gbrain sync --source <id>`.-- `upstream_unknown`: the checkout and upstream diverged and nothing usable was- recorded (the first pull after an upgrade, after an earlier fetch already- brought the rewrite in). Same fix; the preview names any local commit that- was never on the upstream.-- `upstream_diverged`: the checkout has its own commits and the upstream moved- forward normally. Run `gbrain git commit-push --pull --path <checkout>`, then- `gbrain sync --source <id>`.--Nothing is classified while a rebase, merge, cherry-pick or revert is in-progress in the checkout. `reset-upstream` takes the checkout's commit lock-and changes nothing (`reset_upstream_refused`) when HEAD or the upstream moved-since the command was printed (`expect_mismatch`: sync again for a fresh-command), when tracked files have uncommitted edits (`dirty_tree`), or when a-local commit was never on the upstream (`local_commits`: it names them and the-backup ref a reset would create; push or re-apply them first). Otherwise it-keeps the old HEAD under `refs/gbrain/backup/<UTC stamp>-<sha>`, runs-`git reset --keep` to the upstream and verifies HEAD before it reports-`reset`. To get the old history back: `git log <backup ref>`.--## Sync freshness: no successful sync recorded--<a id="sync-freshness-no-successful-sync"></a>--**Say to your agent:** *"Doctor says my source was never synced, but a sync keeps running. What's going on?"*--A sync stamps a source's `last_sync_at` only when it succeeds, so a source whose-syncs keep ending `partial` or failing has none, however many pages it imported.-`gbrain doctor` keeps freshness and sync outcome apart for such a source:--- **First sync running** (`warn`, code `sync_first_run_in_progress`): the source- holds a live sync lock inside the staleness ceiling. Running is not fresh, and- a second sync only contends for the lock, so the fix is to wait and re-run- `gbrain doctor --only sync_freshness --json`. A lock held past the ceiling- reads as wedged (`fail`) with its `--break-lock` command.-- **No successful sync recorded** (`fail`, code `sync_no_successful_sync`): no- sync is running. The message names the last attempt, read-only from the newest- `sync` job and (on a managed brain) `gbrain sync status`: its time, result- (`failed`, `completed (partial)`, a managed error code) and held files, or- `no attempt recorded`. `details.no_successful_sync[]` carries each source's- `reason` and `fix`:- - `attempt_queued`: a sync job is queued or running; wait.- - `holds_pending`: files are held; inspect them with- `gbrain sync status --source <id> --json` and follow its `next`.- - `last_attempt_unsuccessful`: read the job (`gbrain jobs get <id> --json`)- or the managed failure, then retry.- - `no_attempt`: run `gbrain sync --source <id>` (`--no-pull` on a managed brain).----## docs/guides/exit-codes.mddiff --git a/src/commands/apply-migrations-schema.ts b/src/commands/apply-migrations-schema.tsindex 9238a21602..9cb690b0a2 100644--- a/src/commands/apply-migrations-schema.ts+++ b/src/commands/apply-migrations-schema.ts@@ -24,6 +24,7 @@ import { opError, type OperationError } from '../core/ops/contract.ts';import { PgliteBusyError } from '../core/pglite-lock.ts';import { connectMigrationEngine } from './migrations/run-engine.ts';import { DB_ACCESS_MARKER_PREFIX, shouldEmitDbAccessMarker } from '../core/pg-access-classify.ts';+import { migrationTimeoutAdvice, readMigrationTimeout, type MigrationTimeoutRecord } from '../core/migration-timeout.ts';export type SchemaPendingReason = 'not_applied' | 'still_behind' | 'schema_unreadable';@@ -36,6 +37,8 @@ export interface SchemaPending {pending: number[];/** Redacted read error (`schema_unreadable` only). */read_error?: string;+ /** #7108: the pending migration that last ran out of its statement budget (`still_behind` only). */+ timeout?: MigrationTimeoutRecord;}/** Connect the configured brain and read its schema version. The caller disconnects; a failed read disconnects here. */@@ -66,8 +69,8 @@ async function pendingAbove(version: number | null): Promise<{ latest: number; p}/** The pre-flight's finding when it saw the schema behind and did not bring it to head. */-export async function schemaBehindAtPreflight(version: number, authorized: boolean): Promise<SchemaPending> {- return { reason: authorized ? 'still_behind' : 'not_applied', current: version, ...(await pendingAbove(version)) };+export async function schemaBehindAtPreflight(version: number, authorized: boolean, timeout?: MigrationTimeoutRecord): Promise<SchemaPending> {+ return { reason: authorized ? 'still_behind' : 'not_applied', current: version, ...(await pendingAbove(version)), ...(authorized && timeout ? { timeout } : {}) };}/**@@ -90,6 +93,7 @@ export async function checkSchemaAfterOrchestrators(opts: {try {const { engine, close } = await connectMigrationEngine(cfg);let current: number;+ let timeout: MigrationTimeoutRecord | null = null;try {current = parseInt(await engine.getConfig('version') || '1', 10);const { latest } = await pendingAbove(current);@@ -98,13 +102,14 @@ export async function checkSchemaAfterOrchestrators(opts: {try { await opts.apply(engine, current); } catch (err) { console.error(`Schema migration failed: ${await redactDbError(err)}`); }current = parseInt(await engine.getConfig('version') || '1', 10);}+ if (authorized && current < latest) timeout = await readMigrationTimeout(engine, current);} finally {await close();}lastRead = current;const { latest, pending } = await pendingAbove(current);if (current >= latest) return null;- return { reason: authorized ? 'still_behind' : 'not_applied', current, latest, pending };+ return { reason: authorized ? 'still_behind' : 'not_applied', current, latest, pending, ...(timeout ? { timeout } : {}) };} catch (err) {if (err instanceof PgliteBusyError) throw err;// A PGLite datastore without the config table was never initialized: `gbrain init` creates a brain, not this run.@@ -133,6 +138,13 @@ export function schemaPendingError(p: SchemaPending, rerunWithYes: Action): Oper'Apply them with `gbrain apply-migrations --yes` (or `--force-schema`).',{ reason: p.reason, fix: rerunWithYes });}+ if (p.reason === 'still_behind' && p.timeout) {+ const advice = migrationTimeoutAdvice(p.timeout, { argv: ['gbrain', 'doctor', '--only', 'schema_version', '--json'] });+ return opError('migrations_pending', `Schema migrations are still behind after an authorized run (${where}). ${advice.message}`,+ advice.fix.user_message ?? advice.fix.why,+ { reason: p.reason, why: 'A schema migration ran out of its statement budget, so the run stopped below it; what helps depends on the gbrain release that ran it and on whether a session was blocking it.',+ fix: advice.fix });+ }if (p.reason === 'still_behind') {return opError('migrations_pending', `Schema migrations are still behind after an authorized run (${where}); the schema migration did not apply, and running --yes again repeats that.`,REPORT_SUGGESTION,diff --git a/src/commands/apply-migrations.ts b/src/commands/apply-migrations.tsindex 3941d207e0..705831e894 100644--- a/src/commands/apply-migrations.ts+++ b/src/commands/apply-migrations.ts@@ -54,6 +54,7 @@ import {schemaPendingError,type SchemaPending,} from './apply-migrations-schema.ts';+import { readMigrationTimeout, setMigrationStatementTimeoutMs, type MigrationTimeoutRecord } from '../core/migration-timeout.ts';interface ApplyMigrationsArgs {list: boolean;@@ -82,6 +83,8 @@ interface ApplyMigrationsArgs {skipVerify?: boolean;/** #4364: exit 1 when the DB pre-flight probe fails instead of proceeding filesystem-only. */requireDb: boolean;+ /** #7108: operator-only statement budget (minutes, 0 = none) for this run's schema migrations. */+ statementTimeoutMinutes?: number;help: boolean;}@@ -105,6 +108,11 @@ function parseArgs(args: string[]): ApplyMigrationsArgs {'Example: gbrain apply-migrations --migration 0.53.0 --accept-reviewed-inventory default=<digest> --yes'), COMMAND);accepted[match![1]] = match![2];});+ const budget = val('--statement-timeout');+ if (has('--statement-timeout') && !/^\d+$/.test(budget ?? '')) {+ exitCliError(usageError('--statement-timeout takes whole minutes (0 removes the limit) for this run\'s schema migrations.',+ 'Example: gbrain apply-migrations --yes --statement-timeout 120'), COMMAND);+ }if (mode && !['always', 'pain_triggered', 'off'].includes(mode)) {exitCliError(usageError(`Invalid --mode "${mode}". Allowed: always, pain_triggered, off.`,'Example: gbrain apply-migrations --yes --mode pain_triggered'), COMMAND);@@ -129,6 +137,7 @@ function parseArgs(args: string[]): ApplyMigrationsArgs {forceAll: has('--force-all') || has('--force'),skipVerify: has('--skip-verify'),requireDb: has('--require-db'),+ ...(budget !== undefined && has('--statement-timeout') ? { statementTimeoutMinutes: Number(budget) } : {}),help: has('--help') || has('-h'),};}@@ -186,6 +195,12 @@ Flags:--require-db Exit 1 when the database is unreachableinstead of continuing with thefilesystem-only migration plan.+ --statement-timeout <minutes> Operator escape hatch (#7108): the statement+ budget for this run's schema migrations+ (default 10; 0 removes it). Each one holds+ its table locks that long, so writes wait.+ Use it only when a migration times out with+ nothing blocking it (doctor schema_version).--mode <always|pain_triggered|off> Set minion_mode without prompting.--host-dir <path> Include this directory in host-file walk(default scope: \$HOME/.claude + \$HOME/.openclaw).@@ -526,6 +541,7 @@ export async function runApplyMigrations(args: string[]): Promise<void> {export async function applyMigrations(args: string[]): Promise<{ exitCode: number | undefined; failure?: OperationError }> {const cli = parseArgs(args);if (cli.help) { printHelp(); return { exitCode: undefined }; }+ if (cli.statementTimeoutMinutes !== undefined) setMigrationStatementTimeoutMs(cli.statementTimeoutMinutes * 60_000);const installed = VERSION.replace(/^v/, '').trim() || '0.0.0';const report: RunReport = { doc: { status: 'ok', installed } };@@ -693,7 +709,7 @@ async function runLockedMigrations(}// Pre-flight: schema drift (#1530) and the DB probe (#4364); see preflightSchema.- const { schemaBehind, dbProbe } = await preflightSchema(cli, migrateSchema);+ const { schemaBehind, dbProbe, schemaTimeout } = await preflightSchema(cli, migrateSchema);if (!cli.list && !cli.dryRun) await clearRepoPathWedge(loadCompletedMigrations());const completed = loadCompletedMigrations();@@ -762,7 +778,7 @@ async function runLockedMigrations(const pendingWork = [...plan.partial, ...plan.pending, ...plan.pending_fresh_install];const authorized = cli.yes || cli.nonInteractive;if (schemaBehind && pendingWork.length === 0 && dbProbe.status === 'connected') {- return failSchemaBehind(report, args, await schemaBehindAtPreflight(dbProbe.schemaVer, authorized));+ return failSchemaBehind(report, args, await schemaBehindAtPreflight(dbProbe.schemaVer, authorized, schemaTimeout));}const toRun: Migration[] = [...pendingWork, ...plan.applied.filter(migration => migration.reconcile)].sort((left, right) => compareVersions(left.version, right.version));@@ -923,8 +939,9 @@ function failSchemaBehind(report: RunReport, args: readonly string[], pending: Sasync function preflightSchema(cli: ApplyMigrationsArgs,migrateSchema: (eng: BrainEngine, from: number) => Promise<{ applied: number; current: number }>,-): Promise<{ schemaBehind: boolean; dbProbe: DbProbeOutcome }> {+): Promise<{ schemaBehind: boolean; dbProbe: DbProbeOutcome; schemaTimeout?: MigrationTimeoutRecord }> {let schemaBehind = false;+ let schemaTimeout: MigrationTimeoutRecord | undefined;let dbProbe: DbProbeOutcome = { status: 'skipped', reason: 'no probe attempted' };// Detect schema migrations (migrate.ts) being behind.// apply-migrations historically ran orchestrator migrations only; schema@@ -958,6 +975,7 @@ async function preflightSchema(autoApply: (cli.yes || cli.nonInteractive) && !cli.dryRun && !cli.list,run: () => migrateSchema(eng, schemaVer),});+ if (schemaBehind) schemaTimeout = (await readMigrationTimeout(eng, parseInt(await eng.getConfig('version') || String(schemaVer), 10))) ?? undefined;await eng.disconnect();}}@@ -973,7 +991,7 @@ async function preflightSchema(access: classifyPgAccessError(err, { url: cfg?.database_url ?? null }).reason,};}- return { schemaBehind, dbProbe };+ return { schemaBehind, dbProbe, schemaTimeout };}/** #6696 C5: the clearing step for a wedged migration; it needs the user, since the cause behind the partial runs must be fixed first. */diff --git a/src/commands/doctor/checks/schema-health.ts b/src/commands/doctor/checks/schema-health.tsindex a869eec95a..c67af23c80 100644--- a/src/commands/doctor/checks/schema-health.ts+++ b/src/commands/doctor/checks/schema-health.ts@@ -26,7 +26,8 @@ import type { BrainEngine } from '../../../core/engine.ts';import { connectedEngine, type DoctorContext, type DoctorEntry, doctorHealth } from '../context.ts';import { embeddingsDisabled } from '../../../core/embedding-disabled.ts';import { quoteIdentifier, resolveActiveEmbeddingColumnFromEngine } from '../../../core/search/embedding-column.ts';-import { agentFix, checkError, infoCheck, keylessEnablementFix } from '../check-fix.ts';+import { agentFix, checkError, doctorVerify, infoCheck, keylessEnablementFix } from '../check-fix.ts';+import { migrationTimeoutAdvice, readMigrationTimeout } from '../../../core/migration-timeout.ts';import type { MissingTable, MissingTablesReport } from '../../../core/schema-missing-tables.ts';const MISSING_TABLES_DOCS = 'docs/guides/repair.md#missing-tables';@@ -215,7 +216,13 @@ async function runSchemaVersion(ctx: DoctorContext): Promise<Check[]> {try {const version = await engine.getConfig('version');schemaVersion = parseInt(version || '0', 10);- checks.push({ name: 'schema_version', ...schemaVersionHealth(schemaVersion, LATEST_VERSION) });+ const timeout = schemaVersion > 0 && schemaVersion < LATEST_VERSION ? await readMigrationTimeout(engine, schemaVersion) : null;+ if (timeout) {+ const advice = migrationTimeoutAdvice(timeout, doctorVerify('schema_version'));+ checks.push({ name: 'schema_version', status: 'warn', message: `Version ${schemaVersion}, latest is ${LATEST_VERSION}. ${advice.message}`, details: { migration_timeout: timeout }, fix: advice.fix });+ } else {+ checks.push({ name: 'schema_version', ...schemaVersionHealth(schemaVersion, LATEST_VERSION) });+ }// 6b. Schema columns — gbrain#4421/#4425. The ledger counter alone can// lie: a PgBouncer transaction-mode pooler can swallow an ALTER TABLEdiff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 1c420f87ed..1a773904b4 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -17,7 +17,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'advisor': ['--apply', '--brain', '--help', '--json', '--skills-dir', '--source', '--workspace', '--yes'],'agent': ['--allow-old-serve', '--brain', '--detach', '--fanout-manifest', '--federated-read', '--flags', '--follow', '--harness', '--help', '--http', '--json', '--max-turns', '--mcp-only', '--model', '--no-follow', '--path', '--port', '--preset', '--reissue', '--scopes', '--show-token', '--since', '--source', '--subagent-def', '--surface', '--timeout-ms', '--token-ttl', '--tools', '--url', '--word', '--yes'],'anomalies': ['--brain', '--help', '--json', '--lookback-days', '--mcp-only', '--sigma', '--since', '--source'],- 'apply-migrations': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--apply', '--apply-rewrites', '--backup-confirmed', '--brain', '--break-lock', '--confirm-quiesced', '--content-root', '--dry-run', '--export-db-only', '--export-source', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--help', '--host-dir', '--http', '--install', '--json', '--legacy-lock', '--list', '--locks', '--migrate-only', '--migration', '--mode', '--no-autopilot-install', '--non-interactive', '--path', '--prefer-postgres', '--probe', '--repo', '--require-db', '--skip-verify', '--source', '--uninstall', '--url', '--yes'],+ 'apply-migrations': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--apply', '--apply-rewrites', '--backup-confirmed', '--brain', '--break-lock', '--confirm-quiesced', '--content-root', '--dry-run', '--export-db-only', '--export-source', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--help', '--host-dir', '--http', '--install', '--json', '--legacy-lock', '--list', '--locks', '--migrate-only', '--migration', '--mode', '--no-autopilot-install', '--non-interactive', '--only', '--path', '--prefer-postgres', '--probe', '--repo', '--require-db', '--skip-verify', '--source', '--statement-timeout', '--uninstall', '--url', '--yes'],'auth': ['--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all-new', '--allowed-operations', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--category', '--cleanup-dead-local-locks', '--client', '--code', '--confirm-quiesced', '--confirm-relocated-root', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--disable', '--dry-run', '--enable', '--enable-dcr-insecure', '--expected-epoch', '--expected-state', '--federated-read', '--fix', '--force', '--grant-types', '--group-by', '--help', '--id', '--if-version', '--json', '--limit', '--manifest', '--max-concurrent', '--migrate-legacy', '--min-trust', '--no-pull', '--operations', '--origin', '--parked-pushes', '--pat-file', '--path', '--probe', '--profile', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--replace', '--request-id', '--reset-default', '--scopes', '--self-transfer', '--shared-skills', '--since', '--slug-prefixes', '--source', '--source-ids', '--sources', '--state', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--usage', '--wait', '--warn-only', '--yes'],'autopilot': ['--apply', '--batch', '--brain', '--check', '--dimensions', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expect', '--explain', '--ff-only', '--force', '--force-retry', '--from-pages', '--help', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--markdown', '--max-cost', '--max-rss', '--max-runtime', '--max-usd', '--migrate-only', '--model', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-embed-cache', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--output', '--params', '--path', '--pause', '--phase', '--reader-mode', '--reason', '--refresh-cache', '--refs', '--remediation-plan', '--repo', '--resume', '--retry-global', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--source', '--stale', '--status', '--swap-only', '--tags', '--target', '--trust', '--uninstall', '--user', '--verify', '--version', '--yes'],'backfill': ['--batch-size', '--brain', '--concurrency', '--dry-run', '--fresh', '--help', '--json', '--keep-index', '--list', '--max-errors', '--max-rows', '--resume', '--source'],@@ -34,7 +34,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'check-backlinks': ['--accept-pending', '--background', '--brain', '--dir', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],'check-resolvable': ['--brain', '--dry-run', '--fix', '--help', '--json', '--skills-dir', '--source', '--strict', '--verbose'],'check-update': ['--brain', '--exit-code', '--ff-only', '--force-retry', '--help', '--json', '--markdown', '--migrate-only', '--no-autopilot-install', '--no-bun-floor-check', '--non-interactive', '--refresh-cache', '--refs', '--remediation-plan', '--source', '--swap-only', '--tags', '--version', '--yes'],- 'claw-test': ['--agent', '--apply', '--brain', '--dir', '--force-retry', '--format', '--help', '--json', '--keep-tempdir', '--list-agents', '--live', '--local', '--locks', '--message', '--no-embed', '--no-embedding', '--output-format', '--pglite', '--progress-json', '--run-id', '--scenario', '--skip-verify', '--source', '--version', '--yes'],+ 'claw-test': ['--agent', '--apply', '--brain', '--dir', '--force-retry', '--format', '--help', '--json', '--keep-tempdir', '--list-agents', '--live', '--local', '--locks', '--message', '--no-embed', '--no-embedding', '--output-format', '--pglite', '--progress-json', '--run-id', '--scenario', '--skip-verify', '--source', '--statement-timeout', '--version', '--yes'],'code-callees': ['--all-sources', '--brain', '--force', '--help', '--json', '--lang', '--limit', '--no-embed', '--no-json', '--probe', '--source', '--yes'],'code-callers': ['--all-sources', '--brain', '--force', '--help', '--json', '--lang', '--limit', '--no-embed', '--no-json', '--probe', '--source', '--yes'],'code-def': ['--all-sources', '--brain', '--force', '--help', '--json', '--lang', '--limit', '--no-embed', '--no-json', '--probe', '--source', '--yes'],@@ -46,9 +46,9 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'conversation-parser': ['--brain', '--help', '--json', '--source'],'core': ['--apply', '--brain', '--fail-fast', '--help', '--include-core', '--json', '--priority', '--revision', '--slug', '--source', '--tools-json'],'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--plan', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--search-mode', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],- 'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--legacy-lock', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--timeout', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],+ 'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--legacy-lock', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--statement-timeout', '--supabase', '--timeout', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--items-out', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],- 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--class', '--clear', '--clear-never-installed', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--conversation', '--count', '--cursor', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--fuzzy', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-filters', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--non-interactive', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restore-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],+ 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--class', '--clear', '--clear-never-installed', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--conversation', '--count', '--cursor', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--fuzzy', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-filters', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--non-interactive', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restore-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--statement-timeout', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--probe', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],'edge-proposals': ['--access', '--add', '--all', '--all-applied', '--all-held', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],@@ -77,13 +77,13 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'init': ['--access', '--acknowledge-managed', '--adopt', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--background', '--batch', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--catch-up', '--chat-model', '--check', '--class', '--clear-never-installed', '--client', '--close', '--confirm-relocated-root', '--conflicts', '--content-root', '--conversation', '--cursor', '--db-only', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--explain', '--facts', '--fast', '--file', '--fix', '--force', '--force-retry', '--format', '--fresh-token', '--from', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--install', '--issuer-url', '--json', '--keep', '--keep-checkout', '--key', '--lanes', '--legacy-lock', '--limit', '--list', '--local-postgres', '--markdown', '--max-cost-usd', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--min-n', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-filters', '--no-git', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--older-than', '--once', '--only', '--oversized', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--reset', '--resolve', '--resume', '--retry-failed', '--retry-parked', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--semantic', '--session', '--session-id', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--state', '--status', '--strategy', '--supabase', '--surface', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--body', '--brain', '--check', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--timeout', '--type', '--wait'],- 'jobs': ['--abbrev-ref', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--close', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-ambiguous', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--pull', '--purge', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--row', '--scopes', '--section', '--segment-limit', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],+ 'jobs': ['--abbrev-ref', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--close', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-ambiguous', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--pull', '--purge', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--row', '--scopes', '--section', '--segment-limit', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--statement-timeout', '--status', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],'lint': ['--abbrev-ref', '--accept-pending', '--adopt-slug-path', '--audit', '--autostash', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--conflicts', '--dry-run', '--enable', '--exclude', '--expect-remote', '--expected-epoch', '--expected-revision', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--get', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--infer-entity', '--is-inside-work-tree', '--json', '--keep', '--local', '--local-env-vars', '--manifest', '--max-cost-usd', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-pull', '--no-tags', '--no-verify', '--only', '--pat-file', '--path', '--prefer', '--preview', '--probe', '--progress-interval', '--progress-json', '--provenance', '--pull', '--purge', '--push-only', '--quiet', '--rebase', '--require-clean', '--resolve', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--slugs', '--source', '--source-id', '--timeout', '--unset-all', '--wait', '--yes'],'loops': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],'maintain': ['--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--apply', '--assign-corpus', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--conversation', '--count', '--detach', '--detail', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--entity', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--group-by', '--hard-deadline', '--harness', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--keep-checkout', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-pull', '--once', '--only', '--operations', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--push-only', '--query', '--question', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--safe', '--scope', '--scopes', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--state', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--to', '--token', '--top-k', '--type', '--unindexed', '--url-env', '--user', '--verbose', '--version', '--window', '--workers', '--yes'],'mcp': ['--admin-token-file', '--agent', '--arg', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--queue', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],- 'migrate': ['--accept-pending', '--admin-intent', '--all', '--apply', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--follow', '--force', '--force-retry', '--harness', '--held', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--manifest', '--max-cost', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-migrate', '--non-interactive', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--path', '--pglite', '--plan', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--resume', '--retarget', '--rollback-to-source', '--scope', '--skip-verify', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--trigger-bypass', '--trust', '--url', '--url-env', '--wait', '--yes'],+ 'migrate': ['--accept-pending', '--admin-intent', '--all', '--apply', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--follow', '--force', '--force-retry', '--harness', '--held', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--manifest', '--max-cost', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-migrate', '--non-interactive', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--path', '--pglite', '--plan', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--resume', '--retarget', '--rollback-to-source', '--scope', '--skip-verify', '--slugs', '--source', '--stale', '--statement-timeout', '--status', '--timeout', '--to', '--trigger-bypass', '--trust', '--url', '--url-env', '--wait', '--yes'],'models': ['--batch', '--brain', '--concurrent', '--cycles', '--dim', '--dimensions', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--limit', '--max-tokens', '--max-usd', '--output', '--receipt-dir', '--skip', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--source', '--status', '--task', '--to', '--yes'],'mounts': ['--alias', '--brain', '--database-path', '--database-url', '--db-path', '--db-url', '--engine', '--help', '--id', '--json', '--mcp-url', '--path', '--skills-dir', '--source'],'notability-eval': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--in', '--json', '--out', '--repo', '--skip-llm', '--source', '--status', '--target-high', '--target-low', '--target-medium'],@@ -92,7 +92,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'orphans': ['--accept-pending', '--background', '--brain', '--count', '--explain', '--follow', '--force', '--help', '--include-pseudo', '--json', '--mode', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],'pages': ['--brain', '--dry-run', '--force', '--help', '--json', '--limit', '--older-than', '--retry-parked', '--source', '--state', '--yes'],'pglite-repair': ['--brain', '--break-lock', '--dry-run', '--expect', '--help', '--http', '--json', '--legacy-lock', '--path', '--probe', '--source', '--vectors', '--yes'],- 'post-upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--check', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expand', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--held', '--help', '--host-dir', '--images', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--oversized', '--path', '--pause', '--phase', '--quiet', '--reason', '--refs', '--remediation-plan', '--repo', '--require-db', '--resume', '--retry-global', '--search-mode', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--tags', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],+ 'post-upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--check', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expand', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--held', '--help', '--host-dir', '--images', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--oversized', '--path', '--pause', '--phase', '--quiet', '--reason', '--refs', '--remediation-plan', '--repo', '--require-db', '--resume', '--retry-global', '--search-mode', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--statement-timeout', '--status', '--swap-only', '--tags', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],'pricing': ['--brain', '--help', '--input', '--json', '--max-cost', '--max-runtime', '--output', '--rate', '--source'],'projections': ['--brain', '--dry-run', '--enable-dcr', '--help', '--http', '--images', '--install', '--json', '--limit', '--now', '--only', '--port', '--public-url', '--remove', '--source', '--stale', '--status', '--surface', '--user'],'protocol': ['--access', '--add', '--all', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--provenance', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--synthesize', '--target', '--to', '--token', '--updated-after', '--url', '--yes'],@@ -134,7 +134,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--only', '--reference-date', '--rounds', '--save', '--since', '--source', '--source-id', '--take', '--until', '--with-calibration'],'transcripts': ['--accept-pending', '--all', '--all-discovery', '--apply', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--only', '--progress-interval', '--progress-json', '--purge', '--quiet', '--since', '--source', '--source-id', '--timeout', '--wait'],'trust': ['--accept-all', '--accept-pending', '--all', '--background', '--batch-size', '--brain', '--break-lock', '--db-url', '--dry-run', '--expect', '--explain', '--follow', '--from', '--help', '--http', '--json', '--kind', '--legacy-lock', '--no-accept-pending', '--only', '--path', '--progress-interval', '--progress-json', '--quiet', '--reason', '--reason-family', '--relower', '--remove', '--repair-unknown-markers', '--resume', '--since', '--slug', '--source', '--source-id', '--timeout', '--undo', '--uri-prefix', '--version', '--wait', '--yes'],- 'upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--check', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expand', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--held', '--help', '--host-dir', '--images', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--oversized', '--path', '--pause', '--phase', '--quiet', '--reason', '--refs', '--remediation-plan', '--repo', '--require-db', '--resume', '--retry-global', '--search-mode', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--tags', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],+ 'upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--check', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expand', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--held', '--help', '--host-dir', '--images', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--oversized', '--path', '--pause', '--phase', '--quiet', '--reason', '--refs', '--remediation-plan', '--repo', '--require-db', '--resume', '--retry-global', '--search-mode', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--statement-timeout', '--status', '--swap-only', '--tags', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],'waiting': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],'watch': ['--brain', '--help', '--json', '--max-pages', '--min-confidence', '--source', '--window-turns'],'whoknows': ['--access', '--add', '--all', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--to', '--updated-after', '--url', '--yes'],diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex d64c41cd92..d4881cbde9 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -431,8 +431,8 @@ export const CODES = {suggestion: 'Run the read-only inventory `gbrain apply-migrations --migration <version> --dry-run --json` on the brain host, do each source\'s next step it names (ask the user before publishing or activating), then run `gbrain apply-migrations --yes`.',fix: { argv: ['gbrain', 'apply-migrations', '--list', '--json'], consent: [], actor: 'agent', why: 'Lists each migration\'s status and the read-only inventory command for host work still pending; changes nothing.', requires_exclusive: false } },migrations_pending: { class: 'caller', summary: "Schema migrations are behind (or could not be confirmed at head), or an orchestrator migration is wedged, so the command did not report success.",- why: 'apply-migrations reasons: not_applied: the run had no --yes (or --non-interactive), so it did not apply the schema migrations; the fix applies them with --yes. still_behind: an authorized run tried them and they did not apply; another --yes repeats the failure, so run `gbrain doctor --json` and report. schema_unreadable: the schema version could not be read back after the orchestrators ran, so the run cannot confirm it reached head; report it. wedged: an orchestrator migration ended partial three or more times in a row, so runs skip it until a person fixes the cause and clears it with --force-retry. Each failure names the migrations still pending. schema_behind (#6904): a managed write was refused at admission because the brain schema is below the version this build needs. Not retryable as is (class caller): the same write refuses until the migrations are applied; nothing was admitted, so the request_id was not consumed and the same request_id commits once the schema is migrated (a replay of an already accepted id still reconciles).',- suggestion: 'schema_behind: apply them with `gbrain apply-migrations --yes` as the database role that owns the gbrain tables (the brain host operator when this connection does not own them), then resubmit the write with the same request_id. not_applied: apply them with `gbrain apply-migrations --yes`. still_behind or schema_unreadable: run `gbrain doctor --json` and report it to the user; another --yes repeats the failure. wedged: ask the user, read the migration\'s partial rows in the brain home\'s migrations/completed.jsonl (phases[].detail, if present; apply-migrations prints the resolved path), fix the cause, then `gbrain apply-migrations --force-retry <version>` and `gbrain apply-migrations --yes`.',+ why: 'apply-migrations reasons: not_applied: the run had no --yes (or --non-interactive), so it did not apply the schema migrations; the fix applies them with --yes. still_behind: an authorized run tried them and they did not apply; another --yes repeats the failure, so run `gbrain doctor --json` and report; when a migration ran out of its statement budget (#7108) the error names it and its fix depends on the case: recorded by another gbrain release (rerun), an idle-in-transaction blocker (end it once the user agrees, rerun) or nothing blocking (once the user agrees, one run with --statement-timeout). schema_unreadable: the schema version could not be read back after the orchestrators ran, so the run cannot confirm it reached head; report it. wedged: an orchestrator migration ended partial three or more times in a row, so runs skip it until a person fixes the cause and clears it with --force-retry. Each failure names the migrations still pending. schema_behind (#6904): a managed write was refused at admission because the brain schema is below the version this build needs. Not retryable as is (class caller): the same write refuses until the migrations are applied; nothing was admitted, so the request_id was not consumed and the same request_id commits once the schema is migrated (a replay of an already accepted id still reconciles).',+ suggestion: 'schema_behind: apply them with `gbrain apply-migrations --yes` as the database role that owns the gbrain tables (the brain host operator when this connection does not own them), then resubmit the write with the same request_id. not_applied: apply them with `gbrain apply-migrations --yes`. still_behind or schema_unreadable: run `gbrain doctor --json` and report it to the user; another --yes repeats the failure (a still_behind that names a timed-out migration carries its own fix: follow it). See docs/guides/troubleshooting.md#migration-statement-timeout. wedged: ask the user, read the migration\'s partial rows in the brain home\'s migrations/completed.jsonl (phases[].detail, if present; apply-migrations prints the resolved path), fix the cause, then `gbrain apply-migrations --force-retry <version>` and `gbrain apply-migrations --yes`.',reasons: ['not_applied', 'still_behind', 'schema_unreadable', 'wedged', 'schema_behind'] },migrations_running: { class: 'retryable', summary: "Another apply-migrations run holds the migration orchestration lock.", exit: 75 },missing_source_scope: { class: 'server', summary: "A remote tool call reached dispatch without a resolved source scope; the shared default source is refused." },diff --git a/src/core/migrate.ts b/src/core/migrate.tsindex 73f4a9341c..fe1bc0cef2 100644--- a/src/core/migrate.ts+++ b/src/core/migrate.ts@@ -5,6 +5,8 @@ import { resolveSchemaLockTimeoutMs, schemaLockBlockedError, withSchemaLockTimeoimport { MIGRATIONS } from './schema-migrations/registry.generated.ts';import { hasPendingMigrations } from './migrate-pending.ts';import { setQuietMigrationNotices } from './schema-migrations/helpers.ts';+import { runMigrationPrelude } from './migration-preludes.ts';+import { clearMigrationTimeout, migrationStatementTimeoutMs, recordMigrationTimeout } from './migration-timeout.ts';// runMigrations executes while an initialized engine is live. Keep its helper// modules in the static graph rather than importing them from async handlers.import {@@ -172,6 +174,7 @@ async function runMigrationSQLWithRetry(}}}+ await runMigrationPrelude(engine, m.version);await runMigrationSQL(engine, m, sql);return;} catch (err: unknown) {@@ -215,7 +218,7 @@ export async function runMigrationSQL(await engine.transaction(async (tx) => {if (engine.kind === 'postgres') {try {- await tx.runMigration(m.version, "SET LOCAL statement_timeout = '600000'");+ await tx.runMigration(m.version, `SET LOCAL statement_timeout = '${migrationStatementTimeoutMs()}'`);// #5227 (W14 P1.6): a real transaction, so SET LOCAL binds the lock wait to this migration only.await tx.runMigration(m.version, `SET LOCAL lock_timeout = '${resolveSchemaLockTimeoutMs()}ms'`);} catch {@@ -245,7 +248,7 @@ export async function runMigrationSQL(// BrainEngine.withReservedConnection.await engine.withReservedConnection(async (conn) => {try {- await conn.executeRaw("SET statement_timeout = '600000'");+ await conn.executeRaw(`SET statement_timeout = '${migrationStatementTimeoutMs()}'`);} catch {// Non-fatal: some managed Postgres may restrict this GUC.// Falling through means the DDL runs with the server default.@@ -503,6 +506,9 @@ export async function runMigrations(engine: BrainEngine): Promise<{ applied: num// Quiet fresh-install replay: name the failing migration — without the// per-step lines, the error would otherwise be anonymous.if (quietReplay) process.stderr.write(` [${m.version}] ${m.name} failed\n`);+ // #7108: apply-migrations and doctor read this to name the migration and the step that helps.+ const timedOut = err instanceof MigrationRetryExhausted ? isStatementTimeoutError(err.lastError) : isStatementTimeoutError(err);+ if (timedOut) await recordMigrationTimeout(engine, m, err instanceof MigrationRetryExhausted ? err.lastBlockers.map(b => b.pid) : []);throw err;}@@ -514,6 +520,7 @@ export async function runMigrations(engine: BrainEngine): Promise<{ applied: num// covers every exit path from here on (incl. the pre-flight probe).setQuietMigrationNotices(false);}+ await clearMigrationTimeout(engine);await backfill();return { applied, current: LATEST_VERSION };}@@ -545,13 +552,14 @@ async function applyOneMigration(engine: BrainEngine, m: Migration): Promise<voiconsole.error('');} else {console.error('');- console.error(' Cause: another connection holds a lock on the target table, or the');- console.error(' server statement_timeout (~2 min on Supabase) is too short for this DDL.');+ console.error(` Cause: no idle-in-transaction session was blocking it, so the migration's own work`);+ console.error(` outlasted its ${Math.round(migrationStatementTimeoutMs() / 60_000)}-minute statement budget on this brain; every attempt rolled back.`);+ console.error(' A plain rerun with this gbrain release repeats the failure (#7108).');console.error('');console.error(' Fix:');- console.error(' 1. gbrain doctor --locks # find idle-in-transaction blockers');- console.error(' 2. Terminate blocker(s) shown by step 1 via pg_terminate_backend(<pid>)');- console.error(' 3. gbrain apply-migrations --yes # re-run from the version that failed');+ console.error(' 1. gbrain doctor --locks # confirm no session holds a lock on the table');+ console.error(' 2. If a newer gbrain release exists: gbrain upgrade, then gbrain apply-migrations --yes');+ console.error(" 3. Otherwise, with the user's agreement: gbrain apply-migrations --yes --statement-timeout 120, and report it");console.error('');}console.error(' Verify:');diff --git a/src/core/migration-preludes.ts b/src/core/migration-preludes.tsnew file mode 100644index 0000000000..63c0a91d33--- /dev/null+++ b/src/core/migration-preludes.ts@@ -0,0 +1,220 @@+/**+ * #7108: runner-side preludes for published schema migrations whose SQL+ * rewrites a large table in one transaction.+ *+ * A published migration file never changes: brains that applied it never run+ * it again, so an edit would land only on some brains, and release restamp+ * refuses one. A migration's SQL runs in a single transaction under the+ * runner's statement budget (10 minutes), so a backfill that updates every row+ * of a large table can time out on every attempt and roll back, leaving the+ * brain below that migration for good (#7108: v221 on 1.7 million chunks+ * without a vector).+ *+ * A prelude does that migration's row writes first, right before the runner+ * applies the migration on a brain that has not applied it yet, in id-ordered+ * batches of a bounded size, each its own committed transaction with its own+ * statement budget. Progress is the data itself: a batch writes only rows the+ * migration's own predicate still selects, so an interrupted run resumes and+ * never rewrites a row it already wrote. The migration's SQL then runs+ * unchanged and finds nothing left to write, which also covers rows another+ * process wrote after the last batch. A prelude adds a column the migration+ * would add first, in the migration's own column order, so fresh and upgraded+ * brains keep the same column ordinals.+ *+ * Only a backfill whose predicate excludes the rows it already wrote can be+ * moved here; docs/guides/troubleshooting.md#migration-statement-timeout lists+ * the migrations that cannot and the operator budget for them.+ */+import type { BrainEngine } from './engine.ts';+import { migrationNotice, buildIndexOnline } from './schema-migrations/helpers.ts';+import { migrationStatementTimeoutMs } from './migration-timeout.ts';+import { isLockTimeoutError } from './retry-matcher.ts';+import { resolveSchemaLockTimeoutMs, schemaLockBlockedError } from './postgres-engine/schema-lock-timeout.ts';++export interface PreludeContext {+ /** Statement budget for each batch transaction (Postgres). */+ statementTimeoutMs: number;+ /** Lock wait budget for each batch transaction (Postgres). */+ lockTimeoutMs: number;+}++export type MigrationPrelude = (engine: BrainEngine, ctx: PreludeContext) => Promise<void>;++/** Rows one backfill batch may visit; a batch is one short transaction. */+const BACKFILL_BATCH_ROWS = 5_000;+let backfillBatchRows = BACKFILL_BATCH_ROWS;++/** Test-only: shrink the batch so a small fixture spans many batches; null restores the default. */+export function __setBackfillBatchRowsForTests(rows: number | null): void {+ backfillBatchRows = rows ?? BACKFILL_BATCH_ROWS;+}++/** Progress lines at most this often, so a long backfill shows it is moving without a line per batch. */+const PROGRESS_INTERVAL_MS = 15_000;++async function boundedTransaction<T>(engine: BrainEngine, ctx: PreludeContext, run: (tx: BrainEngine) => Promise<T>): Promise<T> {+ return engine.transaction(async tx => {+ if (engine.kind === 'postgres') {+ await tx.executeRaw(`SET LOCAL statement_timeout = '${ctx.statementTimeoutMs}ms'`);+ await tx.executeRaw(`SET LOCAL lock_timeout = '${ctx.lockTimeoutMs}ms'`);+ }+ return run(tx);+ });+}++interface BatchedUpdate {+ version: number;+ /** Table updated as alias `t`, batched on its integer `id` key; a table without one is left to the migration. */+ table: string;+ /** SET list over `t` (and `from` aliases), identical to the migration's. */+ set: string;+ /** The migration's own predicate over `t`; it must stop matching a row once the row is written. */+ where: string;+ /** Extra FROM items joined beside the batch, as in the migration's UPDATE ... FROM. */+ from?: string;+ what: string;+ /** Runs inside a batch transaction that wrote at least one row. */+ onWritten?: (tx: BrainEngine) => Promise<unknown>;+}++async function batchedUpdate(engine: BrainEngine, ctx: PreludeContext, u: BatchedUpdate): Promise<void> {+ const [keyed] = await engine.executeRaw<{ ok: boolean }>(+ `SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = current_schema() AND table_name = $1 AND column_name = 'id') AS ok`, [u.table]);+ if (!keyed?.ok) return;+ let cursor = 0;+ let written = 0;+ let announced = false;+ let lastProgress = Date.now();+ for (;;) {+ const row = await boundedTransaction(engine, ctx, async tx => {+ const [batch] = await tx.executeRaw<{ last_id: number | null; written: number }>(+ `-- chunk-visibility-ok: a migration backfill writes every row its published UPDATE writes, staged and retired chunks included+ WITH b AS (SELECT id FROM ${u.table} WHERE id > $1 ORDER BY id LIMIT $2),+ w AS (UPDATE ${u.table} t SET ${u.set} FROM b${u.from ? `, ${u.from}` : ''} WHERE t.id = b.id AND (${u.where}) RETURNING 1)+ SELECT (SELECT max(id) FROM b) AS last_id, (SELECT count(*) FROM w)::int AS written`,+ [cursor, backfillBatchRows]);+ if (Number(batch?.written ?? 0) > 0) await u.onWritten?.(tx);+ return batch;+ });+ if (row?.last_id == null) break;+ cursor = Number(row.last_id);+ written += Number(row.written);+ if (!announced && written > 0) {+ announced = true;+ migrationNotice(` [${u.version}] ${u.what}, ${backfillBatchRows} rows per committed batch; `+ + 'an interrupted run resumes where it stopped: gbrain apply-migrations --yes\n');+ }+ if (announced && Date.now() - lastProgress >= PROGRESS_INTERVAL_MS) {+ lastProgress = Date.now();+ migrationNotice(` [${u.version}] ${written} ${u.table} row(s) written, through id ${cursor}\n`);+ }+ }+ if (announced) migrationNotice(` [${u.version}] wrote ${written} ${u.table} row(s)\n`);+}++const addColumn = (engine: BrainEngine, ctx: PreludeContext, ddl: string) => boundedTransaction(engine, ctx, tx => tx.executeRaw(ddl));++/** v011 links_provenance_columns: legacy edges become link_source 'markdown'. Below Postgres 15 the migration refuses on its own, so nothing runs here. */+async function v011(engine: BrainEngine, ctx: PreludeContext): Promise<void> {+ const [pg] = await engine.executeRaw<{ n: number }>(`SELECT current_setting('server_version_num')::int AS n`);+ if (Number(pg?.n ?? 0) < 150000) return;+ await addColumn(engine, ctx, 'ALTER TABLE links ADD COLUMN IF NOT EXISTS link_source TEXT');+ await batchedUpdate(engine, ctx, { version: 11, table: 'links', set: `link_source = 'markdown'`, where: 't.link_source IS NULL', what: 'setting link_source on legacy links' });+}++/** v028 cathedral_ii_chunk_fts_backfill: chunk keyword vectors, with the migration's exact weights. */+async function v028(engine: BrainEngine, ctx: PreludeContext): Promise<void> {+ await batchedUpdate(engine, ctx, {+ version: 28, table: 'content_chunks', what: 'building chunk keyword vectors',+ set: `search_vector =+ setweight(to_tsvector('english', COALESCE(t.doc_comment, '')), 'A') ||+ setweight(to_tsvector('english', COALESCE(t.symbol_name_qualified, '')), 'A') ||+ setweight(to_tsvector('english', COALESCE(t.chunk_text, '')), 'B')`,+ where: 't.search_vector IS NULL',+ });+}++/** v033 admin_dashboard_columns_v0_26_3: request-log agent names, resolved as the migration resolves them. */+async function v033(engine: BrainEngine, ctx: PreludeContext): Promise<void> {+ await addColumn(engine, ctx, 'ALTER TABLE mcp_request_log ADD COLUMN IF NOT EXISTS agent_name TEXT');+ await batchedUpdate(engine, ctx, {+ version: 33, table: 'mcp_request_log', what: 'resolving request-log agent names',+ set: `agent_name = COALESCE(+ (SELECT client_name FROM oauth_clients WHERE client_id = t.token_name LIMIT 1),+ (SELECT name FROM access_tokens WHERE name = t.token_name LIMIT 1),+ t.token_name)`,+ where: 't.agent_name IS NULL',+ });+}++/** v116 code_edges_source_backfill_and_callee_index: each edge takes its source chunk's page source. */+async function v116(engine: BrainEngine, ctx: PreludeContext): Promise<void> {+ for (const table of ['code_edges_symbol', 'code_edges_chunk']) {+ await batchedUpdate(engine, ctx, {+ version: 116, table, what: `setting ${table}.source_id`,+ set: `source_id = COALESCE(p.source_id, 'default')`,+ from: 'content_chunks c JOIN pages p ON p.id = c.page_id',+ where: 'c.id = t.from_chunk_id AND t.source_id IS NULL',+ });+ }+}++/**+ * v161 index_pending_text_projections: the migration builds this partial index+ * on pages under its own 30-second statement cap, which no runner budget lifts.+ * Built here without blocking writers and without that cap, the migration's+ * CREATE INDEX IF NOT EXISTS finds it and does nothing.+ */+async function v161(engine: BrainEngine): Promise<void> {+ await buildIndexOnline(engine, 161, {+ name: 'idx_pages_projection_pending', table: 'pages',+ sql: `CREATE INDEX IF NOT EXISTS idx_pages_projection_pending ON pages(source_id, page_kind, slug)+ WHERE deleted_at IS NULL AND text_projection_revision IS DISTINCT FROM knowledge_revision`,+ }, { notice: migrationNotice });+}++/**+ * v221 chunk_embedding_pending_since: stamps every chunk whose active embedding+ * column is NULL with its created_at. The active column is chosen exactly as+ * v221 chooses it (`search_embedding_column` when it names an existing+ * content_chunks column, else `embedding`). The first batch that stamps a row+ * also records `embedding_pending_since_backfilled_at` in the same transaction+ * (kept on a resume), which doctor uses to label those ages as a created_at+ * backfill; v221 records it only when it stamped a row, and so does this.+ */+async function v221(engine: BrainEngine, ctx: PreludeContext): Promise<void> {+ await addColumn(engine, ctx, 'ALTER TABLE content_chunks ADD COLUMN IF NOT EXISTS embedding_pending_since TIMESTAMPTZ');+ const [active] = await engine.executeRaw<{ column_name: string }>(+ `SELECT c.column_name FROM config k+ JOIN information_schema.columns c+ ON c.table_schema = current_schema() AND c.table_name = 'content_chunks' AND c.column_name = k.value+ WHERE k.key = 'search_embedding_column'`);+ const column = `"${(active?.column_name ?? 'embedding').replaceAll('"', '""')}"`;+ await batchedUpdate(engine, ctx, {+ version: 221, table: 'content_chunks', what: 'stamping embedding_pending_since on chunks without a vector',+ set: 'embedding_pending_since = t.created_at',+ where: `t.${column} IS NULL AND t.embedding_pending_since IS NULL`,+ onWritten: tx => tx.executeRaw(`INSERT INTO config (key, value) VALUES ('embedding_pending_since_backfilled_at', now()::text)+ ON CONFLICT (key) DO NOTHING`),+ });+}++/** Preludes by migration version. */+export const MIGRATION_PRELUDES: ReadonlyMap<number, MigrationPrelude> = new Map<number, MigrationPrelude>([+ [11, v011], [28, v028], [33, v033], [116, v116], [161, v161], [221, v221],+]);++/** The runner calls this right before a migration's SQL; a lock wait that runs out is the schema-lock refusal, as for the SQL. */+export async function runMigrationPrelude(engine: BrainEngine, version: number): Promise<void> {+ const prelude = MIGRATION_PRELUDES.get(version);+ if (!prelude) return;+ const lockTimeoutMs = resolveSchemaLockTimeoutMs();+ try {+ await prelude(engine, { statementTimeoutMs: migrationStatementTimeoutMs(), lockTimeoutMs });+ } catch (error) {+ if (engine.kind === 'postgres' && isLockTimeoutError(error)) {+ throw schemaLockBlockedError({ step: `migration v${version} batched backfill`, timeoutMs: lockTimeoutMs, sessions: null, sampledDuringWait: false });+ }+ throw error;+ }+}diff --git a/src/core/migration-timeout.ts b/src/core/migration-timeout.tsnew file mode 100644index 0000000000..8f6d119f80--- /dev/null+++ b/src/core/migration-timeout.ts@@ -0,0 +1,99 @@+/**+ * #7108: the last schema migration that used up its statement budget, kept in+ * config so `gbrain apply-migrations` and `gbrain doctor` can name it and the+ * next step that actually helps. Before this, both said "rerun+ * apply-migrations --yes", which repeats the failure when no session is+ * blocking: the migration's own work outlasts the budget on every attempt.+ *+ * runMigrations writes the record when a migration's SQL times out (SQLSTATE+ * 57014, or the retry wrapper exhausting its attempts) and deletes it after a+ * pass applies every pending migration. Readers use it only while the schema+ * is still below the recorded migration.+ */+import type { BrainEngine } from './engine.ts';+import type { Action } from './agent-output.ts';+import { VERSION } from '../version.ts';++export const MIGRATION_TIMEOUT_KEY = 'schema_migration_timeout';++/** The one-run budget the advice offers when a migration times out with nothing blocking it. */+const LONG_BUDGET_MINUTES = 120;++/** Statement budget for one migration transaction on Postgres; it overrides a lower server default (Supabase enforces about 2 minutes). */+const MIGRATION_STATEMENT_TIMEOUT_MS = 600_000;+let statementTimeoutMs = MIGRATION_STATEMENT_TIMEOUT_MS;++export function migrationStatementTimeoutMs(): number {+ return statementTimeoutMs;+}++/** `gbrain apply-migrations --statement-timeout` (operator only; 0 removes the limit) and tests; null restores the default. */+export function setMigrationStatementTimeoutMs(ms: number | null): void {+ statementTimeoutMs = ms ?? MIGRATION_STATEMENT_TIMEOUT_MS;+}++export interface MigrationTimeoutRecord {+ version: number;+ name: string;+ /** Idle-in-transaction sessions seen holding locks after the last attempt. */+ blocker_pids: number[];+ /** The gbrain release that ran the migration. */+ gbrain_version: string;+ at: string;+}++/** Best effort: a failing database must not hide the migration error being reported. */+export async function recordMigrationTimeout(engine: BrainEngine, m: { version: number; name: string }, blockerPids: number[]): Promise<void> {+ const record: MigrationTimeoutRecord = { version: m.version, name: m.name, blocker_pids: blockerPids, gbrain_version: VERSION, at: new Date().toISOString() };+ await engine.setConfig(MIGRATION_TIMEOUT_KEY, JSON.stringify(record)).catch(() => {});+}++export async function clearMigrationTimeout(engine: BrainEngine): Promise<void> {+ await engine.unsetConfig(MIGRATION_TIMEOUT_KEY).catch(() => {});+}++/** The recorded timeout when the schema is still below that migration; null otherwise or when unreadable. */+export async function readMigrationTimeout(engine: BrainEngine, schemaVersion: number): Promise<MigrationTimeoutRecord | null> {+ try {+ const record = JSON.parse((await engine.getConfig(MIGRATION_TIMEOUT_KEY)) ?? 'null') as MigrationTimeoutRecord | null;+ return record && Number.isInteger(record.version) && record.version > schemaVersion ? record : null;+ } catch {+ return null;+ }+}++/**+ * What to tell the user about a recorded timeout, as one sentence and the fix.+ * A different gbrain release recorded it: this one may run the migration+ * differently (v221 backfills in committed batches since #7108), so rerun.+ * A blocking session was seen: ending it (with the user's agreement) and+ * rerunning can work. Otherwise the same release fails the same way, so the+ * fix is one run with a longer budget, after the user agrees (its table locks+ * are held that long).+ */+export function migrationTimeoutAdvice(record: MigrationTimeoutRecord, verify: { argv: string[] }): { message: string; fix: Action } {+ const which = `Migration v${record.version} (${record.name})`;+ const rerun = ['gbrain', 'apply-migrations', '--yes'];+ if (record.gbrain_version !== VERSION) {+ return {+ message: `${which} ran out of its statement budget under gbrain ${record.gbrain_version}; this gbrain (${VERSION}) may apply it, so run gbrain apply-migrations --yes.`,+ fix: { argv: rerun, consent: [], actor: 'agent', requires_exclusive: false, verify,+ why: `The timeout was recorded by gbrain ${record.gbrain_version}; this release may run v${record.version} differently (long backfills run in committed batches since #7108). Each batch that commits is kept, so a rerun resumes.` },+ };+ }+ if (record.blocker_pids.length > 0) {+ const pids = record.blocker_pids.join(', ');+ return {+ message: `${which} ran out of its statement budget while idle-in-transaction session(s) ${pids} held locks; end them, then run gbrain apply-migrations --yes.`,+ fix: { ask_user: true, argv: rerun, consent: [], actor: 'agent', requires_exclusive: false, verify,+ why: `Session(s) ${pids} were idle in a transaction while v${record.version} waited; the rerun works once they are gone.`,+ user_message: `gbrain migration v${record.version} timed out while database session(s) ${pids} sat idle in a transaction. With your agreement, end them on the database host (SELECT pg_terminate_backend(<pid>)), then run gbrain apply-migrations --yes. Go ahead?` },+ };+ }+ return {+ message: `${which} used its whole statement budget on every attempt under this gbrain (${VERSION}) with no session blocking it, so a plain rerun repeats the failure; with the user's agreement, rerun it with a longer budget.`,+ fix: { ask_user: true, argv: [...rerun, '--statement-timeout', String(LONG_BUDGET_MINUTES)], consent: [], actor: 'agent', requires_exclusive: true, verify,+ why: `v${record.version}'s own work outlasts the default migration statement budget on this brain; the same release fails the same way every run unless the budget is raised for one run.`,+ user_message: `gbrain migration v${record.version} (${record.name}) times out on this brain on every attempt, and nothing is blocking it. A plain rerun fails the same way. It can run once with a ${LONG_BUDGET_MINUTES}-minute budget (gbrain apply-migrations --yes --statement-timeout ${LONG_BUDGET_MINUTES}); while it runs, writes to the table it changes wait. Please also report it at https://github.com/garrytan/gbrain/issues with the output of gbrain doctor --json. Run it now?` },+ };+}diff --git a/test/e2e/migration-v221-batched-backfill-7108.test.ts b/test/e2e/migration-v221-batched-backfill-7108.test.tsnew file mode 100644index 0000000000..967836ca75--- /dev/null+++ b/test/e2e/migration-v221-batched-backfill-7108.test.ts@@ -0,0 +1,313 @@+/**+ * #7108 on Postgres: migration v221 (chunk_embedding_pending_since) stamped+ * every chunk without a vector in one UPDATE inside the runner's single+ * migration transaction. On a large brain that statement outlived the fixed+ * statement budget on every attempt, rolled back, and left the brain at+ * schema 220. The runner now runs v221's prelude first: it adds the column and+ * stamps the rows in committed, bounded batches, so no statement scales with+ * the table and an interrupted run resumes. v221's published SQL then runs+ * unchanged and finds nothing left to write.+ *+ * The budget is forced low and a trigger makes each stamped row cost about a+ * millisecond, so the published single statement over 3,000 rows exceeds the+ * budget while a 200-row batch stays far inside it.+ * Each case resets one scratch database to "applied v220, not v221". The other+ * preludes (v011, v028, v033, v116, v161) are checked on the same database:+ * rows put back in the state their migration backfills, the prelude writes+ * them in batches, and the published migration SQL afterwards rewrites none.+ * Run: DATABASE_URL=... bun test test/e2e/migration-v221-batched-backfill-7108.test.ts+ */+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import postgres from '#postgres';+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';+import { PostgresEngine } from '../../src/core/postgres-engine.ts';+import { LATEST_VERSION, MIGRATIONS, runMigrationSQL, runMigrations } from '../../src/core/migrate.ts';+import { MIGRATION_TIMEOUT_KEY, migrationTimeoutAdvice, readMigrationTimeout, setMigrationStatementTimeoutMs } from '../../src/core/migration-timeout.ts';+import { __setBackfillBatchRowsForTests, MIGRATION_PRELUDES, runMigrationPrelude } from '../../src/core/migration-preludes.ts';+import { schemaPendingError } from '../../src/commands/apply-migrations-schema.ts';+import { VERSION } from '../../src/version.ts';++const DATABASE_URL = process.env.DATABASE_URL;+const describeE2E = DATABASE_URL ? describe : describe.skip;+const v221 = MIGRATIONS.find(m => m.version === 221)!;+const STAMP_KEY = 'embedding_pending_since_backfilled_at';++let scratchName = '';+let admin: ReturnType<typeof postgres> | null = null;+let engine: PostgresEngine | null = null;+let backoff: string | undefined;++const sql = <T = Record<string, unknown>>(query: string, params: unknown[] = []) => engine!.executeRaw<T>(query, params);++/** Reset to a brain that applied v220 and not v221: no column, no provenance stamp, `rows` chunks of which every tenth has a vector. */+async function stuckAt220(rows: number): Promise<void> {+ await sql('DROP TRIGGER IF EXISTS slow_stamp_7108 ON content_chunks');+ await sql('DROP TRIGGER IF EXISTS fault_7108 ON content_chunks');+ await sql('DELETE FROM content_chunks');+ await sql('ALTER TABLE content_chunks DROP COLUMN IF EXISTS embedding_pending_since');+ await sql('DELETE FROM config WHERE key = ANY($1::text[])', [[STAMP_KEY, 'search_embedding_column']]);+ const [{ type }] = await sql<{ type: string }>(`SELECT format_type(atttypid, atttypmod) AS type FROM pg_attribute+ WHERE attrelid = 'content_chunks'::regclass AND attname = 'embedding'`);+ const dims = Number(/\((\d+)\)/.exec(type)![1]);+ const [page] = await sql<{ id: number }>(`INSERT INTO pages (slug, type, title) VALUES ('bench-7108/page', 'note', 'page')+ ON CONFLICT (source_id, slug) DO UPDATE SET title = EXCLUDED.title RETURNING id`);+ await sql(`INSERT INTO content_chunks (page_id, chunk_index, chunk_text, embedding, created_at)+ SELECT $1, g, 'chunk ' || g, CASE WHEN g % 10 = 0 THEN array_fill(0.1::real, ARRAY[$3::int])::${type} END, now() - make_interval(mins => g)+ FROM generate_series(1, $2::int) g`, [page!.id, rows, dims]);+ await sql(`INSERT INTO config (key, value) VALUES ('version', '220') ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value`);+}++/** About a millisecond per row whose embedding_pending_since changes; rows the statement leaves alone cost nothing. */+async function slowStamping(): Promise<void> {+ await sql(`CREATE OR REPLACE FUNCTION slow_stamp_7108() RETURNS trigger LANGUAGE plpgsql AS $$+ BEGIN+ IF (to_jsonb(NEW) -> 'embedding_pending_since') IS DISTINCT FROM (to_jsonb(OLD) -> 'embedding_pending_since') THEN+ PERFORM pg_sleep(0.001);+ END IF;+ RETURN NEW;+ END $$`);+ await sql('CREATE TRIGGER slow_stamp_7108 BEFORE UPDATE ON content_chunks FOR EACH ROW EXECUTE FUNCTION slow_stamp_7108()');+}++async function version(): Promise<number> {+ return Number(await engine!.getConfig('version'));+}++/** Chunks missing a vector that are not stamped with their created_at, and stamped chunks that have one. */+async function wrongStamps(column = 'embedding'): Promise<{ missing: number; extra: number }> {+ const [row] = await sql<{ missing: number; extra: number }>(`SELECT+ count(*) FILTER (WHERE "${column}" IS NULL AND embedding_pending_since IS DISTINCT FROM created_at)::int AS missing,+ count(*) FILTER (WHERE "${column}" IS NOT NULL AND embedding_pending_since IS NOT NULL)::int AS extra+ FROM content_chunks`);+ return row!;+}++/** Run the published migration SQL and return the ids of `table` rows it rewrote (xmin changed). */+async function rewrittenBy(version: number, table: string): Promise<number[]> {+ const before = await sql<{ id: number; xmin: string }>(`SELECT id, xmin::text AS xmin FROM ${table}`);+ const m = MIGRATIONS.find(x => x.version === version)!;+ await runMigrationSQL(engine!, m, m.sqlFor?.postgres ?? m.sql);+ const after = new Map((await sql<{ id: number; xmin: string }>(`SELECT id, xmin::text AS xmin FROM ${table}`)).map(r => [Number(r.id), r.xmin]));+ return before.filter(r => after.get(Number(r.id)) !== r.xmin).map(r => Number(r.id));+}++describeE2E('#7108: v221 backfills in resumable batches (Postgres)', () => {+ beforeAll(async () => {+ assertSafeE2eDatabaseUrl(DATABASE_URL!);+ backoff = process.env.GBRAIN_MIGRATE_BACKOFF_MS;+ process.env.GBRAIN_MIGRATE_BACKOFF_MS = '0';+ scratchName = `gbrain_test_v221_${randomUUID().replaceAll('-', '')}`;+ admin = postgres(DATABASE_URL!, { max: 1, prepare: false });+ await admin.unsafe(`CREATE DATABASE ${scratchName}`);+ const url = new URL(DATABASE_URL!);+ url.pathname = `/${scratchName}`;+ engine = new PostgresEngine();+ await engine.connect({ database_url: url.toString() });+ await engine.initSchema();+ }, 180_000);++ afterEach(() => {+ setMigrationStatementTimeoutMs(null);+ __setBackfillBatchRowsForTests(null);+ });++ afterAll(async () => {+ await engine?.disconnect();+ if (admin) {+ await admin.unsafe(`DROP DATABASE IF EXISTS ${scratchName} WITH (FORCE)`);+ await admin.end();+ }+ if (backoff === undefined) delete process.env.GBRAIN_MIGRATE_BACKOFF_MS;+ else process.env.GBRAIN_MIGRATE_BACKOFF_MS = backoff;+ });++ test('a backfill that outlives the statement budget as one statement completes in batches', async () => {+ await stuckAt220(3_000);+ await slowStamping();+ setMigrationStatementTimeoutMs(1_500);+ __setBackfillBatchRowsForTests(200);++ // The published single statement exceeds the budget and rolls back, column included.+ const single = await runMigrationSQL(engine!, v221, v221.sql).then(() => null, (error: unknown) => error as { code?: string });+ expect(single?.code).toBe('57014');+ expect(await sql(`SELECT 1 FROM information_schema.columns WHERE table_name = 'content_chunks' AND column_name = 'embedding_pending_since'`)).toHaveLength(0);++ // The runner gets the brain to head under the same budget.+ await runMigrations(engine!);+ expect(await version()).toBe(LATEST_VERSION);+ expect(await wrongStamps()).toEqual({ missing: 0, extra: 0 });+ const [{ stamped }] = await sql<{ stamped: number }>('SELECT count(*)::int AS stamped FROM content_chunks WHERE embedding_pending_since IS NOT NULL');+ expect(stamped).toBe(2_700);+ expect(await engine!.getConfig(STAMP_KEY)).toBeTruthy();+ }, 120_000);++ test('an interrupted backfill keeps its committed batches and resumes without rewriting them', async () => {+ await stuckAt220(2_000);+ __setBackfillBatchRowsForTests(200);+ const [{ fault }] = await sql<{ fault: number }>('SELECT id AS fault FROM content_chunks ORDER BY id OFFSET 1100 LIMIT 1');+ await sql(`CREATE OR REPLACE FUNCTION fault_7108() RETURNS trigger LANGUAGE plpgsql AS $$+ BEGIN RAISE EXCEPTION 'injected interruption at chunk %', NEW.id; END $$`);+ await sql(`CREATE TRIGGER fault_7108 BEFORE UPDATE ON content_chunks FOR EACH ROW WHEN (NEW.id = ${fault}) EXECUTE FUNCTION fault_7108()`);++ await expect(runMigrations(engine!)).rejects.toThrow(/injected interruption/);+ expect(await version()).toBe(220);+ const [done] = await sql<{ stamped: number; max_id: number | null; after: number }>(`SELECT+ count(*) FILTER (WHERE embedding_pending_since IS NOT NULL)::int AS stamped,+ max(id) FILTER (WHERE embedding_pending_since IS NOT NULL) AS max_id,+ count(*) FILTER (WHERE id >= $1 AND embedding_pending_since IS NOT NULL)::int AS after+ FROM content_chunks`, [fault]);+ // Five committed batches of 200 ids (1,000 rows, 900 without a vector); the sixth, holding the fault, rolled back.+ expect(done!.stamped).toBe(900);+ expect(done!.after).toBe(0);+ const firstStamp = await engine!.getConfig(STAMP_KEY);+ expect(firstStamp).toBeTruthy();+ const before = await sql<{ id: number; xmin: string }>('SELECT id, xmin::text AS xmin FROM content_chunks WHERE embedding_pending_since IS NOT NULL ORDER BY id');++ await sql('DROP TRIGGER fault_7108 ON content_chunks');+ await runMigrations(engine!);+ expect(await version()).toBe(LATEST_VERSION);+ expect(await wrongStamps()).toEqual({ missing: 0, extra: 0 });+ // The rows the first run stamped were not written again, and the provenance stamp kept its first value.+ const after = await sql<{ id: number; xmin: string }>('SELECT id, xmin::text AS xmin FROM content_chunks WHERE id = ANY($1::int[]) ORDER BY id', [before.map(r => r.id)]);+ expect(after).toEqual(before);+ expect(await engine!.getConfig(STAMP_KEY)).toBe(firstStamp);+ }, 120_000);++ test('a brain stuck at 220 upgrades to head and stamps against the active embedding column', async () => {+ await stuckAt220(1_000);+ await sql('ALTER TABLE content_chunks ADD COLUMN IF NOT EXISTS embedding_alt_7108 vector(3)');+ await sql(`UPDATE content_chunks SET embedding_alt_7108 = '[1,2,3]' WHERE chunk_index % 4 = 0`);+ await sql(`INSERT INTO config (key, value) VALUES ('search_embedding_column', 'embedding_alt_7108')`);++ await runMigrations(engine!);+ expect(await version()).toBe(LATEST_VERSION);+ expect(await wrongStamps('embedding_alt_7108')).toEqual({ missing: 0, extra: 0 });+ await sql(`DELETE FROM config WHERE key = 'search_embedding_column'`);+ await sql('ALTER TABLE content_chunks DROP COLUMN embedding_alt_7108');+ }, 120_000);++ test('a search_embedding_column naming no column falls back to embedding, as v221 does', async () => {+ await stuckAt220(500);+ await sql(`INSERT INTO config (key, value) VALUES ('search_embedding_column', 'no_such_column_7108')`);+ await runMigrations(engine!);+ expect(await version()).toBe(LATEST_VERSION);+ expect(await wrongStamps()).toEqual({ missing: 0, extra: 0 });+ await sql(`DELETE FROM config WHERE key = 'search_embedding_column'`);+ }, 120_000);++ test('a brain with no chunk missing a vector records no backfill stamp', async () => {+ await stuckAt220(0);+ await runMigrations(engine!);+ expect(await version()).toBe(LATEST_VERSION);+ expect(await engine!.getConfig(STAMP_KEY)).toBeNull();+ }, 120_000);++ test('a timeout is recorded with the next step; a run with a longer budget applies the migration and clears it', async () => {+ await stuckAt220(3_000);+ await slowStamping();+ setMigrationStatementTimeoutMs(1_500);+ __setBackfillBatchRowsForTests(3_000);++ await expect(runMigrations(engine!)).rejects.toThrow(/v221/);+ expect(await version()).toBe(220);+ const record = await readMigrationTimeout(engine!, 220);+ expect(record).toMatchObject({ version: 221, name: 'chunk_embedding_pending_since', blocker_pids: [], gbrain_version: VERSION });+ const advice = migrationTimeoutAdvice(record!, { argv: ['gbrain', 'doctor', '--json'] });+ expect(advice.fix.ask_user).toBe(true);+ expect(advice.fix.argv).toEqual(['gbrain', 'apply-migrations', '--yes', '--statement-timeout', '120']);+ const failure = schemaPendingError({ reason: 'still_behind', current: 220, latest: LATEST_VERSION, pending: [221], timeout: record! },+ { consent: [], actor: 'agent', why: 'unused', requires_exclusive: false });+ expect(failure.code).toBe('migrations_pending');+ expect(failure.message).toContain('v221 (chunk_embedding_pending_since)');+ expect(failure.fix?.argv).toContain('--statement-timeout');++ setMigrationStatementTimeoutMs(0);+ await runMigrations(engine!);+ expect(await version()).toBe(LATEST_VERSION);+ expect(await wrongStamps()).toEqual({ missing: 0, extra: 0 });+ expect(await engine!.getConfig(MIGRATION_TIMEOUT_KEY)).toBeNull();+ }, 120_000);++ describe('the other published backfills run in batches first', () => {+ let pageId = 0;+ let chunkIds: number[] = [];++ beforeAll(async () => {+ await stuckAt220(0);+ await runMigrations(engine!);+ const [page] = await sql<{ id: number }>(`SELECT id FROM pages WHERE slug = 'bench-7108/page'`);+ pageId = Number(page!.id);+ await sql(`INSERT INTO content_chunks (page_id, chunk_index, chunk_text, doc_comment, symbol_name_qualified)+ SELECT $1, g, 'text ' || g, CASE WHEN g % 3 = 0 THEN 'doc ' || g END, CASE WHEN g % 5 = 0 THEN 'mod.fn' || g END+ FROM generate_series(1, 50) g`, [pageId]);+ chunkIds = (await sql<{ id: number }>('SELECT id FROM content_chunks ORDER BY id')).map(r => Number(r.id));+ __setBackfillBatchRowsForTests(7);+ }, 120_000);++ afterAll(() => __setBackfillBatchRowsForTests(null));++ test('every prelude names a registered migration', () => {+ const versions = new Set(MIGRATIONS.map(m => m.version));+ for (const version of MIGRATION_PRELUDES.keys()) expect(versions.has(version)).toBe(true);+ });++ test('v028 chunk keyword vectors', async () => {+ const expected = `setweight(to_tsvector('english', COALESCE(doc_comment, '')), 'A') || setweight(to_tsvector('english', COALESCE(symbol_name_qualified, '')), 'A') || setweight(to_tsvector('english', COALESCE(chunk_text, '')), 'B')`;+ await sql('UPDATE content_chunks SET search_vector = NULL');+ await runMigrationPrelude(engine!, 28);+ const [row] = await sql<{ wrong: number }>(`SELECT count(*)::int AS wrong FROM content_chunks WHERE search_vector IS DISTINCT FROM (${expected})`);+ expect(row!.wrong).toBe(0);+ expect(await rewrittenBy(28, 'content_chunks')).toEqual([]);+ });++ test('v033 request-log agent names', async () => {+ await sql(`INSERT INTO oauth_clients (client_id, client_name) VALUES ('client-7108', 'Agent Example') ON CONFLICT DO NOTHING`);+ await sql(`INSERT INTO mcp_request_log (token_name, operation)+ SELECT CASE g % 3 WHEN 0 THEN 'client-7108' WHEN 1 THEN 'raw-token-' || g END, 'search' FROM generate_series(1, 40) g`);+ await sql('UPDATE mcp_request_log SET agent_name = NULL');+ await runMigrationPrelude(engine!, 33);+ const names = await sql<{ token_name: string | null; agent_name: string | null }>('SELECT token_name, agent_name FROM mcp_request_log');+ for (const r of names) expect(r.agent_name).toBe(r.token_name === 'client-7108' ? 'Agent Example' : r.token_name);+ // A row with no token resolves to NULL, so v033's own predicate keeps selecting it; only those are rewritten.+ const unresolved = (await sql<{ id: number }>('SELECT id FROM mcp_request_log WHERE token_name IS NULL ORDER BY id')).map(r => Number(r.id));+ expect(unresolved.length).toBeGreaterThan(0);+ expect((await rewrittenBy(33, 'mcp_request_log')).sort((a, b) => a - b)).toEqual(unresolved);+ });++ test('v116 code edge sources', async () => {+ await sql(`INSERT INTO code_edges_symbol (from_chunk_id, from_symbol_qualified, to_symbol_qualified, edge_type)+ SELECT id, 'a', 'b' || id, 'calls' FROM content_chunks`);+ await sql(`INSERT INTO code_edges_chunk (from_chunk_id, to_chunk_id, from_symbol_qualified, to_symbol_qualified, edge_type)+ SELECT id, $1, 'a', 'b' || id, 'calls' FROM content_chunks`, [chunkIds[0]]);+ await sql('UPDATE code_edges_symbol SET source_id = NULL');+ await sql('UPDATE code_edges_chunk SET source_id = NULL');+ await runMigrationPrelude(engine!, 116);+ for (const table of ['code_edges_symbol', 'code_edges_chunk']) {+ const [row] = await sql<{ wrong: number }>(`SELECT count(*)::int AS wrong FROM ${table} WHERE source_id IS DISTINCT FROM 'default'`);+ expect(row!.wrong).toBe(0);+ }+ expect(await rewrittenBy(116, 'code_edges_symbol')).toEqual([]);+ });++ test('v011 legacy link sources', async () => {+ const [other] = await sql<{ id: number }>(`INSERT INTO pages (slug, type, title) VALUES ('bench-7108/other', 'note', 'other')+ ON CONFLICT (source_id, slug) DO UPDATE SET title = EXCLUDED.title RETURNING id`);+ await sql(`INSERT INTO links (from_page_id, to_page_id, link_type, link_source)+ SELECT $1, $2, 'mentions-' || g, NULL FROM generate_series(1, 30) g`, [pageId, other!.id]);+ await runMigrationPrelude(engine!, 11);+ const [row] = await sql<{ wrong: number }>(`SELECT count(*)::int AS wrong FROM links WHERE link_source IS DISTINCT FROM 'markdown'`);+ expect(row!.wrong).toBe(0);+ expect(await rewrittenBy(11, 'links')).toEqual([]);+ });++ test('v161 builds the pending-projection index without the migration\'s 30-second cap', async () => {+ await sql('DROP INDEX IF EXISTS idx_pages_projection_pending');+ await runMigrationPrelude(engine!, 161);+ const [idx] = await sql<{ valid: boolean }>(`SELECT indisvalid AS valid FROM pg_index WHERE indexrelid = to_regclass('idx_pages_projection_pending')`);+ expect(idx?.valid).toBe(true);+ const m = MIGRATIONS.find(x => x.version === 161)!;+ await runMigrationSQL(engine!, m, m.sqlFor!.postgres!);+ });+ });+});diff --git a/test/migrate.test.ts b/test/migrate.test.tsindex fa4f3d5883..87b18ee563 100644--- a/test/migrate.test.ts+++ b/test/migrate.test.ts@@ -1,6 +1,7 @@import { describe, test, expect, beforeAll, afterAll, spyOn } from 'bun:test';import { LATEST_VERSION, runMigrations, MIGRATIONS, getIdleBlockers, hasPendingMigrations } from '../src/core/migrate.ts';import type { IdleBlocker } from '../src/core/migrate.ts';+import { migrationStatementTimeoutMs } from '../src/core/migration-timeout.ts';import type { BrainEngine } from '../src/core/engine.ts';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { withColdPglite } from './helpers/with-snapshot.ts';@@ -1454,7 +1455,8 @@ describe('PR #356 — non-transactional DDL runs via reserved connection', () =>expect(runFnIdx).toBeGreaterThan(-1);const fnBody = source.slice(runFnIdx, runFnIdx + 2500);expect(fnBody).toContain('withReservedConnection');- expect(fnBody).toContain("SET statement_timeout = '600000'");+ expect(fnBody).toContain("SET statement_timeout = '${migrationStatementTimeoutMs()}'");+ expect(migrationStatementTimeoutMs()).toBe(600_000);});});diff --git a/test/migration-v221-prelude-pglite-7108.test.ts b/test/migration-v221-prelude-pglite-7108.test.tsnew file mode 100644index 0000000000..767e6da2db--- /dev/null+++ b/test/migration-v221-prelude-pglite-7108.test.ts@@ -0,0 +1,50 @@+/**+ * #7108 on PGLite: the runner backfills v221 through its prelude on PGLite too.+ * A brain that applied v220 and not v221 reaches head, every chunk without a+ * vector carries its created_at, chunks with one stay unstamped, and the+ * backfill provenance stamp is recorded. The Postgres timeout, interruption+ * and resume cases are in test/e2e/migration-v221-batched-backfill-7108.test.ts.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { LATEST_VERSION, runMigrations } from '../src/core/migrate.ts';+import { __setBackfillBatchRowsForTests } from '../src/core/migration-preludes.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});++afterAll(async () => {+ __setBackfillBatchRowsForTests(null);+ await engine.disconnect();+});++describe('#7108: v221 prelude on PGLite', () => {+ test('a brain at 220 upgrades to head with v221 stamped in batches', async () => {+ const [{ type }] = await engine.executeRaw<{ type: string }>(`SELECT format_type(atttypid, atttypmod) AS type FROM pg_attribute+ WHERE attrelid = 'content_chunks'::regclass AND attname = 'embedding'`);+ const dims = Number(/\((\d+)\)/.exec(type)![1]);+ const [page] = await engine.executeRaw<{ id: number }>(`INSERT INTO pages (slug, type, title) VALUES ('prelude-7108/page', 'note', 'page') RETURNING id`);+ await engine.executeRaw(`INSERT INTO content_chunks (page_id, chunk_index, chunk_text, embedding, created_at)+ SELECT $1, g, 'chunk ' || g, CASE WHEN g % 4 = 0 THEN array_fill(0.1::real, ARRAY[$2::int])::${type} END, now() - make_interval(mins => g)+ FROM generate_series(1, 120) g`, [page!.id, dims]);+ await engine.executeRaw('ALTER TABLE content_chunks DROP COLUMN embedding_pending_since');+ await engine.executeRaw(`DELETE FROM config WHERE key = 'embedding_pending_since_backfilled_at'`);+ await engine.setConfig('version', '220');+ __setBackfillBatchRowsForTests(25);++ await runMigrations(engine);++ expect(Number(await engine.getConfig('version'))).toBe(LATEST_VERSION);+ const [row] = await engine.executeRaw<{ stamped: number; wrong: number }>(`SELECT+ count(*) FILTER (WHERE embedding IS NULL AND embedding_pending_since = created_at)::int AS stamped,+ count(*) FILTER (WHERE (embedding IS NULL) <> (embedding_pending_since IS NOT NULL))::int AS wrong+ FROM content_chunks`);+ expect(row).toEqual({ stamped: 90, wrong: 0 });+ expect(await engine.getConfig('embedding_pending_since_backfilled_at')).toBeTruthy();+ });+});