feat(research): cut over canonical runtime and enforce agent budgets

This commit is contained in:
Boki 2026-10-24 16:47:19 -04:00
parent ab08db82fd
commit bbf0dd4453
103 changed files with 6138 additions and 3112 deletions

View file

@ -48,14 +48,14 @@ export class BacktestDispatcher {
// Recovery is independent of Redis availability. Every terminal write fences the old owner.
await this.postgres.transaction(async client => {
await client.query(
`UPDATE runs SET
`UPDATE runs AS r SET
status = CASE WHEN cancel_requested THEN 'cancelled'::run_status
WHEN attempt_number >= $1 THEN 'failed'::run_status ELSE 'pending'::run_status END,
WHEN (attempt_number >= LEAST($1,COALESCE((to_jsonb(r)#>>'{research_limits,maxAttempts}')::integer,$1)) OR ((to_jsonb(r)->>'research_deadline_at')::timestamptz <= clock_timestamp())) THEN 'failed'::run_status ELSE 'pending'::run_status END,
error = CASE WHEN cancel_requested THEN NULL
WHEN attempt_number >= $1 THEN 'Execution lease expired; retry limit reached' ELSE NULL END,
completed_at = CASE WHEN cancel_requested OR attempt_number >= $1 THEN NOW() ELSE NULL END,
WHEN (attempt_number >= LEAST($1,COALESCE((to_jsonb(r)#>>'{research_limits,maxAttempts}')::integer,$1)) OR ((to_jsonb(r)->>'research_deadline_at')::timestamptz <= clock_timestamp())) THEN CASE WHEN ((to_jsonb(r)->>'research_deadline_at')::timestamptz <= clock_timestamp()) THEN 'Research attempt wall time exceeded' ELSE 'Execution lease expired; retry limit reached' END ELSE NULL END,
completed_at = CASE WHEN cancel_requested OR (attempt_number >= LEAST($1,COALESCE((to_jsonb(r)#>>'{research_limits,maxAttempts}')::integer,$1)) OR ((to_jsonb(r)->>'research_deadline_at')::timestamptz <= clock_timestamp())) THEN NOW() ELSE NULL END,
attempt_id = NULL, lease_expires_at = NULL, updated_at = NOW()
WHERE status IN ('running', 'paused') AND lease_expires_at <= clock_timestamp()`,
WHERE status IN ('running', 'paused') AND (lease_expires_at <= clock_timestamp() OR ((to_jsonb(r)->>'research_deadline_at')::timestamptz <= clock_timestamp()))`,
[this.options.maxAttempts]
);
});

View file

@ -27,7 +27,11 @@ import {
canonicalStrategyJson,
validateStrategyParameters,
} from '@stock-bot/stock-config/strategy';
import type { BacktestRunDatasetSelection, StrategyParameterValue } from '@stock-bot/types';
import type {
BacktestRunDatasetSelection,
ResearchActor,
StrategyParameterValue,
} from '@stock-bot/types';
import { HistoricalDataRequestError } from '@stock-bot/types';
import { buildCanonicalBacktestReport } from '../../../orchestrator/src/backtest/canonical-result';
import { getWebSocketHandler } from '../websocket/run-updates';
@ -107,7 +111,7 @@ export interface RunRequest {
}
export interface RunSubmission {
principal: 'operator' | 'service';
principal: ResearchActor;
key: string;
}
@ -443,6 +447,11 @@ export class BacktestServiceV2 {
}
const definition = this.mapBacktest(at(parent.rows, 0));
const catalog = definition.strategyVersionId !== null || definition.strategy === 'catalog';
if (!catalog) {
throw new CatalogExecutionUnavailableError(
'Legacy backtest execution is retired. Select an approved strategy version and retained canonical dataset.'
);
}
if (catalog && multiplier !== null) {
throw new CatalogExecutionUnavailableError('Canonical research runs at maximum speed');
}

View file

@ -16,6 +16,7 @@ import type {
ValidationResultEvidence,
} from '@stock-bot/stock-config/chronological-validation';
import type { ExperimentPreview } from '@stock-bot/stock-config/experiments';
import type { ResearchActor } from '@stock-bot/types';
import { HistoricalDataRequestError } from '@stock-bot/types';
import { validateDatasetV2 } from '../../../orchestrator/src/data/historical-dataset-v2';
import { BacktestServiceV2 } from './backtest-v2.service';
@ -28,6 +29,7 @@ import {
experimentTrialRequest,
} from './experiment-input';
import { ExperimentsService } from './experiments.service';
import { lockExperimentResearchAgent, lockResearchAgent } from './research-agent-budget';
import { RunReproductionError, verifyReproductionInputs } from './run-reproduction';
import {
parseValidationFinalization,
@ -89,6 +91,7 @@ export class ChronologicalValidationService {
submission,
});
return this.database.transaction(async client => {
await lockResearchAgent(client, identity.principal);
const replay = async () => {
const row = (
await client.query(
@ -144,7 +147,7 @@ export class ChronologicalValidationService {
prepared: ReturnType<typeof prepareChronologicalValidation>,
identity: {
id: string;
principal: 'operator' | 'service';
principal: ResearchActor;
key: string;
hash: string;
membership?: { id: string; index: number };
@ -225,12 +228,14 @@ export class ChronologicalValidationService {
const operation = 'select-and-admit-holdouts' as const;
const hash = experimentHash({ version: 1, operation, validationId: id, input });
return this.database.transaction(async client => {
await lockResearchAgent(client, identity.principal);
const replay = () =>
this.actionReplay(client, 'validation_selection', operation, identity, hash);
const prior = await replay();
if (prior) {
return prior;
}
await lockExperimentResearchAgent(client, id, identity.principal, true);
const { root, parent } = await this.lockRoot(client, id);
const concurrent = await replay();
if (concurrent) {
@ -357,6 +362,7 @@ export class ChronologicalValidationService {
const operation = 'finalize-report' as const,
hash = experimentHash({ version: 1, operation, validationId: id, input });
return this.database.transaction(async client => {
await lockResearchAgent(client, identity.principal);
const replay = () =>
this.actionReplay(client, 'validation_report', operation, identity, hash);
const prior = await replay();

View file

@ -13,6 +13,7 @@ import {
type ExperimentPreview,
type ExperimentSubmission,
} from '@stock-bot/stock-config/experiments';
import { researchActorSchema } from '@stock-bot/stock-config/research';
import {
assertStrategyJsonText,
builtinStrategySelectionSchema,
@ -58,7 +59,7 @@ export function experimentId(input: unknown): string {
export function experimentReceipt(input: { principal: string; key: string }) {
const parsed = z
.object({
principal: z.enum(['operator', 'service']),
principal: researchActorSchema,
key: z.string().regex(/^[\x21-\x7e]{1,200}$/),
})
.strict()

View file

@ -39,6 +39,7 @@ import {
PREVIEW_RUN_ID,
} from './experiment-input';
import { mapExperimentRetry, parseExperimentRetry, retryColumns } from './experiment-retry';
import { lockExperimentResearchAgent, lockResearchAgent } from './research-agent-budget';
import { RunReproductionError, verifyReproductionInputs } from './run-reproduction';
import { StrategyCatalogError } from './strategy-catalog.service';
import { parseChronologicalValidation, prepareChronologicalValidation } from './validation-preview';
@ -222,6 +223,7 @@ export class ExperimentsService {
submission,
});
return this.database.transaction(async client => {
await lockResearchAgent(client, receipt.principal);
const replay = async () => {
const row = (
await client.query(
@ -412,6 +414,7 @@ export class ExperimentsService {
...input,
});
return this.database.transaction(async client => {
await lockResearchAgent(client, receipt.principal);
const replay = async (): Promise<WorkbenchExperimentRetryResult | null> => {
const saved = (
await client.query(
@ -437,6 +440,7 @@ export class ExperimentsService {
if (previous) {
return previous;
}
await lockExperimentResearchAgent(client, id, receipt.principal);
// Same ordering as admission, followed by the existing original-family verification lock.
const parent = (
await client.query(

View file

@ -0,0 +1,94 @@
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';
return {
datasetHash: request.datasetHash,
versionId: 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);
}
}

View file

@ -0,0 +1,327 @@
import { createHash, randomBytes, randomUUID } from 'node:crypto';
import type { PoolClient, QueryResultRow } from 'pg';
import { z } from 'zod';
import { requireServices, type IServiceContainer } from '@stock-bot/services';
import {
createResearchAgentSchema,
researchAgentIdSchema,
updateResearchAgentSchema,
type ResearchAgentBudget,
type ResearchAgentRecord,
} from '@stock-bot/stock-config/research-agents';
import { HistoricalDataRequestError, isResearchAgent } from '@stock-bot/types';
import { admitCanonicalRequest } from './canonical-research.service';
import { PREVIEW_RUN_ID } from './experiment-input';
import {
ResearchAgentError,
researchGrantHash,
researchGrantPolicy,
} from './research-agent-budget';
import { StrategyCatalogError } from './strategy-catalog.service';
const tokenHash = (token: string) => createHash('sha256').update(token).digest('hex');
function record(row: QueryResultRow): ResearchAgentRecord {
return {
id: row.id,
name: row.name,
enabled: row.enabled,
revision: row.revision,
allowedProjectIds: row.policy.allowedProjectIds,
grants: row.policy.grants.map((grant: { backtestId: string; policyHash: string }) => ({
backtestId: grant.backtestId,
policyHash: grant.policyHash,
})),
limits: row.policy.limits,
createdAt: new Date(row.created_at).toISOString(),
updatedAt: new Date(row.updated_at).toISOString(),
};
}
const uuid = '[0-9a-fA-F-]{36}';
function permitted(request: Request): boolean {
const path = new URL(request.url).pathname,
method = request.method;
if (method === 'GET' || method === 'HEAD') {
return (
/^\/api\/v2\/(research-projects|hypotheses|analysis-artifacts|strategies|strategy-versions|experiments|backtests|runs)(\/|$)/.test(
path
) || path === '/api/v2/research-agent/budget'
);
}
if (method === 'PUT') {
return new RegExp(`^/api/v2/research-projects/${uuid}/strategies/${uuid}$`).test(path);
}
if (method !== 'POST') {
return false;
}
return (
path === '/api/v2/strategies' ||
new RegExp(`^/api/v2/strategies/${uuid}/versions$`).test(path) ||
new RegExp(`^/api/v2/strategy-versions/${uuid}/(clone|validate)$`).test(path) ||
new RegExp(`^/api/v2/research-projects/${uuid}/(hypotheses|analysis-artifacts)$`).test(path) ||
new RegExp(`^/api/v2/(hypotheses|analysis-artifacts)/${uuid}/revisions$`).test(path) ||
/^\/api\/v2\/experiments(?:\/(?:preview|cost-sensitivity(?:\/preview)?|validation(?:\/preview)?|walk-forward(?:\/preview)?))?$/.test(
path
) ||
new RegExp(
`^/api/v2/experiments/(?:validation/|walk-forward/)?${uuid}/(?:cancel|select|finalize)$`
).test(path) ||
new RegExp(`^/api/v2/experiments/${uuid}/trials/${uuid}/retry$`).test(path)
);
}
export class ResearchAgentsService {
private readonly database;
constructor(private readonly container: IServiceContainer) {
this.database = requireServices(container, 'postgres').postgres;
}
private async policy(
client: PoolClient,
input: {
allowedProjectIds: string[];
allowedBacktestIds: string[];
limits: ResearchAgentRecord['limits'];
}
) {
for (const id of input.allowedProjectIds) {
if (
!(
await client.query(
'SELECT id FROM research_projects WHERE id=$1 AND archived_at IS NULL',
[id]
)
).rows.length
) {
throw new ResearchAgentError(400, 'Choose existing active research projects');
}
}
// Lock every parent before acquiring any family lock; interleaving these can deadlock
// a concurrent admission on another granted template sharing the same family.
const parents = (
await client.query(
'SELECT * FROM backtests WHERE id=ANY($1::uuid[]) ORDER BY id FOR UPDATE',
[input.allowedBacktestIds]
)
).rows;
if (
parents.length !== input.allowedBacktestIds.length ||
parents.some(row => row.archived_at)
) {
throw new ResearchAgentError(400, 'Choose existing active canonical templates');
}
await client.query(
'SELECT id FROM strategies WHERE id IN (SELECT strategy_id FROM strategy_versions WHERE id=ANY($1::uuid[])) ORDER BY id FOR UPDATE',
[parents.map(row => row.strategy_version_id).filter(Boolean)]
);
const grants = [];
for (const row of parents) {
const id = row.id as string;
let request;
try {
request = await admitCanonicalRequest(
client,
this.container,
{
name: row.name,
strategyVersionId: row.strategy_version_id,
strategyParameters: row.strategy_parameters,
symbols: row.symbols,
startDate: row.start_date,
endDate: row.end_date,
initialCapital: Number(row.initial_capital),
config: row.config,
},
id,
PREVIEW_RUN_ID
);
} catch (error) {
if (
!(
error instanceof HistoricalDataRequestError ||
error instanceof StrategyCatalogError ||
error instanceof z.ZodError
)
) {
throw error;
}
throw new ResearchAgentError(
400,
'Agent grants require currently approved canonical templates'
);
}
const policy = researchGrantPolicy(request);
grants.push({ backtestId: id, policyHash: researchGrantHash(policy), policy });
}
return { version: 1, allowedProjectIds: input.allowedProjectIds, grants, limits: input.limits };
}
async create(raw: unknown) {
const input = createResearchAgentSchema.parse(raw),
token = `sb-research.${randomBytes(32).toString('base64url')}`;
const agent = await this.database.transaction(async client => {
const policy = await this.policy(client, input);
const row = (
await client.query(
'INSERT INTO research_agents(id,name,token_hash,policy) VALUES($1,$2,$3,$4::jsonb) RETURNING *',
[`agent:${randomUUID()}`, input.name, tokenHash(token), JSON.stringify(policy)]
)
).rows[0];
if (!row) {
throw new Error('Research agent was not created');
}
return record(row);
});
return { agent, token };
}
async list(): Promise<ResearchAgentRecord[]> {
return (
await this.database.query('SELECT * FROM research_agents ORDER BY created_at,id')
).rows.map(record);
}
async update(id: string, raw: unknown): Promise<ResearchAgentRecord> {
researchAgentIdSchema.parse(id);
const input = updateResearchAgentSchema.parse(raw);
return this.database.transaction(async client => {
const old = (await client.query('SELECT * FROM research_agents WHERE id=$1 FOR UPDATE', [id]))
.rows[0];
if (!old) {
throw new ResearchAgentError(404, 'Research principal not found');
}
if (old.revision !== input.expectedRevision) {
throw new ResearchAgentError(
409,
'Research principal policy changed; reload before editing'
);
}
const policy =
input.allowedBacktestIds === undefined
? {
...old.policy,
allowedProjectIds: input.allowedProjectIds ?? old.policy.allowedProjectIds,
limits: input.limits ?? old.policy.limits,
}
: await this.policy(client, {
allowedProjectIds: input.allowedProjectIds ?? old.policy.allowedProjectIds,
allowedBacktestIds: input.allowedBacktestIds,
limits: input.limits ?? old.policy.limits,
});
if (input.allowedProjectIds) {
for (const projectId of input.allowedProjectIds) {
if (
!(
await client.query(
'SELECT id FROM research_projects WHERE id=$1 AND archived_at IS NULL',
[projectId]
)
).rows.length
) {
throw new ResearchAgentError(400, 'Choose existing active research projects');
}
}
}
const row = (
await client.query(
'UPDATE research_agents SET name=$2,enabled=$3,policy=$4::jsonb,revision=revision+1,updated_at=NOW() WHERE id=$1 RETURNING *',
[id, input.name ?? old.name, input.enabled ?? old.enabled, JSON.stringify(policy)]
)
).rows[0];
if (!row) {
throw new Error('Research principal update disappeared');
}
return record(row);
});
}
async budget(id: string, allowDisabled = false): Promise<ResearchAgentBudget> {
const row = (
await this.database.query(
`SELECT a.*,(SELECT count(*)::integer FROM runs r WHERE r.research_agent_id=a.id AND r.status IN ('pending','running','paused')) AS active_trials FROM research_agents a WHERE a.id=$1`,
[researchAgentIdSchema.parse(id)]
)
).rows[0];
if (!row || (!allowDisabled && !row.enabled)) {
throw new ResearchAgentError(403, 'Research principal is disabled or unavailable');
}
const agent = record(row),
activeTrials = Number(row.active_trials);
return {
agent,
activeTrials,
remainingActiveTrials: Math.max(0, agent.limits.maxActiveTrials - activeTrials),
};
}
async authenticate(
request: Request
): Promise<{ principal: `agent:${string}` } | Response | undefined> {
const match = /^Bearer (sb-research\.[A-Za-z0-9_-]+)$/i.exec(
request.headers.get('authorization') ?? ''
);
if (!match?.[1]) {
return undefined;
}
const row = (
await this.database.query(
'SELECT id,enabled,policy FROM research_agents WHERE token_hash=$1',
[tokenHash(match[1])]
)
).rows[0];
if (!row?.enabled || !isResearchAgent(row.id)) {
return undefined;
}
const deny = () =>
Response.json(
{ error: 'Research credential does not permit this operation' },
{ status: 403, headers: { 'Cache-Control': 'no-store' } }
);
if (!permitted(request)) {
return deny();
}
if (!['GET', 'HEAD'].includes(request.method)) {
const path = new URL(request.url).pathname;
const project = new RegExp(`^/api/v2/research-projects/(${uuid})/`).exec(path);
if (project && !row.policy.allowedProjectIds.includes(project[1]?.toLowerCase())) {
return deny();
}
const experiment = new RegExp(
`^/api/v2/experiments/(walk-forward/|validation/)?(${uuid})/`
).exec(path);
if (experiment) {
const table =
experiment[1] === 'walk-forward/' ? 'research_walk_forwards' : 'research_experiments';
const owned = (
await this.database.query(`SELECT submission_principal FROM ${table} WHERE id=$1`, [
experiment[2],
])
).rows[0];
if (owned?.submission_principal !== row.id) {
return deny();
}
}
const family = new RegExp(`^/api/v2/strategies/(${uuid})/versions$`).exec(path);
if (
family &&
(
await this.database.query('SELECT owner_principal FROM strategies WHERE id=$1', [
family[1],
])
).rows[0]?.owner_principal !== row.id
) {
return deny();
}
const narrative = new RegExp(
`^/api/v2/(hypotheses|analysis-artifacts)/(${uuid})/revisions$`
).exec(path);
if (narrative) {
const table = narrative[1] === 'hypotheses' ? 'research_hypotheses' : 'analysis_artifacts';
const owned = (
await this.database.query(`SELECT owner_principal,project_id FROM ${table} WHERE id=$1`, [
narrative[2],
])
).rows[0];
if (
owned?.owner_principal !== row.id ||
!row.policy.allowedProjectIds.includes(owned.project_id)
) {
return deny();
}
}
}
return { principal: row.id };
}
}

View file

@ -13,6 +13,7 @@ import type {
import type { WorkbenchExperimentPreview } from '@stock-bot/stock-config/cost-sensitivity';
import type { ExperimentCandidate } from '@stock-bot/stock-config/experiments';
import type { WalkForwardSegment } from '@stock-bot/stock-config/walk-forward';
import { isResearchActor } from '@stock-bot/types';
import type { ResearchEvidenceReference, ResearchFindingSource } from '@stock-bot/types';
import type { BacktestResultQuery } from './backtest-v2.service';
import { retainedWorkbenchPreview, workbenchTrialRequest } from './cost-sensitivity-input';
@ -44,7 +45,7 @@ function documentMetadata(value: Record<string, unknown>, report: boolean): void
/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(value.id) &&
typeof value.createdAt === 'string' &&
Number.isFinite(Date.parse(value.createdAt)) &&
(value.principal === 'operator' || value.principal === 'service') &&
isResearchActor(value.principal) &&
typeof receipt?.key === 'string' &&
/^[!-~]{1,200}$/.test(receipt.key) &&
typeof receipt.hash === 'string' &&

View file

@ -28,6 +28,7 @@ import type {
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';
@ -47,12 +48,16 @@ function required(row: QueryResultRow | undefined, label: string): QueryResultRo
}
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');
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' : 'unknown'),
contentOrigin:
origin ?? (actor === 'operator' ? 'human' : actor.startsWith('agent:') ? 'ai' : 'unknown'),
};
}
function project(row: QueryResultRow): ResearchProject {
@ -169,6 +174,7 @@ export class ResearchService {
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 (
@ -217,6 +223,7 @@ export class ResearchService {
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]))
@ -241,6 +248,7 @@ export class ResearchService {
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',
@ -274,6 +282,7 @@ export class ResearchService {
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(
(
@ -313,6 +322,7 @@ export class ResearchService {
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);
@ -339,6 +349,7 @@ export class ResearchService {
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(
(
@ -377,6 +388,7 @@ export class ResearchService {
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 = (
@ -440,6 +452,7 @@ export class ResearchService {
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);
@ -482,6 +495,7 @@ export class ResearchService {
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(
(

View file

@ -2,6 +2,7 @@ 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,
@ -11,15 +12,17 @@ import {
} 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 = 'operator' | 'service';
export type StrategyActor = ResearchActor;
export class StrategyCatalogError extends Error {
constructor(
public readonly status: 400 | 401 | 403 | 404 | 409,
@ -29,7 +32,7 @@ export class StrategyCatalogError extends Error {
}
}
const id = z.string().uuid();
const actorSchema = z.enum(['operator', 'service']);
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('') })
@ -144,6 +147,7 @@ export class StrategyCatalogService {
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(
@ -303,6 +307,7 @@ export class StrategyCatalogService {
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));
});
@ -476,6 +481,7 @@ export class StrategyCatalogService {
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];

View file

@ -19,6 +19,7 @@ import {
experimentReceipt,
} from './experiment-input';
import { ExperimentsService } from './experiments.service';
import { lockResearchAgent } from './research-agent-budget';
import { validationEqual } from './validation-evidence';
import {
parseWalkForwardFinalization,
@ -93,6 +94,7 @@ export class WalkForwardService {
{ previewHash, ...input } = submission;
const hash = experimentHash({ version: 1, operation: 'submit-walk-forward', submission });
return this.database.transaction(async client => {
await lockResearchAgent(client, identity.principal);
const replay = async () => {
const row = (
await client.query(
@ -212,6 +214,7 @@ export class WalkForwardService {
input,
});
return this.database.transaction(async client => {
await lockResearchAgent(client, identity.principal);
const replay = async () => {
const row = (
await client.query(