Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
test(sync): #6712 PR 4b item 6 pass-era tests assert the pass on the same data
garrytan196d9341a78b
diff --git a/test/hold-action-chain-6712.test.ts b/test/hold-action-chain-6712.test.tsindex 511700e08c..960f2c92e7 100644--- a/test/hold-action-chain-6712.test.ts+++ b/test/hold-action-chain-6712.test.ts@@ -8,7 +8,9 @@* - runs the hold's fix chain step by step (`next: run` only; a repair preview, then the apply command it printed,* bound to the preview's hash with `--expect`; then the next step), and the hold clears.* A code whose way out is a person's act (commit the dirty edit, exclude the image, pick the drift side) gets that act- * from the fixture first, as the person would, and the chain then clears it.+ * from the fixture first, as the person would, and the chain then clears it. #6712 PR 4b: the file_drift fixture moves+ * the page on both sides (a database-only edit of an unchanged file is db_ahead and kept without a hold), and the+ * concurrent write races the pass's in-memory batch instead of a cursor row.* Fails when: a printed fix cannot clear its hold, a hold that cannot clear asks nobody (or asks in more than one* sentence), or a needs_human hold's first step writes.* PGLite always; Postgres too when DATABASE_URL is set.@@ -30,6 +32,7 @@ import { performManagedSync } from '../src/core/persistence/sync-run.ts';import { GIT_HOLD_OP, gitHoldFingerprint, readGitSourceHolds, SYNC_IMPORT_PROVENANCE_OP, writeGitHold } from '../src/core/persistence/sync-holds.ts';import { HOLD_ATTEMPTS_NEEDS_HUMAN, HOLD_ESCALATE_MS } from '../src/core/persistence/sync-fault-class.ts';import { installFaultHook } from '../src/core/persistence/fault-points.ts';+import { PASS_BATCH_KEY_PREFIX, readPassBatch } from '../src/core/persistence/sync-pass-batch.ts';import { localHostId } from '../src/core/persistence/identity.ts';import { runPersistenceEffects } from '../src/core/persistence/effects.ts';import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';@@ -278,7 +281,8 @@ test('worktree_dirty: once the editor commits, unblock schedules the file and thexpect((await agent(engine, s.id, 'notes/b.md')).outcome).toBe('still_held');commit(s.root, 'the editor commits');const result = await agent(engine, s.id, 'notes/b.md');- expect(result.ran).toEqual([`gbrain sync unblock --source ${s.id} --apply --json`, `gbrain sync --source ${s.id} --no-pull --no-embed --no-extract`]);+ // #6712 PR 4b: the pass that held b converged and closed its opt-out episode, so the printed sync carries no inherited flags.+ expect(result.ran).toEqual([`gbrain sync unblock --source ${s.id} --apply --json`, `gbrain sync --source ${s.id} --no-pull`]);expect(result.outcome).toBe('cleared');expect((await engine.getPage('notes/b', { sourceId: s.id }))?.compiled_truth).toContain('A private edit still in progress.');}), 180_000);@@ -352,7 +356,7 @@ test('managed_image_sync_unsupported: never escalates and is nobody\'s next stepexpect(await s.held()).toEqual([]);}), 180_000);-test('file_drift: a person picks the side; the database-side preview, its apply and the sync then clear the hold', () => each(async engine => {+test('file_drift: a person picks the side of a page that moved on both sides; the database-side preview, its apply and the sync then clear the hold', () => each(async engine => {const s = await managed(engine, { 'notes/a.md': note('notes/a', 'The committed body.', 'type: concept\n') });await engine.setConfig('sync.write_through', 'false');await s.sync();@@ -361,11 +365,12 @@ test('file_drift: a person picks the side; the database-side preview, its applyawait submitPageMutation(s.ctx, { operation: 'put_page', params: { slug: 'notes/a', request_id: requestId, expected_revision: current!.revision, content: note('notes/a', 'The database-only edit.', 'type: concept\n') } });await waitFor(async () => (await engine.executeRaw<{ state: string }>('SELECT state FROM persistence_requests WHERE request_id=$1::uuid', [requestId]))[0]?.state === 'committed',{ timeoutMs: 20_000, label: 'the database-only put_page commits' });- // A history rewrite makes the next sync walk the whole tree at HEAD, so it meets the unchanged file and the moved page.- const rewritten = git(s.root, 'commit-tree', 'HEAD^{tree}', '-m', 'rewritten');- git(s.root, 'reset', '-q', '--soft', rewritten); git(s.root, 'reflog', 'expire', '--expire=now', '--all'); git(s.root, 'gc', '-q', '--prune=now');+ // The file changes too: both sides moved since the last import, so the pass holds the file instead of choosing.+ // (A database-only edit of an unchanged file is db_ahead and kept without a hold.)+ s.write('notes/a.md', note('notes/a', 'The committed edit.', 'type: concept\n')); commit(s.root, 'file edit');await s.sync();expect(await s.held()).toEqual([{ path: 'notes/a.md', code: 'file_drift' }]);+ expect((await engine.getPage('notes/a', { sourceId: s.id }))?.compiled_truth).toContain('The database-only edit.');const asked = await agent(engine, s.id, 'notes/a.md');expect(expectAsked(asked)).toContain('a person chooses which version wins');expect(asked.hold.fix.argv).toEqual(['gbrain', 'repair', 'file-drift', '--source', s.id, '--slug', 'notes/a', '--prefer', 'database']);@@ -390,8 +395,10 @@ test('concurrent_write: the two versions diverged under the sync; the agent relalet fired = false;installFaultHook(async (point, detail) => {if (point !== 'sync:mid_checkpoint' || detail.sourceId !== s.id || fired) return;- const [row] = await engine.executeRaw<{ slug: string | null }>("SELECT completed_keys->0->'pending'->>'slug' AS slug FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [s.id]);- if (row?.slug !== 'people/alice-example') return;+ // The pass's in-memory batch holds the page's frozen import, not yet published.+ const [row] = await engine.executeRaw<{ pass_id: string | null }>("SELECT completed_keys->0->'telemetry'->>'pass_id' AS pass_id FROM op_checkpoints WHERE op='managed-sync-pass' AND completed_keys->0->>'source_id'=$1", [s.id]);+ const pending = row?.pass_id ? Array.from({ length: 8 }, (_, batch) => readPassBatch<{ pending?: { slug?: string } | null }>(`${PASS_BATCH_KEY_PREFIX}${row.pass_id}:${batch}`)?.pending?.slug).find(Boolean) : undefined;+ if (pending !== 'people/alice-example') return;fired = true;const requestId = randomUUID();const current = await engine.readPageSnapshot('people/alice-example', { sourceId: s.id });diff --git a/test/managed-sync-blocked-job-6858.test.ts b/test/managed-sync-blocked-job-6858.test.tsindex ee30c84d3c..0e1346eff3 100644--- a/test/managed-sync-blocked-job-6858.test.ts+++ b/test/managed-sync-blocked-job-6858.test.ts@@ -111,14 +111,14 @@ test('#6858: a freshness sync job whose managed run is blocked ends dead with thconst stale = await readBrainHealthBands(engine, { sourceIds: [s.id] }, Date.now() + 2_000_000 + nth);expect(stale).toMatchObject({ status: 'attention', sync_blocked: { band: '1-9' } });- // A resumed run saves its cursor after the recorded stop while the failure row stays until the run finishes: it is- // draining, not blocked. A stop recorded again after that save is blocked again.- const [{ key }] = await engine.executeRaw<{ key: string }>("SELECT fingerprint AS key FROM op_checkpoints WHERE op='managed-sync-failure' AND completed_keys->0->>'source_id'=$1", [s.id]);- await engine.executeRaw("UPDATE op_checkpoints SET updated_at=now()+interval '1 minute' WHERE op='managed-sync' AND fingerprint=$1", [key]);+ // #6712 PR 4b: a resumed pass records itself open in its pass row while the failure row stays until a pass converges:+ // it is draining, not blocked. A pass that stops blocked again is blocked again, with the write's code.+ const outcome = (value: string) => engine.executeRaw("UPDATE op_checkpoints SET completed_keys=jsonb_set(completed_keys,'{0,telemetry,outcome}',to_jsonb($2::text)) WHERE op='managed-sync-pass' AND completed_keys->0->>'source_id'=$1", [s.id, value]);+ await outcome('open');expect(await readBlockedManagedSyncs(engine, [s.id])).toEqual([]);expect(await check()).toEqual([expect.objectContaining({ name: 'managed_sync_blocked', status: 'ok' })]);expect((await readBrainHealthBands(engine, { sourceIds: [s.id] }, Date.now() + 3_000_000 + nth)).sync_blocked.band).toBe('none');- await engine.executeRaw("UPDATE op_checkpoints SET updated_at=now()+interval '2 minutes' WHERE op='managed-sync-failure' AND fingerprint=$1", [key]);+ await outcome('blocked');expect(await readBlockedManagedSyncs(engine, [s.id])).toEqual([expect.objectContaining({ source_id: s.id, code: 'source_changed' })]);nth++;await disposePersistenceConsumer(engine);diff --git a/test/managed-sync-concurrent-write-hold.test.ts b/test/managed-sync-concurrent-write-hold.test.tsindex 53ed92bcfd..0d053db746 100644--- a/test/managed-sync-concurrent-write-hold.test.ts+++ b/test/managed-sync-concurrent-write-hold.test.ts@@ -18,6 +18,7 @@ import { performManagedSync } from '../src/core/persistence/sync-run.ts';import { installFaultHook } from '../src/core/persistence/fault-points.ts';import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';import { readGitHold } from '../src/core/persistence/sync-holds.ts';+import { PASS_BATCH_KEY_PREFIX, readPassBatch } from '../src/core/persistence/sync-pass-batch.ts';import { withCoordinatedWrite } from '../src/core/persistence/context.ts';import { managedBrain } from './helpers/managed-brain.ts';import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';@@ -27,9 +28,15 @@ const SLUG = 'people/alice-example';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) => `---\ntype: person\ntitle: Alice Example\n---\n\n${body}\n`;+/** The slug of the import the running pass froze and has not settled yet (its in-memory batch's pending entry). */async function storedPending(engine: BrainEngine): Promise<string | null> {- const [row] = await engine.executeRaw<{ slug: string | null }>("SELECT completed_keys->0->'pending'->>'slug' AS slug FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'='default'");- return row?.slug ?? null;+ const [row] = await engine.executeRaw<{ pass_id: string | null }>("SELECT completed_keys->0->'telemetry'->>'pass_id' AS pass_id FROM op_checkpoints WHERE op='managed-sync-pass' AND completed_keys->0->>'source_id'='default'");+ if (!row?.pass_id) return null;+ for (let batch = 0; batch < 8; batch++) {+ const slug = readPassBatch<{ pending?: { slug?: string } | null }>(`${PASS_BATCH_KEY_PREFIX}${row.pass_id}:${batch}`)?.pending?.slug;+ if (slug) return slug;+ }+ return null;}/** First sync imports the page; then Git gets a newer version and a database-only write races the next import. */diff --git a/test/managed-sync-keep-disk-6858.test.ts b/test/managed-sync-keep-disk-6858.test.tsindex d1bfb6b1a8..0f523f8f9e 100644--- a/test/managed-sync-keep-disk-6858.test.ts+++ b/test/managed-sync-keep-disk-6858.test.ts@@ -6,6 +6,8 @@* `blocked_by_failures` and every later plain sync returned the same parked run. The abandoned page is a changed-file* page fault now: it is retried after the manifest end in the same pass, imported when the disk bytes are HEAD's* (the lossless case), held `worktree_dirty` when they are an uncommitted edit, and the rest of the source drains.+ * #6712 PR 4b: a non-company source runs the live pass, which pins HEAD, so the lossless case ends at the commit of the+ * kept bytes rather than the cursor's frozen target.* Synthetic content only.*/import { afterAll, beforeAll, expect, test } from 'bun:test';@@ -127,8 +129,11 @@ test('#6858: a page abandoned by repair stuck-recovery --keep disk with uncommittest('#6858: when the kept disk bytes are HEAD (the lossless --keep disk case) the re-freeze imports them in the same pass', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {for (const engine of engines) {const { f, pin } = await abandonedMidRun(engine, root => { commit(root, 'the stamped bytes are committed'); });+ const head = git(f.root, 'rev-parse', 'HEAD');+ expect(head).not.toBe(pin);+ // The pass pins HEAD, the commit of the stamped bytes, where the cursor finished at its frozen target.const resumed = await settle(engine, f.opts);- expect(resumed).toMatchObject({ status: 'synced', toCommit: pin });+ expect(resumed).toMatchObject({ status: 'synced', toCommit: head, pass: { kind: 'full', outcome: 'synced', remaining: 0 } });expect(resumed.held ?? []).toEqual([]);expect(resumed.failedFiles ?? 0).toBe(0);expect(await readManagedSyncFailures(engine, [f.id])).toEqual([]);diff --git a/test/managed-sync-page-fault-holds.test.ts b/test/managed-sync-page-fault-holds.test.tsindex a255e70dae..e05f5993e0 100644--- a/test/managed-sync-page-fault-holds.test.ts+++ b/test/managed-sync-page-fault-holds.test.ts@@ -10,6 +10,16 @@* returns `blocked_by_failures`, or the next run rediscovers from index 0) and* passes with the resolver (`sync-page-fault.ts`), the receipt conversions and* the ledger skip. Synthetic content only.+ *+ * #6712 PR 4b: a non-company source runs the live pass, which has no frozen manifest or cursor. The rewritten probes+ * protect the same data under the pass: after an interrupted pass the next pass pins the new HEAD and imports a page+ * committed since, without re-importing what the interrupted pass absorbed; a database edit landing between passes on a+ * page whose file changed too is held file_drift (both sides), one that already holds the file's import is waived, and+ * one deleted there is held file_drift on its deleted side (tombstone_edited) and stays deleted;+ * a dropped connection leaves no failure-ledger row and the relaunch imports only what is left; a file committed after+ * admission is passed over and imported in a later round, and one that moves under every request stops the pass+ * not_converged after PASS_MAX_ROUNDS requests without a hold. The cursor conversion probes (--retry-failed in place)+ * still describe the cursor engine.*/import { afterAll, beforeAll, expect, test } from 'bun:test';import { randomUUID } from 'node:crypto';@@ -32,6 +42,8 @@ import { withEnv } from './helpers/with-env.ts';import { loadSyncFailures } from '../src/core/sync-failure-ledger.ts';import { parseMarkdown } from '../src/core/markdown.ts';import { contentHash } from '../src/core/utils.ts';+import { PASS_MAX_ROUNDS } from '../src/core/persistence/sync-pass-run.ts';+import { readShadowLevel } from '../src/core/persistence/sync-pass.ts';const home = mkdtempSync(join(tmpdir(), 'gbrain-page-fault-holds-'));const engines: BrainEngine[] = [];@@ -87,23 +99,29 @@ afterAll(async () => {rmSync(home, { recursive: true, force: true });});-test('a resumed cursor imports a page committed past its pinned target instead of refusing it (#6320, from PR #6323)', async () => withEnv({ GBRAIN_HOME: home }, async () => {+test('after an interrupted pass, the next pass pins the new HEAD and imports a page committed past the interrupted target instead of refusing it (#6320, from PR #6323)', async () => withEnv({ GBRAIN_HOME: home }, async () => {for (const engine of engines) {const f = await fixture(engine, { 'a.md': note('First observation, version one.'), 'b.md': note('Second observation, version one.') });expect((await performManagedSync(engine, f.opts)).status).toBe('first_sync');writeFileSync(join(f.root, 'a.md'), note('First observation, version two.')); writeFileSync(join(f.root, 'b.md'), note('Second observation, version two.'));- const pin = commit(f.root, 'version two of both');+ commit(f.root, 'version two of both');await interruptedAfter(engine, f.opts, 1);- // A live checkout keeps committing while the cursor drains: b.md moves past the pin.+ // A live checkout keeps committing: b.md moves past the interrupted pass's target.writeFileSync(join(f.root, 'b.md'), note('Second observation, version three.')); const head = commit(f.root, 'version three of b, past the pin');expect(headCommittedBytes({ root: f.root, gitRoot: f.root }, 'b.md')).toMatchObject({ oid: git(f.root, 'rev-parse', 'HEAD:b.md') });+ const before = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM persistence_requests WHERE source_id=$1 AND intent->>'path'='a.md'", [f.id]);const resumed = await performManagedSync(engine, f.opts);- expect(resumed).toMatchObject({ status: 'synced', toCommit: pin }); expect(resumed.held_count ?? 0).toBe(0); expect(resumed.managedWrite).toBeUndefined();+ // a.md was absorbed by the interrupted pass, so only b.md is a candidate, imported at HEAD.+ expect(resumed).toMatchObject({ status: 'synced', toCommit: head, modified: 1, pass: { kind: 'full', candidates: 1, outcome: 'synced' } });+ expect(resumed.held_count ?? 0).toBe(0); expect(resumed.managedWrite).toBeUndefined();+ expect(await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM persistence_requests WHERE source_id=$1 AND intent->>'path'='a.md'", [f.id])).toEqual(before);+ expect((await engine.getPage('a', { sourceId: f.id }))?.compiled_truth).toContain('version two');expect((await engine.getPage('b', { sourceId: f.id }))?.compiled_truth).toContain('version three');expect(readFileSync(join(f.root, 'b.md'), 'utf8')).toBe(note('Second observation, version three.'));expect(git(f.root, 'status', '--porcelain')).toBe('');const next = await performManagedSync(engine, f.opts);- expect(next).toMatchObject({ toCommit: head, status: 'synced', modified: 0, waived: { imports: 1, deletes: 0 } });+ expect(next).toMatchObject({ toCommit: head, status: 'up_to_date', modified: 0 });+ expect(next.pass).toBeUndefined();expect(loadSyncFailures().filter(row => row.source_id === f.id)).toHaveLength(0);expect(await readManagedSyncFailures(engine, [f.id])).toEqual([]);}@@ -240,44 +258,49 @@ test('#6513: a cursor an older run left blocked on the canonical-writeback confl}}), 120_000);-test('a page edited in the database after the manifest froze is held concurrent_write with its revisions; one that already holds the import is re-bound and waived', async () => withEnv({ GBRAIN_HOME: home }, async () => {+test('a page edited in the database after an interrupted pass, whose file changed too, is held file_drift with both sides; one that already holds the import is waived; one deleted there is held on its deleted side and stays deleted', async () => withEnv({ GBRAIN_HOME: home }, async () => {for (const engine of engines) {const f = await fixture(engine, { 'a.md': note('Alpha one.'), 'b.md': note('Beta one.'), 'c.md': note('Gamma one.'), 'd.md': note('Delta one.') });expect((await performManagedSync(engine, f.opts)).status).toBe('first_sync');for (const name of ['a', 'b', 'c', 'd']) writeFileSync(join(f.root, `${name}.md`), note(`${name} two.`));const pin = commit(f.root, 'version two');await interruptedAfter(engine, f.opts, 1);- const frozen = await cursorOf(engine, f.id);// b: a database-only edit that diverges from the file; c: a database write that already carries exactly what the file would import.+ // No import of either is in flight when they land, so the pass classifies them: b moved on both sides, c already holds the file's import.await dbWrite(engine, f.id, 'b', 'Beta, edited straight in the database.');const parsed = parseMarkdown(note('c two.'), 'c.md');const page = { type: parsed.type, title: parsed.title, compiled_truth: parsed.compiled_truth, timeline: parsed.timeline ?? '', frontmatter: parsed.frontmatter };await engine.transaction(tx => withCoordinatedWrite(tx, [f.id], () => tx.putPage('c', { ...page, content_hash: contentHash(page) }, { sourceId: f.id }), TEST_WRITE_ATTRIBUTION));const resumed = await performManagedSync(engine, f.opts);- expect(resumed).toMatchObject({ status: 'synced', toCommit: pin, held_count: 1, held: [{ path: 'b.md', code: 'concurrent_write' }] });+ expect(resumed).toMatchObject({ status: 'synced', toCommit: pin, held_count: 1, held: [{ path: 'b.md', code: 'file_drift' }], modified: 1, waived: { imports: 1 } });expect(resumed.managedWrite).toBeUndefined();- expect((await cursorOf(engine, f.id))?.run_id).toBe(frozen.run_id);expect((await engine.getPage('b', { sourceId: f.id }))?.compiled_truth).toBe('Beta, edited straight in the database.');expect((await engine.getPage('c', { sourceId: f.id }))?.compiled_truth).toBe(parsed.compiled_truth);expect((await engine.getPage('d', { sourceId: f.id }))?.compiled_truth).toContain('d two.');const [source] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [f.id]);const hold = (await readGitHold(engine, f.id, source.incarnation, 'b.md'))!;- expect(hold.meta.page_revision).toBeDefined(); expect(hold.meta.expected_revision).toBeDefined();- expect(hold.meta.page_revision).not.toBe(hold.meta.expected_revision);- expect(resumed.held![0]!.fix.argv).toEqual(['gbrain', 'sources', 'reconcile', f.id, 'b', '--preview']);+ expect(hold.meta).toMatchObject({ sides: 'both', page_revision: (await engine.readPageSnapshot('b', { sourceId: f.id }))!.revision, blob_oid: git(f.root, 'rev-parse', `${pin}:b.md`) });+ expect(resumed.held![0]!.fix.argv).toEqual(['gbrain', 'repair', 'file-drift', '--source', f.id, '--slug', 'b', '--prefer', 'database']);expect(await readGitHold(engine, f.id, source.incarnation, 'c.md')).toBeNull();+ const level = (await readShadowLevel(engine, { sourceId: f.id }))!;+ expect(level.paths.find(entry => entry.path === 'b.md')?.result).toMatchObject({ cls: 'held', settled: true });+ expect(level.paths.find(entry => entry.path === 'c.md')?.result).toMatchObject({ cls: 'matched', settled: true });expect(await readManagedSyncFailures(engine, [f.id])).toEqual([]);- // A page deleted in the database after the freeze holds the same way; the page stays deleted. #6712: b still holds its- // database-only edit, so the next committed edit of b.md is held file_drift instead of overwriting it.+ // A page deleted in the database after an interrupted pass, whose file changed too, is held file_drift on its deleted+ // side and stays deleted; b's file moved again, so its hold is re-screened at the new level and held again.for (const name of ['a', 'b', 'c', 'd']) writeFileSync(join(f.root, `${name}.md`), note(`${name} three.`));const pin3 = commit(f.root, 'version three');await interruptedAfter(engine, f.opts, 1);await engine.transaction(tx => withCoordinatedWrite(tx, [f.id], () => tx.softDeletePage('d', { sourceId: f.id }), TEST_WRITE_ATTRIBUTION));const third = await performManagedSync(engine, f.opts);expect(third).toMatchObject({ status: 'synced', toCommit: pin3 });- expect(third.held?.map(hold => [hold.path, hold.code])).toEqual([['b.md', 'file_drift'], ['d.md', 'concurrent_write']]);+ expect(third.held?.map(hold => [hold.path, hold.code])).toEqual([['b.md', 'file_drift'], ['d.md', 'file_drift']]);+ expect(await readGitHold(engine, f.id, source.incarnation, 'd.md')).toMatchObject({ code: 'file_drift', meta: { side: 'deleted', state: 'tombstone_edited', blob_oid: git(f.root, 'rev-parse', `${pin3}:d.md`) } });+ expect(await readGitHold(engine, f.id, source.incarnation, 'b.md')).toMatchObject({ code: 'file_drift', meta: { sides: 'both', blob_oid: git(f.root, 'rev-parse', `${pin3}:b.md`) } });expect((await engine.getPage('b', { sourceId: f.id }))?.compiled_truth).toBe('Beta, edited straight in the database.');expect(await engine.getPage('d', { sourceId: f.id })).toBeNull();+ expect((await engine.getPage('b', { sourceId: f.id }))?.compiled_truth).toBe('Beta, edited straight in the database.');+ expect((await engine.getPage('c', { sourceId: f.id }))?.compiled_truth).toContain('c three.');}}), 120_000);@@ -321,7 +344,7 @@ test('a cursor an older run left blocked on a pinned-worktree conflict converts}}), 120_000);-test('a dropped database connection mid-run leaves no failure-ledger row, and the relaunch resumes the same run at the stored index without discovery', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {+test('a dropped database connection mid-pass leaves no failure-ledger row, and the relaunch finishes without re-importing what the dropped pass committed', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {for (const engine of engines) {const f = await fixture(engine, { 'a.md': note('Alpha one.'), 'b.md': note('Beta one.'), 'c.md': note('Gamma one.'), 'd.md': note('Delta one.') });expect((await performManagedSync(engine, f.opts)).status).toBe('first_sync');@@ -339,26 +362,26 @@ test('a dropped database connection mid-run leaves no failure-ledger row, and thawait performManagedSync(engine, { ...f.opts, onProgress: p => { if (p.phase === 'managed_sync.page_committed' && p.bankedFiles === 2) armed = true; } }).catch(error => { died = error; });} finally { engine.executeRaw = executeRaw; await disposePersistenceConsumer(engine); }expect(String((died as Error)?.message)).toContain('ECONNABORTED');- // No failure-ledger row (the read view still reports the unfinished cursor as `sync_incomplete`, which is not a recorded failure).+ // No failure-ledger row, and no unfinished cursor for the read view to report.expect(await engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op='managed-sync-failure' AND completed_keys::text LIKE $1", [`%${f.id}%`])).toEqual([]);- expect((await readManagedSyncFailures(engine, [f.id])).map(row => row.code)).toEqual(['sync_incomplete']);- const stored = await cursorOf(engine, f.id);- expect(stored).toMatchObject({ target: pin }); expect(stored.done).toBeFalsy();- expect(stored.index).toBeGreaterThanOrEqual(2);- // With or without --retry-failed (the operator's loop passes it), the relaunch resumes the stored run: no rediscovery.+ expect(await readManagedSyncFailures(engine, [f.id])).toEqual([]);+ expect(await cursorOf(engine, f.id)).toBeUndefined();+ const importsOf = async (path: string) => (await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM persistence_requests WHERE source_id=$1 AND intent->>'path'=$2 AND state='committed'", [f.id, path]))[0]!.n;+ // The dropped pass committed a and b (one import each since the first sync); c and d are still the first sync's.+ expect(await importsOf('a.md')).toBe(2); expect(await importsOf('b.md')).toBe(2);+ expect((await engine.getPage('c', { sourceId: f.id }))?.compiled_truth).toContain('Gamma one.');+ // With or without --retry-failed (the operator's loop passes it), the relaunch's pass imports only c and d, then the source is idle.for (const retryFailed of [true, false]) {- const discoveries = countDiscoveries(engine, f.id);- try {- const resumed = await performManagedSync(engine, { ...f.opts, retryFailed });- expect(resumed.status).toBe(retryFailed ? 'synced' : 'up_to_date');- if (retryFailed) { expect(resumed).toMatchObject({ runId: stored.run_id, toCommit: pin }); expect(discoveries.count()).toBe(0); }- } finally { discoveries.restore(); }+ const resumed = await performManagedSync(engine, { ...f.opts, retryFailed });+ if (retryFailed) expect(resumed).toMatchObject({ status: 'synced', toCommit: pin, modified: 2, pass: { kind: 'full', candidates: 2, outcome: 'synced' } });+ else expect(resumed).toMatchObject({ status: 'up_to_date', toCommit: pin });}- expect((await engine.getPage('d', { sourceId: f.id }))?.compiled_truth).toContain('d two.');+ for (const path of ['a.md', 'b.md', 'c.md', 'd.md']) expect(await importsOf(path)).toBe(2);+ for (const name of ['a', 'b', 'c', 'd']) expect((await engine.getPage(name, { sourceId: f.id }))?.compiled_truth).toContain(`${name} two.`);}}), 120_000);-test('when HEAD moves past the pinned target during the run, the drain takes exactly one more pass and ends at HEAD', async () => withEnv({ GBRAIN_HOME: home }, async () => {+test('when HEAD moves past the pass\'s first level during the run, its next round reads the new HEAD and the drain ends there in one pass', async () => withEnv({ GBRAIN_HOME: home }, async () => {const { drainManagedSync } = await import('../src/core/persistence/sync-drain.ts');for (const engine of engines) {const f = await fixture(engine, { 'a.md': note('Alpha one.'), 'b.md': note('Beta one.'), 'c.md': note('Gamma one.') });@@ -373,8 +396,10 @@ test('when HEAD moves past the pinned target during the run, the drain takes examoved = commit(f.root, 'commits during the run');} } }, false);expect(moved).not.toBeNull();- expect(result).toMatchObject({ status: 'synced', toCommit: moved, drain: { outcome: 'synced', extra_pass: { from: pin, to: moved } } });- expect(result.drain!.passes).toBeGreaterThanOrEqual(2);+ // #6712 PR 4b: each round reads the current HEAD, so the pass that started at pin imports the commits made under it.+ expect(pin).not.toBe(moved);+ expect(result).toMatchObject({ status: 'synced', toCommit: moved, drain: { outcome: 'synced', passes: 1 } });+ expect(result.drain?.extra_pass).toBeUndefined();expect((await engine.getPage('d', { sourceId: f.id }))?.compiled_truth).toContain('committed during the run');expect((await engine.getPage('c', { sourceId: f.id }))?.compiled_truth).toContain('c three');expect((await engine.executeRaw<{ last_commit: string }>('SELECT last_commit FROM sources WHERE id=$1', [f.id]))[0].last_commit).toBe(moved!);@@ -384,53 +409,76 @@ test('when HEAD moves past the pinned target during the run, the drain takes exa}}), 120_000);-test('a file committed between admission and publication (raw_file_changed) is retried after the manifest end and imported as HEAD has it; #6712: a file that keeps changing is held after DEFER_PER_ENTRY retries', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {+test('a file committed between admission and publication (raw_file_changed) is passed over and imported in a later round as HEAD has it; #6712: a file that keeps changing stops the pass not_converged after PASS_MAX_ROUNDS requests, unheld, and the next sync imports it', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {for (const engine of engines) {const f = await fixture(engine, { 'a.md': note('Alpha one.'), 'b.md': note('Beta one.'), 'c.md': note('Gamma one.') });expect((await performManagedSync(engine, f.opts)).status).toBe('first_sync');for (const name of ['a', 'b', 'c']) writeFileSync(join(f.root, `${name}.md`), note(`${name} two.`));const pin = commit(f.root, 'version two');- // The admission transaction's last statement re-checks the cursor still holds this entry (ENG-A7). Right after it, for b.md,- // another agent commits version three: publication then finds the file's bytes changed after admission.+ // Right after the pass admits b.md's import (its request row is inserted), another agent commits a newer version:+ // publication then finds the file's bytes changed after admission.const executeRaw = engine.executeRaw;let commits = 0, versions = 0;- const armed = (sql: string, params?: unknown[]) => sql.includes("completed_keys->0->'pending'->>'requestId' AS request_id") && sql.includes('FOR SHARE') && String(params?.[2] ?? '').includes('"path":"b.md"');+ const armed = (sql: string, params?: unknown[]) => { const text = JSON.stringify(params ?? []).replaceAll('\\"', '"'); return sql.includes('INSERT INTO persistence_requests') && text.includes('"path":"b.md"') && text.includes('managed_sync_import'); };engine.executeRaw = async function (this: BrainEngine, sql: string, params?: unknown[]) {const rows = await executeRaw.call(this, sql, params);if (armed(sql, params) && commits < versions) { writeFileSync(join(f.root, 'b.md'), note(`b round ${versions} change ${commits}, committed after admission.`)); commit(f.root, `b moves after admission ${commits}`); commits++; }return rows;} as BrainEngine['executeRaw'];+ let seen = 0;+ /** b.md's import requests since the last call, as [state, error_message]. */+ const newRequests = async () => {+ const rows = await engine.executeRaw<{ state: string; error_message: string | null }>("SELECT state, error_message FROM persistence_requests WHERE source_id=$1 AND intent->>'path'='b.md' ORDER BY sequence", [f.id]);+ const fresh = rows.slice(seen).map(row => [row.state, row.error_message]); seen = rows.length;+ return fresh;+ };+ const CHANGED = ['conflict', 'The imported file changed after sync admission.'];try {+ await newRequests();versions = 1;const once = await performManagedSync(engine, { ...f.opts, noBulk: true });- expect(once).toMatchObject({ status: 'synced', toCommit: pin });+ // #6712 PR 4b: the round after the refusal reads the new HEAD, so the pass ends at the commit it imported, past pin.+ expect(once).toMatchObject({ status: 'synced', toCommit: git(f.root, 'rev-parse', 'HEAD'), pass: { outcome: 'synced' } });+ expect(once.toCommit).not.toBe(pin);expect(once.held ?? []).toEqual([]);- expect(once.converted_from_failed).toHaveLength(1);+ // One refused request, passed over; the next round imports the file as HEAD has it. No second refusal, no double import.+ expect(await newRequests()).toEqual([CHANGED, ['committed', null]]);expect((await engine.getPage('b', { sourceId: f.id }))?.compiled_truth).toContain('b round 1 change 0');expect(await readManagedSyncFailures(engine, [f.id])).toEqual([]);- // #6712: a file that moves again under its retried request is deferred again, and imported once it holds still.+ // #6712: a file that moves again under its next request is passed over again, and imported once it holds still.for (const name of ['a', 'b', 'c']) writeFileSync(join(f.root, `${name}.md`), note(`${name} four.`));commit(f.root, 'version four');commits = 0; versions = 2;const twice = await performManagedSync(engine, { ...f.opts, noBulk: true });- expect(twice.status).toBe('synced');+ expect(twice).toMatchObject({ status: 'synced', pass: { outcome: 'synced' } });expect(twice.held ?? []).toEqual([]);- expect(twice.converted_from_failed).toHaveLength(2);expect(commits).toBe(2);+ expect(await newRequests()).toEqual([CHANGED, CHANGED, ['committed', null]]);expect((await engine.getPage('b', { sourceId: f.id }))?.compiled_truth).toContain('b round 2 change 1');- // A file that moves under every retry is held after DEFER_PER_ENTRY of them (never a fifth request for the same entry).+ // A file that moves under every request gets one per round: PASS_MAX_ROUNDS of them, then the pass stops not_converged.+ // It is not held, and the page keeps the last version it imported.for (const name of ['a', 'b', 'c']) writeFileSync(join(f.root, `${name}.md`), note(`${name} five.`));const pin5 = commit(f.root, 'version five');- commits = 0; versions = DEFER_PER_ENTRY + 1;+ commits = 0; versions = PASS_MAX_ROUNDS + 1;const restless = await performManagedSync(engine, { ...f.opts, noBulk: true });- expect(restless).toMatchObject({ status: 'synced', toCommit: pin5, held_count: 1, held: [{ path: 'b.md', code: 'worktree_dirty' }] });- expect(commits).toBe(DEFER_PER_ENTRY + 1);+ // Its last round read the commit before the one made under that round's request.+ expect(restless.toCommit).not.toBe(pin5);+ expect(restless).toMatchObject({ status: 'partial', reason: 'not_converged', toCommit: git(f.root, 'rev-parse', 'HEAD~1'), pass: { round: PASS_MAX_ROUNDS, outcome: 'resumable', stop_reason: 'not_converged', not_converged_streak: 1 } });+ expect(restless.held_count ?? 0).toBe(0);+ expect(commits).toBe(PASS_MAX_ROUNDS);+ expect(await newRequests()).toEqual(Array.from({ length: PASS_MAX_ROUNDS }, () => CHANGED));expect((await engine.getPage('b', { sourceId: f.id }))?.compiled_truth).toContain('b round 2 change 1');- // The next sync re-screens the hold (the blob at HEAD differs from the hold's) and imports the latest commit.+ expect((await engine.getPage('a', { sourceId: f.id }))?.compiled_truth).toContain('a five.');+ // Once the file holds still, the next sync imports the latest commit.+ versions = 0;const settled = await performManagedSync(engine, { ...f.opts, noBulk: true });- expect(settled.status).toBe('synced');- expect((await engine.getPage('b', { sourceId: f.id }))?.compiled_truth).toContain(`b round ${DEFER_PER_ENTRY + 1} change ${DEFER_PER_ENTRY}`);+ expect(settled).toMatchObject({ status: 'synced', modified: 1, pass: { outcome: 'synced' } });+ expect(await newRequests()).toEqual([['committed', null]]);+ expect((await engine.getPage('b', { sourceId: f.id }))?.compiled_truth).toContain(`b round ${PASS_MAX_ROUNDS + 1} change ${PASS_MAX_ROUNDS - 1}`);expect(await readManagedSyncFailures(engine, [f.id])).toEqual([]);+ const [row] = await engine.executeRaw<{ streak: number }>("SELECT (completed_keys->0->'obligations'->>'not_converged_streak')::int AS streak FROM op_checkpoints WHERE op='managed-sync-pass' AND completed_keys->0->>'source_id'=$1", [f.id]);+ expect(row?.streak).toBe(0);+ expect((await performManagedSync(engine, { ...f.opts, noBulk: true })).status).toBe('up_to_date');} finally { engine.executeRaw = executeRaw; await disposePersistenceConsumer(engine); }}}), 120_000);diff --git a/test/managed-sync-preparation-stalled-holds.test.ts b/test/managed-sync-preparation-stalled-holds.test.tsindex 5f3079844e..68fe45d781 100644--- a/test/managed-sync-preparation-stalled-holds.test.ts+++ b/test/managed-sync-preparation-stalled-holds.test.ts@@ -4,8 +4,12 @@* delete as a delete hold, a rename with its endpoints; the checkpoint never* holds; `sync.holds=fail` keeps blocking. The hold lands behind the narrowed* gate: an unrelated maintenance write on the same source no longer blocks- * it, a write on the same page still does, and a run killed before the cursor- * consumed the failure holds the entry at the start of the next run. Every+ * it, a write on the same page still does (#6712 PR 4b: the live pass does not+ * admit a file whose page has open work, so it mints no request until that+ * write settles), and once the cause is gone the next run imports the file+ * under a new request. A breaker trip stops the pass blocked; once the cause is+ * fixed the next pass imports every file and clears the holds. A retry-held+ * schedule survives a killed pass and is consumed by the pass's stamp. Every* surface routes the hold to writer status, then `sources retry-held` and the* same sync with its options, never to frontmatter repair. #6712: the hold is* transient, so every sync retries it until it has been held@@ -134,7 +138,6 @@ test('an import whose preparation stalls is held in the same run, the run finishexpect(await engine.getPage('notes/z', { sourceId: s.id })).not.toBeNull();const failed = await s.failedRequests();expect(failed).toEqual([expect.objectContaining({ error_code: 'preparation_stalled', state: 'failed', path: 'notes/stuck.md' })]);- expect(result.converted_from_failed).toEqual([failed[0]!.request_id]);expect(await s.ledger()).toEqual([]);const [hold] = result.held!;expect(hold).toMatchObject({ path: 'notes/stuck.md', code: 'preparation_stalled', stale: false, docs: 'docs/guides/write-refusals.md#preparation_stalled' });@@ -237,7 +240,7 @@ test('a stalled rename holds the destination with its origin; the hold gate lockexpect(await engine.getPage('notes/new', { sourceId: s.id })).not.toBeNull();}), 180_000);-test('sync.holds=fail keeps blocking with the typed receipt; the next run after holds are on converts it at its start (a kill before the cursor consumed the failure)', () => each(async engine => {+test('sync.holds=fail keeps blocking with the typed receipt; once the cause is gone and holds are on, the next run re-admits the file under a new request and imports it', () => each(async engine => {await engine.setConfig('sync.holds', 'fail');const s = await source(engine, { 'notes/a.md': note('A'), 'notes/stuck.md': note('Stuck') });stallPaths(engine, s.id, new Set(['notes/stuck.md']));@@ -247,14 +250,19 @@ test('sync.holds=fail keeps blocking with the typed receipt; the next run afterexpect(await s.holds()).toEqual([]);expect(await s.ledger()).toHaveLength(1);const [failed] = await s.failedRequests();- // The cursor is still pending on the failed receipt (as after a watchdog kill): the next run with holds on converts it before admitting anything.+ expect(failed).toMatchObject({ path: 'notes/stuck.md', error_code: 'preparation_stalled' });+ // The pass keeps no cursor pending on the failed receipt: the next run classifies the file again and, the stall gone, imports it.await engine.unsetConfig('sync.holds');installFaultHook(undefined);- const converted = await s.sync();- expect(converted).toMatchObject({ status: 'first_sync', held_count: 1, converted_from_failed: [failed!.request_id] });- expect(converted.held![0]).toMatchObject({ path: 'notes/stuck.md', code: 'preparation_stalled' });+ const resumed = await s.sync();+ expect(resumed).toMatchObject({ status: 'first_sync', pass: { outcome: 'synced' } });+ expect(resumed.held_count ?? 0).toBe(0);+ expect(await s.holds()).toEqual([]);expect(await engine.getPage('notes/a', { sourceId: s.id })).not.toBeNull();- expect(await s.failedRequests()).toHaveLength(1);+ expect(await engine.getPage('notes/stuck', { sourceId: s.id })).not.toBeNull();+ expect(await s.failedRequests()).toEqual([failed]);+ const [imports] = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM persistence_requests WHERE source_id=$1 AND intent->>'path'='notes/stuck.md' AND state='committed'", [s.id]);+ expect(imports!.n).toBe(1);}), 180_000);test('narrowed gate: an unfinished maintenance write on another page of the same source no longer blocks the hold; one on the same page still does', () => each(async engine => {@@ -273,22 +281,25 @@ test('narrowed gate: an unfinished maintenance write on another page of the sameexpect(result).toMatchObject({ status: 'synced', modified: 1, held_count: 1 });expect(result.held![0]).toMatchObject({ path: 'notes/stuck.md', code: 'preparation_stalled', stale: true });await unrelated.finish();- // Same page, by page id: the hold waits for it, and the run yields writer_pending within its wait budget.+ // Same page, by page id: the pass does not admit a file whose page has open work (in_flight), so it mints no request and+ // the hold keeps its receipt; the run yields writer_pending within its wait budget.installFaultHook(undefined);await retryHeld(engine, s.id);s.write('notes/stuck.md', note('Stuck v3')); commit(s.root, 'edit again');const samePage = await s.unfinishedWrite('notes/stuck', stuck);stallPaths(engine, s.id, new Set(['notes/stuck.md']));+ const receipts = (await s.failedRequests()).length;+ const receipt = (await s.holds())[0]!.meta.stall!.request_id;const pending = await s.sync();- expect(pending).toMatchObject({ status: 'partial', reason: 'writer_pending' });+ expect(pending).toMatchObject({ status: 'partial', reason: 'writer_pending', pass: { outcome: 'resumable', stop_reason: 'writer_pending' } });+ expect(await s.failedRequests()).toHaveLength(receipts);expect(await s.holds()).toHaveLength(1);- expect((await s.holds())[0]!.meta.stall!.request_id).not.toBe((await s.failedRequests()).at(-1)!.request_id);- // Once it settles, the next pass holds the entry from the same failed receipt without a new request.+ expect((await s.holds())[0]!.meta.stall!.request_id).toBe(receipt);+ // Once it settles, the next pass admits the file; it stalls again and is held under that new receipt.await samePage.finish();- const before = (await s.failedRequests()).length;const held = await s.sync();expect(held).toMatchObject({ status: 'synced', held_count: 1 });- expect((await s.failedRequests()).length).toBe(before);+ expect(await s.failedRequests()).toHaveLength(receipts + 1);expect((await s.holds())[0]!.meta.stall!.request_id).toBe((await s.failedRequests()).at(-1)!.request_id);// The same-path match also works for a write that names the file rather than the slug.installFaultHook(undefined);@@ -297,8 +308,11 @@ test('narrowed gate: an unfinished maintenance write on another page of the sameconst byPath = await s.unfinishedWrite('elsewhere/slug', null, 'notes/stuck.md');stallPaths(engine, s.id, new Set(['notes/stuck.md']));expect(await s.sync()).toMatchObject({ status: 'partial', reason: 'writer_pending' });+ expect(await s.failedRequests()).toHaveLength(receipts + 1);await byPath.finish();expect(await s.sync()).toMatchObject({ status: 'synced', held_count: 1 });+ expect(await s.failedRequests()).toHaveLength(receipts + 2);+ expect(await engine.getPage('notes/stuck', { sourceId: s.id })).toMatchObject({ compiled_truth: expect.stringContaining('Stuck.') });}), 240_000);test('bulk groups: a stalled first, middle or last member is held, the committed prefix stays, the rest is re-frozen and the run finishes in one invocation', () => each(async engine => {@@ -391,7 +405,7 @@ test('retry-held while the stall persists: the file is re-held once under the neexpect(await s.holds()).toHaveLength(1);}), 180_000);-test('a scheduled re-screen survives a run killed before it reached the file; a run killed after freezing it carries it in its manifest and leaves no stale schedule', () => each(async engine => {+test('a scheduled re-screen survives a run killed before it reached the file and a pass killed after its batch froze it (only the stamp consumes it); the next run imports the file and consumes the schedule', () => each(async engine => {const s = await source(engine, { 'notes/a.md': note('A'), 'notes/stuck.md': note('Stuck') });stallPaths(engine, s.id, new Set(['notes/stuck.md']));expect(await s.sync()).toMatchObject({ status: 'first_sync', held_count: 1 });@@ -402,17 +416,19 @@ test('a scheduled re-screen survives a run killed before it reached the file; aconst aborted = new AbortController(); aborted.abort();expect((await s.sync({ signal: aborted.signal })).status).toBe('partial');expect(await readGitHoldRetryPaths(engine, s.id, incarnation)).toEqual(['notes/stuck.md']);- // Killed right after the fresh cursor is saved: the manifest carries the entry and the schedule was consumed with the same save.+ // Killed right after the pass's batch froze the file, before admitting it: no request was minted, and the schedule stays,+ // because only the pass's stamp consumes it.+ const requests = (await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM persistence_requests WHERE source_id=$1 AND intent->>'path'='notes/stuck.md'", [s.id]))[0]!.n;let killed = 0;installFaultHook(async (point, detail) => { if (point === 'sync:mid_checkpoint' && detail.sourceId === s.id && killed++ === 0) throw new Error('injected kill after the cursor save'); });await expect(s.sync()).rejects.toThrow('injected kill');installFaultHook(undefined);expect(killed).toBe(1);- const [cursor] = await engine.executeRaw<{ c: { entries?: Array<{ path: string }>; total: number; index: number } }>(- "SELECT completed_keys->0 AS c FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [s.id]);- expect(cursor!.c).toMatchObject({ total: 1, index: 0 });- expect(await readGitHoldRetryPaths(engine, s.id, incarnation)).toEqual([]);- // The next run resumes that cursor and imports the file; nothing is left scheduled, so the run after it has nothing to do.+ expect(await engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [s.id])).toEqual([]);+ expect((await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM persistence_requests WHERE source_id=$1 AND intent->>'path'='notes/stuck.md'", [s.id]))[0]!.n).toBe(requests);+ expect(await readGitHoldRetryPaths(engine, s.id, incarnation)).toEqual(['notes/stuck.md']);+ expect(await engine.getPage('notes/stuck', { sourceId: s.id })).toBeNull();+ // The next run imports the file and its stamp consumes the schedule, so the run after it has nothing to do.expect(await s.sync()).toMatchObject({ status: 'synced', added: 1 });expect(await engine.getPage('notes/stuck', { sourceId: s.id })).not.toBeNull();expect(await s.holds()).toEqual([]);@@ -422,7 +438,7 @@ test('a scheduled re-screen survives a run killed before it reached the file; a// ── #6278 (B2): the systemic breaker ──-test('breaker: five consecutive stalled entries with no commit between stop the run with one systemic diagnostic; the next run re-freezes and re-screens instead of holding', () => each(async engine => {+test('breaker: five consecutive stalled entries with no commit between stop the run with one systemic diagnostic; once the cause is fixed the next run imports every file and clears the holds', () => each(async engine => {const files: Record<string, string> = {};for (let i = 0; i < 7; i++) files[`notes/s${i}.md`] = note(`S${i}`);const s = await source(engine, files);@@ -432,25 +448,21 @@ test('breaker: five consecutive stalled entries with no commit between stop thebreaker: { code: 'preparation_systemic', rule: 'consecutive', stalled: 5, consecutive: 5 } });expect(tripped.breaker!.fix.argv).toEqual(['gbrain', 'sources', 'writer', 'status', '--source', s.id, '--json']);expect(tripped.managedWrite?.write_error).toBe('preparation_stalled');- // Four holds were written before the trip; the fifth receipt is counted, not held, and the cursor still points at it.+ // Four holds were written before the trip; the fifth receipt is counted, not held, and the pass stopped blocked.expect((await s.holds()).map(hold => hold.path).sort()).toEqual(['notes/s0.md', 'notes/s1.md', 'notes/s2.md', 'notes/s3.md']);expect(await s.failedRequests()).toHaveLength(5);- const [cursor] = await engine.executeRaw<{ c: { index: number; breaker: { stalled: string[]; streak: number; tripped?: { rule: string } }; pending: { intent: { path: string } } } }>(- "SELECT completed_keys->0 AS c FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [s.id]);- expect(cursor!.c).toMatchObject({ index: 4, pending: { intent: { path: 'notes/s4.md' } }, breaker: { streak: 5, tripped: { rule: 'consecutive' } } });- expect(cursor!.c.breaker.stalled).toHaveLength(5);- // Cause fixed: the next run re-freezes the stopped entry under a fresh request (nothing held), finishes, and scheduled the run's four stalled holds- // for a re-screen. B7: that schedule is the same catch-up's work, so the pass yields (`writer_yield`) for the drain's next pass to discover and take it.+ expect(tripped.pass).toMatchObject({ outcome: 'blocked', stop_reason: 'blocked_by_failures' });+ for (let i = 0; i < 7; i++) expect(await engine.getPage(`notes/s${i}`, { sourceId: s.id })).toBeNull();+ // Cause fixed: the next pass re-screens the four transient holds and imports every file under fresh requests (nothing held,+ // no new failed receipt), and the run after it has nothing to do.installFaultHook(undefined);const resumed = await s.sync();- expect(resumed).toMatchObject({ status: 'partial', reason: 'writer_yield', added: 3, managedCursor: { index: 7, total: 7 } });- expect(resumed.converted_from_failed).toEqual([...cursor!.c.breaker.stalled]);+ expect(resumed).toMatchObject({ status: 'first_sync', added: 7, pass: { outcome: 'synced', candidates: 7 } });+ expect(resumed.held_count ?? 0).toBe(0);expect(await s.failedRequests()).toHaveLength(5);- expect(await engine.getPage('notes/s4', { sourceId: s.id })).not.toBeNull();- expect(await s.holds()).toHaveLength(4);- const rescreened = await s.sync();- expect(rescreened).toMatchObject({ status: 'synced', added: 4 });+ for (let i = 0; i < 7; i++) expect(await engine.getPage(`notes/s${i}`, { sourceId: s.id })).not.toBeNull();expect(await s.holds()).toEqual([]);+ expect(await s.sync()).toMatchObject({ status: 'up_to_date' });}), 240_000);test('breaker: the count rule trips above GBRAIN_SYNC_HOLD_ESCALATE_COUNT (greater than), and a committed page resets the consecutive streak', () => each(async engine => {diff --git a/test/persistence-managed-sync.test.ts b/test/persistence-managed-sync.test.tsindex dd1ce59a45..49a269514e 100644--- a/test/persistence-managed-sync.test.ts+++ b/test/persistence-managed-sync.test.ts@@ -29,6 +29,7 @@ import type { OperationContext } from '../src/core/ops/contract.ts';import { loadSyncFailures, syncFailuresPath } from '../src/core/sync-failure-ledger.ts';import { renderFactsTable } from '../src/core/facts-fence.ts';import { recordFactWithdrawal } from '../src/core/facts/withdrawal.ts';+import { readShadowLevel } from '../src/core/persistence/sync-pass.ts';const home = mkdtempSync(join(tmpdir(), 'gbrain-managed-sync-'));const engines: BrainEngine[] = [];@@ -212,7 +213,7 @@ test('a stale up-to-date run does not stamp a source re-added under a new incarn}}),120_000);-test('interrupted cursor resumes its pinned target before a newer HEAD and never advances early', async () => withEnv({ GBRAIN_HOME: home }, async () => {+test('an interrupted first pass resumes at the newer HEAD, never advances early and never re-imports what it imported', async () => withEnv({ GBRAIN_HOME: home }, async () => {for (const engine of engines) {const f = await fixture(engine, {'a.md':'First stable observation about engineering.\n','b.md':'Original second observation about engineering.\n'});const abort = new AbortController();@@ -220,12 +221,15 @@ test('interrupted cursor resumes its pinned target before a newer HEAD and neverexpect(first).toMatchObject({status:'partial',filesImported:1});expect((await engine.executeRaw<{last_commit:string|null}>('SELECT last_commit FROM sources WHERE id=$1',[f.id]))[0].last_commit).toBeNull();writeFileSync(join(f.root,'b.md'),'Newer second observation about engineering.\n'); const secondHead=commit(f.root,'new content after interruption');- // The checkpoint stays at the pin; #6340 imports b.md as HEAD commits it (a commit past the pin is not a local edit), and- // the pin..HEAD diff then re-imports the same bytes as a no-op.- const second = await performManagedSync(engine,{sourceId:f.id,noPull:true}); expect(second.toCommit).toBe(f.head); expect(second.status).toBe('first_sync');+ // #6712 PR 4b: the live pass pins HEAD on every run, so the resumed pass syncs to the newer commit; a.md, which the+ // interrupted pass imported, is matched (not a candidate) and b.md imports the bytes HEAD commits.+ const second = await performManagedSync(engine,{sourceId:f.id,noPull:true});+ expect(second.toCommit).toBe(secondHead); expect(second).toMatchObject({ status: 'first_sync', added: 1, pass: { kind: 'full', candidates: 1 } });expect((await engine.getPage('b',{sourceId:f.id}))?.compiled_truth).toContain('Newer second');+ expect((await engine.executeRaw<{last_commit:string|null}>('SELECT last_commit FROM sources WHERE id=$1',[f.id]))[0].last_commit).toBe(secondHead);+ expect((await engine.executeRaw<{slug:string}>("SELECT slug FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_import' ORDER BY sequence",[f.id])).map(row=>row.slug)).toEqual(['a','b']);const third = await performManagedSync(engine,{sourceId:f.id,noPull:true});- expect(third.toCommit).toBe(secondHead); expect(third).toMatchObject({ status: 'synced', modified: 0, waived: { imports: 1, deletes: 0 } });+ expect(third).toMatchObject({ status: 'up_to_date', toCommit: secondHead });expect((await engine.getPage('b',{sourceId:f.id}))?.compiled_truth).toContain('Newer second');}}),120_000);@@ -338,9 +342,10 @@ test('a write between batches cannot be overwritten by an older enumerated Git p}, TEST_WRITE_ATTRIBUTION)); }}});expect(first.status).toBe('partial'); await changed;- // #6340: the overtaken page is held, never overwritten, and the run finishes with the hold listed.+ // #6340: the overtaken page is held, never overwritten, and the run finishes with the hold listed. #6712 PR 4b: the pass+ // sees a database-only page at b.md's slug with no import record, so it holds file_drift (#6887), naming the repair.const resumed = await performManagedSync(engine,{sourceId:f.id,noPull:true});- expect(resumed).toMatchObject({ status: 'first_sync', held_count: 1, held: [{ path: 'b.md', code: 'concurrent_write' }] });+ expect(resumed).toMatchObject({ status: 'first_sync', held_count: 1, held: [{ path: 'b.md', code: 'file_drift' }] });expect((await engine.getPage('b',{sourceId:f.id}))?.compiled_truth).toBe('A concurrently accepted newer observation.');expect((await engine.executeRaw<{last_commit:string|null}>('SELECT last_commit FROM sources WHERE id=$1',[f.id]))[0].last_commit).toBe(f.head);expect(loadSyncFailures().filter(row => row.source_id === f.id)).toHaveLength(0);@@ -743,13 +748,20 @@ function onScreen(engine: BrainEngine, slug: string, hook: () => Promise<void>,}const note = (body: string) => `---\ntitle: Example\n---\n${body}\n`;-test('a mostly-waived manifest reports waived deletes, not deleted pages, and admits only the live delete', async () => withEnv({ GBRAIN_HOME: home }, async () => {+// #6712 PR 4b: the live pass classifies a soft-deleted page whose file is gone at the pinned commit as `untracked` (settled), so it is never a+// candidate, waived or admitted; only a live page whose file is gone is deleted.+test('soft-deleted pages whose files are gone are not pass candidates; only the live page is deleted', async () => withEnv({ GBRAIN_HOME: home }, async () => {for (const engine of engines) {const f = await deletedFixture(engine, { 'a.md': note('First'), 'b.md': note('Second'), 'c.md': note('Third'), 'd.md': note('Fourth') }, ['a', 'b', 'c']);+ const [{ sequence: seen }] = await engine.executeRaw<{ sequence: string }>('SELECT max(sequence)::text AS sequence FROM persistence_requests WHERE source_id=$1', [f.id]);const result = await performManagedSync(engine, { sourceId: f.id, ...WAIVER_OPTS });- expect(result).toMatchObject({ status: 'synced', deleted: 1, waived: { imports: 0, deletes: 3 }, filesImported: 4 });+ expect(result).toMatchObject({ status: 'synced', deleted: 1, waived: { imports: 0, deletes: 0 }, filesImported: 1, pass: { kind: 'full', candidates: 1 } });expect(result.legacySkips).toBeUndefined();- expect((await runRequests(engine, f.id, result.runId!)).map(row => [row.kind, row.slug, row.state]))+ const level = await readShadowLevel(engine, { sourceId: f.id });+ for (const path of ['a.md', 'b.md', 'c.md']) expect(level!.paths.find(entry => entry.path === path)?.result).toMatchObject({ cls: 'untracked', settled: true });+ for (const slug of ['a', 'b', 'c']) expect((await engine.readPageSnapshot(slug, { sourceId: f.id, includeDeleted: true }))?.page.deleted_at).toBeTruthy();+ expect((await engine.executeRaw<{ kind: string; slug: string; state: string }>("SELECT intent->>'kind' AS kind,slug,state FROM persistence_requests WHERE source_id=$1 AND sequence>$2::bigint ORDER BY sequence", [f.id, seen]))+ .map(row => [row.kind, row.slug, row.state])).toEqual([['managed_sync_delete', 'd', 'committed'], ['managed_sync_checkpoint', '__managed_sync_checkpoint__', 'committed']]);expect(await engine.getPage('d', { sourceId: f.id })).toBeNull();expect((await engine.executeRaw<{ last_commit: string }>('SELECT last_commit FROM sources WHERE id=$1', [f.id]))[0].last_commit).toBe(git(f.root, 'rev-parse', 'HEAD'));@@ -813,25 +825,26 @@ test.each(['restore', 'rename', 'database-only'] as const)('an unfinished %s req} finally { hold.resolve(); }}), 120_000);-test('revoked sync authority refuses before any waiver or cursor advance', async () => withEnv({ GBRAIN_HOME: home }, async () => {+// #6712 PR 4b: a soft-deleted page whose file is gone is no pass candidate (nothing is read or waived), so the revocation+// lands on a live page's delete: its screen re-reads the page, and the revoked grant refuses before any admission.+test('revoked sync authority refuses before any delete is admitted', async () => withEnv({ GBRAIN_HOME: home }, async () => {for (const engine of engines) {- const f = await deletedFixture(engine, { 'a.md': note('Deleted before the grant is revoked') }, ['a']);+ const f = await deletedFixture(engine, { 'a.md': note('Live until the grant is revoked') }, []);const clientId = `sync-client-${randomUUID()}`;await engine.executeRaw(`INSERT INTO oauth_clients(client_id,client_name,client_secret_hash,scope,source_id,allowed_operations)VALUES($1,'example-client','test-only','admin',$2,ARRAY['submit_job'])`, [clientId, f.id]);const ctx = { engine, remote: true, sourceId: f.id, auth: { clientId, principal: { kind: 'oauth_client', id: clientId }, scopes: ['admin'], sourceId: f.id, allowedOperations: ['submit_job'] } } as OperationContext;const accepted = await prepareRemoteJob(ctx, 'sync', { noPull: true });- const before = (await engine.readPageSnapshot('a', { sourceId: f.id, includeDeleted: true }))!.revision;- const proxy = onScreen(engine, 'a', async () => { await engine.executeRaw("UPDATE oauth_clients SET scope='read' WHERE client_id=$1", [clientId]); });+ const before = (await engine.readPageSnapshot('a', { sourceId: f.id }))!.revision;+ let revoked = false;+ const proxy = onScreen(engine, 'a', async () => { await engine.executeRaw("UPDATE oauth_clients SET scope='read' WHERE client_id=$1", [clientId]); revoked = true; });try {await expect(withSubmissionAuthority(accepted.authority, () => performManagedSync(proxy, accepted.data))).rejects.toMatchObject({ code: 'permission_denied' });+ expect(revoked).toBe(true);expect(await deleteRequests(engine, f.id)).toHaveLength(0);- const [cursor] = await engine.executeRaw<{ completed_keys: [{ index: number; pending?: { slug: string }; counts: { waived?: unknown } }] }>(- "SELECT completed_keys FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1 AND completed_keys->0->'authority'->'writer'->>'remote'='true'", [f.id]);- expect(cursor.completed_keys[0]).toMatchObject({ index: 0 });- expect(cursor.completed_keys[0].pending).toBeUndefined();- expect(cursor.completed_keys[0].counts.waived).toBeUndefined();- expect((await engine.readPageSnapshot('a', { sourceId: f.id, includeDeleted: true }))!.revision).toBe(before);+ const after = await engine.readPageSnapshot('a', { sourceId: f.id });+ expect(after?.page.deleted_at ?? null).toBeNull();+ expect(after!.revision).toBe(before);} finally { await disposePersistenceConsumer(proxy); }}}), 120_000);diff --git a/test/persistence-sync-failures.serial.test.ts b/test/persistence-sync-failures.serial.test.tsindex f5c94b4f0c..4b2e78f2e2 100644--- a/test/persistence-sync-failures.serial.test.ts+++ b/test/persistence-sync-failures.serial.test.ts@@ -16,6 +16,7 @@ import { loadSyncFailures, acknowledgeFailures, autoSkipFailures } from '../src/import { printSyncResult, runSync } from '../src/commands/sync.ts';import { buildSingleSyncJsonEnvelope } from '../src/core/sync-embed-backfill.ts';import { readManagedSyncFailures } from '../src/core/persistence/sync-failures.ts';+import { readGitSourceHolds } from '../src/core/persistence/sync-holds.ts';import { classifyManagedSyncOrphans, retireManagedSyncOrphan } from '../src/core/persistence/managed-sync-orphans.ts';import { checkSyncFailures } from '../src/commands/doctor/checks/sync-failures.ts';import { purgeStaleCheckpoints } from '../src/core/op-checkpoint.ts';@@ -58,8 +59,10 @@ beforeAll(async () => {for (const engine of engines) await engine.setConfig('sync.holds', 'fail');}, 120_000);-// #6712 PR 3 (L7): the next plain sync retries a recorded failure through the guarded rediscovery --retry-failed used to run.-test('withdrawal-conflicted sync resumes through guarded rediscovery on the next plain sync and cannot restore the fact', async () => withEnv(env, async () => {+// #6712 PR 4b: the withdrawal moves the page and the commit moves its file, so the live pass sees both sides moved (drift):+// it refuses file_drift under sync.holds=fail on every plain sync without a new request, holds it under the default policy,+// and never imports the file over the withdrawal.+test('a withdrawal that conflicts with a committed edit is drift: refused file_drift on every plain sync, held under the default policy, and the fact is never restored', async () => withEnv(env, async () => {for (const engine of engines) {const body = renderFactsTable([{ rowNum: 1, claim: 'synthetic sync withdrawal', visibility: 'world', kind: 'fact', confidence: 1,notability: 'medium', active: true }]);@@ -73,15 +76,27 @@ test('withdrawal-conflicted sync resumes through guarded rediscovery on the nextexpect((await performManagedSync(engine, options, { maxPages: 1, maxMs: 1000 })).status).toBe('partial');await disposePersistenceConsumer(engine);await engine.transaction(tx => withCoordinatedWrite(tx, [f.id], () => recordFactWithdrawal(tx, fact.id, f.id), TEST_WRITE_ATTRIBUTION));- await expect(performManagedSync(engine, options)).rejects.toMatchObject({ code: 'revision_conflict' });- expect(await readManagedSyncFailures(engine, [f.id])).toEqual([expect.objectContaining({ phase: 'freeze', path: 'z.md', code: 'revision_conflict' })]);- const repaired = await performManagedSync(engine, options);- expect(repaired.status).toBe('synced');- const current = (await engine.readPageSnapshot('z', { sourceId: f.id }))!;- expect(current.page.compiled_truth).toContain('Preserve this new prose.');- expect(parseFactsFence(current.page.compiled_truth).facts[0].forgotten).toBe(true);- expect(parseFactsFence(readFileSync(join(f.root, 'z.md'), 'utf8')).facts[0].forgotten).toBe(true);- expect(await readManagedSyncFailures(engine, [f.id])).toHaveLength(0);+ const requests = () => engine.executeRaw('SELECT id,state FROM persistence_requests WHERE source_id=$1 ORDER BY sequence', [f.id]);+ const before = await requests();+ const withdrawn = async () => {+ const current = (await engine.readPageSnapshot('z', { sourceId: f.id }))!;+ expect(current.page.compiled_truth).not.toContain('Preserve this new prose.');+ expect(parseFactsFence(current.page.compiled_truth).facts[0].forgotten).toBe(true);+ expect(readFileSync(join(f.root, 'z.md'), 'utf8')).toBe(`Preserve this new prose.\n${body}`);+ };+ await expect(performManagedSync(engine, options)).rejects.toMatchObject({ code: 'file_drift' });+ expect(await readManagedSyncFailures(engine, [f.id])).toEqual([expect.objectContaining({ phase: 'freeze', path: 'z.md', code: 'file_drift' })]);+ await expect(performManagedSync(engine, options)).rejects.toMatchObject({ code: 'file_drift' });+ expect(await requests()).toEqual(before);+ await withdrawn();+ await engine.unsetConfig('sync.holds');+ try {+ const held = await performManagedSync(engine, options);+ expect(held).toMatchObject({ status: 'synced', held: [{ path: 'z.md', code: 'file_drift' }] });+ expect(((await readGitSourceHolds(engine, { sourceIds: [f.id] }))[0]?.holds ?? []).map(hold => [hold.path, hold.code, hold.meta.side])).toEqual([['z.md', 'file_drift', 'both']]);+ await withdrawn();+ expect(await readManagedSyncFailures(engine, [f.id])).toHaveLength(0);+ } finally { await engine.setConfig('sync.holds', 'fail'); }}}), 120_000);afterAll(async () => {@@ -162,7 +177,9 @@ test.each(['lone_cr', 'trailing_spaces', 'bom', 'content'] as const)('fresh CRLF}}), 120_000);-test('CRLF checkout of a newer commit does not replace the stale blob pinned by an unfinished run', async () => withEnv(env, async () => {+// #6712 PR 4b: no unfinished run pins the stale blob any more. The next pass pins the newer commit, whose CRLF checkout is+// the same content, and imports it; the bytes the interrupted pass saw for z.md are never published.+test('CRLF checkout of a newer commit after an interrupted pass imports the newer commit; the stale blob the interrupted pass saw is never published', async () => withEnv(env, async () => {for (const engine of engines) {const f = await fixture(engine, { 'a.md': 'Original first observation.\n', 'z.md': 'Original last observation.\n' });const options = { sourceId: f.id, noPull: true };@@ -174,17 +191,14 @@ test('CRLF checkout of a newer commit does not replace the stale blob pinned byconst newer = 'Newer last observation.\n';writeFileSync(join(f.root, 'z.md'), newer); const newerHead = commit(f.root);writeFileSync(join(f.root, 'z.md'), newer.replace(/\n/g, '\r\n'));- const blocked = await performManagedSync(engine, options);- expect(blocked).toMatchObject({ status: 'blocked_by_failures', toCommit: pinned, failureCodes: [{ code: 'source_changed', count: 1 }] });- expect(blocked.managedWrite?.line_endings).toBeUndefined();- expect((await engine.getPage('z', { sourceId: f.id }))?.compiled_truth).toBe('Original last observation.');- expect(readFileSync(join(f.root, 'z.md'), 'utf8')).toBe(newer.replace(/\n/g, '\r\n'));- expect((await engine.executeRaw<{ last_commit: string }>('SELECT last_commit FROM sources WHERE id=$1', [f.id]))[0].last_commit).toBe(f.head);- // #6712 PR 3 (L7): the next plain sync retries the recorded failure as --retry-failed did: it rediscovers at HEAD, so the- // newer bytes import under their own commit and the pinned run never publishes them.- expect(await performManagedSync(engine, options)).toMatchObject({ status: 'synced', toCommit: newerHead });+ const resumed = await performManagedSync(engine, options);+ expect(resumed).toMatchObject({ status: 'synced', toCommit: newerHead, modified: 1, pass: { kind: 'full', outcome: 'synced', candidates: 1 } });+ expect(resumed.managedWrite?.line_endings).toBeUndefined();expect((await engine.getPage('z', { sourceId: f.id }))?.compiled_truth).toBe('Newer last observation.');+ expect(readFileSync(join(f.root, 'z.md'), 'utf8')).toBe(newer.replace(/\n/g, '\r\n'));expect((await engine.executeRaw<{ last_commit: string }>('SELECT last_commit FROM sources WHERE id=$1', [f.id]))[0].last_commit).toBe(newerHead);+ // z.md was imported by the first sync and by the newer commit, never at the stale pinned blob.+ expect(await engine.executeRaw("SELECT 1 FROM persistence_requests WHERE source_id=$1 AND intent->>'path'='z.md' AND intent->>'kind'='managed_sync_import'", [f.id])).toHaveLength(2);}}), 120_000);@@ -391,7 +405,9 @@ test('local single and all-source CLI JSON carry durable diagnostics and fail thtry {await runSync(engine, [...flags, '--source', f.id]);const single = JSON.parse(stdout.trim());- expect(single).toEqual(expect.objectContaining({ sync_status: 'blocked_by_failures', failures: [expect.objectContaining({ path: 'bad.md', source_id: f.id, request_id: expect.any(String), phase: 'receipt' })], counts_scope: 'run_cumulative' }));+ // #6712 PR 4b: the pass has no cursor run, so the envelope carries no run-cumulative counts (no run_id, no counts_scope).+ expect(single).toEqual(expect.objectContaining({ sync_status: 'blocked_by_failures', outcome: 'blocked', failures: [expect.objectContaining({ path: 'bad.md', source_id: f.id, request_id: expect.any(String), phase: 'receipt' })] }));+ expect(single).not.toHaveProperty('counts_scope');expect(currentExitCode()).toBe(1); expect(stderr).toContain(`After repair, run gbrain sync --source ${f.id} --no-pull --no-embed --no-extract --no-schema-pack to retry it under a new request.`);expect(stderr).not.toContain('--retry-failed'); expect(stderr).not.toContain('--skip-failed');stdout = ''; stderr = '';@@ -472,26 +488,38 @@ test('remote pending sync keeps its private receipt off the response while resumexpect(requests).toHaveLength(1);const serialized = JSON.stringify(pending);for (const privateValue of ['private-pending', 'A private observation', f.root, f.head, requests[0].request_id]) expect(serialized).not.toContain(privateValue);- expect(await run()).toEqual(pending);+ // #6712 PR 4b: each pass has its own pass_id; otherwise the second pending result is identical and resumes the same request.+ const again = await run();+ expect(again.pass!.pass_id).not.toBe(pending.pass!.pass_id);+ expect({ ...again, pass: { ...again.pass!, pass_id: '' } }).toEqual({ ...pending, pass: { ...pending.pass!, pass_id: '' } });expect(await engine.executeRaw('SELECT request_id FROM persistence_requests WHERE source_id=$1', [f.id])).toEqual(requests);- expect(await readManagedSyncFailures(engine, [f.id])).toHaveLength(1);+ // A pass that waits on its own queued request stops resumable (writer_pending) and records no failure; only a blocked stop does.+ expect(await readManagedSyncFailures(engine, [f.id])).toHaveLength(0);await lock!.release();- expect(await run()).toMatchObject({ status: 'first_sync', added: 1 });+ // The same request commits once the worktree is free, but a remote caller cannot stamp the converged checkpoint: the+ // pass stops for the brain host, with the page imported and last_commit untouched.+ expect(await run()).toMatchObject({ status: 'blocked_by_failures', reason: 'reconcile_host_required',+ pass: { kind: 'full', outcome: 'blocked', stop_reason: 'reconcile_host_required', candidates: 0 } });+ expect((await engine.getPage('private-pending', { sourceId: f.id }))?.compiled_truth).toContain('A private observation awaiting publication.');+ expect(await engine.executeRaw('SELECT request_id,state FROM persistence_requests WHERE source_id=$1', [f.id])).toEqual([{ request_id: requests[0].request_id, state: 'committed' }]);+ expect((await engine.executeRaw<{ last_commit: string | null }>('SELECT last_commit FROM sources WHERE id=$1', [f.id]))[0].last_commit).toBeNull();} finally { await lock?.release(); await disposePersistenceConsumer(engine); }}}), 120_000);-// #6712 PR 1 (L1): a lost manifest no longer blocks until an explicit idle retry. The next plain sync re-discovers against-// HEAD and finishes under a new run; the page the lost run already imported is prescreened (the old cursor is a skip-ahead).-test('missing manifest re-discovers against HEAD on the next sync; the page the lost run imported is prescreened', async () => withEnv(env, async () => {+// #6712 PR 4b: a non-company source keeps no manifest. An interrupted pass resumes on the next plain sync under a new pass,+// and the page it already imported is no longer a candidate (it is not imported twice).+test('an interrupted pass resumes on the next sync; the page it imported is not a candidate again', async () => withEnv(env, async () => {for (const engine of engines) {const f = await fixture(engine, { 'a.md': 'First committed observation.\n', 'b.md': 'Second committed observation.\n' });const options = { sourceId: f.id, noPull: true };const partial = await performManagedSync(engine, options, { maxPages: 1, maxMs: 1000 });- await engine.executeRaw("DELETE FROM op_checkpoints WHERE op='managed-sync-manifest' AND fingerprint=$1", [partial.runId]);+ expect(partial).toMatchObject({ status: 'partial', reason: 'writer_yield', filesImported: 1 });const resumed = await performManagedSync(engine, options);- expect(resumed.status).toBe('first_sync'); expect(resumed.runId).not.toBe(partial.runId);- expect(resumed.prescreened).toBe(1);+ expect(resumed).toMatchObject({ status: 'first_sync', pass: { kind: 'full', outcome: 'synced', candidates: 1 } });+ expect(resumed.pass!.pass_id).not.toBe(partial.pass!.pass_id);+ const imports = await engine.executeRaw<{ path: string }>("SELECT intent->>'path' AS path FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_import'", [f.id]);+ expect(imports.map(row => row.path).sort()).toEqual(['a.md', 'b.md']);expect(await readManagedSyncFailures(engine, [f.id])).toHaveLength(0);expect((await engine.executeRaw<{ last_commit: string | null }>('SELECT last_commit FROM sources WHERE id=$1', [f.id]))[0].last_commit).toBe(f.head);}diff --git a/test/persistence-sync-options.serial.test.ts b/test/persistence-sync-options.serial.test.tsindex 7d1655f028..dfcf648163 100644--- a/test/persistence-sync-options.serial.test.ts+++ b/test/persistence-sync-options.serial.test.ts@@ -132,27 +132,34 @@ check('noSchemaPack bypasses the configured pack and noExtract queues no optiona});});-// #6712 PR 1: a changed-option resume no longer refuses `invalid_params`; it inherits the cursor's opt-outs (reported in-// `inherited_options`) and still never rewrites accepted work.+// #6712 PR 1: a changed-option resume no longer refuses `invalid_params`; it inherits the interrupted run's opt-outs+// (reported in `inherited_options`) and still never rewrites accepted work. #6712 PR 4b: a non-company source runs the+// live pass, whose open episode carries the opt-outs (there is no cursor), so every import of the source keeps them.+const importIntents = (engine: BrainEngine, source: string) => engine.executeRaw<{ id: string; intent: SyncIntent }>(+ "SELECT id,intent FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_import' ORDER BY sequence", [source]);check('interrupted options survive resume and changed-option retries cannot rewrite accepted work', async engine => {const f = await fixture(engine, 2);const first = await performManagedSync(engine, f.opts, { maxPages: 1, maxMs: 1000 });expect(first).toMatchObject({ status: 'partial', filesImported: 1 });const requests = await engine.executeRaw('SELECT id,intent FROM persistence_requests WHERE source_id=$1', [f.id]);const resumed = await performManagedSync(engine, { ...f.opts, noEmbed: false, noSchemaPack: false, noExtract: false });- expect(resumed).toMatchObject({ status: 'first_sync', runId: first.runId, filesImported: 2 });+ expect(resumed).toMatchObject({ status: 'first_sync', filesImported: 1, pass: { kind: 'full' } });expect([...(resumed.inherited_options ?? [])].sort()).toEqual(['noEmbed', 'noExtract', 'noSchemaPack']);expect(await engine.executeRaw('SELECT id,intent FROM persistence_requests WHERE id=ANY($1::uuid[])', [requests.map(row => (row as { id: string }).id)])).toEqual(requests);- expect((await cursor(engine, f.id)).value.processingOptions).toEqual({ noEmbed: true, noSchemaPack: true, noExtract: true });+ const imports = await importIntents(engine, f.id);+ expect(imports).toHaveLength(2);+ for (const row of imports) expect(row.intent.processingOptions).toEqual({ noEmbed: true, noSchemaPack: true, noExtract: true });expect(await engine.executeRaw("SELECT kind FROM persistence_effects WHERE source_id=$1 AND kind IN ('embedding','facts-backstop')", [f.id])).toEqual([]);const retry = await fixture(engine, 2);- const interrupted = await performManagedSync(engine, retry.opts, { maxPages: 1, maxMs: 1000 });+ expect(await performManagedSync(engine, retry.opts, { maxPages: 1, maxMs: 1000 })).toMatchObject({ status: 'partial', filesImported: 1 });const original = await engine.executeRaw('SELECT id,intent FROM persistence_requests WHERE source_id=$1 ORDER BY id', [retry.id]);// Without a failure (the refusal used to record one) `--retry-failed` has nothing to rediscover: it resumes the- // interrupted run with the cursor's opt-outs.+ // interrupted pass with its opt-outs.const rediscovered = await performManagedSync(engine, { ...retry.opts, noSchemaPack: false, retryFailed: true });- expect(rediscovered).toMatchObject({ status: 'first_sync', runId: interrupted.runId, inherited_options: ['noSchemaPack'] });- expect((await cursor(engine, retry.id)).value.processingOptions.noSchemaPack).toBe(true);+ expect(rediscovered).toMatchObject({ status: 'first_sync', filesImported: 1, inherited_options: ['noSchemaPack'] });+ const retried = await importIntents(engine, retry.id);+ expect(retried).toHaveLength(2);+ for (const row of retried) expect(row.intent.processingOptions?.noSchemaPack).toBe(true);expect(await engine.executeRaw('SELECT id,intent FROM persistence_requests WHERE id=ANY($1::uuid[]) ORDER BY id', [original.map(row => row.id)])).toEqual(original);});@@ -305,10 +312,11 @@ test('fresh processes resume persisted pending opt-outs under the original requeexpect(resumed.before).toEqual(frozen!);expect(resumed.changedOptions).toEqual({ inherited: noEmbed ? ['noEmbed'] : [] });expect(resumed.afterChangedOptions).toEqual(resumed.after);- expect(resumed.result).toMatchObject({ status: 'first_sync', runId: pending!.runId, added: 1, filesImported: 1 });+ expect(resumed.result).toMatchObject({ status: 'first_sync', added: 1, filesImported: 1, pass: { outcome: 'synced' } });+ expect(frozen![0].intent.passId).toBe(pending!.pass!.pass_id);expect(resumed.after).toHaveLength(2);expect(resumed.after[0]).toEqual({ ...frozen![0], state: 'committed' });- expect(resumed.after[1]).toMatchObject({ state: 'committed', intent: { kind: 'managed_sync_checkpoint', runId: pending!.runId } });+ expect(resumed.after[1]).toMatchObject({ state: 'committed', intent: { kind: 'managed_sync_checkpoint', passId: resumed.result.pass.pass_id } });expect(resumed.beforeDrain).toEqual(noEmbed ? [] : [{ kind: 'embedding', state: 'queued' }]);expect(resumed.effects).toEqual(noEmbed ? [] : [{ kind: 'embedding', state: 'committed' }]);expect(resumed.networkCalls).toBe(0);@@ -667,7 +675,16 @@ for (const boundary of ['discovery', 'discovery-commit', 'foreground', 'freeze',else await outer;expect(observed).toBe(true);await disposePersistenceConsumer(engine);- expect(await syncState(engine, f.id)).toEqual(before!);+ const after = await syncState(engine, f.id);+ if (interrupted === 'explicit-abort' || interrupted === 'caller-abort') {+ // #6712 PR 4b: a caller abort returns partial and the live pass records that stop on its pass row (a lost lease or a+ // released context cannot write it, a job abort rejects); every other row is as the interrupt found it.+ const passRow = (row: Record<string, unknown>) => row.op === 'managed-sync-pass' && String(row.fingerprint).startsWith(`${f.id}:`);+ const [row] = after.checkpoints.filter(passRow) as Array<{ completed_keys: Array<{ telemetry: unknown }> }>;+ expect(row.completed_keys[0].telemetry).toMatchObject({ outcome: 'resumable', stop_reason: 'timeout', counts: { added: 0, modified: 0, deleted: 0 } });+ expect({ ...after, checkpoints: after.checkpoints.filter(row => !passRow(row)) })+ .toEqual({ ...before!, checkpoints: before!.checkpoints.filter(row => !passRow(row)) });+ } else expect(after).toEqual(before!);expect(readFileSync(join(f.root, 'records/example-0.md'), 'utf8')).toBe(body.replace('synthetic record', 'synthetic record 0'));console.info(`SYNC_ADMISSION_ABORT engine=${engine.kind} boundary=${boundary} case=${interrupted} requests_at_interrupt=0 state_unchanged=true`);} finally {@@ -774,17 +791,20 @@ for (const boundary of ['accepted-commit', 'receipt-banking'] as const) check(`cexpect(first).toMatchObject({ status: 'partial', reason: 'timeout', added: 1, filesImported: 1, bankedFiles: 1 });expect(observed).toBe(true);await disposePersistenceConsumer(engine);- const banked = await cursor(engine, f.id), before = await syncState(engine, f.id);- expect(banked.value).toMatchObject({ index: 1, counts: { added: 1 } });- expect(banked.value.pending).toBeUndefined();+ // #6712 PR 4b: the live pass has no cursor; its pass row banks the accepted page and records the stop.+ const before = await syncState(engine, f.id);+ const [passRow] = before.checkpoints.filter(row => row.op === 'managed-sync-pass' && String(row.fingerprint).startsWith(`${f.id}:`)) as Array<{ completed_keys: Array<{ telemetry: unknown }> }>;+ expect(passRow.completed_keys[0].telemetry).toMatchObject({ outcome: 'resumable', stop_reason: 'timeout', counts: { added: 1 } });expect(before.requests).toHaveLength(1);expect(before.requests[0]).toMatchObject({ state: 'committed' });expect(before.pages).toHaveLength(1);expect(before.effects).toEqual([]);expect(before.source).toEqual([{ last_commit: null, last_sync_at: null }]);engine.executeRaw = execute; engine.transaction = transaction;- expect(await performSync(engine, f.opts)).toMatchObject({ status: 'first_sync', runId: first.runId, added: 2, filesImported: 2 });+ // The next pass imports only the page the stopped pass never admitted.+ expect(await performSync(engine, f.opts)).toMatchObject({ status: 'first_sync', added: 1, filesImported: 1 });expect(await engine.executeRaw('SELECT * FROM persistence_requests WHERE id=$1', [before.requests[0].id])).toEqual(before.requests);+ expect(await engine.executeRaw("SELECT id FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_import'", [f.id])).toHaveLength(2);} finally { engine.executeRaw = execute; engine.transaction = transaction; }});@@ -797,22 +817,25 @@ check('cancelled waits retain the accepted pending receipt and resume it after oif (value && typeof value === 'object' && 'request_id' in value && 'source_id' in value && value.source_id === f.id) abort.abort();return value;} as BrainEngine['transaction'];- let requestId: string, runId: string;+ let requestId: string;try {const pending = await performSync(engine, { ...f.opts, signal: abort.signal });expect(abort.signal.aborted).toBe(true);expect(pending).toMatchObject({ status: 'partial', reason: 'timeout', filesImported: 0,managedWrite: { write_error: 'write_pending' } });expect(['queued', 'running', 'recovering']).toContain(pending.managedWrite!.write_request.state);- requestId = pending.managedWrite!.write_request.request_id; runId = pending.runId!;+ requestId = pending.managedWrite!.write_request.request_id;await disposePersistenceConsumer(engine);- const frozen = await cursor(engine, f.id), state = await syncState(engine, f.id);- expect(frozen.value.pending.requestId).toBe(requestId);+ // #6712 PR 4b: the live pass has no cursor; its pass row records the stop and the accepted request stays queued under its id.+ const state = await syncState(engine, f.id);+ const [passRow] = state.checkpoints.filter(row => row.op === 'managed-sync-pass' && String(row.fingerprint).startsWith(`${f.id}:`)) as Array<{ completed_keys: Array<{ telemetry: unknown }> }>;+ expect(passRow.completed_keys[0].telemetry).toMatchObject({ outcome: 'resumable', stop_reason: 'timeout' });expect(state.requests).toHaveLength(1);+ expect(state.requests[0]).toMatchObject({ request_id: requestId, state: 'queued' });expect(state.pages).toEqual([]); expect(state.effects).toEqual([]);expect(state.source).toEqual([{ last_commit: null, last_sync_at: null }]);} finally { engine.transaction = transaction; await disposePersistenceConsumer(engine); await lock?.release(); }- expect(await performSync(engine, f.opts)).toMatchObject({ status: 'first_sync', runId: runId!, added: 1 });+ expect(await performSync(engine, f.opts)).toMatchObject({ status: 'first_sync', added: 1, filesImported: 1, pass: { outcome: 'synced' } });expect(await engine.executeRaw("SELECT request_id,state FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_import'", [f.id])).toEqual([{ request_id: requestId!, state: 'committed' }]);});diff --git a/test/persistence-sync-origin-native.test.ts b/test/persistence-sync-origin-native.test.tsindex 2bcd2b596b..99c19d8545 100644--- a/test/persistence-sync-origin-native.test.ts+++ b/test/persistence-sync-origin-native.test.ts@@ -1,3 +1,14 @@+/**+ * Native sync-origin identity (separators, case, root spellings) and deletion provenance of managed sync.+ *+ * #6712 PR 4b: a non-company source syncs by the live pass, so these tests assert the pass where they used to assert the+ * cursor. Protects, for the pass: a remote sync keeps its accepted path and payload unchanged across root spellings and,+ * on a page no sync import recorded, asks for the brain host and writes nothing; deleting a filename no page claims is not+ * a candidate (no request, the live or tombstoned page unchanged; a tombstone whose file is still present is held+ * file_drift deleted/tombstone_edited); a committed or working-tree deletion of a page no sync import recorded is held+ * file_drift deleted/file_gone and the page stays live. The cursor-only tests (frozen manifests, resumed and legacy+ * cursors, hand-built cursor intents) still pin the cursor engine.+ */import { afterAll, beforeAll, expect, test } from 'bun:test';import { randomUUID } from 'node:crypto';import { execFileSync } from 'node:child_process';@@ -25,6 +36,7 @@ import { computeSyncDelta } from '../src/core/sync-delta.ts';import { sha256 } from '../src/core/persistence/digest.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import { prepareRemoteJob, withSubmissionAuthority } from '../src/core/minions/submission-authority.ts';+import { readGitSourceHolds } from '../src/core/persistence/sync-holds.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';import { interruptAfterSyncDiscovery } from './helpers/persistence-sync-interruption.ts';import { makeGitFixture } from './helpers/git-fixture.ts';@@ -154,7 +166,7 @@ check('native root spellings retain the registered owner and resume the same syn}});-check('native sync retains the exact accepted remote path and payload hash across root spellings', async engine => {+check('a native remote sync keeps the accepted path and payload across root spellings; on a page no sync import recorded it asks for the brain host and writes nothing', async engine => {const f = await fixture(engine);const clientId = `fixture-admin-${randomUUID()}`;await engine.executeRaw(`INSERT INTO oauth_clients(client_id,client_name,client_secret_hash,scope,source_id,allowed_operations)@@ -167,16 +179,12 @@ check('native sync retains the exact accepted remote path and payload hash acrosif (process.platform === 'win32' && process.env.GBRAIN_TEST_REQUIRE_CASE_INSENSITIVE === '1') {expect(remote.data.repoPath).not.toBe(binding.local_path);}+ // The page has no sync import record, so only the brain host can reconcile it: the remote pass stops before admitting anything.expect(await withSubmissionAuthority(remote.authority, () => performManagedSync(engine, remote.data as SyncOpts)))- .toMatchObject({ status: 'first_sync', added: 0, deleted: 0 });- const receipts = await engine.executeRaw<{ intent: { syncAuthority: { remoteData: unknown; remoteJob: unknown } }; state: string }>(- 'SELECT intent,state FROM persistence_requests WHERE source_id=$1', [f.id]);- expect(receipts.length).toBeGreaterThan(0);- for (const receipt of receipts) {- expect(receipt.state).toBe('committed');- expect(receipt.intent.syncAuthority.remoteData).toEqual(accepted.data);- expect(receipt.intent.syncAuthority.remoteJob).toEqual(accepted.authority);- }+ .toMatchObject({ status: 'blocked_by_failures', reason: 'reconcile_host_required', added: 0, deleted: 0,+ pass: { kind: 'full', outcome: 'blocked', stop_reason: 'reconcile_host_required' } });+ expect(await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1', [f.id])).toEqual([]);+ expect(await engine.readPageSnapshot(f.slug, { sourceId: f.id })).toEqual(f.snapshot);expect(remote).toEqual(accepted);expect(await getWorktreeBinding(engine, f.id)).toEqual(binding);expect((await engine.getPage(f.slug, { sourceId: f.id }))?.id).toBe(f.snapshot.page.id);@@ -288,7 +296,7 @@ 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 => {+check('deleting an unowned filename is not a pass candidate and 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,@@ -305,14 +313,18 @@ check('deleting an unowned filename preserves the live or tombstoned foreign-oriconst 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 });+ const result = await performManagedSync(engine, opts);+ expect(result).toMatchObject({ status: 'synced', deleted: 0, filesImported: 0, toCommit: target, pass: { kind: 'full', outcome: 'synced', candidates: 0 } });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' } });+ // No page claims notes/example.md, so the pass has nothing to delete: the checkpoint is its only request.+ const requests = await engine.executeRaw<{ kind: string; state: string }>("SELECT intent->>'kind' AS kind,state FROM persistence_requests WHERE source_id=$1 ORDER BY sequence", [f.id]);+ expect(requests).toEqual([{ kind: 'managed_sync_checkpoint', state: 'committed' }]);expect((await engine.executeRaw('SELECT last_commit FROM sources WHERE id=$1', [f.id]))[0].last_commit).toBe(target);+ // A tombstone whose recorded file is still in the tree is a deletion the file never saw: held, never revived.+ const holds = ((await readGitSourceHolds(engine, { sourceIds: [f.id] }))[0]?.holds ?? []).map(hold => ({ path: hold.path, code: hold.code, side: hold.meta.side, state: hold.meta.state }));+ expect(holds).toEqual(deleted ? [{ path: 'notes/recorded.md', code: 'file_drift', side: 'deleted', state: 'tombstone_edited' }] : []);}});@@ -354,7 +366,7 @@ check('unowned deletion rechecks absent ownership and file bytes at publication'}});-check('a genuine committed Git deletion commits one deletion and the exact checkpoint', async engine => {+check('a committed Git deletion of a page no sync import recorded is held file_drift (deleted, file_gone): the page stays live and only the checkpoint commits', 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]), TEST_WRITE_ATTRIBUTION));const history = await engine.getVersions(f.slug, { sourceId: f.id });@@ -367,21 +379,21 @@ check('a genuine committed Git deletion commits one deletion and the exact checkexpect(await engine.readPageSnapshot(f.slug, { sourceId: f.id })).toEqual(f.snapshot);expect(await engine.getVersions(f.slug, { sourceId: f.id })).toEqual(history);expect(await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1', [f.id])).toEqual([]);- expect(await performManagedSync(engine, { ...f.opts, full: false })).toMatchObject({ status: 'synced', deleted: 1, filesImported: 1, fromCommit: f.head, toCommit: target });- const deleted = (await engine.readPageSnapshot(f.slug, { sourceId: f.id, includeDeleted: true }))!;- expect(deleted.page.id).toBe(f.snapshot.page.id);- expect(deleted.page.deleted_at).not.toBeNull();- expect(deleted.revision).not.toBe(f.snapshot.revision);- expect(await engine.getVersions(f.slug, { sourceId: f.id })).toHaveLength(history.length + 1);+ // The page was imported outside sync (no import record), so nothing proves the database still holds the deleted file's bytes.+ const result = await performManagedSync(engine, { ...f.opts, full: false });+ expect(result).toMatchObject({ status: 'synced', deleted: 0, filesImported: 0, fromCommit: f.head, toCommit: target, pass: { kind: 'full', outcome: 'synced', candidates: 0 } });+ expect(result.held?.map(item => [item.path, item.code])).toEqual([['notes/example.md', 'file_drift']]);+ const [hold] = (await readGitSourceHolds(engine, { sourceIds: [f.id] }))[0]!.holds;+ expect(hold!.meta).toMatchObject({ side: 'deleted', state: 'file_gone' });+ expect(await engine.readPageSnapshot(f.slug, { sourceId: f.id })).toEqual(f.snapshot);+ expect(await engine.getVersions(f.slug, { sourceId: f.id })).toEqual(history);const requests = await engine.executeRaw<{ intent: SyncIntent; state: string }>('SELECT intent,state FROM persistence_requests WHERE source_id=$1 ORDER BY sequence', [f.id]);- expect(requests).toHaveLength(2);- expect(requests.every(row => row.state === 'committed')).toBe(true);- expect(requests[0].intent).toMatchObject({ kind: 'managed_sync_delete', working: false, target, from: f.head });- expect(requests[1].intent.kind).toBe('managed_sync_checkpoint');+ expect(requests.map(row => [row.intent.kind, row.state])).toEqual([['managed_sync_checkpoint', 'committed']]);expect((await engine.executeRaw('SELECT last_commit FROM sources WHERE id=$1', [f.id]))[0].last_commit).toBe(target);expect(await performManagedSync(engine, { ...f.opts, full: false })).toMatchObject({ status: 'up_to_date', deleted: 0 });- expect(await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1', [f.id])).toHaveLength(2);- expect(await engine.getVersions(f.slug, { sourceId: f.id })).toHaveLength(history.length + 1);+ expect(await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1', [f.id])).toHaveLength(1);+ expect(await engine.readPageSnapshot(f.slug, { sourceId: f.id })).toEqual(f.snapshot);+ expect(await engine.getVersions(f.slug, { sourceId: f.id })).toEqual(history);});check('old manifest reuse refuses a present-file deletion before admitting any request', async engine => {@@ -413,14 +425,19 @@ check('already-admitted legacy deletion fails under its original ID and the nextexpect(readFileSync(join(f.root, 'notes/example.md'), 'utf8')).toBe(content);});-check('explicit working-tree deletion remains valid even when the pinned Git target contains the file', async engine => {+check('an explicit working-tree deletion of a page no sync import recorded is held file_drift (deleted, file_gone), even when the pinned Git target contains the file', async engine => {const f = await fixture(engine);unlinkSync(join(f.root, 'notes/example.md'));const result = await performManagedSync(engine, { ...f.opts, workingTree: true });- expect(result).toMatchObject({ status: 'first_sync', deleted: 1 });- expect(await engine.getPage(f.slug, { sourceId: f.id })).toBeNull();- const [request] = await engine.executeRaw<{ intent: SyncIntent }>("SELECT intent FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_delete'", [f.id]);- expect(request.intent.working).toBe(true);+ // --working-tree differs from the configured mode, so the pass converges selection-scoped and stamps no checkpoint.+ expect(result).toMatchObject({ status: 'synced', reason: 'selection_scoped', deleted: 0, pass: { kind: 'full', outcome: 'synced', candidates: 0 } });+ expect(result.held?.map(item => [item.path, item.code])).toEqual([['notes/example.md', 'file_drift']]);+ const [hold] = (await readGitSourceHolds(engine, { sourceIds: [f.id] }))[0]!.holds;+ expect(hold!.meta).toMatchObject({ side: 'deleted', state: 'file_gone' });+ expect((await engine.getPage(f.slug, { sourceId: f.id }))?.id).toBe(f.snapshot.page.id);+ expect(await engine.readPageSnapshot(f.slug, { sourceId: f.id })).toEqual(f.snapshot);+ expect(await engine.executeRaw("SELECT intent FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_delete'", [f.id])).toEqual([]);+ expect((await engine.executeRaw('SELECT last_commit FROM sources WHERE id=$1', [f.id]))[0].last_commit).toBeNull();});check('native case aliases refuse rather than merge distinct origins', async engine => {diff --git a/test/repair-fences-during-catchup.test.ts b/test/repair-fences-during-catchup.test.tsindex ff2a71481a..40282bac4b 100644--- a/test/repair-fences-during-catchup.test.ts+++ b/test/repair-fences-during-catchup.test.ts@@ -2,18 +2,21 @@* #6278 R2: `gbrain repair fences --apply` during a live managed catch-up.** Protects: a source whose sync is running is no longer skipped as a whole.- * While a sync member is being prepared, the candidate it names and a- * candidate still ahead in the run's frozen manifest are `sync_in_progress`- * and nothing is written to them; between two entries of the same run a held- * candidate (the hold's bytes unchanged, so not in the manifest) and an- * unsynced working-tree candidate are repaired, while the far-ahead one still- * waits; the sync then finishes with no `source_changed` refusal and imports- * the entry it had ahead. A plan approved before a sync started is not+ * #6712 PR 4b: a non-company source syncs by the live pass, which keeps no+ * frozen manifest, so only its open requests are busy (design v3.2 §3.7).+ * While a pass member is being prepared, the candidate it names is+ * `sync_in_progress` and nothing is written to it, while a candidate the pass+ * has not frozen yet is repairable; between two of the pass's entries the+ * held candidate (the hold's bytes unchanged), an unsynced working-tree+ * candidate and the candidate still ahead in the pass are all repaired; the+ * pass then finishes synced with no failed request and the ahead page+ * imported with its repaired fence. A plan approved before a sync started is not* applied to a candidate that sync froze in between (`sync_in_progress` at* apply), and the entry imports once the sync reaches it.* Fails when: the blanket skip comes back (nothing repaired during a sync),- * a manifest-ahead or in-flight candidate is written (the sync would refuse- * it on its raw hash), or a held path counts as busy.+ * an in-flight candidate is written (the sync would refuse it on its raw+ * hash), a held path counts as busy, or the pass refuses a candidate a repair+ * wrote before the pass froze it.* Seams: installFaultHook (`consumer:preparing`, `sync:mid_checkpoint`) pauses* the real sync; __setChatTransportForTests answers the model tier.* Postgres arm: test/e2e/repair-fences-during-catchup-postgres.test.ts.@@ -94,7 +97,8 @@ async function managed(engine: BrainEngine, files: Record<string, string>) {"SELECT request_id::text AS request_id, error_code, slug FROM persistence_requests WHERE source_id=$1 AND state IN ('failed','conflict')", [id]);const cursor = async () => (await engine.executeRaw<{ index: string | null; run_id: string | null }>(`SELECT completed_keys->0->>'index' AS index, completed_keys->0->>'runId' AS run_idFROM op_checkpoints WHERE op='managed-sync' AND COALESCE(completed_keys->0->>'done','false')<>'true' AND completed_keys->0->>'sourceId'=$1`, [id]))[0] ?? null;- return { id, root, write, read: (path: string) => readFileSync(join(root, path), 'utf8'), sync, holds, run, failed, cursor };+ const requests = (path: string) => engine.executeRaw<{ state: string }>("SELECT state FROM persistence_requests WHERE source_id=$1 AND intent->>'path'=$2 ORDER BY sequence", [id, path]);+ return { id, root, write, read: (path: string) => readFileSync(join(root, path), 'utf8'), sync, holds, run, failed, cursor, requests };}/** A gate the fault hook parks the sync at: `reached` resolves when it is hit, `release()` lets the sync go on. */@@ -116,14 +120,14 @@ async function each(run: (engine: BrainEngine) => Promise<void>) {});}-test('during a live catch-up: the admitted and the far-ahead candidates wait, the held and the working-tree candidates repair, and the sync finishes clean', () => each(async engine => {+test('during a live pass: only the admitted candidate waits; the held, the working-tree and the not-yet-frozen candidates repair, and the sync finishes clean', () => each(async engine => {const s = await managed(engine, { 'people/held.md': md('Held', noHeader()), 'notes/plain.md': md('Plain', 'Nothing here.\n') });expect((await s.sync()).held_count).toBe(1);- // Commit 2: the entry the sync admits first (a Tier 1 defect, so it is a census file candidate until it imports) and one far behind it.+ // Commit 2: the entry the pass admits first (a Tier 1 defect, so it is a census file candidate until it imports) and one behind it.s.write('people/aa-admitted.md', md('Admitted', fixable('Synthetic admitted partnership')));s.write('people/zz-ahead.md', md('Ahead', fixable('Synthetic ahead partnership')));commit(s.root, 'two fences');- // Never synced, never committed: a working-tree candidate outside the manifest.+ // Never synced, never committed: a working-tree candidate the committed-mode pass never imports.s.write('people/later.md', md('Later', fixable('Synthetic later partnership')));let calls = 0;__setChatTransportForTests(async () => { calls++; return answer(CLAIM); });@@ -136,41 +140,41 @@ test('during a live catch-up: the admitted and the far-ahead candidates wait, thif (req?.path !== 'people/aa-admitted.md') return;pausedPreparing = true; preparing.reached(); await preparing.released;}- if (point === 'sync:mid_checkpoint' && pausedPreparing && !pausedBetween && (await s.cursor())?.index === '1') {+ if (point === 'sync:mid_checkpoint' && pausedPreparing && !pausedBetween && (await s.requests('people/aa-admitted.md')).some(row => row.state === 'committed')) {pausedBetween = true; between.reached(); await between.released;}});const sync = s.sync();await preparing.hit;- // Entry 0 is admitted and preparing; entry 1 is frozen in the manifest and not admitted.+ // The pass's first entry is admitted and preparing; the one behind it is not frozen yet, and no cursor row exists.const [running] = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM persistence_requests WHERE source_id=$1 AND state='running'", [s.id]);expect(running!.n).toBe(1);+ expect(await s.cursor()).toBeNull();const busyPreview = await s.run({ only: ['people/aa-admitted.md', 'people/zz-ahead.md'] });- expect(classes(busyPreview, s.id)).toEqual({ 'people/aa-admitted.md': 'sync_in_progress', 'people/zz-ahead.md': 'sync_in_progress' });- expect(busyPreview.affected).toBe(0);- const busyApply = await s.run({ apply: true, only: ['people/aa-admitted.md', 'people/zz-ahead.md'] });- expect(busyApply).toMatchObject({ applied: 0, remaining: { sync_in_progress: 2 } });+ expect(classes(busyPreview, s.id)).toEqual({ 'people/aa-admitted.md': 'sync_in_progress', 'people/zz-ahead.md': 'deterministic' });+ const busyApply = await s.run({ apply: true, only: ['people/aa-admitted.md'] });+ expect(busyApply).toMatchObject({ applied: 0, remaining: { sync_in_progress: 1 } });expect(s.read('people/aa-admitted.md')).toBe(md('Admitted', fixable('Synthetic admitted partnership')));expect(s.read('people/zz-ahead.md')).toBe(md('Ahead', fixable('Synthetic ahead partnership')));preparing.release();await between.hit;- // Entry 0 committed, entry 1 still ahead: the held and the working-tree candidates repair now; the far-ahead one waits.+ // The first entry committed, the second not frozen yet: the held, the working-tree and the ahead candidates all repair now.expect(await s.failed()).toEqual([]);const preview = await s.run();- expect(classes(preview, s.id)).toEqual({ 'people/held.md': 'llm', 'people/later.md': 'deterministic', 'people/zz-ahead.md': 'sync_in_progress' });+ expect(classes(preview, s.id)).toEqual({ 'people/held.md': 'llm', 'people/later.md': 'deterministic', 'people/zz-ahead.md': 'deterministic' });const applied = await s.run({ apply: true });- expect(applied).toMatchObject({ repaired: 2, remaining: { sync_in_progress: 1 } });+ expect(applied).toMatchObject({ repaired: 3, remaining: {} });expect(calls).toBe(1);expect(s.read('people/held.md')).toContain(FH.split('\n')[0]!);expect(s.read('people/later.md')).toContain(FBE);- expect(s.read('people/zz-ahead.md')).toBe(md('Ahead', fixable('Synthetic ahead partnership')));+ expect(s.read('people/zz-ahead.md')).toContain(FBE);expect(await s.holds()).toEqual([]);between.release();const result = await sync;- expect(result.status).not.toBe('error');+ expect(result).toMatchObject({ status: 'synced', pass: { kind: 'full', outcome: 'synced', candidates: 2, remaining: 0 } });expect(await s.failed()).toEqual([]);expect(await s.cursor()).toBeNull();- // The far-ahead entry imported on the bytes the sync froze, and the import normalized its fence.+ // The ahead entry is imported with its repaired fence, and nothing refused it.expect(await engine.readPageSnapshot('people/zz-ahead', { sourceId: s.id })).not.toBeNull();expect(s.read('people/zz-ahead.md')).toContain(FBE);expect((await s.run()).affected).toBe(0);diff --git a/test/sync-delegated-options-6696.serial.test.ts b/test/sync-delegated-options-6696.serial.test.tsindex aa8cbf0eba..133a63bae9 100644--- a/test/sync-delegated-options-6696.serial.test.ts+++ b/test/sync-delegated-options-6696.serial.test.ts@@ -21,6 +21,9 @@* Existing coverage (`serve-sync-handoff.serial.test.ts`) delegates only onto* fresh sources, so a resume never crossed the wire there.*+ * #6712 PR 4b: a non-company source runs the live pass, which keeps no cursor; the+ * opt-outs a flagless run inherits live on the pass row's open episode.+ ** Serial: the runner is a module singleton and the tests bind local sockets.*/@@ -78,8 +81,9 @@ async function partialCursor(id: string, opts: Partial<SyncOpts>): Promise<void>embedded.length = 0;}-const storedOptions = async (id: string) => (await engine.executeRaw<{ options: unknown }>(- "SELECT completed_keys->0->'processingOptions' AS options FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [id]))[0]?.options;+/** The opt-outs of the pass row's open episode (what a flagless pass inherits), or null when no episode is open. */+const episodeOptions = async (id: string) => (await engine.executeRaw<{ inherited: { noEmbed: boolean; noExtract: boolean; noSchemaPack: boolean } | null }>(+ "SELECT completed_keys->0->'obligations'->'episode'->'inherited' AS inherited FROM op_checkpoints WHERE op='managed-sync-pass' AND completed_keys->0->>'source_id'=$1", [id]))[0]?.inherited ?? null;/** Embedding effects queued for this source's page requests (any state): zero means no provider call can follow. */const embeddingEffects = async (id: string) => (await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM persistence_effects WHERE source_id=$1 AND kind='embedding'", [id]))[0]!.n;@@ -165,7 +169,7 @@ describe('the client builders send no explicit-processing list (#6712 PR 1)', ()test('a flagless delegated run adopts the unfinished cursor\'s stored options (noEmbed=true) instead of refusing', async () => withEnv(env, async () => {const f = await fixture(3);await partialCursor(f.id, { noEmbed: true, noExtract: true });- expect(await storedOptions(f.id)).toEqual({ noEmbed: true, noExtract: true, noSchemaPack: false });+ expect(await episodeOptions(f.id)).toMatchObject({ noEmbed: true, noExtract: true, noSchemaPack: false });const sock = await serveSocket();const delegated = await quiet(() => maybeDelegateManagedSyncToServe(engine, ['--source', f.id, '--no-pull'],{ sourceId: f.id, noPull: true, drain: true } as SyncOpts, deps(sock)).catch((error: unknown) => error));@@ -193,7 +197,7 @@ describe('the serve infers a missing list from an older CLI\'s true-valued flagstest('an older CLI\'s --no-embed (noEmbed: true, no list) never resumes a noEmbed=false cursor into embedding', async () => withEnv(env, async () => {const f = await fixture(3);await partialCursor(f.id, {});- expect(await storedOptions(f.id)).toEqual({ noEmbed: false, noExtract: false, noSchemaPack: false });+ expect(await episodeOptions(f.id)).toBeNull();const before = await embeddingEffects(f.id);const local = await registerLocalWriter(engine, 'cli');const start = await startDelegatedSync(engine, { sourceId: f.id, noPull: true, noEmbed: true, timeoutSeconds: 120 }, randomUUID(),@@ -202,7 +206,8 @@ describe('the serve infers a missing list from an older CLI\'s true-valued flagsconst done = await quiet(() => waitTerminal(start.jobId!));expect(done.jobErrorEnvelope).toBeUndefined();expect(done).toMatchObject({ state: 'done', result: { status: 'first_sync' } });- expect(await storedOptions(f.id)).toEqual({ noEmbed: true, noExtract: false, noSchemaPack: false });+ // The --no-embed pass converged, so the opt-out episode it opened is closed.+ expect(await episodeOptions(f.id)).toBeNull();await drainEffects();expect(await embeddingEffects(f.id)).toBe(before);expect(embedded).toEqual([]);@@ -213,7 +218,7 @@ describe('a runtime embedding deferral is never lifted by cursor adoption', () =test('delegated: the deferral crosses the wire; a cursor storing noEmbed=false embeds nothing in this run', async () => withEnv(env, async () => {const f = await fixture(3);await partialCursor(f.id, {});- expect(await storedOptions(f.id)).toEqual({ noEmbed: false, noExtract: false, noSchemaPack: false });+ expect(await episodeOptions(f.id)).toBeNull();const before = await embeddingEffects(f.id);const sock = await serveSocket();const delegated = await quiet(() => maybeDelegateManagedSyncToServe(engine, ['--source', f.id, '--no-pull'],@@ -222,8 +227,8 @@ describe('a runtime embedding deferral is never lifted by cursor adoption', () =await drainEffects();expect(await embeddingEffects(f.id)).toBe(before);expect(embedded).toEqual([]);- // The cursor's own options are untouched: the deferral is a property of this run, not of the cursor.- expect(await engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1 AND completed_keys->0->'processingOptions'->>'noEmbed'='false'", [f.id])).toHaveLength(1);+ // No episode keeps the deferral: it is a property of this run, not of the source.+ expect(await episodeOptions(f.id)).toBeNull();}), 180_000);test('in-process CLI: the cost gate auto-defers (non-TTY, floor $0); adoption of noEmbed=false still makes zero embedding calls', async () => withEnv(env, async () => {diff --git a/test/sync-drain-finish-tail.test.ts b/test/sync-drain-finish-tail.test.tsindex 753074564e..a2869115ae 100644--- a/test/sync-drain-finish-tail.test.ts+++ b/test/sync-drain-finish-tail.test.ts@@ -4,6 +4,9 @@* as `no_admission`. L5 moves it out: the checkpoint's own transaction records the tail as owed, the pass returns at the* checkpoint commit, and the tail runs after the drain lease is released, bounded, with a degraded notice when it fails or* is cut short. These tests pinned the C4 behavior (the `finish` step and window); they now assert the L5 behavior.+ * #6712 PR 4b: a non-company source runs the live pass, whose stamp records the tail under the pass id (`recordPassTail`);+ * an owed tail keeps the next tick from being idle, so that sync is a full pass with no candidates that stamps (synced)+ * and runs the tail, where the cursor engine answered up_to_date. The tail obligations here are recorded the pass's way.*/import { afterAll, beforeAll, describe, expect, test } from 'bun:test';import { randomUUID } from 'node:crypto';@@ -94,13 +97,18 @@ test('the tail runs after the drain lease is released: a second sync takes the lawait Promise.race([inTail, sleep(60_000)]);expect(slowed).toBe(true);// On the base the first run still held the lease here (its link tail ran inside the pass), so this threw SyncLockBusyError.+ // The first run's tail is still owed, so this tick is a full pass with nothing to import that stamps.const second = await performSync(engine, { sourceId: id, noPull: true, noEmbed: true, drain: true });- expect(second.status).toBe('up_to_date');+ expect(second).toMatchObject({ status: 'synced', added: 0, modified: 0, deleted: 0, pass: { kind: 'full', candidates: 0 } });+ // The second run's tail runs both owed obligations and derives the two pages while the first one's tail waits.+ expect(second.tail).toMatchObject({ status: 'done', runs: 2 });+ expect(second.links?.pages).toBe(2);release();const result = await first;expect(result.drain).toMatchObject({ outcome: 'synced', written: 2, remaining: 0 });expect(result.status).toBe('first_sync');expect(result.tail).toMatchObject({ status: 'done', runs: 1 });+ // A sync's own imports are re-derived regardless of their watermark (links-maintenance.ts), the second run's pass included.expect(result.links?.pages).toBe(2);expect(await stale(id)).toBe(0);expect(await readSyncTail(engine, id)).toBeNull();@@ -124,9 +132,10 @@ test('a tail that never ran after its checkpoint committed stays owed and the neconst owed = await readSyncTail(engine, id);expect(owed?.map(item => ({ changed: item.changed, extract: item.extract }))).toEqual([{ changed: 2, extract: true }]);expect(await stale(id)).toBe(2);+ // The owed tail keeps this tick from being idle: a full pass with nothing to import stamps and runs the tail.const second = await performSync(engine, { sourceId: id, noPull: true, noEmbed: true, drain: true });- expect(second.status).toBe('up_to_date');- expect(second.tail).toMatchObject({ status: 'done', runs: 1, statistics: 'refreshed' });+ expect(second).toMatchObject({ status: 'synced', added: 0, modified: 0, deleted: 0, pass: { kind: 'full', candidates: 0 } });+ expect(second.tail).toMatchObject({ status: 'done', runs: 2, statistics: 'refreshed' });expect(second.tail?.notice).toBeUndefined();expect(await stale(id)).toBe(0);expect(await readSyncTail(engine, id)).toBeNull();@@ -140,10 +149,9 @@ test('a --no-extract run owes statistics only, and a run past its deadline deferexpect(result.links).toBeUndefined();expect(await stale(id)).toBe(2);const { runSyncTail } = await import('../src/core/persistence/sync-tail.ts');- const { recordSyncTail } = await import('../src/core/persistence/sync-tail-record.ts');- const [cursor] = await engine.executeRaw<{ fingerprint: string; run_id: string }>("SELECT fingerprint, completed_keys->0->>'runId' AS run_id FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [id]);- await engine.executeRaw("UPDATE op_checkpoints SET completed_keys=jsonb_set(completed_keys,'{0,processingOptions,noExtract}','false'::jsonb) WHERE op='managed-sync' AND fingerprint=$1", [cursor!.fingerprint]);- await recordSyncTail(engine, id, cursor!.fingerprint, cursor!.run_id);+ const { recordPassTail } = await import('../src/core/persistence/sync-tail-record.ts');+ // The pass's tail obligation as if the run had extracted: its two imported pages, links owed.+ await recordPassTail(engine, id, result.pass!.pass_id, { changed: 2, extract: true });const deferred = await runSyncTail(engine, id, { deadlineAtMs: Date.now() - 1 });expect(deferred).toMatchObject({ status: 'deferred', notice: { code: 'sync_tail_degraded' } });expect(await readSyncTail(engine, id)).not.toBeNull();@@ -166,12 +174,13 @@ test('a tail cut short reports only the imported pages it left underived, neverconst [{ local_path: root }] = await engine.executeRaw<{ local_path: string }>('SELECT local_path FROM sources WHERE id=$1', [id]);for (const name of ['n2', 'n3']) writeFileSync(join(root, 'notes', `${name}.md`), `---\ntitle: ${name}\n---\nSee [[notes/n0]].\n`);git(root, 'add', '.'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'two more');- await performSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true, drain: true });+ const twoMore = await performSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true, drain: true });+ expect(twoMore).toMatchObject({ added: 2, pass: { kind: 'full' } });+ const pinnedAt = async () => (await engine.executeRaw<{ since: string }>("SELECT completed_keys->0->'telemetry'->>'started_at' AS since FROM op_checkpoints WHERE op='managed-sync-pass' AND completed_keys->0->>'source_id'=$1", [id]))[0]!.since;+ const twoMoreSince = await pinnedAt();expect(await stale(id)).toBe(4);const { runSyncTail } = await import('../src/core/persistence/sync-tail.ts');- const { recordSyncTail } = await import('../src/core/persistence/sync-tail-record.ts');- const [cursor] = await engine.executeRaw<{ fingerprint: string; run_id: string }>("SELECT fingerprint, completed_keys->0->>'runId' AS run_id FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [id]);- await engine.executeRaw("UPDATE op_checkpoints SET completed_keys=jsonb_set(completed_keys,'{0,processingOptions,noExtract}','false'::jsonb) WHERE op='managed-sync' AND fingerprint=$1", [cursor!.fingerprint]);+ const { recordPassTail } = await import('../src/core/persistence/sync-tail-record.ts');// The first page read of each tail outlasts its budget, so exactly one page is derived before the deadline stops it.const slowFirst = (budgetMs: number) => {let reads = 0;@@ -185,7 +194,7 @@ test('a tail cut short reports only the imported pages it left underived, never} }) as unknown as BrainEngine;};// Two imported pages, one derived: the notice counts the one left, not the two older stale pages behind it.- await recordSyncTail(engine, id, cursor!.fingerprint, cursor!.run_id);+ await recordPassTail(engine, id, twoMore.pass!.pass_id, { changed: 2, extract: true, since: twoMoreSince });const cut = await runSyncTail(slowFirst(1_000), id, { budgetMs: 1_000 });expect(cut?.links).toMatchObject({ pages: 1 });expect(cut).toMatchObject({ status: 'truncated', notice: { code: 'sync_tail_degraded', fix: { argv: ['gbrain', 'extract', '--stale', '--source-id', id] } } });@@ -193,10 +202,9 @@ test('a tail cut short reports only the imported pages it left underived, never// One imported page, derived before the deadline, with the older backlog still stale: the tail is done.writeFileSync(join(root, 'notes', 'n4.md'), '---\ntitle: n4\n---\nSee [[notes/n0]].\n');git(root, 'add', '.'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'one more');- await performSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true, drain: true });- const [next] = await engine.executeRaw<{ fingerprint: string; run_id: string }>("SELECT fingerprint, completed_keys->0->>'runId' AS run_id FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [id]);- await engine.executeRaw("UPDATE op_checkpoints SET completed_keys=jsonb_set(completed_keys,'{0,processingOptions,noExtract}','false'::jsonb) WHERE op='managed-sync' AND fingerprint=$1", [next!.fingerprint]);- await recordSyncTail(engine, id, next!.fingerprint, next!.run_id);+ const oneMore = await performSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true, drain: true });+ expect(oneMore).toMatchObject({ added: 1, pass: { kind: 'full' } });+ await recordPassTail(engine, id, oneMore.pass!.pass_id, { changed: 1, extract: true, since: await pinnedAt() });const staleBefore = await stale(id);expect(staleBefore).toBeGreaterThan(1);const done = await runSyncTail(slowFirst(1_000), id, { budgetMs: 1_000 });diff --git a/test/sync-pass-shadow-6712.test.ts b/test/sync-pass-shadow-6712.test.tsindex 59a9f82510..93da6013e5 100644--- a/test/sync-pass-shadow-6712.test.ts+++ b/test/sync-pass-shadow-6712.test.ts@@ -179,8 +179,14 @@ describe('#6712 PR 4a convergence shadow (pglite)', () => {expect(await footprint(engine)).toBe(before);}, { setup }), 120_000);- test('sync status: plain status skips the heavy convergence read; --detail reports it with dry_run: true', () => managedBrain(async ({ engine }) => {+ test('sync status: plain status reports the live pass row, and without one it skips the heavy convergence read; --detail reports it with dry_run: true', () => managedBrain(async ({ engine }) => {expect((await performManagedSync(engine, SYNC)).status).toBe('first_sync');+ // #6712 PR 4b: a live pass's row is the convergence plain status reports, read in the status's own statements.+ const live = await readSyncStatus(engine, 'default', { detail: false });+ expect(live.convergence_read).toEqual({ status: 'read' });+ expect(live.convergence).toMatchObject({ dry_run: false, outcome: 'synced', candidates: 3, settled: 3 });+ // A source with no pass row (no pass has run there yet) keeps the 4a contract.+ await engine.executeRaw("DELETE FROM op_checkpoints WHERE op='managed-sync-pass' AND completed_keys->0->>'source_id'='default'");const plain = await readSyncStatus(engine, 'default', { detail: false });expect(plain.convergence).toBeNull();expect(plain.convergence_read).toMatchObject({ status: 'not_read', fix: { argv: ['gbrain', 'sync', 'status', '--source', 'default', '--detail', '--json'] } });diff --git a/test/sync-status-unblock.test.ts b/test/sync-status-unblock.test.tsindex 6e47335ea1..2410b0525e 100644--- a/test/sync-status-unblock.test.ts+++ b/test/sync-status-unblock.test.ts@@ -13,6 +13,10 @@* `--no-llm` keeps the model-tier file held; `--no-repair` refuses every* repair-class hold as before. Sentinel claim text must never reach a hold,* an outcome, a receipt or a printed line.+ *+ * #6712 PR 4b: a non-company source runs the live pass, so status reports the pass (`convergence`, no cursor), a+ * database-only edit of a file that also changed is held `file_drift` (side both) where the cursor held+ * `concurrent_write`, and a printed sync carries opt-outs only while the pass's opt-out episode is open.*/import { afterAll, beforeAll, expect, test } from 'bun:test';import { randomUUID } from 'node:crypto';@@ -79,13 +83,15 @@ test('the classifier: every table code has a class and at least one safe action;expect(classifySyncFault({ code: 'something_new' }).human_reason).toContain('gbrain errors something_new');});-test('status joins the cursor, the recent commits, each hold with its triple and one next; unblock schedules a committed dirty file, refuses a still-dirty one and a concurrent write by name', async () => withEnv({ GBRAIN_HOME: home }, async () => {+test('status joins the pass, the recent commits, each hold with its triple and one next; unblock schedules a committed dirty file, refuses a still-dirty one and a file drift by name', async () => withEnv({ GBRAIN_HOME: home }, async () => {const f = await fixture({ 'a.md': note('Alpha one.'), 'b.md': note('Beta one.'), 'c.md': note('Gamma one.'), 'd.md': note('Delta one.') });expect((await performManagedSync(engine, f.opts)).status).toBe('first_sync');const clean = await readSyncStatus(engine, f.id);- expect(clean).toMatchObject({ source_id: f.id, cursor: { index: 4, total: 4, done: true }, holds: [], last_error: null, needs_human: false, next: null });+ expect(clean).toMatchObject({ source_id: f.id, cursor: null, state: 'synced', convergence: { kind: 'full', outcome: 'synced', settled: 4, remaining: 0, episode: null },+ holds: [], last_error: null, needs_human: false, next: null });expect(clean.committed_last_10m).toBe(4);- expect(clean.resume_argv).toEqual(['--source', f.id, '--no-pull', '--no-embed', '--no-extract']);+ // The pass converged and closed its opt-out episode, so the plain sync carries no inherited opt-out.+ expect(clean.resume_argv).toEqual(['--source', f.id, '--no-pull']);for (const name of ['a', 'b', 'c', 'd']) writeFileSync(join(f.root, `${name}.md`), note(`${name} two.`));const pin = commit(f.root, 'version two');const abort = new AbortController();@@ -96,18 +102,18 @@ test('status joins the cursor, the recent commits, each hold with its triple andawait engine.transaction(tx => withCoordinatedWrite(tx, [f.id], () => tx.putPage('d', { type: 'note', title: 'Example', compiled_truth: 'Delta, edited in the database.', timeline: '', frontmatter: {}, content_hash: 'd-db' }, { sourceId: f.id }), TEST_WRITE_ATTRIBUTION));const resumed = await performManagedSync(engine, f.opts);expect(resumed.status).toBe('synced');- expect(resumed.held?.map(hold => [hold.path, hold.code]).sort()).toEqual([['b.md', 'worktree_dirty'], ['c.md', 'worktree_dirty'], ['d.md', 'concurrent_write']]);+ expect(resumed.held?.map(hold => [hold.path, hold.code]).sort()).toEqual([['b.md', 'worktree_dirty'], ['c.md', 'worktree_dirty'], ['d.md', 'file_drift']]);const status = await readSyncStatus(engine, f.id);- expect(status.cursor).toMatchObject({ index: 4, total: 4, pinned_target: pin, done: true });+ expect(status).toMatchObject({ cursor: null, convergence: { target: pin, outcome: 'synced', remaining: 0 } });expect(status.holds.map(hold => ({ path: hold.path, code: hold.code, class: hold.class, safe_actions: hold.safe_actions, needs_human: hold.needs_human, attempts: hold.attempts })).sort((x, y) => x.path.localeCompare(y.path))).toEqual([{ path: 'b.md', code: 'worktree_dirty', class: 'page', safe_actions: ['retry_when_clean'], needs_human: false, attempts: 1 },{ path: 'c.md', code: 'worktree_dirty', class: 'page', safe_actions: ['retry_when_clean'], needs_human: false, attempts: 1 },- { path: 'd.md', code: 'concurrent_write', class: 'page', safe_actions: ['reconcile'], needs_human: true, attempts: 1 },+ { path: 'd.md', code: 'file_drift', class: 'page', safe_actions: ['reconcile'], needs_human: true, attempts: 1 },]);expect(status.needs_human).toBe(true);- expect(status.human_reason).toContain('reconcile');- expect(status.next).toMatchObject({ argv: ['gbrain', 'sources', 'reconcile', f.id, 'd', '--preview'] });+ expect(status.human_reason).toContain('which version wins');+ expect(status.next).toMatchObject({ argv: ['gbrain', 'repair', 'file-drift', '--source', f.id, '--slug', 'd', '--prefer', 'database'] });expect(status.next!.user_message).toContain('page d');expect(JSON.stringify(status)).not.toContain('edited and not committed');@@ -117,13 +123,13 @@ test('status joins the cursor, the recent commits, each hold with its triple andconst [source] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [f.id]);const preview = await unblockSync(engine, f.id, { apply: false });expect(preview.applied.map(entry => [entry.path, entry.action])).toEqual([['b.md', 'retry_when_clean']]);- expect(preview.refused.map(entry => [entry.path, entry.code, entry.needs_human]).sort()).toEqual([['c.md', 'worktree_dirty', false], ['d.md', 'concurrent_write', true]]);+ expect(preview.refused.map(entry => [entry.path, entry.code, entry.needs_human]).sort()).toEqual([['c.md', 'worktree_dirty', false], ['d.md', 'file_drift', true]]);expect(preview.refused.find(entry => entry.path === 'c.md')!.reason).toContain('still_dirty');expect(preview.next).toMatchObject({ argv: ['gbrain', 'sync', 'unblock', '--source', f.id, '--apply', '--json'] });expect(await readGitHoldRetryPaths(engine, f.id, source.incarnation)).toEqual([]);const applied = await unblockSync(engine, f.id, { apply: true });expect(applied.applied.map(entry => entry.path)).toEqual(['b.md']);- expect(applied.next).toMatchObject({ argv: ['gbrain', 'sync', '--source', f.id, '--no-pull', '--no-embed', '--no-extract'] });+ expect(applied.next).toMatchObject({ argv: ['gbrain', 'sync', '--source', f.id, '--no-pull'] });expect(await readGitHoldRetryPaths(engine, f.id, source.incarnation)).toEqual(['b.md']);// Idempotent.await unblockSync(engine, f.id, { apply: true });@@ -156,7 +162,7 @@ test('status reports an older release\'s recorded failure as a retryable page fatry { expect((await performManagedSync(engine, f.opts)).status).toBe('blocked_by_failures'); }finally { await engine.executeRaw("DELETE FROM config WHERE key='sync.holds'"); }const status = await readSyncStatus(engine, f.id);- expect(status.cursor).toMatchObject({ index: 1, total: 2, done: false });+ expect(status).toMatchObject({ cursor: null, state: 'resumable', convergence: { outcome: 'blocked', stop_reason: 'blocked_by_failures', candidates: 2, remaining: 2, counts: { modified: 1 } } });expect(status.last_error).toMatchObject({ code: 'source_changed', class: 'page', safe_actions: ['retry'], needs_human: false, path: 'b.md', phase: 'receipt' });expect(status.needs_human).toBe(false);expect(status.next).toMatchObject({ argv: ['gbrain', 'sync', '--source', f.id, '--no-pull', '--no-embed', '--no-extract'] });@@ -232,12 +238,13 @@ test('#6377: unblock --apply repairs an invalid_fence hold through the fences kiconst applied = await unblockSync(engine, f.id, { apply: true, noLlm: true });const repaired = applied.applied.find(entry => entry.path === 'people/holder.md');expect(repaired).toMatchObject({ code: 'invalid_fence', action: 'repair', repair: { kind: 'fences', outcome: 'repaired', tier: 'resolver', receipt: { mode: 'managed', path: 'people/holder.md', tier: 'resolver', classes: 'holder_verified', hold_cleared: true, committed: 'queued' } } });- expect(repaired!.action === 'repair' && repaired!.repair.next).toMatchObject({ argv: ['gbrain', 'sync', '--source', f.id, '--no-pull', '--no-embed', '--no-extract'] });+ // The pass that held the fences converged and closed its opt-out episode, so the printed sync carries no inherited opt-out.+ expect(repaired!.action === 'repair' && repaired!.repair.next).toMatchObject({ argv: ['gbrain', 'sync', '--source', f.id, '--no-pull'] });const model = applied.applied.find(entry => entry.path === 'people/model.md');// The model-tier file was kept out of the plan (--no-llm); the kind recorded llm_disabled on its hold, and its next step is the hold's own paid fix.expect(model).toMatchObject({ action: 'repair', repair: { kind: 'fences', outcome: 'held', reason: 'llm_disabled', next: { argv: ['gbrain', 'config', 'set', 'fences.repair.llm', 'true'], consent: ['paid'] } } });expect(applied.refused.map(entry => entry.path)).toEqual(['people/manual.md']);- expect(applied.next).toMatchObject({ argv: ['gbrain', 'sync', '--source', f.id, '--no-pull', '--no-embed', '--no-extract'] });+ expect(applied.next).toMatchObject({ argv: ['gbrain', 'sync', '--source', f.id, '--no-pull'] });expect(applied.next!.why).toContain('1 repaired by the content-repair lane');expect(await readGitHoldRetryPaths(engine, f.id, source.incarnation)).toEqual(['people/holder.md']);expect(readFileSync(join(f.root, 'people/holder.md'), 'utf8')).toContain('people/alice-example');diff --git a/test/sync-waiver-run-imports.test.ts b/test/sync-waiver-run-imports.test.tsindex cb28b74464..9b4fc12335 100644--- a/test/sync-waiver-run-imports.test.ts+++ b/test/sync-waiver-run-imports.test.ts@@ -5,6 +5,11 @@* screen of an entry the cursor does not yet name validates against this run's cursor* with nothing pending; the run's transaction re-checks each file's bytes and the* owner epoch, so an edit or an owner change after the screens still ends the run.+ *+ * #6712 PR 4b: a non-company source syncs by the live pass, whose batch drains through+ * the same waiver runs on a batch cursor with no cursor row; the pass's result (`pass`)+ * says what the cursor row said: an edited file still ends the run and the pass converges,+ * and an owner change blocks the pass with nothing settled.*/import { afterAll, beforeAll, expect, test } from 'bun:test';import { execFileSync } from 'node:child_process';@@ -95,8 +100,9 @@ test('a file edited after its screen ends the waiver run before it: earlier fileconst admitted = (await importRequests(engine, f.id)).slice(before);expect(new Set(admitted.map(row => row.slug))).toEqual(new Set(['n03']));expect(admitted[0]!.state).toBe('conflict');- const [cursor] = await engine.executeRaw<{ index: number; done: boolean }>("SELECT (completed_keys->0->>'index')::int AS index,(completed_keys->0->>'done')::boolean AS done FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [f.id]);- expect(cursor).toMatchObject({ index: 8, done: true });+ // The pass keeps no cursor row: it settled all eight candidates of its round and converged.+ expect(await engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [f.id])).toEqual([]);+ expect(result.pass).toMatchObject({ kind: 'full', outcome: 'synced', stop_reason: null, candidates: 8, remaining: 0 });} finally { installFaultHook(undefined); await disposePersistenceConsumer(engine); }}}), 120_000);@@ -121,10 +127,11 @@ test('an owner change during a waiver run\'s screens waives nothing: the run falconst outcome = await performManagedSync(proxy, { sourceId: f.id, ...OPTS, full: true }).then(result => ({ result }), (error: unknown) => ({ error }));expect(bumped).toBe(true);// The run re-reads the owner epoch under its lock and passes nothing; the head's per-entry screen then admits it,- // and its publication refuses the stale owner, so the cursor stays at the head.+ // and its publication refuses the stale owner, so the pass stops blocked with nothing settled.expect('result' in outcome).toBe(true);const result = (outcome as { result: Awaited<ReturnType<typeof performManagedSync>> }).result;- expect(result).toMatchObject({ status: 'blocked_by_failures', waived: { imports: 0, deletes: 0 }, managedCursor: { index: 0 }, failureCodes: [{ code: 'owner_unavailable' }] });+ expect(result).toMatchObject({ status: 'blocked_by_failures', waived: { imports: 0, deletes: 0 }, failureCodes: [{ code: 'owner_unavailable' }],+ pass: { kind: 'full', outcome: 'blocked', stop_reason: 'blocked_by_failures', candidates: 8, settled: 0, remaining: 8 } });} finally { await disposePersistenceConsumer(proxy); }}}), 120_000);