/** Pure decision staging shared by trusted and OS-isolated strategy hosts. * This module never imports a native engine, dataset loader or service container. */ import type { FinancialStrategyDecision } from '@stock-bot/types'; import type { DeepReadonly, StrategyDiagnostic, StrategyDiagnosticSnapshot, StrategyProgram, } from '@stock-bot/research/strategy-api'; import { nativeAdmissionOrders, type DecisionContext, type PublishedObservation, type ReplayIdentity, type ReplaySubmissionOutcome, } from '@stock-bot/stock-config/canonical-replay'; import { freeze, increment, initialStrategyDiagnostic, metadataSchema, ownerAdmissionFeedback, stageStrategyDecision, type Metadata, } from '../strategies/strategy-decision'; interface Slot { program: Metadata & { decide: StrategyProgram['decide'] }; diagnostic: DeepReadonly; pendingObservations: PublishedObservation[]; } /** * Coordinates a two-step callback transition: stage all due owners against the * same financial view, then confirm their state after native batch admission. * This owns strategy state and RNG diagnostics, never cash or order matching. * A failed attempt discards the controller; snapshots are not restart tokens. */ export class StrategyController { private slots: Map; private committedBarriers = 0; private lastBarrierId: string | null = null; private observed = 0; private staged: { barrierId: string; expectedRevision: number; owners: { ownerId: string; diagnostic: StrategyDiagnostic; decision: FinancialStrategyDecision; }[]; } | null = null; /** Bind each configured owner exactly once and detach its initial JSON state. */ constructor( private readonly identity: ReplayIdentity, programs: readonly StrategyProgram[], config: { matching: { owners: { ownerId: string; mode: 'Target' | 'Orders' }[] } } ) { this.slots = new Map( programs.map(program => { const { ownerId, strategyId, strategyVersion, mode, seed } = program; const metadata = metadataSchema.parse({ ownerId, strategyId, strategyVersion, mode, seed }); const decide = program.decide; if (typeof decide !== 'function') { throw new Error('Strategy decide must be synchronous callable code'); } const diagnostic = freeze(initialStrategyDiagnostic(metadata, program.initialState)); return [ownerId, { program: { ...metadata, decide }, diagnostic, pendingObservations: [] }]; }) ); const owners = config.matching.owners; if ( this.slots.size !== programs.length || this.slots.size !== owners.length || owners.some(owner => this.slots.get(owner.ownerId)?.program.mode !== owner.mode.toLowerCase()) ) { throw new Error('Programs must exactly match configured owners and modes'); } } /** Expose confirmed transitions in stable owner order, excluding staged work. */ snapshot(): DeepReadonly { return freeze({ version: 1, identity: this.identity, committedBarriers: this.committedBarriers, lastBarrierId: this.lastBarrierId, strategies: [...this.slots.values()] .sort((a, b) => a.program.ownerId < b.program.ownerId ? -1 : a.program.ownerId > b.program.ownerId ? 1 : 0 ) .map(slot => slot.diagnostic), }); } /** * Buffer the replay driver's newly published observations for every owner, * then evaluate only owners due at this barrier. Return one complete batch * for native submission; callback state and RNG changes remain proposals. * Any error aborts the attempt rather than retrying this mutated controller. */ stage(context: DecisionContext, observations: readonly PublishedObservation[]) { if (this.staged) { throw new Error('Previous strategy barrier has not committed'); } // The cumulative count detects dropped/repeated input at the host boundary; // available_at prevents exposing observations ahead of this engine barrier. this.observed = increment(this.observed, observations.length); const due = new Set(context.barrier.owner_ids); if ( this.observed !== context.barrier.observation_count || due.size !== context.barrier.owner_ids.length || [...due].some(owner => !this.slots.has(owner)) || observations.some(observation => observation.available_at > context.barrier.at) ) { throw new Error('Strategy barrier observation or owner mismatch'); } const staged: NonNullable = { barrierId: context.barrier.barrier_id, expectedRevision: increment(context.barrier.revision), owners: [], }; for (const slot of this.slots.values()) { // Other owners may have slower cadence. Do not discard their warmup/prefix. for (const observation of observations) { slot.pendingObservations.push(observation); } if (!due.has(slot.program.ownerId)) { continue; } staged.owners.push( stageStrategyDecision( this.identity.sessionId, slot.program, slot.diagnostic, slot.pendingObservations, context ) ); } this.staged = staged; return staged.owners.map(owner => owner.decision); } /** * Confirm the staged callback transitions only for the expected native revision. * Order rejection is valid feedback; acknowledgement does not imply a fill. * An unexpected or replayed acknowledgement leaves confirmed state unchanged. */ committed(outcome: ReplaySubmissionOutcome): void { const staged = this.staged; if ( !staged || outcome.replayed || outcome.status !== 'Running' || outcome.revision !== staged.expectedRevision ) { throw new Error('Unexpected strategy admission acknowledgement'); } const orders = nativeAdmissionOrders(outcome.effects); if ( orders.some( order => !staged.owners.some(owner => owner.ownerId === order.order.decision.ownerId) ) ) { throw new Error('Admission feedback belongs to an owner outside the barrier'); } const nextCount = increment(this.committedBarriers); const next = new Map(this.slots); // Parse/detach ALL feedback before swapping any committed slot. Even an // ambiguous/malformed acknowledgement leaves diagnostics at the old barrier. for (const owner of staged.owners) { const slot = this.slots.get(owner.ownerId); if (!slot) { throw new Error('Staged strategy owner is missing'); } const previousAdmission = ownerAdmissionFeedback( owner.decision.decision, outcome.revision, orders ); next.set(owner.ownerId, { program: slot.program, diagnostic: freeze({ ...owner.diagnostic, previousAdmission }), pendingObservations: [], }); } this.slots = next; this.committedBarriers = nextCount; this.lastBarrierId = staged.barrierId; this.staged = null; } }