Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
test(barrier): kill-and-resume with a deferred write, --check-downgrade exit 3, revoked-token recheck
garrytan2fe6cb391eae
diff --git a/test/refresh-write-barrier.test.ts b/test/refresh-write-barrier.test.tsindex bf9907c962..6588113d02 100644--- a/test/refresh-write-barrier.test.ts+++ b/test/refresh-write-barrier.test.ts@@ -6,11 +6,15 @@* refresh ends it commits, unless the refresh changed its file, which ends it `revision_conflict` with nothing applied;* a consumer claim without the barrier's session declaration (an older binary) cannot move a deferred row; a replay of the* request id returns the same receipt; a write past the wait limit ends `refresh_barrier_expired` with its counters- * released; past the per-refresh cap a further write keeps the refusal; a live consumer without the capability keeps the- * refusal; a repo-less source is never deferred.+ * released; a token revoked while its write waits ends it `permission_denied`; past the per-refresh cap a further write keeps the refusal; a live consumer without the capability keeps the+ * refusal; a repo-less source is never deferred; `gbrain upgrade --check-downgrade` exits 3 while a deferred write waits.* Seams: the real refresh state machine paused at its drained boundary (`hooks.boundary`); GBRAIN_REFRESH_BARRIER.*/-import { afterAll, afterEach, beforeAll, beforeEach, expect, test } from 'bun:test';+import { afterAll, afterEach, beforeAll, beforeEach, expect, spyOn, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { run as runUpgradeCommand } from '../src/cli/commands/upgrade.ts';+import { mintLegacyToken } from '../src/core/token-mint.ts';+import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';import type { BrainEngine } from '../src/core/engine.ts';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { dispatchToolCall } from '../src/mcp/dispatch.ts';@@ -221,6 +225,52 @@ test('past persistence.refresh_barrier_max_deferred a further write during the r}}), 180_000);+test('gbrain upgrade --check-downgrade exits 3 downgrade_blocked_deferred_writes while a deferred write waits, 0 once it drained', () => each(async f => {+ const engine = new Proxy(f.engine, { get: (target, key) => key === 'disconnect' ? async () => undefined : Reflect.get(target, key, target) });+ const check = async () => {+ _resetCliExitVerdictForTests();+ const errors: string[] = []; const errorSpy = spyOn(console, 'error').mockImplementation((...a: unknown[]) => { errors.push(a.map(String).join(' ')); });+ const writes: string[] = []; const stderrSpy = spyOn(process.stderr, 'write').mockImplementation(((chunk: unknown) => { writes.push(String(chunk)); return true; }) as never);+ const logs: string[] = []; const logSpy = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { logs.push(a.map(String).join(' ')); });+ try { await runUpgradeCommand(['--check-downgrade', '--json'], { connectEngine: async () => engine } as never); }+ finally { errorSpy.mockRestore(); stderrSpy.mockRestore(); logSpy.mockRestore(); }+ const code = currentExitCode(); _resetCliExitVerdictForTests(); process.exitCode = 0;+ return { code, out: [...errors, ...writes, ...logs].join('\n') };+ };+ let deferred!: WriteRequest;+ const refresh = await duringRefresh(f, async () => {+ const out = await call(f, 'put_page', { slug: 'notes/downgrade', content: page('Downgrade', 'waits') });+ deferred = await requestRow(f, out.body.request_id);+ const blocked = await check();+ expect(blocked.code).toBe(3);+ expect(blocked.out).toContain('downgrade_blocked_deferred_writes');+ });+ expect((await refresh).status).toBe('completed');+ expect((await settle(f, deferred)).state).toBe('committed');+ const clear = await check();+ expect(clear.code).toBe(0);+ expect(JSON.parse(clear.out)).toEqual({ ok: true, deferred: 0 });+}), 180_000);++test('a deferred write whose token is revoked while it waits ends permission_denied with nothing applied', () => each(async f => {+ const minted = await mintLegacyToken(f.engine, { name: `token-${randomUUID()}`, scopes: ['read', 'write'], sourceGrant: [f.alpha], takesHolders: ['world'] });+ let deferred!: WriteRequest;+ const refresh = await duringRefresh(f, async () => {+ const result = await dispatchToolCall(f.engine, 'put_page', { slug: 'notes/revoked', content: page('Revoked', 'never applied') }, { remote: true, transport: 'http', sourceId: f.alpha,+ admissionOrigin: 'interactive', takesHoldersAllowList: ['world'],+ auth: { token: '', clientId: minted.id, principal: { kind: 'legacy_token', id: minted.id }, sourceId: f.alpha, allowedSources: [f.alpha], scopes: ['read', 'write'] } } as never);+ const body = JSON.parse(result.content[0]!.text) as Record<string, any>;+ expect(body.status).toBe('pending');+ deferred = await requestRow(f, body.request_id);+ expect(deferred.state).toBe('deferred');+ await f.engine.executeRaw('UPDATE access_tokens SET revoked_at=now() WHERE id=$1', [minted.id]);+ });+ expect((await refresh).status).toBe('completed');+ expect(await settle(f, deferred)).toMatchObject({ state: 'failed', error_code: 'permission_denied' });+ const [{ n }] = await f.engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM pages WHERE source_id=$1 AND slug=$2', [f.alpha, 'notes/revoked']);+ expect(Number(n)).toBe(0);+}), 180_000);+test('with the barrier off a write during a refresh is still refused worktree_refreshing', () => each(async f => {process.env.GBRAIN_REFRESH_BARRIER = '0'; resetWriteSwitches();const refresh = await duringRefresh(f, async () => {diff --git a/test/worktree-refresh-orphan-7679.test.ts b/test/worktree-refresh-orphan-7679.test.tsindex 96ee14ac82..b7fec8d412 100644--- a/test/worktree-refresh-orphan-7679.test.ts+++ b/test/worktree-refresh-orphan-7679.test.ts@@ -7,7 +7,8 @@* `--resume` path, then refreshes; owner recovery completes an orphaned* `syncing` row once its members synced to the target or a descendant of it;* writer status and sync status name the recorded holder, whether it is- * orphaned, and a fix naming `--resume`.+ * orphaned, and a fix naming `--resume`; with the PR B barrier on, a write deferred behind the orphan commits once+ * the next refresh finishes it.* Regression it catches: every scheduled refresh refusing `refresh_in_progress`* forever after a crash (and every page write to the worktree refusing* `worktree_refreshing`), owner recovery skipping `syncing` rows, status that@@ -29,7 +30,11 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { printRefreshOutcome, runSourcesRefresh } from '../src/commands/sources-refresh.ts';import { _resetCliExitVerdictForTests } from '../src/core/cli-force-exit.ts';import { runPersistenceAdministration } from '../src/core/persistence/administration.ts';-import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { disposePersistenceConsumer, waitForWrite } from '../src/core/persistence/service.ts';+import { getWriteRequestById } from '../src/core/persistence/journal.ts';+import { resetWriteSwitches } from '../src/core/persistence/switches.ts';+import type { WriteRequest } from '../src/core/persistence/model.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';import { readSyncStatus } from '../src/core/persistence/sync-status.ts';import { performManagedSync } from '../src/core/persistence/sync-run.ts';import { refreshWorktree, resumeWorktreeRefreshes } from '../src/core/persistence/worktree-refresh.ts';@@ -131,6 +136,28 @@ test('#7679: a refresh killed mid-syncing is reported orphaned with its holder,});}, 300_000);+test('PR B: a write deferred behind a refresh whose process was killed commits once the next refresh finishes the orphan', async () => {+ for (const item of cases) await withKilledRefresh(item, async ({ f, orphan }) => {+ await withEnv({ GBRAIN_REFRESH_BARRIER: '1' }, async () => {+ resetWriteSwitches();+ try {+ const result = await dispatchToolCall(f.engine, 'put_page', { slug: 'notes/deferred-past-kill', content: page('Deferred past a kill', 'admitted while the refresh was orphaned') },+ { remote: true, transport: 'stdio', sourceId: f.beta, admissionOrigin: 'interactive' });+ const body = JSON.parse(result.content[0]!.text) as Record<string, any>;+ expect(result.isError === true).toBe(false);+ expect(body).toMatchObject({ status: 'pending', deferred: { refresh_id: orphan.id } });+ const [row] = await f.engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE request_id=$1::uuid', [body.request_id]);+ expect(row!.state).toBe('deferred');+ expect(await refreshWorktree(f.engine, f.alpha)).toMatchObject({ recovered: { refresh_id: orphan.id, state: 'completed' } });+ const done = await waitForWrite(f.engine, (await getWriteRequestById(f.engine, row!.id))!, { engine: f.engine.kind } as never, 30_000);+ expect(done.state).toBe('committed');+ const [{ n }] = await f.engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [f.beta, 'notes/deferred-past-kill']);+ expect(Number(n)).toBe(1);+ } finally { resetWriteSwitches(); }+ });+ });+}, 300_000);+test('#7679: owner recovery completes an orphaned syncing refresh once every member synced past its target, and leaves one whose members lag', async () => {for (const item of cases) await withKilledRefresh(item, async ({ f, target, orphan }) => {expect(await resumeWorktreeRefreshes(f.engine)).toBe(0);