Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

test(persistence): F0 refresh tests 1-13 on PGLite with a Postgres E2E mirror

garrytanf6687f666101
diff --git a/test/e2e/worktree-refresh-postgres.test.ts b/test/e2e/worktree-refresh-postgres.test.ts
new file mode 100644
index 0000000000..22d1c98c2c
--- /dev/null
+++ b/test/e2e/worktree-refresh-postgres.test.ts
@@ -0,0 +1,8 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+// F0 `gbrain sources refresh` on Postgres: the same state machine, admission
+// fence, claim predicates and crash recovery as the PGLite unit files.
+await registerPostgresTests(
+ () => import('../persistence-worktree-refresh.test.ts'),
+ () => import('../persistence-worktree-refresh-restart.test.ts'),
+);
diff --git a/test/helpers/worktree-refresh-child.ts b/test/helpers/worktree-refresh-child.ts
new file mode 100644
index 0000000000..ebc9bdde0f
--- /dev/null
+++ b/test/helpers/worktree-refresh-child.ts
@@ -0,0 +1,52 @@
+/**
+ * Child process for the F0 restart test. `crash`: queue a page write, start a
+ * refresh, and exit the process right after `git merge --ff-only` succeeded
+ * and before the merged bookkeeping commits. `restart`: open the brain as a
+ * fresh owner, let the resident consumer's startup recovery move the refresh,
+ * then `--resume` it and report the final state as one JSON line.
+ */
+import { randomUUID } from 'node:crypto';
+import type { GBrainConfig } from '../../src/core/config.ts';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { submitPageMutation } from '../../src/core/persistence/page-mutations.ts';
+import { disposePersistenceConsumer, startPersistenceConsumer } from '../../src/core/persistence/service.ts';
+import { refreshWorktree } from '../../src/core/persistence/worktree-refresh.ts';
+import { assertSafeE2eDatabaseUrl } from './db-guard.ts';
+
+const input = JSON.parse(process.env.GBRAIN_TEST_REFRESH_CHILD!) as { database: GBrainConfig; sourceId: string; worktreeId: string; mode: 'crash' | 'restart' };
+if (input.database.database_url) assertSafeE2eDatabaseUrl(input.database.database_url);
+const engine: BrainEngine = input.database.engine === 'pglite' ? new PGLiteEngine() : new PostgresEngine();
+await engine.connect(input.database);
+const state = async () => (await engine.executeRaw<{ state: string }>(
+ 'SELECT state FROM persistence_worktree_refreshes WHERE worktree_id=$1::uuid ORDER BY created_at DESC LIMIT 1', [input.worktreeId]))[0]?.state ?? null;
+
+if (input.mode === 'crash') {
+ const requestId = randomUUID();
+ await submitPageMutation({ engine, sourceId: input.sourceId, remote: false, dryRun: false, config: { engine: engine.kind, embedding_disabled: true } as never,
+ logger: { info() {}, warn() {}, error() {} } }, { operation: 'put_page', waitMs: 0,
+ params: { slug: 'notes/pre-fence', content: '---\ntitle: Pre fence\ntype: note\n---\nAccepted before the fence.\n', request_id: requestId } }).catch(() => {});
+ process.stdout.write(`REFRESH_PRE_FENCE ${requestId}\n`);
+ await refreshWorktree(engine, input.sourceId, { hooks: { boundary: point => {
+ if (point !== 'merged') return;
+ process.stdout.write('REFRESH_CRASH_AFTER_MERGE\n');
+ process.exit(137);
+ } } });
+ process.stdout.write('REFRESH_UNEXPECTED_FINISH\n');
+} else {
+ const seen: Array<string | null> = [await state()];
+ startPersistenceConsumer(engine, { engine: engine.kind } as GBrainConfig);
+ const deadline = Date.now() + 20_000;
+ while (Date.now() < deadline && seen[seen.length - 1] !== 'syncing') {
+ await new Promise(resolve => setTimeout(resolve, 100));
+ const next = await state();
+ if (next !== seen[seen.length - 1]) seen.push(next);
+ }
+ const result = await refreshWorktree(engine, input.sourceId, { resume: true });
+ seen.push(await state());
+ const requests = await engine.executeRaw<{ state: string; slug: string }>('SELECT state,slug FROM persistence_requests WHERE worktree_id=$1::uuid ORDER BY sequence', [input.worktreeId]);
+ process.stdout.write(`REFRESH_RESULT ${JSON.stringify({ seen, result, requests })}\n`);
+ await disposePersistenceConsumer(engine);
+}
+await engine.disconnect();
diff --git a/test/helpers/worktree-refresh-fixture.ts b/test/helpers/worktree-refresh-fixture.ts
new file mode 100644
index 0000000000..16be1e979c
--- /dev/null
+++ b/test/helpers/worktree-refresh-fixture.ts
@@ -0,0 +1,87 @@
+/**
+ * F0 `gbrain sources refresh` fixture: a bare upstream, a pushing clone, and a
+ * managed clone whose `alpha/` and `beta/` directories are two sources bound
+ * to ONE canonical worktree (the multi-source case a per-source fence cannot
+ * protect). Both sources are synced once, so `last_commit` is the clone HEAD.
+ */
+import { execFileSync } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import type { OperationContext } from '../../src/core/ops/contract.ts';
+import { registerLocalWriter } from '../../src/core/persistence/identity.ts';
+import { claimWorktree, getWorktreeBinding } from '../../src/core/persistence/ownership.ts';
+import { submitPageMutation } from '../../src/core/persistence/page-mutations.ts';
+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
+import { performManagedSync } from '../../src/core/persistence/sync-run.ts';
+import { withEnv } from './with-env.ts';
+
+export const page = (title: string, body: string) => `---\ntitle: ${title}\ntype: note\n---\n${body}\n`;
+export const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, '-c', 'user.name=Example', '-c', '[email protected]',
+ '-c', 'commit.gpgsign=false', ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+export function commitFile(root: string, path: string, content: string, message = `update ${path}`): string {
+ mkdirSync(join(root, path, '..'), { recursive: true });
+ writeFileSync(join(root, path), content);
+ git(root, 'add', '--', path); git(root, 'commit', '-qm', message);
+ return git(root, 'rev-parse', 'HEAD');
+}
+
+export interface RefreshFixture {
+ engine: BrainEngine; dir: string; home: string; remote: string; upstream: string; root: string;
+ alpha: string; beta: string; worktreeId: string; head: () => string;
+ ctx: (sourceId: string) => OperationContext;
+ /** Commit in the pushing clone and push; returns the new upstream commit. */
+ push: (path: string, content: string) => string;
+ put: (sourceId: string, slug: string, content: string, requestId?: string) => Promise<Record<string, unknown>>;
+ lastCommit: (sourceId: string) => Promise<string | null>;
+ refreshRows: () => Promise<Array<{ id: string; state: string; outcome: Record<string, unknown>; preserved_uncommitted: string[] }>>;
+ requestCount: () => Promise<number>;
+}
+
+/** Caller runs this with GBRAIN_HOME set to `join(dir, 'home')`. */
+export async function setupRefreshFixture(engine: BrainEngine, dir: string): Promise<RefreshFixture> {
+ const home = join(dir, 'home'), remote = join(dir, 'origin.git'), upstream = join(dir, 'upstream'), root = join(dir, 'brain');
+ execFileSync('git', ['init', '-q', '--bare', '-b', 'main', remote]);
+ execFileSync('git', ['clone', '-q', remote, upstream], { stdio: 'ignore' });
+ git(upstream, 'checkout', '-q', '-b', 'main');
+ commitFile(upstream, 'alpha/one.md', page('Alpha one', 'The first alpha observation.'));
+ commitFile(upstream, 'beta/one.md', page('Beta one', 'The first beta observation.'));
+ git(upstream, 'push', '-q', 'origin', 'main');
+ execFileSync('git', ['clone', '-q', remote, root], { stdio: 'ignore' });
+ const tag = randomUUID().replace(/-/g, '').slice(0, 8);
+ const alpha = `alpha-${tag}`, beta = `beta-${tag}`;
+ await registerLocalWriter(engine, 'cli');
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ for (const [id, sub] of [[alpha, 'alpha'], [beta, 'beta']]) {
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,$3::text::jsonb)',
+ [id, join(root, sub), JSON.stringify({ remote_url: remote })]);
+ await claimWorktree(engine, id, join(root, sub));
+ }
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ for (const id of [alpha, beta]) await performManagedSync(engine, { sourceId: id, noPull: true, noEmbed: true });
+ const worktreeId = (await getWorktreeBinding(engine, alpha))!.worktree_id;
+ const ctx = (sourceId: string): OperationContext => ({ engine, sourceId, remote: false, dryRun: false,
+ config: { engine: engine.kind, embedding_disabled: true } as never, logger: { info() {}, warn() {}, error() {} } });
+ return {
+ engine, dir, home, remote, upstream, root, alpha, beta, worktreeId, ctx,
+ head: () => git(root, 'rev-parse', 'HEAD'),
+ push: (path, content) => { const sha = commitFile(upstream, path, content); git(upstream, 'push', '-q', 'origin', 'main'); return sha; },
+ put: (sourceId, slug, content, requestId = randomUUID()) => submitPageMutation(ctx(sourceId), { operation: 'put_page', params: { slug, content, request_id: requestId } }),
+ lastCommit: async sourceId => (await engine.executeRaw<{ last_commit: string | null }>('SELECT last_commit FROM sources WHERE id=$1', [sourceId]))[0]?.last_commit ?? null,
+ refreshRows: async () => engine.executeRaw('SELECT id,state,outcome,preserved_uncommitted FROM persistence_worktree_refreshes WHERE worktree_id=$1::uuid ORDER BY created_at', [worktreeId]),
+ requestCount: async () => Number((await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM persistence_requests WHERE worktree_id=$1::uuid', [worktreeId]))[0].n),
+ };
+}
+
+/** Runs `fn` with GBRAIN_HOME pointed at the fixture, then removes the fixture and parks the brain. */
+export async function withRefreshFixture(engine: BrainEngine, fn: (f: RefreshFixture) => Promise<void>): Promise<void> {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-refresh-'));
+ try {
+ await withEnv({ GBRAIN_HOME: join(dir, 'home') }, async () => {
+ try { await fn(await setupRefreshFixture(engine, dir)); }
+ finally { await disposePersistenceConsumer(engine); }
+ });
+ } finally { rmSync(dir, { recursive: true, force: true }); }
+}
diff --git a/test/persistence-worktree-refresh-restart.test.ts b/test/persistence-worktree-refresh-restart.test.ts
new file mode 100644
index 0000000000..bc8856e754
--- /dev/null
+++ b/test/persistence-worktree-refresh-restart.test.ts
@@ -0,0 +1,88 @@
+/**
+ * F0 `gbrain sources refresh`, spec test 1.8.2 (O-ENG-9, "restart converges").
+ *
+ * Protects: a process killed after `git merge --ff-only` and before the merged
+ * bookkeeping commits leaves the worktree fenced; the next owner start moves
+ * the refresh to `syncing` (only because HEAD is the verified target and the
+ * old HEAD is its ancestor), `--resume` completes it with every member at the
+ * target commit, and the write accepted before the fence is committed.
+ * Regression it catches: recovery adopting an unverified HEAD, recovery not
+ * wired into owner startup, or accepted writes lost across the crash.
+ * Seams: a real child process exits inside the refresh's `merged` boundary.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { spawnSync } from 'node:child_process';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { GBrainConfig } from '../src/core/config.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { git, page, setupRefreshFixture } from './helpers/worktree-refresh-fixture.ts';
+
+const backends = testBackends();
+const dir = mkdtempSync(join(tmpdir(), 'gbrain-refresh-restart-'));
+const cases: Array<{ engine: BrainEngine; database: GBrainConfig; close: () => Promise<void> }> = [];
+
+beforeAll(async () => {
+ if (backends.includes('pglite')) {
+ const database = { engine: 'pglite', database_path: join(dir, 'brain.pglite') } as GBrainConfig;
+ const engine = new PGLiteEngine();
+ await engine.connect(database); await engine.initSchema();
+ cases.push({ engine, database, close: () => engine.disconnect() });
+ }
+ if (backends.includes('postgres')) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ cases.push({ engine: pg.engine, database: { engine: 'postgres', database_url: pg.databaseUrl } as GBrainConfig, close: pg.close });
+ }
+}, 120_000);
+afterAll(async () => {
+ for (const item of cases) { await disposePersistenceConsumer(item.engine); await item.close(); }
+ rmSync(dir, { recursive: true, force: true });
+});
+
+function child(env: Record<string, string>, payload: Record<string, unknown>): { status: number | null; stdout: string; stderr: string } {
+ const run = spawnSync(process.execPath, [join(import.meta.dir, 'helpers/worktree-refresh-child.ts')],
+ { env: { ...process.env, ...env, GBRAIN_TEST_REFRESH_CHILD: JSON.stringify(payload) }, encoding: 'utf8', timeout: 90_000 });
+ return { status: run.status, stdout: run.stdout, stderr: run.stderr };
+}
+
+test('2. O-ENG-9: a crash after git merge and before bookkeeping converges after restart: syncing, then completed', async () => {
+ for (const [index, item] of cases.entries()) {
+ const caseDir = mkdtempSync(join(dir, `case-${index}-`));
+ const home = join(caseDir, 'home');
+ let f!: Awaited<ReturnType<typeof setupRefreshFixture>>;
+ await withEnv({ GBRAIN_HOME: home }, async () => {
+ f = await setupRefreshFixture(item.engine, caseDir);
+ await disposePersistenceConsumer(item.engine);
+ });
+ const target = f.push('alpha/two.md', page('Alpha two', 'An observation that survived a crash.'));
+ const old = f.head();
+ if (item.engine.kind === 'pglite') await item.engine.disconnect();
+ const payload = { database: item.database, sourceId: f.alpha, worktreeId: f.worktreeId };
+
+ const crashed = child({ GBRAIN_HOME: home }, { ...payload, mode: 'crash' });
+ expect(crashed.stdout, crashed.stderr).toContain('REFRESH_CRASH_AFTER_MERGE');
+ expect(crashed.status).toBe(137);
+ expect(git(f.root, 'rev-parse', 'HEAD')).toBe(target);
+ expect(target).not.toBe(old);
+
+ const restarted = child({ GBRAIN_HOME: home }, { ...payload, mode: 'restart' });
+ const line = restarted.stdout.split('\n').find(row => row.startsWith('REFRESH_RESULT '));
+ expect(line, `${restarted.stdout}\n${restarted.stderr}`).toBeDefined();
+ const report = JSON.parse(line!.slice('REFRESH_RESULT '.length)) as { seen: string[]; result: { status: string; synced: Array<{ last_commit: string }> };
+ requests: Array<{ state: string; slug: string }> };
+ expect(report.seen[0]).toBe('fenced');
+ expect(report.seen).toContain('syncing');
+ expect(report.seen[report.seen.length - 1]).toBe('completed');
+ expect(report.result.status).toBe('completed');
+ expect(report.result.synced.map(member => member.last_commit)).toEqual([target, target]);
+ const preFence = report.requests.filter(row => row.slug === 'notes/pre-fence');
+ expect(preFence).toHaveLength(1);
+ expect(report.requests.every(row => row.state === 'committed')).toBe(true);
+ }
+}, 300_000);
diff --git a/test/persistence-worktree-refresh.test.ts b/test/persistence-worktree-refresh.test.ts
new file mode 100644
index 0000000000..405ca5b9f1
--- /dev/null
+++ b/test/persistence-worktree-refresh.test.ts
@@ -0,0 +1,267 @@
+/**
+ * F0 `gbrain sources refresh` (spec section 1.8; tests 1 and 3-13, test 2 is
+ * persistence-worktree-refresh-restart.test.ts).
+ *
+ * Protects: a managed checkout shared by several sources is fast-forwarded only
+ * after every accepted write to it drained, never under a moving HEAD, and the
+ * refresh converges or refuses with a typed, filled fix.
+ * Regression it catches: admission or claiming ignoring the refresh fence (a
+ * write publishing onto a checkout whose HEAD is moving), a per-source fence,
+ * a refresh that merges dirty or diverged checkouts, a refresh that leaves the
+ * fence up after a refusal, or topology changes racing a refresh.
+ * Existing coverage: none; managed sync refused to pull and lane B only
+ * reported the stale upstream.
+ * Seams: the `hooks.boundary` callback pauses the real state machine at its
+ * drained, fenced and merged points; no production behavior is replaced.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { existsSync, readFileSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { operations } from '../src/core/operations.ts';
+import { runSourcesRefresh } from '../src/commands/sources-refresh.ts';
+import { claimCoalescedGitEffects, claimPersistenceEffect } from '../src/core/persistence/effect-journal.ts';
+import { localHostId } from '../src/core/persistence/identity.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { runManagedSourceLifecycle } from '../src/core/persistence/source-lifecycle.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { refreshWorktree, resumeWorktreeRefreshes } from '../src/core/persistence/worktree-refresh.ts';
+import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { git, page, withRefreshFixture, type RefreshFixture } from './helpers/worktree-refresh-fixture.ts';
+
+const backends = testBackends();
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+
+beforeAll(async () => {
+ if (backends.includes('pglite')) {
+ const engine = new PGLiteEngine();
+ await engine.connect({}); await engine.initSchema(); engines.push(engine);
+ }
+ if (backends.includes('postgres')) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ engines.push(pg.engine); closePostgres = pg.close;
+ }
+}, 120_000);
+afterAll(async () => {
+ for (const engine of engines) { await disposePersistenceConsumer(engine); if (engine.kind === 'pglite') await engine.disconnect(); }
+ await closePostgres?.();
+});
+
+const each = async (fn: (f: RefreshFixture) => Promise<void>) => { for (const engine of engines) await withRefreshFixture(engine, fn); };
+const refusedWith = async (promise: Promise<unknown>, code: string) => {
+ const error = await promise.then(() => null, e => e as { code?: string; suggestion?: string; message?: string; docs?: string });
+ expect(error, `expected refusal ${code}`).not.toBeNull();
+ expect(error!.code).toBe(code);
+ return error!;
+};
+/** Requeue a committed git effect so the drain must wait for the consumer to process it again. */
+async function requeueGitEffect(f: RefreshFixture, delayMs: number): Promise<number> {
+ const [effect] = await f.engine.executeRaw<{ id: number }>(`SELECT id FROM persistence_effects WHERE worktree_id=$1::uuid AND kind='git' ORDER BY id DESC LIMIT 1`, [f.worktreeId]);
+ expect(effect).toBeDefined();
+ await f.engine.executeRaw(`UPDATE persistence_effects SET state='queued',execution_token=NULL,claim_expires_at=NULL,
+ next_attempt_at=now()+($2::double precision*interval '1 millisecond') WHERE id=$1`, [effect.id, delayMs]);
+ return Number(effect.id);
+}
+
+test('1. O-ENG-9: writes and syncs to every member are refused while draining, then the same request ids succeed', () => each(async f => {
+ const target = f.push('alpha/two.md', page('Alpha two', 'An upstream observation about narwhals.'));
+ const before = await f.requestCount();
+ const ids = { alpha: randomUUID(), beta: randomUUID() };
+ const result = await refreshWorktree(f.engine, f.alpha, { hooks: { boundary: async point => {
+ if (point !== 'drained') return;
+ await refusedWith(f.put(f.alpha, 'notes/during-alpha', page('During', 'alpha body'), ids.alpha), 'worktree_refreshing');
+ const beta = await refusedWith(f.put(f.beta, 'notes/during-beta', page('During', 'beta body'), ids.beta), 'worktree_refreshing');
+ expect(beta.suggestion).toContain(`gbrain sources writer status ${f.beta}`);
+ expect(beta.docs).toBe('docs/guides/write-refusals.md#worktree_refreshing');
+ await refusedWith(performManagedSync(f.engine, { sourceId: f.beta, noPull: true, noEmbed: true }), 'worktree_refreshing');
+ expect(await f.requestCount()).toBe(before);
+ } } });
+ expect(result).toMatchObject({ status: 'completed', target_head: target, source_ids: [f.alpha, f.beta].sort() });
+ expect(await f.lastCommit(f.alpha)).toBe(target);
+ expect(await f.lastCommit(f.beta)).toBe(target);
+ expect(f.head()).toBe(target);
+ expect((await f.put(f.alpha, 'notes/during-alpha', page('During', 'alpha body'), ids.alpha)).state ?? 'committed').toBe('committed');
+ expect((await f.put(f.beta, 'notes/during-beta', page('During', 'beta body'), ids.beta)).state ?? 'committed').toBe('committed');
+ expect((await f.engine.getPage('two', { sourceId: f.alpha }))?.compiled_truth ?? (await f.engine.getPage('alpha/two', { sourceId: f.alpha }))?.compiled_truth).toContain('narwhals');
+ expect((await f.refreshRows()).map(r => r.state)).toEqual(['completed']);
+}), 180_000);
+
+test('3. a fetch killed by its bound leaves no refresh row and HEAD unchanged', () => each(async f => {
+ f.push('alpha/two.md', page('Alpha two', 'Never fetched.'));
+ const head = f.head();
+ git(f.root, 'config', 'remote.origin.uploadpack', 'sleep 5; git-upload-pack');
+ const error = await refusedWith(refreshWorktree(f.engine, f.alpha, { fetchTimeoutMs: 300 }), 'fetch_failed');
+ expect(error.message).toContain('300 ms');
+ expect(error.suggestion).toContain('--fetch-timeout-ms');
+ expect(await f.refreshRows()).toEqual([]);
+ expect(f.head()).toBe(head);
+}), 120_000);
+
+test('4. a diverged checkout is refused with no row and HEAD unchanged', () => each(async f => {
+ f.push('alpha/two.md', page('Alpha two', 'Upstream side.'));
+ writeFileSync(join(f.root, 'beta/local.md'), page('Local', 'A local commit nobody pushed.'));
+ git(f.root, 'add', 'beta/local.md'); git(f.root, 'commit', '-qm', 'local only');
+ const head = f.head();
+ const error = await refusedWith(refreshWorktree(f.engine, f.alpha), 'refresh_diverged');
+ expect(error.suggestion).toContain(`gbrain sources reclone ${f.alpha}`);
+ expect(await f.refreshRows()).toEqual([]);
+ expect(f.head()).toBe(head);
+}), 120_000);
+
+test('5. dirt overlapping the incoming diff refuses naming the path; unrelated dirt is preserved and listed', () => each(async f => {
+ const target = f.push('alpha/one.md', page('Alpha one', 'The upstream rewrite.'));
+ writeFileSync(join(f.root, 'alpha/one.md'), page('Alpha one', 'An uncommitted local edit.'));
+ writeFileSync(join(f.root, 'beta/draft.txt'), 'unrelated scratch\n');
+ const error = await refusedWith(refreshWorktree(f.engine, f.alpha), 'refresh_dirty');
+ expect(error.message).toContain('alpha/one.md');
+ expect(error.message).not.toContain('beta/draft.txt');
+ expect(await f.refreshRows()).toEqual([]);
+ git(f.root, 'checkout', '--', 'alpha/one.md');
+ const result = await refreshWorktree(f.engine, f.alpha);
+ expect(result.status).toBe('completed');
+ expect(result.preserved_uncommitted).toEqual(['beta/draft.txt']);
+ expect(readFileSync(join(f.root, 'beta/draft.txt'), 'utf8')).toBe('unrelated scratch\n');
+ expect(f.head()).toBe(target);
+}), 180_000);
+
+test('6. an external commit between precheck and merge aborts with refresh_source_changed and lifts the fence', () => each(async f => {
+ f.push('alpha/two.md', page('Alpha two', 'Upstream.'));
+ await refusedWith(refreshWorktree(f.engine, f.alpha, { hooks: { boundary: point => {
+ if (point === 'drained') git(f.root, 'commit', '-q', '--allow-empty', '-m', 'external');
+ } } }), 'refresh_source_changed');
+ const rows = await f.refreshRows();
+ expect(rows.map(r => r.state)).toEqual(['aborted']);
+ expect((rows[0].outcome.refusal as { code: string }).code).toBe('refresh_source_changed');
+ expect((await f.put(f.alpha, 'notes/after', page('After', 'admitted again'))).state ?? 'committed').toBe('committed');
+}), 180_000);
+
+test('7. a crash leaving HEAD on an unrelated commit is recovery_required; writes name the resume; --abandon after reset lifts the fence', () => each(async f => {
+ const target = f.push('alpha/two.md', page('Alpha two', 'Upstream.'));
+ const old = f.head();
+ await expect(refreshWorktree(f.engine, f.alpha, { hooks: { boundary: point => { if (point === 'merged') throw new Error('simulated crash after merge'); } } }))
+ .rejects.toThrow('simulated crash');
+ expect(f.head()).toBe(target);
+ git(f.root, 'reset', '-q', '--hard', old);
+ git(f.root, 'commit', '-q', '--allow-empty', '-m', 'unrelated');
+ await resumeWorktreeRefreshes(f.engine);
+ expect((await f.refreshRows()).map(r => r.state)).toEqual(['recovery_required']);
+ const refused = await refusedWith(f.put(f.alpha, 'notes/blocked', page('Blocked', 'refused')), 'refresh_recovery_required');
+ expect(refused.suggestion).toContain(`gbrain sources refresh ${f.alpha} --resume`);
+ const resume = await refusedWith(refreshWorktree(f.engine, f.alpha, { resume: true }), 'refresh_recovery_required');
+ expect(resume.suggestion).toContain(`reset --hard ${old}`);
+ git(f.root, 'reset', '-q', '--hard', old);
+ expect((await refreshWorktree(f.engine, f.alpha, { abandon: true })).status).toBe('abandoned');
+ expect((await f.refreshRows()).map(r => r.state)).toEqual(['aborted']);
+ expect((await f.put(f.alpha, 'notes/after', page('After', 'admitted again'))).state ?? 'committed').toBe('committed');
+}), 180_000);
+
+test('8. a queued git effect drains before fenced, and nothing on the worktree is claimed while fenced', () => each(async f => {
+ f.push('alpha/two.md', page('Alpha two', 'Upstream.'));
+ await f.put(f.beta, 'notes/effect', page('Effect', 'Has a git effect.'));
+ const effectId = await requeueGitEffect(f, 800);
+ const started = performance.now();
+ const result = await refreshWorktree(f.engine, f.alpha, { hooks: { boundary: async point => {
+ if (point === 'drained') {
+ expect(performance.now() - started).toBeGreaterThanOrEqual(700);
+ expect((await f.engine.executeRaw<{ state: string }>('SELECT state FROM persistence_effects WHERE id=$1', [effectId]))[0].state).toBe('committed');
+ }
+ if (point === 'fenced') {
+ await f.engine.executeRaw(`UPDATE persistence_effects SET state='queued',next_attempt_at=now()-interval '1 second' WHERE id=$1`, [effectId]);
+ expect(await claimPersistenceEffect(f.engine, localHostId())).toBeNull();
+ expect(await claimCoalescedGitEffects(f.engine, localHostId(), f.worktreeId, 5)).toEqual([]);
+ // The resident consumer polls too; a claimable effect would leave 'queued' within a few polls.
+ await new Promise(resolve => setTimeout(resolve, 1200));
+ expect((await f.engine.executeRaw<{ state: string }>('SELECT state FROM persistence_effects WHERE id=$1', [effectId]))[0].state).toBe('queued');
+ await f.engine.executeRaw(`UPDATE persistence_effects SET state='committed' WHERE id=$1`, [effectId]);
+ }
+ } } });
+ expect(result.status).toBe('completed');
+}), 180_000);
+
+test('9. an unexhausted managed-sync cursor refuses sync_in_progress with its resume command and no fence', () => each(async f => {
+ f.push('alpha/two.md', page('Alpha two', 'Upstream.'));
+ const key = `test-cursor-${randomUUID()}`;
+ await f.engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES('managed-sync',$1,$2::text::jsonb)`,
+ [key, JSON.stringify([{ sourceId: f.beta, done: false, processingOptions: { noEmbed: true, noExtract: false, noSchemaPack: false },
+ syncOptions: { full: false, workingTree: false, srcSubpath: null, exclude: [], includeHidden: [], strategy: null } }])]);
+ try {
+ const error = await refusedWith(refreshWorktree(f.engine, f.alpha), 'sync_in_progress');
+ expect(error.suggestion).toContain(`gbrain sync --source ${f.beta} --no-pull --no-embed`);
+ expect(error.suggestion).not.toContain('--retry-failed');
+ expect(await f.refreshRows()).toEqual([]);
+ } finally { await f.engine.executeRaw(`DELETE FROM op_checkpoints WHERE op='managed-sync' AND fingerprint=$1`, [key]); }
+}), 120_000);
+
+test('10. source add and remove on the worktree during a refresh refuse refresh_in_progress', () => each(async f => {
+ f.push('alpha/two.md', page('Alpha two', 'Upstream.'));
+ const result = await refreshWorktree(f.engine, f.alpha, { hooks: { boundary: async point => {
+ if (point !== 'drained') return;
+ const add = await refusedWith(runManagedSourceLifecycle(f.engine, { operation: 'add', sourceId: `gamma-${randomUUID().slice(0, 6)}`, path: join(f.root, 'alpha') }), 'refresh_in_progress');
+ expect(add.suggestion).toContain('--resume');
+ await refusedWith(runManagedSourceLifecycle(f.engine, { operation: 'remove', sourceId: f.beta, confirmDestructive: true }), 'refresh_in_progress');
+ await refusedWith(refreshWorktree(f.engine, f.beta), 'refresh_in_progress');
+ } } });
+ expect(result.status).toBe('completed');
+}), 180_000);
+
+test('11. end to end: a new upstream commit, `gbrain sources refresh --json`, then query finds it', () => each(async f => {
+ f.push('beta/zebra.md', page('Zebra', 'A zebracorn observation pushed upstream.'));
+ const out: string[] = [];
+ const log = console.log;
+ _resetCliExitVerdictForTests();
+ console.log = (line: string) => { out.push(line); };
+ try { await runSourcesRefresh(f.engine, [f.beta, '--json']); } finally { console.log = log; }
+ const printed = JSON.parse(out.join('\n'));
+ expect(printed).toMatchObject({ status: 'completed', target_head: f.head() });
+ expect(currentExitCode()).toBe(0);
+ const query = operations.find(op => op.name === 'query')!;
+ const ctx = { ...f.ctx(f.beta), sourceId: f.beta };
+ expect(JSON.stringify(await query.handler(ctx as never, { query: 'zebracorn', limit: 5, expand: false }))).toContain('zebra');
+ const [observed] = await f.engine.executeRaw<{ upstream_commit: string; upstream_behind: number }>('SELECT upstream_commit,upstream_behind FROM sources WHERE id=$1', [f.beta]);
+ expect(observed).toEqual({ upstream_commit: f.head(), upstream_behind: 0 });
+}), 180_000);
+
+test('12. an unmanaged brain refuses refresh_not_managed naming gbrain sync, on stdout with exit 1', () => each(async f => {
+ await f.engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ try {
+ await refusedWith(refreshWorktree(f.engine, f.alpha), 'refresh_not_managed').then(error => expect(error.suggestion).toBe(`gbrain sync --source ${f.alpha}`));
+ const out: string[] = [];
+ const log = console.log;
+ _resetCliExitVerdictForTests();
+ console.log = (line: string) => { out.push(line); };
+ try { await runSourcesRefresh(f.engine, [f.alpha, '--json']); } finally { console.log = log; }
+ expect(JSON.parse(out.join('\n'))).toMatchObject({ status: 'refused', code: 'refresh_not_managed', fix: `gbrain sync --source ${f.alpha}`,
+ docs: 'docs/guides/write-refusals.md#refresh_not_managed' });
+ expect(currentExitCode()).toBe(1);
+ _resetCliExitVerdictForTests();
+ } finally { await f.engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1'); }
+}), 120_000);
+
+test('13. drain starvation: a writer every 50 ms is refused during draining and the refresh completes inside --wait-drain', () => each(async f => {
+ const target = f.push('alpha/two.md', page('Alpha two', 'Upstream.'));
+ await f.put(f.alpha, 'notes/seed', page('Seed', 'Has a git effect.'));
+ await requeueGitEffect(f, 1000);
+ let stop = false;
+ const outcomes: string[] = [];
+ const writer = (async () => {
+ while (!stop) {
+ try { await f.put(f.alpha, `notes/w-${randomUUID().slice(0, 8)}`, page('W', 'steady traffic')); outcomes.push('accepted'); }
+ catch (error) { outcomes.push((error as { code?: string }).code ?? 'error'); }
+ await new Promise(resolve => setTimeout(resolve, 50));
+ }
+ })();
+ let result;
+ try {
+ await new Promise(resolve => setTimeout(resolve, 120));
+ result = await refreshWorktree(f.engine, f.alpha, { waitDrainMs: 15_000 });
+ } finally { stop = true; await writer; }
+ expect(result.status).toBe('completed');
+ expect(result.target_head).toBe(target);
+ expect(outcomes.filter(code => code === 'worktree_refreshing').length).toBeGreaterThan(3);
+ expect(existsSync(join(f.root, 'alpha/two.md'))).toBe(true);
+}), 180_000);