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

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

View file

@ -41,6 +41,13 @@ const logger = getLogger('backtest-v2-service');
const ORCHESTRATOR_URL = process.env.ORCHESTRATOR_URL || 'http://localhost:2004';
export type BacktestTransport = (url: string, init?: RequestInit) => Promise<Response>;
/** Reads may share an existing transaction without acquiring another pool connection. */
export interface BacktestResultQuery {
query<T extends QueryResultRow = QueryResultRow>(
text: string,
values?: unknown[]
): Promise<{ rows: T[] }>;
}
export interface BacktestRequest {
name: string;
@ -580,8 +587,11 @@ export class BacktestServiceV2 {
}
// Get run results
async getRunResults(runId: string): Promise<ResearchRunResult | null> {
const result = await this.container.postgres.query<
async getRunResults(
runId: string,
database: BacktestResultQuery = this.container.postgres
): Promise<ResearchRunResult | null> {
const result = await database.query<
StoredBacktestResult & {
canonical_result?: CanonicalRunResult | null;
request_snapshot?: unknown;

View file

@ -0,0 +1,8 @@
export class ResearchError extends Error {
constructor(
public readonly status: 400 | 401 | 403 | 404 | 409 | 422,
message: string
) {
super(message);
}
}

View file

@ -0,0 +1,161 @@
import { requireServices, type IServiceContainer } from '@stock-bot/services';
import {
isCanonicalRunResult,
type ResearchRunResult,
} from '@stock-bot/stock-config/canonical-research';
import {
parseResearchInput,
researchEvidenceReferenceSchema,
} from '@stock-bot/stock-config/research';
import type {
CanonicalMetrics,
ResearchEvidence,
ResearchEvidenceReference,
} from '@stock-bot/types';
import { BacktestServiceV2, type BacktestResultQuery } from './backtest-v2.service';
import { ResearchError } from './research-errors';
function unitOf(path: string): ResearchEvidence['unit'] {
const name = path.split('.').at(-1);
if (['fillCount', 'roundTripCount', 'totalTrades'].includes(name ?? '')) {
return 'count';
}
if (['avgWin', 'avgLoss'].includes(name ?? '')) {
return 'currency';
}
if (
['sharpeRatio', 'sortinoRatio', 'profitFactor', 'beta', 'informationRatio'].includes(name ?? '')
) {
return 'ratio';
}
return 'fraction';
}
/** Select existing scalar measurements only. No metric, accounting or validation recalculation. */
export function projectResearchEvidence(
input: ResearchEvidenceReference,
result: ResearchRunResult
): ResearchEvidence {
const reference = parseResearchInput(researchEvidenceReferenceSchema, input);
if (result.runId !== reference.runId || result.status !== 'completed') {
throw new ResearchError(422, 'Evidence must refer to the completed retained run');
}
let value: number | null | undefined;
let unavailableReason: string | null;
let details: Pick<
ResearchEvidence,
'resultKind' | 'financialEngine' | 'datasetHash' | 'limitations'
>;
if (isCanonicalRunResult(result)) {
if (reference.metricsVersion !== 'canonical-analytics/v1' || result.analytics.version !== 1) {
throw new ResearchError(422, 'Metrics version does not match this retained result');
}
if (
reference.strategyVersionId &&
reference.strategyVersionId !== result.request.strategy.versionId
) {
throw new ResearchError(422, 'Strategy version is not bound by this run');
}
const key = reference.metricPath.slice('analytics.metrics.'.length) as keyof CanonicalMetrics;
value =
reference.metricPath === 'analytics.fillCount'
? result.analytics.fillCount
: result.analytics.metrics[key];
unavailableReason =
value === null ? (result.analytics.unavailable[key] ?? 'not-reported') : null;
details = {
resultKind: 'canonical',
financialEngine: 'rust',
datasetHash: result.request.datasetHash,
limitations: [...result.financial.limitations, ...result.financial.modelLimitations].map(
message => ({ code: 'canonical-model-limitation', message })
),
};
} else {
if (reference.metricsVersion !== 'legacy-display/v1' || reference.strategyVersionId) {
throw new ResearchError(
422,
'Legacy results cannot certify this metrics or executable version'
);
}
value =
reference.metricPath === 'analytics.exposureTime'
? result.analytics.exposureTime
: result.metrics[reference.metricPath.slice('metrics.'.length)];
unavailableReason = value === null || value === undefined ? 'legacy-unavailable' : null;
// Legacy v1 names this read-only display adapter, not an engine/economics version.
details = {
resultKind: 'legacy',
financialEngine: result.engine,
datasetHash: result.provenance?.datasetHash ?? null,
limitations: [
{
code: 'legacy-unverified-economics',
message:
'Legacy display measurements are exploratory evidence; financial correctness and historical engine versions are not certified.',
},
...(result.provenance?.limitations ?? []),
],
};
}
if (
value !== null &&
value !== undefined &&
(typeof value !== 'number' || !Number.isFinite(value))
) {
throw new ResearchError(422, 'Retained metric is not a finite scalar measurement');
}
if (value === undefined) {
value = null;
unavailableReason ??= 'not-reported';
}
return {
...reference,
backtestId: result.backtestId,
value,
unit: unitOf(reference.metricPath),
availability: value === null ? 'unavailable' : 'available',
unavailableReason,
...details,
};
}
export class ResearchEvidenceResolver {
private readonly database;
private readonly results;
constructor(container: IServiceContainer) {
this.database = requireServices(container, 'postgres').postgres;
this.results = new BacktestServiceV2(container);
}
async resolve(
input: ResearchEvidenceReference,
database: BacktestResultQuery = this.database
): Promise<ResearchEvidence> {
const reference = parseResearchInput(researchEvidenceReferenceSchema, input);
const run = (
await database.query<{ id: string; backtest_id: string; status: string }>(
'SELECT id,backtest_id,status FROM runs WHERE id=$1',
[reference.runId]
)
).rows[0];
if (!run || run.status !== 'completed') {
throw new ResearchError(422, 'Evidence requires a completed retained run');
}
let result;
try {
result = await this.results.getRunResults(reference.runId, database);
} catch (cause) {
// Validation here concerns retained storage, not the caller's valid reference.
// Preserve the cause for server diagnostics without returning a false HTTP 400.
throw new Error('Retained research result could not be read', { cause });
}
if (!result || result.runId !== run.id || result.backtestId !== run.backtest_id) {
throw new ResearchError(
422,
'Retained evidence result is missing or has a different identity'
);
}
return projectResearchEvidence(reference, result);
}
}

View file

@ -0,0 +1,631 @@
import { randomUUID } from 'node:crypto';
import type { PoolClient, QueryResultRow } from 'pg';
import { requireServices, type IServiceContainer } from '@stock-bot/services';
import {
archiveResearchSchema,
createResearchArtifactSchema,
createResearchHypothesisSchema,
createResearchProjectSchema,
parseResearchInput,
researchActorSchema,
researchIdSchema,
reviseResearchArtifactSchema,
reviseResearchHypothesisSchema,
updateResearchProjectSchema,
} from '@stock-bot/stock-config/research';
import type {
ResearchActor,
ResearchArtifact,
ResearchArtifactRevision,
ResearchAuthorship,
ResearchContentOrigin,
ResearchEvidenceReference,
ResearchHypothesis,
ResearchHypothesisRevision,
ResearchProject,
StrategyRecord,
} from '@stock-bot/types';
import { ResearchError } from './research-errors';
import { ResearchEvidenceResolver } from './research-evidence';
import { StrategyCatalogService } from './strategy-catalog.service';
type Database = {
query<T extends QueryResultRow = QueryResultRow>(
text: string,
values?: unknown[]
): Promise<{ rows: T[] }>;
};
const iso = (value: string | Date) => new Date(value).toISOString();
function required(row: QueryResultRow | undefined, label: string): QueryResultRow {
if (!row) {
throw new ResearchError(404, `${label} not found`);
}
return row;
}
function authorship(actor: ResearchActor, origin?: ResearchContentOrigin): ResearchAuthorship {
researchActorSchema.parse(actor);
if (actor === 'service' && origin === 'human') {
throw new ResearchError(403, 'Service credentials cannot declare human authorship');
}
return {
submittedBy: actor,
contentOrigin: origin ?? (actor === 'operator' ? 'human' : 'unknown'),
};
}
function project(row: QueryResultRow): ResearchProject {
return {
id: row.id,
title: row.title,
description: row.description,
revision: row.revision,
ownerPrincipal: row.owner_principal,
updatedBy: row.updated_by,
archived: row.archived_at !== null,
createdAt: iso(row.created_at),
updatedAt: iso(row.updated_at),
};
}
function hypothesisRevision(row: QueryResultRow): ResearchHypothesisRevision {
return {
id: row.id,
hypothesisId: row.hypothesis_id,
ordinal: row.ordinal,
title: row.title,
proposition: row.proposition,
validationCriteria: row.validation_criteria,
submittedBy: row.submitted_by,
contentOrigin: row.content_origin,
validationState: 'unvalidated',
createdAt: iso(row.created_at),
};
}
function expectRevision(actual: number, expected: number): void {
if (actual !== expected) {
throw new ResearchError(409, 'Research revision changed; reload before editing');
}
}
function active(row: QueryResultRow, label: string): void {
if (row.archived_at !== null) {
throw new ResearchError(409, `${label} is archived; restore it before editing`);
}
}
/** Metadata transactions only. The existing result reader owns every measured value. */
export class ResearchService {
private readonly database;
private readonly evidence;
private readonly catalog;
constructor(container: IServiceContainer) {
this.database = requireServices(container, 'postgres').postgres;
this.evidence = new ResearchEvidenceResolver(container);
this.catalog = new StrategyCatalogService(container);
}
async listProjects(includeArchived = false): Promise<ResearchProject[]> {
return (
await this.database.query(
'SELECT * FROM research_projects WHERE ($1::boolean OR archived_at IS NULL) ORDER BY created_at DESC,id',
[includeArchived]
)
).rows.map(project);
}
async createProject(input: unknown, actor: ResearchActor): Promise<ResearchProject> {
const data = parseResearchInput(createResearchProjectSchema, input);
researchActorSchema.parse(actor);
return project(
required(
(
await this.database.query(
'INSERT INTO research_projects(id,title,description,owner_principal,updated_by) VALUES($1,$2,$3,$4,$4) RETURNING *',
[randomUUID(), data.title, data.description, actor]
)
).rows[0],
'Created project'
)
);
}
async getProject(id: string): Promise<ResearchProject> {
return project(await this.projectRow(this.database, researchIdSchema.parse(id)));
}
async updateProject(id: string, input: unknown, actor: ResearchActor): Promise<ResearchProject> {
researchIdSchema.parse(id);
const data = parseResearchInput(updateResearchProjectSchema, input);
researchActorSchema.parse(actor);
if (data.title === undefined && data.description === undefined && data.archived === undefined) {
throw new ResearchError(400, 'Supply a project change');
}
return this.database.transaction(async client => {
const old = await this.projectRow(client, id, true);
expectRevision(old.revision, data.expectedRevision);
if (
old.archived_at !== null &&
(data.archived !== false || data.title !== undefined || data.description !== undefined)
) {
throw new ResearchError(409, 'Archived projects only permit restoration');
}
return project(
required(
(
await client.query(
`UPDATE research_projects SET title=$2,description=$3,archived_at=$4,revision=revision+1,
updated_by=$5,updated_at=NOW() WHERE id=$1 RETURNING *`,
[
id,
data.title ?? old.title,
data.description ?? old.description,
data.archived === undefined
? old.archived_at
: data.archived
? (old.archived_at ?? new Date())
: null,
actor,
]
)
).rows[0],
'Project'
)
);
});
}
async listProjectStrategies(projectId: string): Promise<StrategyRecord[]> {
await this.getProject(projectId);
const rows = (
await this.database.query(
'SELECT strategy_id FROM research_project_strategies WHERE project_id=$1 ORDER BY created_at,strategy_id',
[projectId]
)
).rows;
return Promise.all(rows.map(row => this.catalog.getStrategy(row.strategy_id)));
}
async linkStrategy(projectId: string, strategyId: string, actor: ResearchActor): Promise<void> {
researchIdSchema.parse(projectId);
researchIdSchema.parse(strategyId);
researchActorSchema.parse(actor);
await this.database.transaction(async client => {
active(await this.projectRow(client, projectId, true), 'Project');
const selected = required(
(await client.query('SELECT * FROM strategies WHERE id=$1 FOR UPDATE', [strategyId]))
.rows[0],
'Strategy'
);
active(selected, 'Strategy');
const inserted = await client.query(
'INSERT INTO research_project_strategies(project_id,strategy_id,added_by) VALUES($1,$2,$3) ON CONFLICT DO NOTHING RETURNING project_id',
[projectId, strategyId, actor]
);
if (inserted.rows.length) {
await client.query(
'UPDATE research_projects SET revision=revision+1,updated_by=$2,updated_at=NOW() WHERE id=$1',
[projectId, actor]
);
}
});
}
async unlinkStrategy(projectId: string, strategyId: string, actor: ResearchActor): Promise<void> {
researchIdSchema.parse(projectId);
researchIdSchema.parse(strategyId);
researchActorSchema.parse(actor);
await this.database.transaction(async client => {
active(await this.projectRow(client, projectId, true), 'Project');
const removed = await client.query(
'DELETE FROM research_project_strategies WHERE project_id=$1 AND strategy_id=$2 RETURNING project_id',
[projectId, strategyId]
);
if (removed.rows.length) {
await client.query(
'UPDATE research_projects SET revision=revision+1,updated_by=$2,updated_at=NOW() WHERE id=$1',
[projectId, actor]
);
}
});
}
async listHypotheses(projectId: string, includeArchived = false): Promise<ResearchHypothesis[]> {
await this.getProject(projectId);
const rows = (
await this.database.query(
'SELECT * FROM research_hypotheses WHERE project_id=$1 AND ($2::boolean OR archived_at IS NULL) ORDER BY created_at DESC,id',
[projectId, includeArchived]
)
).rows;
return Promise.all(rows.map(row => this.hypothesis(this.database, row)));
}
async createHypothesis(
projectId: string,
input: unknown,
actor: ResearchActor
): Promise<ResearchHypothesis> {
researchIdSchema.parse(projectId);
const data = parseResearchInput(createResearchHypothesisSchema, input);
const author = authorship(actor, data.contentOrigin);
return this.database.transaction(async client => {
active(await this.projectRow(client, projectId, true), 'Project');
const row = required(
(
await client.query(
'INSERT INTO research_hypotheses(id,project_id,owner_principal,updated_by) VALUES($1,$2,$3,$3) RETURNING *',
[randomUUID(), projectId, actor]
)
).rows[0],
'Created hypothesis'
);
await this.insertHypothesisRevision(client, row.id, 1, data, author);
return this.hypothesis(client, row);
});
}
async getHypothesis(id: string): Promise<ResearchHypothesis> {
return this.hypothesis(
this.database,
await this.hypothesisRow(this.database, researchIdSchema.parse(id))
);
}
async listHypothesisRevisions(id: string): Promise<ResearchHypothesisRevision[]> {
researchIdSchema.parse(id);
await this.hypothesisRow(this.database, id);
return (
await this.database.query(
'SELECT * FROM research_hypothesis_revisions WHERE hypothesis_id=$1 ORDER BY ordinal',
[id]
)
).rows.map(hypothesisRevision);
}
async reviseHypothesis(
id: string,
input: unknown,
actor: ResearchActor
): Promise<ResearchHypothesis> {
researchIdSchema.parse(id);
const data = parseResearchInput(reviseResearchHypothesisSchema, input);
const author = authorship(actor, data.contentOrigin);
return this.database.transaction(async client => {
const row = await this.lockHypothesis(client, id);
active(row, 'Hypothesis');
const current = await this.hypothesis(client, row);
expectRevision(current.latestRevision.ordinal, data.expectedRevision);
await this.insertHypothesisRevision(client, id, data.expectedRevision + 1, data, author);
const updated = required(
(
await client.query(
'UPDATE research_hypotheses SET updated_by=$2,updated_at=NOW() WHERE id=$1 RETURNING *',
[id, actor]
)
).rows[0],
'Hypothesis'
);
return this.hypothesis(client, updated);
});
}
async archiveHypothesis(
id: string,
input: unknown,
actor: ResearchActor
): Promise<ResearchHypothesis> {
researchIdSchema.parse(id);
const data = parseResearchInput(archiveResearchSchema, input);
researchActorSchema.parse(actor);
return this.database.transaction(async client => {
await this.lockHypothesis(client, id);
const row = required(
(
await client.query(
'UPDATE research_hypotheses SET archived_at=CASE WHEN $2 THEN COALESCE(archived_at,NOW()) ELSE NULL END,updated_by=$3,updated_at=NOW() WHERE id=$1 RETURNING *',
[id, data.archived, actor]
)
).rows[0],
'Hypothesis'
);
return this.hypothesis(client, row);
});
}
async listArtifacts(projectId: string, includeArchived = false): Promise<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)));
}
async createArtifact(
projectId: string,
input: unknown,
actor: ResearchActor
): Promise<ResearchArtifact> {
researchIdSchema.parse(projectId);
const data = parseResearchInput(createResearchArtifactSchema, input);
const author = authorship(actor, data.contentOrigin);
this.requireFindingEvidence(data.kind, data.evidence);
return this.database.transaction(async client => {
active(await this.projectRow(client, projectId, true), 'Project');
if (data.hypothesisRevisionId) {
const linked = (
await client.query(
`SELECT h.* FROM research_hypothesis_revisions r JOIN research_hypotheses h ON h.id=r.hypothesis_id
WHERE r.id=$1 FOR UPDATE OF h`,
[data.hypothesisRevisionId]
)
).rows[0];
if (!linked || linked.project_id !== projectId) {
throw new ResearchError(422, 'Hypothesis revision must belong to this project');
}
active(linked, 'Hypothesis');
}
const row = required(
(
await client.query(
'INSERT INTO analysis_artifacts(id,project_id,hypothesis_revision_id,kind,owner_principal,updated_by) VALUES($1,$2,$3,$4,$5,$5) RETURNING *',
[randomUUID(), projectId, data.hypothesisRevisionId, data.kind, actor]
)
).rows[0],
'Created artifact'
);
await this.insertArtifactRevision(client, row.id, 1, data, author);
return this.artifact(client, row);
});
}
async getArtifact(id: string): Promise<ResearchArtifact> {
return this.artifact(
this.database,
await this.artifactRow(this.database, researchIdSchema.parse(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)));
}
async reviseArtifact(
id: string,
input: unknown,
actor: ResearchActor
): Promise<ResearchArtifact> {
researchIdSchema.parse(id);
const data = parseResearchInput(reviseResearchArtifactSchema, input);
const author = authorship(actor, data.contentOrigin);
return this.database.transaction(async client => {
const row = await this.lockArtifact(client, id);
active(row, 'Artifact');
this.requireFindingEvidence(row.kind, data.evidence);
const current = required(
(
await client.query(
'SELECT ordinal FROM analysis_artifact_revisions WHERE artifact_id=$1 ORDER BY ordinal DESC LIMIT 1',
[id]
)
).rows[0],
'Artifact revision'
);
expectRevision(current.ordinal, data.expectedRevision);
await this.insertArtifactRevision(client, id, data.expectedRevision + 1, data, author);
const updated = required(
(
await client.query(
'UPDATE analysis_artifacts SET updated_by=$2,updated_at=NOW() WHERE id=$1 RETURNING *',
[id, actor]
)
).rows[0],
'Artifact'
);
return this.artifact(client, updated);
});
}
async archiveArtifact(
id: string,
input: unknown,
actor: ResearchActor
): Promise<ResearchArtifact> {
researchIdSchema.parse(id);
const data = parseResearchInput(archiveResearchSchema, input);
researchActorSchema.parse(actor);
return this.database.transaction(async client => {
await this.lockArtifact(client, id);
const row = required(
(
await client.query(
'UPDATE analysis_artifacts SET archived_at=CASE WHEN $2 THEN COALESCE(archived_at,NOW()) ELSE NULL END,updated_by=$3,updated_at=NOW() WHERE id=$1 RETURNING *',
[id, data.archived, actor]
)
).rows[0],
'Artifact'
);
return this.artifact(client, row);
});
}
private async projectRow(database: Database, id: string, lock = false): Promise<QueryResultRow> {
return required(
(
await database.query(
`SELECT * FROM research_projects WHERE id=$1${lock ? ' FOR UPDATE' : ''}`,
[id]
)
).rows[0],
'Project'
);
}
private async hypothesisRow(
database: Database,
id: string,
lock = false
): Promise<QueryResultRow> {
return required(
(
await database.query(
`SELECT * FROM research_hypotheses WHERE id=$1${lock ? ' FOR UPDATE' : ''}`,
[id]
)
).rows[0],
'Hypothesis'
);
}
private async artifactRow(database: Database, id: string, lock = false): Promise<QueryResultRow> {
return required(
(
await database.query(
`SELECT * FROM analysis_artifacts WHERE id=$1${lock ? ' FOR UPDATE' : ''}`,
[id]
)
).rows[0],
'Artifact'
);
}
private async lockHypothesis(client: PoolClient, id: string): Promise<QueryResultRow> {
const row = await this.hypothesisRow(client, id);
active(await this.projectRow(client, row.project_id, true), 'Project');
return this.hypothesisRow(client, id, true);
}
private async lockArtifact(client: PoolClient, id: string): Promise<QueryResultRow> {
const row = await this.artifactRow(client, id);
active(await this.projectRow(client, row.project_id, true), 'Project');
return this.artifactRow(client, id, true);
}
private async hypothesis(database: Database, row: QueryResultRow): Promise<ResearchHypothesis> {
const latest = required(
(
await database.query(
'SELECT * FROM research_hypothesis_revisions WHERE hypothesis_id=$1 ORDER BY ordinal DESC LIMIT 1',
[row.id]
)
).rows[0],
'Hypothesis revision'
);
return {
id: row.id,
projectId: row.project_id,
ownerPrincipal: row.owner_principal,
updatedBy: row.updated_by,
updatedAt: iso(row.updated_at),
archived: row.archived_at !== null,
createdAt: iso(row.created_at),
latestRevision: hypothesisRevision(latest),
};
}
private async insertHypothesisRevision(
client: PoolClient,
id: string,
ordinal: number,
data: { title: string; proposition: string; validationCriteria: string },
author: ResearchAuthorship
): Promise<void> {
await client.query(
`INSERT INTO research_hypothesis_revisions(id,hypothesis_id,ordinal,title,proposition,validation_criteria,submitted_by,content_origin)
VALUES($1,$2,$3,$4,$5,$6,$7,$8)`,
[
randomUUID(),
id,
ordinal,
data.title,
data.proposition,
data.validationCriteria,
author.submittedBy,
author.contentOrigin,
]
);
}
private async artifact(database: Database, row: QueryResultRow): Promise<ResearchArtifact> {
const latest = required(
(
await database.query(
'SELECT * FROM analysis_artifact_revisions WHERE artifact_id=$1 ORDER BY ordinal DESC LIMIT 1',
[row.id]
)
).rows[0],
'Artifact revision'
);
return {
id: row.id,
projectId: row.project_id,
hypothesisRevisionId: row.hypothesis_revision_id,
kind: row.kind,
ownerPrincipal: row.owner_principal,
updatedBy: row.updated_by,
updatedAt: iso(row.updated_at),
archived: row.archived_at !== null,
createdAt: iso(row.created_at),
latestRevision: await this.artifactRevision(database, latest),
};
}
private async artifactRevision(
database: Database,
row: QueryResultRow
): Promise<ResearchArtifactRevision> {
const references = (
await database.query(
'SELECT * FROM analysis_evidence WHERE revision_id=$1 ORDER BY ordinal',
[row.id]
)
).rows;
const evidence = await Promise.all(
references.map(item =>
this.evidence.resolve(
{
runId: item.run_id,
metricsVersion: item.metrics_version,
metricPath: item.metric_path,
strategyVersionId: item.strategy_version_id,
},
database
)
)
);
return {
id: row.id,
artifactId: row.artifact_id,
ordinal: row.ordinal,
title: row.title,
body: row.body,
submittedBy: row.submitted_by,
contentOrigin: row.content_origin,
validationState: 'unvalidated',
evidenceState: evidence.length ? 'referenced' : 'none',
evidence,
createdAt: iso(row.created_at),
};
}
private requireFindingEvidence(kind: string, evidence: ResearchEvidenceReference[]): void {
if (kind === 'finding' && evidence.length === 0) {
throw new ResearchError(422, 'A finding requires at least one retained evidence reference');
}
}
private async insertArtifactRevision(
client: PoolClient,
id: string,
ordinal: number,
data: { title: string; body: string; evidence: ResearchEvidenceReference[] },
author: ResearchAuthorship
): Promise<void> {
// Validate using the authoritative reader; only references are persisted.
for (const reference of data.evidence) {
await this.evidence.resolve(reference, client);
}
const revisionId = randomUUID();
await client.query(
`INSERT INTO analysis_artifact_revisions(id,artifact_id,ordinal,title,body,submitted_by,content_origin)
VALUES($1,$2,$3,$4,$5,$6,$7)`,
[revisionId, id, ordinal, data.title, data.body, author.submittedBy, author.contentOrigin]
);
for (const [index, reference] of data.evidence.entries()) {
await client.query(
`INSERT INTO analysis_evidence(revision_id,ordinal,run_id,metrics_version,metric_path,strategy_version_id)
VALUES($1,$2,$3,$4,$5,$6)`,
[
revisionId,
index + 1,
reference.runId,
reference.metricsVersion,
reference.metricPath,
reference.strategyVersionId ?? null,
]
);
}
}
}