import type { BehaviorDecisionAction, BehaviorDecisionFrame, BehaviorDecisionFrameStatus, } from '../../../../sdk/module-input/index.js'; export const BEHAVIOR_DECISION_HISTORY_LIMIT = 100; interface DecisionFrameStart { readonly epochId: number; readonly tick: number; readonly instanceGeneration: number; } function cloneActions( actions: readonly Readonly[] | undefined, ): readonly Readonly[] { return Object.freeze((actions ?? []).map((action) => Object.freeze(structuredClone(action)))); } /** One Owner-owned, activation-local ring shared by concurrent Decision computations. */ export class BehaviorDecisionHistory { private readonly frames: BehaviorDecisionFrame[] = []; private cachedSnapshot?: readonly Readonly[]; begin(start: DecisionFrameStart): Readonly { const existing = this.frames.find((frame) => frame.epochId === start.epochId); if (existing) return existing; const frame = Object.freeze({ ...start, status: 'pending' as const, actions: null, }); this.frames.push(frame); if (this.frames.length > BEHAVIOR_DECISION_HISTORY_LIMIT) { this.frames.splice(0, this.frames.length - BEHAVIOR_DECISION_HISTORY_LIMIT); } this.cachedSnapshot = undefined; return frame; } complete( epochId: number, actions: readonly Readonly[] | undefined, ): Readonly | undefined { return this.resolve(epochId, 'completed', cloneActions(actions)); } notComputed(epochId: number, reason: string): Readonly | undefined { return this.resolve(epochId, 'not_computed', null, reason); } fail(epochId: number, reason: string): Readonly | undefined { return this.resolve(epochId, 'failed', null, reason); } snapshot(): readonly Readonly[] { this.cachedSnapshot ??= Object.freeze([...this.frames]); return this.cachedSnapshot; } clear(): void { this.frames.length = 0; this.cachedSnapshot = undefined; } private resolve( epochId: number, status: Exclude, actions: readonly Readonly[] | null, reason?: string, ): Readonly | undefined { const index = this.frames.findIndex((frame) => frame.epochId === epochId); if (index < 0) return undefined; const previous = this.frames[index]!; const next = Object.freeze({ epochId: previous.epochId, tick: previous.tick, instanceGeneration: previous.instanceGeneration, status, actions, ...(reason ? { reason } : {}), }); this.frames[index] = next; this.cachedSnapshot = undefined; return next; } }