Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
test(#6712 PR 4b lane C): drop the non-company path-slice and stage-resume real-brain tests; a pass-bounded first sync and deletion backlog converge with last_commit moving only at the end (the dry run keeps sliceEntries/stagedSyncTarget unit tests)
garrytan243cb98e2a71
diff --git a/test/sync-full-cursor-slices-6349.test.ts b/test/sync-full-cursor-slices-6349.test.tsindex d986f07065..12c8bcffdb 100644--- a/test/sync-full-cursor-slices-6349.test.ts+++ b/test/sync-full-cursor-slices-6349.test.ts@@ -4,7 +4,8 @@* Discovery now cuts such a target into path slices ordered `(phase, path)`: every import slice, then bounded deletion* slices, pinned at one target. Each slice's checkpoint records `{ phase, after, head, target }` in the same transaction* instead of advancing `last_commit`, which moves only when the last slice settles. The bound is lowered through the- * test seam. Synthetic content only.+ * test seam. #6712 PR 4b: only the dry run's discovery still slices (`sliceEntries`); a source's writes run by the live pass,+ * whose bounded runs the real-brain test below covers. Synthetic content only.*/import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';import { execFileSync } from 'node:child_process';@@ -16,11 +17,10 @@ import type { BrainEngine } from '../src/core/engine.ts';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { claimWorktree } from '../src/core/persistence/ownership.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';-import { drainManagedSync } from '../src/core/persistence/sync-drain.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';import { _setCursorBoundForTest } from '../src/core/persistence/sync-discovery.ts';import { sliceEntries, SYNC_SLICE_OP } from '../src/core/persistence/sync-slices.ts';import type { SyncEntry } from '../src/core/persistence/sync-discovery.ts';-import { performSync } from '../src/commands/sync/perform.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';import { testBackends } from './helpers/test-backends.ts';import { withEnv } from './helpers/with-env.ts';@@ -67,7 +67,11 @@ describe('sliceEntries (phase, then code-unit path order)', () => {});});-describe('path-sliced managed sync on a real brain', () => {+// #6712 PR 4b: a non-company source syncs by the live pass, which batches candidates per round (`PASS_BATCH_MAX`) and keeps+// no path-slice record; the cursor's path slices are left only to the dry run's discovery (`sliceEntries` above). What the+// slices protected, completion of a target too large for one run with `last_commit` moving only at the end, holds for+// passes bounded to a few pages per run.+describe('a pass-bounded first sync and deletion backlog on a real brain', () => {const engines: BrainEngine[] = [];let closePostgres: (() => Promise<void>) | undefined;beforeAll(async () => {@@ -76,139 +80,44 @@ describe('path-sliced managed sync on a real brain', () => {}, 120_000);afterAll(async () => { for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); } await closePostgres?.(); });- async function managedSource(engine: BrainEngine, seed: (r: ReturnType<typeof repo>) => void = r => { r.write('base'); r.commit('base'); }) {- // Each engine iteration starts at the real bound: the previous engine's lowered bound must not slice this fixture's seed sync.- _setCursorBoundForTest();- const r = repo();- const id = `slc-${randomUUID().replace(/-/g, '').slice(0, 16)}`;- seed(r);- await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');- await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [id, r.root]);- await claimWorktree(engine, id, r.root);- await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');- const opts = { sourceId: id, noPull: true, noEmbed: true, noExtract: true };- const pages = async () => (await engine.executeRaw<{ slug: string }>('SELECT slug FROM pages WHERE source_id=$1 AND deleted_at IS NULL ORDER BY slug', [id])).map(p => p.slug);- const lastCommit = async () => (await engine.executeRaw<{ last_commit: string | null }>('SELECT last_commit FROM sources WHERE id=$1', [id]))[0]!.last_commit;- const sliceRecords = async () => (await engine.executeRaw<{ n: string }>("SELECT COUNT(*)::text AS n FROM op_checkpoints WHERE op=$1 AND fingerprint LIKE $2", [SYNC_SLICE_OP, `${id}:%`]))[0]!.n;- return { r, id, opts, pages, lastCommit, sliceRecords };- }- const env = { GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home };-- test('a first sync above the bound completes over several import slices; last_commit lands only at the end and the slice record is gone', () => withEnv(env, async () => {+ test('runs bounded to two pages complete a first sync and then a deletion backlog; last_commit moves only on the converging run, and no slice record is written', () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {for (const engine of engines) {+ const r = repo();+ const id = `slc-${randomUUID().replace(/-/g, '').slice(0, 16)}`;const names = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];- let head = '';- const { opts, pages, lastCommit, sliceRecords } = await managedSource(engine, r => { for (const n of names) r.write(n); head = r.commit('seven at once'); });- _setCursorBoundForTest({ entries: 3, bytes: 1024 ** 2 });- const first = await drainManagedSync(engine, opts, false);- expect(first.drain?.outcome).toBe('synced');- expect(first.staged).toMatchObject({ target: head, head, slice: { phase: 'import', after: 'notes/c.md' } });- expect(await lastCommit()).toBeNull();- expect(await pages()).toEqual(['notes/a', 'notes/b', 'notes/c']);- expect(await sliceRecords()).toBe('1');- const result = await performSync(engine, { ...opts, drain: true });- expect(result.drain?.outcome).toBe('synced');- expect(result.staged).toBeUndefined();- expect(await lastCommit()).toBe(head);- expect(await pages()).toEqual(names.map(n => `notes/${n}`));+ for (const name of names) r.write(name);+ const first = r.commit('seven at once');+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [id, r.root]);+ await claimWorktree(engine, id, r.root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const opts = { sourceId: id, noPull: true, noEmbed: true, noExtract: true };+ const pages = async () => (await engine.executeRaw<{ slug: string }>('SELECT slug FROM pages WHERE source_id=$1 AND deleted_at IS NULL ORDER BY slug', [id])).map(p => p.slug);+ const lastCommit = async () => (await engine.executeRaw<{ last_commit: string | null }>('SELECT last_commit FROM sources WHERE id=$1', [id]))[0]!.last_commit;+ const sliceRecords = async () => (await engine.executeRaw<{ n: string }>("SELECT COUNT(*)::text AS n FROM op_checkpoints WHERE op=$1 AND fingerprint LIKE $2", [SYNC_SLICE_OP, `${id}:%`]))[0]!.n;+ const drain = async (before: string | null) => {+ const statuses: string[] = [];+ for (let run = 0; run < 12; run++) {+ const result = await performManagedSync(engine, opts, { maxPages: 2, maxMs: 60_000 });+ statuses.push(result.status);+ if (result.status !== 'partial') break;+ expect(await lastCommit()).toBe(before);+ }+ return statuses;+ };+ const firstRuns = await drain(null);+ expect(firstRuns.length).toBeGreaterThan(2);+ expect(firstRuns.at(-1)).toBe('first_sync');+ expect(await lastCommit()).toBe(first);+ expect(await pages()).toEqual(names.map(name => `notes/${name}`));+ for (const name of ['a', 'b', 'c', 'd', 'e']) r.remove(name);+ const second = r.commit('delete five');+ const deleteRuns = await drain(first);+ expect(deleteRuns.length).toBeGreaterThan(1);+ expect(deleteRuns.at(-1)).toBe('synced');+ expect(await lastCommit()).toBe(second);+ expect(await pages()).toEqual(['notes/f', 'notes/g']);expect(await sliceRecords()).toBe('0');}}), 300_000);-- test('deletions above the bound run in bounded slices after every import slice; a drain finishes the target', () => withEnv(env, async () => {- for (const engine of engines) {- const { r, opts, pages, lastCommit } = await managedSource(engine, r => { for (const n of ['a', 'b', 'c', 'd', 'e', 'f', 'g']) r.write(n); r.commit('seven'); });- expect((await drainManagedSync(engine, opts, false)).drain).toMatchObject({ outcome: 'synced' });- const synced = await lastCommit();- for (const n of ['b', 'c', 'd', 'e', 'f']) r.remove(n);- r.write('a', 'Edited after the deletions.'); r.write('h');- const head = r.commit('delete five, edit one, add one');- _setCursorBoundForTest({ entries: 2, bytes: 1024 ** 2 });- const full = { ...opts, full: true };- const phases: string[] = [];- for (let slice = 0; slice < 10; slice++) {- const step = await drainManagedSync(engine, full, false);- expect(step.drain?.outcome).toBe('synced');- if (!step.staged) break;- phases.push(`${step.staged.slice!.phase}:${step.staged.slice!.after}`);- expect(await lastCommit()).toBe(synced);- }- // Imports (a, g, h: the tree walk re-screens every path, two per slice) precede the deletions (five, two per slice).- expect(phases).toEqual(['import:notes/g.md', 'import:notes/h.md', 'delete:notes/c.md', 'delete:notes/e.md']);- expect(await lastCommit()).toBe(head);- expect(await pages()).toEqual(['notes/a', 'notes/g', 'notes/h']);- expect((await engine.getPage('notes/a', { sourceId: opts.sourceId }))?.compiled_truth).toContain('Edited after the deletions.');- }- }), 300_000);-- test('a run stopped inside a slice resumes at the stored slice cursor with the pinned target; no page is skipped or duplicated', () => withEnv(env, async () => {- for (const engine of engines) {- const names = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];- let head = '';- const { r, opts, pages, lastCommit, sliceRecords, id } = await managedSource(engine, r => { for (const n of names) r.write(n); head = r.commit('seven at once'); });- _setCursorBoundForTest({ entries: 3, bytes: 1024 ** 2 });- // First slice committed whole; the second slice is aborted after its first page.- expect((await drainManagedSync(engine, opts, false)).staged?.slice).toEqual({ phase: 'import', after: 'notes/c.md' });- const abort = new AbortController();- let committed = 0;- const stopped = await drainManagedSync(engine, { ...opts, signal: abort.signal, onProgress: event => { if (event.phase === 'managed_sync.page_committed' && ++committed === 1) abort.abort(); } }, false);- expect(stopped.drain?.outcome).not.toBe('synced');- expect(await lastCommit()).toBeNull();- expect(await sliceRecords()).toBe('1');- // HEAD moves on while the sliced target is pending: the resume stays pinned at the sliced target.- r.write('z'); const later = r.commit('after the pin');- const resumed = await performSync(engine, { ...opts, drain: true });- expect(resumed.drain?.outcome).toBe('synced');- expect(await pages()).toEqual([...names, 'z'].map(n => `notes/${n}`));- expect(await lastCommit()).toBe(later);- expect(await sliceRecords()).toBe('0');- const rows = await engine.executeRaw<{ slug: string; n: string }>('SELECT slug,COUNT(*)::text AS n FROM pages WHERE source_id=$1 GROUP BY slug HAVING COUNT(*)>1', [id]);- expect(rows).toEqual([]);- expect(head).not.toBe(later);- }- }), 300_000);-- test('a byte bound slices by path bytes; one commit above the entry bound is pinned and sliced instead of refused; a rename inside it keeps the page', () => withEnv(env, async () => {- for (const engine of engines) {- const { r, opts, pages, lastCommit, id } = await managedSource(engine, r => { r.write('base'); r.write('keep'); r.commit('base'); });- expect((await drainManagedSync(engine, opts, false)).drain).toMatchObject({ outcome: 'synced' });- const before = await lastCommit();- const long = Array.from({ length: 6 }, (_, i) => `a-rather-long-synthetic-name-${i}-${'x'.repeat(40)}`);- for (const n of long) r.write(n);- r.move('keep', 'kept');- const big = r.commit('seven paths in one commit, one a rename');- r.write('tail'); const head = r.commit('one more');- // Ample entries, but the serialized manifest of three long paths already exceeds the byte bound (one resolved entry is ~150 bytes).- const one = Buffer.byteLength(JSON.stringify([{ path: `notes/${long[0]}.md`, sourcePath: `notes/${long[0]}.md`, action: 'import', working: false, pageId: null, revision: null }]));- _setCursorBoundForTest({ entries: 100, bytes: Math.round(one * 2.5) });- const first = await drainManagedSync(engine, opts, false);- expect(first.drain?.outcome).toBe('synced');- expect(first.staged).toMatchObject({ target: big, head, slice: { phase: 'import' } });- // Path bytes cut the import phase short of its last entry: the slice ends on one of the long paths, not the whole set.- expect(long.slice(0, 4).map(n => `notes/${n}.md`)).toContain(first.staged!.slice!.after ?? '');- expect(await lastCommit()).toBe(before);- const result = await performSync(engine, { ...opts, drain: true });- expect(result.drain?.outcome).toBe('synced');- expect(result.staged).toBeUndefined();- expect(await lastCommit()).toBe(head);- expect(await pages()).toEqual([...long.map(n => `notes/${n}`), 'notes/base', 'notes/kept', 'notes/tail'].sort());- const kept = await engine.executeRaw<{ slug: string; deleted_at: string | null }>("SELECT slug,deleted_at FROM pages WHERE source_id=$1 AND slug IN ('notes/keep','notes/kept')", [id]);- expect(kept).toEqual([{ slug: 'notes/kept', deleted_at: null }]);- }- }), 300_000);-- test('a single entry above the byte bound refuses by name with nothing written', () => withEnv(env, async () => {- for (const engine of engines) {- const { r, opts, pages, lastCommit } = await managedSource(engine, r => { r.write('base'); r.commit('base'); });- expect((await drainManagedSync(engine, opts, false)).drain).toMatchObject({ outcome: 'synced' });- const before = await lastCommit();- r.write(`a${'y'.repeat(200)}`); r.write('small'); r.commit('one enormous path');- _setCursorBoundForTest({ entries: 100, bytes: 200 });- const refusal = await drainManagedSync(engine, opts, false).then(() => null, (error: { code?: string; message: string }) => error);- expect(refusal).toMatchObject({ code: 'request_too_large' });- expect(refusal!.message).toContain('One sync entry exceeds the bounded cursor size.');- expect(await lastCommit()).toBe(before);- expect(await pages()).toEqual(['notes/base']);- }- }), 300_000);});diff --git a/test/sync-staged-catchup.test.ts b/test/sync-staged-catchup.test.tsindex b5b4bcfe45..a8d764e110 100644--- a/test/sync-staged-catchup.test.ts+++ b/test/sync-staged-catchup.test.ts@@ -3,7 +3,9 @@* sync forever. Discovery now stages it: the furthest first-parent commit whose delta fits, found by a forward gallop that* verifies every candidate (a net delta is not monotone along history, so binary search has no valid predicate); a drain* then takes stage after stage to HEAD. One commit above the bound is pinned and cut into path slices (#6349 P4.4,- * `test/sync-full-cursor-slices-6349.test.ts`). The bound is lowered through the test seam. Synthetic content only.+ * `test/sync-full-cursor-slices-6349.test.ts`). The bound is lowered through the test seam. #6712 PR 4b: only the dry run's+ * discovery still stages; a source's writes run by the live pass, so the real-brain test checks that a backlog past the+ * bound converges to HEAD with the page set of an unbounded sync. Synthetic content only.*/import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';import { execFileSync } from 'node:child_process';@@ -107,46 +109,4 @@ describe('staged managed catch-up on a real brain', () => {expect((await engine.getPage('notes/a', { sourceId: id }))?.compiled_truth).toContain('Edited twice.');}}), 300_000);-- test('a stage stopped mid-way resumes from its stored cursor; then the next stage reaches HEAD', () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {- for (const engine of engines) {- const { r, opts, pages, lastCommit } = await managedSource(engine);- r.write('a'); r.write('b'); const c1 = r.commit('add 2');- r.write('c'); r.write('d'); const head = r.commit('add 2 more');- _setCursorBoundForTest({ entries: 3, bytes: 1024 ** 2 });- const abort = new AbortController();- let committed = 0;- const first = await drainManagedSync(engine, { ...opts, signal: abort.signal, onProgress: event => { if (event.phase === 'managed_sync.page_committed' && ++committed === 1) abort.abort(); } }, false);- expect(first.drain?.outcome).not.toBe('synced');- expect(first.toCommit).toBe(c1);- const resumed = await drainManagedSync(engine, opts, false);- expect(resumed).toMatchObject({ toCommit: c1, staged: { target: c1, head } });- expect(await lastCommit()).toBe(c1);- const finished = await drainManagedSync(engine, opts, false);- expect(finished.staged).toBeUndefined();- expect(await lastCommit()).toBe(head);- expect(await pages()).toEqual(['notes/a', 'notes/b', 'notes/base', 'notes/c', 'notes/d']);- }- }), 300_000);-- test('the byte bound stages too, and one commit above the bound is pinned and path-sliced (#6349 P4.4) instead of refused', () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {- for (const engine of engines) {- const { r, opts, lastCommit, pages } = await managedSource(engine);- const before = await lastCommit();- for (const n of ['p', 'q', 'r', 's']) r.write(n);- const big = r.commit('add 4 in one commit');- _setCursorBoundForTest({ entries: 3, bytes: 1024 ** 2 });- const sliced = await drainManagedSync(engine, opts, false);- expect(sliced.staged).toMatchObject({ target: big, head: big, slice: { phase: 'import', after: 'notes/r.md' } });- expect(await lastCommit()).toBe(before);- expect((await drainManagedSync(engine, opts, false)).staged).toBeUndefined();- expect(await lastCommit()).toBe(big);- expect(await pages()).toEqual(['notes/base', 'notes/p', 'notes/q', 'notes/r', 'notes/s']);- // The byte bound: ample entries, but only one entry's worth of bytes per stage.- _setCursorBoundForTest({ entries: 100, bytes: 120 });- r.write('x'); const c1 = r.commit('x'); r.write('y'); r.commit('y');- const staged = await drainManagedSync(engine, opts, false);- expect(staged.staged?.target).toBe(c1);- }- }), 300_000);});