Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Merge remote-tracking branch 'origin/master' into capy/large-pages-hardening

garrytana2a6e6bb995d
diff --cc docs/architecture/key-files/core-persistence-request-indexes.md
index 6be827a0ff,6296624201..18bf64377e
--- a/docs/architecture/key-files/core-persistence-request-indexes.md
+++ b/docs/architecture/key-files/core-persistence-request-indexes.md
@@@ -6,6 -6,8 +6,9 @@@ The online-built request-table indexes
- `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`), `large_file:stage_streaming` (after each piece `stageStreamedContent` writes to a stage's in-progress name), `effect_recovery:before_stage` / `effect_recovery:staged` (a streamed, version 2 withdrawal mirror: once its record is durable, before its file is streamed into the publication stage, and after that step, before the recovery transaction renames the stage), `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. A record whose prior file is over the single-string ceiling (`staging.before`) resolves the same way in bounded memory: the disk file and the staged copy are hashed in pieces (the copy's state, `verified`, `missing` or `mismatched`, is in the prior view and the digest), backups are kernel copies checked by streamed hash, the diff file is a summary (both fingerprints, the first differing byte, a window of at most 1 KiB; `cmp` reproduces it), `--keep prior` runs recovery's `restoreBeforeStage` after `cleanupRecoveryStaging(keepBefore)`, and `--keep disk` backs up a mismatched copy (`<index>.prior-stage`) and removes it before abandoning. `--keep prior` without a verified copy refuses `recovery_prior_stage_unavailable` (registry entry; its fix is the `--keep disk` apply under the same hash). 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/large-pages/stuck-recovery-large.slow.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. A record whose prior file is over the single-string ceiling (`staging.before`) resolves the same way in bounded memory: the disk file and the staged copy are hashed in pieces (the copy's state, `verified`, `missing` or `mismatched`, is in the prior view and the digest), backups are kernel copies checked by streamed hash, the diff file is a summary (both fingerprints, the first differing byte, a window of at most 1 KiB; `cmp` reproduces it), `--keep prior` runs recovery's `restoreBeforeStage` after `cleanupRecoveryStaging(keepBefore)`, and `--keep disk` backs up a mismatched copy (`<index>.prior-stage`) and removes it before abandoning. `--keep prior` without a verified copy refuses `recovery_prior_stage_unavailable` (registry entry; its fix is the `--keep disk` apply under the same hash). 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` (first `rebaseStaleEffectRecovery` (`effect-recovery.ts`): when a later withdrawal moved the page past the record, the record is rebased under its page lock on the latest snapshot's `mirrorContent` bytes (the rendering `mirrorPage` itself writes), its publication stage and reserved bytes following them, and the journal stores the rebased `identity` in the same transaction, so the recorded bytes never put a later-withdrawn fact back on disk and a rerun resumes; a page deleted, replaced or segmented meanwhile refuses `recovery_effect_unsupported` with nothing written; then `upgradeRecoveryStaging` `forward` and the record's `after` bytes published at its 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).
+ - `src/core/persistence/native-file-target.ts` — shared preparation/Git execution spelling resolution. Native directory-entry inode/device identity proves aliases; no global case folding or separator rewrite. Missing suffixes retain exact spelling, descendant symlinks and ambiguous aliases refuse, and physical root identity is rechecked. Exact POSIX case-distinct names and literal backslashes remain distinct. #5032: `isWindowsColonTarget(rel)` and `colonSlugWindowsRefusal(slug, sourceId)` name the one Windows-only refusal (`colon_slug_windows_write_through`: `:` names an NTFS alternate data stream); `submitPageMutation` raises it before admission when this host publishes the file, `prepareFileTarget` at publication, and managed (`fileRefusals`) and unmanaged (`failedFiles`) sync skip each such path by name (`test/colon-slug-windows-5032.test.ts`). A path segment over 255 bytes, or `ENAMETOOLONG` from the lookup, refuses `invalid_params` with detail `file_name_too_long` and a fix naming a slug whose segments fit 240 bytes (`test/pathological/b12-slug-segment-bytes.test.ts`).
+ - `src/core/persistence/admission-retry.ts` — bounded retries for database-confirmed admission transaction aborts. Each retry reuses the UUID and normalized intent, rechecks guarded authority and reserves quota only on commitment. Standalone journal admission uses 100ms lock waits within the five-second retry budget to retain queue position behind short counter transactions; backoff occurs after rollback releases the connection so counter contention leaves pool capacity for reads. Ambiguous connection/commit errors are never classified as confirmed rollback. #6355: a session that drops under the attempt (`isConnectionLoss` in `retry-matcher.ts`: connection-class SQLSTATEs, postgres.js's connection codes, `57P01`/`57P02`/`57P03`, the socket errnos) re-runs the attempt after `CONNECTION_LOSS_RETRY_MS` (100/300/900 ms), which is safe because every attempt reads the retained request id first and replays an admitted row; when the session keeps dropping the caller gets `writeOutcomeUnknown` (`write_outcome_unknown`, `reason: connection_lost`, fix: read the request by id), never the raw socket error the crash robot's receipt oracle took for a refusal while the write committed (`test/persistence-admission-connection-loss.test.ts`, forced probes: a lost COMMIT acknowledgment; a dead lent transaction used once with the pool finishing the write). The optional `recover(error)` hook runs before each re-run; `admitWrite` uses it to rebuild the pool (`engine.reconnect`) and to move the re-run from a lent transaction (the consumer's lane, `onPersistenceLane`) to `engine.transaction`, since a dropped reservation fails every later use the same way ("Connection is no longer owned"). Real counter-lock, sustained-queue progress, read-capacity and after-insert rollback tests live in `test/persistence-journal.test.ts`. Withdrawal retries wrap its whole source-exclusive transaction with its existing lock policy; `admitWriteInTransaction` never backs off inside an existing unit of work. `test/persistence-withdrawal-retry.test.ts` verifies guard release, complete rollback and bounded contention. #6278 (B7): also the outstanding-request cap's `detail` format (`outstandingCapacityDetail`, `outstanding=N limit=M`, stamped by `journal.ts` `capacityError`) and its readers `isWriteCapacityWait` / `outstandingCapacityOf`, which the managed drain and `sync-run.ts`'s failure ledger use to tell a refusal that clears by itself from a cumulative cap.
+ - `src/core/persistence/unbound-source.ts` — #5254 policy for a Postgres page write to a filesystem source (`local_path`, or `sync.repo_path` for `default`) with default write-through and no worktree binding. `submitPageMutation` refuses `owner_unavailable` with `detail: unbound_source`, a `docs` pointer to `write-refusals.md#unbound-sources-on-postgres`, and a hint naming the filled `sources writer status`/`writer claim ... --admin-intent writer_claim --expected-state <admin_state>` bind command (host path only for trusted local callers) and, for `put_page` to a page without `source_path`, `gbrain config set persistence.unbound_write database_only`. That key (`refuse` default, validated by `config set`; any other stored value refuses) lets such a `put_page` admit with `databaseOnlyReason: 'unbound_source'`. `decideUnboundWrite` is the one rule page writers and fact writers (`remember`, loop-fact retirement and relink through `fact-write-target.ts`, #6608) apply to a rooted source with no binding: connector → `connector_database`; PGLite not activation-listed database-only (#6449) → automatic claim; otherwise a page with a recorded canonical file, or the key unset, refuses and the rest is database-only. `remember` keeps its frozen `unavailable` code and carries the refusal's detail, docs and fix (`verb-errors.ts`). On a classic brain (managed persistence not activated) the hint leads with the classic write path: write `<checkout>/<slug>.md`, commit it, `gbrain sync --source <id>` (a remote caller is told to ask the user to). The refusal is `retryable: false` with a `fix` of `next: ask_user` and a `user_message` (classic or managed wording), because every way out is the user's choice (`test/unbound-source-hint.test.ts`). Publication rechecks inside its transaction, after `authorizeStoredRequest` share-locks the source row, that the source is still unbound and the page still has no `source_path` (else `owner_unavailable`/`unbound_source`, hint rebuilt from the persisted message by `writeResponse`), then stamps `pages.database_only_reason='unbound_source'` (migration 177). After binding, `prepareFileTarget` keeps a stamped page with no file database-only (receipt `write_through.skipped: unbound_source` with a warning) and managed sync refuses to import a file at its path (`source_changed`, diagnostic reason `unbound_source`). PGLite keeps auto-claiming. Tests: `test/e2e/unbound-source-postgres.test.ts`, `test/persistence-unbound-source.test.ts`. See [persistence stalls](persistence-stalls.md).
-- Segmented withdrawal mirror (`src/core/persistence/{effects,effect-recovery,effect-model,staging}.ts`, flip lane A) — a withdrawal's mirror and Git scans treat a page stored in segments as an inline page (older binaries skipped it with `page_body_segmented`). `mirrorPage` renders its file from the segments (`page-prepare.ts` `unreadPageFile`, a `StreamedFileContent`) and reserves a version 2 `EffectRecovery` (`after: null`; `staging.publication` names the streamed file by path and SHA-256; the reservation counts the file once). `recoverEffectPublication` writes that stage before its transaction (`stageStreamedMirror`: from the measured file, or after a crash from the segments at the recorded revision, first discarding a stream a crash cut short under its in-progress name; seams `effect_recovery:before_stage` / `effect_recovery:staged`), then renames the verified stage (`staging.ts` `publishStreamedStage`). A segmented page's withdrawal is not materialized again: its rows were struck in its segments when the withdrawal committed. An older binary refuses a version 2 record (it has no embedded file) and leaves it for this one. Test: `test/large-pages/segmented-withdrawal-mirror.test.ts` (purge and forget twins, Git commits, two interruption seams, both engines).
+- Segmented withdrawal mirror (`src/core/persistence/{effects,effect-recovery,effect-model,staging}.ts`, flip lane A) — a withdrawal's mirror and Git scans treat a page stored in segments as an inline page (older binaries skipped it with `page_body_segmented`). `mirrorPage` renders its file from the segments (`page-prepare.ts` `unreadPageFile`, a `StreamedFileContent`) and reserves a version 2 `EffectRecovery` (`after: null`; `staging.publication` names the streamed file by path and SHA-256; the reservation counts the file once). `recoverEffectPublication` writes that stage before its transaction (`stageStreamedMirror`: from the measured file, or after a crash from the segments at the recorded revision, first discarding a stream a crash cut short under its in-progress name; seams `effect_recovery:before_stage` / `effect_recovery:staged`), then renames the verified stage (`staging.ts` `publishStreamedStage`). A segmented page's withdrawal is not materialized again: its rows were struck in its segments when the withdrawal committed. v0.60.290.0 reads a version 2 record as version 1 (`Buffer.from(null)`, untyped `effect_unavailable` on every attempt, never parks) but never deletes it or its stage, so `mirrorPage` writes none while that binary could claim it (next entry). Test: `test/large-pages/segmented-withdrawal-mirror.test.ts` (purge and forget twins, Git commits, two interruption seams, both engines).
+- `src/core/persistence/{recovery-version,segmented-mirror-gate,segmented-gate-hold}.ts` — forward compatibility of recovery records. `recovery-version.ts` lists the record versions this binary reads (`EFFECT_RECOVERY_VERSIONS`, `REQUEST_RECOVERY_VERSIONS`); `assertRecoveryVersion` refuses any other `recovery_version_unsupported` (fix `gbrain upgrade`, `host_admin`) before a reader touches the record: `recoverEffectPublication`, `reserveEffectRecovery`, `upgradeRecoveryStaging` (both tables) and `model.ts` `recoveryFiles` (request recovery, clearing, stuck-recovery); `head-blocker.ts` reports such a record as an intervention with the same fix. `segmented-mirror-gate.ts`: `mirrorPage` calls `assertSegmentedMirrorGate` before streaming a segmented page's file; while `mirrorGateBlockers` sees a live writer below SEGMENTED_WRITER_FLOOR (the switch's TTL-cached `segmentedWriterBlockers`, filtered by `segmented-gate-hold.ts` `liveSegmentedBlockers`, the classification doctor `segmented_storage` uses: this host's own pre-upgrade writes superseded by the same kind of write from this build are not live; cached per gate read and host) it refuses `segmented_mirror_writer_gate` without reserving a record, and the target retries and parks as usual. `resumeGatedMirrors` (each effect pass, at most once per gate TTL per engine) requeues, via `retryParkedEffects`, requests whose parked targets all carry that code once the gate is clear. No version 1 fallback: it would hold the file whole, and v0.60.290.0's recovery of it refuses to materialize a segmented page forever. Tests: `test/pathological/lp-d-recovery-version.test.ts`, `test/pathological/lp-d-segmented-mirror-gate.test.ts` (both engines).
diff --cc docs/guides/repair.md
index 6e3c3ceb5d,5627788632..179a8a0402
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@@ -9,7 -9,7 +9,7 @@@ fixes those and the other kinds listed
[What each kind fixes](#what-each-kind-fixes). Every run is a preview unless
you pass `--apply`.
The explicit-only kinds, among them `google-file-modes`, `stale-atoms`, `extractor-facts`,
- `captured-facts`, `loop-facts`, `ontology-facts`, `orphan-children`, `failed-writes`, `frontmatter`, `managed-sync-orphans`, `stuck-recovery`, `aliases`, `rename-identity` and `segmented-mirror`, run only when you name them (see [Explicit-only repair kinds](#explicit-only-repair-kinds)).
-`captured-facts`, `loop-facts`, `ontology-facts`, `orphan-children`, `failed-writes`, `frontmatter`, `managed-sync-orphans`, `content-receipt-root`, `stuck-recovery`, `aliases` and `rename-identity`, run only when you name them (see [Explicit-only repair kinds](#explicit-only-repair-kinds)).
++`captured-facts`, `loop-facts`, `ontology-facts`, `orphan-children`, `failed-writes`, `frontmatter`, `managed-sync-orphans`, `content-receipt-root`, `stuck-recovery`, `aliases`, `rename-identity` and `segmented-mirror`, run only when you name them (see [Explicit-only repair kinds](#explicit-only-repair-kinds)).
`gbrain doctor --remediation-plan` lists the same kinds as repair steps, and
`gbrain doctor --remediate --yes --include-repairs --expect <plan_hash>` runs them under a budget
(see [Run repairs through doctor](#run-repairs-through-doctor)).
@@@ -150,7 -151,7 +151,8 @@@ work behind exits 0, so scripts should
| `rename-identity` | `rename_identity_downgrades` | Explicit-only, preview-bound, destructive consent. For an inexact Git rename that sync split into a delete plus an add (#6729): carries the old page's identity (id, version history, timeline, links, facts, aliases) onto the new slug, imports the new file onto it as an edit and retires the provisional page; or, with `--close`, settles the pair and moves nothing. `--slug <new-slug>` (and `--from <old-slug>`) names one pair; `--apply --expect <hash> --yes`. See [rename identity](#rename-identity). | `fact_rows_collide` (a fence row of the old page the new file does not keep with the same claim); `managed_remedy_unavailable` (a carry on a managed source; `--close` is the remedy there); pages changed after the preview (`changed_since_preview`). |
| `overwritten-edits` | `sync_overwritten_db_edits` | Explicit-only, preview-bound. Restores database edits that an incremental managed sync replaced with a committed file edit and no `file_drift` hold (#6712, fixed by #6887). It restores only what the records prove: a database-only revision (its receipt published no file) archived by a managed-sync import that wrote different content, with no later revision holding the edit again. The preview diffs the live page against the edit; `--apply --expect <hash>` reverts each page to that version through a revision-bound, database-only `revert_version` and holds the committed file `file_drift` when it differs. See [overwritten edits](#overwritten-edits). | `unknown_*` findings (no persistence outcome on the writer's receipt, the import's content no longer readable, a segmented version), listed but not restored; pages that moved after the preview (`changed_since_preview`). |
| `missing-tables` | `schema_missing_tables` | Explicit-only, preview-bound. Recreates, empty, a rebuildable cache table (`query_cache`, `code_traversal_cache`) that the applied migrations created but the brain no longer has, on a brain whose schema version already covers its creating migration, so `apply-migrations` never recreates it (#6911). DDL only (`IF NOT EXISTS`), no journal admission, brain-wide. See [missing tables](#missing-tables). | `user_data_tables`: a missing table that holds user data; this repair never recreates it, so restore its rows from a backup first. `other_tables`: a missing table that holds no user data; `gbrain init --migrate-only` recreates it if the base schema defines it. |
+ | `url-clone-fences` | none (`gbrain sync --source <id>` stops at the pull with `pull_blocked_local_changes`) | Explicit-only, preview-bound, destructive consent. Clears the `## Facts` fence rows an older gbrain appended to files of a clone it owns (`gbrain sources add --url`), which block every `git pull --ff-only` that touches those files (#6946). The preview proves each changed file differs from HEAD only by appended fence rows; `--apply --expect <hash> --yes` backs each file up, keeps its rows database-only and restores the file from HEAD. Unmanaged brains only. See [URL clone fences](#url-clone-fences). | `non_fence_edit`, `unparsed_fence`, `staged_change`, `deleted`, `not_in_head`, `unreadable_checkout`: a file with any other difference from HEAD, named with why; files that changed after the preview (`changed_since_preview`). |
+| `segmented-mirror` | none (doctor does not read segmented files; run the preview once if the brain ran a version before v0.60.299.0) | Explicit-only, preview-bound, destructive consent. Rewrites the canonical file of a page stored in segments that an older binary's withdrawal mirror passed by (`page_body_segmented`), so the file still holds a row `forget`, `forget_fact` or `purge_fact` removed from the database. The file becomes the page's canonical render (`gbrain export`'s bytes), written by the withdrawal mirror and committed by its Git effect. See [segmented mirror](#segmented-mirror). | `file_database_drift`: the file also differs from the database for another reason; it is listed held and never rewritten. `not_owner_host`: the preview ran off the source's owner host and read none of its files. |
Timeline rows that an earlier version of a page produced and its current text
no longer has are removals, not history, so `timeline` neither counts nor
diff --cc docs/guides/write-refusals.md
index 0789d860e6,4f5fbdab8c..295eb20c64
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@@ -524,7 -522,7 +524,7 @@@ retry_after_ms, eta_seconds, rate_pages
| <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. `effect_recovery` or `request_recovery` with state [`recovery_version_unsupported`](#recovery_version_unsupported) is a record a newer gbrain wrote, which no recovery here finishes. 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; `recovery_version_unsupported` tells the user to run `gbrain upgrade` on the owner host. 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="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). `effect_recovery` or `request_recovery` with state [`recovery_version_unsupported`](#recovery_version_unsupported) is a record a newer gbrain wrote, which no recovery here finishes. 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>`; `recovery_version_unsupported` tells the user to run `gbrain upgrade` on the owner host. |
| <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. |
diff --cc src/core/persistence/effects.ts
index 6dd13281e8,c908f9f79e..f6940b13b2
--- a/src/core/persistence/effects.ts
+++ b/src/core/persistence/effects.ts
@@@ -594,13 -726,18 +728,19 @@@ export async function claimAndRecoverEf
export async function runPersistenceEffects(engine: BrainEngine, config: GBrainConfig, opts: EffectWorkerOptions): Promise<number> {
// #6696 (A1): every request whose effect this pass claimed is trued up after the pass, outside the settling transactions.
const touched = new Set<string>();
- try { return await runEffectPass(engine, config, opts, touched); }
- finally { await trueUpRequests(engine, touched).catch(() => { /* idempotent; the next settlement of the request retries it */ }); }
+ const derived: DerivedFailures = { run: new ItemRun('effects.derived_retry_budget'), counted: [] };
+ try { return await runEffectPass(engine, config, opts, touched, derived); }
+ finally {
+ await settleDerivedFailures(engine, derived).catch(() => { /* an unsettled claim expires and the effect is claimed again */ });
+ await (async () => { if (await hasRearmableTargets(engine, [...touched])) await engine.transaction(tx => rearmWithheldTargets(tx, [...touched])); })()
+ .catch(() => { /* idempotent; the next pass touching the request retries it */ });
+ await trueUpRequests(engine, touched).catch(() => { /* idempotent; the next settlement of the request retries it */ });
+ }
}
- async function runEffectPass(engine: BrainEngine, config: GBrainConfig, opts: EffectWorkerOptions, touched: Set<string>): Promise<number> {
+ async function runEffectPass(engine: BrainEngine, config: GBrainConfig, opts: EffectWorkerOptions, touched: Set<string>, derived: DerivedFailures): Promise<number> {
const limit = Math.max(1, Math.min(opts.limit ?? 2, 20));
+ await resumeGatedMirrors(engine, opts.hostId);
const recoveries = await selectEffectRecoveries(engine, opts.hostId, limit);
let attempted = 0;
for (const recovery of recoveries) {
diff --cc src/core/persistence/head-blocker.ts
index 5f7e6458ff,882c56d702..f7a1a37d7e
--- a/src/core/persistence/head-blocker.ts
+++ b/src/core/persistence/head-blocker.ts
@@@ -7,8 -7,8 +7,9 @@@
* reports `restart_required` (a zombie publication), or a withdrawal-mirror effect recovery its own last attempt refused
* `unexpected_file_bytes` whose file still matches neither recorded version (an edit made while the mirror was publishing;
* recovery only finishes forward and never overwrites it), or a page write's publication recovery refused the same way (#6650;
- * `gbrain repair stuck-recovery` is its exit), whether it blocks a queued head or is the head itself, or an effect or request
- * recovery record a newer gbrain wrote (`recovery_version_unsupported`: an upgrade is its exit). Every other blocker is live and transient (a foreground publication,
+ * `gbrain repair stuck-recovery` is its exit, for a page write and a shared-skill bundle alike), whether it blocks a queued head or is the head itself;
- * the effect recovery's exit is the same preview (`--keep withdrawn`). Every other blocker is live and transient (a foreground publication,
++ * the effect recovery's exit is the same preview (`--keep withdrawn`); or an effect or request recovery record a newer gbrain wrote
++ * (`recovery_version_unsupported`: an upgrade is its exit). Every other blocker is live and transient (a foreground publication,
* a refresh or recovery making progress, a lapsed lease the next consumer reclaims), so the drain keeps its progress-aware wait.
*/
import { existsSync, readFileSync } from 'node:fs';
@@@ -45,11 -44,13 +46,13 @@@ interface RowRef { request_id: string;
interface ProbeRow { id: string; worktree_id: string | null; owner_host_id: string | null; worktree_state: string | null; claimable: boolean;
fence: { id: string; state: string } | null; effect_recovery: EffectRecoveryRef[] | null; mirrors: string[] | null; request_recovery: RequestRecoveryRef[] | null;
earlier: RowRef[] | null; ahead: RowRef[] | null }
- interface EffectRecoveryRef { id: string; error_code: string | null; slug: string | null; path: string | null; before: string | null; after: string | null; version: unknown }
-interface EffectRecoveryRef { id: string; request_id: string | null; error_code: string | null; slug: string | null; path: string | null; before: string | null; after: string | null }
++interface EffectRecoveryRef { id: string; request_id: string | null; error_code: string | null; slug: string | null; path: string | null; before: string | null; after: string | null; version: unknown }
interface RequestRecoveryRef { request_id: string; state: RequestState; blocked_reason: string | null; slug: string; version: string | null; path: string | null;
- before: string | null; after: string | null }
+ before: string | null; after: string | null; files: Array<{ path: string | null; before: string | null; after: string | null }> | null }
const REQUEST_RECOVERY = (alias: string) => `jsonb_build_object('request_id',${alias}.request_id::text,'state',${alias}.state,'blocked_reason',${alias}.blocked_reason,
- 'slug',${alias}.slug,'version',${alias}.recovery->>'version','path',${alias}.recovery->>'path','before',${alias}.recovery->>'beforeHash','after',${alias}.recovery->>'afterHash')`;
+ 'slug',${alias}.slug,'version',${alias}.recovery->>'version','path',${alias}.recovery->>'path','before',${alias}.recovery->>'beforeHash','after',${alias}.recovery->>'afterHash',
+ 'files',(SELECT jsonb_agg(jsonb_build_object('path',f->>'path','before',f->>'beforeHash','after',f->>'afterHash'))
+ FROM jsonb_array_elements(CASE WHEN jsonb_typeof(${alias}.recovery->'files')='array' THEN ${alias}.recovery->'files' ELSE '[]'::jsonb END) f))`;
/**
* Whether a recovery's last attempt refused `unexpected_file_bytes` and its file still matches neither recorded hash (the check
@@@ -64,18 -65,16 +67,21 @@@ function stuckOnFile(code: string | nul
} catch { return true; }
}
const effectRecoveryStuck = (effect: EffectRecoveryRef) => stuckOnFile(effect.error_code, effect.path, effect.before, effect.after);
- /** A live page recovery (a terminal one never restores its file; a skill bundle has no stuck-recovery exit). */
- const requestRecoveryStuck = (request: RequestRecoveryRef) => request.version === '1' && !isTerminal(request)
- && stuckOnFile(request.blocked_reason, request.path, request.before, request.after);
+ /** A live page or skill-bundle recovery's first file that matches neither recorded version (a terminal one never restores its file). */
+ const requestRecoveryStuckFile = (request: RequestRecoveryRef): string | null => {
+ if (isTerminal(request)) return null;
+ const files = request.version === '1' ? [{ path: request.path, before: request.before, after: request.after }] : request.version === '2' ? request.files ?? [] : [];
+ return files.find(file => stuckOnFile(request.blocked_reason, file.path, file.before, file.after))?.path ?? null;
+ };
+/** A record a newer gbrain wrote (recovery-version.ts): no recovery here finishes it, so only an upgrade clears it. */
+const newerRecord = (table: RecoveryTable, version: unknown) => !recoveryVersionKnown(table, { version: typeof version === 'string' && /^\d+$/.test(version) ? Number(version) : version });
+const newerBlocker = (predicate: 'effect_recovery' | 'request_recovery', ids: string[]): HeadBlocker =>
+ ({ predicate, ids, state: 'recovery_version_unsupported', owner: null, intervention: true });
const requestRecoveryBlocker = (refs: RequestRecoveryRef[]): HeadBlocker => {
+ if (refs.some(ref => newerRecord('persistence_requests', ref.version))) return newerBlocker('request_recovery', refs.map(ref => ref.request_id));
- const stuck = refs.find(requestRecoveryStuck);
+ const stuck = refs.map(ref => ({ ref, path: requestRecoveryStuckFile(ref) })).find(entry => entry.path);
return { predicate: 'request_recovery', ids: refs.map(ref => ref.request_id), state: stuck ? 'unexpected_file_bytes' : null, owner: null, intervention: !!stuck,
- ...(stuck ? { file: { slug: stuck.slug, path: stuck.path! } } : {}) };
+ ...(stuck ? { file: { slug: stuck.ref.slug, path: stuck.path! } } : {}) };
};
const REF = (alias: string) => `jsonb_build_object('request_id',${alias}.request_id::text,'state',${alias}.state,'claim_phase',${alias}.claim_phase,
@@@ -95,8 -94,8 +101,8 @@@ export async function readHeadBlockers(
(${claimableWriteSql(priority)}) AS claimable,
(SELECT jsonb_build_object('id',f.id::text,'state',f.state) FROM persistence_worktree_refreshes f
WHERE f.worktree_id=r.worktree_id AND f.state IN ('fenced','merged','recovery_required') LIMIT 1) AS fence,
- (SELECT jsonb_agg(jsonb_build_object('id',e.id::text,'error_code',e.error_code,'slug',e.recovery->>'slug','path',e.recovery->>'path',
+ (SELECT jsonb_agg(jsonb_build_object('id',e.id::text,'request_id',(SELECT q.request_id::text FROM persistence_requests q WHERE q.id=e.request_id),'error_code',e.error_code,'slug',e.recovery->>'slug','path',e.recovery->>'path',
- 'before',e.recovery->>'beforeHash','after',e.recovery->>'afterHash') ORDER BY e.id) FROM persistence_effects e WHERE e.worktree_id=r.worktree_id AND e.recovery IS NOT NULL) AS effect_recovery,
+ 'before',e.recovery->>'beforeHash','after',e.recovery->>'afterHash','version',e.recovery->'version') ORDER BY e.id) FROM persistence_effects e WHERE e.worktree_id=r.worktree_id AND e.recovery IS NOT NULL) AS effect_recovery,
(SELECT array_agg(m.id::text) FROM persistence_effects m WHERE m.worktree_id=r.worktree_id AND m.kind='withdrawal-mirror' AND m.state IN ('queued','running')
AND (NOT (m.data ? 'targets') OR m.data->'targets' @> jsonb_build_array(jsonb_build_object('slug',r.slug)))) AS mirrors,
(SELECT jsonb_agg(${REQUEST_RECOVERY('b')} ORDER BY b.sequence) FROM persistence_requests b WHERE b.worktree_id=r.worktree_id AND b.recovery IS NOT NULL) AS request_recovery,
@@@ -158,7 -153,7 +164,7 @@@
async function recoveringHeadBlocker(engine: BrainEngine, id: string, hostId: string | null, opts: { timeoutMs?: number; signal?: AbortSignal }): Promise<HeadBlocker | null> {
const [row] = await engine.executeRaw<{ ref: RequestRecoveryRef; owner_host_id: string | null }>(`SELECT ${REQUEST_RECOVERY('r')} AS ref, w.owner_host_id::text AS owner_host_id
FROM persistence_requests r JOIN persistence_worktrees w ON w.id=r.worktree_id WHERE r.id=$1::uuid AND r.recovery IS NOT NULL`, [id], opts);
- if (!row || !hostId || row.owner_host_id !== hostId || (!requestRecoveryStuck(row.ref) && !newerRecord('persistence_requests', row.ref.version))) return null;
- if (!row || !hostId || row.owner_host_id !== hostId || !requestRecoveryStuckFile(row.ref)) return null;
++ if (!row || !hostId || row.owner_host_id !== hostId || (!requestRecoveryStuckFile(row.ref) && !newerRecord('persistence_requests', row.ref.version))) return null;
return requestRecoveryBlocker([row.ref]);
}
diff --cc src/core/repair/core.ts
index 3a7e34e627,0bd3765bcc..7b8ede14bb
--- a/src/core/repair/core.ts
+++ b/src/core/repair/core.ts
@@@ -49,7 -49,7 +49,7 @@@ import { RECEIPT_RESERVATION_FLOOR } fr
import { readFix } from '../ops/op-fix.ts';
import { ItemRun, type ItemFailure } from '../item-failure.ts';
- export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'accepted-takes', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'missing-tables', 'segmented-mirror'] as const;
-export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'accepted-takes', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'missing-tables', 'url-clone-fences'] as const;
++export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'accepted-takes', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'missing-tables', 'url-clone-fences', 'segmented-mirror'] as const;
export type RepairKind = typeof REPAIR_KINDS[number];
export interface RepairScope { brain_id: string; source_ids: string[] }
diff --cc src/core/repair/registry.ts
index 427e5b6974,11e3a3ddfa..b4c1000662
--- a/src/core/repair/registry.ts
+++ b/src/core/repair/registry.ts
@@@ -73,7 -74,7 +74,8 @@@ import { aliasesRepair } from './aliase
import { renameIdentityRepair, RENAME_IDENTITY_CONSENT_TEXT } from './rename-identity.ts';
import { overwrittenEditsRepair } from './overwritten-edits.ts';
import { missingTablesRepair } from './missing-tables.ts';
+ import { urlCloneFencesRepair } from './url-clone-fences.ts';
+import { segmentedMirrorRepair } from './segmented-mirror.ts';
import { ERROR_CATALOGUE, catalogueError } from '../error-catalogue.ts';
import type { OperationError } from '../ops/contract.ts';
@@@ -406,22 -414,20 +415,36 @@@ const SPECS: Record<RepairKind, Omit<Re
+ 'recreated. DDL only (IF NOT EXISTS), no journal admission. The preview prints a hash; --apply --expect <hash> recreates exactly that set. '
+ 'Runs only when named; never on upgrade. Brain-wide.',
},
+ 'url-clone-fences': {
+ handler: urlCloneFencesRepair, embeds: 'none', checks: [], explicit_only: true, preview_bound: true, consent: 'destructive',
+ consentText: {
+ what: 'Restore the previewed files of a clone gbrain owns from HEAD after keeping their gbrain fence rows database-only',
+ why: 'An older release appended ## Facts fence rows to these clone files, and the local change blocks every git pull --ff-only that touches them; the preview proved each file differs from HEAD by those rows alone.',
+ risk: 'Each file is backed up under ~/.gbrain/backups/url-clone-fences/ before it changes, and its fact rows stay active and recallable in the database. A file that changed since the preview is skipped. Copy the backup back to undo.',
+ user_message: 'Restore the previewed clone files from the last pulled commit? Their facts stay in the database and each file is backed up first',
+ },
+ summary: 'Clear the local changes an older release left in a gbrain-owned clone (sources add --url), which make every sync stop at the pull with '
+ + 'pull_blocked_local_changes (#6946). The preview lists each tracked file that differs from HEAD and proves the difference is only ## Facts fence '
+ + 'rows gbrain appended; any other difference (a user edit, a staged change, a deleted file) is named and left untouched. --apply --expect <hash> --yes, '
+ + 'per previewed file: back it up, keep its appended rows database-only in one transaction, import HEAD\'s bytes as the page, then restore the file '
+ + 'from HEAD. Unmanaged brains only (a managed brain uses gbrain sources mirror-readonly). Runs only when named.',
+ },
+ 'segmented-mirror': {
+ handler: segmentedMirrorRepair, embeds: 'none', checks: [], explicit_only: true, preview_bound: true, consent: 'destructive',
+ consentText: {
+ what: 'Rewrite the previewed canonical files of pages stored in segments without their withdrawn or purged rows',
+ why: 'The preview listed each file an older binary left holding a row a withdrawal or purge removed from the database; the apply rewrites each one to the page\'s canonical render through the withdrawal mirror.',
+ risk: 'Each listed file is replaced by the bytes gbrain export writes for its page (other formatting differences in it are normalized the same way). A file that changed since the preview refuses the apply (preview_changed), and one that differs from the database for any other reason is never rewritten. The Git effect commits the change; the old bytes stay in earlier commits.',
+ user_message: 'Rewrite the previewed page files without their withdrawn rows? Each becomes the page\'s canonical render',
+ },
+ summary: 'Re-mirror the canonical files of pages stored in segments whose withdrawal mirror an older binary (before v0.60.299.0) passed by '
+ + '(skipped page_body_segmented), so the file still holds a row forget, forget_fact or purge_fact removed from the database. The preview, '
+ + 'on the source\'s owner host and in bounded memory, lists each file-backed segmented page whose file is an older render: it passes the '
+ + 'mirror\'s own file/database check and still holds a withdrawn or purged row; it prints the path, the file\'s SHA-256 and size and those '
+ + 'of the canonical render (gbrain export\'s bytes). A file that differs from the database for another reason is listed held '
+ + '(file_database_drift) and never rewritten. Preview-bound and destructive: --apply --expect <hash> --yes re-checks each page and commits, per '
+ + 'page, one receipted request whose withdrawal-mirror and Git effects rewrite and commit the file. Runs only when named; never on upgrade.',
+ },
};
export const REPAIR_REGISTRY: readonly RepairKindSpec[] = REPAIR_KINDS.map(kind => ({ kind, ...SPECS[kind] }));
diff --cc test/fix-wave-5-integration.test.ts
index d8fba1046b,3f76873836..e96173b89c
--- a/test/fix-wave-5-integration.test.ts
+++ b/test/fix-wave-5-integration.test.ts
@@@ -195,9 -195,9 +195,9 @@@ for (const backend of testBackends())
const untouched = async () => { expect(await liveAtoms()).toBe(30); expect(await activeFacts()).toBe(0); };
const previews = { 'accepted-takes': 'gbrain repair accepted-takes', 'google-file-modes': 'gbrain repair google-file-modes', 'stale-atoms': 'gbrain repair stale-atoms', 'extractor-facts': 'gbrain repair extractor-facts',
'conversation-labels': 'gbrain repair conversation-labels', 'captured-facts': 'gbrain repair captured-facts', 'loop-facts': 'gbrain repair loop-facts', 'ontology-facts': 'gbrain repair ontology-facts', 'facts-rehome': 'gbrain repair facts-rehome', 'orphan-children': 'gbrain repair orphan-children', 'failed-writes': 'gbrain repair failed-writes', 'split-facts': 'gbrain repair split-facts',
- frontmatter: 'gbrain repair frontmatter', 'timeline-comments': 'gbrain repair timeline-comments', 'managed-sync-orphans': 'gbrain repair managed-sync-orphans', 'frontmatter-keys': 'gbrain repair frontmatter-keys', 'file-drift': 'gbrain repair file-drift',
+ frontmatter: 'gbrain repair frontmatter', 'timeline-comments': 'gbrain repair timeline-comments', 'managed-sync-orphans': 'gbrain repair managed-sync-orphans', 'content-receipt-root': 'gbrain repair content-receipt-root', 'frontmatter-keys': 'gbrain repair frontmatter-keys', 'file-drift': 'gbrain repair file-drift',
'stuck-recovery': 'gbrain repair stuck-recovery', 'ghost-pages': 'gbrain repair ghost-pages', 'origin-twins': 'gbrain repair origin-twins', 'receipt-compaction': 'gbrain repair receipt-compaction', aliases: 'gbrain repair aliases', 'rename-identity': 'gbrain repair rename-identity',
- 'overwritten-edits': 'gbrain repair overwritten-edits', 'missing-tables': 'gbrain repair missing-tables', 'segmented-mirror': 'gbrain repair segmented-mirror' };
- 'overwritten-edits': 'gbrain repair overwritten-edits', 'missing-tables': 'gbrain repair missing-tables', 'url-clone-fences': 'gbrain repair url-clone-fences' };
++ 'overwritten-edits': 'gbrain repair overwritten-edits', 'missing-tables': 'gbrain repair missing-tables', 'url-clone-fences': 'gbrain repair url-clone-fences', 'segmented-mirror': 'gbrain repair segmented-mirror' };
// The post-upgrade banner names both findings with the kind's read-only preview.
const banner = await postUpgradeRecoveryBanner(engine, 'host');
diff --cc test/postgres-unit-arms.txt
index ad5a65751f,739dbd70ec..1eb7ebe3a9
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@@ -254,11 -266,11 +266,16 @@@ test/pathological/b5-export-unsafe-slug
test/pathological/b6-triage-verdict-surrogate.test.ts
test/pathological/c-23-override-and-doctor-fixes.test.ts
test/pathological/c-9-facts-absorb-dead.test.ts
+ test/pathological/c1-effect-stuck-recovery.test.ts
+ test/pathological/c2-url-clone-fences.test.ts
+ test/pathological/c4-bundle-stuck-recovery.test.ts
+ test/pathological/c5-writer-transfer-cancel.test.ts
+ test/pathological/c7-content-receipt-root.test.ts
+test/pathological/lp-a-segmented-mirror.test.ts
+test/pathological/lp-d-recovery-version.test.ts
+test/pathological/lp-d-segmented-mirror-gate.test.ts
+test/pathological/lp-f-split-fence-withdrawal-capacity.test.ts
+test/pathological/lp-g-file-digest-fence-bound.test.ts
test/persistence-background-pause.test.ts
test/persistence-bounded-read-session.test.ts
test/persistence-capacity-forecast.test.ts
diff --cc test/repair-explicit-only.test.ts
index f4e1501ef2,fc38ae5d68..3fac51a033
--- a/test/repair-explicit-only.test.ts
+++ b/test/repair-explicit-only.test.ts
@@@ -24,7 -24,7 +24,7 @@@ import { REPAIR_HELP, parseRepairArgs,
import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';
import { withEnv } from './helpers/with-env.ts';
- const EXPLICIT: RepairKind[] = ['accepted-takes', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'missing-tables', 'segmented-mirror'];
-const EXPLICIT: RepairKind[] = ['accepted-takes', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'timeline-comments', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'missing-tables', 'url-clone-fences'];
++const EXPLICIT: RepairKind[] = ['accepted-takes', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'timeline-comments', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'missing-tables', 'url-clone-fences', 'segmented-mirror'];
let engine: PGLiteEngine;
const home = mkdtempSync(join(tmpdir(), 'gbrain-repair-explicit-'));