stock-bot/apps/stock/web-api/src/services/research-agent-budget.ts

118 lines
4.4 KiB
TypeScript

import { createHash } from 'node:crypto';
import type { QueryResultRow } from 'pg';
import type { CanonicalRunRequest } from '@stock-bot/stock-config/canonical-research';
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
import { isResearchAgent } from '@stock-bot/types';
export type AgentQuery = {
query(text: string, values?: unknown[]): Promise<{ rows: QueryResultRow[] }>;
};
export class ResearchAgentError extends Error {
constructor(
readonly status: 400 | 401 | 403 | 404 | 409 | 429,
message: string
) {
super(message);
}
}
/** Economic inputs are pinned. Only transport identity and strategy parameter variation are excluded. */
export function researchGrantPolicy(request: CanonicalRunRequest) {
const policy = structuredClone(request.policy);
policy.matching.risk.ledger.sessionId = 'agent-grant-run';
policy.matching.risk.ledger.accountId = 'agent-grant-account';
if (request.strategy.origin === 'candidate') {
const ownerId = `strategy:${request.strategy.baselineVersionId}`;
policy.matching.risk.ledger.ownerIds = [ownerId];
policy.matching.owners = [{ ownerId, mode: 'Target' }];
policy.cadence = [{ owner_id: ownerId, series_ids: [request.strategy.selection.seriesId] }];
}
return {
datasetHash: request.datasetHash,
versionId:
request.strategy.origin === 'candidate'
? request.strategy.baselineVersionId
: request.strategy.versionId,
ownerBudget: request.strategy.selection.ownerBudget,
seed: request.strategy.selection.seed,
policy,
analyticsPolicy: request.analyticsPolicy,
build: request.build,
modelArtifacts: request.modelArtifacts,
};
}
export const researchGrantHash = (policy: ReturnType<typeof researchGrantPolicy>) =>
createHash('sha256').update(canonicalStrategyJson(policy)).digest('hex');
/** First lock for every agent admission. Existing receipt replay follows this authentication fence. */
export async function lockResearchAgent(database: AgentQuery, principal: string): Promise<void> {
if (!isResearchAgent(principal)) {
return;
}
const row = (
await database.query('SELECT id,enabled FROM research_agents WHERE id=$1 FOR UPDATE', [
principal,
])
).rows[0];
if (!row?.enabled) {
throw new ResearchAgentError(403, 'Research principal is disabled or unavailable');
}
}
/** SQL guards are authoritative; map only the deliberately typed guard diagnostics. */
export function researchAgentDatabaseError(error: unknown): ResearchAgentError | null {
if (
error &&
typeof error === 'object' &&
'code' in error &&
'message' in error &&
error.code === 'P0001' &&
typeof error.message === 'string'
) {
if (error.message.startsWith('research_budget:')) {
return new ResearchAgentError(429, error.message.slice('research_budget:'.length));
}
if (error.message.startsWith('research_access:')) {
return new ResearchAgentError(403, error.message.slice('research_access:'.length));
}
}
return null;
}
/** Operator interventions must reserve the owning agent before the existing parent/resource locks. */
export async function lockExperimentResearchAgent(
database: AgentQuery,
experimentId: string,
principal: string,
ownerOnly = false
): Promise<void> {
const owner = (
await database.query('SELECT submission_principal FROM research_experiments WHERE id=$1', [
experimentId,
])
).rows[0]?.submission_principal;
if (isResearchAgent(principal) && owner !== undefined && owner !== principal) {
throw new ResearchAgentError(403, 'Research action requires its owning principal');
}
if (ownerOnly && isResearchAgent(owner) && owner !== principal) {
throw new ResearchAgentError(
403,
'New holdouts must be selected by the owning research principal'
);
}
if (isResearchAgent(owner) && owner !== principal) {
await lockResearchAgent(database, owner);
}
}
/** SQL remains authoritative; this preflight never executes candidate code or changes grants. */
export async function verifyCandidateGrant(
database: AgentQuery,
request: CanonicalRunRequest,
principal: string
): Promise<void> {
if (!isResearchAgent(principal) || request.strategy.origin !== 'candidate') {
return;
}
await database.query(
'SELECT assert_research_agent_grant(a,$2,$3::jsonb) FROM research_agents a WHERE id=$1',
[principal, request.backtestId, request]
);
}