diff --git a/scripts/examples/research-cycle.ts b/scripts/examples/research-cycle.ts index d47ae479..ecc7e651 100644 --- a/scripts/examples/research-cycle.ts +++ b/scripts/examples/research-cycle.ts @@ -207,7 +207,11 @@ export async function runResearchCycle( error: error instanceof Error ? error.message : String(error), uncertain: error instanceof ResearchRequestError ? error.uncertain : true, }; - await options.onEvent(stopped); + try { + await options.onEvent(stopped); + } catch (journalError) { + throw new ResearchCycleStopped(stopped, journalError); + } throw new ResearchCycleStopped(stopped, error); } } @@ -495,11 +499,20 @@ if (import.meta.main) { 2 ) ); - } finally { - await journal.close(); + } catch (error) { + // An acknowledged resource can be recoverable only through the primary error. + await journal.close().catch(() => undefined); + throw error; } + await journal.close(); } catch (error) { - console.error(error instanceof Error ? error.message : String(error)); + console.error( + error instanceof ResearchCycleStopped + ? JSON.stringify({ error: error.message, event: error.event }) + : error instanceof Error + ? error.message + : String(error) + ); process.exitCode = 1; } } diff --git a/scripts/test/fixtures/research-cycle-cli-preload.ts b/scripts/test/fixtures/research-cycle-cli-preload.ts new file mode 100644 index 00000000..5519ee83 --- /dev/null +++ b/scripts/test/fixtures/research-cycle-cli-preload.ts @@ -0,0 +1,71 @@ +/** Child-process-only fault injection. No network, database or strategy execution. */ +import { appendFileSync, readFileSync } from 'node:fs'; +import * as filesystem from 'node:fs/promises'; +import { mock } from 'bun:test'; + +const path = process.env.RESEARCH_CYCLE_CLI_FIXTURE; +if (!path) { + throw new Error('Research CLI fixture path is required'); +} +const fixture: { + fault: 'accepted-write' | 'accepted-sync' | 'stopped-write' | 'intent-write' | 'none'; + closeFailure: boolean; + receiptsPath: string; + requestsPath: string; + budget: unknown; + hypothesis: unknown; +} = JSON.parse(readFileSync(path, 'utf8')); +const originalOpen = filesystem.open; +mock.module('node:fs/promises', () => ({ + ...filesystem, + open: async (...args: Parameters) => { + const file = await originalOpen(...args); + if (String(args[0]) !== fixture.receiptsPath) { + return file; + } + const write = file.writeFile.bind(file); + const sync = file.sync.bind(file); + const close = file.close.bind(file); + let writes = 0; + file.writeFile = async (...input) => { + writes++; + if ( + (writes === 1 && fixture.fault === 'intent-write') || + (writes === 2 && ['accepted-write', 'stopped-write'].includes(fixture.fault)) + ) { + throw new Error('Injected journal write failure'); + } + return write(...input); + }; + file.sync = async () => { + if (writes === 2 && fixture.fault === 'accepted-sync') { + throw new Error('Injected journal sync failure'); + } + return sync(); + }; + file.close = async () => { + await close(); + if (fixture.closeFailure) { + throw new Error('Injected journal close failure'); + } + }; + return file; + }, +})); + +globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => { + const pathname = new URL(String(input)).pathname; + appendFileSync( + fixture.requestsPath, + JSON.stringify({ pathname, method: init?.method, body: init?.body }) + '\n' + ); + if (pathname === '/api/v2/research-agent/budget') { + return Response.json(fixture.budget); + } + if (/^\/api\/v2\/research-projects\/[a-f0-9-]+\/hypotheses$/.test(pathname)) { + return fixture.fault === 'stopped-write' + ? Response.json({ error: 'Fixture admission refused' }, { status: 429 }) + : Response.json({ hypothesis: fixture.hypothesis }, { status: 201 }); + } + throw new Error(`Unexpected research CLI request: ${pathname}`); +}) as typeof fetch; diff --git a/scripts/test/research-cycle.test.ts b/scripts/test/research-cycle.test.ts index 4a3bcb75..444a6335 100644 --- a/scripts/test/research-cycle.test.ts +++ b/scripts/test/research-cycle.test.ts @@ -1,3 +1,7 @@ +import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; import { describe, expect, test } from 'bun:test'; import { walkForwardDataset } from '../../test/fixtures/walk-forward'; import { tableFixture } from '../benchmark-experiment-tables'; @@ -228,3 +232,158 @@ describe('bounded executable research cycle', () => { expect(f.calls).toHaveLength(2); }); }); + +describe('research cycle CLI recovery output', () => { + const repository = fileURLToPath(new URL('../..', import.meta.url)); + const credential = 'sb-research.fixture-cli-secret-never-print'; + const acceptedHypothesis = () => ({ + id: '33333333-3333-4333-8333-333333333333', + projectId, + latestRevision: { + id: '44444444-4444-4444-8444-444444444444', + ordinal: 1, + ...plan().hypothesis, + contentOrigin: 'ai', + submittedBy: budget().agent.id, + validationState: 'unvalidated', + }, + }); + async function invoke( + fault: 'accepted-write' | 'accepted-sync' | 'stopped-write' | 'intent-write' | 'none', + closeFailure = false, + existingJournal = false + ) { + const directory = await mkdtemp(join(tmpdir(), 'stock-bot-cycle-cli-')); + try { + const planPath = join(directory, 'plan.json'); + const receiptsPath = join(directory, 'receipts.jsonl'); + const requestsPath = join(directory, 'requests.jsonl'); + const fixturePath = join(directory, 'fixture.json'); + await writeFile(planPath, JSON.stringify(plan())); + await writeFile(requestsPath, ''); + if (existingJournal) { + await writeFile(receiptsPath, 'existing journal must remain unchanged\n'); + } + await writeFile( + fixturePath, + JSON.stringify({ + fault, + closeFailure, + receiptsPath, + requestsPath, + budget: budget(), + hypothesis: acceptedHypothesis(), + }) + ); + const child = Bun.spawn( + [ + process.execPath, + '--preload', + 'scripts/test/fixtures/research-cycle-cli-preload.ts', + 'scripts/examples/research-cycle.ts', + '--plan', + planPath, + '--receipts', + receiptsPath, + ], + { + cwd: repository, + env: { + ...process.env, + RESEARCH_API_ORIGIN: 'http://127.0.0.1:2003', + RESEARCH_API_TOKEN: credential, + RESEARCH_CYCLE_CLI_FIXTURE: fixturePath, + }, + stdout: 'pipe', + stderr: 'pipe', + } + ); + const [status, stdout, stderr] = await Promise.all([ + child.exited, + new Response(child.stdout).text(), + new Response(child.stderr).text(), + ]); + return { + status, + stdout, + stderr, + receipts: await readFile(receiptsPath, 'utf8'), + requests: (await readFile(requestsPath, 'utf8')) + .split('\n') + .filter(Boolean) + .map(line => JSON.parse(line) as { pathname: string; method: string; body?: string }), + }; + } finally { + await rm(directory, { recursive: true, force: true }); + } + } + const originalIntent = () => ({ + cycleId: plan().cycleId, + candidateKey: null, + operation: 'create-hypothesis', + phase: 'intent', + key: null, + input: { ...plan().hypothesis, contentOrigin: 'ai' }, + resourceId: projectId, + }); + test.each([ + ['accepted-write', false], + ['accepted-sync', false], + ['accepted-write', true], + ['accepted-sync', true], + ] as const)('%s failure retains the exact receipt (close fails: %s)', async (fault, closeFailure) => { + const result = await invoke(fault, closeFailure); + expect(result.status).toBe(1); + expect(result.stdout).toBe(''); + const recovery = JSON.parse(result.stderr); + const accepted = { ...originalIntent(), phase: 'accepted', result: acceptedHypothesis() }; + expect(recovery.event).toEqual(accepted); + expect(recovery.error).toContain('stopped at create-hypothesis'); + const retained = result.receipts.trim().split('\n').map(line => JSON.parse(line)); + expect(retained[0]).toEqual(originalIntent()); + expect(retained).toHaveLength(fault === 'accepted-write' ? 1 : 2); + if (fault === 'accepted-sync') { + expect(retained[1]).toEqual(accepted); + } + expect(result.requests.map(request => [request.method, request.pathname])).toEqual([ + ['GET', '/api/v2/research-agent/budget'], + ['POST', `/api/v2/research-projects/${projectId}/hypotheses`], + ]); + expect(JSON.parse(result.requests[1]!.body!)).toEqual(originalIntent().input); + expect(result.stderr + result.stdout + result.receipts).not.toContain(credential); + }); + test('a rejected request and failed stopped-event write preserve rejection without claiming acceptance', async () => { + const result = await invoke('stopped-write', true); + expect(result.status).toBe(1); + expect(result.stdout).toBe(''); + expect(JSON.parse(result.stderr).event).toEqual({ + ...originalIntent(), + phase: 'stopped', + error: 'Fixture admission refused', + uncertain: false, + }); + expect(JSON.parse(result.receipts)).toEqual(originalIntent()); + expect(result.requests).toHaveLength(2); + expect(result.stderr).not.toContain(acceptedHypothesis().id); + expect(result.stderr + result.stdout + result.receipts).not.toContain(credential); + }); + test('an intent write failure stays an ordinary error and prevents the mutation even if close fails', async () => { + const result = await invoke('intent-write', true); + expect(result.status).toBe(1); + expect(result.stdout).toBe(''); + expect(result.stderr.trim()).toBe('Injected journal write failure'); + expect(result.receipts).toBe(''); + expect(result.requests.map(request => request.method)).toEqual(['GET']); + expect(result.stderr).not.toContain(credential); + }); + test('an existing journal is never overwritten or treated as a new cycle', async () => { + const result = await invoke('none', false, true); + expect(result.status).toBe(1); + expect(result.stdout).toBe(''); + expect(result.stderr).toContain('EEXIST'); + expect(result.stderr).not.toContain('"event"'); + expect(result.receipts).toBe('existing journal must remain unchanged\n'); + expect(result.requests).toEqual([]); + expect(result.stderr).not.toContain(credential); + }); +});