/** Real authenticated APIs + disposable PostgreSQL + isolated candidate/Rust execution. No finance mocks. */ import { createHash, randomUUID } from 'node:crypto'; import { readFileSync } from 'node:fs'; import { afterEach, describe, expect, test } from 'bun:test'; import { Hono } from 'hono'; import { Pool } from 'pg'; import { createHttpSecurity } from '@stock-bot/di'; import { getLogger, setLoggerConfig } from '@stock-bot/logger'; import { PostgreSQLClient } from '@stock-bot/postgres'; import type { StrategyVersionPackage } from '@stock-bot/types'; import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner'; import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository'; import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter'; import { createExperimentRoutes } from '../../apps/stock/web-api/src/routes/experiments.routes'; import { createResearchAgentRoutes } from '../../apps/stock/web-api/src/routes/research-agents.routes'; import { createResearchRoutes } from '../../apps/stock/web-api/src/routes/research.routes'; import { createStrategyRoutes } from '../../apps/stock/web-api/src/routes/strategies.routes'; import { ResearchAgentsService } from '../../apps/stock/web-api/src/services/research-agents.service'; import { ResearchService } from '../../apps/stock/web-api/src/services/research.service'; import { runResearchCycle, type ResearchCycleEvent, type ResearchCyclePlan, } from '../../scripts/examples/research-cycle'; import { retainResearchDataset } from '../../scripts/import-research-dataset'; import { packageBuiltinStrategies } from '../../scripts/package-builtin-strategies'; import { ResearchClient } from '../../scripts/research-client'; import { canonicalAdmissionFixture } from '../fixtures/canonical-admission'; import { canonicalRegimeSelection } from '../fixtures/canonical-regime-research'; import { walkForwardDataset } from '../fixtures/walk-forward'; setLoggerConfig({ logLevel: 'fatal', logConsole: false }); const logger = getLogger('ai-research-workflow'); const url = process.env.PIPELINE_TEST_DATABASE_URL; const cleanups: (() => Promise)[] = []; afterEach(async () => { for (const close of cleanups.splice(0).reverse()) { await close(); } }); let packages: ReturnType | undefined; async function fixture() { if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) { throw new Error('Disposable safety database required'); } const schema = `stock_bot_safety_ai_cycle_${randomUUID().replaceAll('-', '')}`; const admin = new Pool({ connectionString: url }); await admin.query(`CREATE SCHEMA ${schema}`); const pool = new Pool({ connectionString: url, max: 4, options: `-c search_path=${schema} -c statement_timeout=10000`, }); cleanups.push(async () => { await pool.end(); await admin.query(`DROP SCHEMA ${schema} CASCADE`); await admin.end(); }); const postgres = new PostgreSQLClient( { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, logger ); Object.defineProperty(postgres, 'connectionPool', { get: () => pool }); const base = await canonicalAdmissionFixture(pool, postgres); for (const name of [ '20-research-workspace.sql', '27-research-evidence-sources.sql', '28-research-agents.sql', '29-isolated-candidates.sql', '31-research-agent-project-links.sql', '32-candidate-parameter-defaults.sql', '33-candidate-decimal-normalization.sql', ]) { await pool.query( readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8') ); } const dataset = walkForwardDataset(); await retainResearchDataset(pool, dataset.dataset); const draft = await base.api.createBacktest( { ...base.definition, name: 'AI workflow granted source', startDate: new Date(dataset.dataset.manifest.bounds.tradeStart).toISOString(), endDate: new Date(dataset.dataset.manifest.bounds.tradeEnd).toISOString(), config: { ...base.definition.config, datasetHash: dataset.dataset.manifest.hash }, }, { autoStart: false } ); const container = { postgres, logger }; const agents = new ResearchAgentsService(container), research = new ResearchService(container); const project = await research.createProject({ title: 'AI research acceptance' }, 'operator'); const provisioned = await agents.create({ name: 'Workflow researcher', allowedProjectIds: [project.id], allowedBacktestIds: [draft.id], allowOwnCandidateBacktestIds: [draft.id], limits: { maxActiveTrials: 4, maxTrialsPerExperiment: 4, maxBarEvaluationsPerExperiment: 10000, maxAttemptWallMs: 60000, maxAttempts: 1, }, }); const app = new Hono(); const security = createHttpSecurity({ adminToken: 'operator-test-secret-12345678901234567890', serviceToken: 'service-test-secret-123456789012345678901', environment: 'test', resolveResearchCredential: request => agents.authenticate(request), }); security.mount(app); app.route('/', createResearchAgentRoutes(container, security.researchEnabled)); app.route('/', createStrategyRoutes(container)); app.route('/', createResearchRoutes(container)); app.route('/', createExperimentRoutes(container)); const engine = new RustBacktestAdapter({ logger, }); const runner = new BacktestRunner({ engine, repository: new PostgresBacktestRunRepository(postgres), logger, }); const executionErrors: unknown[] = []; let pending = Promise.resolve(); // A small test worker drives the existing durable runner. It changes no engine/fill behavior. const drain = () => { pending = pending.then(async () => { for (const row of ( await pool.query<{ id: string }>( "SELECT id FROM runs WHERE status='pending' ORDER BY created_at,id" ) ).rows) { try { await runner.runQueued(row.id); } catch (error) { executionErrors.push(error); } } }); }; cleanups.push(async () => { await pending; await runner.shutdown(); await engine.shutdown(); }); const requests: { path: string; method: string; key: string | null; body: unknown; status: number; }[] = []; const transport: typeof fetch = (async (input: string | URL | Request, init?: RequestInit) => { const request = new Request(input, init); const body: unknown = request.body === null ? undefined : await request.clone().json(); const response = await app.fetch(request); requests.push({ path: new URL(request.url).pathname, method: request.method, key: request.headers.get('Idempotency-Key'), body, status: response.status, }); if (response.status === 202) { drain(); } return response; }) as typeof fetch; const client = new ResearchClient({ origin: 'http://127.0.0.1:2003', token: provisioned.token, fetch: transport, }); const prepared = await (packages ??= packageBuiltinStrategies()); function candidate(index: number): StrategyVersionPackage { const pkg = prepared[index]; if (!pkg) { throw new Error('Missing prepared fixture'); } return { ...structuredClone(pkg), execution: { kind: 'isolated-candidate/v1', warmupBars: 3 } }; } function suggestions(): ResearchCyclePlan { const trend = candidate(0), regime = candidate(1), failure = candidate(0); failure.artifact.content += '\nthrow new Error("Deliberate research candidate failure");\n'; failure.artifact.sha256 = createHash('sha256').update(failure.artifact.content).digest('hex'); const common = { recipe: dataset.windows[0]!, costScenarios: [{ feeRate: '0.02', slippageRate: '0.01' }], }; // Deterministic fake-model suggestions; bundles are inert input until the real isolated worker. return { cycleId: 'acceptance-cycle', projectId: project.id, backtestId: draft.id, maxTotalTrials: 16, hypothesis: { title: 'Trend and regime-aware mean reversion', proposition: 'These independent candidates may respond differently to the same market observations', validationCriteria: 'Train-only selection, held-out diagnostics, fixed cost scenarios; no fitted-model or profitable-strategy claim', }, candidates: [ { ...common, key: 'trend', name: 'Trend candidate', rationale: 'Short/long trend signals', package: trend, // Exercise default expansion throughout training, holdouts and saved evidence. parameters: { slowPeriod: 6 }, grid: { fastPeriod: [1, 2] }, }, { ...common, key: 'regime', name: 'Regime candidate', rationale: 'Mean reversion with momentum, trend, volume and volatility gates', package: regime, parameters: canonicalRegimeSelection().parameters, grid: {}, }, { ...common, key: 'broken', name: 'Broken candidate', rationale: 'Failure is evidence of implementation failure, not a zero return', package: failure, parameters: { fastPeriod: 2, slowPeriod: 3 }, grid: {}, }, ], }; } return { ...base, pool, agents, research, project, provisioned, app, client, requests, suggestions, executionErrors, transport, drain, }; } describe.skipIf(!url)('AI research workflow through authenticated APIs and Rust', () => { test('defaulted candidate validation accepts, reopens and replays the exact original input', async () => { const f = await fixture(); const plan = f.suggestions(); const family = await f.client.createStrategy({ name: 'Defaulted validation candidate', description: 'Omitted and partial parameter defaults', }); const version = await f.client.publishVersion( family.id, plan.candidates[0]!.package, 'defaults:version' ); const cases: { parameters: Record; normalized: Record }[] = [ { parameters: {}, normalized: { fastPeriod: 5, slowPeriod: 15 } }, { parameters: { slowPeriod: 6 }, normalized: { fastPeriod: 5, slowPeriod: 6 } }, ]; for (const [index, item] of cases.entries()) { const input = { backtestId: plan.backtestId, name: `Defaulted candidate ${index}`, candidate: { versionId: version.id, parameters: item.parameters }, grid: {}, recipe: plan.candidates[0]!.recipe, }; const preview = await f.client.previewValidation(input); expect(preview.input).toEqual(input); expect(preview.partitions[0].request.strategy.selection.parameters).toEqual(item.normalized); const submission = { ...preview.input, previewHash: preview.previewHash }; const key = `defaults:validation:${index}`; const saved = await f.client.submitValidation(submission, key); expect(saved.preview.input).toEqual(input); expect(saved.phases[0]!.experiment!.preview.input.candidate).toEqual({ versionId: version.id, parameters: item.normalized, }); const reopened = await f.client.waitForValidation(saved.id, { timeoutMs: 60000, intervalMs: 20, }); expect(reopened.previewHash).toBe(preview.previewHash); expect(reopened.preview.input).toEqual(input); expect(reopened.phases[0]!.experiment!.trials[0]!.status).toBe('completed'); const replayed = await f.client.submitValidation(submission, key); expect(replayed.id).toBe(saved.id); expect(replayed.previewHash).toBe(preview.previewHash); expect(replayed.phases[0]!.experiment!.trials[0]!.runId).toBe( reopened.phases[0]!.experiment!.trials[0]!.runId! ); const writes = f.requests.filter(request => request.key === key); expect(writes).toHaveLength(2); expect(writes[0]).toEqual(writes[1]!); expect(writes[0]!.body).toEqual(submission); expect(writes[0]!.status).toBe(202); } expect((await f.pool.query('SELECT count(*)::int AS count FROM runs')).rows[0].count).toBe(2); expect(f.executionErrors).toEqual([]); }, 60000); test('candidate revisions retain automatic and explicit lineage across delayed receipt replay', async () => { const f = await fixture(); const family = await f.client.createStrategy({ name: 'Refined candidate', description: 'Successive revisions and a delayed publication receipt', }); const pkg = f.suggestions().candidates[0]!.package; const first = await f.client.publishVersion(family.id, pkg, 'lineage:first'); expect(first).toMatchObject({ ordinal: 1, parentVersionId: null, createdBy: f.provisioned.agent.id, }); const second = await f.client.publishVersion(family.id, pkg, 'lineage:second'); expect(second).toMatchObject({ ordinal: 2, parentVersionId: first.id }); const third = await f.client.publishVersion(family.id, pkg, 'lineage:third', null); expect(third).toMatchObject({ ordinal: 3, parentVersionId: second.id }); // An explicit branch parent remains binding even when another version is latest. const branch = await f.client.publishVersion(family.id, pkg, 'lineage:branch', first.id); expect(branch).toMatchObject({ ordinal: 4, parentVersionId: first.id }); const replayed = await f.client.publishVersion(family.id, pkg, 'lineage:second'); expect(replayed).toEqual(second); const publications = f.requests.filter( request => request.path === `/api/v2/strategies/${family.id}/versions` ); expect(publications).toHaveLength(5); expect( publications.every(request => request.status === 201 && request.method === 'POST') ).toBeTrue(); expect(publications[1]).toEqual(publications[4]!); expect(publications[1]!.body).toEqual({ package: pkg, parentVersionId: null }); expect(publications[3]!.body).toEqual({ package: pkg, parentVersionId: first.id }); expect( ( await f.pool.query( 'SELECT count(*)::int AS count FROM strategy_versions WHERE strategy_id=$1', [family.id] ) ).rows[0].count ).toBe(4); expect((await f.pool.query('SELECT count(*)::int AS count FROM runs')).rows[0].count).toBe(0); expect(f.executionErrors).toEqual([]); }); test('two generated candidates, train-only selection, costs, exact saved evidence and a retained failure', async () => { const f = await fixture(); const events: ResearchCycleEvent[] = []; const result = await runResearchCycle(f.client, f.suggestions(), { onEvent: async event => { events.push(structuredClone(event)); }, poll: { timeoutMs: 60000, intervalMs: 20 }, }); expect(result.totalPlannedTrials).toBe(16); expect(result.outcomes).toHaveLength(3); expect(result.hypothesis.latestRevision.contentOrigin).toBe('ai'); expect(result.hypothesis.latestRevision.validationState).toBe('unvalidated'); expect(result.regimeAttribution).toContain('unavailable'); for (const outcome of result.outcomes.slice(0, 2)) { expect(outcome.stoppedReason).toBeNull(); expect( outcome.screening?.trials.every(trial => trial.status === 'completed' && trial.comparable) ).toBeTrue(); const report = outcome.validation?.report, selection = outcome.validation?.selection; if (!report || !selection || !outcome.costs) { throw new Error('Missing sealed native evidence'); } expect(outcome.validation?.preview.policy.model).toBe('unverified-candidate'); expect(selection.training.every(run => run.phase === 'train')).toBeTrue(); expect(report.test.phase).toBe('test'); expect(outcome.costs.trials).toHaveLength(2); for (const trial of outcome.costs.trials) { expect(trial.status).toBe('completed'); expect(trial.comparable).toBeTrue(); expect(trial.parameters).toEqual(selection.winner.parameters); } const finding = outcome.findings[0]!; expect(finding.latestRevision.source).toEqual({ kind: 'chronological-report/v1', validationId: outcome.validation!.id, previewHash: outcome.validation!.previewHash, reportId: report.id, reportHash: report.reportHash, }); expect(finding.latestRevision.evidence).toHaveLength(6); for (const evidence of finding.latestRevision.evidence) { const saved = await f.api.getRunResults(evidence.runId); if (!saved || !('kind' in saved) || saved.kind !== 'canonical-result/v1') { throw new Error('Missing native result'); } expect(saved.strategyExecution).toBe('typescript-isolated-candidate/v1'); expect(saved.request.strategy.versionId).toBe(outcome.versionId); expect(saved.request.strategy.package.artifact.sha256).toHaveLength(64); expect(evidence.datasetHash).toBe(saved.request.datasetHash); const metric = evidence.metricPath.slice('analytics.metrics.'.length) as | 'totalReturn' | 'maxDrawdown' | 'sharpeRatio'; expect(evidence.value).toBe(saved.analytics.metrics[metric]); expect(evidence.availability).toBe(evidence.value === null ? 'unavailable' : 'available'); if (evidence.value === null) { expect(evidence.unavailableReason).toBeTruthy(); } } } const broken = result.outcomes[2]!; expect(broken.screening?.trials[0]?.status).toBe('failed'); expect(broken.screening?.trials[0]?.metrics).toBeNull(); expect(broken.screening?.trials[0]?.error).toContain('Deliberate research candidate failure'); expect(broken.validation?.report).toBeNull(); expect(broken.validation?.selection).toBeNull(); expect( broken.validation?.phases.slice(1).every(phase => phase.status === 'not-admitted') ).toBeTrue(); expect(broken.findings).toEqual([]); expect(broken.stoppedReason).toContain('failed'); expect(result.comparison?.rows).toHaveLength(4); expect(result.comparison?.selection.leftId).toBe(result.outcomes[0]!.costs!.id); expect(result.comparison?.selection.rightId).toBe(result.outcomes[1]!.costs!.id); expect( events.filter(event => event.phase === 'accepted' && event.operation === 'submit-training') ).toHaveLength(3); const keyed = events.filter(event => event.phase === 'intent' && event.key); expect(new Set(keyed.map(event => event.key)).size).toBe(keyed.length); expect( keyed.every( event => f.requests.some( request => request.key === event.key && JSON.stringify(request.body) === JSON.stringify(event.input) ) || event.operation === 'publish-version' ) ).toBeTrue(); expect( f.requests.some(request => /\/(?:paper(?:-deployments)?|deployments|live|reviews)(?:\/|$)/.test(request.path) ) ).toBeFalse(); expect((await f.pool.query('SELECT count(*)::int AS count FROM runs')).rows[0].count).toBe(12); const accepted = events.find( event => event.operation === 'submit-training' && event.phase === 'intent' )!; const before = (await f.pool.query('SELECT count(*)::int AS count FROM runs')).rows[0].count; const replay = await f.client.submitValidation( accepted.input as Parameters[0], accepted.key! ); expect(replay.id).toBe(result.outcomes[0]!.validation!.id); expect((await f.pool.query('SELECT count(*)::int AS count FROM runs')).rows[0].count).toBe( before ); const reopened = await f.client.validation(result.outcomes[0]!.validation!.id); expect(reopened.report).toEqual(result.outcomes[0]!.validation!.report); // A comparison across candidates has no single aggregate report attachment. // Each reference must still resolve to its exact retained native result. const comparisonInput = { kind: 'finding' as const, title: 'Cross-candidate observations', body: 'AI-generated comparison, unvalidated; no comparability or profitability claim.', hypothesisRevisionId: result.hypothesis.latestRevision.id, evidence: result.outcomes.slice(0, 2).map(outcome => ({ runId: outcome.validation!.report!.test.runId, strategyVersionId: outcome.versionId, metricsVersion: 'canonical-analytics/v1' as const, metricPath: 'analytics.metrics.totalReturn' as const, })), }; expect(new Set(comparisonInput.evidence.map(item => item.strategyVersionId)).size).toBe(2); for (const source of [null, undefined]) { const finding = await f.client.saveFinding(f.project.id, { ...comparisonInput, source }); expect(finding.latestRevision).toMatchObject({ source: null, contentOrigin: 'ai', submittedBy: f.provisioned.agent.id, validationState: 'unvalidated', evidenceState: 'referenced', }); expect(finding.latestRevision.evidence).toHaveLength(2); const savedInput = f.requests.at(-1)!.body as Record; expect(Object.hasOwn(savedInput, 'source')).toBe(source === null); expect(savedInput.evidence).toEqual(comparisonInput.evidence); for (const reference of finding.latestRevision.evidence) { const native = await f.api.getRunResults(reference.runId); if (!native || !('kind' in native) || native.kind !== 'canonical-result/v1') { throw new Error('Missing native comparison evidence'); } expect(reference.strategyVersionId).toBe(native.request.strategy.versionId); expect(reference.datasetHash).toBe(native.request.datasetHash); expect(reference.value).toBe(native.analytics.metrics.totalReturn); } const response = await f.transport( `http://127.0.0.1:2003/api/v2/analysis-artifacts/${finding.id}`, { headers: { Authorization: `Bearer ${f.provisioned.token}` } } ); expect(response.status).toBe(200); const retained = (await response.json()).artifact; expect(retained.latestRevision.id).toBe(finding.latestRevision.id); expect(retained.latestRevision.source).toBeNull(); expect(retained.latestRevision.evidence).toMatchObject(finding.latestRevision.evidence); expect(retained.latestRevision.validationState).toBe('unvalidated'); } const artifactsBeforeRefusals = ( await f.pool.query('SELECT count(*)::int AS count FROM analysis_artifacts') ).rows[0].count; const reference = comparisonInput.evidence[0]!; for (const invalid of [ { ...reference, strategyVersionId: result.outcomes[1]!.versionId }, { ...reference, runId: randomUUID() }, { ...reference, runId: broken.screening!.trials[0]!.runId!, strategyVersionId: broken.versionId, }, ]) { await expect( f.client.saveFinding(f.project.id, { ...comparisonInput, source: null, evidence: [invalid], }) ).rejects.toMatchObject({ status: 422, uncertain: false }); } await expect( f.client.saveFinding(randomUUID(), { ...comparisonInput, source: null }) ).rejects.toMatchObject({ status: 403, uncertain: false }); expect( (await f.pool.query('SELECT count(*)::int AS count FROM analysis_artifacts')).rows[0].count ).toBe(artifactsBeforeRefusals); expect((await f.pool.query('SELECT count(*)::int AS count FROM runs')).rows[0].count).toBe( before ); }, 180000); test('real quota refusal and oversized search create no runs; nonmember evidence cannot become a finding', async () => { const f = await fixture(), plan = f.suggestions(); const hypothesis = await f.client.createHypothesis(f.project.id, plan.hypothesis); const family = await f.client.createStrategy({ name: 'Bounded candidate', description: 'Budget adversary', }); const version = await f.client.publishVersion( family.id, plan.candidates[0]!.package, 'bounded-version' ); const input = { backtestId: plan.backtestId, name: 'Exceeds admission', candidate: { versionId: version.id, parameters: { fastPeriod: 2, slowPeriod: 10 } }, grid: { fastPeriod: [1, 2, 3, 4, 5] }, }; const overBudget = await f.client.previewExperiment(input); await expect( f.client.submitExperiment( { ...overBudget.input, previewHash: overBudget.previewHash }, 'over-budget' ) ).rejects.toMatchObject({ status: 429, uncertain: false, }); expect(() => f.client.previewExperiment({ ...input, grid: { fastPeriod: Array.from({ length: 101 }, (_, i) => i + 1) }, }) ).toThrow(); expect((await f.pool.query('SELECT count(*)::int AS count FROM runs')).rows[0].count).toBe(0); const good = await f.client.previewExperiment({ ...input, grid: {} }); const admitted = await f.client.submitExperiment( { ...good.input, previewHash: good.previewHash }, 'bounded-admitted' ); const complete = await f.client.waitForExperiment(admitted.id, { timeoutMs: 60000, intervalMs: 20, }); expect(complete.trials[0]?.status).toBe('completed'); const evidence = { kind: 'finding' as const, title: 'Incorrect evidence', body: 'Must not be retained', hypothesisRevisionId: hypothesis.latestRevision.id, source: { kind: 'experiment/v1' as const, experimentId: admitted.id, previewHash: admitted.previewHash, }, evidence: [ { runId: randomUUID(), strategyVersionId: version.id, metricsVersion: 'canonical-analytics/v1' as const, metricPath: 'analytics.metrics.totalReturn' as const, }, ], }; await expect(f.client.saveFinding(f.project.id, evidence)).rejects.toMatchObject({ uncertain: false, }); expect( (await f.pool.query('SELECT count(*)::int AS count FROM analysis_artifacts')).rows[0].count ).toBe(0); const wrongVersion = { ...evidence, evidence: [ { ...evidence.evidence[0]!, runId: complete.trials[0]!.runId!, strategyVersionId: f.version.id, }, ], }; await expect(f.client.saveFinding(f.project.id, wrongVersion)).rejects.toMatchObject({ uncertain: false, }); }, 60000); });