import { prepareNotificationContent } from './notification-content.js'; import { preparePerceptionNotification } from './report-content.js'; import { isNotificationTurn } from '../../notification-turn.js'; import type { RuntimeEpochFlushReason, RuntimeEpochPlugin, RuntimeEpochPluginContext, RuntimeEpochPluginInput, RuntimeEpochPluginResult, RuntimeDiagnosticSeverity, RuntimeEventProposal, } from '../../../framework/plugins/index.js'; import { performance } from 'node:perf_hooks'; import type { StoredStateFrame } from '../../../framework/state/history/contracts.js'; import { isClawclawRuntimeState } from '../../runtime-state.js'; import { PERCEPTION_PLUGIN_API_VERSION, ClawclawPerception, hasValidClawclawResourceLocalizations, resolveClawclawResourceMetadata, type ClawclawResolvedResourceMetadata, type ClawclawPerceptionClass, type ClawclawPerceptionManifest, type PerceptionApi, type PerceptionAnalysisInput, type PerceptionBoundary, type PerceptionBoundaryKind, type PerceptionEventProposal, type PerceptionFrame, type PerceptionSpatialFacts, } from './contracts.js'; import { DEFAULT_PERCEPTION_MODULES } from './official-module-ids.js'; import { ImportedLocalPerceptionModuleRunner, type PerceptionModuleRunner, } from './module-runner.js'; import { listClawclawPerceptionSources, type ResolvedClawclawPerceptionSource, } from './perception-source.js'; import { PerceptionAnalysisThreadPool, perceptionAnalysisWorkerStartModuleId, type PerceptionAnalysisJob, } from './perception-analysis-thread-pool.js'; import { PerceptionModuleLoader, type PerceptionThreadModuleSpec, } from './perception-module-loader.js'; import { PerceptionReducerThreadPool } from './perception-reducer-thread-pool.js'; import { CLAWCLAW_PERCEPTION_SPATIAL_API, CLAWCLAW_PERCEPTION_SPATIAL_FACTS, } from './spatial-facts.js'; import { ObservationFrameProjector } from '../../observation-frame-projector.js'; export { DEFAULT_PERCEPTION_MODULES } from './official-module-ids.js'; export const CLAWCLAW_PERCEPTION_PLUGIN_ID = 'clawclaw.perception'; export const DEFAULT_MAX_PERCEPTION_BACKFILL_VISUAL_FRAMES = 10; export const DEFAULT_PERCEPTION_RECOVERY_TIMEOUT_MS = 30_000; const PERCEPTION_MODULE_TIMING_WINDOW_MS = 10_000; const PERCEPTION_ANALYSIS_WINDOW_FRAMES = 10; export interface ClawclawPerceptionConfig { modules?: readonly string[]; /** Explicit source workspace for tooling and isolated replay. */ workspaceDir?: string; /** Runtime-resolved sources, used when an account snapshot adds immutable Hub modules. */ moduleSources?: readonly ResolvedClawclawPerceptionSource[]; /** Maximum visual frames replayed into modules during one live Runtime invocation. */ maxBackfillVisualFrames?: number; /** Samples Worker heaps only for explicit full diagnostics. */ diagnosticsEnabled?: boolean; } export interface PerceptionModuleDescriptor extends ClawclawPerceptionManifest { /** Every module is hosted by the same Runtime plugin. */ readonly pluginId: typeof CLAWCLAW_PERCEPTION_PLUGIN_ID; } export interface LocalizedPerceptionEventDescriptor { readonly type: string; readonly perceptionId: string; readonly name: string; readonly description: string; } export interface PerceptionFrameInspection { visual: PerceptionFrame | null; proposals: readonly RuntimeEventProposal[]; moduleStates: Record; reason?: string; } interface PerceptionModuleSlot { readonly manifest: ClawclawPerceptionManifest; readonly runner: PerceptionModuleRunner; readonly source: ResolvedClawclawPerceptionSource; /** Invalidates analyses that were computed before an ordered reducer barrier. */ analysisGeneration: number; /** Oldest raw visual frame that a new generation may use as trajectory history. */ analysisHistoryFloorFrameSeq: number; /** The first successful reducer application after failure establishes state only. */ analysisBaselinePending: boolean; /** Undefined follows global replay; null means reset with no successful reducer commit yet. */ reducerReplayFromFrameSeq: number | null | undefined; } interface PerceptionParallelStartupCandidate { readonly module: PerceptionModuleSlot; readonly threadModule: PerceptionThreadModuleSpec; } function elapsedMs(startedAt: number): number { return Math.round(Math.max(0, performance.now() - startedAt) * 1_000) / 1_000; } interface PerceptionModuleTimingWindow { readonly moduleId: string; readonly operation: string; readonly durationsMs: number[]; eventCount: number; failureCount: number; } function percentile95(values: readonly number[]): number { if (values.length === 0) return 0; const sorted = [...values].sort((left, right) => left - right); return sorted[Math.max(0, Math.ceil(sorted.length * 0.95) - 1)]!; } function roundedAverage(values: readonly number[]): number { if (values.length === 0) return 0; return Math.round((values.reduce((sum, value) => sum + value, 0) / values.length) * 1_000) / 1_000; } interface PreparedPerceptionFrame { readonly stored: StoredStateFrame>; readonly visual: PerceptionFrame | null; readonly analyses: readonly PerceptionModuleAnalysis[]; readonly analysisTiming: PerceptionAnalysisTiming; } interface PerceptionAnalysisTiming { readonly workerQueueMs: number; readonly workerRoundtripMs: number; readonly moduleCpuSumMs: number; readonly moduleCpuMaxMs: number; readonly workerCount: number; } interface PerceptionFrameComputationTiming extends PerceptionAnalysisTiming { readonly projectionMs: number; readonly historyPrepareMs: number; readonly updateTotalMs: number; } interface PerceptionFrameTimingWindow { readonly startedAtMs: number; readonly projectionMs: number[]; readonly historyPrepareMs: number[]; readonly workerQueueMs: number[]; readonly workerRoundtripMs: number[]; readonly moduleCpuSumMs: number[]; readonly moduleCpuMaxMs: number[]; readonly updateTotalMs: number[]; readonly commitMs: number[]; readonly totalMs: number[]; workerCountMax: number; } interface PerceptionFrameTimingSample extends PerceptionFrameComputationTiming { readonly commitMs: number; readonly totalMs: number; } interface CachedProjectedFrame { readonly stored: Pick>, 'frameSeq' | 'connectionId'>; readonly visual: PerceptionFrame; } interface PerceptionModuleAnalysis { readonly moduleId: string; readonly generation: number; readonly outcome: 'fulfilled' | 'rejected'; readonly durationMs: number; readonly analysis?: unknown; readonly failure?: Readonly<{ errorCode: string; messagePresent: boolean; messageLength?: number; }>; } interface PerceptionComputationProposal { readonly schema: 'clawclaw.perception-computation.v1'; readonly visual: PerceptionFrame | null; readonly analyses: readonly PerceptionModuleAnalysis[]; readonly timing?: PerceptionFrameComputationTiming; } interface PerceptionCheckpoint { readonly schema: 'clawclaw.perception-checkpoint.v1'; /** First frame in the current in-process slice; process restart deliberately does not replay it. */ readonly replayFromFrameSeq: number | null; /** Per parallel module, the first frame allowed after its latest private failure boundary. */ readonly parallelModuleHistoryFloors?: Readonly>; /** Actual first reducer commit after a private boundary; null means the reducer is still empty. */ readonly parallelModuleReducerReplayStarts?: Readonly>; /** Whether the next successful reducer commit establishes state without emitting Events. */ readonly parallelModuleBaselinePending?: Readonly>; } type PerceptionDiagnostic = ( name: string, attributes?: Readonly>, severity?: RuntimeDiagnosticSeverity, ) => void; const PERCEPTION_CHECKPOINT_SCHEMA = 'clawclaw.perception-checkpoint.v1' as const; const PERCEPTION_COMPUTATION_SCHEMA = 'clawclaw.perception-computation.v1' as const; const PERCEPTION_FAILURE_REPORT_WINDOW_MS = 30_000; function nonEmpty(value: unknown): value is string { return typeof value === 'string' && value.trim().length > 0; } /** Runtime-only lifecycle key. Module authors inspect the canonical Game State directly. */ function perceptionLifecycle(frame: Readonly): string { const phase = frame.gameState.phase ?? 'unknown'; return phase === 'wandering' && frame.gameState.you?.is_alive === false ? 'dead' : phase; } function hasValidPerceptionEventMetadata(manifest: ClawclawPerceptionManifest): boolean { if (manifest.wakeAgent !== undefined && typeof manifest.wakeAgent !== 'boolean') return false; const metadata = manifest.eventMetadata; if (metadata === undefined) return true; if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) return false; const entries = Object.entries(metadata); return ( entries.length === manifest.produces.length && entries.every(([type, value]) => ( manifest.produces.includes(type) && !!value && typeof value === 'object' && !Array.isArray(value) && nonEmpty(value.name) && nonEmpty(value.description) && hasValidClawclawResourceLocalizations(value.localizations) )) ); } function moduleClass(instance: ClawclawPerception): ClawclawPerceptionClass { return instance.constructor as ClawclawPerceptionClass; } function perceptionFailureDetails(reason: unknown): Readonly<{ errorCode: string; messagePresent: boolean; messageLength?: number; }> { const code = reason && typeof reason === 'object' && typeof (reason as any).code === 'string' ? (reason as any).code.trim() : ''; const message = reason instanceof Error ? reason.message : typeof reason === 'string' ? reason : ''; const prefix = /^([A-Za-z][A-Za-z0-9_.-]{0,119})(?::|$)/.exec(message.trim())?.[1]; return { errorCode: /^[A-Za-z][A-Za-z0-9_.-]{0,119}$/.test(code) ? code : prefix ?? 'PERCEPTION_MODULE_FAILED', messagePresent: message.length > 0, ...(message ? { messageLength: message.length } : {}), }; } export function perceptionManifest(instance: ClawclawPerception): ClawclawPerceptionManifest { const ModuleClass = moduleClass(instance); return validatePerceptionManifest(ModuleClass.manifest); } export function validatePerceptionManifest( manifest: ClawclawPerceptionManifest | undefined, ): ClawclawPerceptionManifest { if ( !manifest || manifest.apiVersion !== PERCEPTION_PLUGIN_API_VERSION || !/^[a-z0-9][a-z0-9._-]*$/.test(manifest.id) || (manifest.name !== undefined && !nonEmpty(manifest.name)) || !nonEmpty(manifest.description) || !hasValidClawclawResourceLocalizations(manifest.localizations) || !['others', 'self_and_others', 'visible_pairs', 'corpses'].includes(manifest.subjectScope) || !Array.isArray(manifest.produces) || manifest.produces.length === 0 || manifest.produces.some((type) => !/^visual\.[a-z0-9_.-]+$/.test(type)) || new Set(manifest.produces).size !== manifest.produces.length || !hasValidPerceptionEventMetadata(manifest) || (manifest.execution !== undefined && manifest.execution !== 'parallel_analysis') || ( manifest.boundaryBaseline !== undefined && ( manifest.execution !== 'parallel_analysis' || manifest.boundaryBaseline !== 'current_only' ) ) ) { throw new Error('Perception module manifest is invalid.'); } return manifest; } function createModuleSlots( config: ClawclawPerceptionConfig, loader: PerceptionModuleLoader, ): Readonly<{ modules: PerceptionModuleSlot[]; reducerPool?: PerceptionReducerThreadPool; }> { const ids = [...new Set(config.modules ?? DEFAULT_PERCEPTION_MODULES)].sort(); const sources = new Map( (config.moduleSources ?? listClawclawPerceptionSources(config.workspaceDir)) .map((source) => [source.id, source]), ); const selected = ids.map((id) => { const source = sources.get(id); if (!source) throw new Error(`Unknown perception module '${id}'.`); return source; }).filter(source => !source.reminder && !source.module); const reducerPool = selected.length > 0 ? new PerceptionReducerThreadPool({ modules: selected.map((source) => loader.threadSpec(source)), loader: loader.threadConfig(), spatialFacts: CLAWCLAW_PERCEPTION_SPATIAL_FACTS satisfies PerceptionSpatialFacts, diagnosticsEnabled: config.diagnosticsEnabled === true, }) : undefined; return { reducerPool, modules: selected.map((source) => { const runner = new ImportedLocalPerceptionModuleRunner(source, loader, reducerPool); return { manifest: validatePerceptionManifest(runner.manifest), runner, source, analysisGeneration: 0, analysisHistoryFloorFrameSeq: 0, analysisBaselinePending: false, reducerReplayFromFrameSeq: undefined, }; }), }; } function proposals(value: readonly PerceptionEventProposal[] | void): RuntimeEventProposal[] { return value ? value.map((proposal) => ({ ...proposal, payload: { ...proposal.payload }, })) : []; } /** One Runtime plugin that projects each frame once and fans it out to perception modules. */ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin> { readonly agentNotificationProducer = true; readonly kind = 'epoch' as const; readonly id = CLAWCLAW_PERCEPTION_PLUGIN_ID; readonly version = String(PERCEPTION_PLUGIN_API_VERSION); get catchUp(): 'every_epoch' | 'latest_only' { return this.maxBackfillVisualFrames === 1 && this.modules.some(({ runner }) => runner.execution === 'parallel_analysis') ? 'latest_only' : 'every_epoch'; } readonly maxInFlight: number; readonly maxPendingEpochs = 10; readonly backlogPolicy = 'finish_started' as const; // Includes bounded analysis queueing and ordered reducer roundtrips. A 1s // framework default killed healthy Workers during CPU contention/recovery. readonly timeoutMs = 5_000; readonly recoveryTimeoutMs = DEFAULT_PERCEPTION_RECOVERY_TIMEOUT_MS; readonly produces: { readonly events: readonly string[] }; private readonly configuredModules: readonly PerceptionModuleSlot[]; private readonly reducerPool?: PerceptionReducerThreadPool; /** Modules that completed every startup stage for the current lifecycle. */ private modules: readonly PerceptionModuleSlot[]; private readonly maxBackfillVisualFrames: number; private readonly diagnosticsEnabled: boolean; private readonly moduleLoader = new PerceptionModuleLoader(); private analysisPool?: PerceptionAnalysisThreadPool; private readonly projector = new ObservationFrameProjector(); private readonly api: PerceptionApi = Object.freeze({ spatial: CLAWCLAW_PERCEPTION_SPATIAL_API, }); private lifecyclePhase: string | null = null; private lastFrameSeq = 0; private lastFrameTimeMs: number | null = null; private lastVisualTick: number | null = null; private lastVisualFrame: PerceptionFrame | null = null; private lastConnectionId: string | null = null; private readonly analysisWindow: PerceptionFrame[] = []; /** Bounded projection cache shared by overlapping epoch analyses. */ private readonly projectedFrameCache = new Map(); private replayFromFrameSeq: number | null = null; private readonly moduleFailureReports = new Map(); private readonly disabledModuleIds = new Set(); private readonly moduleTimingWindows = new Map(); private moduleTimingWindowStartedAt = performance.now(); private frameTimingWindow: PerceptionFrameTimingWindow = this.newFrameTimingWindow(); private runnersStarted = false; private runnersStartTask?: Promise; private runnersStartGeneration = 0; private runnersStopTask?: Promise; private runnerLifecycleGeneration = 0; constructor(config: ClawclawPerceptionConfig = {}) { const maxBackfillVisualFrames = config.maxBackfillVisualFrames ?? DEFAULT_MAX_PERCEPTION_BACKFILL_VISUAL_FRAMES; if ( !Number.isInteger(maxBackfillVisualFrames) || maxBackfillVisualFrames <= 0 || maxBackfillVisualFrames > 10 ) { throw new TypeError('maxBackfillVisualFrames must be an integer between 1 and 10.'); } this.maxBackfillVisualFrames = maxBackfillVisualFrames; this.diagnosticsEnabled = config.diagnosticsEnabled === true; const configured = createModuleSlots(config, this.moduleLoader); this.configuredModules = configured.modules; this.reducerPool = configured.reducerPool; // Keep configured descriptors available before the first Runtime start. // Once startup settles, this is narrowed to only successfully active modules. this.modules = this.configuredModules; // Pure legacy assemblies do all module work in ordered commit. Keeping // them at one in-flight epoch preserves the scheduler's normal catch-up // path instead of buffering ten empty analysis proposals ahead of a slow // stateful reducer. Only an explicit parallel analyzer needs the ROB. this.maxInFlight = this.modules.some(({ runner }) => ( runner.execution === 'parallel_analysis' )) ? maxBackfillVisualFrames : 1; this.produces = { events: [...new Set(this.modules.flatMap(({ manifest }) => [...manifest.produces]))], }; } async start(context: RuntimeEpochPluginContext>): Promise { await this.startRunners(context.signal, context.diagnostic); } async recover(context: RuntimeEpochPluginContext>): Promise { const completedThroughEpochSeq = context.progress().completedThroughEpochSeq; if (completedThroughEpochSeq <= 0) return; const latestCompletedFrame = context.stateHistory.queryStateFrames({ scope: context.scope, toEpochSeq: completedThroughEpochSeq, order: 'desc', limit: 1, }).frames[0]; if (!latestCompletedFrame) return; const nextFrameSeq = latestCompletedFrame.frameSeq + 1; this.resetProjection(); this.lastFrameSeq = latestCompletedFrame.frameSeq; this.replayFromFrameSeq = nextFrameSeq; for (const module of this.modules) { if (module.runner.execution !== 'parallel_analysis') continue; this.advanceParallelGeneration(module, nextFrameSeq); } context.diagnostic('perception.recovery_history_skipped', { completed_through_epoch_seq: completedThroughEpochSeq, skipped_through_frame_seq: latestCompletedFrame.frameSeq, resume_from_frame_seq: nextFrameSeq, }); } async update( input: RuntimeEpochPluginInput>, context: RuntimeEpochPluginContext>, ): Promise { if (isNotificationTurn(input.epoch.state)) return { outcome: 'noop', reason: 'notification_only' }; if (input.epoch.state.cycle && !input.epoch.state.cycle.hasNewState && input.epoch.state.connection === 'connected' && input.epoch.state.stage !== 'ended') { return { outcome: 'noop', reason: 'unchanged_observation' }; } const updateStartedAt = performance.now(); const projectionStartedAt = performance.now(); const visual = this.projector.project(input.frame); const projectionMs = elapsedMs(projectionStartedAt); const historyStartedAt = performance.now(); const analysisInput = visual && this.shouldAnalyze(input.frame) ? this.analysisInputFromHistory(input.frame, visual, context) : null; const historyPrepareMs = elapsedMs(historyStartedAt); const prepared = await this.prepareFrame(input.frame, visual, context.signal, analysisInput); const proposal: PerceptionComputationProposal = { schema: PERCEPTION_COMPUTATION_SCHEMA, visual: prepared.visual, analyses: prepared.analyses, timing: { projectionMs, historyPrepareMs, ...prepared.analysisTiming, updateTotalMs: elapsedMs(updateStartedAt), }, }; return { outcome: 'processed', reason: prepared.visual ? 'visual_analyzed' : 'state_classified', proposal, }; } async commit( input: RuntimeEpochPluginInput>, computation: Readonly, context: RuntimeEpochPluginContext>, ): Promise { if (isNotificationTurn(input.epoch.state) || computation.reason === 'unchanged_observation') return computation; const proposal = this.computationProposal(computation.proposal); const commitStartedAt = performance.now(); const previousFrameSeq = this.lastFrameSeq; const inspected = await this.inspectPreparedFrame({ stored: input.frame, visual: proposal.visual, analyses: proposal.analyses, analysisTiming: proposal.timing ?? this.emptyAnalysisTiming(), }, context.signal, context.diagnostic); if (!input.epoch.state.cycle && input.frame.frameSeq > previousFrameSeq + 1) { context.diagnostic('perception.catchup_frames_dropped', { target_epoch_seq: input.epoch.epochSeq, max_backfill_visual_frames: this.maxBackfillVisualFrames, dropped_state_frame_count: input.frame.frameSeq - previousFrameSeq - 1, dropped_from_frame_seq: previousFrameSeq + 1, dropped_through_frame_seq: input.frame.frameSeq - 1, retained_from_frame_seq: input.frame.frameSeq, retained_through_frame_seq: input.frame.frameSeq, }); } const checkpoint = this.checkpointValue(); const commitMs = elapsedMs(commitStartedAt); if (proposal.timing) { this.recordFrameTiming({ ...proposal.timing, commitMs, totalMs: proposal.timing.updateTotalMs + commitMs, }, context.diagnostic); } return inspected.visual || inspected.proposals.length > 0 ? { outcome: 'processed', ...(inspected.reason ? { reason: inspected.reason } : {}), events: inspected.proposals.map(event => ({ ...event, notificationContent: event.notificationContent ?? prepareNotificationContent(event.type, event.payload, input.currentState.state, 'custom') })), checkpoint, } : { outcome: 'noop', reason: inspected.reason ?? 'not_visual_state', checkpoint }; } /** Advances one frame; used by Runtime and deterministic offline replay. */ async inspectFrame( input: StoredStateFrame>, signal = new AbortController().signal, diagnostic?: PerceptionDiagnostic, ): Promise { if (!this.runnersStarted) await this.startRunners(signal); if (input.frameSeq <= this.lastFrameSeq) { return { visual: null, proposals: [], moduleStates: this.moduleStateSnapshot() }; } const projected = this.projector.project(input); return this.inspectPreparedFrame( await this.prepareFrame( input, projected, signal, projected && this.shouldAnalyze(input) ? this.localAnalysisInput(input, projected) : null, ), signal, diagnostic, ); } private async inspectPreparedFrame( input: PreparedPerceptionFrame, signal: AbortSignal, diagnostic?: PerceptionDiagnostic, ): Promise { if (input.stored.frameSeq <= this.lastFrameSeq) { return { visual: null, proposals: [], moduleStates: this.moduleStateSnapshot() }; } const stateFrameGap = !input.stored.state.cycle && this.lastFrameSeq > 0 && input.stored.frameSeq > this.lastFrameSeq + 1; this.lastFrameSeq = input.stored.frameSeq; const runtimeState = input.stored.state; if (isClawclawRuntimeState(runtimeState)) { if (runtimeState.connection !== 'connected') { const events = await this.flushAndReset( 'trajectory_gap', signal, diagnostic, input.stored.frameSeq + 1, ); return { visual: null, proposals: events, moduleStates: this.moduleStateSnapshot(), reason: runtimeState.connection, }; } if ( runtimeState.cause === 'agent_events_query' && runtimeState.control?.type === 'events_query' ) { const events = await this.flushModules( 'events_requested', 'snapshot', signal, diagnostic, ); return { visual: null, proposals: events, moduleStates: this.moduleStateSnapshot(), reason: 'events_requested', }; } if (runtimeState.stage === 'ended') { const events = await this.flushAndReset( 'segment_ending', signal, diagnostic, input.stored.frameSeq + 1, ); return { visual: null, proposals: events, moduleStates: this.moduleStateSnapshot(), reason: 'segment_ending', }; } if (runtimeState.game_snapshot.status !== 'fresh' && runtimeState.game_snapshot.status !== 'cached') { return { visual: null, proposals: [], moduleStates: this.moduleStateSnapshot(), reason: `game_snapshot:${runtimeState.game_snapshot.status}`, }; } } const projected = input.visual; if (!projected) { return { visual: null, proposals: [], moduleStates: this.moduleStateSnapshot() }; } const previousVisualTick = this.lastVisualTick; const projectedLifecycle = perceptionLifecycle(projected); const phaseChanged = this.lifecyclePhase !== null && this.lifecyclePhase !== projectedLifecycle; const tickDelta = previousVisualTick === null ? null : projected.tick - previousVisualTick; const sameConnection = this.lastConnectionId === input.stored.connectionId; const emitted: RuntimeEventProposal[] = []; if (previousVisualTick !== null && projected.tick > previousVisualTick + 1) { diagnostic?.('runtime.plugin.coverage_gap', { reason: 'game_tick_gap', previous_game_tick: previousVisualTick, received_game_tick: projected.tick, missing_from_game_tick: previousVisualTick + 1, missing_to_game_tick: projected.tick - 1, frame_seq: input.stored.frameSeq, }); } const continuousFromPrevious = !stateFrameGap && !phaseChanged && tickDelta !== null && tickDelta >= 0 && tickDelta <= 3 && sameConnection; const frame: PerceptionFrame = { ...projected, tickDelta, continuousFromPrevious }; const gap = this.lastVisualTick !== null && !phaseChanged && !continuousFromPrevious; // Close every module's old slice before it receives the new phase/gap frame. if (gap || phaseChanged) { const kind: PerceptionBoundaryKind = gap ? 'trajectory_gap' : 'phase_changed'; emitted.push(...await this.flushModules(kind, 'close', signal, diagnostic, projected)); await this.resetModules( kind, signal, diagnostic, input.stored.frameSeq, false, ); this.replayFromFrameSeq = input.stored.frameSeq; } if (this.replayFromFrameSeq === null) this.replayFromFrameSeq = input.stored.frameSeq; emitted.push(...await this.deliverVisualFrame( frame, input.stored.connectionId, input.analyses, gap || phaseChanged, signal, diagnostic, )); return { visual: frame, proposals: emitted, moduleStates: this.moduleStateSnapshot() }; } async flushForEventsQuery(signal = new AbortController().signal): Promise { const events = await this.flushModules('events_requested', 'snapshot', signal); return events.length > 0 ? { outcome: 'processed', reason: 'events_requested', events } : { outcome: 'noop', reason: 'events_requested' }; } async flush( reason: RuntimeEpochFlushReason, context: RuntimeEpochPluginContext>, ): Promise { const events = await this.flushModules(reason, 'close', context.signal, context.diagnostic); if (events.length > 0) { context.diagnostic('perception.lifecycle_output_uncommitted', { event_count: events.length, reason, }); } await this.resetModules( reason, context.signal, context.diagnostic, this.lastFrameSeq + 1, ); this.flushModuleTimingWindows(context.diagnostic, true); this.flushFrameTimingWindow(context.diagnostic, true); } stop(reason: 'segment_ending' | 'shutdown'): Promise { if (this.runnersStopTask) return this.runnersStopTask; this.runnerLifecycleGeneration += 1; this.runnersStarted = false; let task!: Promise; task = this.stopRunners(reason).finally(() => { if (this.runnersStopTask === task) this.runnersStopTask = undefined; }); this.runnersStopTask = task; return task; } private async stopRunners(reason: 'segment_ending' | 'shutdown'): Promise { const analysisPool = this.analysisPool; this.analysisPool = undefined; await analysisPool?.stop(); // This includes reducer Workers that are still starting; their own // generation fence prevents a late ready result from resurrecting them. await Promise.allSettled(this.configuredModules.map(({ runner }) => runner.stop(reason))); await this.reducerPool?.stop(); await this.moduleLoader.stop(); this.modules = []; this.moduleFailureReports.clear(); this.disabledModuleIds.clear(); this.moduleTimingWindows.clear(); this.moduleTimingWindowStartedAt = performance.now(); this.frameTimingWindow = this.newFrameTimingWindow(); this.resetProjection(); } /** Starts the same module lifecycle without constructing a Runtime context. */ async startForReplay(signal = new AbortController().signal): Promise { await this.startRunners(signal); } async stopForReplay(): Promise { await this.stop('shutdown'); } moduleDescriptors(): PerceptionModuleDescriptor[] { return this.modules.map(({ manifest }) => ({ ...manifest, produces: [...manifest.produces], pluginId: CLAWCLAW_PERCEPTION_PLUGIN_ID, })); } diagnosticSnapshot(): Readonly> { const pool = this.analysisPool?.snapshot(); const reducerPool = this.reducerPool?.snapshot(); return Object.freeze({ configured_module_count: this.configuredModules.length, active_module_count: this.modules.length, active_module_ids: this.modules.map(({ manifest }) => manifest.id), analysis_pool: pool ? { state: pool.state, min_worker_count: pool.minWorkers, max_worker_count: pool.maxWorkers, worker_count: pool.workerCount, idle_worker_count: pool.idleWorkerCount, busy_worker_count: pool.busyWorkerCount, queued_batch_count: pool.queuedBatchCount, queued_job_count: pool.queuedJobCount, in_flight_batch_count: pool.inFlightBatchCount, started_worker_count: pool.startedWorkerCount, retired_worker_count: pool.retiredWorkerCount, worker_heap_used_bytes: pool.workerHeapUsedBytes, peak_worker_heap_used_bytes: pool.peakWorkerHeapUsedBytes, } : null, reducer_pool: reducerPool ? { state: reducerPool.state, max_worker_count: reducerPool.maxWorkerCount, worker_count: reducerPool.workerCount, busy_worker_count: reducerPool.busyWorkerCount, queued_request_count: reducerPool.queuedRequestCount, in_flight_request_count: reducerPool.inFlightRequestCount, active_module_count: reducerPool.activeModuleCount, unavailable_module_ids: reducerPool.unavailableModuleIds, restarted_worker_count: reducerPool.restartedWorkerCount, worker_heap_used_bytes: reducerPool.workerHeapUsedBytes, peak_worker_heap_used_bytes: reducerPool.peakWorkerHeapUsedBytes, } : null, }); } localizedModuleDescriptors(locale: string): ClawclawResolvedResourceMetadata[] { return this.modules.map(({ manifest, source }) => resolveClawclawResourceMetadata({ ...manifest, display: source.display, }, locale)); } localizedModuleDescriptorForEvent( type: string, locale: string, ): (ClawclawResolvedResourceMetadata & { perceptionId: string }) | undefined { const module = this.modules.find(({ manifest }) => manifest.produces.includes(type)); if (!module) return undefined; return { ...resolveClawclawResourceMetadata({ ...module.manifest, display: module.source.display }, locale), perceptionId: module.manifest.id, }; } localizedEventDescriptors(locale: string): LocalizedPerceptionEventDescriptor[] { return this.modules.flatMap(({ manifest }) => manifest.produces.flatMap((type) => { const metadata = manifest.eventMetadata?.[type]; if (!metadata) return []; const localized = resolveClawclawResourceMetadata({ id: type, ...metadata }, locale); return [{ type, perceptionId: manifest.id, name: localized.name, description: localized.description, }]; })); } moduleStateSnapshot(): Record { return Object.fromEntries(this.modules.map(({ manifest, runner }) => [ manifest.id, runner.debugSnapshot(), ])); } private async deliverVisualFrame( frame: Readonly, connectionId: string, analyses: readonly PerceptionModuleAnalysis[], discardParallelAnalysis: boolean, signal: AbortSignal, diagnostic?: PerceptionDiagnostic, ): Promise { this.lastFrameTimeMs = frame.timeMs; this.lifecyclePhase = perceptionLifecycle(frame); this.lastVisualTick = frame.tick; this.lastVisualFrame = frame; this.lastConnectionId = connectionId; this.analysisWindow.push(frame); if (this.analysisWindow.length > PERCEPTION_ANALYSIS_WINDOW_FRAMES) this.analysisWindow.shift(); return this.withOccurredAt( await this.updateModules( frame, analyses, discardParallelAnalysis, signal, diagnostic, ), frame.timeMs, ); } private async updateModules( frame: Readonly, analyses: readonly PerceptionModuleAnalysis[], discardParallelAnalysis: boolean, signal: AbortSignal, diagnostic?: PerceptionDiagnostic, ): Promise { const analysisByModule = new Map(analyses.map((entry) => [entry.moduleId, entry] as const)); this.recordAnalysisResults(analyses, diagnostic); return this.collectModuleEvents( 'update', async (module) => { const { manifest, runner } = module; if (runner.execution === 'ordered_update') { return runner.update(frame, this.api, signal); } if (!this.shouldRunParallelModuleForFrame(module, frame.frameSeq)) return []; const analysis = analysisByModule.get(manifest.id); // A computation may have started before the scheduler dropped older // epochs. Its analysis can therefore describe relationships to frames // that will never commit. Only a module with the explicit current-only // contract may install this frame into its freshly reset reducer, and // even then no boundary Event is accepted. if (discardParallelAnalysis) { if ( manifest.boundaryBaseline !== 'current_only' || !analysis || analysis.outcome === 'rejected' || analysis.generation + 1 !== module.analysisGeneration ) { module.analysisBaselinePending = true; module.reducerReplayFromFrameSeq = null; return []; } await runner.commit(frame, analysis.analysis, this.api, signal); module.reducerReplayFromFrameSeq = frame.frameSeq; module.analysisBaselinePending = false; return []; } if (!analysis || analysis.outcome === 'rejected') { const failure = analysis?.outcome === 'rejected' ? analysis.failure : undefined; if ( failure && this.analysisFailureDisablesModule(failure.errorCode) && !this.disabledModuleIds.has(manifest.id) ) { this.disabledModuleIds.add(manifest.id); diagnostic?.('perception.module.disabled', { module_id: manifest.id, reason: failure.errorCode, }, 'error'); } await this.invalidateParallelModule( module, frame.frameSeq + 1, signal, ); return []; } if (analysis.generation !== module.analysisGeneration) { // A current-only hard boundary can install its own frame as the new // reducer baseline while later, already-computed frames still belong // to the old generation. Dropping those frames creates another // reducer discontinuity. Reset once, but do not advance generation: // the first valid current-generation analysis can then establish a // fresh baseline without emitting an Event. if (!module.analysisBaselinePending) { module.analysisBaselinePending = true; module.reducerReplayFromFrameSeq = null; await runner.reset('trajectory_gap', signal); } return []; } const events = await runner.commit(frame, analysis.analysis, this.api, signal); if ( module.reducerReplayFromFrameSeq === null || ( module.reducerReplayFromFrameSeq === undefined && module.analysisBaselinePending && module.analysisHistoryFloorFrameSeq > 0 ) ) module.reducerReplayFromFrameSeq = frame.frameSeq; if (module.analysisBaselinePending) { module.analysisBaselinePending = false; return []; } return events; }, diagnostic, async (module) => { if (module.runner.execution !== 'parallel_analysis') return; await this.invalidateParallelModule( module, frame.frameSeq + 1, signal, ); }, ); } private async invalidateParallelModule( module: PerceptionModuleSlot, historyFloorFrameSeq: number, signal: AbortSignal, ): Promise { this.advanceParallelGeneration(module, historyFloorFrameSeq); await module.runner.reset('trajectory_gap', signal); } private advanceParallelGeneration( module: PerceptionModuleSlot, historyFloorFrameSeq: number, baselinePending = true, ): void { module.analysisGeneration += 1; module.analysisHistoryFloorFrameSeq = Math.max( module.analysisHistoryFloorFrameSeq, historyFloorFrameSeq, ); module.analysisBaselinePending = baselinePending; module.reducerReplayFromFrameSeq = null; } private async prepareFrame( stored: StoredStateFrame>, visual: PerceptionFrame | null, signal: AbortSignal, analysisInput: Readonly | null = null, ): Promise { if (!visual || !this.shouldAnalyze(stored)) { return { stored, visual, analyses: [], analysisTiming: this.emptyAnalysisTiming() }; } const preparedVisual = analysisInput?.frame ?? visual; const analyzerInput = analysisInput ?? this.localAnalysisInput(stored, visual); const parallelModules = this.modules.filter((module) => ( module.runner.execution === 'parallel_analysis' && this.shouldRunParallelModuleForFrame(module, stored.frameSeq) )); if (parallelModules.length === 0) { return { stored, visual: preparedVisual, analyses: [], analysisTiming: this.emptyAnalysisTiming(), }; } const analysisPool = this.analysisPool; if (!analysisPool) throw new Error('perception_analysis_pool_not_started'); // Capture generations and module-specific history before submitting one // frame batch. Ordered commit may advance an individual generation while // this Worker is still running; the existing reducer gate rejects it. const generations = new Map(parallelModules.map((module) => [ module.manifest.id, module.analysisGeneration, ] as const)); const jobs: PerceptionAnalysisJob[] = parallelModules.map((module) => ({ moduleId: module.manifest.id, input: this.analysisInputForModule(analyzerInput, module), })); const startedAt = performance.now(); try { signal.throwIfAborted(); const batch = await analysisPool.analyze(jobs, signal); const analyses: PerceptionModuleAnalysis[] = batch.results.map((result) => result.outcome === 'fulfilled' ? { moduleId: result.moduleId, generation: generations.get(result.moduleId)!, outcome: 'fulfilled', durationMs: result.durationMs, analysis: result.analysis, } : { moduleId: result.moduleId, generation: generations.get(result.moduleId)!, outcome: 'rejected', durationMs: result.durationMs, failure: result.failure, }); const moduleDurations = batch.results.map((result) => result.durationMs); return { stored, visual: preparedVisual, analyses, analysisTiming: { workerQueueMs: batch.queueDurationMs, workerRoundtripMs: Math.max(0, batch.durationMs - batch.queueDurationMs), moduleCpuSumMs: moduleDurations.reduce((sum, duration) => sum + duration, 0), moduleCpuMaxMs: Math.max(0, ...moduleDurations), workerCount: batch.workerCount, }, }; } catch (error) { const failure = perceptionFailureDetails(error); const durationMs = elapsedMs(startedAt); return { stored, visual: preparedVisual, analyses: parallelModules.map((module) => ({ moduleId: module.manifest.id, generation: generations.get(module.manifest.id)!, outcome: 'rejected' as const, durationMs, failure, })), analysisTiming: { workerQueueMs: 0, workerRoundtripMs: durationMs, moduleCpuSumMs: 0, moduleCpuMaxMs: 0, workerCount: analysisPool.snapshot().workerCount, }, }; } } private emptyAnalysisTiming(): PerceptionAnalysisTiming { return { workerQueueMs: 0, workerRoundtripMs: 0, moduleCpuSumMs: 0, moduleCpuMaxMs: 0, workerCount: this.analysisPool?.snapshot().workerCount ?? 0, }; } private analysisInputForModule( input: Readonly, module: PerceptionModuleSlot, ): PerceptionAnalysisInput { const floor = module.analysisHistoryFloorFrameSeq; if (floor <= 0) return input as PerceptionAnalysisInput; const history = input.history.filter((frame) => frame.frameSeq >= floor); const previous = history.at(-1); const keptImmediatePrevious = previous === input.history.at(-1); const tickDelta = previous ? input.frame.tick - previous.tick : null; const frame: PerceptionFrame = { ...input.frame, tickDelta, continuousFromPrevious: !!previous && keptImmediatePrevious && input.frame.continuousFromPrevious, }; return { frame, history, gapBefore: input.gapBefore || history.length !== input.history.length || !frame.continuousFromPrevious, }; } private shouldRunParallelModuleForFrame( module: PerceptionModuleSlot, frameSeq: number, ): boolean { return !this.disabledModuleIds.has(module.manifest.id) && frameSeq >= module.analysisHistoryFloorFrameSeq; } private analysisFailureDisablesModule(errorCode: string): boolean { return errorCode === 'perception_analysis_worker_exited' || errorCode === 'perception_analysis_worker_memory_invalid' || errorCode === 'perception_analysis_output_too_large'; } private analysisInputFromHistory( stored: StoredStateFrame>, currentVisual: PerceptionFrame, context: RuntimeEpochPluginContext>, ): PerceptionAnalysisInput { this.rememberProjectedFrame(stored, currentVisual); const cached = (context.processingIntervalMs !== undefined ? [] : [...this.projectedFrameCache.values()]) .filter((value) => value.stored.frameSeq <= stored.frameSeq) .sort((left, right) => left.stored.frameSeq - right.stored.frameSeq) .slice(-(PERCEPTION_ANALYSIS_WINDOW_FRAMES + 1)); // The first frame after process recovery deliberately reads durable history // once. Normal overlapping epochs reuse projections already built by the // plugin and avoid re-querying/re-projecting the same ten frames per tick. const cacheIsContinuous = cached.every((value, index) => ( index === 0 || value.stored.frameSeq === cached[index - 1]!.stored.frameSeq + 1 )); if ( cached.length > 1 && cacheIsContinuous && cached.at(-1)?.stored.frameSeq === stored.frameSeq ) { return this.enrichAnalysisInput(cached); } const projected = new Map>; visual: PerceptionFrame; }>(); let beforeFrameSeq = stored.state.cycle?.stateFrameSeq ?? stored.frameSeq + 1; while (projected.size < PERCEPTION_ANALYSIS_WINDOW_FRAMES + 1 && beforeFrameSeq > 1) { context.signal.throwIfAborted(); const page = context.stateHistory.queryStateFrames({ scope: context.scope, beforeFrameSeq, order: 'desc', limit: 32, }); if (page.frames.length === 0) break; for (const candidate of page.frames) { if (stored.state.cycle && candidate.state.cycle) continue; if (candidate.frameSeq > stored.frameSeq) continue; const visual = candidate.frameSeq === stored.frameSeq ? currentVisual : this.projector.project(candidate); if (visual) { projected.set(candidate.frameSeq, { stored: candidate, visual }); this.rememberProjectedFrame(candidate, visual); } if (projected.size >= PERCEPTION_ANALYSIS_WINDOW_FRAMES + 1) break; } beforeFrameSeq = page.frames.at(-1)!.frameSeq; if (!page.page.hasMore) break; } if (!projected.has(stored.frameSeq)) { projected.set(stored.frameSeq, { stored, visual: currentVisual }); } const values = [...projected.values()].sort((left, right) => left.stored.frameSeq - right.stored.frameSeq); return this.enrichAnalysisInput(values); } private enrichAnalysisInput(values: readonly CachedProjectedFrame[]): PerceptionAnalysisInput { const enriched: PerceptionFrame[] = []; values.forEach((value, index) => { const previous = index > 0 ? values[index - 1] : undefined; const before = enriched.at(-1); const tickDelta = before ? value.visual.tick - before.tick : null; const continuousFromPrevious = !!before && perceptionLifecycle(before) === perceptionLifecycle(value.visual) && tickDelta !== null && tickDelta >= 0 && tickDelta <= 3 && previous?.stored.connectionId === value.stored.connectionId; enriched.push({ ...value.visual, tickDelta, continuousFromPrevious }); }); const bounded = enriched.slice(-PERCEPTION_ANALYSIS_WINDOW_FRAMES); const frame = bounded.at(-1)!; const history = bounded.slice(0, -1); return { frame, history, gapBefore: history.length > 0 && !frame.continuousFromPrevious, }; } private rememberProjectedFrame( stored: Pick>, 'frameSeq' | 'connectionId'>, visual: PerceptionFrame, ): void { this.projectedFrameCache.set(stored.frameSeq, { stored, visual }); const maximum = PERCEPTION_ANALYSIS_WINDOW_FRAMES + this.maxInFlight + 2; while (this.projectedFrameCache.size > maximum) { const oldest = Math.min(...this.projectedFrameCache.keys()); this.projectedFrameCache.delete(oldest); } } private localAnalysisInput( stored: StoredStateFrame>, visual: PerceptionFrame, ): PerceptionAnalysisInput { const history = this.analysisWindow.slice(-(PERCEPTION_ANALYSIS_WINDOW_FRAMES - 1)); const previous = history.at(-1); const tickDelta = previous ? visual.tick - previous.tick : null; const frame: PerceptionFrame = { ...visual, tickDelta, continuousFromPrevious: !!previous && perceptionLifecycle(previous) === perceptionLifecycle(visual) && tickDelta !== null && tickDelta >= 0 && tickDelta <= 3 && this.lastConnectionId === stored.connectionId, }; return { frame, history, gapBefore: history.length > 0 && !frame.continuousFromPrevious, }; } private shouldAnalyze(stored: StoredStateFrame>): boolean { const runtimeState = stored.state; if (!isClawclawRuntimeState(runtimeState)) return true; return runtimeState.connection === 'connected' && runtimeState.stage !== 'ended' && (runtimeState.game_snapshot.status === 'fresh' || runtimeState.game_snapshot.status === 'cached') && !( runtimeState.cause === 'agent_events_query' && runtimeState.control?.type === 'events_query' ); } private computationProposal(value: unknown): PerceptionComputationProposal { if (!value || typeof value !== 'object' || Array.isArray(value)) { throw new Error('perception_computation_missing'); } const proposal = value as Partial; if ( proposal.schema !== PERCEPTION_COMPUTATION_SCHEMA || !Array.isArray(proposal.analyses) || (proposal.visual !== null && typeof proposal.visual !== 'object') ) throw new Error('perception_computation_invalid'); return proposal as PerceptionComputationProposal; } private recordAnalysisResults( analyses: readonly PerceptionModuleAnalysis[], diagnostic?: PerceptionDiagnostic, ): void { if (analyses.length === 0) return; this.recordModuleTimings('analyze', analyses.map((entry) => ({ module_id: entry.moduleId, duration_ms: entry.durationMs, outcome: entry.outcome, event_count: 0, }))); this.flushModuleTimingWindows(diagnostic); for (const entry of analyses) { if (entry.outcome !== 'rejected' || !entry.failure) continue; this.reportModuleFailure(entry.moduleId, 'analyze', entry.failure, diagnostic); } } private async flushModules( kind: PerceptionBoundaryKind, mode: PerceptionBoundary['mode'], signal: AbortSignal, diagnostic?: PerceptionDiagnostic, next?: Readonly | null, ): Promise { const boundary: PerceptionBoundary = Object.freeze({ kind, mode, through: this.lastVisualFrame, ...(next === undefined ? {} : { next }), }); const output = await this.collectModuleEvents( `flush:${kind}`, ({ runner }) => runner.flush(boundary, this.api, signal), diagnostic, ); return this.withOccurredAt(output, boundary.through?.timeMs ?? this.lastFrameTimeMs); } private async flushAndReset( kind: Exclude, signal: AbortSignal, diagnostic?: PerceptionDiagnostic, replayFromFrameSeq: number | null = null, ): Promise { const emitted = await this.flushModules(kind, 'close', signal, diagnostic); await this.resetModules( kind, signal, diagnostic, replayFromFrameSeq ?? this.lastFrameSeq + 1, ); this.lifecyclePhase = null; this.lastFrameTimeMs = null; this.lastVisualTick = null; this.lastVisualFrame = null; this.lastConnectionId = null; this.analysisWindow.length = 0; this.replayFromFrameSeq = replayFromFrameSeq; return emitted; } private async resetModules( reason: Exclude | 'replay', signal: AbortSignal, diagnostic?: PerceptionDiagnostic, parallelHistoryFloorFrameSeq?: number, parallelBaselinePending = true, ): Promise { const modules = this.modules; if (parallelHistoryFloorFrameSeq !== undefined) { for (const module of modules) { if (module.runner.execution !== 'parallel_analysis') continue; this.advanceParallelGeneration( module, parallelHistoryFloorFrameSeq, parallelBaselinePending || module.manifest.boundaryBaseline !== 'current_only', ); } } const results = await Promise.allSettled( modules.map(({ runner }) => runner.reset(reason, signal)), ); this.reportModuleFailures(`reset:${reason}`, modules, results, diagnostic); } private async collectModuleEvents( operation: string, invoke: ( module: PerceptionModuleSlot, ) => readonly PerceptionEventProposal[] | void | Promise, diagnostic?: PerceptionDiagnostic, onRejected?: (module: PerceptionModuleSlot, error: unknown) => void | Promise, ): Promise { const modules = this.modules; const timings: Array<{ module_id: string; duration_ms: number; outcome: 'fulfilled' | 'rejected'; event_count: number; }> = new Array(modules.length); const results = await Promise.allSettled(modules.map(async (module, index) => { const startedAt = performance.now(); try { const result = await invoke(module); timings[index] = { module_id: module.manifest.id, duration_ms: elapsedMs(startedAt), outcome: 'fulfilled', event_count: proposals(result).length, }; return result; } catch (error) { timings[index] = { module_id: module.manifest.id, duration_ms: elapsedMs(startedAt), outcome: 'rejected', event_count: 0, }; throw error; } })); this.reportModuleFailures(operation, modules, results, diagnostic); if (onRejected) { await Promise.allSettled(results.map((result, index) => ( result.status === 'rejected' ? onRejected(modules[index]!, result.reason) : Promise.resolve() ))); } if (diagnostic) { this.recordModuleTimings(operation, timings); this.flushModuleTimingWindows(diagnostic); } return results.flatMap((result, index) => { if (result.status !== 'fulfilled') return []; const module = modules[index]!; const values = proposals(result.value); // Aliased copies may emit the same source-level dedupe key. Keep their // outputs separate without renaming any public Event type or payload. return values.map(value => ({ ...value, ...(module.source?.declaredId && module.source.declaredId !== module.manifest.id ? { dedupeKey: `ccl-alias:${JSON.stringify([module.manifest.id, value.dedupeKey])}` } : {}), notificationContent: preparePerceptionNotification(value.type, value.payload, this.lastVisualFrame?.gameState ?? null, module.manifest.id, this.lastVisualTick), })); }); } private recordModuleTimings( operation: string, timings: readonly { module_id: string; duration_ms: number; outcome: 'fulfilled' | 'rejected'; event_count: number; }[], ): void { for (const timing of timings) { const key = `${timing.module_id}\0${operation}`; let window = this.moduleTimingWindows.get(key); if (!window) { window = { moduleId: timing.module_id, operation, durationsMs: [], eventCount: 0, failureCount: 0, }; this.moduleTimingWindows.set(key, window); } window.durationsMs.push(timing.duration_ms); window.eventCount += timing.event_count; if (timing.outcome === 'rejected') window.failureCount += 1; } } private newFrameTimingWindow(): PerceptionFrameTimingWindow { return { startedAtMs: performance.now(), projectionMs: [], historyPrepareMs: [], workerQueueMs: [], workerRoundtripMs: [], moduleCpuSumMs: [], moduleCpuMaxMs: [], updateTotalMs: [], commitMs: [], totalMs: [], workerCountMax: 0, }; } private recordFrameTiming( sample: PerceptionFrameTimingSample, diagnostic: PerceptionDiagnostic | undefined, ): void { const window = this.frameTimingWindow; window.projectionMs.push(sample.projectionMs); window.historyPrepareMs.push(sample.historyPrepareMs); window.workerQueueMs.push(sample.workerQueueMs); window.workerRoundtripMs.push(sample.workerRoundtripMs); window.moduleCpuSumMs.push(sample.moduleCpuSumMs); window.moduleCpuMaxMs.push(sample.moduleCpuMaxMs); window.updateTotalMs.push(sample.updateTotalMs); window.commitMs.push(sample.commitMs); window.totalMs.push(sample.totalMs); window.workerCountMax = Math.max(window.workerCountMax, sample.workerCount); this.flushFrameTimingWindow(diagnostic); } private flushFrameTimingWindow( diagnostic: PerceptionDiagnostic | undefined, force = false, ): void { const window = this.frameTimingWindow; if (!diagnostic || window.totalMs.length === 0) return; const windowMs = Math.max(0, performance.now() - window.startedAtMs); if (!force && windowMs < PERCEPTION_MODULE_TIMING_WINDOW_MS) return; diagnostic('perception.frame.timing_window', { window_ms: Math.round(windowMs), count: window.totalMs.length, projection_avg_ms: roundedAverage(window.projectionMs), projection_p95_ms: percentile95(window.projectionMs), history_prepare_avg_ms: roundedAverage(window.historyPrepareMs), history_prepare_p95_ms: percentile95(window.historyPrepareMs), worker_queue_avg_ms: roundedAverage(window.workerQueueMs), worker_queue_p95_ms: percentile95(window.workerQueueMs), worker_roundtrip_avg_ms: roundedAverage(window.workerRoundtripMs), worker_roundtrip_p95_ms: percentile95(window.workerRoundtripMs), module_cpu_sum_avg_ms: roundedAverage(window.moduleCpuSumMs), module_cpu_sum_p95_ms: percentile95(window.moduleCpuSumMs), module_cpu_max_p95_ms: percentile95(window.moduleCpuMaxMs), update_total_avg_ms: roundedAverage(window.updateTotalMs), update_total_p95_ms: percentile95(window.updateTotalMs), commit_avg_ms: roundedAverage(window.commitMs), commit_p95_ms: percentile95(window.commitMs), total_avg_ms: roundedAverage(window.totalMs), total_p95_ms: percentile95(window.totalMs), total_max_ms: Math.max(...window.totalMs), worker_count_max: window.workerCountMax, }); this.frameTimingWindow = this.newFrameTimingWindow(); } private flushModuleTimingWindows( diagnostic: PerceptionDiagnostic | undefined, force = false, ): void { if (!diagnostic || this.moduleTimingWindows.size === 0) return; const now = performance.now(); const windowMs = Math.max(0, now - this.moduleTimingWindowStartedAt); if (!force && windowMs < PERCEPTION_MODULE_TIMING_WINDOW_MS) return; for (const window of this.moduleTimingWindows.values()) { diagnostic('perception.module.timing_window', { module_id: window.moduleId, operation: window.operation, window_ms: Math.round(windowMs), count: window.durationsMs.length, average_duration_ms: roundedAverage(window.durationsMs), p95_duration_ms: percentile95(window.durationsMs), max_duration_ms: Math.max(...window.durationsMs), failure_count: window.failureCount, event_count: window.eventCount, }); } this.moduleTimingWindows.clear(); this.moduleTimingWindowStartedAt = now; } private reportModuleFailures( operation: string, modules: readonly PerceptionModuleSlot[], results: readonly PromiseSettledResult[], diagnostic?: PerceptionDiagnostic, ): void { results.forEach((result, index) => { if (result.status === 'fulfilled' || !diagnostic) return; const moduleId = modules[index]!.manifest.id; this.reportModuleFailure( moduleId, operation, perceptionFailureDetails(result.reason), diagnostic, ); }); } private reportModuleFailure( moduleId: string, operation: string, details: Readonly<{ errorCode: string; messagePresent: boolean; messageLength?: number; }>, diagnostic?: PerceptionDiagnostic, ): void { if (!diagnostic) return; const now = Date.now(); const previous = this.moduleFailureReports.get(moduleId); const failureCount = (previous?.failureCount ?? 0) + 1; if (previous && now - previous.lastReportedAtMs < PERCEPTION_FAILURE_REPORT_WINDOW_MS) { this.moduleFailureReports.set(moduleId, { ...previous, failureCount, suppressedCount: previous.suppressedCount + 1, }); return; } diagnostic('perception.module.failed', { module_id: moduleId, operation, error_code: details.errorCode, error_message_present: details.messagePresent, error_message_length: details.messageLength, failure_count: failureCount, suppressed_failure_count: previous?.suppressedCount ?? 0, }, 'error'); this.moduleFailureReports.set(moduleId, { lastReportedAtMs: now, failureCount, suppressedCount: 0, }); } private startRunners( signal: AbortSignal, diagnostic?: PerceptionDiagnostic, ): Promise { signal.throwIfAborted(); if (this.runnersStarted) return Promise.resolve(); if (this.runnersStopTask) { const pending = [this.runnersStopTask, this.runnersStartTask].filter( (task): task is Promise => !!task, ); return Promise.allSettled(pending).then(() => { signal.throwIfAborted(); return this.startRunners(signal, diagnostic); }); } if (this.runnersStartTask) { if (this.runnersStartGeneration === this.runnerLifecycleGeneration) { return this.runnersStartTask; } return this.runnersStartTask.catch(() => {}).then(() => { signal.throwIfAborted(); return this.startRunners(signal, diagnostic); }); } const generation = ++this.runnerLifecycleGeneration; let task!: Promise; task = this.startRunnersInternal(signal, diagnostic, generation).finally(() => { if (this.runnersStartTask === task) this.runnersStartTask = undefined; }); this.runnersStartGeneration = generation; this.runnersStartTask = task; return task; } private async startRunnersInternal( signal: AbortSignal, diagnostic: PerceptionDiagnostic | undefined, generation: number, ): Promise { let analysisPool: PerceptionAnalysisThreadPool | undefined; try { const candidates = this.configuredModules; this.disabledModuleIds.clear(); for (const module of candidates) { module.analysisGeneration = 0; module.analysisHistoryFloorFrameSeq = 0; module.analysisBaselinePending = false; module.reducerReplayFromFrameSeq = undefined; } const startResults = await Promise.allSettled(candidates.map(({ runner }) => runner.start( CLAWCLAW_PERCEPTION_SPATIAL_FACTS satisfies PerceptionSpatialFacts, this.api, signal, diagnostic, ))); this.assertRunnerLifecycle(generation, signal); const startedModules = candidates.filter((module, index) => { const result = startResults[index]!; if (result.status === 'fulfilled') return true; this.reportModuleFailure( module.manifest.id, 'start', perceptionFailureDetails(result.reason), diagnostic, ); return false; }); await Promise.allSettled(candidates.flatMap((module, index) => ( startResults[index]?.status === 'rejected' ? [module.runner.stop('shutdown')] : [] ))); this.assertRunnerLifecycle(generation, signal); const parallelModules = startedModules.filter(({ runner }) => ( runner.execution === 'parallel_analysis' )); const threadSpecResults = await Promise.allSettled(parallelModules.map((module) => ( Promise.resolve().then(() => this.moduleLoader.threadSpec(module.source)) ))); this.assertRunnerLifecycle(generation, signal); let parallelCandidates: PerceptionParallelStartupCandidate[] = []; const threadSpecFailures: PerceptionModuleSlot[] = []; threadSpecResults.forEach((result, index) => { const module = parallelModules[index]!; if (result.status === 'fulfilled') { parallelCandidates.push({ module, threadModule: result.value }); return; } this.reportModuleFailure( module.manifest.id, 'worker_start', perceptionFailureDetails(result.reason), diagnostic, ); threadSpecFailures.push(module); }); await Promise.allSettled(threadSpecFailures.map(({ runner }) => runner.stop('shutdown'))); this.assertRunnerLifecycle(generation, signal); let usedSingletonPreflight = false; while (parallelCandidates.length > 0) { const currentPool = new PerceptionAnalysisThreadPool({ modules: parallelCandidates.map(({ threadModule }) => threadModule), loader: this.moduleLoader.threadConfig(), spatialFacts: CLAWCLAW_PERCEPTION_SPATIAL_FACTS satisfies PerceptionSpatialFacts, maxWorkers: Math.min(this.maxInFlight, Math.max(2, parallelCandidates.length)), maxPendingBatches: this.maxInFlight, fixedWorkers: true, diagnosticsEnabled: this.diagnosticsEnabled, diagnostic, }); analysisPool = currentPool; this.analysisPool = currentPool; try { await currentPool.start(); this.assertRunnerLifecycle(generation, signal); break; } catch (error) { await currentPool.stop(); if (this.analysisPool === currentPool) this.analysisPool = undefined; analysisPool = undefined; // A concurrent stop is a lifecycle cancellation, not a user-module // failure. Preserve that cancellation instead of reporting it as one. this.assertRunnerLifecycle(generation, signal); const failedModuleId = perceptionAnalysisWorkerStartModuleId(error); const failedIndex = failedModuleId ? parallelCandidates.findIndex(({ module }) => module.manifest.id === failedModuleId) : -1; if (failedIndex >= 0) { const [failed] = parallelCandidates.splice(failedIndex, 1); this.reportModuleFailure( failed!.module.manifest.id, 'worker_start', perceptionFailureDetails(error), diagnostic, ); await Promise.allSettled([failed!.module.runner.stop('shutdown')]); continue; } if (!usedSingletonPreflight) { usedSingletonPreflight = true; parallelCandidates = await this.preflightParallelStartupCandidates( parallelCandidates, signal, diagnostic, generation, ); // Retry the shared pool once even when every singleton succeeded: // the first unattributed failure may have been transient. continue; } for (const candidate of parallelCandidates) { this.reportModuleFailure( candidate.module.manifest.id, 'worker_start', perceptionFailureDetails(error), diagnostic, ); } await Promise.allSettled(parallelCandidates.map(({ module }) => ( module.runner.stop('shutdown') ))); parallelCandidates = []; } } const activeParallelIds = new Set( parallelCandidates.map(({ module }) => module.manifest.id), ); const activeModules = startedModules.filter(({ manifest, runner }) => ( runner.execution === 'ordered_update' || activeParallelIds.has(manifest.id) )); this.assertRunnerLifecycle(generation, signal); this.modules = activeModules; this.moduleTimingWindows.clear(); this.moduleTimingWindowStartedAt = performance.now(); await this.resetModules('replay', signal, diagnostic); this.assertRunnerLifecycle(generation, signal); this.resetProjection(); this.runnersStarted = true; } catch (error) { await analysisPool?.stop(); if (this.analysisPool === analysisPool) this.analysisPool = undefined; await Promise.allSettled(this.configuredModules.map(({ runner }) => runner.stop('shutdown'))); await this.reducerPool?.stop(); if (generation === this.runnerLifecycleGeneration) { await this.moduleLoader.stop(); this.modules = []; this.runnersStarted = false; } throw error; } } private async preflightParallelStartupCandidates( candidates: readonly PerceptionParallelStartupCandidate[], signal: AbortSignal, diagnostic: PerceptionDiagnostic | undefined, generation: number, ): Promise { const healthy: PerceptionParallelStartupCandidate[] = []; for (const candidate of candidates) { this.assertRunnerLifecycle(generation, signal); const pool = new PerceptionAnalysisThreadPool({ modules: [candidate.threadModule], loader: this.moduleLoader.threadConfig(), spatialFacts: CLAWCLAW_PERCEPTION_SPATIAL_FACTS satisfies PerceptionSpatialFacts, maxWorkers: 1, diagnosticsEnabled: this.diagnosticsEnabled, }); this.analysisPool = pool; let failure: unknown; let failed = false; try { await pool.start(); this.assertRunnerLifecycle(generation, signal); } catch (error) { failed = true; failure = error; } finally { await pool.stop().catch(() => {}); if (this.analysisPool === pool) this.analysisPool = undefined; } this.assertRunnerLifecycle(generation, signal); if (!failed) { healthy.push(candidate); continue; } this.reportModuleFailure( candidate.module.manifest.id, 'worker_start', perceptionFailureDetails(failure), diagnostic, ); await Promise.allSettled([candidate.module.runner.stop('shutdown')]); } return healthy; } private assertRunnerLifecycle(generation: number, signal: AbortSignal): void { signal.throwIfAborted(); if (generation !== this.runnerLifecycleGeneration) { throw new Error('perception_runners_start_cancelled'); } } private resetProjection(): void { this.projector.reset(); this.lifecyclePhase = null; this.lastFrameSeq = 0; this.lastFrameTimeMs = null; this.lastVisualTick = null; this.lastVisualFrame = null; this.lastConnectionId = null; this.analysisWindow.length = 0; this.projectedFrameCache.clear(); this.replayFromFrameSeq = null; } private checkpointValue(): PerceptionCheckpoint { const parallelModuleHistoryFloors = Object.fromEntries(this.modules.flatMap((module) => ( module.runner.execution === 'parallel_analysis' && module.analysisHistoryFloorFrameSeq > 0 ? [[module.manifest.id, module.analysisHistoryFloorFrameSeq] as const] : [] ))); const parallelModuleReducerReplayStarts = Object.fromEntries(this.modules.flatMap((module) => ( module.runner.execution === 'parallel_analysis' && module.reducerReplayFromFrameSeq !== undefined ? [[module.manifest.id, module.reducerReplayFromFrameSeq] as const] : [] ))); const parallelModuleBaselinePending = Object.fromEntries(this.modules.flatMap((module) => ( module.runner.execution === 'parallel_analysis' && ( module.analysisHistoryFloorFrameSeq > 0 || module.reducerReplayFromFrameSeq !== undefined ) ? [[module.manifest.id, module.analysisBaselinePending] as const] : [] ))); return { schema: PERCEPTION_CHECKPOINT_SCHEMA, replayFromFrameSeq: this.replayFromFrameSeq, ...(Object.keys(parallelModuleHistoryFloors).length === 0 ? {} : { parallelModuleHistoryFloors }), ...(Object.keys(parallelModuleReducerReplayStarts).length === 0 ? {} : { parallelModuleReducerReplayStarts }), ...(Object.keys(parallelModuleBaselinePending).length === 0 ? {} : { parallelModuleBaselinePending }), }; } private withOccurredAt( values: readonly RuntimeEventProposal[], timeMs: number | null, ): RuntimeEventProposal[] { const occurredAt = timeMs !== null && Number.isFinite(timeMs) ? new Date(timeMs).toISOString() : undefined; return values.map((proposal) => ( proposal.occurredAt || !occurredAt ? proposal : { ...proposal, occurredAt } )); } }