From b4589d5af1c4b78026ef4fad484a8f493bc98786 Mon Sep 17 00:00:00 2001 From: Boki Date: Wed, 28 Oct 2026 14:02:03 -0400 Subject: [PATCH] refactor(runtime): expose shared admission and artifact boundaries (CL26) --- apps/stock/config/package.json | 8 + .../src/contracts/canonical-execution.ts | 291 +++++++++++ .../config/src/contracts/paper-runtime.ts | 123 +++++ apps/stock/orchestrator/package.json | 3 +- .../src/backtest/NativeBacktestWorker.ts | 4 +- .../src/backtest/candidate-sandbox.ts | 118 +---- .../src/backtest/canonical-build.ts | 81 +-- .../src/contracts/canonical-execution.ts | 289 +--------- .../src/contracts/paper-runtime.ts | 121 +---- .../orchestrator/src/data/preparation.ts | 12 +- .../src/data/retained-research-dataset.ts | 25 +- .../src/paper/PaperDeploymentHost.ts | 2 +- apps/stock/orchestrator/src/paper/feed.ts | 116 +---- .../src/paper/paper-deployment-custody.ts | 192 +------ .../src/paper/paper-host-identity.ts | 78 +-- .../orchestrator/src/paper/paper-operator.ts | 25 +- .../src/services/StorageService.ts | 492 +----------------- .../src/strategies/retained-program.ts | 19 +- apps/stock/web-api/package.json | 3 +- .../web-api/src/routes/datasets.routes.ts | 2 +- .../src/routes/paper-deployments.routes.ts | 6 +- .../services/canonical-research.service.ts | 4 +- .../services/dataset-preparation.service.ts | 2 +- .../src/services/paper-deployments.service.ts | 6 +- .../web-api/src/services/run-reproduction.ts | 4 +- .../services/stored-dataset-preparation.ts | 2 +- .../src/services/stored-source-inspection.ts | 2 +- bun.lock | 20 + .../architecture-cleanup-execution.md | 2 + docs/development/backlog/README.md | 2 +- docs/development/backlog/manifest.json | 20 +- docs/development/backlog/tasks/CL26.md | 4 + libs/trading-runtime/package.json | 35 ++ libs/trading-runtime/src/artifacts.ts | 66 +++ .../src/candidate-environment.ts | 109 ++++ libs/trading-runtime/src/canonical-build.ts | 31 ++ .../trading-runtime/src/historical-storage.ts | 490 +++++++++++++++++ .../src/paper-configuration.ts | 145 ++++++ .../src/paper-deployment-custody.ts | 190 +++++++ .../src/paper-host-identity.ts | 30 ++ libs/trading-runtime/src/paper-operator.ts | 23 + libs/trading-runtime/src/preparation.ts | 10 + libs/trading-runtime/src/retained-dataset.ts | 23 + libs/trading-runtime/src/retained-package.ts | 19 + libs/trading-runtime/tsconfig.json | 23 + scripts/test/architecture.test.ts | 2 + scripts/test/shared-runtime.test.ts | 69 +++ test/integration/candidate-sandbox.test.ts | 10 +- .../retained-strategy-worker.test.ts | 2 +- 49 files changed, 1790 insertions(+), 1565 deletions(-) create mode 100644 apps/stock/config/src/contracts/canonical-execution.ts create mode 100644 apps/stock/config/src/contracts/paper-runtime.ts create mode 100644 libs/trading-runtime/package.json create mode 100644 libs/trading-runtime/src/artifacts.ts create mode 100644 libs/trading-runtime/src/candidate-environment.ts create mode 100644 libs/trading-runtime/src/canonical-build.ts create mode 100644 libs/trading-runtime/src/historical-storage.ts create mode 100644 libs/trading-runtime/src/paper-configuration.ts create mode 100644 libs/trading-runtime/src/paper-deployment-custody.ts create mode 100644 libs/trading-runtime/src/paper-host-identity.ts create mode 100644 libs/trading-runtime/src/paper-operator.ts create mode 100644 libs/trading-runtime/src/preparation.ts create mode 100644 libs/trading-runtime/src/retained-dataset.ts create mode 100644 libs/trading-runtime/src/retained-package.ts create mode 100644 libs/trading-runtime/tsconfig.json create mode 100644 scripts/test/shared-runtime.test.ts diff --git a/apps/stock/config/package.json b/apps/stock/config/package.json index adcf6e8c..ffc744d1 100644 --- a/apps/stock/config/package.json +++ b/apps/stock/config/package.json @@ -76,6 +76,14 @@ "./product-responses": { "types": "./dist/contracts/product-responses/index.d.ts", "default": "./dist/contracts/product-responses/index.js" + }, + "./canonical-execution": { + "types": "./dist/contracts/canonical-execution.d.ts", + "default": "./dist/contracts/canonical-execution.js" + }, + "./paper-runtime": { + "types": "./dist/contracts/paper-runtime.d.ts", + "default": "./dist/contracts/paper-runtime.js" } }, "scripts": { diff --git a/apps/stock/config/src/contracts/canonical-execution.ts b/apps/stock/config/src/contracts/canonical-execution.ts new file mode 100644 index 00000000..f015bd10 --- /dev/null +++ b/apps/stock/config/src/contracts/canonical-execution.ts @@ -0,0 +1,291 @@ +/** Trusted durable-host wire boundary. Native checkpoints are opaque custody, + * not a TypeScript accounting implementation or a strategy mutation API. */ +import { z } from 'zod'; +export type { financialDecimal }; +import type { financialDecimal, FinancialDecimal } from '@stock-bot/types'; +import { + parseFinancialDecimal, + parseFinancialEffects, + parseFinancialStrategyDecision, +} from '@stock-bot/types'; +import { + nativeFinancialViewSchema, + nativeManagedOrderSchema, + nativeMatchingOutcomeSchema, + replayConfigSchema, +} from './canonical-replay'; + +const id = z + .string() + .min(1) + .refine(value => + [...value].every(char => char.charCodeAt(0) >= 32 && char.charCodeAt(0) !== 127) + ); +const counter = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER); +const time = z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER); +const decimal: z.ZodType = z + .string() + .transform(value => parseFinancialDecimal(value)); +const nonnegative = decimal.refine(value => !value.startsWith('-')); +const positive = nonnegative.refine(value => value !== '0.00000000'); +const identitySchema = z.object({ sessionId: id, accountId: id }).strict(); +export type CanonicalExecutionIdentity = z.infer; +export const canonicalMatchingConfigSchema = replayConfigSchema.shape.matching.extend({ + series: z.array( + replayConfigSchema.shape.matching.shape.series.element.extend({ + mode: z.enum(['Open', 'Quote']), + }) + ), +}); +export type CanonicalMatchingConfig = z.input; +const eventKeySchema = z + .object({ + at: time, + phase: z.enum(['Observation', 'Decision', 'Execution', 'SessionClose']), + instrumentId: id, + sourceSequence: counter, + }) + .strict(); +const venueSessionSchema = z.object({ sessionId: id, opensAt: time, closesAt: time }).strict(); +const riskSessionSchema = + replayConfigSchema.shape.matching.shape.risk.shape.ledger.shape.riskSession; +export const matchingCommandSchema = z + .object({ + commandId: id, + key: eventKeySchema, + body: z.discriminatedUnion('kind', [ + z + .object({ + kind: z.literal('submit'), + decisions: z.array(z.unknown().transform(value => parseFinancialStrategyDecision(value))), + }) + .strict(), + z + .object({ + kind: z.literal('execute'), + seriesId: id, + observation: z.discriminatedUnion('kind', [ + z + .object({ + kind: z.literal('open'), + opensAt: time, + price: positive, + capacity: nonnegative, + }) + .strict(), + z + .object({ + kind: z.literal('quote'), + observedAt: time, + bid: positive, + ask: positive, + bidSize: nonnegative, + askSize: nonnegative, + }) + .strict(), + ]), + }) + .strict(), + z + .object({ kind: z.literal('mark'), seriesId: id, price: positive, observedAt: time }) + .strict(), + z.object({ kind: z.literal('openSession'), session: venueSessionSchema }).strict(), + z.object({ kind: z.literal('closeSession'), sessionId: id }).strict(), + z.object({ kind: z.literal('riskSessionBoundary'), riskSession: riskSessionSchema }).strict(), + z.object({ kind: z.literal('finish') }).strict(), + ]), + }) + .strict(); +export type CanonicalMatchingCommand = z.input; + +/** Event ordering must agree with Rust, including UTF-8 instrument identity ties. */ +export function compareEventKeys( + a: CanonicalMatchingCommand['key'], + b: CanonicalMatchingCommand['key'] +): number { + const phases = { Observation: 0, Decision: 1, Execution: 2, SessionClose: 3 }; + return ( + a.at - b.at || + phases[a.phase] - phases[b.phase] || + Buffer.compare(Buffer.from(a.instrumentId), Buffer.from(b.instrumentId)) || + a.sourceSequence - b.sourceSequence + ); +} + +/** Metadata and shapes only. Rust restores and validates all nested receipts, + * reservations, accounting and indexes before any transition. */ +export const canonicalExecutionCheckpointSchema = z + .object({ + version: z.literal(1), + config: canonicalMatchingConfigSchema, + risk: z.record(z.unknown()), + revision: counter, + status: nativeMatchingOutcomeSchema.shape.status, + cursor: eventKeySchema.nullable(), + orders: z.array(nativeManagedOrderSchema), + sessions: z.array(z.tuple([id, venueSessionSchema])), + receipts: z.array(z.record(z.unknown())), + }) + .strict(); +export type CanonicalExecutionCheckpoint = z.infer; + +export const financialTransactionRequestSchema = z.discriminatedUnion('kind', [ + z + .object({ + version: z.literal(1), + kind: z.literal('initialize'), + identity: identitySchema, + config: canonicalMatchingConfigSchema, + }) + .strict(), + z + .object({ + version: z.literal(1), + kind: z.literal('apply'), + identity: identitySchema, + checkpoint: canonicalExecutionCheckpointSchema, + command: matchingCommandSchema, + }) + .strict(), +]); +export type FinancialTransactionRequest = z.input; +const riskOutcomeSchema = z + .object({ + replayed: z.boolean(), + revision: counter, + disposition: z.union([z.literal('Accepted'), nativeManagedOrderSchema.shape.status.options[1]]), + financial: z + .object({ + replayed: z.boolean(), + effects: z.unknown().transform(value => parseFinancialEffects(value)), + }) + .strict() + .nullable(), + remaining: z.record(z.unknown()).nullable(), + releasedOrder: id.nullable(), + resetBaseline: nonnegative.nullable(), + }) + .strict(); +const matchingEffectSchema = z.union([ + z.object({ Order: nativeManagedOrderSchema }).strict(), + z + .object({ + Risk: z.object({ command: z.record(z.unknown()), outcome: riskOutcomeSchema }).strict(), + }) + .strict(), + z + .object({ + Operator: z.object({ command: z.record(z.unknown()), outcome: riskOutcomeSchema }).strict(), + }) + .strict(), +]); +export const financialTransactionResultSchema = z + .object({ + version: z.literal(1), + identity: identitySchema, + checkpoint: canonicalExecutionCheckpointSchema, + view: nativeFinancialViewSchema, + outcome: nativeMatchingOutcomeSchema.nullable(), + journal: z.array( + z + .object({ + index: counter, + effect: matchingEffectSchema, + viewAfter: nativeFinancialViewSchema, + }) + .strict() + ), + }) + .strict(); +export type FinancialTransactionResult = z.infer; +export type CanonicalFinancialView = z.infer; + +// JSON object key order is not semantically significant (including opaque commands). +function equalJson(left: unknown, right: unknown): boolean { + if (left === right) { + return true; + } + if (left === null || right === null || typeof left !== 'object' || typeof right !== 'object') { + return false; + } + if (Array.isArray(left) || Array.isArray(right)) { + return ( + Array.isArray(left) && + Array.isArray(right) && + left.length === right.length && + left.every((value, index) => equalJson(value, right[index])) + ); + } + const a = left as Record, + b = right as Record; + return ( + Object.keys(a).length === Object.keys(b).length && + Object.keys(a).every(key => Object.hasOwn(b, key) && equalJson(a[key], b[key])) + ); +} + +export function parseFinancialTransactionResult( + input: string, + expectedIdentity: CanonicalExecutionIdentity +): FinancialTransactionResult { + const result = financialTransactionResultSchema.parse(JSON.parse(input)); + const expected = identitySchema.parse(expectedIdentity), + ledger = result.checkpoint.config.risk.ledger; + if ( + !equalJson(result.identity, expected) || + ledger.sessionId !== expected.sessionId || + ledger.accountId !== expected.accountId || + result.view.admissionRevision !== result.checkpoint.revision + ) { + throw new Error('Native financial transaction identity or revision mismatch'); + } + const checkView = (view: CanonicalFinancialView) => { + if ( + view.portfolio.sessionId !== expected.sessionId || + view.portfolio.accountId !== expected.accountId || + view.portfolio.baseCurrency !== ledger.baseCurrency || + view.portfolio.reserveOwnerId !== ledger.reserveOwnerId + ) { + throw new Error('Native financial transaction view identity mismatch'); + } + }; + checkView(result.view); + if (result.outcome === null) { + if ( + result.checkpoint.revision !== 0 || + result.checkpoint.status !== 'Running' || + result.checkpoint.cursor !== null || + result.checkpoint.orders.length !== 0 || + result.checkpoint.sessions.length !== 0 || + result.view.orders.length !== 0 || + result.view.reservations.length !== 0 || + result.journal.length !== 0 || + result.checkpoint.receipts.length !== 0 + ) { + throw new Error('Invalid initialized financial transaction'); + } + } else if (result.outcome.replayed) { + if (result.journal.length !== 0 || result.outcome.revision > result.checkpoint.revision) { + throw new Error('Replayed financial transaction cannot publish effects'); + } + } else { + if ( + result.outcome.revision !== result.checkpoint.revision || + !equalJson(result.outcome.status, result.checkpoint.status) || + result.journal.length !== result.outcome.effects.length + ) { + throw new Error('Native financial transaction outcome mismatch'); + } + for (const [index, row] of result.journal.entries()) { + checkView(row.viewAfter); + if ( + row.index !== index || + row.viewAfter.admissionRevision !== result.checkpoint.revision - 1 || + !equalJson(row.effect, matchingEffectSchema.parse(result.outcome.effects[index])) + ) { + throw new Error('Native financial transaction journal mismatch'); + } + } + } + return result; +} diff --git a/apps/stock/config/src/contracts/paper-runtime.ts b/apps/stock/config/src/contracts/paper-runtime.ts new file mode 100644 index 00000000..615d83c3 --- /dev/null +++ b/apps/stock/config/src/contracts/paper-runtime.ts @@ -0,0 +1,123 @@ +/** Explicit trusted producer boundary. No legacy timestamp repair or broker capabilities. */ +import { z } from 'zod'; +export type { financialDecimal }; +import type { financialDecimal, FinancialDecimal } from '@stock-bot/types'; +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 { stepSchema } from './canonical-replay'; + +const id = matchingCommandSchema.shape.key.shape.instrumentId; +const time = matchingCommandSchema.shape.key.shape.at; +const counter = matchingCommandSchema.shape.key.shape.sourceSequence; +const decimal: z.ZodType = z + .string() + .transform(value => parseFinancialDecimal(value)); + +export { paperPolicySchema } from '@stock-bot/stock-config/paper-deployments'; + +const legacyPaperConfigurationSchema = z + .object({ + version: z.literal(1), + matching: canonicalMatchingConfigSchema, + strategies: z.array(builtinStrategySelectionSchema).min(1), + policy: paperPolicySchema, + }) + .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. */ +export const paperFrameSchema = z + .object({ + version: z.literal(1), + sourceId: id, + connectionId: id, + id, + sequence: counter, + availableAt: time, + quotes: z + .array( + z + .object({ + instrumentId: id, + seriesId: id, + observedAt: time, + sourceSequence: counter, + bid: decimal, + ask: decimal, + bidSize: decimal, + askSize: decimal, + }) + .strict() + ) + .min(1), + observations: z.array(stepSchema.shape.observations.element), + }) + .strict(); + +export const paperConnectionSchema = z.object({ sourceId: id, connectionId: id }).strict(); +export const paperActivationSchema = z + .object({ recoverPending: z.boolean().default(false) }) + .strict(); +export const paperHaltSchema = z.object({ reason: z.string().trim().min(1) }).strict(); + +export type PaperConfigurationInput = z.input; +export type PaperConfiguration = z.output; +export type PaperPolicy = z.output; +export type PaperFrameInput = z.input; +export type PaperFrame = z.output; +export type PaperConnection = z.infer; + +export class PaperRuntimeError extends Error { + constructor( + readonly kind: 'invalid-input' | 'not-ready' | 'conflict', + message: string + ) { + super(message); + this.name = 'PaperRuntimeError'; + } +} + +export interface PaperReadiness { + configured: boolean; + accountId: string | null; + sourceId: string | null; + active: boolean; + ready: boolean; + operatorHalted: boolean; + connected: boolean; + reasons: string[]; + lastReceivedAt: number | null; + lastAvailableAt: number | null; + requiresHistoricalRecovery: boolean; + pendingInput: string | null; + pendingBatch: string | null; + pendingDecisionSequence: number | null; + nativeStatus: 'Running' | 'Complete' | { Failed: { diagnostic: string } } | null; + risk: { dailyHalted: boolean; drawdownHalted: boolean } | null; +} + +export interface PaperRuntime { + initialize(configuration: PaperConfigurationInput): Promise; + connect(connection: PaperConnection): Promise; + ingest(frame: PaperFrameInput): Promise<{ + duplicate: boolean; + disposition: 'health-only' | 'admitted'; + readiness: PaperReadiness; + }>; + disconnect(connection: PaperConnection): Promise; + activate(options: { recoverPending: boolean }): Promise; + halt(reason: string): Promise; + status(): Promise; + shutdown(): Promise; +} diff --git a/apps/stock/orchestrator/package.json b/apps/stock/orchestrator/package.json index 90888fcc..f886767a 100644 --- a/apps/stock/orchestrator/package.json +++ b/apps/stock/orchestrator/package.json @@ -38,7 +38,8 @@ "@stock-bot/postgres": "workspace:*", "@stock-bot/invariants": "workspace:*", "@stock-bot/types": "workspace:*", - "@stock-bot/handlers": "workspace:*" + "@stock-bot/handlers": "workspace:*", + "@stock-bot/trading-runtime": "workspace:*" }, "peerDependencies": { "@tensorflow/tfjs-node": "^4.0.0" diff --git a/apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts b/apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts index 7cf65c3a..59fe006e 100644 --- a/apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts +++ b/apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts @@ -92,12 +92,12 @@ export class NativeBacktestWorker { retainedRequest && this.workerUrl && realpathSync(fileURLToPath(this.workerUrl)) !== - realpathSync(fileURLToPath(canonicalWorkerUrl)) + realpathSync(fileURLToPath(canonicalWorkerUrl())) ) { throw new Error('Retained strategy execution requires the canonical bundled worker'); } const workerUrl = retainedRequest - ? canonicalWorkerUrl + ? canonicalWorkerUrl() : (this.workerUrl ?? new URL( import.meta.url.endsWith('.ts') ? './native-worker.ts' : './native-worker.js', diff --git a/apps/stock/orchestrator/src/backtest/candidate-sandbox.ts b/apps/stock/orchestrator/src/backtest/candidate-sandbox.ts index 93ae193d..bb609012 100644 --- a/apps/stock/orchestrator/src/backtest/candidate-sandbox.ts +++ b/apps/stock/orchestrator/src/backtest/candidate-sandbox.ts @@ -1,18 +1,21 @@ /** 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 { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process'; +import { mkdtemp, 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 { join } from 'node:path'; 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 { + daemon, + docker, + dockerRead, + environment, + readCandidateExecution, + verifyCandidateExecution, +} from '@stock-bot/trading-runtime/candidate-environment'; import { parseFinancialStrategyDecision } from '@stock-bot/types'; import type { ReplaySubmissionOutcome } from '../contracts/native-replay'; import { @@ -28,100 +31,13 @@ import type { 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'; -} +export { + candidateDescriptorPath, + CandidateSandboxUnavailable, + readCandidateExecution, + verifyCandidateExecution, +} from '@stock-bot/trading-runtime/candidate-environment'; -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 { - 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 { - 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'); diff --git a/apps/stock/orchestrator/src/backtest/canonical-build.ts b/apps/stock/orchestrator/src/backtest/canonical-build.ts index 97987229..616b9e8a 100644 --- a/apps/stock/orchestrator/src/backtest/canonical-build.ts +++ b/apps/stock/orchestrator/src/backtest/canonical-build.ts @@ -1,79 +1,2 @@ -/** 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 { - canonicalBuildIdentitySchema, - type CanonicalBuildIdentity, -} from '@stock-bot/stock-config/canonical-research'; -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('Canonical engine resolves outside this checkout'); -} -if (engineWrapper !== resolve(repositoryRoot, 'apps/stock/engine/index.mjs')) { - throw new Error('Unsupported canonical engine wrapper location'); -} - -export const canonicalWorkerUrl = pathToFileURL( - resolve(repositoryRoot, 'apps/stock/orchestrator/dist/native-worker.js') -); - -async function hashLocalFile(path: string): Promise { - if (realpathSync(path) !== path) { - throw new Error('Canonical 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 readCanonicalBuildIdentity(): Promise { - if (typeof Bun === 'undefined') { - throw new Error('Canonical research requires the Bun runtime'); - } - const [workerSha256, engineWrapperSha256, engineBinarySha256, dependencyLockSha256] = - await Promise.all([ - hashLocalFile(fileURLToPath(canonicalWorkerUrl)), - hashLocalFile(engineWrapper), - hashLocalFile(resolve(repositoryRoot, 'apps/stock/engine/dist/engine.node')), - hashLocalFile(resolve(repositoryRoot, 'bun.lock')), - ]); - return canonicalBuildIdentitySchema.parse({ - version: 1, - workerSha256, - 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 verifyCanonicalWorkerBuild( - expected: CanonicalBuildIdentity, - actualWorkerUrl: string -): Promise { - if ( - realpathSync(fileURLToPath(actualWorkerUrl)) !== realpathSync(fileURLToPath(canonicalWorkerUrl)) - ) { - throw new Error('Canonical research requires the bundled worker from this checkout'); - } - const actual = await readCanonicalBuildIdentity(); - if ( - canonicalStrategyJson(actual) !== - canonicalStrategyJson(canonicalBuildIdentitySchema.parse(expected)) - ) { - throw new Error('Canonical worker/native/runtime build identity mismatch'); - } - return actual; -} +/** Shared read-only artifact inspection. */ +export * from '@stock-bot/trading-runtime/canonical-build'; diff --git a/apps/stock/orchestrator/src/contracts/canonical-execution.ts b/apps/stock/orchestrator/src/contracts/canonical-execution.ts index c1877b9c..3d2d3678 100644 --- a/apps/stock/orchestrator/src/contracts/canonical-execution.ts +++ b/apps/stock/orchestrator/src/contracts/canonical-execution.ts @@ -1,287 +1,2 @@ -/** Trusted durable-host wire boundary. Native checkpoints are opaque custody, - * not a TypeScript accounting implementation or a strategy mutation API. */ -import { z } from 'zod'; -import { - parseFinancialDecimal, - parseFinancialEffects, - parseFinancialStrategyDecision, -} from '@stock-bot/types'; -import { - nativeFinancialViewSchema, - nativeManagedOrderSchema, - nativeMatchingOutcomeSchema, - replayConfigSchema, -} from './native-replay'; - -const id = z - .string() - .min(1) - .refine(value => - [...value].every(char => char.charCodeAt(0) >= 32 && char.charCodeAt(0) !== 127) - ); -const counter = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER); -const time = z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER); -const decimal = z.string().transform(value => parseFinancialDecimal(value)); -const nonnegative = decimal.refine(value => !value.startsWith('-')); -const positive = nonnegative.refine(value => value !== '0.00000000'); -const identitySchema = z.object({ sessionId: id, accountId: id }).strict(); -export type CanonicalExecutionIdentity = z.infer; -export const canonicalMatchingConfigSchema = replayConfigSchema.shape.matching.extend({ - series: z.array( - replayConfigSchema.shape.matching.shape.series.element.extend({ - mode: z.enum(['Open', 'Quote']), - }) - ), -}); -export type CanonicalMatchingConfig = z.input; -const eventKeySchema = z - .object({ - at: time, - phase: z.enum(['Observation', 'Decision', 'Execution', 'SessionClose']), - instrumentId: id, - sourceSequence: counter, - }) - .strict(); -const venueSessionSchema = z.object({ sessionId: id, opensAt: time, closesAt: time }).strict(); -const riskSessionSchema = - replayConfigSchema.shape.matching.shape.risk.shape.ledger.shape.riskSession; -export const matchingCommandSchema = z - .object({ - commandId: id, - key: eventKeySchema, - body: z.discriminatedUnion('kind', [ - z - .object({ - kind: z.literal('submit'), - decisions: z.array(z.unknown().transform(value => parseFinancialStrategyDecision(value))), - }) - .strict(), - z - .object({ - kind: z.literal('execute'), - seriesId: id, - observation: z.discriminatedUnion('kind', [ - z - .object({ - kind: z.literal('open'), - opensAt: time, - price: positive, - capacity: nonnegative, - }) - .strict(), - z - .object({ - kind: z.literal('quote'), - observedAt: time, - bid: positive, - ask: positive, - bidSize: nonnegative, - askSize: nonnegative, - }) - .strict(), - ]), - }) - .strict(), - z - .object({ kind: z.literal('mark'), seriesId: id, price: positive, observedAt: time }) - .strict(), - z.object({ kind: z.literal('openSession'), session: venueSessionSchema }).strict(), - z.object({ kind: z.literal('closeSession'), sessionId: id }).strict(), - z.object({ kind: z.literal('riskSessionBoundary'), riskSession: riskSessionSchema }).strict(), - z.object({ kind: z.literal('finish') }).strict(), - ]), - }) - .strict(); -export type CanonicalMatchingCommand = z.input; - -/** Event ordering must agree with Rust, including UTF-8 instrument identity ties. */ -export function compareEventKeys( - a: CanonicalMatchingCommand['key'], - b: CanonicalMatchingCommand['key'] -): number { - const phases = { Observation: 0, Decision: 1, Execution: 2, SessionClose: 3 }; - return ( - a.at - b.at || - phases[a.phase] - phases[b.phase] || - Buffer.compare(Buffer.from(a.instrumentId), Buffer.from(b.instrumentId)) || - a.sourceSequence - b.sourceSequence - ); -} - -/** Metadata and shapes only. Rust restores and validates all nested receipts, - * reservations, accounting and indexes before any transition. */ -export const canonicalExecutionCheckpointSchema = z - .object({ - version: z.literal(1), - config: canonicalMatchingConfigSchema, - risk: z.record(z.unknown()), - revision: counter, - status: nativeMatchingOutcomeSchema.shape.status, - cursor: eventKeySchema.nullable(), - orders: z.array(nativeManagedOrderSchema), - sessions: z.array(z.tuple([id, venueSessionSchema])), - receipts: z.array(z.record(z.unknown())), - }) - .strict(); -export type CanonicalExecutionCheckpoint = z.infer; - -export const financialTransactionRequestSchema = z.discriminatedUnion('kind', [ - z - .object({ - version: z.literal(1), - kind: z.literal('initialize'), - identity: identitySchema, - config: canonicalMatchingConfigSchema, - }) - .strict(), - z - .object({ - version: z.literal(1), - kind: z.literal('apply'), - identity: identitySchema, - checkpoint: canonicalExecutionCheckpointSchema, - command: matchingCommandSchema, - }) - .strict(), -]); -export type FinancialTransactionRequest = z.input; -const riskOutcomeSchema = z - .object({ - replayed: z.boolean(), - revision: counter, - disposition: z.union([z.literal('Accepted'), nativeManagedOrderSchema.shape.status.options[1]]), - financial: z - .object({ - replayed: z.boolean(), - effects: z.unknown().transform(value => parseFinancialEffects(value)), - }) - .strict() - .nullable(), - remaining: z.record(z.unknown()).nullable(), - releasedOrder: id.nullable(), - resetBaseline: nonnegative.nullable(), - }) - .strict(); -const matchingEffectSchema = z.union([ - z.object({ Order: nativeManagedOrderSchema }).strict(), - z - .object({ - Risk: z.object({ command: z.record(z.unknown()), outcome: riskOutcomeSchema }).strict(), - }) - .strict(), - z - .object({ - Operator: z.object({ command: z.record(z.unknown()), outcome: riskOutcomeSchema }).strict(), - }) - .strict(), -]); -export const financialTransactionResultSchema = z - .object({ - version: z.literal(1), - identity: identitySchema, - checkpoint: canonicalExecutionCheckpointSchema, - view: nativeFinancialViewSchema, - outcome: nativeMatchingOutcomeSchema.nullable(), - journal: z.array( - z - .object({ - index: counter, - effect: matchingEffectSchema, - viewAfter: nativeFinancialViewSchema, - }) - .strict() - ), - }) - .strict(); -export type FinancialTransactionResult = z.infer; -export type CanonicalFinancialView = z.infer; - -// JSON object key order is not semantically significant (including opaque commands). -function equalJson(left: unknown, right: unknown): boolean { - if (left === right) { - return true; - } - if (left === null || right === null || typeof left !== 'object' || typeof right !== 'object') { - return false; - } - if (Array.isArray(left) || Array.isArray(right)) { - return ( - Array.isArray(left) && - Array.isArray(right) && - left.length === right.length && - left.every((value, index) => equalJson(value, right[index])) - ); - } - const a = left as Record, - b = right as Record; - return ( - Object.keys(a).length === Object.keys(b).length && - Object.keys(a).every(key => Object.hasOwn(b, key) && equalJson(a[key], b[key])) - ); -} - -export function parseFinancialTransactionResult( - input: string, - expectedIdentity: CanonicalExecutionIdentity -): FinancialTransactionResult { - const result = financialTransactionResultSchema.parse(JSON.parse(input)); - const expected = identitySchema.parse(expectedIdentity), - ledger = result.checkpoint.config.risk.ledger; - if ( - !equalJson(result.identity, expected) || - ledger.sessionId !== expected.sessionId || - ledger.accountId !== expected.accountId || - result.view.admissionRevision !== result.checkpoint.revision - ) { - throw new Error('Native financial transaction identity or revision mismatch'); - } - const checkView = (view: CanonicalFinancialView) => { - if ( - view.portfolio.sessionId !== expected.sessionId || - view.portfolio.accountId !== expected.accountId || - view.portfolio.baseCurrency !== ledger.baseCurrency || - view.portfolio.reserveOwnerId !== ledger.reserveOwnerId - ) { - throw new Error('Native financial transaction view identity mismatch'); - } - }; - checkView(result.view); - if (result.outcome === null) { - if ( - result.checkpoint.revision !== 0 || - result.checkpoint.status !== 'Running' || - result.checkpoint.cursor !== null || - result.checkpoint.orders.length !== 0 || - result.checkpoint.sessions.length !== 0 || - result.view.orders.length !== 0 || - result.view.reservations.length !== 0 || - result.journal.length !== 0 || - result.checkpoint.receipts.length !== 0 - ) { - throw new Error('Invalid initialized financial transaction'); - } - } else if (result.outcome.replayed) { - if (result.journal.length !== 0 || result.outcome.revision > result.checkpoint.revision) { - throw new Error('Replayed financial transaction cannot publish effects'); - } - } else { - if ( - result.outcome.revision !== result.checkpoint.revision || - !equalJson(result.outcome.status, result.checkpoint.status) || - result.journal.length !== result.outcome.effects.length - ) { - throw new Error('Native financial transaction outcome mismatch'); - } - for (const [index, row] of result.journal.entries()) { - checkView(row.viewAfter); - if ( - row.index !== index || - row.viewAfter.admissionRevision !== result.checkpoint.revision - 1 || - !equalJson(row.effect, matchingEffectSchema.parse(result.outcome.effects[index])) - ) { - throw new Error('Native financial transaction journal mismatch'); - } - } - } - return result; -} +/** Shared financial wire contract. */ +export * from '@stock-bot/stock-config/canonical-execution'; diff --git a/apps/stock/orchestrator/src/contracts/paper-runtime.ts b/apps/stock/orchestrator/src/contracts/paper-runtime.ts index 62adab89..8863950c 100644 --- a/apps/stock/orchestrator/src/contracts/paper-runtime.ts +++ b/apps/stock/orchestrator/src/contracts/paper-runtime.ts @@ -1,119 +1,2 @@ -/** 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 { 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 decimal = z.string().transform(value => parseFinancialDecimal(value)); - -export { paperPolicySchema } from '@stock-bot/stock-config/paper-deployments'; - -const legacyPaperConfigurationSchema = z - .object({ - version: z.literal(1), - matching: canonicalMatchingConfigSchema, - strategies: z.array(builtinStrategySelectionSchema).min(1), - policy: paperPolicySchema, - }) - .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. */ -export const paperFrameSchema = z - .object({ - version: z.literal(1), - sourceId: id, - connectionId: id, - id, - sequence: counter, - availableAt: time, - quotes: z - .array( - z - .object({ - instrumentId: id, - seriesId: id, - observedAt: time, - sourceSequence: counter, - bid: decimal, - ask: decimal, - bidSize: decimal, - askSize: decimal, - }) - .strict() - ) - .min(1), - observations: z.array(stepSchema.shape.observations.element), - }) - .strict(); - -export const paperConnectionSchema = z.object({ sourceId: id, connectionId: id }).strict(); -export const paperActivationSchema = z - .object({ recoverPending: z.boolean().default(false) }) - .strict(); -export const paperHaltSchema = z.object({ reason: z.string().trim().min(1) }).strict(); - -export type PaperConfigurationInput = z.input; -export type PaperConfiguration = z.output; -export type PaperPolicy = z.output; -export type PaperFrameInput = z.input; -export type PaperFrame = z.output; -export type PaperConnection = z.infer; - -export class PaperRuntimeError extends Error { - constructor( - readonly kind: 'invalid-input' | 'not-ready' | 'conflict', - message: string - ) { - super(message); - this.name = 'PaperRuntimeError'; - } -} - -export interface PaperReadiness { - configured: boolean; - accountId: string | null; - sourceId: string | null; - active: boolean; - ready: boolean; - operatorHalted: boolean; - connected: boolean; - reasons: string[]; - lastReceivedAt: number | null; - lastAvailableAt: number | null; - requiresHistoricalRecovery: boolean; - pendingInput: string | null; - pendingBatch: string | null; - pendingDecisionSequence: number | null; - nativeStatus: 'Running' | 'Complete' | { Failed: { diagnostic: string } } | null; - risk: { dailyHalted: boolean; drawdownHalted: boolean } | null; -} - -export interface PaperRuntime { - initialize(configuration: PaperConfigurationInput): Promise; - connect(connection: PaperConnection): Promise; - ingest(frame: PaperFrameInput): Promise<{ - duplicate: boolean; - disposition: 'health-only' | 'admitted'; - readiness: PaperReadiness; - }>; - disconnect(connection: PaperConnection): Promise; - activate(options: { recoverPending: boolean }): Promise; - halt(reason: string): Promise; - status(): Promise; - shutdown(): Promise; -} +/** Shared financial wire contract. */ +export * from '@stock-bot/stock-config/paper-runtime'; diff --git a/apps/stock/orchestrator/src/data/preparation.ts b/apps/stock/orchestrator/src/data/preparation.ts index c20dae0e..c4719585 100644 --- a/apps/stock/orchestrator/src/data/preparation.ts +++ b/apps/stock/orchestrator/src/data/preparation.ts @@ -1,10 +1,2 @@ -import { setImmediate } from 'node:timers/promises'; - -export const PREPARATION_BATCH_SIZE = 2048; - -/** Yield to cancellation, timeouts and lease heartbeats between bounded CPU batches. */ -export async function preparationCheckpoint(signal?: AbortSignal): Promise { - signal?.throwIfAborted(); - await setImmediate(); - signal?.throwIfAborted(); -} +/** Compatibility entrypoint; implementation is shared by the API and orchestrator. */ +export * from '@stock-bot/trading-runtime/preparation'; diff --git a/apps/stock/orchestrator/src/data/retained-research-dataset.ts b/apps/stock/orchestrator/src/data/retained-research-dataset.ts index 9a4e07ce..be375c0d 100644 --- a/apps/stock/orchestrator/src/data/retained-research-dataset.ts +++ b/apps/stock/orchestrator/src/data/retained-research-dataset.ts @@ -1,23 +1,2 @@ -import { validateDatasetV2 } from './historical-dataset-v2'; - -export interface RetainedDatasetStore { - query(text: string, values?: unknown[]): Promise<{ rows: Record[] }>; -} - -/** Content-addressed custody shared by explicit CLI import and web source preparation. */ -export async function retainResearchDataset(database: RetainedDatasetStore, input: unknown) { - const dataset = validateDatasetV2(input); - await database.query( - 'INSERT INTO backtest_datasets(hash,payload) VALUES($1,$2::jsonb) ON CONFLICT(hash) DO NOTHING', - [dataset.manifest.hash, JSON.stringify(dataset)] - ); - const stored = ( - await database.query('SELECT payload FROM backtest_datasets WHERE hash=$1', [ - dataset.manifest.hash, - ]) - ).rows[0]; - if (!stored || validateDatasetV2(stored.payload).manifest.hash !== dataset.manifest.hash) { - throw new Error('Retained dataset content does not match the imported identity'); - } - return dataset.manifest; -} +/** Compatibility entrypoint; implementation is shared by the API and orchestrator. */ +export * from '@stock-bot/trading-runtime/retained-dataset'; diff --git a/apps/stock/orchestrator/src/paper/PaperDeploymentHost.ts b/apps/stock/orchestrator/src/paper/PaperDeploymentHost.ts index 4e4680fd..538340cf 100644 --- a/apps/stock/orchestrator/src/paper/PaperDeploymentHost.ts +++ b/apps/stock/orchestrator/src/paper/PaperDeploymentHost.ts @@ -80,7 +80,7 @@ export class PaperDeploymentHost { return this.status(id); } const { deployment, pkg } = await this.authorized(id); - const url = new URL(paperHostUrl); + const url = new URL(paperHostUrl()); url.searchParams.set('sha256', deployment.preview.host.hostSha256); const module = (await import(url.href)) as { createPromotedPaperRuntime: typeof createPromotedPaperRuntime; diff --git a/apps/stock/orchestrator/src/paper/feed.ts b/apps/stock/orchestrator/src/paper/feed.ts index 54ab6715..02cd6f5d 100644 --- a/apps/stock/orchestrator/src/paper/feed.ts +++ b/apps/stock/orchestrator/src/paper/feed.ts @@ -8,11 +8,9 @@ import { type CanonicalMatchingCommand, } from '../contracts/canonical-execution'; import { - paperConfigurationSchema, paperFrameSchema, PaperRuntimeError, type PaperConfiguration, - type PaperConfigurationInput, type PaperFrame, type PaperFrameInput, } from '../contracts/paper-runtime'; @@ -75,119 +73,7 @@ function activeSession(config: PaperConfiguration, instrumentId: string, at: num return session; } -export function validatePaperConfiguration(input: PaperConfigurationInput): PaperConfiguration { - const config = parseInput(paperConfigurationSchema, input); - const { matching, policy, strategies } = config; - if (!matching.series.length || matching.series.some(series => series.mode !== 'Quote')) { - invalid('Canonical paper feed supports Quote execution only'); - } - unique( - matching.series.map(item => item.instrumentId), - 'execution instrument' - ); - unique( - matching.series.map(item => item.seriesId), - 'execution series' - ); - unique( - matching.owners.map(item => item.ownerId), - 'owner' - ); - unique(matching.risk.ledger.ownerIds, 'ledger owner'); - unique( - strategies.map(item => item.ownerId), - 'strategy owner' - ); - unique( - policy.observations.map(item => item.seriesId), - 'observation series' - ); - unique( - policy.cadence.map(item => item.ownerId), - 'cadence owner' - ); - unique( - policy.calendars.map(item => item.instrumentId), - 'calendar instrument' - ); - const owners = matching.owners.map(item => item.ownerId).sort(compareText); - if ( - matching.owners.some(item => item.mode !== 'Target') || - !isDeepStrictEqual(owners, [...matching.risk.ledger.ownerIds].sort(compareText)) || - !isDeepStrictEqual(owners, strategies.map(item => item.ownerId).sort(compareText)) || - !isDeepStrictEqual(owners, policy.cadence.map(item => item.ownerId).sort(compareText)) - ) { - invalid('Paper built-ins must exactly match the target owner and cadence cohort'); - } - const instruments = matching.series.map(item => item.instrumentId).sort(compareText); - if ( - !isDeepStrictEqual( - instruments, - policy.calendars.map(item => item.instrumentId).sort(compareText) - ) - ) { - invalid('Paper calendars must exactly cover execution instruments'); - } - for (const observation of policy.observations) { - if (!instruments.includes(observation.instrumentId)) { - invalid('Paper observation references an unknown instrument'); - } - } - for (const cadence of policy.cadence) { - unique(cadence.seriesIds, 'cadence series'); - if (cadence.seriesIds.some(id => !policy.observations.some(item => item.seriesId === id))) { - invalid('Paper cadence references an unknown observation series'); - } - cadence.seriesIds.sort(compareText); - } - for (const strategy of strategies) { - const series = policy.observations.find(item => item.seriesId === strategy.seriesId); - if ( - series?.instrumentId !== strategy.instrumentId || - !policy.cadence - .find(item => item.ownerId === strategy.ownerId) - ?.seriesIds.includes(strategy.seriesId) - ) { - invalid('Paper strategy requires its bound instrument/observation series in its cadence'); - } - } - const initial = matching.risk.ledger.riskSession; - for (const calendar of policy.calendars) { - unique( - calendar.sessions.map(item => item.sessionId), - 'venue session' - ); - calendar.sessions.sort((a, b) => a.opensAt - b.opensAt); - let previousClose = initial.startsAt; - for (const session of calendar.sessions) { - if (session.opensAt < previousClose || session.opensAt >= session.closesAt) { - invalid('Paper venue sessions overlap, are invalid, or precede the initial risk clock'); - } - previousClose = session.closesAt; - } - } - unique([initial.sessionId, ...policy.riskBoundaries.map(item => item.sessionId)], 'risk session'); - policy.riskBoundaries.sort((a, b) => a.startsAt - b.startsAt); - let previousRisk = initial.startsAt; - for (const boundary of policy.riskBoundaries) { - if ( - boundary.calendarId !== initial.calendarId || - boundary.calendarRevision !== initial.calendarRevision || - boundary.startsAt <= previousRisk - ) { - invalid('Paper risk boundaries must advance the declared account calendar revision'); - } - previousRisk = boundary.startsAt; - } - matching.owners.sort((a, b) => compareText(a.ownerId, b.ownerId)); - matching.series.sort((a, b) => compareText(a.instrumentId, b.instrumentId)); - matching.risk.ledger.ownerIds.sort(compareText); - strategies.sort((a, b) => compareText(a.ownerId, b.ownerId)); - policy.observations.sort((a, b) => compareText(a.seriesId, b.seriesId)); - policy.cadence.sort((a, b) => compareText(a.ownerId, b.ownerId)); - policy.calendars.sort((a, b) => compareText(a.instrumentId, b.instrumentId)); - return config; -} +export { validatePaperConfiguration } from '@stock-bot/trading-runtime/paper-configuration'; export function validatePaperFrame( config: PaperConfiguration, diff --git a/apps/stock/orchestrator/src/paper/paper-deployment-custody.ts b/apps/stock/orchestrator/src/paper/paper-deployment-custody.ts index e9bb6657..bdf86147 100644 --- a/apps/stock/orchestrator/src/paper/paper-deployment-custody.ts +++ b/apps/stock/orchestrator/src/paper/paper-deployment-custody.ts @@ -1,190 +1,2 @@ -/** 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 -) { - 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 { - 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, - 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 | 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'); - } - } -} +/** Compatibility entrypoint; implementation is shared by the API and orchestrator. */ +export * from '@stock-bot/trading-runtime/paper-deployment-custody'; diff --git a/apps/stock/orchestrator/src/paper/paper-host-identity.ts b/apps/stock/orchestrator/src/paper/paper-host-identity.ts index 665d7368..ede54088 100644 --- a/apps/stock/orchestrator/src/paper/paper-host-identity.ts +++ b/apps/stock/orchestrator/src/paper/paper-host-identity.ts @@ -1,76 +1,2 @@ -/** 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 { - 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 { - 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 { - 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; -} +/** Shared read-only artifact inspection. */ +export * from '@stock-bot/trading-runtime/paper-host-identity'; diff --git a/apps/stock/orchestrator/src/paper/paper-operator.ts b/apps/stock/orchestrator/src/paper/paper-operator.ts index 4ea511d1..4af8480f 100644 --- a/apps/stock/orchestrator/src/paper/paper-operator.ts +++ b/apps/stock/orchestrator/src/paper/paper-operator.ts @@ -1,23 +1,2 @@ -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) ?? []; +/** Compatibility entrypoint; implementation is shared by the API and orchestrator. */ +export * from '@stock-bot/trading-runtime/paper-operator'; diff --git a/apps/stock/orchestrator/src/services/StorageService.ts b/apps/stock/orchestrator/src/services/StorageService.ts index 9f4843c6..feb242ca 100644 --- a/apps/stock/orchestrator/src/services/StorageService.ts +++ b/apps/stock/orchestrator/src/services/StorageService.ts @@ -1,490 +1,2 @@ -import type { Logger, MongoDBClient, QuestDBClient } from '@stock-bot/services'; -import { parseInstrumentId, type HistoricalDataPolicy } from '@stock-bot/types'; -import { PREPARATION_BATCH_SIZE, preparationCheckpoint } from '../data/preparation'; - -export interface HistoricalBar { - symbol: string; - timestamp: Date; - open: number; - high: number; - low: number; - close: number; - volume: number; - vwap?: number; - interpolated?: boolean; - source?: 'eod' | 'questdb' | 'synthetic'; - adjustedClose?: number; -} - -export type HistoricalStorageProvider = 'questdb' | 'eod'; -export type HistoricalStorageErrorCode = - | 'unsupported-provider' - | 'unsupported-interval' - | 'provider-unavailable' - | 'missing-range'; - -/** Storage routing failures are distinct from invalid records and transport failures. */ -export class HistoricalStorageError extends Error { - constructor( - readonly code: HistoricalStorageErrorCode, - message: string, - readonly provider?: HistoricalStorageProvider | 'synthetic' - ) { - super(message); - this.name = 'HistoricalStorageError'; - } -} - -const historicalIntervals = ['1m', '5m', '15m', '1h', '1d'] as const; -const eodIntradayCollections: Readonly> = { - '1m': 'eodIntraday1M', - '5m': 'eodIntraday5M', - '1h': 'eodIntraday1H', -}; - -/** Historical reads over borrowed adapters; ingestion and migrations own all writes. */ -export class StorageService { - private readonly questdb: QuestDBClient | null; - private readonly mongodb: MongoDBClient | null; - - constructor( - private readonly logger: Pick, - mongoClient: MongoDBClient | null | undefined, - questdbClient: QuestDBClient | null, - private readonly options: { allowSyntheticData?: boolean; syntheticSeed?: number } = {} - ) { - this.mongodb = mongoClient ?? null; - this.questdb = questdbClient; - } - - /** Adapter support and current connectivity, not evidence of stored range coverage. */ - getHistoricalCapabilities() { - return [ - { - provider: 'questdb' as const, - configured: this.questdb !== null, - connected: this.questdb?.connected ?? false, - intervals: [...historicalIntervals], - }, - { - provider: 'eod' as const, - configured: this.mongodb !== null, - connected: this.mongodb?.connected ?? false, - intervals: ['1m', '5m', '1h', '1d'] as const, - }, - ]; - } - - private selectHistoricalProvider( - requested: HistoricalStorageProvider | 'auto' - ): HistoricalStorageProvider | 'synthetic' { - if (!['auto', 'questdb', 'eod'].includes(requested)) { - throw new HistoricalStorageError('unsupported-provider', 'Unsupported historical provider'); - } - if (requested === 'questdb' || (requested === 'auto' && this.questdb)) { - if (!this.questdb) { - throw new HistoricalStorageError( - 'provider-unavailable', - 'QuestDB historical storage is unavailable', - 'questdb' - ); - } - return 'questdb'; - } - if (requested === 'eod' || (requested === 'auto' && this.mongodb)) { - if (!this.mongodb) { - throw new HistoricalStorageError( - 'provider-unavailable', - 'EOD historical storage is unavailable', - 'eod' - ); - } - return 'eod'; - } - if (this.options.allowSyntheticData) { - return 'synthetic'; - } - throw new HistoricalStorageError( - 'provider-unavailable', - 'No historical data store configured; synthetic data requires explicit opt-in' - ); - } - - /** One historical-data policy for native and TypeScript execution. */ - async getHistoricalBars( - symbol: string, - startTime: Date, - endTime: Date, - interval = '1m', - policy: HistoricalDataPolicy = { - adjustment: 'raw', - timestamp: interval === '1d' ? 'utc-session-date' : 'utc-instant', - }, - signal?: AbortSignal, - provider: HistoricalStorageProvider | 'auto' = 'auto' - ): Promise { - signal?.throwIfAborted(); - parseInstrumentId(symbol); - if ( - !Number.isFinite(startTime.getTime()) || - !Number.isFinite(endTime.getTime()) || - endTime <= startTime - ) { - throw new Error('Invalid historical date range'); - } - if (!(historicalIntervals as readonly string[]).includes(interval)) { - throw new HistoricalStorageError('unsupported-interval', 'Unsupported historical interval'); - } - if ( - (interval === '1d') !== (policy.timestamp === 'utc-session-date') || - (interval === '1d' && - (startTime.getTime() % 86400000 !== 0 || endTime.getTime() % 86400000 !== 0)) - ) { - throw new Error( - 'Daily ranges must use UTC midnight session dates; intraday ranges use UTC instants' - ); - } - const selectedProvider = this.selectHistoricalProvider(provider); - const rows = await this.readHistoricalBars( - symbol, - startTime, - endTime, - interval, - selectedProvider, - signal - ); - signal?.throwIfAborted(); - const bars: HistoricalBar[] = []; - let processed = 0; - for (const row of rows) { - if (row.symbol !== symbol) { - throw new Error(`Historical instrument identity mismatch for ${symbol}`); - } - if (typeof row.timestamp === 'string' && !/(Z|[+-]\d{2}:\d{2})$/.test(row.timestamp)) { - throw new Error('Historical instants require an explicit UTC offset'); - } - const timestamp = new Date(row.timestamp); - const numeric = (value: unknown) => - typeof value === 'number' - ? value - : typeof value === 'string' && value.trim() - ? Number(value) - : NaN; - let open = numeric(row.open), - high = numeric(row.high), - low = numeric(row.low), - close = numeric(row.close); - const volume = numeric(row.volume); - if ( - !Number.isFinite(timestamp.getTime()) || - ![open, high, low, close, volume].every(Number.isFinite) || - low <= 0 || - high < Math.max(open, close) || - low > Math.min(open, close) || - volume < 0 || - (interval === '1d' && timestamp.getTime() % 86400000 !== 0) - ) { - throw new Error(`Invalid historical OHLCV data for ${symbol}`); - } - let vwap = row.vwap === null || row.vwap === undefined ? undefined : numeric(row.vwap); - if (policy.adjustment === 'provider-adjusted') { - const adjustedClose = numeric(row.adjustedClose); - if (!(adjustedClose > 0) || !Number.isFinite(adjustedClose)) { - throw new Error(`Provider-adjusted prices unavailable for ${symbol}`); - } - const factor = adjustedClose / close; - open *= factor; - high *= factor; - low *= factor; - close = adjustedClose; - if (vwap !== undefined) { - vwap *= factor; - } - } - if ( - ![open, high, low, close].every(value => Number.isFinite(value) && value > 0) || - (vwap !== undefined && (!Number.isFinite(vwap) || vwap <= 0)) - ) { - throw new Error(`Invalid adjusted historical data for ${symbol}`); - } - if (timestamp >= startTime && timestamp < endTime) { - bars.push({ ...row, symbol, timestamp, open, high, low, close, volume, vwap }); - } - if (++processed % PREPARATION_BATCH_SIZE === 0) { - await preparationCheckpoint(signal); - } - } - signal?.throwIfAborted(); - bars.sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime()); - if (!bars.length) { - throw new HistoricalStorageError( - 'missing-range', - `No historical data for ${symbol} in the requested range`, - selectedProvider - ); - } - if ( - bars.some( - (bar, index) => - index > 0 && bars[index - 1]?.timestamp.getTime() === bar.timestamp.getTime() - ) - ) { - throw new Error(`Duplicate historical timestamps for ${symbol}`); - } - return bars; - } - - private async readHistoricalBars( - symbol: string, - startTime: Date, - endTime: Date, - interval: string, - provider: HistoricalStorageProvider | 'synthetic', - signal?: AbortSignal - ): Promise { - // Select once, before reading: empty ranges/errors never switch providers. - if (provider === 'questdb' && this.questdb) { - const result = await this.questdb.query( - `SELECT * FROM bars_${interval} WHERE symbol = $1 AND timestamp >= $2 AND timestamp < $3 ORDER BY timestamp`, - [symbol, startTime, endTime] - ); - return result.rows.map(row => ({ ...row, source: 'questdb' })); - } - - if (provider === 'eod' && this.mongodb) { - const identity = parseInstrumentId(symbol); - if (interval !== '1d') { - const collection = eodIntradayCollections[interval]; - if (!collection) { - throw new HistoricalStorageError( - 'unsupported-interval', - `EOD historical storage does not support ${interval}`, - 'eod' - ); - } - // fetchIntraday writes raw bar-start UTC Unix seconds, not local datetime labels. - // https://eodhd.com/financial-apis/intraday-historical-data-api - // This instant is not publication time; availability/calendar policy belongs to datasets. - const records = await this.mongodb.find<{ - symbol: string; - exchange: string; - eodSearchCode: string; - timestamp: number; - open: number; - high: number; - low: number; - close: number; - volume: number; - }>( - collection, - { - eodSearchCode: identity.id, - timestamp: { $gte: startTime.getTime() / 1000, $lt: endTime.getTime() / 1000 }, - }, - { - sort: { timestamp: 1 }, - projection: { - symbol: 1, - exchange: 1, - eodSearchCode: 1, - timestamp: 1, - open: 1, - high: 1, - low: 1, - close: 1, - volume: 1, - }, - } - ); - signal?.throwIfAborted(); - const bars: HistoricalBar[] = []; - for (const record of records) { - if ( - record.eodSearchCode !== identity.id || - record.symbol !== identity.symbol || - record.exchange !== identity.exchange - ) { - throw new Error(`Historical instrument identity mismatch for ${symbol}`); - } - const milliseconds = record.timestamp * 1000; - if ( - !Number.isSafeInteger(record.timestamp) || - !Number.isSafeInteger(milliseconds) || - !Number.isFinite(new Date(milliseconds).getTime()) - ) { - throw new Error(`Invalid historical Unix-seconds timestamp for ${symbol}`); - } - bars.push({ - symbol, - timestamp: new Date(milliseconds), - open: record.open, - high: record.high, - low: record.low, - close: record.close, - volume: record.volume, - source: 'eod', - }); - if (bars.length % PREPARATION_BATCH_SIZE === 0) { - await preparationCheckpoint(signal); - } - } - return bars; - } - const prices = await this.mongodb.find<{ - symbol: string; - exchange: string; - eodSearchCode: string; - providerExchange?: string; - date: string; - open: number; - high: number; - low: number; - close: number; - volume: number; - adjustedClose?: number; - }>( - 'eodPrices', - { - eodSearchCode: identity.id, - date: { - $gte: startTime.toISOString().slice(0, 10), - $lt: endTime.toISOString().slice(0, 10), - }, - }, - { - sort: { date: 1 }, - projection: { - symbol: 1, - exchange: 1, - eodSearchCode: 1, - providerExchange: 1, - date: 1, - open: 1, - high: 1, - low: 1, - close: 1, - volume: 1, - adjustedClose: 1, - }, - } - ); - return prices.map(price => { - if ( - price.eodSearchCode !== identity.id || - price.symbol !== identity.symbol || - (price.providerExchange !== undefined && price.providerExchange !== identity.exchange) - ) { - throw new Error(`Historical instrument identity mismatch for ${symbol}`); - } - if ( - !/^\d{4}-\d{2}-\d{2}$/.test(price.date) || - !Number.isFinite(Date.parse(price.date)) || - new Date(price.date).toISOString().slice(0, 10) !== price.date - ) { - throw new Error(`Invalid historical session date for ${symbol}`); - } - return { - symbol, - timestamp: new Date(price.date), - open: price.open, - high: price.high, - low: price.low, - close: price.close, - volume: price.volume, - adjustedClose: price.adjustedClose, - source: 'eod' as const, - }; - }); - } - return this.generateMockBars(symbol, startTime, endTime, interval).map(bar => ({ - ...bar, - source: 'synthetic', - })); - } - - private generateMockBars( - symbol: string, - startTime: Date, - endTime: Date, - interval: string - ): HistoricalBar[] { - const bars = []; - const msPerInterval = this.getIntervalMilliseconds(interval); - let currentTime = new Date(startTime); - - // Synthetic data is only generated with explicit opt-in and a stable seed. - const seed = this.options.syntheticSeed ?? 42; - const seedMultiplier = (seed % 1000) / 1000; // 0-1 based on milliseconds - - // Starting price based on symbol with some randomness - let basePrice = - symbol === 'AAPL' - ? 150 + (seedMultiplier * 20 - 10) - : symbol === 'MSFT' - ? 300 + (seedMultiplier * 30 - 15) - : symbol === 'GOOGL' - ? 120 + (seedMultiplier * 15 - 7.5) - : 100 + (seedMultiplier * 10 - 5); - - // Random walk seed to make each run different - let walkSeed = seedMultiplier; - - while (currentTime < endTime) { - // Use a pseudo-random based on walkSeed for deterministic but different results - walkSeed = (walkSeed * 9.73 + 0.27) % 1; - - // Random walk with trend - increased volatility for testing - const trend = 0.0002; // Slight upward trend - const volatility = 0.01; // 1% volatility - const change = (walkSeed - 0.5 + trend) * volatility; - - basePrice *= 1 + change; - - // Generate OHLC data with more realistic volatility - const openSeed = (walkSeed * 7.13 + 0.31) % 1; - const highSeed = (walkSeed * 5.17 + 0.41) % 1; - const lowSeed = (walkSeed * 3.19 + 0.59) % 1; - const volumeSeed = (walkSeed * 11.23 + 0.67) % 1; - - const open = basePrice * (1 + (openSeed - 0.5) * 0.005); - const close = basePrice; - const high = Math.max(open, close) * (1 + highSeed * 0.008); - const low = Math.min(open, close) * (1 - lowSeed * 0.008); - const volume = 1000000 + volumeSeed * 500000; - - bars.push({ - symbol, - timestamp: new Date(currentTime), - open, - high, - low, - close, - volume, - vwap: (high + low + close) / 3, - }); - - currentTime = new Date(currentTime.getTime() + msPerInterval); - } - - this.logger.info(`Generated ${bars.length} mock bars for ${symbol} with seed ${seed}`); - - return bars; - } - - private getIntervalMilliseconds(interval: string): number { - switch (interval) { - case '1m': - return 60 * 1000; - case '5m': - return 5 * 60 * 1000; - case '15m': - return 15 * 60 * 1000; - case '1h': - return 60 * 60 * 1000; - case '1d': - return 24 * 60 * 60 * 1000; - default: - return 60 * 1000; // Default to 1 minute - } - } -} +/** Compatibility entrypoint; implementation is shared by the API and orchestrator. */ +export * from '@stock-bot/trading-runtime/historical-storage'; diff --git a/apps/stock/orchestrator/src/strategies/retained-program.ts b/apps/stock/orchestrator/src/strategies/retained-program.ts index 7a509343..080f4522 100644 --- a/apps/stock/orchestrator/src/strategies/retained-program.ts +++ b/apps/stock/orchestrator/src/strategies/retained-program.ts @@ -1,32 +1,17 @@ /** 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 { verifyRetainedProgramPackage } from '@stock-bot/trading-runtime/retained-package'; 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 { verifyRetainedProgramPackage } from '@stock-bot/trading-runtime/retained-package'; export async function importRetainedProgram( input: StrategyVersionPackage, diff --git a/apps/stock/web-api/package.json b/apps/stock/web-api/package.json index 00fd1513..cafb0925 100644 --- a/apps/stock/web-api/package.json +++ b/apps/stock/web-api/package.json @@ -26,7 +26,8 @@ "hono": "^4.0.0", "@stock-bot/invariants": "workspace:*", "@stock-bot/types": "workspace:*", - "zod": "^3.22.4" + "zod": "^3.22.4", + "@stock-bot/trading-runtime": "workspace:*" }, "devDependencies": { "typescript": "^5.0.0" diff --git a/apps/stock/web-api/src/routes/datasets.routes.ts b/apps/stock/web-api/src/routes/datasets.routes.ts index 6bd6d7c7..c300eabb 100644 --- a/apps/stock/web-api/src/routes/datasets.routes.ts +++ b/apps/stock/web-api/src/routes/datasets.routes.ts @@ -2,7 +2,7 @@ import { Hono } from 'hono'; import { getLogger } from '@stock-bot/logger'; import { requireServices, type IServiceContainer } from '@stock-bot/services'; import { HistoricalDataRequestError } from '@stock-bot/types'; -import { StorageService } from '../../../orchestrator/src/services/StorageService'; +import { StorageService } from '@stock-bot/trading-runtime/historical-storage'; import { canonicalDatasetEntry, CanonicalDatasetReadError, diff --git a/apps/stock/web-api/src/routes/paper-deployments.routes.ts b/apps/stock/web-api/src/routes/paper-deployments.routes.ts index 0108a135..eded588c 100644 --- a/apps/stock/web-api/src/routes/paper-deployments.routes.ts +++ b/apps/stock/web-api/src/routes/paper-deployments.routes.ts @@ -6,12 +6,12 @@ import { paperActivationSchema, paperHaltSchema, PaperRuntimeError, -} from '../../../orchestrator/src/contracts/paper-runtime'; -import { PaperDeploymentError } from '../../../orchestrator/src/paper/paper-deployment-custody'; +} from '@stock-bot/stock-config/paper-runtime'; +import { PaperDeploymentError } from '@stock-bot/trading-runtime/paper-deployment-custody'; import { paperAllowedOrigins, requirePaperOperator, -} from '../../../orchestrator/src/paper/paper-operator'; +} from '@stock-bot/trading-runtime/paper-operator'; import { PaperDeploymentsService } from '../services/paper-deployments.service'; import { ResearchError } from '../services/research-errors'; diff --git a/apps/stock/web-api/src/services/canonical-research.service.ts b/apps/stock/web-api/src/services/canonical-research.service.ts index 193891f0..1d128a32 100644 --- a/apps/stock/web-api/src/services/canonical-research.service.ts +++ b/apps/stock/web-api/src/services/canonical-research.service.ts @@ -30,8 +30,8 @@ import { type HistoricalDatasetV2, type StrategyParameterValue, } from '@stock-bot/types'; -import { readCandidateExecution } from '../../../orchestrator/src/backtest/candidate-sandbox'; -import { readCanonicalBuildIdentity } from '../../../orchestrator/src/backtest/canonical-build'; +import { readCandidateExecution } from '@stock-bot/trading-runtime/candidate-environment'; +import { readCanonicalBuildIdentity } from '@stock-bot/trading-runtime/canonical-build'; import { canonicalRiskSessionClock } from './canonical-risk-clock'; import type { DatasetCatalogQuery } from './dataset-catalog.service'; import { StrategyCatalogService } from './strategy-catalog.service'; diff --git a/apps/stock/web-api/src/services/dataset-preparation.service.ts b/apps/stock/web-api/src/services/dataset-preparation.service.ts index 5659c506..24129f91 100644 --- a/apps/stock/web-api/src/services/dataset-preparation.service.ts +++ b/apps/stock/web-api/src/services/dataset-preparation.service.ts @@ -5,7 +5,7 @@ import type { HistoricalDatasetInputV2, HistoricalDatasetV2 } from '@stock-bot/t import { retainResearchDataset, type RetainedDatasetStore, -} from '../../../orchestrator/src/data/retained-research-dataset'; +} from '@stock-bot/trading-runtime/retained-dataset'; import { canonicalDatasetUnavailableReason } from './canonical-research.service'; export class DatasetPreparationError extends Error { diff --git a/apps/stock/web-api/src/services/paper-deployments.service.ts b/apps/stock/web-api/src/services/paper-deployments.service.ts index a532269f..3007ea66 100644 --- a/apps/stock/web-api/src/services/paper-deployments.service.ts +++ b/apps/stock/web-api/src/services/paper-deployments.service.ts @@ -14,7 +14,7 @@ import { } from '@stock-bot/stock-config/paper-deployments'; import { assertStrategyJsonText, canonicalStrategyJson } from '@stock-bot/stock-config/strategy'; import type { ResearchEvidenceReference } from '@stock-bot/types'; -import { validatePaperConfiguration } from '../../../orchestrator/src/paper/feed'; +import { validatePaperConfiguration } from '@stock-bot/trading-runtime/paper-configuration'; import { authorizedPaperPackage, PaperDeploymentError, @@ -22,8 +22,8 @@ import { paperPreviewHash, readPaperDeployment, retainedPaperDeployment, -} from '../../../orchestrator/src/paper/paper-deployment-custody'; -import { readPaperHostIdentity } from '../../../orchestrator/src/paper/paper-host-identity'; +} from '@stock-bot/trading-runtime/paper-deployment-custody'; +import { readPaperHostIdentity } from '@stock-bot/trading-runtime/paper-host-identity'; import { BacktestServiceV2, type BacktestResultQuery } from './backtest-v2.service'; import { retainedCostSensitivityPreview } from './cost-sensitivity-input'; import { canonicalReproductionHash } from './reproduction-comparison'; diff --git a/apps/stock/web-api/src/services/run-reproduction.ts b/apps/stock/web-api/src/services/run-reproduction.ts index 35da8e39..9804715e 100644 --- a/apps/stock/web-api/src/services/run-reproduction.ts +++ b/apps/stock/web-api/src/services/run-reproduction.ts @@ -3,8 +3,8 @@ import type { IServiceContainer } from '@stock-bot/services'; import type { CanonicalRunRequest } from '@stock-bot/stock-config/canonical-research'; import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy'; import { HistoricalDataRequestError } from '@stock-bot/types'; -import { verifyCandidateExecution } from '../../../orchestrator/src/backtest/candidate-sandbox'; -import { readCanonicalBuildIdentity } from '../../../orchestrator/src/backtest/canonical-build'; +import { verifyCandidateExecution } from '@stock-bot/trading-runtime/candidate-environment'; +import { readCanonicalBuildIdentity } from '@stock-bot/trading-runtime/canonical-build'; import { readCanonicalDataset } from './canonical-research.service'; import { StrategyCatalogError, StrategyCatalogService } from './strategy-catalog.service'; diff --git a/apps/stock/web-api/src/services/stored-dataset-preparation.ts b/apps/stock/web-api/src/services/stored-dataset-preparation.ts index 27a07999..f31ad0da 100644 --- a/apps/stock/web-api/src/services/stored-dataset-preparation.ts +++ b/apps/stock/web-api/src/services/stored-dataset-preparation.ts @@ -8,7 +8,7 @@ import type { HistoricalDatasetInputV2, HistoricalDatasetMetadataV2 } from '@sto import { HistoricalStorageError, type StorageService, -} from '../../../orchestrator/src/services/StorageService'; +} from '@stock-bot/trading-runtime/historical-storage'; import { DatasetPreparationError, previewDatasetPreparation } from './dataset-preparation.service'; export class StoredDatasetPreparationError extends Error { diff --git a/apps/stock/web-api/src/services/stored-source-inspection.ts b/apps/stock/web-api/src/services/stored-source-inspection.ts index d506bc7d..d511a797 100644 --- a/apps/stock/web-api/src/services/stored-source-inspection.ts +++ b/apps/stock/web-api/src/services/stored-source-inspection.ts @@ -11,7 +11,7 @@ import { parseInstrumentId } from '@stock-bot/types'; import { PREPARATION_BATCH_SIZE, preparationCheckpoint, -} from '../../../orchestrator/src/data/preparation'; +} from '@stock-bot/trading-runtime/preparation'; const collections = { '1m': 'eodIntraday1M', diff --git a/bun.lock b/bun.lock index 69343b10..79860f7d 100644 --- a/bun.lock +++ b/bun.lock @@ -143,6 +143,7 @@ "@stock-bot/services": "workspace:*", "@stock-bot/shutdown": "*", "@stock-bot/stock-config": "*", + "@stock-bot/trading-runtime": "workspace:*", "@stock-bot/types": "workspace:*", "axios": "^1.6.0", "decimal.js-light": "2.5.1", @@ -180,6 +181,7 @@ "@stock-bot/services": "workspace:*", "@stock-bot/shutdown": "*", "@stock-bot/stock-config": "*", + "@stock-bot/trading-runtime": "workspace:*", "@stock-bot/types": "workspace:*", "hono": "^4.0.0", "zod": "^3.22.4", @@ -508,6 +510,22 @@ "typescript": "^5.0.0", }, }, + "libs/trading-runtime": { + "name": "@stock-bot/trading-runtime", + "version": "1.0.0", + "dependencies": { + "@stock-bot/di": "workspace:*", + "@stock-bot/engine": "workspace:*", + "@stock-bot/research": "workspace:*", + "@stock-bot/services": "workspace:*", + "@stock-bot/stock-config": "workspace:*", + "@stock-bot/types": "workspace:*", + "zod": "^3.22.4", + }, + "devDependencies": { + "@types/pg": "^8.15.4", + }, + }, "libs/utils": { "name": "@stock-bot/utils", "version": "1.0.0", @@ -1024,6 +1042,8 @@ "@stock-bot/stock-config": ["@stock-bot/stock-config@workspace:apps/stock/config"], + "@stock-bot/trading-runtime": ["@stock-bot/trading-runtime@workspace:libs/trading-runtime"], + "@stock-bot/types": ["@stock-bot/types@workspace:libs/core/types"], "@stock-bot/utils": ["@stock-bot/utils@workspace:libs/utils"], diff --git a/docs/development/architecture-cleanup-execution.md b/docs/development/architecture-cleanup-execution.md index 5cf688d2..b57ddb3c 100644 --- a/docs/development/architecture-cleanup-execution.md +++ b/docs/development/architecture-cleanup-execution.md @@ -21,3 +21,5 @@ Agents use root-reserved disjoint files in the integration worktree. Root alone - **CL25:** Shared response wire schemas and server type aliases; root mapping/date/invalid-response/run-control tests 59 passed (388 assertions), agent complete focused UI/transport/reproduction set 358 passed. Scoped lint/format passed. Preserves historical optional records and submission receipt/idempotency guards. - **CL32:** Independent pure projection/runtime suite 4 passed, 22 assertions; disposable PostgreSQL paper-runtime suite 22 passed, 143 assertions. Verified atomic expiry latch, rollback on storage failure, no implicit reactivation, stale generation and restart recovery. Scoped lint/format passed. + +- **CL26:** Moved existing shared server helpers to explicit trading-runtime subpaths, shared financial wire contracts to config, split metadata verifier from executable loader, and made artifact paths lazy. Config/runtime/API/orchestrator builds and full source typecheck passed. Architecture/Turbo/browser gates: 30 passed (7363 assertions); shared admission/storage/feed tests passed; isolated retained worker final15 passed after preserving rejection diagnostics. Native finance unchanged. diff --git a/docs/development/backlog/README.md b/docs/development/backlog/README.md index 4287b257..e8362636 100644 --- a/docs/development/backlog/README.md +++ b/docs/development/backlog/README.md @@ -1,6 +1,6 @@ # Canonical development backlog -**Active: E13 architecture cleanup, CL22–CL35 (7/14 complete).** Owner authorized all October 28 audit recommendations and a commit per validated task. Earlier completion counts below are historical. [Execution record](../architecture-cleanup-execution.md). +**Active: E13 architecture cleanup, CL22–CL35 (8/14 complete).** Owner authorized all October 28 audit recommendations and a commit per validated task. Earlier completion counts below are historical. [Execution record](../architecture-cleanup-execution.md). **Current scheduled backlog: 99/99 complete.** The owner resumed performance and authorized review of all seven conditions. P08 and O02 are implemented; five optional extensions remain deliberately deferred, and four merged IDs are redirects. This is not a claim that all 108 retained IDs were implemented. [Decisions, measurements and validation](../conditional-review.md). diff --git a/docs/development/backlog/manifest.json b/docs/development/backlog/manifest.json index fabfcdd1..caa043ec 100644 --- a/docs/development/backlog/manifest.json +++ b/docs/development/backlog/manifest.json @@ -3830,7 +3830,7 @@ "epic": "E13", "priority": "P1", "severity": "High", - "status": "ready", + "status": "done", "dependencies": [], "decision_dependencies": [], "task_file": "backlog/tasks/CL26.md", @@ -3840,7 +3840,9 @@ "completed_commit": null, "blocker": null, "release_gates": [], - "completion_evidence": "architecture-cleanup-execution.md" + "completion_evidence": "architecture-cleanup-execution.md", + "integration_state": "accepted", + "validation": "Moved existing shared server helpers to explicit trading-runtime subpaths, shared financial wire contracts to config, split metadata verifier from executable loader, and made artifact paths lazy. Config/runtime/API/orchestrator builds and full source typecheck passed. Architecture/Turbo/browser gates: 30 passed (7363 assertions); shared admission/storage/feed tests passed; isolated retained worker final15 passed after preserving rejection diagnostics. Native finance unchanged." }, { "id": "CL27", @@ -3868,7 +3870,7 @@ "epic": "E13", "priority": "P2", "severity": "Medium", - "status": "blocked", + "status": "ready", "dependencies": ["CL26"], "decision_dependencies": [], "task_file": "backlog/tasks/CL28.md", @@ -3876,7 +3878,7 @@ "assignment": null, "write_locks": ["CL28"], "completed_commit": null, - "blocker": "Implementation dependencies", + "blocker": null, "release_gates": [], "completion_evidence": "architecture-cleanup-execution.md" }, @@ -3922,7 +3924,7 @@ "epic": "E13", "priority": "P2", "severity": "Medium", - "status": "blocked", + "status": "ready", "dependencies": ["CL26"], "decision_dependencies": [], "task_file": "backlog/tasks/CL31.md", @@ -3930,7 +3932,7 @@ "assignment": null, "write_locks": ["CL31"], "completed_commit": null, - "blocker": "Implementation dependencies", + "blocker": null, "release_gates": [], "completion_evidence": "architecture-cleanup-execution.md" }, @@ -3947,7 +3949,7 @@ "complexity": "M", "assignment": null, "write_locks": ["CL32"], - "completed_commit": null, + "completed_commit": "2165a2efa845b601ce478d59d31bce5ea5cfbaa4", "blocker": null, "release_gates": [], "completion_evidence": "architecture-cleanup-execution.md", @@ -10395,7 +10397,7 @@ ], "work_policy": "Root integrates/commits reviewed tasks; agents own disjoint explicit files in the root integration worktree. Only root builds shared outputs and runs combined gates. No isolated native agent build claim.", "first_wave": ["CL22", "CL23", "CL24"], - "completed": 7, - "last_verification": "Independent pure projection/runtime suite 4 passed, 22 assertions; disposable PostgreSQL paper-runtime suite 22 passed, 143 assertions. Verified atomic expiry latch, rollback on storage failure, no implicit reactivation, stale generation and restart recovery. Scoped lint/format passed." + "completed": 8, + "last_verification": "Moved existing shared server helpers to explicit trading-runtime subpaths, shared financial wire contracts to config, split metadata verifier from executable loader, and made artifact paths lazy. Config/runtime/API/orchestrator builds and full source typecheck passed. Architecture/Turbo/browser gates: 30 passed (7363 assertions); shared admission/storage/feed tests passed; isolated retained worker final15 passed after preserving rejection diagnostics. Native finance unchanged." } } diff --git a/docs/development/backlog/tasks/CL26.md b/docs/development/backlog/tasks/CL26.md index 981e2df6..4fd7db10 100644 --- a/docs/development/backlog/tasks/CL26.md +++ b/docs/development/backlog/tasks/CL26.md @@ -18,3 +18,7 @@ Import/Turbo graph; dataset/candidate/paper admission; artifact identity; browse No new service/framework, financial simulator, real trading activation, external research execution, push/PR or .env changes. D04/P03/P05/P06/CL21 remain deferred. Root owns shared outputs, task state and commits; agents own disjoint files in the integration worktree. + +## Accepted verification + +Moved existing shared server helpers to explicit trading-runtime subpaths, shared financial wire contracts to config, split metadata verifier from executable loader, and made artifact paths lazy. Config/runtime/API/orchestrator builds and full source typecheck passed. Architecture/Turbo/browser gates: 30 passed (7363 assertions); shared admission/storage/feed tests passed; isolated retained worker final15 passed after preserving rejection diagnostics. Native finance unchanged. diff --git a/libs/trading-runtime/package.json b/libs/trading-runtime/package.json new file mode 100644 index 00000000..df26c5b4 --- /dev/null +++ b/libs/trading-runtime/package.json @@ -0,0 +1,35 @@ +{ + "name": "@stock-bot/trading-runtime", + "version": "1.0.0", + "private": true, + "type": "module", + "description": "Shared server-side artifact inspection, historical storage and paper admission; no strategy or financial execution", + "exports": { + "./preparation": "./src/preparation.ts", + "./historical-storage": "./src/historical-storage.ts", + "./retained-dataset": "./src/retained-dataset.ts", + "./retained-package": "./src/retained-package.ts", + "./paper-configuration": "./src/paper-configuration.ts", + "./paper-deployment-custody": "./src/paper-deployment-custody.ts", + "./paper-operator": "./src/paper-operator.ts", + "./artifacts": "./src/artifacts.ts", + "./canonical-build": "./src/canonical-build.ts", + "./paper-host-identity": "./src/paper-host-identity.ts", + "./candidate-environment": "./src/candidate-environment.ts" + }, + "scripts": { + "build": "tsc" + }, + "dependencies": { + "@stock-bot/types": "workspace:*", + "@stock-bot/research": "workspace:*", + "@stock-bot/stock-config": "workspace:*", + "@stock-bot/services": "workspace:*", + "@stock-bot/di": "workspace:*", + "@stock-bot/engine": "workspace:*", + "zod": "^3.22.4" + }, + "devDependencies": { + "@types/pg": "^8.15.4" + } +} diff --git a/libs/trading-runtime/src/artifacts.ts b/libs/trading-runtime/src/artifacts.ts new file mode 100644 index 00000000..f648d976 --- /dev/null +++ b/libs/trading-runtime/src/artifacts.ts @@ -0,0 +1,66 @@ +/** Shared server-only artifact custody. Resolve paths on demand, never while importing APIs. */ +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'; + +export function localBuildArtifacts() { + 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('Canonical engine resolves outside this checkout'); + } + if (engineWrapper !== resolve(repositoryRoot, 'apps/stock/engine/index.mjs')) { + throw new Error('Unsupported canonical engine wrapper location'); + } + return { repositoryRoot, engineWrapper }; +} +export function bundledHostUrl(name: 'native-worker' | 'paper-host'): URL { + return pathToFileURL( + resolve(localBuildArtifacts().repositoryRoot, `apps/stock/orchestrator/dist/${name}.js`) + ); +} +export async function hashLocalArtifact(path: string): Promise { + if (realpathSync(path) !== path) { + throw new Error('Canonical build artifacts must belong to this checkout'); + } + return createHash('sha256') + .update(await readFile(path)) + .digest('hex'); +} +export async function readBuildArtifacts(name: 'native-worker' | 'paper-host') { + if (typeof Bun === 'undefined') { + throw new Error('Canonical execution requires the Bun runtime'); + } + const { repositoryRoot, engineWrapper } = localBuildArtifacts(); + const [executableSha256, engineWrapperSha256, engineBinarySha256, dependencyLockSha256] = + await Promise.all([ + hashLocalArtifact(fileURLToPath(bundledHostUrl(name))), + hashLocalArtifact(engineWrapper), + hashLocalArtifact(resolve(repositoryRoot, 'apps/stock/engine/dist/engine.node')), + hashLocalArtifact(resolve(repositoryRoot, 'bun.lock')), + ]); + return { + executableSha256, + engineWrapperSha256, + engineBinarySha256, + dependencyLockSha256, + runtime: 'bun' as const, + runtimeVersion: Bun.version, + platform: process.platform, + arch: process.arch, + }; +} +export function verifyBundledHost(name: 'native-worker' | 'paper-host', actualUrl: string): void { + if ( + realpathSync(fileURLToPath(actualUrl)) !== realpathSync(fileURLToPath(bundledHostUrl(name))) + ) { + throw new Error( + name === 'native-worker' + ? 'Canonical research requires the bundled worker from this checkout' + : 'Paper deployment requires the bundled paper host from this checkout' + ); + } +} diff --git a/libs/trading-runtime/src/candidate-environment.ts b/libs/trading-runtime/src/candidate-environment.ts new file mode 100644 index 00000000..d84bb0cc --- /dev/null +++ b/libs/trading-runtime/src/candidate-environment.ts @@ -0,0 +1,109 @@ +/** Installed candidate metadata and isolation inspection. Never launches or imports a strategy. */ +import { execFile } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { mkdtemp, readFile, realpath, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { promisify } from 'node:util'; +import { + candidateExecutionSchema, + type CandidateExecution, +} from '@stock-bot/stock-config/candidate-execution'; +import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy'; +import { localBuildArtifacts } from './artifacts'; + +const runFile = promisify(execFile); +export const docker = '/usr/bin/docker'; +export const daemon = ['--host', 'unix:///var/run/docker.sock']; +export const environment = (config: string) => ({ PATH: '/usr/bin:/bin', DOCKER_CONFIG: config }); +export const candidateDescriptorPath = () => + resolve( + localBuildArtifacts().repositoryRoot, + 'apps/stock/orchestrator/dist/candidate-sandbox.json' + ); +export class CandidateSandboxUnavailable extends Error { + readonly code = 'candidate_sandbox_unavailable'; +} + +export 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 { + try { + if (process.platform !== 'linux' || process.arch !== 'x64') { + throw new Error('Unsupported candidate platform'); + } + const root = localBuildArtifacts().repositoryRoot; + 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 { + if ( + canonicalStrategyJson(await readCandidateExecution()) !== + canonicalStrategyJson(candidateExecutionSchema.parse(expected)) + ) { + throw new CandidateSandboxUnavailable( + 'The retained isolated candidate runtime is not installed' + ); + } +} diff --git a/libs/trading-runtime/src/canonical-build.ts b/libs/trading-runtime/src/canonical-build.ts new file mode 100644 index 00000000..bb282e31 --- /dev/null +++ b/libs/trading-runtime/src/canonical-build.ts @@ -0,0 +1,31 @@ +/** Read-only identity; importing this module neither resolves nor loads executable artifacts. */ +import { + canonicalBuildIdentitySchema, + type CanonicalBuildIdentity, +} from '@stock-bot/stock-config/canonical-research'; +import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy'; +import { bundledHostUrl, readBuildArtifacts, verifyBundledHost } from './artifacts'; + +export const canonicalWorkerUrl = () => bundledHostUrl('native-worker'); +export async function readCanonicalBuildIdentity(): Promise { + const { executableSha256, ...common } = await readBuildArtifacts('native-worker'); + return canonicalBuildIdentitySchema.parse({ + version: 1, + workerSha256: executableSha256, + ...common, + }); +} +export async function verifyCanonicalWorkerBuild( + expected: CanonicalBuildIdentity, + actualUrl: string +): Promise { + verifyBundledHost('native-worker', actualUrl); + const actual = await readCanonicalBuildIdentity(); + if ( + canonicalStrategyJson(actual) !== + canonicalStrategyJson(canonicalBuildIdentitySchema.parse(expected)) + ) { + throw new Error('Canonical worker/native/runtime build identity mismatch'); + } + return actual; +} diff --git a/libs/trading-runtime/src/historical-storage.ts b/libs/trading-runtime/src/historical-storage.ts new file mode 100644 index 00000000..519e99c7 --- /dev/null +++ b/libs/trading-runtime/src/historical-storage.ts @@ -0,0 +1,490 @@ +import type { Logger, MongoDBClient, QuestDBClient } from '@stock-bot/services'; +import { parseInstrumentId, type HistoricalDataPolicy } from '@stock-bot/types'; +import { PREPARATION_BATCH_SIZE, preparationCheckpoint } from './preparation'; + +export interface HistoricalBar { + symbol: string; + timestamp: Date; + open: number; + high: number; + low: number; + close: number; + volume: number; + vwap?: number; + interpolated?: boolean; + source?: 'eod' | 'questdb' | 'synthetic'; + adjustedClose?: number; +} + +export type HistoricalStorageProvider = 'questdb' | 'eod'; +export type HistoricalStorageErrorCode = + | 'unsupported-provider' + | 'unsupported-interval' + | 'provider-unavailable' + | 'missing-range'; + +/** Storage routing failures are distinct from invalid records and transport failures. */ +export class HistoricalStorageError extends Error { + constructor( + readonly code: HistoricalStorageErrorCode, + message: string, + readonly provider?: HistoricalStorageProvider | 'synthetic' + ) { + super(message); + this.name = 'HistoricalStorageError'; + } +} + +const historicalIntervals = ['1m', '5m', '15m', '1h', '1d'] as const; +const eodIntradayCollections: Readonly> = { + '1m': 'eodIntraday1M', + '5m': 'eodIntraday5M', + '1h': 'eodIntraday1H', +}; + +/** Historical reads over borrowed adapters; ingestion and migrations own all writes. */ +export class StorageService { + private readonly questdb: QuestDBClient | null; + private readonly mongodb: MongoDBClient | null; + + constructor( + private readonly logger: Pick, + mongoClient: MongoDBClient | null | undefined, + questdbClient: QuestDBClient | null, + private readonly options: { allowSyntheticData?: boolean; syntheticSeed?: number } = {} + ) { + this.mongodb = mongoClient ?? null; + this.questdb = questdbClient; + } + + /** Adapter support and current connectivity, not evidence of stored range coverage. */ + getHistoricalCapabilities() { + return [ + { + provider: 'questdb' as const, + configured: this.questdb !== null, + connected: this.questdb?.connected ?? false, + intervals: [...historicalIntervals], + }, + { + provider: 'eod' as const, + configured: this.mongodb !== null, + connected: this.mongodb?.connected ?? false, + intervals: ['1m', '5m', '1h', '1d'] as const, + }, + ]; + } + + private selectHistoricalProvider( + requested: HistoricalStorageProvider | 'auto' + ): HistoricalStorageProvider | 'synthetic' { + if (!['auto', 'questdb', 'eod'].includes(requested)) { + throw new HistoricalStorageError('unsupported-provider', 'Unsupported historical provider'); + } + if (requested === 'questdb' || (requested === 'auto' && this.questdb)) { + if (!this.questdb) { + throw new HistoricalStorageError( + 'provider-unavailable', + 'QuestDB historical storage is unavailable', + 'questdb' + ); + } + return 'questdb'; + } + if (requested === 'eod' || (requested === 'auto' && this.mongodb)) { + if (!this.mongodb) { + throw new HistoricalStorageError( + 'provider-unavailable', + 'EOD historical storage is unavailable', + 'eod' + ); + } + return 'eod'; + } + if (this.options.allowSyntheticData) { + return 'synthetic'; + } + throw new HistoricalStorageError( + 'provider-unavailable', + 'No historical data store configured; synthetic data requires explicit opt-in' + ); + } + + /** One historical-data policy for native and TypeScript execution. */ + async getHistoricalBars( + symbol: string, + startTime: Date, + endTime: Date, + interval = '1m', + policy: HistoricalDataPolicy = { + adjustment: 'raw', + timestamp: interval === '1d' ? 'utc-session-date' : 'utc-instant', + }, + signal?: AbortSignal, + provider: HistoricalStorageProvider | 'auto' = 'auto' + ): Promise { + signal?.throwIfAborted(); + parseInstrumentId(symbol); + if ( + !Number.isFinite(startTime.getTime()) || + !Number.isFinite(endTime.getTime()) || + endTime <= startTime + ) { + throw new Error('Invalid historical date range'); + } + if (!(historicalIntervals as readonly string[]).includes(interval)) { + throw new HistoricalStorageError('unsupported-interval', 'Unsupported historical interval'); + } + if ( + (interval === '1d') !== (policy.timestamp === 'utc-session-date') || + (interval === '1d' && + (startTime.getTime() % 86400000 !== 0 || endTime.getTime() % 86400000 !== 0)) + ) { + throw new Error( + 'Daily ranges must use UTC midnight session dates; intraday ranges use UTC instants' + ); + } + const selectedProvider = this.selectHistoricalProvider(provider); + const rows = await this.readHistoricalBars( + symbol, + startTime, + endTime, + interval, + selectedProvider, + signal + ); + signal?.throwIfAborted(); + const bars: HistoricalBar[] = []; + let processed = 0; + for (const row of rows) { + if (row.symbol !== symbol) { + throw new Error(`Historical instrument identity mismatch for ${symbol}`); + } + if (typeof row.timestamp === 'string' && !/(Z|[+-]\d{2}:\d{2})$/.test(row.timestamp)) { + throw new Error('Historical instants require an explicit UTC offset'); + } + const timestamp = new Date(row.timestamp); + const numeric = (value: unknown) => + typeof value === 'number' + ? value + : typeof value === 'string' && value.trim() + ? Number(value) + : NaN; + let open = numeric(row.open), + high = numeric(row.high), + low = numeric(row.low), + close = numeric(row.close); + const volume = numeric(row.volume); + if ( + !Number.isFinite(timestamp.getTime()) || + ![open, high, low, close, volume].every(Number.isFinite) || + low <= 0 || + high < Math.max(open, close) || + low > Math.min(open, close) || + volume < 0 || + (interval === '1d' && timestamp.getTime() % 86400000 !== 0) + ) { + throw new Error(`Invalid historical OHLCV data for ${symbol}`); + } + let vwap = row.vwap === null || row.vwap === undefined ? undefined : numeric(row.vwap); + if (policy.adjustment === 'provider-adjusted') { + const adjustedClose = numeric(row.adjustedClose); + if (!(adjustedClose > 0) || !Number.isFinite(adjustedClose)) { + throw new Error(`Provider-adjusted prices unavailable for ${symbol}`); + } + const factor = adjustedClose / close; + open *= factor; + high *= factor; + low *= factor; + close = adjustedClose; + if (vwap !== undefined) { + vwap *= factor; + } + } + if ( + ![open, high, low, close].every(value => Number.isFinite(value) && value > 0) || + (vwap !== undefined && (!Number.isFinite(vwap) || vwap <= 0)) + ) { + throw new Error(`Invalid adjusted historical data for ${symbol}`); + } + if (timestamp >= startTime && timestamp < endTime) { + bars.push({ ...row, symbol, timestamp, open, high, low, close, volume, vwap }); + } + if (++processed % PREPARATION_BATCH_SIZE === 0) { + await preparationCheckpoint(signal); + } + } + signal?.throwIfAborted(); + bars.sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime()); + if (!bars.length) { + throw new HistoricalStorageError( + 'missing-range', + `No historical data for ${symbol} in the requested range`, + selectedProvider + ); + } + if ( + bars.some( + (bar, index) => + index > 0 && bars[index - 1]?.timestamp.getTime() === bar.timestamp.getTime() + ) + ) { + throw new Error(`Duplicate historical timestamps for ${symbol}`); + } + return bars; + } + + private async readHistoricalBars( + symbol: string, + startTime: Date, + endTime: Date, + interval: string, + provider: HistoricalStorageProvider | 'synthetic', + signal?: AbortSignal + ): Promise { + // Select once, before reading: empty ranges/errors never switch providers. + if (provider === 'questdb' && this.questdb) { + const result = await this.questdb.query( + `SELECT * FROM bars_${interval} WHERE symbol = $1 AND timestamp >= $2 AND timestamp < $3 ORDER BY timestamp`, + [symbol, startTime, endTime] + ); + return result.rows.map(row => ({ ...row, source: 'questdb' })); + } + + if (provider === 'eod' && this.mongodb) { + const identity = parseInstrumentId(symbol); + if (interval !== '1d') { + const collection = eodIntradayCollections[interval]; + if (!collection) { + throw new HistoricalStorageError( + 'unsupported-interval', + `EOD historical storage does not support ${interval}`, + 'eod' + ); + } + // fetchIntraday writes raw bar-start UTC Unix seconds, not local datetime labels. + // https://eodhd.com/financial-apis/intraday-historical-data-api + // This instant is not publication time; availability/calendar policy belongs to datasets. + const records = await this.mongodb.find<{ + symbol: string; + exchange: string; + eodSearchCode: string; + timestamp: number; + open: number; + high: number; + low: number; + close: number; + volume: number; + }>( + collection, + { + eodSearchCode: identity.id, + timestamp: { $gte: startTime.getTime() / 1000, $lt: endTime.getTime() / 1000 }, + }, + { + sort: { timestamp: 1 }, + projection: { + symbol: 1, + exchange: 1, + eodSearchCode: 1, + timestamp: 1, + open: 1, + high: 1, + low: 1, + close: 1, + volume: 1, + }, + } + ); + signal?.throwIfAborted(); + const bars: HistoricalBar[] = []; + for (const record of records) { + if ( + record.eodSearchCode !== identity.id || + record.symbol !== identity.symbol || + record.exchange !== identity.exchange + ) { + throw new Error(`Historical instrument identity mismatch for ${symbol}`); + } + const milliseconds = record.timestamp * 1000; + if ( + !Number.isSafeInteger(record.timestamp) || + !Number.isSafeInteger(milliseconds) || + !Number.isFinite(new Date(milliseconds).getTime()) + ) { + throw new Error(`Invalid historical Unix-seconds timestamp for ${symbol}`); + } + bars.push({ + symbol, + timestamp: new Date(milliseconds), + open: record.open, + high: record.high, + low: record.low, + close: record.close, + volume: record.volume, + source: 'eod', + }); + if (bars.length % PREPARATION_BATCH_SIZE === 0) { + await preparationCheckpoint(signal); + } + } + return bars; + } + const prices = await this.mongodb.find<{ + symbol: string; + exchange: string; + eodSearchCode: string; + providerExchange?: string; + date: string; + open: number; + high: number; + low: number; + close: number; + volume: number; + adjustedClose?: number; + }>( + 'eodPrices', + { + eodSearchCode: identity.id, + date: { + $gte: startTime.toISOString().slice(0, 10), + $lt: endTime.toISOString().slice(0, 10), + }, + }, + { + sort: { date: 1 }, + projection: { + symbol: 1, + exchange: 1, + eodSearchCode: 1, + providerExchange: 1, + date: 1, + open: 1, + high: 1, + low: 1, + close: 1, + volume: 1, + adjustedClose: 1, + }, + } + ); + return prices.map(price => { + if ( + price.eodSearchCode !== identity.id || + price.symbol !== identity.symbol || + (price.providerExchange !== undefined && price.providerExchange !== identity.exchange) + ) { + throw new Error(`Historical instrument identity mismatch for ${symbol}`); + } + if ( + !/^\d{4}-\d{2}-\d{2}$/.test(price.date) || + !Number.isFinite(Date.parse(price.date)) || + new Date(price.date).toISOString().slice(0, 10) !== price.date + ) { + throw new Error(`Invalid historical session date for ${symbol}`); + } + return { + symbol, + timestamp: new Date(price.date), + open: price.open, + high: price.high, + low: price.low, + close: price.close, + volume: price.volume, + adjustedClose: price.adjustedClose, + source: 'eod' as const, + }; + }); + } + return this.generateMockBars(symbol, startTime, endTime, interval).map(bar => ({ + ...bar, + source: 'synthetic', + })); + } + + private generateMockBars( + symbol: string, + startTime: Date, + endTime: Date, + interval: string + ): HistoricalBar[] { + const bars = []; + const msPerInterval = this.getIntervalMilliseconds(interval); + let currentTime = new Date(startTime); + + // Synthetic data is only generated with explicit opt-in and a stable seed. + const seed = this.options.syntheticSeed ?? 42; + const seedMultiplier = (seed % 1000) / 1000; // 0-1 based on milliseconds + + // Starting price based on symbol with some randomness + let basePrice = + symbol === 'AAPL' + ? 150 + (seedMultiplier * 20 - 10) + : symbol === 'MSFT' + ? 300 + (seedMultiplier * 30 - 15) + : symbol === 'GOOGL' + ? 120 + (seedMultiplier * 15 - 7.5) + : 100 + (seedMultiplier * 10 - 5); + + // Random walk seed to make each run different + let walkSeed = seedMultiplier; + + while (currentTime < endTime) { + // Use a pseudo-random based on walkSeed for deterministic but different results + walkSeed = (walkSeed * 9.73 + 0.27) % 1; + + // Random walk with trend - increased volatility for testing + const trend = 0.0002; // Slight upward trend + const volatility = 0.01; // 1% volatility + const change = (walkSeed - 0.5 + trend) * volatility; + + basePrice *= 1 + change; + + // Generate OHLC data with more realistic volatility + const openSeed = (walkSeed * 7.13 + 0.31) % 1; + const highSeed = (walkSeed * 5.17 + 0.41) % 1; + const lowSeed = (walkSeed * 3.19 + 0.59) % 1; + const volumeSeed = (walkSeed * 11.23 + 0.67) % 1; + + const open = basePrice * (1 + (openSeed - 0.5) * 0.005); + const close = basePrice; + const high = Math.max(open, close) * (1 + highSeed * 0.008); + const low = Math.min(open, close) * (1 - lowSeed * 0.008); + const volume = 1000000 + volumeSeed * 500000; + + bars.push({ + symbol, + timestamp: new Date(currentTime), + open, + high, + low, + close, + volume, + vwap: (high + low + close) / 3, + }); + + currentTime = new Date(currentTime.getTime() + msPerInterval); + } + + this.logger.info(`Generated ${bars.length} mock bars for ${symbol} with seed ${seed}`); + + return bars; + } + + private getIntervalMilliseconds(interval: string): number { + switch (interval) { + case '1m': + return 60 * 1000; + case '5m': + return 5 * 60 * 1000; + case '15m': + return 15 * 60 * 1000; + case '1h': + return 60 * 60 * 1000; + case '1d': + return 24 * 60 * 60 * 1000; + default: + return 60 * 1000; // Default to 1 minute + } + } +} diff --git a/libs/trading-runtime/src/paper-configuration.ts b/libs/trading-runtime/src/paper-configuration.ts new file mode 100644 index 00000000..d1779731 --- /dev/null +++ b/libs/trading-runtime/src/paper-configuration.ts @@ -0,0 +1,145 @@ +import { isDeepStrictEqual } from 'node:util'; +import { ZodError } from 'zod'; +import { + paperConfigurationSchema, + PaperRuntimeError, + type PaperConfiguration, + type PaperConfigurationInput, +} from '@stock-bot/stock-config/paper-runtime'; + +function invalid(message: string): never { + throw new PaperRuntimeError('invalid-input', message); +} +// Decimal wire transforms throw ordinary Errors. Classify only this synchronous +// input parsing boundary, never arbitrary storage/native errors, as bad input. +function parseInput(schema: { parse(input: unknown): T }, input: unknown): T { + try { + return schema.parse(input); + } catch (error) { + if (error instanceof ZodError) { + throw error; + } + invalid(error instanceof Error ? error.message : 'Malformed paper input'); + } +} +// UTF-8 ordering agrees with Rust Id/String ordering, including supplementary characters. +const compareText = (a: string, b: string) => Buffer.compare(Buffer.from(a), Buffer.from(b)); +function unique(values: readonly string[], label: string): void { + if (new Set(values).size !== values.length) { + invalid(`Duplicate paper ${label}`); + } +} + +export function validatePaperConfiguration(input: PaperConfigurationInput): PaperConfiguration { + const config = parseInput(paperConfigurationSchema, input); + const { matching, policy, strategies } = config; + if (!matching.series.length || matching.series.some(series => series.mode !== 'Quote')) { + invalid('Canonical paper feed supports Quote execution only'); + } + unique( + matching.series.map(item => item.instrumentId), + 'execution instrument' + ); + unique( + matching.series.map(item => item.seriesId), + 'execution series' + ); + unique( + matching.owners.map(item => item.ownerId), + 'owner' + ); + unique(matching.risk.ledger.ownerIds, 'ledger owner'); + unique( + strategies.map(item => item.ownerId), + 'strategy owner' + ); + unique( + policy.observations.map(item => item.seriesId), + 'observation series' + ); + unique( + policy.cadence.map(item => item.ownerId), + 'cadence owner' + ); + unique( + policy.calendars.map(item => item.instrumentId), + 'calendar instrument' + ); + const owners = matching.owners.map(item => item.ownerId).sort(compareText); + if ( + matching.owners.some(item => item.mode !== 'Target') || + !isDeepStrictEqual(owners, [...matching.risk.ledger.ownerIds].sort(compareText)) || + !isDeepStrictEqual(owners, strategies.map(item => item.ownerId).sort(compareText)) || + !isDeepStrictEqual(owners, policy.cadence.map(item => item.ownerId).sort(compareText)) + ) { + invalid('Paper built-ins must exactly match the target owner and cadence cohort'); + } + const instruments = matching.series.map(item => item.instrumentId).sort(compareText); + if ( + !isDeepStrictEqual( + instruments, + policy.calendars.map(item => item.instrumentId).sort(compareText) + ) + ) { + invalid('Paper calendars must exactly cover execution instruments'); + } + for (const observation of policy.observations) { + if (!instruments.includes(observation.instrumentId)) { + invalid('Paper observation references an unknown instrument'); + } + } + for (const cadence of policy.cadence) { + unique(cadence.seriesIds, 'cadence series'); + if (cadence.seriesIds.some(id => !policy.observations.some(item => item.seriesId === id))) { + invalid('Paper cadence references an unknown observation series'); + } + cadence.seriesIds.sort(compareText); + } + for (const strategy of strategies) { + const series = policy.observations.find(item => item.seriesId === strategy.seriesId); + if ( + series?.instrumentId !== strategy.instrumentId || + !policy.cadence + .find(item => item.ownerId === strategy.ownerId) + ?.seriesIds.includes(strategy.seriesId) + ) { + invalid('Paper strategy requires its bound instrument/observation series in its cadence'); + } + } + const initial = matching.risk.ledger.riskSession; + for (const calendar of policy.calendars) { + unique( + calendar.sessions.map(item => item.sessionId), + 'venue session' + ); + calendar.sessions.sort((a, b) => a.opensAt - b.opensAt); + let previousClose = initial.startsAt; + for (const session of calendar.sessions) { + if (session.opensAt < previousClose || session.opensAt >= session.closesAt) { + invalid('Paper venue sessions overlap, are invalid, or precede the initial risk clock'); + } + previousClose = session.closesAt; + } + } + unique([initial.sessionId, ...policy.riskBoundaries.map(item => item.sessionId)], 'risk session'); + policy.riskBoundaries.sort((a, b) => a.startsAt - b.startsAt); + let previousRisk = initial.startsAt; + for (const boundary of policy.riskBoundaries) { + if ( + boundary.calendarId !== initial.calendarId || + boundary.calendarRevision !== initial.calendarRevision || + boundary.startsAt <= previousRisk + ) { + invalid('Paper risk boundaries must advance the declared account calendar revision'); + } + previousRisk = boundary.startsAt; + } + matching.owners.sort((a, b) => compareText(a.ownerId, b.ownerId)); + matching.series.sort((a, b) => compareText(a.instrumentId, b.instrumentId)); + matching.risk.ledger.ownerIds.sort(compareText); + strategies.sort((a, b) => compareText(a.ownerId, b.ownerId)); + policy.observations.sort((a, b) => compareText(a.seriesId, b.seriesId)); + policy.cadence.sort((a, b) => compareText(a.ownerId, b.ownerId)); + policy.calendars.sort((a, b) => compareText(a.instrumentId, b.instrumentId)); + return config; +} diff --git a/libs/trading-runtime/src/paper-deployment-custody.ts b/libs/trading-runtime/src/paper-deployment-custody.ts new file mode 100644 index 00000000..97039a83 --- /dev/null +++ b/libs/trading-runtime/src/paper-deployment-custody.ts @@ -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 './retained-package'; + +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 +) { + 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 { + 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, + 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 | 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'); + } + } +} diff --git a/libs/trading-runtime/src/paper-host-identity.ts b/libs/trading-runtime/src/paper-host-identity.ts new file mode 100644 index 00000000..74f751a9 --- /dev/null +++ b/libs/trading-runtime/src/paper-host-identity.ts @@ -0,0 +1,30 @@ +/** Read-only identity; importing this module neither resolves nor loads executable artifacts. */ +import { + paperHostIdentitySchema, + type PaperHostIdentity, +} from '@stock-bot/stock-config/paper-deployments'; +import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy'; +import { bundledHostUrl, readBuildArtifacts, verifyBundledHost } from './artifacts'; + +export const paperHostUrl = () => bundledHostUrl('paper-host'); +export async function readPaperHostIdentity(): Promise { + const { executableSha256, ...common } = await readBuildArtifacts('paper-host'); + return paperHostIdentitySchema.parse({ + version: 'paper-host/v1', + hostSha256: executableSha256, + ...common, + }); +} +export async function verifyPaperHostBuild( + expected: PaperHostIdentity, + actualUrl: string +): Promise { + verifyBundledHost('paper-host', actualUrl); + const actual = await readPaperHostIdentity(); + if ( + canonicalStrategyJson(actual) !== canonicalStrategyJson(paperHostIdentitySchema.parse(expected)) + ) { + throw new Error('Paper host/native/runtime build identity mismatch'); + } + return actual; +} diff --git a/libs/trading-runtime/src/paper-operator.ts b/libs/trading-runtime/src/paper-operator.ts new file mode 100644 index 00000000..4ea511d1 --- /dev/null +++ b/libs/trading-runtime/src/paper-operator.ts @@ -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) ?? []; diff --git a/libs/trading-runtime/src/preparation.ts b/libs/trading-runtime/src/preparation.ts new file mode 100644 index 00000000..c20dae0e --- /dev/null +++ b/libs/trading-runtime/src/preparation.ts @@ -0,0 +1,10 @@ +import { setImmediate } from 'node:timers/promises'; + +export const PREPARATION_BATCH_SIZE = 2048; + +/** Yield to cancellation, timeouts and lease heartbeats between bounded CPU batches. */ +export async function preparationCheckpoint(signal?: AbortSignal): Promise { + signal?.throwIfAborted(); + await setImmediate(); + signal?.throwIfAborted(); +} diff --git a/libs/trading-runtime/src/retained-dataset.ts b/libs/trading-runtime/src/retained-dataset.ts new file mode 100644 index 00000000..82601dfa --- /dev/null +++ b/libs/trading-runtime/src/retained-dataset.ts @@ -0,0 +1,23 @@ +import { validateDatasetV2 } from '@stock-bot/research/datasets'; + +export interface RetainedDatasetStore { + query(text: string, values?: unknown[]): Promise<{ rows: Record[] }>; +} + +/** Content-addressed custody shared by explicit CLI import and web source preparation. */ +export async function retainResearchDataset(database: RetainedDatasetStore, input: unknown) { + const dataset = validateDatasetV2(input); + await database.query( + 'INSERT INTO backtest_datasets(hash,payload) VALUES($1,$2::jsonb) ON CONFLICT(hash) DO NOTHING', + [dataset.manifest.hash, JSON.stringify(dataset)] + ); + const stored = ( + await database.query('SELECT payload FROM backtest_datasets WHERE hash=$1', [ + dataset.manifest.hash, + ]) + ).rows[0]; + if (!stored || validateDatasetV2(stored.payload).manifest.hash !== dataset.manifest.hash) { + throw new Error('Retained dataset content does not match the imported identity'); + } + return dataset.manifest; +} diff --git a/libs/trading-runtime/src/retained-package.ts b/libs/trading-runtime/src/retained-package.ts new file mode 100644 index 00000000..72036bfa --- /dev/null +++ b/libs/trading-runtime/src/retained-package.ts @@ -0,0 +1,19 @@ +import { createHash } from 'node:crypto'; +import { parseStrategyVersionPackage } from '@stock-bot/stock-config/strategy'; +import type { StrategyVersionPackage } from '@stock-bot/types'; + +/** 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; +} diff --git a/libs/trading-runtime/tsconfig.json b/libs/trading-runtime/tsconfig.json new file mode 100644 index 00000000..c8c7167b --- /dev/null +++ b/libs/trading-runtime/tsconfig.json @@ -0,0 +1,23 @@ +{ + "extends": "../../tsconfig.lib.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "dist", + "composite": true + }, + "include": ["src/**/*.ts"], + "references": [ + { + "path": "../core/types" + }, + { + "path": "../../apps/stock/config" + }, + { + "path": "../core/di" + }, + { + "path": "../core/services" + } + ] +} diff --git a/scripts/test/architecture.test.ts b/scripts/test/architecture.test.ts index 3118911c..6616468a 100644 --- a/scripts/test/architecture.test.ts +++ b/scripts/test/architecture.test.ts @@ -91,6 +91,8 @@ describe('orchestrator architecture boundaries', () => { '@stock-bot/stock-config/canonical-research', '@stock-bot/stock-config/candidate-execution', '@stock-bot/stock-config/paper-deployments', + '@stock-bot/stock-config/paper-runtime', + '@stock-bot/stock-config/canonical-execution', '@stock-bot/calculations/analytics', '@stock-bot/calculations/returns', '@stock-bot/research/results', diff --git a/scripts/test/shared-runtime.test.ts b/scripts/test/shared-runtime.test.ts new file mode 100644 index 00000000..876b2eb0 --- /dev/null +++ b/scripts/test/shared-runtime.test.ts @@ -0,0 +1,69 @@ +import { mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { expect, test } from 'bun:test'; +import ts from 'typescript'; +import { runtimeImports } from '../runtime-imports'; + +const root = fileURLToPath(new URL('../../', import.meta.url)); +const api = join(root, 'apps/stock/web-api/src'); +const shared = join(root, 'libs/trading-runtime/src'); + +test('API and shared server modules cannot import another application implementation', () => { + for (const directory of [api, shared]) { + for (const name of new Bun.Glob('**/*.ts').scanSync({ cwd: directory })) { + const source = ts.createSourceFile(name, readFileSync(join(directory, name), 'utf8'), ts.ScriptTarget.Latest, true); + for (const statement of source.statements) { + if ((ts.isImportDeclaration(statement) || ts.isExportDeclaration(statement)) && statement.moduleSpecifier && ts.isStringLiteral(statement.moduleSpecifier)) { + expect(statement.moduleSpecifier.text).not.toMatch(/orchestrator\/src|(?:\.\.\/)+apps\//); + } + } + } + } +}); + +test('read-only custody cannot reach executable strategy loaders or a native addon', () => { + for (const name of ['artifacts', 'canonical-build', 'paper-host-identity', 'candidate-environment', 'paper-deployment-custody', 'retained-package']) { + const path = join(shared, name + '.ts'); + for (const dependency of runtimeImports(path)) { + expect(dependency).not.toMatch(/@stock-bot\/engine|orchestrator|retained-program|native-replay/); + } + expect(readFileSync(path, 'utf8')).not.toMatch(/\b(?:spawn|fork)\s*\(|\bimport\s*\(/); + } +}); + +test('metadata imports work outside an installed checkout; artifact access fails only when requested', async () => { + const directory = mkdtempSync(join(tmpdir(), 'stock-bot-metadata-import-')); + try { + const bundle = await Bun.build({ entrypoints: ['canonical-build', 'paper-host-identity', 'candidate-environment'].map(name => join(shared, name + '.ts')), target: 'bun', outdir: directory, external: ['@stock-bot/engine'] }); + expect(bundle.success).toBe(true); + const child = Bun.spawnSync([process.execPath, '--no-env-file', '-e', ` + const { canonicalWorkerUrl } = await import('./canonical-build.js'); + await import('./paper-host-identity.js'); + await import('./candidate-environment.js'); + let rejected = false; + try { canonicalWorkerUrl(); } catch { rejected = true; } + if (!rejected) process.exit(9); + `], { cwd: directory, env: { PATH: process.env.PATH } }); + expect(new TextDecoder().decode(child.stderr)).toBe(''); + expect(child.exitCode).toBe(0); + } finally { rmSync(directory, { recursive: true, force: true }); } +}); + +test('shared runtime dependencies participate in the actual Turbo build graph', () => { + const child = Bun.spawnSync([process.execPath, 'run', 'build', '--dry=json'], { cwd: root, env: { ...process.env, TURBO_TELEMETRY_DISABLED: '1' } }); + expect(child.exitCode).toBe(0); + const plan = JSON.parse(new TextDecoder().decode(child.stdout)) as { tasks: { taskId: string; dependencies: string[] }[] }; + for (const name of ['web-api', 'orchestrator']) { + expect(plan.tasks.find(task => task.taskId === `@stock-bot/${name}#build`)?.dependencies).toContain('@stock-bot/trading-runtime#build'); + } +}); + +test('shared paper and product contracts bundle without server or native dependencies', async () => { + const bundle = await Bun.build({ entrypoints: [join(root, 'apps/stock/config/src/contracts/paper-runtime.ts'), join(root, 'apps/stock/config/src/contracts/product-responses/index.ts')], target: 'browser' }); + expect(bundle.success).toBe(true); + for (const output of bundle.outputs) { + expect(await output.text()).not.toMatch(/PostgresClient|engine\.node|node:fs|node:child_process/); + } +}); diff --git a/test/integration/candidate-sandbox.test.ts b/test/integration/candidate-sandbox.test.ts index e6d71acd..fd855b76 100644 --- a/test/integration/candidate-sandbox.test.ts +++ b/test/integration/candidate-sandbox.test.ts @@ -370,9 +370,9 @@ suite('actual OS-isolated candidate runtime', () => { // The candidate artifact remains inert JSON in this trusted supervisor fixture. await writeFile( parentPath, - `import {fork} from 'node:child_process';const child=fork(${JSON.stringify(fileURLToPath(canonicalWorkerUrl))},[],{execPath:process.execPath,execArgv:[],serialization:'json',stdio:['ignore','ignore','pipe','ipc']});child.stderr?.resume();child.send(${JSON.stringify(input)});` + `import {fork} from 'node:child_process';const child=fork(${JSON.stringify(fileURLToPath(canonicalWorkerUrl()))},[],{execPath:process.execPath,execArgv:[],serialization:'json',stdio:['ignore','ignore','pipe','ipc']});child.stderr?.resume();child.send(${JSON.stringify(input)});` ); - const child = fork(target === 'worker' ? fileURLToPath(canonicalWorkerUrl) : parentPath, [], { + const child = fork(target === 'worker' ? fileURLToPath(canonicalWorkerUrl()) : parentPath, [], { execPath: process.execPath, execArgv: [], serialization: 'json', @@ -454,14 +454,14 @@ suite('actual OS-isolated candidate runtime', () => { 'not installed' ); await absent(f.name); - const hidden = candidateDescriptorPath + '.missing-test-' + randomUUID(); - await rename(candidateDescriptorPath, hidden); + const hidden = candidateDescriptorPath() + '.missing-test-' + randomUUID(); + await rename(candidateDescriptorPath(), hidden); try { await expect(IsolatedCandidateController.start(f.request, f.name)).rejects.toThrow( 'unavailable' ); } finally { - await rename(hidden, candidateDescriptorPath); + await rename(hidden, candidateDescriptorPath()); } await absent(f.name); if (f.request.strategy.origin !== 'candidate') { diff --git a/test/integration/retained-strategy-worker.test.ts b/test/integration/retained-strategy-worker.test.ts index 89763e90..b0e4d4c5 100644 --- a/test/integration/retained-strategy-worker.test.ts +++ b/test/integration/retained-strategy-worker.test.ts @@ -373,7 +373,7 @@ describe('retained canonical strategy worker', () => { ) ).rejects.toThrow('canonical bundled worker'); expect( - await new NativeBacktestWorker(canonicalWorkerUrl).execute( + await new NativeBacktestWorker(canonicalWorkerUrl()).execute( value, new AbortController().signal, () => {}