Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sync): preserve pages when deleting unowned files (#5648, #5565)
garrytan5c25d42591a2
diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.mdindex ca43e2b428..dc328e35cc 100644--- a/docs/architecture/key-files/google-and-loops-continued.md+++ b/docs/architecture/key-files/google-and-loops-continued.md@@ -15,7 +15,7 @@- `src/core/persistence/diagnostics.ts` — trusted administrator counts for owners/epochs, queued bytes/age, outbox recovery, configured quota usage and actionable capacity warnings; bigint values are transport-safe strings and diagnostics exclude intent, credentials and private paths.-- **`src/core/persistence/sync-discovery.ts`** + **`sync-origin.ts`** — managed owner-only Git discovery with source-relative exclusions and one-statement page identity/revision snapshots. Nested full discovery filters source scope before slicing paths. Windows separator aliases retain their page identity; ambiguous aliases refuse, while POSIX backslashes/case remain exact. Under `source-root` mode a stored `<scope>/<path>` origin (the Git-root form older write-through minted from the slug, recognized because `<path>` names the page slug) is accepted as `<path>` at discovery, freeze, preparation and the page-origin query, and an import rewrites it in place; when both readings name existing files the stored origin refuses with `detail: ambiguous_source_path`. A genuine origin mismatch refuses with `detail: sync_origin_mismatch` and the filled paths. Deletions must be absent from the pinned Git target or their explicitly selected working tree. Existing cursors reuse their accepted manifests, with unknown old deletion provenance refused rather than rewritten. Imports whose origin has no page claim their slug together: a live page whose own file is still in the tree keeps the slug, otherwise the file named like the slug (else the first path) wins, and the losers leave the manifest and are reported as `slugCollisions` (the library path's `slug_collision` skip) instead of failing the run. A winner whose slug is held by a page with a vanished or deleted origin takes that page over (`renameFrom`, same slug). A Git-detected rename to an unoccupied slug becomes one import carrying `renameFrom` in place of a delete plus a create. Origins for one slug that differ only by case or separator spelling refuse, except a case-only respelling whose old file the same sync removes. Code files keep exact per-origin identity. On Windows a path containing `:` is reported in `SyncDiscovery.fileRefusals` (code `colon_slug_windows_write_through`, with its filled `gbrain sync --source <id> --no-pull` hint) and kept out of the run and its origin checks, so one such file no longer fails the whole sync (#5032).+- **`src/core/persistence/sync-discovery.ts`** + **`sync-origin.ts`** — managed owner-only Git discovery with source-relative exclusions and one-statement page identity/revision snapshots. Nested full discovery filters source scope before slicing paths. Windows separator aliases retain their page identity; ambiguous aliases refuse, while POSIX backslashes/case remain exact. Under `source-root` mode a stored `<scope>/<path>` origin (the Git-root form older write-through minted from the slug, recognized because `<path>` names the page slug) is accepted as `<path>` at discovery, freeze, preparation and the page-origin query, and an import rewrites it in place; when both readings name existing files the stored origin refuses with `detail: ambiguous_source_path`. A genuine origin mismatch refuses with `detail: sync_origin_mismatch` and the filled paths. Deletions must be absent from the pinned Git target or their explicitly selected working tree. Deleting a file that no page records as its origin (for example a skipped slug twin) while its slug's page keeps another origin commits an explicit no-op receipt (`unownedDeletion`, outcome reason `unowned_deleted_path`) that preserves that live page or tombstone; freeze and publication re-prove that no page owns the path and that the file is still absent. Existing cursors reuse their accepted manifests, with unknown old deletion provenance refused rather than rewritten. Imports whose origin has no page claim their slug together: a live page whose own file is still in the tree keeps the slug, otherwise the file named like the slug (else the first path) wins, and the losers leave the manifest and are reported as `slugCollisions` (the library path's `slug_collision` skip) instead of failing the run. A winner whose slug is held by a page with a vanished or deleted origin takes that page over (`renameFrom`, same slug). A Git-detected rename to an unoccupied slug becomes one import carrying `renameFrom` in place of a delete plus a create. Origins for one slug that differ only by case or separator spelling refuse, except a case-only respelling whose old file the same sync removes. Code files keep exact per-origin identity. On Windows a path containing `:` is reported in `SyncDiscovery.fileRefusals` (code `colon_slug_windows_write_through`, with its filled `gbrain sync --source <id> --no-pull` hint) and kept out of the run and its origin checks, so one such file no longer fails the whole sync (#5032).- **`src/core/persistence/sync-run.ts`** + **`sync-authority.ts`** — one immutable request at a time, bounded fairness and pinned-target resumption. Cursors and requests freeze `noEmbed`, `noExtract` and `noSchemaPack`. A resume adopts the stored options for every option the caller did not set explicitly (`SyncOpts.explicitProcessing`: CLI flags, wire flags, job params; autopilot and the cycle set none); an explicit conflict refuses with `detail: cursor_processing_options_conflict`, the stored options and the exact resume command. Callers that omit `explicitProcessing` stay strict. Explicit idle ordinary-source retry creates fresh discovery/admission and retains terminal receipts; company consent retry retains its approved manifest/run. Active work blocks replacement. Claimed/inactive sync, including connector/company dispatch, remains refused: existing leases and native locks do not fence already-running engine-only legacy writers. No automatic activation or new transition protocol. `freezeEntry` checks a rename's source page (id, revision, origin) as well as its target slug, and a committed rename counts in `renamed`. #5522: a new-file entry (`pageId: null`) whose origin another cursor of the source has since imported is re-frozen against that page when it is live, holds exactly that origin at the entry's slug in the cursor's incarnation, and the sync preparer finds its content unchanged; otherwise the origin refusal stands, and the manifest is never rewritten. #5751: the working-tree screen passes the kernel waivers for working-tree entries and counts them into `legacySkips` (printed by `sync-diagnostics.ts` with `gbrain repair contextual-mode`). A terminal `checkpoint_validation_timeout` receipt gets its hint from `checkpoint-validation.ts`. After the checkpoint commits (and unless `noExtract`), the owner derives links for the source's stale pages through `links-maintenance.ts`, so a PGLite-delegated sync and a Postgres sync take the same path; the result carries `links`, and an extraction failure leaves pages stale without failing the committed sync.- **`src/core/persistence/sync-prepare.ts`** — guarded raw fingerprint/revision, source root and active coordinator checks before preparation and at locked publication. Old imports/checkpoints without durable processing consent refuse under their original IDs; old deletions require their immutable origin manifest and a still-matching page origin. `noEmbed` suppresses the effect itself; `noSchemaPack` bypasses pack loading; optional extraction stays disabled, but mandatory provider-free canonical projections remain. A filename-derived slug mismatch is accepted on every platform only when the page's stored canonical path is this file and the parsed slug is that page's slug; a different declared slug still refuses. CRLF equivalence never weakens raw CAS. No uncoordinated filesystem writes. The checkpoint validates receipts through `checkpoint-validation.ts` and, for a run whose entries another cursor imported (`overtaken`, #5522), also commits when that cursor already checkpointed the same target. Tests: `persistence-sync-origin-native.serial.test.ts`, `persistence-sync-options.serial.test.ts`, `persistence-sync-company.serial.test.ts`. A same-slug `renameFrom` accepts the page's recorded old origin. A different-slug rename prepares against the page where it stands, locks the old slug as an additional page key, and at publication moves the page with `updateSlug` (same id, inbound links and history, `old -> new` in `slug_aliases`, withdrawn claims follow), re-infers an implicit type from the new path, then re-prepares and applies the file content at the new slug, so the move never writes back to the file. Tests: `persistence-managed-lifecycle.test.ts`.- **`src/core/persistence/links-maintenance.ts`** — `extractManagedStaleLinks` derives links for pages whose extraction watermark is stale with `prepareAutomaticLinks` (put_page's replace contract; other producers' edges stay) and adds the coordinator's unrecorded canonical timeline tuples (insert-only) and each page's watermark in the same `withCoordinatedWrite` transaction, bound to the revision it read; an edited page or unresolved attendance stays stale. A page skipped for unresolved attendance is marked attendance-blocked at that revision (`pages.links_attendance_blocked_revision` / `_at`, written by `markPagesAttendanceBlocked` in `engine-sql/pages.ts` only while the revision still matches, cleared by `markPagesExtractedBatch` with the watermark); it is still reconsidered every run, and the `links_extraction_lag` doctor check counts it apart from lag while the marker equals the page's current revision. It is the one managed extraction path: managed sync, `extractStaleFromDB` on a managed brain, and the owner delegation all run it. `runManagedStaleExtraction` backs `gbrain extract --stale` on managed brains, locally or through the `writer_extract_stale` administration operation inside a PGLite owner (`src/commands/extract-stale-delegate.ts`, trusted CLI registration only). `links-preparation.ts` retargets a link written against a renamed page's old slug to the live canonical page through `slug_aliases`, as `get_page` does. Tests: `persistence-managed-lifecycle.test.ts`, `persistence-sync-stdio-owner.serial.test.ts`.diff --git a/src/core/persistence/sync-discovery.ts b/src/core/persistence/sync-discovery.tsindex 33e33dfd48..c47cd3f0d3 100644--- a/src/core/persistence/sync-discovery.ts+++ b/src/core/persistence/sync-discovery.ts@@ -22,7 +22,9 @@ import { assertManagedSyncActive } from './sync-authority.ts';/** The page an import takes over from its previous origin: a Git rename, or a file that replaced a vanished origin at the same slug. */export interface SyncRename { sourcePath: string; slug: string; pageId: number; revision: string; }export interface SyncEntry { path: string; sourcePath: string; action: 'import' | 'delete'; working: boolean; slug?: string; pageId?: number | null; revision?: string | null;- renameFrom?: SyncRename; }+ renameFrom?: SyncRename;+ /** #5565: a deleted file no page records as its origin; its slug's page keeps another origin, so the deletion is a fenced no-op. */+ unownedDeletion?: boolean; }/** Files that map to a slug another origin keeps; they are left out of the manifest until one is renamed. */export interface SyncSlugCollision { slug: string; kept: string; skipped: string[]; }/** #5032: a file sync skipped on this host with a named refusal, without failing the run. */@@ -245,13 +247,16 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, ccontinue;}const page = origins[0] ?? bySlug.get(slug);- if (page?.source_path != null && !sameSyncOrigin(page.source_path, entry.sourcePath, originScope, page.slug)) {+ const foreignOrigin = page?.source_path != null && !sameSyncOrigin(page.source_path, entry.sourcePath, originScope, page.slug);+ // Deleting a file that no page records (a skipped slug twin) must not delete the page another file backs.+ const unownedDeletion = foreignOrigin && entry.action === 'delete' && !origins.length && !company;+ if (foreignOrigin && !unownedDeletion) {const error = new OperationError('page_identity_changed', 'A different origin occupies the imported slug.',`Page ${slug} in source ${sourceId} records the origin '${page.source_path}', but sync found it at '${entry.sourcePath}'. On the brain host, rename or move one of the two files so each page has one origin, commit, then run gbrain sync --source ${sourceId} --no-pull --retry-failed.`);error.detail = 'sync_origin_mismatch';throw error;}- Object.assign(entry, { slug, pageId: page?.id ?? null, revision: page?.knowledge_revision ?? null });+ Object.assign(entry, { slug, pageId: page?.id ?? null, revision: page?.knowledge_revision ?? null, ...(unownedDeletion ? { unownedDeletion: true } : {}) });}const deletions = new Map(selected.filter(entry => entry.action === 'delete').map(entry => [syncOriginPath(entry.sourcePath), entry]));// A soft-delete advances knowledge_revision, so the frozen revisions still guard this read.diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.tsindex 08039403df..499c298d6a 100644--- a/src/core/persistence/sync-prepare.ts+++ b/src/core/persistence/sync-prepare.ts@@ -39,6 +39,8 @@ export interface SyncIntent extends Record<string, unknown> {expected_revision: string | null; sourcePath: string | null; path: string | null;rawHash: string | null; content: string | null; ownerEpoch: string;lineEndingOnly?: boolean;+ /** #5565: the deleted file is no page's origin; publication only re-proves that and commits a no-op. */+ unownedDeletion?: boolean;working?: boolean;renameFrom?: SyncRename;processingOptions?: SyncProcessingOptions;@@ -53,6 +55,8 @@ export interface SyncIntent extends Record<string, unknown> {export async function prepareManagedSyncMutation(engine: BrainEngine, row: WriteRequest, _config: GBrainConfig): Promise<PreparedMutation> {const p = row.intent as SyncIntent | null;if (!p || !['managed_sync_import', 'managed_sync_delete', 'managed_sync_checkpoint'].includes(p.kind)) throw new OperationError('invalid_params', 'Unsupported internal sync intent.');+ if (p.unownedDeletion && p.kind !== 'managed_sync_delete') throw new OperationError('invalid_params', 'Only a deletion can record an unowned path.');+ const originPageId = p.unownedDeletion ? null : row.page_id;await assertManagedSyncActive(engine);if (p.kind !== 'managed_sync_delete' && (!p.processingOptions ||['noEmbed', 'noExtract', 'noSchemaPack'].some(key => typeof p.processingOptions?.[key as keyof SyncProcessingOptions] !== 'boolean'))) {@@ -88,7 +92,7 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: WriteoriginContext = { root, gitRoot: realpathSync(syncGit(root, ['rev-parse', '--show-toplevel']).trim()), target: p.target, slugMode: p.slugMode };assertSyncEntryOrigin(originContext, origin);originScope = syncOriginScope({ ...originContext, sourceId: row.source_id });- await assertSyncPageOrigin(engine, row.source_id, p.sourcePath, row.page_id, p.kind === 'managed_sync_delete', originScope);+ await assertSyncPageOrigin(engine, row.source_id, p.sourcePath, originPageId, p.kind === 'managed_sync_delete', originScope);if (p.renameFrom) await assertSyncPageOrigin(engine, row.source_id, p.renameFrom.sourcePath, p.renameFrom.pageId, true, originScope);}const moved = p.kind === 'managed_sync_import' ? p.renameFrom : undefined;@@ -114,7 +118,7 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Writeif (p.path !== null && syncRawHash(root, p.path) !== p.rawHash) throw new OperationError('source_changed', 'The imported file changed after sync admission.');if (origin && originContext) {assertSyncEntryOrigin(originContext, origin);- await assertSyncPageOrigin(tx, row.source_id, origin.sourcePath, row.page_id, p.kind === 'managed_sync_delete', originScope);+ await assertSyncPageOrigin(tx, row.source_id, origin.sourcePath, originPageId, p.kind === 'managed_sync_delete', originScope);if (moved) await assertSyncPageOrigin(tx, row.source_id, moved.sourcePath, moved.pageId, true, originScope);await assertRenameSource(tx);}@@ -152,9 +156,12 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Writeconst snapshot = await engine.readPageSnapshot(row.slug, { ...source, includeDeleted: true });assertPageRevision(snapshot, p.expected_revision === null ? {} : { expectedRevision: p.expected_revision });const recordedOrigin = moved?.slug === row.slug ? moved.sourcePath : p.sourcePath!;- if ((snapshot?.page.id ?? null) !== row.page_id || (snapshot?.page.source_path != null && !sameSyncOrigin(snapshot.page.source_path, recordedOrigin, originScope, snapshot.page.slug))) {+ const foreignOrigin = snapshot?.page.source_path != null && !sameSyncOrigin(snapshot.page.source_path, recordedOrigin, originScope, snapshot.page.slug);+ if ((snapshot?.page.id ?? null) !== row.page_id || (p.unownedDeletion ? !foreignOrigin : foreignOrigin)) {throw new OperationError('page_identity_changed', 'The imported path no longer names the accepted page.');}+ if (p.unownedDeletion) return { observedRevision: snapshot!.revision, noop: true, validate,+ apply: async () => ({ status: 'skipped', slug: row.slug, source_id: row.source_id, noop: true, reason: 'unowned_deleted_path' }) };if (snapshot && snapshot.page.source_path == null && await isUnboundSourcePage(engine, row.source_id, row.slug)) {throw new OperationError('source_changed', UNBOUND_COLLISION_MESSAGE);}diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex 152ff5c6c3..29484352f6 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -180,8 +180,8 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, assoccupantRebound = occupant !== null;const moved = entry.renameFrom;const recorded = moved?.slug === slug ? moved.sourcePath : entry.sourcePath;- if ((snapshot?.page.id ?? null) !== pageId || (snapshot?.revision ?? null) !== revision ||- (snapshot?.page.source_path != null && !sameSyncOrigin(snapshot.page.source_path, recorded, originScope, snapshot.page.slug))) {+ const foreignOrigin = snapshot?.page.source_path != null && !sameSyncOrigin(snapshot.page.source_path, recorded, originScope, snapshot.page.slug);+ if ((snapshot?.page.id ?? null) !== pageId || (snapshot?.revision ?? null) !== revision || (entry.unownedDeletion ? !foreignOrigin : foreignOrigin)) {throw new OperationError('revision_conflict', 'A page changed after this sync cursor was enumerated.');}if (moved && moved.slug !== slug) {@@ -197,6 +197,7 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, assassertActive();return { requestId: randomUUID(), slug, pageId, ...(occupantRebound ? { rebound: true as const } : {}), intent: { kind: !entry ? 'managed_sync_checkpoint' : entry.action === 'import' ? 'managed_sync_import' : 'managed_sync_delete',expected_revision: revision, sourcePath: entry?.sourcePath ?? null, path: entry?.path ?? null, rawHash, content, lineEndingOnly,+ ...(entry?.unownedDeletion ? { unownedDeletion: true } : {}),...(entry?.renameFrom ? { renameFrom: entry.renameFrom } : {}),processingOptions: cursor.processingOptions,// A cursor created before its options were recorded has the same key, so this run's options are its options.@@ -217,7 +218,7 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, ass*/async function alreadyImportedAtOrigin(engine: BrainEngine, cursor: Cursor, entry: Cursor['entries'][number], originScope: ReturnType<typeof syncOriginScope>) {try {- await assertSyncPageOrigin(engine, cursor.sourceId, entry.sourcePath, entry.pageId ?? null, entry.action === 'delete', originScope);+ await assertSyncPageOrigin(engine, cursor.sourceId, entry.sourcePath, entry.unownedDeletion ? null : entry.pageId ?? null, entry.action === 'delete', originScope);return null;} catch (error) {if (!(error instanceof OperationError) || error.code !== 'page_identity_changed' || entry.action !== 'import' || (entry.pageId ?? null) !== nulldiff --git a/test/persistence-managed-lifecycle.test.ts b/test/persistence-managed-lifecycle.test.tsindex 086295d4d2..e50abec6bb 100644--- a/test/persistence-managed-lifecycle.test.ts+++ b/test/persistence-managed-lifecycle.test.ts@@ -92,6 +92,24 @@ test('two files mapping to one slug skip the loser instead of blocking the whole}}), 180_000);+test('removing the skipped slug twin keeps the page its kept file backs (#5565)', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ for (const engine of engines) {+ const f = await fixture(engine, {+ 'notes/Foo Bar.md': note('Foo Bar spaced', 'Apples and orchards.'),+ 'notes/foo-bar.md': note('foo-bar dashed', 'Oranges and groves.'),+ });+ expect(await performManagedSync(engine, { sourceId: f.id, noPull: true })).toMatchObject({ status: 'first_sync', added: 1 });+ const kept = await engine.readPageSnapshot('notes/foo-bar', { sourceId: f.id });+ expect(kept?.page.source_path).toBe('notes/foo-bar.md');+ rmSync(join(f.root, 'notes/Foo Bar.md'));+ const head = commit(f.root, 'remove the skipped twin');+ expect(await performManagedSync(engine, { sourceId: f.id, noPull: true })).toMatchObject({ status: 'synced', deleted: 0, toCommit: head });+ expect(await engine.readPageSnapshot('notes/foo-bar', { sourceId: f.id })).toEqual(kept);+ expect(readFileSync(join(f.root, 'notes/foo-bar.md'), 'utf8')).toContain('Oranges');+ expect((await engine.executeRaw<{ last_commit: string }>('SELECT last_commit FROM sources WHERE id=$1', [f.id]))[0].last_commit).toBe(head);+ }+}), 180_000);+test('a live page keeps its slug when a later file maps onto it', async () => withEnv({ GBRAIN_HOME: home }, async () => {for (const engine of engines) {const f = await fixture(engine, { 'notes/Foo Bar.md': note('Foo Bar spaced', 'Apples and orchards.') });diff --git a/test/persistence-sync-origin-native.serial.test.ts b/test/persistence-sync-origin-native.serial.test.tsindex 7165edc7ce..9a29fb3691 100644--- a/test/persistence-sync-origin-native.serial.test.ts+++ b/test/persistence-sync-origin-native.serial.test.ts@@ -287,6 +287,72 @@ for (const alias of [false, true]) check(`native historical ${alias ? 'alias' :if (process.platform !== 'win32') expect(readFileSync(join(f.root, literal), 'utf8')).toBe(content);});+check('deleting an unowned filename preserves the live or tombstoned foreign-origin page', async engine => {+ for (const deleted of [false, true]) {+ const f = await fixture(engine, 'notes/recorded.md', 'notes/example', {+ 'notes/recorded.md': content, 'notes/example.md': content,+ });+ await engine.transaction(tx => withCoordinatedWrite(tx, [f.id], async () => {+ await tx.executeRaw('UPDATE sources SET last_commit=$2 WHERE id=$1', [f.id, f.head]);+ if (deleted) await tx.softDeletePage(f.slug, { sourceId: f.id });+ }));+ const before = await engine.readPageSnapshot(f.slug, { sourceId: f.id, includeDeleted: true });+ const history = await engine.getVersions(f.slug, { sourceId: f.id });+ unlinkSync(join(f.root, 'notes/example.md'));+ execFileSync('git', ['-C', f.root, 'add', '-A']);+ execFileSync('git', ['-C', f.root, 'commit', '-qm', 'Remove only an unowned duplicate']);+ const target = execFileSync('git', ['-C', f.root, 'rev-parse', 'HEAD'], { encoding: 'utf8' }).trim();+ const opts = { ...f.opts, full: false };+ expect(await performManagedSync(engine, { ...opts, dryRun: true })).toMatchObject({ status: 'dry_run' });+ expect(await performManagedSync(engine, opts)).toMatchObject({ status: 'synced', deleted: 0, filesImported: 1, toCommit: target });+ expect(await engine.readPageSnapshot(f.slug, { sourceId: f.id, includeDeleted: true })).toEqual(before);+ expect(await engine.getVersions(f.slug, { sourceId: f.id })).toEqual(history);+ expect(readFileSync(join(f.root, 'notes/recorded.md'), 'utf8')).toBe(content);+ const [receipt] = await engine.executeRaw<{ state: string; outcome: unknown }>(+ "SELECT state,outcome FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_delete'", [f.id]);+ expect(receipt).toMatchObject({ state: 'committed', outcome: { noop: true, reason: 'unowned_deleted_path' } });+ expect((await engine.executeRaw('SELECT last_commit FROM sources WHERE id=$1', [f.id]))[0].last_commit).toBe(target);+ }+});++check('unowned deletion rechecks absent ownership and file bytes at publication', async engine => {+ for (const change of ['origin', 'file']) {+ const f = await fixture(engine, 'notes/recorded.md', 'notes/example', {+ 'notes/recorded.md': content, 'notes/example.md': content,+ });+ await engine.transaction(tx => withCoordinatedWrite(tx, [f.id], () =>+ tx.executeRaw('UPDATE sources SET last_commit=$2 WHERE id=$1', [f.id, f.head])));+ unlinkSync(join(f.root, 'notes/example.md'));+ execFileSync('git', ['-C', f.root, 'add', '-A']);+ execFileSync('git', ['-C', f.root, 'commit', '-qm', 'Remove the unowned duplicate']);+ expect((await interruptAfterSyncDiscovery(engine, { ...f.opts, full: false })).status).toBe('partial');+ const [stored] = await engine.executeRaw<{ fingerprint: string; completed_keys: any[] }>(+ "SELECT fingerprint,completed_keys FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [f.id]);+ const cursor = stored.completed_keys[0], requestId = randomUUID();+ const intent: SyncIntent = { kind: 'managed_sync_delete', expected_revision: f.snapshot.revision,+ sourcePath: 'notes/example.md', path: 'notes/example.md', rawHash: null, content: null, unownedDeletion: true, working: false,+ ownerEpoch: String(cursor.binding.owner_epoch), syncAuthority: cursor.authority, cursorKey: stored.fingerprint,+ runId: cursor.runId, index: 0, total: 1, from: cursor.from, target: cursor.target, slugMode: cursor.slugMode };+ cursor.pending = { requestId, slug: f.slug, pageId: f.snapshot.page.id, intent };+ await engine.executeRaw("UPDATE op_checkpoints SET completed_keys=$2::text::jsonb WHERE op='managed-sync' AND fingerprint=$1",+ [stored.fingerprint, JSON.stringify([cursor])]);+ const accepted = await admitWrite(engine, { requestId, operation: 'submit_job', sourceId: f.id, sourceIncarnation: cursor.incarnation,+ slug: f.slug, pageId: f.snapshot.page.id, worktreeId: cursor.binding.worktree_id, topologyGeneration: cursor.binding.topology_generation,+ principal: cursor.authority.writer.principal, authority: cursor.authority.writer, callerIntent: intent, intent });+ const row = (await claimNextWrite(engine, localHostId()))!;+ expect(row.id).toBe(accepted.id);+ const prepared = await prepareManagedSyncMutation(engine, row, { engine: engine.kind });+ expect(prepared.noop).toBe(true);+ if (change === 'origin') await engine.executeRaw('UPDATE pages SET source_path=$2 WHERE id=$1', [f.snapshot.page.id, 'notes/example.md']);+ else writeFileSync(join(f.root, 'notes/example.md'), content);+ const published = await publishMutation(engine, row, prepared);+ expect(published.state).not.toBe('committed');+ expect(published.error_code).toBe(change === 'origin' ? 'page_identity_changed' : 'source_changed');+ expect((await engine.readPageSnapshot(f.slug, { sourceId: f.id }))?.revision).toBe(f.snapshot.revision);+ expect((await engine.executeRaw('SELECT last_commit FROM sources WHERE id=$1', [f.id]))[0].last_commit).toBe(f.head);+ }+});+check('a genuine committed Git deletion commits one deletion and the exact checkpoint', async engine => {const f = await fixture(engine);await engine.transaction(tx => withCoordinatedWrite(tx, [f.id], () => tx.executeRaw('UPDATE sources SET last_commit=$2 WHERE id=$1', [f.id, f.head])));