import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs'; import { dirname, isAbsolute, join, resolve } from 'path'; import { spawnSync } from 'child_process'; import { AuthStore } from '../src/lib/auth.js'; import { getProfileEventLedgerPath, getProfileStateHistoryPath, getRuntimeAccountId, } from '../src/lib/init-command.js'; import { CLAWCLAW_VISUAL_EVENT_TYPES } from '../src/runtime/clawclaw-event-catalog.js'; import { DEFAULT_PERCEPTION_MODULES, listClawclawPerceptionSources, replayPerceptionFrames, } from '../src/runtime/clawclaw/plugins/perception/index.js'; import { SqliteEventRepository } from '../src/runtime/framework/events/index.js'; import { SqliteStateHistoryRepository, type RuntimeScope, type StoredStateFrame, } from '../src/runtime/framework/state/index.js'; interface Options { tick?: number; fromTick?: number; toTick?: number; frameSeq?: number; modules?: string[]; output?: string; manifest?: string; renderOffsetMs?: number; extractFrames: boolean; frameDir?: string; ffmpeg?: string; stateHistory?: string; eventLedger?: string; accountId?: string; sessionId?: string; segmentId?: string; segmentSeq?: number; } interface RecorderManifest { pageCreatedAtEpochMs?: number; outputVideo?: string; diagnostics?: Array<{ type?: string; text?: string }>; } function usage(exitCode = 2): never { process.stderr.write(`Usage: npm run replay:perception -- --tick 580 [--output tmp/perception-580.json] npm run replay:perception -- --from-tick 560 --to-tick 580 --modules visual.motion,visual.follow npm run replay:perception -- --tick 580 --manifest --extract-frames Options: --tick Capture every stored revision at one backend tick. --from-tick/--to-tick Capture a tick range. --frame-seq Capture one exact persisted frame instead of tick range. --modules Comma-separated loaded perception modules. --manifest 15Hz spectator recorder manifest for video alignment. --render-offset-ms Override inferred frontend render delay. --extract-frames Extract aligned PNG frames with FFmpeg. --frame-dir PNG output directory; defaults beside JSON output. --ffmpeg FFmpeg executable; otherwise FFMPEG_PATH or PATH. --output Write JSON report; otherwise print to stdout. --state-history Inspect an explicit State History SQLite database. --event-ledger Optional matching canonical Event Ledger. --account-id Scope for an explicit State History database. --session-id Scope for an explicit State History database. --segment-id Scope for an explicit State History database. --segment-seq Optional segment ordinal for an explicit scope. `); process.exit(exitCode); } function integer(value: string | undefined, name: string): number | undefined { if (value === undefined) return undefined; const parsed = Number(value); if (!Number.isInteger(parsed) || parsed < 0) throw new Error(`${name} must be a non-negative integer.`); return parsed; } function numberValue(value: string | undefined, name: string): number | undefined { if (value === undefined) return undefined; const parsed = Number(value); if (!Number.isFinite(parsed) || parsed < 0) throw new Error(`${name} must be a non-negative number.`); return parsed; } function parseOptions(argv: string[]): Options { const values = new Map(); const flags = new Set(); for (let index = 0; index < argv.length; index += 1) { const arg = argv[index]; if (arg === '--help' || arg === '-h') usage(0); if (arg === '--extract-frames') { flags.add(arg); continue; } if (!arg.startsWith('--') || index + 1 >= argv.length) usage(); values.set(arg, argv[index + 1]); index += 1; } const known = new Set([ '--tick', '--from-tick', '--to-tick', '--frame-seq', '--modules', '--output', '--manifest', '--render-offset-ms', '--frame-dir', '--ffmpeg', '--state-history', '--event-ledger', '--account-id', '--session-id', '--segment-id', '--segment-seq', ]); for (const key of values.keys()) if (!known.has(key)) throw new Error(`Unknown option: ${key}`); const tick = integer(values.get('--tick'), '--tick'); const frameSeq = integer(values.get('--frame-seq'), '--frame-seq'); const fromTick = integer(values.get('--from-tick'), '--from-tick') ?? tick; const toTick = integer(values.get('--to-tick'), '--to-tick') ?? tick; if (frameSeq === undefined && fromTick === undefined && toTick === undefined) usage(); if (frameSeq !== undefined && (fromTick !== undefined || toTick !== undefined)) { throw new Error('--frame-seq cannot be combined with tick selectors.'); } if (fromTick !== undefined && toTick !== undefined && fromTick > toTick) { throw new Error('--from-tick cannot be greater than --to-tick.'); } const moduleValue = values.get('--modules'); const modules = moduleValue ? moduleValue.split(',').map((value) => value.trim()).filter(Boolean) : undefined; if (modules) { const allowed = new Set([ ...DEFAULT_PERCEPTION_MODULES, ...listClawclawPerceptionSources().map((source) => source.id), ]); for (const moduleId of modules) if (!allowed.has(moduleId)) throw new Error(`Unknown module: ${moduleId}`); } return { tick, fromTick, toTick, frameSeq, modules, output: values.get('--output') ? resolve(values.get('--output')!) : undefined, manifest: values.get('--manifest') ? resolve(values.get('--manifest')!) : undefined, renderOffsetMs: numberValue(values.get('--render-offset-ms'), '--render-offset-ms'), extractFrames: flags.has('--extract-frames'), frameDir: values.get('--frame-dir') ? resolve(values.get('--frame-dir')!) : undefined, ffmpeg: values.get('--ffmpeg'), stateHistory: values.get('--state-history') ? resolve(values.get('--state-history')!) : undefined, eventLedger: values.get('--event-ledger') ? resolve(values.get('--event-ledger')!) : undefined, accountId: values.get('--account-id'), sessionId: values.get('--session-id'), segmentId: values.get('--segment-id'), segmentSeq: integer(values.get('--segment-seq'), '--segment-seq'), }; } function readAllFrames( repository: SqliteStateHistoryRepository>, scope: RuntimeScope, ): StoredStateFrame>[] { const frames: StoredStateFrame>[] = []; let afterFrameSeq = 0; while (true) { const page = repository.queryStateFrames({ scope, afterFrameSeq, order: 'asc', limit: 1_000 }); frames.push(...page.frames); if (!page.page.hasMore || page.page.lastFrameSeq === null) break; afterFrameSeq = page.page.lastFrameSeq; } return frames; } function inferRenderOffsetMs(manifest: RecorderManifest, explicit?: number): number { if (explicit !== undefined) return explicit; const values: number[] = []; for (const diagnostic of manifest.diagnostics ?? []) { if (diagnostic.type !== 'console.warning' || typeof diagnostic.text !== 'string') continue; const match = diagnostic.text.match(/\[ObserverTimeline\]\[Diagnostic\]\s*(\{.*\})$/); if (!match) continue; try { const value = JSON.parse(match[1]) as { renderDelayMs?: number }; if (Number.isFinite(value.renderDelayMs)) values.push(value.renderDelayMs!); } catch {} } if (values.length === 0) return 300; values.sort((a, b) => a - b); const middle = Math.floor(values.length / 2); return Math.round(values.length % 2 ? values[middle] : (values[middle - 1] + values[middle]) / 2); } function eventOverlaps(payload: Record, fromTick?: number, toTick?: number): boolean { if (fromTick === undefined && toTick === undefined) return true; const from = typeof payload.from_tick === 'number' ? payload.from_tick : null; const to = typeof payload.to_tick === 'number' ? payload.to_tick : from; if (from === null || to === null) return false; return (toTick === undefined || from <= toTick) && (fromTick === undefined || to >= fromTick); } function extractFrame(ffmpeg: string, video: string, seconds: number, output: string): void { const result = spawnSync(ffmpeg, [ '-hide_banner', '-loglevel', 'error', '-y', '-ss', seconds.toFixed(3), '-i', video, '-frames:v', '1', output, ], { encoding: 'utf8' }); if (result.error) throw result.error; if (result.status !== 0) throw new Error(result.stderr || `FFmpeg exited with ${result.status}.`); } async function main(): Promise { const options = parseOptions(process.argv.slice(2)); const explicitScope = options.accountId && options.sessionId && options.segmentId ? { adapterId: 'clawclaw', accountId: options.accountId, sessionId: options.sessionId, segmentId: options.segmentId, ...(options.segmentSeq === undefined ? {} : { segmentSeq: options.segmentSeq }), } satisfies RuntimeScope : null; if ( options.stateHistory && !explicitScope ) { throw new Error('Explicit --state-history requires --account-id, --session-id, and --segment-id.'); } const profile = new AuthStore().getActive(); if (!profile && !options.stateHistory) throw new Error('No active CCL profile.'); const historyPath = options.stateHistory ?? getProfileStateHistoryPath(profile!); const eventPath = options.eventLedger ?? (options.stateHistory ? null : getProfileEventLedgerPath(profile!)); if (!existsSync(historyPath)) throw new Error('State History database is unavailable.'); const opened = eventPath && existsSync(eventPath) ? SqliteEventRepository.open(eventPath) : null; if (opened && !opened.ok) throw new Error(opened.unavailable.message); const history = new SqliteStateHistoryRepository>(historyPath); try { const current = opened?.ok && profile ? opened.repository.latestScope( { adapterId: 'clawclaw', accountId: getRuntimeAccountId(profile) }, { segmentKinds: ['game'] }, ) : null; const scope: RuntimeScope = explicitScope ?? (current ? { adapterId: current.session.adapterId, accountId: current.session.accountId, sessionId: current.session.sessionId, segmentId: current.segment.segmentId, segmentSeq: current.segment.sequence, } : (() => { throw new Error('No game segment exists in the canonical Event Ledger.'); })()); const inputFrames = readAllFrames(history, scope); const replay = await replayPerceptionFrames(inputFrames, { modules: options.modules, fromTick: options.fromTick, toTick: options.toTick, frameSeq: options.frameSeq, }); if (replay.frames.length === 0) throw new Error('No persisted State frame matches the requested tick/frame.'); const selectedTicks = replay.frames.map((frame) => frame.perceptionFrame?.tick ?? frame.backendTick).filter( (tick): tick is number => tick !== null, ); const rangeFrom = options.fromTick ?? (selectedTicks.length ? Math.min(...selectedTicks) : undefined); const rangeTo = options.toTick ?? (selectedTicks.length ? Math.max(...selectedTicks) : undefined); const canonicalEvents = opened?.ok ? opened.repository.listCommittedEvents({ sessionId: scope.sessionId, segmentId: scope.segmentId, types: [...new Set([ ...CLAWCLAW_VISUAL_EVENT_TYPES, ...replay.modules.flatMap((module) => [...module.produces]), ])], order: 'asc', }).filter((event) => eventOverlaps(event.payload, rangeFrom, rangeTo)) : []; let video: Record | null = null; if (options.manifest) { const manifest = JSON.parse(readFileSync(options.manifest, 'utf8')) as RecorderManifest; if (!Number.isFinite(manifest.pageCreatedAtEpochMs) || !manifest.outputVideo) { throw new Error('Recorder manifest lacks pageCreatedAtEpochMs or outputVideo.'); } const offset = inferRenderOffsetMs(manifest, options.renderOffsetMs); const videoPath = isAbsolute(manifest.outputVideo) ? manifest.outputVideo : resolve(dirname(options.manifest), manifest.outputVideo); const alignments = replay.frames.map((frame) => ({ frame_seq: frame.frameSeq, tick: frame.perceptionFrame?.tick ?? frame.backendTick, received_at_ms: frame.receivedAtMs, video_time_seconds: Math.round(((frame.receivedAtMs + offset - manifest.pageCreatedAtEpochMs!) / 1_000) * 1_000) / 1_000, })); const frameDir = options.frameDir ?? resolve(dirname(options.output ?? options.manifest), 'perception-frames'); if (options.extractFrames) { mkdirSync(frameDir, { recursive: true }); const ffmpeg = options.ffmpeg ?? process.env.FFMPEG_PATH ?? 'ffmpeg'; for (const alignment of alignments) { if (alignment.video_time_seconds < 0) throw new Error(`Tick ${alignment.tick} maps before the recording.`); const output = join(frameDir, `tick-${alignment.tick}-frame-${alignment.frame_seq}.png`); extractFrame(ffmpeg, videoPath, alignment.video_time_seconds, output); Object.assign(alignment, { image: output }); } } video = { manifest: options.manifest, video: videoPath, render_offset_ms: offset, alignments, }; } else if (options.extractFrames) { throw new Error('--extract-frames requires --manifest.'); } const report = { schema: 'ccl.perception.replay.v2', generated_at: new Date().toISOString(), scope: { adapter_id: scope.adapterId, session_id: scope.sessionId, segment_id: scope.segmentId, segment_seq: scope.segmentSeq, }, selection: { from_tick: options.fromTick ?? null, to_tick: options.toTick ?? null, frame_seq: options.frameSeq ?? null, }, modules: replay.modules, frames: replay.frames, generated_proposals_covering_selection: replay.proposals.filter((proposal) => ( eventOverlaps(proposal.payload ?? {}, rangeFrom, rangeTo) )), canonical_visual_events_covering_selection: canonicalEvents, video, }; const text = `${JSON.stringify(report, null, 2)}\n`; if (options.output) { mkdirSync(dirname(options.output), { recursive: true }); writeFileSync(options.output, text, 'utf8'); process.stdout.write(`[perception-replay] report: ${options.output}\n`); } else { process.stdout.write(text); } } finally { history.close(); if (opened?.ok) opened.repository.close(); } } try { await main(); } catch (error) { process.stderr.write(`[perception-replay] ${error instanceof Error ? error.message : String(error)}\n`); process.exitCode = 1; }