feat(research): retain exact experiment and report citations in findings
This commit is contained in:
parent
46a4f13acd
commit
06039d17ba
36 changed files with 4170 additions and 253 deletions
|
|
@ -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[];
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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();
|
||||
|
||||
|
|
|
|||
|
|
@ -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();
|
||||
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
341
apps/stock/web-api/src/services/research-source-evidence.ts
Normal file
341
apps/stock/web-api/src/services/research-source-evidence.ts
Normal 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 });
|
||||
}
|
||||
}
|
||||
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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}
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
);
|
||||
}
|
||||
|
|
@ -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>
|
||||
);
|
||||
}
|
||||
|
|
@ -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),
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
);
|
||||
}
|
||||
|
|
@ -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}
|
||||
|
|
|
|||
|
|
@ -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()}
|
||||
>
|
||||
|
|
|
|||
|
|
@ -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.',
|
||||
]
|
||||
);
|
||||
}
|
||||
|
|
@ -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)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue