stock-bot/scripts/test/fixtures/research-cycle-cli-preload.ts

71 lines
2.4 KiB
TypeScript

/** 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<typeof originalOpen>) => {
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;