582 lines
20 KiB
TypeScript
582 lines
20 KiB
TypeScript
import { createHash, randomUUID } from 'node:crypto';
|
|
import type { PoolClient, QueryResultRow } from 'pg';
|
|
import { z } from 'zod';
|
|
import { requireServices, type IServiceContainer } from '@stock-bot/services';
|
|
import { researchActorSchema } from '@stock-bot/stock-config/research';
|
|
import {
|
|
assertStrategyJsonText,
|
|
builtinCatalogDescriptors,
|
|
canonicalStrategyJson,
|
|
parseStrategyVersionPackage,
|
|
validateStrategyParameters,
|
|
} from '@stock-bot/stock-config/strategy';
|
|
import type {
|
|
ParameterValidationResult,
|
|
ResearchActor,
|
|
StrategyRecord,
|
|
StrategyReviewEvent,
|
|
StrategyVersionPackage,
|
|
StrategyVersionSummary,
|
|
} from '@stock-bot/types';
|
|
import { lockResearchAgent } from './research-agent-budget';
|
|
|
|
export type { StrategyRecord, StrategyVersionSummary } from '@stock-bot/types';
|
|
|
|
export type StrategyActor = ResearchActor;
|
|
export class StrategyCatalogError extends Error {
|
|
constructor(
|
|
public readonly status: 400 | 401 | 403 | 404 | 409,
|
|
message: string
|
|
) {
|
|
super(message);
|
|
}
|
|
}
|
|
const id = z.string().uuid();
|
|
const actorSchema = researchActorSchema;
|
|
const keySchema = z.string().regex(/^[\x21-\x7e]{1,200}$/);
|
|
const createSchema = z
|
|
.object({ name: z.string().trim().min(1), description: z.string().default('') })
|
|
.strict();
|
|
const updateSchema = z
|
|
.object({
|
|
name: z.string().trim().min(1).optional(),
|
|
description: z.string().optional(),
|
|
archived: z.boolean().optional(),
|
|
})
|
|
.strict();
|
|
const reviewSchema = z
|
|
.object({ decision: z.enum(['approve', 'revoke']), reason: z.string().trim().min(1) })
|
|
.strict();
|
|
const hash = (value: string) => createHash('sha256').update(value, 'utf8').digest('hex');
|
|
function stable(value: unknown): string {
|
|
try {
|
|
assertStrategyJsonText(value);
|
|
return canonicalStrategyJson(value);
|
|
} catch {
|
|
throw new StrategyCatalogError(400, 'Publication metadata must be JSON');
|
|
}
|
|
}
|
|
function checkText(value: unknown): void {
|
|
try {
|
|
assertStrategyJsonText(value);
|
|
} catch {
|
|
throw new StrategyCatalogError(400, 'Strategy metadata must contain valid JSON text');
|
|
}
|
|
}
|
|
function checkedPackage(value: unknown): StrategyVersionPackage {
|
|
let pkg;
|
|
try {
|
|
pkg = parseStrategyVersionPackage(value);
|
|
} catch (error) {
|
|
throw new StrategyCatalogError(
|
|
400,
|
|
error instanceof Error ? error.message : 'Invalid strategy package'
|
|
);
|
|
}
|
|
if (
|
|
hash(pkg.artifact.content) !== pkg.artifact.sha256 ||
|
|
hash(pkg.dependencyLock.content) !== pkg.dependencyLock.sha256
|
|
) {
|
|
throw new StrategyCatalogError(400, 'Strategy artifact or dependency lock hash mismatch');
|
|
}
|
|
return pkg;
|
|
}
|
|
const metadata = `v.id,v.strategy_id,v.ordinal,v.parent_version_id,v.created_by,v.origin,v.created_at,
|
|
(v.envelope #- '{artifact,content}' #- '{dependencyLock,content}') AS package,
|
|
COALESCE((SELECT CASE r.decision WHEN 'approve' THEN 'approved' ELSE 'revoked' END
|
|
FROM strategy_review_events r WHERE r.version_id=v.id ORDER BY r.ordinal DESC LIMIT 1),'pending') AS review_status`;
|
|
const strategy = (row: QueryResultRow): StrategyRecord => ({
|
|
id: row.id,
|
|
name: row.name,
|
|
description: row.description,
|
|
ownerPrincipal: row.owner_principal,
|
|
updatedBy: row.updated_by,
|
|
archived: row.archived_at !== null,
|
|
createdAt: new Date(row.created_at).toISOString(),
|
|
updatedAt: new Date(row.updated_at).toISOString(),
|
|
});
|
|
const version = (row: QueryResultRow): StrategyVersionSummary => ({
|
|
id: row.id,
|
|
strategyId: row.strategy_id,
|
|
ordinal: Number(row.ordinal),
|
|
parentVersionId: row.parent_version_id,
|
|
createdBy: row.created_by,
|
|
origin: row.origin,
|
|
createdAt: new Date(row.created_at).toISOString(),
|
|
package: row.package,
|
|
reviewStatus: row.review_status,
|
|
runnable: false,
|
|
reason:
|
|
row.origin === 'builtin'
|
|
? row.review_status === 'approved'
|
|
? 'Configure a supported canonical dataset and explicit financial policy before execution.'
|
|
: 'An operator must approve this built-in version before configuring execution.'
|
|
: row.review_status === 'revoked'
|
|
? 'Candidate is revoked; new research admissions are unavailable.'
|
|
: row.package.execution?.kind === 'isolated-candidate/v1'
|
|
? 'Candidate runs only in the isolated research host. Configure retained data and financial policy; approval never selects trusted execution.'
|
|
: 'Publish a new immutable version with an isolated execution declaration and author-declared warmup before execution.',
|
|
});
|
|
class ReceiptRace extends Error {}
|
|
|
|
export class StrategyCatalogService {
|
|
private readonly database;
|
|
constructor(container: IServiceContainer) {
|
|
this.database = requireServices(container, 'postgres').postgres;
|
|
}
|
|
|
|
async createStrategy(
|
|
input: { name: string; description?: string },
|
|
actor: StrategyActor
|
|
): Promise<StrategyRecord> {
|
|
const data = createSchema.parse(input);
|
|
checkText(data);
|
|
const row = (
|
|
await this.database.query(
|
|
'INSERT INTO strategies(id,name,description,owner_principal,updated_by) VALUES($1,$2,$3,$4,$4) RETURNING *',
|
|
[randomUUID(), data.name, data.description, actorSchema.parse(actor)]
|
|
)
|
|
).rows[0];
|
|
if (!row) {
|
|
throw new Error('Strategy insertion returned no row');
|
|
}
|
|
return strategy(row);
|
|
}
|
|
async updateStrategy(
|
|
strategyId: string,
|
|
input: { name?: string; description?: string; archived?: boolean },
|
|
actor: StrategyActor
|
|
): Promise<StrategyRecord> {
|
|
actorSchema.parse(actor);
|
|
const data = updateSchema.parse(input);
|
|
checkText(data);
|
|
return this.database.transaction(async client => {
|
|
await lockResearchAgent(client, actor);
|
|
const old = await this.lock(client, strategyId, false);
|
|
const row = (
|
|
await client.query(
|
|
`UPDATE strategies SET name=$2,description=$3,archived_at=$4,updated_by=$5,updated_at=NOW() WHERE id=$1 RETURNING *`,
|
|
[
|
|
old.id,
|
|
data.name ?? old.name,
|
|
data.description ?? old.description,
|
|
data.archived === undefined
|
|
? old.archived_at
|
|
: data.archived
|
|
? (old.archived_at ?? new Date())
|
|
: null,
|
|
actor,
|
|
]
|
|
)
|
|
).rows[0];
|
|
if (!row) {
|
|
throw new Error('Strategy update returned no row');
|
|
}
|
|
return strategy(row);
|
|
});
|
|
}
|
|
async listStrategies(agentId?: string): Promise<StrategyRecord[]> {
|
|
if (agentId !== undefined) {
|
|
return (
|
|
await this.database.query(
|
|
`SELECT s.* FROM strategies s
|
|
JOIN research_agents a ON a.id = $1
|
|
WHERE s.owner_principal = $1
|
|
OR EXISTS (
|
|
SELECT 1 FROM research_project_strategies rps
|
|
WHERE rps.strategy_id = s.id AND (a.policy->'allowedProjectIds' ? rps.project_id::text)
|
|
)
|
|
OR EXISTS (
|
|
SELECT 1 FROM strategy_versions sv
|
|
JOIN backtests b ON b.strategy_version_id = sv.id
|
|
WHERE sv.strategy_id = s.id
|
|
AND EXISTS (
|
|
SELECT 1 FROM jsonb_array_elements(a.policy->'grants') g
|
|
WHERE g->>'backtestId' = b.id::text
|
|
)
|
|
)
|
|
ORDER BY s.created_at DESC, s.id`,
|
|
[agentId]
|
|
)
|
|
).rows.map(strategy);
|
|
}
|
|
return (
|
|
await this.database.query('SELECT * FROM strategies ORDER BY created_at DESC,id')
|
|
).rows.map(strategy);
|
|
}
|
|
async getStrategy(strategyId: string): Promise<StrategyRecord> {
|
|
const row = (
|
|
await this.database.query('SELECT * FROM strategies WHERE id=$1', [id.parse(strategyId)])
|
|
).rows[0];
|
|
if (!row) {
|
|
throw new StrategyCatalogError(404, 'Strategy not found');
|
|
}
|
|
return strategy(row);
|
|
}
|
|
async listVersions(strategyId: string): Promise<StrategyVersionSummary[]> {
|
|
await this.getStrategy(strategyId);
|
|
return (
|
|
await this.database.query(
|
|
`SELECT ${metadata} FROM strategy_versions v WHERE v.strategy_id=$1 ORDER BY v.ordinal DESC`,
|
|
[strategyId]
|
|
)
|
|
).rows.map(version);
|
|
}
|
|
async getVersion(versionId: string): Promise<StrategyVersionSummary> {
|
|
const row = (
|
|
await this.database.query(`SELECT ${metadata} FROM strategy_versions v WHERE v.id=$1`, [
|
|
id.parse(versionId),
|
|
])
|
|
).rows[0];
|
|
if (!row) {
|
|
throw new StrategyCatalogError(404, 'Strategy version not found');
|
|
}
|
|
return version(row);
|
|
}
|
|
async getVersionArtifact(
|
|
versionId: string,
|
|
database: {
|
|
query(text: string, values?: unknown[]): Promise<{ rows: QueryResultRow[] }>;
|
|
} = this.database
|
|
): Promise<StrategyVersionPackage> {
|
|
const row = (
|
|
await database.query('SELECT envelope FROM strategy_versions WHERE id=$1', [
|
|
id.parse(versionId),
|
|
])
|
|
).rows[0];
|
|
if (!row) {
|
|
throw new StrategyCatalogError(404, 'Strategy version not found');
|
|
}
|
|
return checkedPackage(row.envelope);
|
|
}
|
|
async getVersionReviews(versionId: string): Promise<StrategyReviewEvent[]> {
|
|
await this.getVersion(versionId);
|
|
return (
|
|
await this.database.query(
|
|
'SELECT id,ordinal,decision,actor,reason,created_at FROM strategy_review_events WHERE version_id=$1 ORDER BY ordinal',
|
|
[versionId]
|
|
)
|
|
).rows.map(row => ({
|
|
id: row.id,
|
|
ordinal: Number(row.ordinal),
|
|
decision: row.decision as 'approve' | 'revoke',
|
|
actor: 'operator' as const,
|
|
reason: row.reason as string,
|
|
createdAt: new Date(row.created_at).toISOString(),
|
|
}));
|
|
}
|
|
async validateVersionParameters(
|
|
versionId: string,
|
|
input: unknown
|
|
): Promise<ParameterValidationResult> {
|
|
const pkg = await this.getVersionArtifact(versionId);
|
|
let parameters;
|
|
try {
|
|
parameters = validateStrategyParameters(pkg, input);
|
|
} catch (error) {
|
|
throw new StrategyCatalogError(
|
|
400,
|
|
error instanceof Error ? error.message : 'Invalid strategy parameters'
|
|
);
|
|
}
|
|
return {
|
|
parameters,
|
|
runnable: false as const,
|
|
reason: (await this.getVersion(versionId)).reason,
|
|
};
|
|
}
|
|
private async lock(
|
|
client: PoolClient,
|
|
strategyId: string,
|
|
active = true
|
|
): Promise<QueryResultRow> {
|
|
const row = (
|
|
await client.query('SELECT * FROM strategies WHERE id=$1 FOR UPDATE', [id.parse(strategyId)])
|
|
).rows[0];
|
|
if (!row) {
|
|
throw new StrategyCatalogError(404, 'Strategy not found');
|
|
}
|
|
if (active && row.archived_at !== null) {
|
|
throw new StrategyCatalogError(409, 'Strategy is archived');
|
|
}
|
|
return row;
|
|
}
|
|
private async receipt(
|
|
database: { query(text: string, values?: unknown[]): Promise<{ rows: QueryResultRow[] }> },
|
|
actor: StrategyActor,
|
|
key: string,
|
|
fingerprint: string
|
|
): Promise<string | null> {
|
|
const row = (
|
|
await database.query(
|
|
'SELECT id,submission_fingerprint FROM strategy_versions WHERE created_by=$1 AND submission_key=$2',
|
|
[actor, key]
|
|
)
|
|
).rows[0];
|
|
if (!row) {
|
|
return null;
|
|
}
|
|
if (row.submission_fingerprint !== fingerprint) {
|
|
throw new StrategyCatalogError(
|
|
409,
|
|
'Idempotency key was already used with different publication content'
|
|
);
|
|
}
|
|
return row.id;
|
|
}
|
|
private async publication(
|
|
actor: StrategyActor,
|
|
key: string,
|
|
fingerprint: string,
|
|
work: (client: PoolClient) => Promise<string>
|
|
): Promise<StrategyVersionSummary> {
|
|
actorSchema.parse(actor);
|
|
keySchema.parse(key);
|
|
let versionId: string;
|
|
try {
|
|
versionId = await this.database.transaction(async client => {
|
|
await lockResearchAgent(client, actor);
|
|
const old = await this.receipt(client, actor, key, fingerprint);
|
|
return old ?? (await work(client));
|
|
});
|
|
} catch (error) {
|
|
if (!(error instanceof ReceiptRace)) {
|
|
throw error;
|
|
}
|
|
// Rollback also removes a losing clone/seed's newly-created strategy.
|
|
const winner = await this.receipt(this.database, actor, key, fingerprint);
|
|
if (!winner) {
|
|
throw new StrategyCatalogError(
|
|
409,
|
|
'Concurrent publication disappeared; retry the same key'
|
|
);
|
|
}
|
|
versionId = winner;
|
|
}
|
|
return this.getVersion(versionId);
|
|
}
|
|
private async insertVersion(
|
|
client: PoolClient,
|
|
strategyId: string,
|
|
pkg: StrategyVersionPackage,
|
|
parentVersionId: string | null,
|
|
actor: StrategyActor,
|
|
origin: 'candidate' | 'builtin',
|
|
key: string,
|
|
fingerprint: string
|
|
): Promise<string> {
|
|
if (parentVersionId !== null) {
|
|
const parent = await client.query('SELECT id FROM strategy_versions WHERE id=$1', [
|
|
id.parse(parentVersionId),
|
|
]);
|
|
if (!parent.rows[0]) {
|
|
throw new StrategyCatalogError(404, 'Parent strategy version not found');
|
|
}
|
|
}
|
|
const row = (
|
|
await client.query(
|
|
`INSERT INTO strategy_versions(id,strategy_id,ordinal,parent_version_id,envelope,created_by,origin,submission_key,submission_fingerprint)
|
|
SELECT $1,$2,COALESCE(MAX(ordinal),0)+1,$3,$4::jsonb,$5,$6,$7,$8 FROM strategy_versions WHERE strategy_id=$2
|
|
ON CONFLICT(created_by,submission_key) DO NOTHING RETURNING id`,
|
|
[
|
|
randomUUID(),
|
|
strategyId,
|
|
parentVersionId,
|
|
JSON.stringify(pkg),
|
|
actor,
|
|
origin,
|
|
key,
|
|
fingerprint,
|
|
]
|
|
)
|
|
).rows[0];
|
|
if (!row) {
|
|
throw new ReceiptRace();
|
|
}
|
|
return row.id;
|
|
}
|
|
async publishVersion(
|
|
strategyId: string,
|
|
input: unknown,
|
|
parentVersionId: string | null,
|
|
actor: StrategyActor,
|
|
key: string
|
|
): Promise<StrategyVersionSummary> {
|
|
id.parse(strategyId);
|
|
if (parentVersionId !== null) {
|
|
id.parse(parentVersionId);
|
|
}
|
|
const fingerprint = hash(
|
|
stable({ kind: 'publish', strategyId, parentVersionId, origin: 'candidate', package: input })
|
|
);
|
|
return this.publication(actor, key, fingerprint, async client => {
|
|
const parent = await this.lock(client, strategyId, false);
|
|
const old = await this.receipt(client, actor, key, fingerprint);
|
|
if (old) {
|
|
return old;
|
|
}
|
|
if (parent.archived_at !== null) {
|
|
throw new StrategyCatalogError(409, 'Strategy is archived');
|
|
}
|
|
const pkg = checkedPackage(input);
|
|
let lineageId = parentVersionId;
|
|
if (lineageId === null) {
|
|
lineageId =
|
|
(
|
|
await client.query(
|
|
'SELECT id FROM strategy_versions WHERE strategy_id=$1 ORDER BY ordinal DESC LIMIT 1',
|
|
[strategyId]
|
|
)
|
|
).rows[0]?.id ?? null;
|
|
} else {
|
|
const lineage = (
|
|
await client.query('SELECT strategy_id FROM strategy_versions WHERE id=$1', [lineageId])
|
|
).rows[0];
|
|
if (!lineage) {
|
|
throw new StrategyCatalogError(404, 'Parent strategy version not found');
|
|
}
|
|
if (lineage.strategy_id !== strategyId) {
|
|
throw new StrategyCatalogError(
|
|
400,
|
|
'Publication parent must belong to the same strategy; use clone for cross-strategy lineage'
|
|
);
|
|
}
|
|
}
|
|
return this.insertVersion(
|
|
client,
|
|
strategyId,
|
|
pkg,
|
|
lineageId,
|
|
actor,
|
|
'candidate',
|
|
key,
|
|
fingerprint
|
|
);
|
|
});
|
|
}
|
|
async cloneVersion(
|
|
sourceId: string,
|
|
input: { name: string; description?: string },
|
|
actor: StrategyActor,
|
|
key: string
|
|
) {
|
|
id.parse(sourceId);
|
|
const data = createSchema.parse(input);
|
|
const fingerprint = hash(stable({ kind: 'clone', sourceId, ...data, origin: 'candidate' }));
|
|
const cloned = await this.publication(actor, key, fingerprint, async client => {
|
|
const source = (
|
|
await client.query('SELECT strategy_id,envelope FROM strategy_versions WHERE id=$1', [
|
|
sourceId,
|
|
])
|
|
).rows[0];
|
|
if (!source) {
|
|
throw new StrategyCatalogError(404, 'Source strategy version not found');
|
|
}
|
|
await this.lock(client, source.strategy_id, false);
|
|
const old = await this.receipt(client, actor, key, fingerprint);
|
|
if (old) {
|
|
return old;
|
|
}
|
|
const pkg = checkedPackage(source.envelope);
|
|
const strategyId = randomUUID();
|
|
await client.query(
|
|
'INSERT INTO strategies(id,name,description,owner_principal,updated_by) VALUES($1,$2,$3,$4,$4)',
|
|
[strategyId, data.name, data.description, actor]
|
|
);
|
|
await this.lock(client, strategyId);
|
|
return this.insertVersion(
|
|
client,
|
|
strategyId,
|
|
pkg,
|
|
sourceId,
|
|
actor,
|
|
'candidate',
|
|
key,
|
|
fingerprint
|
|
);
|
|
});
|
|
return { strategy: await this.getStrategy(cloned.strategyId), version: cloned };
|
|
}
|
|
async reviewVersion(
|
|
versionId: string,
|
|
input: { decision: 'approve' | 'revoke'; reason: string },
|
|
actor: StrategyActor
|
|
) {
|
|
if (actor !== 'operator') {
|
|
throw new StrategyCatalogError(403, 'Human operator approval required');
|
|
}
|
|
id.parse(versionId);
|
|
const data = reviewSchema.parse(input);
|
|
checkText(data);
|
|
await this.database.transaction(async client => {
|
|
await lockResearchAgent(client, actor);
|
|
const row = (
|
|
await client.query('SELECT strategy_id FROM strategy_versions WHERE id=$1', [versionId])
|
|
).rows[0];
|
|
if (!row) {
|
|
throw new StrategyCatalogError(404, 'Strategy version not found');
|
|
}
|
|
await this.lock(client, row.strategy_id, data.decision === 'approve');
|
|
await client.query(
|
|
`INSERT INTO strategy_review_events(id,version_id,ordinal,decision,actor,reason)
|
|
SELECT $1,$2,COALESCE(MAX(ordinal),0)+1,$3,'operator',$4 FROM strategy_review_events WHERE version_id=$2`,
|
|
[randomUUID(), versionId, data.decision, data.reason]
|
|
);
|
|
});
|
|
return this.getVersion(versionId);
|
|
}
|
|
/** Trusted local import only. This is deliberately absent from HTTP routes. */
|
|
async seedBuiltin(name: string, input: unknown, key: string): Promise<StrategyVersionSummary> {
|
|
const pkg = checkedPackage(input);
|
|
const descriptor = builtinCatalogDescriptors.find(
|
|
item => stable(item.program) === stable(pkg.program)
|
|
);
|
|
if (
|
|
!descriptor ||
|
|
descriptor.entryExport !== pkg.artifact.entryExport ||
|
|
stable(descriptor.parameterSchema) !== stable(pkg.parameterSchema)
|
|
) {
|
|
throw new StrategyCatalogError(400, 'Builtin package does not match a registered descriptor');
|
|
}
|
|
const data = createSchema.parse({ name, description: descriptor.description });
|
|
const fingerprint = hash(stable({ kind: 'seed', origin: 'builtin', ...data, package: pkg }));
|
|
return this.publication('operator', key, fingerprint, async client => {
|
|
await client.query(
|
|
`INSERT INTO strategies(id,name,description,owner_principal,updated_by,builtin_key)
|
|
VALUES($1,$2,$3,'operator','operator',$4) ON CONFLICT(builtin_key) DO NOTHING`,
|
|
[randomUUID(), data.name, data.description, descriptor.program.strategyId]
|
|
);
|
|
const family = (
|
|
await client.query('SELECT * FROM strategies WHERE builtin_key=$1 FOR UPDATE', [
|
|
descriptor.program.strategyId,
|
|
])
|
|
).rows[0];
|
|
if (!family) {
|
|
throw new Error('Builtin strategy family disappeared');
|
|
}
|
|
const old = await this.receipt(client, 'operator', key, fingerprint);
|
|
if (old) {
|
|
return old;
|
|
}
|
|
if (family.archived_at !== null) {
|
|
throw new StrategyCatalogError(409, 'Strategy is archived');
|
|
}
|
|
const previous = (
|
|
await client.query(
|
|
'SELECT id FROM strategy_versions WHERE strategy_id=$1 ORDER BY ordinal DESC LIMIT 1',
|
|
[family.id]
|
|
)
|
|
).rows[0];
|
|
return this.insertVersion(
|
|
client,
|
|
family.id,
|
|
pkg,
|
|
previous?.id ?? null,
|
|
'operator',
|
|
'builtin',
|
|
key,
|
|
fingerprint
|
|
);
|
|
});
|
|
}
|
|
}
|