feat(research): isolate candidates and add reviewed paper promotion

This commit is contained in:
Boki 2026-10-24 18:46:55 -04:00
parent 26b97265c6
commit 25b5cbf481
128 changed files with 13038 additions and 1388 deletions

View file

@ -15,6 +15,7 @@ import { createExchangeRoutes } from './exchange.routes';
import { createExperimentRoutes } from './experiments.routes';
import { createHealthRoutes } from './health.routes';
import { createMonitoringRoutes } from './monitoring.routes';
import { createPaperDeploymentRoutes } from './paper-deployments.routes';
import { createPipelineRoutes } from './pipeline.routes';
import { createResearchAgentRoutes } from './research-agents.routes';
import { createResearchRoutes } from './research.routes';
@ -24,7 +25,11 @@ import { createStrategyRoutes } from './strategies.routes';
// the old 1 MiB restriction; normalizers still validate every submitted record.
export const WEB_API_MAX_REQUEST_BODY_SIZE = Number.MAX_SAFE_INTEGER;
export function createRoutes(container: IServiceContainer, suppliedSecurity?: HttpSecurity): Hono {
export function createRoutes(
container: IServiceContainer,
suppliedSecurity?: HttpSecurity,
integrations?: { paperOrchestratorOrigin?: string }
): Hono {
const agents = new ResearchAgentsService(container);
const security =
suppliedSecurity ??
@ -67,6 +72,13 @@ export function createRoutes(container: IServiceContainer, suppliedSecurity?: Ht
app.route('/', createResearchRoutes(container));
app.route('/', createResearchAgentRoutes(container, security.researchEnabled));
app.route('/', createExperimentRoutes(container));
app.route(
'/',
createPaperDeploymentRoutes(container, {
origin: integrations ? integrations.paperOrchestratorOrigin : process.env.ORCHESTRATOR_URL,
origins: security.allowedOrigins,
})
);
return app;
}

View file

@ -75,7 +75,10 @@ export function createExperimentRoutes(container: IServiceContainer) {
};
app.post('/api/v2/experiments/cost-sensitivity/preview', async c =>
c.json({
preview: await service.previewCosts(parseCostSensitivityInput(await body(c.req.raw))),
preview: await service.previewCosts(
parseCostSensitivityInput(await body(c.req.raw)),
getResearchHttpPrincipal(c.req.raw) ?? ''
),
})
);
app.post('/api/v2/experiments/cost-sensitivity', async c => {
@ -91,7 +94,12 @@ export function createExperimentRoutes(container: IServiceContainer) {
return c.json({ experiment }, 202);
});
app.post('/api/v2/experiments/walk-forward/preview', async c =>
c.json({ preview: await walkForwards.preview(parseWalkForwardInput(await body(c.req.raw))) })
c.json({
preview: await walkForwards.preview(
parseWalkForwardInput(await body(c.req.raw)),
getResearchHttpPrincipal(c.req.raw) ?? ''
),
})
);
app.post('/api/v2/experiments/walk-forward', async c => {
const input = parseWalkForwardSubmission(await body(c.req.raw));
@ -140,7 +148,9 @@ export function createExperimentRoutes(container: IServiceContainer) {
});
app.post('/api/v2/experiments/validation/preview', async c => {
const input = parseChronologicalValidation(await body(c.req.raw));
return c.json({ preview: await service.previewValidation(input) });
return c.json({
preview: await service.previewValidation(input, getResearchHttpPrincipal(c.req.raw) ?? ''),
});
});
app.post('/api/v2/experiments/validation', async c => {
const input = parseValidationSubmission(await body(c.req.raw));
@ -204,7 +214,9 @@ export function createExperimentRoutes(container: IServiceContainer) {
});
app.post('/api/v2/experiments/preview', async c => {
const input = parseExperimentInput(await body(c.req.raw));
return c.json({ preview: await service.preview(input) });
return c.json({
preview: await service.preview(input, getResearchHttpPrincipal(c.req.raw) ?? ''),
});
});
app.post('/api/v2/experiments', async c => {
const input = parseExperimentSubmission(await body(c.req.raw));

View file

@ -0,0 +1,178 @@
import { Hono } from 'hono';
import { z } from 'zod';
import type { IServiceContainer } from '@stock-bot/services';
import { paperDeploymentStatusSchema } from '@stock-bot/stock-config/paper-deployments';
import {
paperActivationSchema,
paperHaltSchema,
PaperRuntimeError,
} from '../../../orchestrator/src/contracts/paper-runtime';
import { PaperDeploymentError } from '../../../orchestrator/src/paper/paper-deployment-custody';
import {
paperAllowedOrigins,
requirePaperOperator,
} from '../../../orchestrator/src/paper/paper-operator';
import { PaperDeploymentsService } from '../services/paper-deployments.service';
import { ResearchError } from '../services/research-errors';
/** Forwards the original human credential; never substitutes a service token. */
export async function forwardPaperCommand(
request: Request,
id: string,
operation: 'bind' | 'activate' | 'halt' | 'readiness',
body: unknown,
options: {
origin?: string;
request?: (url: string | URL | Request, init?: RequestInit) => Promise<Response>;
}
) {
if (!options.origin) {
throw new PaperDeploymentError(503, 'Paper orchestrator origin is not configured');
}
let base: URL;
try {
base = new URL(options.origin);
} catch {
throw new PaperDeploymentError(503, 'Paper orchestrator origin is invalid');
}
if (
!['http:', 'https:'].includes(base.protocol) ||
base.username ||
base.password ||
base.pathname !== '/' ||
base.search ||
base.hash
) {
throw new PaperDeploymentError(503, 'Paper orchestrator requires a fixed HTTP origin');
}
const headers = new Headers({ 'Content-Type': 'application/json' });
for (const name of ['authorization', 'cookie', 'origin']) {
const value = request.headers.get(name);
if (value) {
headers.set(name, value);
}
}
let response: Response;
try {
response = await (options.request ?? fetch)(
new URL(`/api/paper/deployments/${id}/${operation}`, base),
{
method: operation === 'readiness' ? 'GET' : 'POST',
headers,
...(operation === 'readiness' ? {} : { body: JSON.stringify(body) }),
redirect: 'error',
signal: AbortSignal.timeout(15000),
}
);
} catch {
throw new PaperDeploymentError(
503,
'Paper orchestrator could not confirm the command; check readiness before retrying'
);
}
const value: unknown = await response.json().catch(() => null);
if (!response.ok) {
const status = [400, 403, 404, 409, 422, 503].includes(response.status) ? response.status : 503;
const message =
value && typeof value === 'object' && 'error' in value && typeof value.error === 'string'
? value.error
: 'Paper orchestrator rejected the request';
throw new PaperDeploymentError(status as 400 | 403 | 404 | 409 | 422 | 503, message);
}
const status = paperDeploymentStatusSchema.parse(value);
if (status.deploymentId !== id) {
throw new Error('Paper orchestrator returned another deployment');
}
return status;
}
export function createPaperDeploymentRoutes(
container: IServiceContainer,
options: {
origin?: string;
origins?: readonly string[];
request?: (url: string | URL | Request, init?: RequestInit) => Promise<Response>;
service?: PaperDeploymentsService;
} = {}
) {
const app = new Hono(),
service = options.service ?? new PaperDeploymentsService(container),
origins = options.origins ?? paperAllowedOrigins();
app.use('*', async (c, next) => {
c.header('Cache-Control', 'no-store');
if (c.req.method !== 'GET' || c.req.path.endsWith('/readiness')) {
requirePaperOperator(c.req.raw, origins);
}
await next();
});
app.onError((error, c) => {
if (error instanceof PaperDeploymentError || error instanceof ResearchError) {
return c.json({ error: error.message }, error.status);
}
if (
error instanceof z.ZodError ||
error instanceof SyntaxError ||
error instanceof PaperRuntimeError
) {
return c.json(
{
error:
error instanceof PaperRuntimeError ? error.message : 'Invalid paper promotion request',
},
400
);
}
container.logger.error('Paper deployment operation failed', { error });
return c.json({ error: 'Paper deployment evidence or storage unavailable' }, 500);
});
app.get('/api/v2/paper-deployments', async c => c.json({ deployments: await service.list() }));
app.post('/api/v2/paper-deployments/preview', async c =>
c.json(await service.preview(await c.req.json()))
);
app.post('/api/v2/paper-deployments', async c =>
c.json(await service.create(await c.req.json(), c.req.header('Idempotency-Key') ?? ''), 201)
);
app.get('/api/v2/paper-deployments/:id', async c =>
c.json(
await service.get(
z
.string()
.uuid()
.transform(value => value.toLowerCase())
.parse(c.req.param('id'))
)
)
);
for (const operation of ['bind', 'activate', 'halt', 'readiness'] as const) {
const path = `/api/v2/paper-deployments/:id/${operation}`;
app.on(operation === 'readiness' ? 'GET' : 'POST', path, async c => {
const id = z
.string()
.uuid()
.transform(value => value.toLowerCase())
.parse(c.req.param('id'));
const body =
operation === 'readiness'
? undefined
: operation === 'activate'
? paperActivationSchema.parse(await c.req.json())
: operation === 'halt'
? paperHaltSchema.parse(await c.req.json())
: z
.object({})
.strict()
.parse(await c.req.json());
if (operation === 'bind' || operation === 'activate') {
await service.authorizeCommand(id);
} else {
await service.get(id);
}
return c.json(
await forwardPaperCommand(c.req.raw, id, operation, body, {
origin: options.origin ?? process.env.ORCHESTRATOR_URL,
request: options.request,
})
);
});
}
return app;
}