Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

wip(#6712 PR 4b lane M): deletion markers, withheld record, GC exemptions

garrytan3c8a6331147f
diff --git a/src/core/belief/purge-mirror.ts b/src/core/belief/purge-mirror.ts
index 44e2f8ab74..fa062ab966 100644
--- a/src/core/belief/purge-mirror.ts
+++ b/src/core/belief/purge-mirror.ts
@@ -31,6 +31,7 @@ import { COVERAGE_KEY, factKey, pageKey, slugRef } from './keys.ts';
import { appendBeliefEvents, type BeliefEventDraft } from './append.ts';
import { appendDerivedHidden, bumpPurgeEpoch, derivedBeliefTargets, pageLifetimesOf, pagePurgeClaims, redactCarryingFields, redactPurgedKeys, registerLiveCarriers } from './purge.ts';
import { derivedRowsFrom, hideDerivedRows, type DerivationRef } from '../facts/derivation-inputs.ts';
+import { writeOriginDeletedMarker } from '../persistence/sync-markers.ts';
export const PURGE_MIRROR_FILE = 'purge-events.jsonl';
@@ -126,11 +127,11 @@ async function replayOne(tx: BrainEngine, intent: PurgeMirrorIntent, ledger: boo
let inputs: DerivationRef[] = [];
let removeRows = async () => {};
if (intent.scope === 'page' && intent.slug) {
- const [page] = await tx.executeRaw<{ id: number; slug: string }>(`SELECT p.id, p.slug FROM pages p WHERE p.source_id = $1 AND (p.content_hash = ANY($2::text[])
+ const [page] = await tx.executeRaw<{ id: number; slug: string; source_path: string | null }>(`SELECT p.id, p.slug, p.source_path FROM pages p WHERE p.source_id = $1 AND (p.content_hash = ANY($2::text[])
${ledger ? 'OR p.id IN (SELECT l.page_id FROM belief_page_lifetimes l WHERE l.source_id = $1 AND l.page_lifetime = ANY($3::uuid[]))' : 'OR $3::uuid[] IS NULL'})
ORDER BY (p.slug = $4) DESC, p.id LIMIT 1`, [src, intent.content_hashes ?? [], intent.lifetimes, intent.slug]);
if (page) {
- const restored = { id: Number(page.id), slug: page.slug };
+ const restored = { id: Number(page.id), slug: page.slug, source_path: page.source_path };
if (ledger) lifetimes = [...new Set([...lifetimes, ...await pageLifetimesOf(tx, src, restored.slug, restored.id)])];
claims = (await pagePurgeClaims(tx, { sourceId: src, slug: restored.slug, pageId: restored.id, lifetimes: ledger ? lifetimes : [] })).claims;
const owned = await tx.executeRaw<{ t: string; id: number }>(`SELECT 'facts' AS t, id FROM facts WHERE source_id = $1 AND source_markdown_slug = $2
@@ -138,6 +139,7 @@ async function replayOne(tx: BrainEngine, intent: PurgeMirrorIntent, ledger: boo
inputs = [{ table: 'pages', id: restored.id }, ...owned.map(r => ({ table: r.t, id: Number(r.id) }))];
removeRows = async () => {
await tx.executeRaw('DELETE FROM facts WHERE source_id = $1 AND source_markdown_slug = $2', [src, restored.slug]);
+ await writeOriginDeletedMarker(tx, { sourceId: src, page: restored });
await tx.deletePage(restored.slug, { sourceId: src });
};
}
diff --git a/src/core/op-checkpoint.ts b/src/core/op-checkpoint.ts
index 5f83ab0b4f..d17f16e676 100644
--- a/src/core/op-checkpoint.ts
+++ b/src/core/op-checkpoint.ts
@@ -4,6 +4,7 @@ import { withRetry, BULK_RETRY_OPTS, RetryAbortError } from './retry.ts';
import { FENCE_REPAIR_ATTEMPT_OP } from './fence-repair/attempts.ts';
import { FENCE_CANDIDATE_OP, FENCE_SCAN_OP } from './fence-repair/census-store.ts';
import { FENCE_UNCOMMITTED_OP } from './fence-repair/uncommitted.ts';
+import { SYNC_PASS_ROW_OPS } from './persistence/sync-pass-row.ts';
/** Max paths per append-INSERT round-trip; bounds the param-array size. */
const APPEND_CHUNK = 1000;
@@ -491,9 +492,10 @@ export function syncFingerprint(p: { sourceId?: string; lastCommit: string }): s
* sync holds, their summary while it counts any, retry requests, sync
* import provenance, the blocked-cursor conversion log, and the #6188 fence
* census (candidates and scan cursors), paid fence-repair attempt claims
- * and memos, and uncommitted legacy fence-repair notices of a live source
- * incarnation leave only on resolution (or with
- * the incarnation), and connector hold-retry requests and stuck-recovery
+ * and memos, uncommitted legacy fence-repair notices, and the #6712 managed
+ * sync pass row, deletion markers, withheld mass-delete record and cost
+ * reservations (`SYNC_PASS_ROW_OPS`) of a live source incarnation leave only
+ * on resolution (or with the incarnation), and connector hold-retry requests and stuck-recovery
* resolution audit entries never expire (#5988, #6650).
*/
export async function purgeStaleCheckpoints(
@@ -511,7 +513,7 @@ export async function purgeStaleCheckpoints(
AND op NOT IN ('managed-atoms','managed-atoms-generation','managed-connector','managed-connector-retry','managed-connector-state','managed-connector-migration')
AND op<>'connector-hold-retry'
AND op<>'stuck-recovery-resolution'
- AND NOT (op IN ('sync-hold','sync-hold-retry','sync-import-provenance','sync-hold-summary','sync-conversions','${FENCE_CANDIDATE_OP}','${FENCE_SCAN_OP}','${FENCE_REPAIR_ATTEMPT_OP}','${FENCE_UNCOMMITTED_OP}')
+ AND NOT (op IN ('sync-hold','sync-hold-retry','sync-import-provenance','sync-hold-summary','sync-conversions','${FENCE_CANDIDATE_OP}','${FENCE_SCAN_OP}','${FENCE_REPAIR_ATTEMPT_OP}','${FENCE_UNCOMMITTED_OP}',${SYNC_PASS_ROW_OPS.map(op => `'${op}'`).join(',')})
AND NOT (op='sync-hold-summary' AND COALESCE((completed_keys->0->>'count')::int,0)=0)
AND EXISTS (SELECT 1 FROM sources s WHERE s.id=op_checkpoints.completed_keys->0->>'source_id'
AND s.incarnation::text=op_checkpoints.completed_keys->0->>'incarnation'))
diff --git a/src/core/persistence/fault-points.ts b/src/core/persistence/fault-points.ts
index 2f29a536a6..61fbaf94d0 100644
--- a/src/core/persistence/fault-points.ts
+++ b/src/core/persistence/fault-points.ts
@@ -35,6 +35,8 @@ export type FaultPoint = `publication:${PublicationBoundary}` | `effect:${Effect
| 'purge:sweep_chunk' | 'purge:carrying_lookup'
// 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'
+ // #6712 PR 4b: after a page-row deletion of a managed Git source wrote its origin's deletion marker (sync-markers.ts), before the row goes.
+ | 'purge:marker_written'
// #6650: `gbrain repair stuck-recovery` (recovery-resolve.ts): after the backup is durable (before its journal step), after the prior
// bytes are written (before their journal step), after a --keep disk write is abandoned (its journal step written), and after recoverPublication returns.
| 'stuck_recovery:backed_up' | 'stuck_recovery:written' | 'stuck_recovery:abandoned' | 'stuck_recovery:recovered'
diff --git a/src/core/persistence/page-purge.ts b/src/core/persistence/page-purge.ts
index c3886bd4b1..35d3f311d2 100644
--- a/src/core/persistence/page-purge.ts
+++ b/src/core/persistence/page-purge.ts
@@ -36,6 +36,7 @@ import { enterClaimStep, type ClaimPhaseClock } from './claim-phase.ts';
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 { findRequestsForSlugs, recheckRequestsCarrying, redactRequestIntents, sweepRequestsCarrying, type JournalSweep } from './intent-redaction.ts';
import { dropPurgedFenceRows } from '../facts/purge-overlay.ts';
import { derivedRowsFrom, hideDerivedRows } from '../facts/derivation-inputs.ts';
@@ -245,6 +246,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 } });
await tx.deletePage(slug, { sourceId });
if (!retention) appendPurgeIntent({ request: row.id, request_id: row.request_id, source_id: sourceId, source_incarnation: row.source_incarnation,
scope: 'page', slug, purge_epoch: epoch, content_hashes: [...hashes], facts: mirrorFacts, takes: mirrorTakes, lifetimes });
diff --git a/src/core/persistence/sync-markers.ts b/src/core/persistence/sync-markers.ts
new file mode 100644
index 0000000000..817271415e
--- /dev/null
+++ b/src/core/persistence/sync-markers.ts
@@ -0,0 +1,169 @@
+/**
+ * #6712 PR 4b (design v3.2 §2.5, §2.6): the deletion marker of a managed Git source's origin, and the source-level
+ * record of a withheld mass delete. Both are `op_checkpoints` rows whose value carries `source_id` and `incarnation`,
+ * so the checkpoint GC keeps them while the incarnation lives (`op-checkpoint.ts`).
+ *
+ * - `sync-origin-deleted`, fingerprint `<source>:<incarnation>:<origin>`: written by `writeOriginDeletedMarker` in
+ * the transaction of every page-row deletion of a managed Git source (`page-purge.ts`, the belief purge-mirror
+ * replay), only when it can matter: the origin is in the source's `last_commit` tree or a file backs it on disk.
+ * The classifier reads it (`sync-pass.ts` `readMarkers`: `kind`, `blob_oids`), so a purged page's unchanged file
+ * settles `deleted_same` and a changed one is held, never imported as a new page. A full round retires it by
+ * compare-and-delete (`retireOriginDeletedMarker`) when the origin is independently absent from the pinned tree
+ * and the disk, or a live page claims the origin again.
+ * - `sync-deletes-withheld`, fingerprint `<source>:<incarnation>`: a round's tripped mass-delete valve (#2828),
+ * refreshed each pass while the trip lasts and cleared when it clears.
+ */
+import { realpathSync } from 'node:fs';
+import { relative, resolve, sep } from 'node:path';
+import type { BrainEngine } from '../engine.ts';
+import { hardenedGitSync } from '../hardened-git.ts';
+import { companyBrainProfile } from '../company-brain/policy.ts';
+import { sha256 } from './digest.ts';
+import { faultPoint } from './fault-points.ts';
+import { getWorktreeBinding, managedPersistenceEnabled } from './ownership.ts';
+import { readSyncFile } from './sync-discovery.ts';
+import { readSyncImportProvenance } from './sync-holds.ts';
+import { syncOriginPath } from './sync-origin.ts';
+import { SYNC_DELETES_WITHHELD_OP, SYNC_ORIGIN_DELETED_OP, passFingerprint } from './sync-pass-row.ts';
+
+type Exec = Pick<BrainEngine, 'executeRaw'>;
+
+export interface OriginDeletedMarker {
+ source_id: string;
+ incarnation: string;
+ kind: 'deleted';
+ /** The blob ids the brain held for the origin (the import record's `blob_oid` and `disk_blob_oid`); empty without a record, so every level differs (fail closed). */
+ blob_oids: string[];
+ page_id: number;
+ slug: string;
+ at: string;
+}
+
+export const originMarkerFingerprint = (sourceId: string, incarnation: string, origin: string) => `${sourceId}:${incarnation}:${syncOriginPath(origin)}`;
+
+/** Bounds of the `ls-tree` read that decides whether the purged origin is still committed. */
+const TREE_READ_LIMITS = { timeoutMs: 10_000, maxBytes: 1024 * 1024 };
+
+/**
+ * Whether the marker can matter: the origin is in the `last_commit` tree, or a file backs it on disk. Every read that
+ * cannot answer counts as present (fail closed), so an unreadable checkout or tree writes the marker.
+ */
+function originStillBacked(root: string | null, lastCommit: string | null, slugMode: string | null, sourcePath: string): boolean {
+ if (!root) return true;
+ const toplevel = hardenedGitSync(root, ['rev-parse', '--show-toplevel'], { timeoutMs: 10_000, maxBytes: 4096 });
+ if (!toplevel.ok) return true;
+ const gitRoot = toplevel.stdout.toString('utf8').trim();
+ let scope: string;
+ try { scope = relative(realpathSync.native(gitRoot), realpathSync.native(root)).split(sep).join('/'); } catch { return true; }
+ if (scope.startsWith('..')) return true;
+ const candidates = new Set<string>();
+ if (slugMode !== 'git-root') candidates.add(scope ? `${scope}/${sourcePath}` : sourcePath);
+ if (slugMode !== 'source-root' && (!scope || sourcePath.startsWith(`${scope}/`))) candidates.add(sourcePath);
+ for (const gitPath of candidates) {
+ try { if (readSyncFile(root, scope ? gitPath.slice(scope.length + 1) : gitPath) !== null) return true; } catch { return true; }
+ }
+ if (!lastCommit || candidates.size === 0) return false;
+ const tree = hardenedGitSync(gitRoot, ['ls-tree', '-z', '--full-tree', lastCommit, '--', ...candidates], TREE_READ_LIMITS);
+ return !tree.ok || tree.stdout.length > 0;
+}
+
+/**
+ * Writes the deletion marker of `page`'s origin inside `tx`, the transaction that deletes the page row (call it before
+ * the delete). Writes nothing on an unmanaged brain, for a page without an origin, while another live page records the
+ * origin (a shared origin, #6517: the live page owns it), for a source without a worktree binding or a company-brain
+ * source (its frozen manifest decides), or when the origin left both `last_commit` and the disk. Returns the marker
+ * written, or null.
+ */
+export async function writeOriginDeletedMarker(tx: BrainEngine, input: { sourceId: string; page: { id: number; slug: string; source_path?: string | null } }):
+ Promise<OriginDeletedMarker | null> {
+ const { sourceId, page } = input;
+ if (!page.source_path) return null;
+ let origin: string;
+ try { origin = syncOriginPath(page.source_path); } catch { return null; }
+ if (!await managedPersistenceEnabled(tx)) return null;
+ const [owned] = await tx.executeRaw('SELECT 1 FROM pages WHERE source_id=$1 AND id<>$2 AND deleted_at IS NULL AND source_path = ANY($3::text[]) LIMIT 1',
+ [sourceId, page.id, [...new Set([page.source_path, origin, `./${origin}`])]]);
+ if (owned) return null;
+ const [source] = await tx.executeRaw<{ incarnation: string; last_commit: string | null; config: Record<string, unknown> | null }>(
+ 'SELECT incarnation::text AS incarnation, last_commit, config FROM sources WHERE id=$1', [sourceId]);
+ if (!source || companyBrainProfile(source.config) !== null) return null;
+ const binding = await getWorktreeBinding(tx, sourceId);
+ if (!binding) return null;
+ const root = binding.local_path ? resolve(binding.local_path, binding.relative_path) : null;
+ const slugMode = typeof source.config?.slug_root_mode === 'string' ? source.config.slug_root_mode : null;
+ if (!originStillBacked(root, source.last_commit, slugMode, page.source_path)) return null;
+ const record = await readSyncImportProvenance(tx, sourceId, source.incarnation, page.id);
+ const marker: OriginDeletedMarker = {
+ source_id: sourceId, incarnation: source.incarnation, kind: 'deleted',
+ blob_oids: [...new Set([record?.blob_oid, record?.disk_blob_oid].filter((oid): oid is string => typeof oid === 'string' && oid.length > 0))],
+ page_id: page.id, slug: page.slug, at: new Date().toISOString(),
+ };
+ await tx.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at) VALUES($1,$2,jsonb_build_array($3::text::jsonb),now())
+ ON CONFLICT (op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys, updated_at=now()`,
+ [SYNC_ORIGIN_DELETED_OP, originMarkerFingerprint(sourceId, source.incarnation, origin), JSON.stringify(marker)]);
+ await faultPoint('purge:marker_written', { sourceId, slug: page.slug, path: origin });
+ return marker;
+}
+
+/** The deletion marker at one origin of an incarnation, or null. */
+export async function readOriginDeletedMarker(exec: Exec, sourceId: string, incarnation: string, origin: string): Promise<OriginDeletedMarker | null> {
+ const [row] = await exec.executeRaw<{ value: OriginDeletedMarker | null }>('SELECT completed_keys->0 AS value FROM op_checkpoints WHERE op=$1 AND fingerprint=$2',
+ [SYNC_ORIGIN_DELETED_OP, originMarkerFingerprint(sourceId, incarnation, origin)]);
+ return row?.value ?? null;
+}
+
+/**
+ * Retires a marker by compare-and-delete on the value the pass read: a marker rewritten since (another purge at the
+ * same origin) stays. Returns whether it was deleted.
+ */
+export async function retireOriginDeletedMarker(tx: Exec, input: { sourceId: string; incarnation: string; origin: string; expected: unknown }): Promise<boolean> {
+ const rows = await tx.executeRaw('DELETE FROM op_checkpoints WHERE op=$1 AND fingerprint=$2 AND completed_keys->0 = $3::text::jsonb RETURNING 1',
+ [SYNC_ORIGIN_DELETED_OP, originMarkerFingerprint(input.sourceId, input.incarnation, input.origin), JSON.stringify(input.expected)]);
+ return rows.length > 0;
+}
+
+/** The sample paths a withheld record keeps. */
+export const DELETES_WITHHELD_SAMPLES = 20;
+
+export interface DeletesWithheld {
+ source_id: string;
+ incarnation: string;
+ /** The pinned commit of the round that tripped the valve. */
+ target: string;
+ count: number;
+ /** The valve's denominator: live file-backed pages whose origin is eligible. */
+ reconcilable: number;
+ ratio: number;
+ /** `deleteSetHash` of the withheld paths: the record matches a later trip only while the set is the same. */
+ set_hash: string;
+ samples: string[];
+ at: string;
+}
+
+/** sha256 (hex) over the set of paths, sorted and joined with NUL. */
+export function deleteSetHash(paths: Iterable<string>): string {
+ return sha256([...new Set(paths)].sort().join('\0'));
+}
+
+/** Writes (or refreshes) the source's withheld mass-delete record inside `tx`; keeps the first `DELETES_WITHHELD_SAMPLES` samples. */
+export async function writeDeletesWithheld(tx: Exec, input: { sourceId: string; incarnation: string; target: string; count: number; reconcilable: number; ratio: number;
+ set_hash: string; samples: readonly string[] }): Promise<DeletesWithheld> {
+ const value: DeletesWithheld = { source_id: input.sourceId, incarnation: input.incarnation, target: input.target, count: input.count, reconcilable: input.reconcilable,
+ ratio: input.ratio, set_hash: input.set_hash, samples: input.samples.slice(0, DELETES_WITHHELD_SAMPLES), at: new Date().toISOString() };
+ await tx.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at) VALUES($1,$2,jsonb_build_array($3::text::jsonb),now())
+ ON CONFLICT (op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys, updated_at=now()`,
+ [SYNC_DELETES_WITHHELD_OP, passFingerprint(input.sourceId, input.incarnation), JSON.stringify(value)]);
+ return value;
+}
+
+export async function readDeletesWithheld(exec: Exec, sourceId: string, incarnation: string): Promise<DeletesWithheld | null> {
+ const [row] = await exec.executeRaw<{ value: DeletesWithheld | null }>('SELECT completed_keys->0 AS value FROM op_checkpoints WHERE op=$1 AND fingerprint=$2',
+ [SYNC_DELETES_WITHHELD_OP, passFingerprint(sourceId, incarnation)]);
+ return row?.value ?? null;
+}
+
+/** Deletes the source's withheld record (the trip cleared); returns whether one existed. */
+export async function clearDeletesWithheld(tx: Exec, sourceId: string, incarnation: string): Promise<boolean> {
+ return (await tx.executeRaw('DELETE FROM op_checkpoints WHERE op=$1 AND fingerprint=$2 RETURNING 1',
+ [SYNC_DELETES_WITHHELD_OP, passFingerprint(sourceId, incarnation)])).length > 0;
+}
diff --git a/test/sync-origin-markers-6712.test.ts b/test/sync-origin-markers-6712.test.ts
new file mode 100644
index 0000000000..97625fb658
--- /dev/null
+++ b/test/sync-origin-markers-6712.test.ts
@@ -0,0 +1,147 @@
+/**
+ * #6712 PR 4b lane M (design v3.2 §2.5, probes 44, 45, 22): the deletion marker every page-row deletion of a managed
+ * Git source writes, on a real managed brain (PGLite plus a Git checkout).
+ *
+ * Authoring gate: (1) protects the classifier's view of a purged origin: an unchanged file stays `deleted_same` and a
+ * changed one `deleted_edited`, never `import` (resurrection); (2) a purge or a mirrored purge replay that writes no
+ * marker, one written where it cannot matter (the origin left `last_commit` and the disk) or under a live page that
+ * still owns the origin, fails here; (3) the helper's unit test cannot see the purge transaction or the replay;
+ * (4) no seam: purges run through the coordinator and the replay through `replayPurges`, as production calls them.
+ */
+import { describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { readShadowLevel } from '../src/core/persistence/sync-pass.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
+import { replayPurges, type PurgeMirrorLine } from '../src/core/belief/purge-mirror.ts';
+import { SYNC_IMPORT_PROVENANCE_OP } from '../src/core/persistence/sync-holds.ts';
+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+const commit = (root: string, message: string) => { git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message); };
+const note = (title: string, body: string) => `---\ntitle: ${title}\n---\n\n${body}\n`;
+const NAMES = ['alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta', 'eta', 'theta'];
+const setup = ({ root }: { root: string }) => {
+ git(root, 'init', '-q');
+ mkdirSync(join(root, 'notes'), { recursive: true });
+ for (const name of NAMES) writeFileSync(join(root, 'notes', name + '.md'), note(name, 'Synthetic ' + name + ' one.'));
+ commit(root, 'notes');
+};
+const SYNC = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };
+
+async function markers(engine: BrainEngine): Promise<Map<string, { kind: string; blob_oids: string[]; slug: string; page_id: number; source_id: string; incarnation: string }>> {
+ const rows = await engine.executeRaw<{ fingerprint: string; value: any }>("SELECT fingerprint, completed_keys->0 AS value FROM op_checkpoints WHERE op='sync-origin-deleted'");
+ return new Map(rows.map(row => [row.fingerprint.split(':').slice(2).join(':'), row.value]));
+}
+async function recordOids(engine: BrainEngine, origin: string): Promise<string[]> {
+ const [row] = await engine.executeRaw<{ record: { blob_oid?: string; disk_blob_oid?: string } }>(
+ "SELECT completed_keys->0 AS record FROM op_checkpoints WHERE op=$1 AND completed_keys->0->>'origin'=$2", [SYNC_IMPORT_PROVENANCE_OP, origin]);
+ return [...new Set([row?.record.blob_oid, row?.record.disk_blob_oid].filter((oid): oid is string => !!oid))];
+}
+async function mutate(ctx: OperationContext, engine: BrainEngine, slug: string, extra: Record<string, unknown> = {}) {
+ const snapshot = await engine.readPageSnapshot(slug, { sourceId: 'default', includeDeleted: true });
+ return submitPageMutation(ctx, { operation: 'delete_page', params: { slug, request_id: randomUUID(), expected_revision: snapshot!.revision, ...extra }, waitMs: 30_000 });
+}
+const purge = (ctx: OperationContext, engine: BrainEngine, slug: string) => mutate(ctx, engine, slug, { purge: true });
+const pageRow = async (engine: BrainEngine, slug: string) => (await engine.executeRaw<{ id: number; deleted_at: unknown; content_hash: string }>(
+ "SELECT id, deleted_at, content_hash FROM pages WHERE source_id='default' AND slug=$1", [slug]))[0] ?? null;
+async function classOf(engine: BrainEngine, path: string) {
+ const level = (await readShadowLevel(engine, { sourceId: 'default' }))!;
+ return level.paths.find(entry => entry.path === path)?.result ?? null;
+}
+
+describe('#6712 PR 4b deletion markers (pglite)', () => {
+ test('probe 44: a purge leaves a marker while the origin is in last_commit or on disk, and none once the file left both', () => managedBrain(async ({ engine, ctx, root }) => {
+ expect((await performManagedSync(engine, SYNC)).status).toBe('first_sync');
+ await engine.setConfig('sync.write_through', 'false');
+
+ // In last_commit only: a database delete, then the file removed from the worktree alone, then the purge.
+ const betaOids = await recordOids(engine, 'notes/beta.md');
+ expect(betaOids.length).toBeGreaterThan(0);
+ expect((await mutate(ctx, engine, 'notes/beta')).state).toBe('committed');
+ rmSync(join(root, 'notes', 'beta.md'));
+ expect((await purge(ctx, engine, 'notes/beta')).state).toBe('committed');
+ expect(await pageRow(engine, 'notes/beta')).toBeNull();
+ const [source] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text AS incarnation FROM sources WHERE id='default'");
+ expect((await markers(engine)).get('notes/beta.md')).toMatchObject({ kind: 'deleted', blob_oids: betaOids, slug: 'notes/beta', source_id: 'default', incarnation: source!.incarnation });
+
+ // On disk only: the commit no longer has it, the file is still there.
+ git(root, 'rm', '-q', '--cached', 'notes/gamma.md');
+ git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'untrack gamma');
+ await performManagedSync(engine, SYNC);
+ const [after] = await engine.executeRaw<{ last_commit: string }>("SELECT last_commit FROM sources WHERE id='default'");
+ expect(after!.last_commit).toBe(git(root, 'rev-parse', 'HEAD'));
+ expect(git(root, 'ls-tree', after!.last_commit, '--', 'notes/gamma.md')).toBe('');
+ expect((await purge(ctx, engine, 'notes/gamma')).state).toBe('committed');
+ expect((await markers(engine)).get('notes/gamma.md')).toMatchObject({ kind: 'deleted', slug: 'notes/gamma' });
+
+ // Left both: git rm, commit, the sync deletes the page, then the purge writes nothing.
+ await engine.setConfig('sync.write_through', 'true');
+ git(root, 'rm', '-q', 'notes/alpha.md');
+ git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'remove alpha');
+ await performManagedSync(engine, SYNC);
+ expect((await pageRow(engine, 'notes/alpha'))?.deleted_at).toBeTruthy();
+ expect((await purge(ctx, engine, 'notes/alpha')).state).toBe('committed');
+ expect(await pageRow(engine, 'notes/alpha')).toBeNull();
+ expect((await markers(engine)).has('notes/alpha.md')).toBe(false);
+ // ...so a new file at that path is a new page.
+ writeFileSync(join(root, 'notes', 'alpha.md'), note('alpha', 'A new alpha.'));
+ commit(root, 'new alpha');
+ expect((await classOf(engine, 'notes/alpha.md'))?.cls).toBe('import');
+ }, { setup }), 240_000);
+
+ test('probe 44 (shared origin): a purged tombstone whose origin a live page still records writes no marker; without the twin it does', () => managedBrain(async ({ engine, ctx }) => {
+ expect((await performManagedSync(engine, SYNC)).status).toBe('first_sync');
+ await engine.setConfig('sync.write_through', 'false');
+ // Without a twin: the marker is written (the origin is in last_commit and on disk).
+ expect((await mutate(ctx, engine, 'notes/eta')).state).toBe('committed');
+ expect((await purge(ctx, engine, 'notes/eta')).state).toBe('committed');
+ expect((await markers(engine)).has('notes/eta.md')).toBe(true);
+ // A live twin records delta's file; delta is soft-deleted (shared_origin) and purged: the twin owns the origin.
+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.putPage('notes/delta-twin', { type: 'note', title: 'Twin', compiled_truth: 'A twin recording delta.',
+ timeline: '', frontmatter: {}, content_hash: 'twin-delta', source_path: 'notes/delta.md' }, { sourceId: 'default' }), TEST_WRITE_ATTRIBUTION));
+ expect((await mutate(ctx, engine, 'notes/delta')).state).toBe('committed');
+ expect((await purge(ctx, engine, 'notes/delta')).state).toBe('committed');
+ expect(await pageRow(engine, 'notes/delta')).toBeNull();
+ expect((await markers(engine)).has('notes/delta.md')).toBe(false);
+ }, { setup }), 240_000);
+
+ test('probe 45: a mirrored purge replay writes a marker, and the classifier reads deleted_same / deleted_edited for that path, never import', () => managedBrain(async ({ engine, root }) => {
+ expect((await performManagedSync(engine, SYNC)).status).toBe('first_sync');
+ const page = (await pageRow(engine, 'notes/epsilon'))!;
+ const [source] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text AS incarnation FROM sources WHERE id='default'");
+ const request = randomUUID();
+ const lines: PurgeMirrorLine[] = [
+ { kind: 'intent', request, request_id: request, source_id: 'default', source_incarnation: source!.incarnation, scope: 'page', recorded_at: new Date().toISOString(),
+ purge_epoch: 0, slug: 'notes/epsilon', content_hashes: [page.content_hash], facts: [], takes: [], lifetimes: [] },
+ { kind: 'committed', request, recorded_at: new Date().toISOString() },
+ ];
+ const replay = await replayPurges(engine, { lines, archivedAt: new Date(Date.now() - 60_000).toISOString(), apply: true });
+ expect(replay.replays.map(r => r.request)).toEqual([request]);
+ expect(await pageRow(engine, 'notes/epsilon')).toBeNull();
+ expect((await markers(engine)).get('notes/epsilon.md')).toMatchObject({ kind: 'deleted', slug: 'notes/epsilon', blob_oids: await recordOids(engine, 'notes/epsilon.md') });
+ expect(await classOf(engine, 'notes/epsilon.md')).toMatchObject({ cls: 'deleted_same', settled: true });
+ writeFileSync(join(root, 'notes', 'epsilon.md'), note('epsilon', 'Synthetic epsilon two.'));
+ commit(root, 'edit epsilon');
+ expect(await classOf(engine, 'notes/epsilon.md')).toMatchObject({ cls: 'deleted_edited', state: 'purged_differs' });
+ }, { setup }), 240_000);
+
+ test('probe 22: a manual purge, then the same bytes back in a later commit, classifies deleted_same, never import', () => managedBrain(async ({ engine, ctx, root }) => {
+ expect((await performManagedSync(engine, SYNC)).status).toBe('first_sync');
+ await engine.setConfig('sync.write_through', 'false');
+ expect((await purge(ctx, engine, 'notes/zeta')).state).toBe('committed');
+ expect((await markers(engine)).has('notes/zeta.md')).toBe(true);
+ git(root, 'rm', '-q', 'notes/zeta.md');
+ git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'remove zeta');
+ writeFileSync(join(root, 'notes', 'zeta.md'), note('zeta', 'Synthetic zeta one.'));
+ commit(root, 'zeta back');
+ expect(await classOf(engine, 'notes/zeta.md')).toMatchObject({ cls: 'deleted_same', settled: true });
+ }, { setup }), 240_000);
+});