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

@ -0,0 +1,96 @@
import { Hono } from 'hono';
import { z } from 'zod';
import {
paperActivationSchema,
paperHaltSchema,
PaperRuntimeError,
} from '../../contracts/paper-runtime';
import { ExecutionConflictError } from '../../execution/repository';
import { PaperDeploymentError } from '../../paper/paper-deployment-custody';
import { paperAllowedOrigins, requirePaperOperator } from '../../paper/paper-operator';
import type { PaperDeploymentHost } from '../../paper/PaperDeploymentHost';
export function createPaperDeploymentHostRoutes(
host?: PaperDeploymentHost,
origins: readonly string[] = paperAllowedOrigins()
) {
const app = new Hono();
app.use('*', async (c, next) => {
c.header('Cache-Control', 'no-store');
requirePaperOperator(c.req.raw, origins);
await next();
});
app.onError((error, c) => {
if (error instanceof PaperDeploymentError) {
return c.json({ error: error.message }, error.status);
}
if (error instanceof z.ZodError || error instanceof SyntaxError) {
return c.json({ error: 'Invalid paper command' }, 400);
}
if (error instanceof PaperRuntimeError || error instanceof ExecutionConflictError) {
return c.json({ error: error.message }, 409);
}
return c.json({ error: 'Paper deployment host unavailable' }, 503);
});
const configured = () => {
if (!host) {
throw new PaperDeploymentError(
503,
'Paper deployment host is explicitly disabled or unconfigured'
);
}
return host;
};
app.get('/:id/readiness', async c =>
c.json(
await configured().status(
z
.string()
.uuid()
.transform(value => value.toLowerCase())
.parse(c.req.param('id'))
)
)
);
app.post('/:id/bind', async c => {
z.object({})
.strict()
.parse(await c.req.json());
return c.json(
await configured().bind(
z
.string()
.uuid()
.transform(value => value.toLowerCase())
.parse(c.req.param('id'))
)
);
});
app.post('/:id/activate', async c => {
const input = paperActivationSchema.parse(await c.req.json());
return c.json(
await configured().activate(
z
.string()
.uuid()
.transform(value => value.toLowerCase())
.parse(c.req.param('id')),
input.recoverPending
)
);
});
app.post('/:id/halt', async c => {
const input = paperHaltSchema.parse(await c.req.json());
return c.json(
await configured().halt(
z
.string()
.uuid()
.transform(value => value.toLowerCase())
.parse(c.req.param('id')),
input.reason
)
);
});
return app;
}

View file

@ -1,6 +1,6 @@
import { Hono } from 'hono';
import { z } from 'zod';
import { getVerifiedHttpPrincipal } from '@stock-bot/di';
import { getCredentialHttpPrincipal } from '@stock-bot/di';
import {
paperActivationSchema,
paperConnectionSchema,
@ -10,12 +10,20 @@ import {
type PaperReadiness,
} from '../../contracts/paper-runtime';
import { ExecutionConflictError } from '../../execution/repository';
import { PaperDeploymentError } from '../../paper/paper-deployment-custody';
import { paperAllowedOrigins, requirePaperOperator } from '../../paper/paper-operator';
import type { PaperDeploymentHost } from '../../paper/PaperDeploymentHost';
import type { OrchestratorServices } from '../../types';
export function createPaperRoutes(services: OrchestratorServices): Hono {
export function createPaperRoutes(
services: OrchestratorServices,
options: { deploymentHost?: PaperDeploymentHost; origins?: readonly string[] } = {}
): Hono {
const app = new Hono();
const runtime = () => {
const value = services.custom?.CanonicalPaperRuntime;
const value = options.deploymentHost
? options.deploymentHost.runtime()
: services.custom?.CanonicalPaperRuntime;
if (!value) {
throw new PaperRuntimeError('not-ready', 'Canonical paper execution is not configured');
}
@ -24,8 +32,11 @@ export function createPaperRoutes(services: OrchestratorServices): Hono {
app.use('*', async (c, next) => {
c.header('Cache-Control', 'no-store');
if (c.req.method !== 'GET') {
const principal = getVerifiedHttpPrincipal(c.req.raw);
const principal = getCredentialHttpPrincipal(c.req.raw);
const feed = c.req.path.includes('/feed/');
if (!feed) {
requirePaperOperator(c.req.raw, options.origins ?? paperAllowedOrigins());
}
if (principal !== 'operator' && !(feed && principal === 'service')) {
return c.json(
{ error: feed ? 'Verified feed producer required' : 'Human operator required' },
@ -37,6 +48,9 @@ export function createPaperRoutes(services: OrchestratorServices): Hono {
return undefined;
});
app.onError((error, c) => {
if (error instanceof PaperDeploymentError) {
return c.json({ error: error.message }, error.status);
}
if (error instanceof z.ZodError || error instanceof SyntaxError) {
return c.json({ error: 'Invalid paper request' }, 400);
}
@ -53,7 +67,10 @@ export function createPaperRoutes(services: OrchestratorServices): Hono {
return c.json({ error: 'Canonical paper runtime unavailable' }, 503);
});
app.get('/readiness', async c => {
if (!services.custom?.CanonicalPaperRuntime) {
if (options.deploymentHost) {
return c.json(await options.deploymentHost.readiness());
}
if (!services.custom?.CanonicalPaperRuntime && !options.deploymentHost) {
const unavailable: PaperReadiness = {
configured: false,
accountId: null,
@ -76,9 +93,12 @@ export function createPaperRoutes(services: OrchestratorServices): Hono {
}
return c.json(await runtime().status());
});
app.post('/activate', async c =>
c.json(await runtime().activate(paperActivationSchema.parse(await c.req.json())))
);
app.post('/activate', async c => {
if (options.deploymentHost) {
throw new PaperDeploymentError(409, 'Use the deployment-bound activation endpoint');
}
return c.json(await runtime().activate(paperActivationSchema.parse(await c.req.json())));
});
app.post('/halt', async c =>
c.json(await runtime().halt(paperHaltSchema.parse(await c.req.json()).reason))
);

View file

@ -3,6 +3,7 @@ import type { Logger } from '@stock-bot/services';
import { parseBacktestRequest } from '@stock-bot/stock-config/backtest';
import {
canonicalRunRequestSchema,
canonicalStrategyExecution,
type CanonicalRunRequest,
type CanonicalRunResult,
} from '@stock-bot/stock-config/canonical-research';
@ -260,14 +261,17 @@ export class BacktestRunner extends EventEmitter {
throw new Error('Canonical execution capabilities are unavailable');
}
const claim = this.active;
const report = await engine.runCanonical(executionConfig, signal =>
loadCanonicalDataset.call(
repository,
claim.runId,
claim.attemptId,
executionConfig.datasetHash,
signal
)
const report = await engine.runCanonical(
executionConfig,
signal =>
loadCanonicalDataset.call(
repository,
claim.runId,
claim.attemptId,
executionConfig.datasetHash,
signal
),
{ executionDeadlineAt: claim.executionDeadlineAt }
);
if (this.cancelled) {
throw new BacktestCancelledError();
@ -280,7 +284,7 @@ export class BacktestRunner extends EventEmitter {
completedAt: new Date().toISOString(),
executionTime: performance.now() - started,
financialEngine: 'rust',
strategyExecution: 'typescript-retained-builtin/v1',
strategyExecution: canonicalStrategyExecution(executionConfig),
request: executionConfig,
...report,
};

View file

@ -1,4 +1,5 @@
import { fork, type ChildProcess } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import { realpathSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import {
@ -13,6 +14,7 @@ import {
parseStrategyReplayResult,
strategyReplayRequestSchema,
} from '../contracts/strategy-replay';
import { removeCandidateContainer } from './candidate-sandbox';
import { canonicalWorkerUrl } from './canonical-build';
import {
nativeWorkerMessageSchema,
@ -49,6 +51,16 @@ export class NativeBacktestWorker {
request.type === 'runStrategyReplay'
? structuredClone(strategyReplayRequestSchema.parse(request))
: undefined;
const candidateContainerName =
retainedRequest?.request.strategy.origin === 'candidate'
? `stock-bot-candidate-${randomUUID()}`
: undefined;
if (retainedRequest) {
delete retainedRequest.candidateContainerName;
if (candidateContainerName) {
retainedRequest.candidateContainerName = candidateContainerName;
}
}
const submitted = retainedRequest ?? strategyRequest ?? request;
if (
retainedRequest &&
@ -155,7 +167,7 @@ export class NativeBacktestWorker {
}
}
};
const finish = (code: number | null, exitSignal: NodeJS.Signals | null) => {
const finish = async (code: number | null, exitSignal: NodeJS.Signals | null) => {
if (settled) {
return;
}
@ -163,6 +175,13 @@ export class NativeBacktestWorker {
signal.removeEventListener('abort', onAbort);
child.off('message', onMessage);
child.stderr?.off('data', onStderr);
if (candidateContainerName) {
try {
await removeCandidateContainer(candidateContainerName);
} catch (error) {
failure ??= error instanceof Error ? error : new Error(String(error));
}
}
this.active = undefined;
if (failure) {
reject(failure);

View file

@ -8,6 +8,7 @@ import {
} from '@stock-bot/stock-config/backtest';
import {
canonicalRunRequestSchema,
canonicalStrategyExecution,
parseCanonicalFinancialResult,
type CanonicalRunRequest,
type CanonicalRunResult,
@ -414,7 +415,7 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
result.runId !== request.runId ||
result.backtestId !== request.backtestId ||
result.financialEngine !== 'rust' ||
result.strategyExecution !== 'typescript-retained-builtin/v1'
result.strategyExecution !== canonicalStrategyExecution(request)
) {
throw new BacktestConflictError('Canonical result identity mismatch');
}

View file

@ -58,7 +58,8 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti
async runCanonical(
input: CanonicalRunRequest,
resolveDataset: (signal: AbortSignal) => Promise<HistoricalDatasetV2>
resolveDataset: (signal: AbortSignal) => Promise<HistoricalDatasetV2>,
controls: { executionDeadlineAt?: number } = {}
): Promise<Pick<CanonicalRunResult, 'financial' | 'analytics'>> {
const request = canonicalRunRequestSchema.parse(input);
return this.runOwned(
@ -67,7 +68,14 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti
const dataset = await Promise.race([resolveDataset(signal), aborted]);
signal.throwIfAborted();
const raw = await this.worker.execute(
{ type: 'runRetainedStrategy', request, dataset },
{
type: 'runRetainedStrategy',
request,
dataset,
...(controls.executionDeadlineAt === undefined
? {}
: { executionDeadlineAt: controls.executionDeadlineAt }),
},
signal,
progress => {
this.progress = progress.progress;

View file

@ -0,0 +1,99 @@
/** This entrypoint runs ONLY inside the restricted image; never the API/native supervisor. */
import { sameIdentity } from '../contracts/native-replay';
import { importRetainedProgram } from '../strategies/retained-program';
import { StrategyController } from '../strategies/strategy-controller';
import { freeze } from '../strategies/strategy-decision';
import {
candidateRequestSchema,
readCandidateFrames,
writeCandidateFrame,
} from './candidate-protocol';
// Ordinary logs are diagnostics, not protocol. Deliberate raw stdout forgery remains untrusted.
// eslint-disable-next-line no-console -- stdout belongs exclusively to the framed protocol.
console.log = console.info = console.debug = (...values: unknown[]) => console.error(...values);
let controller: StrategyController | undefined;
let identity: ConstructorParameters<typeof StrategyController>[0] | undefined;
let sequence = 0;
try {
for await (const raw of readCandidateFrames(process.stdin)) {
const request = candidateRequestSchema.parse(raw);
if (request.sequence !== sequence) {
throw new Error('Candidate protocol sequence mismatch');
}
const response = { version: 1, sequence };
if (request.type === 'transpile') {
if (sequence !== 0 || controller) {
throw new Error('Packaging must be the first and only host operation');
}
const compiler = new Bun.Transpiler({ loader: 'ts', target: 'browser' });
if (
compiler.scanImports(request.source).length ||
/\b(?:import|require)\s*\(/.test(request.source)
) {
throw new Error(
'Candidate packaging accepts self-contained TypeScript without import/require edges'
);
}
// Transformation only: top-level statements are data and are never imported or evaluated.
const content = compiler.transformSync(request.source);
if (compiler.scanImports(content).length) {
throw new Error('Packaged candidate retained an import edge');
}
await writeCandidateFrame(process.stdout, {
...response,
type: 'transpiled',
content,
runtimeVersion: Bun.version,
});
process.exit(0);
} else if (request.type === 'init') {
if (controller || sequence !== 0) {
throw new Error('Candidate host already initialized');
}
identity = freeze(request.identity);
const program = await importRetainedProgram(
request.package as Parameters<typeof importRetainedProgram>[0],
request.selection
);
controller = new StrategyController(identity, [program], {
matching: { owners: [{ ownerId: request.selection.ownerId, mode: 'Target' }] },
});
await writeCandidateFrame(process.stdout, { ...response, type: 'ready' });
} else {
if (!controller || !identity) {
throw new Error('Candidate host is not initialized');
}
if (request.type === 'stage') {
sameIdentity(request.published.identity, identity);
if (request.published.step.type !== 'decisionBatch') {
throw new Error('Candidate requires a decision barrier');
}
freeze(request.published);
const decisions = controller.stage(request.published.step, request.published.observations);
await writeCandidateFrame(process.stdout, { ...response, type: 'decisions', decisions });
} else if (request.type === 'committed') {
sameIdentity(request.admitted.identity, identity);
freeze(request.admitted.outcome);
controller.committed(request.admitted.outcome);
await writeCandidateFrame(process.stdout, { ...response, type: 'ack' });
} else {
await writeCandidateFrame(process.stdout, { ...response, type: 'finished' });
process.exit(0);
}
}
sequence++;
}
throw new Error('Candidate supervisor disconnected before finish');
} catch (error) {
try {
await writeCandidateFrame(process.stdout, {
version: 1,
sequence,
type: 'error',
message: String(error).slice(0, 4096),
});
} finally {
process.exit(1);
}
}

View file

@ -0,0 +1,89 @@
/** Bounded transport, shared by the restricted host and its untrusted-output supervisor. */
import { Readable, Writable } from 'node:stream';
import { z } from 'zod';
import {
candidateSandboxLimits,
retainedProgramSelectionSchema,
} from '@stock-bot/stock-config/candidate-execution';
import { parseFinancialStrategyDecision } from '@stock-bot/types';
import { replayIdentitySchema, stepSchema, submissionSchema } from '../contracts/native-replay';
const base = {
version: z.literal(1),
sequence: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
};
export const candidateRequestSchema = z.discriminatedUnion('type', [
z.object({ ...base, type: z.literal('transpile'), source: z.string().min(1) }).strict(),
z
.object({
...base,
type: z.literal('init'),
identity: replayIdentitySchema,
package: z.unknown(),
selection: retainedProgramSelectionSchema,
})
.strict(),
z.object({ ...base, type: z.literal('stage'), published: stepSchema }).strict(),
z.object({ ...base, type: z.literal('committed'), admitted: submissionSchema }).strict(),
z.object({ ...base, type: z.literal('finish') }).strict(),
]);
export const candidateResponseSchema = z.discriminatedUnion('type', [
z.object({ ...base, type: z.literal('ready') }).strict(),
z
.object({
...base,
type: z.literal('transpiled'),
content: z.string(),
runtimeVersion: z.string().min(1),
})
.strict(),
z
.object({
...base,
type: z.literal('decisions'),
decisions: z.array(z.unknown().transform(parseFinancialStrategyDecision)).length(1),
})
.strict(),
z.object({ ...base, type: z.literal('ack') }).strict(),
z.object({ ...base, type: z.literal('finished') }).strict(),
z.object({ ...base, type: z.literal('error'), message: z.string().max(4096) }).strict(),
]);
export type CandidateResponse = z.infer<typeof candidateResponseSchema>;
export async function writeCandidateFrame(stream: Writable, value: unknown): Promise<void> {
const body = Buffer.from(JSON.stringify(value));
if (body.length > candidateSandboxLimits.frameBytes) {
throw new Error('Candidate protocol frame exceeds its retained resource limit');
}
const header = Buffer.alloc(4);
header.writeUInt32BE(body.length);
await new Promise<void>((resolve, reject) =>
stream.write(Buffer.concat([header, body]), error => (error ? reject(error) : resolve()))
);
}
export async function* readCandidateFrames(stream: Readable): AsyncGenerator<unknown> {
let buffer = Buffer.alloc(0);
for await (const raw of stream) {
const chunk = Buffer.isBuffer(raw) ? raw : Buffer.from(raw as string);
// Readable chunks are bounded by stream buffering; reject oversized buffered input before parsing.
if (buffer.length + chunk.length > candidateSandboxLimits.frameBytes + 4) {
throw new Error('Candidate protocol buffer exceeds its retained resource limit');
}
buffer = Buffer.concat([buffer, chunk]);
while (buffer.length >= 4) {
const length = buffer.readUInt32BE(0);
if (length === 0 || length > candidateSandboxLimits.frameBytes) {
throw new Error('Invalid or oversized candidate protocol frame');
}
if (buffer.length < length + 4) {
break;
}
const content = buffer.subarray(4, length + 4);
buffer = buffer.subarray(length + 4);
yield JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(content));
}
}
if (buffer.length) {
throw new Error('Truncated candidate protocol frame');
}
}

View file

@ -0,0 +1,467 @@
/** Trusted launcher. Candidate code is never imported in this process. */
import { execFile, spawn, type ChildProcessWithoutNullStreams } from 'node:child_process';
import { createHash } from 'node:crypto';
import { mkdtemp, readFile, realpath, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { promisify } from 'node:util';
import {
candidateExecutionSchema,
candidateSandboxLimits,
type CandidateExecution,
} from '@stock-bot/stock-config/candidate-execution';
import type { CanonicalRunRequest } from '@stock-bot/stock-config/canonical-research';
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
import { parseFinancialStrategyDecision } from '@stock-bot/types';
import type { ReplaySubmissionOutcome } from '../contracts/native-replay';
import {
candidateResponseSchema,
readCandidateFrames,
writeCandidateFrame,
type CandidateResponse,
} from './candidate-protocol';
import type {
AsyncReplayController,
DecisionContext,
PublishedObservation,
ReplayIdentity,
} from './native-replay';
const runFile = promisify(execFile);
const docker = '/usr/bin/docker';
const daemon = ['--host', 'unix:///var/run/docker.sock'];
const environment = (config: string) => ({ PATH: '/usr/bin:/bin', DOCKER_CONFIG: config });
const root = resolve(dirname(fileURLToPath(import.meta.resolve('@stock-bot/engine'))), '../../..');
export const candidateDescriptorPath = resolve(
root,
'apps/stock/orchestrator/dist/candidate-sandbox.json'
);
export class CandidateSandboxUnavailable extends Error {
readonly code = 'candidate_sandbox_unavailable';
}
async function dockerRead(args: string[]) {
const config = await mkdtemp(join(tmpdir(), 'stock-bot-docker-client-'));
try {
return (
await runFile(docker, [...daemon, ...args], {
env: environment(config),
timeout: 10000,
maxBuffer: 65536,
})
).stdout.trim();
} finally {
await rm(config, { recursive: true, force: true });
}
}
export async function readCandidateExecution(): Promise<CandidateExecution> {
try {
if (process.platform !== 'linux' || process.arch !== 'x64') {
throw new Error('Unsupported candidate platform');
}
const execution = candidateExecutionSchema.parse(
JSON.parse(await readFile(candidateDescriptorPath, 'utf8'))
);
const files = [
resolve(root, 'apps/stock/orchestrator/dist/candidate-host.js'),
resolve(root, 'apps/stock/orchestrator/dist/candidate-guardian'),
await realpath(process.execPath),
];
const hashes = await Promise.all(
files.map(async path =>
createHash('sha256')
.update(await readFile(path))
.digest('hex')
)
);
if (
hashes[0] !== execution.profile.hostSha256 ||
hashes[1] !== execution.profile.guardianSha256 ||
hashes[2] !== execution.profile.bunSha256
) {
throw new Error('Candidate installed host/runtime bytes differ');
}
const info = JSON.parse(await dockerRead(['info', '--format', '{{json .}}'])) as Record<
string,
unknown
>;
if (
info.OSType !== 'linux' ||
info.CgroupVersion !== '2' ||
info.MemoryLimit !== true ||
info.SwapLimit !== true ||
info.CpuCfsQuota !== true ||
info.PidsLimit !== true ||
!Array.isArray(info.SecurityOptions) ||
!info.SecurityOptions.some(v => String(v).startsWith('name=seccomp')) ||
!info.SecurityOptions.some(v => String(v).startsWith('name=apparmor'))
) {
throw new Error('Candidate cgroup/seccomp/AppArmor isolation is unavailable');
}
if (
(await dockerRead(['image', 'inspect', execution.imageId, '--format', '{{.Id}}'])) !==
execution.imageId
) {
throw new Error('Candidate exact image is unavailable');
}
return execution;
} catch (cause) {
throw new CandidateSandboxUnavailable('The exact isolated candidate runtime is unavailable', {
cause,
});
}
}
export async function verifyCandidateExecution(expected: CandidateExecution): Promise<void> {
if (
canonicalStrategyJson(await readCandidateExecution()) !==
canonicalStrategyJson(candidateExecutionSchema.parse(expected))
) {
throw new CandidateSandboxUnavailable(
'The retained isolated candidate runtime is not installed'
);
}
}
export function validateCandidateContainerName(value: string): string {
if (!/^stock-bot-candidate-[0-9a-f-]{36}$/.test(value)) {
throw new Error('Invalid owned candidate container name');
}
return value;
}
/** Removal is exact-name only; never touches other research or operator containers. */
export async function removeCandidateContainer(name: string): Promise<void> {
validateCandidateContainerName(name);
try {
await dockerRead(['rm', '--force', name]);
} catch (cause) {
// A successful --rm exit races explicit cancellation cleanup. Confirm absence.
if ((await dockerRead(['ps', '--all', '--quiet', '--filter', `name=^/${name}$`])) !== '') {
throw cause;
}
}
}
export class IsolatedCandidateController implements AsyncReplayController {
private readonly child: ChildProcessWithoutNullStreams;
private readonly closed: Promise<{ code: number | null; signal: NodeJS.Signals | null }>;
private failure: Error | undefined;
private pending:
| {
sequence: number;
type: CandidateResponse['type'];
resolve(value: CandidateResponse): void;
reject(error: Error): void;
}
| undefined;
private sequence = 0;
private decisionSequence = 0;
private stderr = Buffer.alloc(0);
private readonly timer: ReturnType<typeof setTimeout>;
private disposed = false;
private expectedExit = false;
private hasClosed = false;
private readonly identity: ReplayIdentity | undefined;
private constructor(
private readonly request: CandidateRequest | null,
private readonly name: string,
deadlineAt: number,
private readonly dockerConfig: string,
execution: CandidateExecution
) {
this.identity = request
? { version: 1, sessionId: request.runId, datasetHash: request.datasetHash }
: undefined;
const limits = candidateSandboxLimits;
this.child = spawn(
docker,
[
...daemon,
'run',
'--rm',
'--interactive',
'--pull=never',
'--name',
name,
'--network',
'none',
'--ipc',
'none',
'--read-only',
'--tmpfs',
`/tmp:rw,nosuid,nodev,noexec,size=${limits.tmpBytes}`,
'--memory',
String(limits.memoryBytes),
'--memory-swap',
String(limits.memoryBytes),
'--cpus',
String(limits.cpuQuota),
'--pids-limit',
String(limits.pids),
'--cap-drop',
'ALL',
'--cap-add',
'SETUID',
'--cap-add',
'SETGID',
'--cap-add',
'KILL',
'--security-opt',
'no-new-privileges=true',
'--log-driver',
'none',
execution.imageId,
String(deadlineAt),
],
{ env: environment(dockerConfig), stdio: ['pipe', 'pipe', 'pipe'] }
);
this.child.stdin.on('error', cause => this.fail(cause));
this.child.stderr.on('data', (chunk: Buffer) => {
this.stderr = Buffer.concat([this.stderr, chunk]).subarray(-limits.stderrBytes);
});
this.closed = new Promise(resolveClosed => {
this.child.once('error', cause => this.fail(cause));
this.child.once('close', (code, signal) => {
this.hasClosed = true;
if (!this.disposed && (!this.expectedExit || this.pending)) {
this.fail(
new Error(`Candidate host exited before completion (code ${code}, signal ${signal})`)
);
}
resolveClosed({ code, signal });
});
});
this.timer = setTimeout(
() => this.fail(new Error('Candidate host exceeded its wall deadline')),
Math.max(1, deadlineAt - Date.now())
);
void this.readResponses();
}
static async start(
request: CanonicalRunRequest,
name: string,
suppliedDeadline?: number
): Promise<IsolatedCandidateController> {
if (request.strategy.origin !== 'candidate') {
throw new Error('Only candidates may use the isolated controller');
}
validateCandidateContainerName(name);
await verifyCandidateExecution(request.strategy.execution);
const deadlineAt = Math.min(
Date.now() + candidateSandboxLimits.wallMs,
suppliedDeadline ?? Infinity
);
if (!Number.isSafeInteger(deadlineAt) || deadlineAt <= Date.now()) {
throw new Error('Candidate execution deadline is expired or invalid');
}
const config = await mkdtemp(join(tmpdir(), 'stock-bot-docker-client-'));
const controller = new IsolatedCandidateController(
request as CandidateRequest,
name,
deadlineAt,
config,
request.strategy.execution
);
try {
await controller.exchange('ready', {
type: 'init',
identity: controller.identity,
package: request.strategy.package,
selection: request.strategy.selection,
});
return controller;
} catch (cause) {
try {
await controller.dispose();
} catch (cleanup) {
throw new AggregateError([cause, cleanup], 'Candidate initialization and cleanup failed');
}
throw cause;
}
}
static async transpile(
source: string,
name: string
): Promise<{ content: string; runtimeVersion: string; execution: CandidateExecution }> {
validateCandidateContainerName(name);
const execution = await readCandidateExecution();
const config = await mkdtemp(join(tmpdir(), 'stock-bot-docker-client-'));
const controller = new IsolatedCandidateController(
null,
name,
Date.now() + candidateSandboxLimits.wallMs,
config,
execution
);
try {
const response = await controller.exchange('transpiled', { type: 'transpile', source });
const status = await controller.closed;
if (response.type !== 'transpiled' || controller.failure || status.code !== 0) {
throw controller.failure ?? new Error('Candidate packaging failed');
}
return { content: response.content, runtimeVersion: response.runtimeVersion, execution };
} finally {
await controller.dispose();
}
}
private fail(error: Error) {
this.failure ??= error;
const pending = this.pending;
this.pending = undefined;
pending?.reject(this.failure);
this.child.stdin.destroy();
}
private async readResponses() {
try {
for await (const raw of readCandidateFrames(this.child.stdout)) {
const response = candidateResponseSchema.parse(raw);
const pending = this.pending;
if (
!pending ||
response.sequence !== pending.sequence ||
(response.type !== pending.type && response.type !== 'error')
) {
throw new Error('Unsolicited or mismatched candidate response');
}
if (response.type === 'error') {
throw new Error(`Candidate strategy failed: ${response.message}`);
}
if (response.type === 'finished' || response.type === 'transpiled') {
this.expectedExit = true;
}
this.pending = undefined;
pending.resolve(response);
}
if (!this.disposed && !this.expectedExit) {
this.fail(new Error('Candidate protocol closed before completion'));
}
} catch (cause) {
this.fail(cause instanceof Error ? cause : new Error(String(cause)));
}
}
private async exchange(
type: CandidateResponse['type'],
message: Record<string, unknown>
): Promise<CandidateResponse> {
if (this.failure) {
throw this.failure;
}
if (this.pending || this.disposed || this.hasClosed || this.expectedExit) {
throw new Error('Candidate controller is unavailable or busy');
}
const sequence = this.sequence++;
const response = new Promise<CandidateResponse>((resolveResponse, reject) => {
this.pending = { sequence, type, resolve: resolveResponse, reject };
});
void response.catch(() => undefined);
try {
await writeCandidateFrame(this.child.stdin, { version: 1, sequence, ...message });
} catch (cause) {
this.fail(cause instanceof Error ? cause : new Error(String(cause)));
}
return response;
}
async stage(context: DecisionContext, observations: readonly PublishedObservation[]) {
const response = await this.exchange('decisions', {
type: 'stage',
published: { identity: this.identity, step: context, observations },
});
if (response.type !== 'decisions') {
throw new Error('Expected candidate decisions');
}
const decision = parseFinancialStrategyDecision(response.decisions[0]);
if (!this.request || !this.identity) {
throw new Error('Packaging host cannot make decisions');
}
const selected = this.request.strategy.selection;
const expectedId = JSON.stringify([
'strategy',
selected.ownerId,
selected.strategyId,
selected.strategyVersion,
this.decisionSequence,
]);
if (
context.barrier.owner_ids.length !== 1 ||
context.barrier.owner_ids[0] !== selected.ownerId ||
decision.sessionId !== this.identity.sessionId ||
decision.barrierId !== context.barrier.barrier_id ||
decision.revision !== context.barrier.revision ||
decision.decision.ownerId !== selected.ownerId ||
decision.decision.sequence !== this.decisionSequence ||
decision.decision.decisionId !== expectedId ||
decision.intent.mode !== 'target'
) {
throw new Error('Candidate returned a forged decision identity or mode');
}
return [decision];
}
async committed(outcome: ReplaySubmissionOutcome): Promise<void> {
if (!this.identity) {
throw new Error('Packaging host cannot accept financial acknowledgements');
}
await this.exchange('ack', {
type: 'committed',
admitted: { identity: this.identity, outcome },
});
this.decisionSequence++;
}
async finish(): Promise<void> {
await this.exchange('finished', { type: 'finish' });
const status = await this.closed;
if (this.failure || status.code !== 0) {
throw this.failure ?? new Error(`Candidate host did not exit successfully: ${this.stderr}`);
}
}
async dispose(): Promise<void> {
if (this.disposed) {
return;
}
this.disposed = true;
if (this.pending) {
this.fail(new Error('Candidate controller disposed before acknowledgement'));
}
clearTimeout(this.timer);
this.child.stdin.destroy();
const errors: unknown[] = [];
// Always attempt every cleanup stage, including when the daemon is unavailable.
// The independent guardian still enforces its frozen wall deadline in that case.
try {
await removeCandidateContainer(this.name);
} catch (error) {
errors.push(error);
}
if (!this.hasClosed) {
this.child.kill('SIGKILL');
}
let timer: ReturnType<typeof setTimeout> | undefined;
try {
await Promise.race([
this.closed,
new Promise<never>((_, reject) => {
timer = setTimeout(
() => reject(new Error('Candidate Docker client did not close during cleanup')),
10000
);
}),
]);
} catch (error) {
errors.push(error);
} finally {
clearTimeout(timer);
}
try {
await rm(this.dockerConfig, { recursive: true, force: true });
} catch (error) {
errors.push(error);
}
if (errors.length) {
throw new AggregateError(
this.failure ? [this.failure, ...errors] : errors,
'Candidate cleanup failed'
);
}
}
}
type CandidateRequest = CanonicalRunRequest & {
strategy: Extract<CanonicalRunRequest['strategy'], { origin: 'candidate' }>;
};

View file

@ -17,7 +17,8 @@ export interface BacktestExecutionEngine extends Pick<EventEmitter, 'on' | 'off'
): Promise<BacktestResult | NativeBacktestResult>;
runCanonical?(
request: CanonicalRunRequest,
resolveDataset: (signal: AbortSignal) => Promise<HistoricalDatasetV2>
resolveDataset: (signal: AbortSignal) => Promise<HistoricalDatasetV2>,
controls?: { executionDeadlineAt?: number }
): Promise<Pick<CanonicalRunResult, 'financial' | 'analytics'>>;
stopBacktest(): Promise<void>;
pauseBacktest(): Promise<void>;

View file

@ -1,4 +1,8 @@
import { z } from 'zod';
import {
candidateExecutionSchema,
type CandidateExecution,
} from '@stock-bot/stock-config/candidate-execution';
import {
canonicalBuildIdentitySchema,
canonicalRunRequestSchema,
@ -19,6 +23,11 @@ export const retainedStrategyRequestSchema = z
type: z.literal('runRetainedStrategy'),
request: canonicalRunRequestSchema,
dataset: z.unknown(),
executionDeadlineAt: z.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional(),
candidateContainerName: z
.string()
.regex(/^stock-bot-candidate-[0-9a-f-]{36}$/)
.optional(),
})
.strict();
@ -33,6 +42,7 @@ export interface RetainedStrategyResult {
version: 1;
build: CanonicalBuildIdentity;
artifactHash: string;
execution?: CandidateExecution;
financial: ReplayReportResult;
analytics: CanonicalBacktestAnalytics;
}
@ -43,6 +53,7 @@ const retainedStrategyResultSchema = z
version: z.literal(1),
build: canonicalBuildIdentitySchema,
artifactHash: z.string().regex(/^[a-f0-9]{64}$/),
execution: candidateExecutionSchema.optional(),
financial: z.unknown(),
analytics: z.unknown(),
})
@ -60,6 +71,14 @@ export function parseRetainedStrategyResult(
) {
throw new Error('Retained strategy result build/artifact identity mismatch');
}
if (
request.strategy.origin === 'candidate'
? canonicalStrategyJson(envelope.execution) !==
canonicalStrategyJson(request.strategy.execution)
: envelope.execution !== undefined
) {
throw new Error('Retained strategy result execution identity mismatch');
}
const financial = parseCanonicalFinancialResult(envelope.financial, request);
const analytics = buildCanonicalBacktestReport(financial, request.analyticsPolicy).analytics;
if (canonicalStrategyJson(envelope.analytics) !== canonicalStrategyJson(analytics)) {

View file

@ -1,14 +1,21 @@
import { createHash } from 'node:crypto';
import type { StrategyProgram } from '../contracts/canonical-strategy';
import type { StrategyReplayResult } from '../contracts/strategy-replay';
import {
createBuiltinStrategy,
validateBuiltinStrategyBindings,
} from '../strategies/canonical-builtins';
import { freeze } from '../strategies/strategy-decision';
import {
importRetainedProgram,
verifyRetainedProgramPackage,
} from '../strategies/retained-program';
import { IsolatedCandidateController } from './candidate-sandbox';
import { verifyCanonicalWorkerBuild } from './canonical-build';
import { buildCanonicalBacktestReport } from './canonical-result';
import { executeReplayTrace, prepareReplayLoad } from './native-replay';
import {
executeReplayTrace,
NativeReplaySession,
prepareReplayLoad,
runReplaySessionAsync,
} from './native-replay';
import {
nativeWorkerRequestSchema,
type NativeWorkerMessage,
@ -34,17 +41,7 @@ process.once('message', async (input: unknown) => {
const admitted = request.request;
// Identity checks precede bundle import, including any top-level module side effects.
const build = await verifyCanonicalWorkerBuild(admitted.build, import.meta.url);
const pkg = admitted.strategy.package;
const hash = (content: string) => createHash('sha256').update(content, 'utf8').digest('hex');
if (
hash(pkg.artifact.content) !== pkg.artifact.sha256 ||
hash(pkg.dependencyLock.content) !== pkg.dependencyLock.sha256
) {
throw new Error('Retained strategy artifact or dependency lock hash mismatch');
}
if (pkg.program.apiVersion !== 'canonical-ts/v1') {
throw new Error('Unsupported retained strategy API version');
}
const pkg = verifyRetainedProgramPackage(admitted.strategy.package);
const load = prepareReplayLoad(request.dataset, admitted.policy);
if (
load.identity.datasetHash !== admitted.datasetHash ||
@ -53,50 +50,48 @@ process.once('message', async (input: unknown) => {
) {
throw new Error('Retained strategy requires its exact eligible single-series dataset');
}
const selection = admitted.strategy.selection;
validateBuiltinStrategyBindings([selection], load);
// Only server-admitted built-ins reach this trusted worker path. Candidate
// execution requires separate isolation; import is never performed by an API.
// Bun's data-URL loader rejects real bundle-sized specifiers. A Blob keeps
// these exact UTF-8 bytes in memory without temporary files surviving SIGKILL.
const moduleUrl = URL.createObjectURL(
new Blob([pkg.artifact.content], { type: 'text/javascript' })
);
let module: Record<string, unknown>;
try {
module = await import(moduleUrl);
} finally {
URL.revokeObjectURL(moduleUrl);
}
const factory = module[pkg.artifact.entryExport];
if (typeof factory !== 'function') {
throw new Error('Retained strategy factory export is missing');
}
const program = factory(freeze(structuredClone(selection))) as StrategyProgram;
if (
!program ||
typeof program !== 'object' ||
program.ownerId !== selection.ownerId ||
program.strategyId !== selection.strategyId ||
program.strategyVersion !== selection.strategyVersion ||
program.seed !== selection.seed ||
program.mode !== 'target' ||
typeof program.decide !== 'function'
) {
throw new Error('Retained strategy factory identity or API mismatch');
}
await send({
type: 'progress',
progress: 0,
message: 'Retained canonical strategy replay started',
});
const { result } = runStrategyReplay(load, [program], { resultFormat: 'report' });
let result;
if (admitted.strategy.origin === 'candidate') {
if (!request.candidateContainerName) {
throw new Error('Isolated candidate lacks its owned container identity');
}
const controller = await IsolatedCandidateController.start(
admitted,
request.candidateContainerName,
request.executionDeadlineAt
);
try {
result = (
await runReplaySessionAsync(new NativeReplaySession(load), controller, {
resultFormat: 'report',
})
).result;
await controller.finish();
} finally {
await controller.dispose();
}
} else {
validateBuiltinStrategyBindings([admitted.strategy.selection], load);
const program = await importRetainedProgram(pkg, admitted.strategy.selection);
result = runStrategyReplay(load, [program], { resultFormat: 'report' }).result;
}
if (!('format' in result) || result.format !== 'report') {
throw new Error('Retained replay requires the canonical report format');
}
const report = buildCanonicalBacktestReport(result, admitted.analyticsPolicy);
const envelope: RetainedStrategyResult = {
type: 'retainedStrategyResult',
version: 1,
build,
artifactHash: pkg.artifact.sha256,
...(admitted.strategy.origin === 'candidate'
? { execution: admitted.strategy.execution }
: {}),
financial: report.financial,
analytics: report.analytics,
};

View file

@ -0,0 +1,218 @@
//! Minimal Linux x86_64 PID1. This executable contains no strategy/data logic.
use std::{
os::{fd::FromRawFd, unix::process::CommandExt},
process::{Command, Stdio},
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
};
#[repr(C)]
struct Filter {
code: u16,
jt: u8,
jf: u8,
k: u32,
}
#[repr(C)]
struct Program {
len: u16,
filter: *const Filter,
}
#[repr(C)]
struct PollFd {
fd: i32,
events: i16,
revents: i16,
}
#[repr(C)]
struct Limit {
current: u64,
maximum: u64,
}
unsafe extern "C" {
fn prctl(option: i32, ...) -> i32;
fn setgid(gid: u32) -> i32;
fn setuid(uid: u32) -> i32;
fn setgroups(size: usize, list: *const u32) -> i32;
fn setrlimit(resource: i32, limit: *const Limit) -> i32;
fn poll(fds: *mut PollFd, nfds: usize, timeout: i32) -> i32;
fn kill(pid: i32, signal: i32) -> i32;
}
fn stmt(code: u16, k: u32) -> Filter {
Filter {
code,
jt: 0,
jf: 0,
k,
}
}
fn equal(k: u32, jt: u8, jf: u8) -> Filter {
Filter {
code: 0x15,
jt,
jf,
k,
}
}
fn error() -> std::io::Error {
std::io::Error::last_os_error()
}
fn main() {
if !cfg!(all(target_os = "linux", target_arch = "x86_64")) {
std::process::exit(126);
}
let deadline: u128 = std::env::args()
.nth(1)
.and_then(|s| s.parse().ok())
.unwrap_or(0);
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("system clock")
.as_millis();
if deadline <= now || deadline - now > 300_000 {
std::process::exit(124);
}
let remaining = Duration::from_millis((deadline - now) as u64);
let clock = Instant::now();
let mut command = Command::new("/usr/bin/bun");
command
.arg("/app/candidate-host.js")
.current_dir("/tmp")
.env_clear()
.stdin(Stdio::inherit())
.stdout(Stdio::piped())
.stderr(Stdio::inherit());
unsafe {
command.pre_exec(|| {
if setgroups(0, std::ptr::null()) != 0 || setgid(65534) != 0 || setuid(65534) != 0 {
return Err(error());
}
if setrlimit(
0,
&Limit {
current: 300,
maximum: 300,
},
) != 0
|| setrlimit(
4,
&Limit {
current: 0,
maximum: 0,
},
) != 0
{
return Err(error());
}
if prctl(38, 1, 0, 0, 0) != 0 {
return Err(error());
}
// Check architecture and reject x32 syscall-number aliases before any allow rule.
let mut filter = vec![
stmt(0x20, 4),
equal(0xc000003e, 1, 0),
stmt(0x06, 0x80000000),
stmt(0x20, 0),
Filter {
code: 0x35,
jt: 0,
jf: 1,
k: 0x40000000,
},
stmt(0x06, 0x00050001),
];
// fork, vfork, socket, ptrace, mount, umount2, unshare, setns, bpf, perf_event_open.
for nr in [57, 58, 41, 101, 165, 166, 272, 308, 321, 298] {
filter.push(equal(nr, 0, 1));
filter.push(stmt(0x06, 0x00050001));
}
// clone3 cannot inspect the pointed-to flags; make libc use checked clone instead.
filter.push(equal(435, 0, 1));
filter.push(stmt(0x06, 0x00050026));
filter.push(equal(56, 0, 4));
filter.push(stmt(0x20, 16));
filter.push(Filter {
code: 0x45,
jt: 0,
jf: 1,
k: 0x00010000,
});
filter.push(stmt(0x06, 0x7fff0000));
filter.push(stmt(0x06, 0x00050001));
filter.push(stmt(0x06, 0x7fff0000));
let program = Program {
len: filter.len() as u16,
filter: filter.as_ptr(),
};
if prctl(22, 2, &program as *const Program) != 0 {
return Err(error());
}
Ok(())
});
}
let mut child = command
.spawn()
.expect("restricted host initialization failed");
let mut output = child.stdout.take().expect("restricted host stdout missing");
let output_closed = Arc::new(AtomicBool::new(false));
let relay_closed = Arc::clone(&output_closed);
// A bounded std::io::copy buffer relays bytes only. A separate watchdog remains
// responsive even if the child floods stdout or the consumer stops reading.
// Direct File writes avoid line-buffering the binary protocol.
std::thread::spawn(move || {
let mut destination = unsafe { std::fs::File::from_raw_fd(1) };
let _ = std::io::copy(&mut output, &mut destination);
relay_closed.store(true, Ordering::Release);
});
let mut exit_status = None;
let mut stdout_closed_at = None;
loop {
if exit_status.is_none() {
if let Some(status) = child.try_wait().expect("restricted host wait failed") {
exit_status = Some(status.code().unwrap_or(125));
}
}
if output_closed.load(Ordering::Acquire) {
if let Some(code) = exit_status {
// Drain the complete final frame before ending a normal finish/transpile.
std::process::exit(code);
}
stdout_closed_at.get_or_insert_with(Instant::now);
}
// EOF can precede the child's normal exit by a few scheduler turns.
let protocol_closed =
stdout_closed_at.is_some_and(|at| at.elapsed() >= Duration::from_millis(100));
let mut input = PollFd {
fd: 0,
events: 0,
revents: 0,
};
let ready = unsafe { poll(&mut input, 1, 0) };
let disconnected = ready < 0 || input.revents & (0x10 | 0x08 | 0x20) != 0;
if disconnected || protocol_closed || clock.elapsed() >= remaining {
unsafe {
kill(child.id() as i32, 9);
}
let _ = child.wait();
eprintln!(
"Candidate host {}",
if disconnected {
"supervisor disconnected"
} else if protocol_closed {
"protocol stdout closed"
} else {
"wall deadline exceeded"
}
);
// Exiting namespace PID1 kills remaining threads/processes independently of JS.
std::process::exit(if disconnected || protocol_closed {
125
} else {
124
});
}
std::thread::sleep(Duration::from_millis(10));
}
}

View file

@ -1,4 +1,5 @@
import { asValue, type AwilixContainer } from 'awilix';
import { z } from 'zod';
import type { ServiceCradle as ServiceDefinitions } from '@stock-bot/di';
import { BacktestRunner } from './backtest/BacktestRunner';
import { PostgresBacktestRunRepository } from './backtest/PostgresBacktestRunRepository';
@ -10,6 +11,7 @@ import { PostgresCanonicalExecutionRepository } from './execution/PostgresCanoni
import { BacktestHandler } from './handlers/backtest/backtest.handler';
import { CanonicalPaperRuntime } from './paper/CanonicalPaperRuntime';
import { validatePaperConfiguration } from './paper/feed';
import { PaperDeploymentHost } from './paper/PaperDeploymentHost';
import { AnalyticsService } from './services/AnalyticsService';
import { StorageService } from './services/StorageService';
import { createBuiltinStrategy } from './strategies/canonical-builtins';
@ -29,6 +31,45 @@ export function assertSupportedComposition(role: OrchestratorRole, useRustEngine
}
}
/** Validate before opening resources as well as before registering runtime services. */
export function resolvePaperComposition(
role: OrchestratorRole,
canonicalInput?: PaperConfigurationInput,
deploymentInput?: unknown
) {
if ((canonicalInput !== undefined || deploymentInput !== undefined) && role !== 'paper') {
throw new Error('Canonical paper configuration requires a paper composition');
}
if (canonicalInput !== undefined && deploymentInput !== undefined) {
throw new Error('Choose canonicalPaper or paperDeploymentHost, never two account owners');
}
const canonicalPaper =
canonicalInput === undefined ? undefined : validatePaperConfiguration(canonicalInput);
if (canonicalPaper && canonicalPaper.version !== 1) {
throw new Error('Promoted paper strategies require an explicitly reviewed deployment host');
}
const paperDeploymentHost =
deploymentInput === undefined
? undefined
: z
.object({
enabled: z.literal(true),
deploymentId: z
.string()
.uuid()
.transform(id => id.toLowerCase())
.optional(),
})
.strict()
.parse(deploymentInput);
if (role === 'paper' && !canonicalPaper && !paperDeploymentHost) {
throw new Error(
'Paper composition requires explicit canonicalPaper or paperDeploymentHost configuration; accounts are never migrated automatically'
);
}
return { canonicalPaper, paperDeploymentHost };
}
/**
* Register orchestrator-specific services in the DI container
*/
@ -43,6 +84,7 @@ export async function registerOrchestratorServices(
nativeExecutionTimeoutMs?: number;
maxConcurrent?: number;
canonicalPaper?: PaperConfigurationInput;
paperDeploymentHost?: { enabled: true; deploymentId?: string };
} = {}
): Promise<void> {
const role = options.role === undefined ? 'research-only' : options.role;
@ -50,18 +92,11 @@ export async function registerOrchestratorServices(
assertSupportedComposition(role, useRustEngine);
const maxConcurrent = options.maxConcurrent === undefined ? 1 : options.maxConcurrent;
assertResearchConcurrency(maxConcurrent);
if (options.canonicalPaper !== undefined && role !== 'paper') {
throw new Error('Canonical paper configuration requires a paper composition');
}
const canonicalPaper =
options.canonicalPaper === undefined
? undefined
: validatePaperConfiguration(options.canonicalPaper);
if (role === 'paper' && !canonicalPaper) {
throw new Error(
'Paper composition requires explicit canonicalPaper configuration; accounts are never migrated automatically'
);
}
const { canonicalPaper, paperDeploymentHost } = resolvePaperComposition(
role,
options.canonicalPaper,
options.paperDeploymentHost
);
// Create a service adapter that provides the expected interface
const services = container.resolve('serviceContainer') as IServiceContainer;
@ -72,6 +107,7 @@ export async function registerOrchestratorServices(
if (
[
'CanonicalPaperRuntime',
'PaperDeploymentHost',
'ModeManager',
'ExecutionService',
'MarketDataService',
@ -93,7 +129,7 @@ export async function registerOrchestratorServices(
options
);
if (canonicalPaper && !services.postgres) {
if ((canonicalPaper || paperDeploymentHost) && !services.postgres) {
throw new Error('Canonical paper requires durable PostgreSQL custody');
}
const paper =
@ -103,6 +139,13 @@ export async function registerOrchestratorServices(
programs: canonicalPaper.strategies.map(createBuiltinStrategy),
})
: undefined;
const deploymentHost =
paperDeploymentHost && services.postgres
? new PaperDeploymentHost({
database: services.postgres,
repository: new PostgresCanonicalExecutionRepository(services.postgres),
})
: undefined;
const runner = new ResearchBacktestPool({
runners: Array.from(
{ length: maxConcurrent },
@ -129,12 +172,14 @@ export async function registerOrchestratorServices(
AnalyticsService: analytics,
BacktestRunner: runner,
...(paper ? { CanonicalPaperRuntime: paper } : {}),
...(deploymentHost ? { PaperDeploymentHost: deploymentHost } : {}),
});
const canonicalContainer = container as AwilixContainer<
ServiceDefinitions & {
StorageService: StorageService;
AnalyticsService: AnalyticsService;
CanonicalPaperRuntime: PaperRuntime;
PaperDeploymentHost: PaperDeploymentHost;
BacktestRunner: ResearchBacktestPool;
orchestratorServices: IServiceContainer;
}
@ -145,6 +190,7 @@ export async function registerOrchestratorServices(
BacktestRunner: asValue(runner),
orchestratorServices: asValue(services),
...(paper ? { CanonicalPaperRuntime: asValue(paper) } : {}),
...(deploymentHost ? { PaperDeploymentHost: asValue(deploymentHost) } : {}),
});
container
.resolve('handlerScanner')
@ -153,10 +199,14 @@ export async function registerOrchestratorServices(
if (paper && canonicalPaper && options.initializeMode !== false) {
await paper.initialize(canonicalPaper);
}
if (deploymentHost && paperDeploymentHost?.deploymentId && options.initializeMode !== false) {
await deploymentHost.bind(paperDeploymentHost.deploymentId);
}
services.queueManager?.getQueue('orchestrator', { workers: 1, concurrency: maxConcurrent });
} catch (error) {
await runner.shutdown().catch(() => {});
await paper?.shutdown().catch(() => {});
await deploymentHost?.shutdown().catch(() => {});
throw error;
}
}

View file

@ -1,54 +1,22 @@
/** Explicit trusted producer boundary. No legacy timestamp repair or broker capabilities. */
import { z } from 'zod';
import {
deployedPaperConfigurationSchema,
paperPolicySchema,
} from '@stock-bot/stock-config/paper-deployments';
import { parseFinancialDecimal } from '@stock-bot/types';
import { builtinStrategySelectionSchema } from './builtin-strategy';
import { canonicalMatchingConfigSchema, matchingCommandSchema } from './canonical-execution';
import { replayConfigSchema, stepSchema } from './native-replay';
import { stepSchema } from './native-replay';
const id = matchingCommandSchema.shape.key.shape.instrumentId;
const time = matchingCommandSchema.shape.key.shape.at;
const counter = matchingCommandSchema.shape.key.shape.sourceSequence;
const duration = counter.refine(value => value > 0, 'Duration must be positive');
const decimal = z.string().transform(value => parseFinancialDecimal(value));
export const paperPolicySchema = z
.object({
version: z.literal(1),
sourceId: id,
priceBasis: z.literal('raw'),
maxFeedAgeMs: duration,
observations: z.array(
z
.object({
seriesId: id,
instrumentId: id,
intervalMs: duration,
staleAfterMs: counter,
})
.strict()
),
cadence: z.array(z.object({ ownerId: id, seriesIds: z.array(id).min(1) }).strict()),
calendars: z
.array(
z
.object({
instrumentId: id,
calendarId: id,
revision: id,
sessions: z
.array(z.object({ sessionId: id, opensAt: time, closesAt: time }).strict())
.min(1),
})
.strict()
)
.min(1),
riskBoundaries: z.array(
replayConfigSchema.shape.matching.shape.risk.shape.ledger.shape.riskSession
),
})
.strict();
export { paperPolicySchema } from '@stock-bot/stock-config/paper-deployments';
export const paperConfigurationSchema = z
const legacyPaperConfigurationSchema = z
.object({
version: z.literal(1),
matching: canonicalMatchingConfigSchema,
@ -57,6 +25,11 @@ export const paperConfigurationSchema = z
})
.strict();
export const paperConfigurationSchema = z.union([
legacyPaperConfigurationSchema,
deployedPaperConfigurationSchema,
]);
/** availableAt is the producer's atomic release time for the whole quote frame.
* Quotes retain their original physical timestamp and source sequence. The
* supplied completed bars were available by this release; quotes never synthesize bars. */

View file

@ -98,12 +98,14 @@ export class PostgresCanonicalExecutionRepository implements CanonicalExecutionR
config: account.checkpoint.config,
definitions: account.definitions,
hostConfiguration: account.host?.configuration ?? null,
deployment: account.host?.deployment ?? null,
}) !==
canonicalJson({
identity: expected.identity,
config: expected.checkpoint.config,
definitions: expected.definitions,
hostConfiguration: expected.host?.configuration ?? null,
deployment: expected.host?.deployment ?? null,
})
) {
throw new ExecutionConflictError(

View file

@ -1,6 +1,7 @@
/** Durable custody contracts. Financial values and transitions belong to Rust. */
import { z } from 'zod';
import type { PostgresClient } from '@stock-bot/services';
import { paperDeploymentBindingSchema } from '@stock-bot/stock-config/paper-deployments';
import {
canonicalExecutionCheckpointSchema,
financialTransactionResultSchema,
@ -29,6 +30,7 @@ export const canonicalPaperHostSchema = z
.object({
version: z.literal(1),
configuration: paperConfigurationSchema,
deployment: paperDeploymentBindingSchema.optional(),
generation: z.string().min(1),
active: z.boolean(),
operatorHalted: z.boolean(),

View file

@ -13,7 +13,11 @@ import { createContainer } from './simple-container';
// Initialize configuration with service-specific overrides
const config = initializeStockConfig('orchestrator');
const security = createHttpSecurity({ ...httpSecurityOptions(), environment: config.environment });
const security = createHttpSecurity({
...httpSecurityOptions(),
environment: config.environment,
browserSessions: true,
});
const logger = getLogger('orchestrator');
// Get service-specific config
@ -71,7 +75,7 @@ async function main() {
});
// Create and mount routes (without Socket.IO for now)
const routes = createRoutes(services);
const routes = createRoutes(services, undefined, security.allowedOrigins);
app.route('/', routes);
// Start Bun server
@ -153,6 +157,7 @@ async function main() {
try {
const failures: unknown[] = [];
for (const close of [
() => services.custom?.PaperDeploymentHost?.shutdown(),
() => services.custom?.CanonicalPaperRuntime?.shutdown(),
() => services.custom?.BacktestRunner?.shutdown(),
() => services.queueManager?.shutdown(),

View file

@ -1,4 +1,5 @@
import { createHash, randomUUID } from 'node:crypto';
import type { PaperDeploymentBinding } from '@stock-bot/stock-config/paper-deployments';
import type { StrategyProgram } from '../contracts/canonical-strategy';
import {
paperActivationSchema,
@ -43,6 +44,7 @@ export class CanonicalPaperRuntime implements PaperRuntime {
constructor(
private readonly options: {
repository: CanonicalExecutionRepository;
deployment?: PaperDeploymentBinding;
programs: readonly StrategyProgram[];
now?: () => number;
publish?: (entries: readonly CanonicalJournalEntry[]) => void | Promise<void>;
@ -84,6 +86,7 @@ export class CanonicalPaperRuntime implements PaperRuntime {
const host: CanonicalPaperHost = {
version: 1,
configuration,
...(this.options.deployment ? { deployment: structuredClone(this.options.deployment) } : {}),
generation: this.generation,
active: false,
operatorHalted: true,

View file

@ -0,0 +1,145 @@
import { z } from 'zod';
import type { PaperDeploymentStatus } from '@stock-bot/stock-config/paper-deployments';
import type { PaperReadiness, PaperRuntime } from '../contracts/paper-runtime';
import type { CanonicalExecutionRepository, CanonicalPostgres } from '../execution/canonical-paper';
import {
authorizedPaperPackage,
PaperDeploymentError,
paperHash,
readPaperDeployment,
verifyPaperEvidenceCustody,
} from './paper-deployment-custody';
import type { createPromotedPaperRuntime } from './paper-host';
import { paperHostUrl, readPaperHostIdentity } from './paper-host-identity';
export const unboundPaperReadiness = (reason = 'deployment-not-bound'): PaperReadiness => ({
configured: false,
accountId: null,
sourceId: null,
active: false,
ready: false,
operatorHalted: true,
connected: false,
reasons: [reason],
lastReceivedAt: null,
lastAvailableAt: null,
requiresHistoricalRecovery: false,
pendingInput: null,
pendingBatch: null,
pendingDecisionSequence: null,
nativeStatus: null,
risk: null,
});
/** One explicit paper host. No default account, scheduler, automatic activation or strategy hot swap. */
export class PaperDeploymentHost {
private bound?: { id: string; runtime: PaperRuntime };
private tail: Promise<unknown> = Promise.resolve();
private readonly startupIdentity = readPaperHostIdentity().catch(() => null);
constructor(
private readonly options: {
database: CanonicalPostgres;
repository: CanonicalExecutionRepository;
now?: () => number;
}
) {}
private serial<T>(work: () => Promise<T>): Promise<T> {
const next = this.tail.then(work, work);
this.tail = next.catch(() => undefined);
return next;
}
private async authorized(id: string) {
return this.options.database.transaction(async tx => {
const deployment = await readPaperDeployment(tx, id);
const { pkg } = await authorizedPaperPackage(tx, deployment, true);
await verifyPaperEvidenceCustody(tx, deployment);
const startup = await this.startupIdentity;
if (
!startup ||
paperHash(startup) !== paperHash(deployment.preview.host) ||
paperHash(await readPaperHostIdentity()) !== paperHash(deployment.preview.host)
) {
throw new PaperDeploymentError(
409,
'Installed paper host/native/runtime differs from the reviewed promotion'
);
}
return { deployment, pkg };
});
}
async bind(id: string): Promise<PaperDeploymentStatus> {
id = z.string().uuid().parse(id).toLowerCase();
return this.serial(async () => {
if (this.bound) {
if (this.bound.id !== id) {
throw new PaperDeploymentError(
409,
'This paper host is already bound; restart with the explicit deployment configuration to change it'
);
}
return this.status(id);
}
const { deployment, pkg } = await this.authorized(id);
const url = new URL(paperHostUrl);
url.searchParams.set('sha256', deployment.preview.host.hostSha256);
const module = (await import(url.href)) as {
createPromotedPaperRuntime: typeof createPromotedPaperRuntime;
};
const runtime = await module.createPromotedPaperRuntime({
deployment,
pkg,
repository: this.options.repository,
now: this.options.now,
});
this.bound = { id, runtime };
return this.status(id);
});
}
async activate(id: string, recoverPending = false): Promise<PaperDeploymentStatus> {
id = z.string().uuid().parse(id).toLowerCase();
return this.serial(async () => {
await this.authorized(id);
const runtime = this.runtime(id);
await runtime.activate({ recoverPending });
return this.status(id);
});
}
async halt(id: string, reason: string): Promise<PaperDeploymentStatus> {
id = z.string().uuid().parse(id).toLowerCase();
// Emergency halt remains available even if evidence/build/review later becomes unavailable.
return this.serial(async () => {
await this.runtime(id).halt(reason);
return this.status(id);
});
}
async readiness(): Promise<PaperReadiness> {
return this.bound ? this.bound.runtime.status() : unboundPaperReadiness();
}
async status(id: string): Promise<PaperDeploymentStatus> {
id = z.string().uuid().parse(id).toLowerCase();
await this.options.database.transaction(tx => readPaperDeployment(tx, id));
return {
deploymentId: id,
boundDeploymentId: this.bound?.id ?? null,
readiness:
this.bound?.id === id
? await this.bound.runtime.status()
: unboundPaperReadiness(
this.bound ? 'host-bound-to-another-deployment' : 'deployment-not-bound'
),
};
}
runtime(id?: string): PaperRuntime {
if (!this.bound || (id !== undefined && this.bound.id !== id)) {
throw new PaperDeploymentError(409, 'Deployment is not bound to this paper host');
}
return this.bound.runtime;
}
async shutdown() {
return this.serial(async () => {
await this.bound?.runtime.shutdown();
this.bound = undefined;
});
}
}

View file

@ -0,0 +1,190 @@
/** Read-only promotion custody. This module cannot import or execute strategy code. */
import { createHash } from 'node:crypto';
import type { QueryResultRow } from 'pg';
import {
paperDeploymentSchema,
type PaperDeployment,
type PaperPromotionPreview,
} from '@stock-bot/stock-config/paper-deployments';
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
import { verifyRetainedProgramPackage } from '../strategies/retained-program';
export interface PaperDeploymentDatabase {
query(text: string, values?: unknown[]): Promise<{ rows: QueryResultRow[] }>;
}
export class PaperDeploymentError extends Error {
constructor(
readonly status: 400 | 403 | 404 | 409 | 422 | 503,
message: string
) {
super(message);
}
}
export const paperHash = (value: unknown) =>
createHash('sha256').update(canonicalStrategyJson(value)).digest('hex');
export function paperPreviewHash(
preview: Omit<PaperPromotionPreview, 'previewHash'> | PaperPromotionPreview
) {
const { previewHash: _ignored, ...body } = preview as PaperPromotionPreview;
return paperHash(body);
}
export function retainedPaperDeployment(raw: unknown): PaperDeployment {
const value = paperDeploymentSchema.parse(raw);
const { promotionHash, ...body } = value;
if (
paperHash(body) !== promotionHash ||
paperPreviewHash(value.preview) !== value.preview.previewHash
) {
throw new Error('Retained paper promotion identity mismatch');
}
return value;
}
export async function readPaperDeployment(
database: PaperDeploymentDatabase,
id: string
): Promise<PaperDeployment> {
const row = (await database.query('SELECT * FROM paper_deployments WHERE id=$1', [id])).rows[0];
if (!row) {
throw new PaperDeploymentError(404, 'Paper deployment not found');
}
const value = retainedPaperDeployment(row.document);
if (
value.id !== row.id ||
value.preview.configuration.matching.risk.ledger.accountId !== row.account_id ||
value.preview.strategy.versionId !== row.strategy_version_id ||
value.promotionHash !== row.promotion_hash
) {
throw new Error('Retained paper deployment row identity mismatch');
}
return value;
}
/** Admission and activation require a current operator approval. Historical GET stays available. */
export async function authorizedPaperPackage(
database: PaperDeploymentDatabase,
deployment: PaperDeployment | Pick<PaperPromotionPreview, 'strategy'>,
lock = false
) {
const preview = 'preview' in deployment ? deployment.preview : deployment;
const version = (
await database.query(
`SELECT v.envelope,v.origin,s.archived_at FROM strategy_versions v JOIN strategies s ON s.id=v.strategy_id WHERE v.id=$1 AND s.id=$2${lock ? ' FOR UPDATE OF s' : ''}`,
[preview.strategy.versionId, preview.strategy.familyId]
)
).rows[0];
const review = (
await database.query(
'SELECT id,decision FROM strategy_review_events WHERE version_id=$1 ORDER BY ordinal DESC LIMIT 1',
[preview.strategy.versionId]
)
).rows[0];
if (!version || version.archived_at !== null || review?.decision !== 'approve') {
throw new PaperDeploymentError(
409,
'Paper deployment requires an active family and current operator approval'
);
}
const pkg = verifyRetainedProgramPackage(version.envelope);
if (
version.origin !== preview.strategy.origin ||
pkg.artifact.sha256 !== preview.strategy.artifactSha256 ||
pkg.dependencyLock.sha256 !== preview.strategy.dependencyLockSha256
) {
throw new Error('Paper promotion artifact no longer matches retained bytes');
}
return { pkg, reviewId: String(review.id) };
}
/** Host-side retained identity check, independent of the web API's full financial source reader. */
export async function verifyPaperEvidenceCustody(
database: PaperDeploymentDatabase,
deployment: PaperDeployment
) {
const { input, evidence } = deployment.preview,
source = input.outOfSample;
let report: Record<string, unknown> | undefined;
if (source.kind === 'chronological-report/v1') {
const row = (
await database.query('SELECT validation_report FROM research_experiments WHERE id=$1', [
source.validationId,
])
).rows[0];
report = row?.validation_report;
if ((report?.test as { runId?: string } | undefined)?.runId !== input.testRunId) {
throw new Error('Paper test membership changed');
}
} else if (source.kind === 'walk-forward-report/v1') {
const row = (
await database.query('SELECT report FROM research_walk_forwards WHERE id=$1', [
source.walkForwardId,
])
).rows[0];
report = row?.report;
if (
!(report?.segments as Array<{ test: { runId: string } }> | undefined)?.some(
segment => segment.test.runId === input.testRunId
)
) {
throw new Error('Paper walk-forward test membership changed');
}
} else {
throw new Error('Paper promotion requires sealed out-of-sample evidence');
}
if (!report) {
throw new Error('Paper source report is missing');
}
const { _receipt, reportHash, ...body } = report;
if (
!_receipt ||
paperHash(body) !== reportHash ||
reportHash !== source.reportHash ||
report.id !== source.reportId ||
report.previewHash !== source.previewHash
) {
throw new Error('Paper source report changed');
}
const cost = (
await database.query(
'SELECT preview,preview_hash,validation_phase FROM research_experiments WHERE id=$1',
[input.costExperimentId]
)
).rows[0];
if (
!cost ||
cost.validation_phase !== null ||
cost.preview?.version !== 'cost-sensitivity-preview/v1' ||
cost.preview_hash !== input.costPreviewHash ||
cost.preview?.previewHash !== input.costPreviewHash ||
cost.preview.candidates.length !== evidence.costs.length
) {
throw new Error('Paper cost source changed');
}
const rows = (
await database.query('SELECT id FROM runs WHERE experiment_id=$1 ORDER BY trial_index', [
input.costExperimentId,
])
).rows;
if (
canonicalStrategyJson(rows.map(row => row.id)) !==
canonicalStrategyJson(evidence.costs.map(item => item.runId))
) {
throw new Error('Paper cost membership changed');
}
for (const item of [evidence.test, ...evidence.costs]) {
const row = (
await database.query(
'SELECT r.status,r.request_snapshot,r.dataset_hash,br.canonical_result FROM runs r JOIN backtest_results br ON br.run_id=r.id WHERE r.id=$1',
[item.runId]
)
).rows[0];
if (
!row ||
row.status !== 'completed' ||
row.dataset_hash !== item.datasetHash ||
paperHash(row.canonical_result) !== item.resultHash ||
canonicalStrategyJson(row.canonical_result.request) !==
canonicalStrategyJson(row.request_snapshot)
) {
throw new Error('Paper retained result identity changed');
}
}
}

View file

@ -0,0 +1,76 @@
/** Read-only build identity. This module never imports the native addon or strategy code. */
import { createHash } from 'node:crypto';
import { realpathSync } from 'node:fs';
import { readFile } from 'node:fs/promises';
import { dirname, isAbsolute, relative, resolve } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import {
paperHostIdentitySchema,
type PaperHostIdentity,
} from '@stock-bot/stock-config/paper-deployments';
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
const engineWrapper = realpathSync(fileURLToPath(import.meta.resolve('@stock-bot/engine')));
const repositoryRoot = resolve(dirname(engineWrapper), '../../..');
const ownPath = relative(repositoryRoot, realpathSync(fileURLToPath(import.meta.url)));
if (isAbsolute(ownPath) || ownPath === '..' || ownPath.startsWith('../')) {
throw new Error('Paper engine resolves outside this checkout');
}
if (engineWrapper !== resolve(repositoryRoot, 'apps/stock/engine/index.mjs')) {
throw new Error('Unsupported canonical engine wrapper location');
}
export const paperHostUrl = pathToFileURL(
resolve(repositoryRoot, 'apps/stock/orchestrator/dist/paper-host.js')
);
async function hashLocalFile(path: string): Promise<string> {
if (realpathSync(path) !== path) {
throw new Error('Paper build artifacts must belong to this checkout');
}
return createHash('sha256')
.update(await readFile(path))
.digest('hex');
}
/** Capture all executable worker/native bytes and the runtime that interprets them. */
export async function readPaperHostIdentity(): Promise<PaperHostIdentity> {
if (typeof Bun === 'undefined') {
throw new Error('Paper deployment requires the Bun runtime');
}
const [hostSha256, engineWrapperSha256, engineBinarySha256, dependencyLockSha256] =
await Promise.all([
hashLocalFile(fileURLToPath(paperHostUrl)),
hashLocalFile(engineWrapper),
hashLocalFile(resolve(repositoryRoot, 'apps/stock/engine/dist/engine.node')),
hashLocalFile(resolve(repositoryRoot, 'bun.lock')),
]);
return paperHostIdentitySchema.parse({
version: 'paper-host/v1',
hostSha256,
engineWrapperSha256,
engineBinarySha256,
dependencyLockSha256,
runtime: 'bun',
runtimeVersion: Bun.version,
platform: process.platform,
arch: process.arch,
});
}
/** The running child supplies its own module URL, never a URL from the request. */
export async function verifyPaperHostBuild(
expected: PaperHostIdentity,
actualHostUrl: string
): Promise<PaperHostIdentity> {
if (realpathSync(fileURLToPath(actualHostUrl)) !== realpathSync(fileURLToPath(paperHostUrl))) {
throw new Error('Paper deployment requires the bundled paper host from this checkout');
}
const actual = await readPaperHostIdentity();
if (
canonicalStrategyJson(actual) !== canonicalStrategyJson(paperHostIdentitySchema.parse(expected))
) {
throw new Error('Paper host/native/runtime build identity mismatch');
}
return actual;
}

View file

@ -0,0 +1,53 @@
/** Dedicated bundled entry point. Importing it does not start a host or import a strategy. */
import { loadedNativeIdentity } from '@stock-bot/engine';
import type { PaperDeployment } from '@stock-bot/stock-config/paper-deployments';
import type { StrategyVersionPackage } from '@stock-bot/types';
import type { CanonicalExecutionRepository } from '../execution/canonical-paper';
import { importRetainedProgram } from '../strategies/retained-program';
import { CanonicalPaperRuntime } from './CanonicalPaperRuntime';
import { retainedPaperDeployment } from './paper-deployment-custody';
import { verifyPaperHostBuild } from './paper-host-identity';
/** Caller must have verified the immutable operator promotion and current permission before calling. */
export async function createPromotedPaperRuntime(options: {
deployment: PaperDeployment;
pkg: StrategyVersionPackage;
repository: CanonicalExecutionRepository;
now?: () => number;
}) {
const deployment = retainedPaperDeployment(options.deployment);
await verifyPaperHostBuild(deployment.preview.host, import.meta.url);
if (
loadedNativeIdentity.engineWrapperSha256 !== deployment.preview.host.engineWrapperSha256 ||
loadedNativeIdentity.engineBinarySha256 !== deployment.preview.host.engineBinarySha256
) {
throw new Error(
'Loaded native identity differs from paper promotion; restart with immutable build artifacts'
);
}
if (
options.pkg.artifact.sha256 !== deployment.preview.strategy.artifactSha256 ||
options.pkg.dependencyLock.sha256 !== deployment.preview.strategy.dependencyLockSha256
) {
throw new Error('Paper host artifact does not match the operator promotion');
}
const program = await importRetainedProgram(
options.pkg,
deployment.preview.configuration.strategies[0]
);
const runtime = new CanonicalPaperRuntime({
repository: options.repository,
programs: [program],
now: options.now,
deployment: {
deploymentId: deployment.id,
promotionHash: deployment.promotionHash,
strategyVersionId: deployment.preview.strategy.versionId,
artifactSha256: deployment.preview.strategy.artifactSha256,
dependencyLockSha256: deployment.preview.strategy.dependencyLockSha256,
host: deployment.preview.host,
},
});
await runtime.initialize(deployment.preview.configuration);
return runtime;
}

View file

@ -0,0 +1,23 @@
import { getCredentialHttpPrincipal } from '@stock-bot/di';
import { PaperDeploymentError } from './paper-deployment-custody';
/** Defense in depth for both public services, including bearer requests carrying browser Origin. */
export function requirePaperOperator(request: Request, origins: readonly string[]) {
if (getCredentialHttpPrincipal(request) !== 'operator') {
throw new PaperDeploymentError(
403,
'Credential-backed human operator required for paper commands'
);
}
const origin = request.headers.get('origin');
if (origin && (!origins.length || !origins.includes(origin))) {
throw new PaperDeploymentError(
403,
'Paper commands require an explicitly configured trusted Origin'
);
}
}
export const paperAllowedOrigins = () =>
process.env.STOCK_BOT_ALLOWED_ORIGINS?.split(',')
.map(v => v.trim())
.filter(Boolean) ?? [];

View file

@ -3,12 +3,17 @@ import type { Server as SocketIOServer } from 'socket.io';
import { createAnalyticsRoutes } from '../api/rest/analytics';
import { createBacktestRoutes } from '../api/rest/backtest';
import { createPaperRoutes } from '../api/rest/paper';
import { createPaperDeploymentHostRoutes } from '../api/rest/paper-deployments';
import type { OrchestratorServices as IServiceContainer } from '../types';
/**
* Create all routes for the orchestrator service
*/
export function createRoutes(services: IServiceContainer, _io?: SocketIOServer): Hono {
export function createRoutes(
services: IServiceContainer,
_io?: SocketIOServer,
origins?: readonly string[]
): Hono {
const app = new Hono();
services.logger.info('Creating orchestrator routes');
@ -17,8 +22,15 @@ export function createRoutes(services: IServiceContainer, _io?: SocketIOServer):
return c.json({
status: 'healthy',
service: 'orchestrator',
mode: services.custom?.CanonicalPaperRuntime ? 'paper' : 'research-only',
execution: services.custom?.CanonicalPaperRuntime ? 'canonical-paper' : 'canonical-research',
mode:
services.custom?.CanonicalPaperRuntime || services.custom?.PaperDeploymentHost
? 'paper'
: 'research-only',
execution: services.custom?.PaperDeploymentHost
? 'reviewed-paper-deployment'
: services.custom?.CanonicalPaperRuntime
? 'canonical-paper'
: 'canonical-research',
timestamp: new Date().toISOString(),
});
});
@ -32,13 +44,26 @@ export function createRoutes(services: IServiceContainer, _io?: SocketIOServer):
...(await services.custom.CanonicalPaperRuntime.status()),
});
}
if (services.custom?.PaperDeploymentHost) {
return c.json({
engine: 'reviewed-paper-deployment',
...(await services.custom.PaperDeploymentHost.readiness()),
});
}
return c.json({ error: 'Research-only runtime has no account execution gateway' }, 503);
} catch (error) {
services.logger.error('Could not read strategy recovery status', { error });
return c.json({ error: 'Strategy recovery status unavailable' }, 503);
}
});
app.route('/api/paper', createPaperRoutes(services));
app.route(
'/api/paper/deployments',
createPaperDeploymentHostRoutes(services.custom?.PaperDeploymentHost, origins)
);
app.route(
'/api/paper',
createPaperRoutes(services, { deploymentHost: services.custom?.PaperDeploymentHost, origins })
);
// Retired gateways remain explicit diagnostics, never a fallback simulator.
const unavailable = new Hono().all('*', c =>
c.json(

View file

@ -2,10 +2,10 @@ import { ServiceContainerBuilder } from '@stock-bot/di';
import type { StockAppConfig } from '@stock-bot/stock-config';
import { assertResearchConcurrency } from './backtest/ResearchBacktestPool';
import { paperConfigurationSchema } from './contracts/paper-runtime';
import { validatePaperConfiguration } from './paper/feed';
import {
assertSupportedComposition,
registerOrchestratorServices,
resolvePaperComposition,
type OrchestratorRole,
} from './container';
import type { OrchestratorServices } from './types';
@ -32,21 +32,17 @@ export async function createContainer(
const maxConcurrent =
settings?.backtesting?.maxConcurrent === undefined ? 1 : settings.backtesting.maxConcurrent;
assertResearchConcurrency(maxConcurrent);
if (settings?.canonicalPaper !== undefined && role !== 'paper') {
throw new Error('Canonical paper configuration requires a paper composition');
}
const canonicalPaper =
const { canonicalPaper, paperDeploymentHost } = resolvePaperComposition(
role,
settings?.canonicalPaper === undefined
? undefined
: validatePaperConfiguration(paperConfigurationSchema.parse(settings.canonicalPaper));
if (role === 'paper' && !canonicalPaper) {
throw new Error(
'Paper composition requires explicit canonicalPaper configuration; accounts are never migrated automatically'
);
}
if (canonicalPaper && !config.database?.postgres?.enabled) {
: paperConfigurationSchema.parse(settings.canonicalPaper),
settings?.paperDeploymentHost
);
if ((canonicalPaper || paperDeploymentHost) && !config.database?.postgres?.enabled) {
throw new Error('Canonical paper requires durable PostgreSQL custody');
}
const container = await new ServiceContainerBuilder()
.withConfig(config)
.withOptions({
@ -67,6 +63,7 @@ export async function createContainer(
syntheticSeed: config.services?.orchestrator?.backtesting?.syntheticSeed ?? 42,
nativeExecutionTimeoutMs: config.services?.orchestrator?.backtesting?.executionTimeoutMs,
canonicalPaper,
paperDeploymentHost,
});
return container.resolve('serviceContainer') as OrchestratorServices;
}

View file

@ -0,0 +1,70 @@
/** Executable loader: call only in an OS-isolated candidate host or after a server-owned
* trusted builtin/paper-promotion authorization. Metadata never grants that authority. */
import { createHash } from 'node:crypto';
import {
retainedProgramSelectionSchema,
type RetainedProgramSelection,
} from '@stock-bot/stock-config/candidate-execution';
import { parseStrategyVersionPackage } from '@stock-bot/stock-config/strategy';
import type { StrategyVersionPackage } from '@stock-bot/types';
import type { StrategyProgram } from '../contracts/canonical-strategy';
import { freeze } from './strategy-decision';
export type { RetainedProgramSelection } from '@stock-bot/stock-config/candidate-execution';
/** Validates bytes and metadata only; never imports, compiles or calls candidate code. */
export function verifyRetainedProgramPackage(input: unknown): StrategyVersionPackage {
const pkg = parseStrategyVersionPackage(input);
const hash = (content: string) => createHash('sha256').update(content, 'utf8').digest('hex');
if (
hash(pkg.artifact.content) !== pkg.artifact.sha256 ||
hash(pkg.dependencyLock.content) !== pkg.dependencyLock.sha256
) {
throw new Error('Retained strategy artifact or dependency lock hash mismatch');
}
if (pkg.program.apiVersion !== 'canonical-ts/v1') {
throw new Error('Unsupported retained strategy API version');
}
return pkg;
}
export async function importRetainedProgram(
input: StrategyVersionPackage,
rawSelection: RetainedProgramSelection
): Promise<StrategyProgram> {
const pkg = verifyRetainedProgramPackage(input);
const selection = retainedProgramSelectionSchema.parse(rawSelection);
if (
pkg.program.strategyId !== selection.strategyId ||
pkg.program.strategyVersion !== selection.strategyVersion
) {
throw new Error('Retained strategy selection identity mismatch');
}
const moduleUrl = URL.createObjectURL(
new Blob([pkg.artifact.content], { type: 'text/javascript' })
);
let module: Record<string, unknown>;
try {
module = await import(moduleUrl);
} finally {
URL.revokeObjectURL(moduleUrl);
}
const factory = module[pkg.artifact.entryExport];
if (typeof factory !== 'function') {
throw new Error('Retained strategy factory export is missing');
}
const program = factory(freeze(structuredClone(selection))) as StrategyProgram;
if (
!program ||
typeof program !== 'object' ||
program.ownerId !== selection.ownerId ||
program.strategyId !== selection.strategyId ||
program.strategyVersion !== selection.strategyVersion ||
program.seed !== selection.seed ||
program.mode !== 'target' ||
typeof program.decide !== 'function'
) {
throw new Error('Retained strategy factory identity or API mismatch');
}
return program;
}

View file

@ -12,7 +12,6 @@ import {
nativeAdmissionOrders,
type DecisionContext,
type PublishedObservation,
type replayConfigSchema,
type ReplayIdentity,
type ReplaySubmissionOutcome,
} from '../contracts/native-replay';
@ -48,7 +47,7 @@ export class StrategyController {
constructor(
private readonly identity: ReplayIdentity,
programs: readonly StrategyProgram[],
config: ReturnType<typeof replayConfigSchema.parse>
config: { matching: { owners: { ownerId: string; mode: 'Target' | 'Orders' }[] } }
) {
this.slots = new Map(
programs.map(program => {

View file

@ -56,6 +56,7 @@ export type OrchestratorServices = import('@stock-bot/services').IServiceContain
PaperTradingManager: import('./paper/PaperTradingManager').PaperTradingManager;
ModeManager: import('./core/ModeManager').ModeManager;
CanonicalPaperRuntime: import('./contracts/paper-runtime').PaperRuntime;
PaperDeploymentHost: import('./paper/PaperDeploymentHost').PaperDeploymentHost;
}>;
};
export type { BacktestResult } from './backtest/RustBacktestAdapter';