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