Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Recheck derived pages inside the purge so a page written mid-purge is stamped or its origin parked
garrytan3c96749084ee
diff --git a/changelog.d/capy-derived-origin-delete-carry-private.md b/changelog.d/capy-derived-origin-delete-carry-private.mdindex 74be8ed18c..603295ab4d 100644--- a/changelog.d/capy-derived-origin-delete-carry-private.md+++ b/changelog.d/capy-derived-origin-delete-carry-private.md@@ -11,5 +11,5 @@ important: security- A summary whose `derived_from` names a private page, an atom extracted from a private page, and a synthesized concept built from such an atom read as private to remote callers even when their own label says world, because their origin is private. Once the origin's row was removed (an explicit `gbrain delete --purge`, or the purge after the 72-hour recovery window, including after a remote delete or a `git rm`), nothing kept them private any more, and every remote caller that is not the owner could read them through `get_page`, `get_versions`, `list_pages` and search.- Now gbrain gives each such page `visibility: private` first, as a label-only write. The page keeps its trust tier, no lowering proposal is filed, and on a brain with Git only the label line of its file changes. A soft delete (local or over MCP) writes the label once the delete committed, as a maintenance write (on a managed brain its batch names the delete's request id); if that write fails, the delete still goes through and the purge writes the label later. The delete's response is unchanged and names none of the labelled pages. Every purge writes the label again for each origin expired or expiring within a day before it removes any row, so an origin removed outside gbrain is covered from the next cycle.- Pages that are already private, pinned questions and pages that do not derive from the deleted page are never changed. A page that names readers (`readable_by`) and was hidden from them only through its private origin gets the label too and keeps its readers, so its listed readers still can't read it. The owner, a `granted_sources` credential and a listed reader read exactly the same pages as before.-- When a label cannot be written (for example a file in the checkout that gbrain may not write), the deleted page is kept soft-deleted instead of purged. An explicit purge returns `purge_held`, the purge phase lists the page as `derived_origin_parked` and warns, and the new doctor check `derived_origin_parked` names the page with the derived page that blocks it and the reason. Once the cause is fixed, the next purge writes the label and frees the page, and the purge after removes it (a consented `gbrain pages purge-deleted --yes` does both, so its preview lists it). A derived page that is itself soft-deleted holds the deleted page the same way until it is purged or restored, so restoring it never brings it back readable.+- When a label cannot be written (for example a file in the checkout that gbrain may not write), the deleted page is kept soft-deleted instead of purged. An explicit purge returns `purge_held`, the purge phase lists the page as `derived_origin_parked` and warns, and the new doctor check `derived_origin_parked` names the page with the derived page that blocks it and the reason. Once the cause is fixed, the next purge writes the label and frees the page, and the purge after removes it (a consented `gbrain pages purge-deleted --yes` does both, so its preview lists it). A page derived from it that is written while a purge runs is caught inside the purge's own transaction and holds the deleted page the same way, and a derived page that is itself soft-deleted holds it until it is purged or restored, so restoring it never brings it back readable.- A deleted page that is restored and later made world leaves its derived pages private until the owner relabels them. (GST-2689)diff --git a/docs/architecture/derived-census.tsv b/docs/architecture/derived-census.tsvindex f86a9167ee..ba8ef4808c 100644--- a/docs/architecture/derived-census.tsv+++ b/docs/architecture/derived-census.tsv@@ -16,6 +16,7 @@ src/core/page-body/segment-rewrite.ts 1 pending:inventory derived or mixed writesrc/core/persistence/connector-sync.ts 1 canonical connector sync applies an upstream deletion of a connected itemsrc/core/persistence/derived-retirement-hold.ts 4 primitive retireDerivedPagesInTransaction: versions, soft-deletes and stamps retired_by; the helper every generation adapter retires throughsrc/core/persistence/page-prepare.ts 2 canonical coordinated delete_page preparation (an operator or agent deletion)+src/core/persistence/page-purge.ts 1 canonical GST-2689: an explicit delete_page purge held by the in-transaction derived-page recheck soft-deletes the live page insteadsrc/core/persistence/sync-image.ts 1 canonical sync image publication applies a committed file deletionsrc/core/persistence/sync-prepare.ts 1 canonical managed sync prepares the soft delete of a page whose file was removedsrc/core/persistence/twin-merge.ts 1 canonical origin-twin merge retires the losing duplicate of one canonical filediff --git a/docs/architecture/key-files/memory-purge.md b/docs/architecture/key-files/memory-purge.mdindex c7eb93ae6e..e56af3e9da 100644--- a/docs/architecture/key-files/memory-purge.md+++ b/docs/architecture/key-files/memory-purge.md@@ -34,6 +34,6 @@ User-facing contract: [expire versus purge](../../guides/memory-boundaries.md#pu- `src/commands/doctor/checks/atom-fence-rows.ts` — doctor `atom_fence_rows` (BRAIN, a host-only `WAVE_CHECKS` repair entry cleared by the explicit-only `atom-fence-rows`, so remediation classifies it `explicit_kind_required`): runs `findAtomFenceRows` per source, each statement bounded by `PLAN_STATEMENT_MS`; `warn` names the count per source and the read-only preview `gbrain repair atom-fence-rows --source <id> --json` as an agent `fix`, never a slug or row text; an overrun reports the count as unknown.- `src/core/persistence/purge-parks.ts` — #6741 C: per-tombstone purge parks in op_checkpoints (op `purge-deleted-park`, key source+slug+deleted_at, so a re-deleted page starts fresh); park at `PURGE_PARK_LIMIT` (5) non-deferral failures, a success clears it, and parks of a source seen inactive rearm the first run its writer is active again (`notePurgeSourceWriter`). `purgeStaleCheckpoints` exempts the op; `prunePurgeParks` drops parks whose tombstone is gone. A park records the gbrain `version` of its last failure; `isParked` (the managed and unmanaged selection, doctor `purge_parked_pages`) counts only the running version's, so a park another version wrote (or one with no version) gets one automatic attempt and a failure re-parks it under the running version. Tests: `test/purge-deleted-parks.test.ts`, `test/purge-parks-version.test.ts` (Postgres: `test/e2e/purge-parks-version-postgres.test.ts`).-- `src/core/persistence/derived-origin-hold.ts` + `src/core/repair/origin-carry.ts` — GST-2689: a page that reads as world by its own label but is hidden from remote callers only through a private origin (`derived_from`, an atom's `source_slug`, followed through `slug_aliases` and `slug_rename_history`, or a concept's provenance atom) keeps that privacy once the origin row is gone. `origin-carry.ts` finds the dependents with `private-labels.ts` `dependentsSql('remove')` (the postimage drops the origin rows; a page that names readers is returned when its listed readers would gain it, and gets the label with its `readable_by` kept; life-chronicle events are never returned) and gives each `visibility: private` through the label door (`publishMaintenancePages` with `keepTrust` and the label edit on a managed brain, batch `derived-origin-carry:<request_id>`; `writeLabelFile` or `importAtRevision` otherwise). `deletePageCarryingPrivate` is the `delete_page` handler body: a soft delete (local or remote) labels after it committed and returns the unchanged receipt; a purge labels first and, when that fails, soft-deletes instead (an existing tombstone stays), parks the origin and returns `purge_held`. `carryPrivateBeforePurge` runs before every expiry over all the origins (`type = 'atom'` or hidden by `privacyPartSql`) expired or expiring within `CARRY_LEAD_HOURS` (24) at once, so a page private through two of them is found and none crosses the cutoff mid-run uncarried; it publishes the labels 200 per maintenance batch, parks the blocked ones and returns the ones whose park no longer applies, which `purgeDeletedPagesCoordinated` clears only after its purge, so an origin parked when the purge was previewed stays that run; a consented manual purge (`gbrain pages purge-deleted`, `purge_deleted_pages`) first runs `retryParkedOrigins` so its preview lists the origins it frees. A soft-deleted dependent is returned too but never labelled: it blocks its origin (`dependent_soft_deleted`) until it is purged or restored, since a restore would bring it back with the origin row gone; a removed origin tied to another removed origin counts as such a dependent (judged on its own row), since another hold may keep it. The origin is looked up by the lowercased slug, as `submitPageMutation` deletes it. `derived-origin-hold.ts` is the park (op_checkpoints op `derived-origin-park`, fingerprint the page id, with `blocking_slug`, `code` and `reason`), `derivedOriginPurgeHold` (no engine-sql imports), prune of restored or purged pages, and `readDerivedOriginParks` for doctor `derived_origin_parked`; `purgeStaleCheckpoints` exempts the op. Tests: `test/derived-origin-carry-private.test.ts` (repo-less, minted tokens), `test/derived-origin-carry-managed.test.ts` (managed Git brain).+- `src/core/persistence/derived-origin-hold.ts` + `src/core/repair/origin-carry.ts` — GST-2689: a page that reads as world by its own label but is hidden from remote callers only through a private origin (`derived_from`, an atom's `source_slug`, followed through `slug_aliases` and `slug_rename_history`, or a concept's provenance atom) keeps that privacy once the origin row is gone. `origin-carry.ts` finds the dependents with `private-labels.ts` `dependentsSql('remove')` (the postimage drops the origin rows; a page that names readers is returned when its listed readers would gain it, and gets the label with its `readable_by` kept; life-chronicle events are never returned) and gives each `visibility: private` through the label door (`publishMaintenancePages` with `keepTrust` and the label edit on a managed brain, batch `derived-origin-carry:<request_id>`; `writeLabelFile` or `importAtRevision` otherwise). `deletePageCarryingPrivate` is the `delete_page` handler body: a soft delete (local or remote) labels after it committed and returns the unchanged receipt; a purge labels first and, when that fails, soft-deletes instead (an existing tombstone stays), parks the origin and returns `purge_held`. `carryPrivateBeforePurge` runs before every expiry over all the origins (`type = 'atom'` or hidden by `privacyPartSql`) expired or expiring within `CARRY_LEAD_HOURS` (24) at once, so a page private through two of them is found and none crosses the cutoff mid-run uncarried; it publishes the labels 200 per maintenance batch, parks the blocked ones and returns the ones whose park no longer applies, which `purgeDeletedPagesCoordinated` clears only after its purge, so an origin parked when the purge was previewed stays that run; a consented manual purge (`gbrain pages purge-deleted`, `purge_deleted_pages`) first runs `retryParkedOrigins` so its preview lists the origins it frees. A soft-deleted dependent is returned too but never labelled: it blocks its origin (`dependent_soft_deleted`) until it is purged or restored, since a restore would bring it back with the origin row gone; a removed origin tied to another removed origin counts as such a dependent (judged on its own row), since another hold may keep it. Inside each delete transaction `parkUncarriedInPurge` rechecks the origins about to go (the page purge for an explicit or managed retention purge, the unmanaged bulk delete, and each recorded tombstone): an origin a page written after the carry still depends on is parked in that transaction and its row is kept (a live page is soft-deleted instead, and the receipt carries `purge_held` naming no page), so the next purge labels the page and the one after removes the origin. The origin is looked up by the lowercased slug, as `submitPageMutation` deletes it. `derived-origin-hold.ts` is the park (op_checkpoints op `derived-origin-park`, fingerprint the page id, with `blocking_slug`, `code` and `reason`), `derivedOriginPurgeHold` (no engine-sql imports), prune of restored or purged pages, and `readDerivedOriginParks` for doctor `derived_origin_parked`; `purgeStaleCheckpoints` exempts the op. Tests: `test/derived-origin-carry-private.test.ts` (repo-less, minted tokens), `test/derived-origin-carry-managed.test.ts` (managed Git brain).- `src/core/repair/segmented-mirror.ts` — `gbrain repair segmented-mirror` (LPH a), explicit-only, preview-bound, destructive consent, `checks: []` (no doctor scan: detection reads every segmented file). `scanSegmentedMirrors` (read-only, owner host; a non-owner source is held `not_owner_host`) walks live `body_storage='segmented'` pages of sources with a worktree binding whose snapshot ledger applies (`ledgerApplies`), runs `prepareFileTarget(..., null, { allowMissing })` (the mirror's own drift check; `file_database_drift` or any other `OperationError` is held, never rewritten), then lists the page only when overlaying the ledger on the file's facts fences changes its region digests (`fileBodyDigests` vs `overlaidFileBodyDigests` over `FileBytes`, bounded memory) and the streamed render (`unreadPageFile`) hashes differently. The hash (`segmented-mirror-v1`) binds source selection, slug, page id, revision, path and both SHA-256s; the approved set lives in `op_checkpoints`. Apply re-checks revision and file hash of every page not yet admitted (`preview_changed`), then per page admits and commits, in one transaction like a withdrawal, a `repair_segmented_mirror` request (request id derived from the hash; its receipt) that inserts a version-2 targeted `withdrawal-mirror` + `git` effect (no embedding) whose `data.approved_file` carries the preview's file and render SHA-256 (`mirrorPage` skips the target `preview_changed` when the file's before-hash or the streamed render differs, before the gate or any recovery record; `publishGitPage` skips it when the file is not the approved render; the outcome is `refused` `preview_changed` with a read-only fix re-running the preview); it wakes this process's consumer and waits up to the write wait for them (`mirrored` / `mirror_queued` / `held` / `failed`; a replay is `replayed`). Test: `test/pathological/lp-a-segmented-mirror.test.ts`.diff --git a/src/core/persistence/fault-points.ts b/src/core/persistence/fault-points.tsindex db1b001f37..9cb1ff816c 100644--- a/src/core/persistence/fault-points.ts+++ b/src/core/persistence/fault-points.ts@@ -48,6 +48,8 @@ export type FaultPoint = `publication:${PublicationBoundary}` | `effect:${Effect| 'purge:slug_lookup' | 'purge:tail_recheck' | 'purge:pending_recheck' | 'purge:redaction_read'// #6511: before each keyset chunk of the preparation-time journal sweep (a stalling hook models a slow chunk), and the fact purge's planning read.| 'purge:sweep_chunk' | 'purge:carrying_lookup'+ // GST-2689: after a purge labelled the pages derived from its origins (repair/origin-carry.ts) and before it deletes any row.+ | 'purge:after_carry'// W1: before each keyset batch of the belief ledger's purge redaction (belief/purge.ts); a 57014 from the hook models its statement timeout.| 'purge:ledger_redaction'// Before a fact purge records its derivation sweep in its transaction (segment-derive.ts recordDerivationPurge); a 57014 from the hook models its statement timeout.diff --git a/src/core/persistence/page-purge.ts b/src/core/persistence/page-purge.tsindex b127b6d1d0..03af4856d9 100644--- a/src/core/persistence/page-purge.ts+++ b/src/core/persistence/page-purge.ts@@ -44,6 +44,7 @@ import { PERSISTENCE_REQUEST_SLUG_INTENT_INDEX } from './schema.ts';import { readRequestIndexStates, REQUEST_INDEXES_REPAIR_COMMAND, type RequestIndexState } from './checkpoint-validation.ts';import { faultPoint } from './fault-points.ts';import { writeOriginDeletedMarker } from './sync-markers.ts';+import { withTrustKeep } from './context.ts';import { clearRebuildableCache } from './rebuildable-cache.ts';import { carryingNeedles, findRequestsForSlugs, JOURNAL_SWEEP_MATCH_CAP, recheckRequestsCarrying, redactRequestIntents, sweepRequestsCarrying, sweepRequestsForGroups,type IntentRedactionTarget, type JournalSweep } from './intent-redaction.ts';@@ -279,6 +280,12 @@ const TIMELINE_RECEIPT_CAP = 10_000;export async function purgePageInTransaction(tx: BrainEngine, row: WriteRequest, snapshot: PageSnapshot, prepared: PreparedPagePurge): Promise<Record<string, unknown>> {const page = snapshot.page, sourceId = row.source_id, slug = page.slug;+ // GST-2689: a page derived from this one written after the purge's carry keeps it: soft-deleted (a live page) and parked.+ const { MID_PURGE_HOLD, parkUncarriedInPurge } = await import('../repair/origin-carry.ts');+ if ((await parkUncarriedInPurge(tx, [Number(page.id)])).length) {+ if (!page.deleted_at) { await tx.createVersion(slug, { sourceId }); await withTrustKeep(tx, ['pages'], () => tx.softDeletePage(slug, { sourceId })); }+ return { status: 'soft_deleted', slug, source_id: sourceId, noop: !!page.deleted_at, ...(prepared.retention ? { retention: true } : {}), purge_held: MID_PURGE_HOLD };+ }const actor = `${row.principal_kind}:${row.principal_id}`;const [stored] = await tx.executeRaw<{ content_hash: string | null; body_generation: number | string }>('SELECT content_hash,body_generation FROM pages WHERE id=$1', [page.id]);const storedHash = stored?.content_hash ?? null;diff --git a/src/core/persistence/purge-deleted.ts b/src/core/persistence/purge-deleted.tsindex 39c4a8045a..ee609ad8e2 100644--- a/src/core/persistence/purge-deleted.ts+++ b/src/core/persistence/purge-deleted.ts@@ -14,7 +14,8 @@ 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 { clearDerivedOriginParks, DERIVED_ORIGIN_PARKED_CODE, derivedOriginPurgeHold, type DerivedOriginPark } from './derived-origin-hold.ts';+import { faultPoint } from './fault-points.ts';+import { clearDerivedOriginParks, DERIVED_ORIGIN_PARKED_CODE, derivedOriginPurgeHold, readDerivedOriginParks, type DerivedOriginPark } from './derived-origin-hold.ts';import { writerOnboardingPreflight } from './onboarding.ts';import { clearPurgePark, isParked, notePurgeSourceWriter, PURGE_PARK_LIMIT, purgeParkKey, prunePurgeParks, readPurgeParks, recordPurgeFailure, type PurgePark } from './purge-parks.ts';import { ItemRun, type ItemFailure } from '../item-failure.ts';@@ -118,7 +119,7 @@ async function recordedTombstones(engine: BrainEngine, hours: string): Promise<Rconst parkedReason = (park: PurgePark) =>`Parked after ${park.failures} failed purges (last: ${park.code ?? 'error'}: ${park.reason}); retry once with gbrain pages purge-deleted --retry-parked.`;-interface RecordedExpiry { slugs: string[]; exclude: number[]; blocked: DeletedPagePurge['blocked']; failed: number; parked: number }+interface RecordedExpiry { slugs: string[]; exclude: number[]; blocked: DeletedPagePurge['blocked']; failed: number; parked: number; reparked: DerivedOriginPark[] }/*** W1 (BELIEF_LEDGER.md 6.5): on an unmanaged brain, each expired tombstone of a source the belief ledger records is@@ -132,9 +133,10 @@ interface RecordedExpiry { slugs: string[]; exclude: number[]; blocked: DeletedP*/async function expireRecordedTombstones(engine: BrainEngine, olderThanHours: number, retryParked: boolean, held: ReadonlySet<number>, only?: PurgeFilter): Promise<RecordedExpiry> {const hours = String(Math.max(0, Math.floor(olderThanHours)));+ const { parkUncarriedInPurge } = await import('../repair/origin-carry.ts');await prunePurgeParks(engine);const run = new ItemRun('purge.recorded_tombstones');- const out: RecordedExpiry = { slugs: [], exclude: [], blocked: [], failed: 0, parked: 0 };+ const out: RecordedExpiry = { slugs: [], exclude: [], blocked: [], failed: 0, parked: 0, reparked: [] };const failures: Array<{ row: RecordedTombstone; failure: ItemFailure }> = [];for (const row of await recordedTombstones(engine, hours)) {if (held.has(row.id)) continue;@@ -152,6 +154,7 @@ async function expireRecordedTombstones(engine: BrainEngine, olderThanHours: numawait 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 () => {+ out.reparked.push(...await parkUncarriedInPurge(tx, [row.id]));const gone = await tx.executeRaw<{ source_id: string; slug: string; deleted_at: string }>(`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')} AND ${derivedOriginPurgeHold('pages')} RETURNING source_id, slug, deleted_at::text AS deleted_at`,[row.id, hours]);await expireGonePageFacts(tx, gone);@@ -334,9 +337,12 @@ export type PurgeFilter = (page: { source_id: string; slug: string }) => booleanexport async function purgeDeletedPagesCoordinated(engine: BrainEngine, olderThanHours: number, opts: { retryParked?: boolean; automatic?: boolean; only?: PurgeFilter } = {}): Promise<DeletedPagePurge> {const carried = await (await import('../repair/origin-carry.ts')).carryPrivateBeforePurge(engine, olderThanHours);const origins = originParked(carried.parks);+ await faultPoint('purge:after_carry');const result = await purgeExpired(engine, olderThanHours, opts);- await clearDerivedOriginParks(engine, carried.unparked);- return origins.length ? { ...result, blocked: [...origins, ...result.blocked], origin_parked: origins.length } : result;+ const reparked = new Set(result.blocked.filter(b => b.code === DERIVED_ORIGIN_PARKED_CODE).map(b => `${b.source_id}/${b.slug}`));+ await clearDerivedOriginParks(engine, carried.unparked.filter(origin => !reparked.has(`${origin.source_id}/${origin.slug}`)).map(origin => origin.id));+ const parked = origins.length + (result.origin_parked ?? 0);+ return parked ? { ...result, blocked: [...origins, ...result.blocked], origin_parked: parked } : result;}function originParked(parks: DerivedOriginPark[]): DeletedPagePurge['blocked'] {@@ -346,21 +352,29 @@ function originParked(parks: DerivedOriginPark[]): DeletedPagePurge['blocked'] {}async function purgeExpired(engine: BrainEngine, olderThanHours: number, opts: { retryParked?: boolean; automatic?: boolean; only?: PurgeFilter }): Promise<DeletedPagePurge> {+ const { parkUncarriedInPurge } = await import('../repair/origin-carry.ts');if (!await managedPersistenceEnabled(engine)) {// #7130: a brain deactivated after managed syncs keeps their tombstones' records and receipts, so the hold applies here too.const kept = opts.automatic ? await readUnreviewedSyncTombstones(engine, olderThanHours) : [];const recorded = await expireRecordedTombstones(engine, olderThanHours, opts.retryParked === true, new Set(kept.map(row => row.id)), opts.only);const exclude = [...recorded.exclude, ...kept.map(row => row.id)];+ const reparked = [...recorded.reparked];const result = await maintenanceTransaction(engine, async tx => {const unlisted = opts.only ? (await tx.executeRaw<{ id: number; source_id: string; slug: string }>(`SELECT id, source_id, slug FROM pages WHERE deleted_at IS NOT NULL AND deleted_at < now() - ($1 || ' hours')::interval`,[String(Math.max(0, Math.floor(olderThanHours)))])).filter(page => !opts.only!(page)).map(page => Number(page.id)) : [];const excludeIds = [...exclude, ...unlisted];+ const skip = new Set(excludeIds);+ const expiring = await tx.executeRaw<{ id: number }>(`SELECT id FROM pages WHERE deleted_at IS NOT NULL AND deleted_at < now() - ($1 || ' hours')::interval`,+ [String(Math.max(0, Math.floor(olderThanHours)))]);+ // GST-2689: the recheck parks, in this transaction, each origin a page written after the carry still depends on; the delete's hold skips it.+ reparked.push(...await parkUncarriedInPurge(tx, expiring.map(page => Number(page.id)).filter(id => !skip.has(id))));return tx.purgeDeletedPages(olderThanHours, excludeIds.length ? { excludeIds } : undefined);});const held = kept.filter(row => row.expired);- return { slugs: [...recorded.slugs, ...result.slugs], count: recorded.slugs.length + result.count, blocked: [...recorded.blocked, ...held.map(row => syncDeleteHeld(row, olderThanHours))],- deferred: 0, failed: recorded.failed, inactive: 0, parked: recorded.parked, capacity_deferred: 0, held: held.length };+ return { slugs: [...recorded.slugs, ...result.slugs], count: recorded.slugs.length + result.count,+ blocked: [...originParked(reparked), ...recorded.blocked, ...held.map(row => syncDeleteHeld(row, olderThanHours))],+ deferred: 0, failed: recorded.failed, inactive: 0, parked: recorded.parked, capacity_deferred: 0, held: held.length, ...(reparked.length ? { origin_parked: reparked.length } : {}) };}// W3 (#7587): an automatic run reconciles the purges an earlier run left pending before it selects or submits anything.const deferral = await DreamWriteDeferralPass.start(engine, 'purge', opts.automatic === true);@@ -371,6 +385,7 @@ async function purgeExpired(engine: BrainEngine, olderThanHours: number, opts: {const slugs: string[] = [];const blocked: DeletedPagePurge['blocked'] = [...selection.blocked];let deferred = 0, failed = 0, capacityDeferred = 0;+ const reparked: DerivedOriginPark[] = [];const reconciledFailures = new Set<string>();for (const entry of deferral?.reconcile.failed ?? []) {const [source_id, ...rest] = entry.subject.split('/');@@ -411,8 +426,12 @@ async function purgeExpired(engine: BrainEngine, olderThanHours: number, opts: {if (!snapshot?.page.deleted_at) continue;// Restored and deleted again since the scan: its recovery window restarted.if (new Date(snapshot.page.deleted_at).getTime() >= new Date(row.cutoff).getTime()) { deferred++; continue; }- await submitPageMutation(ctx, { operation: 'delete_page', waitMs: maintenancePublishWaitMs(), params: { slug: row.slug, source_id: row.source_id,+ const purged = await submitPageMutation(ctx, { operation: 'delete_page', waitMs: maintenancePublishWaitMs(), params: { slug: row.slug, source_id: row.source_id,purge: true, retention: true, expected_revision: snapshot.revision, request_id: randomUUID() } });+ if ((purged.purge_held as { code?: unknown } | undefined)?.code === DERIVED_ORIGIN_PARKED_CODE) {+ reparked.push(...await readDerivedOriginParks(engine).then(parks => parks.filter(park => park.page_id === Number(snapshot.page.id))));+ continue;+ }slugs.push(row.slug);if (row.park) await clearPurgePark(engine, row.key);} catch (error) {@@ -435,6 +454,6 @@ async function purgeExpired(engine: BrainEngine, olderThanHours: number, opts: {message: `${failed} expired page(s) could not be purged through the coordinator: ${failures.slice(0, 3).map(b => `${b.source_id}/${b.slug}: ${b.reason}`).join('; ')}` } : undefined;const parked = selection.parked.filter(park => !park.retried).length;- return { slugs, count: slugs.length, blocked, deferred, failed, inactive: selection.inactive, parked, capacity_deferred: capacityDeferred, held: selection.held,- ...(deferral ? { write_deferred: deferral.skipped, deferral } : {}), ...(error ? { error } : {}) };+ return { slugs, count: slugs.length, blocked: [...originParked(reparked), ...blocked], deferred, failed, inactive: selection.inactive, parked, capacity_deferred: capacityDeferred, held: selection.held,+ ...(reparked.length ? { origin_parked: reparked.length } : {}), ...(deferral ? { write_deferred: deferral.skipped, deferral } : {}), ...(error ? { error } : {}) };}diff --git a/src/core/repair/origin-carry.ts b/src/core/repair/origin-carry.tsindex 510c3d56b3..cf70a3360f 100644--- a/src/core/repair/origin-carry.ts+++ b/src/core/repair/origin-carry.ts@@ -20,8 +20,9 @@ import { serializePageToMarkdown } from '../markdown.ts';import { isSegmentedPage } from '../page-body/page-shape.ts';import type { LabelEdit } from '../persistence/label-edit.ts';import { maintenancePreflight, publishMaintenancePages } from '../persistence/prepared-maintenance.ts';-import { clearDerivedOriginParks, DERIVED_ORIGIN_PARKED_CODE, parkDerivedOrigin, pruneDerivedOriginParks, readDerivedOriginParks, type DerivedOriginPark } from '../persistence/derived-origin-hold.ts';+import { clearDerivedOriginParks, DERIVED_ORIGIN_PARKED_CODE, derivedOriginPurgeHold, parkDerivedOrigin, pruneDerivedOriginParks, readDerivedOriginParks, type DerivedOriginPark } from '../persistence/derived-origin-hold.ts';import { privacyPartSql, readHonorAliases, withoutCallerAccess } from '../search/private-visibility.ts';+import { faultPoint } from '../persistence/fault-points.ts';import { filesInCheckout, importAtRevision, writeLabelFile } from './label-write.ts';import { dependentsSql } from './private-labels.ts';@@ -148,6 +149,7 @@ export async function deletePageCarryingPrivate(ctx: OperationContext, p: Record}const block = origin ? (await carryPrivate(ctx.engine, [origin], batch)).get(origin.id) : undefined;if (!origin || !block) {+ await faultPoint('purge:after_carry', { sourceId, slug: origin?.slug });const result = await finishPagePurge(ctx, await submitPageMutation(ctx, { operation: 'delete_page', params: p }));if (origin && result.status === 'purged') await clearDerivedOriginParks(ctx.engine, [origin.id]);return result;@@ -169,7 +171,7 @@ export const CARRY_LEAD_HOURS = 24;* still blocked is parked (the purge skips it). The parks written this run, and the origins whose earlier park no longer* applies: the caller clears those after its purge, so an origin parked when the purge was previewed stays this run.*/-export async function carryPrivateBeforePurge(engine: BrainEngine, olderThanHours: number): Promise<{ parks: DerivedOriginPark[]; unparked: number[] }> {+export async function carryPrivateBeforePurge(engine: BrainEngine, olderThanHours: number): Promise<{ parks: DerivedOriginPark[]; unparked: Origin[] }> {await pruneDerivedOriginParks(engine);const origins = await withoutCallerAccess(async () => {await readHonorAliases(engine);@@ -187,7 +189,7 @@ export async function carryPrivateBeforePurge(engine: BrainEngine, olderThanHourawait parkDerivedOrigin(engine, parked(origin, block));parks.push({ ...parked(origin, block), parked_at: new Date().toISOString() });}- return { parks, unparked: expired.filter(origin => !blocked.has(origin.id)).map(origin => origin.id) };+ return { parks, unparked: expired.filter(origin => !blocked.has(origin.id)) };}/**@@ -196,5 +198,39 @@ export async function carryPrivateBeforePurge(engine: BrainEngine, olderThanHour*/export async function retryParkedOrigins(engine: BrainEngine, olderThanHours: number): Promise<void> {if (!(await readDerivedOriginParks(engine)).length) return;- await clearDerivedOriginParks(engine, (await carryPrivateBeforePurge(engine, olderThanHours)).unparked);+ await clearDerivedOriginParks(engine, (await carryPrivateBeforePurge(engine, olderThanHours)).unparked.map(origin => origin.id));+}++/** The receipt note of a purge the in-transaction recheck held; it names no page and counts none. */+export const MID_PURGE_HOLD = { code: DERIVED_ORIGIN_PARKED_CODE,+ message: 'Not purged: a page derived from this one was written during the purge and is not labelled private yet, so this page is kept soft-deleted and parked; the next purge labels it and frees this page, and the one after removes it (gbrain doctor: derived_origin_parked).' };++/**+ * Inside a purge's delete transaction, after the carry: the origins among `ids` (not already parked) that a page would+ * still open without, which means a dependent was written after the carry labelled the rest. The label door cannot write+ * inside this transaction (a managed label is its own publication, a Git label its own commit), so each such origin is+ * parked here, in the same transaction, and the caller skips its row delete; the next purge labels the page and the one+ * after removes the origin. The parks written, by origin.+ */+export async function parkUncarriedInPurge(tx: BrainEngine, ids: readonly number[]): Promise<DerivedOriginPark[]> {+ if (!ids.length) return [];+ return withoutCallerAccess(async () => {+ await readHonorAliases(tx);+ const origins = (await tx.executeRaw<{ id: number; source_id: string; slug: string }>(`SELECT p.id, p.source_id, p.slug FROM pages p+ WHERE p.id = ANY($1::int[]) AND ${originSql('p')} AND ${derivedOriginPurgeHold('p')} ORDER BY p.id`, [[...ids]], bounded))+ .map(row => ({ id: Number(row.id), source_id: row.source_id, slug: row.slug }));+ if (!origins.length) return [];+ const first = new Map<number, Dependent>();+ for (const page of await dependentsOf(tx, origins)) if (!first.has(page.origin_id)) first.set(page.origin_id, page);+ const parks: DerivedOriginPark[] = [];+ for (const origin of origins) {+ const page = first.get(origin.id);+ if (!page) continue;+ const park = { source_id: origin.source_id, slug: origin.slug, page_id: origin.id, blocking_slug: page.slug, code: 'dependent_written_mid_purge',+ reason: `${page.slug} was written while ${origin.slug} was being purged and is private only through it; the next purge labels it.` };+ await parkDerivedOrigin(tx, park);+ parks.push({ ...park, parked_at: new Date().toISOString() });+ }+ return parks;+ });}diff --git a/test/derived-origin-carry-managed.test.ts b/test/derived-origin-carry-managed.test.tsindex 38d8809984..022e734acf 100644--- a/test/derived-origin-carry-managed.test.ts+++ b/test/derived-origin-carry-managed.test.ts@@ -24,6 +24,9 @@ import { operationsByName } from '../src/core/operations.ts';import { performManagedSync } from '../src/core/persistence/sync-run.ts';import { SYNC_DELETE_TOMBSTONE_OP } from '../src/core/persistence/sync-delete-tombstones.ts';import { runPages } from '../src/commands/pages.ts';+import { installFaultHook } from '../src/core/persistence/fault-points.ts';+import { purgeDeletedPagesCoordinated } from '../src/core/persistence/purge-deleted.ts';+import { importFromContent } from '../src/core/import-file.ts';import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';import { sqlQueryForEngine } from '../src/core/sql-query.ts';import { mintLegacyToken } from '../src/core/token-mint.ts';@@ -58,7 +61,7 @@ function fileText(k: string, shape: Shape): string {};return ['---', `title: ${k} ${shape}`, ...fm[shape], '---', '', `Harbor ledger planning notes ${canaryOf(k, shape)} for the roadmap.`, ''].join('\n');}-const KEYS = ['gitrm', 'purge', 'remote'];+const KEYS = ['gitrm', 'purge', 'remote', 'midpurge'];const setup = ({ root }: { root: string }) => {mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q', '-b', 'main');for (const k of KEYS) for (const shape of SHAPES) writeFileSync(join(root, `${slugOf(k, shape)}.md`), fileText(k, shape));@@ -148,6 +151,35 @@ for (const backend of testBackends()) {await expectCarried(engine, root, k, files);}, { setup, databaseUrl }), 300_000);+ test('the managed retention purge rechecks inside its transaction: a derived page written after the carry parks the origin and skips its row', () => managedBrain(async ({ engine, root }) => {+ await performManagedSync(engine, OPTS);+ const k = 'midpurge', origin = slugOf(k, 'origin'), late = `notes/${k}-late`;+ await before(engine, root, k);+ git(root, 'rm', '-q', `${origin}.md`); commit(root, 'remove the origin');+ await performManagedSync(engine, OPTS);+ await age(engine, 100);+ let fired = false;+ installFaultHook(async point => {+ if (point !== 'purge:after_carry' || fired) return;+ fired = true;+ await fixtureWrite(engine, async () => {+ expect((await importFromContent(engine, late, ['---', 'title: late', 'type: note', `derived_from: ${origin}.md`, '---', '', `Harbor ledger planning notes ${canaryOf(k, 'plain')}late for the roadmap.`, ''].join('\n'),+ { sourceId: 'default', noEmbed: true })).status).toBe('imported');+ });+ });+ let held: Awaited<ReturnType<typeof purgeDeletedPagesCoordinated>>;+ try { held = await purgeDeletedPagesCoordinated(engine, 72); }+ finally { installFaultHook(undefined); }+ expect(fired).toBe(true);+ expect(held.slugs).not.toContain(origin);+ expect(held.blocked.find(b => b.slug === origin)?.code).toBe('derived_origin_parked');+ expect((await page(engine, origin))?.deleted_at).not.toBeNull();+ __resetPrivateVisibilityCacheForTests();+ const ctx = { engine, config: { engine: engine.kind }, logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote: true, sourceId: 'default' } as unknown as OperationContext;+ const read = async () => { try { return JSON.stringify(await operationsByName.get_page!.handler(ctx, { slug: late })); } catch { return ''; } };+ expect((await read()).includes(`${canaryOf(k, 'plain')}late`)).toBe(false);+ }, { setup, databaseUrl }), 300_000);+test('an explicit local purge: the derived files gain the label line through the Git door before the row goes', () => managedBrain(async ({ engine, root, ctx }) => {await performManagedSync(engine, OPTS);const k = 'purge', origin = slugOf(k, 'origin');diff --git a/test/derived-origin-carry-private.test.ts b/test/derived-origin-carry-private.test.tsindex d3e6b48805..800a7b187a 100644--- a/test/derived-origin-carry-private.test.ts+++ b/test/derived-origin-carry-private.test.ts@@ -35,6 +35,7 @@ import { setOwner } from '../src/core/access/owner.ts';import { bindCredential } from '../src/core/access/members.ts';import { consentedPurgeDeletedPages, purgeDeletedPagesCoordinated, selectPurgeCandidates } from '../src/core/persistence/purge-deleted.ts';import { checkDerivedOriginParked } from '../src/commands/doctor/checks/purge-parks.ts';+import { installFaultHook } from '../src/core/persistence/fault-points.ts';import type { AuthInfo } from '../src/core/ops/contract.ts';import { testBackends } from './helpers/test-backends.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';@@ -356,6 +357,64 @@ for (const kind of testBackends()) {await nothingKept(origin);}, 240_000);+ /** Writes a world-labelled page derived from the origin once, between the purge's carry and its row delete. */+ function lateDerivedPage(k: string): string {+ const late = `${k}/late`;+ let fired = false;+ installFaultHook(async point => {+ if (point !== 'purge:after_carry' || fired) return;+ fired = true;+ expect((await importFromContent(engine, late, ['---', 'title: late', 'type: note', `derived_from: ${slugOf(k, 'origin')}.md`, '---', '# late', '',+ `Harbor ledger planning notes ${canaryOf(k, 'plain')}late for the roadmap.`].join('\n'), { sourceId: SRC, noEmbed: true })).status).toBe('imported');+ });+ return late;+ }+ async function expectLateHidden(k: string, late: string): Promise<void> {+ __resetPrivateVisibilityCacheForTests();+ for (const who of ['unbound', 'alice'] as const) expect({ who, read: (await call(who, 'get_page', { slug: late })).text.includes(`${canaryOf(k, 'plain')}late`) }).toEqual({ who, read: false });+ }++ test('an explicit purge rechecks inside its transaction: a derived page written after the carry keeps the origin soft-deleted and parked', async () => {+ const k = 'midsingle';+ await seed(k);+ const origin = slugOf(k, 'origin');+ const late = lateDerivedPage(k);+ let out: { isError: boolean; text: string };+ try { out = await localCall('delete_page', { slug: origin, purge: true, request_id: randomUUID(), expected_revision: await revision(origin) }); }+ finally { installFaultHook(undefined); }+ expect(out.isError ? out.text : '').toBe('');+ const receipt = JSON.parse(out.text);+ expect(receipt.status).not.toBe('purged');+ expect(receipt.purge_held?.code).toBe('derived_origin_parked');+ expect((await row(origin))?.deleted_at).not.toBeNull();+ await expectLateHidden(k, late);+ await backdate(origin);+ expect((await purgeDeletedPagesCoordinated(engine, 72, { automatic: true })).slugs).not.toContain(origin);+ expect((await fm(late)).visibility).toBe('private');+ expect((await purgeDeletedPagesCoordinated(engine, 72, { automatic: true })).slugs).toContain(origin);+ await expectLateHidden(k, late);+ }, 240_000);++ test('the bulk retention purge rechecks inside its transaction: a derived page written after the carry parks the origin and skips its row', async () => {+ const k = 'midbulk';+ await seed(k);+ const origin = slugOf(k, 'origin');+ await softDelete(origin);+ await backdate(origin);+ const late = lateDerivedPage(k);+ let held: Awaited<ReturnType<typeof purgeDeletedPagesCoordinated>>;+ try { held = await purgeDeletedPagesCoordinated(engine, 72, { automatic: true }); }+ finally { installFaultHook(undefined); }+ expect(held.slugs).not.toContain(origin);+ expect(held.blocked.find(b => b.slug === origin)?.code).toBe('derived_origin_parked');+ expect((await row(origin))?.deleted_at).not.toBeNull();+ await expectLateHidden(k, late);+ expect((await purgeDeletedPagesCoordinated(engine, 72, { automatic: true })).slugs).not.toContain(origin);+ expect((await fm(late)).visibility).toBe('private');+ expect((await purgeDeletedPagesCoordinated(engine, 72, { automatic: true })).slugs).toContain(origin);+ await expectLateHidden(k, late);+ }, 240_000);+test('a stamp that fails parks the origin: never purged, named by doctor with the page that blocks it, the derived page stays hidden; fixed, the next purge stamps and unparks and the one after purges', async () => {const k = 'park';await seed(k);