feat(research): retain exact experiment and report citations in findings

This commit is contained in:
Boki 2026-10-24 14:42:14 -04:00
parent 46a4f13acd
commit 06039d17ba
36 changed files with 4170 additions and 253 deletions

View file

@ -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[];
}

View file

@ -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();

View file

@ -66,7 +66,8 @@ export async function runMigrations(container: IServiceContainer): Promise<void>
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();

View file

@ -561,7 +561,7 @@ export class ExperimentsService {
async readDetail(database: Query, id: string): Promise<WorkbenchExperimentDetail> {
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;
}
}

View file

@ -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<ResearchEvidence[]> {
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

View file

@ -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<string, unknown>, 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<ResearchRunResult | null>;
/** Historical provenance only. The existing canonical reader owns all financial validation. */
export async function verifyResearchSource(
source: ResearchFindingSource,
references: ResearchEvidenceReference[],
database: BacktestResultQuery,
readResult: ResultReader
): Promise<Map<string, CanonicalRunResult>> {
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<string, CanonicalRunResult>();
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<ChronologicalValidationReport> => {
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<ChronologicalValidationSelection>(
root.validation_selection,
'selectionHash'
);
const report = publicValidationDocument<ChronologicalValidationReport>(
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<string>;
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 });
}
}

View file

@ -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<ResearchArtifact[]> {
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<ResearchArtifact> {
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<ResearchArtifactRevision[]> {
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<ResearchArtifact> {
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<ResearchArtifact> {
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<ResearchArtifactRevision> {
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<void> {
// Validate using the authoritative reader; only references are persisted.
for (const reference of data.evidence) {
await this.evidence.resolve(reference, client);
}
): Promise<ResearchArtifactRevision> {
// 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);
}
}

View file

@ -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 }) {
<div
className="h-full overflow-auto p-1 space-y-4"
onClickCapture={event => {
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 && (
<>
<RegimeEvidenceUnavailable />
{!validation.report && (
<SourceFindingAction
source={null}
disabled
onDirtyChange={setFindingDirty}
unavailable="Save the complete report before linking its evidence to a research finding."
/>
)}
<p className="font-semibold">
{validation.report
? 'Execution complete · report saved'
@ -481,6 +510,13 @@ function ValidationDetail({ validationId }: { validationId: string }) {
{validation.report && (
<section aria-label="Saved validation report" className="space-y-3">
<h2 className="font-semibold">Saved validation report</h2>
<SourceFindingAction
key={validation.report.reportHash}
source={chronologicalFindingSource(validation)}
disabled={loading || busy || Boolean(intent)}
onDirtyChange={setFindingDirty}
unavailable="A sealed report is required to cite this source."
/>
<p className="break-all text-xs">
Report {validation.report.id} · {validation.report.reportHash} ·{' '}
{validation.report.createdAt} · {validation.report.principal}

View file

@ -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 <ExperimentDetailView key={experimentId} experimentId={experimentId} />;
}
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 }) {
<div
className="h-full overflow-auto space-y-5 p-1"
onClickCapture={event => {
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 && (
<>
<ExperimentCounts experiment={experiment} />
<RegimeEvidenceUnavailable />
<SourceFindingAction
key={`experiment:${experiment.id}:${experiment.previewHash}`}
source={experimentFindingSource(experiment)}
disabled={loading || mutating || retryIntents.length > 0}
onDirtyChange={setFindingDirty}
unavailable="Only explicitly standalone experiments can be cited here. Use the saved chronological or walk-forward report for validation evidence."
/>
<div className="flex flex-wrap items-center gap-4">
<Link
className="text-primary-500 text-sm"

View file

@ -2,7 +2,10 @@ import { useEffect, useRef, useState } from 'react';
import { Link, useParams } from 'react-router-dom';
import type { WalkForwardReceipt } from '@stock-bot/stock-config/walk-forward';
import { Button } from '@/components/ui/Button';
import { walkForwardFindingSource } from '@/features/research/components/findingSources';
import { useUnsavedWarning } from '@/features/strategies/components/useUnsavedWarning';
import { RegimeEvidenceUnavailable } from './components/RegimeEvidenceUnavailable';
import { SourceFindingAction } from './components/SourceFindingAction';
import { ValidationEvidence } from './components/ValidationEvidence';
import {
walkForwardApi,
@ -16,6 +19,7 @@ export function WalkForwardDetailPage() {
}
type Intent = { id: string; body: { previewHash: string }; key: string };
function WalkForwardDetail({ walkForwardId }: { walkForwardId: string }) {
const [findingDirty, setFindingDirty] = useState(false);
const alive = useRef(false),
pending = useRef(false),
reading = useRef(true),
@ -170,6 +174,22 @@ function WalkForwardDetail({ walkForwardId }: { walkForwardId: string }) {
<div
className="h-full overflow-auto p-1 space-y-4"
onClickCapture={event => {
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 && (
<>
<RegimeEvidenceUnavailable />
{!value.report && (
<SourceFindingAction
source={null}
disabled
onDirtyChange={setFindingDirty}
unavailable="Save the complete report before linking its evidence to a research finding."
/>
)}
<p className="font-semibold">
{value.report
? 'Execution complete · walk-forward report saved'
@ -348,6 +377,13 @@ function WalkForwardDetail({ walkForwardId }: { walkForwardId: string }) {
{value.report && (
<section aria-label="Saved walk-forward report" className="space-y-3">
<h2 className="font-semibold">Saved walk-forward report</h2>
<SourceFindingAction
key={value.report.reportHash}
source={walkForwardFindingSource(value)}
disabled={loading || busy || Boolean(intent)}
onDirtyChange={setFindingDirty}
unavailable="A sealed report is required to cite this source."
/>
<p className="break-all">
Report {value.report.id} · {value.report.createdAt} · Hash {value.report.reportHash}
</p>

View file

@ -0,0 +1,15 @@
export function RegimeEvidenceUnavailable() {
return (
<section aria-label="Regime evidence" className="text-sm space-y-1">
<h2 className="font-semibold">Regime evidence unavailable</h2>
<p>
No versioned as-of regime annotations were retained for these results. Regime sample counts,
unclassified samples and window coverage are unavailable.
</p>
<p>
Strategy names, parameters and current market classifications do not establish historical
regime evidence.
</p>
</section>
);
}

View file

@ -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<FindingDraftSource | null>(null);
const eligible = source?.runs.some(run => run.metrics.length);
return (
<div className="space-y-2">
<Button
variant="outline"
disabled={disabled || !eligible}
onClick={() => {
if (source && eligible) {
setSnapshot(structuredClone(source));
}
}}
>
Save research finding
</Button>
{!eligible && (
<p className="text-sm">
{source
? 'No completed, comparable measurements are available to cite yet.'
: unavailable}
</p>
)}
{snapshot && (
<SaveSourceFindingDialog
source={snapshot}
onClose={() => setSnapshot(null)}
onDirtyChange={onDirtyChange}
/>
)}
</div>
);
}

View file

@ -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),
});

View file

@ -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 (
<section aria-label="Finding source" className="space-y-1 break-all text-sm">
<h3 className="font-medium">Exact evidence source</h3>
<p>
{source.kind} · {identity}
</p>
<p>Preview hash: {source.previewHash}</p>
{'reportId' in source && (
<p>
Report: {source.reportId} · Report hash: {source.reportHash}
</p>
)}
<p>
Selected contributing evidence; the source does not validate this narrative or endorse the
whole experiment or report.
</p>
{link && (
<Link className="text-primary-500 underline" to={href}>
Open cited source
</Link>
)}
</section>
);
}

View file

@ -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({
</p>
</div>
)}
{'evidence' in revision && <ResearchEvidenceList evidence={revision.evidence} />}
{'evidence' in revision && (
<>
<FindingSource source={revision.source} />
<ResearchEvidenceList evidence={revision.evidence} />
</>
)}
{entry.kind === 'artifact' && entry.entity.hypothesisRevisionId && (
<HypothesisReference
projectId={projectId}

View file

@ -1,13 +1,7 @@
import { useEffect, useRef, useState } from 'react';
import { Link } from 'react-router-dom';
import {
isCanonicalRunResult,
type ResearchRunResult,
} from '@stock-bot/stock-config/canonical-research';
import {
canonicalResearchMetricPaths,
legacyResearchMetricPaths,
} from '@stock-bot/stock-config/research';
import type { ResearchRunResult } from '@stock-bot/stock-config/canonical-research';
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
import type {
ResearchArtifact,
ResearchContentOrigin,
@ -22,16 +16,49 @@ import {
useUnsavedWarning,
} from '@/features/strategies/components/useUnsavedWarning';
import { researchApi, ResearchApiError, type ArtifactInput } from '../services/researchApi';
import { FindingSource } from './FindingSource';
import {
findingMetricKey,
singleRunFindingSource,
type FindingDraftSource,
} from './findingSources';
import { ResearchEvidenceList, researchMetricLabel } from './ResearchEvidence';
/** Remount even when a caller replaces the result without keying its dialog. */
export function SaveFindingDialog(props: { result: ResearchRunResult; onClose: () => void }) {
return <FindingDraft key={`${props.result.backtestId}:${props.result.runId}`} {...props} />;
/** Preserve the original single-run API and initial total-return selection. */
export function SaveFindingDialog({
result,
onClose,
}: {
result: ResearchRunResult;
onClose: () => void;
}) {
return (
<FindingDraft
key={`${result.backtestId}:${result.runId}`}
source={singleRunFindingSource(result)}
onClose={onClose}
/>
);
}
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 <FindingDraft key={props.source.key} {...props} />;
}
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<ResearchProject[]>([]);
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<ResearchContentOrigin>('human');
const [selectedMetrics, setSelectedMetrics] = useState<string[]>([metricPaths[0]]);
const [selectedMetrics, setSelectedMetrics] = useState<string[]>(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 (
<Dialog open onOpenChange={open => !open && close()}>
<DialogContent className="max-w-2xl w-[min(42rem,95vw)]">
@ -260,22 +289,23 @@ function FindingDraft({ result, onClose }: { result: ResearchRunResult; onClose:
<DialogTitle>Save finding</DialogTitle>
</DialogHeader>
<p className="text-sm break-all">
Run: {result.runId} ·{' '}
{canonical ? 'Canonical Rust result' : 'Legacy · Unverified economics'}
{source.label} ·{' '}
{source.legacy ? 'Legacy · Unverified economics' : 'Canonical Rust result'}
</p>
{!canonical && (
{source.legacy && (
<p className="text-sm text-text-secondary">
Legacy display measurements are exploratory evidence; financial correctness and
historical engine versions are not certified.
</p>
)}
{limitations.length > 0 && (
{source.limitations.length > 0 && (
<ul className="list-disc pl-5 text-sm text-text-secondary">
{limitations.map((limit, index) => (
{source.limitations.map((limit, index) => (
<li key={index}>{limit}</li>
))}
</ul>
)}
<FindingSource source={source.context} link={Boolean(saved)} />
{saved ? (
<>
<p role="status">Finding saved. Its narrative remains unvalidated.</p>
@ -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.
</p>
<fieldset disabled={blocked} className="grid gap-2 sm:grid-cols-2">
<legend className="mb-2 text-sm font-medium">Referenced measurements</legend>
{metricPaths.map(path => {
const value = path
.split('.')
.reduce<unknown>(
(item, key) =>
item && typeof item === 'object'
? (item as Record<string, unknown>)[key]
: undefined,
result
{source.context && (
<p className="text-sm">
Choose contributing runs and measurements explicitly. Unselected and unavailable
outcomes remain visible.
</p>
)}
{source.runs.map(run => (
<fieldset
key={run.key}
aria-label={source.context ? run.label : undefined}
disabled={blocked}
className="grid gap-2 sm:grid-cols-2"
>
<legend className="mb-2 text-sm font-medium">
{source.context ? `${run.label} · ${run.status}` : 'Referenced measurements'}
</legend>
{run.diagnostic && <p className="text-sm sm:col-span-2">{run.diagnostic}</p>}
{!run.metrics.length && (
<p className="text-sm sm:col-span-2">
No selectable measurements. A completed, comparable saved result is required.
</p>
)}
{run.metrics.map(metric => {
const key = findingMetricKey(metric.reference);
const label = researchMetricLabel(metric.reference.metricPath);
return (
<label key={key} className="text-sm flex gap-2 items-start">
<input
type="checkbox"
data-run-id={metric.reference.runId}
data-metric-path={metric.reference.metricPath}
aria-label={source.context ? `${run.label}: ${label}` : label}
checked={selectedMetrics.includes(key)}
onChange={event =>
setSelectedMetrics(previous =>
event.target.checked
? [...previous, key]
: previous.filter(item => item !== key)
)
}
/>
{label}
{source.context
? ` (${metric.reference.metricPath.endsWith('sharpeRatio') ? 'ratio' : 'fraction'})`
: ''}
{metric.value === null
? ` · Unavailable${source.context && metric.unavailableReason ? `: ${metric.unavailableReason}` : ''}`
: source.context
? ` · ${String(metric.value)}`
: ''}
</label>
);
return (
<label key={path} className="text-sm flex gap-2 items-start">
<input
type="checkbox"
aria-label={researchMetricLabel(path)}
checked={selectedMetrics.includes(path)}
onChange={event =>
setSelectedMetrics(previous =>
event.target.checked
? [...previous, path]
: previous.filter(item => item !== path)
)
}
/>
{researchMetricLabel(path)}
{value === null || value === undefined ? ' · Unavailable' : ''}
</label>
);
})}
</fieldset>
})}
</fieldset>
))}
{error && <p role="alert">{error}</p>}
{ambiguous && (
<div role="alert" className="space-y-2">
@ -475,7 +528,7 @@ function FindingDraft({ result, onClose }: { result: ResearchRunResult; onClose:
destinationLoading ||
!title.trim() ||
!selectedMetrics.length ||
result.status !== 'completed'
!metrics.length
}
onClick={() => void save()}
>

View file

@ -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<ArtifactInput['evidence']>[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<string, string>
): 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<unknown>(
(item, key) =>
item && typeof item === 'object'
? (item as Record<string, unknown>)[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.',
]
);
}

View file

@ -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<string, unknown> =>
typeof value === 'object' && value !== null && !Array.isArray(value);
const identified = (value: unknown): value is Record<string, unknown> =>
record(value) && typeof value.id === 'string' && value.id.length > 0;
function validSource(value: Record<string, unknown>): 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)

View file

@ -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();

View file

@ -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.

View file

@ -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.

View file

@ -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

View file

@ -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"
}
}
}

View file

@ -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.

View file

@ -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).

View file

@ -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 {

View file

@ -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')

View file

@ -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<ReturnType<typeof fixture>>,
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 {

View file

@ -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<unknown>) => {
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);

View file

@ -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<string, unknown>[] }>;
function fixture(
security: 'enabled' | 'disabled' | 'absent' = 'enabled',
query: Query = async () => {
throw new Error('Rejected request reached storage');
}
) {
const database = {
query: mock(query),
transaction: mock(async <T>(work: (client: { query: Query }) => Promise<T>) => 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<string, string> = {}
) {
return app.request(`/api/v2/${path}`, {
method,
headers: {
...(role ? { Authorization: `Bearer ${tokens[role]}` } : {}),
'Content-Type': 'application/json',
...extra,
},
...(body === undefined ? {} : { body: JSON.stringify(body) }),
});
},
};
}
const projectId = randomUUID(),
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
);
});
});

View file

@ -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);
});
});

File diff suppressed because it is too large Load diff

View file

@ -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(

View file

@ -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<void>)[] = [];
afterEach(async () => {

View file

@ -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<void>)[] = [];
let packages: ReturnType<typeof packageBuiltinStrategies> | 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<string, unknown> = {};
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<ReturnType<typeof fixture>>;
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<T extends Record<string, unknown>>(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<void>
) {
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<string, unknown>[];
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<unknown>) =>
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);
});

View file

@ -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,