Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(purge): retention purge removes shared-origin tombstones database-only (#7311, #7305)

garrytancd182ca2b714
diff --git a/docs/architecture/key-files/canonical-reconciliation.md b/docs/architecture/key-files/canonical-reconciliation.md
index 2449182668..ab2e8097cc 100644
--- a/docs/architecture/key-files/canonical-reconciliation.md
+++ b/docs/architecture/key-files/canonical-reconciliation.md
@@ -30,7 +30,7 @@
- `src/core/persistence/sync-pass-status.ts` — the live `convergence` block of `gbrain sync status` (#6712 PR 4b, design §9, `dry_run: false`): built from the pass row (one primary-key read), the withheld-delete record and `syncAdmissionStatus`, plus `passStatusState`, which keeps a source off `synced` while its newest pass is open or ended unconverged (reasons `pass_unfinished`, `not_converged`, `settle_mismatch`, `deletes_withheld`, `selection_scoped`, `admission_paused`, and `writeback_failed`: a writeback the stamp recorded in `converged.writeback` whose Git effect failed or parked, next step `gbrain sources writer retry-effects --dry-run`). Tests: `test/sync-pass-completion-6712.test.ts`, `test/sync-pass-writeback-fold-6712.test.ts`.
- `src/core/persistence/sync-markers.ts` — the deletion marker and the withheld mass-delete record of a managed Git source (#6712 PR 4b). `writeOriginDeletedMarker` runs in the transaction of every page-row deletion of a managed source (`page-purge.ts`, the purge-mirror replay; `test/page-row-deleters-guard-6712.test.ts` refuses any other deleter) and writes `sync-origin-deleted` (`<source>:<incarnation>:<origin>`, value `{kind:'deleted', blob_oids, page_id, slug}` from the import record) only when it can matter: the origin is in the `last_commit` tree (hardened `ls-tree`) or a file backs it on disk, no other live page records it, and the source is bound and not a company brain; an unreadable checkout counts as present. `retireOriginDeletedMarker` is compare-and-delete on the value read. `writeDeletesWithheld` / `readDeletesWithheld` / `clearDeletesWithheld` keep one `sync-deletes-withheld` record per incarnation (`{target, count, reconcilable, ratio, set_hash, samples≤20}`, `deleteSetHash`: sha256 over the sorted NUL-joined set). Seam: `purge:marker_written`.
- `src/commands/doctor/checks/managed-sync-convergence.ts` — doctor `managed_sync_convergence` (#6712 PR 4a, `deep` tier): the convergence shadow's counts for each managed source this host owns; always `ok` (informational), read-only. Tests: `test/doctor-managed-sync-convergence.test.ts`.
-- `src/core/persistence/file-claims.ts` — the recorded-origin census shared by reconcile and the shared-origin delete (#6517): `fileClaimCandidatesQuery` (the paged same-name query and its binds, built per platform so every bound placeholder is referenced (#6659: an unreferenced bind failed every Windows `delete_page` with 42P18), 100 rows per batch below the source's highest page id, served by the v219 name indexes; `source_path` in any spelling or a `file:` URI; tombstones excluded) and `findLiveFileClaimants`, realpath deciding each candidate. In `page-prepare.ts`, a `delete_page` whose file another live page records (`prepareFileTarget` with `sharedOrigin`, before the byte comparison) owns no file: a soft delete publishes database-only with receipt `write_through.skipped: 'shared_origin'` and a warning ("hidden … does not erase", the `gbrain repair file-drift --source <id> --slug <survivor> --prefer file` that imports the kept file into the survivor; #6712 PR 1: sync holds a survivor that differs from the file `file_drift`, and that hold's fix leads with the same command), `validate` re-runs the census under the publication guards (`validateSharedOrigin`: the file moved or removed, or a different claimant set, refuses `source_changed` and never removes the file), and the surviving slug is named only when `slugDisclosable` (authority.ts: the local owner, or a remote writer whose prefix grant, delegated namespace and visibility cover it). A purge of a shared-origin page refuses and names the soft delete. Tests: `test/page-prepare-shared-origin-6517.test.ts`, `test/sync-origin-live-wins-6517.test.ts`, `test/e2e/managed-sync-shared-origin-6517.test.ts`.
+- `src/core/persistence/file-claims.ts` — the recorded-origin census shared by reconcile and the shared-origin delete (#6517): `fileClaimCandidatesQuery` (the paged same-name query and its binds, built per platform so every bound placeholder is referenced (#6659: an unreferenced bind failed every Windows `delete_page` with 42P18), 100 rows per batch below the source's highest page id, served by the v219 name indexes; `source_path` in any spelling or a `file:` URI; tombstones excluded) and `findLiveFileClaimants`, realpath deciding each candidate. In `page-prepare.ts`, a `delete_page` whose file another live page records (`prepareFileTarget` with `sharedOrigin`, before the byte comparison) owns no file: a soft delete publishes database-only with receipt `write_through.skipped: 'shared_origin'` and a warning ("hidden … does not erase", the `gbrain repair file-drift --source <id> --slug <survivor> --prefer file` that imports the kept file into the survivor; #6712 PR 1: sync holds a survivor that differs from the file `file_drift`, and that hold's fix leads with the same command), `validate` re-runs the census under the publication guards (`validateSharedOrigin`: the file moved or removed, or a different claimant set, refuses `source_changed` and never removes the file), and the surviving slug is named only when `slugDisclosable` (authority.ts: the local owner, or a remote writer whose prefix grant, delegated namespace and visibility cover it). An owner purge of a shared-origin page refuses and names the soft delete (the retention purge for a tombstone). #7311: the retention purge of a shared-origin tombstone is database-only like an `origin_twin` page's (`sharedRetention`: no file target, applied with `source_path`/`source_uri` forgotten, so no deletion marker names the survivor's file); `validate` re-runs the census, and a changed one refuses `revision_conflict` (`sharedTombstoneChanged`, a purge deferral), so the next run takes the normal path. Tests: `test/purge-shared-origin-tombstone-7311.test.ts` (Postgres: `test/e2e/purge-shared-origin-tombstone-7311-postgres.test.ts`), `test/page-prepare-shared-origin-6517.test.ts`, `test/sync-origin-live-wins-6517.test.ts`, `test/e2e/managed-sync-shared-origin-6517.test.ts`.
- `src/core/persistence/drift-conflicts.ts` — the `source_changed` / `file_database_drift` conflict pile (#6643). `auditDriftConflicts` groups conflict receipts by slug over a bounded window of request sequences (default 100,000, at most 1,000,000), paginated by slug with a `complete` flag; it backs `gbrain sources reconcile <source> --audit --conflicts` (`reconcile-audit.ts`) and MCP `list_write_conflicts` (`ops/persistence.ts`). The window ends at the source's own newest request (current incarnation, the `(source_incarnation, sequence)` index; a cursor never reads past it), and a source the caller may not read returns before anything is computed; the MCP op refuses an out-of-grant `source_id` through `resolveRequestedScope`. Remote callers get database-derived fields only, with source grant, slug fence and visibility filtered in the aggregating SQL; `liveFileDrift` (the `prepareFileTarget` comparison; reason `canonical_file_missing` for a live page whose canonical file is gone, `file_missing` for any other `source_changed`) and `driftClass` (the `reconcile-additive.ts` verdict) run only for a trusted local caller on the canonical owner, and such a row carries the compared file `path`. `submitMaintenance` (`prepared-maintenance.ts`, `maintenanceDriftRefusal`) refuses a drifted page before admission, and `synthesize_concepts` skips a drifted concept before spend, recording it in `dream.concepts.drift_skips` (per-entry atomic updates, released when the sides agree). Tests: `test/maintenance-file-drift-6643.test.ts` (PGLite; Postgres via `test/e2e/maintenance-file-drift-6643-postgres.test.ts`).
- `src/core/repair/file-drift.ts` — `gbrain repair file-drift` (#6643): explicit-only, preview-bound resolution of drifted pages through `reconcileCanonical` with one side preferred (`preferSideDecisions`) inside reconcile's protections; `driftExceptions` lists where the result differs from the preferred side. The preview writes a private artifact under `configDir()/repair-previews/file-drift/<hash>.json` and saves the approved set; apply runs `runReconcileApply` per page under request ids derived from the hash and slug, so an interrupted apply resumes. `--all-drifted` refuses mixed drift classes unless `--class` keeps one. Repeatable `--only`/`--skip` over the source-relative canonical file path (`src/core/repair/path-glob.ts` `matchesRepairPath`: a value without `*` is an exact path, as every kind's `--only`; with `*` it is a glob, file-drift only: `*` within a segment, `**` across) narrow the selection before the class check, the 1,000-page bound and any preview work (`not_selected` residual); they join the selection digest only when given (so earlier hashes are unchanged) and appear in every printed preview and apply command. `prepareDriftPage` builds one page's ready reconcile preview for a preferred side; the plan and the keep_db policy share it. `--keep` is refused at parse in `src/commands/repair.ts` with the same command rewritten to `--prefer database`. `reconcile-prepare.ts` keeps the file bytes when they already parse to the result digest. Doctor `maintenance_write_drift` (`src/commands/doctor/checks/maintenance-drift.ts`) counts what remains and, on the owner host, echoes each declared `storage.keep_db` policy as `keep_db_policy` (prefixes, matched drifted pages among those checked live, `unchecked`, receipt cost from `keepDbReceiptCost`). #6712 wave: a selected page whose `liveFileDrift` reason is `canonical_file_missing` goes through `fileGonePage` (`ghostPageNow` for the path, revision and owner; `canonicalDeletionState` for the route): still committed at HEAD is listed `deletion_uncommitted`, gone from HEAD becomes a `prepareDriftPage(..., { fileGone: true })` recreate (`file_gone`, details `action: 'recreate_file'`; a warning when `gitDurabilityPolicy` is not durable, since an uncommitted recreated file loses to the committed deletion on the next sync) or a `SoftDeletePage` applied through `retireGhost` (exported from `repair/ghost-pages.ts`, under the file-drift request id) with the ghost-pages mass valve; `--all-drifted` never selects missing files. `--held [--side both|unknown|deleted [--state tombstone_edited|purged_differs|file_gone]]` (#6712 PR 4b) selects the source's held `file_drift` pages of one Decision (`selectHeld`, side from `fileDriftSide`): several sides or states without `--side` refuse `file_drift_mixed_selection`, a deleted side without `--state` refuses `file_drift_state_required`, and holds with no side (`sides: database`) list `legacy_side`. Both/unknown and `file_gone` pages take the paths above; `tombstone_edited` and `purged_differs` go through `deletedPage` over `readDeletedDriftTarget`: `--prefer database` is a `RemoveFilePage` applied as the `managed_maintenance_file_drift_remove` intent (`prepareDriftFileRemoval`, dispatched from `prepared-maintenance.ts`: a page file target with no bytes bound to the previewed hash, the tombstone revision or marker value re-checked under the publication guard, the hold cleared in the publishing transaction, the page row untouched), `--prefer file` an `ImportFilePage` applied through `submitManagedFileRepair` with the file's own bytes (restores the tombstone, or creates the page; the deletion marker stays for sync to retire). Each `details.pages` entry carries `verb` (`fileDriftActionVerb`), printed by `render`. The Decision is the hold's `meta.side` / `meta.state` (`sync-holds.ts`: `fileDriftSide` reads older holds' `sides`; `gitHoldItem` lists both; a deleted hold's fix previews `heldDriftPreviewArgv` for its path and names each option's verb). Test: `test/repair-file-drift-held-6712.test.ts`.
- `src/core/ghost-pages.ts` — #6696 B5, the one ghost-page classifier: a ghost is a live page for which `liveFileDrift` returns reason `canonical_file_missing` on the source's canonical owner host (`prepareFileTarget` tags that refusal `detail: 'canonical_file_missing'`). `scanGhostSource` reads a source's live pages in id order (at most `GHOST_SCAN_LIMIT`), resolves each recorded canonical path exactly as `prepareFileTarget` does and stats it, skips `publishesDatabaseOnly` and legacy slugs, and runs the full check on at most `candidateLimit` candidates; it returns the ghosts, `inspected`, `file_backed` (the mass-delete valve's population), `truncated` and the owner it ran under (host, worktree, owner epoch, incarnation). Off the owner host a source is `not_applicable` (`not_owner_host`, or `not_applicable` with no binding); a missing root is `unknown` (`storage_unavailable`), a stat error, invalid gbrain.yml or inconclusive check `unknown` (`ambiguous_storage`). `ghostPageNow` re-checks one page (the repair's recheck); `readGhostPages(engine, { sourceIds?, sampleLimit? })` is the counts-and-samples summary for doctor and the read-scope health op. Tests: `test/ghost-pages-6696.test.ts`.
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index 5c3a64d147..3137ef79ce 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -1260,6 +1260,12 @@ the same in one transaction):
database 72 h later without refusing it as a page whose file another page
records.
+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`.
+
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
through the alias. The twin's import-owned tags, chunks, versions and the facts and takes its
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index f50db6b34b..aba8f92baa 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. A 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. 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, soft-delete instead. 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: `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="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/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 39ac344787..a000ee5291 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1097,6 +1097,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.359.0', text: 'A `gbrain repair <kind> --apply` that the database refuses mid-run (deadlock 40P01, serialization failure 40001, a lost connection) now stops with a result (`stopped.reason` `database_contention` or `connection_lost`, the SQLSTATE in its message, what it applied, and the command that resumes from the refused item) instead of ending with an error and, under `--json`, no record of what it applied. A SIGTERM or SIGHUP (an outer timeout, a closed terminal) stops the apply before its next item with `stopped.reason: interrupted` and the same result; a second signal exits at once.' },
// #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.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index ba3ab9c660..3a60892bb2 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -453,15 +453,17 @@ export const sharedOriginReceipt = (sourceId: string, survivor: string | null) =
* same live pages must still record it; otherwise the delete refuses and the file is never removed as a fallback.
* [R9]: the receipt names a surviving slug only to the trusted local owner, or to a remote writer whose grant and visibility cover it.
*/
-async function validateSharedOrigin(tx: BrainEngine, row: WriteRequest, shared: SharedOrigin): Promise<string> {
+async function validateSharedOrigin(tx: BrainEngine, row: WriteRequest, shared: SharedOrigin, retentionPurge: boolean): Promise<string> {
+ const changed = retentionPurge ? sharedTombstoneChanged : sharedOriginChanged;
let canonicalPath: string;
try { canonicalPath = realpathSync(shared.target.path); }
- catch { throw sharedOriginChanged(row, 'the shared file was moved or removed'); }
+ catch { throw changed(row, 'the shared file was moved or removed'); }
const claimants = await findLiveFileClaimants(tx, { ...shared.target, canonicalPath });
- if (claimants.map(page => page.id).join(',') !== shared.claimants.map(page => page.id).join(',')) throw sharedOriginChanged(row, 'the pages recording the shared file changed');
+ if (claimants.map(page => page.id).join(',') !== shared.claimants.map(page => page.id).join(',')) throw changed(row, 'the pages recording the shared file changed');
const named: string[] = [];
for (const page of claimants) if (await slugDisclosable(tx, row.authority, page.slug)) named.push(page.slug);
const who = named.length ? `Another page of this source records the same file: ${named.join(', ')}.` : 'Another page of this source records the same file.';
+ if (retentionPurge) return `${who} The expired tombstone was removed database-only: the file and the surviving page are untouched, and no content tombstone was written.`;
return `${who} ${sharedOriginReceipt(row.source_id, named.length === 1 ? named[0]! : null)}`;
}
function sharedOriginChanged(row: WriteRequest, what: string): OperationError {
@@ -470,6 +472,15 @@ function sharedOriginChanged(row: WriteRequest, what: string): OperationError {
error.detail = 'shared_origin';
return error;
}
+/**
+ * #7311: the retention purge of a shared-origin tombstone whose census moved defers (a revision race to the purge, which
+ * retries it next run): the next preparation reads the claimants again, so a tombstone that now owns the file alone
+ * takes the normal purge path and its file is compared and removed, never left behind.
+ */
+function sharedTombstoneChanged(row: WriteRequest, what: string): OperationError {
+ return pageRefusal('revision_conflict', `The shared canonical file changed while the purge was prepared: ${what} before it published, so nothing was purged and the file was not removed. The next purge run reads the file's claimants again.`, row,
+ `Page ${row.slug}'s file in source ${row.source_id} was recorded by another live page when this retention purge was prepared.`, pageFix(row.source_id, row.slug));
+}
async function assertStillSyncExcluded(tx: BrainEngine, row: WriteRequest, excludedPath: string): Promise<void> {
if (matchesAnyGlob(excludedPath, await syncExcludePatterns(tx))) return;
@@ -494,10 +505,14 @@ async function prepareDeletePageMutation(engine: BrainEngine, row: WriteRequest,
// removal before the guarded hard-delete and receipt commit; failure rolls
// back to the prior row, and replay survives the eventual absence of that row.
const { file, excludedPath, shared } = await prepareDeleteFileTarget(engine, row, snapshot, purge, { allowMissing: purge || options.allowMissingFile, deleting: true, activePack: options.activePack, remote: row.authority.remote });
- // #6517: a purge tombstones content hashes source-wide, so a page whose file another live page records is only soft-deleted.
- if (shared && purge) {
- const error = pageRefusal('source_changed', 'The page\'s canonical file is shared with another live page, so a purge (which tombstones its content source-wide) was refused and nothing was removed, tombstoned or redacted. '
- + `Soft-delete it instead (gbrain delete ${row.slug} --source-id ${row.source_id} --expected-revision <rev>): the page is hidden, the file and the surviving page remain, and nothing is erased.`, row,
+ // #6517: an owner purge tombstones content hashes source-wide, so a page whose file another live page records is only
+ // soft-deleted. #7311: the retention purge of such a tombstone tombstones nothing, so it removes the row database-only.
+ const sharedRetention = shared !== null && purge && p.retention === true && snapshot.page.deleted_at != null;
+ if (shared && purge && !sharedRetention) {
+ const next = snapshot.page.deleted_at != null
+ ? 'The page is already soft-deleted (hidden; the file and the surviving page remain): the retention purge removes it database-only once it is older than the recovery window, with no content tombstone (gbrain pages purge-deleted --older-than 72h --yes, or the autopilot purge phase).'
+ : `Soft-delete it instead (gbrain delete ${row.slug} --source-id ${row.source_id} --expected-revision <rev>): the page is hidden, the file and the surviving page remain, and nothing is erased.`;
+ const error = pageRefusal('source_changed', `The page's canonical file is shared with another live page, so a purge (which tombstones its content source-wide) was refused and nothing was removed, tombstoned or redacted. ${next}`, row,
`Another live page of source ${row.source_id} records the file of ${row.slug}.`, pageFix(row.source_id, row.slug));
error.detail = 'shared_origin';
throw error;
@@ -520,9 +535,11 @@ async function prepareDeletePageMutation(engine: BrainEngine, row: WriteRequest,
...(preparedPurge && !preparedPurge.retention ? { afterCommit: async () => { appendPurgeCommitted(row.id); } } : {}),
...(preparedPurge?.derivedSlugs.length ? { additionalPageKeys: preparedPurge.derivedSlugs.map(slug => ({ sourceId: row.source_id, slug })) } : {}),
...(excludedPath !== null ? { databaseOnlyReason: 'sync_excluded' as const } : {}), ...(shared ? { databaseOnlyReason: 'shared_origin' as const } : {}),
- ...(shared ? { validate: async (tx: BrainEngine) => { prepared.databaseOnlyWarning = await validateSharedOrigin(tx, row, shared); } } : {}),
+ ...(shared ? { validate: async (tx: BrainEngine) => { prepared.databaseOnlyWarning = await validateSharedOrigin(tx, row, shared, sharedRetention); } } : {}),
apply: async tx => {
if (purge && excludedPath !== null) await assertStillSyncExcluded(tx, row, excludedPath);
+ // #7311: the tombstone forgets the survivor's file, as an origin_twin page has, so its purge writes no deletion marker for it.
+ if (preparedPurge && sharedRetention) return purgePageInTransaction(tx, row, { ...snapshot, page: { ...snapshot.page, source_path: null, source_uri: null } }, preparedPurge);
if (preparedPurge) return purgePageInTransaction(tx, row, snapshot, preparedPurge);
if (!noop) { await tx.createVersion(row.slug, source); await tx.softDeletePage(row.slug, source); }
return { status: 'soft_deleted', slug: row.slug, source_id: row.source_id, noop,
diff --git a/test/e2e/purge-shared-origin-tombstone-7311-postgres.test.ts b/test/e2e/purge-shared-origin-tombstone-7311-postgres.test.ts
new file mode 100644
index 0000000000..b9988652f5
--- /dev/null
+++ b/test/e2e/purge-shared-origin-tombstone-7311-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../purge-shared-origin-tombstone-7311.test.ts'));
diff --git a/test/purge-shared-origin-tombstone-7311.test.ts b/test/purge-shared-origin-tombstone-7311.test.ts
new file mode 100644
index 0000000000..33ffbdbd1f
--- /dev/null
+++ b/test/purge-shared-origin-tombstone-7311.test.ts
@@ -0,0 +1,207 @@
+/**
+ * #7311 / #7305: a soft-deleted page whose canonical file a live page of its source also records (a shared-origin
+ * tombstone: what `gbrain delete` of a duplicate-origin twin leaves, receipt `write_through.skipped: shared_origin`).
+ * Master refused every purge of it as a shared origin, the 72 h retention purge included, so the cycle purge phase
+ * failed every pass (`managed_purge_failed`), the tombstone parked after PURGE_PARK_LIMIT failures and global
+ * maintenance never stamped.
+ *
+ * Protects: the retention purge (the cycle purge phase, `gbrain pages purge-deleted`) removes such a tombstone
+ * database-only, like an `origin_twin` page: the page row and its facts go, the file and the surviving page (its row,
+ * facts and later fact inserts) are untouched, no content or fact tombstone is written and the phase reports ok; a
+ * tombstone parked by the old refusal is purged by `--retry-parked`; an owner `--purge` of the tombstone still refuses
+ * and names the retention purge instead of a soft delete; the census is revalidated under publication [#6517 R8]: a
+ * survivor that stopped recording the file defers the purge and the next run takes the normal path, which removes
+ * the file the tombstone now owns alone; an unmanaged brain's bulk purge removes only the tombstone row.
+ *
+ * PGLite always; Postgres through test/e2e/purge-shared-origin-tombstone-7311-postgres.test.ts. Synthetic content only.
+ */
+import { describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { OperationError, type OperationContext } from '../src/core/ops/contract.ts';
+import { runCycle } from '../src/core/cycle.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { readGitSourceHolds } from '../src/core/persistence/sync-holds.ts';
+import { purgeDeletedPagesCoordinated, purgePhaseStatus } from '../src/core/persistence/purge-deleted.ts';
+import { PURGE_PARK_LIMIT, readPurgeParks, recordPurgeFailure } from '../src/core/persistence/purge-parks.ts';
+import { installFaultHook } from '../src/core/persistence/fault-points.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';
+import { dropOriginIndex } from './helpers/origin-index.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+const commit = (root: string, message: string) => { git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message); };
+const OPTS = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };
+const FILE = 'notes/x-example.md', SURVIVOR = 'notes/x-example', TWIN = 'notes/x-example-copy';
+const BODY = 'A synthetic observation about acme-example, recorded once.';
+const BYTES = `---\ntype: note\ntitle: X Example\n---\n\n${BODY}\n`;
+const SURVIVOR_FACT = 'acme-example is a synthetic company', TWIN_FACT = 'acme-example ships a synthetic widget';
+const setup = ({ root }: { root: string }) => {
+ mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');
+ writeFileSync(join(root, FILE), BYTES); commit(root, 'notes');
+};
+const CONSENT_ENV = { GBRAIN_CONSENT: undefined };
+
+/** A fixture write as legacy data left it: managed persistence off around the statement. */
+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 pageRow = async (engine: BrainEngine, slug: string) => (await engine.executeRaw<Record<string, unknown>>(
+ `SELECT id, slug, deleted_at, source_path, source_uri, content_hash, compiled_truth, knowledge_revision::text AS revision, database_only_reason
+ FROM pages WHERE source_id='default' AND slug=$1`, [slug]))[0];
+const count = async (engine: BrainEngine, table: string) => Number((await engine.executeRaw<{ n: string }>(`SELECT count(*)::text AS n FROM ${table} WHERE source_id='default'`))[0]!.n);
+const facts = async (engine: BrainEngine, slug: string) => (await engine.executeRaw<{ fact: string }>(
+ "SELECT fact FROM facts WHERE source_id='default' AND source_markdown_slug=$1 ORDER BY id", [slug])).map(row => row.fact);
+const insertFact = (engine: BrainEngine, slug: string, fact: string) => engine.executeRaw(
+ "INSERT INTO facts(source_id, fact, entity_slug, visibility, source, source_markdown_slug) VALUES ('default', $1, 'companies/acme-example', 'world', 'test', $2)", [fact, slug]);
+const ageTombstones = (engine: BrainEngine) => raw(engine, () => engine.executeRaw("UPDATE pages SET deleted_at = now() - interval '73 hours' WHERE source_id='default' AND deleted_at IS NOT NULL"));
+async function refusal(fn: () => Promise<unknown>): Promise<OperationError> {
+ try { await fn(); } catch (error) { if (error instanceof OperationError) return error; throw error; }
+ throw new Error('expected a refusal');
+}
+
+/**
+ * The first sync imports FILE into SURVIVOR; a duplicate-origin twin TWIN (same content, recording the same file, as a
+ * sync before #6948 left it) holds a fact of its own, and SURVIVOR holds one too. `gbrain delete TWIN` keeps the file
+ * (`shared_origin`), leaving a tombstone that still records it.
+ */
+async function sharedTombstone(engine: BrainEngine, ctx: OperationContext): Promise<void> {
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ await dropOriginIndex(engine);
+ await raw(engine, async () => {
+ await engine.executeRaw(`INSERT INTO pages(source_id, slug, type, title, compiled_truth, timeline, frontmatter, content_hash, source_path)
+ SELECT source_id, $2, type, title, compiled_truth, timeline, frontmatter, content_hash, source_path FROM pages WHERE source_id='default' AND slug=$1`, [SURVIVOR, TWIN]);
+ await insertFact(engine, TWIN, TWIN_FACT);
+ await insertFact(engine, SURVIVOR, SURVIVOR_FACT);
+ });
+ const deleted = await submitPageMutation(ctx, { operation: 'delete_page', params: { slug: TWIN, expected_revision: (await pageRow(engine, TWIN))!.revision, request_id: randomUUID() } });
+ expect(deleted).toMatchObject({ status: 'soft_deleted', write_through: { written: false, skipped: 'shared_origin' } });
+ expect((await pageRow(engine, TWIN))!.source_path).toBe(FILE);
+}
+
+const snapshotBefore = async (engine: BrainEngine) => ({ survivor: await pageRow(engine, SURVIVOR), purges: await count(engine, 'page_purges'), factPurges: await count(engine, 'fact_purges') });
+/** The survivor, its file and its facts are untouched, nothing was tombstoned, and a later fact insert for it is not refused. */
+async function expectSurvivorIntact(engine: BrainEngine, root: string, before: Awaited<ReturnType<typeof snapshotBefore>>, managed = true): Promise<void> {
+ expect(await pageRow(engine, TWIN)).toBeUndefined();
+ if (managed) expect(await facts(engine, TWIN)).toEqual([]);
+ expect(await pageRow(engine, SURVIVOR)).toEqual(before.survivor);
+ expect(readFileSync(join(root, FILE), 'utf8')).toBe(BYTES);
+ expect(await facts(engine, SURVIVOR)).toEqual([SURVIVOR_FACT]);
+ expect(await count(engine, 'page_purges')).toBe(before.purges);
+ expect(await count(engine, 'fact_purges')).toBe(before.factPurges);
+ await (managed ? raw(engine, () => insertFact(engine, SURVIVOR, TWIN_FACT)) : insertFact(engine, SURVIVOR, TWIN_FACT));
+ expect(await facts(engine, SURVIVOR)).toEqual([SURVIVOR_FACT, TWIN_FACT]);
+}
+
+for (const backend of testBackends()) {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+ describe(`#7311 #7305 ${backend}: the retention purge of a shared-origin tombstone`, () => {
+ test('the cycle purge phase removes it database-only and reports ok; the survivor, its file and its facts stay', () => managedBrain(async ({ engine, ctx, root }) => {
+ await sharedTombstone(engine, ctx);
+ await ageTombstones(engine);
+ const before = await snapshotBefore(engine);
+ const phase = (await withEnv(CONSENT_ENV, () => runCycle(engine, { brainDir: root, phases: ['purge'], sourceId: 'default' }))).phases.find(p => p.phase === 'purge')!;
+ expect({ status: phase.status, blocked: phase.details.purged_pages_blocked, slugs: phase.details.purged_page_slugs }).toEqual({ status: 'ok', blocked: [], slugs: [TWIN] });
+ await expectSurvivorIntact(engine, root, before);
+ // The next full sync finds the file unchanged under the survivor: no hold, no deletion, no new page.
+ await performManagedSync(engine, { ...OPTS, full: true });
+ expect((await pageRow(engine, SURVIVOR))!.deleted_at).toBeNull();
+ expect(await pageRow(engine, TWIN)).toBeUndefined();
+ expect(((await readGitSourceHolds(engine, { sourceIds: ['default'] }))[0]?.holds ?? []).map(hold => hold.code)).toEqual([]);
+ expect(readFileSync(join(root, FILE), 'utf8')).toBe(BYTES);
+ }, { setup, databaseUrl }), 300_000);
+
+ test('a tombstone the old refusal parked is purged by --retry-parked', () => managedBrain(async ({ engine, ctx, root }) => {
+ await sharedTombstone(engine, ctx);
+ await ageTombstones(engine);
+ const [row] = await engine.executeRaw<{ deleted_us: string }>(
+ "SELECT floor(extract(epoch FROM deleted_at)*1000000)::bigint::text AS deleted_us FROM pages WHERE source_id='default' AND slug=$1", [TWIN]);
+ for (let i = 0; i < PURGE_PARK_LIMIT; i++) await recordPurgeFailure(engine, { source_id: 'default', slug: TWIN, deleted_us: row!.deleted_us, code: 'source_changed',
+ reason: "The page's canonical file is shared with another live page, so a purge (which tombstones its content source-wide) was refused" });
+ const before = await snapshotBefore(engine);
+ const automatic = await purgeDeletedPagesCoordinated(engine, 72, { automatic: true });
+ expect({ count: automatic.count, parked: automatic.parked, status: purgePhaseStatus(automatic) }).toEqual({ count: 0, parked: 1, status: 'warn' });
+ const retried = await purgeDeletedPagesCoordinated(engine, 72, { retryParked: true });
+ expect({ count: retried.count, slugs: retried.slugs, blocked: retried.blocked, error: retried.error, status: purgePhaseStatus(retried) })
+ .toEqual({ count: 1, slugs: [TWIN], blocked: [], error: undefined, status: 'ok' });
+ expect((await readPurgeParks(engine)).size).toBe(0);
+ await expectSurvivorIntact(engine, root, before);
+ }, { setup, databaseUrl }), 300_000);
+
+ test('an owner --purge of the tombstone refuses, names the retention purge and changes nothing', () => managedBrain(async ({ engine, ctx, root }) => {
+ await sharedTombstone(engine, ctx);
+ const before = { twin: await pageRow(engine, TWIN), ...await snapshotBefore(engine) };
+ const error = await refusal(async () => submitPageMutation(ctx, { operation: 'delete_page',
+ params: { slug: TWIN, purge: true, expected_revision: (await pageRow(engine, TWIN))!.revision, request_id: randomUUID() } }));
+ expect(error.code).toBe('source_changed');
+ expect(error.message).toContain('shared with another live page');
+ expect(error.message).not.toContain('Soft-delete it instead');
+ expect(error.message).toContain('already soft-deleted');
+ expect(error.message).toContain('gbrain pages purge-deleted --older-than 72h --yes');
+ expect(await pageRow(engine, TWIN)).toEqual(before.twin);
+ expect(await pageRow(engine, SURVIVOR)).toEqual(before.survivor);
+ expect(await count(engine, 'page_purges')).toBe(before.purges);
+ expect(readFileSync(join(root, FILE), 'utf8')).toBe(BYTES);
+ }, { setup, databaseUrl }), 300_000);
+
+ test('[#6517 R8] a survivor that stops recording the file during preparation defers the purge; the next run removes the file the tombstone owns alone', () => managedBrain(async ({ engine, ctx, root }) => {
+ await sharedTombstone(engine, ctx);
+ await ageTombstones(engine);
+ let disturbed = false;
+ installFaultHook(async (point, detail) => {
+ if (point !== 'consumer:prepared' || detail.operation !== 'delete_page' || disturbed) return;
+ disturbed = true;
+ await raw(engine, () => engine.executeRaw("UPDATE pages SET source_path='notes/elsewhere-example.md' WHERE source_id='default' AND slug=$1", [SURVIVOR]));
+ });
+ let first: Awaited<ReturnType<typeof purgeDeletedPagesCoordinated>>;
+ try { first = await purgeDeletedPagesCoordinated(engine, 72); } finally { installFaultHook(undefined); }
+ expect(disturbed).toBe(true);
+ expect({ count: first.count, deferred: first.deferred, failed: first.failed, error: first.error, codes: first.blocked.map(b => b.code) })
+ .toEqual({ count: 0, deferred: 1, failed: 0, error: undefined, codes: ['revision_conflict'] });
+ expect(first.blocked[0]!.reason).toContain('shared canonical file changed');
+ expect((await pageRow(engine, TWIN))!.source_path).toBe(FILE);
+ expect(readFileSync(join(root, FILE), 'utf8')).toBe(BYTES);
+ // The tombstone is the file's only claimant now: the normal purge path compares and removes the file, never leaving it behind.
+ const second = await purgeDeletedPagesCoordinated(engine, 72);
+ expect({ count: second.count, blocked: second.blocked, error: second.error }).toEqual({ count: 1, blocked: [], error: undefined });
+ expect(await pageRow(engine, TWIN)).toBeUndefined();
+ expect(existsSync(join(root, FILE))).toBe(false);
+ }, { setup, databaseUrl }), 300_000);
+ });
+
+ describe(`#7311 ${backend}: an unmanaged brain's bulk purge of a shared-origin tombstone`, () => {
+ test('removes only the tombstone row; the survivor, its file and its facts stay', async () => {
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-7311-'));
+ try {
+ await withEnv({ DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {
+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);
+ try {
+ setup({ root });
+ await engine.executeRaw("UPDATE sources SET local_path=$1 WHERE id='default'", [root]);
+ await dropOriginIndex(engine);
+ for (const slug of [SURVIVOR, TWIN]) {
+ await engine.putPage(slug, { type: 'note', title: 'X Example', compiled_truth: BODY, timeline: '', frontmatter: {}, content_hash: 'x-example' }, { sourceId: 'default' });
+ await engine.executeRaw("UPDATE pages SET source_path=$2 WHERE source_id='default' AND slug=$1", [slug, FILE]);
+ }
+ await insertFact(engine, TWIN, TWIN_FACT);
+ await insertFact(engine, SURVIVOR, SURVIVOR_FACT);
+ await engine.softDeletePage(TWIN, { sourceId: 'default' });
+ await engine.executeRaw("UPDATE pages SET deleted_at = now() - interval '73 hours' WHERE source_id='default' AND slug=$1", [TWIN]);
+ const before = await snapshotBefore(engine);
+ const result = await purgeDeletedPagesCoordinated(engine, 72, { automatic: true });
+ expect({ count: result.count, slugs: result.slugs, blocked: result.blocked, status: purgePhaseStatus(result) }).toEqual({ count: 1, slugs: [TWIN], blocked: [], status: 'ok' });
+ await expectSurvivorIntact(engine, root, before, false);
+ } finally { await close(); }
+ });
+ } finally { rmSync(root, { recursive: true, force: true }); }
+ }, 300_000);
+ });
+}
diff --git a/test/repair-legacy-twins-6885.test.ts b/test/repair-legacy-twins-6885.test.ts
index 731163b4d6..bf91e99762 100644
--- a/test/repair-legacy-twins-6885.test.ts
+++ b/test/repair-legacy-twins-6885.test.ts
@@ -309,23 +309,27 @@ for (const backend of testBackends()) describe(`#6885 repair legacy-twins (${bac
expect((await pageRow(f.sourceId, f.ids.twin))!.deleted).toBe(false);
}), 180_000);
- test('why the repair exists: a hand delete of the twin withdraws the file, and a tombstone that keeps its origin is never purged', () => fixture(async f => {
+ test('why the repair exists: a hand delete of the twin withdraws the file, and a tombstone that keeps its origin is purged database-only (#7311)', () => fixture(async f => {
const bytes = readFileSync(join(f.root, FILE), 'utf8');
const ctx = { engine, sourceId: f.sourceId, remote: false, config: { engine: engine.kind, embedding_disabled: true } as never, dryRun: false, logger } as OperationContext;
// The legacy page records nothing, so the twin's file has no other claimant: delete_page removes it (#6885).
await submitPageMutation(ctx, { operation: 'delete_page', params: { slug: TWIN, expected_revision: (await pageRow(f.sourceId, f.ids.twin))!.revision, request_id: randomUUID() } });
expect(existsSync(join(f.root, FILE))).toBe(false);
- // Put the file back and let the legacy page record it, but leave the twin's tombstone recording it too: the retention purge refuses it as a shared origin, every run.
+ // Put the file back and let the legacy page record it, but leave the twin's tombstone recording it too. Master refused
+ // its retention purge as a shared origin, every run (#7311); it is removed database-only: the file and the legacy page stay.
writeFileSync(join(f.root, FILE), bytes);
await raw(async () => {
await engine.executeRaw('UPDATE pages SET source_path=$2 WHERE id=$1', [f.ids.legacy, FILE]);
await engine.executeRaw('UPDATE pages SET source_path=$2 WHERE id=$1', [f.ids.twin, FILE]);
await engine.executeRaw("UPDATE pages SET deleted_at=now() - interval '73 hours' WHERE id=$1", [f.ids.twin]);
});
+ const legacyBefore = await pageRow(f.sourceId, f.ids.legacy);
+ const purges = Number((await engine.executeRaw<{ n: string }>('SELECT count(*)::text AS n FROM page_purges WHERE source_id=$1', [f.sourceId]))[0]!.n);
const purged = await purgeDeletedPagesCoordinated(engine, 72);
- expect(purged.count).toBe(0);
- expect(purged.blocked.map(entry => ({ slug: entry.slug, code: entry.code }))).toEqual([{ slug: TWIN, code: 'source_changed' }]);
- expect(purged.blocked[0]!.reason).toContain('shared with another live page');
+ expect({ count: purged.count, blocked: purged.blocked, error: purged.error }).toEqual({ count: 1, blocked: [], error: undefined });
+ expect(await pageRow(f.sourceId, f.ids.twin)).toBeUndefined();
+ expect(await pageRow(f.sourceId, f.ids.legacy)).toEqual(legacyBefore);
+ expect(Number((await engine.executeRaw<{ n: string }>('SELECT count(*)::text AS n FROM page_purges WHERE source_id=$1', [f.sourceId]))[0]!.n)).toBe(purges);
expect(readFileSync(join(f.root, FILE), 'utf8')).toBe(bytes);
}), 180_000);