Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(purge): a park another gbrain version wrote gets one automatic attempt

garrytana54d30c3e865
diff --git a/docs/architecture/key-files/commands-2-continued.md b/docs/architecture/key-files/commands-2-continued.md
index 2eb72a793b..889321eb4a 100644
--- a/docs/architecture/key-files/commands-2-continued.md
+++ b/docs/architecture/key-files/commands-2-continued.md
@@ -39,6 +39,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/doctor/checks/rename-identity-downgrades.ts` — `rename_identity_downgrades` (#6729): warn while a downgraded rename record is open (`sync-identity-downgrades.ts`), naming up to 5 pairs with their facts and links; fix = the first pair's `gbrain repair rename-identity` apply (destructive, `ask_user`, `preview_argv`, `plan_hash`; `--close` on a managed brain), so unbound classic Postgres pairs get an actionable fix too; `gbrain restore <old-slug> --source-id <id> --force` is named as the alternative in its text only where `restore_available !== false`, and `restore_unavailable_sources` lists the rest.
-- `src/commands/doctor/checks/purge-parks.ts` — `purge_parked_pages` (#6741 C): names parked purges with their last error; fix `gbrain pages purge-deleted --retry-parked --yes` (preview `--dry-run --json`), consent destructive, ask_user.
+- `src/commands/doctor/checks/purge-parks.ts` — `purge_parked_pages` (#6741 C): names parked purges with their last error (only parks the running version wrote, `isParked`; another version's is retried by the next purge); fix `gbrain pages purge-deleted --retry-parked --yes` (preview `--dry-run --json`), consent destructive, ask_user.
- `src/commands/doctor/checks/unlinked-facts.ts` — `unlinked_facts` (#5836), registered before `search_mode` and mirrored in `doctorReportRemote`: per the doctor's source scope (`--source`, else every source; the caller's grant remotely), the unlinked share of the newest 100,000 active facts per source (`idx_facts_since` LATERAL walk), the 7-day unlinked share of new facts, `no_subject` judgments and the 7-day `linked` tiers from `fact_relink_attempts`, fence-owned unlinked rows (row_num or source_markdown_slug set, conversation rows excluded), the conversation extractor's unlinked derived rows (`cli:extract-conversation-facts*`, #6764: count, origin `conversation`, and `details.conversation` naming the source with the most and its pages, most rows first, up to `CONVERSATION_FIX_SLUGS` = 50), origins (`conversation`, `mcp:put_page`, extraction, remember) and 7-day write-time inferred links by tier (`entity inferred from <tier>` context, bare or after ` — `). Warns when over 25% of at least 20 new facts are unlinked, facts judged `no_subject` and conversation rows memoized `conversation_unresolved` excluded (`new_7d.conversation_unresolved`); the fix is `gbrain facts relink --dry-run`; when conversation rows are unlinked the envelope `fix` (`details.conversation.fix`) is, for rows the free conversation relink has not tried, `gbrain facts relink --conversation --source <id> --slugs <csv>` (preview `--dry-run`, consent none, actor agent, host operator remotely; test `test/conversation-relink-6764.test.ts`) and, once only rows it memoized `conversation_unresolved` remain (a memo that a page created later re-arms unless the reason is memoized, `core/facts/conversation-memo.ts`), a bounded re-extraction of those pages not yet re-extracted on their current content (`gbrain extract-conversation-facts --source-id <id> --slugs <csv> --force --max-cost-usd <N>`, input `N` the approved USD, preview `--dry-run`, consent paid + egress, ask_user; test `test/conversation-facts-unlinked-6764.test.ts`), both verified by `gbrain doctor --only unlinked_facts --json`, because plain relink never examines derived rows; the remote report asks the brain host operator to run it. When only rows on pages already re-extracted on their current content remain, `details.conversation.fix` is `manual`: no envelope `fix`, and the message names linking by hand with `--entity` (test `test/conversation-memo-6764.test.ts`). Without `fact_relink_attempts` the relink figures are null and nothing is excluded. Tests: `test/doctor-unlinked-facts.test.ts`.
diff --git a/docs/architecture/key-files/memory-purge.md b/docs/architecture/key-files/memory-purge.md
index abbaa85577..7f7be855f7 100644
--- a/docs/architecture/key-files/memory-purge.md
+++ b/docs/architecture/key-files/memory-purge.md
@@ -26,6 +26,6 @@ User-facing contract: [expire versus purge](../../guides/memory-boundaries.md#pu
- `src/core/persistence/atom-retirement-hold.ts` — #7013: the one SQL rule for atoms `gbrain repair atoms-restore` restores. `atomRetirementsSql(scope)` is set-based (CTEs over `pages` joined on source and origin key, linear in the atoms in scope) and returns every non-imported atom soft-deleted with `retired_by: managed-reextract` with `origin_live` (a live page origin in its source, or a transcript), `replaced` (a live atom of the same origin carries another stripped source hash), `latest` (its hash is the hash of the origin's latest `managed-reextract` retirement) and `restorable` (all three right); `atomOriginScopeSql` narrows it to one atom's source and origin through the frontmatter GIN index for the apply recheck; `atomRetirementPurgeHold`, which keeps such an atom out of every batch purge selection (engine `purgeDeletedPages` preview and delete, the belief-ledger expiry, `selectPurgeCandidates`) for `ATOM_RESTORE_HOLD_DAYS` (30) after `deleted_at`, next to the #6729 `identityDowngradePurgeHold`. An explicit `delete --purge` is not held. Static strings only, so `engine-sql/pages.ts` imports it.
- `src/core/repair/atoms-restore.ts` — `gbrain repair atoms-restore` (#7013), explicit-only and preview-bound: lists atoms an empty managed re-extraction retired (`retired_by: managed-reextract`) that `atomRetirementsSql` (`persistence/atom-retirement-hold.ts`) marks `restorable`, each with origin, stripped source hash and `retired_at`, and residuals `restorable`, `origins`, `origin_gone`, `replaced`, `older_generation`; `--apply --expect <hash>` restores the approved set, rechecking each atom (id, incarnation, revision, origin, hash, `retired_at`, rule match) and reporting `changed_since_preview` otherwise. Managed: one `managed_maintenance_restore_reextract_atom` request per atom (`deleted_page: true`, bound to the deleted revision, request id in the outcome detail); `prepareAtomRestore` (dispatched from `prepared-maintenance.ts`) rechecks the rule under the atom and origin page locks and publishes a revision-bound `revert_version` to `version_id`, the newest live version of the atom at its source hash without `retired_by` (the one the coordinated delete archived; file written back, `allowMissingFile`); none is `no_version`, lowered to the `derive:atoms` tier of its origin with taint edges. Unmanaged: `createVersion`, `restorePage` and the two keys dropped in one `maintenanceTransaction`. Extraction state is not touched. Test: `test/pathological/h5-atoms-restore.test.ts`.
-- `src/core/persistence/purge-parks.ts` — #6741 C: per-tombstone purge parks in op_checkpoints (op `purge-deleted-park`, key source+slug+deleted_at, so a re-deleted page starts fresh); park at `PURGE_PARK_LIMIT` (5) non-deferral failures, a success clears it, and parks of a source seen inactive rearm the first run its writer is active again (`notePurgeSourceWriter`). `purgeStaleCheckpoints` exempts the op; `prunePurgeParks` drops parks whose tombstone is gone. Tests: `test/purge-deleted-parks.test.ts`.
+- `src/core/persistence/purge-parks.ts` — #6741 C: per-tombstone purge parks in op_checkpoints (op `purge-deleted-park`, key source+slug+deleted_at, so a re-deleted page starts fresh); park at `PURGE_PARK_LIMIT` (5) non-deferral failures, a success clears it, and parks of a source seen inactive rearm the first run its writer is active again (`notePurgeSourceWriter`). `purgeStaleCheckpoints` exempts the op; `prunePurgeParks` drops parks whose tombstone is gone. A park records the gbrain `version` of its last failure; `isParked` (the managed and unmanaged selection, doctor `purge_parked_pages`) counts only the running version's, so a park another version wrote (or one with no version) gets one automatic attempt and a failure re-parks it under the running version. Tests: `test/purge-deleted-parks.test.ts`, `test/purge-parks-version.test.ts` (Postgres: `test/e2e/purge-parks-version-postgres.test.ts`).
- `src/core/repair/segmented-mirror.ts` — `gbrain repair segmented-mirror` (LPH a), explicit-only, preview-bound, destructive consent, `checks: []` (no doctor scan: detection reads every segmented file). `scanSegmentedMirrors` (read-only, owner host; a non-owner source is held `not_owner_host`) walks live `body_storage='segmented'` pages of sources with a worktree binding whose snapshot ledger applies (`ledgerApplies`), runs `prepareFileTarget(..., null, { allowMissing })` (the mirror's own drift check; `file_database_drift` or any other `OperationError` is held, never rewritten), then lists the page only when overlaying the ledger on the file's facts fences changes its region digests (`fileBodyDigests` vs `overlaidFileBodyDigests` over `FileBytes`, bounded memory) and the streamed render (`unreadPageFile`) hashes differently. The hash (`segmented-mirror-v1`) binds source selection, slug, page id, revision, path and both SHA-256s; the approved set lives in `op_checkpoints`. Apply re-checks revision and file hash of every page not yet admitted (`preview_changed`), then per page admits and commits, in one transaction like a withdrawal, a `repair_segmented_mirror` request (request id derived from the hash; its receipt) that inserts a version-2 targeted `withdrawal-mirror` + `git` effect (no embedding) whose `data.approved_file` carries the preview's file and render SHA-256 (`mirrorPage` skips the target `preview_changed` when the file's before-hash or the streamed render differs, before the gate or any recovery record; `publishGitPage` skips it when the file is not the approved render; the outcome is `refused` `preview_changed` with a read-only fix re-running the preview); it wakes this process's consumer and waits up to the write wait for them (`mirrored` / `mirror_queued` / `held` / `failed`; a replay is `replayed`). Test: `test/pathological/lp-a-segmented-mirror.test.ts`.
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index 3137ef79ce..25cf0f6d62 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -319,10 +319,12 @@ the schema. If the brain schema is newer than this gbrain client, upgrade
gbrain first; the repair refuses rather than build an older table shape.
Purges that failed on the missing cache before this fix may have been parked
-after five failures, and the nightly purge skips parked pages. After the
-upgrade, preview them with `gbrain pages purge-deleted --retry-parked
---dry-run` and run it without `--dry-run` after the user agrees; doctor
-`purge_parked_pages` lists them.
+after five failures. A park records the gbrain version that wrote it, and the
+first purge run after an upgrade tries a park an older version wrote once more,
+so these clear by themselves. One that fails again is parked under the new
+version: doctor `purge_parked_pages` lists it; preview
+`gbrain pages purge-deleted --retry-parked --dry-run` and run it without
+`--dry-run` after the user agrees.
A missing table that holds user data is listed under `user_data_tables`; this
repair never recreates it, because an empty table would hide that its rows are
@@ -1264,7 +1266,8 @@ A twin soft-deleted by hand while the legacy page records the file (receipt
`write_through.skipped: shared_origin`) keeps its recorded file, and the
retention purge removes it database-only too: the file and the legacy page stay
and no content tombstone is written. A tombstone an older release parked after
-refusing it is purged once by `gbrain pages purge-deleted --retry-parked --yes`.
+refusing it gets one automatic attempt from the first purge run after the
+upgrade (a park another gbrain version wrote is retried once) and is purged then.
The legacy page keeps its slug: that is also the slug sync gives a never-forked
file whose legacy page it takes over (#6727), and the folded slug resolves to it
diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.md
index f02958e61c..d678730427 100644
--- a/docs/guides/troubleshooting.md
+++ b/docs/guides/troubleshooting.md
@@ -58,7 +58,7 @@
| [A page write refused `owner_unavailable`, detail `unbound_source`, on a classic Postgres brain](write-refusals.md#unbound-sources-on-postgres) | don't retry; write the page as `<slug>.md` in the source's checkout, commit it, and run `gbrain sync --source <id>` (a remote agent gives those steps to the user); database-only pages or managed mode are the user's choice | agent, after the user agrees (remote: user) | none | `gbrain get <slug> --source <id>` |
| [`owner_unavailable`, reason `binding_missing`, `incarnation_changed`, `local_path_missing` or `coordination_path_missing`](#owner-unavailable) | `gbrain sources writer status --source <id> --json`; the registration is missing or outdated and re-binding or re-registering the checkout is the host administrator's decision | brain host | none | the same status read shows an active binding for this host |
| Background work (autopilot, jobs, connector syncs) refused `owner_unavailable` "Background writes to source <id> are paused: its canonical owner could not be verified" or "its worktree is recovering" | run the fix, `gbrain sources writer status --source <id> --json`, which names what the source waits on; a deleted owner marker (`.gbrain-owner.json`) is repaired by a writer self-transfer, the user's decision. Nothing was submitted and no request id was used; interactive writes are unaffected | agent; the self-transfer after the user agrees | none to inspect | the same status read shows an active binding; the next background run admits |
-| Doctor warns `purge_parked_pages` | fix the cause each page's last error names, preview `gbrain pages purge-deleted --retry-parked --dry-run --json`, then with the user's agreement run `gbrain pages purge-deleted --retry-parked --yes` | agent, after the user agrees | `destructive` | `gbrain doctor --only purge_parked_pages --json` |
+| Doctor warns `purge_parked_pages` | a park an older gbrain wrote is retried once by the next purge run after an upgrade and is not counted; for the rest, fix the cause each page's last error names, preview `gbrain pages purge-deleted --retry-parked --dry-run --json`, then with the user's agreement run `gbrain pages purge-deleted --retry-parked --yes` | agent, after the user agrees | `destructive` | `gbrain doctor --only purge_parked_pages --json` |
| [`gbrain repair fences` skipped a file `sync_in_progress` while a sync runs](repair.md#fence-repair-during-a-sync) | nothing: a write in flight or the running sync's frozen manifest still names that file; every other candidate repairs now and the next run picks this one up (`gbrain sync --source <id> --no-pull` finishes the sync) | agent | none | `gbrain doctor --only fence_integrity --json` |
| [A Google or GitHub item is held (`connector_held_items`)](#held-connector-items) | `gbrain sources status <id>`, fix the cause, then `gbrain sources retry-held <id>` and `gbrain sync --source <id>` | agent, after the user agrees | `egress` (fetches from the provider again) | `gbrain doctor --only connector_held_items --json` |
| `gbrain google status` exits 1 naming `calendar_unreadable`, doctor warns `google_calendar_readable`, or the sync log prints `[google] calendar_unreadable` (calendar pages stop arriving) | `gbrain google calendars --account <email>` lists the calendars the account can read; then `gbrain sources set-calendar <source> <calendar-id>` and `gbrain sync --source <source>` ([unreadable calendar](google-connect.md#unreadable-calendar)) | agent, after the user agrees which calendar | none (on a managed brain whose source also syncs Gmail or Contacts, the change re-reads their history: `confirmation_required`, re-run with `--yes` after the user agrees) | `gbrain doctor --only google_calendar_readable --json` is ok |
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index aba8f92baa..2a6a3cf798 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -56,7 +56,7 @@ of making a duplicate.
| <a id="refusal_breaker"></a>`refusal_breaker` | the code of the earlier refusals | The same maintenance write (same source, slug, page revision, planner and intent) was refused `persistence.maintenance.refusal_breaker_threshold` times (default 3; `0` turns it off) in the last 24 hours, so maintenance submits nothing for it instead of adding another receipt (#6696). It is tried again once the page, the planner or the write changes, or when the oldest refusal is 24 hours old. | Read the last refusal with `gbrain write-request -- <request_id>` (named in the message) and fix what it names. Doctor `maintenance_write_drift` lists every held-back write with its exit. |
| <a id="canonical_file_absent"></a>`canonical_file_absent` | `source_changed` (`restore_page` / `gbrain restore`) | On a brain without managed persistence, a restore that writes no file (`sync.write_through` off, a sandbox, a database-only source) of a soft-deleted page whose recorded file is no longer among the files sync imports (#6609). A plain restore would be undone by the next `gbrain sync --full`, so nothing was restored. Not retryable; the fix asks the user. | Ask the user. To keep the page with its file: put the file back at its recorded path, commit it and `gbrain sync --source <source>`. To keep it database-only: `gbrain restore <slug> --source-id <source> --detach` (MCP `restore_page` with `detach: true`), which forgets the recorded file and stamps `database_only_reason='detached'`. See [restoring a page whose file is gone](../storage-tiering.md#restoring-a-page-whose-file-is-gone). |
| <a id="pending_import"></a>`pending_import` | `source_changed` (detail `file_database_drift`, reason `pending_import`) | The page's canonical file holds a change committed through Git (another agent's commit, a pull) that managed sync has not imported yet: the file on disk is exactly the blob `HEAD` holds for its path and not the one the source's last imported commit holds. The message is "The canonical file holds a committed Git change that sync has not imported yet." Nothing was overwritten. Since #6693 the receipt records origin `pending_import`; a write refused because sync holds the file records origin `sync_held` (see [held files](#held-files-and-content-refusals)). | A `remember` needs nothing from the caller: its `fix.next` is `wait`, the fact is kept in the receipt, and the first managed sync that imports the file (any outcome, a partial run included) makes one replay attempt on the original caller's lane with the fact's original `valid_from` and expiry (the sync result's `replayedRemembers` counts examined, replayed, waiting, skipped, remaining; at most 50 per run and 30 s). Do not save the fact again. A remember refused while sync held its file is replayed the same way once the repaired file is imported. A replay that is refused (authority revoked, page rewritten) stays listed by `gbrain repair failed-writes --source <source>` for a person. Any other write (`put_page`, `add_timeline_entry`) is never replayed automatically, because its body would replace the imported change: run `gbrain sync --source <source> --no-pull` on the brain host (the refusal's fix), read the page again and resubmit with a new request ID. An uncommitted hand edit still refuses `file_database_drift` and needs reconcile. |
-| <a id="shared_origin"></a>`shared_origin` | `source_changed` (purge, or a delete whose survivor changed); a soft delete commits with `write_through.skipped: shared_origin` | Two live pages of one source recorded the same canonical file (a duplicate-origin twin: the shared file renders one of them, so a delete of either used to refuse `file_database_drift`, reconcile refused "Several pages claim the recorded canonical file" and every managed sync refused `page_identity_changed`). A soft delete (`gbrain delete <slug> --source-id <id> --expected-revision <rev>`) of a page whose file another live page records now keeps the file and publishes database-only: the selected database page is hidden; the file and the surviving page remain. This does not erase that file's contents. The receipt's `write_through.warning` says so and names the surviving slug to the trusted local owner, or to a remote writer whose grant and visibility cover that slug; other remote writers read a generic "another page of this source records the same file". Sync's census and both origin guards apply one rule: a live page wins over tombstones, several live pages refuse, a single tombstone may be reused, several tombstones stay ambiguous. An owner purge (`--purge`) of a shared-origin page refuses with this reason: a purge tombstones the content source-wide and a same-content survivor would refuse `purged_content` on its next import. The 72 h retention purge (the autopilot purge phase, `gbrain pages purge-deleted --older-than 72h --yes`) of such a page once it is soft-deleted writes no tombstone, so it removes the page row, its chunks, links and facts database-only and leaves the file and the surviving page untouched (#7311); a census that changed under it defers to the next run, which re-reads the claimants and, when the tombstone now owns the file alone, purges it normally, file included. A delete whose surviving claimant changed between preparation and publication (the file moved or removed, a survivor deleted or re-pointed) refuses and never removes the file as a fallback. | Delete the page that should not own the file; the kept file still holds whatever text it had, so edit it first if it holds the deleted page's text, then import its current content into the surviving page with `gbrain repair file-drift --source <id> --slug <surviving-slug> --prefer file` (preview, then the apply command it prints) and `gbrain sync --source <id> --no-pull`. Sync does not overwrite a surviving page that differs from the file: it holds it [`file_drift`](#file_drift), whose fix leads with the same command. For a purge of a live page, soft-delete it instead; a soft-deleted one is removed by the retention purge (a tombstone an older release parked after its refusals: `gbrain pages purge-deleted --retry-parked --yes`). After a `source_changed` on a changed survivor, submit the delete again with a new `request_id`; it re-reads the file's claimants. |
+| <a id="shared_origin"></a>`shared_origin` | `source_changed` (purge, or a delete whose survivor changed); a soft delete commits with `write_through.skipped: shared_origin` | Two live pages of one source recorded the same canonical file (a duplicate-origin twin: the shared file renders one of them, so a delete of either used to refuse `file_database_drift`, reconcile refused "Several pages claim the recorded canonical file" and every managed sync refused `page_identity_changed`). A soft delete (`gbrain delete <slug> --source-id <id> --expected-revision <rev>`) of a page whose file another live page records now keeps the file and publishes database-only: the selected database page is hidden; the file and the surviving page remain. This does not erase that file's contents. The receipt's `write_through.warning` says so and names the surviving slug to the trusted local owner, or to a remote writer whose grant and visibility cover that slug; other remote writers read a generic "another page of this source records the same file". Sync's census and both origin guards apply one rule: a live page wins over tombstones, several live pages refuse, a single tombstone may be reused, several tombstones stay ambiguous. An owner purge (`--purge`) of a shared-origin page refuses with this reason: a purge tombstones the content source-wide and a same-content survivor would refuse `purged_content` on its next import. The 72 h retention purge (the autopilot purge phase, `gbrain pages purge-deleted --older-than 72h --yes`) of such a page once it is soft-deleted writes no tombstone, so it removes the page row, its chunks, links and facts database-only and leaves the file and the surviving page untouched (#7311); a census that changed under it defers to the next run, which re-reads the claimants and, when the tombstone now owns the file alone, purges it normally, file included. A delete whose surviving claimant changed between preparation and publication (the file moved or removed, a survivor deleted or re-pointed) refuses and never removes the file as a fallback. | Delete the page that should not own the file; the kept file still holds whatever text it had, so edit it first if it holds the deleted page's text, then import its current content into the surviving page with `gbrain repair file-drift --source <id> --slug <surviving-slug> --prefer file` (preview, then the apply command it prints) and `gbrain sync --source <id> --no-pull`. Sync does not overwrite a surviving page that differs from the file: it holds it [`file_drift`](#file_drift), whose fix leads with the same command. For a purge of a live page, soft-delete it instead; a soft-deleted one is removed by the retention purge (a tombstone an older release parked after its refusals is retried once by the first purge run after the upgrade). After a `source_changed` on a changed survivor, submit the delete again with a new `request_id`; it re-reads the file's claimants. |
| <a id="writer-coordinator-required"></a>`database_guard` or `database_trigger` | `writer_coordinator_required` (or `storage_error` for another trigger) | A database trigger refused a row while a write was being prepared or published, so nothing was committed and any canonical file already replaced was restored. With `database_guard`, a gbrain process wrote a row its publication does not own (another source, an unresolvable source, or a source checkpoint/topology change outside owner administration). This is a gbrain defect or a version mismatch between gbrain processes sharing the database, not a content conflict. The receipt's `write_error_detail` names the table, operation, guard branch, source relationship and stage; it never contains page text or source names. For another trigger it also carries a closed `reason`: `attribution_unclassified_table` or `trust_unclassified_table` (a gbrain stamp trigger met a table it is not built for: a version mismatch), `graduation_in_progress` (the engine-graduation fence, SQLSTATE 55000, refuses writes until the move finishes: retry later), or `unknown` (an operator trigger gbrain does not know; its message text stays on the brain host). The same `reason`, raiser and table appear on the managed sync failure (`gbrain doctor`, the failure ledger) and in `gbrain sync status --json` `last_error.write_error_detail`. | On the brain host run `gbrain sources writer status --probe --json`. Its `recent_failures[].error_detail` adds the source ids and the gbrain build and host that ran the attempt (`attempt.consumer_version`). If that build differs from `gbrain --version`, upgrade or restart every gbrain process that shares the database (serve, autopilot, sync jobs), then retry with a **new** request ID. If the builds match, report `error_detail` on the gbrain issue tracker. Never force-write, edit SQL or disable the guard. |
| `ambiguous_source_path` | `page_identity_changed` | A source registered at a Git subfolder `<sub>` has a page whose stored path `<sub>/<file>` could mean either `<file>` in the source directory (the older Git-root spelling) or `<sub>/<file>` inside a folder of the source that repeats its name, and both files exist. Sync refuses instead of guessing. See [sources in a Git subfolder](multi-source-brains.md#sources-in-a-git-subfolder). | Rename or move one of the two files, commit, then `gbrain sync --source <source> --no-pull`. |
| `physical_root_device_changed` | `recovery_required` | The checkout's filesystem device number changed while everything else matches, which macOS can do after a reboot. When the owner token, brain, worktree, root, inode and a non-zero birth time all match and the caller can verify database ownership, the write path re-stamps ownership by itself and the write proceeds. This refusal means the automatic re-stamp could not be verified; the suggestion says why. | Do a deliberate self-transfer: `gbrain sources writer status <source>` (note `admin_state`), then `gbrain sources writer transfer prepare <source> --self-transfer --admin-intent writer_transfer_prepare --expected-state <admin_state>`, then `gbrain sources writer transfer accept <source> --path <root> --expected-epoch <epoch> --manifest <digest from prepare> --self-transfer --admin-intent writer_transfer_accept --expected-state <fresh admin_state>`. Retry the original write with the **same** request ID. Never delete ownership marker files. |
diff --git a/llms-full.txt b/llms-full.txt
index 9026a08a0e..4f513f6413 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -10498,7 +10498,7 @@ Source: https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/tro
| [A page write refused `owner_unavailable`, detail `unbound_source`, on a classic Postgres brain](write-refusals.md#unbound-sources-on-postgres) | don't retry; write the page as `<slug>.md` in the source's checkout, commit it, and run `gbrain sync --source <id>` (a remote agent gives those steps to the user); database-only pages or managed mode are the user's choice | agent, after the user agrees (remote: user) | none | `gbrain get <slug> --source <id>` |
| [`owner_unavailable`, reason `binding_missing`, `incarnation_changed`, `local_path_missing` or `coordination_path_missing`](#owner-unavailable) | `gbrain sources writer status --source <id> --json`; the registration is missing or outdated and re-binding or re-registering the checkout is the host administrator's decision | brain host | none | the same status read shows an active binding for this host |
| Background work (autopilot, jobs, connector syncs) refused `owner_unavailable` "Background writes to source <id> are paused: its canonical owner could not be verified" or "its worktree is recovering" | run the fix, `gbrain sources writer status --source <id> --json`, which names what the source waits on; a deleted owner marker (`.gbrain-owner.json`) is repaired by a writer self-transfer, the user's decision. Nothing was submitted and no request id was used; interactive writes are unaffected | agent; the self-transfer after the user agrees | none to inspect | the same status read shows an active binding; the next background run admits |
-| Doctor warns `purge_parked_pages` | fix the cause each page's last error names, preview `gbrain pages purge-deleted --retry-parked --dry-run --json`, then with the user's agreement run `gbrain pages purge-deleted --retry-parked --yes` | agent, after the user agrees | `destructive` | `gbrain doctor --only purge_parked_pages --json` |
+| Doctor warns `purge_parked_pages` | a park an older gbrain wrote is retried once by the next purge run after an upgrade and is not counted; for the rest, fix the cause each page's last error names, preview `gbrain pages purge-deleted --retry-parked --dry-run --json`, then with the user's agreement run `gbrain pages purge-deleted --retry-parked --yes` | agent, after the user agrees | `destructive` | `gbrain doctor --only purge_parked_pages --json` |
| [`gbrain repair fences` skipped a file `sync_in_progress` while a sync runs](repair.md#fence-repair-during-a-sync) | nothing: a write in flight or the running sync's frozen manifest still names that file; every other candidate repairs now and the next run picks this one up (`gbrain sync --source <id> --no-pull` finishes the sync) | agent | none | `gbrain doctor --only fence_integrity --json` |
| [A Google or GitHub item is held (`connector_held_items`)](#held-connector-items) | `gbrain sources status <id>`, fix the cause, then `gbrain sources retry-held <id>` and `gbrain sync --source <id>` | agent, after the user agrees | `egress` (fetches from the provider again) | `gbrain doctor --only connector_held_items --json` |
| `gbrain google status` exits 1 naming `calendar_unreadable`, doctor warns `google_calendar_readable`, or the sync log prints `[google] calendar_unreadable` (calendar pages stop arriving) | `gbrain google calendars --account <email>` lists the calendars the account can read; then `gbrain sources set-calendar <source> <calendar-id>` and `gbrain sync --source <source>` ([unreadable calendar](google-connect.md#unreadable-calendar)) | agent, after the user agrees which calendar | none (on a managed brain whose source also syncs Gmail or Contacts, the change re-reads their history: `confirmation_required`, re-run with `--yes` after the user agrees) | `gbrain doctor --only google_calendar_readable --json` is ok |
diff --git a/src/commands/doctor/checks/purge-parks.ts b/src/commands/doctor/checks/purge-parks.ts
index b77c72ce87..4865b2fbee 100644
--- a/src/commands/doctor/checks/purge-parks.ts
+++ b/src/commands/doctor/checks/purge-parks.ts
@@ -7,7 +7,7 @@
*/
import type { Check } from '../../doctor.ts';
import type { BrainEngine } from '../../../core/engine.ts';
-import { PURGE_PARK_LIMIT, readPurgeParks } from '../../../core/persistence/purge-parks.ts';
+import { isParked, PURGE_PARK_LIMIT, readPurgeParks } from '../../../core/persistence/purge-parks.ts';
import { checkError, doctorVerify } from '../check-fix.ts';
import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
@@ -17,7 +17,7 @@ const SAMPLE = 20;
export async function checkPurgeParkedPages(engine: BrainEngine): Promise<Check> {
let parked;
try {
- parked = [...(await readPurgeParks(engine)).values()].filter(park => park.failures >= PURGE_PARK_LIMIT);
+ parked = [...(await readPurgeParks(engine)).values()].filter(isParked);
} catch (error) {
return checkError(NAME, 'read the parked page purges', error);
}
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index a000ee5291..c961b93205 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1098,7 +1098,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
// #7190 (GBRA-150): per-source applied-through watermark. `since` is stamped at the merge slot.
{ since: '0.60.361.0', id: 'applied_watermark_7190', text: '`get_write_request` with `applied: true` (`gbrain write-request <id> --applied`) now returns `applied`, read live: whether the write is searchable yet (`searchable_yet`, `searchable`, `state`), the gap (`requests_ahead`, `unembedded_chunks`), the request `sequence` and the source\'s write watermark (`indexed_through`, `committed_through_request`, `requests_pending`), and a pending write\'s hint names that read; a write\'s own reply is otherwise unchanged. `gbrain sources status --json`, MCP `sources_status` and `gbrain sync --json` add a `watermark` per source: `indexed_through` (the last commit a finished sync pass reached; a deadline-stopped or partial pass never moves it), `embedded_through` (held pages count as not embedded), `committed_through_request`, `pending` (requests, commits and files behind HEAD, held files, withheld deletes) and `writer_heartbeat` (the drain-lease holder and its last progress).' },
// #7311 / #7305 (GBRA-177): retention purge of a shared-origin tombstone. `since` is stamped at the merge slot.
- { since: 'TBD', text: 'The 72 h retention purge (the autopilot purge phase, `gbrain pages purge-deleted`) now removes a soft-deleted page whose canonical file another live page of its source records (a duplicate deleted with receipt `write_through.skipped: shared_origin`) database-only: its row, chunks, links and facts go; the file and the surviving page stay, and no content or fact tombstone is written. It used to refuse every run as a shared origin, so the purge phase failed each pass (`managed_purge_failed`), `global_maintenance_stalled` never cleared and the tombstone parked after 5 failures. A tombstone parked by that refusal is not retried automatically: `gbrain pages purge-deleted --retry-parked --yes` purges it once. An owner `gbrain delete <slug> --purge` of such a page still refuses (it would tombstone the survivor\'s content), and on a soft-deleted page it now names the retention purge instead of a soft delete. Nothing changes on upgrade.' },
+ { since: 'TBD', text: 'The 72 h retention purge (the autopilot purge phase, `gbrain pages purge-deleted`) now removes a soft-deleted page whose canonical file another live page of its source records (a duplicate deleted with receipt `write_through.skipped: shared_origin`) database-only: its row, chunks, links and facts go; the file and the surviving page stay, and no content or fact tombstone is written. It used to refuse every run as a shared origin, so the purge phase failed each pass (`managed_purge_failed`), `global_maintenance_stalled` never cleared and the tombstone parked after 5 failures. A tombstone parked by that refusal is retried once by the first purge run after the upgrade and purged then. An owner `gbrain delete <slug> --purge` of such a page still refuses (it would tombstone the survivor\'s content), and on a soft-deleted page it now names the retention purge instead of a soft delete. Nothing changes on upgrade.' },
+ { since: 'TBD', text: 'A purge park (a soft-deleted page the purge stopped retrying after 5 failed purges) now records the gbrain version that wrote it. The first purge run of another version (the autopilot purge phase, the purge job, `gbrain pages purge-deleted`) tries such a park once more, so a park whose cause the upgrade fixed clears by itself instead of waiting for `--retry-parked`; a failure parks it again under the new version, so each version tries it at most once. A park written before parks recorded a version counts as another version\'s. Doctor `purge_parked_pages` counts only parks the running version wrote. `--retry-parked` is unchanged.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index e9a6543319..5b4e18d389 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -79,7 +79,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],
'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--body', '--brain', '--check', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--timeout', '--timings', '--type', '--wait'],
'jobs': ['--abbrev-ref', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--close', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filters', '--finished-since', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-ambiguous', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--pull', '--purge', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--row', '--scope', '--scopes', '--section', '--segment-limit', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--statement-timeout', '--status', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
- 'lint': ['--abbrev-ref', '--accept-pending', '--adopt-slug-path', '--audit', '--autostash', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--conflicts', '--dry-run', '--enable', '--exclude', '--expect-remote', '--expected-epoch', '--expected-revision', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--get', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--infer-entity', '--is-inside-work-tree', '--json', '--keep', '--local', '--local-env-vars', '--manifest', '--max-cost-usd', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-pull', '--no-tags', '--no-verify', '--only', '--pat-file', '--path', '--prefer', '--preview', '--probe', '--progress-interval', '--progress-json', '--provenance', '--pull', '--purge', '--push-only', '--quiet', '--rebase', '--require-clean', '--resolve', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--slugs', '--source', '--source-id', '--timeout', '--timings', '--unset-all', '--wait', '--yes'],
+ 'lint': ['--abbrev-ref', '--accept-pending', '--adopt-slug-path', '--audit', '--autostash', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--conflicts', '--dry-run', '--enable', '--exclude', '--expect-remote', '--expected-epoch', '--expected-revision', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--get', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--infer-entity', '--is-inside-work-tree', '--json', '--keep', '--local', '--local-env-vars', '--manifest', '--max-cost-usd', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-pull', '--no-tags', '--no-verify', '--older-than', '--only', '--pat-file', '--path', '--prefer', '--preview', '--probe', '--progress-interval', '--progress-json', '--provenance', '--pull', '--purge', '--push-only', '--quiet', '--rebase', '--require-clean', '--resolve', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--slugs', '--source', '--source-id', '--timeout', '--timings', '--unset-all', '--wait', '--yes'],
'loops': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],
'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],
'maintain': ['--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--apply', '--assign-corpus', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--class', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--conversation', '--count', '--detach', '--detail', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--entity', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--keep-checkout', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--name-only', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-pull', '--once', '--only', '--operations', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--push-only', '--query', '--question', '--queue', '--reader-mode', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--safe', '--scope', '--scopes', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--state', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--to', '--token', '--top-k', '--type', '--unindexed', '--url-env', '--user', '--verbose', '--version', '--window', '--workers', '--yes'],
diff --git a/src/core/persistence/purge-deleted.ts b/src/core/persistence/purge-deleted.ts
index 04c3f2deda..677e5eba4d 100644
--- a/src/core/persistence/purge-deleted.ts
+++ b/src/core/persistence/purge-deleted.ts
@@ -14,7 +14,7 @@ import { linkStreamSlugs } from './page-purge.ts';
import { identityDowngradePurgeHold } from '../sync-identity-downgrades.ts';
import { atomRetirementPurgeHold } from './atom-retirement-hold.ts';
import { writerOnboardingPreflight } from './onboarding.ts';
-import { clearPurgePark, notePurgeSourceWriter, PURGE_PARK_LIMIT, purgeParkKey, prunePurgeParks, readPurgeParks, recordPurgeFailure, type PurgePark } from './purge-parks.ts';
+import { clearPurgePark, isParked, notePurgeSourceWriter, PURGE_PARK_LIMIT, purgeParkKey, prunePurgeParks, readPurgeParks, recordPurgeFailure, type PurgePark } from './purge-parks.ts';
import { ItemRun, type ItemFailure } from '../item-failure.ts';
import { readUnreviewedSyncTombstones, syncDeleteHeld } from './sync-delete-tombstones.ts';
@@ -117,7 +117,7 @@ async function expireRecordedTombstones(engine: BrainEngine, olderThanHours: num
const failures: Array<{ row: RecordedTombstone; failure: ItemFailure }> = [];
for (const row of await recordedTombstones(engine, hours)) {
if (held.has(row.id)) continue;
- if (row.park && row.park.failures >= PURGE_PARK_LIMIT && !retryParked) {
+ if (isParked(row.park) && !retryParked) {
out.parked++;
out.exclude.push(row.id);
out.blocked.push({ source_id: row.source_id, slug: row.slug, code: 'purge_parked', reason: parkedReason(row.park) });
@@ -189,7 +189,7 @@ export interface PurgeSelection {
export async function selectPurgeCandidates(engine: BrainEngine, olderThanHours: number, opts: { retryParked?: boolean; automatic?: boolean } = {}): Promise<PurgeSelection> {
if (!await managedPersistenceEnabled(engine)) {
const parked = (await recordedTombstones(engine, String(Math.max(0, Math.floor(olderThanHours)))))
- .filter((row): row is RecordedTombstone & { park: PurgePark } => !!row.park && row.park.failures >= PURGE_PARK_LIMIT);
+ .filter((row): row is RecordedTombstone & { park: PurgePark } => isParked(row.park));
const skipped = new Set(opts.retryParked ? [] : parked.map(row => row.id));
const unreviewed = (await readUnreviewedSyncTombstones(engine, olderThanHours)).filter(row => !skipped.has(row.id));
const kept = opts.automatic ? unreviewed : [];
@@ -231,7 +231,7 @@ export async function selectPurgeCandidates(engine: BrainEngine, olderThanHours:
const key = purgeParkKey(row.source_id, row.slug, row.deleted_us);
// A record marked while the writer was not active is dropped by this run (the rearm), so it does not count here.
const park = parks.get(key)?.inactive_seen ? undefined : parks.get(key);
- if (park && park.failures >= PURGE_PARK_LIMIT) {
+ if (isParked(park)) {
selection.parked.push({ source_id: row.source_id, slug: row.slug, failures: park.failures, code: park.code, retried: opts.retryParked === true });
if (!opts.retryParked) {
selection.blocked.push({ source_id: row.source_id, slug: row.slug, code: 'purge_parked', reason: parkedReason(park) });
diff --git a/src/core/persistence/purge-parks.ts b/src/core/persistence/purge-parks.ts
index f46e168878..d50e659f6e 100644
--- a/src/core/persistence/purge-parks.ts
+++ b/src/core/persistence/purge-parks.ts
@@ -12,13 +12,28 @@
* seen not active (rearm), or by one more attempt through
* `gbrain pages purge-deleted --retry-parked`. Rows are exempt from the
* op_checkpoints TTL sweep.
+ *
+ * A park records the gbrain version that wrote it, as a global-maintenance
+ * phase streak does: only a park the running version wrote is parked
+ * (`isParked`). One another version wrote, or one from before parks recorded
+ * a version, gets one automatic attempt (the refusal behind it may be fixed);
+ * a failure re-parks it under the running version, so it is tried once per
+ * version per tombstone.
*/
+import { VERSION } from '../../version.ts';
import type { SqlEngine } from './model.ts';
export const PURGE_PARK_OP = 'purge-deleted-park';
export const PURGE_PARK_LIMIT = 5;
-export interface PurgePark { source_id: string; slug: string; deleted_us: string; failures: number; code: string | null; reason: string; failed_at: string; inactive_seen?: true }
+export interface PurgePark { source_id: string; slug: string; deleted_us: string; failures: number; code: string | null; reason: string; failed_at: string; inactive_seen?: true;
+ /** The gbrain version that recorded the last failure; absent on a park written before parks recorded one. */
+ version?: string }
+
+/** Parked: PURGE_PARK_LIMIT failures, the last one recorded by the running gbrain version. */
+export function isParked(park: PurgePark | undefined): park is PurgePark {
+ return park !== undefined && park.failures >= PURGE_PARK_LIMIT && park.version === VERSION;
+}
export function purgeParkKey(sourceId: string, slug: string, deletedUs: string): string {
return JSON.stringify([sourceId, slug, deletedUs]);
@@ -41,11 +56,11 @@ export async function prunePurgeParks(engine: SqlEngine): Promise<void> {
}
export async function recordPurgeFailure(engine: SqlEngine, park: Pick<PurgePark, 'source_id' | 'slug' | 'deleted_us' | 'code' | 'reason'>): Promise<void> {
- const first: PurgePark = { ...park, failures: 1, failed_at: new Date().toISOString() };
+ const first: PurgePark = { ...park, failures: 1, failed_at: new Date().toISOString(), version: VERSION };
await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,$3::text::jsonb)
ON CONFLICT (op,fingerprint) DO UPDATE SET updated_at=now(), completed_keys=jsonb_build_array((op_checkpoints.completed_keys->0)
- || jsonb_build_object('failures', COALESCE((op_checkpoints.completed_keys->0->>'failures')::int, 0) + 1, 'code', $4::text, 'reason', $5::text, 'failed_at', $6::text))`,
- [PURGE_PARK_OP, purgeParkKey(park.source_id, park.slug, park.deleted_us), JSON.stringify([first]), park.code, park.reason, first.failed_at]);
+ || jsonb_build_object('failures', COALESCE((op_checkpoints.completed_keys->0->>'failures')::int, 0) + 1, 'code', $4::text, 'reason', $5::text, 'failed_at', $6::text, 'version', $7::text))`,
+ [PURGE_PARK_OP, purgeParkKey(park.source_id, park.slug, park.deleted_us), JSON.stringify([first]), park.code, park.reason, first.failed_at, VERSION]);
}
export async function clearPurgePark(engine: SqlEngine, key: string): Promise<void> {
diff --git a/test/e2e/purge-parks-version-postgres.test.ts b/test/e2e/purge-parks-version-postgres.test.ts
new file mode 100644
index 0000000000..a6510c9fdb
--- /dev/null
+++ b/test/e2e/purge-parks-version-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../purge-parks-version.test.ts'));
diff --git a/test/purge-parks-version.test.ts b/test/purge-parks-version.test.ts
new file mode 100644
index 0000000000..99ca5a4fa6
--- /dev/null
+++ b/test/purge-parks-version.test.ts
@@ -0,0 +1,94 @@
+/**
+ * A purge park (purge-parks.ts) left by another gbrain version. A tombstone parked after PURGE_PARK_LIMIT failed purges
+ * stayed parked until an operator ran `gbrain pages purge-deleted --retry-parked`, even when the refusal behind it was
+ * gone in the running version (#7311: the shared-origin refusal), so the purge phase warned and doctor
+ * `purge_parked_pages` stayed warning. A park now records the gbrain version that wrote it, as a global-maintenance phase
+ * streak does: a park another version wrote, or one written before parks recorded a version, gets one automatic
+ * attempt, and a failure re-parks it under the running version. A park the running version wrote is not retried
+ * automatically; `--retry-parked` still retries it once.
+ *
+ * PGLite always; Postgres through test/e2e/purge-parks-version-postgres.test.ts. Synthetic content only.
+ */
+import { describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { VERSION } from '../src/version.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { purgeDeletedPagesCoordinated, purgePhaseStatus } from '../src/core/persistence/purge-deleted.ts';
+import { PURGE_PARK_LIMIT, PURGE_PARK_OP, readPurgeParks } from '../src/core/persistence/purge-parks.ts';
+import { checkPurgeParkedPages } from '../src/commands/doctor/checks/purge-parks.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+
+const SLUG = 'notes/expired-example';
+
+async function raw<T>(engine: BrainEngine, fn: () => Promise<T>): Promise<T> {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ try { return await fn(); } finally { await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1'); }
+}
+const tombstone = async (engine: BrainEngine) => (await engine.executeRaw("SELECT 1 FROM pages WHERE source_id='default' AND slug=$1", [SLUG])).length > 0;
+const purgeRequests = async (engine: BrainEngine) => (await engine.executeRaw(
+ "SELECT 1 FROM persistence_requests WHERE source_id='default' AND operation='delete_page' AND (intent->>'purge')::boolean IS TRUE")).length;
+const park = async (engine: BrainEngine) => [...(await readPurgeParks(engine)).values()][0];
+const automatic = (engine: BrainEngine) => purgeDeletedPagesCoordinated(engine, 72, { automatic: true });
+
+/** An expired tombstone whose hard delete the database refuses, parked by PURGE_PARK_LIMIT real automatic purges. */
+async function parkedTombstone(engine: BrainEngine, ctx: OperationContext): Promise<void> {
+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug: SLUG, content: '---\ntitle: Expired\ntype: note\n---\nA synthetic page that expires.', request_id: randomUUID() } });
+ const snapshot = await engine.readPageSnapshot(SLUG, { sourceId: 'default' });
+ await submitPageMutation(ctx, { operation: 'delete_page', params: { slug: SLUG, expected_revision: snapshot!.revision, request_id: randomUUID() } });
+ await raw(engine, () => engine.executeRaw("UPDATE pages SET deleted_at=now() - interval '100 hours' WHERE source_id='default' AND slug=$1", [SLUG]));
+ await engine.executeRaw(`CREATE OR REPLACE FUNCTION purge_parks_version_refuse() RETURNS trigger LANGUAGE plpgsql AS $$
+ BEGIN RAISE EXCEPTION 'synthetic purge refusal'; END $$`);
+ await engine.executeRaw(`CREATE TRIGGER purge_parks_version_refuse BEFORE DELETE ON pages FOR EACH ROW WHEN (OLD.slug = '${SLUG}') EXECUTE FUNCTION purge_parks_version_refuse()`);
+ for (let attempt = 1; attempt <= PURGE_PARK_LIMIT; attempt++) expect(await automatic(engine)).toMatchObject({ count: 0, failed: 1, parked: 0 });
+ expect(await automatic(engine)).toMatchObject({ count: 0, failed: 0, parked: 1 });
+ expect(await purgeRequests(engine)).toBe(PURGE_PARK_LIMIT);
+}
+const allowPurge = (engine: BrainEngine) => engine.executeRaw('DROP TRIGGER IF EXISTS purge_parks_version_refuse ON pages');
+/** Rewrites the park as an older gbrain left it: another version's stamp, or (null) none at all. */
+const parkedBy = (engine: BrainEngine, version: string | null) => engine.executeRaw(
+ `UPDATE op_checkpoints SET completed_keys = jsonb_build_array(CASE WHEN $2::text IS NULL THEN (completed_keys->0) - 'version'
+ ELSE (completed_keys->0) || jsonb_build_object('version', $2::text) END) WHERE op=$1`, [PURGE_PARK_OP, version]);
+
+for (const backend of testBackends()) {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+ describe(`purge parks across gbrain versions (${backend})`, () => {
+ test('a park the running version wrote records it and is not retried automatically; --retry-parked still retries it once', () => managedBrain(async ({ engine, ctx }) => {
+ await parkedTombstone(engine, ctx);
+ expect(await park(engine)).toMatchObject({ failures: PURGE_PARK_LIMIT, version: VERSION });
+ await allowPurge(engine);
+ const run = await automatic(engine);
+ expect({ count: run.count, parked: run.parked, status: purgePhaseStatus(run) }).toEqual({ count: 0, parked: 1, status: 'warn' });
+ expect(await purgeRequests(engine)).toBe(PURGE_PARK_LIMIT);
+ expect((await checkPurgeParkedPages(engine)).status).toBe('warn');
+ expect(await purgeDeletedPagesCoordinated(engine, 72, { retryParked: true })).toMatchObject({ count: 1, failed: 0 });
+ expect(await tombstone(engine)).toBe(false);
+ }), 300_000);
+
+ for (const older of ['0.60.1.0', null]) test(`a park ${older ? 'an older version wrote' : 'written before parks recorded a version'} gets one automatic attempt after the upgrade and is purged`, () => managedBrain(async ({ engine, ctx }) => {
+ await parkedTombstone(engine, ctx);
+ await parkedBy(engine, older);
+ expect((await checkPurgeParkedPages(engine)).status).toBe('ok');
+ await allowPurge(engine);
+ const run = await automatic(engine);
+ expect({ count: run.count, slugs: run.slugs, parked: run.parked, blocked: run.blocked, status: purgePhaseStatus(run) })
+ .toEqual({ count: 1, slugs: [SLUG], parked: 0, blocked: [], status: 'ok' });
+ expect(await tombstone(engine)).toBe(false);
+ expect(await park(engine)).toBeUndefined();
+ }), 300_000);
+
+ test('the attempt is bounded: a failure re-parks it under the running version, and the next run does not retry it', () => managedBrain(async ({ engine, ctx }) => {
+ await parkedTombstone(engine, ctx);
+ await parkedBy(engine, null);
+ expect(await automatic(engine)).toMatchObject({ count: 0, failed: 1, parked: 0 });
+ expect(await purgeRequests(engine)).toBe(PURGE_PARK_LIMIT + 1);
+ expect(await park(engine)).toMatchObject({ failures: PURGE_PARK_LIMIT + 1, version: VERSION });
+ expect(await automatic(engine)).toMatchObject({ count: 0, failed: 0, parked: 1 });
+ expect(await purgeRequests(engine)).toBe(PURGE_PARK_LIMIT + 1);
+ expect(await tombstone(engine)).toBe(true);
+ await allowPurge(engine);
+ }), 300_000);
+ });
+}