Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

docs: stuck-recovery covers effect and bundle recoveries

garrytan67b2c0b59424
diff --git a/docs/architecture/key-files/core-persistence-continued.md b/docs/architecture/key-files/core-persistence-continued.md
index a74f4bb23b..8d6b1dc2ac 100644
--- a/docs/architecture/key-files/core-persistence-continued.md
+++ b/docs/architecture/key-files/core-persistence-continued.md
@@ -41,7 +41,7 @@ Managed connector ingestion, connector item holds and the no-op kernel (checkpoi
- `src/core/persistence/accepted-pending.ts` — `acceptedPendingReceipt(error)`: the shared test for an accepted, not yet committed write, used by managed atom publication, extract_atoms, managed import and the connector budget. `publicationHold(error)` returns `pending` for such a receipt or `contention` for an OperationError `storage_error` with detail `database_contention` and no receipt (admission rolled back, nothing recorded), else null — never from a message, a terminal receipt, a contention error carrying a receipt or a permission refusal; `publishOrHold(fn)` runs one publication and returns null on commit, the hold when there is one, and rethrows anything else. Used by the patterns, drift and synthesize dream phases.
- `src/core/persistence/connector-checkpoint-migration.ts` — migration 176 and orphan cleanup. The newest committed checkpoint receipt per source incarnation (found by slug, so a compacted one is still seen and re-walks) is copied to the stable key with `INSERT … ON CONFLICT DO NOTHING`; state rows are seeded; the cutoff is stored in `op_checkpoints` (`op=managed-connector-migration`, fingerprint `v2-cutoff`, excluded from the checkpoint purge). `orphanConnectorCheckpoints` keeps rows touched after the start, rows any registered source (archived included) can load under its stable or alias key (`loadableConnectorKeys`, #6561), and rows referenced by a non-terminal request or a pending set; timestamps bind as text. `gbrain repair connector-checkpoints` (`src/core/repair/connector-checkpoints.ts`, whose preview counts alias-kept rows as `alias_protected`) and the `connector_checkpoints` doctor check reuse it with a 7-day floor. No upgrade step rewrites alias rows (#6561): `connector-sync.ts` `resumeCheckpoint` resumes from an alias row written after the stable one when the stable key has none or the alias holds the newer completed Gmail backfill, and the run's first save moves that cursor to the stable key; every checkpoint and page write compares against and writes only the stable row. `connector-reset.ts` guards `gbrain sync --reset-checkpoint` to connector sources.
- `src/core/persistence/graduation-target.ts` — engine graduation target side. `resolveTargetRoutes` reads the URL from `--url` or the `--url-env` variable and resolves the DDL route once (explicit `GBRAIN_DIRECT_DATABASE_URL`, else the Supabase direct derivation, else the main URL); `connectTargetEngines` hands that route to the connection manager as an explicit override, so no session-pooler fallback is chosen for the run. `targetIdentity` hashes host, port, database and user, never the password; `redactTargetUrl` is the only display form. `probeTarget` runs read-only probes in `BEGIN READ ONLY` sessions on both routes (server version, `vector` with halfvec, CREATE privilege, `session_replication_role` permission inside a savepoint, table ownership, seed-only emptiness, existing embedding columns, the role's superuser and BYPASSRLS standing and the auto-RLS event trigger and its function owner); `targetProbeBlockers` (non-superuser targets get the exact SQL a DBA runs for `vector`, BYPASSRLS and the event trigger) and `assertTargetReachable` turn a probe into plan blockers and typed refusals. `crossCheckRoutes` proves both routes reach one database with a transaction-scoped advisory lock keyed by a fresh nonce, read back from `pg_locks` through the other route. Tests: `test/graduation-target.test.ts`.
-- `src/core/persistence/graduation-drain.ts` — engine graduation drain. `graduationBlockers` lists what keeps a brain from copying, each with its structured action: requests this host owns (drained), requests and host bindings owned by another host, recovering topology changes and effects, the writer admin lock, and OAuth clients bound to a missing source (an FK only Postgres enforces; never cleared silently, since unbinding widens access). `drainForGraduation` refuses up front on anything the drain cannot clear, then publishes this host's queued, running and recovering requests with a `requestsOnly` `PersistenceConsumer` bounded by the timeout and always runs its stop barrier before returning; the `graduation_drain_timeout` refusal is built by `graduation-errors.ts`. `freezeSource` stops the resident consumer and sets the PGLite connection to read-only transactions; `withSourceWritable` runs one read-write transaction for custody writes. Tests: `test/graduation-drain.test.ts`.
+- `src/core/persistence/graduation-drain.ts` — engine graduation drain. `graduationBlockers` lists what keeps a brain from copying, each with its structured action: requests this host owns (drained; a live recovery blocked on `unexpected_file_bytes` is not drainable: `needsUser`, argv `gbrain repair stuck-recovery --source <id> --request-id <request>`), requests and host bindings owned by another host, recovering topology changes and effects (a withdrawal-mirror effect blocked on `unexpected_file_bytes` names the same stuck-recovery preview, `needsUser`), the writer admin lock, and OAuth clients bound to a missing source (an FK only Postgres enforces; never cleared silently, since unbinding widens access). `drainForGraduation` refuses up front on anything the drain cannot clear (any blocker that is not a `request`, or one that `needsUser`), then publishes this host's queued, running and recovering requests with a `requestsOnly` `PersistenceConsumer` bounded by the timeout and always runs its stop barrier before returning; the `graduation_drain_timeout` refusal is built by `graduation-errors.ts`. `freezeSource` stops the resident consumer and sets the PGLite connection to read-only transactions; `withSourceWritable` runs one read-write transaction for custody writes. Tests: `test/graduation-drain.test.ts`.
- `src/core/persistence/graduation-copy.ts` — engine graduation copier (in process). `copyTable` reads source rows through the digest's own plan (`digestPlan` with inventory transforms, `rowFilter`, `::text` values, COLLATE "C" keyset batches) and writes them in one target transaction per table that sets `gbrain.graduation_run`, bypasses user triggers (`session_replication_role = replica`, or DISABLE/ENABLE TRIGGER by name in the same transaction, never the `gbrain_graduation_fence` triggers), deletes the target's rows (seed rows included) and inserts byte-sized batches as one `$1::text::jsonb` array cast back per column type. The per-column contract (`columnContract`) refuses missing, retyped, target-only or differently generated columns outside the entry's `columnAllowlist`; generated columns are never inserted. Self-FKs take a second update pass under DISABLE TRIGGER. `copySequences` applies each source sequence's exact position, raised to the target column maximum. `deferIndexes`/`buildDeferredIndexes` drop and rebuild HNSW (through `buildDeferredAnnIndexes`) and GIN indexes, keeping the pending list in the target-owned `graduation.deferred_indexes` config row. Tests: `test/graduation-copy.test.ts`, `test/e2e/graduation-copy.test.ts`.
- `src/core/persistence/root-metadata.ts` — engine-free ownership-marker names. `isPhysicalRootMetadata` matches `.gbrain-owner.json`, `.gbrain-owner-<sha256>.json` (reservation) and `.gbrain-owner.json.<uuid>.tmp` (`physical-root-record.ts` re-exports it and `PHYSICAL_ROOT_MARKER`). `OWNERSHIP_MARKER_GLOBS` (#5186) are those names in gitignore dialect: `physical-root-record.ts` `excludeOwnershipMarkers` appends them to `<gitdir>/info/exclude` (`git rev-parse --git-path`, idempotent, best effort) after `writePhysicalRootStamp` / `adoptTransferredRootStamp`, for the stamped directory, the root and the reservation's parent. `PUSH_DENY_GLOBS` denies them with `.gbrain-bootstrap.lock/**`; the bootstrap `.gitignore` template has them; doctor `tracked_ownership_marker` warns when a source checkout's index has one. `withoutPhysicalRootMetadata` drops `git status --porcelain` entries made only of such metadata (doctor `bootstrap_push_health`, stop-hook dirty probes): a stamp-only tree is clean, a real change beside the stamp, a rename across it and a quoted path still count. Test: `test/persistence-root-metadata.test.ts`.
- `src/core/persistence/automatic-sync-policy.ts` — `automaticSyncPull(engine, source)`: whether an automatic sync (autopilot freshness `sync` job, per-source fanout cycle) may request a Git pull. It needs a parsed `remote_url`, exactly one boolean `persistence_brain` state that is off, and no worktree binding; a managed brain or claimed source syncs local HEAD with `pull: false`. Missing, duplicated or non-boolean persistence metadata throws `storage_error` (why, read-only `gbrain sources writer status --probe --json` fix) instead of granting a pull, so the caller queues nothing. Clone, immutable and federation flags grant nothing. Pinned by `test/automatic-sync-pull-policy.test.ts`.
diff --git a/docs/architecture/key-files/core-persistence-request-indexes.md b/docs/architecture/key-files/core-persistence-request-indexes.md
index 80c3094167..4a42b9cb3c 100644
--- a/docs/architecture/key-files/core-persistence-request-indexes.md
+++ b/docs/architecture/key-files/core-persistence-request-indexes.md
@@ -6,4 +6,4 @@ The online-built request-table indexes (the managed sync checkpoint pair, the pa
- `src/core/persistence/checkpoint-validation.ts` — the managed sync checkpoint's incomplete-receipt validation (#5762): `INCOMPLETE_SYNC_RECEIPT_SQL` is three `LIMIT 1` probes (recovery; an open page receipt of the run; a non-committed page receipt with no committed sibling at its index) served by `persistence_requests_recovery`, `persistence_requests_sync_run_open` and `persistence_requests_sync_run_committed`, with the same result as the former single predicate. `findIncompleteSyncReceipt` returns the blocking receipt's request id and maps only this statement's 57014 statement timeout to the terminal, non-transient `checkpoint_validation_timeout`. `readRequestIndexStates` reads each index of `PERSISTENCE_REQUEST_ONLINE_INDEXES` (or the list passed) as valid, missing, INVALID or building (Postgres `pg_stat_progress_create_index`); `formatCheckpointTimeoutHint` / `checkpointTimeoutHint` is the one formatter for the three-state hint and the filled retry (`gbrain sync --source <id> --no-pull --retry-failed` plus the cursor-selecting options the checkpoint intent records in `syncOptions` and the saved processing flags), used by the sync summary and `get_write_request`. Tests: `test/persistence-sync-checkpoint-validation.test.ts`, `test/e2e/persistence-request-indexes-postgres.test.ts`.
- `src/core/persistence/fault-points.ts` — named crash seams for the persistence gate. `faultPoint(point, detail)` is a no-op unless a gate worker installed a hook with `installFaultHook`; production never does. Seams: `publication:<boundary>` (the five `PublicationHooks.boundary` names, routed through `withFaultPoints` in `publishMutation`), `effect:<kind>:mid` for every `EffectKind` in `completeEffect` (after the side effect, before its completion is recorded; `EFFECT_FAULT_POINTS` is a `Record<EffectKind, FaultPoint>`), `effect_recovery:before_clear` (`effect-recovery.ts`), `publication_recovery:before_clear` (`recoverPublication`), `sync:mid_checkpoint` (after each committed cursor step in `sync-run.ts` `saveCursor`), `sync:after_freeze` (#6712 PR 0: at the end of `freezeEntry` for an import entry, after its bytes are read and before the request is admitted; detail carries `slug` and `path`), `consumer:prepared` (between preparing a claimed request and publishing it), `stuck_recovery:*` (between the steps of `recovery-resolve.ts`) and the purge lookups `purge:*` (page-purge.ts, intent-redaction.ts, facts/purge.ts; a hook throwing a 57014 models a statement timeout). Used by `scripts/persistence/crash-robot.ts`, the #6511 tests and `test/sync-convergence.serial.test.ts`, which installs it in real `serve`/`sync` processes through the `test/fixtures/convergence-fault-kill.ts` preload (one action registry: kill, uncommitted edit, stall until released, or throw a given SQLSTATE, at the nth hit).
-- `src/core/persistence/recovery-resolve.ts` + `src/core/repair/stuck-recovery.ts` — `gbrain repair stuck-recovery [--source <id>] [--request-id <uuid>]` (#6650 §1.10), explicit-only, preview-bound and destructive (registry `consentText`; `--apply --expect <hash> --keep prior|disk --yes`, a non-interactive apply without `--yes` exits 3). `scanStuckRecoveries` (owner host only, else `owner_unavailable` for a named source) reads the source's queued head blocker (`readHeadBlockers`; its `request_recovery` ids select the records) and every non-terminal recovery record on the worktree blocked on `unexpected_file_bytes` or whose file matches neither recorded version; a v2 shared-skill bundle record refuses `recovery_bundle_unsupported` (catalogue entry, `docs/guides/repair.md#recovery-bundle-unsupported`), a withdrawal-mirror effect recovery on the worktree is listed in `refused` (residual `effect_recovery`; named with `--request-id` it refuses `recovery_effect_unsupported`), a blocked terminal request is listed in `refused` (residual `terminal_refused`; named with `--request-id` it refuses `recovery_choice_refused`, as does a choice the record cannot support), and unblocked terminal cleanups, staging-byte blocks and self-recovering records are residuals. Each item lists every file's prior (or absent) and disk (or deleted) fingerprints and what recovery sees; a local preview writes the prior, disk and unified-diff files 0600 under `~/.gbrain/backups/stuck-recovery/<request>/<digest>/` (a private directory outside every checkout) and prints the `diff -u` command. The item digest binds the recovery identity (attempt, owner epoch, path and published hash per file), the recorded prior hashes, each file's disk view and the page's `knowledge_revision`. `resolveStuckRecovery` runs under `acquireWorktree` with a bounded wait (10 s, then `writer_lock_unavailable`; so the resident recovery pass returns unchanged), re-verifies the digest (`preview_changed`) and journals in `op_checkpoints` op `stuck-recovery-resolution` keyed `<request row id>:<preview hash>` (exempt from the checkpoint purge; the finished row is the audit entry): `backed_up` (disk and prior bytes durable, always), then `written` (`--keep prior`: `upgradeRecoveryStaging` reserves an older record's restoration stage within the recovery budget, `queue_capacity` otherwise, then the prior bytes are published through `publishPersistenceFile` at that stage after `cleanupRecoveryStaging`, an absent prior unlinked) or `abandoned` (`--keep disk`, #6640's drop: `completeWrite` ends the live request `conflict` `source_changed`, or `finishUnpublishedFailure` with its recorded failure; the record is never rewritten, so its reserved bytes are released by the terminal path's `clearResolvedRecovery`), then `recoverPublication(…, alreadyLocked)` finishes by its unchanged rule and the journal records `done` with the result. A step refuses `unexpected_file_bytes` when the file changed again; a different `--keep` for the same hash refuses `idempotency_conflict`; an identical apply after `done` replays the result (also after the approved set aged out). A record the resident consumer (any version) or an earlier killed run already finished reports `finished_by: another_pass`. `--keep prior` on a request with no recorded failure requeues it (the accepted write publishes again). `--keep disk` hands off to `gbrain sources reconcile <source> <slug> --brain host --preview` and never reports the page repaired. Fault seams `stuck_recovery:{backed_up,written,abandoned,recovered}`. Tests: `test/repair-stuck-recovery.test.ts`, `test/e2e/repair-stuck-recovery-postgres.test.ts`.
+- `src/core/persistence/recovery-resolve.ts` + `src/core/repair/stuck-recovery.ts` — `gbrain repair stuck-recovery [--source <id>] [--request-id <uuid>]` (#6650 §1.10; GBRA-130 C-1, C-4), explicit-only, preview-bound and destructive (registry `consentText`; `--apply --expect <hash> --keep prior|disk|withdrawn --yes`, a non-interactive apply without `--yes` exits 3; a `--keep` some approved record does not offer refuses `recovery_choice_refused` in the kind's plan before anything runs). `scanStuckRecoveries` (owner host only, else `owner_unavailable` for a named source) reads the source's queued head blocker (`readHeadBlockers`; its `request_recovery` ids select the records) and every non-terminal recovery record on the worktree blocked on `unexpected_file_bytes` or whose file matches neither recorded version: a page record (`target: 'page'`) or a v2 shared-skill bundle record (`target: 'skill_bundle'`, every file of the bundle; a file matches a recorded version only when `bundleFileHash` also accepts its mode and shape). A bundle record `recoveryFiles` cannot read is listed in `refused` as `recovery_bundle_unsupported` (residual `bundle_refused`; named with `--request-id` it throws with the same ask_user fix). Every withdrawal-mirror effect recovery on the worktree whose file is not a regular file holding its pre-withdrawal or withdrawn bytes is an item too (`target: 'withdrawal_mirror'`, id `effect:<id>`, `effect_id`, the forget's `request_id`; its file view adds `withdrawn`, the recorded post-withdrawal fingerprint, and its only choice is `withdrawn`); a record without usable withdrawn bytes, or bound to another owner epoch, root or incarnation, is listed in `refused` as `recovery_effect_unsupported` (residual `effect_recovery`) with `fix` `{ ask_user, argv: gbrain repair stuck-recovery --source <id> --request-id <request> }` and a `user_message`, and named with `--request-id` it throws with that fix; a blocked terminal request is listed in `refused` (residual `terminal_refused`; named with `--request-id` it refuses `recovery_choice_refused`, as does a choice the record cannot support), and unblocked terminal cleanups, staging-byte blocks and self-recovering records are residuals. Each item lists every file's prior (or absent) and disk (or deleted) fingerprints and what recovery sees; a local preview writes the prior (an effect's `withdrawn`), disk and unified-diff files 0600 under `~/.gbrain/backups/stuck-recovery/<request>/<digest>/` (a private directory outside every checkout) and prints the `diff -u` command. The item digest binds the recovery identity (attempt, owner epoch, path and published hash per file), the recorded prior hashes, each file's disk view and the page's `knowledge_revision`. `resolveStuckRecovery` runs under `acquireWorktree` with a bounded wait (10 s, then `writer_lock_unavailable`; so the resident recovery pass returns unchanged), re-verifies the digest (`preview_changed`) and journals in `op_checkpoints` op `stuck-recovery-resolution` keyed `<request row id>:<preview hash>` (exempt from the checkpoint purge; the finished row is the audit entry): `backed_up` (disk and prior bytes durable, always), then `written` (`--keep prior`: `upgradeRecoveryStaging` reserves an older record's restoration stage within the recovery budget, `queue_capacity` otherwise, then the prior bytes are published through `publishPersistenceFile` at that stage after `cleanupRecoveryStaging`, an absent prior unlinked) or `abandoned` (`--keep disk`, #6640's drop: `completeWrite` ends the live request `conflict` `source_changed`, or `finishUnpublishedFailure` with its recorded failure; the record is never rewritten, so its reserved bytes are released by the terminal path's `clearResolvedRecovery`), then `recoverPublication(…, alreadyLocked)` finishes by its unchanged rule and the journal records `done` with the result. A step refuses `unexpected_file_bytes` when the file changed again; a different `--keep` for the same hash refuses `idempotency_conflict`; an identical apply after `done` replays the result (also after the approved set aged out). A record the resident consumer (any version) or an earlier killed run already finished reports `finished_by: another_pass`. `--keep prior` on a request with no recorded failure requeues it (the accepted write publishes again). `--keep disk` hands off to `gbrain sources reconcile <source> <slug> --brain host --preview` and never reports the page repaired. An effect item resolves through `resolveEffectRecovery` under the same lock and journal (key `effect:<id>:<preview hash>`): `backed_up` (the edited bytes beside the withdrawn bytes and their diff), `written` (`upgradeRecoveryStaging` `forward`, then the recorded `after` bytes published at the record's publication stage, mode restored), then `claimAndRecoverEffect` (`effects.ts`, the resident pass's own claim + `recoverEffectPublication` + failure recording) materializes the page, clears the record and advances the effect's cursor, and `trueUpRequests` settles the forget's receipt; `--keep disk`/`prior` on it refuse `recovery_choice_refused`, since keeping the edited or pre-withdrawal bytes would let the next sync re-import the forgotten fact. A bundle's `--keep prior` writes the prior bytes of its edited files and `recoverPublication` restores the rest; `--keep disk` keeps every file and abandons the publication; both back up every file first. Fault seams `stuck_recovery:{backed_up,written,abandoned,recovered}`. Tests: `test/repair-stuck-recovery.test.ts`, `test/e2e/repair-stuck-recovery-postgres.test.ts`, `test/pathological/c1-effect-stuck-recovery.test.ts` and `test/pathological/c4-bundle-stuck-recovery.test.ts` (both engines; the effect probe asserts the forgotten fact stays forgotten after the resolution, a commit and a sync).
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index 7406200baa..622f5f91f6 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -135,7 +135,7 @@ work behind exits 0, so scripts should also check `results[].complete`.
| `connector-checkpoints` | `connector_checkpoints` | Deletes managed connector checkpoint rows and retry pointers that no registered connector source can load and that are older than 7 days. They accumulate after a content setting such as `g_history_days` changes, or when a connector host older than v0.60.11.0 runs during an upgrade. Cleanup only: it never copies or re-keys a checkpoint, takes no journal admission and runs brain-wide (`--source` does not narrow it). | Rows a queued or running connector write, or a connector's recorded pending set, still references. |
| `orphan-bindings` | `orphan_persistence_bindings` | Deletes persistence source bindings whose source was removed, or that belong to an earlier incarnation of a source re-added under the same id. `gbrain sources remove` and `gbrain sources purge` delete the binding; one an older gbrain left behind makes the re-added source read as claimed, so every `gbrain sync --source <id>` fails with `writer_coordinator_required`. Bookkeeping only: no journal admission, no page or file changes, and it runs brain-wide (`--source` does not narrow it). See [orphan bindings](#orphan-bindings). | A binding that a queued, running or recovering write request of the same source incarnation still references. |
| `managed-sync-orphans` | `sync_failures` | Explicit-only, preview-bound. Retires managed sync bookkeeping nothing current can resume or clear: a `managed-sync-failure` row whose cursor key has no cursor, and an unfinished `managed-sync` cursor recorded by a principal that is no longer an active local writer (or a pre-options cursor a later run superseded) whose pending request is terminal, or (#6834) a cursor whose checkpoint can never publish because the source's `last_commit` moved elsewhere (`checkpoint_moved`). `op_checkpoints` rows only; no journal admission, no page or file changes. The preview prints a hash; `--apply --expect <hash>` retires exactly that set. See [managed sync orphans](#managed-sync-orphans). | An unfinished cursor whose pending request is still queued, running or recovering, or one the live writer can resume with its recorded options (doctor prints that sync command). |
-| `stuck-recovery` | none (`gbrain sources writer status` shows the request `recovering` with `unexpected_file_bytes`) | Explicit-only, preview-bound, destructive consent. Resolves a live page publication recovery whose file matches neither its recorded prior nor its published bytes, which stops every write on its worktree. The preview lists each blocked file with both fingerprints and writes a private diff; `--apply --expect <hash> --keep prior\|disk --yes` backs up both versions, then restores the prior (the write publishes again) or keeps the edit and abandons the write. See [stuck recovery](#stuck-recovery). | A terminal request with its recovery still set (listed as refused, `recovery_choice_refused`), a withdrawal-mirror effect recovery (listed as refused, `recovery_effect_unsupported`), a shared-skill bundle recovery (`recovery_bundle_unsupported`), a recovery blocked on staging bytes, and a recovery whose file already matches a recorded version (the resident writer finishes those). |
+| `stuck-recovery` | none (`gbrain sources writer status` shows the request `recovering`, or the withdrawal-mirror effect, with `unexpected_file_bytes`) | Explicit-only, preview-bound, destructive consent. Resolves a live page or shared-skill bundle publication recovery whose file matches neither its recorded prior nor its published bytes, and a withdrawal-mirror effect recovery whose file was edited while it was mirroring; each stops every write on its worktree. The preview lists each blocked file with both fingerprints and writes a private diff; `--apply --expect <hash> --keep prior\|disk --yes` backs up both versions, then restores the prior (the write publishes again) or keeps the edit and abandons the write (every file of a bundle one way); an effect's only choice, `--keep withdrawn`, backs up the edit and writes the withdrawn version. See [stuck recovery](#stuck-recovery). | A terminal request with its recovery still set (listed as refused, `recovery_choice_refused`), an effect or bundle record that cannot be resolved (listed as refused, `recovery_effect_unsupported` or `recovery_bundle_unsupported`, with an ask_user fix), a recovery blocked on staging bytes, and a recovery whose file already matches a recorded version (the resident writer finishes those). |
| `frontmatter-keys` | `stale_frontmatter_keys` | Explicit-only, preview-bound. Strips the parser's reserved top-level keys (`type`, `title`, `tags`, `slug`) that an older import stored inside `pages.frontmatter`. Since v0.60.176.0 those keys are not file/database drift and never render (#6454), so this is hygiene: database rows only, in source-scoped coordinated batches of up to 1,000 pages, no file, body or embedding change. Each swept page advances its `knowledge_revision` once, so a client holding an older revision of a swept page gets one `revision_conflict` and re-reads. See [frontmatter keys](#frontmatter-keys). | A page whose keys were cleared by a write between preview and apply (`already_clean`). |
| `embedding-effects` | `stale_embedding_effects` | Settles stale queued and failed embedding effects of committed writes, which block receipt compaction and activation: `reconciled` when current vectors pass the effect verifier, `superseded` when the page was deleted or a newer revision owns its own effect, `retry_queued` for the owner (paid; a used-up retry allowance gets one new bounded cycle per explicit apply). See [stale queued embedding effects](#stale-queued-embedding-effects). | `blocked` effects, counted by reason (`owner_unavailable`, `embedding_disabled`, `embedding_unconfigured`, `projection_pending`, `no_replacement_obligation`). |
| `attribution-backfill` | none | Fills write attribution (who wrote it) on pages, page versions and facts written before attribution was recorded, only where exactly one committed request in the write journal proves the writer: the page write whose recorded result is the row's revision, or the `remember` that inserted the fact. Fills NULLs only, in committed batches of 1,000 that resume after an interruption; no content, revision, page file or request ID changes. See [write attribution](../mcp/ADMIN.md#write-attribution). | `unrecorded_pages`, `unrecorded_page_versions`, `unrecorded_facts`: rows the journal cannot prove. They stay `unrecorded`; nothing is inferred. |
@@ -721,6 +721,10 @@ delete `op_checkpoints` rows by hand.
hour and writer status says a request is recovering with unexpected_file_bytes.
Show me what changed and let me pick which version to keep."*
+The same applies to a shared-skill bundle publication (several skill files
+published together) and to a withdrawal-mirror effect (gbrain rewriting a page
+file after `forget`) whose file was edited while it was being written.
+
A page write records its file's prior bytes before it publishes. If the
process dies mid-publication, the owner's recovery pass restores the prior
bytes or finishes the write. When the file matches neither the recorded prior
@@ -740,10 +744,12 @@ gbrain repair stuck-recovery --source notes # preview: each b
gbrain repair stuck-recovery --source notes --request-id <uuid> # only one request
gbrain repair stuck-recovery --source notes --keep prior --apply --expect <hash> --yes
gbrain repair stuck-recovery --source notes --keep disk --apply --expect <hash> --yes
+gbrain repair stuck-recovery --source notes --request-id <uuid> --keep withdrawn --apply --expect <hash> --yes # a withdrawal-mirror effect
```
The preview starts from the blocker of the source's queued head and lists
-every recovery record on the worktree. For each file it prints the prior
+every recovery record on the worktree, and every withdrawal-mirror effect
+recovery whose file matches neither recorded version. For each file it prints the prior
(hash, size, mode, or `absent: prior was a create`), the bytes on disk (or
`deleted on disk`), what recovery sees, and a private diff written under
`~/.gbrain/backups/stuck-recovery/<request>/` with the exact `diff -u`
@@ -765,6 +771,29 @@ What a choice does depends on the request's state:
| Live with a recorded failure (`publication_failed`) | Prior bytes back; the request ends `failed` or `conflict` with that failure. | Disk bytes kept; the request ends with that failure. |
| Terminal (`committed`, `failed`, `conflict`, `cancelled`) with its recovery record still set | Refused (`recovery_choice_refused`): recovery never restores a terminal request's file, so this would roll back committed bytes. | Refused (`recovery_choice_refused`): a terminal outcome is immutable and there is no publication to abandon. |
+A shared-skill bundle record is listed with every file of the bundle, each
+with both fingerprints, and either choice applies to the whole bundle: every
+file is backed up first, then `--keep prior` writes the prior bytes of the
+edited files back and recovery restores the rest (the publication requeues, or
+ends with its recorded failure), and `--keep disk` keeps every file as it is on
+disk and abandons the publication. After `--keep disk` the shared-skill records
+keep the version from before the publication; publish the skill again if the
+files on disk should become its new version.
+
+A withdrawal-mirror effect has one choice, `--keep withdrawn`. The withdrawal
+is already committed, so keeping the edited file (or the bytes from before the
+withdrawal) would leave the forgotten fact on disk, and the next sync would
+import it again; `--keep disk` and `--keep prior` are refused
+(`recovery_choice_refused`) before anything runs. The preview lists the file,
+its bytes from before the withdrawal, the withdrawn bytes the mirror recorded
+and the bytes on disk, with a diff of the withdrawn and disk bytes. The apply
+backs the edited file up (`0.disk` beside `0.withdrawn` and the diff), writes
+the withdrawn bytes through the mirror's own staged publication, and finishes
+the effect forward, so the writes queued behind it resume. Commit the file
+before the next sync, and make any other change from the edit again from the
+backup, leaving the forgotten fact out. A record without usable withdrawn
+bytes is listed as refused ([`recovery_effect_unsupported`](#recovery-effect-unsupported)).
+
The preview lists a terminal request as `refused` with the reason and offers
no choice for it. After `--keep disk` the database page still holds the
content from before the write, so the page shows as file/database drift until
@@ -780,9 +809,10 @@ same apply again after it finished replays the recorded result; the same hash
with the other `--keep` refuses `idempotency_conflict`. The finished journal
row is the resolution's audit entry and does not expire; the request's own
receipt is never rewritten by this command (`--keep disk` completes the live
-request; it never changes a terminal one). A shared-skill bundle recovery is
-refused with [`recovery_bundle_unsupported`](#recovery-bundle-unsupported), and
-a withdrawal-mirror effect recovery on the worktree is listed as refused with
+request; it never changes a terminal one). A bundle record this binary cannot
+read is listed as refused with
+[`recovery_bundle_unsupported`](#recovery-bundle-unsupported), and an effect
+record without usable withdrawn bytes with
[`recovery_effect_unsupported`](#recovery-effect-unsupported). The apply waits
at most 10 seconds for the worktree lock, then refuses `writer_lock_unavailable`
with nothing changed; `--keep prior` on a record that predates reserved staging
@@ -2697,12 +2727,14 @@ applies to `gbrain jobs authorize-legacy --select`, `gbrain jobs cancel
`recovery_bundle_unsupported`: `gbrain repair stuck-recovery` found a
shared-skill bundle recovery record (several skill files published together)
-among the selected requests. It resolves page recoveries only, so nothing was
-changed. Inspect the request read-only with `gbrain sources writer status
---source <id> --json`, ask the user which version of each skill file to keep,
-put those bytes in place by hand, and let the resident writer finish the
-recovery. Pass `--request-id` to resolve the page recoveries on the same
-source.
+that this binary cannot read: an unknown shape, or more files than a bundle
+holds. A readable bundle record is resolved like a page recovery (see
+[stuck recovery](#stuck-recovery)). Nothing was changed. The preview lists it
+under `refused`, and its `fix` is `ask_user` with the exact preview command;
+naming it with `--request-id` refuses with this code. Upgrade gbrain on the
+brain host and preview again, or ask the user which version of each skill file
+to keep, put those bytes in place by hand, and let the resident writer finish
+the recovery.
### Recovery large file unsupported
@@ -2728,22 +2760,30 @@ recovery never restores its file, and `--keep prior` would roll back committed
bytes; the record only waits for staging cleanup, see `gbrain sources writer
status --source <id> --json`), or the record cannot support the choice
(`--keep prior` without stored prior bytes, or a blocked path that is not a
-regular file). The preview lists only the choices it can make safe.
+regular file), or a record in the approved preview does not offer that choice
+(`--keep disk` or `--keep prior` on a withdrawal-mirror effect, `--keep
+withdrawn` on a page or bundle; refused before anything runs, so narrow the
+preview with `--request-id`). The preview lists only the choices it can make
+safe.
### Recovery effect unsupported
`recovery_effect_unsupported`: a withdrawal-mirror effect recovery blocks the
-source's worktree, and `gbrain repair stuck-recovery` does not resolve it.
-That recovery only finishes forward (it never restores the bytes from before a
-withdrawal), so either `--keep` choice could put withdrawn content back on
-disk. Nothing was changed. Inspect the effect read-only with `gbrain sources
-writer status --source <id> --json` and ask the user whether the edited file
-may be replaced by its withdrawn version; the resident writer finishes the
-effect once the file matches one of its recorded versions. The preview lists
-the effect as `refused`; naming its request with `--request-id` refuses with
-this code. A sync queued behind such an effect stops at once with
+source's worktree, and its record cannot be written forward: it holds no
+usable withdrawn bytes (missing or corrupt), or it was recorded for another
+owner epoch, root or source incarnation. A usable record is resolved with
+`--keep withdrawn` (see [stuck recovery](#stuck-recovery)). That recovery
+only finishes forward (it never restores the bytes from before a withdrawal),
+so nothing was changed. The preview lists the effect as `refused`, and its
+`fix` is `ask_user` with the exact preview command
+(`gbrain repair stuck-recovery --source <id> --request-id <request>`) and a
+`user_message` to relay; naming its request with `--request-id` refuses with
+this code and the same fix. The user copies the edited file aside and puts it
+back to its committed version (never deletes it); the resident writer then
+finishes the effect, and the edit is made again without the forgotten fact. A
+sync queued behind a stuck effect stops at once with
[`drain_stalled`, `cause: head_blocked`](write-refusals.md#head-blocked), and
-its fix names the file.
+its fix runs the stuck-recovery preview.
### Legacy job authority
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index 24924d8c5b..4abd72249b 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -519,7 +519,7 @@ retry_after_ms, eta_seconds, rate_pages_per_min, why, docs }`. Run
| <a id="drain-write-capacity"></a>`write_capacity` | `queue_capacity` | `blocked` | The sync could not admit its next write for the whole no-progress window (30 s) because other writers' requests held the outstanding-request cap of its write principal (`persistence.limits.principal_outstanding`, default 100; the brain cap `persistence.limits.brain_outstanding`, 1000, works the same way): on one host the CLI sync and a maintenance run (fact-fence adoption, `dream`) share the `local_cli` principal, so a long adoption queue leaves no room for a sync write. Nothing failed and the cursor is intact: the drain retried the admission with backoff while they settled, printing `waiting for write capacity (N outstanding of M)`, and stopped only when the window passed. `drain.capacity` carries the counts and the wait; exit 1. A cumulative cap (permanent request IDs, receipt bytes) is a different refusal: it names its config key and stops at once. | `gbrain sources writer status --source <source> --json` lists the outstanding requests (read-only). Let them finish, or raise the cap (`gbrain config set persistence.limits.principal_outstanding 200`), then rerun the same sync; it resumes where it stopped. |
| <a id="drain-connection-lost"></a>`connection_lost` | `connection_lost` | `blocked` | The database connection dropped three times in a row (`write ECONNABORTED`, `ECONNRESET`, `ETIMEDOUT`, `EPIPE`: a pooler closing the socket mid-statement) with no page committed between the drops (#6340). Each drop was reconnected and retried after 5, 15 and 45 s; a drop that then moves data is not reported at all. Nothing is recorded against the source: the cursor and its frozen manifest stand, and `drain.connection` carries the count and the last error text (never a URL). Exit 1. | Check the database and pooler (`gbrain doctor --json`), then rerun `next.command` (`safe_to_loop` is true, `retry_after_ms` 60 s): it resumes at the stored cursor without re-freezing the manifest. Runbook: [sync unblock](sync-unblock-runbook.md#connection). |
| <a id="drain-capacity-paused"></a>`capacity_paused` | `capacity_paused` | `resumable` | The run passed its capacity preflight, then a cumulative write cap refused its next admission (`write_quota_exhausted`) or, for a background sync, the pause line did (`write_capacity_backpressure`): another writer used the room the preflight counted on. Nothing failed; the cursor and every accepted write stand, and `drain.capacity_pause` names the refusal and its config raise. | Run the `gbrain config set` the report names on the brain host (request ids never free; receipt bytes also free as receipts compact), then rerun the same `gbrain sync`. Verify with `gbrain doctor --only persistence_capacity --json`. |
-| <a id="head-blocked"></a>`drain_stalled` with `cause: head_blocked` | `drain_stalled` | `blocked` | The queued write at the head of the source cannot be claimed by any consumer, and its blocker needs an operator (#6543). `drain.stall.blocked_by` names the predicate, its ids, state and owner: `refresh_fence` (a refresh left the checkout `fenced`, `merged` or `recovery_required` and no refresh process holds its lock), `zombie_publication` (a running request ahead of the head is held by a process that reports `restart_required`), or `effect_recovery` with state `unexpected_file_bytes` (a fact-withdrawal mirror's page file was edited while the mirror was publishing, so its forward-only recovery refuses to overwrite it), or `request_recovery` with state `unexpected_file_bytes` (a page write's file was edited while it was publishing, #6650; this also covers a head that is itself that recovering write). For both, `blocked_by.file` names the page and path. A recovery stuck on `unexpected_staging_bytes` is not classified yet and still waits out the window. The drain stops after one governor tick of confirmation instead of the no-progress window. Live blockers (`root_hold`, a foreground publication; `lease`, a lapsed claim the next consumer reclaims; `withdrawal_mirror`, an `effect_recovery` or `request_recovery` that can still finish, `worktree_owner`) never stop it: the stall line names them as `blocked_by=` beside `consumer=` and the drain keeps waiting. `claimable here` is read for the head itself and prints `unknown` when the probe could not read it. | Run `next.fix`: `refresh_fence` resumes the refresh (`gbrain sources refresh <source> --resume`, which lifts the fence or names why it cannot); `zombie_publication` tells the host admin to restart the named process; `effect_recovery` asks the user to copy the edited file aside and put it back to a version gbrain recorded (undo the edit, or restore the committed version), never to delete it, and to redo the edit after the withdrawal finishes; `request_recovery` runs the [`gbrain repair stuck-recovery --source <source>`](repair.md#stuck-recovery) preview, and the user either keeps one version through it or undoes the edit. Then rerun the sync. `gbrain sources writer status --source <source> --json` names the same blocker for every queued head and, only when the caller may cancel the blocking request, `gbrain cancel-write-request <request_id>`. |
+| <a id="head-blocked"></a>`drain_stalled` with `cause: head_blocked` | `drain_stalled` | `blocked` | The queued write at the head of the source cannot be claimed by any consumer, and its blocker needs an operator (#6543). `drain.stall.blocked_by` names the predicate, its ids, state and owner: `refresh_fence` (a refresh left the checkout `fenced`, `merged` or `recovery_required` and no refresh process holds its lock), `zombie_publication` (a running request ahead of the head is held by a process that reports `restart_required`), or `effect_recovery` with state `unexpected_file_bytes` (a fact-withdrawal mirror's page file was edited while the mirror was publishing, so its forward-only recovery refuses to overwrite it), or `request_recovery` with state `unexpected_file_bytes` (a page write's file, or a file of a shared-skill bundle, was edited while it was publishing, #6650; this also covers a head that is itself that recovering write). For both, `blocked_by.file` names the page and path (an effect's also names its withdrawal request). A recovery stuck on `unexpected_staging_bytes` is not classified yet and still waits out the window. The drain stops after one governor tick of confirmation instead of the no-progress window. Live blockers (`root_hold`, a foreground publication; `lease`, a lapsed claim the next consumer reclaims; `withdrawal_mirror`, an `effect_recovery` or `request_recovery` that can still finish, `worktree_owner`) never stop it: the stall line names them as `blocked_by=` beside `consumer=` and the drain keeps waiting. `claimable here` is read for the head itself and prints `unknown` when the probe could not read it. | Run `next.fix`: `refresh_fence` resumes the refresh (`gbrain sources refresh <source> --resume`, which lifts the fence or names why it cannot); `zombie_publication` tells the host admin to restart the named process; `effect_recovery` runs the [`gbrain repair stuck-recovery --source <source> --request-id <request>`](repair.md#stuck-recovery) preview, whose only choice (`--keep withdrawn`, the user's to apply) backs the edit up and writes the withdrawn version; or the user restores the committed version, never deletes the file, and redoes the edit without the forgotten fact; `request_recovery` runs the [`gbrain repair stuck-recovery --source <source>`](repair.md#stuck-recovery) preview, and the user either keeps one version through it or undoes the edit. Then rerun the sync. `gbrain sources writer status --source <source> --json` names the same blocker for every queued head and, only when the caller may cancel the blocking request, `gbrain cancel-write-request <request_id>`. |
| <a id="sync_drain_lease_held"></a>`drain_lease_held` | `sync_drain_lease_held` | `resumable` | Another process holds the source's drain lease (#6712): one managed drainer per source, and that holder (a serve, a `sync` job, the dream cycle, another terminal) is still committing pages. `gbrain sync` follows it within its own `--timeout` and run deadline, printing the holder (kind, pid, host, gbrain version) and the pages it commits (every 10 s on a terminal, 60 s otherwise), and takes the lease when the holder releases it. This code means the budget ended first, or the lease moved to another process mid-pass (`lost`); nothing this run admitted is lost and the cursor is intact. `--no-delegate` never skips the lease. `drain.lease_held.holder` reuses the drain's owner fields: `kind`, `id`, `host`, `pid`, `started_at`, `last_heartbeat_at`, `version` and `progress` (`committed`, `last_committed_at`, `last_progress_at`); `next.retry_after_ms` is 60 s and `next.safe_to_loop` is true. Exit 0. A cron that runs `gbrain sync` every few minutes beside a serve exits 0 here on each tick while the serve works. | Rerun `next.command` after `next.retry_after_ms`, or let the holder finish. Ctrl-C while following stops only this run; the holder keeps going. A holder that commits nothing for 5 minutes is not reported here: the run stops [`drain_stalled`](#drain-lease-stalled) instead. |
| <a id="drain-lease-stalled"></a>`drain_stalled` with `cause: no_progress` and `stall.lease_holder` | `drain_stalled` | `blocked` | The process holding the source's drain lease committed no page and saved no cursor for 5 minutes, so following it would exit 0 forever (#6712). `drain.stall.lease_holder` names it with the fields above; the lease itself is renewed by a live process, so a wedged holder keeps it. A holder that died lets its lease lapse within 2 minutes and the next run takes over without this stop. Exit 1, `next.safe_to_loop` false. | `gbrain sources writer status --source <source> --json` (read-only) shows what the holder is waiting on. Stop or restart the named process; when it is gone but its lock row remains, `gbrain sync --source <source> --no-pull --break-lock` releases a lock whose pid is dead (`--force-break-lock` skips the liveness check: only when you know the holder is gone). Then rerun the same sync. |