Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix: pre-landing review fixes
garrytancff3aaa6de5e
diff --git a/src/core/persistence/intent-redaction.ts b/src/core/persistence/intent-redaction.tsindex ac5693664b..e079a81fe5 100644--- a/src/core/persistence/intent-redaction.ts+++ b/src/core/persistence/intent-redaction.ts@@ -212,10 +212,11 @@ export async function findRequestsCarrying(engine: BrainEngine, sourceId: string}/** Replace every JSON string that carries one of `needles` (case-insensitive) with "[purged]"; structure and other values stay. */-export function redactJson<T>(value: T, needles: readonly string[]): T {+export function redactJson<T>(value: T, needles: readonly string[], exact?: ReadonlySet<string>): T {const lowered = needles.map(n => n.toLowerCase()).filter(Boolean);- if (!lowered.length || value === null || value === undefined) return value;- const walk = (v: unknown): unknown => typeof v === 'string' ? (lowered.some(n => v.toLowerCase().includes(n)) ? '[purged]' : v)+ if ((!lowered.length && !exact?.size) || value === null || value === undefined) return value;+ const hit = (v: string) => { if (exact?.has(v.trim())) return true; const low = v.toLowerCase(); return lowered.some(n => low.includes(n)); };+ const walk = (v: unknown): unknown => typeof v === 'string' ? (hit(v) ? '[purged]' : v): Array.isArray(v) ? v.map(walk) : v && typeof v === 'object' ? Object.fromEntries(Object.entries(v).map(([k, x]) => [k, walk(x)])) : v;return walk(value) as T;}@@ -272,7 +273,7 @@ export function redactionCounterKeys(targets: readonly IntentRedactionTarget[]):* `exclude` is the purge's own request id. Returns the number redacted.*/export async function redactRequestIntents(tx: BrainEngine, targets: readonly IntentRedactionTarget[], exclude?: string,- opts: { skipPending?: boolean; needles?: readonly string[] } = {}): Promise<number> {+ opts: { skipPending?: boolean; needles?: readonly string[]; exact?: ReadonlySet<string> } = {}): Promise<number> {const ids = targets.map(t => t.id).filter(id => id !== exclude);if (!ids.length) return 0;await lockCounters(tx, ['brain', ...redactionCounterKeys(targets)]);@@ -290,8 +291,8 @@ export async function redactRequestIntents(tx: BrainEngine, targets: readonly Infor (const current of rows) {if (!isTerminal(current) || current.recovery) continue;// The stored outcome stays the replay answer, with every string carrying the claim replaced by "[purged]".- const outcome = redactJson(current.outcome, opts.needles ?? []);- const detail = redactJson(current.error_detail, opts.needles ?? []);+ const outcome = redactJson(current.outcome, opts.needles ?? [], opts.exact);+ const detail = redactJson(current.error_detail, opts.needles ?? [], opts.exact);if (current.compacted && JSON.stringify(outcome) === JSON.stringify(current.outcome) && JSON.stringify(detail) === JSON.stringify(current.error_detail)&& current.error_message === null) continue;const [effects] = await tx.executeRaw<{ bytes: string }>(`SELECT COALESCE(SUM(${EFFECT_BYTES_SQL}),0)::text AS bytesdiff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.tsindex 11017c2672..e83a09c716 100644--- a/src/core/persistence/page-prepare.ts+++ b/src/core/persistence/page-prepare.ts@@ -667,13 +667,16 @@ async function prepareDeletePageMutation(engine: BrainEngine, row: WriteRequest,&& await originCommitted(engine, row.source_id, snapshot.page.source_path)&& (await engine.executeRaw(`SELECT 1 FROM persistence_requests r WHERE r.source_id=$1 AND r.slug=$2 AND (r.page_id IS NULL OR r.page_id=$3) AND r.operation='delete_page'AND r.state='committed' AND r.outcome->'write_through'->>'skipped'='shared_origin' LIMIT 1`, [row.source_id, row.slug, snapshot.page.id])).length === 0;+ let keepOrigin = false;if (committedFile) {const [made] = await engine.executeRaw<{ sync: boolean }>(`SELECT ${syncDeleteOrigin('p')} AS sync FROM pages p WHERE p.id=$1`, [snapshot.page.id]);- if (made?.sync) throw pageRefusal('revision_conflict', 'The file of this sync-deleted page is committed again, so the retention purge left the page and the file alone; the next sync restores the page.', row,+ // Only a file on disk can come back through sync: one off disk in working-tree mode is purged database-only instead.+ if (made?.sync && existsSync(file!.path)) throw pageRefusal('revision_conflict', 'The file of this sync-deleted page is committed again, so the retention purge left the page and the file alone; the next sync restores the page.', row,`Page ${row.slug}'s file is committed in source ${row.source_id}'s checkout.`, pageFix(row.source_id, row.slug));+ keepOrigin = made?.sync === true;}// #6511: the purge's journal sweep runs here, under the preparation budget, never inside the 5 s publication transaction.- const preparedPurge: PreparedPagePurge | null = purge ? await preparePagePurge(engine, row, snapshot, clock) : null;+ const preparedPurge: PreparedPagePurge | null = purge ? { ...await preparePagePurge(engine, row, snapshot, clock), ...(keepOrigin ? { keepOrigin } : {}) } : null;// #6948: a page merged into its duplicate holds that page's body, so an owner purge would tombstone the survivor's content.if (preparedPurge && !preparedPurge.retention && await isOriginTwinPage(engine, row.source_id, row.slug)) {const error = pageRefusal('source_changed', 'The page was merged into a duplicate that holds the same content, so a purge (which tombstones its content source-wide) was refused and nothing was removed, tombstoned or redacted. 'diff --git a/src/core/persistence/page-purge.ts b/src/core/persistence/page-purge.tsindex 7539c520ec..00dd46f49b 100644--- a/src/core/persistence/page-purge.ts+++ b/src/core/persistence/page-purge.ts@@ -163,6 +163,8 @@ export interface PreparedPagePurge {needles: string[]; sweep: JournalSweep; slugIndex: RequestIndexState['state'];/** Retention removal of an expired tombstone (`gbrain pages purge-deleted`): no content tombstone, no ledger redaction, `page.expired`. */retention: boolean;+ /** GST-2201: a sync-made tombstone purged database-only beside its committed file: the file's return imports it, so no deletion marker. */+ keepOrigin?: boolean;/*** The belief streams locked with the page: those of the rows the derivation walk would hide (their `derived.hidden`* events append under their keys) and those of the links the delete cascades away (their `link.retracted`).@@ -269,6 +271,9 @@ async function tombstonePage(tx: BrainEngine, sourceId: string, slug: string, pa}/** Inside the coordinated delete transaction, before the page row is deleted. */+/** The page's add_timeline_entry receipts one purge redacts; a page with more leaves `journal_sweep.complete` false. */+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;const actor = `${row.principal_kind}:${row.principal_id}`;@@ -327,21 +332,24 @@ export async function purgePageInTransaction(tx: BrainEngine, row: WriteRequest,// #6511 [R2]: the preparation sweep's targets, plus the tail past its ceiling and the rows pending at scan time, re-tested here.const recheck = await lookup('tail_recheck', () => recheckRequestsCarrying(tx, sourceId, needles, prepared.sweep,{ exclude: row.id, beforePending: () => faultPoint('purge:pending_recheck', { requestId: row.request_id, sourceId, operation: row.operation }) }));- // The page's add_timeline_entry receipts keep the entry text in their outcome (`entry`, `bullet`), compacted ones included:- // that text is a needle in the page's own requests, as its reasons are.+ // The page's add_timeline_entry receipts keep the entry text in their outcome (`entry`, `bullet`), compacted ones included.+ // In those receipts the text is matched whole (a set lookup, linear in the receipts); in the page's other requests it is a+ // needle, as its reasons are. A page past the cap leaves the journal sweep incomplete instead of claiming every receipt.const timeline = await lookup('slug_lookup', () => tx.executeRaw<IntentRedactionTarget & { summary: string | null; bullet: string | null }>(`SELECT id::text AS id, principal_kind, principal_id,outcome->'entry'->>'summary' AS summary, outcome->>'bullet' AS bullet FROM persistence_requests- WHERE source_id=$1 AND slug=$2 AND operation='add_timeline_entry' AND outcome ? 'entry' ORDER BY sequence LIMIT 10000`, [sourceId, slug]));- const timelineText = [...new Set(timeline.flatMap(t => [t.summary, t.bullet]).map(text => text?.trim() ?? '').filter(Boolean))];+ WHERE source_id=$1 AND slug=$2 AND operation='add_timeline_entry' AND outcome ? 'entry' ORDER BY sequence LIMIT $3`, [sourceId, slug, TIMELINE_RECEIPT_CAP]));+ const timelineText = new Set(timeline.flatMap(t => [t.summary, t.bullet]).map(text => text?.trim() ?? '').filter(Boolean));+ const timelineIds = new Set(timeline.map(t => t.id));const forSlug = await lookup('slug_lookup', async () => [...await findRequestsForSlugs(tx, sourceId, [slug]), ...reasons.length ? await requestsRecordingReasons(tx, sourceId, slug) : [], ...timeline]);const own = new Set(forSlug.map(r => r.id));const requests = [...new Map([...forSlug, ...prepared.sweep.targets, ...recheck.targets].map(r => [r.id, r])).values()];// GBRA-217: the page's reasons are needles in its own requests only, so a short reason never redacts another page's receipt.- removed.persistence_requests = await lookup('redaction_read', async () => await redactRequestIntents(tx, requests.filter(r => own.has(r.id)), row.id,+ removed.persistence_requests = await lookup('redaction_read', async () => await redactRequestIntents(tx, requests.filter(r => timelineIds.has(r.id)), row.id,+ { skipPending: true, needles: [...needles, ...reasons], exact: timelineText }) + await redactRequestIntents(tx, requests.filter(r => own.has(r.id) && !timelineIds.has(r.id)), row.id,{ skipPending: true, needles: [...needles, ...reasons, ...timelineText] }) + await redactRequestIntents(tx, requests.filter(r => !own.has(r.id)), row.id, { skipPending: true, needles }));removed.persistence_effects = await stripPageGitNotes(tx, sourceId, slug);const journalSweep = { scanned: prepared.sweep.scanned, ceiling: prepared.sweep.ceiling, watermark: prepared.sweep.watermark ?? null, batch: prepared.sweep.batch ?? 1,- tail: recheck.tail, pending_rechecked: recheck.pendingRechecked, complete: prepared.sweep.complete && recheck.complete };+ tail: recheck.tail, pending_rechecked: recheck.pendingRechecked, complete: prepared.sweep.complete && recheck.complete && timeline.length < TIMELINE_RECEIPT_CAP };const files = await tx.executeRaw<{ storage_path: string }>(`DELETE FROM files WHERE (page_id=$1 OR (page_id IS NULL AND page_slug=$2 AND (source_id=$3 OR source_id IS NULL)))RETURNING storage_path`, [page.id, slug, sourceId]);removed.files = files.length;@@ -359,7 +367,7 @@ export async function purgePageInTransaction(tx: BrainEngine, row: WriteRequest,derived_hidden: await appendDerivedHidden(tx, { sourceId, request: row.id, publicationId: row.id, op: 'delete_page', targets: heldTargets, truncated: walk === 'truncated' }),derived_walk: walk })) : null;if (ledger) removed.belief_events = ledger.purged_events + ledger.redacted_fields.length;- await writeOriginDeletedMarker(tx, { sourceId, page: { id: page.id, slug, source_path: page.source_path } });+ if (!prepared.keepOrigin) await writeOriginDeletedMarker(tx, { sourceId, page: { id: page.id, slug, source_path: page.source_path } });const { shas, ...segmentRows } = await deletePageWithSegments(tx, sourceId, slug, page.id, segmentClaims);Object.assign(removed, segmentRows);if (!retention) appendPurgeIntent({ request: row.id, request_id: row.request_id, source_id: sourceId, source_incarnation: row.source_incarnation,diff --git a/src/core/persistence/sync-classify.ts b/src/core/persistence/sync-classify.tsindex 820026430a..240694eba6 100644--- a/src/core/persistence/sync-classify.ts+++ b/src/core/persistence/sync-classify.ts@@ -62,8 +62,9 @@ export interface SyncPathState {/*** An active hold at `p`: whether it is at level `L` in its own domain, re-screen due, or in the retry set. #7199 `unscreened`:* a side-`unknown` drift hold an older gbrain wrote before the drift screen compared the page with the file at the baseline commit.+ * GST-2201 `deletionSide`: a `file_drift` hold on the deletion side (`tombstone_edited`, `purged_differs`, `file_gone`).*/- hold: { atLevel: boolean; rescreenDue: boolean; retried: boolean; unscreened?: boolean } | null;+ hold: { atLevel: boolean; rescreenDue: boolean; retried: boolean; unscreened?: boolean; deletionSide?: boolean } | null;/*** A deletion marker at the origin: `deleted` (with the blob ids it held) or `legacy` (the baseline blob of a page deleted* before PR 4; `deletion` is the committed deleting request that proves it, and a legacy marker without one settles nothing).@@ -159,8 +160,9 @@ type Matched = Omit<SyncClassified, 'inFlight' | 'classAction'>;* is at its level and not re-screen due, the pass re-runs it (`held`, `rescreenDue`).*/function firstMatch(s: SyncPathState, strict = false): Matched {- // GST-2201: a hold an older version raised over a sync-made tombstone whose file came back (tombstone_edited) is re-run.- const syncRestored = s.page?.live === false && s.page.syncDeleted === true && s.level !== null;+ // GST-2201: a deletion-side hold an older version raised over a sync-made tombstone whose file came back (tombstone_edited)+ // is re-run; a hold the import itself raised (invalid frontmatter, a slug conflict) stands.+ const syncRestored = s.page?.live === false && s.page.syncDeleted === true && s.level !== null && s.hold?.deletionSide === true;if (s.hold && s.hold.atLevel && !s.hold.rescreenDue && !s.hold.retried && !syncRestored) return { cls: 'held', settled: true, action: 'none' };const rest = strict ? gitWins(s) : afterHold(s);// The re-run is the import the hold refused, where an import is what the level would get anyway (`import`) or changesdiff --git a/src/core/persistence/sync-pass.ts b/src/core/persistence/sync-pass.tsindex 4db8f5d50f..947118201a 100644--- a/src/core/persistence/sync-pass.ts+++ b/src/core/persistence/sync-pass.ts@@ -820,7 +820,7 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: strecord: record ? { blobOids: recordBlobOids, revision: recordRevision != null ? String(recordRevision) : null, parserSame: sameParser(pages.parserOf(at!), fp(path)) } : null,attested, levelSha256: probe?.rawSha256 ?? null,published: !!attested?.hash && probe?.rawSha256 === attested.hash,- hold: hold ? { atLevel: holdAtLevel(hold, level, probe?.rawSha256 ?? null) && !moved.has(path), rescreenDue: holdRescreenDue(hold, retry.has(hold.path)), retried: retry.has(hold.path), ...(unscreenedDrift(hold) ? { unscreened: true } : {}) } : null,+ hold: hold ? { atLevel: holdAtLevel(hold, level, probe?.rawSha256 ?? null) && !moved.has(path), rescreenDue: holdRescreenDue(hold, retry.has(hold.path)), retried: retry.has(hold.path), ...(unscreenedDrift(hold) ? { unscreened: true } : {}), ...(hold.code === 'file_drift' && fileDriftSide(hold.meta) === 'deleted' ? { deletionSide: true } : {}) } : null,marker: marker ?? virtualMarker, baseline: needsBaseline ? baselineOf(path) : null,spelling: legacySpelling.has(path) ? 'legacy' : twins.has(path),episodeUnsatisfied: input.pass ? !!input.pass.episodeFullId && live && (record ? pages.fullEpisode[at!] : undefined) !== input.pass.episodeFullIddiff --git a/test/purge-eval-fixes.test.ts b/test/purge-eval-fixes.test.tsindex 5a1b8367c9..12dfe857f9 100644--- a/test/purge-eval-fixes.test.ts+++ b/test/purge-eval-fixes.test.ts@@ -26,6 +26,7 @@ import { submissionAuthority } from '../src/core/persistence/authority.ts';import { frozenVerbWriteError, runMemoryWrite } from '../src/core/persistence/verb-errors.ts';import { opError } from '../src/core/ops/contract.ts';import { DELETION_INVENTORY } from '../src/core/deletion-inventory.ts';+import { redactJson } from '../src/core/persistence/intent-redaction.ts';import { withEnv } from './helpers/with-env.ts';const CLAIM = 'Vault combination is 7731';@@ -105,6 +106,16 @@ describe('purge eval fixes', () => {expect(outcomes.map(o => [o.outcome.entry.summary, o.outcome.bullet])).toEqual([['[purged]', '[purged]'], ['[purged]', '[purged]']]);}, 60_000);+ test('W3: timeline text is matched whole in its own receipts, so redacting 5,000 of them costs one set lookup per string', () => {+ const receipts = Array.from({ length: 5000 }, (_, i) => ({ status: 'ok', entry: { date: '2026-02-03', summary: `Entry ${i} for acme-example` }, bullet: `- **2026-02-03** | Entry ${i} for acme-example` }));+ const exact = new Set(receipts.flatMap(r => [r.entry.summary, r.bullet]));+ const started = performance.now();+ const redacted = receipts.map(r => redactJson(r, [], exact));+ expect(performance.now() - started).toBeLessThan(1000);+ expect(redacted.every(r => r.entry.summary === '[purged]' && r.bullet === '[purged]' && r.entry.date === '2026-02-03' && r.status === 'ok')).toBe(true);+ expect(redactJson({ note: 'Entry 7 for acme-example, quoted elsewhere' }, [], exact)).toEqual({ note: 'Entry 7 for acme-example, quoted elsewhere' });+ });+test('39-3: remembering a purged claim refuses with purged_content (verb path, local and remote mapping)', async () => {const id = await seed();await purgeFact(id);diff --git a/test/sync-classify-6712.test.ts b/test/sync-classify-6712.test.tsindex 51fed3183a..8424d71f11 100644--- a/test/sync-classify-6712.test.ts+++ b/test/sync-classify-6712.test.ts@@ -24,7 +24,7 @@ const CLEAN: ReadonlySet<SyncDirtiness | null> = new Set(['clean', 'clean_eol',/** The reference model: page state first, then level, then dirtiness, then the fileSame × dbSame × proof regions. */function reference(s: SyncPathState): SyncClass {- const syncRestored = s.page?.live === false && s.page.syncDeleted === true && s.level !== null;+ const syncRestored = s.page?.live === false && s.page.syncDeleted === true && s.level !== null && s.hold?.deletionSide === true;if (s.hold && s.hold.atLevel && !s.hold.rescreenDue && !s.hold.retried && !syncRestored) return 'held';const rest = referenceAfterHold(s);if (!s.hold) return rest;@@ -96,6 +96,8 @@ describe('rows (v3.2 §2.3)', () => {['9 deleted_edited (tombstone)', { tree: 'B', level: 'B', page: { live: false, revision: 'R1', originMatches: true } }, 'deleted_edited', false],['8 a sync-made tombstone whose file is back unchanged imports (a revert, a branch switch)', { page: { live: false, revision: 'R1', originMatches: true, syncDeleted: true } }, 'import', false],['9 a sync-made tombstone whose file is back edited imports', { tree: 'B', level: 'B', page: { live: false, revision: 'R1', originMatches: true, syncDeleted: true } }, 'import', false],+ ['1 a sync-made tombstone whose file is back under an import hold at its level stays held (the import itself refused)', { page: { live: false, revision: 'R1', originMatches: true, syncDeleted: true }, hold: { atLevel: true, rescreenDue: false, retried: false } }, 'held', true],+ ['1 a deletion-side hold an older version raised over a sync-made tombstone whose file is back is re-run', { tree: 'B', level: 'B', page: { live: false, revision: 'R1', originMatches: true, syncDeleted: true }, hold: { atLevel: true, rescreenDue: false, retried: false, deletionSide: true } }, 'held', false],['7 a sync-made tombstone whose file is still gone stays gone', { mode: 'working', tree: 'A', level: null, present: false, dirty: null, page: { live: false, revision: 'R1', originMatches: true, syncDeleted: true } }, 'gone', true],['9 deleted_edited (marker without OIDs, fail closed)', { page: null, record: null, marker: { kind: 'deleted', blobOids: [] } }, 'deleted_edited', false],['10 legacy_same: a marker that records a deletion', { page: null, record: null, marker: { kind: 'legacy', blobOids: ['A'], deletion: 'req-1' } }, 'legacy_same', true],@@ -173,7 +175,7 @@ const stateArb: fc.Arbitrary<SyncPathState> = fc.record({attested: fc.constantFrom<SyncPathState['attested']>(null, { hash: sha('A'), arm1: false }, { hash: sha('B'), arm1: false }, { hash: null, arm1: true }),published: fc.boolean(),hold: fc.constantFrom<SyncPathState['hold']>(null, { atLevel: true, rescreenDue: false, retried: false }, { atLevel: false, rescreenDue: false, retried: false },- { atLevel: true, rescreenDue: true, retried: false }, { atLevel: true, rescreenDue: false, retried: true }),+ { atLevel: true, rescreenDue: true, retried: false }, { atLevel: true, rescreenDue: false, retried: true }, { atLevel: true, rescreenDue: false, retried: false, deletionSide: true }),marker: fc.constantFrom<SyncPathState['marker']>(null, { kind: 'deleted', blobOids: ['A'] }, { kind: 'deleted', blobOids: [] }, { kind: 'legacy', blobOids: ['A'] }, { kind: 'legacy', blobOids: ['A'], deletion: 'req-1' }),baseline: fc.constantFrom<string | null>(null, 'A', 'B'),spelling: fc.boolean(), episodeUnsatisfied: fc.boolean(), fullObligation: fc.boolean(), keepDb: fc.boolean(), openWork: fc.boolean(),@@ -227,11 +229,13 @@ describe('P0 properties', () => {}), { numRuns: 40_000, seed: 67121 });});- test('(j2) a tombstone sync made from a file\'s absence imports the file once it is back, a hold over it included', () => {+ test('(j2) a tombstone sync made from a file\'s absence imports the file once it is back, a deletion-side hold over it included', () => {fc.assert(fc.property(stateArb, s => {if (s.page?.live !== false || !s.page.syncDeleted || s.level === null || s.spelling) return;if (s.mode === 'committed' && (s.tree === null || !['clean', 'clean_eol', 'clean_lfs', 'deleted'].includes(s.dirty!))) return;- expect(classifySyncPath(s)).toMatchObject(s.hold ? { cls: 'held', action: 'import', settled: false } : { cls: 'import', action: 'import', settled: false });+ const standing = !!s.hold && s.hold.atLevel && !s.hold.rescreenDue && !s.hold.retried && !s.hold.deletionSide;+ expect(classifySyncPath(s)).toMatchObject(standing ? { cls: 'held', action: 'none', settled: true }+ : s.hold ? { cls: 'held', action: 'import', settled: false } : { cls: 'import', action: 'import', settled: false });}), { numRuns: 40_000, seed: 22011 });});diff --git a/test/sync-restored-file-purge.test.ts b/test/sync-restored-file-purge.test.tsindex c7d74e0923..61ae7fb430 100644--- a/test/sync-restored-file-purge.test.ts+++ b/test/sync-restored-file-purge.test.ts@@ -229,6 +229,41 @@ for (const backend of testBackends()) {});describe(`${backend}: the retention purge never removes a file that is committed`, () => {+ test('working-tree mode: a sync-deleted page whose committed file stays off disk is purged database-only, not deferred forever', () => managedBrain(async ({ engine, root }) => {+ await engine.setConfig('sync.include_working_tree', 'true');+ await sync(engine);+ const parked = join(root, '..', 'doc-a.parked');+ renameSync(join(root, `${A}.md`), parked);+ await sync(engine);+ expect((await page(engine, A))?.deleted_at).not.toBeNull();+ await age(engine, 100);+ await purge(engine, root, 'CLI purge-deleted');+ expect(await page(engine, A)).toBeUndefined();+ expect(git(root, 'ls-tree', '--name-only', 'HEAD', '--', `${A}.md`)).toBe(`${A}.md`);+ renameSync(parked, join(root, `${A}.md`));+ await sync(engine);+ expect((await page(engine, A))?.deleted_at).toBeNull();+ fileKept(root, A);+ }, { setup, databaseUrl }), 300_000);++ test('a sync-made tombstone whose returned file sync holds is refused with the hold, not deferred, and the file stays', () => managedBrain(async ({ engine, root }) => {+ await sync(engine);+ await removeAndSync(engine, root, [A]);+ const broken = '---\ntype: concept\ntitle: [unclosed\n---\n\nAlice-example wrote about topic a.\n';+ writeFileSync(join(root, `${A}.md`), broken); commit(root, 're-add with broken frontmatter');+ await sync(engine);+ expect((await page(engine, A))?.deleted_at).not.toBeNull();+ expect((await status(engine)).state).not.toBe('synced');+ await age(engine, 100);+ const { purgeDeletedPagesCoordinated } = await import('../src/core/persistence/purge-deleted.ts');+ const result = await purgeDeletedPagesCoordinated(engine, 72);+ expect({ count: result.count, deferred: result.deferred, codes: result.blocked.map(b => b.code) }).toEqual({ count: 0, deferred: 0, codes: ['source_changed'] });+ expect(result.blocked[0]!.reason).toContain('held by sync (invalid_frontmatter)');+ expect((await page(engine, A))?.deleted_at).not.toBeNull();+ expect(readFileSync(join(root, `${A}.md`), 'utf8')).toBe(broken);+ expect(git(root, 'status', '--porcelain', '--', `${A}.md`)).toBe('');+ }, { setup, databaseUrl }), 300_000);+test("an older version purged the page and committed the file's removal; a revert of that commit imports the file as a new page", () => managedBrain(async ({ engine, root }) => {await sync(engine);const before = await page(engine, A);