Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(migrate): address review: restore troubleshooting guide, keep version out of the schema graph, v161 under the budget, scoped --statement-timeout
garrytan5b9774d67913
diff --git a/docs/architecture/key-files/engines-2.md b/docs/architecture/key-files/engines-2.mdindex fea615fbd3..98f3d3c923 100644--- a/docs/architecture/key-files/engines-2.md+++ b/docs/architecture/key-files/engines-2.md@@ -58,5 +58,5 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/postgres-engine/` + `src/core/pglite-engine/` — per-engine module directories for code that is genuinely dialect-specific. Migrated storage domains (the `migrated` rows of `scripts/engine-sql-baseline.tsv`) do not live here: their SQL exists once in `src/core/engine-sql/` (see that entry in engines-2.md). What remains: `pglite-engine/checkpoint-guard.ts`, `pglite-engine/code-edges.ts` (PGLite's `getEdgesByChunk`, whose master SQL behaves differently from Postgres's: one UNION ALL under a shared LIMIT; listed in `docs/designs/refactor-wave-1/w1-inventory.md`), `postgres-engine/cancellation.ts`, `postgres-engine/init-schema-lock.ts`, `postgres-engine/keyword-statement-timeout.ts` (#6495: `KEYWORD_STATEMENT_TIMEOUT_KEY` = `search.keyword_statement_timeout_ms`, default 8000, range 1000-60000; `keywordStatementTimeoutMs` accepts an integer in range, `resolveKeywordStatementTimeoutMs(file, db)` applies file > DB > default, `keywordStatementTimeoutValueProblem` is the `config set` refusal text, and `loadKeywordStatementTimeout(reader, fileValue)` yields the `<ms>ms` setting one connection binds; pinned by `test/keyword-statement-timeout-knob-6495.test.ts` on a recording handle and, with DATABASE_URL, on a real Postgres whose locked tables make each statement wait until the bound cancels it), `postgres-engine/keyword-timeout-cache.ts` (#6495 negative cache: `KeywordTimeoutNegativeCache.run(enabled, db, keyParts, exec)` wraps `searchKeyword`'s strict and relaxed statements when hybrid's keyword arm opts in with `SearchOpts.keywordTimeoutCache`; the key hashes the statement text, its parameters, the RLS source scope and the statement timeout, so only the exact statement is skipped; a genuine statement-timeout 57014, never a user cancel, records an entry for `search.keyword_timeout_negative_cache_seconds` (default 600, 0 = off, read once on the first timeout) and later identical runs throw `KeywordSkippedAfterTimeoutError` (code `keyword_skipped_after_timeout`, arm reason `skipped_after_timeout`) without a statement; at most 256 entries per engine; each timeout writes one bounded `search.keyword_timeout_stats` row that doctor `keyword_plan` reads; pinned by `test/keyword-timeout-negative-cache-6495.test.ts`), `postgres-engine/schema-lock-timeout.ts` (#5227: `resolveSchemaLockTimeoutMs` reads `GBRAIN_SCHEMA_LOCK_TIMEOUT_SECONDS`, default 60 s; `withSchemaLockTimeout` sets a session-level `lock_timeout` on the reserved DDL backend and restores the prior value on release, used by the `schema.sql` replay in `postgres-engine.ts` and the `transaction: false` path of `migrate.ts`, while a transaction-wrapped migration binds the same wait with `SET LOCAL`; `schemaDiagnosticConnection` opens a one-backend connection that samples `pg_blocking_pids()` of the waiting backend while the wait is active so `schemaLockBlockedError` names blockers by pid, application, state and transaction age, never query text; `init-schema-retry.ts` retries `schema_lock_blocked` / SQLSTATE 55P03 with a short backoff; handler migrations and the post-migration `verifySchema` run outside the bound) and `postgres-engine/search-settings.ts` (search transactions run with `jit = off`; `withSearchSettings` applies a read's settings in one statement and restores a caller's values when nested), `postgres-engine/reserved-transactions.ts` (`withReservedConnection` lends its connection a `transaction()`; BEGIN and SAVEPOINT go out with the statements after them, and a COMMIT answered with ROLLBACK throws), `postgres-engine/transaction-abort.ts` (`transaction(fn, { signal })`: an abort calls the begin handle's `cancelAndDiscard()`, which sends the running fenced statement's CancelRequest, keeps successors out until it settles (bounded by `GBRAIN_CANCEL_SETTLE_MS`), then discards the connection, so a statement blocked on a lock stops instead of waiting out its statement timeout (#6598) and the server rolls the transaction back; the caller gets an `AbortError` with the driver's `CONNECTION_CLOSED` as `cause` and, when the cancel could not be confirmed (unfenced statement, transport failure, settle timeout), the `CANCEL_UNCONFIRMED` rejection as `cancelFailure`; an abort after COMMIT keeps the committed result; an already-aborted signal rejects before BEGIN; pinned offline by `test/postgres-transaction-cancel-order.test.ts` and on direct Postgres and PgBouncer by `test/e2e/transaction-cancel-held-lock.test.ts`); the forward-reference bootstrap lives once in `engine-sql/bootstrap.ts` for both engines. Façades import these modules statically (engine-live no-runtime-dynamic-import rule) and keep their full public surface.- `src/core/analyze-lock.ts` — #7083: `lockTableForAnalyze` takes a table's SHARE UPDATE EXCLUSIVE lock with NOWAIT before every ANALYZE gbrain runs on Postgres on its own (the projection and chunk refreshes, `repair planner-stats`, `analyzeAfterIndexBuild` through `analyzeYieldingToVacuum`), and `analyzeDeferred` recognizes its 55P03 refusal. An ANALYZE that waited `deadlock_timeout` on a running autovacuum made Postgres cancel it, so a refresh after every embed drain kept a 10M-chunk content_chunks from ever being vacuumed; a request that never waits never signals a vacuum, and the caller defers its ANALYZE. Doctor `planner_stats_stale` reports a hot table whose autovacuum stays starved (`readVacuumStarvation`). Test: `test/e2e/analyze-yields-to-autovacuum-postgres.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`.+- `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, inlined so a generic prepared plan cannot scan the table per batch; `__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 (NULL-token rows stay the migration's own), v116 code-edge `source_id`, v161 (Postgres) the partial pages index built concurrently under the budget on a reserved connection (the migration caps its own build at 30 s; another session's build or an invalid result stops the run), v221 `embedding_pending_since` (v221's active-column choice; the first stamping batch writes `embedding_pending_since_backfilled_at` in its transaction). 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>`, restored when that run returns; 0 removes it) and the timed-out-migration record (config `schema_migration_timeout`: version, name, whether the run had a prelude, idle-in-transaction pids sampled at the failure): `runMigrations` writes it on a 57014 or a statement-timeout retry exhaustion and deletes it after a pass reaches head. A schema-graph leaf (no release version, so the PGLite snapshot hash stays stable). `migration-timeout-advice.ts` turns a record into the one fix both apply-migrations (`migrations_pending` still_behind) and doctor `schema_version` show: timed out unbatched and this release has a prelude → rerun; idle sessions open → ask_user, check `doctor --locks`, end the ones still open, rerun; none → ask_user, one run with `--statement-timeout 120`.diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.mdindex 87aac53ed0..6bf83b4e23 100644--- a/docs/guides/troubleshooting.md+++ b/docs/guides/troubleshooting.md@@ -25,7 +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` |+| `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 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` |@@ -93,3 +93,672 @@<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.++## Migration statement timeout++<a id="migration-statement-timeout"></a>++**Symptom.** `gbrain apply-migrations --yes` (or `gbrain upgrade`) prints+`Migration <N> (<name>) exhausted retries` or `hit statement_timeout (SQLSTATE+57014)`, exits 1 with `migrations_pending` (reason `still_behind`), and the+schema stays below head. Doctor's `schema_version` check names the migration.++**Why.** Each migration's SQL runs in one transaction under a 10-minute+statement budget, which overrides a lower server default (Supabase enforces+about 2 minutes). A lock wait stops much sooner, at the schema lock timeout+(`schema_lock_blocked`), so a statement timeout means the migration's own work+outlasted the budget. Every attempt then rolls back.++**What gbrain does about it.** Before some published migrations, gbrain runs+their backfill in committed batches of 5,000 rows, using the migration's own+predicate. An interrupted run keeps every committed batch, and+`gbrain apply-migrations --yes` continues from the rows still left. The+published migration then runs unchanged and has little or nothing left to+write.++| Migration | Done in batches first |+|---|---|+| v011 `links_provenance_columns` | `link_source = 'markdown'` on legacy links |+| v028 `cathedral_ii_chunk_fts_backfill` | chunk keyword vectors |+| v033 `admin_dashboard_columns_v0_26_3` | request-log agent names. A row with no token resolves to NULL, so the migration still rewrites those rows itself. |+| v116 `code_edges_source_backfill_and_callee_index` | `source_id` on code edges |+| v161 `index_pending_text_projections` | its partial pages index, built concurrently under the migration statement budget (Postgres), because the migration caps its own build at 30 seconds |+| v221 `chunk_embedding_pending_since` | `embedding_pending_since` on chunks without a vector, with the same active-column choice and `embedding_pending_since_backfilled_at` provenance (#7108) |++The other migrations whose work grows with a table are either bounded+differently or can't be split without editing a published migration:++- v153 rewrites every page row and queues one projection job per live page. It+ grows with the page count, not the chunk count.+- v189 scans page bodies for private-key markers. The scan only reads, and it+ writes only the matching pages.+- v123's handler rewrites keyword vectors only when the configured keyword+ language changes. It runs outside the migration transaction.+- Index builds and constraint validations inside a migration (v011's unique+ constraint, v174, v226 and similar) are single statements that can't be+ split. Apart from the build itself, they only read.+- v160 (ANALYZE samples `pages`), v200 (a partial index on `op_checkpoints`)+ and v234 (a column on `persistence_host_bindings`) cap themselves at 30+ seconds. They touch a sample, a small table or only the catalog.++**When it still happens.** gbrain records the timed-out migration (config+`schema_migration_timeout`, deleted once a run reaches head). Apply-migrations+and doctor then name it and give the fix for the case:++1. **This release batches a migration that timed out without batching.** Run+ `gbrain apply-migrations --yes`.+2. **Idle-in-transaction sessions were open.** They may hold locks on the+ table. Check them with `gbrain doctor --locks`. With the user's agreement,+ end the ones that are still open on the database host+ (`SELECT pg_terminate_backend(<pid>)`), then run+ `gbrain apply-migrations --yes`.+3. **No idle session was seen.** A plain rerun fails the same way. With the+ user's agreement, run it once with a longer budget:+ `gbrain apply-migrations --yes --statement-timeout 120` (whole minutes;+ `0` removes the limit). While it runs, the migration holds its table locks,+ so writes to that table wait. Please also report it, so the migration can be+ batched.++`--statement-timeout` is operator-only and applies to that run only. It sets+the budget for migration SQL and for the batches above. It doesn't lift the+30-second caps that v160, v200 and v234 set on themselves, or the timeouts of+migration handlers.++## 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 06c10fcc19..8844e977f3 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -10399,7 +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` |+| `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 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` |@@ -10468,6 +10468,675 @@ 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.++## Migration statement timeout++<a id="migration-statement-timeout"></a>++**Symptom.** `gbrain apply-migrations --yes` (or `gbrain upgrade`) prints+`Migration <N> (<name>) exhausted retries` or `hit statement_timeout (SQLSTATE+57014)`, exits 1 with `migrations_pending` (reason `still_behind`), and the+schema stays below head. Doctor's `schema_version` check names the migration.++**Why.** Each migration's SQL runs in one transaction under a 10-minute+statement budget, which overrides a lower server default (Supabase enforces+about 2 minutes). A lock wait stops much sooner, at the schema lock timeout+(`schema_lock_blocked`), so a statement timeout means the migration's own work+outlasted the budget. Every attempt then rolls back.++**What gbrain does about it.** Before some published migrations, gbrain runs+their backfill in committed batches of 5,000 rows, using the migration's own+predicate. An interrupted run keeps every committed batch, and+`gbrain apply-migrations --yes` continues from the rows still left. The+published migration then runs unchanged and has little or nothing left to+write.++| Migration | Done in batches first |+|---|---|+| v011 `links_provenance_columns` | `link_source = 'markdown'` on legacy links |+| v028 `cathedral_ii_chunk_fts_backfill` | chunk keyword vectors |+| v033 `admin_dashboard_columns_v0_26_3` | request-log agent names. A row with no token resolves to NULL, so the migration still rewrites those rows itself. |+| v116 `code_edges_source_backfill_and_callee_index` | `source_id` on code edges |+| v161 `index_pending_text_projections` | its partial pages index, built concurrently under the migration statement budget (Postgres), because the migration caps its own build at 30 seconds |+| v221 `chunk_embedding_pending_since` | `embedding_pending_since` on chunks without a vector, with the same active-column choice and `embedding_pending_since_backfilled_at` provenance (#7108) |++The other migrations whose work grows with a table are either bounded+differently or can't be split without editing a published migration:++- v153 rewrites every page row and queues one projection job per live page. It+ grows with the page count, not the chunk count.+- v189 scans page bodies for private-key markers. The scan only reads, and it+ writes only the matching pages.+- v123's handler rewrites keyword vectors only when the configured keyword+ language changes. It runs outside the migration transaction.+- Index builds and constraint validations inside a migration (v011's unique+ constraint, v174, v226 and similar) are single statements that can't be+ split. Apart from the build itself, they only read.+- v160 (ANALYZE samples `pages`), v200 (a partial index on `op_checkpoints`)+ and v234 (a column on `persistence_host_bindings`) cap themselves at 30+ seconds. They touch a sample, a small table or only the catalog.++**When it still happens.** gbrain records the timed-out migration (config+`schema_migration_timeout`, deleted once a run reaches head). Apply-migrations+and doctor then name it and give the fix for the case:++1. **This release batches a migration that timed out without batching.** Run+ `gbrain apply-migrations --yes`.+2. **Idle-in-transaction sessions were open.** They may hold locks on the+ table. Check them with `gbrain doctor --locks`. With the user's agreement,+ end the ones that are still open on the database host+ (`SELECT pg_terminate_backend(<pid>)`), then run+ `gbrain apply-migrations --yes`.+3. **No idle session was seen.** A plain rerun fails the same way. With the+ user's agreement, run it once with a longer budget:+ `gbrain apply-migrations --yes --statement-timeout 120` (whole minutes;+ `0` removes the limit). While it runs, the migration holds its table locks,+ so writes to that table wait. Please also report it, so the migration can be+ batched.++`--statement-timeout` is operator-only and applies to that run only. It sets+the budget for migration SQL and for the batches above. It doesn't lift the+30-second caps that v160, v200 and v234 set on themselves, or the timeouts of+migration handlers.++## 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 9cb690b0a2..191130ef5c 100644--- a/src/commands/apply-migrations-schema.ts+++ b/src/commands/apply-migrations-schema.ts@@ -24,7 +24,8 @@ 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';+import { readMigrationTimeout, type MigrationTimeoutRecord } from '../core/migration-timeout.ts';+import { migrationTimeoutAdvice } from '../core/migration-timeout-advice.ts';export type SchemaPendingReason = 'not_applied' | 'still_behind' | 'schema_unreadable';diff --git a/src/commands/apply-migrations.ts b/src/commands/apply-migrations.tsindex 705831e894..2f8be17b47 100644--- a/src/commands/apply-migrations.ts+++ b/src/commands/apply-migrations.ts@@ -54,7 +54,7 @@ import {schemaPendingError,type SchemaPending,} from './apply-migrations-schema.ts';-import { readMigrationTimeout, setMigrationStatementTimeoutMs, type MigrationTimeoutRecord } from '../core/migration-timeout.ts';+import { migrationStatementTimeoutMs, readMigrationTimeout, setMigrationStatementTimeoutMs, type MigrationTimeoutRecord } from '../core/migration-timeout.ts';interface ApplyMigrationsArgs {list: boolean;@@ -541,8 +541,18 @@ 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);+ if (cli.statementTimeoutMinutes === undefined) return applyParsed(cli, args);+ // #7108: the operator's budget covers this run only, whichever way it returns.+ const prior = migrationStatementTimeoutMs();+ setMigrationStatementTimeoutMs(cli.statementTimeoutMinutes * 60_000);+ try {+ return await applyParsed(cli, args);+ } finally {+ setMigrationStatementTimeoutMs(prior);+ }+}+async function applyParsed(cli: ApplyMigrationsArgs, args: string[]): Promise<{ exitCode: number | undefined; failure?: OperationError }> {const installed = VERSION.replace(/^v/, '').trim() || '0.0.0';const report: RunReport = { doc: { status: 'ok', installed } };diff --git a/src/commands/doctor/checks/schema-health.ts b/src/commands/doctor/checks/schema-health.tsindex c67af23c80..d02af2e213 100644--- a/src/commands/doctor/checks/schema-health.ts+++ b/src/commands/doctor/checks/schema-health.ts@@ -27,7 +27,8 @@ import { connectedEngine, type DoctorContext, type DoctorEntry, doctorHealth } fimport { embeddingsDisabled } from '../../../core/embedding-disabled.ts';import { quoteIdentifier, resolveActiveEmbeddingColumnFromEngine } from '../../../core/search/embedding-column.ts';import { agentFix, checkError, doctorVerify, infoCheck, keylessEnablementFix } from '../check-fix.ts';-import { migrationTimeoutAdvice, readMigrationTimeout } from '../../../core/migration-timeout.ts';+import { readMigrationTimeout } from '../../../core/migration-timeout.ts';+import { migrationTimeoutAdvice } from '../../../core/migration-timeout-advice.ts';import type { MissingTable, MissingTablesReport } from '../../../core/schema-missing-tables.ts';const MISSING_TABLES_DOCS = 'docs/guides/repair.md#missing-tables';diff --git a/src/core/migrate.ts b/src/core/migrate.tsindex fe1bc0cef2..ace78a549e 100644--- a/src/core/migrate.ts+++ b/src/core/migrate.ts@@ -5,7 +5,7 @@ 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 { MIGRATION_PRELUDES, 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.@@ -508,7 +508,7 @@ export async function runMigrations(engine: BrainEngine): Promise<{ applied: numif (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) : []);+ if (timedOut) await recordMigrationTimeout(engine, m, MIGRATION_PRELUDES.has(m.version), err instanceof MigrationRetryExhausted ? err.lastBlockers.map(b => b.pid) : []);throw err;}@@ -552,7 +552,7 @@ async function applyOneMigration(engine: BrainEngine, m: Migration): Promise<voiconsole.error('');} else {console.error('');- console.error(` Cause: no idle-in-transaction session was blocking it, so the migration's own work`);+ console.error(` Cause: no idle-in-transaction session was open, and a lock wait stops at the lock timeout, so its 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('');diff --git a/src/core/migration-preludes.ts b/src/core/migration-preludes.tsindex 3d8d828812..e19a86e67d 100644--- a/src/core/migration-preludes.ts+++ b/src/core/migration-preludes.ts@@ -16,8 +16,8 @@* 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+ * unchanged and finds nothing the prelude could write, and it still 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.*@@ -26,7 +26,7 @@* 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 { dropInvalidConcurrentIndex, migrationNotice } 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';@@ -138,7 +138,11 @@ async function v028(engine: BrainEngine, ctx: PreludeContext): Promise<void> {});}-/** v033 admin_dashboard_columns_v0_26_3: request-log agent names, resolved as the migration resolves them. */+/**+ * v033 admin_dashboard_columns_v0_26_3: request-log agent names, resolved as the+ * migration resolves them. A row with no token resolves to NULL and would stay+ * selected, so it is left to the migration's own UPDATE.+ */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, {@@ -147,7 +151,7 @@ async function v033(engine: BrainEngine, ctx: PreludeContext): Promise<void> {(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',+ where: 't.agent_name IS NULL AND t.token_name IS NOT NULL',});}@@ -163,18 +167,40 @@ async function v116(engine: BrainEngine, ctx: PreludeContext): Promise<void> {}}+const V161_INDEX = 'idx_pages_projection_pending';+/**- * 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.+ * v161 index_pending_text_projections (Postgres): the migration builds this+ * partial index on pages under its own 30-second statement cap, which no+ * runner budget lifts. It is built here concurrently, under the migration+ * statement budget, so the migration's CREATE INDEX IF NOT EXISTS finds a valid+ * index and does nothing. The budget is a session setting on a reserved+ * connection, reset afterwards, as runMigrationSQL does for a transaction:false+ * migration. Another session's build in progress, or a build that ends invalid,+ * stops the run, because the migration's IF NOT EXISTS would accept an invalid+ * index. PGLite builds it in the migration itself, which has no cap there.*/-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 });+async function v161(engine: BrainEngine, ctx: PreludeContext): Promise<void> {+ if (engine.kind !== 'postgres') return;+ const state = async () => (await engine.executeRaw<{ valid: boolean; building: boolean }>(+ `SELECT i.indisvalid AS valid, EXISTS (SELECT 1 FROM pg_stat_progress_create_index p+ WHERE p.relid = i.indrelid AND p.index_relid IN (i.indexrelid, 0)) AS building+ FROM pg_index i WHERE i.indexrelid = to_regclass($1)`, [V161_INDEX]))[0];+ const before = await state();+ if (before?.valid) return;+ if (before?.building) throw new Error(`Index ${V161_INDEX} is being built by another session; once that build ends, run gbrain apply-migrations --yes again.`);+ if (before) await dropInvalidConcurrentIndex(engine, 161, V161_INDEX);+ migrationNotice(` [161] building ${V161_INDEX} concurrently; this can take minutes and is safe to interrupt (the next run rebuilds it)\n`);+ await engine.withReservedConnection(async conn => {+ await conn.executeRaw(`SET statement_timeout = '${ctx.statementTimeoutMs}'`);+ try {+ await conn.executeRaw(`CREATE INDEX CONCURRENTLY IF NOT EXISTS ${V161_INDEX} ON pages(source_id, page_kind, slug)+ WHERE deleted_at IS NULL AND text_projection_revision IS DISTINCT FROM knowledge_revision`);+ } finally {+ await conn.executeRaw('RESET statement_timeout').catch(() => {});+ }+ }, { selfContained: true });+ if (!(await state())?.valid) throw new Error(`Index ${V161_INDEX} is not valid after its concurrent build; run gbrain apply-migrations --yes again to rebuild it.`);}/**diff --git a/src/core/migration-timeout-advice.ts b/src/core/migration-timeout-advice.tsnew file mode 100644index 0000000000..f6123ae8d0--- /dev/null+++ b/src/core/migration-timeout-advice.ts@@ -0,0 +1,50 @@+/**+ * #7108: what to tell the user about a recorded migration timeout+ * (migration-timeout.ts), as one sentence and the fix. apply-migrations+ * (`migrations_pending`, reason `still_behind`) and doctor `schema_version`+ * both use it.+ *+ * A lock wait stops at the schema lock timeout (`schema_lock_blocked`) long+ * before the 10-minute budget, so a timeout means the migration's own work took+ * that long. Three cases:+ * - The run had no prelude for the migration and this release has one: rerun.+ * - Idle-in-transaction sessions were open: they may hold locks the work+ * waited on row by row. They were sampled once and may be gone or unrelated,+ * so the user checks them with doctor --locks, and only after agreeing ends+ * the ones still open, then reruns.+ * - None were seen: a plain rerun fails the same way, so once the user agrees,+ * one run with a longer budget (its table locks are held that long).+ */+import type { Action } from './agent-output.ts';+import type { MigrationTimeoutRecord } from './migration-timeout.ts';+import { MIGRATION_PRELUDES } from './migration-preludes.ts';++/** The one-run budget offered when a migration times out with no idle session seen. */+const LONG_BUDGET_MINUTES = 120;++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.batched && MIGRATION_PRELUDES.has(record.version)) {+ return {+ message: `${which} ran out of its statement budget in one transaction; this gbrain runs its backfill in committed batches first, so run gbrain apply-migrations --yes.`,+ fix: { argv: rerun, consent: [], actor: 'agent', requires_exclusive: false, verify,+ why: `This release backfills v${record.version} in committed batches before the migration (#7108), so no statement grows with the table; an interrupted run keeps its batches.` },+ };+ }+ if (record.idle_pids.length > 0) {+ const pids = record.idle_pids.join(', ');+ return {+ message: `${which} ran out of its statement budget while idle-in-transaction session(s) ${pids} were open; they may hold locks on its table. Check them with gbrain doctor --locks, end the ones still open once the user agrees, 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 for over five minutes when v${record.version} timed out; a session holding a lock on its table would make the work wait. They were sampled then and may be gone or unrelated now.`,+ user_message: `gbrain migration v${record.version} timed out while database session(s) ${pids} were idle in an open transaction. Run gbrain doctor --locks to see whether they are still open. With your agreement, end the ones that are 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 with no idle session open, so a plain rerun repeats the failure; once the user agrees, 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: `A lock wait would have stopped at the schema lock timeout instead, so v${record.version}'s own work outlasts the default budget on this brain; the same release fails the same way 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 no database session was 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/src/core/migration-timeout.ts b/src/core/migration-timeout.tsindex 8f6d119f80..ba15b6b375 100644--- a/src/core/migration-timeout.ts+++ b/src/core/migration-timeout.ts@@ -1,24 +1,20 @@/**- * #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.+ * #7108: the migration statement budget, and the last schema migration that+ * used it up, kept in config so `gbrain apply-migrations` and `gbrain doctor`+ * can name it and the next step that helps (migration-timeout-advice.ts).+ * Before this, both said "terminate blockers, rerun apply-migrations --yes",+ * which repeats the failure when the migration's own work outlasts the budget.*- * 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+ * runMigrations writes the record when a migration times out (SQLSTATE 57014,+ * or the retry wrapper exhausting its attempts on one) and deletes it after a* pass applies every pending migration. Readers use it only while the schema- * is still below the recorded migration.+ * is still below the recorded migration. A leaf of the schema import graph:+ * no release version here, so the test snapshot hash stays stable.*/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;@@ -27,7 +23,7 @@ export function migrationStatementTimeoutMs(): number {return statementTimeoutMs;}-/** `gbrain apply-migrations --statement-timeout` (operator only; 0 removes the limit) and tests; null restores the default. */+/** `gbrain apply-migrations --statement-timeout` (operator only, restored after the run; 0 removes the limit) and tests; null restores the default. */export function setMigrationStatementTimeoutMs(ms: number | null): void {statementTimeoutMs = ms ?? MIGRATION_STATEMENT_TIMEOUT_MS;}@@ -35,16 +31,16 @@ export function setMigrationStatementTimeoutMs(ms: number | null): void {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;+ /** Whether the run that timed out had a batched prelude for this migration (migration-preludes.ts). */+ batched: boolean;+ /** Idle-in-transaction sessions older than five minutes when the last attempt failed; they may or may not hold locks on the table. */+ idle_pids: number[];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() };+export async function recordMigrationTimeout(engine: BrainEngine, m: { version: number; name: string }, batched: boolean, idlePids: number[]): Promise<void> {+ const record: MigrationTimeoutRecord = { version: m.version, name: m.name, batched, idle_pids: idlePids, at: new Date().toISOString() };await engine.setConfig(MIGRATION_TIMEOUT_KEY, JSON.stringify(record)).catch(() => {});}@@ -56,44 +52,9 @@ export async function clearMigrationTimeout(engine: BrainEngine): Promise<void>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;+ if (!record || !Number.isInteger(record.version) || record.version <= schemaVersion) return null;+ return { ...record, batched: record.batched === true, idle_pids: Array.isArray(record.idle_pids) ? record.idle_pids : [] };} 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.tsindex 967836ca75..89bdd147f0 100644--- a/test/e2e/migration-v221-batched-backfill-7108.test.ts+++ b/test/e2e/migration-v221-batched-backfill-7108.test.ts@@ -17,16 +17,16 @@* 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 { afterAll, afterEach, beforeAll, beforeEach, 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 { MIGRATION_TIMEOUT_KEY, readMigrationTimeout, setMigrationStatementTimeoutMs } from '../../src/core/migration-timeout.ts';+import { migrationTimeoutAdvice } from '../../src/core/migration-timeout-advice.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;@@ -92,6 +92,12 @@ async function rewrittenBy(version: number, table: string): Promise<number[]> {return before.filter(r => after.get(Number(r.id)) !== r.xmin).map(r => Number(r.id));}+/** Distinct writing transactions among the rows: more than one means the prelude committed more than one batch. */+async function writers(table: string, where = 'true'): Promise<number> {+ const [row] = await sql<{ n: number }>(`SELECT count(DISTINCT xmin::text)::int AS n FROM ${table} WHERE ${where}`);+ return Number(row!.n);+}+describeE2E('#7108: v221 backfills in resumable batches (Postgres)', () => {beforeAll(async () => {assertSafeE2eDatabaseUrl(DATABASE_URL!);@@ -212,7 +218,7 @@ describeE2E('#7108: v221 backfills in resumable batches (Postgres)', () => {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 });+ expect(record).toMatchObject({ version: 221, name: 'chunk_embedding_pending_since', batched: true, idle_pids: [] });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']);@@ -242,10 +248,9 @@ describeE2E('#7108: v221 backfills in resumable batches (Postgres)', () => {SELECT $1, g, 'text ' || g, CASE WHEN g % 3 = 0 THEN 'doc ' || g END, CASE WHEN g % 5 = 0 THEN 'mod.fn' || g ENDFROM 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));+ beforeEach(() => __setBackfillBatchRowsForTests(7));test('every prelude names a registered migration', () => {const versions = new Set(MIGRATIONS.map(m => m.version));@@ -256,6 +261,7 @@ describeE2E('#7108: v221 backfills in resumable batches (Postgres)', () => {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);+ expect(await writers('content_chunks')).toBeGreaterThan(1);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([]);@@ -267,6 +273,7 @@ describeE2E('#7108: v221 backfills in resumable batches (Postgres)', () => {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);+ expect(await writers('mcp_request_log', 'token_name IS NOT NULL')).toBeGreaterThan(1);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.@@ -283,6 +290,7 @@ describeE2E('#7108: v221 backfills in resumable batches (Postgres)', () => {await sql('UPDATE code_edges_symbol SET source_id = NULL');await sql('UPDATE code_edges_chunk SET source_id = NULL');await runMigrationPrelude(engine!, 116);+ expect(await writers('code_edges_symbol')).toBeGreaterThan(1);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);@@ -296,6 +304,7 @@ describeE2E('#7108: v221 backfills in resumable batches (Postgres)', () => {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);+ expect(await writers('links')).toBeGreaterThan(1);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([]);@@ -304,6 +313,9 @@ describeE2E('#7108: v221 backfills in resumable batches (Postgres)', () => {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);+ // An INVALID leftover (an interrupted concurrent build) is dropped and rebuilt, never accepted.+ await sql(`UPDATE pg_index SET indisvalid = false WHERE indexrelid = to_regclass('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)!;diff --git a/test/migration-timeout-advice-7108.test.ts b/test/migration-timeout-advice-7108.test.tsnew file mode 100644index 0000000000..24bebae571--- /dev/null+++ b/test/migration-timeout-advice-7108.test.ts@@ -0,0 +1,62 @@+/**+ * #7108: the timed-out-migration advice picks one fix per case, and+ * `apply-migrations --statement-timeout` sets the migration budget for its own+ * run only. Recording and clearing on a real migration are covered on Postgres+ * in test/e2e/migration-v221-batched-backfill-7108.test.ts.+ */+import { describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { migrationTimeoutAdvice } from '../src/core/migration-timeout-advice.ts';+import { migrationStatementTimeoutMs, type MigrationTimeoutRecord } from '../src/core/migration-timeout.ts';+import { applyMigrations } from '../src/commands/apply-migrations.ts';+import { withEnv } from './helpers/with-env.ts';++const verify = { argv: ['gbrain', 'doctor', '--only', 'schema_version', '--json'] };+const record = (over: Partial<MigrationTimeoutRecord>): MigrationTimeoutRecord =>+ ({ version: 221, name: 'chunk_embedding_pending_since', batched: true, idle_pids: [], at: '2026-10-20T00:00:00.000Z', ...over });++describe('#7108 migration timeout advice', () => {+ test('a migration that timed out unbatched and now has a prelude: rerun, no consent needed', () => {+ const { message, fix } = migrationTimeoutAdvice(record({ batched: false }), verify);+ expect(message).toContain('committed batches');+ expect(fix.ask_user).toBeUndefined();+ expect(fix.argv).toEqual(['gbrain', 'apply-migrations', '--yes']);+ });++ test('idle sessions were open: ask the user, check them with doctor --locks before ending any', () => {+ const { message, fix } = migrationTimeoutAdvice(record({ idle_pids: [4242] }), verify);+ expect(message).toContain('4242');+ expect(message).toContain('may hold locks');+ expect(fix.ask_user).toBe(true);+ expect(fix.user_message).toContain('gbrain doctor --locks');+ expect(fix.argv).toEqual(['gbrain', 'apply-migrations', '--yes']);+ });++ test('nothing open: ask the user for one run with a longer budget', () => {+ const { fix } = migrationTimeoutAdvice(record({}), verify);+ expect(fix.ask_user).toBe(true);+ expect(fix.argv).toEqual(['gbrain', 'apply-migrations', '--yes', '--statement-timeout', '120']);+ expect(fix.verify).toEqual(verify);+ });++ test('a migration with no prelude that timed out unbatched gets the same advice as a batched one', () => {+ expect(migrationTimeoutAdvice(record({ version: 153, name: 'verified_text_projection_activation', batched: false }), verify).fix.argv)+ .toContain('--statement-timeout');+ });+});++describe('#7108 apply-migrations --statement-timeout', () => {+ test('the budget applies to that run only', async () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-7108-'));+ try {+ await withEnv({ GBRAIN_HOME: home }, async () => {+ await applyMigrations(['--statement-timeout', '0', '--list']);+ expect(migrationStatementTimeoutMs()).toBe(600_000);+ });+ } finally {+ rmSync(home, { recursive: true, force: true });+ }+ });+});