From 06039d17bac7220d8504e68d1d4f66896eb13b91 Mon Sep 17 00:00:00 2001 From: Boki Date: Sat, 24 Oct 2026 14:42:14 -0400 Subject: [PATCH] feat(research): retain exact experiment and report citations in findings --- .../stock/config/src/contracts/experiments.ts | 2 + apps/stock/config/src/contracts/research.ts | 36 + .../src/migrations/migration-runner.ts | 3 +- .../src/services/experiments.service.ts | 10 +- .../web-api/src/services/research-evidence.ts | 22 + .../src/services/research-source-evidence.ts | 341 +++++ .../web-api/src/services/research.service.ts | 222 ++- .../ChronologicalValidationDetailPage.tsx | 36 + .../experiments/ExperimentDetailPage.tsx | 28 + .../experiments/WalkForwardDetailPage.tsx | 36 + .../components/RegimeEvidenceUnavailable.tsx | 15 + .../components/SourceFindingAction.tsx | 48 + .../experiments/services/experimentApi.ts | 7 +- .../research/components/FindingSource.tsx | 49 + .../research/components/ResearchEntry.tsx | 11 +- .../research/components/SaveFindingDialog.tsx | 205 ++- .../research/components/findingSources.ts | 215 +++ .../features/research/services/researchApi.ts | 20 +- .../init/27-research-evidence-sources.sql | 92 ++ docs/development/ROADMAP.md | 18 +- docs/development/backlog/README.md | 8 +- docs/development/backlog/dependencies.mmd | 2 +- docs/development/backlog/manifest.json | 176 ++- docs/development/backlog/tasks/R07.md | 4 +- docs/development/backlog/tasks/R09.md | 18 +- libs/core/types/src/research.ts | 20 + test/e2e/fixture.ts | 1 + test/e2e/workbench.test.ts | 148 ++ test/integration/research-api.test.ts | 165 +- .../research-source-evidence-api.test.ts | 149 ++ .../research-source-evidence.test.ts | 104 ++ test/integration/research-source-ui.test.tsx | 1321 +++++++++++++++++ .../chronological-validation-durable.test.ts | 3 + test/postgres/migration-runner.test.ts | 1 + .../postgres/research-source-evidence.test.ts | 884 +++++++++++ test/postgres/research-workspace.test.ts | 3 + 36 files changed, 4170 insertions(+), 253 deletions(-) create mode 100644 apps/stock/web-api/src/services/research-source-evidence.ts create mode 100644 apps/stock/web-app/src/features/experiments/components/RegimeEvidenceUnavailable.tsx create mode 100644 apps/stock/web-app/src/features/experiments/components/SourceFindingAction.tsx create mode 100644 apps/stock/web-app/src/features/research/components/FindingSource.tsx create mode 100644 apps/stock/web-app/src/features/research/components/findingSources.ts create mode 100644 database/postgres/init/27-research-evidence-sources.sql create mode 100644 test/integration/research-source-evidence-api.test.ts create mode 100644 test/integration/research-source-evidence.test.ts create mode 100644 test/integration/research-source-ui.test.tsx create mode 100644 test/postgres/research-source-evidence.test.ts diff --git a/apps/stock/config/src/contracts/experiments.ts b/apps/stock/config/src/contracts/experiments.ts index 1d231d6d..6b27a5ba 100644 --- a/apps/stock/config/src/contracts/experiments.ts +++ b/apps/stock/config/src/contracts/experiments.ts @@ -129,6 +129,8 @@ export interface ExperimentTrial extends ExperimentCandidate { limitations: string[]; } export interface ExperimentDetail extends ExperimentSummary { + /** Server-derived role. Absent in older clients; only true admits a standalone source link. */ + standalone?: boolean; preview: ExperimentPreview; trials: ExperimentTrial[]; } diff --git a/apps/stock/config/src/contracts/research.ts b/apps/stock/config/src/contracts/research.ts index 14f6794c..3dd6867b 100644 --- a/apps/stock/config/src/contracts/research.ts +++ b/apps/stock/config/src/contracts/research.ts @@ -6,6 +6,39 @@ 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); +const sourceId = z + .string() + .uuid() + .transform(id => id.toLowerCase()); +const sourceHash = z.string().regex(/^[a-f0-9]{64}$/); +/** One source per immutable narrative revision; metrics remain ordinary run references. */ +export const researchFindingSourceSchema = z.discriminatedUnion('kind', [ + z + .object({ + kind: z.literal('experiment/v1'), + experimentId: sourceId, + previewHash: sourceHash, + }) + .strict(), + z + .object({ + kind: z.literal('chronological-report/v1'), + validationId: sourceId, + previewHash: sourceHash, + reportId: sourceId, + reportHash: sourceHash, + }) + .strict(), + z + .object({ + kind: z.literal('walk-forward-report/v1'), + walkForwardId: sourceId, + previewHash: sourceHash, + reportId: sourceId, + reportHash: sourceHash, + }) + .strict(), +]); export const createResearchProjectSchema = z .object({ title, @@ -107,6 +140,7 @@ export const createResearchArtifactSchema = z body: z.string(), contentOrigin: origin, evidence, + source: researchFindingSourceSchema.nullable().optional(), }) .strict(); export const reviseResearchArtifactSchema = z @@ -116,6 +150,8 @@ export const reviseResearchArtifactSchema = z body: z.string(), contentOrigin: origin, evidence, + /** Omitted preserves the prior revision's source; explicit null detaches the new revision. */ + source: researchFindingSourceSchema.nullable().optional(), }) .strict(); diff --git a/apps/stock/web-api/src/migrations/migration-runner.ts b/apps/stock/web-api/src/migrations/migration-runner.ts index 0bdb192d..b8926e67 100644 --- a/apps/stock/web-api/src/migrations/migration-runner.ts +++ b/apps/stock/web-api/src/migrations/migration-runner.ts @@ -66,7 +66,8 @@ export async function runMigrations(container: IServiceContainer): Promise f === '23-experiment-retries.sql' || f === '24-chronological-validation.sql' || f === '25-walk-forward.sql' || - f === '26-cost-sensitivity.sql') + f === '26-cost-sensitivity.sql' || + f === '27-research-evidence-sources.sql') ) // Explicit additive migration allowlist; never replay destructive init migrations .sort(); diff --git a/apps/stock/web-api/src/services/experiments.service.ts b/apps/stock/web-api/src/services/experiments.service.ts index c59c57ed..b666aa78 100644 --- a/apps/stock/web-api/src/services/experiments.service.ts +++ b/apps/stock/web-api/src/services/experiments.service.ts @@ -561,7 +561,7 @@ export class ExperimentsService { async readDetail(database: Query, id: string): Promise { const row = ( await database.query( - `SELECT ${summaryColumns},e.preview FROM research_experiments e WHERE e.id=$1`, + `SELECT ${summaryColumns},e.preview,(to_jsonb(e) ? 'validation_phase' AND to_jsonb(e)->'validation_phase' = 'null'::jsonb) AS standalone FROM research_experiments e WHERE e.id=$1`, [id] ) ).rows[0]; @@ -686,6 +686,12 @@ export class ExperimentsService { counts[run.status as keyof ExperimentCounts]++; } } - return { ...summary(row), counts, preview, trials } as WorkbenchExperimentDetail; + return { + ...summary(row), + standalone: row.standalone === true, + counts, + preview, + trials, + } as WorkbenchExperimentDetail; } } diff --git a/apps/stock/web-api/src/services/research-evidence.ts b/apps/stock/web-api/src/services/research-evidence.ts index e40516e8..d9397853 100644 --- a/apps/stock/web-api/src/services/research-evidence.ts +++ b/apps/stock/web-api/src/services/research-evidence.ts @@ -11,9 +11,11 @@ import type { CanonicalMetrics, ResearchEvidence, ResearchEvidenceReference, + ResearchFindingSource, } from '@stock-bot/types'; import { BacktestServiceV2, type BacktestResultQuery } from './backtest-v2.service'; import { ResearchError } from './research-errors'; +import { verifyResearchSource } from './research-source-evidence'; function unitOf(path: string): ResearchEvidence['unit'] { const name = path.split('.').at(-1); @@ -128,6 +130,26 @@ export class ResearchEvidenceResolver { this.results = new BacktestServiceV2(container); } + async resolveAll( + references: ResearchEvidenceReference[], + source: ResearchFindingSource | null, + database: BacktestResultQuery + ): Promise { + if (!source) { + return Promise.all(references.map(reference => this.resolve(reference, database))); + } + const results = await verifyResearchSource(source, references, database, (id, query) => + this.results.getRunResults(id, query) + ); + return references.map(reference => { + const result = results.get(reference.runId); + if (!result) { + throw new Error('Verified source result is missing'); + } + return projectResearchEvidence(reference, result); + }); + } + async resolve( input: ResearchEvidenceReference, database: BacktestResultQuery = this.database diff --git a/apps/stock/web-api/src/services/research-source-evidence.ts b/apps/stock/web-api/src/services/research-source-evidence.ts new file mode 100644 index 00000000..16fada46 --- /dev/null +++ b/apps/stock/web-api/src/services/research-source-evidence.ts @@ -0,0 +1,341 @@ +import type { QueryResultRow } from 'pg'; +import { at } from '@stock-bot/invariants'; +import { + isCanonicalRunResult, + type CanonicalRunResult, + type ResearchRunResult, +} from '@stock-bot/stock-config/canonical-research'; +import type { + ChronologicalValidationReport, + ChronologicalValidationSelection, + ValidationPhase, +} from '@stock-bot/stock-config/chronological-validation'; +import type { WorkbenchExperimentPreview } from '@stock-bot/stock-config/cost-sensitivity'; +import type { ExperimentCandidate } from '@stock-bot/stock-config/experiments'; +import type { WalkForwardSegment } from '@stock-bot/stock-config/walk-forward'; +import type { ResearchEvidenceReference, ResearchFindingSource } from '@stock-bot/types'; +import type { BacktestResultQuery } from './backtest-v2.service'; +import { retainedWorkbenchPreview, workbenchTrialRequest } from './cost-sensitivity-input'; +import { ResearchError } from './research-errors'; +import { + publicValidationDocument, + retainedValidationPreview, + selectValidationWinner, + validationEqual, + validationEvidence, + validationPhasePreview, +} from './validation-evidence'; +import { publicWalkForwardReport, retainedWalkForwardPreview } from './walk-forward-input'; + +function retained(condition: unknown, message: string): asserts condition { + if (!condition) { + throw new Error(`Retained finding source ${message}`); + } +} +function requested(condition: unknown, message: string): asserts condition { + if (!condition) { + throw new ResearchError(422, message); + } +} +function documentMetadata(value: Record, report: boolean): void { + const receipt = value._receipt as { key?: unknown; hash?: unknown } | undefined; + retained( + typeof value.id === 'string' && + /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(value.id) && + typeof value.createdAt === 'string' && + Number.isFinite(Date.parse(value.createdAt)) && + (value.principal === 'operator' || value.principal === 'service') && + typeof receipt?.key === 'string' && + /^[!-~]{1,200}$/.test(receipt.key) && + typeof receipt.hash === 'string' && + /^[a-f0-9]{64}$/.test(receipt.hash) && + (!report || + (Array.isArray(value.limitations) && + value.limitations.every(item => typeof item === 'string'))), + 'document metadata is invalid' + ); +} +type ResultReader = ( + id: string, + database: BacktestResultQuery +) => Promise; + +/** Historical provenance only. The existing canonical reader owns all financial validation. */ +export async function verifyResearchSource( + source: ResearchFindingSource, + references: ResearchEvidenceReference[], + database: BacktestResultQuery, + readResult: ResultReader +): Promise> { + requested( + references.length > 0 && references.every(r => r.metricsVersion === 'canonical-analytics/v1'), + 'A finding source requires at least one canonical metric reference' + ); + const results = new Map(); + const experiment = async (id: string) => + (await database.query('SELECT * FROM research_experiments WHERE id=$1', [id])).rows[0]; + const previewOf = (row: QueryResultRow): WorkbenchExperimentPreview => { + const preview = retainedWorkbenchPreview(row.preview); + retained( + preview.previewHash === row.preview_hash && + preview.input.backtestId === row.backtest_id && + preview.input.name === row.name, + 'experiment identity mismatch' + ); + return preview; + }; + const resultOf = async ( + row: QueryResultRow, + preview: WorkbenchExperimentPreview, + candidate: ExperimentCandidate + ) => { + retained( + row.status === 'completed' && + row.backtest_id === preview.input.backtestId && + row.trial_key === candidate.trialKey && + row.trial_index === candidate.index, + 'completed trial identity mismatch' + ); + const request = workbenchTrialRequest(preview, candidate, row.id); + retained( + validationEqual(row.request_snapshot, request) && row.dataset_hash === request.datasetHash, + 'trial request mismatch' + ); + let result = results.get(row.id); + if (!result) { + const saved = await readResult(row.id, database); + retained( + saved && + isCanonicalRunResult(saved) && + saved.runId === row.id && + saved.backtestId === row.backtest_id && + saved.status === 'completed', + 'canonical result unavailable' + ); + result = saved; + results.set(row.id, result); + } + retained(validationEqual(result.request, request), 'result request mismatch'); + return result; + }; + const phaseEvidence = async ( + row: QueryResultRow, + phase: ValidationPhase, + sourceIndex?: number + ) => { + const preview = previewOf(row); + retained( + preview.version === 'research-experiment-preview/v1' && row.validation_phase === phase, + 'phase kind mismatch' + ); + const runs = ( + await database.query('SELECT * FROM runs WHERE experiment_id=$1 ORDER BY trial_index', [ + row.id, + ]) + ).rows; + retained(runs.length === preview.candidates.length, 'phase run count mismatch'); + const evidence = []; + for (const [index, candidate] of preview.candidates.entries()) { + const run = at(runs, index); + const result = await resultOf(run, preview, candidate); + evidence.push( + validationEvidence(phase, row.id, candidate, sourceIndex ?? candidate.index, result) + ); + } + return evidence; + }; + const chronological = async (root: QueryResultRow): Promise => { + retained( + root.validation_phase === 'train' && + root.validation_parent_id === null && + root.validation_selection && + root.validation_report, + 'sealed chronological report unavailable' + ); + documentMetadata(root.validation_selection, false); + documentMetadata(root.validation_report, true); + const preview = retainedValidationPreview(root.validation_manifest); + const selection = publicValidationDocument( + root.validation_selection, + 'selectionHash' + ); + const report = publicValidationDocument( + root.validation_report, + 'reportHash' + ); + retained( + preview.input.backtestId === root.backtest_id && + validationEqual(previewOf(root), validationPhasePreview(preview, 'train')), + 'training preview mismatch' + ); + retained( + selection.version === 'chronological-validation-selection/v1' && + selection.validationId === root.id && + selection.previewHash === preview.previewHash && + report.version === 'chronological-validation-report/v1' && + report.validationId === root.id && + report.previewHash === preview.previewHash && + report.selectionHash === selection.selectionHash && + report.reset === 'initial-capital-empty-positions', + 'chronological report identity mismatch' + ); + const training = await phaseEvidence(root, 'train'); + const winner = selectValidationWinner(previewOf(root).candidates, training); + retained( + validationEqual(selection.training, training) && + validationEqual(report.training, training) && + validationEqual(selection.winner, winner), + 'training selection or report mismatch' + ); + const children = ( + await database.query( + 'SELECT * FROM research_experiments WHERE validation_parent_id=$1 ORDER BY validation_phase', + [root.id] + ) + ).rows; + retained(children.length === 2, 'holdout membership mismatch'); + for (const phase of ['validation', 'test'] as const) { + const child = children.find( + item => item.id === selection.holdoutExperimentIds[phase] && item.validation_phase === phase + ); + retained( + child && + child.backtest_id === root.backtest_id && + validationEqual( + previewOf(child), + validationPhasePreview(preview, phase, winner, selection.reviewId) + ), + 'holdout preview or membership mismatch' + ); + const evidence = await phaseEvidence(child, phase, winner.index); + retained( + evidence.length === 1 && validationEqual(report[phase], at(evidence, 0)), + 'holdout report mismatch' + ); + } + return report; + }; + try { + let members: Set; + if (source.kind === 'experiment/v1') { + const row = await experiment(source.experimentId); + requested( + row && row.validation_phase === null, + 'Source must be a retained standalone experiment' + ); + const preview = previewOf(row); + requested( + preview.previewHash === source.previewHash, + 'Source experiment preview does not match' + ); + members = new Set(); + for (const reference of references) { + const run = ( + await database.query('SELECT * FROM runs WHERE id=$1 AND experiment_id=$2', [ + reference.runId, + row.id, + ]) + ).rows[0]; + requested( + run && run.status === 'completed', + 'Evidence must be a completed source experiment trial' + ); + const candidate = preview.candidates[run.trial_index]; + retained(candidate, 'trial candidate unavailable'); + await resultOf(run, preview, candidate); + members.add(run.id); + } + } else if (source.kind === 'chronological-report/v1') { + const row = await experiment(source.validationId); + requested( + row && row.validation_phase === 'train' && row.validation_report, + 'Source requires a sealed chronological report' + ); + const report = await chronological(row); + requested( + report.id === source.reportId && + report.reportHash === source.reportHash && + report.previewHash === source.previewHash, + 'Source chronological report does not match' + ); + members = new Set( + [...report.training, report.validation, report.test].map(item => item.runId) + ); + } else { + const header = ( + await database.query('SELECT * FROM research_walk_forwards WHERE id=$1', [ + source.walkForwardId, + ]) + ).rows[0]; + requested(header && header.report, 'Source requires a sealed walk-forward report'); + documentMetadata(header.report, true); + const preview = retainedWalkForwardPreview(header.preview), + report = publicWalkForwardReport(header.report); + retained( + header.preview_hash === preview.previewHash && + header.backtest_id === preview.input.backtestId && + header.name === preview.input.name && + Array.isArray(header.member_ids) && + header.member_ids.length === preview.windows.length && + new Set(header.member_ids).size === header.member_ids.length, + 'walk-forward header identity mismatch' + ); + retained( + report.version === 'walk-forward-report/v1' && + report.walkForwardId === header.id && + report.previewHash === preview.previewHash && + report.reset === 'initial-capital-empty-positions', + 'walk-forward report identity mismatch' + ); + requested( + report.id === source.reportId && + report.reportHash === source.reportHash && + report.previewHash === source.previewHash, + 'Source walk-forward report does not match' + ); + const rows = ( + await database.query( + 'SELECT * FROM research_experiments WHERE walk_forward_id=$1 ORDER BY walk_forward_index', + [header.id] + ) + ).rows; + retained(rows.length === header.member_ids.length, 'walk-forward member count mismatch'); + const segments: WalkForwardSegment[] = []; + for (const [index, row] of rows.entries()) { + const window = at(preview.windows, index); + retained( + row.id === header.member_ids[index] && + row.walk_forward_index === index && + row.backtest_id === header.backtest_id && + validationEqual(row.validation_manifest, window.preview), + 'walk-forward member identity mismatch' + ); + const member = await chronological(row); + segments.push({ + index, + validationId: row.id, + previewHash: member.previewHash, + selectionHash: member.selectionHash, + reportId: member.id, + reportHash: member.reportHash, + validation: member.validation, + test: member.test, + }); + } + retained(validationEqual(report.segments, segments), 'walk-forward segment report mismatch'); + members = new Set( + segments.flatMap(segment => [segment.validation.runId, segment.test.runId]) + ); + } + requested( + references.every(reference => members.has(reference.runId)), + 'Evidence run does not belong to the selected source' + ); + return results; + } catch (cause) { + if (cause instanceof ResearchError) { + throw cause; + } + throw new Error('Retained research source could not be verified', { cause }); + } +} diff --git a/apps/stock/web-api/src/services/research.service.ts b/apps/stock/web-api/src/services/research.service.ts index 5cfece18..379e9686 100644 --- a/apps/stock/web-api/src/services/research.service.ts +++ b/apps/stock/web-api/src/services/research.service.ts @@ -8,6 +8,7 @@ import { createResearchProjectSchema, parseResearchInput, researchActorSchema, + researchFindingSourceSchema, researchIdSchema, reviseResearchArtifactSchema, reviseResearchHypothesisSchema, @@ -19,7 +20,9 @@ import type { ResearchArtifactRevision, ResearchAuthorship, ResearchContentOrigin, + ResearchEvidence, ResearchEvidenceReference, + ResearchFindingSource, ResearchHypothesis, ResearchHypothesisRevision, ResearchProject, @@ -90,6 +93,37 @@ function active(row: QueryResultRow, label: string): void { } } +function findingSource(raw: unknown): ResearchFindingSource | null { + if (raw === null || raw === undefined) { + return null; + } + try { + return researchFindingSourceSchema.parse(raw); + } catch (cause) { + throw new Error('Retained finding source identity is invalid', { cause }); + } +} +function artifactRevisionValue( + row: QueryResultRow, + evidence: ResearchEvidence[], + source: ResearchFindingSource | null +): ResearchArtifactRevision { + 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, + source, + createdAt: iso(row.created_at), + }; +} + /** Metadata transactions only. The existing result reader owns every measured value. */ export class ResearchService { private readonly database; @@ -320,14 +354,18 @@ export class ResearchService { } 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))); + researchIdSchema.parse(projectId); + return this.database.transaction(async client => { + await client.query('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY'); + await this.projectRow(client, projectId); + const rows = ( + await client.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(client, row))); + }); } async createArtifact( projectId: string, @@ -362,26 +400,36 @@ export class ResearchService { ).rows[0], 'Created artifact' ); - await this.insertArtifactRevision(client, row.id, 1, data, author); - return this.artifact(client, row); + const revision = await this.insertArtifactRevision( + client, + row.id, + 1, + { ...data, source: data.source ?? null }, + author + ); + return this.artifact(client, row, revision); }); } async getArtifact(id: string): Promise { - return this.artifact( - this.database, - await this.artifactRow(this.database, researchIdSchema.parse(id)) - ); + researchIdSchema.parse(id); + return this.database.transaction(async client => { + await client.query('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY'); + return this.artifact(client, await this.artifactRow(client, 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))); + return this.database.transaction(async client => { + await client.query('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY'); + await this.artifactRow(client, id); + const rows = ( + await client.query( + 'SELECT * FROM analysis_artifact_revisions WHERE artifact_id=$1 ORDER BY ordinal', + [id] + ) + ).rows; + return Promise.all(rows.map(row => this.artifactRevision(client, row))); + }); } async reviseArtifact( id: string, @@ -398,14 +446,21 @@ export class ResearchService { const current = required( ( await client.query( - 'SELECT ordinal FROM analysis_artifact_revisions WHERE artifact_id=$1 ORDER BY ordinal DESC LIMIT 1', + 'SELECT ordinal,source 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 source = data.source === undefined ? findingSource(current.source) : data.source; + const revision = await this.insertArtifactRevision( + client, + id, + data.expectedRevision + 1, + { ...data, source }, + author + ); const updated = required( ( await client.query( @@ -415,7 +470,7 @@ export class ResearchService { ).rows[0], 'Artifact' ); - return this.artifact(client, updated); + return this.artifact(client, updated, revision); }); } async archiveArtifact( @@ -531,16 +586,25 @@ export class ResearchService { ] ); } - 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] + private async artifact( + database: Database, + row: QueryResultRow, + resolved?: ResearchArtifactRevision + ): Promise { + const latest = + resolved ?? + (await this.artifactRevision( + database, + 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' ) - ).rows[0], - 'Artifact revision' - ); + )); return { id: row.id, projectId: row.project_id, @@ -551,45 +615,35 @@ export class ResearchService { updatedAt: iso(row.updated_at), archived: row.archived_at !== null, createdAt: iso(row.created_at), - latestRevision: await this.artifactRevision(database, latest), + latestRevision: latest, }; } private async artifactRevision( database: Database, row: QueryResultRow ): Promise { - const references = ( + const references: ResearchEvidenceReference[] = ( 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), - }; + ).rows.map(item => ({ + runId: item.run_id, + metricsVersion: item.metrics_version, + metricPath: item.metric_path, + strategyVersionId: item.strategy_version_id, + })); + const source = findingSource(row.source); + let evidence; + try { + evidence = await this.evidence.resolveAll(references, source, database); + } catch (cause) { + if (!source) { + throw cause; + } + throw new Error('Retained finding source evidence could not be resolved', { cause }); + } + return artifactRevisionValue(row, evidence, source); } private requireFindingEvidence(kind: string, evidence: ResearchEvidenceReference[]): void { if (kind === 'finding' && evidence.length === 0) { @@ -600,18 +654,39 @@ export class ResearchService { client: PoolClient, id: string, ordinal: number, - data: { title: string; body: string; evidence: ResearchEvidenceReference[] }, + data: { + title: string; + body: string; + evidence: ResearchEvidenceReference[]; + source: ResearchFindingSource | null; + }, author: ResearchAuthorship - ): Promise { - // Validate using the authoritative reader; only references are persisted. - for (const reference of data.evidence) { - await this.evidence.resolve(reference, client); - } + ): Promise { + // Validate once per revision; only references are persisted. + const references = data.evidence.map(reference => ({ + ...reference, + strategyVersionId: reference.strategyVersionId ?? null, + })); + const evidence = await this.evidence.resolveAll(references, data.source, 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] + const row = required( + ( + await client.query( + `INSERT INTO analysis_artifact_revisions(id,artifact_id,ordinal,title,body,submitted_by,content_origin,source) + VALUES($1,$2,$3,$4,$5,$6,$7,$8) RETURNING *`, + [ + revisionId, + id, + ordinal, + data.title, + data.body, + author.submittedBy, + author.contentOrigin, + data.source, + ] + ) + ).rows[0], + 'Artifact revision' ); for (const [index, reference] of data.evidence.entries()) { await client.query( @@ -627,5 +702,6 @@ export class ResearchService { ] ); } + return artifactRevisionValue(row, evidence, data.source); } } diff --git a/apps/stock/web-app/src/features/experiments/ChronologicalValidationDetailPage.tsx b/apps/stock/web-app/src/features/experiments/ChronologicalValidationDetailPage.tsx index 164bfd44..03f40b07 100644 --- a/apps/stock/web-app/src/features/experiments/ChronologicalValidationDetailPage.tsx +++ b/apps/stock/web-app/src/features/experiments/ChronologicalValidationDetailPage.tsx @@ -2,8 +2,11 @@ import { useEffect, useRef, useState } from 'react'; import { Link, useParams } from 'react-router-dom'; import type { ChronologicalValidationActionReceipt } from '@stock-bot/stock-config/chronological-validation'; import { Button } from '@/components/ui/Button'; +import { chronologicalFindingSource } from '@/features/research/components/findingSources'; import { useUnsavedWarning } from '@/features/strategies/components/useUnsavedWarning'; import { ExperimentCounts } from './components/ExperimentCounts'; +import { RegimeEvidenceUnavailable } from './components/RegimeEvidenceUnavailable'; +import { SourceFindingAction } from './components/SourceFindingAction'; import { ValidationEvidence } from './components/ValidationEvidence'; import { chronologicalValidationDurableApi, @@ -24,6 +27,7 @@ type Intent = key: string; }; function ValidationDetail({ validationId }: { validationId: string }) { + const [findingDirty, setFindingDirty] = useState(false); const alive = useRef(false), pending = useRef(false), reading = useRef(true), @@ -195,6 +199,22 @@ function ValidationDetail({ validationId }: { validationId: string }) {
{ + const findingLink = (event.target as HTMLElement).closest('a'); + if ( + findingLink && + (!findingLink.target || findingLink.target === '_self') && + findingDirty && + !event.ctrlKey && + !event.metaKey && + !event.shiftKey && + !window.confirm( + 'Leave this finding draft? The previous request may already have saved if its response was lost. Inspect saved records before submitting again.' + ) + ) { + event.preventDefault(); + event.stopPropagation(); + return; + } if ( (event.target as HTMLElement).closest('a') && captured.current && @@ -270,6 +290,15 @@ function ValidationDetail({ validationId }: { validationId: string }) { )} {validation && ( <> + + {!validation.report && ( + + )}

{validation.report ? 'Execution complete · report saved' @@ -481,6 +510,13 @@ function ValidationDetail({ validationId }: { validationId: string }) { {validation.report && (

Saved validation report

+

Report {validation.report.id} · {validation.report.reportHash} ·{' '} {validation.report.createdAt} · {validation.report.principal} diff --git a/apps/stock/web-app/src/features/experiments/ExperimentDetailPage.tsx b/apps/stock/web-app/src/features/experiments/ExperimentDetailPage.tsx index 90a10d55..8c808f5e 100644 --- a/apps/stock/web-app/src/features/experiments/ExperimentDetailPage.tsx +++ b/apps/stock/web-app/src/features/experiments/ExperimentDetailPage.tsx @@ -2,10 +2,13 @@ import { useCallback, useEffect, useRef, useState } from 'react'; import { Link, useParams } from 'react-router-dom'; import type { ExperimentTrial } from '@stock-bot/stock-config/experiments'; import { Button } from '@/components/ui/Button'; +import { experimentFindingSource } from '@/features/research/components/findingSources'; import { useUnsavedWarning } from '@/features/strategies/components/useUnsavedWarning'; import { ExperimentCounts } from './components/ExperimentCounts'; import { ExperimentInputs } from './components/ExperimentInputs'; import { ExperimentTrialRecovery } from './components/ExperimentTrialRecovery'; +import { RegimeEvidenceUnavailable } from './components/RegimeEvidenceUnavailable'; +import { SourceFindingAction } from './components/SourceFindingAction'; import { metricText } from './components/trialMetricText'; import { experimentApi, @@ -17,6 +20,7 @@ export function ExperimentDetailPage() { return ; } function ExperimentDetailView({ experimentId }: { experimentId: string }) { + const [findingDirty, setFindingDirty] = useState(false); const alive = useRef(false); const pending = useRef(false); const reading = useRef(true); @@ -135,6 +139,22 @@ function ExperimentDetailView({ experimentId }: { experimentId: string }) {

{ + const findingLink = (event.target as HTMLElement).closest('a'); + if ( + findingLink && + (!findingLink.target || findingLink.target === '_self') && + findingDirty && + !event.ctrlKey && + !event.metaKey && + !event.shiftKey && + !window.confirm( + 'Leave this finding draft? The previous request may already have saved if its response was lost. Inspect saved records before submitting again.' + ) + ) { + event.preventDefault(); + event.stopPropagation(); + return; + } if ( (event.target as HTMLElement).closest('a') && retryIntents.length > 0 && @@ -181,6 +201,14 @@ function ExperimentDetailView({ experimentId }: { experimentId: string }) { {experiment && ( <> + + 0} + onDirtyChange={setFindingDirty} + unavailable="Only explicitly standalone experiments can be cited here. Use the saved chronological or walk-forward report for validation evidence." + />
{ + const findingLink = (event.target as HTMLElement).closest('a'); + if ( + findingLink && + (!findingLink.target || findingLink.target === '_self') && + findingDirty && + !event.ctrlKey && + !event.metaKey && + !event.shiftKey && + !window.confirm( + 'Leave this finding draft? The previous request may already have saved if its response was lost. Inspect saved records before submitting again.' + ) + ) { + event.preventDefault(); + event.stopPropagation(); + return; + } if ( (event.target as HTMLElement).closest('a') && captured.current && @@ -239,6 +259,15 @@ function WalkForwardDetail({ walkForwardId }: { walkForwardId: string }) { )} {value && ( <> + + {!value.report && ( + + )}

{value.report ? 'Execution complete · walk-forward report saved' @@ -348,6 +377,13 @@ function WalkForwardDetail({ walkForwardId }: { walkForwardId: string }) { {value.report && (

Saved walk-forward report

+

Report {value.report.id} · {value.report.createdAt} · Hash {value.report.reportHash}

diff --git a/apps/stock/web-app/src/features/experiments/components/RegimeEvidenceUnavailable.tsx b/apps/stock/web-app/src/features/experiments/components/RegimeEvidenceUnavailable.tsx new file mode 100644 index 00000000..56343010 --- /dev/null +++ b/apps/stock/web-app/src/features/experiments/components/RegimeEvidenceUnavailable.tsx @@ -0,0 +1,15 @@ +export function RegimeEvidenceUnavailable() { + return ( +
+

Regime evidence unavailable

+

+ No versioned as-of regime annotations were retained for these results. Regime sample counts, + unclassified samples and window coverage are unavailable. +

+

+ Strategy names, parameters and current market classifications do not establish historical + regime evidence. +

+
+ ); +} diff --git a/apps/stock/web-app/src/features/experiments/components/SourceFindingAction.tsx b/apps/stock/web-app/src/features/experiments/components/SourceFindingAction.tsx new file mode 100644 index 00000000..dd0f392e --- /dev/null +++ b/apps/stock/web-app/src/features/experiments/components/SourceFindingAction.tsx @@ -0,0 +1,48 @@ +import { useState } from 'react'; +import { Button } from '@/components/ui/Button'; +import type { FindingDraftSource } from '@/features/research/components/findingSources'; +import { SaveSourceFindingDialog } from '@/features/research/components/SaveFindingDialog'; + +export function SourceFindingAction({ + source, + unavailable, + disabled, + onDirtyChange, +}: { + source: FindingDraftSource | null; + unavailable: string; + disabled?: boolean; + onDirtyChange: (dirty: boolean) => void; +}) { + const [snapshot, setSnapshot] = useState(null); + const eligible = source?.runs.some(run => run.metrics.length); + return ( +
+ + {!eligible && ( +

+ {source + ? 'No completed, comparable measurements are available to cite yet.' + : unavailable} +

+ )} + {snapshot && ( + setSnapshot(null)} + onDirtyChange={onDirtyChange} + /> + )} +
+ ); +} diff --git a/apps/stock/web-app/src/features/experiments/services/experimentApi.ts b/apps/stock/web-app/src/features/experiments/services/experimentApi.ts index d524ff5c..2ed9fb45 100644 --- a/apps/stock/web-app/src/features/experiments/services/experimentApi.ts +++ b/apps/stock/web-app/src/features/experiments/services/experimentApi.ts @@ -144,7 +144,11 @@ const trial = candidate.extend({ unavailable: z.record(z.string()).nullable(), limitations: z.array(z.string()), }); -const detail = summary.extend({ preview, trials: z.array(trial).max(MAX_EXPERIMENT_TRIALS) }); +const detail = summary.extend({ + standalone: z.boolean().optional(), + preview, + trials: z.array(trial).max(MAX_EXPERIMENT_TRIALS), +}); const retryReceipt = z.object({ id: z.string().uuid(), experimentId: z.string().uuid(), @@ -219,6 +223,7 @@ const costPreview = preview .strict(); const costDetail = summary.extend({ kind: z.literal('cost-sensitivity'), + standalone: z.boolean().optional(), preview: z.unknown(), trials: z.array(trial.extend({ costs: costScenarioSchema })).max(MAX_EXPERIMENT_TRIALS), }); diff --git a/apps/stock/web-app/src/features/research/components/FindingSource.tsx b/apps/stock/web-app/src/features/research/components/FindingSource.tsx new file mode 100644 index 00000000..5e034711 --- /dev/null +++ b/apps/stock/web-app/src/features/research/components/FindingSource.tsx @@ -0,0 +1,49 @@ +import { Link } from 'react-router-dom'; +import type { ResearchFindingSource } from '@stock-bot/types'; + +export function FindingSource({ + source, + link = true, +}: { + source?: ResearchFindingSource | null; + link?: boolean; +}) { + if (!source) { + return null; + } + const identity = + source.kind === 'experiment/v1' + ? source.experimentId + : source.kind === 'chronological-report/v1' + ? source.validationId + : source.walkForwardId; + const href = + source.kind === 'experiment/v1' + ? `/experiments/${identity}` + : source.kind === 'chronological-report/v1' + ? `/experiments/validation/${identity}` + : `/experiments/walk-forward/${identity}`; + return ( +
+

Exact evidence source

+

+ {source.kind} · {identity} +

+

Preview hash: {source.previewHash}

+ {'reportId' in source && ( +

+ Report: {source.reportId} · Report hash: {source.reportHash} +

+ )} +

+ Selected contributing evidence; the source does not validate this narrative or endorse the + whole experiment or report. +

+ {link && ( + + Open cited source + + )} +
+ ); +} diff --git a/apps/stock/web-app/src/features/research/components/ResearchEntry.tsx b/apps/stock/web-app/src/features/research/components/ResearchEntry.tsx index 7423636c..14acffd3 100644 --- a/apps/stock/web-app/src/features/research/components/ResearchEntry.tsx +++ b/apps/stock/web-app/src/features/research/components/ResearchEntry.tsx @@ -12,6 +12,7 @@ import { Card } from '@/components/ui/Card'; import { actionClass, fieldClass } from '../../strategies/components/StrategyParameterForm'; import { confirmDiscard, useUnsavedWarning } from '../../strategies/components/useUnsavedWarning'; import { researchApi, ResearchApiError } from '../services/researchApi'; +import { FindingSource } from './FindingSource'; import { evidenceReferences, ResearchAuthorshipBadge, @@ -255,6 +256,9 @@ export function ResearchEntry({ body, contentOrigin: origin, evidence: evidenceReferences(entry.entity.latestRevision.evidence), + ...(entry.entity.latestRevision.source !== undefined + ? { source: entry.entity.latestRevision.source } + : {}), }) ); } @@ -355,7 +359,12 @@ export function ResearchEntry({

)} - {'evidence' in revision && } + {'evidence' in revision && ( + <> + + + + )} {entry.kind === 'artifact' && entry.entity.hypothesisRevisionId && ( void }) { - return ; +/** Preserve the original single-run API and initial total-return selection. */ +export function SaveFindingDialog({ + result, + onClose, +}: { + result: ResearchRunResult; + onClose: () => void; +}) { + return ( + + ); } - -function FindingDraft({ result, onClose }: { result: ResearchRunResult; onClose: () => void }) { - const canonical = isCanonicalRunResult(result); - const metricPaths = canonical ? canonicalResearchMetricPaths : legacyResearchMetricPaths; +export function SaveSourceFindingDialog(props: { + source: FindingDraftSource; + onClose: () => void; + onDirtyChange?: (dirty: boolean) => void; +}) { + return ; +} +function FindingDraft({ + source: incoming, + onClose, + onDirtyChange, +}: { + source: FindingDraftSource; + onClose: () => void; + onDirtyChange?: (dirty: boolean) => void; +}) { + // Retain the exact open-time source and choices through background page refreshes. + const [source] = useState(() => structuredClone(incoming)); + const metrics = source.runs.flatMap(run => run.metrics); const [projects, setProjects] = useState([]); const [projectsLoading, setProjectsLoading] = useState(true); const [projectsError, setProjectsError] = useState(''); @@ -46,7 +73,7 @@ function FindingDraft({ result, onClose }: { result: ResearchRunResult; onClose: const [title, setTitle] = useState(''); const [body, setBody] = useState(''); const [contentOrigin, setContentOrigin] = useState('human'); - const [selectedMetrics, setSelectedMetrics] = useState([metricPaths[0]]); + const [selectedMetrics, setSelectedMetrics] = useState(source.initialSelection); const [pending, setPending] = useState(false); const [ambiguous, setAmbiguous] = useState(false); const [error, setError] = useState(''); @@ -63,10 +90,14 @@ function FindingDraft({ result, onClose }: { result: ResearchRunResult; onClose: body || projectId || contentOrigin !== 'human' || - selectedMetrics.length !== 1 || - selectedMetrics[0] !== metricPaths[0] + selectedMetrics.length !== source.initialSelection.length || + selectedMetrics.some((key, index) => key !== source.initialSelection[index]) ); useUnsavedWarning(dirty); + useEffect(() => { + onDirtyChange?.(dirty || pending || ambiguous); + }, [dirty, pending, ambiguous, onDirtyChange]); + useEffect(() => () => onDirtyChange?.(false), [onDirtyChange]); useEffect(() => { alive.current = true; @@ -159,7 +190,7 @@ function FindingDraft({ result, onClose }: { result: ResearchRunResult; onClose: destinationLoading || !title.trim() || !selectedMetrics.length || - result.status !== 'completed' + !metrics.length ) { return; } @@ -176,22 +207,10 @@ function FindingDraft({ result, onClose }: { result: ResearchRunResult; onClose: body, contentOrigin, hypothesisRevisionId: hypothesisRevisionId || null, - evidence: canonical - ? canonicalResearchMetricPaths - .filter(path => selectedMetrics.includes(path)) - .map(metricPath => ({ - runId: result.runId, - metricsVersion: 'canonical-analytics/v1' as const, - strategyVersionId: result.request.strategy.versionId, - metricPath, - })) - : legacyResearchMetricPaths - .filter(path => selectedMetrics.includes(path)) - .map(metricPath => ({ - runId: result.runId, - metricsVersion: 'legacy-display/v1' as const, - metricPath, - })), + evidence: metrics + .filter(metric => selectedMetrics.includes(findingMetricKey(metric.reference))) + .map(metric => metric.reference), + ...(source.context ? { source: source.context } : {}), }; submission.current = true; setPending(true); @@ -232,7 +251,20 @@ function FindingDraft({ result, onClose }: { result: ResearchRunResult; onClose: !artifact?.id || artifact.projectId !== projectId || artifact.hypothesisRevisionId !== input.hypothesisRevisionId || - artifact.kind !== 'finding' + artifact.kind !== 'finding' || + (source.context !== null && + (canonicalStrategyJson(artifact.latestRevision.source ?? null) !== + canonicalStrategyJson(source.context) || + canonicalStrategyJson( + artifact.latestRevision.evidence.map( + ({ runId, metricsVersion, metricPath, strategyVersionId }) => ({ + runId, + metricsVersion, + metricPath, + strategyVersionId, + }) + ) + ) !== canonicalStrategyJson(input.evidence))) ) { throw new ResearchApiError('The saved finding response could not be verified.', null); } @@ -249,9 +281,6 @@ function FindingDraft({ result, onClose }: { result: ResearchRunResult; onClose: } } } - const limitations = canonical - ? [...result.financial.limitations, ...result.financial.modelLimitations] - : (result.provenance?.limitations.map(item => item.message) ?? []); return ( !open && close()}> @@ -260,22 +289,23 @@ function FindingDraft({ result, onClose }: { result: ResearchRunResult; onClose: Save finding

- Run: {result.runId} ·{' '} - {canonical ? 'Canonical Rust result' : 'Legacy · Unverified economics'} + {source.label} ·{' '} + {source.legacy ? 'Legacy · Unverified economics' : 'Canonical Rust result'}

- {!canonical && ( + {source.legacy && (

Legacy display measurements are exploratory evidence; financial correctness and historical engine versions are not certified.

)} - {limitations.length > 0 && ( + {source.limitations.length > 0 && (
    - {limitations.map((limit, index) => ( + {source.limitations.map((limit, index) => (
  • {limit}
  • ))}
)} + {saved ? ( <>

Finding saved. Its narrative remains unvalidated.

@@ -404,38 +434,61 @@ function FindingDraft({ result, onClose }: { result: ResearchRunResult; onClose: A finding is an unvalidated narrative with references to saved measurements. Values are resolved by the server.

-
- Referenced measurements - {metricPaths.map(path => { - const value = path - .split('.') - .reduce( - (item, key) => - item && typeof item === 'object' - ? (item as Record)[key] - : undefined, - result + {source.context && ( +

+ Choose contributing runs and measurements explicitly. Unselected and unavailable + outcomes remain visible. +

+ )} + {source.runs.map(run => ( +
+ + {source.context ? `${run.label} · ${run.status}` : 'Referenced measurements'} + + {run.diagnostic &&

{run.diagnostic}

} + {!run.metrics.length && ( +

+ No selectable measurements. A completed, comparable saved result is required. +

+ )} + {run.metrics.map(metric => { + const key = findingMetricKey(metric.reference); + const label = researchMetricLabel(metric.reference.metricPath); + return ( + ); - return ( - - ); - })} -
+ })} +
+ ))} {error &&

{error}

} {ambiguous && (
@@ -475,7 +528,7 @@ function FindingDraft({ result, onClose }: { result: ResearchRunResult; onClose: destinationLoading || !title.trim() || !selectedMetrics.length || - result.status !== 'completed' + !metrics.length } onClick={() => void save()} > diff --git a/apps/stock/web-app/src/features/research/components/findingSources.ts b/apps/stock/web-app/src/features/research/components/findingSources.ts new file mode 100644 index 00000000..37a04d9f --- /dev/null +++ b/apps/stock/web-app/src/features/research/components/findingSources.ts @@ -0,0 +1,215 @@ +import { + isCanonicalRunResult, + type ResearchRunResult, +} from '@stock-bot/stock-config/canonical-research'; +import type { ValidationResultEvidence } from '@stock-bot/stock-config/chronological-validation'; +import { + canonicalResearchMetricPaths, + legacyResearchMetricPaths, +} from '@stock-bot/stock-config/research'; +import type { ResearchFindingSource } from '@stock-bot/types'; +import type { ValidationDetailView } from '@/features/experiments/services/chronologicalValidationDurableApi'; +import type { WorkbenchExperimentDetailView } from '@/features/experiments/services/experimentApi'; +import type { WalkForwardDetailView } from '@/features/experiments/services/walkForwardApi'; +import type { ArtifactInput } from '../services/researchApi'; + +type Reference = NonNullable[number]; +export interface FindingMetricChoice { + reference: Reference; + value: number | null; + unavailableReason?: string | null; +} +export interface FindingRunChoice { + key: string; + label: string; + status: string; + diagnostic: string | null; + metrics: FindingMetricChoice[]; +} +export interface FindingDraftSource { + key: string; + label: string; + context: ResearchFindingSource | null; + legacy: boolean; + limitations: string[]; + runs: FindingRunChoice[]; + initialSelection: string[]; +} +export const findingMetricKey = (reference: Reference) => + `${reference.runId}:${reference.metricsVersion}:${reference.metricPath}`; +const sourceMetrics = ['totalReturn', 'maxDrawdown', 'sharpeRatio'] as const; +function choices( + runId: string, + strategyVersionId: string, + metrics: Record<(typeof sourceMetrics)[number], number | null>, + unavailable: Record +): FindingMetricChoice[] { + return sourceMetrics.map(key => ({ + reference: { + runId, + strategyVersionId, + metricsVersion: 'canonical-analytics/v1', + metricPath: `analytics.metrics.${key}`, + }, + value: metrics[key], + unavailableReason: unavailable[key], + })); +} +export function singleRunFindingSource(result: ResearchRunResult): FindingDraftSource { + const canonical = isCanonicalRunResult(result); + const references: Reference[] = canonical + ? canonicalResearchMetricPaths.map(metricPath => ({ + runId: result.runId, + metricsVersion: 'canonical-analytics/v1', + strategyVersionId: result.request.strategy.versionId, + metricPath, + })) + : legacyResearchMetricPaths.map(metricPath => ({ + runId: result.runId, + metricsVersion: 'legacy-display/v1', + metricPath, + })); + const metrics = + result.status === 'completed' + ? references.map(reference => { + const value = reference.metricPath + .split('.') + .reduce( + (item, key) => + item && typeof item === 'object' + ? (item as Record)[key] + : undefined, + result + ); + return { reference, value: typeof value === 'number' ? value : null }; + }) + : []; + return { + key: `${result.backtestId}:${result.runId}`, + label: `Run: ${result.runId}`, + context: null, + legacy: !canonical, + limitations: canonical + ? [...result.financial.limitations, ...result.financial.modelLimitations] + : (result.provenance?.limitations.map(item => item.message) ?? []), + runs: [{ key: result.runId, label: 'Run', status: result.status, diagnostic: null, metrics }], + initialSelection: metrics[0] ? [findingMetricKey(metrics[0].reference)] : [], + }; +} +function source( + context: ResearchFindingSource, + label: string, + runs: FindingRunChoice[], + limitations: string[] +): FindingDraftSource { + return { + key: JSON.stringify(context), + label, + context, + legacy: false, + runs, + limitations, + initialSelection: [], + }; +} +export function experimentFindingSource( + value: WorkbenchExperimentDetailView +): FindingDraftSource | null { + if (value.standalone !== true) { + return null; + } + return source( + { kind: 'experiment/v1', experimentId: value.id, previewHash: value.previewHash }, + value.name, + value.trials.map(trial => ({ + key: trial.trialKey, + label: + value.kind === 'cost-sensitivity' + ? trial.index === 0 + ? 'Baseline' + : `Scenario ${trial.index}` + : `Trial ${trial.index + 1}`, + status: + trial.status === 'completed' && !trial.comparable + ? 'completed · incomparable' + : trial.status, + diagnostic: trial.error ?? trial.diagnostic, + metrics: + trial.status === 'completed' && + trial.comparable && + trial.runId && + trial.metrics && + trial.unavailable + ? choices(trial.runId, value.strategyVersionId, trial.metrics, trial.unavailable) + : [], + })), + [ + 'Selected contributing measurements do not endorse the whole experiment or establish out-of-sample validity.', + ] + ); +} +function reportRun( + item: ValidationResultEvidence, + strategyVersionId: string, + prefix = '' +): FindingRunChoice { + return { + key: `${prefix}${item.phase}:${item.runId}`, + label: `${prefix}${item.phase} candidate ${item.sourceCandidateIndex + 1}`, + status: 'completed', + diagnostic: null, + metrics: choices(item.runId, strategyVersionId, item.metrics, item.unavailable), + }; +} +export function chronologicalFindingSource(value: ValidationDetailView): FindingDraftSource | null { + const report = value.report; + if (!report) { + return null; + } + return source( + { + kind: 'chronological-report/v1', + validationId: value.id, + previewHash: value.previewHash, + reportId: report.id, + reportHash: report.reportHash, + }, + value.name, + [...report.training, report.validation, report.test].map(item => + reportRun(item, value.preview.source.request.strategy.versionId) + ), + [ + ...report.limitations, + 'Selected contributing measurements do not endorse the whole report. Training, validation and test remain distinct reset accounts.', + ] + ); +} +export function walkForwardFindingSource(value: WalkForwardDetailView): FindingDraftSource | null { + const report = value.report; + if (!report) { + return null; + } + return source( + { + kind: 'walk-forward-report/v1', + walkForwardId: value.id, + previewHash: value.previewHash, + reportId: report.id, + reportHash: report.reportHash, + }, + value.name, + report.segments.flatMap(segment => + [segment.validation, segment.test].map(item => + reportRun( + item, + value.preview.source.request.strategy.versionId, + `Window ${segment.index + 1} ` + ) + ) + ), + [ + ...report.limitations, + 'Selected contributing measurements do not endorse the whole report. Windows are independent reset segments, not continuous portfolio equity.', + ] + ); +} diff --git a/apps/stock/web-app/src/features/research/services/researchApi.ts b/apps/stock/web-app/src/features/research/services/researchApi.ts index b45a30c8..4cdb5071 100644 --- a/apps/stock/web-app/src/features/research/services/researchApi.ts +++ b/apps/stock/web-app/src/features/research/services/researchApi.ts @@ -1,4 +1,5 @@ import type { z } from 'zod'; +import { researchFindingSourceSchema } from '@stock-bot/stock-config/research'; import type { createResearchArtifactSchema, createResearchHypothesisSchema, @@ -49,6 +50,17 @@ const record = (value: unknown): value is Record => typeof value === 'object' && value !== null && !Array.isArray(value); const identified = (value: unknown): value is Record => record(value) && typeof value.id === 'string' && value.id.length > 0; +function validSource(value: Record): boolean { + if (value.source === undefined || value.source === null) { + return true; + } + const parsed = researchFindingSourceSchema.safeParse(value.source); + if (!parsed.success) { + return false; + } + value.source = parsed.data; + return true; +} function validEnvelope(body: unknown, field: ResponseField): boolean { if (!record(body)) { return false; @@ -61,9 +73,13 @@ function validEnvelope(body: unknown, field: ResponseField): boolean { return typeof item.title === 'string' && Number.isInteger(item.revision); } if (['hypothesis', 'hypotheses', 'artifact', 'artifacts'].includes(field)) { - return typeof item.projectId === 'string' && identified(item.latestRevision); + return ( + typeof item.projectId === 'string' && + identified(item.latestRevision) && + validSource(item.latestRevision) + ); } - return true; + return validSource(item); }; const value = body[field]; return ['project', 'hypothesis', 'artifact'].includes(field) diff --git a/database/postgres/init/27-research-evidence-sources.sql b/database/postgres/init/27-research-evidence-sources.sql new file mode 100644 index 00000000..7a34410b --- /dev/null +++ b/database/postgres/init/27-research-evidence-sources.sql @@ -0,0 +1,92 @@ +-- Add source identity to immutable narrative revisions. Measurements remain run references. +ALTER TABLE analysis_artifact_revisions ADD COLUMN IF NOT EXISTS source JSONB; +DO $$ BEGIN + IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname='workspace_source_object' AND conrelid='analysis_artifact_revisions'::regclass) THEN + ALTER TABLE analysis_artifact_revisions ADD CONSTRAINT workspace_source_object CHECK (source IS NULL OR jsonb_typeof(source)='object'); + END IF; +END $$; + +CREATE OR REPLACE FUNCTION require_workspace_source_evidence() RETURNS trigger LANGUAGE plpgsql AS $$ +DECLARE source JSONB; revision analysis_artifact_revisions; experiment research_experiments; header research_walk_forwards; + document JSONB; allowed TEXT[]; ref RECORD; expected JSONB; count_refs INTEGER:=0; +BEGIN + IF TG_TABLE_NAME='analysis_evidence' THEN + SELECT * INTO revision FROM analysis_artifact_revisions WHERE id=NEW.revision_id; + ELSE revision:=NEW; END IF; + source:=revision.source; + IF source IS NULL THEN RETURN NULL; END IF; + IF (jsonb_typeof(source)='object' AND source->>'previewHash' ~ '^[a-f0-9]{64}$') IS NOT TRUE THEN + RAISE EXCEPTION 'Finding source requires a strict immutable identity' USING ERRCODE='23514'; + END IF; + IF source->>'kind'='experiment/v1' THEN + IF (source=jsonb_build_object('kind','experiment/v1','experimentId',source->'experimentId','previewHash',source->'previewHash') + AND source->>'experimentId' ~ '^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$') IS NOT TRUE THEN + RAISE EXCEPTION 'Finding experiment source shape is invalid' USING ERRCODE='23514'; + END IF; + SELECT * INTO experiment FROM research_experiments WHERE id::text=source->>'experimentId'; + IF (experiment.id IS NOT NULL AND experiment.validation_phase IS NULL AND experiment.preview_hash=source->>'previewHash' + AND experiment.preview->>'previewHash'=experiment.preview_hash) IS NOT TRUE THEN + RAISE EXCEPTION 'Finding source requires the exact standalone experiment preview' USING ERRCODE='23514'; + END IF; + SELECT array_agg(id::text) INTO allowed FROM runs WHERE experiment_id=experiment.id; + ELSIF source->>'kind'='chronological-report/v1' THEN + IF (source=jsonb_build_object('kind','chronological-report/v1','validationId',source->'validationId','previewHash',source->'previewHash','reportId',source->'reportId','reportHash',source->'reportHash') + AND source->>'validationId' ~ '^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$' + AND source->>'reportId' ~ '^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$' + AND source->>'reportHash' ~ '^[a-f0-9]{64}$') IS NOT TRUE THEN + RAISE EXCEPTION 'Finding chronological source shape is invalid' USING ERRCODE='23514'; + END IF; + SELECT * INTO experiment FROM research_experiments WHERE id::text=source->>'validationId'; + document:=experiment.validation_report; + IF (experiment.validation_phase='train' AND document->>'version'='chronological-validation-report/v1' + AND document->>'validationId'=experiment.id::text AND document->>'id'=source->>'reportId' + AND document->>'reportHash'=source->>'reportHash' AND document->>'previewHash'=source->>'previewHash' + AND experiment.validation_manifest->>'previewHash'=source->>'previewHash' + AND document->>'selectionHash'=experiment.validation_selection->>'selectionHash') IS NOT TRUE THEN + RAISE EXCEPTION 'Finding source requires the exact sealed chronological report' USING ERRCODE='23514'; + END IF; + SELECT array_agg(item->>'runId') INTO allowed FROM jsonb_array_elements((document->'training') || jsonb_build_array(document->'validation',document->'test')) item; + ELSIF source->>'kind'='walk-forward-report/v1' THEN + IF (source=jsonb_build_object('kind','walk-forward-report/v1','walkForwardId',source->'walkForwardId','previewHash',source->'previewHash','reportId',source->'reportId','reportHash',source->'reportHash') + AND source->>'walkForwardId' ~ '^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$' + AND source->>'reportId' ~ '^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$' + AND source->>'reportHash' ~ '^[a-f0-9]{64}$') IS NOT TRUE THEN + RAISE EXCEPTION 'Finding walk-forward source shape is invalid' USING ERRCODE='23514'; + END IF; + SELECT * INTO header FROM research_walk_forwards WHERE id::text=source->>'walkForwardId'; + document:=header.report; + IF (document->>'version'='walk-forward-report/v1' AND document->>'walkForwardId'=header.id::text + AND document->>'id'=source->>'reportId' AND document->>'reportHash'=source->>'reportHash' + AND document->>'previewHash'=source->>'previewHash' AND header.preview_hash=source->>'previewHash') IS NOT TRUE THEN + RAISE EXCEPTION 'Finding source requires the exact sealed walk-forward report' USING ERRCODE='23514'; + END IF; + SELECT array_agg(item->>'runId') INTO allowed FROM jsonb_array_elements(document->'segments') segment, + LATERAL jsonb_array_elements(jsonb_build_array(segment->'validation',segment->'test')) item; + ELSE + RAISE EXCEPTION 'Unsupported finding source kind' USING ERRCODE='23514'; + END IF; + FOR ref IN SELECT ae.*,r.status,r.experiment_id,r.backtest_id,r.trial_index,r.trial_key,r.request_snapshot,r.dataset_hash, + e.preview,br.canonical_result FROM analysis_evidence ae JOIN runs r ON r.id=ae.run_id + JOIN backtest_results br ON br.run_id=r.id LEFT JOIN research_experiments e ON e.id=r.experiment_id WHERE ae.revision_id=revision.id LOOP + count_refs:=count_refs+1; + IF (ref.metrics_version='canonical-analytics/v1' AND ref.run_id::text=ANY(allowed) AND ref.status='completed' + AND ref.experiment_id IS NOT NULL AND ref.preview#>>ARRAY['candidates',ref.trial_index::text,'trialKey']=ref.trial_key) IS NOT TRUE THEN + RAISE EXCEPTION 'Finding evidence requires completed canonical members of its source' USING ERRCODE='23514'; + END IF; + expected:=experiment_trial_request(ref.preview,ref.trial_index,ref.run_id); + IF (ref.request_snapshot=expected AND ref.dataset_hash=expected->>'datasetHash' + AND ref.backtest_id::text=expected->>'backtestId' AND ref.canonical_result->'request'=expected + AND ref.canonical_result->>'runId'=ref.run_id::text AND ref.canonical_result->>'kind'='canonical-result/v1') IS NOT TRUE THEN + RAISE EXCEPTION 'Finding source evidence requires its exact frozen trial request' USING ERRCODE='23514'; + END IF; + END LOOP; + IF count_refs=0 THEN RAISE EXCEPTION 'A source requires at least one canonical metric reference' USING ERRCODE='23514'; END IF; + RETURN NULL; +END $$; +DROP TRIGGER IF EXISTS workspace_source_evidence ON analysis_artifact_revisions; +CREATE CONSTRAINT TRIGGER workspace_source_evidence AFTER INSERT ON analysis_artifact_revisions + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION require_workspace_source_evidence(); + +DROP TRIGGER IF EXISTS workspace_source_member ON analysis_evidence; +CREATE CONSTRAINT TRIGGER workspace_source_member AFTER INSERT ON analysis_evidence + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION require_workspace_source_evidence(); diff --git a/docs/development/ROADMAP.md b/docs/development/ROADMAP.md index 33247ffc..bac6ffc0 100644 --- a/docs/development/ROADMAP.md +++ b/docs/development/ROADMAP.md @@ -1,8 +1,8 @@ # Revised development roadmap -**First thirty-two waves committed; R07 functional comparison is validated and awaiting commit.** Full R08 is committed as `397cd0e`; **36 of 45 scheduled tasks are fully committed (80% by count)**. R05 remains partial; R07 retains only its paused table measurement after this functional component is accepted. +**First thirty-three waves committed; R09 research source citations are validated and ready to commit.** R07 functional comparison is committed as `46a4f13`; **36 of 45 scheduled tasks are fully committed (80% by count)**, with R09 in review. R05 remains partial, and R07 retains its paused table measurement. -Authorization update: the owner requested “commit and continue”. Walk-forward is committed as `3ed7b98`; bounded fee/slippage sensitivity is now implemented and independently validated. No performance work, new-wave commits/pushes/PRs, candidate execution or trading/default activation is included. +Authorization update: the owner requested “commit and continue”. R07 functional comparison was committed as `46a4f13`; supported R09 evidence citations are now independently reviewed and validated. Performance work remains paused. No new-wave commit, push, PR, candidate execution or trading/default activation occurred. ## Strategy and review outcome @@ -683,3 +683,17 @@ All repository gates passed: **988 integration /150 Rust**, plus 93 tooling, 43 Independent review accepted both six-file overlays plus root contract/route/browser composition; all 17 source hashes and the archive are recorded in `manifest.json` → `thirty_third_wave_validation`, under `/tmp/stock-bot-wave33.c3IAY2/`. The unchanged release engine was restored before final database/browser gates. Both exact disposable containers were removed; development services are untouched. Wave33 remains uncommitted; no push or PR. Full R07 remains partial solely because its large-table measurement is explicitly paused and unrun. After accepting/committing this functional component, R09 can consume it without waiting for performance work: record the component commit as a satisfied prerequisite rather than claiming the whole task complete. Next non-performance work is evidence/finding integration over existing R08 validation and cost outputs. R05 provider/default cutover, pending architecture approvals and candidate/AI/multiasset/paper/live activation gates remain unchanged. + +## Thirty-fourth-wave handoff — 2026-10-24 + +The accepted R07 functional comparison is committed as `46a4f13`. Supported R09 is independently reviewed and validated, with new changes uncommitted. Its prerequisite uses the accepted R07 component; the paused table measurement is not a functional dependency. Existing R08 phase/reset/warmup/cost/sample displays remain intact. + +- **Exact citations:** Existing immutable finding revisions can cite one standalone experiment, sealed chronological report or sealed walk-forward report, together with selected canonical run/metric references. SQL27 is additive; historical SQL20/22–26 are unchanged. Omitted source preserves the previous citation on revision; explicit null detaches only the new revision. Existing single-run findings and unvalidated narrative status remain. +- **Historical integrity:** One repeatable read-only client verifies immutable source identity, membership and full retained Rust results, including all training evidence underlying sealed reports. Archived, cancelled or currently ineligible sources remain historically readable. Checks reject forged reports, mismatched members, corrupt metrics and direct SQL insertion/timing bypasses. No new evidence store, scheduler, financial calculation or engine path. +- **Web workflow:** The existing finding form offers explicit eligible run/metric choices from experiment and report pages. Stored raw values carry units/null reasons. Source links survive edits, immutable history and reopening. Ambiguous writes remain frozen until the user checks saved records. Regime evidence is explicitly unavailable: S05 retains no versioned as-of classification series, so positive regime reconciliation is neither implemented nor claimed tested. + +All final gates passed: **1024 integration /150 Rust** tests, plus 93 tooling, 43 utility and 44 calculation tests; build, types, contracts, lint and secret audit. Release **PostgreSQL/Redis: 235 tests /2099 assertions**; **Chromium: 16 workflows /569 assertions**. Strict affected-test types, scoped lint/format, source/hash/DAG and whitespace checks pass. The first full database run exposed a pre-SQL24 role-projection regression; a conservative metadata-presence projection fixed it, a real pre/post-migration test was added, and all gates were rerun successfully. Four preexisting manual Rust cases remain ignored. + +Independent review accepted backend/frontend overlays and root contracts/browser/compatibility changes. Thirty source/test/config/SQL file hashes, exact archive, native identities and logs are recorded in `manifest.json` → `thirty_fourth_wave_validation`, under `/tmp/stock-bot-wave34.02YVEd/`. Archive SHA256: `7df43baf277dc28d7ee186aee233ad13c134b20e0bd86a7300688acb6e0fd8af`. The unchanged release engine was restored before final database/browser gates. Both exact disposable containers were stopped; development services were untouched. + +R09 is in review pending acceptance/commit. R05 provider preparation/default cutover, R07 paused measurement, pending architecture approvals and candidate/AI/multiasset/paper/live activation gates remain unchanged. No performance measurements, new-wave commit, push or PR occurred. diff --git a/docs/development/backlog/README.md b/docs/development/backlog/README.md index d0ed04e4..28dc8444 100644 --- a/docs/development/backlog/README.md +++ b/docs/development/backlog/README.md @@ -1,6 +1,6 @@ # Canonical development backlog -**First thirty-two waves committed; R07 functional comparison is validated and awaiting commit.** Full R08 is committed as `397cd0e`; **36 of 45 scheduled tasks are fully committed (80% by count)**. R05 remains partial; R07 retains only its paused table measurement after this functional component is accepted. +**First thirty-three waves committed; R09 research source citations are validated and ready to commit.** R07 functional comparison is committed as `46a4f13`; **36 of 45 scheduled tasks are fully committed (80% by count)**, with R09 in review. R05 remains partial, and R07 retains its paused table measurement. ## One source of truth @@ -78,9 +78,9 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr | [R04 Deliver research workspace and save-findings flow](tasks/R04.md) | P1 / done | 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 / done | Accepted R05 retained-input component; R01/R10/F08/S02/D01/W03/C06/R12, ADR-006 | — | Full-stack research product / M | -| [R07 Deliver sweep configuration and comparable-result views](tasks/R07.md) | P1 / in_progress (functional validated, awaiting commit; measurement paused) | R06, ADR-006 | W04 | Full-stack research product / M | +| [R07 Deliver sweep configuration and comparable-result views](tasks/R07.md) | P1 / in_progress (functional committed; measurement paused) | R06, ADR-006 | W04 | Full-stack research product / M | | [R08 Add bounded chronological and reset-segment validation](tasks/R08.md) | P1 / done | R06, ADR-006 | — | Quantitative research integrity / M | -| [R09 Expose validation, cost and regime evidence in the workbench](tasks/R09.md) | P1 / blocked | R07, R08, ADR-006 | S05 when Regime comparison is enabled; R03 when Saving or linking a research finding is enabled | Full-stack research product / M | +| [R09 Expose validation, cost and regime evidence in the workbench](tasks/R09.md) | P1 / review (validated, uncommitted) | R08, committed R07 functional component, ADR-006 | S05 when Regime comparison is enabled; R03 when Saving or linking a research finding is enabled | Full-stack research product / M | | [R10 Protect retained research evidence and artifact integrity](tasks/R10.md) | P1 / done | R01, ADR-006 | — | Full-stack research product / M | | [R11 Select and reuse frozen datasets in the workbench](tasks/R11.md) | P1 / done | D01, O01, ADR-003, ADR-006 | W04 | Full-stack market data/research / M | | [R12 Reproduce an original run separately from rerunning current settings](tasks/R12.md) | P1 / done | Accepted R05 retained-input component; W04/R01/R10/F08/S02/D01/W03/C06, ADR-006 | — | Full-stack reproducible research / S | @@ -118,4 +118,4 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr Before any wave: unique IDs; existing task/ADR references; acyclic implementation graph; no scheduled task dependent on merged/deferred work; approvals/readiness; actual file locks; isolated native build outputs/workspace dependencies and test databases. Release gates are checked separately at activation. -R06 is complete (`b373410`), and full supported R08 is committed as `397cd0e`. Wave33 independently validates read-only comparison across saved standalone experiments and awaits commit. R07 functional acceptance does not require resuming its paused table measurement; R09 may consume the accepted functional component after commit. R05 remains partial, and AI/default/trading activation retain their gates. +R06 and R08 are committed. R07 functional comparison is accepted and committed as `46a4f13`; only its paused measurement remains. R09 consumes that functional component and now implements source-linked findings over existing validation/cost evidence. Positive regime slicing requires a retained annotation contract that S05 does not provide. Performance and candidate/AI/default/trading gates remain unchanged. diff --git a/docs/development/backlog/dependencies.mmd b/docs/development/backlog/dependencies.mmd index dfe09453..45f442d9 100644 --- a/docs/development/backlog/dependencies.mmd +++ b/docs/development/backlog/dependencies.mmd @@ -157,7 +157,7 @@ flowchart TD W04 -. release only .-> R07 R06 --> R08 ADR006 --> R08 - R07 --> R09 + R07 -. accepted functional component 46a4f13 .-> R09 R08 --> R09 ADR006 --> R09 S05 -. Regime comparison is enabled .-> R09 diff --git a/docs/development/backlog/manifest.json b/docs/development/backlog/manifest.json index b0bf3d1b..f785784e 100644 --- a/docs/development/backlog/manifest.json +++ b/docs/development/backlog/manifest.json @@ -1,14 +1,14 @@ { "schema_version": 1, - "plan_revision": "2026-10-24.70", + "plan_revision": "2026-10-24.71", "repository_base": "b7aeca4", - "plan_status": "thirty_third_wave_functional_validated_awaiting_commit", + "plan_status": "thirty_fourth_wave_validated_awaiting_commit", "execution_authorized": true, "execution_scope": { - "authorized_by": "User: commit and continue; accepted full R08 committed 397cd0e1603b7ccd01bf80c9ff3930ba2a1b9963", - "tasks": ["R07"], + "authorized_by": "User: commit and continue; accepted R07 functional comparison committed 46a4f13acd5fdce08f1b19e465f428471656269f", + "tasks": ["R09"], "permissions": [ - "Read-only comparisons across two saved standalone experiments, explicit reference trial and preserved native summaries; no rankings or financial recomputation" + "R09 exact experiment/report source links in existing research findings; historical verification, web save/reopen and explicit unavailable regime evidence." ], "excluded": [ "performance_profiling_or_optimization", @@ -1402,12 +1402,12 @@ "completed_commit": null, "blocker": null, "release_gates": ["W04"], - "integration_state": "partial_validated_uncommitted", + "integration_state": "partial_validated_committed", "integration_base": "397cd0e1603b7ccd01bf80c9ff3930ba2a1b9963", "worktree": "/home/boki/repos/stock-bot", "execution_component": "Read-only cross-experiment comparison with explicit reference and retained input compatibility", "component_exclusions": ["Large-table performance measurements remain paused"], - "component_readiness": "Cross-experiment comparison is independently reviewed and all root gates pass. Functional acceptance awaits owner commit; only explicitly paused large-table measurement remains outstanding in full R07.", + "component_readiness": "Accepted functional sweep/comparison/retry UI committed46a4f13. Only paused/unrun large-table measurement remains outstanding; accepted component satisfies R09 functional dependency.", "reviewed_by": "/root/r04_review", "verification_reference": "ROADMAP.md#thirty-third-wave-handoff--2026-10-24", "review_notes": "Final exact source snapshots accepted. Full repository, PostgreSQL/Redis, Chromium and authored types/lint/format pass. Matching retained inputs is not financial/statistical equivalence; no performance measurement claimed.", @@ -1427,7 +1427,7 @@ "scope": "Shared DTO/export and route, real native browser acceptance, integrated gates and planning" } ], - "partial_commit": "b373410320e987ddce1ee8dd5e8a691cf183d527" + "partial_commit": "46a4f13acd5fdce08f1b19e465f428471656269f" }, { "id": "R08", @@ -1487,8 +1487,8 @@ "epic": "E6", "priority": "P1", "severity": "High", - "status": "blocked", - "dependencies": ["R07", "R08"], + "status": "review", + "dependencies": ["R08"], "decision_dependencies": ["ADR-006"], "task_file": "backlog/tasks/R09.md", "findings": ["RES-01", "WEB-01"], @@ -1496,7 +1496,7 @@ "specialization": "Full-stack research product", "write_locks": ["web-experiments"], "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, @@ -1512,7 +1512,37 @@ "tasks": ["R03"] } ], - "component_readiness": "After accepted wave33 functional commit, replace whole-R07 prerequisite with a satisfied_component_dependencies record for accepted comparison/sweep/retry UI, retaining R08 dependency. Paused table measurement is not a functional prerequisite; do not mark ready before commit." + "component_readiness": "R08 and R03 committed; R07 functional component accepted. S05 does not retain per-session as-of regime annotations, so positive regime slicing remains unavailable.", + "integration_state": "validated_uncommitted", + "integration_base": "46a4f13acd5fdce08f1b19e465f428471656269f", + "worktree": "/home/boki/repos/stock-bot", + "execution_component": "Exact retained experiment/report citations through existing findings, with explicit unavailable regime evidence", + "satisfied_component_dependencies": [ + { + "task": "R07", + "scope": "Accepted functional sweep/comparison/retry UI; paused table measurement not required for citations", + "commit": "46a4f13acd5fdce08f1b19e465f428471656269f" + } + ], + "implementation_slices": [ + { + "owner": "/root/r12_backend", + "worktree": "/tmp/stock-bot-wave34.02YVEd/backend", + "scope": "SQL27 optional revision source and historical verifier; research service and role emission; pure/API/PostgreSQL tests" + }, + { + "owner": "/root/r12_frontend", + "worktree": "/tmp/stock-bot-wave34.02YVEd/frontend", + "scope": "Existing finding form generalized, page source actions, historical source links and explicit regime unavailable; UI tests" + }, + { + "owner": "/root", + "scope": "Shared DTO/types, migration registry/old workspace fixtures, native browser workflow and combined gates/planning" + } + ], + "reviewed_by": "/root/r04_review", + "verification_reference": "ROADMAP.md#thirty-fourth-wave-handoff--2026-10-24", + "completion_scope": "Supported source-linked findings and unavailable-regime display validated. Positive regime slicing remains conditional on a retained as-of annotation contract and is not claimed implemented or tested." }, { "id": "R10", @@ -7278,7 +7308,7 @@ "Root integrates shared contract and actual native browser lifecycle; backend/frontend isolated; independent reviewer; no new-wave commit/push/PR." ], "thirty_third_wave_validation": { - "state": "partial_validated_uncommitted", + "state": "partial_validated_committed", "log_directory": "/tmp/stock-bot-wave33.c3IAY2", "integration_base": "397cd0e1603b7ccd01bf80c9ff3930ba2a1b9963", "scope": "R07 functional comparison; table measurement explicitly not run, so full original R07 checklist remains partial.", @@ -7357,7 +7387,123 @@ "No performance/profiling/benchmarks. Full R07 retains paused table measurement; its accepted functional component may satisfy R09 after commit.", "R05 provider/default cutover and candidate/AI/multiasset/paper/live gates remain unchanged." ], - "commits": "Wave32 committed397cd0e. Wave33 remains uncommitted; no push or PR.", - "fixture_cleanup": "Both exact disposable PostgreSQL37f4d89... and Redisf1e69a88... containers stopped and removed after final gates. Development services untouched; worktrees and local evidence retained." + "commits": "Committed as 46a4f13acd5fdce08f1b19e465f428471656269f at owner request; no push or PR.", + "fixture_cleanup": "Both exact disposable PostgreSQL37f4d89... and Redisf1e69a88... containers stopped and removed after final gates. Development services untouched; worktrees and local evidence retained.", + "completed_commit": "46a4f13acd5fdce08f1b19e465f428471656269f" + }, + "thirty_fourth_wave": ["R09"], + "thirty_fourth_wave_base": "46a4f13acd5fdce08f1b19e465f428471656269f", + "thirty_fourth_wave_notes": [ + "Existing result/sample/phase/warmup/reset/cost display retained. Add one optional exact source to each immutable artifact revision, existing run/metric references unchanged.", + "Source variants standalone experiment/chrono report/walk-forward report; no copied metric store or new API/entity. Omitted revision source preserves old; explicit null detaches new revision only.", + "Same-client historical full retained-result verification, complete report/member facts, readonly snapshot reads; no current approval/build/cancel gate or operational row locks.", + "SQL27 additive nullable JSONB+source membership guard, existingSQL20/22–26 unchanged. Sources/results retain existing deletion guards.", + "Generic detail exposes optional server standalone boolean, absent fails closed for source action. Existing single-run finding behavior/ambiguous response handling remains.", + "No retained as-of regime annotations exist; explicit unavailable counts/coverage. No classifier, inferred labels, current analytics API or fabricated sample counts.", + "No performance, native financial changes, candidate/AI/default/multiasset/paper/live activation or new-wave commits/push/PR." + ], + "thirty_fourth_wave_validation": { + "state": "validated_uncommitted", + "integration_base": "46a4f13acd5fdce08f1b19e465f428471656269f", + "log_directory": "/tmp/stock-bot-wave34.02YVEd", + "scope": "Supported R09 source-linked findings and explicit unavailable-regime state; positive regime slicing requires future retained annotations.", + "source_archive": "/tmp/stock-bot-wave34.02YVEd/validated-source.tar.gz", + "source_archive_sha256": "7df43baf277dc28d7ee186aee233ad13c134b20e0bd86a7300688acb6e0fd8af", + "source_hashes": { + "apps/stock/config/src/contracts/experiments.ts": "7aeaa124defd8442899ca3271ea9b9b68bc4c63202179cd53c7129f318dee1af", + "apps/stock/config/src/contracts/research.ts": "236c16b3fa14852d04b03cb0b301fdb2009efe92446ba9882b6eb69e62e0b93a", + "apps/stock/web-api/src/migrations/migration-runner.ts": "f7fe806f1db54e64ced73803aaee86802e3c3fd34cb379a7946d9be548e34cad", + "apps/stock/web-api/src/services/experiments.service.ts": "597a3ef594979792fd68bb6f2814be21d1651b0478003e7e06c133f93c2699e7", + "apps/stock/web-api/src/services/research-evidence.ts": "251a0fbe755767ac0e3c6e944478e2721c6b7a8f85de6a3ba9ffa7d177880419", + "apps/stock/web-api/src/services/research-source-evidence.ts": "af4fcc6d521e6c24a89c033ff2590119a677fde1d084fc03a6e6fa620d0aad5f", + "apps/stock/web-api/src/services/research.service.ts": "ff67ae381b44bade01c57b79500e699b1b2c480ca57b33e689f4d050d0f435a4", + "apps/stock/web-app/src/features/experiments/ChronologicalValidationDetailPage.tsx": "7465d19a4990e98db6b0abd07694a8f9486e32da59559a4adf90f4843a8e9395", + "apps/stock/web-app/src/features/experiments/ExperimentDetailPage.tsx": "0fd4235395968578486f888c7b12ef8f7c2f560cd4dbe509022a556fbff8e386", + "apps/stock/web-app/src/features/experiments/WalkForwardDetailPage.tsx": "0082f0a45f6aedad30edf1d872f41cf82d1a1b1137976cb6004fb76eb5d6b460", + "apps/stock/web-app/src/features/experiments/components/RegimeEvidenceUnavailable.tsx": "cdff056dc3a2a39a61c4cc43d361e16103f68b605bb9a9fc088c11f533a0ef61", + "apps/stock/web-app/src/features/experiments/components/SourceFindingAction.tsx": "06cdb2c3e82f1ea2742629a258ebeb0b061c76de5a40ccb4a235025d3dc39655", + "apps/stock/web-app/src/features/experiments/services/experimentApi.ts": "b864f6150977056eb44d877f4660b5240f9416ea8dae8d31ca216a3db818a276", + "apps/stock/web-app/src/features/research/components/FindingSource.tsx": "a563b4197d4874cbbd494c73fc24519de3b60b626b74a14cc7fbb5158aa197b0", + "apps/stock/web-app/src/features/research/components/ResearchEntry.tsx": "c6eb7c7d521cec389481ef69751c46f2cb3f33f23e4207873fcadb09060a28ab", + "apps/stock/web-app/src/features/research/components/SaveFindingDialog.tsx": "c8e3b7694b38492dc6cd82de4b71d42c92a99caf8a460b7e450600a373d4b08e", + "apps/stock/web-app/src/features/research/components/findingSources.ts": "568a51427c0e7194d632122fd01add02e41c43ed7dec941421230b029e7a38c1", + "apps/stock/web-app/src/features/research/services/researchApi.ts": "addcbd429d4f0166a32e12e923b24b83ee7ba3fe4ad430706fd2cc1c07d7ca56", + "database/postgres/init/27-research-evidence-sources.sql": "ea14fefc7d8ea7db3c3560d73b2ecc25b98928b78542d52878592359778e013e", + "libs/core/types/src/research.ts": "7b452fda376a62fc04621ab65fe1e43b28db4d54a6e7275d640cb66e2f7f19bf", + "test/e2e/fixture.ts": "af5ff8a097493f9d148c49eae7867d0d368ec392a269840bf180306e0e13b81a", + "test/e2e/workbench.test.ts": "ec63e37eca432725043f3ffdd6c7f92161012960bcc7fea03fb48f277ff92e17", + "test/integration/research-api.test.ts": "899351377ebc18618117978300c89973c10c339dfd8732d3e41059ceca710a40", + "test/integration/research-source-evidence-api.test.ts": "799c4e3feede464efb4a417f25b10f8a012c93dd47725fb0f4aaf13043d0a199", + "test/integration/research-source-evidence.test.ts": "630889c002b757639ddeb27c58318ce53a25a3c655b2b1bc190bad90e95ebaba", + "test/integration/research-source-ui.test.tsx": "64c8a9578adf91346177a4bf9482e0eacbbc843e8246fac60aa9d3f985ffaa35", + "test/postgres/chronological-validation-durable.test.ts": "b6a6854921b95b36eb86b474b24ddd3702187e99397d0e8173f8e43ad2ceeac9", + "test/postgres/migration-runner.test.ts": "386353604af2036dd54a80e85031ab8553a652024e6ce44160f71e3fa8900e59", + "test/postgres/research-source-evidence.test.ts": "d41bbe8b9dbc3a86ae48c395ba5055c40a4c425dde7c0ba9c7fb04cce5713c44", + "test/postgres/research-workspace.test.ts": "94b4ef7d05f4edbc78cca3433b15327c89c1fba30006b3cd0864dde168b1672e" + }, + "commands": [ + { + "command": "CARGO_BUILD_JOBS=2 bun run check", + "log": "integration-check-final.log", + "result": "Passed all repository gates: secret audit/build/types/contracts/lint; 93 tooling, 43 utility, 44 calculation, 1024 integration and 150 Rust tests; zero failures. Four preexisting manual Rust cases remain ignored." + }, + { + "command": "bun run test:postgres", + "log": "integration-postgres-final.log", + "result": "Passed: 235 tests /2099 assertions on final release source against disposable PostgreSQL/Redis, including real pre-SQL24 upgrade compatibility." + }, + { + "command": "bun run test:e2e", + "log": "integration-browser-final.log", + "result": "Passed: 16 Chromium workflows /569 assertions against the same-origin production build and unchanged release engine. Actual cost/chronological/walk-forward citations preserve exact native metrics and historical source identity." + }, + { + "command": "Strict all authored/affected test TypeScript; explicit source/test ESLint; changed-source Prettier", + "logs": [ + "root-tests-types-final.log", + "authored-lint-final.log", + "workspace-fixture-lint.log", + "source-format-final.log", + "compatibility-lint-final.log", + "compatibility-format-final.log" + ], + "result": "Passed, including new tests and modified existing API/workspace/migration/browser fixtures." + }, + { + "command": "git diff --check; manifest references/dependency DAG; exact overlay/source SHA256 and historical SQL verification", + "result": "Passed: 55 unique task references, acyclic implementation DAG, 20 exact accepted agent files and all 30 integrated source hashes. SQL20/22–26 byte-for-byte unchanged." + } + ], + "review": { + "independent_reviewer": "/root/r04_review", + "backend": "Accepted eight-file overlay: focused6 tests/39 assertions, native PostgreSQL7/84; full source facts, retained financial/analytics corruption, recomputed report forgery, readonly concurrent snapshot, active lease migration preservation and immediate-constraint guard bypass regression.", + "backend_archive": "/tmp/stock-bot-wave34.02YVEd/backend-final.tar", + "backend_archive_sha256": "570048079836cbad776963774dfe76b5ccd6cd0067fce8fa5fae9a12f8f28033", + "frontend": "Accepted12-file overlay: independent sourceUI30/140 and author combined401/1682. Existing single-run form preserved; explicit run/metric selections, historical source/revisions, lazy R03 reads, unknown-response freeze, new-tab inspect and absent-regime labels.", + "frontend_archive": "/tmp/stock-bot-wave34.02YVEd/frontend-final.tar", + "frontend_archive_sha256": "316c1a4371097e1ac507aaf7e5fd227ebc0a14d327a34587713dc7045e8e3c4a", + "root": "Shared DTO/standalone seam, migration registry/current workspace fixtures and actual native browser helper independently reviewed. Focused native cost/walk2/169 proves all3 source kinds, exact native scalar/null values, revision history and source reopening; oldworkspace9/121 and API10/200 compatibility pass.", + "corrections": "Review closed same-transaction SQL constraint timing bypass, public-document metadata shape gap, missing raw metric units and new-tab inspection navigation guard. Existing corrupt-evidence API test now uses a real transaction callback mock and asserts no pool reads; assertions preserved. Final database gate exposed a pre-SQL24 fixture regression from the new role projection; key-presence/JSON-null extraction now fails closed on missing metadata while keeping historical reads working. Actual pre24=false/post24=true upgrade regression passes; full gates rerun. Initial failing PG log retained as integration-postgres-before-role-compatibility.log.", + "task_completion": "Reviewer accepts R09 supported scope after root gates. Positive regime_slice_reconciliation is not run/inapplicable without retained as-of annotations; not falsely enabled by S05." + }, + "engine": { + "debug_sha256": "75e33ffdd1e2738537879e62243a9d8f63665864835a58c46087bb4b78f274ff", + "release_sha256": "ef00eed556f5c32332d36a9a00ef710682e90deb00b54552e4b5c8bfdfbe8103", + "note": "Existing authoritative Rust engine unchanged. Debug built by fullcheck; verified unchanged release restored before final database/browser gates." + }, + "limits": [ + "One exact source per artifact revision, selected existing run/metric references. No copied metric/report store or new findings endpoint; prose remains unvalidated.", + "Standalone parameter/cost experiments can cite completed members without certifying the rest of an incomplete/cancelled study. Chronological sources require sealed report; series cites only published validation/test segments, with training fully verified underneath.", + "Historical citation checks ignore mutable admission/approval/build/archive/cancel gates but verify immutable identity, every sealed member and retained canonical financial results.", + "Regime evidence, sample counts and coverage explicitly unavailable. S05 internal signal/current analytics endpoint is not a retained as-of annotation artifact. Positive regime reconciliation not implemented or claimed tested.", + "Existing finding creation remains non-idempotent; ambiguous writes freeze and require checking saved records, without automatic retry.", + "Performance, R07 table measurement, R05 provider/default cutover and candidate/AI/multiasset/paper/live activation remain paused or separately gated." + ], + "commits": "Wave33 committed46a4f13. Wave34 remains uncommitted; no push or PR.", + "fixture_cleanup": { + "result": "Both exact disposable --rm containers stopped after successful final gates; development services untouched.", + "postgres": "c9d963c8b00dd98b4b4058fa91a9ad19cdf57ca4239853c3d55d8aa3b23e48d1", + "redis": "f5edaed388c92939721f4afe32e18619068587a87b07d12ffadbd38fa2168bd3" + } } } diff --git a/docs/development/backlog/tasks/R07.md b/docs/development/backlog/tasks/R07.md index 84e6d27a..8114b568 100644 --- a/docs/development/backlog/tasks/R07.md +++ b/docs/development/backlog/tasks/R07.md @@ -99,6 +99,6 @@ Functional acceptance and the explicitly paused large-table measurement are trac ### Validated comparison handoff -The functional comparison component is independently accepted and awaiting commit. All 17 integrated source/test/config files match reviewed snapshots. Whole repository gates pass (988 integration /150 Rust), final PostgreSQL 228/2013 assertions and Chromium 16/500; all authored tests pass strict types/lint and changed-source formatting. Exact hashes, commands and review corrections: `manifest.json` → `thirty_third_wave_validation`. Historical compact reads share a repeatable read-only transaction; actual native browser acceptance confirms cost references, changed/archived inputs, saved metrics and exact-run reopening. +The functional comparison component is independently accepted and committed as `46a4f13` at owner request. All 17 integrated source/test/config files match reviewed snapshots. Whole repository gates pass (988 integration /150 Rust), final PostgreSQL 228/2013 assertions and Chromium 16/500; all authored tests pass strict types/lint and changed-source formatting. Exact hashes, commands and review corrections: `manifest.json` → `thirty_third_wave_validation`. Historical compact reads share a repeatable read-only transaction; actual native browser acceptance confirms cost references, changed/archived inputs, saved metrics and exact-run reopening. -The large-table measurement remains explicitly paused/unrun; full R07 therefore stays partial. After functional component commit, R09 may consume the accepted sweep/comparison/retry UI through a recorded component prerequisite. No new economic formulas, ranking, statistical certification or performance work was added. +The large-table measurement remains explicitly paused/unrun; full R07 therefore stays partial. R09 consumes the accepted sweep/comparison/retry UI through the recorded `46a4f13` component prerequisite. No new economic formulas, ranking, statistical certification or performance work was added. diff --git a/docs/development/backlog/tasks/R09.md b/docs/development/backlog/tasks/R09.md index d7d879f3..9c67afe4 100644 --- a/docs/development/backlog/tasks/R09.md +++ b/docs/development/backlog/tasks/R09.md @@ -27,7 +27,7 @@ Write locks: web-experiments. One agent owns this change. Lock names do not over ## Dependencies and blockers -Implementation requires [R07](R07.md), [R08](R08.md) integrated. +Implementation requires the accepted functional component of [R07](R07.md) and [R08](R08.md) integrated. R07's explicitly paused table measurement is not a citation prerequisite; the manifest records its accepted component commit. Architecture decisions: ADR-006. Agents may not independently amend their policies. @@ -63,3 +63,19 @@ 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. + +## Authorized source-citation continuation — 2026-10-24 + +R07 functional comparison is accepted as `46a4f13`; its paused measurement does not gate this task. R03/R08 are committed. Existing phase/reset/warmup/cost/sample displays are retained. Add one optional exact experiment/chronological-report/walk-forward-report source to each immutable artifact revision and preserve existing run/metric evidence. All cited runs must belong to that source; sealed reports are verified against full retained native evidence through the same read-only client. Historical source resolution ignores current admission/archive/cancellation gates. Existing create/revise locks and narrative-unvalidated status remain. + +Use additive SQL27 and existing findings endpoints/form, not a new store or scheduler. An omitted source on revision preserves the prior source; explicit null detaches only the new revision. Generic experiment details expose a server-derived standalone flag so phase pages cannot masquerade as standalone findings. Save actions lazily load research destinations; report viewing remains independent of R03 availability. Preserve ambiguous-create behavior and original single-run findings. + +No persisted as-of regime annotation contract exists: S05's internal volatility flag and current analytics endpoint do not qualify. Show regime counts/coverage unavailable, never zero or inferred classifications. Positive regime reconciliation remains conditional future capability, not a test claimed by this slice. Required gates include exact sources/metrics, forged-report rejection, raw SQL/upgrade preservation, snapshot/pool1/concurrent revisions, archival historical reads, source-preserving edits and actual native browser save/reopen. Performance remains paused. + +## Validated handoff — 2026-10-24 + +Supported scope is independently reviewed and validated on `46a4f13`; status is `review`, new changes uncommitted. Existing OOS/reset/cost displays are retained. All three exact source kinds save through the existing finding API/form, retain canonical contributing run/metric references, survive revision/history and reopen the exact source. SQL27 and historical read verification reject source/metric/report tampering while preserving old findings and archived evidence. Actual native Chromium workflows cover cost, chronological and walk-forward citations without admitting extra runs. + +Validation: full repository check passed 1024 integration /150 Rust, plus 93 tooling /43 utility /44 calculation tests; final PostgreSQL/Redis 235/2099 and Chromium 16/569. Strict test types, source/test lint, formatting, diff/source hash/DAG checks passed. The real SQL24 upgrade regression confirms missing role metadata fails closed before migration and ordinary experiments qualify afterward. Four preexisting Rust cases remain ignored. Both temporary test containers were removed. + +Positive `regime_slice_reconciliation` remains conditional and unrun because no retained as-of annotation contract exists. The unavailable-state UI is tested; S05 alone does not enable classification. No performance work, financial changes or trading/AI activation. Exact hashes, logs, independent review and limits: [wave34 manifest evidence](../manifest.json), [roadmap handoff](../../ROADMAP.md#thirty-fourth-wave-handoff--2026-10-24). diff --git a/libs/core/types/src/research.ts b/libs/core/types/src/research.ts index 19835d07..11b9d246 100644 --- a/libs/core/types/src/research.ts +++ b/libs/core/types/src/research.ts @@ -3,6 +3,24 @@ export type ResearchActor = 'operator' | 'service'; export type ResearchContentOrigin = 'human' | 'ai' | 'unknown'; export type ResearchMetricsVersion = 'canonical-analytics/v1' | 'legacy-display/v1'; +/** Exact retained source of selected measurements; never a validation of the narrative. */ +export type ResearchFindingSource = + | { kind: 'experiment/v1'; experimentId: string; previewHash: string } + | { + kind: 'chronological-report/v1'; + validationId: string; + previewHash: string; + reportId: string; + reportHash: string; + } + | { + kind: 'walk-forward-report/v1'; + walkForwardId: string; + previewHash: string; + reportId: string; + reportHash: string; + }; + export interface ResearchAuthorship { submittedBy: ResearchActor; /** Declared content origin, not authenticated model/agent identity. */ @@ -66,6 +84,8 @@ export interface ResearchArtifactRevision extends ResearchAuthorship { validationState: 'unvalidated'; evidenceState: 'none' | 'referenced'; evidence: ResearchEvidence[]; + /** Absent on older clients/fixtures. New responses use null for unscoped evidence. */ + source?: ResearchFindingSource | null; createdAt: string; } export interface ResearchArtifact { diff --git a/test/e2e/fixture.ts b/test/e2e/fixture.ts index 997325dc..09d02bf6 100644 --- a/test/e2e/fixture.ts +++ b/test/e2e/fixture.ts @@ -298,6 +298,7 @@ export async function fixture(browser: Browser, native = false) { '24-chronological-validation.sql', '25-walk-forward.sql', '26-cost-sensitivity.sql', + '27-research-evidence-sources.sql', ]) { await pool.query( readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8') diff --git a/test/e2e/workbench.test.ts b/test/e2e/workbench.test.ts index a8aa6ee7..220e8fa9 100644 --- a/test/e2e/workbench.test.ts +++ b/test/e2e/workbench.test.ts @@ -28,6 +28,7 @@ import type { WalkForwardDetail, WalkForwardPreview, } from '@stock-bot/stock-config/walk-forward'; +import type { ResearchArtifact, ResearchFindingSource } from '@stock-bot/types'; import { retainResearchDataset } from '../../scripts/import-research-dataset'; import { canonicalSettings } from '../fixtures/canonical-research'; import { canonicalSmaFixture } from '../fixtures/canonical-sma'; @@ -55,6 +56,101 @@ afterAll(async () => { }); const fixture = (native = false) => createFixture(browser, native); +/** Uses real retained native measurements, then reopens the exact source from immutable history. */ +async function saveSourceFindingInBrowser( + f: Awaited>, + source: ResearchFindingSource, + choices: { runId: string; metricPath: string }[], + title: string +) { + const sourceUrl = f.page.url(); + await f.page.getByRole('heading', { name: 'Regime evidence unavailable', exact: true }).waitFor(); + const counts = async () => + ( + await f.pool.query(`SELECT + (SELECT count(*)::int FROM runs) AS runs, + (SELECT count(*)::int FROM backtest_dispatch) AS dispatch`) + ).rows[0]; + const before = await counts(); + const { project } = await f.request('/api/v2/research-projects', 'POST', { + title: `${title} project`, + }); + await f.page.getByRole('button', { name: 'Save research finding', exact: true }).click(); + const dialog = f.page.getByRole('dialog', { name: 'Save finding', exact: true }); + await dialog.getByLabel('Finding project', { exact: true }).selectOption(project.id); + await dialog.getByLabel('Finding title', { exact: true }).fill(title); + await dialog + .getByLabel('Finding body', { exact: true }) + .fill( + 'Selected retained measurements support further investigation; this narrative is not validated alpha.' + ); + expect(await dialog.getByRole('button', { name: 'Save finding', exact: true }).isDisabled()).toBe( + true + ); + for (const choice of choices) { + await dialog + .locator(`input[data-run-id="${choice.runId}"][data-metric-path="${choice.metricPath}"]`) + .check(); + } + const creating = f.page.waitForResponse( + response => + response.request().method() === 'POST' && + response.url().endsWith(`/research-projects/${project.id}/analysis-artifacts`) + ); + await dialog.getByRole('button', { name: 'Save finding', exact: true }).click(); + const response = await creating; + expect(response.status()).toBe(201); + expect(response.request().postDataJSON().source).toEqual(source); + const { artifact } = (await response.json()) as { artifact: ResearchArtifact }; + expect(artifact.latestRevision.source).toEqual(source); + expect(artifact.latestRevision.validationState).toBe('unvalidated'); + expect(artifact.latestRevision.evidence).toHaveLength(choices.length); + for (const choice of choices) { + const item = artifact.latestRevision.evidence.find( + evidence => evidence.runId === choice.runId && evidence.metricPath === choice.metricPath + )!; + const result = (await f.request(`/api/v2/runs/${choice.runId}/results`)) as CanonicalRunResult; + const key = choice.metricPath.slice( + 'analytics.metrics.'.length + ) as keyof typeof result.analytics.metrics; + expect(item.value).toBe(result.analytics.metrics[key]); + expect(item.unavailableReason).toBe( + item.value === null ? (result.analytics.unavailable[key] ?? 'not-reported') : null + ); + expect(item.financialEngine).toBe('rust'); + expect(item.datasetHash).toBe(result.request.datasetHash); + } + await dialog.getByRole('link', { name: 'Open saved finding', exact: true }).click(); + const findingUrl = `${f.origin}/research/${project.id}?artifact=${artifact.id}`; + await f.page.waitForURL(findingUrl); + const sourceLink = f.page.getByRole('link', { name: 'Open cited source', exact: true }); + await sourceLink.waitFor(); + expect(await sourceLink.getAttribute('href')).toBe(new URL(sourceUrl).pathname); + await f.page.getByRole('button', { name: 'Edit latest revision', exact: true }).click(); + await f.page.getByLabel('Revision title', { exact: true }).fill(`${title} revised`); + const revising = f.page.waitForResponse( + reply => + reply.request().method() === 'POST' && + reply.url().endsWith(`/analysis-artifacts/${artifact.id}/revisions`) + ); + await f.page.getByRole('button', { name: 'Save new revision', exact: true }).click(); + const revised = await revising; + expect(revised.status()).toBe(201); + expect(revised.request().postDataJSON().source).toEqual(source); + const updated = (await revised.json()) as { artifact: ResearchArtifact }; + expect(updated.artifact.latestRevision.ordinal).toBe(2); + expect(updated.artifact.latestRevision.source).toEqual(source); + expect(updated.artifact.latestRevision.evidence).toEqual(artifact.latestRevision.evidence); + await f.page.getByRole('button', { name: 'View revision 1', exact: true }).click(); + await visible(f.page, 'Immutable history: this revision is read-only.'); + await f.page.reload(); + await visible(f.page, 'Immutable history: this revision is read-only.'); + await sourceLink.click(); + await f.page.waitForURL(sourceUrl); + await f.page.getByRole('button', { name: 'Save research finding', exact: true }).waitFor(); + expect(await counts()).toEqual(before); +} + test('saved_experiment_comparison_preserves_cost_reference_native_summaries_and_archived_history_browser', async () => { const f = await fixture(true); f.page.on('dialog', dialog => void dialog.accept()); @@ -377,6 +473,19 @@ test('cost_sensitivity_freezes_policy_runs_native_scenarios_and_reopens_existing expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(3); await f.page.reload(); await visible(f.page, /completed: 3/); + await saveSourceFindingInBrowser( + f, + { + kind: 'experiment/v1', + experimentId: experiment.id, + previewHash: preview.previewHash, + }, + [ + { runId: experiment.trials[0]!.runId!, metricPath: 'analytics.metrics.totalReturn' }, + { runId: experiment.trials[2]!.runId!, metricPath: 'analytics.metrics.sharpeRatio' }, + ], + 'Retained cost comparison finding' + ); await f.page.getByRole('link', { name: 'All experiments', exact: true }).click(); await f.page.getByRole('link', { name: 'Fixed fee and slippage study', exact: true }).click(); await visible(f.page, /completed: 3/); @@ -602,6 +711,45 @@ test('walk_forward_freezes_all_windows_runs_native_members_and_reopens_reset_rep await visible(f.page, 'Saved walk-forward validations'); await f.page.locator(`a[href="/experiments/walk-forward/${initial.id}"]`).click(); await visible(f.page, 'Execution complete · walk-forward report saved'); + await saveSourceFindingInBrowser( + f, + { + kind: 'walk-forward-report/v1', + walkForwardId: initial.id, + previewHash: report.previewHash, + reportId: report.id, + reportHash: report.reportHash, + }, + [ + { + runId: report.segments[0]!.validation.runId, + metricPath: 'analytics.metrics.totalReturn', + }, + { runId: report.segments[1]!.test.runId, metricPath: 'analytics.metrics.maxDrawdown' }, + { runId: report.segments[1]!.test.runId, metricPath: 'analytics.metrics.sharpeRatio' }, + ], + 'Retained walk-forward finding' + ); + await f.page.getByRole('link', { name: 'Open window 1 validation', exact: true }).click(); + const child = childReports[0]!; + await visible(f.page, 'Execution complete · report saved'); + await saveSourceFindingInBrowser( + f, + { + kind: 'chronological-report/v1', + validationId: child.validationId, + previewHash: child.previewHash, + reportId: child.id, + reportHash: child.reportHash, + }, + [ + { runId: child.training[0]!.runId, metricPath: 'analytics.metrics.totalReturn' }, + { runId: child.test.runId, metricPath: 'analytics.metrics.sharpeRatio' }, + ], + 'Retained chronological finding' + ); + expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(8); + expect((await f.pool.query('SELECT * FROM analysis_artifacts')).rowCount).toBe(2); expect(f.historicalDataReads).toEqual([]); expect(f.unexpectedNetwork).toEqual([]); } finally { diff --git a/test/integration/research-api.test.ts b/test/integration/research-api.test.ts index 884fcc03..587d2224 100644 --- a/test/integration/research-api.test.ts +++ b/test/integration/research-api.test.ts @@ -17,12 +17,17 @@ function fixture( security: 'enabled' | 'disabled' | 'absent' = 'enabled', query: Query = async () => { throw new Error('Rejected request reached storage'); - } + }, + allowReadTransaction = false ) { + const transactionQuery = mock(query); const database = { query: mock(query), - transaction: mock(async () => { - throw new Error('Rejected request reached transaction'); + transaction: mock(async (callback: (client: { query: Query }) => Promise) => { + if (!allowReadTransaction) { + throw new Error('Rejected request reached transaction'); + } + return callback({ query: transactionQuery }); }), }; const logger = { error: mock((_message: string, _details?: unknown) => {}) }; @@ -44,6 +49,7 @@ function fixture( app.post('/api/v2/unrelated', c => c.json({ ok: true })); return { database, + transactionQuery, logger, app, request( @@ -349,79 +355,94 @@ describe('research HTTP credential and transport boundary', () => { 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 f = fixture( + 'enabled', + async sql => { + if (sql === 'SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY') { + return { rows: [] }; + } + 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}`); + }, + true + ); 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.database.query.mock.calls).toHaveLength(0); + expect(f.database.transaction.mock.calls).toHaveLength(1); + expect(f.transactionQuery.mock.calls).toHaveLength(6); + expect(f.transactionQuery.mock.calls[0]?.[0]).toBe( + 'SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY' + ); 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); diff --git a/test/integration/research-source-evidence-api.test.ts b/test/integration/research-source-evidence-api.test.ts new file mode 100644 index 00000000..a1b1e82c --- /dev/null +++ b/test/integration/research-source-evidence-api.test.ts @@ -0,0 +1,149 @@ +import { randomUUID } from 'node:crypto'; +import { describe, expect, mock, test } from 'bun:test'; +import { Hono } from 'hono'; +import { createHttpSecurity } from '@stock-bot/di'; +import type { IServiceContainer } from '@stock-bot/services'; +import { createResearchRoutes } from '../../apps/stock/web-api/src/routes/research.routes'; + +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 (work: (client: { query: Query }) => Promise) => work({ query })), + }; + 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(), + runId = randomUUID(); +const source = { kind: 'experiment/v1', experimentId: randomUUID(), previewHash: 'a'.repeat(64) }; +const body = { + kind: 'finding', + title: 'Evidence', + body: 'Claim', + source, + evidence: [ + { + runId, + metricsVersion: 'canonical-analytics/v1', + metricPath: 'analytics.metrics.totalReturn', + }, + ], +}; +describe('source findings HTTP boundary', () => { + test('malformed source metadata rejects before storage and write credentials remain mandatory', async () => { + for (const change of [ + { ...source, extra: true }, + { ...source, previewHash: null }, + { ...source, experimentId: 'bad' }, + { ...source, kind: 'chronological-report/v1' }, + ]) { + const f = fixture(); + expect( + ( + await f.request( + `research-projects/${projectId}/analysis-artifacts`, + { ...body, source: change }, + 'operator' + ) + ).status + ).toBe(400); + expect(f.database.transaction.mock.calls).toHaveLength(0); + } + const f = fixture(); + expect( + (await f.request(`research-projects/${projectId}/analysis-artifacts`, body)).status + ).toBe(401); + expect( + (await f.request(`research-projects/${projectId}/analysis-artifacts`, body, 'read')).status + ).toBe(403); + expect(f.database.transaction.mock.calls).toHaveLength(0); + }); + test('missing source is422 without exposing storage details; unexpected errors remain sanitized500', async () => { + for (const broken of [false, true]) { + const f = fixture('enabled', async sql => { + if (sql.includes('FROM research_projects')) { + return { rows: [{ id: projectId, archived_at: null }] }; + } + if (sql.startsWith('INSERT INTO analysis_artifacts(')) { + return { rows: [{ id: randomUUID() }] }; + } + if (broken) { + throw new Error('private database details'); + } + return { rows: [] }; + }); + const response = await f.request( + `research-projects/${projectId}/analysis-artifacts`, + body, + 'operator' + ); + expect(response.status).toBe(broken ? 500 : 422); + expect(response.headers.get('Cache-Control')).toBe('no-store'); + if (broken) { + expect(await response.json()).toEqual({ error: 'Research workspace unavailable' }); + } + } + }); + test('artifact reads select repeatable read-only mode before storage and do not require mutation credentials', async () => { + const calls: string[] = []; + const f = fixture('enabled', async sql => { + calls.push(sql); + return { rows: [] }; + }); + const response = await f.request(`analysis-artifacts/${randomUUID()}`, undefined, 'read'); + expect(response.status).toBe(404); + expect(calls[0]).toBe('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY'); + expect(calls.every(sql => !sql.includes('FOR UPDATE') && !sql.includes('FOR SHARE'))).toBe( + true + ); + }); +}); diff --git a/test/integration/research-source-evidence.test.ts b/test/integration/research-source-evidence.test.ts new file mode 100644 index 00000000..2994cf1c --- /dev/null +++ b/test/integration/research-source-evidence.test.ts @@ -0,0 +1,104 @@ +import { describe, expect, mock, test } from 'bun:test'; +import { + createResearchArtifactSchema, + parseResearchInput, + researchFindingSourceSchema, + reviseResearchArtifactSchema, +} from '@stock-bot/stock-config/research'; +import type { BacktestResultQuery } from '../../apps/stock/web-api/src/services/backtest-v2.service'; +import { verifyResearchSource } from '../../apps/stock/web-api/src/services/research-source-evidence'; + +const id = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'; +const source = { kind: 'experiment/v1' as const, experimentId: id, previewHash: 'a'.repeat(64) }; +const canonical = { + runId: id, + metricsVersion: 'canonical-analytics/v1' as const, + metricPath: 'analytics.metrics.totalReturn', +}; +describe('finding source contract', () => { + test('strict source identities normalize UUIDs and reject client measurements, mixed kinds and missing hashes', () => { + expect( + researchFindingSourceSchema.parse({ ...source, experimentId: id.toUpperCase() }) + ).toEqual(source); + for (const raw of [ + { ...source, previewHash: 'A'.repeat(64) }, + { ...source, previewHash: null }, + { ...source, experimentId: null }, + { ...source, totalReturn: 0 }, + { ...source, reportId: id }, + { ...source, kind: 'unknown' }, + { + kind: 'chronological-report/v1', + validationId: id, + previewHash: source.previewHash, + reportId: id, + }, + { + kind: 'walk-forward-report/v1', + walkForwardId: id, + previewHash: source.previewHash, + reportId: id, + reportHash: 'bad', + }, + ]) { + expect(researchFindingSourceSchema.safeParse(raw).success).toBe(false); + } + for (const kind of ['chronological-report/v1', 'walk-forward-report/v1'] as const) { + const owner = + kind === 'chronological-report/v1' + ? { validationId: id.toUpperCase() } + : { walkForwardId: id.toUpperCase() }; + const parsed = researchFindingSourceSchema.parse({ + kind, + ...owner, + previewHash: source.previewHash, + reportId: id.toUpperCase(), + reportHash: 'b'.repeat(64), + }); + expect('reportId' in parsed && parsed.reportId).toBe(id); + } + }); + test('old create and revise requests preserve the distinction between omitted and explicitly detached sources', () => { + const body = { title: 'Observation', body: 'Unvalidated narrative', evidence: [canonical] }; + expect( + parseResearchInput(createResearchArtifactSchema, { ...body, kind: 'finding' }).source + ).toBeUndefined(); + expect( + parseResearchInput(reviseResearchArtifactSchema, { ...body, expectedRevision: 1 }).source + ).toBeUndefined(); + expect( + parseResearchInput(reviseResearchArtifactSchema, { + ...body, + expectedRevision: 1, + source: null, + }).source + ).toBeNull(); + expect( + parseResearchInput(createResearchArtifactSchema, { ...body, kind: 'note', source }).source + ).toEqual(source); + }); + test('source cannot substitute for canonical metric evidence; unavailable source fails before any result reader', async () => { + const query = mock(async () => ({ rows: [] })), + read = mock(async () => null); + const database = { query } as unknown as BacktestResultQuery; + for (const evidence of [ + [], + [ + { + runId: id, + metricsVersion: 'legacy-display/v1' as const, + metricPath: 'metrics.totalReturn', + }, + ], + ]) { + await expect(verifyResearchSource(source, evidence, database, read)).rejects.toMatchObject({ + status: 422, + }); + } + expect(query.mock.calls).toHaveLength(0); + await expect(verifyResearchSource(source, [canonical], database, read)).rejects.toMatchObject({ + status: 422, + }); + expect(read.mock.calls).toHaveLength(0); + }); +}); diff --git a/test/integration/research-source-ui.test.tsx b/test/integration/research-source-ui.test.tsx new file mode 100644 index 00000000..731f850b --- /dev/null +++ b/test/integration/research-source-ui.test.tsx @@ -0,0 +1,1321 @@ +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test'; +import { GlobalWindow } from 'happy-dom'; +import { act, createElement, type ReactElement } from 'react'; +import type { Root } from 'react-dom/client'; +import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research'; +import type { + ChronologicalValidationDetail, + ChronologicalValidationPreview, + ValidationResultEvidence, +} from '@stock-bot/stock-config/chronological-validation'; +import { + costSensitivityInputSchema, + type CostSensitivityDetail, + type CostSensitivityPreview, +} from '@stock-bot/stock-config/cost-sensitivity'; +import type { + ExperimentDetail, + ExperimentPreview, + ExperimentTrial, +} from '@stock-bot/stock-config/experiments'; +import { builtinCatalogDescriptors } from '@stock-bot/stock-config/strategy'; +import { + walkForwardPolicy, + type WalkForwardDetail, + type WalkForwardPreview, +} from '@stock-bot/stock-config/walk-forward'; +import type { + ResearchArtifact, + ResearchFindingSource, + ResearchHypothesis, + ResearchProject, +} from '@stock-bot/types'; +import { buildExperimentPreview } from '../../apps/stock/web-api/src/services/experiment-input'; +import { prepareChronologicalValidation } from '../../apps/stock/web-api/src/services/validation-preview'; +import type { FindingDraftSource } from '../../apps/stock/web-app/src/features/research/components/findingSources'; +import type { ArtifactInput } from '../../apps/stock/web-app/src/features/research/services/researchApi'; +import { nativeReplayFixture } from '../fixtures/native-replay'; +import { walkForwardDataset } from '../fixtures/walk-forward'; + +const browser = new GlobalWindow({ url: 'http://localhost:5173' }); +const keys = ['window', 'document', 'Event', 'ResizeObserver', 'IS_REACT_ACT_ENVIRONMENT'] as const; +const originals = new Map(keys.map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)])); +let createRoot: typeof import('react-dom/client').createRoot; +let router: typeof import('react-router-dom'); +let SaveSourceFindingDialog: typeof import('../../apps/stock/web-app/src/features/research/components/SaveFindingDialog').SaveSourceFindingDialog; +let ResearchEntry: typeof import('../../apps/stock/web-app/src/features/research/components/ResearchEntry').ResearchEntry; +let researchApi: typeof import('../../apps/stock/web-app/src/features/research/services/researchApi').researchApi; +let sources: typeof import('../../apps/stock/web-app/src/features/research/components/findingSources'); +let ExperimentDetailPage: typeof import('../../apps/stock/web-app/src/features/experiments/ExperimentDetailPage').ExperimentDetailPage; +let ChronologicalValidationDetailPage: typeof import('../../apps/stock/web-app/src/features/experiments/ChronologicalValidationDetailPage').ChronologicalValidationDetailPage; +let WalkForwardDetailPage: typeof import('../../apps/stock/web-app/src/features/experiments/WalkForwardDetailPage').WalkForwardDetailPage; +let parseExperiment: typeof import('../../apps/stock/web-app/src/features/experiments/services/experimentApi').parseWorkbenchExperimentDetail; +let parseValidation: typeof import('../../apps/stock/web-app/src/features/experiments/services/chronologicalValidationDurableApi').parseValidationDetail; +let parseWalk: typeof import('../../apps/stock/web-app/src/features/experiments/services/walkForwardApi').parseWalkForwardDetail; +let root: Root | undefined; +let host: HTMLDivElement; +let navigate: ReturnType; +let closed: number; +function deferred() { + let resolve!: (value: T) => void; + let reject!: (reason: Error) => void; + const promise = new Promise((yes, no) => { + resolve = yes; + reject = no; + }); + return { promise, resolve, reject }; +} +type Pending = ReturnType> & { + path: string; + method: string; + body: unknown; + settled: boolean; + signal?: AbortSignal | null; +}; +const requests: Pending[] = []; +function request(path: string, method = 'GET') { + const value = requests.find( + item => !item.settled && item.path === path && item.method === method + ); + if (!value) { + throw new Error( + `Missing ${method} ${path}; requests ${requests.map(item => `${item.method} ${item.path} ${item.settled}`).join(',')}` + ); + } + return value; +} +function reply(item: Pending, body: unknown, status = 200) { + item.settled = true; + item.resolve(Response.json(body, { status })); +} +async function flush(action: () => void = () => {}) { + await act(async () => { + action(); + await Promise.resolve(); + }); +} +function button(label: string) { + const item = [...host.querySelectorAll('button')].find( + item => item.textContent?.trim() === label + ); + if (!item) { + throw new Error(`Missing ${label}: ${host.textContent}`); + } + return item; +} +function field(label: string) { + const item = host.querySelector(`[aria-label="${label}"]`) as + | HTMLInputElement + | HTMLSelectElement + | HTMLTextAreaElement + | null; + if (!item) { + throw new Error(`Missing field ${label}`); + } + return item; +} +function edit(label: string, value: string) { + const input = field(label); + const prototype = + input.tagName === 'SELECT' + ? browser.HTMLSelectElement.prototype + : input.tagName === 'TEXTAREA' + ? browser.HTMLTextAreaElement.prototype + : browser.HTMLInputElement.prototype; + Object.getOwnPropertyDescriptor(prototype, 'value')!.set!.call(input, value); + input.dispatchEvent( + new browser.Event(input.tagName === 'SELECT' ? 'change' : 'input', { + bubbles: true, + }) as unknown as Event + ); +} +function Probe() { + navigate = router.useNavigate(); + return null; +} +const project = (id = 'p1', archived = false): ResearchProject => ({ + id, + archived, + title: `Project ${id}`, + description: '', + revision: 1, + ownerPrincipal: 'operator', + updatedBy: 'operator', + createdAt: '2026-10-23', + updatedAt: '2026-10-23', +}); +const hypothesis = (id = 'h1', projectId = 'p1', archived = false): ResearchHypothesis => ({ + id, + projectId, + archived, + ownerPrincipal: 'operator', + updatedBy: 'operator', + createdAt: '2026-10-23', + updatedAt: '2026-10-23', + latestRevision: { + id: `${id}-revision`, + hypothesisId: id, + ordinal: 2, + title: `Hypothesis ${id}`, + proposition: 'Candidate', + validationCriteria: '', + validationState: 'unvalidated', + contentOrigin: 'human', + submittedBy: 'operator', + createdAt: '2026-10-23', + }, +}); +const artifact = (hypothesisRevisionId: string | null = null): ResearchArtifact => ({ + id: 'saved-finding', + projectId: 'p1', + hypothesisRevisionId, + kind: 'finding', + archived: false, + ownerPrincipal: 'operator', + updatedBy: 'operator', + createdAt: '2026-10-23', + updatedAt: '2026-10-23', + latestRevision: { + id: 'a-revision', + artifactId: 'saved-finding', + ordinal: 1, + title: 'Finding', + body: 'Narrative', + validationState: 'unvalidated', + evidenceState: 'referenced', + evidence: [], + submittedBy: 'operator', + contentOrigin: 'human', + createdAt: '2026-10-23', + }, +}); +async function render(element: ReactElement, initial = '/') { + if (!root) { + root = createRoot(host); + } + await flush(() => + root!.render( + createElement( + router.MemoryRouter, + { initialEntries: [initial] }, + element, + createElement(Probe) + ) + ) + ); +} +async function destination(id = 'p1', items = [hypothesis()]) { + await flush(() => edit('Finding project', id)); + await flush(() => { + reply(request(`/api/v2/research-projects/${id}`), { project: project(id) }); + reply(request(`/api/v2/research-projects/${id}/hypotheses?includeArchived=false`), { + hypotheses: items, + }); + }); +} +async function draft() { + await destination(); + await flush(() => { + edit('Finding title', 'Exact finding'); + edit('Finding body', 'Keep this narrative'); + }); +} +async function preflight() { + await flush(() => button('Save finding').click()); + await flush(() => reply(request('/api/v2/research-projects/p1'), { project: project() })); +} +const post = () => request('/api/v2/research-projects/p1/analysis-artifacts', 'POST'); +beforeAll(async () => { + for (const [key, value] of Object.entries({ + window: browser, + document: browser.document, + Event: browser.Event, + ResizeObserver: browser.ResizeObserver, + IS_REACT_ACT_ENVIRONMENT: true, + })) { + Object.defineProperty(globalThis, key, { configurable: true, writable: true, value }); + } + ({ parseWorkbenchExperimentDetail: parseExperiment } = await import( + '../../apps/stock/web-app/src/features/experiments/services/experimentApi' + )); + ({ parseValidationDetail: parseValidation } = await import( + '../../apps/stock/web-app/src/features/experiments/services/chronologicalValidationDurableApi' + )); + ({ parseWalkForwardDetail: parseWalk } = await import( + '../../apps/stock/web-app/src/features/experiments/services/walkForwardApi' + )); + ({ createRoot } = await import('react-dom/client')); + router = await import('react-router-dom'); + ({ SaveSourceFindingDialog } = await import( + '../../apps/stock/web-app/src/features/research/components/SaveFindingDialog' + )); + ({ ResearchEntry } = await import( + '../../apps/stock/web-app/src/features/research/components/ResearchEntry' + )); + ({ researchApi } = await import( + '../../apps/stock/web-app/src/features/research/services/researchApi' + )); + sources = await import( + '../../apps/stock/web-app/src/features/research/components/findingSources' + ); + ({ ExperimentDetailPage } = await import( + '../../apps/stock/web-app/src/features/experiments/ExperimentDetailPage' + )); + ({ ChronologicalValidationDetailPage } = await import( + '../../apps/stock/web-app/src/features/experiments/ChronologicalValidationDetailPage' + )); + ({ WalkForwardDetailPage } = await import( + '../../apps/stock/web-app/src/features/experiments/WalkForwardDetailPage' + )); +}); +beforeEach(() => { + requests.length = 0; + closed = 0; + host = browser.document.createElement('div') as unknown as HTMLDivElement; + browser.document.body.append(host as never); + Object.defineProperty(browser, 'confirm', { + configurable: true, + writable: true, + value: () => true, + }); + browser.fetch = ((input: RequestInfo | URL, init?: RequestInit) => { + const url = new URL(String(input)); + const item: Pending = { + ...deferred(), + path: url.pathname + url.search, + method: init?.method ?? 'GET', + body: typeof init?.body === 'string' ? JSON.parse(init.body) : undefined, + signal: init?.signal, + settled: false, + }; + requests.push(item); + return item.promise; // Deliberately ignore abort: identity fences must handle late replies. + }) as unknown as typeof browser.fetch; +}); +afterEach(async () => { + if (root) { + await flush(() => root!.unmount()); + } + root = undefined; + host.remove(); +}); +afterAll(async () => { + await browser.happyDOM.close(); + for (const key of keys) { + const descriptor = originals.get(key); + if (descriptor) { + Object.defineProperty(globalThis, key, descriptor); + } else { + Reflect.deleteProperty(globalThis, key); + } + } +}); + +const backtestId = '11111111-1111-4111-8111-111111111111'; +const versionId = '55555555-5555-4555-8555-555555555555'; +const seriesId = 'eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee'; +function sourcePreview(count = 2, parent = backtestId): ExperimentPreview { + const owner = `strategy:${versionId}`; + const { config } = nativeReplayFixture(72, 1, [owner]); + const { dataset } = walkForwardDataset(); + const previewId = '00000000-0000-4000-8000-000000000001'; + config.matching.risk.ledger.sessionId = previewId; + config.matching.risk.ledger.accountId = `research:${previewId}`; + const builtin = builtinCatalogDescriptors[0]!; + const candidates = Array.from({ length: count }, (_, index) => ({ + index, + trialKey: String(index + 1).padStart(64, '0'), + parameters: { fastPeriod: index + 2, slowPeriod: 4 }, + })); + const source: ExperimentPreview = { + version: 'research-experiment-preview/v1', + previewHash: 'e'.repeat(64), + input: { + backtestId: parent, + name: 'Trend study', + grid: { fastPeriod: candidates.map(item => item.parameters.fastPeriod) }, + }, + dataset: dataset.manifest, + candidates, + request: canonicalRunRequestSchema.parse({ + kind: 'canonical-research/v1', + runId: previewId, + backtestId: parent, + name: 'Frozen template name', + strategy: { + familyId: '66666666-6666-4666-8666-666666666666', + versionId, + origin: 'builtin', + reviewId: '88888888-8888-4888-8888-888888888888', + package: { + version: 1, + program: builtin.program, + parameterSchema: builtin.parameterSchema, + artifact: { + format: 'esm-bundle/v1', + entryExport: builtin.entryExport, + content: 'Never execute fixture code', + sha256: 'a'.repeat(64), + }, + dependencyLock: { + format: 'bun-lock/v1', + content: 'Retained lock', + sha256: 'b'.repeat(64), + }, + source: { revision: 'c'.repeat(40), dirty: false }, + build: { tool: 'bun', version: '1.2.17', target: 'browser' }, + }, + selection: { + strategyId: builtin.program.strategyId, + strategyVersion: builtin.program.strategyVersion, + ownerId: owner, + seed: 17, + instrumentId: 'X0.US', + seriesId: 'X0.US:1m', + ownerBudget: '100', + parameters: { fastPeriod: 2, slowPeriod: 4 }, + }, + }, + datasetHash: dataset.manifest.hash, + policy: config, + analyticsPolicy: { version: 1, periodsPerYear: 252, annualRiskFreeRate: 0, benchmark: null }, + build: { + version: 1, + workerSha256: 'a'.repeat(64), + engineWrapperSha256: 'b'.repeat(64), + engineBinarySha256: 'c'.repeat(64), + dependencyLockSha256: 'd'.repeat(64), + runtime: 'bun', + runtimeVersion: '1.2.17', + platform: 'linux', + arch: 'x64', + }, + modelArtifacts: [], + }), + }; + return buildExperimentPreview(source.input, source.request, source.dataset); +} + +function metrics(): NonNullable { + return { + totalReturn: 0, + cagr: null, + maxDrawdown: 0, + exposureTime: 0, + volatility: null, + downsideDeviation: null, + sharpeRatio: null, + sortinoRatio: null, + var95: null, + cvar95: null, + var99: null, + alpha: null, + beta: null, + informationRatio: null, + roundTripCount: null, + winRate: null, + profitFactor: null, + avgWin: null, + avgLoss: null, + }; +} + +function prepared(): WalkForwardPreview { + const source = sourcePreview(), + fixture = walkForwardDataset(); + const input = { ...source.input, windows: fixture.windows }; + return { + version: 'walk-forward-preview/v1', + execution: 'preview-only', + previewHash: 'f'.repeat(64), + input, + source, + policy: walkForwardPolicy, + windows: input.windows.map((recipe, index) => { + const windowSource = buildExperimentPreview( + { ...source.input, name: `${input.name} · window ${index + 1}` }, + source.request, + source.dataset + ); + return { + index, + preview: prepareChronologicalValidation( + { ...windowSource.input, recipe }, + windowSource, + fixture.dataset + ).preview, + }; + }), + counts: { windows: 2, trainingRuns: 4, holdoutRuns: 4, totalRuns: 8, maxRuns: 100 }, + }; +} +const id = (number: number) => `99999999-9999-4999-8999-${String(number).padStart(12, '0')}`; +function memberDocument( + preview: ChronologicalValidationPreview, + index: number, + sealed: boolean +): ChronologicalValidationDetail { + const base = 100 * (index + 1), + winner = preview.source.candidates[1]!; + const phaseIds = { train: id(base), validation: id(base + 1), test: id(base + 2) }; + const experiments = preview.partitions.map((part, phaseIndex): ExperimentDetail => { + const candidates = phaseIndex === 0 ? preview.source.candidates : [{ ...winner, index: 0 }], + request = structuredClone(part.request); + if (phaseIndex !== 0) { + request.strategy.selection.parameters = winner.parameters as never; + } + const input = { + ...preview.source.input, + name: `${preview.input.name} · ${part.phase}`, + grid: phaseIndex === 0 ? preview.input.grid : {}, + }; + const childPreview: ExperimentPreview = { + version: 'research-experiment-preview/v1', + previewHash: String(phaseIndex + 1).repeat(64), + input, + request, + dataset: part.dataset, + candidates, + }; + const trials: ExperimentTrial[] = candidates.map((candidate, trialIndex) => ({ + ...candidate, + runId: id(base + 10 + phaseIndex * 10 + trialIndex), + attemptNumber: sealed ? 1 : 0, + retryCount: 0, + status: sealed ? 'completed' : 'pending', + progress: sealed ? 100 : 0, + cancelRequested: false, + error: null, + comparable: sealed, + diagnostic: null, + metrics: sealed + ? { ...metrics(), totalReturn: phaseIndex === 0 && trialIndex === 0 ? -0.1 : 0 } + : null, + unavailable: sealed ? { sharpeRatio: 'insufficient-periods' } : null, + limitations: ['Reviewed fixture limitation.'], + })); + return { + id: phaseIds[part.phase], + name: input.name, + backtestId, + createdAt: '2026-10-24T10:00:00Z', + cancelRequested: false, + trialCount: trials.length, + counts: { + pending: sealed ? 0 : trials.length, + running: 0, + paused: 0, + completed: sealed ? trials.length : 0, + failed: 0, + cancelled: 0, + }, + datasetHash: part.dataset.hash, + strategyVersionId: versionId, + previewHash: childPreview.previewHash, + preview: childPreview, + trials, + }; + }); + const evidence = (phaseIndex: number, trialIndex: number): ValidationResultEvidence => { + const experiment = experiments[phaseIndex]!, + trial = experiment.trials[trialIndex]!; + return { + phase: preview.partitions[phaseIndex]!.phase, + experimentId: experiment.id, + runId: trial.runId!, + sourceCandidateIndex: phaseIndex === 0 ? trialIndex : 1, + trialKey: trial.trialKey, + parameters: trial.parameters, + datasetHash: experiment.datasetHash, + requestHash: 'b'.repeat(64), + economicHash: 'c'.repeat(64), + metrics: trial.metrics!, + unavailable: trial.unavailable!, + completePeriodCount: 1, + periodicSampleCount: 1, + fillCount: 0, + limitations: trial.limitations, + }; + }; + const selection = sealed + ? { + version: 'chronological-validation-selection/v1' as const, + id: id(base + 3), + validationId: phaseIds.train, + previewHash: preview.previewHash, + selectionHash: 'd'.repeat(64), + createdAt: '2026-10-24T11:00:00Z', + principal: 'operator' as const, + reviewId: preview.source.request.strategy.reviewId, + winner, + training: experiments[0]!.trials.map((_, i) => evidence(0, i)), + holdoutExperimentIds: { validation: phaseIds.validation, test: phaseIds.test }, + } + : null; + return { + id: phaseIds.train, + name: preview.input.name, + backtestId, + createdAt: experiments[0]!.createdAt, + cancelRequested: false, + previewHash: preview.previewHash, + trainingCandidateCount: 2, + stage: sealed ? 'reported' : 'training', + preview, + phases: preview.partitions.map((part, i) => ({ + phase: part.phase, + status: i === 0 || sealed ? 'admitted' : 'not-admitted', + experimentId: i === 0 || sealed ? experiments[i]!.id : null, + experiment: i === 0 || sealed ? experiments[i]! : null, + })) as ChronologicalValidationDetail['phases'], + selection, + report: sealed + ? { + version: 'chronological-validation-report/v1', + id: id(base + 4), + validationId: phaseIds.train, + previewHash: preview.previewHash, + selectionHash: selection!.selectionHash, + reportHash: 'e'.repeat(64), + createdAt: '2026-10-24T12:00:00Z', + principal: 'operator', + reset: 'initial-capital-empty-positions', + training: selection!.training, + validation: evidence(1, 0), + test: evidence(2, 0), + limitations: ['Independent reset accounts.'], + } + : null, + actions: { + select: { + available: false, + reason: sealed ? null : 'Every training candidate must complete.', + }, + finalize: { available: false, reason: sealed ? null : 'Waiting for holdout evidence.' }, + }, + }; +} +function walkDocument(stage: 'training' | 'ready' | 'reported' = 'training'): WalkForwardDetail { + const preview = prepared(), + members = preview.windows.map(item => + memberDocument(item.preview, item.index, stage !== 'training') + ); + return { + id: seriesId, + backtestId, + name: preview.input.name, + previewHash: preview.previewHash, + createdAt: '2026-10-24T10:00:00Z', + cancelRequested: false, + windowCount: 2, + reportedWindowCount: stage === 'training' ? 0 : 2, + trainingRunCount: 4, + plannedRunCount: 8, + stage: stage === 'reported' ? 'reported' : 'windows', + preview, + windows: members.map((validation, index) => ({ + index, + validationId: validation.id, + status: 'admitted', + validation, + })), + report: + stage === 'reported' + ? { + version: 'walk-forward-report/v1', + id: id(999), + walkForwardId: seriesId, + previewHash: preview.previewHash, + reportHash: 'a'.repeat(64), + createdAt: '2026-10-24T13:00:00Z', + principal: 'operator', + reset: 'initial-capital-empty-positions', + segments: members.map((member, index) => ({ + index, + validationId: member.id, + previewHash: member.previewHash, + selectionHash: member.report!.selectionHash, + reportId: member.report!.id, + reportHash: member.report!.reportHash, + validation: member.report!.validation, + test: member.report!.test, + })), + limitations: ['No compounding or averaged metrics.'], + } + : null, + actions: { + finalize: { + available: stage === 'ready', + reason: stage === 'training' ? 'Every window requires a complete immutable report.' : null, + }, + }, + }; +} +function costPreview(): CostSensitivityPreview { + const source = sourcePreview(1); + source.input.grid = {}; + const input = costSensitivityInputSchema.parse({ + backtestId, + name: source.input.name, + scenarios: [{ feeRate: '0.01', slippageRate: '0.02' }], + }); + return { + version: 'cost-sensitivity-preview/v1', + previewHash: 'b'.repeat(64), + input, + source, + request: structuredClone(source.request), + dataset: structuredClone(source.dataset), + candidates: [ + { + feeRate: source.request.policy.matching.risk.feeRate, + slippageRate: source.request.policy.matching.slippageRate, + }, + ...input.scenarios, + ].map((costs, index) => ({ + index, + trialKey: String(index + 11).padStart(64, '0'), + parameters: { ...source.request.strategy.selection.parameters }, + costs, + })), + }; +} +function standalone( + cost = false, + statuses: ExperimentTrial['status'][] = ['completed', 'completed'] +): ExperimentDetail | CostSensitivityDetail { + const base = sourcePreview(Math.min(statuses.length, 2)); + const preview = cost + ? costPreview() + : statuses.length > 2 + ? buildExperimentPreview( + { ...base.input, grid: { slowPeriod: statuses.map((_, index) => index + 20) } }, + base.request, + base.dataset + ) + : base; + const trials = preview.candidates.map((candidate, index) => ({ + ...structuredClone(candidate), + runId: statuses[index] === 'missing' ? null : id(index + 700), + attemptNumber: 0, + retryCount: 0, + status: statuses[index]!, + progress: statuses[index] === 'completed' ? 100 : 0, + cancelRequested: false, + comparable: statuses[index] === 'completed', + error: statuses[index] === 'failed' ? 'Recorded trial failed' : null, + diagnostic: statuses[index] === 'missing' ? 'Expected run missing' : null, + metrics: statuses[index] === 'completed' ? metrics() : null, + unavailable: statuses[index] === 'completed' ? { sharpeRatio: 'insufficient-periods' } : null, + limitations: [], + })); + return { + id: id(777), + backtestId, + kind: cost ? 'cost-sensitivity' : 'parameters', + standalone: true, + name: preview.input.name, + previewHash: preview.previewHash, + datasetHash: preview.request.datasetHash, + strategyVersionId: versionId, + createdAt: '2026-10-24T14:00:00Z', + cancelRequested: false, + trialCount: trials.length, + counts: { + pending: 0, + running: 0, + paused: 0, + completed: 0, + failed: 0, + cancelled: 0, + ...Object.fromEntries( + ['pending', 'running', 'paused', 'completed', 'failed', 'cancelled'].map(status => [ + status, + trials.filter(item => item.status === status).length, + ]) + ), + }, + preview, + trials, + } as ExperimentDetail | CostSensitivityDetail; +} +async function mountSource(source: FindingDraftSource) { + await render( + createElement(SaveSourceFindingDialog, { + source, + onClose: () => { + closed++; + }, + }) + ); + await flush(() => + reply(request('/api/v2/research-projects?includeArchived=false'), { + projects: [project(), project('p2')], + }) + ); +} +function sourceFor(value = standalone()) { + return sources.experimentFindingSource(parseExperiment(value))!; +} +function savedArtifact(body: ArtifactInput): ResearchArtifact { + const value = artifact(); + value.latestRevision.source = body.source ?? null; + value.latestRevision.evidence = (body.evidence ?? []).map(reference => ({ + ...reference, + backtestId, + value: reference.metricPath.endsWith('sharpeRatio') ? null : 0, + unit: 'fraction', + availability: reference.metricPath.endsWith('sharpeRatio') ? 'unavailable' : 'available', + unavailableReason: reference.metricPath.endsWith('sharpeRatio') ? 'insufficient-periods' : null, + resultKind: 'canonical', + financialEngine: 'rust', + datasetHash: 'a'.repeat(64), + limitations: [], + })); + return value; +} +function metric(runId: string, metricPath = 'analytics.metrics.totalReturn') { + const input = host.querySelector( + `input[data-run-id="${runId}"][data-metric-path="${metricPath}"]` + ); + if (!input) { + throw new Error(`Missing ${runId} ${metricPath}`); + } + return input; +} +function link(label: string) { + const item = [...host.querySelectorAll('a')].find(item => item.textContent?.trim() === label); + if (!item) { + throw new Error(`Missing ${label}`); + } + return item; +} +async function showPage( + kind: 'experiment' | 'chrono' | 'walk', + value: + | ExperimentDetail + | CostSensitivityDetail + | ChronologicalValidationDetail + | WalkForwardDetail +) { + const path = + kind === 'experiment' + ? '/experiments' + : kind === 'chrono' + ? '/experiments/validation' + : '/experiments/walk-forward'; + const parameter = + kind === 'experiment' ? 'experimentId' : kind === 'chrono' ? 'validationId' : 'walkForwardId'; + const page = + kind === 'experiment' + ? ExperimentDetailPage + : kind === 'chrono' + ? ChronologicalValidationDetailPage + : WalkForwardDetailPage; + await render( + createElement( + router.Routes, + null, + createElement(router.Route, { path: `${path}/:${parameter}`, element: createElement(page) }) + ), + `${path}/${value.id}` + ); + await flush(() => + reply(request(`/api/v2${path}/${value.id}`), { + [kind === 'experiment' ? 'experiment' : kind === 'chrono' ? 'validation' : 'walkForward']: + value, + }) + ); +} + +describe('source-linked finding selection', () => { + test.each([false, true])( + 'parameter/cost=%s offers exactly three metrics per eligible run and submits references only', + async cost => { + const value = standalone(cost); + const source = sourceFor(value); + await mountSource(source); + await draft(); + expect(host.querySelectorAll('input[type="checkbox"]')).toHaveLength(6); + expect(host.querySelectorAll('input:checked')).toHaveLength(0); + expect(button('Save finding').disabled).toBe(true); + expect(host.textContent).toContain('insufficient-periods'); + expect(host.textContent).toContain('Sharpe Ratio (ratio) · Unavailable'); + expect(host.textContent).toContain('Total Return (fraction) · 0'); + await flush(() => { + metric(id(700)).click(); + metric(id(701), 'analytics.metrics.sharpeRatio').click(); + }); + await preflight(); + const body = post().body as ArtifactInput; + expect(body.source).toEqual(source.context); + expect(body.evidence).toEqual([ + { + runId: id(700), + strategyVersionId: versionId, + metricsVersion: 'canonical-analytics/v1', + metricPath: 'analytics.metrics.totalReturn', + }, + { + runId: id(701), + strategyVersionId: versionId, + metricsVersion: 'canonical-analytics/v1', + metricPath: 'analytics.metrics.sharpeRatio', + }, + ]); + expect(JSON.stringify(body)).not.toContain('value'); + await flush(() => reply(post(), { artifact: savedArtifact(body) }, 201)); + expect(host.textContent).toContain('Finding saved. Its narrative remains unvalidated.'); + expect(link('Open cited source').getAttribute('href')).toBe(`/experiments/${value.id}`); + expect(link('Open saved finding').getAttribute('href')).toContain('?artifact=saved-finding'); + } + ); + test('all original noneligible outcomes remain visible without selectable metrics', async () => { + const value = standalone(false, [ + 'completed', + 'pending', + 'running', + 'paused', + 'failed', + 'cancelled', + 'missing', + 'completed', + ]); + const bad = value.trials[7]!; + bad.comparable = false; + bad.diagnostic = 'Result identity mismatch'; + await mountSource(sourceFor(value)); + expect(host.querySelectorAll('fieldset')).toHaveLength(8); + expect(host.querySelectorAll('input[type="checkbox"]')).toHaveLength(3); + for (const text of [ + 'pending', + 'running', + 'paused', + 'failed', + 'cancelled', + 'missing', + 'incomparable', + 'Recorded trial failed', + 'Result identity mismatch', + ]) { + expect(host.textContent).toContain(text); + } + }); + test('chronological choices include every training candidate followed by validation/test; series only published segments', async () => { + const series = walkDocument('reported'); + const member = series.windows[0]!.validation!; + const chronological = sources.chronologicalFindingSource(parseValidation(member))!; + expect(chronological.runs.map(run => run.label)).toEqual([ + 'train candidate 1', + 'train candidate 2', + 'validation candidate 2', + 'test candidate 2', + ]); + expect(chronological.context).toEqual({ + kind: 'chronological-report/v1', + validationId: member.id, + previewHash: member.previewHash, + reportId: member.report!.id, + reportHash: member.report!.reportHash, + }); + const source = sources.walkForwardFindingSource(parseWalk(series))!; + expect(source.runs.map(run => run.label)).toEqual([ + 'Window 1 validation candidate 2', + 'Window 1 test candidate 2', + 'Window 2 validation candidate 2', + 'Window 2 test candidate 2', + ]); + await mountSource(source); + await draft(); + await flush(() => { + metric(series.report!.segments[0]!.validation.runId).click(); + metric(series.report!.segments[1]!.test.runId, 'analytics.metrics.sharpeRatio').click(); + }); + await preflight(); + const body = post().body as ArtifactInput; + expect(body.source).toEqual(source.context); + expect(body.evidence?.map(item => item.runId)).toEqual([ + series.report!.segments[0]!.validation.runId, + series.report!.segments[1]!.test.runId, + ]); + await flush(() => reply(post(), { artifact: savedArtifact(body) }, 201)); + expect(link('Open cited source').getAttribute('href')).toBe( + `/experiments/walk-forward/${series.id}` + ); + }); + test('same source refresh cannot alter open-time metrics or selectable run set', async () => { + const first = sourceFor(); + await mountSource(first); + await draft(); + await flush(() => metric(id(700)).click()); + const changed = structuredClone(first); + changed.runs[0]!.metrics[0]!.value = 99; + changed.runs[1]!.metrics = []; + await render( + createElement(SaveSourceFindingDialog, { + source: changed, + onClose: () => { + closed++; + }, + }) + ); + expect(host.textContent).not.toContain('Total Return (fraction) · 99'); + expect(host.querySelectorAll('input[type="checkbox"]')).toHaveLength(6); + expect(field('Finding title').value).toBe('Exact finding'); + await preflight(); + expect((post().body as ArtifactInput).evidence?.[0]?.runId).toBe(id(700)); + }); + test('source identity changes reset the form and ignore late accepted results', async () => { + await mountSource(sourceFor()); + await draft(); + await flush(() => metric(id(700)).click()); + await preflight(); + const old = post(); + const changed = sourceFor(); + changed.context = { kind: 'experiment/v1', experimentId: id(888), previewHash: 'c'.repeat(64) }; + changed.key = JSON.stringify(changed.context); + await render( + createElement(SaveSourceFindingDialog, { + source: changed, + onClose: () => { + closed++; + }, + }) + ); + await flush(() => reply(old, { artifact: savedArtifact(old.body as ArtifactInput) }, 201)); + expect(field('Finding title').value).toBe(''); + expect(host.textContent).not.toContain('Finding saved.'); + expect(host.textContent).toContain(id(888)); + }); + test.each(['network', 'malformed', 'foreign-source', 'foreign-evidence'] as const)( + '%s accepted response ambiguity freezes exactly one submission until explicit inspection', + async failure => { + await mountSource(sourceFor()); + await draft(); + await flush(() => metric(id(700)).click()); + await preflight(); + const current = post(); + await flush(() => { + if (failure === 'network') { + current.settled = true; + current.reject(new Error('Lost response')); + return; + } + if (failure === 'malformed') { + reply(current, { artifact: { id: 'bad' } }, 201); + return; + } + const saved = savedArtifact(current.body as ArtifactInput); + if (failure === 'foreign-source') { + saved.latestRevision.source = { + kind: 'experiment/v1', + experimentId: id(888), + previewHash: 'd'.repeat(64), + }; + } else { + saved.latestRevision.evidence[0]!.runId = id(999); + } + reply(current, { artifact: saved }, 201); + }); + expect(host.textContent).toContain('previous request may already'); + expect(button('Save finding').disabled).toBe(true); + expect(field('Finding title').value).toBe('Exact finding'); + expect(link('Check saved records').target).toBe('_blank'); + await flush(() => button('Save finding').click()); + expect(requests.filter(item => item.method === 'POST')).toHaveLength(1); + } + ); + test('new source with no selectable metrics stays disabled and preserves actual statuses', async () => { + await mountSource(sourceFor(standalone(false, ['failed', 'missing']))); + await draft(); + expect(button('Save finding').disabled).toBe(true); + expect(host.querySelectorAll('input[type="checkbox"]')).toHaveLength(0); + }); +}); + +describe('workbench source actions and unavailable regimes', () => { + test.each([false, true])( + 'standalone cost=%s stays readable without research API until action opens', + async cost => { + const value = standalone(cost); + await showPage('experiment', value); + expect(host.textContent).toContain('Regime evidence unavailable'); + expect(host.textContent).toContain('window coverage are unavailable'); + expect(requests).toHaveLength(1); + expect(button('Save research finding').disabled).toBe(false); + await flush(() => button('Save research finding').click()); + expect(request('/api/v2/research-projects?includeArchived=false')).toBeDefined(); + await flush(() => + reply( + request('/api/v2/research-projects?includeArchived=false'), + { error: 'Research API unavailable' }, + 503 + ) + ); + expect(host.textContent).toContain('Research API unavailable'); + expect(button('Retry projects')).toBeDefined(); + expect(requests.some(item => item.path.includes('/analytics/'))).toBe(false); + } + ); + test.each([undefined, false])( + 'absent/phase standalone=%s fails closed despite eligible trials', + async flag => { + const value = standalone(); + value.standalone = flag; + await showPage('experiment', value); + expect(button('Save research finding').disabled).toBe(true); + expect(host.textContent).toContain('explicitly standalone'); + expect(requests).toHaveLength(1); + } + ); + test('page refresh retains an active finding snapshot and owned navigation refuses discard', async () => { + const value = standalone(); + await showPage('experiment', value); + await flush(() => button('Save research finding').click()); + await flush(() => + reply(request('/api/v2/research-projects?includeArchived=false'), { projects: [project()] }) + ); + await draft(); + await flush(() => metric(id(700)).click()); + const changed = structuredClone(value); + changed.trials[0]!.metrics!.totalReturn = 99; + await flush(() => button('Refresh experiment').click()); + await flush(() => reply(request(`/api/v2/experiments/${value.id}`), { experiment: changed })); + const dialog = host.querySelector('[aria-label="Save finding"]')!; + expect(dialog.textContent).not.toContain('Total Return (fraction) · 99'); + expect(field('Finding title').value).toBe('Exact finding'); + let prompts = 0; + Object.defineProperty(browser, 'confirm', { + configurable: true, + value: () => { + prompts++; + return false; + }, + }); + await flush(() => link('All experiments').click()); + expect(prompts).toBe(1); + expect(field('Finding title').value).toBe('Exact finding'); + }); + test.each(['chrono', 'walk'] as const)( + '%s without sealed report displays unavailable action without research reads', + async kind => { + const series = walkDocument('training'); + const value = kind === 'walk' ? series : series.windows[0]!.validation!; + await showPage(kind, value); + expect(button('Save research finding').disabled).toBe(true); + expect(host.textContent).toContain('Save the complete report'); + expect(host.textContent).toContain('Regime evidence unavailable'); + expect(requests).toHaveLength(1); + } + ); + test.each(['chrono', 'walk'] as const)( + '%s sealed report opens original evidence choices with exact source', + async kind => { + const series = walkDocument('reported'); + const value = kind === 'walk' ? series : series.windows[0]!.validation!; + await showPage(kind, value); + expect(button('Save research finding').disabled).toBe(false); + await flush(() => button('Save research finding').click()); + expect(host.querySelectorAll('input[type="checkbox"]')).toHaveLength(12); + expect(host.querySelector('[aria-label="Finding source"]')!.textContent).toContain( + value.report!.reportHash + ); + expect( + requests.some(item => item.method === 'POST' || item.path.includes('/analytics/')) + ).toBe(false); + } + ); +}); + +const noop = () => {}; +async function entry( + value: ResearchArtifact, + revisionId: string | null = null, + revisions = [value.latestRevision] +) { + await render( + createElement(ResearchEntry, { + projectId: 'p1', + id: value.id, + kind: 'artifact', + revisionId, + archived: false, + writeBlocked: '', + hypotheses: [], + onSelectRevision: noop, + onRefresh: noop, + onDirty: noop, + }) + ); + await flush(() => { + reply(request(`/api/v2/analysis-artifacts/${value.id}`), { artifact: value }); + reply(request(`/api/v2/analysis-artifacts/${value.id}/revisions`), { revisions }); + }); +} + +describe('finding navigation and destination safety', () => { + test('ambiguous page finding can inspect saved records in another tab without discarding the draft', async () => { + const value = standalone(); + await showPage('experiment', value); + await flush(() => button('Save research finding').click()); + await flush(() => + reply(request('/api/v2/research-projects?includeArchived=false'), { projects: [project()] }) + ); + await draft(); + await flush(() => metric(id(700)).click()); + await preflight(); + const pending = post(); + await flush(() => { + pending.settled = true; + pending.reject(new Error('Response lost')); + }); + let prompts = 0; + Object.defineProperty(browser, 'confirm', { + configurable: true, + value: () => { + prompts++; + return false; + }, + }); + const event = new browser.MouseEvent('click', { bubbles: true, cancelable: true }); + await flush(() => link('Check saved records').dispatchEvent(event as unknown as Event)); + expect(prompts).toBe(0); + expect(event.defaultPrevented).toBe(false); + expect(field('Finding title').value).toBe('Exact finding'); + expect(metric(id(700)).checked).toBe(true); + expect(button('Save finding').disabled).toBe(true); + expect(requests.filter(item => item.method === 'POST')).toHaveLength(1); + }); + + test('unsaved close refusal preserves source choices and accepted close invokes caller once', async () => { + await mountSource(sourceFor()); + await draft(); + await flush(() => metric(id(700)).click()); + Object.defineProperty(browser, 'confirm', { configurable: true, value: () => false }); + await flush(() => button('Close').click()); + expect(closed).toBe(0); + expect(metric(id(700)).checked).toBe(true); + Object.defineProperty(browser, 'confirm', { configurable: true, value: () => true }); + await flush(() => button('Close').click()); + expect(closed).toBe(1); + }); + test('route replacement drops old source dialog and late accepted mutation cannot show success', async () => { + const value = standalone(); + await showPage('experiment', value); + await flush(() => button('Save research finding').click()); + await flush(() => + reply(request('/api/v2/research-projects?includeArchived=false'), { projects: [project()] }) + ); + await draft(); + await flush(() => metric(id(700)).click()); + await preflight(); + const old = post(); + await flush(() => navigate(`/experiments/${id(888)}`)); + const next = structuredClone(value); + next.id = id(888); + await flush(() => reply(request(`/api/v2/experiments/${id(888)}`), { experiment: next })); + await flush(() => reply(old, { artifact: savedArtifact(old.body as ArtifactInput) }, 201)); + expect(host.querySelector('[aria-label="Save finding"]')).toBeNull(); + expect(host.textContent).not.toContain('Finding saved.'); + }); + test('archived destination preflight sends no POST and retains selected evidence', async () => { + await mountSource(sourceFor()); + await draft(); + await flush(() => metric(id(700)).click()); + await flush(() => { + button('Save finding').click(); + button('Save finding').click(); + }); + await flush(() => + reply(request('/api/v2/research-projects/p1'), { project: project('p1', true) }) + ); + expect(host.textContent).toContain('archived'); + expect(requests.filter(item => item.method === 'POST')).toHaveLength(0); + expect(metric(id(700)).checked).toBe(true); + expect(field('Finding title').value).toBe('Exact finding'); + }); +}); +describe('source-linked historical research revisions', () => { + test('selected historical revision displays its own source and exact report link, not latest', async () => { + const value = artifact(); + value.latestRevision.ordinal = 2; + value.latestRevision.source = { + kind: 'experiment/v1', + experimentId: id(777), + previewHash: 'e'.repeat(64), + }; + const old = { + ...structuredClone(value.latestRevision), + id: 'old-revision', + ordinal: 1, + source: { + kind: 'chronological-report/v1' as const, + validationId: id(100), + previewHash: 'a'.repeat(64), + reportId: id(104), + reportHash: 'b'.repeat(64), + }, + }; + await entry(value, old.id, [old, value.latestRevision]); + expect(link('Open cited source').getAttribute('href')).toBe( + `/experiments/validation/${id(100)}` + ); + expect(host.querySelector('[aria-label="Finding source"]')!.textContent).toContain(id(104)); + expect(host.querySelector('[aria-label="Finding source"]')!.textContent).not.toContain(id(777)); + }); + test('narrative revision forwards source and existing metric references unchanged', async () => { + const body: ArtifactInput = { + kind: 'finding', + title: 'Old', + body: 'Old', + evidence: [ + { + runId: id(700), + strategyVersionId: versionId, + metricsVersion: 'canonical-analytics/v1', + metricPath: 'analytics.metrics.totalReturn', + }, + ], + source: sourceFor().context, + }; + const value = savedArtifact(body); + await entry(value); + await flush(() => button('Edit latest revision').click()); + await flush(() => button('Save new revision').click()); + const pending = request(`/api/v2/analysis-artifacts/${value.id}/revisions`, 'POST'); + expect((pending.body as ArtifactInput).source ?? null).toEqual(body.source ?? null); + expect((pending.body as ArtifactInput).evidence ?? []).toEqual(body.evidence ?? []); + }); + test.each(['extra', 'bad-id', 'bad-hash', 'unknown-kind'] as const)( + 'new source decoder rejects %s on latest and history envelopes', + async problem => { + const source: Record = { + kind: 'experiment/v1', + experimentId: id(777), + previewHash: 'a'.repeat(64), + }; + if (problem === 'extra') { + source.extra = true; + } + if (problem === 'bad-id') { + source.experimentId = 'bad'; + } + if (problem === 'bad-hash') { + source.previewHash = 'bad'; + } + if (problem === 'unknown-kind') { + source.kind = 'unsupported'; + } + const value = artifact(); + value.latestRevision.source = source as ResearchFindingSource; + const load = researchApi.getArtifact(value.id); + reply(request(`/api/v2/analysis-artifacts/${value.id}`), { artifact: value }); + await expect(load).rejects.toThrow('could not be read'); + const history = researchApi.artifactRevisions(value.id); + reply(request(`/api/v2/analysis-artifacts/${value.id}/revisions`), { + revisions: [value.latestRevision], + }); + await expect(history).rejects.toThrow('could not be read'); + } + ); +}); diff --git a/test/postgres/chronological-validation-durable.test.ts b/test/postgres/chronological-validation-durable.test.ts index 09d4606e..4656caa7 100644 --- a/test/postgres/chronological-validation-durable.test.ts +++ b/test/postgres/chronological-validation-durable.test.ts @@ -466,6 +466,8 @@ describe.skipIf(!url)('durable validation adversarial boundaries', () => { { ...ordinaryInput, previewHash: preview.previewHash }, actor() ); + // Missing historical role metadata must remain readable without admitting a source citation. + expect(ordinary.standalone).toBe(false); await f.execute(ordinary.trials[0]!.runId!); const pending = ordinary.trials[1]!.runId!, request = (await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [pending])) @@ -508,6 +510,7 @@ describe.skipIf(!url)('durable validation adversarial boundaries', () => { await f.pool.query(migration); expect(await f.snapshot()).toEqual(first); expect((await f.experiments.list())[0]!.id).toBe(ordinary.id); + expect((await f.experiments.get(ordinary.id)).standalone).toBe(true); // Current chronological admission can link roots to a walk-forward series. await f.pool.query( readFileSync( diff --git a/test/postgres/migration-runner.test.ts b/test/postgres/migration-runner.test.ts index b92729f2..ecd08eed 100644 --- a/test/postgres/migration-runner.test.ts +++ b/test/postgres/migration-runner.test.ts @@ -29,6 +29,7 @@ const migrations = [ '24-chronological-validation.sql', '25-walk-forward.sql', '26-cost-sensitivity.sql', + '27-research-evidence-sources.sql', ]; const cleanup: (() => Promise)[] = []; afterEach(async () => { diff --git a/test/postgres/research-source-evidence.test.ts b/test/postgres/research-source-evidence.test.ts new file mode 100644 index 00000000..3daf3984 --- /dev/null +++ b/test/postgres/research-source-evidence.test.ts @@ -0,0 +1,884 @@ +import { randomUUID } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { afterEach, describe, expect, test } from 'bun:test'; +import { Hono } from 'hono'; +import { Pool, type PoolClient } from 'pg'; +import { createHttpSecurity } from '@stock-bot/di'; +import { getLogger, setLoggerConfig } from '@stock-bot/logger'; +import { PostgreSQLClient } from '@stock-bot/postgres'; +import type { WalkForwardInput } from '@stock-bot/stock-config/walk-forward'; +import type { ResearchEvidenceReference, ResearchFindingSource } 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 { createResearchRoutes } from '../../apps/stock/web-api/src/routes/research.routes'; +import { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service'; +import { ChronologicalValidationService } from '../../apps/stock/web-api/src/services/chronological-validation.service'; +import { experimentHash } from '../../apps/stock/web-api/src/services/experiment-input'; +import { ExperimentsService } from '../../apps/stock/web-api/src/services/experiments.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 { WalkForwardService } from '../../apps/stock/web-api/src/services/walk-forward.service'; +import { retainResearchDataset } from '../../scripts/import-research-dataset'; +import { packageBuiltinStrategies } from '../../scripts/package-builtin-strategies'; +import { canonicalSettings } from '../fixtures/canonical-research'; +import { walkForwardDataset } from '../fixtures/walk-forward'; + +setLoggerConfig({ logLevel: 'fatal', logConsole: false }); +const logger = getLogger('chronological-validation'); +const url = process.env.PIPELINE_TEST_DATABASE_URL; +const cleanup: (() => Promise)[] = []; +let packages: ReturnType | undefined; +afterEach(async () => { + for (const close of cleanup.splice(0).reverse()) { + await close(); + } +}); +async function fixture(poolMax = 1, withSources = true) { + if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) { + throw new Error('Disposable safety database required'); + } + const schema = 'stock_bot_safety_validation_' + randomUUID().replaceAll('-', ''); + const admin = new Pool({ connectionString: url }); + await admin.query(`CREATE SCHEMA ${schema}`); + // A single connection detects accidental nested pool reads while the admission lock is held. + const pool = new Pool({ + connectionString: url, + application_name: schema, + max: poolMax, + 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', + '20-research-workspace.sql', + '21-run-reproduction.sql', + '22-experiments.sql', + '23-experiment-retries.sql', + '24-chronological-validation.sql', + '25-walk-forward.sql', + '26-cost-sensitivity.sql', + ...(withSources ? ['27-research-evidence-sources.sql'] : []), + ]) { + await pool.query( + readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8') + ); + } + 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 }, + api = new BacktestServiceV2(container), + experiments = new ExperimentsService(container), + catalog = new StrategyCatalogService(container); + const version = await catalog.seedBuiltin( + 'Validation SMA', + (await (packages ??= packageBuiltinStrategies()))[0]!, + 'seed' + ); + const data = walkForwardDataset(), + dataset = data.dataset; + await retainResearchDataset(pool, dataset); + const draft = await api.createBacktest( + { + name: 'Validation template', + 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 input: WalkForwardInput = { + backtestId: draft.id, + name: 'Two rolling windows', + grid: { fastPeriod: [1, 2], slowPeriod: [3] }, + windows: data.windows, + }; + const review = async (decision: 'approve' | 'revoke' = 'approve') => { + await catalog.reviewVersion( + version.id, + { decision, reason: 'Disposable validation proof' }, + 'operator' + ); + return (await catalog.getVersionReviews(version.id)).at(-1)!; + }; + const snapshot = async () => { + const tables = ( + await pool.query('SELECT tablename FROM pg_tables WHERE schemaname=$1 ORDER BY tablename', [ + schema, + ]) + ).rows; + const rows: Record = {}; + for (const { tablename } of tables) { + const quoted = '"' + String(tablename).replaceAll('"', '""') + '"'; + rows[String(tablename)] = ( + await pool.query( + `SELECT COALESCE(jsonb_agg(to_jsonb(t) ORDER BY to_jsonb(t)::text),'[]'::jsonb) AS rows FROM ${quoted} t` + ) + ).rows[0].rows; + } + return rows; + }; + const validations = new ChronologicalValidationService(container); + const repository = new PostgresBacktestRunRepository(postgres); + const execute = async (id: string) => { + const engine = new RustBacktestAdapter({ + logger, + storage: { + async getHistoricalBars() { + throw new Error('No provider reads allowed'); + }, + }, + }); + const runner = new BacktestRunner({ engine, engineName: 'native', repository, logger }); + try { + await runner.runQueued(id); + } finally { + await runner.shutdown(); + } + }; + return { + cloneTemplate: async (sourceDataset = dataset) => + api.createBacktest( + { + name: 'Other validation template', + strategy: 'catalog', + strategyVersionId: version.id, + strategyParameters: { fastPeriod: 2, slowPeriod: 3 }, + symbols: ['X0.US'], + startDate: new Date(sourceDataset.manifest.bounds.tradeStart).toISOString(), + endDate: new Date(sourceDataset.manifest.bounds.tradeEnd).toISOString(), + initialCapital: 10000, + config: { + datasetHash: sourceDataset.manifest.hash, + dataFrequency: '1m', + canonical: canonicalSettings, + }, + }, + { autoStart: false } + ), + validations, + walks: new WalkForwardService(container), + repository, + execute, + api, + pool, + postgres, + experiments, + catalog, + version, + draft, + dataset, + input, + research: new ResearchService(container), + container, + schema, + review, + snapshot, + }; +} + +const actor = (key = randomUUID()) => ({ principal: 'operator' as const, key }); +type Fixture = Awaited>; +async function submit(f: Fixture, input = f.input, identity = actor()) { + await f.review(); + const preview = await f.walks.preview(input), + body = { ...input, previewHash: preview.previewHash }; + return { preview, body, identity, walk: await f.walks.submit(body, identity) }; +} +async function finishWindow(f: Fixture, id: string) { + const initial = await f.validations.get(id); + for (const trial of initial.phases[0]!.experiment!.trials) { + await f.execute(trial.runId!); + } + const selected = await f.validations.select(id, { previewHash: initial.previewHash }, actor()); + for (const phase of selected.validation.phases.slice(1)) { + for (const trial of phase.experiment!.trials) { + await f.execute(trial.runId!); + } + } + return f.validations.finalize( + id, + { + previewHash: initial.previewHash, + selectionHash: selected.validation.selection!.selectionHash, + }, + actor() + ); +} + +const reference = ( + runId: string, + metricPath = 'analytics.metrics.totalReturn' +): ResearchEvidenceReference => ({ + runId, + metricsVersion: 'canonical-analytics/v1', + metricPath, +}); +async function save( + f: Fixture, + source: ResearchFindingSource, + evidence: ResearchEvidenceReference[] +) { + const project = await f.research.createProject({ title: 'Evidence workspace' }, 'operator'); + const artifact = await f.research.createArtifact( + project.id, + { + kind: 'finding', + title: 'Selected observations', + body: 'Not a validated claim', + source, + evidence, + }, + 'operator' + ); + return { project, artifact }; +} +async function cost(f: Fixture) { + await f.review(); + const input = { + backtestId: f.draft.id, + name: 'Costs', + scenarios: [ + { feeRate: '0.001', slippageRate: '0.002' }, + { feeRate: '0.003', slippageRate: '0.004' }, + ], + }; + const preview = await f.experiments.previewCosts(input); + const detail = await f.experiments.submitCosts( + { ...input, previewHash: preview.previewHash }, + actor() + ); + return { + detail, + source: { + kind: 'experiment/v1', + experimentId: detail.id, + previewHash: detail.previewHash, + } as const, + }; +} +function rehash>(value: T, field: string): T { + const copy = structuredClone(value), + { _receipt: _private, ...document } = copy; + delete document[field]; + return { ...copy, [field]: experimentHash(document) }; +} +async function mutate(f: Fixture, table: string, id: string, field: string, value: unknown) { + await f.postgres.transaction(async client => { + await client.query(`ALTER TABLE ${table} DISABLE TRIGGER USER`); + await client.query(`UPDATE ${table} SET ${field}=$2 WHERE id=$1`, [id, value]); + await client.query(`ALTER TABLE ${table} ENABLE TRIGGER USER`); + }); +} +async function rawRevision( + f: Fixture, + artifactId: string, + source: unknown, + refs: ResearchEvidenceReference[], + after?: (client: PoolClient, revisionId: string) => Promise +) { + return f.postgres.transaction(async client => { + const revisionId = randomUUID(); + const ordinal = Number( + ( + await client.query( + 'SELECT COALESCE(MAX(ordinal),0)+1 AS n FROM analysis_artifact_revisions WHERE artifact_id=$1', + [artifactId] + ) + ).rows[0].n + ); + await client.query( + "INSERT INTO analysis_artifact_revisions(id,artifact_id,ordinal,title,body,submitted_by,content_origin,source) VALUES($1,$2,$3,'Raw source','Unvalidated','operator','human',$4)", + [revisionId, artifactId, ordinal, source] + ); + for (const [index, ref] of refs.entries()) { + await client.query( + 'INSERT INTO analysis_evidence(revision_id,ordinal,run_id,metrics_version,metric_path) VALUES($1,$2,$3,$4,$5)', + [revisionId, index + 1, ref.runId, ref.metricsVersion, ref.metricPath] + ); + } + if (after) { + await after(client, revisionId); + } + return revisionId; + }); +} +describe.skipIf(!url)('source-linked findings', () => { + test('pool1 cost source saves exact selected facts and nulls; historical read survives cancellation/archive; omitted source persists and explicit null detaches', async () => { + const f = await fixture(), + c = await cost(f); + for (const trial of c.detail.trials.slice(0, 2)) { + await f.execute(trial.runId!); + } + expect((await f.experiments.get(c.detail.id)).standalone).toBe(true); + const evidence = [ + reference(c.detail.trials[0]!.runId!), + reference(c.detail.trials[0]!.runId!, 'analytics.metrics.sharpeRatio'), + reference(c.detail.trials[1]!.runId!), + ]; + const native = await f.api.getRunResults(evidence[0]!.runId); + const { artifact, project } = await save(f, c.source, evidence); + expect(artifact.latestRevision.source).toEqual(c.source); + expect(artifact.latestRevision.validationState).toBe('unvalidated'); + expect(artifact.latestRevision.evidence[0]!.value).toBe( + (native as any).analytics.metrics.totalReturn + ); + expect(artifact.latestRevision.evidence[1]).toMatchObject({ + value: null, + availability: 'unavailable', + }); + await f.experiments.cancel(c.detail.id); + await f.review('revoke'); + await f.pool.query('UPDATE backtests SET archived_at=NOW() WHERE id=$1', [f.draft.id]); + await f.pool.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [ + f.version.strategyId, + ]); + const before = await f.snapshot(); + expect(await f.research.getArtifact(artifact.id)).toEqual(artifact); + expect(await f.research.listArtifacts(project.id)).toEqual([artifact]); + expect(await f.research.listArtifactRevisions(artifact.id)).toEqual([artifact.latestRevision]); + expect(await f.snapshot()).toEqual(before); + const revised = await f.research.reviseArtifact( + artifact.id, + { expectedRevision: 1, title: 'New interpretation', body: 'Still unvalidated', evidence }, + 'operator' + ); + expect(revised.latestRevision.source).toEqual(c.source); + const detached = await f.research.reviseArtifact( + artifact.id, + { + expectedRevision: 2, + title: 'Unscoped', + body: 'Deliberately detached', + evidence, + source: null, + }, + 'operator' + ); + expect(detached.latestRevision.source).toBeNull(); + expect((await f.research.listArtifactRevisions(artifact.id)).map(r => r.source)).toEqual([ + c.source, + c.source, + null, + ]); + }, 60000); + test('native sealed chronological and walk-forward sources retain all proof but only published series segment metrics are selectable', async () => { + const f = await fixture(), + start = await submit(f); + for (const window of start.walk.windows) { + await finishWindow(f, window.validationId); + } + const completed = await f.walks.finalize( + start.walk.id, + { previewHash: start.preview.previewHash }, + actor() + ); + const series = completed.walkForward.report!; + const member = completed.walkForward.windows[0]!.validation!.report!; + const source: ResearchFindingSource = { + kind: 'walk-forward-report/v1', + walkForwardId: start.walk.id, + previewHash: series.previewHash, + reportId: series.id, + reportHash: series.reportHash, + }; + const saved = await save( + f, + source, + series.segments.flatMap(s => [reference(s.validation.runId), reference(s.test.runId)]) + ); + expect(saved.artifact.latestRevision.evidence.map(e => e.value)).toEqual( + series.segments.flatMap(s => [s.validation.metrics.totalReturn, s.test.metrics.totalReturn]) + ); + const chrono: ResearchFindingSource = { + kind: 'chronological-report/v1', + validationId: member.validationId, + previewHash: member.previewHash, + reportId: member.id, + reportHash: member.reportHash, + }; + const original = await save(f, chrono, [ + reference(member.training[0]!.runId), + reference(member.test.runId, 'analytics.metrics.sharpeRatio'), + ]); + expect(original.artifact.latestRevision.evidence[1]!.value).toBeNull(); + expect((await f.experiments.get(member.validationId)).standalone).toBe(false); + await expect(save(f, source, [reference(member.training[0]!.runId)])).rejects.toMatchObject({ + status: 422, + }); + await expect( + save( + f, + { + kind: 'experiment/v1', + experimentId: member.validationId, + previewHash: + completed.walkForward.windows[0]!.validation!.phases[0]!.experiment!.previewHash, + }, + [reference(member.training[0]!.runId)] + ) + ).rejects.toMatchObject({ status: 422 }); + await f.walks.cancel(start.walk.id); + await f.review('revoke'); + await f.pool.query('UPDATE backtests SET archived_at=NOW() WHERE id=$1', [f.draft.id]); + await f.pool.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [ + f.version.strategyId, + ]); + const before = await f.snapshot(); + expect(await f.research.getArtifact(saved.artifact.id)).toEqual(saved.artifact); + expect(await f.research.getArtifact(original.artifact.id)).toEqual(original.artifact); + expect(await f.snapshot()).toEqual(before); + }, 60000); + + test('wrong input identity, empty notes, foreign or incomplete refs and omitted-source revisions reject atomically', async () => { + const f = await fixture(), + c = await cost(f), + other = await cost(f); + await f.execute(c.detail.trials[0]!.runId!); + await f.execute(other.detail.trials[0]!.runId!); + const ref = reference(c.detail.trials[0]!.runId!), + foreign = reference(other.detail.trials[0]!.runId!); + const { artifact, project } = await save(f, c.source, [ref]); + const before = await f.snapshot(); + for (const input of [ + { source: { ...c.source, previewHash: 'f'.repeat(64) }, evidence: [ref] }, + { source: c.source, evidence: [foreign] }, + { source: c.source, evidence: [reference(c.detail.trials[1]!.runId!)] }, + { source: c.source, evidence: [] }, + { + source: c.source, + evidence: [ + { ...ref, metricsVersion: 'legacy-display/v1', metricPath: 'metrics.totalReturn' }, + ], + }, + ]) { + await expect( + f.research.createArtifact( + project.id, + { kind: 'note', title: 'Rejected source', body: '', ...input }, + 'operator' + ) + ).rejects.toMatchObject({ status: 422 }); + } + await expect( + f.research.reviseArtifact( + artifact.id, + { expectedRevision: 1, title: 'Foreign omitted', body: '', evidence: [foreign] }, + 'operator' + ) + ).rejects.toMatchObject({ status: 422 }); + expect(await f.snapshot()).toEqual(before); + expect((await f.research.getArtifact(artifact.id)).latestRevision.source).toEqual(c.source); + const detached = await f.research.reviseArtifact( + artifact.id, + { + expectedRevision: 1, + title: 'Explicit new scope', + body: '', + source: null, + evidence: [foreign], + }, + 'operator' + ); + expect(detached.latestRevision.source).toBeNull(); + }, 60000); + test('recomputed-hash selection, training, holdout, series and document metadata corruption cannot become cited evidence', async () => { + const f = await fixture(), + start = await submit(f); + for (const window of start.walk.windows) { + await finishWindow(f, window.validationId); + } + const done = await f.walks.finalize( + start.walk.id, + { previewHash: start.preview.previewHash }, + actor() + ); + const first = done.walkForward.windows[0]!.validation!, + report = first.report!; + const root = (await f.pool.query('SELECT * FROM research_experiments WHERE id=$1', [first.id])) + .rows[0]; + const header = ( + await f.pool.query('SELECT * FROM research_walk_forwards WHERE id=$1', [start.walk.id]) + ).rows[0]; + const project = await f.research.createProject({ title: 'Corruption refusals' }, 'operator'); + const ref = reference(report.test.runId); + const originalSource: ResearchFindingSource = { + kind: 'chronological-report/v1', + validationId: first.id, + previewHash: report.previewHash, + reportId: report.id, + reportHash: report.reportHash, + }; + const saved = await f.research.createArtifact( + project.id, + { kind: 'finding', title: 'Original', body: '', source: originalSource, evidence: [ref] }, + 'operator' + ); + for (const change of [ + 'training', + 'winner', + 'holdout', + 'principal', + 'time', + 'limitations', + ] as const) { + let selection = structuredClone(root.validation_selection), + changed = structuredClone(root.validation_report); + if (change === 'training') { + selection.training[0].metrics.totalReturn += 1; + changed.training = structuredClone(selection.training); + } + if (change === 'winner') { + selection.winner = structuredClone( + root.preview.candidates.find( + (candidate: any) => candidate.index !== selection.winner.index + ) + ); + } + if (change === 'holdout') { + changed.test.metrics.totalReturn += 1; + } + if (change === 'principal') { + changed.principal = 'fabricated'; + } + if (change === 'time') { + changed.createdAt = 'not-a-time'; + } + if (change === 'limitations') { + changed.limitations = ['ok', 42]; + } + selection = rehash(selection, 'selectionHash'); + changed.selectionHash = selection.selectionHash; + changed = rehash(changed, 'reportHash'); + await mutate(f, 'research_experiments', first.id, 'validation_selection', selection); + await mutate(f, 'research_experiments', first.id, 'validation_report', changed); + const source = { ...originalSource, reportHash: changed.reportHash }; + await expect( + f.research.createArtifact( + project.id, + { kind: 'finding', title: 'Corrupt', body: '', source, evidence: [ref] }, + 'operator' + ) + ).rejects.toThrow('Retained research source could not be verified'); + await mutate( + f, + 'research_experiments', + first.id, + 'validation_selection', + root.validation_selection + ); + await mutate( + f, + 'research_experiments', + first.id, + 'validation_report', + root.validation_report + ); + } + const originalResult = ( + await f.pool.query('SELECT canonical_result FROM backtest_results WHERE run_id=$1', [ + ref.runId, + ]) + ).rows[0].canonical_result; + for (const field of ['analytics', 'financial']) { + const damaged = structuredClone(originalResult); + if (field === 'analytics') { + damaged.analytics.metrics.totalReturn += 1; + } else { + expect(typeof damaged.financial.view.equity).toBe('string'); + damaged.financial.view.equity = '900.00000000'; + } + expect(damaged).not.toEqual(originalResult); + const write = async (value: unknown) => + f.postgres.transaction(async client => { + await client.query('ALTER TABLE backtest_results DISABLE TRIGGER USER'); + await client.query('UPDATE backtest_results SET canonical_result=$2 WHERE run_id=$1', [ + ref.runId, + value, + ]); + await client.query('ALTER TABLE backtest_results ENABLE TRIGGER USER'); + }); + await write(damaged); + await expect( + f.research.createArtifact( + project.id, + { + kind: 'finding', + title: 'Corrupt canonical result', + body: '', + source: originalSource, + evidence: [ref], + }, + 'operator' + ) + ).rejects.toThrow('Retained research source could not be verified'); + await expect(f.research.getArtifact(saved.id)).rejects.toThrow( + 'Retained finding source evidence could not be resolved' + ); + await write(originalResult); + } + const forged = structuredClone(header.report); + forged.segments[1].test.metrics.totalReturn += 1; + const changed = rehash(forged, 'reportHash'); + await mutate(f, 'research_walk_forwards', header.id, 'report', changed); + await expect( + f.research.createArtifact( + project.id, + { + kind: 'finding', + title: 'Forged series', + body: '', + source: { + kind: 'walk-forward-report/v1', + walkForwardId: header.id, + previewHash: header.preview_hash, + reportId: changed.id, + reportHash: changed.reportHash, + }, + evidence: [ref], + }, + 'operator' + ) + ).rejects.toThrow('Retained research source could not be verified'); + await mutate(f, 'research_walk_forwards', header.id, 'report', header.report); + const broken = structuredClone(root.validation_report); + broken.test.metrics.totalReturn += 1; + await mutate( + f, + 'research_experiments', + first.id, + 'validation_report', + rehash(broken, 'reportHash') + ); + const app = new Hono(); + const token = 'source-evidence-read-fixture-not-a-real-secret-1234'; + createHttpSecurity({ + readToken: token, + adminToken: 'source-evidence-admin-fixture-not-a-real-secret-1234', + serviceToken: 'source-evidence-service-fixture-not-a-real-secret-1234', + environment: 'test', + hostname: '127.0.0.1', + }).mount(app); + app.route('/', createResearchRoutes(f.container)); + const response = await app.request('/api/v2/analysis-artifacts/' + saved.id, { + headers: { Authorization: `Bearer ${token}` }, + }); + expect(response.status).toBe(500); + expect(await response.json()).toEqual({ error: 'Research workspace unavailable' }); + }, 60000); + test('SQL source guards reject malformed/member/empty refs, protect immutable history and recheck evidence after constraints become immediate', async () => { + const f = await fixture(), + c = await cost(f), + other = await cost(f); + await f.execute(c.detail.trials[0]!.runId!); + await f.execute(other.detail.trials[0]!.runId!); + const ref = reference(c.detail.trials[0]!.runId!), + foreign = reference(other.detail.trials[0]!.runId!); + const { artifact } = await save(f, c.source, [ref]); + for (const bad of [ + { ...c.source, extra: true }, + { ...c.source, experimentId: null }, + { ...c.source, previewHash: null }, + { ...c.source, previewHash: 'f'.repeat(64) }, + { ...c.source, kind: 'unknown' }, + 'null', + ]) { + await expect(rawRevision(f, artifact.id, bad, [ref])).rejects.toMatchObject({ + code: '23514', + }); + } + await expect(rawRevision(f, artifact.id, c.source, [])).rejects.toMatchObject({ + code: '23514', + }); + await expect(rawRevision(f, artifact.id, c.source, [foreign])).rejects.toThrow( + 'completed canonical members' + ); + await expect( + rawRevision(f, artifact.id, c.source, [ref], async (client, revisionId) => { + await client.query('SET CONSTRAINTS workspace_source_evidence IMMEDIATE'); + await client.query( + 'INSERT INTO analysis_evidence(revision_id,ordinal,run_id,metrics_version,metric_path) VALUES($1,2,$2,$3,$4)', + [revisionId, foreign.runId, foreign.metricsVersion, foreign.metricPath] + ); + }) + ).rejects.toThrow('completed canonical members'); + const accepted = await rawRevision(f, artifact.id, c.source, [ref]); + for (const statement of [ + 'UPDATE analysis_artifact_revisions SET source=NULL WHERE id=$1', + 'DELETE FROM analysis_artifact_revisions WHERE id=$1', + "INSERT INTO analysis_evidence(revision_id,ordinal,run_id,metrics_version,metric_path) VALUES($1,2,'" + + ref.runId + + "','canonical-analytics/v1','analytics.metrics.maxDrawdown')", + ]) { + await expect(f.pool.query(statement, [accepted])).rejects.toMatchObject({ code: '23514' }); + } + await expect( + f.pool.query('TRUNCATE analysis_artifact_revisions CASCADE') + ).rejects.toMatchObject({ code: '23514' }); + expect((await f.research.listArtifactRevisions(artifact.id)).map(item => item.source)).toEqual([ + c.source, + c.source, + ]); + }, 60000); + test('first migration and reapply preserve existing artifacts, receipts, results and pending run custody', async () => { + const f = await fixture(1, false), + c = await cost(f); + await f.execute(c.detail.trials[0]!.runId!); + const project = randomUUID(), + artifact = randomUUID(), + revision = randomUUID(), + runId = c.detail.trials[0]!.runId!; + await f.postgres.transaction(async client => { + await client.query( + "INSERT INTO research_projects(id,title,owner_principal,updated_by) VALUES($1,'Before27','operator','operator')", + [project] + ); + await client.query( + "INSERT INTO analysis_artifacts(id,project_id,kind,owner_principal,updated_by) VALUES($1,$2,'finding','operator','operator')", + [artifact, project] + ); + await client.query( + "INSERT INTO analysis_artifact_revisions(id,artifact_id,ordinal,title,body,submitted_by,content_origin) VALUES($1,$2,1,'Before27','Immutable','operator','human')", + [revision, artifact] + ); + await client.query( + "INSERT INTO analysis_evidence(revision_id,ordinal,run_id,metrics_version,metric_path) VALUES($1,1,$2,'canonical-analytics/v1','analytics.metrics.totalReturn')", + [revision, runId] + ); + }); + const claimedId = c.detail.trials[1]!.runId!; + const request = ( + await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [claimedId]) + ).rows[0].request_snapshot; + const claim = await f.repository.startCanonical(request); + const custody = ( + await f.pool.query( + 'SELECT attempt_id,attempt_number,lease_expires_at,status FROM runs WHERE id=$1', + [claimedId] + ) + ).rows[0]; + expect(custody.attempt_id).toBe(claim.attemptId); + expect(custody.status).toBe('running'); + expect(custody.lease_expires_at).not.toBeNull(); + const before = await f.snapshot(); + const sql = readFileSync( + new URL('../../database/postgres/init/27-research-evidence-sources.sql', import.meta.url), + 'utf8' + ); + await f.pool.query(sql); + const after = await f.snapshot(); + const revisions = after.analysis_artifact_revisions as Record[]; + expect(revisions.every(item => item.source === null)).toBe(true); + after.analysis_artifact_revisions = revisions.map(({ source: _source, ...row }) => row); + expect(after).toEqual(before); + expect( + ( + await f.pool.query( + 'SELECT attempt_id,attempt_number,lease_expires_at,status FROM runs WHERE id=$1', + [claimedId] + ) + ).rows[0] + ).toEqual(custody); + expect((await f.research.getArtifact(artifact)).latestRevision.source).toBeNull(); + const saved = await save(f, c.source, [reference(runId)]), + retained = await f.snapshot(); + await f.pool.query(sql); + expect(await f.snapshot()).toEqual(retained); + expect(await f.research.getArtifact(saved.artifact.id)).toEqual(saved.artifact); + }, 60000); + test('artifact get/list/history use a coherent readonly snapshot despite a committed source/result change', async () => { + const f = await fixture(4), + c = await cost(f); + await f.execute(c.detail.trials[0]!.runId!); + const { artifact, project } = await save(f, c.source, [reference(c.detail.trials[0]!.runId!)]); + const transaction = f.postgres.transaction.bind(f.postgres); + const original = ( + await f.pool.query('SELECT validation_phase FROM research_experiments WHERE id=$1', [ + c.detail.id, + ]) + ).rows[0]; + for (const read of [ + () => f.research.getArtifact(artifact.id), + () => f.research.listArtifacts(project.id), + () => f.research.listArtifactRevisions(artifact.id), + ]) { + let changed = false; + const trace: string[] = []; + let mode: unknown; + Object.defineProperty(f.postgres, 'transaction', { + configurable: true, + value: (work: (client: PoolClient) => Promise) => + transaction(async client => { + const query = client.query.bind(client), + proxy = Object.create(client) as PoolClient; + Object.defineProperty(proxy, 'query', { + value: async (sql: string, values?: unknown[]) => { + trace.push(sql); + const result = await query(sql, values); + if (sql.startsWith('SET TRANSACTION')) { + mode = ( + await query( + "SELECT current_setting('transaction_isolation') AS isolation,current_setting('transaction_read_only') AS readonly" + ) + ).rows[0]; + } + if (sql.startsWith('SELECT * FROM analysis_artifact_revisions') && !changed) { + changed = true; + await transaction(async other => { + await other.query('ALTER TABLE research_experiments DISABLE TRIGGER USER'); + await other.query( + 'UPDATE research_experiments SET preview_hash=$2 WHERE id=$1', + [c.detail.id, 'f'.repeat(64)] + ); + await other.query('ALTER TABLE research_experiments ENABLE TRIGGER USER'); + }); + } + return result; + }, + }); + return work(proxy); + }), + }); + await read(); + expect(changed).toBe(true); + expect(mode).toEqual({ isolation: 'repeatable read', readonly: 'on' }); + expect(trace[0]).toBe('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY'); + expect(trace.some(sql => /FOR (UPDATE|SHARE)|^(INSERT|UPDATE|DELETE)/i.test(sql))).toBe( + false + ); + Object.defineProperty(f.postgres, 'transaction', { configurable: true, value: transaction }); + await expect(f.research.getArtifact(artifact.id)).rejects.toThrow( + 'Retained finding source evidence could not be resolved' + ); + await mutate(f, 'research_experiments', c.detail.id, 'preview_hash', c.source.previewHash); + } + expect(original.validation_phase).toBeNull(); + }, 60000); +}); diff --git a/test/postgres/research-workspace.test.ts b/test/postgres/research-workspace.test.ts index 5860bf45..13a2b21d 100644 --- a/test/postgres/research-workspace.test.ts +++ b/test/postgres/research-workspace.test.ts @@ -71,6 +71,7 @@ async function fixture(applyWorkspace = true, maxConnections = 10) { } if (applyWorkspace) { await pool.query(migration); + await pool.query(sql('27-research-evidence-sources.sql')); } const postgres = new PostgreSQLClient( { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, @@ -715,6 +716,8 @@ describe.skipIf(!url)('research workspace retained narratives and evidence', () await f.pool.query(migration); await f.pool.query(migration); expect(await snapshot()).toEqual(before); + // Current service writes include optional source identity; historical SQL20 assertions above stay scoped. + await f.pool.query(sql('27-research-evidence-sources.sql')); const p = await f.service.createProject({ title: 'After upgrade' }, 'operator'); const finding = await f.service.createArtifact( p.id,