import type { BehaviorContinuation, BehaviorDecisionFrame, BehaviorInput, GameEvent, GameState, } from '../../sdk/module-input/index.js'; import type { RuntimeEpochPluginInput } from '../framework/plugins/contracts.js'; import { isClawclawRuntimeState } from './runtime-state.js'; import { projectTaskChoiceGameState, projectTaskChoiceEventPayload } from './task-choice-projection.js'; function deepFreeze(value: T): T { if (!value || typeof value !== 'object' || Object.isFrozen(value)) return value; Object.freeze(value); for (const child of Object.values(value as Record)) deepFreeze(child); return value; } function behaviorEvents( input: RuntimeEpochPluginInput>, gameState: GameState, ): readonly Readonly[] { return input.pendingEvents.filter(event => !event.notificationOf && !event.producerPluginId?.startsWith('clawclaw.perception.system.')).map((event) => ({ eventId: event.eventId, ...(event.epochSeq === undefined ? {} : { epochId: event.epochSeq }), type: event.type, occurredAt: event.occurredAt, payload: projectTaskChoiceEventPayload(gameState, event.type, event.payload), })); } /** Clone one Runtime GameSync snapshot into the single public GameState shape. */ export function createCanonicalGameState( source: Readonly>, domainTick?: unknown, ): GameState { const gameState = projectTaskChoiceGameState(source) as unknown as GameState; if (typeof domainTick === 'number' && Number.isFinite(domainTick)) { (gameState as { tick?: number }).tick = domainTick; } return gameState; } /** * Build the player-module input from the latest authoritative observation. * Lifecycle plugins decide when a Behavior is eligible to run; modules never * receive Runtime State or a nullable Game State. A cycle reports the actual * age/version when this observation is cached rather than newly received. */ export function createBehaviorInput< TInput extends Readonly>, >( input: RuntimeEpochPluginInput>, behaviorInput: TInput, continuation?: Readonly, decisionHistory: readonly Readonly[] = [], ): BehaviorInput | null { const runtimeState = input.epoch.state; if (!isClawclawRuntimeState(runtimeState) || (runtimeState.game_snapshot.status !== 'fresh' && runtimeState.game_snapshot.status !== 'cached')) { return null; } const gameState = createCanonicalGameState( runtimeState.game_snapshot.state, input.epoch.domainTick, ); return deepFreeze({ epochId: input.epoch.epochSeq, scope: { sessionId: input.epoch.scope.sessionId, segmentId: input.epoch.scope.segmentId, }, nowMs: input.frame.observedAtMs ?? input.frame.receivedAtMs, ...(runtimeState.cycle ? { cycle: structuredClone(runtimeState.cycle) } : {}), gameState, events: behaviorEvents(input, gameState), input: structuredClone(behaviorInput), // The Owner ring exposes one recursively immutable snapshot. Serial modules // can share it directly; Worker postMessage performs the one required clone. decisionHistory, ...(continuation === undefined ? {} : { continuation: structuredClone(continuation) }), }); }