feat(research): add projects and revisioned evidence-linked findings

This commit is contained in:
Boki 2026-10-23 23:38:47 -04:00
parent 618fb9e33c
commit ee45257507
22 changed files with 2947 additions and 17 deletions

View file

@ -291,6 +291,7 @@ export async function fixture(browser: Browser, native = false) {
'17-research-retention.sql',
'18-backtest-strategy-versions.sql',
'19-canonical-research.sql',
'20-research-workspace.sql',
]) {
await pool.query(
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')

View file

@ -0,0 +1,434 @@
import { randomUUID } from 'node:crypto';
import { describe, expect, mock, test } from 'bun:test';
import { Hono } from 'hono';
import { z } from 'zod';
import { createHttpSecurity } from '@stock-bot/di';
import type { IServiceContainer } from '@stock-bot/services';
import { createResearchRoutes } from '../../apps/stock/web-api/src/routes/research.routes';
import { ResearchError } from '../../apps/stock/web-api/src/services/research-errors';
const tokens = {
operator: 'research-admin-fixture-not-a-real-secret-1234',
service: 'research-service-fixture-not-a-real-secret-1234',
read: 'research-read-fixture-not-a-real-secret-1234',
};
type Query = (sql: string, values?: unknown[]) => Promise<{ rows: Record<string, unknown>[] }>;
function fixture(
security: 'enabled' | 'disabled' | 'absent' = 'enabled',
query: Query = async () => {
throw new Error('Rejected request reached storage');
}
) {
const database = {
query: mock(query),
transaction: mock(async () => {
throw new Error('Rejected request reached transaction');
}),
};
const logger = { error: mock((_message: string, _details?: unknown) => {}) };
const app = new Hono();
if (security !== 'absent') {
createHttpSecurity({
adminToken: tokens.operator,
serviceToken: tokens.service,
readToken: tokens.read,
environment: 'test',
hostname: '127.0.0.1',
disabled: security === 'disabled',
}).mount(app);
}
app.route(
'/',
createResearchRoutes({ postgres: database, logger } as unknown as IServiceContainer)
);
app.post('/api/v2/unrelated', c => c.json({ ok: true }));
return {
database,
logger,
app,
request(
path: string,
body?: unknown,
role?: keyof typeof tokens,
method = body === undefined ? 'GET' : 'POST',
extra: Record<string, string> = {}
) {
return app.request(`/api/v2/${path}`, {
method,
headers: {
...(role ? { Authorization: `Bearer ${tokens[role]}` } : {}),
'Content-Type': 'application/json',
...extra,
},
...(body === undefined ? {} : { body: JSON.stringify(body) }),
});
},
};
}
const projectId = randomUUID();
const hypothesisId = randomUUID();
const artifactId = randomUUID();
const strategyId = randomUUID();
const hypothesis = { title: 'Research hypothesis', proposition: 'A testable proposition' };
const note = { kind: 'note', title: 'Research note', body: 'Unvalidated narrative' };
const writes = [
{ path: 'research-projects', body: { title: 'Project' }, method: 'POST' },
{
path: `research-projects/${projectId}`,
body: { expectedRevision: 1, archived: true },
method: 'PATCH',
},
{ path: `research-projects/${projectId}/strategies/${strategyId}`, method: 'PUT' },
{ path: `research-projects/${projectId}/strategies/${strategyId}`, method: 'DELETE' },
{ path: `research-projects/${projectId}/hypotheses`, body: hypothesis, method: 'POST' },
{
path: `hypotheses/${hypothesisId}/revisions`,
body: { ...hypothesis, expectedRevision: 1 },
method: 'POST',
},
{ path: `hypotheses/${hypothesisId}`, body: { archived: true }, method: 'PATCH' },
{ path: `research-projects/${projectId}/analysis-artifacts`, body: note, method: 'POST' },
{
path: `analysis-artifacts/${artifactId}/revisions`,
body: { title: 'Changed', body: '', expectedRevision: 1 },
method: 'POST',
},
{ path: `analysis-artifacts/${artifactId}`, body: { archived: true }, method: 'PATCH' },
];
const readPaths = [
'research-projects',
`research-projects/${projectId}`,
`research-projects/${projectId}/strategies`,
`research-projects/${projectId}/hypotheses`,
`research-projects/${projectId}/analysis-artifacts`,
`hypotheses/${hypothesisId}`,
`hypotheses/${hypothesisId}/revisions`,
`analysis-artifacts/${artifactId}`,
`analysis-artifacts/${artifactId}/revisions`,
];
function noStorage(f: ReturnType<typeof fixture>) {
expect(f.database.query.mock.calls).toHaveLength(0);
expect(f.database.transaction.mock.calls).toHaveLength(0);
}
describe('research HTTP credential and transport boundary', () => {
test('every mutation rejects absent credentials, forged actors and the development bypass', async () => {
for (const mode of ['enabled', 'disabled', 'absent'] as const) {
const f = fixture(mode);
for (const write of writes) {
const response = await f.request(write.path, write.body, undefined, write.method, {
'X-Actor': 'operator',
'X-Principal': 'operator',
});
expect(response.status).toBe(401);
}
noStorage(f);
}
});
test('the mounted read role may read but cannot mutate; anonymous reads reject', async () => {
const f = fixture('enabled', async () => ({ rows: [] }));
for (const path of readPaths) {
expect((await f.request(path)).status).toBe(401);
}
for (const write of writes) {
expect((await f.request(write.path, write.body, 'read', write.method)).status).toBe(403);
}
noStorage(f);
const response = await f.request('research-projects', undefined, 'read');
expect(response.status).toBe(200);
expect(await response.json()).toEqual({ projects: [] });
expect(response.headers.get('Cache-Control')).toBe('no-store');
});
test('service credentials cannot claim human authorship before storage', async () => {
const f = fixture();
const cases = [
{ path: `research-projects/${projectId}/hypotheses`, body: hypothesis },
{
path: `hypotheses/${hypothesisId}/revisions`,
body: { ...hypothesis, expectedRevision: 1 },
},
{ path: `research-projects/${projectId}/analysis-artifacts`, body: note },
{
path: `analysis-artifacts/${artifactId}/revisions`,
body: { title: 'Finding', body: '', expectedRevision: 1 },
},
];
for (const item of cases) {
const response = await f.request(
`${item.path}?actor=operator`,
{ ...item.body, contentOrigin: 'human' },
'service',
'POST',
{ 'X-Actor': 'operator' }
);
expect(response.status).toBe(403);
}
noStorage(f);
});
test('strict metadata bodies reject submitted actor, approval and validation claims', async () => {
const f = fixture();
for (const write of writes) {
for (const field of ['submittedBy', 'ownerPrincipal', 'validationState', 'approved']) {
const response = await f.request(
write.path,
{ ...(write.body ?? {}), [field]: field === 'approved' ? true : 'operator' },
'operator',
write.method
);
expect(response.status).toBe(400);
}
}
noStorage(f);
});
test('invalid revision, text and metric references reject before database access', async () => {
const f = fixture();
const invalidBodies = [
{ path: 'research-projects', body: { title: '' }, method: 'POST' },
{ path: `research-projects/${projectId}`, body: { title: 'No revision' }, method: 'PATCH' },
{
path: `hypotheses/${hypothesisId}/revisions`,
body: { ...hypothesis, expectedRevision: 0 },
method: 'POST',
},
{ path: `analysis-artifacts/${artifactId}`, body: { archived: 'true' }, method: 'PATCH' },
];
for (const item of invalidBodies) {
expect((await f.request(item.path, item.body, 'operator', item.method)).status).toBe(400);
}
for (const badText of ['bad\u0000text', 'bad\ud800text', 'bad\udc00text']) {
expect((await f.request('research-projects', { title: badText }, 'operator')).status).toBe(
400
);
expect(
(
await f.request(
`research-projects/${projectId}/hypotheses`,
{ ...hypothesis, proposition: badText },
'operator'
)
).status
).toBe(400);
expect(
(
await f.request(
`research-projects/${projectId}/analysis-artifacts`,
{ ...note, body: badText },
'operator'
)
).status
).toBe(400);
}
const reference = {
runId: randomUUID(),
metricsVersion: 'canonical-analytics/v1',
metricPath: 'analytics.metrics.totalReturn',
};
for (const evidence of [
[{ ...reference, metricsVersion: 'invented/v1' }],
[{ ...reference, metricPath: '__proto__.totalReturn' }],
[{ ...reference, value: 10 }],
[reference, reference],
]) {
const response = await f.request(
`research-projects/${projectId}/analysis-artifacts`,
{ ...note, evidence },
'operator'
);
expect(response.status).toBe(400);
}
noStorage(f);
});
test('list archive filters and path IDs are strict; unrelated API middleware is unaffected', async () => {
const f = fixture();
for (const path of [
'research-projects',
`research-projects/${projectId}/hypotheses`,
`research-projects/${projectId}/analysis-artifacts`,
]) {
for (const value of ['', '1', 'TRUE', 'maybe']) {
expect(
(await f.request(`${path}?includeArchived=${value}`, undefined, 'read')).status
).toBe(400);
}
}
for (const path of [
'research-projects/not-a-uuid',
'hypotheses/not-a-uuid',
'analysis-artifacts/not-a-uuid',
`research-projects/not-a-uuid/strategies`,
]) {
expect((await f.request(path, undefined, 'read')).status).toBe(400);
}
noStorage(f);
const unrelated = await f.request('unrelated', {}, 'operator');
expect(unrelated.status).toBe(200);
expect(unrelated.headers.get('Cache-Control')).toBeNull();
});
test('malformed JSON rejects and metadata APIs do not expose deletion, approval or execution', async () => {
const f = fixture();
for (const write of writes) {
const response = await f.app.request(`/api/v2/${write.path}`, {
method: write.method,
headers: { Authorization: `Bearer ${tokens.operator}`, 'Content-Type': 'application/json' },
body: '{',
});
expect(response.status).toBe(400);
}
for (const path of [
`research-projects/${projectId}`,
`hypotheses/${hypothesisId}`,
`analysis-artifacts/${artifactId}`,
]) {
expect((await f.request(path, undefined, 'operator', 'DELETE')).status).toBe(404);
for (const action of ['approve', 'execute', 'deploy']) {
expect((await f.request(`${path}/${action}`, {}, 'operator')).status).toBe(404);
}
}
noStorage(f);
});
test('missing resources and typed conflicts retain their statuses; internal details do not leak', async () => {
const missing = fixture('enabled', async () => ({ rows: [] }));
expect(
(await missing.request(`research-projects/${projectId}`, undefined, 'read')).status
).toBe(404);
for (const status of [409, 422] as const) {
const f = fixture('enabled', async () => {
throw new ResearchError(status, 'Retained research reference rejected');
});
const response = await f.request(`research-projects/${projectId}`, undefined, 'read');
expect(response.status).toBe(status);
expect(await response.json()).toEqual({ error: 'Retained research reference rejected' });
}
const internal = fixture('enabled', async () => {
throw new Error('private-database-connection-and-query-detail');
});
const response = await internal.request('research-projects', undefined, 'read');
expect(response.status).toBe(500);
expect(await response.json()).toEqual({ error: 'Research workspace unavailable' });
expect(internal.logger.error.mock.calls).toHaveLength(1);
});
test('project creation records verified principal instead of forged identity headers', async () => {
for (const role of ['operator', 'service'] as const) {
const f = fixture('enabled', async (_sql, values) => ({
rows: [
{
id: projectId,
title: 'Project',
description: '',
revision: 1,
owner_principal: values?.includes('service') ? 'service' : 'operator',
updated_by: values?.includes('service') ? 'service' : 'operator',
archived_at: null,
created_at: new Date('2026-01-01'),
updated_at: new Date('2026-01-01'),
},
],
}));
const response = await f.request('research-projects', { title: 'Project' }, role, 'POST', {
'X-Actor': role === 'service' ? 'operator' : 'service',
});
expect(response.status).toBe(201);
const body = await response.json();
expect(body.project.ownerPrincipal).toBe(role);
expect(body.project.updatedBy).toBe(role);
expect(f.database.query.mock.calls[0]?.[1]).toContain(role);
expect(response.headers.get('Cache-Control')).toBe('no-store');
}
});
test('a valid artifact citation with a corrupt retained request returns a sanitized server error', async () => {
const revisionId = randomUUID();
const runId = randomUUID();
const backtestId = randomUUID();
const stamp = new Date('2026-01-01');
const f = fixture('enabled', async sql => {
if (sql.includes('FROM analysis_artifacts WHERE')) {
return {
rows: [
{
id: artifactId,
project_id: projectId,
hypothesis_revision_id: null,
kind: 'finding',
owner_principal: 'operator',
updated_by: 'operator',
archived_at: null,
created_at: stamp,
updated_at: stamp,
},
],
};
}
if (sql.includes('FROM analysis_artifact_revisions WHERE')) {
return {
rows: [
{
id: revisionId,
artifact_id: artifactId,
ordinal: 1,
title: 'Retained finding',
body: 'Narrative is not a metric',
submitted_by: 'operator',
content_origin: 'human',
created_at: stamp,
},
],
};
}
if (sql.includes('FROM analysis_evidence WHERE')) {
return {
rows: [
{
revision_id: revisionId,
ordinal: 1,
run_id: runId,
metrics_version: 'canonical-analytics/v1',
metric_path: 'analytics.metrics.totalReturn',
strategy_version_id: null,
},
],
};
}
if (sql.includes('FROM runs WHERE')) {
return { rows: [{ id: runId, backtest_id: backtestId, status: 'completed' }] };
}
if (sql.includes('FROM backtest_results br')) {
// The reference is valid. This damage is in retained server evidence,
// and must not be classified as a malformed client request.
return {
rows: [
{
run_id: runId,
backtest_id: backtestId,
run_status: 'completed',
canonical_result: { kind: 'canonical-result/v1' },
request_snapshot: { kind: 'canonical-research/v1', 'private-retained-marker': true },
},
],
};
}
throw new Error(`Unexpected evidence query: ${sql}`);
});
const response = await f.request(`analysis-artifacts/${artifactId}`, undefined, 'read');
expect(response.status).toBe(500);
expect(await response.json()).toEqual({ error: 'Research workspace unavailable' });
expect(response.headers.get('Cache-Control')).toBe('no-store');
expect(f.database.query.mock.calls).toHaveLength(5);
expect(f.logger.error.mock.calls).toHaveLength(1);
const diagnostic = f.logger.error.mock.calls[0]?.[1] as { error?: unknown } | undefined;
expect(diagnostic?.error).toBeInstanceOf(Error);
if (!(diagnostic?.error instanceof Error)) {
throw new Error('Missing retained-read diagnostic');
}
expect(diagnostic.error.message).toBe('Retained research result could not be read');
expect(diagnostic.error.cause).toBeInstanceOf(z.ZodError);
});
});

View file

@ -0,0 +1,173 @@
import { randomUUID } from 'node:crypto';
import { describe, expect, test } from 'bun:test';
import type { CanonicalRunResult } from '@stock-bot/stock-config/canonical-research';
import {
parseResearchInput,
researchEvidenceReferenceSchema,
} from '@stock-bot/stock-config/research';
import type { BacktestRunResult, ResearchEvidenceReference } from '@stock-bot/types';
import { projectResearchEvidence } from '../../apps/stock/web-api/src/services/research-evidence';
const runId = randomUUID();
const backtestId = randomUUID();
const versionId = randomUUID();
const reference = (metricPath: string): ResearchEvidenceReference => ({
runId,
metricPath,
metricsVersion: 'canonical-analytics/v1',
strategyVersionId: versionId,
});
// Projection-only transport fixtures: the real PostgreSQL suite runs the retained
// worker and validates full Rust reports. These deliberately supply only reader fields.
const canonical = {
kind: 'canonical-result/v1',
runId,
backtestId,
status: 'completed',
request: { datasetHash: 'a'.repeat(64), strategy: { versionId } },
analytics: {
version: 1,
fillCount: 2,
metrics: {
totalReturn: -0.125,
exposureTime: 0,
sharpeRatio: 0,
beta: null,
avgWin: null,
roundTripCount: null,
},
unavailable: {
beta: 'missing-benchmark',
avgWin: 'unsupported-round-trips',
roundTripCount: 'unsupported-round-trips',
},
},
financial: {
limitations: ['Fixture data limitation'],
modelLimitations: ['Fixture model limitation'],
},
} as unknown as CanonicalRunResult;
describe('research evidence projection', () => {
test('retains measurements without scaling or treating fills as completed round trips', () => {
const loss = projectResearchEvidence(reference('analytics.metrics.totalReturn'), canonical);
expect(loss.value).toBe(-0.125);
expect(loss.unit).toBe('fraction');
expect(loss.resultKind).toBe('canonical');
expect(loss.financialEngine).toBe('rust');
expect(loss.limitations.map(item => item.message)).toEqual([
'Fixture data limitation',
'Fixture model limitation',
]);
const zero = projectResearchEvidence(reference('analytics.metrics.exposureTime'), canonical);
expect(zero).toMatchObject({ value: 0, availability: 'available', unavailableReason: null });
const fills = projectResearchEvidence(reference('analytics.fillCount'), canonical);
expect(fills).toMatchObject({ value: 2, unit: 'count' });
expect(
projectResearchEvidence(reference('analytics.metrics.roundTripCount'), canonical)
).toMatchObject({
value: null,
unit: 'count',
availability: 'unavailable',
unavailableReason: 'unsupported-round-trips',
});
expect(projectResearchEvidence(reference('analytics.metrics.beta'), canonical)).toMatchObject({
value: null,
unit: 'ratio',
unavailableReason: 'missing-benchmark',
});
expect(projectResearchEvidence(reference('analytics.metrics.avgWin'), canonical).unit).toBe(
'currency'
);
expect(
projectResearchEvidence(reference('analytics.metrics.sharpeRatio'), canonical)
).toMatchObject({ value: 0, unit: 'ratio' });
});
test('legacy display adapter version never claims a recorded engine version or recalculates values', () => {
const legacy = {
runId,
backtestId,
status: 'completed',
engine: 'native',
metrics: { totalReturn: 0.12 },
analytics: { exposureTime: null },
provenance: {
datasetHash: null,
limitations: [{ code: 'same-bar', message: 'Saved same-bar policy' }],
},
} as unknown as BacktestRunResult;
const result = projectResearchEvidence(
{ runId, metricsVersion: 'legacy-display/v1', metricPath: 'metrics.totalReturn' },
legacy
);
expect(result).toMatchObject({
value: 0.12,
unit: 'fraction',
resultKind: 'legacy',
financialEngine: 'native',
datasetHash: null,
});
expect(result.limitations.map(item => item.code)).toEqual([
'legacy-unverified-economics',
'same-bar',
]);
expect(
projectResearchEvidence(
{ runId, metricsVersion: 'legacy-display/v1', metricPath: 'analytics.exposureTime' },
legacy
)
).toMatchObject({
value: null,
availability: 'unavailable',
unavailableReason: 'legacy-unavailable',
});
expect(() =>
projectResearchEvidence(reference('analytics.metrics.totalReturn'), legacy)
).toThrow('Legacy');
});
test('rejects incompatible retained identities, incomplete runs and nonfinite measurements', () => {
expect(() =>
projectResearchEvidence(
{ ...reference('analytics.fillCount'), strategyVersionId: randomUUID() },
canonical
)
).toThrow('not bound');
expect(() =>
projectResearchEvidence(
{ ...reference('analytics.fillCount'), runId: randomUUID() },
canonical
)
).toThrow('completed retained run');
expect(() =>
projectResearchEvidence(
{ runId, metricsVersion: 'legacy-display/v1', metricPath: 'metrics.totalReturn' },
canonical
)
).toThrow('Metrics version');
expect(() =>
projectResearchEvidence(reference('analytics.fillCount'), {
...canonical,
analytics: { ...canonical.analytics, fillCount: NaN },
})
).toThrow('finite scalar');
});
test('accepts only versioned scalar paths and references, never client-supplied measurements', () => {
for (const change of [
{ metricPath: '__proto__.constructor' },
{ metricPath: 'request.strategy.package.artifact.content' },
{ metricsVersion: 'canonical-analytics/v2' },
{ value: 999 },
{ validationState: 'validated' },
]) {
expect(() =>
parseResearchInput(researchEvidenceReferenceSchema, {
...reference('analytics.fillCount'),
...change,
})
).toThrow();
}
});
});

View file

@ -22,6 +22,7 @@ const migrations = [
'17-research-retention.sql',
'18-backtest-strategy-versions.sql',
'19-canonical-research.sql',
'20-research-workspace.sql',
];
const cleanup: (() => Promise<void>)[] = [];
afterEach(async () => {

View file

@ -0,0 +1,735 @@
import { randomUUID } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { afterEach, describe, expect, test } from 'bun:test';
import { Pool } from 'pg';
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
import { PostgreSQLClient } from '@stock-bot/postgres';
import type { ResearchEvidenceReference } 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 { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service';
import { ResearchService } from '../../apps/stock/web-api/src/services/research.service';
import { StrategyCatalogService } from '../../apps/stock/web-api/src/services/strategy-catalog.service';
import { retainResearchDataset } from '../../scripts/import-research-dataset';
import { packageBuiltinStrategies } from '../../scripts/package-builtin-strategies';
import { canonicalSettings } from '../fixtures/canonical-research';
import { canonicalSmaFixture } from '../fixtures/canonical-sma';
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
const logger = getLogger('research-workspace');
const url = process.env.PIPELINE_TEST_DATABASE_URL;
const cleanup: (() => Promise<void>)[] = [];
let packages: ReturnType<typeof packageBuiltinStrategies> | undefined;
const sql = (name: string) =>
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8');
const migration = sql('20-research-workspace.sql');
afterEach(async () => {
for (const close of cleanup.splice(0).reverse()) {
await close();
}
});
async function fixture(applyWorkspace = true, maxConnections = 10) {
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
throw new Error('Disposable safety database required');
}
const schema = 'stock_bot_safety_workspace_' + randomUUID().replaceAll('-', '');
const admin = new Pool({ connectionString: url });
await admin.query(`CREATE SCHEMA ${schema}`);
const pool = new Pool({
connectionString: url,
max: maxConnections,
connectionTimeoutMillis: 2000,
application_name: schema,
options: `-c search_path=${schema} -c statement_timeout=10000`,
});
cleanup.push(async () => {
await pool.end();
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
await admin.end();
});
for (const name of [
'06-create-backtest-tables.sql',
'07-fix-execution-time-type.sql',
'08-create-runs-table.sql',
'09-backtest-run-contract.sql',
'10-durable-backtest-dispatch.sql',
'12-historical-datasets.sql',
'14-backtest-submission.sql',
'16-strategy-catalog.sql',
'17-research-retention.sql',
'18-backtest-strategy-versions.sql',
'19-canonical-research.sql',
]) {
await pool.query(sql(name));
}
if (applyWorkspace) {
await pool.query(migration);
}
const postgres = new PostgreSQLClient(
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
logger
);
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) });
const container = { postgres, logger };
const service = new ResearchService(container);
const backtests = new BacktestServiceV2(container);
const catalog = new StrategyCatalogService(container);
const legacy = async (status = 'completed') => {
const definition = await backtests.createBacktest(
{
name: 'Retained legacy fixture',
strategy: 'sma-crossover',
symbols: ['X0.US'],
startDate: '2024-01-01T00:00:00Z',
endDate: '2024-01-04T00:00:00Z',
initialCapital: 10000,
config: { fastPeriod: 2, slowPeriod: 3, commission: 0, slippage: 0 },
},
{ autoStart: false }
);
const run = await backtests.createRun({ backtestId: definition.id });
// Fixed old-display fixtures exercise custody/conversion, not financial simulation.
await pool.query(
`INSERT INTO backtest_results(run_id,metrics,equity_curve,ohlc_data,trades,positions,analytics,execution_time,engine)
VALUES($1,$2,'[]','{}','[]','[]',$3,0,'native')`,
[
run.id,
{
totalReturn: 12,
sharpeRatio: null,
maxDrawdown: -0.1,
winRate: 50,
totalTrades: 0,
profitFactor: null,
avgWin: 0,
avgLoss: 0,
},
{ exposureTime: 0 },
]
);
await pool.query('UPDATE runs SET status=$2,completed_at=NOW(),progress=100 WHERE id=$1', [
run.id,
status,
]);
return { run, definition };
};
const canonical = async () => {
const pkg = (await (packages ??= packageBuiltinStrategies()))[0]!;
const version = await catalog.seedBuiltin('Retained SMA', pkg, 'seed');
await catalog.reviewVersion(
version.id,
{ decision: 'approve', reason: 'Reviewed fixture' },
'operator'
);
const { dataset } = canonicalSmaFixture();
await retainResearchDataset(pool, dataset);
const definition = await backtests.createBacktest(
{
name: 'Canonical cited fixture',
strategy: 'catalog',
strategyVersionId: version.id,
strategyParameters: { fastPeriod: 2, slowPeriod: 3 },
symbols: ['X0.US'],
startDate: new Date(dataset.manifest.bounds.tradeStart).toISOString(),
endDate: new Date(dataset.manifest.bounds.tradeEnd).toISOString(),
initialCapital: 10000,
config: {
datasetHash: dataset.manifest.hash,
dataFrequency: '1m',
canonical: canonicalSettings,
},
},
{ autoStart: false }
);
const run = await backtests.createRun({ backtestId: definition.id });
const runner = new BacktestRunner({
engine: new RustBacktestAdapter({
logger,
storage: {
async getHistoricalBars() {
throw new Error('No provider fallback');
},
},
}),
engineName: 'native',
repository: new PostgresBacktestRunRepository(postgres),
logger,
});
try {
await runner.runQueued(run.id);
} finally {
await runner.shutdown();
}
expect((await backtests.getRun(run.id))?.status).toBe('completed');
return { run, definition, version, dataset };
};
return { pool, schema, postgres, service, backtests, catalog, legacy, canonical };
}
const hypothesisInput = {
title: 'Trend hypothesis',
proposition: 'A stated claim',
validationCriteria: 'Evaluate held-out data',
};
const noteInput = {
kind: 'note' as const,
title: 'Observation',
body: 'A narrative, not a measured conclusion',
};
const reference = (
runId: string,
metricPath = 'metrics.totalReturn'
): ResearchEvidenceReference => ({ runId, metricsVersion: 'legacy-display/v1', metricPath });
describe.skipIf(!url)('research workspace retained narratives and evidence', () => {
test('evidence create and revise use the transaction connection even with a one-connection pool', async () => {
const f = await fixture(true, 1);
const { run } = await f.legacy();
const p = await f.service.createProject({ title: 'Single connection' }, 'operator');
const finding = await f.service.createArtifact(
p.id,
{
...noteInput,
kind: 'finding',
evidence: [reference(run.id)],
},
'operator'
);
const revised = await f.service.reviseArtifact(
finding.id,
{
title: 'Revised',
body: 'Same retained run',
expectedRevision: 1,
evidence: [reference(run.id, 'metrics.winRate')],
},
'operator'
);
expect(revised.latestRevision.evidence[0]?.value).toBe(0.5);
expect(await f.service.listArtifactRevisions(finding.id)).toHaveLength(2);
});
test('projects and strategy organization are editable and archiveable without altering catalog identity', async () => {
const f = await fixture();
expect(await f.service.listProjects()).toEqual([]);
const p = await f.service.createProject(
{ title: 'Research 🚀', description: 'Tokyo 東京' },
'operator'
);
expect(p).toMatchObject({
revision: 1,
ownerPrincipal: 'operator',
updatedBy: 'operator',
archived: false,
});
const strategy = await f.catalog.createStrategy({ name: 'Candidate' }, 'operator');
await f.service.linkStrategy(p.id, strategy.id, 'service');
await f.service.linkStrategy(p.id, strategy.id, 'operator');
expect(await f.service.listProjectStrategies(p.id)).toEqual([strategy]);
expect(
(await f.pool.query('SELECT added_by FROM research_project_strategies')).rows[0].added_by
).toBe('service');
expect(await f.service.getProject(p.id)).toMatchObject({ revision: 2, updatedBy: 'service' });
await expect(
f.service.updateProject(
p.id,
{ expectedRevision: 1, title: 'Before membership change' },
'operator'
)
).rejects.toThrow('revision changed');
const edited = await f.service.updateProject(
p.id,
{ expectedRevision: 2, title: 'Changed' },
'service'
);
expect(edited).toMatchObject({
revision: 3,
title: 'Changed',
ownerPrincipal: 'operator',
updatedBy: 'service',
});
await expect(
f.service.updateProject(p.id, { expectedRevision: 1, title: 'Stale' }, 'operator')
).rejects.toThrow('revision changed');
await f.catalog.updateStrategy(strategy.id, { archived: true }, 'operator');
await expect(f.service.linkStrategy(p.id, strategy.id, 'operator')).rejects.toThrow('archived');
await f.service.unlinkStrategy(p.id, strategy.id, 'operator');
const unlinked = await f.service.getProject(p.id);
expect(unlinked).toMatchObject({ revision: 4, updatedBy: 'operator' });
await f.service.unlinkStrategy(p.id, strategy.id, 'service');
expect(await f.service.getProject(p.id)).toEqual(unlinked);
await expect(
f.service.updateProject(p.id, { expectedRevision: 3, title: 'Before unlink' }, 'operator')
).rejects.toThrow('revision changed');
expect(await f.service.listProjectStrategies(p.id)).toEqual([]);
const archived = await f.service.updateProject(
p.id,
{ expectedRevision: 4, archived: true },
'operator'
);
expect(await f.service.listProjects()).toEqual([]);
expect(await f.service.listProjects(true)).toEqual([archived]);
await expect(f.service.createHypothesis(p.id, hypothesisInput, 'operator')).rejects.toThrow(
'archived'
);
await expect(f.service.createArtifact(p.id, noteInput, 'operator')).rejects.toThrow('archived');
await expect(
f.service.updateProject(
p.id,
{ expectedRevision: 5, archived: false, title: 'Hidden edit' },
'operator'
)
).rejects.toThrow('only permit restoration');
expect(
(await f.service.updateProject(p.id, { expectedRevision: 5, archived: false }, 'operator'))
.archived
).toBe(false);
expect((await f.catalog.getStrategy(strategy.id)).archived).toBe(true);
});
test('hypothesis_vs_evidence and authorship_audit retain every narrative revision without validation promotion', async () => {
const f = await fixture();
const p = await f.service.createProject({ title: 'Research' }, 'service');
const h = await f.service.createHypothesis(
p.id,
{ ...hypothesisInput, contentOrigin: 'ai' },
'service'
);
expect(h.updatedBy).toBe('service');
expect(Number.isFinite(Date.parse(h.updatedAt))).toBe(true);
expect(h.latestRevision).toMatchObject({
submittedBy: 'service',
contentOrigin: 'ai',
validationState: 'unvalidated',
ordinal: 1,
});
const revised = await f.service.reviseHypothesis(
h.id,
{ ...hypothesisInput, proposition: 'Changed claim', expectedRevision: 1 },
'operator'
);
expect(revised.latestRevision).toMatchObject({
submittedBy: 'operator',
contentOrigin: 'human',
validationState: 'unvalidated',
ordinal: 2,
});
expect((await f.service.listHypothesisRevisions(h.id))[0]).toEqual(h.latestRevision);
expect(revised.ownerPrincipal).toBe('service');
expect(revised.updatedBy).toBe('operator');
await expect(
f.service.createHypothesis(p.id, { ...hypothesisInput, contentOrigin: 'human' }, 'service')
).rejects.toThrow('cannot declare human');
await expect(
f.service.reviseHypothesis(
h.id,
{ ...hypothesisInput, expectedRevision: 2, validationState: 'validated' },
'operator'
)
).rejects.toThrow();
const n = await f.service.createArtifact(
p.id,
{ ...noteInput, hypothesisRevisionId: h.latestRevision.id },
'service'
);
expect(n.latestRevision).toMatchObject({
submittedBy: 'service',
contentOrigin: 'unknown',
validationState: 'unvalidated',
evidenceState: 'none',
evidence: [],
});
expect(n.hypothesisRevisionId).toBe(h.latestRevision.id);
expect((await f.service.archiveHypothesis(h.id, { archived: true }, 'service')).updatedBy).toBe(
'service'
);
expect(
(await f.service.archiveHypothesis(h.id, { archived: false }, 'operator')).updatedBy
).toBe('operator');
await f.service.archiveHypothesis(h.id, { archived: true }, 'service');
expect(await f.service.listHypotheses(p.id)).toEqual([]);
expect(await f.service.listHypotheses(p.id, true)).toHaveLength(1);
await expect(
f.service.reviseHypothesis(h.id, { ...hypothesisInput, expectedRevision: 2 }, 'operator')
).rejects.toThrow('archived');
const changed = await f.service.reviseArtifact(
n.id,
{ title: 'Human note', body: 'Updated narrative', expectedRevision: 1 },
'operator'
);
expect(changed.hypothesisRevisionId).toBe(h.latestRevision.id);
expect(changed.updatedBy).toBe('operator');
expect(Number.isFinite(Date.parse(changed.updatedAt))).toBe(true);
expect((await f.service.listArtifactRevisions(n.id))[0]).toEqual(n.latestRevision);
expect((await f.service.archiveArtifact(n.id, { archived: true }, 'service')).updatedBy).toBe(
'service'
);
expect((await f.service.archiveArtifact(n.id, { archived: false }, 'operator')).updatedBy).toBe(
'operator'
);
await f.service.archiveArtifact(n.id, { archived: true }, 'service');
expect(await f.service.listArtifacts(p.id)).toEqual([]);
expect(await f.service.listArtifacts(p.id, true)).toHaveLength(1);
await expect(
f.service.reviseArtifact(n.id, { title: 'No', body: '', expectedRevision: 2 }, 'operator')
).rejects.toThrow('archived');
await f.service.updateProject(p.id, { expectedRevision: 1, archived: true }, 'operator');
await expect(f.service.archiveArtifact(n.id, { archived: false }, 'operator')).rejects.toThrow(
'Project is archived'
);
await expect(
f.service.archiveHypothesis(h.id, { archived: false }, 'operator')
).rejects.toThrow('Project is archived');
expect((await f.service.getArtifact(n.id)).latestRevision).toEqual(changed.latestRevision);
});
test('cited_metric_matches_run uses retained legacy conversion, preserves zero/null, and never stores measured copies', async () => {
const f = await fixture();
const { run, definition } = await f.legacy();
const p = await f.service.createProject({ title: 'Evidence' }, 'operator');
const finding = await f.service.createArtifact(
p.id,
{
kind: 'finding',
title: 'AI interpretation',
body: 'This assertion is not validated',
contentOrigin: 'ai',
evidence: [
reference(run.id),
reference(run.id, 'metrics.totalTrades'),
reference(run.id, 'analytics.exposureTime'),
],
},
'service'
);
const result = await f.backtests.getRunResults(run.id);
if (!result || 'kind' in result) {
throw new Error('Expected legacy fixture');
}
const revision = finding.latestRevision;
expect(revision.validationState).toBe('unvalidated');
expect(revision.evidenceState).toBe('referenced');
expect(revision.evidence.map(e => e.value)).toEqual([result.metrics.totalReturn, 0, null]);
expect(revision.evidence[0]?.value).toBe(0.12);
expect(revision.evidence[0]?.unit).toBe('fraction');
expect(revision.evidence[1]?.availability).toBe('available');
expect(revision.evidence[2]?.availability).toBe('unavailable');
expect(revision.evidence[0]?.limitations.length).toBeGreaterThan(0);
const stored = (await f.pool.query('SELECT * FROM analysis_evidence ORDER BY ordinal')).rows;
expect(stored).toHaveLength(3);
expect(Object.keys(stored[0]).sort()).toEqual([
'metric_path',
'metrics_version',
'ordinal',
'revision_id',
'run_id',
'strategy_version_id',
]);
const edited = await f.service.reviseArtifact(
finding.id,
{
title: 'Revised interpretation',
body: 'A different narrative and citation set',
expectedRevision: 1,
evidence: [reference(run.id, 'metrics.winRate')],
},
'operator'
);
expect(edited.latestRevision.evidence[0]?.value).toBe(0.5);
expect((await f.service.listArtifactRevisions(finding.id))[0]).toEqual(revision);
expect(
(await f.pool.query('SELECT * FROM analysis_evidence WHERE revision_id=$1', [revision.id]))
.rowCount
).toBe(3);
await f.backtests.updateBacktest(definition.id, { name: 'Changed template' });
await f.backtests.archiveBacktest(definition.id, true);
await f.service.updateProject(p.id, { expectedRevision: 1, archived: true }, 'operator');
expect((await f.service.getArtifact(finding.id)).latestRevision).toEqual(edited.latestRevision);
expect((await f.pool.query('SELECT * FROM backtest_results')).rowCount).toBe(1);
});
test('canonical citations resolve exact native analytics, immutable strategy binding and unavailable round trips', async () => {
const f = await fixture();
const { run, version } = await f.canonical();
const p = await f.service.createProject({ title: 'Canonical evidence' }, 'operator');
const canonicalReference = (metricPath: string): ResearchEvidenceReference => ({
runId: run.id,
metricsVersion: 'canonical-analytics/v1',
metricPath,
strategyVersionId: version.id,
});
const finding = await f.service.createArtifact(
p.id,
{
kind: 'finding',
title: 'Measured result',
body: 'A hypothesis remains unvalidated',
evidence: [
canonicalReference('analytics.metrics.totalReturn'),
canonicalReference('analytics.fillCount'),
canonicalReference('analytics.metrics.roundTripCount'),
],
},
'operator'
);
const result = await f.backtests.getRunResults(run.id);
if (!result || !('kind' in result)) {
throw new Error('Expected canonical fixture');
}
expect(finding.latestRevision.evidence.map(e => e.value)).toEqual([
result.analytics.metrics.totalReturn,
2,
null,
]);
expect(finding.latestRevision.evidence[2]?.unavailableReason).toBe('unsupported-round-trips');
expect(finding.latestRevision.evidence[0]).toMatchObject({
resultKind: 'canonical',
financialEngine: 'rust',
strategyVersionId: version.id,
datasetHash: result.request.datasetHash,
});
await expect(
f.service.createArtifact(p.id, { ...noteInput, evidence: [reference(run.id)] }, 'operator')
).rejects.toThrow();
await expect(
f.service.createArtifact(
p.id,
{
...noteInput,
evidence: [
{ ...canonicalReference('analytics.fillCount'), strategyVersionId: randomUUID() },
],
},
'operator'
)
).rejects.toThrow();
expect((await f.pool.query('SELECT * FROM analysis_artifacts')).rowCount).toBe(1);
});
test('evidence failures and cross-project links reject atomically; incomplete runs cannot become evidence', async () => {
const f = await fixture();
const p = await f.service.createProject({ title: 'One' }, 'operator');
const other = await f.service.createProject({ title: 'Two' }, 'operator');
const h = await f.service.createHypothesis(other.id, hypothesisInput, 'operator');
await expect(
f.service.createArtifact(
p.id,
{ ...noteInput, hypothesisRevisionId: h.latestRevision.id },
'operator'
)
).rejects.toThrow('this project');
await expect(
f.service.createArtifact(p.id, { ...noteInput, kind: 'finding' }, 'operator')
).rejects.toThrow('at least one');
for (const status of ['pending', 'running', 'failed', 'cancelled']) {
const { run } = await f.legacy(status);
await expect(
f.service.createArtifact(p.id, { ...noteInput, evidence: [reference(run.id)] }, 'operator')
).rejects.toThrow();
}
const { run, definition } = await f.legacy();
const missingResult = await f.backtests.createRun({ backtestId: definition.id });
await f.pool.query("UPDATE runs SET status='completed' WHERE id=$1", [missingResult.id]);
for (const bad of [
reference(randomUUID()),
reference(missingResult.id),
reference(run.id, '__proto__.value'),
{ ...reference(run.id), metricsVersion: 'unknown/v1' },
{ ...reference(run.id), strategyVersionId: randomUUID() },
]) {
await expect(
f.service.createArtifact(p.id, { ...noteInput, evidence: [bad] }, 'operator')
).rejects.toThrow();
}
await expect(
f.service.createArtifact(
p.id,
{ ...noteInput, evidence: [reference(run.id), reference(run.id)] },
'operator'
)
).rejects.toThrow('Duplicate');
expect((await f.pool.query('SELECT * FROM analysis_artifacts')).rowCount).toBe(0);
expect((await f.pool.query('SELECT * FROM analysis_artifact_revisions')).rowCount).toBe(0);
expect((await f.pool.query('SELECT * FROM analysis_evidence')).rowCount).toBe(0);
});
test('evidence_fk_integrity and immutable history guards survive direct SQL and after-commit insertion attempts', async () => {
const f = await fixture();
const { run } = await f.legacy();
const p = await f.service.createProject({ title: 'Retained' }, 'operator');
const h = await f.service.createHypothesis(p.id, hypothesisInput, 'operator');
const finding = await f.service.createArtifact(
p.id,
{ ...noteInput, kind: 'finding', evidence: [reference(run.id)] },
'operator'
);
const rev = finding.latestRevision.id;
for (const query of [
"UPDATE research_hypothesis_revisions SET proposition='rewritten'",
'DELETE FROM research_hypothesis_revisions',
"UPDATE analysis_artifact_revisions SET body='rewritten'",
'DELETE FROM analysis_artifact_revisions',
"UPDATE analysis_evidence SET metric_path='metrics.winRate'",
'DELETE FROM analysis_evidence',
'TRUNCATE analysis_evidence',
'TRUNCATE research_projects CASCADE',
'DELETE FROM research_projects',
'DELETE FROM research_hypotheses',
'DELETE FROM analysis_artifacts',
"UPDATE analysis_artifacts SET kind='note'",
"UPDATE research_hypotheses SET owner_principal='service'",
]) {
await expect(f.pool.query(query)).rejects.toThrow();
}
await expect(
f.pool.query(
'INSERT INTO analysis_evidence(revision_id,ordinal,run_id,metrics_version,metric_path) VALUES($1,2,$2,$3,$4)',
[rev, run.id, 'legacy-display/v1', 'metrics.winRate']
)
).rejects.toThrow('atomically');
await expect(
f.postgres.transaction(async client => {
const id = randomUUID();
await client.query(
'INSERT INTO analysis_artifact_revisions(id,artifact_id,ordinal,title,body,submitted_by,content_origin) VALUES($1,$2,2,$3,$4,$5,$6)',
[id, finding.id, 'Invalid reference', '', 'operator', 'human']
);
await client.query(
'INSERT INTO analysis_evidence(revision_id,ordinal,run_id,metrics_version,metric_path) VALUES($1,1,$2,$3,$4)',
[id, randomUUID(), 'legacy-display/v1', 'metrics.winRate']
);
})
).rejects.toThrow('completed retained result');
await expect(
f.pool.query(
'INSERT INTO analysis_artifact_revisions(id,artifact_id,ordinal,title,body,submitted_by,content_origin) VALUES($1,$2,2,$3,$4,$5,$6)',
[randomUUID(), finding.id, 'Empty finding', '', 'operator', 'human']
)
).rejects.toThrow('requires retained evidence');
const fk = (
await f.pool.query(
"SELECT pg_get_constraintdef(oid) AS definition FROM pg_constraint WHERE conrelid='analysis_evidence'::regclass AND contype='f'"
)
).rows.map(row => row.definition);
expect(
fk.some(value => value.includes('REFERENCES backtest_results(run_id) ON DELETE RESTRICT'))
).toBe(true);
expect(await f.service.listHypothesisRevisions(h.id)).toHaveLength(1);
expect(await f.service.listArtifactRevisions(finding.id)).toHaveLength(1);
expect((await f.service.getArtifact(finding.id)).latestRevision).toEqual(
finding.latestRevision
);
});
test('concurrent revisions use optimistic identity and archive waits on the same project lock', async () => {
const f = await fixture();
const p = await f.service.createProject({ title: 'Concurrency' }, 'operator');
const h = await f.service.createHypothesis(p.id, hypothesisInput, 'operator');
const outcomes = await Promise.allSettled(
[1, 2].map(i =>
f.service.reviseHypothesis(
h.id,
{ ...hypothesisInput, expectedRevision: 1, proposition: `Claim ${i}` },
'operator'
)
)
);
expect(outcomes.filter(o => o.status === 'fulfilled')).toHaveLength(1);
expect(outcomes.filter(o => o.status === 'rejected')).toHaveLength(1);
expect(await f.service.listHypothesisRevisions(h.id)).toHaveLength(2);
const n = await f.service.createArtifact(p.id, noteInput, 'operator');
const edits = await Promise.allSettled(
[1, 2].map(i =>
f.service.reviseArtifact(
n.id,
{ title: 'Note', body: `Narrative ${i}`, expectedRevision: 1 },
'operator'
)
)
);
expect(edits.filter(o => o.status === 'fulfilled')).toHaveLength(1);
expect(edits.filter(o => o.status === 'rejected')).toHaveLength(1);
expect(await f.service.listArtifactRevisions(n.id)).toHaveLength(2);
const held = await f.pool.connect();
await held.query('BEGIN');
await held.query('SELECT id FROM research_projects WHERE id=$1 FOR UPDATE', [p.id]);
const archive = f.service.updateProject(
p.id,
{ expectedRevision: 1, archived: true },
'operator'
);
const waiters = async (count: number) => {
const deadline = Date.now() + 5000;
while (Date.now() < deadline) {
const q = await f.pool.query(
"SELECT count(*)::int AS count FROM pg_stat_activity WHERE application_name=$1 AND wait_event_type='Lock'",
[f.schema]
);
if (q.rows[0].count >= count) {
return;
}
await Bun.sleep(10);
}
throw new Error('Expected project lock waiter');
};
try {
await waiters(1);
const revision = f.service
.reviseArtifact(n.id, { title: 'After archive', body: '', expectedRevision: 2 }, 'operator')
.then(
value => ({ value }),
error => ({ error })
);
await waiters(2);
await held.query('COMMIT');
expect((await archive).archived).toBe(true);
const result = await revision;
expect('error' in result).toBe(true);
if ('error' in result) {
expect(String(result.error)).toContain('Project is archived');
}
expect(await f.service.listArtifactRevisions(n.id)).toHaveLength(2);
} finally {
await held.query('ROLLBACK');
held.release();
}
});
test('migration upgrade and reapply preserve existing canonical and legacy runs/results byte-for-byte', async () => {
const f = await fixture(false);
const legacy = await f.legacy();
const canonical = await f.canonical();
const snapshot = async () => ({
runs: (await f.pool.query('SELECT * FROM runs ORDER BY id')).rows,
results: (await f.pool.query('SELECT * FROM backtest_results ORDER BY run_id')).rows,
datasets: (await f.pool.query('SELECT * FROM backtest_datasets ORDER BY hash')).rows,
versions: (await f.pool.query('SELECT * FROM strategy_versions ORDER BY id')).rows,
});
const before = await snapshot();
await f.pool.query(migration);
await f.pool.query(migration);
expect(await snapshot()).toEqual(before);
const p = await f.service.createProject({ title: 'After upgrade' }, 'operator');
const finding = await f.service.createArtifact(
p.id,
{
...noteInput,
kind: 'finding',
evidence: [
reference(legacy.run.id),
{
runId: canonical.run.id,
metricsVersion: 'canonical-analytics/v1',
metricPath: 'analytics.fillCount',
},
],
},
'operator'
);
await f.pool.query(migration);
expect(await snapshot()).toEqual(before);
expect(
(await f.service.getArtifact(finding.id)).latestRevision.evidence.map(e => e.resultKind)
).toEqual(['legacy', 'canonical']);
});
});