feat(research): add projects and revisioned evidence-linked findings
This commit is contained in:
parent
618fb9e33c
commit
ee45257507
22 changed files with 2947 additions and 17 deletions
|
|
@ -24,6 +24,10 @@
|
|||
"./canonical-research": {
|
||||
"types": "./dist/contracts/canonical-research.d.ts",
|
||||
"default": "./dist/contracts/canonical-research.js"
|
||||
},
|
||||
"./research": {
|
||||
"types": "./dist/contracts/research.d.ts",
|
||||
"default": "./dist/contracts/research.js"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
|
|
|
|||
136
apps/stock/config/src/contracts/research.ts
Normal file
136
apps/stock/config/src/contracts/research.ts
Normal file
|
|
@ -0,0 +1,136 @@
|
|||
import { z } from 'zod';
|
||||
import { assertStrategyJsonText } from './strategy';
|
||||
|
||||
export const researchIdSchema = z.string().uuid();
|
||||
export const researchActorSchema = z.enum(['operator', 'service']);
|
||||
const origin = z.enum(['human', 'ai', 'unknown']).optional();
|
||||
const title = z.string().trim().min(1);
|
||||
const ordinal = z.number().int().positive().max(2147483647);
|
||||
export const createResearchProjectSchema = z
|
||||
.object({
|
||||
title,
|
||||
description: z.string().default(''),
|
||||
})
|
||||
.strict();
|
||||
export const updateResearchProjectSchema = z
|
||||
.object({
|
||||
expectedRevision: ordinal,
|
||||
title: title.optional(),
|
||||
description: z.string().optional(),
|
||||
archived: z.boolean().optional(),
|
||||
})
|
||||
.strict();
|
||||
export const archiveResearchSchema = z.object({ archived: z.boolean() }).strict();
|
||||
export const createResearchHypothesisSchema = z
|
||||
.object({
|
||||
title,
|
||||
proposition: z.string().trim().min(1),
|
||||
validationCriteria: z.string().default(''),
|
||||
contentOrigin: origin,
|
||||
})
|
||||
.strict();
|
||||
export const reviseResearchHypothesisSchema = createResearchHypothesisSchema
|
||||
.extend({
|
||||
expectedRevision: ordinal,
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const canonicalResearchMetricPaths = [
|
||||
'analytics.metrics.totalReturn',
|
||||
'analytics.metrics.cagr',
|
||||
'analytics.metrics.maxDrawdown',
|
||||
'analytics.metrics.exposureTime',
|
||||
'analytics.metrics.volatility',
|
||||
'analytics.metrics.downsideDeviation',
|
||||
'analytics.metrics.sharpeRatio',
|
||||
'analytics.metrics.sortinoRatio',
|
||||
'analytics.metrics.var95',
|
||||
'analytics.metrics.cvar95',
|
||||
'analytics.metrics.var99',
|
||||
'analytics.metrics.alpha',
|
||||
'analytics.metrics.beta',
|
||||
'analytics.metrics.informationRatio',
|
||||
'analytics.metrics.roundTripCount',
|
||||
'analytics.metrics.winRate',
|
||||
'analytics.metrics.profitFactor',
|
||||
'analytics.metrics.avgWin',
|
||||
'analytics.metrics.avgLoss',
|
||||
'analytics.fillCount',
|
||||
] as const;
|
||||
export const legacyResearchMetricPaths = [
|
||||
'metrics.totalReturn',
|
||||
'metrics.sharpeRatio',
|
||||
'metrics.maxDrawdown',
|
||||
'metrics.winRate',
|
||||
'metrics.totalTrades',
|
||||
'metrics.profitFactor',
|
||||
'metrics.avgWin',
|
||||
'metrics.avgLoss',
|
||||
'analytics.exposureTime',
|
||||
] as const;
|
||||
export const researchEvidenceReferenceSchema = z.discriminatedUnion('metricsVersion', [
|
||||
z
|
||||
.object({
|
||||
runId: researchIdSchema,
|
||||
metricsVersion: z.literal('canonical-analytics/v1'),
|
||||
metricPath: z.enum(canonicalResearchMetricPaths),
|
||||
strategyVersionId: researchIdSchema.nullable().optional(),
|
||||
})
|
||||
.strict(),
|
||||
z
|
||||
.object({
|
||||
runId: researchIdSchema,
|
||||
metricsVersion: z.literal('legacy-display/v1'),
|
||||
metricPath: z.enum(legacyResearchMetricPaths),
|
||||
strategyVersionId: researchIdSchema.nullable().optional(),
|
||||
})
|
||||
.strict(),
|
||||
]);
|
||||
const evidence = z
|
||||
.array(researchEvidenceReferenceSchema)
|
||||
.default([])
|
||||
.superRefine((items, ctx) => {
|
||||
const keys = new Set<string>();
|
||||
for (const item of items) {
|
||||
const key = `${item.runId}:${item.metricsVersion}:${item.metricPath}`;
|
||||
if (keys.has(key)) {
|
||||
ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Duplicate evidence reference' });
|
||||
}
|
||||
keys.add(key);
|
||||
}
|
||||
});
|
||||
export const createResearchArtifactSchema = z
|
||||
.object({
|
||||
kind: z.enum(['note', 'finding']),
|
||||
hypothesisRevisionId: researchIdSchema.nullable().default(null),
|
||||
title,
|
||||
body: z.string(),
|
||||
contentOrigin: origin,
|
||||
evidence,
|
||||
})
|
||||
.strict();
|
||||
export const reviseResearchArtifactSchema = z
|
||||
.object({
|
||||
expectedRevision: ordinal,
|
||||
title,
|
||||
body: z.string(),
|
||||
contentOrigin: origin,
|
||||
evidence,
|
||||
})
|
||||
.strict();
|
||||
|
||||
/** Shared text validity only; neither financial calculations nor code evaluation. */
|
||||
export function parseResearchInput<S extends z.ZodTypeAny>(schema: S, input: unknown): z.output<S> {
|
||||
try {
|
||||
assertStrategyJsonText(input);
|
||||
} catch {
|
||||
throw new z.ZodError([
|
||||
{
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: [],
|
||||
message: 'Research metadata must contain valid JSON text',
|
||||
},
|
||||
]);
|
||||
}
|
||||
return schema.parse(input);
|
||||
}
|
||||
|
|
@ -59,7 +59,8 @@ export async function runMigrations(container: IServiceContainer): Promise<void>
|
|||
f === '16-strategy-catalog.sql' ||
|
||||
f === '17-research-retention.sql' ||
|
||||
f === '18-backtest-strategy-versions.sql' ||
|
||||
f === '19-canonical-research.sql')
|
||||
f === '19-canonical-research.sql' ||
|
||||
f === '20-research-workspace.sql')
|
||||
) // Explicit additive migration allowlist; never replay destructive init migrations
|
||||
.sort();
|
||||
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ import { createExchangeRoutes } from './exchange.routes';
|
|||
import { createHealthRoutes } from './health.routes';
|
||||
import { createMonitoringRoutes } from './monitoring.routes';
|
||||
import { createPipelineRoutes } from './pipeline.routes';
|
||||
import { createResearchRoutes } from './research.routes';
|
||||
import { createStrategyRoutes } from './strategies.routes';
|
||||
|
||||
export function createRoutes(
|
||||
|
|
@ -51,6 +52,7 @@ export function createRoutes(
|
|||
app.route('/', backtestV2Routes); // V2 routes also mounted at root
|
||||
app.route('/', createDatasetRoutes(container));
|
||||
app.route('/', createStrategyRoutes(container));
|
||||
app.route('/', createResearchRoutes(container));
|
||||
|
||||
return app;
|
||||
}
|
||||
|
|
|
|||
190
apps/stock/web-api/src/routes/research.routes.ts
Normal file
190
apps/stock/web-api/src/routes/research.routes.ts
Normal file
|
|
@ -0,0 +1,190 @@
|
|||
import { Hono, type MiddlewareHandler } from 'hono';
|
||||
import { z } from 'zod';
|
||||
import { getCredentialHttpPrincipal } from '@stock-bot/di';
|
||||
import type { IServiceContainer } from '@stock-bot/services';
|
||||
import { archiveResearchSchema, parseResearchInput } from '@stock-bot/stock-config/research';
|
||||
import { ResearchError } from '../services/research-errors';
|
||||
import { ResearchService } from '../services/research.service';
|
||||
|
||||
const emptyBody = z.object({}).strict();
|
||||
function includeArchived(value: string | undefined): boolean {
|
||||
if (value === undefined || value === 'false') {
|
||||
return false;
|
||||
}
|
||||
if (value === 'true') {
|
||||
return true;
|
||||
}
|
||||
throw new ResearchError(400, 'includeArchived must be true or false');
|
||||
}
|
||||
async function noMutationBody(request: Request): Promise<void> {
|
||||
const body = await request.text();
|
||||
if (body !== '') {
|
||||
emptyBody.parse(JSON.parse(body));
|
||||
}
|
||||
}
|
||||
|
||||
/** Research metadata only; the mounted security layer owns authenticated read access. */
|
||||
export function createResearchRoutes(container: IServiceContainer) {
|
||||
const app = new Hono();
|
||||
const service = new ResearchService(container);
|
||||
const credentials: MiddlewareHandler = async (c, next) => {
|
||||
c.header('Cache-Control', 'no-store');
|
||||
if (!['GET', 'HEAD'].includes(c.req.method) && !getCredentialHttpPrincipal(c.req.raw)) {
|
||||
return c.json({ error: 'Verified credential principal required' }, 401);
|
||||
}
|
||||
await next();
|
||||
return undefined;
|
||||
};
|
||||
for (const path of [
|
||||
'/api/v2/research-projects',
|
||||
'/api/v2/research-projects/*',
|
||||
'/api/v2/hypotheses/*',
|
||||
'/api/v2/analysis-artifacts/*',
|
||||
]) {
|
||||
app.use(path, credentials);
|
||||
}
|
||||
app.onError((error, c) => {
|
||||
if (error instanceof ResearchError) {
|
||||
return c.json({ error: error.message }, error.status);
|
||||
}
|
||||
if (error instanceof z.ZodError || error instanceof SyntaxError) {
|
||||
return c.json({ error: 'Invalid research request' }, 400);
|
||||
}
|
||||
container.logger.error('Research operation failed', { error });
|
||||
return c.json({ error: 'Research workspace unavailable' }, 500);
|
||||
});
|
||||
const actor = (request: Request) => {
|
||||
const principal = getCredentialHttpPrincipal(request);
|
||||
if (!principal) {
|
||||
throw new ResearchError(401, 'Verified credential principal required');
|
||||
}
|
||||
return principal;
|
||||
};
|
||||
|
||||
app.get('/api/v2/research-projects', async c =>
|
||||
c.json({
|
||||
projects: await service.listProjects(includeArchived(c.req.query('includeArchived'))),
|
||||
})
|
||||
);
|
||||
app.post('/api/v2/research-projects', async c =>
|
||||
c.json({ project: await service.createProject(await c.req.json(), actor(c.req.raw)) }, 201)
|
||||
);
|
||||
app.get('/api/v2/research-projects/:id', async c =>
|
||||
c.json({ project: await service.getProject(c.req.param('id')) })
|
||||
);
|
||||
app.patch('/api/v2/research-projects/:id', async c =>
|
||||
c.json({
|
||||
project: await service.updateProject(c.req.param('id'), await c.req.json(), actor(c.req.raw)),
|
||||
})
|
||||
);
|
||||
app.get('/api/v2/research-projects/:id/strategies', async c =>
|
||||
c.json({ strategies: await service.listProjectStrategies(c.req.param('id')) })
|
||||
);
|
||||
app.put('/api/v2/research-projects/:id/strategies/:strategyId', async c => {
|
||||
await noMutationBody(c.req.raw);
|
||||
await service.linkStrategy(c.req.param('id'), c.req.param('strategyId'), actor(c.req.raw));
|
||||
return c.body(null, 204);
|
||||
});
|
||||
app.delete('/api/v2/research-projects/:id/strategies/:strategyId', async c => {
|
||||
await noMutationBody(c.req.raw);
|
||||
await service.unlinkStrategy(c.req.param('id'), c.req.param('strategyId'), actor(c.req.raw));
|
||||
return c.body(null, 204);
|
||||
});
|
||||
|
||||
app.get('/api/v2/research-projects/:id/hypotheses', async c =>
|
||||
c.json({
|
||||
hypotheses: await service.listHypotheses(
|
||||
c.req.param('id'),
|
||||
includeArchived(c.req.query('includeArchived'))
|
||||
),
|
||||
})
|
||||
);
|
||||
app.post('/api/v2/research-projects/:id/hypotheses', async c =>
|
||||
c.json(
|
||||
{
|
||||
hypothesis: await service.createHypothesis(
|
||||
c.req.param('id'),
|
||||
await c.req.json(),
|
||||
actor(c.req.raw)
|
||||
),
|
||||
},
|
||||
201
|
||||
)
|
||||
);
|
||||
app.get('/api/v2/hypotheses/:id', async c =>
|
||||
c.json({ hypothesis: await service.getHypothesis(c.req.param('id')) })
|
||||
);
|
||||
app.get('/api/v2/hypotheses/:id/revisions', async c =>
|
||||
c.json({ revisions: await service.listHypothesisRevisions(c.req.param('id')) })
|
||||
);
|
||||
app.post('/api/v2/hypotheses/:id/revisions', async c =>
|
||||
c.json(
|
||||
{
|
||||
hypothesis: await service.reviseHypothesis(
|
||||
c.req.param('id'),
|
||||
await c.req.json(),
|
||||
actor(c.req.raw)
|
||||
),
|
||||
},
|
||||
201
|
||||
)
|
||||
);
|
||||
app.patch('/api/v2/hypotheses/:id', async c =>
|
||||
c.json({
|
||||
hypothesis: await service.archiveHypothesis(
|
||||
c.req.param('id'),
|
||||
parseResearchInput(archiveResearchSchema, await c.req.json()),
|
||||
actor(c.req.raw)
|
||||
),
|
||||
})
|
||||
);
|
||||
|
||||
app.get('/api/v2/research-projects/:id/analysis-artifacts', async c =>
|
||||
c.json({
|
||||
artifacts: await service.listArtifacts(
|
||||
c.req.param('id'),
|
||||
includeArchived(c.req.query('includeArchived'))
|
||||
),
|
||||
})
|
||||
);
|
||||
app.post('/api/v2/research-projects/:id/analysis-artifacts', async c =>
|
||||
c.json(
|
||||
{
|
||||
artifact: await service.createArtifact(
|
||||
c.req.param('id'),
|
||||
await c.req.json(),
|
||||
actor(c.req.raw)
|
||||
),
|
||||
},
|
||||
201
|
||||
)
|
||||
);
|
||||
app.get('/api/v2/analysis-artifacts/:id', async c =>
|
||||
c.json({ artifact: await service.getArtifact(c.req.param('id')) })
|
||||
);
|
||||
app.get('/api/v2/analysis-artifacts/:id/revisions', async c =>
|
||||
c.json({ revisions: await service.listArtifactRevisions(c.req.param('id')) })
|
||||
);
|
||||
app.post('/api/v2/analysis-artifacts/:id/revisions', async c =>
|
||||
c.json(
|
||||
{
|
||||
artifact: await service.reviseArtifact(
|
||||
c.req.param('id'),
|
||||
await c.req.json(),
|
||||
actor(c.req.raw)
|
||||
),
|
||||
},
|
||||
201
|
||||
)
|
||||
);
|
||||
app.patch('/api/v2/analysis-artifacts/:id', async c =>
|
||||
c.json({
|
||||
artifact: await service.archiveArtifact(
|
||||
c.req.param('id'),
|
||||
parseResearchInput(archiveResearchSchema, await c.req.json()),
|
||||
actor(c.req.raw)
|
||||
),
|
||||
})
|
||||
);
|
||||
return app;
|
||||
}
|
||||
|
|
@ -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;
|
||||
|
|
|
|||
8
apps/stock/web-api/src/services/research-errors.ts
Normal file
8
apps/stock/web-api/src/services/research-errors.ts
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
export class ResearchError extends Error {
|
||||
constructor(
|
||||
public readonly status: 400 | 401 | 403 | 404 | 409 | 422,
|
||||
message: string
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
161
apps/stock/web-api/src/services/research-evidence.ts
Normal file
161
apps/stock/web-api/src/services/research-evidence.ts
Normal 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);
|
||||
}
|
||||
}
|
||||
631
apps/stock/web-api/src/services/research.service.ts
Normal file
631
apps/stock/web-api/src/services/research.service.ts
Normal 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,
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue