Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
test(#6712 PR 4b lane C): a recorded failure is retried by the next plain sync on the pass (and an older binary's blocked cursor with its checkpoint failure converges); drop the cursor-run knock-on, rediscovery and moved-checkpoint tests; settled-range validation moves to a seeded receipt; legacy-retry seeds the older cursors
garrytan23b05bd41325
diff --git a/test/sync-checkpoint-moved-6834.test.ts b/test/sync-checkpoint-moved-6834.test.tsindex 3946d8dc4b..1a47234590 100644--- a/test/sync-checkpoint-moved-6834.test.ts+++ b/test/sync-checkpoint-moved-6834.test.ts@@ -15,6 +15,12 @@* as `checkpoint_moved`, keeps it when the rule no longer holds at apply time, retires it otherwise, and the next* plain sync discovers from the recorded commit;* - ordinary page revision conflicts keep their diagnosis and action.+ * #6712 PR 4b: a non-company source keeps no cursor and its live pass publishes no cursor checkpoint, so the races, the+ * moved-checkpoint blocks, the slice records and the repair applies of a cursor run went with it. What stays here is+ * the classification of the refused receipts an older run left (page vs bookkeeping, supersession). A brain an older+ * binary left with a blocked cursor and its checkpoint failure converging on a plain sync is covered by+ * sync-pass-failure-retry-6712.test.ts; the orphan repair by repair-managed-sync-orphans.test.ts, and its checkpoint_moved+ * classification by persistence-sync-failures.serial.test.ts.* Synthetic content only.*/import { afterAll, beforeAll, describe, expect, test } from 'bun:test';@@ -24,26 +30,14 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { dirname, join } from 'node:path';import type { BrainEngine } from '../src/core/engine.ts';-import type { OperationContext } from '../src/core/ops/contract.ts';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { claimWorktree } from '../src/core/persistence/ownership.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import { performManagedSync } from '../src/core/persistence/sync-run.ts';-import { drainManagedSync } from '../src/core/persistence/sync-drain.ts';-import { _setCursorBoundForTest } from '../src/core/persistence/sync-discovery.ts';-import { SYNC_SLICE_OP } from '../src/core/persistence/sync-slices.ts';-import { __setManagedCursorKeyForTests } from '../src/core/persistence/sync-cursor-key.ts';-import { readManagedSyncFailures } from '../src/core/persistence/sync-failures.ts';import { classifyManagedSyncOrphans } from '../src/core/persistence/managed-sync-orphans.ts';-import { readSyncStatus } from '../src/core/persistence/sync-status.ts';import { classifyTerminal, supersessionSql } from '../src/core/persistence/terminal-classify.ts';import { readTerminalFailures, readTerminalFailureSummary } from '../src/core/persistence/terminal-failures.ts';import { writeFailureDiagnostic } from '../src/core/persistence/verb-errors.ts';-import { checkSyncFailures } from '../src/commands/doctor/checks/sync-failures.ts';-import { checkSyncFreshness } from '../src/commands/doctor/checks/extraction-sync.ts';-import { managedSyncOrphansRepair } from '../src/core/repair/managed-sync-orphans.ts';-import { runRepair } from '../src/core/repair/core.ts';-import { repairSpec } from '../src/core/repair/registry.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';import { testBackends } from './helpers/test-backends.ts';import { withEnv } from './helpers/with-env.ts';@@ -92,216 +86,14 @@ describe('#6834 a managed-sync checkpoint whose source checkpoint moved', () =>return { id, repo, root, seed, side, target, opts };}type Fixture = Awaited<ReturnType<typeof fixture>>;- /** Runs `fn` as an older gbrain whose cursor key for the source is `key`. */- async function legacy<T>(key: string, fn: () => Promise<T>): Promise<T> {- __setManagedCursorKeyForTests(() => key);- try { return await fn(); } finally { __setManagedCursorKeyForTests(null); }- }/** Stops the run after its page writes and before its checkpoint publishes. */async function beforeCheckpoint(engine: BrainEngine, f: Fixture, variant: 'entries' | 'zero') {const abort = new AbortController();const partial = await outcome(performManagedSync(engine, { ...f.opts, signal: abort.signal, onProgress: p => { if (variant === 'zero' || p.bankedFiles === 1) abort.abort(); } }));expect(partial.status).toBe('partial');}- /** The checkpoint column only the owner publishes; another writer moving it is simulated with managed persistence off. */- async function moveCheckpoint(engine: BrainEngine, f: Fixture, commitId: string) {- await disposePersistenceConsumer(engine);- await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');- try { await engine.executeRaw('UPDATE sources SET last_commit=$2 WHERE id=$1', [f.id, commitId]); }- finally { await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1'); }- }- const lastCommit = async (engine: BrainEngine, f: Fixture) => (await engine.executeRaw<{ last_commit: string | null }>('SELECT last_commit FROM sources WHERE id=$1', [f.id]))[0]!.last_commit;- const checkpoints = async (engine: BrainEngine, f: Fixture) => engine.executeRaw<{ id: string; request_id: string; slug: string; operation: string; state: string; error_code: string | null; error_message: string | null; error_detail: object | null }>(- `SELECT id::text AS id, request_id::text AS request_id, slug, operation, state, error_code, error_message, error_detail FROM persistence_requests- WHERE source_id=$1 AND intent->>'kind'='managed_sync_checkpoint' ORDER BY sequence`, [f.id]);- const unfinished = (engine: BrainEngine, f: Fixture) => (engine.executeRaw<{ n: number | string }>(- "SELECT count(*) AS n FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1 AND COALESCE(completed_keys->0->>'done','false')<>'true'", [f.id]).then(rows => Number(rows[0]!.n)));const superseded = async (engine: BrainEngine, id: string) => (await engine.executeRaw(`SELECT 1 FROM persistence_requests r WHERE r.id=$1::uuid AND EXISTS(SELECT 1 FROM persistence_requests c WHERE ${supersessionSql('r', 'c')})`, [id])).length > 0;- const ctx = (engine: BrainEngine) => ({ engine, config: { engine: engine.kind }, logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote: false } as unknown as OperationContext);- const repair = (engine: BrainEngine, f: Fixture, expectHash?: string) => runRepair(ctx(engine), managedSyncOrphansRepair, { brain_id: 'host', source_ids: [f.id] },- { apply: !!expectHash, explicit: true, ...(expectHash ? { expect: expectHash } : {}), spec: repairSpec('managed-sync-orphans') });-- for (const variant of ['entries', 'zero'] as const) {- test(`two older-key cursors race to one target (${variant}): the losing checkpoint finishes instead of blocking`, () => each(async engine => {- const f = await fixture(engine, variant);- const loser = `older-loser-${f.id}`, winner = `older-winner-${f.id}`;- await legacy(loser, () => beforeCheckpoint(engine, f, variant));- // The winner never saw the loser's cursor (an older gbrain keyed it apart): it is parked while the winner runs.- await engine.executeRaw("UPDATE op_checkpoints SET op='managed-sync-parked' WHERE op='managed-sync' AND fingerprint=$1", [loser]);- expect((await legacy(winner, () => outcome(performManagedSync(engine, f.opts)))).status).toBe('synced');- await engine.executeRaw("UPDATE op_checkpoints SET op='managed-sync' WHERE op='managed-sync-parked' AND fingerprint=$1", [loser]);- expect(await lastCommit(engine, f)).toBe(f.target);- // The loser resumes: its checkpoint is refused (last_commit moved), and the same run revives it as overtaken.- const resumed = await legacy(loser, () => outcome(performManagedSync(engine, f.opts)));- expect(resumed.status).toBe('synced');- const rows = await checkpoints(engine, f);- expect(rows.filter(row => row.state !== 'committed').map(row => [row.state, row.error_code, row.error_message])).toEqual([['conflict', 'revision_conflict', MOVED]]);- expect(rows.at(-1)!.state).toBe('committed');- expect(await lastCommit(engine, f)).toBe(f.target);- expect(await readManagedSyncFailures(engine, [f.id])).toEqual([]);- // The refused receipt is history: a later committed checkpoint of the source supersedes it.- expect(await superseded(engine, rows.find(row => row.state === 'conflict')!.id)).toBe(true);- expect((await outcome(performManagedSync(engine, f.opts))).status).toBe('up_to_date');- expect(await unfinished(engine, f)).toBe(0);- }), 180_000);- }-- test('a brain that already carries the refused checkpoint and its failure row, with the source now at the target, finishes on a plain sync', () => each(async engine => {- const f = await fixture(engine, 'entries');- await beforeCheckpoint(engine, f, 'entries');- // An older release recorded the refusal: the checkpoint moved elsewhere first, so its run blocked and wrote the failure row.- await moveCheckpoint(engine, f, f.side);- const blocked = await outcome(performManagedSync(engine, f.opts));- expect(blocked).toMatchObject({ status: 'blocked_by_failures', failureCodes: [{ code: 'revision_conflict', count: 1 }] });- expect((await readManagedSyncFailures(engine, [f.id])).map(row => [row.code, row.phase])).toEqual([['revision_conflict', 'checkpoint']]);- // Another run then checkpointed this run's target.- await moveCheckpoint(engine, f, f.target);- expect((await classifyManagedSyncOrphans(engine, [f.id])).orphans).toEqual([]);- const finished = await outcome(performManagedSync(engine, f.opts));- expect(finished.status).toBe('synced');- expect(await lastCommit(engine, f)).toBe(f.target);- expect(await readManagedSyncFailures(engine, [f.id])).toEqual([]);- expect(await unfinished(engine, f)).toBe(0);- expect((await readSyncStatus(engine, f.id)).last_error).toBeNull();- }), 180_000);-- test('a checkpoint moved elsewhere names no page, is listed as checkpoint_moved, and retiring it lets a plain sync converge', () => each(async engine => {- const f = await fixture(engine, 'entries');- await beforeCheckpoint(engine, f, 'entries');- await moveCheckpoint(engine, f, f.side);- for (let attempt = 0; attempt < 2; attempt++) {- const blocked = await outcome(performManagedSync(engine, f.opts));- expect(blocked).toMatchObject({ status: 'blocked_by_failures', failureCodes: [{ code: 'revision_conflict', count: 1 }] });- expect(blocked.managedWrite).toMatchObject({ slug: '__managed_sync_checkpoint__', reason: 'sync_checkpoint_moved' });- expect(blocked.managedWrite.suggestion).toContain('gbrain repair managed-sync-orphans --source <source>');- expect(blocked.managedWrite.suggestion).not.toContain('Read the current page');- }- // The terminal-failure action reads sync status, never gbrain get on the bookkeeping slug.- const refused = (await checkpoints(engine, f)).filter(row => row.state === 'conflict');- expect(refused.length).toBeGreaterThan(0);- for (const row of refused) {- const verdict = classifyTerminal({ ...row, source_id: f.id, recovery: null, blocked_reason: null, compacted: false, intent_kind: 'managed_sync_checkpoint' })!;- expect(verdict.action.argv).toEqual(['gbrain', 'sync', 'status', '--source', f.id, '--json']);- expect(verdict.class).toBe('systemic');- }- const classified = await classifyManagedSyncOrphans(engine, [f.id]);- expect(classified.orphans.map(orphan => [orphan.kind, orphan.reason])).toEqual([['unfinished_cursor', 'checkpoint_moved']]);- expect(classified.retained).toEqual([]);- // Doctor names the repair as its fix: sync_failures, and sync_freshness once the source is stale.- const failures = (await checkSyncFailures(engine, { remote: false, sourceIds: [f.id] }))!;- expect(failures.message).toContain('checkpoint_moved');- expect((failures.fix as { argv: string[] }).argv).toEqual(['gbrain', 'repair', 'managed-sync-orphans', '--source', f.id]);- const freshness = await checkSyncFreshness(engine, { localOnly: true, nowMs: Date.now() + 5 * 24 * 3600_000 });- expect(freshness.status).toBe('fail');- expect((freshness.fix as { argv: string[] }).argv).toEqual(['gbrain', 'repair', 'managed-sync-orphans', '--source', f.id]);- expect(freshness.message).toContain(`gbrain repair managed-sync-orphans --source ${f.id}`);-- // Preview-first: the apply retires exactly the previewed cursor while its rule still holds.- const preview = await repair(engine, f);- expect(preview.affected).toBe(1);- expect(await unfinished(engine, f)).toBe(1);- const applied = await repair(engine, f, preview.preview_hash);- expect(applied.applied).toBe(1);- expect(await unfinished(engine, f)).toBe(0);- expect(await readManagedSyncFailures(engine, [f.id])).toEqual([]);- expect(await lastCommit(engine, f)).toBe(f.side);- // The next plain sync discovers from the commit the source records and checkpoints HEAD.- const converged = await outcome(performManagedSync(engine, f.opts));- expect(converged.status).toBe('synced');- expect(await lastCommit(engine, f)).toBe(f.target);- expect((await engine.getPage('notes/alpha', { sourceId: f.id }))?.compiled_truth).toContain('A revised observation');- for (const row of refused) expect(await superseded(engine, row.id)).toBe(true);- expect((await outcome(performManagedSync(engine, f.opts))).status).toBe('up_to_date');- }), 180_000);-- test('the apply keeps a previewed cursor whose source has since reached its target, and the plain sync finishes it', () => each(async engine => {- const f = await fixture(engine, 'zero');- await beforeCheckpoint(engine, f, 'zero');- await moveCheckpoint(engine, f, f.side);- expect((await outcome(performManagedSync(engine, f.opts))).status).toBe('blocked_by_failures');- const preview = await repair(engine, f);- expect(preview.affected).toBe(1);- await moveCheckpoint(engine, f, f.target);- const applied = await repair(engine, f, preview.preview_hash);- expect(applied.applied).toBe(0);- expect(await unfinished(engine, f)).toBe(1);- expect((await outcome(performManagedSync(engine, f.opts))).status).toBe('synced');- expect(await unfinished(engine, f)).toBe(0);- }), 180_000);-- test.each([['the run\'s own target'], ['a newer commit']] as const)('a path slice short of its target whose checkpoint moved to %s is listed, no sync rediscovers it, and retiring it clears its slice record', moved => each(async engine => {- _setCursorBoundForTest();- await disposePersistenceConsumer(engine);- await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');- const id = `sliced-${randomUUID().slice(0, 12)}`, root = join(home, id);- mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');- const names = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];- for (const name of names) writeFileSync(join(root, 'notes', `${name}.md`), note(name));- const target = commit(root, 'seven at once');- await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,$3::text::jsonb)', [id, root, '{}']);- await claimWorktree(engine, id, root);- await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');- const f = { id, repo: root, root, seed: target, side: target, target, opts: { sourceId: id, noPull: true, noEmbed: true, noExtract: true } };- const slices = async () => Number((await engine.executeRaw<{ n: string }>("SELECT COUNT(*)::text AS n FROM op_checkpoints WHERE op=$1 AND fingerprint LIKE $2", [SYNC_SLICE_OP, `${id}:%`]))[0]!.n);- try {- _setCursorBoundForTest({ entries: 3, bytes: 1024 ** 2 });- expect((await drainManagedSync(engine, f.opts, false)).staged?.slice).toMatchObject({ phase: 'import', after: 'notes/c.md' });- expect(await slices()).toBe(1);- // The second slice commits its pages and stops before its checkpoint.- const abort = new AbortController();- expect((await outcome(performManagedSync(engine, { ...f.opts, signal: abort.signal, onProgress: p => { if (p.total && p.bankedFiles === p.total) abort.abort(); } }))).status).toBe('partial');- writeFileSync(join(root, 'notes', 'x.md'), note('x'));- const newer = commit(root, 'one more');- await moveCheckpoint(engine, f, moved === 'a newer commit' ? newer : target);- expect((await outcome(performManagedSync(engine, f.opts))).status).toBe('blocked_by_failures');- expect((await classifyManagedSyncOrphans(engine, [id])).orphans.map(orphan => orphan.reason)).toEqual(['checkpoint_moved']);- // #6712 PR 3 (L7): neither a plain sync nor its --retry-failed alias rediscovers it. Rediscovering would resume the slice- // record and finish at the slice's target, moving last_commit back from a newer commit; the repair clears the record.- _setCursorBoundForTest();- for (const retryFailed of [false, true]) {- expect((await outcome(performManagedSync(engine, { ...f.opts, retryFailed }))).status).toBe('blocked_by_failures');- expect(await lastCommit(engine, f)).toBe(moved === 'a newer commit' ? newer : target);- expect(await slices()).toBe(1);- }- const preview = await repair(engine, f);- expect((await repair(engine, f, preview.preview_hash)).applied).toBe(1);- expect(await slices()).toBe(0);- _setCursorBoundForTest();- const next = await outcome(performManagedSync(engine, f.opts));- expect(next.status).not.toBe('blocked_by_failures');- expect(next.deleted ?? 0).toBe(0);- // The source never moves back to the slice's target, and nothing the newer commit has is deleted.- expect(await lastCommit(engine, f)).toBe(newer);- } finally { _setCursorBoundForTest(); }- }), 180_000);-- test('an apply keeps a cursor whose run replaced the previewed one under the same key', () => each(async engine => {- const f = await fixture(engine, 'entries');- await beforeCheckpoint(engine, f, 'entries');- await moveCheckpoint(engine, f, f.side);- expect((await outcome(performManagedSync(engine, f.opts))).status).toBe('blocked_by_failures');- const preview = await repair(engine, f);- const previewed = (await classifyManagedSyncOrphans(engine, [f.id])).orphans[0]!;- // A run replaced under the same key (here: its manifest is lost, so the next sync re-discovers at HEAD; #6712 PR 3 took- // that rediscovery away from --retry-failed); the replacement stops before its checkpoint, which moves too.- await engine.executeRaw("DELETE FROM op_checkpoints WHERE op='managed-sync-manifest' AND fingerprint=$1", [previewed.run_id]);- writeFileSync(join(f.root, 'notes', 'beta.md'), note('beta', 'A revised observation'));- const head = commit(f.repo, 'beta');- const abort = new AbortController();- expect((await outcome(performManagedSync(engine, { ...f.opts, signal: abort.signal, onProgress: p => { if (p.total && p.bankedFiles === p.total) abort.abort(); } }))).status).toBe('partial');- await moveCheckpoint(engine, f, f.seed);- expect((await outcome(performManagedSync(engine, f.opts))).status).toBe('blocked_by_failures');- const current = (await classifyManagedSyncOrphans(engine, [f.id])).orphans[0]!;- expect(current.run_id).not.toBe(previewed.run_id);- expect((await repair(engine, f, preview.preview_hash)).applied).toBe(0);- expect(await unfinished(engine, f)).toBe(1);- // A fresh preview binds to the replacement run and retires it.- const again = await repair(engine, f);- expect((await repair(engine, f, again.preview_hash)).applied).toBe(1);- expect((await outcome(performManagedSync(engine, f.opts))).status).toBe('synced');- expect(await lastCommit(engine, f)).toBe(head);- }), 180_000);test('ordinary page revision conflicts keep their diagnosis and action', () => each(async engine => {const page = writeFailureDiagnostic('revision_conflict', 'The page changed during sync preparation.');diff --git a/test/sync-knock-on-recovery-6643.test.ts b/test/sync-knock-on-recovery-6643.test.tsindex 2ce9d1dd3e..bf1695db57 100644--- a/test/sync-knock-on-recovery-6643.test.ts+++ b/test/sync-knock-on-recovery-6643.test.ts@@ -1,81 +1,56 @@/*** #6643: managed sync recovers from its own knock-ons; #6712 (one page, one fate) retired every producer.*- * Protects: a legacy knock-on receipt an older build wrote (a page cancelled or refused only because another page of- * the same sync did not commit) is re-frozen in place under a fresh request by the run itself, even under- * `sync.holds=fail` and without `--retry-failed`; an operator's cancel is never re-frozen; the re-freeze is bounded per- * entry (`STOPS_PER_ENTRY`, no config key) and past it the failure is recorded as a retryable page fault; the retired- * `knock_on_exhausted` code renders superseded; the pre-#6643 producer messages are recognised, nothing else is; and- * the checkpoint waits on every receipt the cursor did not settle (no knock-on exemption).+ * Protects: the retired `knock_on_exhausted` code renders superseded; the pre-#6643 producer messages are recognised,+ * nothing else is; the checkpoint waits on every receipt the cursor did not settle (no knock-on exemption); the cursor+ * fence's two causes; the never-admitted legacy patterns.+ * #6712 PR 4b: a non-company source keeps no cursor to re-freeze, rediscover or show in sync status, so the cursor-run+ * tests went; a page that failed in one pass and is imported by the next plain sync (and its --retry-failed alias) is+ * covered by sync-pass-failure-retry-6712.test.ts.*/import { afterAll, beforeAll, expect, test } from 'bun:test';import { randomUUID } from 'node:crypto';-import { execFileSync } from 'node:child_process';-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { claimWorktree } from '../src/core/persistence/ownership.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';-import { performManagedSync, STOPS_PER_ENTRY } from '../src/core/persistence/sync-run.ts';-import { __setManagedCursorKeyForTests } from '../src/core/persistence/sync-cursor-key.ts';-import { readSyncStatus } from '../src/core/persistence/sync-status.ts';import { classifySyncFault } from '../src/core/persistence/sync-fault-class.ts';-import { readManagedSyncFailures } from '../src/core/persistence/sync-failures.ts';import { laneFaultCancelMessage, WINDOW_CANCEL_MESSAGE } from '../src/core/persistence/sync-window.ts';import { BULK_GROUP_CANCEL_MESSAGE, EARLIER_PAGE_REFUSAL_MESSAGE, isSyncKnockOn, knockOnDetail, LEGACY_KNOCK_ON_CANCEL_MESSAGES, legacyKnockOnMessage,syncKnockOnSql } from '../src/core/persistence/sync-knock-on.ts';import { CODES } from '../src/core/error-registry.ts';import { addSettledRange, findIncompleteSyncReceipt } from '../src/core/persistence/checkpoint-validation.ts';-import { publicFailureDetail } from '../src/core/persistence/publication-failure.ts';import { cursorFenceRefusal } from '../src/core/persistence/sync-prepare.ts';+import { publicFailureDetail } from '../src/core/persistence/publication-failure.ts';import { withEnv } from './helpers/with-env.ts';const home = mkdtempSync(join(tmpdir(), 'gbrain-6643-'));let engine: PGLiteEngine;-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', '.'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message); };-const note = (body: string) => `---\ntitle: Example\n---\n${body}\n`;const page = (kind: string) => ({ kind });-async function fixture(files: Record<string, string>) {+/** A claimed source and one failed import receipt of a sync run (run `runId`, index 1) on its worktree. */+async function failedReceipt() {const id = `ko-${randomUUID().replace(/-/g, '').slice(0, 20)}`, root = join(home, id);- mkdirSync(root); git(root, 'init', '-q');- for (const [path, body] of Object.entries(files)) writeFileSync(join(root, path), body);- commit(root, 'fixture');+ mkdirSync(root);await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [id, root]);- await claimWorktree(engine, id, root);+ const binding = await claimWorktree(engine, id, root);await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');- return { id, root, opts: { sourceId: id, noPull: true, noEmbed: true, noExtract: true } };-}--/**- * A managed run stopped on its second page (a.md committed, b.md refused because it changed after the freeze), with- * b.md then restored to its committed bytes. Returns the stopped request and the committed request of a.md.- */-async function stoppedRun() {- const f = await fixture({ 'a.md': note('Alpha one.'), 'b.md': note('Beta one.') });- expect((await performManagedSync(engine, f.opts)).status).toBe('first_sync');- writeFileSync(join(f.root, 'a.md'), note('Alpha two.')); writeFileSync(join(f.root, 'b.md'), note('Beta two.'));- commit(f.root, 'version two');- writeFileSync(join(f.root, 'b.md'), note('Beta, uncommitted.'));- await engine.setConfig('sync.holds', 'fail');- expect((await performManagedSync(engine, f.opts)).status).toBe('blocked_by_failures');- git(f.root, 'checkout', '--', 'b.md');- const [failure] = await readManagedSyncFailures(engine, [f.id]);- const stopped = failure!.request_id!;- const [root] = await engine.executeRaw<{ request_id: string }>(- "SELECT request_id::text AS request_id FROM persistence_requests WHERE source_id=$1 AND slug='a' AND state='committed' ORDER BY sequence DESC LIMIT 1", [f.id]);- return { ...f, stopped, rootRequest: root!.request_id };+ const runId = randomUUID(), stopped = randomUUID();+ await engine.executeRaw(`INSERT INTO persistence_requests(principal_kind,principal_id,request_id,operation,source_id,source_incarnation,worktree_id,slug,digest,authority,intent_bytes,+ terminal_reservation,state,error_code,error_message,intent,completed_at,updated_at,admitter_version)+ VALUES('local_cli','fixture',$1::uuid,'submit_job',$2,(SELECT incarnation FROM sources WHERE id=$2),$3::uuid,'b',$4,'{}'::jsonb,0,0,'failed','source_changed',+ 'The file changed after it was frozen.',$5::text::jsonb,now(),now(),'0.60.262.0')`,+ [stopped, id, binding.worktree_id, randomUUID(), JSON.stringify({ kind: 'managed_sync_import', runId, index: 1 })]);+ return { worktreeId: binding.worktree_id, runId, stopped, rootRequest: randomUUID() };}-/** Rewrites the stopped request into the receipt a knock-on producer writes, as first observed (no ledger row yet). */+/** Rewrites the stopped request into the receipt a knock-on producer writes. */async function asKnockOn(requestId: string, message: string, detail: unknown, state = 'cancelled', code = 'cancelled') {- await engine.executeRaw("DELETE FROM op_checkpoints WHERE op='managed-sync-failure' AND completed_keys->0->>'request_id'=$1", [requestId]);await engine.executeRaw(`UPDATE persistence_requests SET state=$2, error_code=$3, error_message=$4, error_detail=$5::jsonb, recovery=NULL, publication_started=falseWHERE request_id=$1::uuid`, [requestId, state, code, message, detail == null ? null : JSON.stringify(detail)]);}-const clearConfig = () => engine.executeRaw("DELETE FROM config WHERE key='sync.holds'");beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 60_000);afterAll(async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); rmSync(home, { recursive: true, force: true }); });@@ -119,122 +94,25 @@ test('the SQL predicate agrees with isSyncKnockOn row by row', async () => {}});-test('a knock-on is re-frozen by the plain sync under sync.holds=fail, and the run finishes', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {- try {- const f = await stoppedRun();- await asKnockOn(f.stopped, WINDOW_CANCEL_MESSAGE, knockOnDetail('window_predecessor', f.rootRequest));- const resumed = await performManagedSync(engine, f.opts);- expect(resumed.status).not.toBe('blocked_by_failures');- const status = await readSyncStatus(engine, f.id);- expect(status.cursor?.done).toBe(true);- // The stopped receipt is immutable; the page committed under a fresh request.- const [old] = await engine.executeRaw<{ state: string }>('SELECT state FROM persistence_requests WHERE request_id=$1::uuid', [f.stopped]);- expect(old!.state).toBe('cancelled');- const [b] = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM persistence_requests WHERE source_id=$1 AND slug='b' AND state='committed'", [f.id]);- expect(b!.n).toBe(2);- } finally { await clearConfig(); }-}), 120_000);--test('a pre-#6643 untyped knock-on is recovered the same way', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {- try {- const f = await stoppedRun();- await asKnockOn(f.stopped, EARLIER_PAGE_REFUSAL_MESSAGE, null, 'conflict', 'revision_conflict');- const resumed = await performManagedSync(engine, f.opts);- expect(resumed.status).not.toBe('blocked_by_failures');- expect((await readSyncStatus(engine, f.id)).cursor?.done).toBe(true);- } finally { await clearConfig(); }-}), 120_000);--test('an operator cancel is never re-frozen', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {- try {- const f = await stoppedRun();- await asKnockOn(f.stopped, 'Cancelled before publication.', null);- const resumed = await performManagedSync(engine, f.opts);- expect(resumed.status).toBe('blocked_by_failures');- expect(resumed.failureCodes).toEqual([{ code: 'cancelled', count: 1 }]);- } finally { await clearConfig(); }-}), 120_000);+test('the checkpoint waits on every receipt the cursor did not settle, a legacy knock-on included (#6712), and skips the indexes a cursor settled', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ const f = await failedReceipt();+ const check = (settled: Parameters<typeof findIncompleteSyncReceipt>[4]) => findIncompleteSyncReceipt(engine, f.worktreeId, f.runId, [], settled);+ // A real failure (no knock-on marker, no matching message) blocks under every cursor shape.+ expect(await check(null)).toBe(f.stopped);+ expect(await check({ from: 0, ranges: [] })).toBe(f.stopped);+ await asKnockOn(f.stopped, WINDOW_CANCEL_MESSAGE, knockOnDetail('window_predecessor', f.rootRequest));+ // #6712: no knock-on exemption: a legacy knock-on blocks unless the cursor settled its index or converted it.+ expect(await check(null)).toBe(f.stopped);+ expect(await findIncompleteSyncReceipt(engine, f.worktreeId, f.runId, [f.stopped], null)).toBeNull();+ expect(await check({ from: 0, ranges: [] })).toBe(f.stopped);+ expect(await check({ from: 0, ranges: [[1, 1]] })).toBeNull();+ expect(addSettledRange(addSettledRange({ from: 0, ranges: [] }, 1, 2), 3, 4)).toEqual({ from: 0, ranges: [[1, 4]] });+ expect(addSettledRange({ from: 0, ranges: [[1, 2]] }, 5, 5)).toEqual({ from: 0, ranges: [[1, 2], [5, 5]] });+}));-test('a legacy knock-on is re-frozen at most STOPS_PER_ENTRY times in a row; past that the failure is recorded as a retryable page fault', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {- try {- const f = await stoppedRun();- await asKnockOn(f.stopped, WINDOW_CANCEL_MESSAGE, knockOnDetail('window_predecessor', f.rootRequest));- // The entry was already re-frozen STOPS_PER_ENTRY times in a row.- await engine.executeRaw(`UPDATE op_checkpoints SET completed_keys=jsonb_set(completed_keys,'{0,pending,stops}',to_jsonb($2::int))- WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1`, [f.id, STOPS_PER_ENTRY]);- const resumed = await performManagedSync(engine, f.opts);- expect(resumed.status).toBe('blocked_by_failures');- expect(resumed.failureCodes).toEqual([{ code: 'cancelled', count: 1 }]);- const status = await readSyncStatus(engine, f.id);- expect(status.last_error).toMatchObject({ code: 'cancelled', class: 'page', safe_actions: ['retry'], needs_human: false });- expect(status.needs_human).toBe(false);- // The printed retry finishes the sync.- const again = await performManagedSync(engine, { ...f.opts, retryFailed: true });- expect(again.status).not.toBe('blocked_by_failures');- expect((await readSyncStatus(engine, f.id)).cursor?.done).toBe(true);- } finally { await clearConfig(); }-}), 180_000);--test('the checkpoint waits on every receipt the cursor did not settle, a legacy knock-on included (#6712), and skips the indexes a cursor settled', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {- try {- const f = await stoppedRun();- const [row] = await engine.executeRaw<{ worktree_id: string; run_id: string; idx: number }>(- "SELECT worktree_id::text AS worktree_id, intent->>'runId' AS run_id, (intent->>'index')::int AS idx FROM persistence_requests WHERE request_id=$1::uuid", [f.stopped]);- const check = (settled: Parameters<typeof findIncompleteSyncReceipt>[4]) => findIncompleteSyncReceipt(engine, row!.worktree_id, row!.run_id, [], settled);- // A real failure (no knock-on marker, no matching message) blocks under every cursor shape.- expect(await check(null)).toBe(f.stopped);- expect(await check({ from: 0, ranges: [] })).toBe(f.stopped);- await asKnockOn(f.stopped, WINDOW_CANCEL_MESSAGE, knockOnDetail('window_predecessor', f.rootRequest));- // #6712: no knock-on exemption: a legacy knock-on blocks unless the cursor settled its index or converted it.- expect(await check(null)).toBe(f.stopped);- expect(await findIncompleteSyncReceipt(engine, row!.worktree_id, row!.run_id, [f.stopped], null)).toBeNull();- expect(await check({ from: 0, ranges: [] })).toBe(f.stopped);- expect(await check({ from: 0, ranges: [[row!.idx, row!.idx]] })).toBeNull();- expect(addSettledRange(addSettledRange({ from: 0, ranges: [] }, 1, 2), 3, 4)).toEqual({ from: 0, ranges: [[1, 4]] });- expect(addSettledRange({ from: 0, ranges: [[1, 2]] }, 5, 5)).toEqual({ from: 0, ranges: [[1, 2], [5, 5]] });- } finally { await clearConfig(); }-}), 120_000);--// #6712 PR 3 (L7): --retry-failed is a deprecated alias of the plain sync, so both rediscover the run and finish.-for (const retryFailed of [false, true]) test(`#6712: a checkpoint a legacy knock-on still blocks is rediscovered by the next ${retryFailed ? '--retry-failed (plain sync alias)' : 'plain'} sync and finishes`, async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {- try {- const f = await stoppedRun();- // The pre-#6643 shape: the cursor passed the stopped page (no settled ranges recorded) and froze its checkpoint.- await engine.executeRaw(`UPDATE op_checkpoints SET completed_keys=jsonb_set(completed_keys #- '{0,pending}' #- '{0,settled}', '{0,index}', completed_keys->0->'total')- WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1`, [f.id]);- await engine.executeRaw("DELETE FROM op_checkpoints WHERE op='managed-sync-failure' AND completed_keys->0->>'source_id'=$1", [f.id]);- const refused = await performManagedSync(engine, f.opts);- expect(refused.status).toBe('blocked_by_failures');- expect(refused.failures?.[0]).toMatchObject({ code: 'recovery_required', phase: 'checkpoint', root_cause: { request_id: f.stopped } });- expect((await readSyncStatus(engine, f.id)).checkpoint_blockers).toEqual([expect.objectContaining({ request_id: f.stopped, slug: 'b', knock_on: false })]);- // The receipt that refused it was a knock-on (a pre-#6643 producer's message): it still blocks, and status says what it is.- await asKnockOn(f.stopped, WINDOW_CANCEL_MESSAGE, null);- expect((await readSyncStatus(engine, f.id)).checkpoint_blockers).toEqual([expect.objectContaining({ request_id: f.stopped, slug: 'b', knock_on: true })]);- const resumed = await performManagedSync(engine, { ...f.opts, retryFailed });- expect(resumed.status).not.toBe('blocked_by_failures');- expect((await readSyncStatus(engine, f.id)).cursor).toMatchObject({ done: true });- const [source] = await engine.executeRaw<{ last_commit: string }>('SELECT last_commit FROM sources WHERE id=$1', [f.id]);- expect(source!.last_commit).toBe(git(f.root, 'rev-parse', 'HEAD'));- } finally { await clearConfig(); }-}), 120_000);--test('a stop on an outside_fence refusal is a root that needs a person in sync status, not a retryable revision_conflict', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {+test('#6712: the cursor fence has two causes; a request the cursor does not hold is outside_fence, even one an older cursor recorded dropping', () => {expect(publicFailureDetail({ origin: 'sync_cursor_fence', cause: 'outside_fence', fence: { index: 3 } })).toMatchObject({ cause: 'outside_fence' });expect(publicFailureDetail({ origin: 'sync_cursor_fence', cause: 'anything else' })).not.toHaveProperty('cause');- try {- const f = await stoppedRun();- await engine.executeRaw(`UPDATE op_checkpoints SET completed_keys=jsonb_set(jsonb_set(completed_keys,'{0,code}','"revision_conflict"'),'{0,write_error_detail}',$1::jsonb)- WHERE op='managed-sync-failure' AND completed_keys->0->>'source_id'=$2`, [JSON.stringify({ origin: 'sync_cursor_fence', cause: 'outside_fence' }), f.id]);- const status = await readSyncStatus(engine, f.id);- expect(status.last_error).toMatchObject({ code: 'revision_conflict', detail: 'outside_fence', class: 'systemic', needs_human: true });- expect(status.needs_human).toBe(true);- expect(status.next?.argv).not.toContain('--retry-failed');- expect(status.cursors).toHaveLength(1);- expect(status.cursors[0]).toMatchObject({ run_id: status.run_id, shown: true, done: false, pending: { request_id: f.stopped } });- } finally { await clearConfig(); }-}), 120_000);--test('#6712: the cursor fence has two causes; a request the cursor does not hold is outside_fence, even one an older cursor recorded dropping', () => {const run = randomUUID(), root = randomUUID(), member = randomUUID(), now = randomUUID();const row = (id: string) => ({ request_id: id, source_id: 'default' }) as never;const intent = { kind: 'managed_sync_import', runId: run, index: 7 } as never;@@ -245,35 +123,6 @@ test('#6712: the cursor fence has two causes; a request the cursor does not holdexpect(detail(member, { ...fence, run_id: randomUUID() })).toMatchObject({ cause: 'run_replaced' });});-test('with two cursors, sync status shows the one its recorded failure belongs to and lists both', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {- try {- const f = await stoppedRun();- const blockedRun = (await readSyncStatus(engine, f.id)).run_id!;- await clearConfig();- // A newer cursor of the same source, selected by different options, runs to the end. #6712 PR 1: one key per source,- // so a second cursor is one an older gbrain left under its own key; it ran while the blocked cursor did not exist for it.- const blockedKey = (await engine.executeRaw<{ fingerprint: string }>("SELECT fingerprint FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [f.id]))[0]!.fingerprint;- await engine.executeRaw("UPDATE op_checkpoints SET op='managed-sync-parked' WHERE op='managed-sync' AND fingerprint=$1", [blockedKey]);- __setManagedCursorKeyForTests(() => `${f.id}-older-key`);- let other: Awaited<ReturnType<typeof performManagedSync>>;- try { other = await performManagedSync(engine, { ...f.opts, exclude: ['nothing-matches/**'] }); }- finally {- __setManagedCursorKeyForTests(null);- await engine.executeRaw("UPDATE op_checkpoints SET op='managed-sync' WHERE op='managed-sync-parked' AND fingerprint=$1", [blockedKey]);- }- expect(other.status).not.toBe('blocked_by_failures');- const status = await readSyncStatus(engine, f.id);- expect(status.run_id).toBe(blockedRun);- expect(status.cursor?.done).toBe(false);- expect(status.last_error?.code).toBe('source_changed');- expect(status.next?.argv).not.toContain('--exclude');- expect(status.cursors).toHaveLength(2);- expect(status.cursors.filter(cursor => cursor.shown).map(cursor => cursor.run_id)).toEqual([blockedRun]);- expect(status.cursors.find(cursor => !cursor.shown)).toMatchObject({ done: true, last_error_code: null });- expect(status.cursors.find(cursor => !cursor.shown)!.resume_argv).toContain('--exclude');- } finally { await clearConfig(); }-}), 120_000);-test('the never-admitted legacy patterns match only with text where their ids stood', () => {const id = randomUUID(), other = randomUUID();expect(legacyKnockOnMessage('cancelled', 'cancelled', `Its predecessor request ${id} was never admitted; this page was not published and is re-frozen on the next sync pass.`)).toBe(true);diff --git a/test/sync-legacy-retry-actions-6696.test.ts b/test/sync-legacy-retry-actions-6696.test.tsindex 33c192da9b..880b0e59ad 100644--- a/test/sync-legacy-retry-actions-6696.test.ts+++ b/test/sync-legacy-retry-actions-6696.test.ts@@ -10,6 +10,10 @@** Regression that fails it: the "no longer records them" text, a legacy failure that survives the retry, or a cursor-less* row with no printed way out.+ *+ * #6712 PR 4b: a non-company source keeps no cursor, so its first live pass retires every older-key cursor of the+ * incarnation with its failure row (`retireLegacyCursors`); the first test seeds the two unfinished cursors an older gbrain+ * left instead of running one, and none of them remains after the retry.*/import { afterAll, beforeAll, expect, test } from 'bun:test';import { randomUUID } from 'node:crypto';@@ -26,7 +30,8 @@ import { claimWorktree } from '../src/core/persistence/ownership.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import { performManagedSync } from '../src/core/persistence/sync-run.ts';import { readManagedSyncFailures, recordManagedSyncFailure } from '../src/core/persistence/sync-failures.ts';-import { __setManagedCursorKeyForTests } from '../src/core/persistence/sync-cursor-key.ts';+import { resolveManagedSyncContext } from '../src/core/persistence/sync-discovery.ts';+import { managedSyncAuthority } from '../src/core/persistence/sync-authority.ts';import { managedSyncOrphansRepair } from '../src/core/repair/managed-sync-orphans.ts';import { runRepair } from '../src/core/repair/core.ts';import { repairSpec } from '../src/core/repair/registry.ts';@@ -70,9 +75,6 @@ afterAll(async () => {const cursorKeys = async (engine: BrainEngine, id: string) => (await engine.executeRaw<{ key: string; syncOptions: Record<string, unknown> | null }>("SELECT fingerprint AS key,completed_keys->0->'syncOptions' AS \"syncOptions\" FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [id]));-/** A run recorded before cursors kept their options: strip them from the header. */-const stripOptions = (engine: BrainEngine, key: string) => engine.executeRaw(- "UPDATE op_checkpoints SET completed_keys=jsonb_set(completed_keys,'{0}',(completed_keys->0)-'syncOptions') WHERE op='managed-sync' AND fingerprint=$1", [key]);const failureKeys = async (engine: BrainEngine, id: string) => (await engine.executeRaw<{ key: string }>("SELECT fingerprint AS key FROM op_checkpoints WHERE op='managed-sync-failure' AND completed_keys->0->>'source_id'=$1 ORDER BY fingerprint", [id])).map(row => row.key);@@ -115,21 +117,27 @@ const actionLine = (out: string, label: RegExp) => {return found!.slice(found!.lastIndexOf(': ') + 2).trim();};-/** Runs `fn` as an older gbrain whose cursor key for this source is `key`, with the other older cursor out of its sight. */-async function legacy<T>(engine: BrainEngine, key: string, fn: () => Promise<T>, hide?: string): Promise<T> {- const park = (fingerprint: string, op: string) => engine.executeRaw("UPDATE op_checkpoints SET op=$2 WHERE fingerprint=$1 AND op IN ('managed-sync','managed-sync-parked')", [fingerprint, op]);- __setManagedCursorKeyForTests(() => key);- if (hide) await park(hide, 'managed-sync-parked');- try { return await fn(); } finally { __setManagedCursorKeyForTests(null); if (hide) await park(hide, 'managed-sync'); }+/** An unfinished cursor (and manifest) an older gbrain left under `key`, recorded before cursors kept their options. */+async function legacyCursor(engine: BrainEngine, id: string, key: string, ageMinutes: number, extra: Record<string, unknown> = {}) {+ const [source] = await engine.executeRaw<{ incarnation: string; root: string }>('SELECT incarnation::text AS incarnation, local_path AS root FROM sources WHERE id=$1', [id]);+ const context = await resolveManagedSyncContext(engine, { sourceId: id, noPull: true } as SyncOpts);+ const authority = await managedSyncAuthority(engine, id, source!.incarnation, source!.root);+ const runId = `run-${key}`, at = new Date(Date.now() - ageMinutes * 60_000).toISOString();+ const entries = [0, 1, 2, 3].map(i => ({ path: `notes/n${i}.md`, sourcePath: `notes/n${i}.md`, action: 'import', working: false, slug: `notes/n${i}`, pageId: null, revision: null }));+ const binding = { ...context.binding, owner_epoch: String((context.binding as { owner_epoch?: unknown }).owner_epoch), topology_generation: String(context.binding.topology_generation) };+ const cursor = { binding, root: context.root, gitRoot: context.gitRoot, sourceId: id, incarnation: source!.incarnation, from: null, target: git(source!.root, 'rev-parse', 'HEAD'),+ slugMode: 'git-root', discoveredAt: at, runId, index: 1, total: entries.length, authority, processingOptions: { noEmbed: false, noExtract: false, noSchemaPack: false },+ counts: { added: 1, modified: 0, deleted: 0, chunks: 0 }, ...extra };+ await engine.executeRaw('INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at) VALUES($1,$2,$3::text::jsonb,$4::timestamptz)', ['managed-sync', key, JSON.stringify([cursor]), at]);+ await engine.executeRaw('INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at) VALUES($1,$2,$3::text::jsonb,$4::timestamptz)', ['managed-sync-manifest', runId, JSON.stringify(entries), at]);}const orphanCommand = (id: string) => `gbrain repair managed-sync-orphans --source ${id}`;test('legacy failures under older keys: one --retry-failed folds their cursors in and settles them; the printed repair settles the cursor-less row', async () => withEnv(env, async () => { for (const engine of engines) {const { id, run, failure } = await fixture(engine);const fullKey = `${id}-full`, excludeKey = `${id}-exclude`;- expect(await legacy(engine, fullKey, () => run({ full: true }))).toMatchObject({ status: 'partial' });- expect(await legacy(engine, excludeKey, () => run({ exclude: ['archive/**'] }), fullKey)).toMatchObject({ status: 'partial' });- await stripOptions(engine, fullKey); await stripOptions(engine, excludeKey);+ await legacyCursor(engine, id, fullKey, 60);+ await legacyCursor(engine, id, excludeKey, 10);const noCursorKey = `legacy-${randomUUID()}`;await failure(fullKey, 'notes/n1.md'); await failure(excludeKey, 'notes/n2.md'); await failure(noCursorKey, 'assets/data.bin');expect((await readManagedSyncFailures(engine, [id])).filter(row => row.syncOptions)).toEqual([]);@@ -139,8 +147,8 @@ test('legacy failures under older keys: one --retry-failed folds their cursors iexpect(out).toContain('Retrying 3 previously-failed file(s)...');expect(out).toContain(`1 of them belong to no sync run any more`);expect(out).toContain(orphanCommand(id));- // The newer older-key cursor finished in place under its own key; the --full one was superseded with its failure.- expect((await cursorKeys(engine, id)).map(row => row.key)).toEqual([excludeKey]);+ // The first pass retired both older-key cursors with their failures; the cursor-less row is left to the printed repair.+ expect((await cursorKeys(engine, id)).map(row => row.key)).toEqual([]);expect(await failureKeys(engine, id)).toEqual([noCursorKey]);await runAction(engine, orphanCommand(id));@@ -152,7 +160,7 @@ test('a cursor-less legacy failure for a file no run imports is named with the oconst { id, run, failure } = await fixture(engine);// A --full run that finished and was retired: its failure row outlived its cursor and never recorded the options.const fullKey = `${id}-full`;- expect(await legacy(engine, fullKey, () => run({ full: true }, { maxPages: 1000, maxMs: 60_000 }))).toMatchObject({ status: 'first_sync' });+ expect(await run({ full: true }, { maxPages: 1000, maxMs: 60_000 })).toMatchObject({ status: 'first_sync' });await engine.executeRaw("DELETE FROM op_checkpoints WHERE op='managed-sync' AND fingerprint=$1", [fullKey]);await failure(fullKey, 'assets/data.bin');const out = await capture(() => runSyncInner(engine, ['--source', id, '--no-pull', '--retry-failed']));diff --git a/test/sync-pass-failure-retry-6712.test.ts b/test/sync-pass-failure-retry-6712.test.tsnew file mode 100644index 0000000000..a17e3eb74f--- /dev/null+++ b/test/sync-pass-failure-retry-6712.test.ts@@ -0,0 +1,110 @@+/**+ * #6712 PR 4b lane C: a recorded failure is retried by the next plain sync, on the live pass.+ *+ * Replaces what sync-knock-on-recovery-6643, sync-legacy-retry-actions-6696 and sync-checkpoint-moved-6834 pinned through a+ * non-company cursor (re-freezing a stopped entry, folding older cursors in on --retry-failed, finishing a checkpoint whose+ * source moved). Protects:+ * - a page whose import fails in one pass is imported by the next plain sync, and by its --retry-failed alias: the source+ * checkpoints HEAD, no failure row of the source remains and sync status shows no error;+ * - a brain an older binary left with a blocked unfinished cursor and its recorded checkpoint failure converges on the+ * next plain sync (and on its --retry-failed alias): the cursor and its failure row are gone and sync status is clean.+ * Synthetic content only.+ */+import { afterAll, afterEach, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { execFileSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { SyncOpts } from '../src/commands/sync.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { installFaultHook } from '../src/core/persistence/fault-points.ts';+import { readManagedSyncFailures, recordManagedSyncFailure } from '../src/core/persistence/sync-failures.ts';+import { readSyncStatus } from '../src/core/persistence/sync-status.ts';+import { resolveManagedSyncContext } from '../src/core/persistence/sync-discovery.ts';+import { managedSyncAuthority } from '../src/core/persistence/sync-authority.ts';+import { syncCursorOptions } from '../src/core/persistence/sync-slices.ts';+import { withEnv } from './helpers/with-env.ts';++const home = mkdtempSync(join(tmpdir(), 'gbrain-pass-failure-retry-'));+let engine: PGLiteEngine;+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+const NAMES = ['a', 'b', 'c'];+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);+afterEach(() => installFaultHook(undefined));+afterAll(async () => {+ await withEnv({ GBRAIN_HOME: home }, async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); });+ rmSync(home, { recursive: true, force: true });+});+const isolated = <T>(fn: () => Promise<T>) => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, OPENAI_API_KEY: undefined, ANTHROPIC_API_KEY: undefined }, fn);+async function fixture() {+ const id = `retry-${randomUUID().slice(0, 12)}`, root = join(home, id);+ mkdirSync(root); git(root, 'init', '-q');+ for (const name of NAMES) writeFileSync(join(root, `${name}.md`), `---\ntitle: ${name}\n---\nA durable observation named ${name} at fund-a.\n`);+ git(root, 'add', '.'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'seed');+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,\'{}\')', [id, root]);+ await claimWorktree(engine, id, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ return { id, root, opts: { sourceId: id, noPull: true, noEmbed: true, noExtract: true } as SyncOpts };+}+const livePages = async (id: string) => (await engine.executeRaw<{ slug: string }>('SELECT slug FROM pages WHERE source_id=$1 AND deleted_at IS NULL ORDER BY slug', [id])).map(row => row.slug);+const lastCommit = async (id: string) => (await engine.executeRaw<{ c: string | null }>('SELECT last_commit AS c FROM sources WHERE id=$1', [id]))[0]!.c;+const cursorRows = async (id: string) => (await engine.executeRaw<{ key: string }>(+ "SELECT fingerprint AS key FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [id])).map(row => row.key);++for (const retryFailed of [false, true]) {+ test(`a page whose import failed in one pass is imported by the next ${retryFailed ? '--retry-failed (plain sync alias)' : 'plain'} sync, which checkpoints HEAD`, async () => isolated(async () => {+ const f = await fixture();+ let failed = 0;+ installFaultHook(async (point, detail) => {+ if (point !== 'consumer:preparing' || !detail.requestId || failed) return;+ const [row] = await engine.executeRaw<{ slug: string; kind: string }>("SELECT slug, intent->>'kind' AS kind FROM persistence_requests WHERE request_id=$1::uuid", [detail.requestId]);+ if (row?.kind === 'managed_sync_import' && row.slug === 'b') { failed++; throw new Error('an injected preparation failure of page b'); }+ });+ const first = await performManagedSync(engine, f.opts).then(result => result.status, (error: { code?: string }) => `threw:${error.code ?? 'unknown'}`);+ installFaultHook(undefined);+ expect(failed).toBe(1);+ expect(first).not.toBe('first_sync');+ expect(await livePages(f.id)).not.toContain('b');+ expect(await lastCommit(f.id)).toBeNull();+ const retried = await performManagedSync(engine, { ...f.opts, retryFailed });+ expect(['first_sync', 'synced']).toContain(retried.status);+ expect(await livePages(f.id)).toEqual(NAMES);+ expect(await lastCommit(f.id)).toBe(git(f.root, 'rev-parse', 'HEAD'));+ expect(await readManagedSyncFailures(engine, [f.id])).toEqual([]);+ expect((await readSyncStatus(engine, f.id)).last_error).toBeNull();+ }), 180_000);++ test(`an older binary's blocked cursor and its recorded checkpoint failure converge on the next ${retryFailed ? '--retry-failed (plain sync alias)' : 'plain'} sync`, async () => isolated(async () => {+ const f = await fixture();+ const incarnation = (await engine.executeRaw<{ i: string }>('SELECT incarnation::text AS i FROM sources WHERE id=$1', [f.id]))[0]!.i;+ const context = await resolveManagedSyncContext(engine, f.opts);+ const authority = await managedSyncAuthority(engine, f.id, incarnation, f.root);+ const head = git(f.root, 'rev-parse', 'HEAD');+ const key = `legacy-blocked-${f.id}`, runId = `run-${key}`;+ const entries = NAMES.map(name => ({ path: `${name}.md`, sourcePath: `${name}.md`, action: 'import', working: false, slug: name, pageId: null, revision: null }));+ const binding = { ...context.binding, owner_epoch: String((context.binding as { owner_epoch?: unknown }).owner_epoch), topology_generation: String(context.binding.topology_generation) };+ const syncOptions = syncCursorOptions(f.opts);+ const cursor = { binding, root: context.root, gitRoot: context.gitRoot, sourceId: f.id, incarnation, from: null, target: head, slugMode: 'git-root', discoveredAt: new Date().toISOString(),+ runId, index: entries.length, total: entries.length, authority, processingOptions: { noEmbed: true, noExtract: true, noSchemaPack: false }, syncOptions,+ counts: { added: 0, modified: 0, deleted: 0, chunks: 0 } };+ await engine.executeRaw("INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES('managed-sync',$1,$2::text::jsonb)", [key, JSON.stringify([cursor])]);+ await engine.executeRaw("INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES('managed-sync-manifest',$1,$2::text::jsonb)", [runId, JSON.stringify(entries)]);+ await recordManagedSyncFailure(engine, { source_id: f.id, source_incarnation: incarnation, path: '__managed_sync_checkpoint__', code: 'revision_conflict',+ message: 'The source checkpoint changed during this sync.', request_id: randomUUID(), run_id: runId, target: head, cursor_key: key, phase: 'checkpoint', state: 'conflict',+ observation_id: randomUUID(), syncOptions, processingOptions: { noEmbed: true, noExtract: true, noSchemaPack: false } });+ expect((await readManagedSyncFailures(engine, [f.id])).map(row => [row.code, row.phase])).toEqual([['revision_conflict', 'checkpoint']]);+ const converged = await performManagedSync(engine, { ...f.opts, retryFailed });+ expect(converged.status).toBe('first_sync');+ expect(await cursorRows(f.id)).toEqual([]);+ expect(await readManagedSyncFailures(engine, [f.id])).toEqual([]);+ expect((await readSyncStatus(engine, f.id)).last_error).toBeNull();+ expect(await livePages(f.id)).toEqual(NAMES);+ expect(await lastCommit(f.id)).toBe(head);+ }), 180_000);+}