import type { RuntimeEpochPlugin, RuntimeEpochPluginContext, RuntimeEpochPluginInput, RuntimeEpochPluginResult, RuntimeEventProposal, RuntimeSourceEvent } from '../../../framework/plugins/index.js'; import type { StoredStateFrame } from '../../../framework/state/index.js'; import type { ClawclawDerivedEventRule } from '../derived-event/derived-event-rules.js'; export class PerceptionRuleRunner implements RuntimeEpochPlugin> { readonly kind = 'epoch' as const; readonly id: string; readonly version = '2'; readonly produces: { events: readonly string[] }; readonly consumes: { events: readonly string[] }; // Never skip a computation boundary. Fixed-cadence boundaries may contain multiple Source inputs. readonly catchUp = 'strict_ordered' as const; readonly timeoutMs = 1_000; private readonly rules: ClawclawDerivedEventRule[]; private lastFrameSeq = 0; constructor(id: string, rules: readonly ClawclawDerivedEventRule[]) { this.id = id; this.rules = [...rules].sort((left, right) => left.id.localeCompare(right.id)); this.produces = { events: [...new Set(this.rules.flatMap(rule => rule.eventTypes))].sort() }; this.consumes = { events: [...new Set(this.rules.flatMap(rule => rule.consumes ?? []))].sort() }; } start(): void { this.reset(); } recover(context: RuntimeEpochPluginContext>): void { const completedThrough = context.progress().completedThroughEpochSeq; if (completedThrough <= 0) return; if (context.processingIntervalMs !== undefined) { const frame = context.stateHistory.queryStateFrames({ scope: context.scope, toEpochSeq: completedThrough, order: 'desc', limit: 1 }).frames[0]; if (frame) { const sourceEpoch = frame.state.cycle?.stateVersion ?? frame.epochSeq; this.inspectFrame(frame, sourceEpoch ? context.sourceEventsAt?.(sourceEpoch) ?? [] : []); } return; } this.scanHistory(context, completedThrough, false); } update( input: RuntimeEpochPluginInput>, context: RuntimeEpochPluginContext>, ): RuntimeEpochPluginResult { const facts = input.pendingEvents.filter(event => !event.producerPluginId && !event.notificationOf) .map(event => ({ type: event.type, payload: event.payload, producer: event.producer, sourceEventId: event.sourceEventId, sourceSeq: event.sourceSequence, observedAt: event.occurredAt, receivedAt: event.receivedAt, replayed: event.replayed })); const events = context.processingIntervalMs !== undefined ? this.inspectFrame(input.frame, facts) : this.scanHistory(context, input.epoch.epochSeq, true, input.frame.frameSeq, input); return { ...(events.length > 0 ? { outcome: 'processed' as const, events } : { outcome: 'noop' as const, reason: 'no_derived_event' }), ...(input.pendingEvents.length ? {consumeEventsThroughCommitSeq: input.pendingEvents.at(-1)!.commitSeq} : {}) }; } stop(): void { this.reset(); } private scanHistory( context: RuntimeEpochPluginContext>, throughEpochSeq: number, collect: boolean, throughFrameSeq?: number, currentInput?: RuntimeEpochPluginInput>, ): RuntimeEventProposal[] { if (this.rules.length === 0) return []; const proposals: RuntimeEventProposal[] = []; let afterFrameSeq = this.lastFrameSeq; while (true) { const page = context.stateHistory.queryStateFrames({ scope: context.scope, afterFrameSeq, toEpochSeq: throughEpochSeq, ...(throughFrameSeq === undefined ? {} : { beforeFrameSeq: throughFrameSeq + 1 }), order: 'asc', limit: 500, }); if (page.frames.length === 0) break; for (const frame of page.frames) { const facts = frame.epochSeq === undefined ? [] : context.sourceEventsAt?.(frame.epochSeq) ?? (frame.epochSeq === currentInput?.epoch.epochSeq ? currentInput.epoch.events : []); const frameEvents = this.inspectFrame(frame, facts); if (collect) proposals.push(...frameEvents); afterFrameSeq = frame.frameSeq; } if (!page.page.hasMore) break; } return proposals; } private inspectFrame(frame: StoredStateFrame>, facts: readonly RuntimeSourceEvent[]): RuntimeEventProposal[] { if (frame.frameSeq <= this.lastFrameSeq) return []; this.lastFrameSeq = frame.frameSeq; return this.rules.flatMap((rule) => rule.inspect(frame, facts)); } private reset(): void { this.lastFrameSeq = 0; for (const rule of this.rules) rule.reset(); } }