import type { RuntimeEventProposal } from '../../../framework/plugins/index.js'; import type { StoredStateFrame } from '../../../framework/state/history/contracts.js'; import { getWorkspaceDir } from '../../../../lib/init-command.js'; import type { ClawclawPerceptionManifest, PerceptionFrame } from './contracts.js'; import { ClawclawPerceptionPlugin, type ClawclawPerceptionConfig, } from './perception-plugin.js'; export interface PerceptionReplayFrame { frameSeq: number; backendTick: number | null; receivedAtMs: number; perceptionFrame: PerceptionFrame | null; proposals: readonly RuntimeEventProposal[]; moduleStates: Record; } export interface PerceptionReplayResult { modules: Array; frames: PerceptionReplayFrame[]; proposals: Array; } export interface PerceptionReplayOptions extends ClawclawPerceptionConfig { fromTick?: number; toTick?: number; frameSeq?: number; } function selected( frame: StoredStateFrame>, options: PerceptionReplayOptions, ): boolean { if (options.frameSeq !== undefined) return frame.frameSeq === options.frameSeq; const tick = frame.backendTick ?? (typeof frame.state.tick === 'number' ? frame.state.tick : undefined); if (tick === undefined) return false; return (options.fromTick === undefined || tick >= options.fromTick) && (options.toTick === undefined || tick <= options.toTick); } /** Replays from the beginning so every module's private state at selected frames is exact. */ export async function replayPerceptionFrames( inputFrames: readonly StoredStateFrame>[], options: PerceptionReplayOptions = {}, ): Promise { const workspaceDir = options.workspaceDir ?? getWorkspaceDir(); const plugin = new ClawclawPerceptionPlugin({ modules: options.modules, workspaceDir, }); const frames: PerceptionReplayFrame[] = []; const emitted: PerceptionReplayResult['proposals'] = []; const ordered = [...inputFrames].sort((a, b) => a.frameSeq - b.frameSeq); const signal = new AbortController().signal; try { await plugin.startForReplay(signal); for (const frame of ordered) { const inspection = await plugin.inspectFrame(frame, signal); const perceptionFrame = inspection.visual; const frameProposals = inspection.proposals; const emittedAtTick = perceptionFrame?.tick ?? frame.backendTick ?? null; for (const proposal of frameProposals) { emitted.push({ ...proposal, emittedAtFrameSeq: frame.frameSeq, emittedAtTick, }); } if (!selected(frame, options)) continue; frames.push({ frameSeq: frame.frameSeq, backendTick: frame.backendTick ?? null, receivedAtMs: frame.receivedAtMs, perceptionFrame, proposals: frameProposals, moduleStates: inspection.moduleStates, }); } } finally { await plugin.stopForReplay(); } return { modules: plugin.moduleDescriptors(), frames, proposals: emitted, }; }