Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix: hold every derived retirement 30 days, version before retire (GBRA-161 PR 0)
garrytan320d76efa577
diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsvindex dac5445d2d..dbff95f368 100644--- a/docs/architecture/canonical-writers.tsv+++ b/docs/architecture/canonical-writers.tsv@@ -2,6 +2,7 @@# path write-reference ceiling enforcement boundary review rationalesrc/core/persistence/activation.ts 0 coordinator Trusted private administration requires explicit quiescence and durable refusal records before enabling managed canonical writer enforcement.src/core/persistence/canonical-projections.ts 10 coordinator Facts, takes, timeline, chunks and aliases install within the guarded canonical publication transaction before its receipt commits; a take whose claim changed in place loses its stored resolution there, and a fence row without resolution cells keeps it.+src/core/persistence/derived-retirement-hold.ts 2 contract retireDerivedPages versions, soft-deletes and stamps retired_by/retired_at on derived pages (unmanaged extract_atoms retirement) inside maintenanceTransaction behind the canonical table trigger; it never revives or rewrites content, and the purge hold it defines only keeps rows longer.src/core/persistence/links-maintenance.ts 1 coordinator Managed extract --stale and post-sync extraction add only the coordinator's unrecorded canonical timeline tuples inside a revision-bound withCoordinatedWrite transaction that also replaces the page's derived links and stamps its watermark.src/core/extract-takes-from-pages.ts 0 coordinator Managed bootstrap submits one revision-checked put_page per source page so its complete takes fence and projected rows commit together; unmanaged writes retain the md-first helper.src/core/persistence/origin-guard.ts 2 engine_guard #6948 bindOrigin records a page origin (and drops an origin_twin marker) only after assertOriginUnclaimed holds the origin advisory lock inside the caller's engine.transaction(); callers are the guarded publication applies and repairs.@@ -45,7 +46,7 @@ src/core/company-brain/demo.ts 2 isolated_eval Fictional source registration usesrc/core/company-brain/profile.ts 2 engine_guard Company-profile legacy deletes use withCompanyBrainSource to lock and validate source incarnation, path, receipt and policy; calls without that context retain engine guards, and managed sync routes to the coordinator before this legacy path. Direct importFromContent calls without prepare refuse on managed brains before any write (assertUnmanagedCanonicalWriter).src/core/company-brain/runtime.ts 1 projection Only source policy metadata advances under the company-source lock and brain/source row locks; the same transaction validates immutable approval and creates a receipt with source-incarnation and managed owner/topology fences, without source-file writes.src/core/cycle/drift.ts 1 coordinator A managed brain preflights maintenance authority before judge spend and publishes the report through publishMaintenancePage; the unmanaged putPage stays behind the canonical table trigger.-src/core/cycle/extract-atoms.ts 3 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.+src/core/cycle/extract-atoms.ts 2 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.src/core/cycle/extract-facts.ts 7 coordinator Managed and unmanaged reconciliation key rows by fence row number, update matched rows in place, expire and detach removed rows instead of deleting them, and expire fence-owned rows of soft-deleted pages; on a managed brain each changed page publishes a managed_maintenance_fence_facts request and each soft-deleted page a managed_maintenance_deleted_page_facts_expire request, whose preparers replan or recheck the deletion under the page key inside the coordinator publication.src/core/cycle/extract-atoms-page-state.ts 1 engine_guard Atom completion updates and cardinality checks share one transaction; managed canonical SQL remains fenced and scan/failure bookkeeping is stored separately.src/core/cycle/extract-takes.ts 4 coordinator On a managed brain the DB-source walk publishes each fenced page that needs a change as a managed_maintenance_takes_reextract request whose preparer re-reads the page under its key and writes the canonical projection's superseded_by while leaving resolution columns untouched; the file walk and unmanaged brains keep direct SQL, which the trigger refuses on managed brains. Stale-row pruning deletes only takes whose rows left a cleanly parsed fence on a live page in the same source.diff --git a/docs/architecture/key-files/memory-purge.md b/docs/architecture/key-files/memory-purge.mdindex abbaa85577..00ebd4406f 100644--- a/docs/architecture/key-files/memory-purge.md+++ b/docs/architecture/key-files/memory-purge.md@@ -23,6 +23,7 @@ User-facing contract: [expire versus purge](../../guides/memory-boundaries.md#pu- Withdrawn-claim refusal on `remember` (`persistence/memory-mutations.ts`, `memory-prepare.ts`) — admission refuses a withdrawn claim (`fact_withdrawn`, `FACT_WITHDRAWN_MESSAGE`/`_SUGGESTION` in `src/core/facts/withdrawal.ts`) before a request exists, and preparation re-checks it; `writeFailureDiagnostic` allowlists that prefix, so a failed receipt and `get_write_request` name it. `replaces` accepts a target saved without an entity (links it by supersession). Test: `test/remember-withdrawn-claim.test.ts`. (R1, Cat 40 Hard.) The refusal carries an additive `withdrawn` object (`factWithdrawnRefusal` in `facts/single-prepare.ts`, from `fact_withdrawals` only: the named entity's row over `all_entities`, then the newest, omitted when the caller cannot read the forgotten rows); `withdrawalFailureDetail`/`withdrawnFromDetail` in `facts/withdrawal.ts` keep it in the failed receipt's `error_detail` for `get_write_request` and replay. Tests: `test/withdrawn-detail.test.ts`, `test/e2e/withdrawn-detail-postgres.test.ts`.- `src/core/persistence/purge-deleted.ts` — `purgeDeletedPagesCoordinated` backs the cycle `purge` phase, the purge job, `purge_deleted_pages` and `gbrain pages purge-deleted`. Unmanaged brains keep the engine bulk delete, after the belief-ledger expiry of recorded sources' tombstones: each is its own transaction and item (ItemRun site `purge.recorded_tombstones`), a run-scoped failure or a systemic run stops the purge, and any other failure lists the tombstone in `blocked` with its classified code, counts it in `failed` (no `error`, so the phase warns) and keeps it out of the bulk delete (`purgeDeletedPages` `excludeIds`); a content failure counts toward the same park as the managed purge, a transient one is retried next run, and parked tombstones are skipped as `purge_parked` unless `retryParked` (the unmanaged preview excludes them too). A managed brain purges each tombstone older than the window (skipping archived sources, which the source lifecycle purges) through `delete_page` with `purge: true` and the internal `retention: true` bound to its revision (retention is not an owner purge; see [belief ledger](belief-ledger.md)). Writer state is read once per run (`writerOnboardingPreflight`): a source whose writer is `recovery_required` submits nothing and its tombstones are listed in `blocked` as `writer_not_active` (counted in `inactive`). Revision races are deferred to the next run; a parked tombstone (`purge-parks.ts`) is skipped as `purge_parked` (counted in `parked`) unless `retryParked`, and any other failure is listed in `blocked` and sets `error`. `selectPurgeCandidates` is the one eligibility selector (preview, consent, `purge_deleted_pages` op, run); #6884: the run submits only while the writer has outstanding-request room (`readOutstandingRoom` in `journal.ts`, at `persistence.capacity.background_pause_pct` of the cap for a background run); the rest, and the rest after a `queue_capacity` refusal, is `blocked` as `write_capacity_deferred` and counted in `capacity_deferred`, never a failure or a park. `purgePhaseStatus`/`purgePhaseNote` shape the cycle purge phase (fail on `error`; warn on `writer_not_active`, parked, capacity-deferred or an unmanaged `failed` tombstone). The engine bulk delete (`engine-sql/pages.ts` `purgeDeletedPages`) also deletes, in its transaction, the purged pages' stagings (by source and slug) and the segment texts only their manifests referenced. Tests: `test/managed-writers-w3.test.ts`, `test/purge-deleted-parks.test.ts`, `test/purge-deleted-capacity-6884.test.ts`, `test/pathological/a49-unmanaged-purge-tombstones.test.ts`.+- `src/core/persistence/derived-retirement-hold.ts` — GBRA-161: the purge hold for every derived retirement. `DERIVED_RETIRED_BY` lists the `retired_by` stamps derived writers put on the pages they retire (extract-atoms, managed-reextract, stale-atoms, life-chronicle); `derivedRetirementPurgeHold(alias)` keeps a stamped page out of every purge route (engine bulk purge and its preview, the coordinated selection and delete) until `DERIVED_RETIREMENT_HOLD_DAYS` (30) after `deleted_at` (the database clock, never the `retired_at` text); `retireDerivedPages` versions, soft-deletes and stamps a batch in one attributed transaction (unmanaged extract_atoms). `assertRetirementStampUnchanged` is the page preparer's refusal (`reserved_frontmatter_key`) of a remote write that adds or changes one of `RESERVED_RETIREMENT_KEYS`. An explicit `gbrain delete --purge` is not held.- `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`.diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 395cecfe2d..e30c2c4e7d 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -3423,6 +3423,14 @@ Reasons: `rename_source_changed`.|---|---|---|---|---|---|---|| This command needs the brain's local database, and this install is a thin client of a remote brain. | Only the operator of the brain host can change what blocks this. | Only the brain host's operator can resolve this. Tell the user the message and run `gbrain doctor --json` on the brain host. | host_admin | `gbrain doctor --json` | 1 | no |+### reserved_frontmatter_key++<a id="reserved_frontmatter_key"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A remote page write tried to add or change a frontmatter key only a trusted derived writer sets (`retired_by`, `retired_at`, `retired_generation`); nothing was written. | Those keys mark a page a derived writer retired, which the purge holds for 30 days and the repairs treat as machine-owned. A remote caller that could set them could make a page look machine-retired. Carrying the stored value unchanged, or dropping the key, is allowed. | Remove the key from the frontmatter (or keep the stored value) and write the page again. | agent | `repeat the read that failed` | 1 | no |+### reset_upstream_refused<a id="reset_upstream_refused"></a>diff --git a/scripts/check-engine-sql-dynamic.ts b/scripts/check-engine-sql-dynamic.tsindex 249aaeb8ed..d322888146 100644--- a/scripts/check-engine-sql-dynamic.ts+++ b/scripts/check-engine-sql-dynamic.ts@@ -76,6 +76,7 @@ const VETTED_BUILDERS: Record<string, string> = {privateProvenanceFilterFragment: 'src/core/search/private-visibility.ts: constant fact-provenance visibility predicate over a caller alias',stagingNeedsTextSql: 'src/core/page-body/schema.ts: constant live-staging text-reference EXISTS predicate over a caller text alias; no values (Wave B purge)',atomRetirementPurgeHold: 'src/core/persistence/atom-retirement-hold.ts: constant #7013 restorable-atom purge-hold predicate over a caller pages alias; no values',+ derivedRetirementPurgeHold: 'src/core/persistence/derived-retirement-hold.ts: constant GBRA-161 derived-retirement purge-hold predicate over a caller pages alias; no values',rankingLinkSql: 'src/core/link-ranking-policy.ts: constant non-ranking link-type predicate (code-constant type names) over a caller alias',vectorLiteralSql: 'src/core/engine-sql/facts.ts: master\'s inlined vector literal; toPgVectorLiteral output (numbers joined by commas) + a ::vector/::halfvec constant',temporalLinkJoinSql: 'src/core/link-validity.ts: constant LEFT JOIN onto link_relationships over a caller alias; scope is one of two literals',diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex f798a11d99..2ea34c8e27 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1069,6 +1069,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;// #7172. `since` is restamped at the merge slot.{ since: '0.60.346.0', text: 'A managed put_page, edit_page, add_timeline_entry, add_tag or remove_tag, managed import or sync whose passages need more than 5 vector-index writes (a passage carrying a vector, inserted or renumbered) commits the page first and finishes its passages in post-commit transactions of at most 5 vector-index writes each, instead of writing them all inside the publication, where a slow index could end it 57014 `write_interrupted`. Search sees the page once the last step seals it; until then its receipt says `searchable: "pending"`, and `gbrain projections drain` finishes a page whose writer stopped. A passage whose text is unchanged keeps its row and vector when an entry above it moves it to another index.' },{ since: '0.60.346.0', text: 'The embedding step after a managed write no longer re-embeds every passage of a page whose stored embedding signature is missing or in an older format: a passage whose recorded embedding input is still current keeps its vector and the page signature is restamped, so only passages whose text changed reach the embedding provider.' },+ { since: 'TBD', text: 'Pages a derived writer retires (an atom a completed re-extraction no longer produces, a chronicle event a re-judged meeting no longer yields, an atom `gbrain repair stale-atoms` retired) now stay restorable for 30 days instead of 72 hours: the purge, automatic and `gbrain pages purge-deleted` alike, skips a page stamped `retired_by` extract-atoms, managed-reextract, stale-atoms or life-chronicle until 30 days after its deletion, and `gbrain restore <slug>` brings it back with its body. The unmanaged extract_atoms and chronicle retirements now save a page version first and stamp the page. A remote page write that adds or changes `retired_by`, `retired_at` or `retired_generation` is refused with `reserved_frontmatter_key`; carrying the stored value unchanged, or dropping the key, still writes.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/chronicle/publish.ts b/src/core/chronicle/publish.tsindex 4fa8c5dc1a..61891026ee 100644--- a/src/core/chronicle/publish.ts+++ b/src/core/chronicle/publish.ts@@ -250,6 +250,7 @@ export async function publishChronicleGeneration(engine: BrainEngine, opts: {if (reason) throw supersededError(reason);const live = await tx.readPageSnapshot(event.slug, { sourceId });if (!live || !owned.has(String(live.page.content_hash ?? ''))) return;+ await tx.createVersion(event.slug, { sourceId, preimage: live });await tx.softDeletePage(event.slug, { sourceId });await stampRetired(tx, sourceId, event.slug);});diff --git a/src/core/cycle/extract-atoms.ts b/src/core/cycle/extract-atoms.tsindex 130fb4ac66..ebfa604659 100644--- a/src/core/cycle/extract-atoms.ts+++ b/src/core/cycle/extract-atoms.ts@@ -95,7 +95,7 @@ import { isOpPageSlug } from '../ops/context.ts';import type { WriteReceipt } from '../persistence/types.ts';import { acceptedPendingReceipt } from '../persistence/accepted-pending.ts';import { AtomPageStateError, completeAtomReceipts, MAX_DETERMINISTIC_FAILURES, readAtomPageIdentity, writeAtomPageState, type AtomPageInput } from './extract-atoms-page-state.ts';-import { maintenanceTransaction } from '../persistence/attribution.ts';+import { ATOM_RETIRED_BY_EXTRACT, retireDerivedPages } from '../persistence/derived-retirement-hold.ts';import { deriveTrust, lowerDerivedPage } from '../trust/taint.ts';import { derivedGateInput } from '../trust/derived-gate.ts';import { ATOM_TYPES, ATOMS_RESPONSE_SCHEMA } from './extract-atoms-schema.ts';@@ -1476,7 +1476,7 @@ async function completeUnmanagedItem(engine: BrainEngine, sourceId: string,* Soft-delete a source's atoms from earlier extractions (a different or* provisional source_hash) that the current, completed extraction did not* re-produce. Imported atoms (`imported_from`) and managed atoms are left- * alone. Best-effort: a failure leaves duplicates, never loses current atoms.+ * alone; retired atoms are held 30 days. Best-effort: a failure leaves duplicates, never loses current atoms.*/async function retireStaleAtoms(engine: BrainEngine,@@ -1497,7 +1497,7 @@ async function retireStaleAtoms([sourceId, origin.value, hash16, currentSlugs],);const stale = rows.map(r => r.slug);- for (let i = 0; i < stale.length; i += 500) await maintenanceTransaction(engine, tx => tx.softDeletePages(stale.slice(i, i + 500), { sourceId }));+ await retireDerivedPages(engine, sourceId, stale, ATOM_RETIRED_BY_EXTRACT);return stale;} catch (err) {console.error(`[extract_atoms] stale atom cleanup failed for ${origin.value} (non-fatal): ${err instanceof Error ? err.message : String(err)}`);diff --git a/src/core/engine-sql/pages.ts b/src/core/engine-sql/pages.tsindex 412ce83a47..27202f880f 100644--- a/src/core/engine-sql/pages.ts+++ b/src/core/engine-sql/pages.ts@@ -33,6 +33,7 @@ import type { ScopedReadRunner } from './cjk-search.ts';import { compileRowNormalizer } from './normalize.ts';import { stagingNeedsTextSql } from '../page-body/schema.ts';import { atomRetirementPurgeHold } from '../persistence/atom-retirement-hold.ts';+import { derivedRetirementPurgeHold } from '../persistence/derived-retirement-hold.ts';import { createPageVersion } from '../page-state/versions.ts';import { renderFragment, sqlFragment, trustedSql } from './fragment.ts';import { frontmatterWhereFragment } from '../search/frontmatter-where.ts';@@ -323,7 +324,8 @@ export async function purgeDeletedPages(AND deleted_at < now() - (${hours} || ' hours')::intervalAND NOT EXISTS (SELECT 1 FROM op_checkpoints dg WHERE dg.op = 'sync-identity-downgrade' AND dg.fingerprint = pages.id::textAND dg.completed_keys->0->>'disposition' IS NULL AND pages.deleted_at = (dg.completed_keys->0->>'old_deleted_at')::timestamptz)- AND ${trustedSql(atomRetirementPurgeHold('pages'))}${excluded}+ AND ${trustedSql(atomRetirementPurgeHold('pages'))}+ AND ${trustedSql(derivedRetirementPurgeHold('pages'))}${excluded}ORDER BY deleted_at ASC, slug ASC`);const pages = rows.map((r) => ({@@ -345,7 +347,9 @@ export async function purgeDeletedPages(AND NOT EXISTS (SELECT 1 FROM op_checkpoints dg WHERE dg.op = 'sync-identity-downgrade' AND dg.fingerprint = pages.id::textAND dg.completed_keys->0->>'disposition' IS NULL AND pages.deleted_at = (dg.completed_keys->0->>'old_deleted_at')::timestamptz)-- #7013: a restorable re-extraction retirement waits out its hold (atomRetirementPurgeHold).- AND ${trustedSql(atomRetirementPurgeHold('pages'))}${excluded}+ AND ${trustedSql(atomRetirementPurgeHold('pages'))}+ -- GBRA-161: every derived retirement waits out its hold (derivedRetirementPurgeHold).+ AND ${trustedSql(derivedRetirementPurgeHold('pages'))}${excluded}RETURNING slug, source_id`);if (rows.length) await tx.run(sqlFragment`DELETE FROM page_body_stagings s USING unnest(${rows.map(r => r.source_id)}::text[], ${rows.map(r => r.slug)}::text[]) AS d(source_id, slug)diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 693f7b7219..bc682a47a4 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -288,6 +288,7 @@ export const CODES = {file_too_large: { class: 'caller', summary: "The file is over the page size limit (24 MiB for a Markdown page, 5 MB for a code file), so it was not imported.", why: "Every page under the limit is stored, chunked and searchable whatever its size; the limit bounds what one page may hold in this release. The same bytes refuse on every retry. A smaller page refused by an MCP or HTTP transport is a different refusal.", docs: 'docs/guides/write-refusals.md#file_too_large', suggestion: 'Leave the file out of the source (sync.exclude), or, if it must be in the brain, split it into files under the limit; then sync or import again. Never split a page under the limit.' },follow_approval_required: { class: 'caller', summary: "Following a brain's shared skills needs the user's explicit follow approval.", docs: 'docs/guides/shared-brain-skills.md#approve-publication-following-and-editing-separately' },forget_requires_owner: { class: 'consent', exit: 3, actor: 'user', summary: "A caller asked to forget a fact (remote forget) or remove a take (takes_remove) more trusted than its own writes, so nothing was removed and the owner was asked instead.", why: "Lower-trust writers cannot overwrite, supersede or forget what the owner confirmed or curated (#5575 guarded supersession). The request became a trust proposal the owner can accept on the brain host; forget's frozen expired meaning is unchanged because nothing expired.", docs: 'docs/guides/error-codes.md#forget_requires_owner', suggestion: 'Do not retry. Tell the user the fact or take needs their decision and give them the command in fix (gbrain trust confirm <proposal_ref> on the brain host).' },+ reserved_frontmatter_key: { class: 'caller', summary: 'A remote page write tried to add or change a frontmatter key only a trusted derived writer sets (`retired_by`, `retired_at`, `retired_generation`); nothing was written.', why: 'Those keys mark a page a derived writer retired, which the purge holds for 30 days and the repairs treat as machine-owned. A remote caller that could set them could make a page look machine-retired. Carrying the stored value unchanged, or dropping the key, is allowed.', suggestion: 'Remove the key from the frontmatter (or keep the stored value) and write the page again.' },frontmatter_slug_conflict: { class: 'caller', summary: "The file's frontmatter `slug:` names a different page than its path does.", why: "The path decides a file's page; a conflicting declared slug would overwrite or fork another page, so the file is refused until one of them changes.", suggestion: 'Remove the `slug:` line or make it match the path, then commit and sync again.' },full_resync_required: { class: 'retryable', summary: "The catalog cursor is invalid or expired." },gate_failed: { class: 'caller', summary: "The eval gate found retrieval regressions or correctness below its thresholds." },diff --git a/src/core/persistence/derived-retirement-hold.ts b/src/core/persistence/derived-retirement-hold.tsnew file mode 100644index 0000000000..43e7f6485b--- /dev/null+++ b/src/core/persistence/derived-retirement-hold.ts@@ -0,0 +1,64 @@+/**+ * GBRA-161 PR 0: every derived retirement stays restorable for `DERIVED_RETIREMENT_HOLD_DAYS` before the purge may+ * remove it. A derived writer that retires a page it generated (an atom an extraction no longer produces, a chronicle+ * event a re-judged depth page no longer yields, an atom `gbrain repair stale-atoms` retired) versions it, soft-deletes+ * it and stamps `retired_by` with one of `DERIVED_RETIRED_BY` in the same transaction. The 72 h purge used to remove+ * those rows, and their `page_versions` with them (ON DELETE CASCADE), before anyone could notice a wrong retirement.+ *+ * The window runs from `deleted_at` (the database clock), never from the `retired_at` text. Remote page writes cannot+ * add or change the stamp keys (`RESERVED_RETIREMENT_KEYS`; the page preparer refuses with `reserved_frontmatter_key`). An+ * explicit `gbrain delete --purge` is not held. No engine-sql imports, so `engine-sql/pages.ts` may import it.+ */+import type { BrainEngine } from '../engine.ts';+import { OperationError } from '../ops/contract.ts';+import { maintenanceTransaction } from './attribution.ts';++/** The `retired_by` stamps derived writers put on the pages they retire. */+export const DERIVED_RETIRED_BY = ['extract-atoms', 'managed-reextract', 'stale-atoms', 'life-chronicle'] as const;+export type DerivedRetiredBy = typeof DERIVED_RETIRED_BY[number];++/** The unmanaged extract_atoms retirement of atoms a completed re-extraction did not reproduce. */+export const ATOM_RETIRED_BY_EXTRACT: DerivedRetiredBy = 'extract-atoms';++/** Days after `deleted_at` that the purge keeps a derived retirement. */+export const DERIVED_RETIREMENT_HOLD_DAYS = 30;++/** Frontmatter keys only a trusted derived writer sets; a remote page write never carries them. */+export const RESERVED_RETIREMENT_KEYS = ['retired_by', 'retired_at', 'retired_generation'] as const;++const stamps = DERIVED_RETIRED_BY.map(stamp => `'${stamp}'`).join(',');++/** SQL predicate for a purge scan over `pages` aliased `alias`: the page is not a derived retirement inside its hold. */+export function derivedRetirementPurgeHold(alias: string): string {+ return `NOT (COALESCE(${alias}.frontmatter->>'retired_by','') IN (${stamps})+ AND ${alias}.deleted_at > now() - interval '${DERIVED_RETIREMENT_HOLD_DAYS} days')`;+}++/** Stamps pages the caller soft-deleted in this transaction as retired by `retiredBy`. */+async function stampDerivedRetirement(tx: BrainEngine, sourceId: string, slugs: readonly string[], retiredBy: DerivedRetiredBy): Promise<void> {+ if (!slugs.length) return;+ await tx.executeRaw(`UPDATE pages SET frontmatter=frontmatter||jsonb_build_object('retired_by',$1::text,'retired_at',$2::text)+ WHERE source_id=$3 AND slug=ANY($4::text[]) AND deleted_at IS NOT NULL`, [retiredBy, new Date().toISOString(), sourceId, [...slugs]]);+}++/** Versions, soft-deletes and stamps `slugs` as retired by `retiredBy`, one attributed transaction per 500 pages. */+export async function retireDerivedPages(engine: BrainEngine, sourceId: string, slugs: readonly string[], retiredBy: DerivedRetiredBy): Promise<void> {+ for (let i = 0; i < slugs.length; i += 500) {+ const batch = slugs.slice(i, i + 500);+ await maintenanceTransaction(engine, async tx => {+ for (const slug of batch) await tx.createVersion(slug, { sourceId });+ await tx.softDeletePages(batch, { sourceId });+ await stampDerivedRetirement(tx, sourceId, batch, retiredBy);+ });+ }+}++/** Refuses a remote write that adds or changes a stamp key; carrying the stored value unchanged, or dropping it, passes. */+export function assertRetirementStampUnchanged(slug: string, incoming: Record<string, unknown> | undefined, stored: Record<string, unknown> | undefined): void {+ const changed = RESERVED_RETIREMENT_KEYS.filter(key => incoming && Object.hasOwn(incoming, key)+ && JSON.stringify(incoming[key]) !== JSON.stringify(stored?.[key]));+ if (!changed.length) return;+ throw new OperationError('reserved_frontmatter_key',+ `A remote write cannot set ${changed.join(', ')} on ${slug}: only a trusted derived writer stamps a retirement, so nothing was written.`,+ `Remove ${changed.join(', ')} from the frontmatter (or keep the stored value) and write the page again.`);+}diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.tsindex ba3ab9c660..6dd0fa9406 100644--- a/src/core/persistence/page-prepare.ts+++ b/src/core/persistence/page-prepare.ts@@ -80,6 +80,7 @@ import { SOURCE_CONFIG_OBJECT_SQL } from '../source-config-sql.ts';import { readSlugRootMode } from '../sync-anchor.ts';import { applyPageEdits, editDiff, parseEditWithin, parsePageEdits, prepareSegmentedEditMutation } from './page-edit.ts';import { carryCoreMarking, prepareCoreGuard } from './core-guard.ts';+import { assertRetirementStampUnchanged } from './derived-retirement-hold.ts';import { fenceWhere } from '../fence-repair/refusal.ts';import { pageFencesNormalized } from '../fence-repair/report.ts';import { parseFenceRepairReceipt } from '../fence-repair/receipt.ts';@@ -747,8 +748,8 @@ async function prepareInlineOrSegmentedMutation(unbounded: BrainEngine, row: Wri}if (row.authority.remote && row.operation !== 'remember' && !row.operation.startsWith('takes_') && typeof content==='string') {const parsed=parseMarkdown(content,row.slug,{ activePack });- const compiled_truth=preserveProtectedTakes(parsed.compiled_truth,snapshot?.page.compiled_truth??'');- const timeline=preserveProtectedTakes(parsed.timeline??'',snapshot?.page.timeline??'');+ assertRetirementStampUnchanged(row.slug, parsed.frontmatter, snapshot?.page.frontmatter);+ const compiled_truth=preserveProtectedTakes(parsed.compiled_truth,snapshot?.page.compiled_truth??''), timeline=preserveProtectedTakes(parsed.timeline??'',snapshot?.page.timeline??'');if (compiled_truth!==parsed.compiled_truth || timeline!==(parsed.timeline??'')) content=serializePageToMarkdown({...(snapshot?.page??{id:0,source_id:row.source_id,created_at:new Date(),updated_at:new Date()}),...parsed,compiled_truth,timeline},parsed.tags);}diff --git a/src/core/persistence/purge-deleted.ts b/src/core/persistence/purge-deleted.tsindex 04c3f2deda..97b220b95e 100644--- a/src/core/persistence/purge-deleted.ts+++ b/src/core/persistence/purge-deleted.ts@@ -13,6 +13,7 @@ import { markBeliefCommits } from '../belief/append.ts';import { linkStreamSlugs } from './page-purge.ts';import { identityDowngradePurgeHold } from '../sync-identity-downgrades.ts';import { atomRetirementPurgeHold } from './atom-retirement-hold.ts';+import { derivedRetirementPurgeHold } from './derived-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 { ItemRun, type ItemFailure } from '../item-failure.ts';@@ -83,7 +84,7 @@ interface RecordedTombstone { id: number; source_id: string; slug: string; deletasync function recordedTombstones(engine: BrainEngine, hours: string): Promise<RecordedTombstone[]> {const rows = await engine.executeRaw<{ id: number; source_id: string; slug: string; deleted_us: string }>(`SELECT p.id, p.source_id, p.slug,floor(extract(epoch FROM p.deleted_at)*1000000)::bigint::text AS deleted_us FROM pages p- WHERE p.deleted_at IS NOT NULL AND p.deleted_at < now() - ($1 || ' hours')::interval AND ${identityDowngradePurgeHold('p')} AND ${atomRetirementPurgeHold('p')}+ WHERE p.deleted_at IS NOT NULL AND p.deleted_at < now() - ($1 || ' hours')::interval AND ${identityDowngradePurgeHold('p')} AND ${atomRetirementPurgeHold('p')} AND ${derivedRetirementPurgeHold('p')}AND EXISTS (SELECT 1 FROM belief_events e WHERE e.source_id = p.source_id AND e.subject_kind = 'coverage')ORDER BY p.deleted_at ASC, p.source_id ASC, p.slug ASC`, [hours]);const parks = rows.length ? await readPurgeParks(engine) : new Map<string, PurgePark>();@@ -129,7 +130,7 @@ async function expireRecordedTombstones(engine: BrainEngine, olderThanHours: numconst slugs = [...new Set([row.slug, ...await linkStreamSlugs(tx, row.source_id, row.id)])].sort();await tx.lockPageKeys(slugs.map(slug => ({ sourceId: row.source_id, slug })));return withBeliefBatch(tx, { sourceId: row.source_id, slugs, publicationId, op: 'purge_deleted_pages', hardDeleteEvent: 'page.expired', report },- async () => (await tx.executeRaw(`DELETE FROM pages WHERE id = $1 AND deleted_at IS NOT NULL AND deleted_at < now() - ($2 || ' hours')::interval AND ${identityDowngradePurgeHold('pages')} AND ${atomRetirementPurgeHold('pages')} RETURNING id`,+ async () => (await tx.executeRaw(`DELETE FROM pages WHERE id = $1 AND deleted_at IS NOT NULL AND deleted_at < now() - ($2 || ' hours')::interval AND ${identityDowngradePurgeHold('pages')} AND ${atomRetirementPurgeHold('pages')} AND ${derivedRetirementPurgeHold('pages')} RETURNING id`,[row.id, hours])).length > 0);});run.succeed();@@ -205,7 +206,7 @@ export async function selectPurgeCandidates(engine: BrainEngine, olderThanHours:const rows = await engine.executeRaw<{ id: number | string; source_id: string; slug: string; cutoff: string; deleted_us: string }>(`SELECT p.id, p.source_id, p.slug, (now() - ($1 || ' hours')::interval)::text AS cutoff,floor(extract(epoch FROM p.deleted_at)*1000000)::bigint::text AS deleted_us FROM pages p JOIN sources s ON s.id = p.source_id- WHERE p.deleted_at IS NOT NULL AND p.deleted_at < now() - ($1 || ' hours')::interval AND NOT s.archived AND ${identityDowngradePurgeHold('p')} AND ${atomRetirementPurgeHold('p')}+ WHERE p.deleted_at IS NOT NULL AND p.deleted_at < now() - ($1 || ' hours')::interval AND NOT s.archived AND ${identityDowngradePurgeHold('p')} AND ${atomRetirementPurgeHold('p')} AND ${derivedRetirementPurgeHold('p')}ORDER BY p.deleted_at ASC, p.source_id ASC, p.slug ASC`, [String(hours)]);const states = new Map<string, { state: string; physical_error?: string }>();if (rows.length) for (const source of (await writerOnboardingPreflight(engine)).sources) states.set(source.source_id, source);diff --git a/test/derived-retirement-keys-remote.test.ts b/test/derived-retirement-keys-remote.test.tsnew file mode 100644index 0000000000..a38fa1a298--- /dev/null+++ b/test/derived-retirement-keys-remote.test.ts@@ -0,0 +1,82 @@+/**+ * GBRA-161 PR 0: the derived-retirement stamp keys (`retired_by`, `retired_at`, `retired_generation`) are set only by+ * trusted derived writers. A remote put_page that adds or changes one is refused with `reserved_frontmatter_key` and+ * writes nothing; carrying the stored value unchanged (a round-trip of a restored page) or dropping it writes; a local+ * write keeps them. Fails when a remote caller can stamp a page so the purge hold or a restore treats it as a derived+ * retirement.+ * PGLite in-memory, through the coordinated write path ($0).+ */+import { afterAll, afterEach, beforeAll, beforeEach, expect, test as bunTest } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { randomUUID } from 'node:crypto';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { withEnv } from './helpers/with-env.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';+import { registerLocalWriter, withVerifiedLocalRegistration, type LocalRegistration } from '../src/core/persistence/identity.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { _resetWriteThroughCacheForTest } from '../src/core/write-through.ts';++let engine: PGLiteEngine;+let fixture: string;+let remoteRegistration: LocalRegistration;+let cliRegistration: LocalRegistration;+const remoteAuth = { token: 'fixture', clientId: 'fixture-client', scopes: ['read', 'write'], sourceId: 'default' };++beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);+afterAll(async () => { await engine.disconnect(); });+beforeEach(async () => {+ await disposePersistenceConsumer(engine);+ await resetPgliteState(engine);+ _resetWriteThroughCacheForTest();+ fixture = mkdtempSync(join(tmpdir(), 'gb-retire-keys-'));+ mkdirSync(join(fixture, 'brain'));+ await engine.setConfig('sync.repo_path', join(fixture, 'brain'));+});+afterEach(async () => { await disposePersistenceConsumer(engine); rmSync(fixture, { recursive: true, force: true }); });++function test(name: string, run: () => Promise<void>) {+ bunTest(name, () => withEnv({ GBRAIN_HOME: join(fixture, 'home') }, async () => {+ remoteRegistration = await registerLocalWriter(engine, 'stdio', { sourceIds: ['*'], operations: null, scopes: ['read', 'write'], slugPrefixes: null });+ cliRegistration = await registerLocalWriter(engine, 'cli');+ try { await run(); } finally { await disposePersistenceConsumer(engine); }+ }), 30_000);+}++async function put(slug: string, content: string, remote: boolean) {+ return withVerifiedLocalRegistration(engine, remote ? remoteRegistration : cliRegistration, () => dispatchToolCall(engine, 'put_page',+ { slug, content, force: true, request_id: randomUUID() }, { remote, config: { engine: 'pglite' }, sourceId: 'default', ...(remote ? { auth: remoteAuth } : {}),+ logger: { info() {}, warn() {}, error() {} } }));+}+async function written(slug: string, content: string, remote: boolean) {+ const response = await put(slug, content, remote);+ expect(response.isError === true).toBe(false);+}+const stamped = '---\ntitle: Stamped\ntype: note\nretired_by: life-chronicle\nretired_at: 2026-01-01T00:00:00.000Z\nretired_generation: 7\nowner: alice-example\n---\n\nBody.\n';+const frontmatter = async (slug: string) => (await engine.executeRaw<{ frontmatter: Record<string, unknown> }>(+ 'SELECT frontmatter FROM pages WHERE slug=$1', [slug]))[0]!.frontmatter;++test('a remote put_page that adds the retirement stamp keys is refused and writes nothing', async () => {+ const response = await put('notes/remote-example', stamped, true);+ expect(response.isError).toBe(true);+ expect(JSON.stringify(response.content)).toContain('reserved_frontmatter_key');+ expect(await engine.executeRaw('SELECT 1 FROM pages WHERE slug=$1', ['notes/remote-example'])).toHaveLength(0);+});++test('a trusted local put_page keeps them', async () => {+ await written('notes/local-example', stamped, false);+ expect(await frontmatter('notes/local-example')).toMatchObject({ retired_by: 'life-chronicle', owner: 'alice-example' });+});++test('a remote put_page that changes a stored stamp is refused; carrying it unchanged or dropping it writes', async () => {+ await written('notes/round-trip-example', stamped, false);+ const changed = await put('notes/round-trip-example', stamped.replace('retired_by: life-chronicle', 'retired_by: stale-atoms'), true);+ expect(changed.isError).toBe(true);+ expect(JSON.stringify(changed.content)).toContain('reserved_frontmatter_key');+ await written('notes/round-trip-example', stamped.replace('Body.', 'Edited body.'), true);+ expect(await frontmatter('notes/round-trip-example')).toMatchObject({ retired_by: 'life-chronicle', owner: 'alice-example' });+ await written('notes/round-trip-example', stamped.replace(/retired_[a-z]+: .*\n/g, ''), true);+ expect(await frontmatter('notes/round-trip-example')).not.toHaveProperty('retired_by');+});diff --git a/test/fixtures/goldens/sql-text/pages.json b/test/fixtures/goldens/sql-text/pages.jsonindex 2bd763e822..6ea1e57365 100644--- a/test/fixtures/goldens/sql-text/pages.json+++ b/test/fixtures/goldens/sql-text/pages.json@@ -789,8 +789,8 @@"params": ["number"],- "sql": "DELETE FROM pages WHERE deleted_at IS NOT NULL AND deleted_at < now() - ($1 || ' hours')::interval -- #6729: the old page of an open rename-identity downgrade waits for its disposition (identityDowngradePurgeHold). AND NOT EXISTS (SELECT 1 FROM op_checkpoints dg WHERE dg.op = 'sync-identity-downgrade' AND dg.fingerprint = pages.id::text AND dg.completed_keys->0->>'disposition' IS NULL AND pages.deleted_at = (dg.completed_keys->0->>'old_deleted_at')::timestamptz) -- #7013: a restorable re-extraction retirement waits out its hold (atomRetirementPurgeHold). AND NOT (pages.type='atom' AND pages.frontmatter->>'retired_by'='managed-reextract' AND pages.deleted_at > now() - interval '30 days' AND pages.id IN (SELECT held.id FROM (WITH retired AS ( SELECT p.id, p.source_id, p.slug, CASE WHEN NULLIF(p.frontmatter->>'source_slug','') IS NOT NULL THEN 'slug:'||(p.frontmatter->>'source_slug') WHEN NULLIF(p.frontmatter->>'source_path','') IS NOT NULL THEN 'path:'||(p.frontmatter->>'source_path') END AS okey, NULLIF(p.frontmatter->>'source_slug','') AS origin_slug, COALESCE(NULLIF(p.frontmatter->>'source_slug',''), p.frontmatter->>'source_path') AS origin, regexp_replace(COALESCE(p.frontmatter->>'source_hash',''),'^pending:','') AS hash, p.frontmatter->>'retired_at' AS retired_at FROM pages p WHERE p.type='atom' AND p.deleted_at IS NOT NULL AND p.frontmatter->>'retired_by'='managed-reextract' AND NULLIF(p.frontmatter->>'imported_from','') IS NULL AND (true) ), latest AS ( SELECT DISTINCT ON (source_id, okey) source_id, okey, hash FROM retired WHERE okey IS NOT NULL ORDER BY source_id, okey, retired_at DESC NULLS LAST, id DESC ), live AS ( SELECT p.source_id, CASE WHEN NULLIF(p.frontmatter->>'source_slug','') IS NOT NULL THEN 'slug:'||(p.frontmatter->>'source_slug') WHEN NULLIF(p.frontmatter->>'source_path','') IS NOT NULL THEN 'path:'||(p.frontmatter->>'source_path') END AS okey, array_agg(DISTINCT regexp_replace(COALESCE(p.frontmatter->>'source_hash',''),'^pending:','')) AS hashes FROM pages p WHERE p.type='atom' AND p.deleted_at IS NULL AND NULLIF(p.frontmatter->>'imported_from','') IS NULL AND (true) GROUP BY 1, 2 ) SELECT r.id, r.source_id, r.slug, CASE WHEN r.origin_slug IS NOT NULL THEN 'page' ELSE 'transcript' END AS origin_kind, r.origin, o.id AS origin_page_id, r.hash, r.retired_at, (r.okey IS NOT NULL AND (r.origin_slug IS NULL OR o.id IS NOT NULL)) AS origin_live, (lv.hashes IS NOT NULL AND NOT (lv.hashes <@ ARRAY[r.hash])) AS replaced, COALESCE(l.hash = r.hash, false) AS latest, (r.okey IS NOT NULL AND (r.origin_slug IS NULL OR o.id IS NOT NULL) AND NOT COALESCE(lv.hashes IS NOT NULL AND NOT (lv.hashes <@ ARRAY[r.hash]), false) AND COALESCE(l.hash = r.hash, false)) AS restorable FROM retired r LEFT JOIN pages o ON o.source_id=r.source_id AND o.slug=r.origin_slug AND o.deleted_at IS NULL LEFT JOIN live lv ON lv.source_id=r.source_id AND lv.okey=r.okey LEFT JOIN latest l ON l.source_id=r.source_id AND l.okey=r.okey) held WHERE held.restorable)) RETURNING slug, source_id",- "textSha256": "f862c722576ff2336a3952630456e751b0308cde53c669ef2e0d4a36ab354fa6"+ "sql": "DELETE FROM pages WHERE deleted_at IS NOT NULL AND deleted_at < now() - ($1 || ' hours')::interval -- #6729: the old page of an open rename-identity downgrade waits for its disposition (identityDowngradePurgeHold). AND NOT EXISTS (SELECT 1 FROM op_checkpoints dg WHERE dg.op = 'sync-identity-downgrade' AND dg.fingerprint = pages.id::text AND dg.completed_keys->0->>'disposition' IS NULL AND pages.deleted_at = (dg.completed_keys->0->>'old_deleted_at')::timestamptz) -- #7013: a restorable re-extraction retirement waits out its hold (atomRetirementPurgeHold). AND NOT (pages.type='atom' AND pages.frontmatter->>'retired_by'='managed-reextract' AND pages.deleted_at > now() - interval '30 days' AND pages.id IN (SELECT held.id FROM (WITH retired AS ( SELECT p.id, p.source_id, p.slug, CASE WHEN NULLIF(p.frontmatter->>'source_slug','') IS NOT NULL THEN 'slug:'||(p.frontmatter->>'source_slug') WHEN NULLIF(p.frontmatter->>'source_path','') IS NOT NULL THEN 'path:'||(p.frontmatter->>'source_path') END AS okey, NULLIF(p.frontmatter->>'source_slug','') AS origin_slug, COALESCE(NULLIF(p.frontmatter->>'source_slug',''), p.frontmatter->>'source_path') AS origin, regexp_replace(COALESCE(p.frontmatter->>'source_hash',''),'^pending:','') AS hash, p.frontmatter->>'retired_at' AS retired_at FROM pages p WHERE p.type='atom' AND p.deleted_at IS NOT NULL AND p.frontmatter->>'retired_by'='managed-reextract' AND NULLIF(p.frontmatter->>'imported_from','') IS NULL AND (true) ), latest AS ( SELECT DISTINCT ON (source_id, okey) source_id, okey, hash FROM retired WHERE okey IS NOT NULL ORDER BY source_id, okey, retired_at DESC NULLS LAST, id DESC ), live AS ( SELECT p.source_id, CASE WHEN NULLIF(p.frontmatter->>'source_slug','') IS NOT NULL THEN 'slug:'||(p.frontmatter->>'source_slug') WHEN NULLIF(p.frontmatter->>'source_path','') IS NOT NULL THEN 'path:'||(p.frontmatter->>'source_path') END AS okey, array_agg(DISTINCT regexp_replace(COALESCE(p.frontmatter->>'source_hash',''),'^pending:','')) AS hashes FROM pages p WHERE p.type='atom' AND p.deleted_at IS NULL AND NULLIF(p.frontmatter->>'imported_from','') IS NULL AND (true) GROUP BY 1, 2 ) SELECT r.id, r.source_id, r.slug, CASE WHEN r.origin_slug IS NOT NULL THEN 'page' ELSE 'transcript' END AS origin_kind, r.origin, o.id AS origin_page_id, r.hash, r.retired_at, (r.okey IS NOT NULL AND (r.origin_slug IS NULL OR o.id IS NOT NULL)) AS origin_live, (lv.hashes IS NOT NULL AND NOT (lv.hashes <@ ARRAY[r.hash])) AS replaced, COALESCE(l.hash = r.hash, false) AS latest, (r.okey IS NOT NULL AND (r.origin_slug IS NULL OR o.id IS NOT NULL) AND NOT COALESCE(lv.hashes IS NOT NULL AND NOT (lv.hashes <@ ARRAY[r.hash]), false) AND COALESCE(l.hash = r.hash, false)) AS restorable FROM retired r LEFT JOIN pages o ON o.source_id=r.source_id AND o.slug=r.origin_slug AND o.deleted_at IS NULL LEFT JOIN live lv ON lv.source_id=r.source_id AND lv.okey=r.okey LEFT JOIN latest l ON l.source_id=r.source_id AND l.okey=r.okey) held WHERE held.restorable)) -- GBRA-161: every derived retirement waits out its hold (derivedRetirementPurgeHold). AND NOT (COALESCE(pages.frontmatter->>'retired_by','') IN ('extract-atoms','managed-reextract','stale-atoms','life-chronicle') AND pages.deleted_at > now() - interval '30 days') RETURNING slug, source_id",+ "textSha256": "a4287bea2e44bfc3207dcedebb9c4640aeb64cc6fb25fff0c89c9c6fc5440610"},{"event": "commit",@@ -803,8 +803,8 @@"params": ["number"],- "sql": "SELECT slug, deleted_at FROM pages WHERE deleted_at IS NOT NULL AND deleted_at < now() - ($1 || ' hours')::interval AND NOT EXISTS (SELECT 1 FROM op_checkpoints dg WHERE dg.op = 'sync-identity-downgrade' AND dg.fingerprint = pages.id::text AND dg.completed_keys->0->>'disposition' IS NULL AND pages.deleted_at = (dg.completed_keys->0->>'old_deleted_at')::timestamptz) AND NOT (pages.type='atom' AND pages.frontmatter->>'retired_by'='managed-reextract' AND pages.deleted_at > now() - interval '30 days' AND pages.id IN (SELECT held.id FROM (WITH retired AS ( SELECT p.id, p.source_id, p.slug, CASE WHEN NULLIF(p.frontmatter->>'source_slug','') IS NOT NULL THEN 'slug:'||(p.frontmatter->>'source_slug') WHEN NULLIF(p.frontmatter->>'source_path','') IS NOT NULL THEN 'path:'||(p.frontmatter->>'source_path') END AS okey, NULLIF(p.frontmatter->>'source_slug','') AS origin_slug, COALESCE(NULLIF(p.frontmatter->>'source_slug',''), p.frontmatter->>'source_path') AS origin, regexp_replace(COALESCE(p.frontmatter->>'source_hash',''),'^pending:','') AS hash, p.frontmatter->>'retired_at' AS retired_at FROM pages p WHERE p.type='atom' AND p.deleted_at IS NOT NULL AND p.frontmatter->>'retired_by'='managed-reextract' AND NULLIF(p.frontmatter->>'imported_from','') IS NULL AND (true) ), latest AS ( SELECT DISTINCT ON (source_id, okey) source_id, okey, hash FROM retired WHERE okey IS NOT NULL ORDER BY source_id, okey, retired_at DESC NULLS LAST, id DESC ), live AS ( SELECT p.source_id, CASE WHEN NULLIF(p.frontmatter->>'source_slug','') IS NOT NULL THEN 'slug:'||(p.frontmatter->>'source_slug') WHEN NULLIF(p.frontmatter->>'source_path','') IS NOT NULL THEN 'path:'||(p.frontmatter->>'source_path') END AS okey, array_agg(DISTINCT regexp_replace(COALESCE(p.frontmatter->>'source_hash',''),'^pending:','')) AS hashes FROM pages p WHERE p.type='atom' AND p.deleted_at IS NULL AND NULLIF(p.frontmatter->>'imported_from','') IS NULL AND (true) GROUP BY 1, 2 ) SELECT r.id, r.source_id, r.slug, CASE WHEN r.origin_slug IS NOT NULL THEN 'page' ELSE 'transcript' END AS origin_kind, r.origin, o.id AS origin_page_id, r.hash, r.retired_at, (r.okey IS NOT NULL AND (r.origin_slug IS NULL OR o.id IS NOT NULL)) AS origin_live, (lv.hashes IS NOT NULL AND NOT (lv.hashes <@ ARRAY[r.hash])) AS replaced, COALESCE(l.hash = r.hash, false) AS latest, (r.okey IS NOT NULL AND (r.origin_slug IS NULL OR o.id IS NOT NULL) AND NOT COALESCE(lv.hashes IS NOT NULL AND NOT (lv.hashes <@ ARRAY[r.hash]), false) AND COALESCE(l.hash = r.hash, false)) AS restorable FROM retired r LEFT JOIN pages o ON o.source_id=r.source_id AND o.slug=r.origin_slug AND o.deleted_at IS NULL LEFT JOIN live lv ON lv.source_id=r.source_id AND lv.okey=r.okey LEFT JOIN latest l ON l.source_id=r.source_id AND l.okey=r.okey) held WHERE held.restorable)) ORDER BY deleted_at ASC, slug ASC",- "textSha256": "1465c25692e36ffd111d5d84cf1ba8e6039a2af4a4bb06fa5a341d3db4aa21ce"+ "sql": "SELECT slug, deleted_at FROM pages WHERE deleted_at IS NOT NULL AND deleted_at < now() - ($1 || ' hours')::interval AND NOT EXISTS (SELECT 1 FROM op_checkpoints dg WHERE dg.op = 'sync-identity-downgrade' AND dg.fingerprint = pages.id::text AND dg.completed_keys->0->>'disposition' IS NULL AND pages.deleted_at = (dg.completed_keys->0->>'old_deleted_at')::timestamptz) AND NOT (pages.type='atom' AND pages.frontmatter->>'retired_by'='managed-reextract' AND pages.deleted_at > now() - interval '30 days' AND pages.id IN (SELECT held.id FROM (WITH retired AS ( SELECT p.id, p.source_id, p.slug, CASE WHEN NULLIF(p.frontmatter->>'source_slug','') IS NOT NULL THEN 'slug:'||(p.frontmatter->>'source_slug') WHEN NULLIF(p.frontmatter->>'source_path','') IS NOT NULL THEN 'path:'||(p.frontmatter->>'source_path') END AS okey, NULLIF(p.frontmatter->>'source_slug','') AS origin_slug, COALESCE(NULLIF(p.frontmatter->>'source_slug',''), p.frontmatter->>'source_path') AS origin, regexp_replace(COALESCE(p.frontmatter->>'source_hash',''),'^pending:','') AS hash, p.frontmatter->>'retired_at' AS retired_at FROM pages p WHERE p.type='atom' AND p.deleted_at IS NOT NULL AND p.frontmatter->>'retired_by'='managed-reextract' AND NULLIF(p.frontmatter->>'imported_from','') IS NULL AND (true) ), latest AS ( SELECT DISTINCT ON (source_id, okey) source_id, okey, hash FROM retired WHERE okey IS NOT NULL ORDER BY source_id, okey, retired_at DESC NULLS LAST, id DESC ), live AS ( SELECT p.source_id, CASE WHEN NULLIF(p.frontmatter->>'source_slug','') IS NOT NULL THEN 'slug:'||(p.frontmatter->>'source_slug') WHEN NULLIF(p.frontmatter->>'source_path','') IS NOT NULL THEN 'path:'||(p.frontmatter->>'source_path') END AS okey, array_agg(DISTINCT regexp_replace(COALESCE(p.frontmatter->>'source_hash',''),'^pending:','')) AS hashes FROM pages p WHERE p.type='atom' AND p.deleted_at IS NULL AND NULLIF(p.frontmatter->>'imported_from','') IS NULL AND (true) GROUP BY 1, 2 ) SELECT r.id, r.source_id, r.slug, CASE WHEN r.origin_slug IS NOT NULL THEN 'page' ELSE 'transcript' END AS origin_kind, r.origin, o.id AS origin_page_id, r.hash, r.retired_at, (r.okey IS NOT NULL AND (r.origin_slug IS NULL OR o.id IS NOT NULL)) AS origin_live, (lv.hashes IS NOT NULL AND NOT (lv.hashes <@ ARRAY[r.hash])) AS replaced, COALESCE(l.hash = r.hash, false) AS latest, (r.okey IS NOT NULL AND (r.origin_slug IS NULL OR o.id IS NOT NULL) AND NOT COALESCE(lv.hashes IS NOT NULL AND NOT (lv.hashes <@ ARRAY[r.hash]), false) AND COALESCE(l.hash = r.hash, false)) AS restorable FROM retired r LEFT JOIN pages o ON o.source_id=r.source_id AND o.slug=r.origin_slug AND o.deleted_at IS NULL LEFT JOIN live lv ON lv.source_id=r.source_id AND lv.okey=r.okey LEFT JOIN latest l ON l.source_id=r.source_id AND l.okey=r.okey) held WHERE held.restorable)) AND NOT (COALESCE(pages.frontmatter->>'retired_by','') IN ('extract-atoms','managed-reextract','stale-atoms','life-chronicle') AND pages.deleted_at > now() - interval '30 days') ORDER BY deleted_at ASC, slug ASC",+ "textSha256": "180642b2b72ef387136dcc3b411df2f7e21e90db965d1c2102ffe5746c6be0a3"}]},diff --git a/test/pathological/g0-derived-retirement-hold.test.ts b/test/pathological/g0-derived-retirement-hold.test.tsnew file mode 100644index 0000000000..b6ab54afcc--- /dev/null+++ b/test/pathological/g0-derived-retirement-hold.test.ts@@ -0,0 +1,132 @@+/**+ * GBRA-161 PR 0: every derived retirement is versioned, stamped and held from the purge for 30 days.+ *+ * Protects: (a) an unmanaged `extract_atoms` re-extraction versions each atom it retires and stamps it+ * `retired_by: extract-atoms`; past the 72 h purge window the engine bulk purge (preview and delete) and the coordinated+ * purge keep it while a plain tombstone of the same age goes, `restore_page` brings it back with its body, and the hold+ * ends 30 days after deletion; (b) an unmanaged chronicle re-judgment versions the event it retires before the soft+ * delete; (c) each derived stamp (extract-atoms, managed-reextract, stale-atoms, life-chronicle) is held on every purge+ * route, and an unknown stamp is not.+ * Fails when: a derived writer retires without a version or stamp, or a purge route removes a derived retirement inside+ * its hold (the pre-fix 72 h loss: purge cascades the page's page_versions with it).+ * Seams: the extract_atoms phase's `_transcripts` / `_chat` inputs and the chronicle phase's injected judge (no paid+ * call). PGLite always, Postgres when DATABASE_URL is set.+ */+import { describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { ChatOpts, ChatResult } from '../../src/core/ai/gateway.ts';+import { runPhaseExtractAtoms } from '../../src/core/cycle/extract-atoms.ts';+import { runPhaseChronicle } from '../../src/core/cycle/chronicle.ts';+import type { BrainEngine } from '../../src/core/engine.ts';+import { managedPersistenceEnabled } from '../../src/core/persistence/ownership.ts';+import { purgeDeletedPagesCoordinated } from '../../src/core/persistence/purge-deleted.ts';+import { DERIVED_RETIRED_BY } from '../../src/core/persistence/derived-retirement-hold.ts';+import { _resetWriteThroughCacheForTest } from '../../src/core/write-through.ts';+import { isolatedSharedSkillsEngine } from '../helpers/shared-skills-engine.ts';+import { withEnv } from '../helpers/with-env.ts';+import { pathologicalArms } from './harness.ts';++const chat = (titles: string[]) => async (_o: ChatOpts): Promise<ChatResult> => {+ const text = JSON.stringify(titles.map(title => ({ title, atom_type: 'insight', body: `${title} body.` })));+ return {+ text, blocks: [{ type: 'text', text }], stopReason: 'end',+ usage: { input_tokens: 100, output_tokens: 50, cache_read_tokens: 0, cache_creation_tokens: 0 },+ model: 'anthropic:claude-haiku-4-5', providerId: 'anthropic',+ };+};++async function withBrain(databaseUrl: string | undefined, run: (engine: BrainEngine) => Promise<void>): Promise<void> {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-g0-'));+ try {+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {+ _resetWriteThroughCacheForTest();+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);+ try {+ expect(await managedPersistenceEnabled(engine)).toBe(false);+ await run(engine);+ } finally { await close(); }+ });+ } finally { rmSync(home, { recursive: true, force: true }); }+}++const extract = (engine: BrainEngine, titles: string[], hash: string) => runPhaseExtractAtoms(engine, {+ _transcripts: [{ filePath: '/fake/2026-09-07-meeting.txt', content: 'content', contentHash: hash }], _pages: [], _chat: chat(titles),+});+const atoms = async (engine: BrainEngine) => engine.executeRaw<{ slug: string; deleted: boolean; retired_by: string | null }>(+ "SELECT slug, deleted_at IS NOT NULL AS deleted, frontmatter->>'retired_by' AS retired_by FROM pages WHERE type='atom' ORDER BY slug");+const versions = async (engine: BrainEngine, slug: string) => Number((await engine.executeRaw<{ n: number }>(+ 'SELECT count(*)::int AS n FROM page_versions v JOIN pages p ON p.id=v.page_id WHERE p.slug=$1', [slug]))[0]!.n);+const backdate = (engine: BrainEngine, slug: string, hours: number) => engine.executeRaw(+ `UPDATE pages SET deleted_at = now() - ($2 || ' hours')::interval WHERE slug=$1`, [slug, String(hours)]);+const exists = async (engine: BrainEngine, slug: string) => (await engine.executeRaw('SELECT 1 FROM pages WHERE slug=$1', [slug])).length === 1;++for (const { backend, databaseUrl } of pathologicalArms()) {+ describe(`GBRA-161 PR 0 derived retirements are versioned, stamped and held (${backend})`, () => {+ test('an unmanaged atom re-extraction versions and stamps what it retires; every purge route holds it for 30 days', async () => {+ await withBrain(databaseUrl, async engine => {+ await extract(engine, ['Renders vs proof'], 'hash-one');+ const [old] = await atoms(engine);+ await extract(engine, ['Proof beats renders'], 'hash-two');+ const rows = await atoms(engine);+ const retired = rows.find(row => row.slug === old!.slug)!;+ expect(retired).toMatchObject({ deleted: true, retired_by: 'extract-atoms' });+ expect(rows.filter(row => !row.deleted)).toHaveLength(1);+ expect(await versions(engine, old!.slug)).toBeGreaterThan(0);++ await engine.putPage('notes/plain-example', { type: 'note', title: 'Plain', compiled_truth: 'A plain page.' });+ await engine.softDeletePage('notes/plain-example');+ await backdate(engine, 'notes/plain-example', 96);+ await backdate(engine, old!.slug, 96);+ expect((await engine.purgeDeletedPages(72, { dryRun: true })).slugs).toEqual(['notes/plain-example']);+ expect((await purgeDeletedPagesCoordinated(engine, 72)).slugs).toEqual(['notes/plain-example']);+ expect(await exists(engine, old!.slug)).toBe(true);++ await engine.restorePage(old!.slug);+ const [restored] = await engine.executeRaw<{ deleted: boolean; compiled_truth: string }>(+ 'SELECT deleted_at IS NOT NULL AS deleted, compiled_truth FROM pages WHERE slug=$1', [old!.slug]);+ expect(restored).toMatchObject({ deleted: false });+ expect(restored!.compiled_truth).toContain('Renders vs proof body.');++ await engine.softDeletePage(old!.slug);+ await backdate(engine, old!.slug, 31 * 24);+ expect((await engine.purgeDeletedPages(72)).slugs).toEqual([old!.slug]);+ });+ }, 120_000);++ test('an unmanaged chronicle re-judgment versions the event it retires', async () => {+ await withBrain(databaseUrl, async engine => {+ const today = new Date().toISOString().slice(0, 10);+ const body = 'Alice and Bob reviewed the launch plan and agreed on the next steps for the beta. '.repeat(3);+ const ev = (what: string) => ({ when: today, who: ['people/alice-example'], what, kind: 'commitment' });+ await engine.setConfig('chronicle.auto_settle_seconds', '0');+ await engine.setConfig('chronicle.activated_at', new Date(Date.now() - 60_000).toISOString());+ await engine.putPage('meetings/sync', { type: 'meeting', title: 'Sync', compiled_truth: body, frontmatter: { date: today } });+ await runPhaseChronicle(engine, { judge: async () => ({ events: [ev('Alice agreed to ship the beta')] }) });+ const [first] = await engine.executeRaw<{ slug: string }>("SELECT slug FROM pages WHERE type='event'");+ await engine.putPage('meetings/sync', { type: 'meeting', title: 'Sync', compiled_truth: `${body} Wording changed.`, frontmatter: { date: today } });+ await runPhaseChronicle(engine, { judge: async () => ({ events: [ev('Alice agreed to ship the beta in May')] }) });+ const [row] = await engine.executeRaw<{ deleted: boolean; retired_by: string | null }>(+ "SELECT deleted_at IS NOT NULL AS deleted, frontmatter->>'retired_by' AS retired_by FROM pages WHERE slug=$1", [first!.slug]);+ expect(row).toEqual({ deleted: true, retired_by: 'life-chronicle' });+ expect(await versions(engine, first!.slug)).toBeGreaterThan(0);+ });+ }, 120_000);++ test('every derived stamp is held on every purge route; an unknown stamp is not', async () => {+ await withBrain(databaseUrl, async engine => {+ const stamps = [...DERIVED_RETIRED_BY, 'operator-cleanup'];+ for (const stamp of stamps) {+ const slug = `notes/${stamp}-example`;+ await engine.putPage(slug, { type: 'note', title: stamp, compiled_truth: `Retired by ${stamp}.`, frontmatter: { retired_by: stamp } });+ await engine.softDeletePage(slug);+ await backdate(engine, slug, 96);+ }+ expect((await engine.purgeDeletedPages(72, { dryRun: true })).slugs).toEqual(['notes/operator-cleanup-example']);+ expect((await purgeDeletedPagesCoordinated(engine, 72)).slugs).toEqual(['notes/operator-cleanup-example']);+ for (const stamp of DERIVED_RETIRED_BY) expect(await exists(engine, `notes/${stamp}-example`)).toBe(true);+ });+ }, 120_000);+ });+}diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 16d9e973e9..b8511edfbd 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -312,6 +312,7 @@ test/pathological/d7-synthesize-reverse-write.test.tstest/pathological/d8-patterns-reverse-write.test.tstest/pathological/d9-dream-summary-overwrite.test.tstest/pathological/facts-mirror-failures.test.ts+test/pathological/g0-derived-retirement-hold.test.tstest/pathological/h1-zero-yield-atom-reextract.test.tstest/pathological/h2-git-effect-moved-remote.test.tstest/pathological/h3-chronicle-partial-generation.test.ts