diff --git a/apps/stock/config/package.json b/apps/stock/config/package.json index 181c5ab4..ddd145a0 100644 --- a/apps/stock/config/package.json +++ b/apps/stock/config/package.json @@ -24,6 +24,10 @@ "./canonical-research": { "types": "./dist/contracts/canonical-research.d.ts", "default": "./dist/contracts/canonical-research.js" + }, + "./research": { + "types": "./dist/contracts/research.d.ts", + "default": "./dist/contracts/research.js" } }, "scripts": { diff --git a/apps/stock/config/src/contracts/research.ts b/apps/stock/config/src/contracts/research.ts new file mode 100644 index 00000000..14f6794c --- /dev/null +++ b/apps/stock/config/src/contracts/research.ts @@ -0,0 +1,136 @@ +import { z } from 'zod'; +import { assertStrategyJsonText } from './strategy'; + +export const researchIdSchema = z.string().uuid(); +export const researchActorSchema = z.enum(['operator', 'service']); +const origin = z.enum(['human', 'ai', 'unknown']).optional(); +const title = z.string().trim().min(1); +const ordinal = z.number().int().positive().max(2147483647); +export const createResearchProjectSchema = z + .object({ + title, + description: z.string().default(''), + }) + .strict(); +export const updateResearchProjectSchema = z + .object({ + expectedRevision: ordinal, + title: title.optional(), + description: z.string().optional(), + archived: z.boolean().optional(), + }) + .strict(); +export const archiveResearchSchema = z.object({ archived: z.boolean() }).strict(); +export const createResearchHypothesisSchema = z + .object({ + title, + proposition: z.string().trim().min(1), + validationCriteria: z.string().default(''), + contentOrigin: origin, + }) + .strict(); +export const reviseResearchHypothesisSchema = createResearchHypothesisSchema + .extend({ + expectedRevision: ordinal, + }) + .strict(); + +export const canonicalResearchMetricPaths = [ + 'analytics.metrics.totalReturn', + 'analytics.metrics.cagr', + 'analytics.metrics.maxDrawdown', + 'analytics.metrics.exposureTime', + 'analytics.metrics.volatility', + 'analytics.metrics.downsideDeviation', + 'analytics.metrics.sharpeRatio', + 'analytics.metrics.sortinoRatio', + 'analytics.metrics.var95', + 'analytics.metrics.cvar95', + 'analytics.metrics.var99', + 'analytics.metrics.alpha', + 'analytics.metrics.beta', + 'analytics.metrics.informationRatio', + 'analytics.metrics.roundTripCount', + 'analytics.metrics.winRate', + 'analytics.metrics.profitFactor', + 'analytics.metrics.avgWin', + 'analytics.metrics.avgLoss', + 'analytics.fillCount', +] as const; +export const legacyResearchMetricPaths = [ + 'metrics.totalReturn', + 'metrics.sharpeRatio', + 'metrics.maxDrawdown', + 'metrics.winRate', + 'metrics.totalTrades', + 'metrics.profitFactor', + 'metrics.avgWin', + 'metrics.avgLoss', + 'analytics.exposureTime', +] as const; +export const researchEvidenceReferenceSchema = z.discriminatedUnion('metricsVersion', [ + z + .object({ + runId: researchIdSchema, + metricsVersion: z.literal('canonical-analytics/v1'), + metricPath: z.enum(canonicalResearchMetricPaths), + strategyVersionId: researchIdSchema.nullable().optional(), + }) + .strict(), + z + .object({ + runId: researchIdSchema, + metricsVersion: z.literal('legacy-display/v1'), + metricPath: z.enum(legacyResearchMetricPaths), + strategyVersionId: researchIdSchema.nullable().optional(), + }) + .strict(), +]); +const evidence = z + .array(researchEvidenceReferenceSchema) + .default([]) + .superRefine((items, ctx) => { + const keys = new Set(); + for (const item of items) { + const key = `${item.runId}:${item.metricsVersion}:${item.metricPath}`; + if (keys.has(key)) { + ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Duplicate evidence reference' }); + } + keys.add(key); + } + }); +export const createResearchArtifactSchema = z + .object({ + kind: z.enum(['note', 'finding']), + hypothesisRevisionId: researchIdSchema.nullable().default(null), + title, + body: z.string(), + contentOrigin: origin, + evidence, + }) + .strict(); +export const reviseResearchArtifactSchema = z + .object({ + expectedRevision: ordinal, + title, + body: z.string(), + contentOrigin: origin, + evidence, + }) + .strict(); + +/** Shared text validity only; neither financial calculations nor code evaluation. */ +export function parseResearchInput(schema: S, input: unknown): z.output { + try { + assertStrategyJsonText(input); + } catch { + throw new z.ZodError([ + { + code: z.ZodIssueCode.custom, + path: [], + message: 'Research metadata must contain valid JSON text', + }, + ]); + } + return schema.parse(input); +} diff --git a/apps/stock/web-api/src/migrations/migration-runner.ts b/apps/stock/web-api/src/migrations/migration-runner.ts index 689f523e..0a6a53a3 100644 --- a/apps/stock/web-api/src/migrations/migration-runner.ts +++ b/apps/stock/web-api/src/migrations/migration-runner.ts @@ -59,7 +59,8 @@ export async function runMigrations(container: IServiceContainer): Promise f === '16-strategy-catalog.sql' || f === '17-research-retention.sql' || f === '18-backtest-strategy-versions.sql' || - f === '19-canonical-research.sql') + f === '19-canonical-research.sql' || + f === '20-research-workspace.sql') ) // Explicit additive migration allowlist; never replay destructive init migrations .sort(); diff --git a/apps/stock/web-api/src/routes/create-routes.ts b/apps/stock/web-api/src/routes/create-routes.ts index fce2b72c..30d0f251 100644 --- a/apps/stock/web-api/src/routes/create-routes.ts +++ b/apps/stock/web-api/src/routes/create-routes.ts @@ -14,6 +14,7 @@ import { createExchangeRoutes } from './exchange.routes'; import { createHealthRoutes } from './health.routes'; import { createMonitoringRoutes } from './monitoring.routes'; import { createPipelineRoutes } from './pipeline.routes'; +import { createResearchRoutes } from './research.routes'; import { createStrategyRoutes } from './strategies.routes'; export function createRoutes( @@ -51,6 +52,7 @@ export function createRoutes( app.route('/', backtestV2Routes); // V2 routes also mounted at root app.route('/', createDatasetRoutes(container)); app.route('/', createStrategyRoutes(container)); + app.route('/', createResearchRoutes(container)); return app; } diff --git a/apps/stock/web-api/src/routes/research.routes.ts b/apps/stock/web-api/src/routes/research.routes.ts new file mode 100644 index 00000000..026cb206 --- /dev/null +++ b/apps/stock/web-api/src/routes/research.routes.ts @@ -0,0 +1,190 @@ +import { Hono, type MiddlewareHandler } from 'hono'; +import { z } from 'zod'; +import { getCredentialHttpPrincipal } from '@stock-bot/di'; +import type { IServiceContainer } from '@stock-bot/services'; +import { archiveResearchSchema, parseResearchInput } from '@stock-bot/stock-config/research'; +import { ResearchError } from '../services/research-errors'; +import { ResearchService } from '../services/research.service'; + +const emptyBody = z.object({}).strict(); +function includeArchived(value: string | undefined): boolean { + if (value === undefined || value === 'false') { + return false; + } + if (value === 'true') { + return true; + } + throw new ResearchError(400, 'includeArchived must be true or false'); +} +async function noMutationBody(request: Request): Promise { + const body = await request.text(); + if (body !== '') { + emptyBody.parse(JSON.parse(body)); + } +} + +/** Research metadata only; the mounted security layer owns authenticated read access. */ +export function createResearchRoutes(container: IServiceContainer) { + const app = new Hono(); + const service = new ResearchService(container); + const credentials: MiddlewareHandler = async (c, next) => { + c.header('Cache-Control', 'no-store'); + if (!['GET', 'HEAD'].includes(c.req.method) && !getCredentialHttpPrincipal(c.req.raw)) { + return c.json({ error: 'Verified credential principal required' }, 401); + } + await next(); + return undefined; + }; + for (const path of [ + '/api/v2/research-projects', + '/api/v2/research-projects/*', + '/api/v2/hypotheses/*', + '/api/v2/analysis-artifacts/*', + ]) { + app.use(path, credentials); + } + app.onError((error, c) => { + if (error instanceof ResearchError) { + return c.json({ error: error.message }, error.status); + } + if (error instanceof z.ZodError || error instanceof SyntaxError) { + return c.json({ error: 'Invalid research request' }, 400); + } + container.logger.error('Research operation failed', { error }); + return c.json({ error: 'Research workspace unavailable' }, 500); + }); + const actor = (request: Request) => { + const principal = getCredentialHttpPrincipal(request); + if (!principal) { + throw new ResearchError(401, 'Verified credential principal required'); + } + return principal; + }; + + app.get('/api/v2/research-projects', async c => + c.json({ + projects: await service.listProjects(includeArchived(c.req.query('includeArchived'))), + }) + ); + app.post('/api/v2/research-projects', async c => + c.json({ project: await service.createProject(await c.req.json(), actor(c.req.raw)) }, 201) + ); + app.get('/api/v2/research-projects/:id', async c => + c.json({ project: await service.getProject(c.req.param('id')) }) + ); + app.patch('/api/v2/research-projects/:id', async c => + c.json({ + project: await service.updateProject(c.req.param('id'), await c.req.json(), actor(c.req.raw)), + }) + ); + app.get('/api/v2/research-projects/:id/strategies', async c => + c.json({ strategies: await service.listProjectStrategies(c.req.param('id')) }) + ); + app.put('/api/v2/research-projects/:id/strategies/:strategyId', async c => { + await noMutationBody(c.req.raw); + await service.linkStrategy(c.req.param('id'), c.req.param('strategyId'), actor(c.req.raw)); + return c.body(null, 204); + }); + app.delete('/api/v2/research-projects/:id/strategies/:strategyId', async c => { + await noMutationBody(c.req.raw); + await service.unlinkStrategy(c.req.param('id'), c.req.param('strategyId'), actor(c.req.raw)); + return c.body(null, 204); + }); + + app.get('/api/v2/research-projects/:id/hypotheses', async c => + c.json({ + hypotheses: await service.listHypotheses( + c.req.param('id'), + includeArchived(c.req.query('includeArchived')) + ), + }) + ); + app.post('/api/v2/research-projects/:id/hypotheses', async c => + c.json( + { + hypothesis: await service.createHypothesis( + c.req.param('id'), + await c.req.json(), + actor(c.req.raw) + ), + }, + 201 + ) + ); + app.get('/api/v2/hypotheses/:id', async c => + c.json({ hypothesis: await service.getHypothesis(c.req.param('id')) }) + ); + app.get('/api/v2/hypotheses/:id/revisions', async c => + c.json({ revisions: await service.listHypothesisRevisions(c.req.param('id')) }) + ); + app.post('/api/v2/hypotheses/:id/revisions', async c => + c.json( + { + hypothesis: await service.reviseHypothesis( + c.req.param('id'), + await c.req.json(), + actor(c.req.raw) + ), + }, + 201 + ) + ); + app.patch('/api/v2/hypotheses/:id', async c => + c.json({ + hypothesis: await service.archiveHypothesis( + c.req.param('id'), + parseResearchInput(archiveResearchSchema, await c.req.json()), + actor(c.req.raw) + ), + }) + ); + + app.get('/api/v2/research-projects/:id/analysis-artifacts', async c => + c.json({ + artifacts: await service.listArtifacts( + c.req.param('id'), + includeArchived(c.req.query('includeArchived')) + ), + }) + ); + app.post('/api/v2/research-projects/:id/analysis-artifacts', async c => + c.json( + { + artifact: await service.createArtifact( + c.req.param('id'), + await c.req.json(), + actor(c.req.raw) + ), + }, + 201 + ) + ); + app.get('/api/v2/analysis-artifacts/:id', async c => + c.json({ artifact: await service.getArtifact(c.req.param('id')) }) + ); + app.get('/api/v2/analysis-artifacts/:id/revisions', async c => + c.json({ revisions: await service.listArtifactRevisions(c.req.param('id')) }) + ); + app.post('/api/v2/analysis-artifacts/:id/revisions', async c => + c.json( + { + artifact: await service.reviseArtifact( + c.req.param('id'), + await c.req.json(), + actor(c.req.raw) + ), + }, + 201 + ) + ); + app.patch('/api/v2/analysis-artifacts/:id', async c => + c.json({ + artifact: await service.archiveArtifact( + c.req.param('id'), + parseResearchInput(archiveResearchSchema, await c.req.json()), + actor(c.req.raw) + ), + }) + ); + return app; +} diff --git a/apps/stock/web-api/src/services/backtest-v2.service.ts b/apps/stock/web-api/src/services/backtest-v2.service.ts index 1263dc51..5b33a053 100644 --- a/apps/stock/web-api/src/services/backtest-v2.service.ts +++ b/apps/stock/web-api/src/services/backtest-v2.service.ts @@ -41,6 +41,13 @@ const logger = getLogger('backtest-v2-service'); const ORCHESTRATOR_URL = process.env.ORCHESTRATOR_URL || 'http://localhost:2004'; export type BacktestTransport = (url: string, init?: RequestInit) => Promise; +/** Reads may share an existing transaction without acquiring another pool connection. */ +export interface BacktestResultQuery { + query( + text: string, + values?: unknown[] + ): Promise<{ rows: T[] }>; +} export interface BacktestRequest { name: string; @@ -580,8 +587,11 @@ export class BacktestServiceV2 { } // Get run results - async getRunResults(runId: string): Promise { - const result = await this.container.postgres.query< + async getRunResults( + runId: string, + database: BacktestResultQuery = this.container.postgres + ): Promise { + const result = await database.query< StoredBacktestResult & { canonical_result?: CanonicalRunResult | null; request_snapshot?: unknown; diff --git a/apps/stock/web-api/src/services/research-errors.ts b/apps/stock/web-api/src/services/research-errors.ts new file mode 100644 index 00000000..0284b33e --- /dev/null +++ b/apps/stock/web-api/src/services/research-errors.ts @@ -0,0 +1,8 @@ +export class ResearchError extends Error { + constructor( + public readonly status: 400 | 401 | 403 | 404 | 409 | 422, + message: string + ) { + super(message); + } +} diff --git a/apps/stock/web-api/src/services/research-evidence.ts b/apps/stock/web-api/src/services/research-evidence.ts new file mode 100644 index 00000000..e40516e8 --- /dev/null +++ b/apps/stock/web-api/src/services/research-evidence.ts @@ -0,0 +1,161 @@ +import { requireServices, type IServiceContainer } from '@stock-bot/services'; +import { + isCanonicalRunResult, + type ResearchRunResult, +} from '@stock-bot/stock-config/canonical-research'; +import { + parseResearchInput, + researchEvidenceReferenceSchema, +} from '@stock-bot/stock-config/research'; +import type { + CanonicalMetrics, + ResearchEvidence, + ResearchEvidenceReference, +} from '@stock-bot/types'; +import { BacktestServiceV2, type BacktestResultQuery } from './backtest-v2.service'; +import { ResearchError } from './research-errors'; + +function unitOf(path: string): ResearchEvidence['unit'] { + const name = path.split('.').at(-1); + if (['fillCount', 'roundTripCount', 'totalTrades'].includes(name ?? '')) { + return 'count'; + } + if (['avgWin', 'avgLoss'].includes(name ?? '')) { + return 'currency'; + } + if ( + ['sharpeRatio', 'sortinoRatio', 'profitFactor', 'beta', 'informationRatio'].includes(name ?? '') + ) { + return 'ratio'; + } + return 'fraction'; +} + +/** Select existing scalar measurements only. No metric, accounting or validation recalculation. */ +export function projectResearchEvidence( + input: ResearchEvidenceReference, + result: ResearchRunResult +): ResearchEvidence { + const reference = parseResearchInput(researchEvidenceReferenceSchema, input); + if (result.runId !== reference.runId || result.status !== 'completed') { + throw new ResearchError(422, 'Evidence must refer to the completed retained run'); + } + let value: number | null | undefined; + let unavailableReason: string | null; + let details: Pick< + ResearchEvidence, + 'resultKind' | 'financialEngine' | 'datasetHash' | 'limitations' + >; + if (isCanonicalRunResult(result)) { + if (reference.metricsVersion !== 'canonical-analytics/v1' || result.analytics.version !== 1) { + throw new ResearchError(422, 'Metrics version does not match this retained result'); + } + if ( + reference.strategyVersionId && + reference.strategyVersionId !== result.request.strategy.versionId + ) { + throw new ResearchError(422, 'Strategy version is not bound by this run'); + } + const key = reference.metricPath.slice('analytics.metrics.'.length) as keyof CanonicalMetrics; + value = + reference.metricPath === 'analytics.fillCount' + ? result.analytics.fillCount + : result.analytics.metrics[key]; + unavailableReason = + value === null ? (result.analytics.unavailable[key] ?? 'not-reported') : null; + details = { + resultKind: 'canonical', + financialEngine: 'rust', + datasetHash: result.request.datasetHash, + limitations: [...result.financial.limitations, ...result.financial.modelLimitations].map( + message => ({ code: 'canonical-model-limitation', message }) + ), + }; + } else { + if (reference.metricsVersion !== 'legacy-display/v1' || reference.strategyVersionId) { + throw new ResearchError( + 422, + 'Legacy results cannot certify this metrics or executable version' + ); + } + value = + reference.metricPath === 'analytics.exposureTime' + ? result.analytics.exposureTime + : result.metrics[reference.metricPath.slice('metrics.'.length)]; + unavailableReason = value === null || value === undefined ? 'legacy-unavailable' : null; + // Legacy v1 names this read-only display adapter, not an engine/economics version. + details = { + resultKind: 'legacy', + financialEngine: result.engine, + datasetHash: result.provenance?.datasetHash ?? null, + limitations: [ + { + code: 'legacy-unverified-economics', + message: + 'Legacy display measurements are exploratory evidence; financial correctness and historical engine versions are not certified.', + }, + ...(result.provenance?.limitations ?? []), + ], + }; + } + if ( + value !== null && + value !== undefined && + (typeof value !== 'number' || !Number.isFinite(value)) + ) { + throw new ResearchError(422, 'Retained metric is not a finite scalar measurement'); + } + if (value === undefined) { + value = null; + unavailableReason ??= 'not-reported'; + } + return { + ...reference, + backtestId: result.backtestId, + value, + unit: unitOf(reference.metricPath), + availability: value === null ? 'unavailable' : 'available', + unavailableReason, + ...details, + }; +} + +export class ResearchEvidenceResolver { + private readonly database; + private readonly results; + constructor(container: IServiceContainer) { + this.database = requireServices(container, 'postgres').postgres; + this.results = new BacktestServiceV2(container); + } + + async resolve( + input: ResearchEvidenceReference, + database: BacktestResultQuery = this.database + ): Promise { + const reference = parseResearchInput(researchEvidenceReferenceSchema, input); + const run = ( + await database.query<{ id: string; backtest_id: string; status: string }>( + 'SELECT id,backtest_id,status FROM runs WHERE id=$1', + [reference.runId] + ) + ).rows[0]; + if (!run || run.status !== 'completed') { + throw new ResearchError(422, 'Evidence requires a completed retained run'); + } + let result; + try { + result = await this.results.getRunResults(reference.runId, database); + } catch (cause) { + // Validation here concerns retained storage, not the caller's valid reference. + // Preserve the cause for server diagnostics without returning a false HTTP 400. + throw new Error('Retained research result could not be read', { cause }); + } + if (!result || result.runId !== run.id || result.backtestId !== run.backtest_id) { + throw new ResearchError( + 422, + 'Retained evidence result is missing or has a different identity' + ); + } + return projectResearchEvidence(reference, result); + } +} diff --git a/apps/stock/web-api/src/services/research.service.ts b/apps/stock/web-api/src/services/research.service.ts new file mode 100644 index 00000000..5cfece18 --- /dev/null +++ b/apps/stock/web-api/src/services/research.service.ts @@ -0,0 +1,631 @@ +import { randomUUID } from 'node:crypto'; +import type { PoolClient, QueryResultRow } from 'pg'; +import { requireServices, type IServiceContainer } from '@stock-bot/services'; +import { + archiveResearchSchema, + createResearchArtifactSchema, + createResearchHypothesisSchema, + createResearchProjectSchema, + parseResearchInput, + researchActorSchema, + researchIdSchema, + reviseResearchArtifactSchema, + reviseResearchHypothesisSchema, + updateResearchProjectSchema, +} from '@stock-bot/stock-config/research'; +import type { + ResearchActor, + ResearchArtifact, + ResearchArtifactRevision, + ResearchAuthorship, + ResearchContentOrigin, + ResearchEvidenceReference, + ResearchHypothesis, + ResearchHypothesisRevision, + ResearchProject, + StrategyRecord, +} from '@stock-bot/types'; +import { ResearchError } from './research-errors'; +import { ResearchEvidenceResolver } from './research-evidence'; +import { StrategyCatalogService } from './strategy-catalog.service'; + +type Database = { + query( + text: string, + values?: unknown[] + ): Promise<{ rows: T[] }>; +}; +const iso = (value: string | Date) => new Date(value).toISOString(); +function required(row: QueryResultRow | undefined, label: string): QueryResultRow { + if (!row) { + throw new ResearchError(404, `${label} not found`); + } + return row; +} +function authorship(actor: ResearchActor, origin?: ResearchContentOrigin): ResearchAuthorship { + researchActorSchema.parse(actor); + if (actor === 'service' && origin === 'human') { + throw new ResearchError(403, 'Service credentials cannot declare human authorship'); + } + return { + submittedBy: actor, + contentOrigin: origin ?? (actor === 'operator' ? 'human' : 'unknown'), + }; +} +function project(row: QueryResultRow): ResearchProject { + return { + id: row.id, + title: row.title, + description: row.description, + revision: row.revision, + ownerPrincipal: row.owner_principal, + updatedBy: row.updated_by, + archived: row.archived_at !== null, + createdAt: iso(row.created_at), + updatedAt: iso(row.updated_at), + }; +} +function hypothesisRevision(row: QueryResultRow): ResearchHypothesisRevision { + return { + id: row.id, + hypothesisId: row.hypothesis_id, + ordinal: row.ordinal, + title: row.title, + proposition: row.proposition, + validationCriteria: row.validation_criteria, + submittedBy: row.submitted_by, + contentOrigin: row.content_origin, + validationState: 'unvalidated', + createdAt: iso(row.created_at), + }; +} +function expectRevision(actual: number, expected: number): void { + if (actual !== expected) { + throw new ResearchError(409, 'Research revision changed; reload before editing'); + } +} +function active(row: QueryResultRow, label: string): void { + if (row.archived_at !== null) { + throw new ResearchError(409, `${label} is archived; restore it before editing`); + } +} + +/** Metadata transactions only. The existing result reader owns every measured value. */ +export class ResearchService { + private readonly database; + private readonly evidence; + private readonly catalog; + constructor(container: IServiceContainer) { + this.database = requireServices(container, 'postgres').postgres; + this.evidence = new ResearchEvidenceResolver(container); + this.catalog = new StrategyCatalogService(container); + } + + async listProjects(includeArchived = false): Promise { + return ( + await this.database.query( + 'SELECT * FROM research_projects WHERE ($1::boolean OR archived_at IS NULL) ORDER BY created_at DESC,id', + [includeArchived] + ) + ).rows.map(project); + } + async createProject(input: unknown, actor: ResearchActor): Promise { + const data = parseResearchInput(createResearchProjectSchema, input); + researchActorSchema.parse(actor); + return project( + required( + ( + await this.database.query( + 'INSERT INTO research_projects(id,title,description,owner_principal,updated_by) VALUES($1,$2,$3,$4,$4) RETURNING *', + [randomUUID(), data.title, data.description, actor] + ) + ).rows[0], + 'Created project' + ) + ); + } + async getProject(id: string): Promise { + return project(await this.projectRow(this.database, researchIdSchema.parse(id))); + } + async updateProject(id: string, input: unknown, actor: ResearchActor): Promise { + researchIdSchema.parse(id); + const data = parseResearchInput(updateResearchProjectSchema, input); + researchActorSchema.parse(actor); + if (data.title === undefined && data.description === undefined && data.archived === undefined) { + throw new ResearchError(400, 'Supply a project change'); + } + return this.database.transaction(async client => { + const old = await this.projectRow(client, id, true); + expectRevision(old.revision, data.expectedRevision); + if ( + old.archived_at !== null && + (data.archived !== false || data.title !== undefined || data.description !== undefined) + ) { + throw new ResearchError(409, 'Archived projects only permit restoration'); + } + return project( + required( + ( + await client.query( + `UPDATE research_projects SET title=$2,description=$3,archived_at=$4,revision=revision+1, + updated_by=$5,updated_at=NOW() WHERE id=$1 RETURNING *`, + [ + id, + data.title ?? old.title, + data.description ?? old.description, + data.archived === undefined + ? old.archived_at + : data.archived + ? (old.archived_at ?? new Date()) + : null, + actor, + ] + ) + ).rows[0], + 'Project' + ) + ); + }); + } + + async listProjectStrategies(projectId: string): Promise { + await this.getProject(projectId); + const rows = ( + await this.database.query( + 'SELECT strategy_id FROM research_project_strategies WHERE project_id=$1 ORDER BY created_at,strategy_id', + [projectId] + ) + ).rows; + return Promise.all(rows.map(row => this.catalog.getStrategy(row.strategy_id))); + } + async linkStrategy(projectId: string, strategyId: string, actor: ResearchActor): Promise { + researchIdSchema.parse(projectId); + researchIdSchema.parse(strategyId); + researchActorSchema.parse(actor); + await this.database.transaction(async client => { + active(await this.projectRow(client, projectId, true), 'Project'); + const selected = required( + (await client.query('SELECT * FROM strategies WHERE id=$1 FOR UPDATE', [strategyId])) + .rows[0], + 'Strategy' + ); + active(selected, 'Strategy'); + const inserted = await client.query( + 'INSERT INTO research_project_strategies(project_id,strategy_id,added_by) VALUES($1,$2,$3) ON CONFLICT DO NOTHING RETURNING project_id', + [projectId, strategyId, actor] + ); + if (inserted.rows.length) { + await client.query( + 'UPDATE research_projects SET revision=revision+1,updated_by=$2,updated_at=NOW() WHERE id=$1', + [projectId, actor] + ); + } + }); + } + async unlinkStrategy(projectId: string, strategyId: string, actor: ResearchActor): Promise { + researchIdSchema.parse(projectId); + researchIdSchema.parse(strategyId); + researchActorSchema.parse(actor); + await this.database.transaction(async client => { + active(await this.projectRow(client, projectId, true), 'Project'); + const removed = await client.query( + 'DELETE FROM research_project_strategies WHERE project_id=$1 AND strategy_id=$2 RETURNING project_id', + [projectId, strategyId] + ); + if (removed.rows.length) { + await client.query( + 'UPDATE research_projects SET revision=revision+1,updated_by=$2,updated_at=NOW() WHERE id=$1', + [projectId, actor] + ); + } + }); + } + + async listHypotheses(projectId: string, includeArchived = false): Promise { + await this.getProject(projectId); + const rows = ( + await this.database.query( + 'SELECT * FROM research_hypotheses WHERE project_id=$1 AND ($2::boolean OR archived_at IS NULL) ORDER BY created_at DESC,id', + [projectId, includeArchived] + ) + ).rows; + return Promise.all(rows.map(row => this.hypothesis(this.database, row))); + } + async createHypothesis( + projectId: string, + input: unknown, + actor: ResearchActor + ): Promise { + researchIdSchema.parse(projectId); + const data = parseResearchInput(createResearchHypothesisSchema, input); + const author = authorship(actor, data.contentOrigin); + return this.database.transaction(async client => { + active(await this.projectRow(client, projectId, true), 'Project'); + const row = required( + ( + await client.query( + 'INSERT INTO research_hypotheses(id,project_id,owner_principal,updated_by) VALUES($1,$2,$3,$3) RETURNING *', + [randomUUID(), projectId, actor] + ) + ).rows[0], + 'Created hypothesis' + ); + await this.insertHypothesisRevision(client, row.id, 1, data, author); + return this.hypothesis(client, row); + }); + } + async getHypothesis(id: string): Promise { + return this.hypothesis( + this.database, + await this.hypothesisRow(this.database, researchIdSchema.parse(id)) + ); + } + async listHypothesisRevisions(id: string): Promise { + researchIdSchema.parse(id); + await this.hypothesisRow(this.database, id); + return ( + await this.database.query( + 'SELECT * FROM research_hypothesis_revisions WHERE hypothesis_id=$1 ORDER BY ordinal', + [id] + ) + ).rows.map(hypothesisRevision); + } + async reviseHypothesis( + id: string, + input: unknown, + actor: ResearchActor + ): Promise { + researchIdSchema.parse(id); + const data = parseResearchInput(reviseResearchHypothesisSchema, input); + const author = authorship(actor, data.contentOrigin); + return this.database.transaction(async client => { + const row = await this.lockHypothesis(client, id); + active(row, 'Hypothesis'); + const current = await this.hypothesis(client, row); + expectRevision(current.latestRevision.ordinal, data.expectedRevision); + await this.insertHypothesisRevision(client, id, data.expectedRevision + 1, data, author); + const updated = required( + ( + await client.query( + 'UPDATE research_hypotheses SET updated_by=$2,updated_at=NOW() WHERE id=$1 RETURNING *', + [id, actor] + ) + ).rows[0], + 'Hypothesis' + ); + return this.hypothesis(client, updated); + }); + } + async archiveHypothesis( + id: string, + input: unknown, + actor: ResearchActor + ): Promise { + researchIdSchema.parse(id); + const data = parseResearchInput(archiveResearchSchema, input); + researchActorSchema.parse(actor); + return this.database.transaction(async client => { + await this.lockHypothesis(client, id); + const row = required( + ( + await client.query( + 'UPDATE research_hypotheses SET archived_at=CASE WHEN $2 THEN COALESCE(archived_at,NOW()) ELSE NULL END,updated_by=$3,updated_at=NOW() WHERE id=$1 RETURNING *', + [id, data.archived, actor] + ) + ).rows[0], + 'Hypothesis' + ); + return this.hypothesis(client, row); + }); + } + + async listArtifacts(projectId: string, includeArchived = false): Promise { + await this.getProject(projectId); + const rows = ( + await this.database.query( + 'SELECT * FROM analysis_artifacts WHERE project_id=$1 AND ($2::boolean OR archived_at IS NULL) ORDER BY created_at DESC,id', + [projectId, includeArchived] + ) + ).rows; + return Promise.all(rows.map(row => this.artifact(this.database, row))); + } + async createArtifact( + projectId: string, + input: unknown, + actor: ResearchActor + ): Promise { + researchIdSchema.parse(projectId); + const data = parseResearchInput(createResearchArtifactSchema, input); + const author = authorship(actor, data.contentOrigin); + this.requireFindingEvidence(data.kind, data.evidence); + return this.database.transaction(async client => { + active(await this.projectRow(client, projectId, true), 'Project'); + if (data.hypothesisRevisionId) { + const linked = ( + await client.query( + `SELECT h.* FROM research_hypothesis_revisions r JOIN research_hypotheses h ON h.id=r.hypothesis_id + WHERE r.id=$1 FOR UPDATE OF h`, + [data.hypothesisRevisionId] + ) + ).rows[0]; + if (!linked || linked.project_id !== projectId) { + throw new ResearchError(422, 'Hypothesis revision must belong to this project'); + } + active(linked, 'Hypothesis'); + } + const row = required( + ( + await client.query( + 'INSERT INTO analysis_artifacts(id,project_id,hypothesis_revision_id,kind,owner_principal,updated_by) VALUES($1,$2,$3,$4,$5,$5) RETURNING *', + [randomUUID(), projectId, data.hypothesisRevisionId, data.kind, actor] + ) + ).rows[0], + 'Created artifact' + ); + await this.insertArtifactRevision(client, row.id, 1, data, author); + return this.artifact(client, row); + }); + } + async getArtifact(id: string): Promise { + return this.artifact( + this.database, + await this.artifactRow(this.database, researchIdSchema.parse(id)) + ); + } + async listArtifactRevisions(id: string): Promise { + researchIdSchema.parse(id); + await this.artifactRow(this.database, id); + const rows = ( + await this.database.query( + 'SELECT * FROM analysis_artifact_revisions WHERE artifact_id=$1 ORDER BY ordinal', + [id] + ) + ).rows; + return Promise.all(rows.map(row => this.artifactRevision(this.database, row))); + } + async reviseArtifact( + id: string, + input: unknown, + actor: ResearchActor + ): Promise { + researchIdSchema.parse(id); + const data = parseResearchInput(reviseResearchArtifactSchema, input); + const author = authorship(actor, data.contentOrigin); + return this.database.transaction(async client => { + const row = await this.lockArtifact(client, id); + active(row, 'Artifact'); + this.requireFindingEvidence(row.kind, data.evidence); + const current = required( + ( + await client.query( + 'SELECT ordinal FROM analysis_artifact_revisions WHERE artifact_id=$1 ORDER BY ordinal DESC LIMIT 1', + [id] + ) + ).rows[0], + 'Artifact revision' + ); + expectRevision(current.ordinal, data.expectedRevision); + await this.insertArtifactRevision(client, id, data.expectedRevision + 1, data, author); + const updated = required( + ( + await client.query( + 'UPDATE analysis_artifacts SET updated_by=$2,updated_at=NOW() WHERE id=$1 RETURNING *', + [id, actor] + ) + ).rows[0], + 'Artifact' + ); + return this.artifact(client, updated); + }); + } + async archiveArtifact( + id: string, + input: unknown, + actor: ResearchActor + ): Promise { + researchIdSchema.parse(id); + const data = parseResearchInput(archiveResearchSchema, input); + researchActorSchema.parse(actor); + return this.database.transaction(async client => { + await this.lockArtifact(client, id); + const row = required( + ( + await client.query( + 'UPDATE analysis_artifacts SET archived_at=CASE WHEN $2 THEN COALESCE(archived_at,NOW()) ELSE NULL END,updated_by=$3,updated_at=NOW() WHERE id=$1 RETURNING *', + [id, data.archived, actor] + ) + ).rows[0], + 'Artifact' + ); + return this.artifact(client, row); + }); + } + + private async projectRow(database: Database, id: string, lock = false): Promise { + return required( + ( + await database.query( + `SELECT * FROM research_projects WHERE id=$1${lock ? ' FOR UPDATE' : ''}`, + [id] + ) + ).rows[0], + 'Project' + ); + } + private async hypothesisRow( + database: Database, + id: string, + lock = false + ): Promise { + return required( + ( + await database.query( + `SELECT * FROM research_hypotheses WHERE id=$1${lock ? ' FOR UPDATE' : ''}`, + [id] + ) + ).rows[0], + 'Hypothesis' + ); + } + private async artifactRow(database: Database, id: string, lock = false): Promise { + return required( + ( + await database.query( + `SELECT * FROM analysis_artifacts WHERE id=$1${lock ? ' FOR UPDATE' : ''}`, + [id] + ) + ).rows[0], + 'Artifact' + ); + } + private async lockHypothesis(client: PoolClient, id: string): Promise { + const row = await this.hypothesisRow(client, id); + active(await this.projectRow(client, row.project_id, true), 'Project'); + return this.hypothesisRow(client, id, true); + } + private async lockArtifact(client: PoolClient, id: string): Promise { + const row = await this.artifactRow(client, id); + active(await this.projectRow(client, row.project_id, true), 'Project'); + return this.artifactRow(client, id, true); + } + private async hypothesis(database: Database, row: QueryResultRow): Promise { + const latest = required( + ( + await database.query( + 'SELECT * FROM research_hypothesis_revisions WHERE hypothesis_id=$1 ORDER BY ordinal DESC LIMIT 1', + [row.id] + ) + ).rows[0], + 'Hypothesis revision' + ); + return { + id: row.id, + projectId: row.project_id, + ownerPrincipal: row.owner_principal, + updatedBy: row.updated_by, + updatedAt: iso(row.updated_at), + archived: row.archived_at !== null, + createdAt: iso(row.created_at), + latestRevision: hypothesisRevision(latest), + }; + } + private async insertHypothesisRevision( + client: PoolClient, + id: string, + ordinal: number, + data: { title: string; proposition: string; validationCriteria: string }, + author: ResearchAuthorship + ): Promise { + await client.query( + `INSERT INTO research_hypothesis_revisions(id,hypothesis_id,ordinal,title,proposition,validation_criteria,submitted_by,content_origin) + VALUES($1,$2,$3,$4,$5,$6,$7,$8)`, + [ + randomUUID(), + id, + ordinal, + data.title, + data.proposition, + data.validationCriteria, + author.submittedBy, + author.contentOrigin, + ] + ); + } + private async artifact(database: Database, row: QueryResultRow): Promise { + const latest = required( + ( + await database.query( + 'SELECT * FROM analysis_artifact_revisions WHERE artifact_id=$1 ORDER BY ordinal DESC LIMIT 1', + [row.id] + ) + ).rows[0], + 'Artifact revision' + ); + return { + id: row.id, + projectId: row.project_id, + hypothesisRevisionId: row.hypothesis_revision_id, + kind: row.kind, + ownerPrincipal: row.owner_principal, + updatedBy: row.updated_by, + updatedAt: iso(row.updated_at), + archived: row.archived_at !== null, + createdAt: iso(row.created_at), + latestRevision: await this.artifactRevision(database, latest), + }; + } + private async artifactRevision( + database: Database, + row: QueryResultRow + ): Promise { + const references = ( + await database.query( + 'SELECT * FROM analysis_evidence WHERE revision_id=$1 ORDER BY ordinal', + [row.id] + ) + ).rows; + const evidence = await Promise.all( + references.map(item => + this.evidence.resolve( + { + runId: item.run_id, + metricsVersion: item.metrics_version, + metricPath: item.metric_path, + strategyVersionId: item.strategy_version_id, + }, + database + ) + ) + ); + return { + id: row.id, + artifactId: row.artifact_id, + ordinal: row.ordinal, + title: row.title, + body: row.body, + submittedBy: row.submitted_by, + contentOrigin: row.content_origin, + validationState: 'unvalidated', + evidenceState: evidence.length ? 'referenced' : 'none', + evidence, + createdAt: iso(row.created_at), + }; + } + private requireFindingEvidence(kind: string, evidence: ResearchEvidenceReference[]): void { + if (kind === 'finding' && evidence.length === 0) { + throw new ResearchError(422, 'A finding requires at least one retained evidence reference'); + } + } + private async insertArtifactRevision( + client: PoolClient, + id: string, + ordinal: number, + data: { title: string; body: string; evidence: ResearchEvidenceReference[] }, + author: ResearchAuthorship + ): Promise { + // Validate using the authoritative reader; only references are persisted. + for (const reference of data.evidence) { + await this.evidence.resolve(reference, client); + } + const revisionId = randomUUID(); + await client.query( + `INSERT INTO analysis_artifact_revisions(id,artifact_id,ordinal,title,body,submitted_by,content_origin) + VALUES($1,$2,$3,$4,$5,$6,$7)`, + [revisionId, id, ordinal, data.title, data.body, author.submittedBy, author.contentOrigin] + ); + for (const [index, reference] of data.evidence.entries()) { + await client.query( + `INSERT INTO analysis_evidence(revision_id,ordinal,run_id,metrics_version,metric_path,strategy_version_id) + VALUES($1,$2,$3,$4,$5,$6)`, + [ + revisionId, + index + 1, + reference.runId, + reference.metricsVersion, + reference.metricPath, + reference.strategyVersionId ?? null, + ] + ); + } + } +} diff --git a/database/postgres/init/20-research-workspace.sql b/database/postgres/init/20-research-workspace.sql new file mode 100644 index 00000000..c59385b2 --- /dev/null +++ b/database/postgres/init/20-research-workspace.sql @@ -0,0 +1,190 @@ +-- Research narratives cite retained measurements; neither table stores financial values. +CREATE TABLE IF NOT EXISTS research_projects ( + id UUID PRIMARY KEY, + title TEXT NOT NULL CHECK (length(btrim(title)) > 0), + description TEXT NOT NULL DEFAULT '', + revision INTEGER NOT NULL DEFAULT 1 CHECK (revision > 0), + owner_principal TEXT NOT NULL CHECK (owner_principal IN ('operator','service')), + updated_by TEXT NOT NULL CHECK (updated_by IN ('operator','service')), + archived_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); +CREATE TABLE IF NOT EXISTS research_hypotheses ( + id UUID PRIMARY KEY, + project_id UUID NOT NULL REFERENCES research_projects(id) ON DELETE RESTRICT, + owner_principal TEXT NOT NULL CHECK (owner_principal IN ('operator','service')), + updated_by TEXT NOT NULL CHECK (updated_by IN ('operator','service')), + archived_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); +CREATE TABLE IF NOT EXISTS research_hypothesis_revisions ( + id UUID PRIMARY KEY, + hypothesis_id UUID NOT NULL REFERENCES research_hypotheses(id) ON DELETE RESTRICT, + ordinal INTEGER NOT NULL CHECK (ordinal > 0), + title TEXT NOT NULL CHECK (length(btrim(title)) > 0), + proposition TEXT NOT NULL CHECK (length(btrim(proposition)) > 0), + validation_criteria TEXT NOT NULL DEFAULT '', + submitted_by TEXT NOT NULL CHECK (submitted_by IN ('operator','service')), + content_origin TEXT NOT NULL CHECK (content_origin IN ('human','ai','unknown')), + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + CHECK (submitted_by <> 'service' OR content_origin <> 'human'), + UNIQUE(hypothesis_id,ordinal) +); +CREATE TABLE IF NOT EXISTS analysis_artifacts ( + id UUID PRIMARY KEY, + project_id UUID NOT NULL REFERENCES research_projects(id) ON DELETE RESTRICT, + hypothesis_revision_id UUID REFERENCES research_hypothesis_revisions(id) ON DELETE RESTRICT, + kind TEXT NOT NULL CHECK (kind IN ('note','finding')), + owner_principal TEXT NOT NULL CHECK (owner_principal IN ('operator','service')), + updated_by TEXT NOT NULL CHECK (updated_by IN ('operator','service')), + archived_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); +CREATE TABLE IF NOT EXISTS analysis_artifact_revisions ( + id UUID PRIMARY KEY, + artifact_id UUID NOT NULL REFERENCES analysis_artifacts(id) ON DELETE RESTRICT, + ordinal INTEGER NOT NULL CHECK (ordinal > 0), + title TEXT NOT NULL CHECK (length(btrim(title)) > 0), + body TEXT NOT NULL, + submitted_by TEXT NOT NULL CHECK (submitted_by IN ('operator','service')), + content_origin TEXT NOT NULL CHECK (content_origin IN ('human','ai','unknown')), + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + -- References can only be inserted in this revision's creation transaction. + created_xid XID8 NOT NULL DEFAULT pg_current_xact_id(), + CHECK (submitted_by <> 'service' OR content_origin <> 'human'), + UNIQUE(artifact_id,ordinal) +); +CREATE TABLE IF NOT EXISTS analysis_evidence ( + revision_id UUID NOT NULL REFERENCES analysis_artifact_revisions(id) ON DELETE RESTRICT, + ordinal INTEGER NOT NULL CHECK (ordinal > 0), + run_id UUID NOT NULL REFERENCES backtest_results(run_id) ON DELETE RESTRICT, + metrics_version TEXT NOT NULL CHECK (metrics_version IN ('canonical-analytics/v1','legacy-display/v1')), + metric_path TEXT NOT NULL, + strategy_version_id UUID REFERENCES strategy_versions(id) ON DELETE RESTRICT, + PRIMARY KEY(revision_id,ordinal), + UNIQUE(revision_id,run_id,metrics_version,metric_path), + CHECK ( + (metrics_version='canonical-analytics/v1' AND metric_path IN ( + 'analytics.metrics.totalReturn','analytics.metrics.cagr','analytics.metrics.maxDrawdown', + 'analytics.metrics.exposureTime','analytics.metrics.volatility','analytics.metrics.downsideDeviation', + 'analytics.metrics.sharpeRatio','analytics.metrics.sortinoRatio','analytics.metrics.var95', + 'analytics.metrics.cvar95','analytics.metrics.var99','analytics.metrics.alpha','analytics.metrics.beta', + 'analytics.metrics.informationRatio','analytics.metrics.roundTripCount','analytics.metrics.winRate', + 'analytics.metrics.profitFactor','analytics.metrics.avgWin','analytics.metrics.avgLoss','analytics.fillCount')) + OR (metrics_version='legacy-display/v1' AND metric_path IN ( + 'metrics.totalReturn','metrics.sharpeRatio','metrics.maxDrawdown','metrics.winRate', + 'metrics.totalTrades','metrics.profitFactor','metrics.avgWin','metrics.avgLoss','analytics.exposureTime')) + ) +); +CREATE TABLE IF NOT EXISTS research_project_strategies ( + project_id UUID NOT NULL REFERENCES research_projects(id) ON DELETE RESTRICT, + strategy_id UUID NOT NULL REFERENCES strategies(id) ON DELETE RESTRICT, + added_by TEXT NOT NULL CHECK (added_by IN ('operator','service')), + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + PRIMARY KEY(project_id,strategy_id) +); +CREATE INDEX IF NOT EXISTS research_hypotheses_project ON research_hypotheses(project_id,created_at,id); +CREATE INDEX IF NOT EXISTS analysis_artifacts_project ON analysis_artifacts(project_id,created_at,id); + +CREATE OR REPLACE FUNCTION reject_workspace_history_mutation() RETURNS trigger +LANGUAGE plpgsql AS $$ BEGIN + RAISE EXCEPTION 'Research history is immutable; append a revision or archive metadata' USING ERRCODE='23514'; +END $$; +DO $$ DECLARE relation TEXT; BEGIN + FOREACH relation IN ARRAY ARRAY['research_hypothesis_revisions','analysis_artifact_revisions','analysis_evidence'] LOOP + EXECUTE format('DROP TRIGGER IF EXISTS workspace_history_immutable ON %I',relation); + EXECUTE format('CREATE TRIGGER workspace_history_immutable BEFORE UPDATE OR DELETE ON %I FOR EACH ROW EXECUTE FUNCTION reject_workspace_history_mutation()',relation); + END LOOP; + FOREACH relation IN ARRAY ARRAY['research_projects','research_hypotheses','analysis_artifacts'] LOOP + EXECUTE format('DROP TRIGGER IF EXISTS workspace_archive_only ON %I',relation); + EXECUTE format('CREATE TRIGGER workspace_archive_only BEFORE DELETE ON %I FOR EACH ROW EXECUTE FUNCTION reject_workspace_history_mutation()',relation); + END LOOP; + FOREACH relation IN ARRAY ARRAY['research_projects','research_hypotheses','research_hypothesis_revisions','analysis_artifacts','analysis_artifact_revisions','analysis_evidence'] LOOP + EXECUTE format('DROP TRIGGER IF EXISTS workspace_no_truncate ON %I',relation); + EXECUTE format('CREATE TRIGGER workspace_no_truncate BEFORE TRUNCATE ON %I FOR EACH STATEMENT EXECUTE FUNCTION reject_workspace_history_mutation()',relation); + END LOOP; +END $$; + +CREATE OR REPLACE FUNCTION protect_workspace_identity() RETURNS trigger +LANGUAGE plpgsql AS $$ BEGIN + IF TG_TABLE_NAME='research_projects' THEN + IF NEW.id IS DISTINCT FROM OLD.id OR NEW.owner_principal IS DISTINCT FROM OLD.owner_principal + OR NEW.created_at IS DISTINCT FROM OLD.created_at THEN + RAISE EXCEPTION 'Research project identity is immutable' USING ERRCODE='23514'; + END IF; + ELSIF (to_jsonb(NEW)-ARRAY['archived_at','updated_by','updated_at']) IS DISTINCT FROM + (to_jsonb(OLD)-ARRAY['archived_at','updated_by','updated_at']) THEN + RAISE EXCEPTION 'Research narrative identity is immutable' USING ERRCODE='23514'; + END IF; + RETURN NEW; +END $$; +DO $$ DECLARE relation TEXT; BEGIN + FOREACH relation IN ARRAY ARRAY['research_projects','research_hypotheses','analysis_artifacts'] LOOP + EXECUTE format('DROP TRIGGER IF EXISTS workspace_identity ON %I',relation); + EXECUTE format('CREATE TRIGGER workspace_identity BEFORE UPDATE ON %I FOR EACH ROW EXECUTE FUNCTION protect_workspace_identity()',relation); + END LOOP; +END $$; + +CREATE OR REPLACE FUNCTION require_workspace_hypothesis_project() RETURNS trigger +LANGUAGE plpgsql AS $$ DECLARE linked_project UUID; BEGIN + IF NEW.hypothesis_revision_id IS NOT NULL THEN + SELECT h.project_id INTO linked_project FROM research_hypothesis_revisions r + JOIN research_hypotheses h ON h.id=r.hypothesis_id WHERE r.id=NEW.hypothesis_revision_id; + IF linked_project IS DISTINCT FROM NEW.project_id THEN + RAISE EXCEPTION 'Hypothesis revision belongs to a different project or is missing' USING ERRCODE='23514'; + END IF; + END IF; + RETURN NEW; +END $$; +DROP TRIGGER IF EXISTS workspace_hypothesis_project ON analysis_artifacts; +CREATE TRIGGER workspace_hypothesis_project BEFORE INSERT ON analysis_artifacts + FOR EACH ROW EXECUTE FUNCTION require_workspace_hypothesis_project(); + +CREATE OR REPLACE FUNCTION require_new_workspace_evidence() RETURNS trigger +LANGUAGE plpgsql AS $$ DECLARE revision_xid XID8; run_status TEXT; result JSONB; BEGIN + SELECT created_xid INTO revision_xid FROM analysis_artifact_revisions WHERE id=NEW.revision_id; + IF revision_xid IS DISTINCT FROM pg_current_xact_id() THEN + RAISE EXCEPTION 'Evidence must be inserted atomically with its new narrative revision' USING ERRCODE='23514'; + END IF; + SELECT r.status,br.canonical_result INTO run_status,result FROM runs r + JOIN backtest_results br ON br.run_id=r.id WHERE r.id=NEW.run_id; + IF run_status IS DISTINCT FROM 'completed' THEN + RAISE EXCEPTION 'Evidence requires a completed retained result' USING ERRCODE='23514'; + END IF; + IF (NEW.metrics_version='canonical-analytics/v1' AND result->>'kind'='canonical-result/v1') IS NOT TRUE + AND NOT (NEW.metrics_version='legacy-display/v1' AND result IS NULL) THEN + RAISE EXCEPTION 'Evidence reporting version does not match its result' USING ERRCODE='23514'; + END IF; + IF NEW.strategy_version_id IS NOT NULL AND + (result#>>'{request,strategy,versionId}'=NEW.strategy_version_id::text) IS NOT TRUE THEN + RAISE EXCEPTION 'Evidence strategy version is not bound by the retained result' USING ERRCODE='23514'; + END IF; + RETURN NEW; +END $$; +DROP TRIGGER IF EXISTS workspace_new_evidence ON analysis_evidence; +CREATE TRIGGER workspace_new_evidence BEFORE INSERT ON analysis_evidence + FOR EACH ROW EXECUTE FUNCTION require_new_workspace_evidence(); + +CREATE OR REPLACE FUNCTION stamp_workspace_revision_transaction() RETURNS trigger +LANGUAGE plpgsql AS $$ BEGIN + NEW.created_xid := pg_current_xact_id(); + RETURN NEW; +END $$; +DROP TRIGGER IF EXISTS workspace_revision_transaction ON analysis_artifact_revisions; +CREATE TRIGGER workspace_revision_transaction BEFORE INSERT ON analysis_artifact_revisions + FOR EACH ROW EXECUTE FUNCTION stamp_workspace_revision_transaction(); + +CREATE OR REPLACE FUNCTION require_workspace_finding_evidence() RETURNS trigger +LANGUAGE plpgsql AS $$ BEGIN + IF EXISTS (SELECT 1 FROM analysis_artifacts WHERE id=NEW.artifact_id AND kind='finding') + AND NOT EXISTS (SELECT 1 FROM analysis_evidence WHERE revision_id=NEW.id) THEN + RAISE EXCEPTION 'A finding revision requires retained evidence' USING ERRCODE='23514'; + END IF; + RETURN NULL; +END $$; +DROP TRIGGER IF EXISTS workspace_finding_evidence ON analysis_artifact_revisions; +CREATE CONSTRAINT TRIGGER workspace_finding_evidence AFTER INSERT ON analysis_artifact_revisions + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION require_workspace_finding_evidence(); diff --git a/docs/development/ROADMAP.md b/docs/development/ROADMAP.md index aa59714f..1883350e 100644 --- a/docs/development/ROADMAP.md +++ b/docs/development/ROADMAP.md @@ -537,3 +537,19 @@ The initial aggregate check exposed stale pure-contract allowlists and lint issu Deployment requires the existing native research runner (`useRustEngine: true`) and matching immutable build files. Capability is input/artifact validation, not worker health. An incompatible deployment fails an accepted run; historical build restoration belongs to R12. [R05](backlog/tasks/R05.md#first-vertical-slice--2026-10-23) documents the explicit offline v2 import and remaining source-preparation contract. No candidate/multi-asset/default activation, benchmark or performance work, new-wave commit, push or PR. **Next after acceptance/commit: R03 research projects, hypotheses and evidence-linked findings APIs.** It is independently ready and adds useful research workflow without pretending full R05 is finished. R05's source-to-v2 preparation and broader cutover remain tracked; R06/S06 dependencies are not released by this partial milestone. + +## Twenty-fourth-wave handoff — 2026-10-23 + +The initial R05 slice is accepted and committed as `618fb9e`; full R05 remains **in_progress**. R03 is independently reviewed and `validated_uncommitted`. Eighteen implementation/shared-contract/migration/test files add the research metadata APIs. Persistence and HTTP agents worked in isolated worktrees under `/tmp/stock-bot-wave24.3Qsd1y/`; root owned contracts, evidence resolution, composition and integration. + +- **Research organization:** Projects can organize existing strategies, hypotheses and notes/findings. Project edits and real membership changes advance revision identity. Hypothesis/artifact edits append immutable narratives with explicit authorship; stale edits return 409. Archive/restore preserves prior narratives and cited results, with actor/time recorded. +- **Evidence:** Findings cite known scalar paths on exact completed retained runs, optionally binding the retained strategy version. The existing result reader supplies canonical or qualified legacy values; no copied metric truth or simulator was introduced. Null reasons, genuine zeros, units and result limitations are preserved. SQL references protect retained results and prevent later additions to an old revision's evidence set. +- **Authorship:** Verified operator/service submitter is separate from declared human/AI/unknown content origin. A service cannot claim human authorship. All prose remains unvalidated; a citation does not certify a conclusion. No AI credential, code execution or review framework was added. +- **Correctness fixes during review:** Evidence resolution now uses the active transaction connection, avoiding deadlock when the pool has one connection. Corrupt retained storage produces a sanitized server error with its diagnostic cause, rather than blaming a valid client request. Project membership changes also preserve actor attribution and optimistic revision identity. +- **Validation:** `bun run check` passed all gates, including **590 integration** and **150 Rust** tests (4 manual ignored), plus build/source/contracts/secrets/lint, 93 tooling, 43 utility and 44 calculation tests. Full disposable PostgreSQL/Redis: **159 tests / 1279 assertions**. Existing Chromium workflows: **9 / 164 assertions**, including actual retained canonical execution/reopen. Strict changed-test types, scoped formatting/test lint and diff checks passed. No research UI is claimed by these browser regressions; that is R04. + +Exact source hashes, commands and review dispositions are recorded in `manifest.json` → `twenty_fourth_wave_validation`. The release addon matches the previous wave and checkout release library; Rust financial source is unchanged. After the interruption, all 18 implementation hashes were reverified and both disposable containers were confirmed removed. Development/production services and data were untouched; worktrees and logs remain for review. + +R03's [implemented API contract](backlog/tasks/R03.md#implemented-contract--2026-10-23) documents revision inputs, archive/error behavior and evidence limitations. Initial metadata POSTs use ordinary creation semantics, so clients must handle ambiguous responses without blind retries. No R03 commit, push, PR, new simulator, performance work or trading/default activation. + +**Next after acceptance/commit: R04 — research workspace and save-findings UI**, consuming these same APIs. R05's remaining source preparation and wider cutover are still tracked; R06/S06 gates remain intact. diff --git a/docs/development/backlog/README.md b/docs/development/backlog/README.md index 845f7ff9..a05976aa 100644 --- a/docs/development/backlog/README.md +++ b/docs/development/backlog/README.md @@ -1,6 +1,6 @@ # Canonical development backlog -**First twenty-two waves committed; the initial R05 vertical slice is validated and uncommitted.** R02 is accepted as `d929db7`. Reviewed built-ins can now run against one eligible retained v2 dataset through the durable Rust engine and reopen canonical results in the web workbench. Full R05 remains in progress. Performance work remains paused. See [current handoff](../ROADMAP.md#twenty-third-wave-handoff--2026-10-23) and manifest execution scope. +**First twenty-three waves committed; R03 is validated and uncommitted.** The initial R05 slice is accepted as `618fb9e`; broader R05 remains in progress. R03 adds research projects, revisioned hypotheses/notes/findings and exact retained metric citations through the shared API. R04 supplies the workspace UI next. Performance work remains paused. See [current handoff](../ROADMAP.md#twenty-fourth-wave-handoff--2026-10-23) and manifest execution scope. ## One source of truth @@ -74,7 +74,7 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr | --- | --- | --- | --- | --- | | [R01 Persist immutable strategy versions and parameter schemas](tasks/R01.md) | P1 / done | O01, ADR-006 | — | Full-stack research product / M | | [R02 Deliver strategy catalog and version-aware backtest setup](tasks/R02.md) | P1 / done | R01, W03, ADR-006 | W04 | Full-stack research product / M | -| [R03 Add projects, hypotheses and evidence-linked findings APIs](tasks/R03.md) | P1 / ready | R01, R10, ADR-006 | — | Full-stack research product / M | +| [R03 Add projects, hypotheses and evidence-linked findings APIs](tasks/R03.md) | P1 / review | R01, R10, ADR-006 | — | Full-stack research product / M | | [R04 Deliver research workspace and save-findings flow](tasks/R04.md) | P1 / blocked | R03, W02, ADR-006 | W04 | Full-stack research product / M | | [R05 Freeze complete provenance and cut over durable canonical runs](tasks/R05.md) | P0 / in_progress | F08, S02, R01, R10, D01, W03, C06, ADR-006 | Multi-asset default mark-policy disposition | Full-stack research product / M | | [R06 Create immutable experiments and bounded sweep expansion](tasks/R06.md) | P1 / blocked | R05, ADR-006 | — | Full-stack research product / M | diff --git a/docs/development/backlog/manifest.json b/docs/development/backlog/manifest.json index 32ca5b75..7ee7d5e8 100644 --- a/docs/development/backlog/manifest.json +++ b/docs/development/backlog/manifest.json @@ -1,16 +1,16 @@ { "schema_version": 1, - "plan_revision": "2026-10-23.50", + "plan_revision": "2026-10-23.52", "repository_base": "b7aeca4", - "plan_status": "twenty_third_wave_partial_validated", + "plan_status": "twenty_fourth_wave_validated", "execution_authorized": true, "execution_scope": { - "authorized_by": "User: commit and continue after validated R02 handoff; R02 committed d929db707a4894096b8b31ebd25c5e39d15289c1.", + "authorized_by": "User: commit and continue after R05 partial handoff naming R03; R05 slice committed 618fb9e33cebc1fde4869eb1f975a12c55bd9b94.", "tasks": [ - "R05" + "R03" ], "permissions": [ - "R05 trusted-built-in single-asset retained-v2 vertical slice, isolated implementation, correctness tests, cross-agent review and planning updates" + "R03 research metadata/evidence APIs, isolated implementation, correctness tests, independent review and planning updates" ], "excluded": [ "performance_profiling_or_optimization", @@ -23,7 +23,9 @@ "candidate_execution", "provider_to_v2_inference", "multi_asset_activation", - "other_backlog_tasks" + "other_backlog_tasks", + "R04_workspace_UI", + "AI_execution_or_credentials" ], "pending_policy_decisions": [ "ADR-007", @@ -1500,7 +1502,7 @@ "epic": "E6", "priority": "P1", "severity": "High", - "status": "ready", + "status": "review", "dependencies": [ "R01", "R10" @@ -1521,12 +1523,34 @@ "research-api" ], "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", - "assignment": null, + "assignment": "/root", "branch": null, "pull_request": null, "completed_commit": null, "blocker": null, - "release_gates": [] + "release_gates": [], + "integration_base": "618fb9e33cebc1fde4869eb1f975a12c55bd9b94", + "integration_state": "validated_uncommitted", + "worktree": "/home/boki/repos/stock-bot", + "implementation_slices": [ + { + "owner": "/root", + "scope": "Shared pure research DTOs, evidence projection, fixture/composition integration and planning" + }, + { + "owner": "/root/r03_persistence", + "worktree": "/tmp/stock-bot-wave24.3Qsd1y/persistence", + "scope": "Migration20, research metadata service and PostgreSQL tests" + }, + { + "owner": "/root/r03_http", + "worktree": "/tmp/stock-bot-wave24.3Qsd1y/http", + "scope": "Research route adapter and HTTP boundary tests" + } + ], + "reviewed_by": "/root/r03_contract_review", + "review_notes": "Independent review accepted metadata/revision/evidence contracts, persistence and HTTP boundaries after transaction-client forwarding and retained-corruption error fixes. Full repository, SQL and existing browser gates pass.", + "verification_reference": "ROADMAP.md#twenty-fourth-wave-handoff--2026-10-23" }, { "id": "R04", @@ -1604,7 +1628,7 @@ "release_gates": [ "Explicit owner disposition of the simultaneous multi-asset mark/risk policy before canonical default activation" ], - "integration_state": "partial_validated_uncommitted", + "integration_state": "partial_validated_committed", "integration_base": "d929db707a4894096b8b31ebd25c5e39d15289c1", "worktree": "/home/boki/repos/stock-bot", "implementation_slices": [ @@ -1634,7 +1658,8 @@ "/root/s04_feed_audit" ], "verification_reference": "ROADMAP.md#twenty-third-wave-handoff--2026-10-23", - "review_notes": "Reviewed retained-builtin/single-asset vertical slice only. Full R05 remains in progress; provider-to-v2 preparation and broader cutover are not claimed. Corrected warmup clock, series/rate/decimal admission mismatches, concurrent approval proof, UI parent identity and drawdown severity." + "review_notes": "Reviewed retained-builtin/single-asset vertical slice only. Full R05 remains in progress; provider-to-v2 preparation and broader cutover are not claimed. Corrected warmup clock, series/rate/decimal admission mismatches, concurrent approval proof, UI parent identity and drawdown severity.", + "partial_commit": "618fb9e33cebc1fde4869eb1f975a12c55bd9b94" }, { "id": "R06", @@ -7210,5 +7235,100 @@ ], "cleanup": "Both exact --rm disposable PostgreSQL/Redis containers stopped; development services untouched. Worktrees and evidence logs retained.", "next": "After acceptance/commit, R03 research projects, hypotheses and evidence-linked findings APIs is independently ready. Keep R05 in progress until explicit source-v2 preparation and broader cutover scope are completed; R06/S06 remain blocked." + }, + "twenty_fourth_wave": [ + "R03" + ], + "twenty_fourth_wave_base": "618fb9e33cebc1fde4869eb1f975a12c55bd9b94", + "twenty_fourth_wave_notes": [ + "Metadata and retained-evidence APIs only; no R04 UI or AI execution/credentials. Narratives remain unvalidated; citations resolve existing retained results, not copied metrics.", + "R05 stays in progress after accepted single-asset slice. Performance work remains paused." + ], + "twenty_fourth_wave_validation": { + "state": "validated_uncommitted", + "log_directory": "/tmp/stock-bot-wave24.3Qsd1y", + "integration_base": "618fb9e33cebc1fde4869eb1f975a12c55bd9b94", + "source_archive": "/tmp/stock-bot-wave24.3Qsd1y/r03-integrated-source.tar", + "source_archive_sha256": "645d9d80a574b1e590023c601aca563f18101ef19b0aafbd03181159665e8d32", + "source_file_count": 18, + "source_sha256": { + "apps/stock/config/package.json": "d2f8581c02e16c90fa5154ed9a1223bc26256ec4c6e29146d5d454cba5fe435e", + "apps/stock/config/src/contracts/research.ts": "60b41535e9ce81a538013e6299dc363a68826eab0d969dfd492de1c1376cfb6e", + "apps/stock/web-api/src/migrations/migration-runner.ts": "a3a8d885af0a5b6c3e1d1193101a3370fcd10c867443e13012ecb384f3b629cf", + "apps/stock/web-api/src/routes/create-routes.ts": "5c2faa9e0f5825d0615ded19af9952281349c43651fd3c47b6e10e6b7e4526c5", + "apps/stock/web-api/src/routes/research.routes.ts": "2a3805186faa5fb3f339c8183834e30038c98f7ca01f6ede8b9a247c559f1990", + "apps/stock/web-api/src/services/backtest-v2.service.ts": "7f64f0244fd18e33bf50f99b960aab2c6e985615513e1d85367e8a1ce5a45e68", + "apps/stock/web-api/src/services/research-errors.ts": "db90da45c8f4a091e3f113d50c6435d4283161995e7570f3cae05a626e745995", + "apps/stock/web-api/src/services/research-evidence.ts": "7174448d404ec90249bcc83b8b1c178e393ede1aaf74f95c6cc8914031a34179", + "apps/stock/web-api/src/services/research.service.ts": "f8436942a22bcbec0e40a7109e28d84459e4994568b54c564f1393146bc8a589", + "database/postgres/init/20-research-workspace.sql": "c9202c23f218c6aa55ee44e6c25ae966cf90cb7e00b21352bac256b393048ec5", + "libs/core/types/src/index.ts": "631c900226aef3bf3cc79e605d1f2cc28df5bbab6b3823595da090faad1303f2", + "libs/core/types/src/research.ts": "5fd981488ac18edacbd92e1fe9e254afe27ef1388f5ef391f9fbda07a3bbe9c7", + "scripts/test/architecture.test.ts": "0f30d5c99544e8420f75711f1a3c47d194c6d74b7bc0592a14b89c8d50a1ee58", + "test/e2e/fixture.ts": "8c2c7c12d1b84adcded82e384065b12c1857e567fd302e2c9b46e71644e52ca1", + "test/integration/research-api.test.ts": "c628c25d070bd613a34fe7edb593fee996cde74e8bec2f460620be91937220c4", + "test/integration/research-evidence.test.ts": "f3cf3a2aa73b6dfc4e2944cbecd3a6db574ac3be9220b9bfccddb4bdb23f20cb", + "test/postgres/migration-runner.test.ts": "b71a74cd4acf4c55dcbcad11a03ebaeefcaa7fcb70a01a0c8291ff1a91c47d27", + "test/postgres/research-workspace.test.ts": "680a650516ccc9c91179119f5d357618a23b9b909b1310e6ee86ce8cdbd77452" + }, + "checks": [ + { + "command": "CARGO_BUILD_JOBS=2 bun run check", + "log": "/tmp/stock-bot-wave24.3Qsd1y/check.log", + "outcome": "All repository checks passed: build/source/contracts/secrets/lint; 93 tooling, 43 utility, 44 calculation, 590 integration and 150 Rust tests. Four manual Rust tests remain ignored." + }, + { + "command": "PIPELINE_TEST_DATABASE_URL= BACKTEST_TEST_REDIS_URL= bun run test:postgres", + "log": "/tmp/stock-bot-wave24.3Qsd1y/postgres.log", + "outcome": "159 tests / 1279 assertions passed across 18 files. Includes new research citations/revisions, one-connection pool, actual canonical execution, legacy conversion, SQL integrity, concurrent revisions/archive and upgrade/reapply preservation." + }, + { + "command": "CARGO_BUILD_JOBS=2 bun run --cwd apps/stock/engine build:release", + "log": "/tmp/stock-bot-wave24.3Qsd1y/native-release.log", + "outcome": "Release addon restored; SHA256 ef00eed556f5c32332d36a9a00ef710682e90deb00b54552e4b5c8bfdfbe8103 matches checkout release library and previous wave. No Rust financial source changes." + }, + { + "command": "PIPELINE_TEST_DATABASE_URL= BACKTEST_TEST_REDIS_URL= bun run test:e2e", + "log": "/tmp/stock-bot-wave24.3Qsd1y/e2e.log", + "outcome": "All 9 existing workflows / 164 assertions passed with migration20 and research routes installed, including retained canonical execution/reopen, legacy results, archive and cancellation. Research workspace UI itself remains R04." + }, + { + "command": "node_modules/.bin/tsc --project /tmp/stock-bot-wave24.3Qsd1y/tests-tsconfig.json --noEmit", + "log": "/tmp/stock-bot-wave24.3Qsd1y/strict-tests.log", + "outcome": "Strict new/changed test and dependent source types passed." + }, + { + "command": "node_modules/.bin/prettier --check ; node_modules/.bin/eslint --max-warnings 0; git diff --check", + "log": "/tmp/stock-bot-wave24.3Qsd1y/scoped-format.log", + "outcome": "Passed scoped formatting, test lint and diff checks; test lint log is scoped-test-lint.log." + }, + { + "command": "bun test test/integration/research-api.test.ts (isolated HTTP worktree)", + "log": "/tmp/stock-bot-wave24.3Qsd1y/http-tests-final.log", + "outcome": "10 tests / 197 assertions passed, including sanitized500 for valid citation of corrupt retained storage. Also covered by full root integration gate." + }, + { + "command": "PIPELINE_TEST_DATABASE_URL= bun test test/postgres/research-workspace.test.ts (isolated persistence worktree)", + "log": "/tmp/stock-bot-wave24.3Qsd1y/persistence-postgres-final.log", + "outcome": "9 tests / 121 assertions passed; also covered by full root SQL gate." + } + ], + "reviews": [ + { + "reviewer": "/root/r03_contract_review", + "scope": "Pinned shared contracts, root resolver/result query seam, persistence/SQL and HTTP adapter", + "outcome": "Accepted. Corrected nested pool deadlock by forwarding active client, preserved actor metadata, and classified corrupt retained-result validation as sanitized500 rather than client400. Reviewed final source and observed scoped passing logs; root ran combined gates." + } + ], + "limitations": [ + "R03 is API/data scope only. R04 owns project/hypothesis/finding screens and the browser save-finding workflow.", + "Narratives always remain unvalidated. EvidenceState referenced is not narrative validation; submittedBy is verified operator/service while contentOrigin is declared human/ai/unknown. No authenticated model identity or AI execution credentials added.", + "Only known scalar metric paths on completed retained results are citeable. Canonical/legacy reporting adapters remain distinct; legacy economics retain existing limitations and null metrics remain unavailable.", + "Revision edits use expectedRevision; archive/history are retained. Ordinary metadata create POSTs have no submission receipt and must not be blindly retried after an ambiguous response.", + "No source-v2 preparation, candidate execution, multi-asset/default activation, paper/live operations or new financial simulator. Partial R05 remains in progress.", + "No profiling/optimization/benchmarks, new-wave commit, push or PR. No production/development schema or data mutation." + ], + "cleanup": "Both exact --rm PostgreSQL/Redis fixtures stopped. After interruption, docker ps -a --filter name=stock-bot-research-workspace returned no containers. All 18 source hashes reverified unchanged. Worktrees and logs retained; development services untouched.", + "next": "After acceptance/commit, R04 research workspace and evidence-linked save-finding UI. Keep R05 partial and R06/S06 gated. Performance remains paused." } } diff --git a/docs/development/backlog/tasks/R03.md b/docs/development/backlog/tasks/R03.md index fc385563..6d511d9d 100644 --- a/docs/development/backlog/tasks/R03.md +++ b/docs/development/backlog/tasks/R03.md @@ -63,3 +63,35 @@ Keep migrations additive and previous results readable. Do not add a switch that ## Handoff Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done. + +## Implemented contract — 2026-10-23 + +R03 adds metadata APIs only; R04 owns the research workspace screens. Migration 20 introduces projects, hypotheses and their revisions, note/finding artifacts and their revisions, evidence references, and project/strategy membership. Existing runs, results, strategy versions, queues and financial engines are reused unchanged. The implementation is in `services/research.service.ts`, `services/research-evidence.ts`, `routes/research.routes.ts` and pure DTOs/schemas at `libs/core/types/src/research.ts` and `@stock-bot/stock-config/research`. + +Every narrative revision remains `validationState: 'unvalidated'`. `evidenceState: 'referenced'` means citations exist, not that the conclusion is true. `submittedBy` comes from verified operator/service credentials; `contentOrigin: human | ai | unknown` is explicitly declared provenance. Operator submissions default to human, service submissions to unknown; a service cannot claim human authorship. Operator imports may be labelled AI. No model identity, AI credential system, approval workflow or trading authority is inferred. + +Project edits require `expectedRevision`; actual strategy-link changes also advance it and record the actor. Hypothesis/artifact content changes append a complete immutable revision under the project/entity lock and require the current ordinal. A stale editor receives 409. Archive/restore preserves history and records the latest metadata actor/time. Archived projects reject child writes; archived records remain readable. A finding can link an exact hypothesis revision from the same project; later hypothesis edits/archive never rewrite that link or prevent independent revisions of an existing finding. + +Findings require at least one reference; notes may have none. References contain `runId`, `metricsVersion`, `metricPath` and optionally a matching retained `strategyVersionId`. They have foreign keys to retained result/version rows and never store copied metric values. Only the known scalar paths in the shared schema are accepted. `canonical-analytics/v1` reads accepted F08 analytics; `legacy-display/v1` versions the existing compatibility reader, **not** a recorded legacy engine or financial policy. Completed runs/results are required. Null stays unavailable with its reason, zero stays zero, fractions are not rescaled, fills do not become round trips, and legacy/model limitations accompany measurements. + +Reads use `BacktestServiceV2.getRunResults`; an optional query client lets evidence resolution share the active metadata transaction. This prevents a nested-pool deadlock with one connection. SQL rejects revision/reference update/delete/truncate, dangling references and later insertion into an old revision's evidence set. Reference creation is limited to its narrative revision's creation transaction, with a deferred nonempty-finding check. There is no second metric store or simulator. + +### API for R04 and other authorized clients + +All routes use `/api/v2`; list payloads may be empty and mutations require real credentials even when development authentication bypass is enabled. Each route sets `Cache-Control: no-store` without changing unrelated APIs. + +| Resource | Operations | +| --- | --- | +| `/research-projects` | GET `{projects}`; POST `{title, description?}` → 201 `{project}` | +| `/research-projects/:id` | GET `{project}`; PATCH `{expectedRevision, title?, description?, archived?}` | +| `/research-projects/:id/strategies` | GET `{strategies}`; PUT/DELETE `/:strategyId` → 204, no body or `{}` | +| `/research-projects/:id/hypotheses` | GET `{hypotheses}`; POST `{title, proposition, validationCriteria?, contentOrigin?}` → 201 `{hypothesis}` | +| `/hypotheses/:id` | GET `{hypothesis}`; PATCH `{archived}` | +| `/hypotheses/:id/revisions` | GET ascending `{revisions}`; POST full new content + `expectedRevision` → 201 `{hypothesis}` | +| `/research-projects/:id/analysis-artifacts` | GET `{artifacts}`; POST `{kind, title, body, hypothesisRevisionId?, contentOrigin?, evidence?}` → 201 `{artifact}` | +| `/analysis-artifacts/:id` | GET `{artifact}`; PATCH `{archived}` | +| `/analysis-artifacts/:id/revisions` | GET ascending `{revisions}`; POST full narrative/evidence + `expectedRevision` → 201 `{artifact}` | + +Project/hypothesis/artifact lists accept `includeArchived=true|false`. Missing resources return 404; stale revisions and archived writes 409; malformed bodies/unknown metric selectors 400; a valid reference incompatible with its retained result 422. Corrupt retained results return a sanitized 500 with internal diagnostics, not a false client-input error. No hard-delete, execution or validation-promotion endpoint exists. Initial metadata creation uses ordinary POST semantics; clients should not automatically retry an ambiguous creation response as though it had an idempotency receipt. + +Mandatory cases are covered by `test/postgres/research-workspace.test.ts`, `test/integration/research-api.test.ts` and `test/integration/research-evidence.test.ts`. The PostgreSQL fixture includes a real retained native run, legacy conversion, exact revisions, direct-SQL guards, concurrent edits/archive, a one-connection pool and migration upgrade/reapply preservation. Combined validation and reviewed source hashes are recorded in the manifest's twenty-fourth-wave handoff. No production/development schema or catalog was changed during implementation. diff --git a/libs/core/types/src/index.ts b/libs/core/types/src/index.ts index 760381ce..defef360 100644 --- a/libs/core/types/src/index.ts +++ b/libs/core/types/src/index.ts @@ -158,3 +158,5 @@ export type { HistoricalDatasetV2, HistoricalDatasetInputV2, } from './historical-data'; + +export type * from './research'; diff --git a/libs/core/types/src/research.ts b/libs/core/types/src/research.ts new file mode 100644 index 00000000..19835d07 --- /dev/null +++ b/libs/core/types/src/research.ts @@ -0,0 +1,83 @@ +/** Research narrative and citations. Referencing a measurement never validates prose. */ +export type ResearchActor = 'operator' | 'service'; +export type ResearchContentOrigin = 'human' | 'ai' | 'unknown'; +export type ResearchMetricsVersion = 'canonical-analytics/v1' | 'legacy-display/v1'; + +export interface ResearchAuthorship { + submittedBy: ResearchActor; + /** Declared content origin, not authenticated model/agent identity. */ + contentOrigin: ResearchContentOrigin; +} +export interface ResearchProject { + id: string; + title: string; + description: string; + revision: number; + ownerPrincipal: ResearchActor; + updatedBy: ResearchActor; + archived: boolean; + createdAt: string; + updatedAt: string; +} +export interface ResearchHypothesisRevision extends ResearchAuthorship { + id: string; + hypothesisId: string; + ordinal: number; + title: string; + proposition: string; + validationCriteria: string; + validationState: 'unvalidated'; + createdAt: string; +} +export interface ResearchHypothesis { + id: string; + projectId: string; + ownerPrincipal: ResearchActor; + updatedBy: ResearchActor; + updatedAt: string; + archived: boolean; + createdAt: string; + latestRevision: ResearchHypothesisRevision; +} +export interface ResearchEvidenceReference { + runId: string; + metricsVersion: ResearchMetricsVersion; + metricPath: string; + /** Optional exact executable version; accepted only when bound by the run. */ + strategyVersionId?: string | null; +} +export interface ResearchEvidence extends ResearchEvidenceReference { + backtestId: string; + value: number | null; + unit: 'fraction' | 'ratio' | 'count' | 'currency'; + availability: 'available' | 'unavailable'; + unavailableReason: string | null; + resultKind: 'canonical' | 'legacy'; + financialEngine: 'rust' | 'native' | 'typescript' | 'legacy'; + datasetHash: string | null; + limitations: { code: string; message: string }[]; +} +export interface ResearchArtifactRevision extends ResearchAuthorship { + id: string; + artifactId: string; + ordinal: number; + title: string; + body: string; + validationState: 'unvalidated'; + evidenceState: 'none' | 'referenced'; + evidence: ResearchEvidence[]; + createdAt: string; +} +export interface ResearchArtifact { + id: string; + projectId: string; + /** Links a particular narrative, not a hypothesis's mutable latest revision. */ + hypothesisRevisionId: string | null; + kind: 'note' | 'finding'; + ownerPrincipal: ResearchActor; + updatedBy: ResearchActor; + updatedAt: string; + archived: boolean; + createdAt: string; + latestRevision: ResearchArtifactRevision; +} diff --git a/scripts/test/architecture.test.ts b/scripts/test/architecture.test.ts index 343282e3..88bbd9cf 100644 --- a/scripts/test/architecture.test.ts +++ b/scripts/test/architecture.test.ts @@ -88,7 +88,7 @@ describe('orchestrator architecture boundaries', () => { it('shared strategy catalog contracts cannot import strategy execution or application services', async () => { const directory = resolve(root, '../../config/src/contracts'); - for (const name of ['strategy.ts', 'builtin-strategy.ts', 'strategy-names.ts', 'canonical-research.ts', 'canonical-replay.ts']) { + for (const name of ['strategy.ts', 'builtin-strategy.ts', 'strategy-names.ts', 'canonical-research.ts', 'canonical-replay.ts', 'research.ts']) { for (const specifier of runtimeImports(join(directory, name))) { expect(['zod', '@stock-bot/types', './builtin-strategy', './strategy-names', './strategy', './canonical-replay'].includes(specifier)).toBe(true); } diff --git a/test/e2e/fixture.ts b/test/e2e/fixture.ts index 5f2789e7..b16559e0 100644 --- a/test/e2e/fixture.ts +++ b/test/e2e/fixture.ts @@ -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') diff --git a/test/integration/research-api.test.ts b/test/integration/research-api.test.ts new file mode 100644 index 00000000..884fcc03 --- /dev/null +++ b/test/integration/research-api.test.ts @@ -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[] }>; +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 = {} + ) { + 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) { + 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); + }); +}); diff --git a/test/integration/research-evidence.test.ts b/test/integration/research-evidence.test.ts new file mode 100644 index 00000000..3d99b9a9 --- /dev/null +++ b/test/integration/research-evidence.test.ts @@ -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(); + } + }); +}); diff --git a/test/postgres/migration-runner.test.ts b/test/postgres/migration-runner.test.ts index 0dae5d38..687f395a 100644 --- a/test/postgres/migration-runner.test.ts +++ b/test/postgres/migration-runner.test.ts @@ -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)[] = []; afterEach(async () => { diff --git a/test/postgres/research-workspace.test.ts b/test/postgres/research-workspace.test.ts new file mode 100644 index 00000000..ed9f0ff2 --- /dev/null +++ b/test/postgres/research-workspace.test.ts @@ -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)[] = []; +let packages: ReturnType | 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']); + }); +});