908 lines
37 KiB
TypeScript
908 lines
37 KiB
TypeScript
/** 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 { createBacktestV2Routes } from '../../apps/stock/web-api/src/routes/backtests-v2.routes';
|
|
import { createDatasetRoutes } from '../../apps/stock/web-api/src/routes/datasets.routes';
|
|
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 { createResearchServices } from '../../apps/stock/web-api/src/services/research-services';
|
|
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<void>)[] = [];
|
|
afterEach(async () => {
|
|
for (const close of cleanups.splice(0).reverse()) {
|
|
await close();
|
|
}
|
|
});
|
|
let packages: ReturnType<typeof packageBuiltinStrategies> | 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 = createResearchServices(container).research;
|
|
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));
|
|
app.route('/', createBacktestV2Routes(container));
|
|
app.route('/', createDatasetRoutes(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('hypothesis reads retain original questions, human revisions and archival without writes', async () => {
|
|
const f = await fixture();
|
|
const created = await f.client.createHypothesis(f.project.id, f.suggestions().hypothesis);
|
|
const original = (await f.research.getHypothesis(created.id)).latestRevision;
|
|
const revised = await f.research.reviseHypothesis(
|
|
created.id,
|
|
{
|
|
expectedRevision: original.ordinal,
|
|
title: 'Human follow-up question',
|
|
proposition: 'A changed proposition is not the original research question.',
|
|
validationCriteria: 'Additional validation remains necessary.',
|
|
contentOrigin: 'human',
|
|
},
|
|
'operator'
|
|
);
|
|
const archived = await f.research.archiveHypothesis(created.id, { archived: true }, 'operator');
|
|
const serviceQuestion = await f.research.createHypothesis(
|
|
f.project.id,
|
|
{ title: 'Service diagnostic', proposition: 'No measured claim.', contentOrigin: 'unknown' },
|
|
'service'
|
|
);
|
|
const totals = async () =>
|
|
(
|
|
await f.pool.query(`SELECT
|
|
(SELECT count(*)::int FROM runs) AS runs,
|
|
(SELECT count(*)::int FROM research_experiments) AS experiments,
|
|
(SELECT count(*)::int FROM research_hypotheses) AS hypotheses,
|
|
(SELECT count(*)::int FROM research_hypothesis_revisions) AS revisions,
|
|
(SELECT count(*)::int FROM analysis_artifacts) AS artifacts`)
|
|
).rows[0];
|
|
const before = await totals();
|
|
const requestStart = f.requests.length;
|
|
expect(await f.client.hypothesis(created.id)).toEqual(archived);
|
|
const history = await f.client.hypothesisRevisions(created.id);
|
|
expect(history).toEqual([original, revised.latestRevision]);
|
|
expect(history.find(item => item.id === created.latestRevision.id)).toEqual(original);
|
|
expect<string>(history[0]!.submittedBy).toBe(f.provisioned.agent.id);
|
|
expect(history[0]!.contentOrigin).toBe('ai');
|
|
expect(history[1]!.submittedBy).toBe('operator');
|
|
expect(history[1]!.contentOrigin).toBe('human');
|
|
expect(history.every(item => item.validationState === 'unvalidated')).toBeTrue();
|
|
expect(await f.client.hypothesis(serviceQuestion.id)).toEqual(serviceQuestion);
|
|
expect(await f.client.hypothesisRevisions(serviceQuestion.id)).toEqual([
|
|
serviceQuestion.latestRevision,
|
|
]);
|
|
const missing = randomUUID();
|
|
await expect(f.client.hypothesis(missing)).rejects.toMatchObject({
|
|
status: 404,
|
|
uncertain: false,
|
|
});
|
|
await expect(f.client.hypothesisRevisions(missing)).rejects.toMatchObject({
|
|
status: 404,
|
|
uncertain: false,
|
|
});
|
|
expect(
|
|
f.requests
|
|
.slice(requestStart)
|
|
.every(
|
|
request => request.method === 'GET' && request.key === null && request.body === undefined
|
|
)
|
|
).toBeTrue();
|
|
expect(await totals()).toEqual(before);
|
|
await f.agents.update(f.provisioned.agent.id, { expectedRevision: 1, enabled: false });
|
|
await expect(f.client.hypothesis(created.id)).rejects.toMatchObject({
|
|
status: 401,
|
|
uncertain: false,
|
|
});
|
|
await expect(f.client.hypothesisRevisions(created.id)).rejects.toMatchObject({
|
|
status: 401,
|
|
uncertain: false,
|
|
});
|
|
expect(await totals()).toEqual(before);
|
|
expect(f.executionErrors).toEqual([]);
|
|
});
|
|
|
|
test('research credentials export known immutable snapshots with exact read-only scope', async () => {
|
|
const f = await fixture();
|
|
const hash = f.dataset.manifest.hash;
|
|
const totals = async () =>
|
|
(
|
|
await f.pool.query(`SELECT
|
|
(SELECT count(*)::int FROM runs) AS runs,
|
|
(SELECT count(*)::int FROM research_experiments) AS experiments,
|
|
(SELECT count(*)::int FROM backtest_datasets) AS datasets`)
|
|
).rows[0];
|
|
const before = await totals();
|
|
expect(await f.client.canonicalDataset(hash)).toEqual(f.dataset);
|
|
const head = await f.transport(
|
|
`http://127.0.0.1:2003/api/v2/datasets/canonical/${hash}/export`,
|
|
{
|
|
method: 'HEAD',
|
|
headers: { Authorization: `Bearer ${f.provisioned.token}` },
|
|
}
|
|
);
|
|
expect(head.status).toBe(200);
|
|
expect(head.headers.get('cache-control')).toBe('no-store');
|
|
expect(head.headers.get('x-content-type-options')).toBe('nosniff');
|
|
expect(head.headers.get('content-disposition')).toBe(
|
|
`attachment; filename="dataset-${hash}.json"`
|
|
);
|
|
expect(await head.text()).toBe('');
|
|
for (const [path, method] of [
|
|
['/datasets/canonical', 'GET'],
|
|
['/datasets/stored-eod/coverage', 'GET'],
|
|
['/datasets/canonical/preview', 'POST'],
|
|
['/datasets/canonical/retain', 'POST'],
|
|
['/datasets/canonical/stored-source', 'POST'],
|
|
['/datasets/stored-eod/inspect', 'POST'],
|
|
[`/datasets/canonical/${hash}/export`, 'POST'],
|
|
]) {
|
|
const response = await f.transport(`http://127.0.0.1:2003/api/v2${path}`, {
|
|
method,
|
|
headers: { Authorization: `Bearer ${f.provisioned.token}` },
|
|
});
|
|
expect(response.status).toBe(403);
|
|
}
|
|
await expect(f.client.canonicalDataset('0'.repeat(64))).rejects.toMatchObject({
|
|
status: 404,
|
|
uncertain: false,
|
|
});
|
|
expect(await totals()).toEqual(before);
|
|
const badHash = 'f'.repeat(64);
|
|
await f.pool.query('INSERT INTO backtest_datasets(hash,payload) VALUES($1,$2::jsonb)', [
|
|
badHash,
|
|
f.dataset,
|
|
]);
|
|
const afterFixtureInsert = await totals();
|
|
await expect(f.client.canonicalDataset(badHash)).rejects.toMatchObject({
|
|
status: 409,
|
|
uncertain: false,
|
|
});
|
|
expect(await totals()).toEqual(afterFixtureInsert);
|
|
await f.agents.update(f.provisioned.agent.id, { expectedRevision: 1, enabled: false });
|
|
await expect(f.client.canonicalDataset(hash)).rejects.toMatchObject({
|
|
status: 401,
|
|
uncertain: false,
|
|
});
|
|
expect(f.executionErrors).toEqual([]);
|
|
});
|
|
|
|
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<string, number>; normalized: Record<string, number> }[] = [
|
|
{ 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);
|
|
const reopenedFinding = await f.client.artifact(finding.id);
|
|
expect(reopenedFinding.latestRevision).toMatchObject(finding.latestRevision);
|
|
expect(await f.client.artifactRevisions(finding.id)).toEqual([
|
|
reopenedFinding.latestRevision,
|
|
]);
|
|
for (const evidence of finding.latestRevision.evidence) {
|
|
const saved = await f.client.canonicalRunResult(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');
|
|
const retained = await f.api.getRunResults(evidence.runId);
|
|
if (!retained || !('kind' in retained) || retained.kind !== 'canonical-result/v1') {
|
|
throw new Error('Missing retained canonical result');
|
|
}
|
|
expect(saved).toEqual(retained);
|
|
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');
|
|
await expect(
|
|
f.client.canonicalRunResult(broken.screening!.trials[0]!.runId!)
|
|
).rejects.toMatchObject({ status: 404, uncertain: false });
|
|
await expect(f.client.canonicalRunResult(randomUUID())).rejects.toMatchObject({
|
|
status: 404,
|
|
uncertain: false,
|
|
});
|
|
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<ResearchClient['submitValidation']>[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 originalQuestion = await f.client.hypothesis(result.hypothesis.id);
|
|
expect(originalQuestion.latestRevision).toMatchObject(result.hypothesis.latestRevision);
|
|
const revisedQuestion = await f.research.reviseHypothesis(
|
|
result.hypothesis.id,
|
|
{
|
|
expectedRevision: originalQuestion.latestRevision.ordinal,
|
|
title: 'Later human interpretation',
|
|
proposition: 'This revision must not replace the candidate study question.',
|
|
validationCriteria: 'Further validation is required.',
|
|
contentOrigin: 'human',
|
|
},
|
|
'operator'
|
|
);
|
|
expect((await f.client.hypothesis(result.hypothesis.id)).latestRevision).toEqual(
|
|
revisedQuestion.latestRevision
|
|
);
|
|
const questionHistory = await f.client.hypothesisRevisions(result.hypothesis.id);
|
|
expect(questionHistory).toEqual([
|
|
originalQuestion.latestRevision,
|
|
revisedQuestion.latestRevision,
|
|
]);
|
|
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<string, unknown>;
|
|
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.client.canonicalRunResult(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 retained = await f.client.artifact(finding.id);
|
|
expect(retained.hypothesisRevisionId).toBe(originalQuestion.latestRevision.id);
|
|
expect(questionHistory.find(item => item.id === retained.hypothesisRevisionId)).toEqual(
|
|
originalQuestion.latestRevision
|
|
);
|
|
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 revised = await f.research.reviseArtifact(
|
|
finding.id,
|
|
{
|
|
expectedRevision: retained.latestRevision.ordinal,
|
|
title: 'Human follow-up to saved AI comparison',
|
|
body: 'A revised interpretation, still unvalidated.',
|
|
contentOrigin: 'human',
|
|
evidence: comparisonInput.evidence,
|
|
source: null,
|
|
},
|
|
'operator'
|
|
);
|
|
const latest = await f.client.artifact(finding.id);
|
|
expect(latest.latestRevision.id).toBe(revised.latestRevision.id);
|
|
expect(latest.latestRevision.contentOrigin).toBe('human');
|
|
expect(latest.latestRevision.submittedBy).toBe('operator');
|
|
const history = await f.client.artifactRevisions(finding.id);
|
|
expect(history).toHaveLength(2);
|
|
expect(history.find(item => item.id === finding.latestRevision.id)).toEqual(
|
|
retained.latestRevision
|
|
);
|
|
expect(history.find(item => item.id === revised.latestRevision.id)).toEqual(
|
|
latest.latestRevision
|
|
);
|
|
expect(latest.latestRevision.evidence).toEqual(retained.latestRevision.evidence);
|
|
expect(f.requests.slice(-3).every(item => item.method === 'GET' && item.key === null)).toBe(
|
|
true
|
|
);
|
|
}
|
|
const note = await f.research.createArtifact(
|
|
f.project.id,
|
|
{
|
|
kind: 'note',
|
|
title: 'Service diagnostic note',
|
|
body: 'No measured claim.',
|
|
contentOrigin: 'unknown',
|
|
},
|
|
'service'
|
|
);
|
|
expect((await f.client.artifact(note.id)).latestRevision).toMatchObject({
|
|
contentOrigin: 'unknown',
|
|
submittedBy: 'service',
|
|
evidence: [],
|
|
evidenceState: 'none',
|
|
source: null,
|
|
});
|
|
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
|
|
);
|
|
const original = await f.client.canonicalRunResult(reference.runId);
|
|
const snapshot = await f.client.canonicalDataset(original.request.datasetHash);
|
|
expect(snapshot).toEqual(
|
|
(
|
|
await f.pool.query('SELECT payload FROM backtest_datasets WHERE hash=$1', [
|
|
original.request.datasetHash,
|
|
])
|
|
).rows[0].payload
|
|
);
|
|
const template = await f.api.getBacktest(original.backtestId);
|
|
if (!template) {
|
|
throw new Error('Missing original template');
|
|
}
|
|
await f.api.updateBacktest(original.backtestId, {
|
|
startDate: new Date(f.dataset.manifest.bounds.tradeStart).toISOString(),
|
|
endDate: new Date(f.dataset.manifest.bounds.tradeEnd).toISOString(),
|
|
symbols: f.dataset.manifest.executionSeries.map(series => series.instrumentId),
|
|
config: {
|
|
...template.config,
|
|
datasetHash: f.dataset.manifest.hash,
|
|
dataFrequency: f.dataset.manifest.series[0]!.interval,
|
|
},
|
|
});
|
|
expect(await f.client.canonicalDataset(original.request.datasetHash)).toEqual(snapshot);
|
|
expect(await f.client.canonicalRunResult(reference.runId)).toEqual(original);
|
|
expect((await f.pool.query('SELECT count(*)::int AS count FROM runs')).rows[0].count).toBe(
|
|
before
|
|
);
|
|
await f.agents.update(f.provisioned.agent.id, {
|
|
expectedRevision: f.provisioned.agent.revision,
|
|
enabled: false,
|
|
});
|
|
await expect(f.client.artifact(note.id)).rejects.toMatchObject({
|
|
status: 401,
|
|
uncertain: false,
|
|
});
|
|
await expect(f.client.canonicalRunResult(reference.runId)).rejects.toMatchObject({
|
|
status: 401,
|
|
uncertain: false,
|
|
});
|
|
await expect(f.client.artifactRevisions(note.id)).rejects.toMatchObject({
|
|
status: 401,
|
|
uncertain: false,
|
|
});
|
|
}, 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);
|
|
});
|