Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(repair): gbrain repair failed-writes replays caller writes the pre-#5983 guard refused
garrytana00726322ef7
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex e082884888..dad8abc3ce 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.60.38.0",+ "version": "0.60.39.0","description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan",diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex c53d1ffe8c..dc858cb259 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.60.38.0",+ "version": "0.60.39.0","description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan",diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.mdindex 4be8b13ccb..c833b0df21 100644--- a/BOOTSTRAP_FOR_AGENTS.md+++ b/BOOTSTRAP_FOR_AGENTS.md@@ -1,4 +1,4 @@-<!-- gbrain-runbook-stamp: 0.60.38.0 -->+<!-- gbrain-runbook-stamp: 0.60.39.0 --><!-- This stamp must equal the VERSION file at every release; CI enforces it(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it tothe installed binary and warns on skew. -->diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 88755852d3..f3cfce348d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,37 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [0.60.39.0] - 2026-10-03++**`gbrain repair failed-writes` replays the `put_page`, `add_timeline_entry` and `remember` calls the managed writer guard refused before v0.60.38.0 (#5983), from the content their failed receipts still hold. Each write is replayed once, and never over a later write of the same page.**++v0.60.38.0 fixed the guard, but writes it had already refused stayed failed. Resubmitting under the same request id returns the stored failure, and the calling agent often has no copy of what it sent. Each failed receipt keeps the write's full intent until receipt compaction (30 days by default). The new repair kind finds receipts the guard refused, sorts them, and submits the caller writes again through their normal path as the local owner under new request ids.++The preview gives every refused write a class:+- `replay`: replayed on apply.+- `already_written`: the same write committed later, or an earlier apply replayed it.+- `duplicate`: a later attempt of the same write is the candidate instead.+- `superseded`: the page was written or deleted later, or a newer failed save of the page exists, so replaying would overwrite or recreate it.+- `unpinned_target`: a `remember` that was saved unattributed. Replaying it would guess its subject again, so it is kept.+- `producer_owned`: gbrain produced the write itself, through sync or file imports, reconcile, relink or a maintenance page. The preview prints the command that produces it again from current content instead.++The apply replays exactly the previewed set (`--expect <hash>`). It first re-checks each write's class and its original caller's authority. A write an agent sent over MCP is prepared as a remote write again, so it can do no more than the original. A page save is bound to the page revision the preview saw, so it never overwrites a page that changed. The failed receipts stay as history.++## To take advantage of v0.60.39.0++On the brain host, after the v0.60.38.0 recovery steps:++1. **Keep the receipts while you recover** (if you have not already):+ ```bash+ gbrain config set persistence.receipt_retention_days 90+ ```+2. **Preview, show the user the listing, then apply after they agree:**+ ```bash+ gbrain repair failed-writes --source <id>+ gbrain repair failed-writes --source <id> --apply --expect <hash>+ ```+3. **Verify:** a second preview lists nothing to replay (`already_written` instead), and the replayed pages show their tags, timeline entries and facts. For each `superseded` write, read the page and re-issue the change by hand if it is still wanted.+## [0.60.38.0] - 2026-10-03**On a managed brain whose `tags`, `timeline_entries` or `takes` table carries a `source_id` column gbrain never created, every tag, timeline and take write was refused, even coordinated ones. Managed sync stalled at the first tagged page, `facts relink` aborted, autopilot dropped timeline rows every cycle, and `remember`, `add_timeline_entry` and maintenance-page writes failed. Those writes commit again (#5983).**@@ -49,7 +80,7 @@ Tags, timeline entries and takes now always take their source from their page. Agbrain facts relink --source <id> --max-usd <n> # only after the user agrees```Follow the printed `next_command` until `has_more` is false. Exit 0 alone does not mean the backlog is done.-6. **Writes that failed outright are not replayed by the upgrade.** A `remember`, `add_timeline_entry` or maintenance-page write refused by this bug keeps its failed receipt; resubmitting the same request id returns that failure. Re-issue the ones you have a record of with a new request id, and tell the user which writes from the incident window could not be recovered.+6. **Writes that failed outright are not replayed by the upgrade.** A `remember`, `add_timeline_entry` or maintenance-page write refused by this bug keeps its failed receipt; resubmitting the same request id returns that failure. From v0.60.39.0, `gbrain repair failed-writes` replays the caller writes from those receipts. Before that, re-issue the ones you have a record of with a new request id.## [0.60.37.0] - 2026-10-03diff --git a/VERSION b/VERSIONindex 403e6a4253..2d5d7d7c52 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-0.60.38.0+0.60.39.0diff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.mdindex 232a0176b7..68edd5284a 100644--- a/docs/architecture/key-files/core-utilities-2.md+++ b/docs/architecture/key-files/core-utilities-2.md@@ -8,6 +8,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/repair/extractor-facts.ts` — `gbrain repair extractor-facts` (#5731), explicit-only and preview-bound. `classifyExtractorFacts` (read-only; also the doctor check's count) takes conversation-extractor facts with `expired_at` set and `row_num` NULL and classes each: `excluded` (page missing or deleted, `superseded_by` set, withdrawn, an active same-text fact on the page, or an earlier same-text candidate), `ambiguous` (unmanaged brain; no committed request of the page with `completed_at = expired_at`, compared in SQL as microsecond UTC text, which only a same-transaction completion satisfies on Postgres; a consumer at or above v0.60.11.0; or the page has ever held fence-projected facts) or `evidenced`. The preview lists every candidate, hashes them with the selection (`--include-ambiguous`) and saves one approved item per page (with its request id) through `preview-approval.ts`; the apply loads only that set, skips pages whose request already committed or whose facts are active again, and restores each still-identical fact with a fresh `row_num` above the page's facts and fence rows. Managed brains publish one database-only `managed_maintenance_restore_extractor_facts` request per page (`submitDatabaseMaintenanceIntent`, dispatched by `prepareMaintenanceMutation` to `prepareExtractorFactsRestore`, which reclassifies under the page lock); unmanaged brains run the same restore in one locked transaction. Previews warn, naming the host, when a consumer older than this release published after `writer_version_cutoff`. On PGLite `now()` has millisecond resolution, so the same-transaction rule is millisecond-exact there.- `src/core/repair/captured-facts.ts` — `gbrain repair captured-facts`, explicit-only and preview-bound. `classifyCapturedFacts` (read-only; also the `captured_facts_active` count) takes active capture-lane facts and classes each by its session (`captureSessionId`: `sweep:corpus:<file>` resolves through `corpusFileSessionId`): `evidenced` when a gbrain claude-cli scratch project holds the session's harness transcript or its corpus file sits in `<corpus>.quarantine/`; `ambiguous` (paste candidate) when a retained corpus file of the session holds a paste block and at least 60% of the claim's content words occur there only inside paste blocks; `excluded:legitimate_duplicate` when the claim and entity also have an active row that is not proven suspect. Sessions with no transcript and no corpus file are counted `unclassifiable`. The preview hashes every candidate with the selection (`--include-ambiguous`) and saves one approved item per page through `preview-approval.ts`; the apply reclassifies each fact, expires database-only rows through one database-only `managed_maintenance_expire_captured_facts` request per page on a managed brain (owner-checked by `maintenancePreflight`; `prepareCapturedFactsExpiry`, dispatched from `prepareMaintenanceMutation`) or one transaction on an unmanaged brain, and strikes fenced rows in the page's `## Facts` fence through one revision-bound `put_page`, so the canonical projection expires them and a later page write cannot reactivate them. No withdrawal is recorded, so `remember` can save the same claim again. Pinned by `test/repair-captured-facts.test.ts` (+ Postgres arm).- `src/core/repair/loop-facts.ts` — `gbrain repair loop-facts` (#5869), explicit-only and preview-bound (`--apply --expect <hash>`): candidates are `loopFactDrift` rows (closed `done`/`dropped` loops whose commitment fact is active, in the loop's source and shared with no open loop); each item is rechecked (`changed_since_preview`) and retired through `retireLoopFact`, the same coordinated strike-plus-expire publication `loops_close` uses.+- `src/core/repair/failed-writes.ts` — `gbrain repair failed-writes` (#5983), explicit-only and preview-bound: candidates are failed, uncompacted `persistence_requests` refused by the managed writer guard (`writer_coordinator_required`, or `storage_error` "Publication failed (P0001)"). Caller writes (`put_page` without an internal `kind`, `add_timeline_entry`, `remember`) are classified `replay` / `already_written` / `duplicate` / `superseded` / `unpinned_target` by later requests on the same page and by a committed replay request id; owner-produced writes are `producer_owned` residuals with the producer command. The approved set records each target page's revision. Apply resumes an admitted replay attempt, otherwise reclassifies and rechecks the revision, re-runs `authorizeStoredRequest` on the failed row, and resubmits the retained intent on the original trust lane (`laneContext`: remote, take holders, delegated prefixes) through `submitPageMutation` / `submitRememberMutation`, with `put_page` bound to the previewed revision and `remember` pinned to its resolved subject, under a request id derived from the failed request id and attempt (`repair-failed-writes-5983.test.ts`).- `src/core/repair/orphan-children.ts` — `gbrain repair orphan-children` (#5216, #4738), explicit-only, brain-wide, projection publication. `PAGE_CHILD_FK_TARGETS` + `orphanPredicate` are the single target list (doctor `child_table_orphans` in `doctor/checks/core-health.ts` imports them and names this repair instead of printing SQL). One item per (table, column); apply deletes orphans or clears the two ON DELETE SET NULL references in one rechecking statement. `probeTornPages` reads every page body in 500-row batches, row by row inside a failing batch, and the plan reports torn rows as the `torn_pages` residual plus a warning naming id/source/slug; they are never changed. The `storage_corrupt` reason in `pg-access-classify.ts` points XX000 storage errors here (`repair-orphan-children-5216.test.ts`, `pg-access-storage-corrupt-5216.test.ts`).- `src/core/persistence/mirror-read-only.ts` and `src/commands/sources-mirror.ts` — #5409 read-only mirror sources. `sourceMirrorReadOnly(engine, sourceId)` reads `sources.config.mirror_read_only` (default false). When true, `prepareFileTarget` (`page-prepare.ts`) returns no file for any coordinated page write into the source (receipt `write_through.skipped: 'mirror_read_only'`, `storage: 'database_only'`, set in `coordinator.ts`), and managed sync (`sync-prepare.ts`) imports an overlay (canonical form differs from the file bytes) database-only: no `file`, no newer-working-tree refusal, and `contentUnchanged` ignores the overlay. A page created that way with no recorded file is stamped `pages.database_only_reason='mirror_read_only'` (`classifyMirrorPage`, in the publication) and stays database-only after the flag is cleared; the coordinator refuses (`source_changed`) a file target prepared before the flag was set (rechecked under the publication with the source row `FOR SHARE`); `gitPage` (`effects.ts`) completes a mirror source's Git effects as skipped. `gbrain sources mirror-readonly|mirror-writable <id>` set and clear the key like `federate`/`unfederate`; `sources list --json` reports `mirror_read_only`.diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex 0912692c18..b79b179e89 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -8,8 +8,8 @@ can load, and Google source files other local users can read. `gbrain repair`fixes those and the other kinds listed in[What each kind fixes](#what-each-kind-fixes). Every run is a preview unlessyou pass `--apply`.-Five explicit-only kinds, `google-file-modes`, `stale-atoms`, `extractor-facts`,-`captured-facts` and `loop-facts`, run only when you name them (see [Explicit-only repair kinds](#explicit-only-repair-kinds)).+Seven explicit-only kinds, `google-file-modes`, `stale-atoms`, `extractor-facts`,+`captured-facts`, `loop-facts`, `orphan-children` and `failed-writes`, 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` runs them under a budget(see [Run repairs through doctor](#run-repairs-through-doctor)).@@ -99,7 +99,7 @@ gives each a fresh row number); it never deletes or rewrites a page.| `--limit <n>` | Repair at most `n` items per kind in this run (a positive integer; with `--all`, up to `n` for each kind). Rerun the same command to continue. || `--no-embed` | `safe-chunks` and `contextual-mode`: skip the embedding provider. Run `gbrain embed --stale` later. `timeline` and `visibility` pages are re-embedded by their publication either way. || `--all` | Run every automatic kind in order. Explicit-only kinds are listed with their preview command, never run. |-| `--expect <hash>` | Explicit-only kinds: apply exactly the set the preview printed under this hash. Required with `--apply` for `stale-atoms`, `extractor-facts`, `captured-facts` and `loop-facts`. |+| `--expect <hash>` | Explicit-only kinds: apply exactly the set the preview printed under this hash. Required with `--apply` for `stale-atoms`, `extractor-facts`, `captured-facts`, `loop-facts` and `failed-writes`. || `--include-ambiguous` | `extractor-facts` and `captured-facts` only: widen the hashed set to `ambiguous` facts. Pass it to both the preview and the apply. See [Extractor facts](#extractor-facts) and [Captured facts](#captured-facts). || `--json` | Print `{ scope, mode, results[], paid_kinds }`, one result per kind with `paid`, `affected`, `sample`, `residuals`, `cost`, `capacity`, `resumed_from`, `applied`, `skipped`, `complete`, `stopped` and `apply_command`, plus `explicit_kinds[]` when the run skipped explicit-only kinds. |@@ -506,6 +506,62 @@ in one coordinated write, exactly for the previewed set; a loop or fact thatchanged since the preview reports `changed_since_preview` and is kept. Nowithdrawal is recorded, so the same promise made again is stored normally.+<a id="failed-writes"></a>+### Failed writes++Before v0.60.38.0, on a managed brain whose `tags`, `timeline_entries` or+`takes` table had a `source_id` column gbrain does not create, the managed+writer guard refused writes it should have allowed (#5983). Each refused write+keeps a failed receipt with its full intent until receipt compaction+(`persistence.receipt_retention_days`, 30 days by default). `gbrain repair+failed-writes` submits those writes again. It is explicit-only and+preview-bound, and needs v0.60.38.0 or later (`gbrain doctor --json` reports+schema version 197 or later).++**Say to your agent:** *"Preview which refused writes gbrain can replay, show+me the list, then apply after I agree."* The agent runs `gbrain repair+failed-writes` and, after you agree, the printed apply command.++```bash+gbrain config set persistence.receipt_retention_days 90 # keep the receipts while you recover+gbrain repair failed-writes --source <id> # preview: every refused write with its class+gbrain repair failed-writes --source <id> --apply --expect <hash>+gbrain repair failed-writes --source <id> # replayed writes now read already_written+```++Candidates are failed receipts refused by the guard: `writer_coordinator_required`,+or `storage_error` "Publication failed (P0001)" from releases that did not keep+the guard's message. Only writes a caller made directly are replayed:+`put_page`, `add_timeline_entry` and `remember`. The preview gives every+candidate one class:++| Class | Meaning | What happens |+| --- | --- | --- |+| `replay` | No later write supersedes it. | Replayed on apply. |+| `already_written` | A later request with the same intent committed, or an earlier apply replayed it. | Kept. |+| `duplicate` | A later request with the same intent exists; that one is the candidate. | Kept. |+| `superseded` | A later write or delete of the page committed or is still pending; for `put_page`, also a later failed `put_page` of the page (the newer content) or a page that changed after the revision the caller read. | Kept. Read the page and re-issue the change by hand if it is still wanted. |+| `unpinned_target` | A `remember` saved unattributed; replaying would infer its subject again and could pick another page. | Kept. Re-issue it with an explicit `entity` if it is still wanted. |+| `producer_owned` | gbrain produced it (sync or file import, reconcile, relink, maintenance page, job). | Kept. The preview prints the command that produces it again from current content, such as `gbrain sync --source <id> --no-pull --retry-failed --json`. |++The apply replays exactly the previewed set. Each write is classified again+and its original caller's authority is checked again first: a write that+changed class since the preview reports `changed_since_preview`, and one whose+caller lost its grant or whose source was re-created reports+`authority_revoked`; both are kept. A replay goes through the operation's+normal path on the original caller's trust lane: a write an agent sent over MCP+is prepared as a remote write again, with its take-holder and delegated+namespace limits, so it can do no more than the original could. A `put_page`+replay is bound to the page revision the preview saw (an original `force: true`+is dropped), so a page changed since the preview reports `changed_since_preview`+or `conflict` instead of being overwritten. A `remember` replay targets the+subject the original resolved. Each replay uses a new request id derived from+the failed one, so a rerun after a crash resumes the same request and a second+apply never writes it twice (`pending_elsewhere` when another writer holds that+request). Attribution names the local owner's writer for that lane. A replay the+brain refuses reports `refused` with the code. The failed receipts stay as+history.+## ResumeRuns are resumable. After each page commits, the position is saved under the@@ -676,7 +732,7 @@ walk me through it before changing anything."*| Symptom or error text | Issue | Preview | Apply | Verify || --- | --- | --- | --- | --- |-| Tag, timeline or take writes fail with `writer_coordinator_required` or `storage_error: Publication failed (P0001)` on a managed brain; sync ends `PARTIAL` at a tagged page | #5983 | `gbrain doctor --json` (`schema_version` is 197 or later) | the original `gbrain sync --source <source> … --no-pull --retry-failed --json`, then `gbrain extract --stale --source-id <source>` and `gbrain extract timeline --source db --source-id <source>`, then `gbrain facts relink --source <source> --dry-run` (paid tier only after the user agrees) | `gbrain sources status` shows the new `last_commit`; a second `gbrain extract timeline --source db` run adds no rows |+| Tag, timeline or take writes fail with `writer_coordinator_required` or `storage_error: Publication failed (P0001)` on a managed brain; sync ends `PARTIAL` at a tagged page | #5983 | `gbrain doctor --json` (`schema_version` is 197 or later) | the original `gbrain sync --source <source> … --no-pull --retry-failed --json`, then `gbrain extract --stale --source-id <source>` and `gbrain extract timeline --source db --source-id <source>`, then `gbrain facts relink --source <source> --dry-run` (paid tier only after the user agrees), then `gbrain repair failed-writes --source <source>` and, after the user agrees, its printed `--apply --expect <hash>` | `gbrain sources status` shows the new `last_commit`; a second `gbrain extract timeline --source db` run adds no rows; a second `gbrain repair failed-writes` preview lists nothing to replay || Sync `BLOCKED` with `checkpoint_validation_timeout` | #5762 | `gbrain doctor` (`persistence_request_indexes`) | `gbrain repair request-indexes --apply` when an index is missing or INVALID, then the printed `gbrain sync --source <source> --no-pull --retry-failed …` | `gbrain doctor` shows `persistence_request_indexes` ok; `gbrain sources status` shows the new `last_commit` || Doctor `persistence_request_indexes` warns | #5762 | `gbrain repair request-indexes` | `gbrain repair request-indexes --apply` | `gbrain doctor` || Doctor `persistence_request_growth` warns | #5751, #5762 | `gbrain doctor --json` | the printed `gbrain config set persistence.limits.<limit> <value>` | `gbrain doctor --json` (check `persistence_request_growth`) |diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 3ad5c04cc0..d4532bffaa 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -97,7 +97,7 @@ a receipt can report has a row here.| `writer_registration_required` | `writer_registration_required` | The source needs an active canonical owner before this operation, for example activation. | Claim the source on its owner host (`gbrain sources writer status <source>` names the next step). || `writer_identity_invalid` | `writer_identity_invalid` | This host's local writer identity file is unreadable or has an unknown format. | Run `gbrain doctor` on the host; it names the identity file to repair. || `writer_not_initialized` | `writer_not_initialized` | The brain has no persistence identity yet, usually because migrations have not run. | Run `gbrain apply-migrations --yes` on the brain host. |-| <a id="managed-guard-page-children"></a>`writer_coordinator_required: canonical writer must use the persistence coordinator` on a tag, timeline or take write; on the client `storage_error: Publication failed (P0001)` | `writer_coordinator_required` (`storage_error` on the stored receipt) | Before v0.60.38.0, on a managed brain whose `tags`, `timeline_entries` or `takes` table had a `source_id` column gbrain does not create, the managed writer guard refused every insert and update of those rows, including coordinated ones (#5983). From v0.60.38.0 those rows always take their source from their page and the column is ignored. An uncoordinated delete of such a row on a live page is now refused there too, as on every other brain. | Upgrade to v0.60.38.0 or later on the brain host, then follow its recovery steps in the [CHANGELOG](../../CHANGELOG.md) (or [repair](repair.md#recover-after-upgrading-to-this-release)): `gbrain sync … --no-pull --retry-failed`, `gbrain extract --stale`, `gbrain extract timeline --source db`, then a previewed `gbrain facts relink`. |+| <a id="managed-guard-page-children"></a>`writer_coordinator_required: canonical writer must use the persistence coordinator` on a tag, timeline or take write; on the client `storage_error: Publication failed (P0001)` | `writer_coordinator_required` (`storage_error` on the stored receipt) | Before v0.60.38.0, on a managed brain whose `tags`, `timeline_entries` or `takes` table had a `source_id` column gbrain does not create, the managed writer guard refused every insert and update of those rows, including coordinated ones (#5983). From v0.60.38.0 those rows always take their source from their page and the column is ignored. An uncoordinated delete of such a row on a live page is now refused there too, as on every other brain. | Upgrade to v0.60.38.0 or later on the brain host, then follow its recovery steps in the [CHANGELOG](../../CHANGELOG.md) (or [repair](repair.md#recover-after-upgrading-to-this-release)): `gbrain sync … --no-pull --retry-failed`, `gbrain extract --stale`, `gbrain extract timeline --source db`, a previewed `gbrain facts relink`, then `gbrain repair failed-writes` (preview, then `--apply --expect <hash>`) for the refused `put_page`, `add_timeline_entry` and `remember` calls; see [failed writes](repair.md#failed-writes). || `writer_coordinator_required` | `writer_coordinator_required` | The operation needs managed persistence (the write coordinator) and this brain or call path does not use it. A file write refused because the path sits in a managed canonical worktree names that worktree in the message, and its `detail` reads `root=<directory> source=<id or unknown> evidence=<marker file, managed-root registry or source binding>`. | Run the operation through the command the message names, on a managed brain. When the brain is not managed and the evidence is an ownership file (`.gbrain-owner.json`, `.gbrain-owner-<hash>.json`, `.gbrain-managed`), check it with `gbrain sources writer status` before removing anything: a half-finished claim is finished or rolled back through writer administration. || `fact_already_expired` | `fact_already_expired` | The fact the write targets is already expired or withdrawn. | Nothing to do; list active facts to find the current one. || `source_writeback_required` | `source_writeback_required` | The write needs a correction to the source's repository files, and this caller or profile never writes them. | Make the correction in the source repository, then sync. |diff --git a/llms-full.txt b/llms-full.txtindex 196585c26f..ce9bcd3f02 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -8906,8 +8906,8 @@ can load, and Google source files other local users can read. `gbrain repair`fixes those and the other kinds listed in[What each kind fixes](#what-each-kind-fixes). Every run is a preview unlessyou pass `--apply`.-Five explicit-only kinds, `google-file-modes`, `stale-atoms`, `extractor-facts`,-`captured-facts` and `loop-facts`, run only when you name them (see [Explicit-only repair kinds](#explicit-only-repair-kinds)).+Seven explicit-only kinds, `google-file-modes`, `stale-atoms`, `extractor-facts`,+`captured-facts`, `loop-facts`, `orphan-children` and `failed-writes`, 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` runs them under a budget(see [Run repairs through doctor](#run-repairs-through-doctor)).@@ -8997,7 +8997,7 @@ gives each a fresh row number); it never deletes or rewrites a page.| `--limit <n>` | Repair at most `n` items per kind in this run (a positive integer; with `--all`, up to `n` for each kind). Rerun the same command to continue. || `--no-embed` | `safe-chunks` and `contextual-mode`: skip the embedding provider. Run `gbrain embed --stale` later. `timeline` and `visibility` pages are re-embedded by their publication either way. || `--all` | Run every automatic kind in order. Explicit-only kinds are listed with their preview command, never run. |-| `--expect <hash>` | Explicit-only kinds: apply exactly the set the preview printed under this hash. Required with `--apply` for `stale-atoms`, `extractor-facts`, `captured-facts` and `loop-facts`. |+| `--expect <hash>` | Explicit-only kinds: apply exactly the set the preview printed under this hash. Required with `--apply` for `stale-atoms`, `extractor-facts`, `captured-facts`, `loop-facts` and `failed-writes`. || `--include-ambiguous` | `extractor-facts` and `captured-facts` only: widen the hashed set to `ambiguous` facts. Pass it to both the preview and the apply. See [Extractor facts](#extractor-facts) and [Captured facts](#captured-facts). || `--json` | Print `{ scope, mode, results[], paid_kinds }`, one result per kind with `paid`, `affected`, `sample`, `residuals`, `cost`, `capacity`, `resumed_from`, `applied`, `skipped`, `complete`, `stopped` and `apply_command`, plus `explicit_kinds[]` when the run skipped explicit-only kinds. |@@ -9404,6 +9404,53 @@ in one coordinated write, exactly for the previewed set; a loop or fact thatchanged since the preview reports `changed_since_preview` and is kept. Nowithdrawal is recorded, so the same promise made again is stored normally.+<a id="failed-writes"></a>+### Failed writes++Before v0.60.38.0, on a managed brain whose `tags`, `timeline_entries` or+`takes` table had a `source_id` column gbrain does not create, the managed+writer guard refused writes it should have allowed (#5983). Each refused write+keeps a failed receipt with its full intent until receipt compaction+(`persistence.receipt_retention_days`, 30 days by default). `gbrain repair+failed-writes` submits those writes again. It is explicit-only and+preview-bound, and needs v0.60.38.0 or later (`gbrain doctor --json` reports+schema version 197 or later).++**Say to your agent:** *"Preview which refused writes gbrain can replay, show+me the list, then apply after I agree."* The agent runs `gbrain repair+failed-writes` and, after you agree, the printed apply command.++```bash+gbrain config set persistence.receipt_retention_days 90 # keep the receipts while you recover+gbrain repair failed-writes --source <id> # preview: every refused write with its class+gbrain repair failed-writes --source <id> --apply --expect <hash>+gbrain repair failed-writes --source <id> # replayed writes now read already_written+```++Candidates are failed receipts refused by the guard: `writer_coordinator_required`,+or `storage_error` "Publication failed (P0001)" from releases that did not keep+the guard's message. Only writes a caller made directly are replayed:+`put_page`, `add_timeline_entry` and `remember`. The preview gives every+candidate one class:++| Class | Meaning | What happens |+| --- | --- | --- |+| `replay` | No later write supersedes it. | Replayed on apply. |+| `already_written` | A later request with the same intent committed, or an earlier apply replayed it. | Kept. |+| `duplicate` | A later request with the same intent exists; that one is the candidate. | Kept. |+| `superseded` | A later write of the page committed (`put_page`, whose full content would overwrite it) or the page was deleted (any operation). | Kept. Read the page and re-issue the change by hand if it is still wanted. |+| `producer_owned` | gbrain produced it (sync or file import, reconcile, relink, maintenance page, job). | Kept. The preview prints the command that produces it again from current content, such as `gbrain sync --source <id> --no-pull --retry-failed --json`. |++The apply replays exactly the previewed set. Each write is classified again and+its original caller's authority is checked again first: a write that changed+class since the preview reports `changed_since_preview`, and one whose caller+lost its grant or whose source was re-created reports `authority_revoked`;+both are kept. A replay is submitted by the local owner under a new request id+derived from the failed one, so its attribution names the owner, a rerun after+a crash waits on the same request, and a second apply never writes it twice. A+replay that the brain refuses reports `refused` (or `conflict` for a stale+`expected_revision`) with the code. The failed receipts stay as history.+## ResumeRuns are resumable. After each page commits, the position is saved under the@@ -9574,7 +9621,7 @@ walk me through it before changing anything."*| Symptom or error text | Issue | Preview | Apply | Verify || --- | --- | --- | --- | --- |-| Tag, timeline or take writes fail with `writer_coordinator_required` or `storage_error: Publication failed (P0001)` on a managed brain; sync ends `PARTIAL` at a tagged page | #5983 | `gbrain doctor --json` (`schema_version` is 197 or later) | the original `gbrain sync --source <source> … --no-pull --retry-failed --json`, then `gbrain extract --stale --source-id <source>` and `gbrain extract timeline --source db --source-id <source>`, then `gbrain facts relink --source <source> --dry-run` (paid tier only after the user agrees) | `gbrain sources status` shows the new `last_commit`; a second `gbrain extract timeline --source db` run adds no rows |+| Tag, timeline or take writes fail with `writer_coordinator_required` or `storage_error: Publication failed (P0001)` on a managed brain; sync ends `PARTIAL` at a tagged page | #5983 | `gbrain doctor --json` (`schema_version` is 197 or later) | the original `gbrain sync --source <source> … --no-pull --retry-failed --json`, then `gbrain extract --stale --source-id <source>` and `gbrain extract timeline --source db --source-id <source>`, then `gbrain facts relink --source <source> --dry-run` (paid tier only after the user agrees), then `gbrain repair failed-writes --source <source>` and, after the user agrees, its printed `--apply --expect <hash>` | `gbrain sources status` shows the new `last_commit`; a second `gbrain extract timeline --source db` run adds no rows; a second `gbrain repair failed-writes` preview lists nothing to replay || Sync `BLOCKED` with `checkpoint_validation_timeout` | #5762 | `gbrain doctor` (`persistence_request_indexes`) | `gbrain repair request-indexes --apply` when an index is missing or INVALID, then the printed `gbrain sync --source <source> --no-pull --retry-failed …` | `gbrain doctor` shows `persistence_request_indexes` ok; `gbrain sources status` shows the new `last_commit` || Doctor `persistence_request_indexes` warns | #5762 | `gbrain repair request-indexes` | `gbrain repair request-indexes --apply` | `gbrain doctor` || Doctor `persistence_request_growth` warns | #5751, #5762 | `gbrain doctor --json` | the printed `gbrain config set persistence.limits.<limit> <value>` | `gbrain doctor --json` (check `persistence_request_growth`) |@@ -9991,7 +10038,7 @@ a receipt can report has a row here.| `writer_registration_required` | `writer_registration_required` | The source needs an active canonical owner before this operation, for example activation. | Claim the source on its owner host (`gbrain sources writer status <source>` names the next step). || `writer_identity_invalid` | `writer_identity_invalid` | This host's local writer identity file is unreadable or has an unknown format. | Run `gbrain doctor` on the host; it names the identity file to repair. || `writer_not_initialized` | `writer_not_initialized` | The brain has no persistence identity yet, usually because migrations have not run. | Run `gbrain apply-migrations --yes` on the brain host. |-| <a id="managed-guard-page-children"></a>`writer_coordinator_required: canonical writer must use the persistence coordinator` on a tag, timeline or take write; on the client `storage_error: Publication failed (P0001)` | `writer_coordinator_required` (`storage_error` on the stored receipt) | Before v0.60.38.0, on a managed brain whose `tags`, `timeline_entries` or `takes` table had a `source_id` column gbrain does not create, the managed writer guard refused every insert and update of those rows, including coordinated ones (#5983). From v0.60.38.0 those rows always take their source from their page and the column is ignored. An uncoordinated delete of such a row on a live page is now refused there too, as on every other brain. | Upgrade to v0.60.38.0 or later on the brain host, then follow its recovery steps in the [CHANGELOG](../../CHANGELOG.md) (or [repair](repair.md#recover-after-upgrading-to-this-release)): `gbrain sync … --no-pull --retry-failed`, `gbrain extract --stale`, `gbrain extract timeline --source db`, then a previewed `gbrain facts relink`. |+| <a id="managed-guard-page-children"></a>`writer_coordinator_required: canonical writer must use the persistence coordinator` on a tag, timeline or take write; on the client `storage_error: Publication failed (P0001)` | `writer_coordinator_required` (`storage_error` on the stored receipt) | Before v0.60.38.0, on a managed brain whose `tags`, `timeline_entries` or `takes` table had a `source_id` column gbrain does not create, the managed writer guard refused every insert and update of those rows, including coordinated ones (#5983). From v0.60.38.0 those rows always take their source from their page and the column is ignored. An uncoordinated delete of such a row on a live page is now refused there too, as on every other brain. | Upgrade to v0.60.38.0 or later on the brain host, then follow its recovery steps in the [CHANGELOG](../../CHANGELOG.md) (or [repair](repair.md#recover-after-upgrading-to-this-release)): `gbrain sync … --no-pull --retry-failed`, `gbrain extract --stale`, `gbrain extract timeline --source db`, a previewed `gbrain facts relink`, then `gbrain repair failed-writes` (preview, then `--apply --expect <hash>`) for the refused `put_page`, `add_timeline_entry` and `remember` calls; see [failed writes](repair.md#failed-writes). || `writer_coordinator_required` | `writer_coordinator_required` | The operation needs managed persistence (the write coordinator) and this brain or call path does not use it. A file write refused because the path sits in a managed canonical worktree names that worktree in the message, and its `detail` reads `root=<directory> source=<id or unknown> evidence=<marker file, managed-root registry or source binding>`. | Run the operation through the command the message names, on a managed brain. When the brain is not managed and the evidence is an ownership file (`.gbrain-owner.json`, `.gbrain-owner-<hash>.json`, `.gbrain-managed`), check it with `gbrain sources writer status` before removing anything: a half-finished claim is finished or rolled back through writer administration. || `fact_already_expired` | `fact_already_expired` | The fact the write targets is already expired or withdrawn. | Nothing to do; list active facts to find the current one. || `source_writeback_required` | `source_writeback_required` | The write needs a correction to the source's repository files, and this caller or profile never writes them. | Make the correction in the source repository, then sync. |diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex fd6523249b..81523478fc 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -1,7 +1,7 @@{"id": "gbrain-context-engine","name": "gbrain",- "version": "0.60.38.0",+ "version": "0.60.39.0","description": "Personal knowledge brain with Postgres + pgvector hybrid search","family": "bundle-plugin","kind": "context-engine",diff --git a/package.json b/package.jsonindex 2802979c87..21bbf20c38 100644--- a/package.json+++ b/package.json@@ -207,7 +207,7 @@"bun": ">=1.4.0"},"license": "MIT",- "version": "0.60.38.0",+ "version": "0.60.39.0","overrides": {"@ai-sdk/provider-utils": "4.0.56","@hono/node-server": "^2.0.5",diff --git a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json b/plugin-variants/gbrain-coding/.claude-plugin/plugin.jsonindex ccac395ad3..36359010d3 100644--- a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-coding",- "version": "0.60.38.0",+ "version": "0.60.39.0","description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json b/plugin-variants/gbrain-coding/.codex-plugin/plugin.jsonindex 78f43e1338..cf1986e3e1 100644--- a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-coding",- "version": "0.60.38.0",+ "version": "0.60.39.0","description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-coding/README.md b/plugin-variants/gbrain-coding/README.mdindex 4df2184dfe..530c3ce2ef 100644--- a/plugin-variants/gbrain-coding/README.md+++ b/plugin-variants/gbrain-coding/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.60.38.0 -->+<!-- gbrain-plugin-tree-stamp: 0.60.39.0 --># gbrain-coding (generated persona variant — do not hand-edit)Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant.diff --git a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.jsonindex b07cbb6b7c..f009608193 100644--- a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-daily",- "version": "0.60.38.0",+ "version": "0.60.39.0","description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json b/plugin-variants/gbrain-daily/.codex-plugin/plugin.jsonindex 328fe99fc2..a1eef469c4 100644--- a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-daily",- "version": "0.60.38.0",+ "version": "0.60.39.0","description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-daily/README.md b/plugin-variants/gbrain-daily/README.mdindex b5336ae6c6..55012e5927 100644--- a/plugin-variants/gbrain-daily/README.md+++ b/plugin-variants/gbrain-daily/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.60.38.0 -->+<!-- gbrain-plugin-tree-stamp: 0.60.39.0 --># gbrain-daily (generated persona variant — do not hand-edit)Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant.diff --git a/plugin/README.md b/plugin/README.mdindex d4e6aa3fa7..09356a4da4 100644--- a/plugin/README.md+++ b/plugin/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.60.38.0 -->+<!-- gbrain-plugin-tree-stamp: 0.60.39.0 --># gbrain plugin skill tree (generated — do not hand-edit)This tree is the curated skill set for the gbrain Codex and Claude Codediff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.tsindex 4b1515d14c..076ed36392 100644--- a/scripts/e2e-test-map.ts+++ b/scripts/e2e-test-map.ts@@ -505,6 +505,7 @@ export const E2E_TEST_MAP: Record<string, string[]> = {"src/core/schema-migrations/v188-facts-ontology-stint-dedup.ts": ["test/e2e/ontology-merge-parity.test.ts", "test/e2e/schema-drift.test.ts"],"src/core/persistence/memory-mutations.ts": ["test/e2e/withdrawal-followup-writes-postgres.test.ts"],"src/core/persistence/coordinator.ts": ["test/e2e/withdrawal-followup-writes-postgres.test.ts"],+ "src/core/repair/failed-writes.ts": ["test/e2e/repair-failed-writes-5983-postgres.test.ts"],"src/core/persistence/writer-guard-schema.ts": ["test/e2e/managed-writer-guard-null-source-5983-postgres.test.ts", "test/e2e/schema-drift.test.ts", "test/e2e/schema-catalog-golden.test.ts"],"src/core/schema-migrations/v197-managed-guard-null-source-fallback.ts": ["test/e2e/managed-writer-guard-null-source-5983-postgres.test.ts", "test/e2e/schema-drift.test.ts", "test/e2e/schema-catalog-golden.test.ts"],"src/core/facts/meta-hook.ts": ["test/e2e/capture-dedup-postgres.test.ts", "test/e2e/hot-memory-invalidation-postgres.test.ts", "test/e2e/facts-context-injection-postgres.test.ts", "test/e2e/serve-http-meta.test.ts"],diff --git a/src/core/persistence/preview-approval.ts b/src/core/persistence/preview-approval.tsindex 8a7a6da7aa..dab2eeb8a7 100644--- a/src/core/persistence/preview-approval.ts+++ b/src/core/persistence/preview-approval.ts@@ -40,7 +40,7 @@ export const PREVIEW_APPROVAL_OP = 'repair-approval';/** The default `purgeStaleCheckpoints` TTL; an older approved set may already be gone. */export const APPROVAL_MAX_AGE_DAYS = 7;-export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'extractor-facts' | 'captured-facts' | 'loop-facts';+export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'extractor-facts' | 'captured-facts' | 'loop-facts' | 'failed-writes';export interface ApprovedSetKey {command: PreviewApprovalCommand;diff --git a/src/core/repair/core.ts b/src/core/repair/core.tsindex 3899903b48..8020cd65c9 100644--- a/src/core/repair/core.ts+++ b/src/core/repair/core.ts@@ -23,7 +23,7 @@ import { getWriteRequest } from '../persistence/journal.ts';import { initializeLocalPersistence, requestPrincipalForContext } from '../persistence/page-mutations.ts';import { lookupEmbeddingPrice, estimateCostFromChars } from '../embedding-pricing.ts';-export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'captured-facts', 'loop-facts', 'orphan-children'] as const;+export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'captured-facts', 'loop-facts', 'orphan-children', 'failed-writes'] as const;export type RepairKind = typeof REPAIR_KINDS[number];export interface RepairScope { brain_id: string; source_ids: string[] }diff --git a/src/core/repair/failed-writes.ts b/src/core/repair/failed-writes.tsnew file mode 100644index 0000000000..cb0b6eae11--- /dev/null+++ b/src/core/repair/failed-writes.ts@@ -0,0 +1,257 @@+/**+ * `gbrain repair failed-writes` (#5983): resubmits caller writes that the+ * managed writer guard refused while it misread page children's source+ * (`writer_coordinator_required`, stored before #5982 as `storage_error`+ * "Publication failed (P0001)"). The failed receipt keeps its full intent until+ * receipt compaction (`persistence.receipt_retention_days`), so the write can+ * be submitted again once the guard is fixed.+ *+ * Only writes a caller made directly are replayed: `put_page` without an+ * owner-internal `kind`, `add_timeline_entry` and `remember`. Writes an owner+ * process produced (sync and file imports, reconcile, relink, maintenance+ * pages, jobs) are counted as residuals with the command that produces them+ * again, because re-running the producer uses current content.+ *+ * A candidate is kept, never replayed, when:+ * - `already_written`: a later committed request carries the same intent, or+ * an earlier apply's replay committed;+ * - `duplicate`: a later failed or pending request carries the same intent+ * (that one is the candidate);+ * - `superseded`: a later request wrote or deleted the page (committed or+ * still pending; for `put_page`, also a later failed `put_page`, which is+ * the newer content), or the page changed after the revision the caller+ * read;+ * - `unpinned_target`: a `remember` whose original target was inferred as+ * unattributed; replaying would infer again and could pick another page.+ *+ * Explicit-only and preview-bound: the preview lists every candidate with its+ * class and saves the replay set, with each target page's revision, under its+ * hash; `--apply --expect <hash>` replays exactly that set. Each item is+ * reclassified (`changed_since_preview`) and its original authority re-checked+ * (`authority_revoked`), then submitted through the operation's normal path on+ * the original trust lane (a remote caller's write is prepared as a remote+ * write, with its take-holder and delegated-namespace limits), bound to the+ * previewed page revision (`force` is dropped), under a request id derived+ * from the failed request id. The failed receipt stays as history.+ */+import { OperationError } from '../ops/contract.ts';+import type { OperationContext } from '../ops/contract.ts';+import type { BrainEngine } from '../engine.ts';+import { digest } from '../persistence/digest.ts';+import { isTerminal, principalKey, type WriteAuthority, type WriteRequest } from '../persistence/model.ts';+import { authorizeStoredRequest } from '../persistence/authority.ts';+import { initializeLocalPersistence, requestPrincipalForContext, submitPageMutation } from '../persistence/page-mutations.ts';+import { submitRememberMutation } from '../persistence/memory-mutations.ts';+import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';+import { resolveEntitySlugWithSource } from '../entities/resolve.ts';+import { afterCursor, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairScope } from './core.ts';++const REPLAYABLE = ['put_page', 'add_timeline_entry', 'remember'];+const REMEMBER_PREPARED_KEYS = ['entity_slug', 'fence', 'valid_from', 'valid_until', 'entity_inferred', 'entity_warning'];+const REMOTE_PREPARED_KEYS = ['source_kind', 'source_uri', 'ingested_via'];+const PAGE_REMOVALS = ['delete_page', 'purge_page'];+const GUARD_REFUSAL = `(r.error_code='writer_coordinator_required'+ OR (r.error_code='storage_error' AND r.error_message LIKE 'Publication failed (P0001)%'))`;++interface FailedWrite {+ id: string; sequence: string; operation: string; source_id: string; slug: string; digest: string;+ intent: Record<string, unknown>; authority: WriteAuthority; created_at: string; producer: string | null;+}+type Disposition = 'replay' | 'already_written' | 'duplicate' | 'superseded' | 'unpinned_target';+/** A replay bound to the page revision the preview saw (null: no live page). */+interface ApprovedWrite extends FailedWrite { revision: string | null; selection: string[] }+interface FailedWriteItem extends RepairItem { failed: ApprovedWrite; hash: string; last: boolean }++function previewCommand(scope: RepairScope): string {+ return `gbrain repair failed-writes${scope.source_ids.length === 1 ? ` --source ${scope.source_ids[0]}` : ''}`;+}++/** The command that produces an owner-internal write again, from current content. */+function producerCommand(producer: string, sourceId: string): string {+ const parts = producer.split(':');+ if (parts.some(part => part.startsWith('managed_sync') || part === 'managed_file_import')) return `gbrain sync --source ${sourceId} --no-pull --retry-failed --json`;+ if (parts.includes('canonical_reconcile')) return `gbrain sources reconcile ${sourceId} --audit`;+ if (parts.includes('relink_facts')) return `gbrain facts relink --source ${sourceId} --dry-run`;+ if (parts.some(part => part.includes('facts'))) return `gbrain extract --stale --source-id ${sourceId} --json`;+ return 'the next `gbrain dream` cycle (or autopilot) produces it again';+}++async function failedWrites(engine: BrainEngine, sourceIds: string[], id?: string): Promise<FailedWrite[]> {+ return engine.executeRaw<FailedWrite>(`SELECT r.id::text, r.sequence::text, r.operation, r.source_id, r.slug, r.digest, r.intent, r.authority,+ to_char(r.created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"') AS created_at,+ CASE WHEN r.operation = ANY($2::text[]) AND NOT (r.operation='put_page' AND r.intent ? 'kind') THEN NULL+ ELSE r.operation || COALESCE(':' || (r.intent->>'kind'), '') END AS producer+ FROM persistence_requests r+ WHERE r.source_id = ANY($1::text[]) AND r.state='failed' AND NOT r.compacted AND r.intent IS NOT NULL AND ${GUARD_REFUSAL}+ ${id ? 'AND r.id=$3::uuid' : ''}+ ORDER BY r.sequence`, id ? [sourceIds, REPLAYABLE, id] : [sourceIds, REPLAYABLE]);+}++async function pageRevision(engine: BrainEngine, sourceId: string, slug: string): Promise<string | null> {+ const [page] = await engine.executeRaw<{ revision: string | null }>(+ 'SELECT knowledge_revision::text AS revision FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [sourceId, slug]);+ return page?.revision ?? null;+}++function replayId(failedId: string, attempt: number): string {+ const h = digest(['failed-writes-replay-v1', failedId, attempt]);+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-a${h.slice(17, 20)}-${h.slice(20, 32)}`;+}++/**+ * The replay's request id: one per failed request and attempt, so a rerun after+ * a crash resumes the same admission and a terminal failure gets a new id.+ * `prior` is that attempt's request when it was already admitted.+ */+async function replayAttempt(engine: BrainEngine, failedId: string): Promise<{ id: string; prior: WriteRequest | null }> {+ for (let attempt = 0; ; attempt++) {+ const id = replayId(failedId, attempt);+ const [prior] = await engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE request_id=$1::uuid', [id]);+ if (!prior || prior.state === 'committed' || !isTerminal(prior)) return { id, prior: prior ?? null };+ }+}++/** Why a caller write must not be replayed now, or `replay`. */+async function disposition(engine: BrainEngine, write: FailedWrite): Promise<{ class: Disposition; detail?: string }> {+ if ((await replayAttempt(engine, write.id)).prior?.state === 'committed') return { class: 'already_written', detail: 'replayed by gbrain repair failed-writes' };+ const replace = write.operation === 'put_page';+ const [later] = await engine.executeRaw<{ state: string; operation: string; same_intent: boolean }>(+ `SELECT state, operation, digest=$3 AS same_intent FROM persistence_requests+ WHERE source_id=$1 AND slug=$2 AND sequence > $4::bigint AND (+ (digest=$3 AND state IN ('committed','failed','queued','running','recovering'))+ OR (state IN ('committed','queued','running','recovering') AND (operation = ANY($6::text[]) OR $5::boolean))+ OR ($5::boolean AND state='failed' AND operation='put_page' AND NOT (intent ? 'kind')))+ ORDER BY (digest=$3 AND state='committed') DESC, (digest=$3) DESC, sequence LIMIT 1`,+ [write.source_id, write.slug, write.digest, write.sequence, replace, PAGE_REMOVALS]);+ if (later?.same_intent && later.state === 'committed') return { class: 'already_written' };+ if (later?.same_intent) return { class: 'duplicate', detail: `a later request with the same intent is ${later.state}` };+ if (later) return { class: 'superseded', detail: `a later ${later.operation} of this page is ${later.state}` };+ const read = write.intent.expected_revision;+ if (replace && typeof read === 'string' && read !== await pageRevision(engine, write.source_id, write.slug)) {+ return { class: 'superseded', detail: 'the page changed after the revision the caller read' };+ }+ if (write.operation === 'remember' && typeof write.intent.entity_slug !== 'string') {+ return { class: 'unpinned_target', detail: 'the fact was saved unattributed; replaying would infer its subject again' };+ }+ return { class: 'replay' };+}++function item(write: ApprovedWrite, hash: string, last: boolean): FailedWriteItem {+ return { cursor: { phase: 1, id: Number(write.sequence) }, source_id: write.source_id, slug: write.slug,+ chars: typeof write.intent.content === 'string' ? write.intent.content.length : 0, action: `replay:${write.operation}`, failed: write, hash, last };+}++export const failedWritesRepair: RepairHandler = {+ kind: 'failed-writes',+ embeds: false,+ async plan(engine, scope, after, opts): Promise<RepairPlan> {+ const command = previewCommand(scope);+ if (!opts?.apply) {+ const rows = await failedWrites(engine, scope.source_ids);+ const residuals: Record<string, number> = {};+ const listing: NonNullable<RepairPlan['listing']> = [];+ const producers = new Map<string, string>();+ const replay: ApprovedWrite[] = [];+ for (const write of rows) {+ const label = `${write.source_id}:${write.slug} ${write.operation} (failed ${write.created_at}, request ${write.id})`;+ if (write.producer) {+ residuals[`producer_owned:${write.producer}`] = (residuals[`producer_owned:${write.producer}`] ?? 0) + 1;+ producers.set(`${write.producer} in ${write.source_id}`, producerCommand(write.producer, write.source_id));+ listing.push({ item: label, class: 'producer_owned', detail: `re-run: ${producerCommand(write.producer, write.source_id)}` });+ continue;+ }+ const verdict = await disposition(engine, write);+ if (verdict.class === 'replay') replay.push({ ...write, revision: await pageRevision(engine, write.source_id, write.slug), selection: scope.source_ids });+ else residuals[verdict.class] = (residuals[verdict.class] ?? 0) + 1;+ listing.push({ item: label, class: verdict.class, ...(verdict.detail ? { detail: verdict.detail } : {}) });+ }+ const sources = await engine.executeRaw<{ id: string; incarnation: string }>(+ 'SELECT id, incarnation::text AS incarnation FROM sources WHERE id=ANY($1::text[]) ORDER BY id', [scope.source_ids]);+ const hash = previewHash({ kind: 'failed-writes-v1', brain_id: scope.brain_id, sources, selection: { source_ids: scope.source_ids },+ replay: replay.map(write => ({ id: write.id, digest: write.digest, revision: write.revision })) });+ if (replay.length) await saveApprovedSet<ApprovedWrite>(engine, { command: 'failed-writes', hash }, replay);+ return { items: replay.map((write, index) => item(write, hash, index === replay.length - 1)), preview_hash: hash, residuals, listing,+ warnings: [...producers].map(([what, run]) => `${what}: produced by gbrain itself, not replayed here; ${run}`) };+ }+ if (!opts.expect) {+ throw new OperationError('invalid_params', 'gbrain repair failed-writes --apply replays only the set a preview printed.',+ `Preview first: ${command} — show the user the listing, then run the apply command it prints: ${command} --apply --expect <preview-hash>`,+ 'docs/guides/repair.md#failed-writes');+ }+ const approved = await loadApprovedSet<ApprovedWrite>(engine, { command: 'failed-writes', hash: opts.expect, previewCommand: command });+ if (approved.items.some(write => JSON.stringify(write.selection) !== JSON.stringify(scope.source_ids))) throw previewChangedError(opts.expect, command);+ const items = approved.items.map((write, index) => item(write, opts.expect!, index === approved.items.length - 1));+ return { items: items.filter(entry => afterCursor(entry.cursor, after)), preview_hash: opts.expect, residuals: {} };+ },+ async apply(ctx, entry): Promise<RepairItemOutcome> {+ const { failed, hash, last } = entry as FailedWriteItem;+ const outcome = await replay(ctx, failed);+ if (last) await clearApprovedSet(ctx.engine, { command: 'failed-writes', hash });+ return outcome;+ },+};++/** The original caller's trust lane: a remote caller's write is prepared as a remote write, within its holder and namespace limits. */+function laneContext(ctx: OperationContext, authority: WriteAuthority): OperationContext {+ if (!authority.remote) return { ...ctx, remote: false };+ return { ...ctx, remote: true, takesHoldersAllowList: authority.takesHolders ? [...authority.takesHolders] : ['world'],+ ...(authority.restrictedNamespace ? { viaSubagent: true, allowedSlugPrefixes: [...(authority.delegatedPrefixes ?? [])] } : {}) };+}++/** The caller's params, without what preparation added, bound to the previewed page revision. */+async function replayParams(ctx: OperationContext, write: ApprovedWrite, requestId: string): Promise<{ params: Record<string, unknown> } | { refused: RepairItemOutcome }> {+ const params: Record<string, unknown> = { ...write.intent, request_id: requestId };+ if (write.authority.remote) for (const key of REMOTE_PREPARED_KEYS) delete params[key];+ if (write.operation === 'remember') {+ const target = String(write.intent.entity_slug);+ for (const key of REMEMBER_PREPARED_KEYS) delete params[key];+ if ((await resolveEntitySlugWithSource(ctx.engine, write.source_id, target))?.slug !== target) {+ return { refused: { applied: false, outcome: 'changed_since_preview', reason: `the fact's subject ${target} no longer resolves to itself` } };+ }+ params.entity = target;+ return { params };+ }+ if (write.operation === 'put_page') {+ delete params.force;+ delete params.expected_revision;+ if (write.revision) params.expected_revision = write.revision;+ }+ return { params };+}++async function replay(ctx: OperationContext, failed: ApprovedWrite): Promise<RepairItemOutcome> {+ const [live] = await failedWrites(ctx.engine, [failed.source_id], failed.id);+ if (!live || live.digest !== failed.digest) return { applied: false, outcome: 'changed_since_preview', reason: 'the failed request was compacted or changed' };+ const lane = laneContext(ctx, live.authority);+ await initializeLocalPersistence(lane);+ const attempt = await replayAttempt(ctx.engine, failed.id);+ if (attempt.prior?.state === 'committed') return { applied: false, outcome: 'already_written' };+ if (attempt.prior && principalKey({ kind: attempt.prior.principal_kind, id: attempt.prior.principal_id }) !== principalKey(await requestPrincipalForContext(lane))) {+ return { applied: false, outcome: 'pending_elsewhere', reason: `replay request ${attempt.id} is ${attempt.prior.state} under another writer` };+ }+ if (!attempt.prior) {+ const verdict = await disposition(ctx.engine, live);+ if (verdict.class !== 'replay') return { applied: false, outcome: 'changed_since_preview', reason: verdict.detail ?? verdict.class };+ if (live.operation === 'put_page' && await pageRevision(ctx.engine, failed.source_id, failed.slug) !== failed.revision) {+ return { applied: false, outcome: 'changed_since_preview', reason: 'the page changed since the preview' };+ }+ }+ const [stored] = await ctx.engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE id=$1::uuid', [failed.id]);+ try { await authorizeStoredRequest(ctx.engine, stored); } catch (error) {+ if (error instanceof OperationError) return { applied: false, outcome: 'authority_revoked', reason: `${error.code}: ${error.message}` };+ throw error;+ }+ const prepared = await replayParams(lane, failed, attempt.id);+ if ('refused' in prepared) return prepared.refused;+ const { params } = prepared;+ try {+ if (live.operation === 'remember') await submitRememberMutation(lane, params);+ else await submitPageMutation(lane, { operation: live.operation, params });+ } catch (error) {+ if (error instanceof OperationError && !['write_pending', 'owner_unavailable', 'writer_lock_unavailable', 'writer_busy'].includes(error.code)) {+ return { applied: false, outcome: ['revision_conflict', 'revision_required'].includes(error.code) ? 'conflict' : 'refused', reason: `${error.code}: ${error.message}` };+ }+ throw error;+ }+ return { applied: true, outcome: 'replayed' };+}diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.tsindex acbdfd95e8..288d8aa1da 100644--- a/src/core/repair/registry.ts+++ b/src/core/repair/registry.ts@@ -37,6 +37,7 @@ import { extractorFactsRepair } from './extractor-facts.ts';import { capturedFactsRepair } from './captured-facts.ts';import { loopFactsRepair } from './loop-facts.ts';import { orphanChildrenRepair } from './orphan-children.ts';+import { failedWritesRepair } from './failed-writes.ts';import { attributionBackfillRepair } from './attribution-backfill.ts';import { plannerStatsRepair } from './planner-stats.ts';import { ERROR_CATALOGUE, catalogueError } from '../error-catalogue.ts';@@ -147,6 +148,14 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {+ 'links.origin_page_id and files.page_id references (#5216, #4738). The preview also probes every page body and reports torn TOAST rows '+ '(SQLSTATE XX000) as torn_pages without changing them. Bookkeeping only; no journal admission. Brain-wide; runs only when named.',},+ 'failed-writes': {+ handler: failedWritesRepair, embeds: 'effect', checks: [], explicit_only: true,+ summary: 'Resubmit caller writes (put_page, add_timeline_entry, remember) that the managed writer guard refused before v0.60.38.0 (#5983), from the '+ + 'intent their failed receipt retains until receipt compaction. A write is kept when a later request with the same intent committed (already_written) '+ + 'or is pending (duplicate), or a later write or delete of the page committed (superseded). Writes gbrain itself produced (sync and file imports, '+ + 'reconcile, relink, maintenance) are counted with the command that produces them again. Preview-bound: --apply --expect <hash> replays exactly '+ + 'the previewed set under new request ids, after re-checking each write\'s original authority; the failed receipts stay as history.',+ },'planner-stats': {handler: plannerStatsRepair, embeds: 'none', checks: ['planner_stats_stale'],summary: 'ANALYZE the hot tables (pages, links, facts, takes, content_chunks, timeline_entries) whose planner statistics are stale (F4b), 'diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.mdindex 1c5ec6eab1..e05410d5b3 100644--- a/templates/bootstrap/template-repo/README.md+++ b/templates/bootstrap/template-repo/README.md@@ -1,6 +1,6 @@# gbrain agent workspace — template-<!-- gbrain-template-stamp: 0.60.38.0 -->+<!-- gbrain-template-stamp: 0.60.39.0 -->This repository is the **"Use this template"** distribution artifact for a[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the samediff --git a/test/e2e/repair-failed-writes-5983-postgres.test.ts b/test/e2e/repair-failed-writes-5983-postgres.test.tsnew file mode 100644index 0000000000..068bb057fa--- /dev/null+++ b/test/e2e/repair-failed-writes-5983-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../repair-failed-writes-5983.test.ts'));diff --git a/test/helpers/pre-5983-guard.ts b/test/helpers/pre-5983-guard.tsnew file mode 100644index 0000000000..3fe65eb6f5--- /dev/null+++ b/test/helpers/pre-5983-guard.ts@@ -0,0 +1,17 @@+import type { BrainEngine } from '../../src/core/engine.ts';++/** gbrain_require_managed_writer() source lookup as shipped through 0.60.37.0 (schema v196): source_id read whenever the key exists. */+const PRE_5983_SOURCE_LOOKUP = `IF row_data ? 'source_id' THEN target_source := row_data->>'source_id';+ ELSE SELECT source_id INTO target_source FROM pages WHERE id=(row_data->>'page_id')::integer; END IF;+ IF TG_OP='UPDATE' THEN+ IF old_data ? 'source_id' THEN old_source := old_data->>'source_id';+ ELSE SELECT source_id INTO old_source FROM pages WHERE id=(old_data->>'page_id')::integer; END IF;+ END IF;`;++/** Re-installs the pre-#5983 guard function in place of the current one. */+export async function installPre5983Guard(engine: BrainEngine): Promise<void> {+ const [{ src }] = await engine.executeRaw<{ src: string }>(`SELECT pg_get_functiondef('gbrain_require_managed_writer'::regproc) AS src`);+ const current = src.slice(src.indexOf("IF TG_TABLE_NAME NOT IN ('tags','timeline_entries','takes')"), src.indexOf('-- Cascaded projection removal'));+ if (!current) throw new Error('installPre5983Guard: the current guard function has an unexpected shape');+ await engine.executeRaw(src.replace(current, `${PRE_5983_SOURCE_LOOKUP}\n `));+}diff --git a/test/managed-writer-guard-null-source-5983.test.ts b/test/managed-writer-guard-null-source-5983.test.tsindex 8b5c103033..7b6d819a8d 100644--- a/test/managed-writer-guard-null-source-5983.test.ts+++ b/test/managed-writer-guard-null-source-5983.test.ts@@ -26,6 +26,7 @@ import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';import { withEnv } from './helpers/with-env.ts';import { testBackends } from './helpers/test-backends.ts';+import { installPre5983Guard } from './helpers/pre-5983-guard.ts';const backends = testBackends();const engines: BrainEngine[] = [];@@ -184,22 +185,10 @@ test('a managed put_page of a tagged page with timeline lines commits on a brain}}, 120_000);-/** gbrain_require_managed_writer() as shipped through 0.60.37.0 (schema v196): source_id read whenever the key exists. */-const PRE_5983_SOURCE_LOOKUP = `IF row_data ? 'source_id' THEN target_source := row_data->>'source_id';- ELSE SELECT source_id INTO target_source FROM pages WHERE id=(row_data->>'page_id')::integer; END IF;- IF TG_OP='UPDATE' THEN- IF old_data ? 'source_id' THEN old_source := old_data->>'source_id';- ELSE SELECT source_id INTO old_source FROM pages WHERE id=(old_data->>'page_id')::integer; END IF;- END IF;`;-test('upgrading a v196 brain with the pre-fix guard: v197 unblocks the refused write and is idempotent', async () => {const v197 = MIGRATIONS.find(migration => migration.version === 197)!;for (const engine of engines) {- const [{ src }] = await engine.executeRaw<{ src: string }>(- `SELECT pg_get_functiondef('gbrain_require_managed_writer'::regproc) AS src`);- const current = src.slice(src.indexOf("IF TG_TABLE_NAME NOT IN ('tags','timeline_entries','takes')"), src.indexOf('-- Cascaded projection removal'));- expect(current.length).toBeGreaterThan(0);- await engine.executeRaw(src.replace(current, `${PRE_5983_SOURCE_LOOKUP}\n `));+ await installPre5983Guard(engine);const pageId = await pageIn(engine, 'default');await expect(guarded(engine, ['default'], INSERTS.tags, [pageId])).rejects.toThrow(REFUSED);const triggers = `SELECT tgrelid::regclass::text AS tbl, oid FROM pg_trigger WHERE tgname='managed_writer_guard' ORDER BY 1`;diff --git a/test/repair-explicit-only.test.ts b/test/repair-explicit-only.test.tsindex aabbdca902..fdc46f7cc2 100644--- a/test/repair-explicit-only.test.ts+++ b/test/repair-explicit-only.test.ts@@ -24,7 +24,7 @@ import { REPAIR_HELP, parseRepairArgs, runRepairCommand } from '../src/commands/import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';import { withEnv } from './helpers/with-env.ts';-const EXPLICIT: RepairKind[] = ['google-file-modes', 'stale-atoms', 'extractor-facts', 'captured-facts', 'loop-facts', 'orphan-children'];+const EXPLICIT: RepairKind[] = ['google-file-modes', 'stale-atoms', 'extractor-facts', 'captured-facts', 'loop-facts', 'orphan-children', 'failed-writes'];let engine: PGLiteEngine;const home = mkdtempSync(join(tmpdir(), 'gbrain-repair-explicit-'));diff --git a/test/repair-failed-writes-5983.test.ts b/test/repair-failed-writes-5983.test.tsnew file mode 100644index 0000000000..d601488bec--- /dev/null+++ b/test/repair-failed-writes-5983.test.ts@@ -0,0 +1,139 @@+/**+ * `gbrain repair failed-writes` (#5983): caller writes the pre-fix managed+ * writer guard refused are replayed from their failed receipts' intent once+ * the guard is fixed, exactly once, and never over a later write of the page.+ * Runs on PGLite and, through test/e2e, Postgres.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import type { OperationContext } from '../src/core/operations.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { submitRememberMutation } from '../src/core/persistence/memory-mutations.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { MANAGED_WRITER_GUARD_FUNCTION_SQL } from '../src/core/persistence/writer-guard-schema.ts';+import { repairRunner } from '../src/core/repair/registry.ts';+import { resolveRepairScope } from '../src/core/repair/core.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { withEnv } from './helpers/with-env.ts';+import { testBackends } from './helpers/test-backends.ts';+import { installPre5983Guard } from './helpers/pre-5983-guard.ts';++const backends = testBackends();+const engines: BrainEngine[] = [];+const dataDir = mkdtempSync(join(tmpdir(), 'gbrain-replay-5983-db-'));+let closePostgres: (() => Promise<void>) | undefined;+const logger = { info() {}, warn() {}, error() {} };++beforeAll(async () => {+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });+ if (backends.includes('pglite')) {+ const engine = new PGLiteEngine();+ await engine.connect({ database_path: dataDir }); await engine.initSchema(); engines.push(engine);+ }+ if (backends.includes('postgres')) {+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ engines.push(pg.engine); closePostgres = pg.close;+ }+ for (const engine of engines) {+ for (const table of ['tags', 'timeline_entries', 'takes']) await engine.executeRaw(`ALTER TABLE ${table} ADD COLUMN IF NOT EXISTS source_id TEXT`);+ }+}, 120_000);+afterAll(async () => {+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }+ await closePostgres?.(); resetGateway(); rmSync(dataDir, { recursive: true, force: true });+});++const ctxFor = (engine: BrainEngine, sourceId: string) =>+ ({ engine, sourceId, remote: false, config: { engine: engine.kind, embedding_disabled: true } as never, dryRun: false, logger }) as OperationContext;+const page = (title: string, tags: string[], body: string) => `---\ntitle: ${title}\ntype: person\ntags: [${tags.join(', ')}]\n---\n${body}`;++async function attempt(engine: BrainEngine, sourceId: string, operation: string, params: Record<string, unknown>, remote = false) {+ const ctx = { ...ctxFor(engine, sourceId), remote };+ const submit = operation === 'remember' ? submitRememberMutation(ctx, { ...params, request_id: randomUUID() })+ : submitPageMutation(ctx, { operation, params: { ...params, request_id: randomUUID() } });+ await submit.catch(() => undefined);+}++test('refused caller writes replay once from their failed receipts; later writes of the page are never overwritten', async () => {+ for (const engine of engines) {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-replay-5983-'));+ const root = join(dir, 'brain'); mkdirSync(root);+ const sourceId = `r5983-${randomUUID().slice(0, 8)}`;+ try {+ await withEnv({ GBRAIN_HOME: join(dir, 'home') }, async () => {+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);+ await engine.setConfig('sync.write_through', 'true');+ await claimWorktree(engine, sourceId, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const ctx = ctxFor(engine, sourceId);+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug: 'people/bob-example', content: page('Bob Example', [], 'Bob.'), request_id: randomUUID() } });+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug: 'people/dana-example', content: page('Dana Example', ['v0'], 'Dana v0.'), request_id: randomUUID() } });++ await installPre5983Guard(engine);+ await attempt(engine, sourceId, 'put_page', { slug: 'people/alice-example', content: page('Alice Example', ['founder'], 'Alice builds things.') });+ await attempt(engine, sourceId, 'put_page', { slug: 'people/carol-example', content: page('Carol Example', ['old'], 'Old Carol.') });+ await attempt(engine, sourceId, 'add_timeline_entry', { slug: 'people/bob-example', date: '2026-09-30', summary: 'Met at demo day' });+ await attempt(engine, sourceId, 'add_timeline_entry', { slug: 'people/bob-example', date: '2026-09-30', summary: 'Met at demo day' });+ await attempt(engine, sourceId, 'put_page', { slug: 'people/dana-example', content: page('Dana Example', ['v1'], 'Dana v1.'), force: true });+ await attempt(engine, sourceId, 'put_page', { slug: 'people/dana-example', content: page('Dana Example', ['v2'], 'Dana v2.'), force: true });+ await attempt(engine, sourceId, 'add_timeline_entry', { slug: 'people/dana-example', date: '2026-10-01', summary: 'Remote note' }, true);+ const refused = await engine.executeRaw<{ operation: string; n: number }>(+ `SELECT operation, count(*)::int AS n FROM persistence_requests WHERE source_id=$1 AND state='failed' AND error_message LIKE 'Publication failed (P0001)%' GROUP BY 1 ORDER BY 1`, [sourceId]);+ expect(refused).toEqual([{ operation: 'add_timeline_entry', n: 3 }, { operation: 'put_page', n: 4 }]);++ await engine.executeRaw(MANAGED_WRITER_GUARD_FUNCTION_SQL);+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug: 'people/carol-example', content: page('Carol Example', ['new'], 'New Carol.'), request_id: randomUUID() } });++ const scope = await resolveRepairScope(engine, sourceId);+ const preview = await (await repairRunner(engine, { apply: false, logger })).run('failed-writes', scope, { explicit: true, sourceFlag: sourceId });+ expect((preview.listing ?? []).map(entry => `${entry.item.split(' ').slice(0, 2).join(' ')} ${entry.class}`)).toEqual([+ `${sourceId}:people/alice-example put_page replay`,+ `${sourceId}:people/carol-example put_page superseded`,+ `${sourceId}:people/bob-example add_timeline_entry duplicate`,+ `${sourceId}:people/bob-example add_timeline_entry replay`,+ `${sourceId}:people/dana-example put_page superseded`,+ `${sourceId}:people/dana-example put_page replay`,+ `${sourceId}:people/dana-example add_timeline_entry replay`,+ ]);+ expect(preview.residuals).toEqual({ superseded: 2, duplicate: 1 });+ expect(preview.apply_command).toMatch(new RegExp(`^gbrain repair failed-writes --source ${sourceId} --apply --expect [0-9a-f]+$`));++ await expect((await repairRunner(engine, { apply: true, logger })).run('failed-writes', scope, { explicit: true, sourceFlag: sourceId }))+ .rejects.toThrow(/replays only the set a preview printed/);+ const applied = await (await repairRunner(engine, { apply: true, logger })).run('failed-writes', scope,+ { explicit: true, sourceFlag: sourceId, expect: preview.apply_command.split('--expect ')[1] });+ expect(applied.outcomes).toEqual({ replayed: 4 });++ expect((await engine.getTags('people/alice-example', { sourceId }))).toEqual(['founder']);+ expect((await engine.getTags('people/carol-example', { sourceId }))).toEqual(['new']);+ expect((await engine.getTimeline('people/bob-example', { sourceId })).map(entry => entry.summary)).toEqual(['Met at demo day']);+ expect((await engine.getPage('people/dana-example', { sourceId }))?.compiled_truth).toContain('Dana v2.');+ expect(await engine.getTags('people/dana-example', { sourceId })).toContain('v2');+ expect(await engine.getTags('people/dana-example', { sourceId })).not.toContain('v1');+ expect((await engine.getTimeline('people/dana-example', { sourceId })).map(entry => entry.summary)).toEqual(['Remote note']);+ const replays = await engine.executeRaw<{ operation: string; principal_kind: string; remote: boolean }>(+ `SELECT operation, principal_kind, (authority->>'remote')::boolean AS remote FROM persistence_requests+ WHERE source_id=$1 AND slug='people/dana-example' AND state='committed' AND operation='add_timeline_entry'`, [sourceId]);+ expect(replays).toEqual([{ operation: 'add_timeline_entry', principal_kind: 'local_stdio', remote: true }]);+ expect((await engine.executeRaw<{ n: number }>(+ `SELECT count(*)::int AS n FROM persistence_requests WHERE source_id=$1 AND state='failed'`, [sourceId]))[0].n).toBe(7);++ const again = await (await repairRunner(engine, { apply: false, logger })).run('failed-writes', scope, { explicit: true, sourceFlag: sourceId });+ expect(again.affected).toBe(0);+ expect(again.residuals).toEqual({ already_written: 5, superseded: 2 });+ });+ } finally {+ await disposePersistenceConsumer(engine);+ await engine.executeRaw(MANAGED_WRITER_GUARD_FUNCTION_SQL);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ rmSync(dir, { recursive: true, force: true });+ }+ }+}, 180_000);