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, researchFindingSourceSchema, researchIdSchema, reviseResearchArtifactSchema, reviseResearchHypothesisSchema, updateResearchProjectSchema, } from '@stock-bot/stock-config/research'; import type { ResearchActor, ResearchArtifact, ResearchArtifactRevision, ResearchAuthorship, ResearchContentOrigin, ResearchEvidence, ResearchEvidenceReference, ResearchFindingSource, ResearchHypothesis, ResearchHypothesisRevision, ResearchProject, StrategyRecord, } from '@stock-bot/types'; import { lockResearchAgent } from './research-agent-budget'; import { ResearchError } from './research-errors'; import { ResearchEvidenceResolver } from './research-evidence'; import { StrategyCatalogService } from './strategy-catalog.service'; type Database = { query( 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.startsWith('agent:') && origin !== undefined && origin !== 'ai') { throw new ResearchError(403, 'Research principals must declare AI authorship'); } if (actor !== 'operator' && origin === 'human') { throw new ResearchError(403, 'Only operator credentials can declare human authorship'); } return { submittedBy: actor, contentOrigin: origin ?? (actor === 'operator' ? 'human' : actor.startsWith('agent:') ? 'ai' : '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`); } } 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; 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 { 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 { 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 { return project(await this.projectRow(this.database, researchIdSchema.parse(id))); } async updateProject(id: string, input: unknown, actor: ResearchActor): Promise { 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 => { await lockResearchAgent(client, actor); 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 { 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 { researchIdSchema.parse(projectId); researchIdSchema.parse(strategyId); researchActorSchema.parse(actor); await this.database.transaction(async client => { await lockResearchAgent(client, actor); 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 { researchIdSchema.parse(projectId); researchIdSchema.parse(strategyId); researchActorSchema.parse(actor); await this.database.transaction(async client => { await lockResearchAgent(client, actor); 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 { 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 { researchIdSchema.parse(projectId); const data = parseResearchInput(createResearchHypothesisSchema, input); const author = authorship(actor, data.contentOrigin); return this.database.transaction(async client => { await lockResearchAgent(client, actor); 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 { return this.hypothesis( this.database, await this.hypothesisRow(this.database, researchIdSchema.parse(id)) ); } async listHypothesisRevisions(id: string): Promise { 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 { researchIdSchema.parse(id); const data = parseResearchInput(reviseResearchHypothesisSchema, input); const author = authorship(actor, data.contentOrigin); return this.database.transaction(async client => { await lockResearchAgent(client, actor); 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 { researchIdSchema.parse(id); const data = parseResearchInput(archiveResearchSchema, input); researchActorSchema.parse(actor); return this.database.transaction(async client => { await lockResearchAgent(client, actor); 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 { 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, input: unknown, actor: ResearchActor ): Promise { 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 => { await lockResearchAgent(client, actor); 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' ); 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 { researchIdSchema.parse(id); return this.database.transaction(async client => { await client.query('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY'); return this.artifact(client, await this.artifactRow(client, id)); }); } async listArtifactRevisions(id: string): Promise { researchIdSchema.parse(id); 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, input: unknown, actor: ResearchActor ): Promise { researchIdSchema.parse(id); const data = parseResearchInput(reviseResearchArtifactSchema, input); const author = authorship(actor, data.contentOrigin); return this.database.transaction(async client => { await lockResearchAgent(client, actor); const row = await this.lockArtifact(client, id); active(row, 'Artifact'); this.requireFindingEvidence(row.kind, data.evidence); const current = required( ( await client.query( '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); 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( 'UPDATE analysis_artifacts SET updated_by=$2,updated_at=NOW() WHERE id=$1 RETURNING *', [id, actor] ) ).rows[0], 'Artifact' ); return this.artifact(client, updated, revision); }); } async archiveArtifact( id: string, input: unknown, actor: ResearchActor ): Promise { researchIdSchema.parse(id); const data = parseResearchInput(archiveResearchSchema, input); researchActorSchema.parse(actor); return this.database.transaction(async client => { await lockResearchAgent(client, actor); 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 { 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 { 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 { 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 { 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 { 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 { 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 { 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, resolved?: ResearchArtifactRevision ): Promise { const latest = resolved ?? (await this.artifactRevision( database, required( ( await database.query( 'SELECT * FROM analysis_artifact_revisions WHERE artifact_id=$1 ORDER BY ordinal DESC LIMIT 1', [row.id] ) ).rows[0], 'Artifact revision' ) )); 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: latest, }; } private async artifactRevision( database: Database, row: QueryResultRow ): Promise { const references: ResearchEvidenceReference[] = ( await database.query( 'SELECT * FROM analysis_evidence WHERE revision_id=$1 ORDER BY ordinal', [row.id] ) ).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) { 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[]; source: ResearchFindingSource | null; }, author: ResearchAuthorship ): Promise { // Validate once per revision; only references are persisted. const references = data.evidence.map(reference => ({ ...reference, strategyVersionId: reference.strategyVersionId ?? null, })); const evidence = await this.evidence.resolveAll(references, data.source, client); const revisionId = randomUUID(); 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( `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, ] ); } return artifactRevisionValue(row, evidence, data.source); } }