import { isNotificationTurn } from '../../notification-turn.js'; import type { ClawclawTrigger, TriggerInput, TriggerMatch, TriggerRearm, TriggerResetReason, } from '../../../../sdk/trigger-plugin/index.js'; import { MAX_TRIGGER_RUNTIME_MS, TRIGGER_PLUGIN_API_VERSION, } from '../../../../sdk/trigger-plugin/index.js'; import type { BehaviorInput, ObservationFrame, } from '../../../../sdk/module-input/index.js'; import type { RuntimeEpochPlugin, RuntimeEpochPluginContext, RuntimeEpochPluginInput, RuntimeEpochPluginResult, } from '../../../framework/plugins/contracts.js'; import { createBehaviorInput } from '../../behavior-input.js'; import { normalizeBehaviorInput } from '../../behavior-input-fields.js'; import { ClawclawBehaviorObservationMemory } from '../../behavior-observation-memory.js'; import { createBehaviorReadApi } from '../../behavior-read-api.js'; import { ObservationFrameProjector } from '../../observation-frame-projector.js'; import { CLAWCLAW_TRIGGER_PLUGIN_ID, type BehaviorReflexActivationDriver, type BehaviorReflexActivationRequest, type BehaviorReflexActivationResult, type ClawclawTriggerEvaluation, type ClawclawTriggerRegistration, } from './contracts.js'; import { TriggerModuleLoader } from './trigger-module-loader.js'; import type { ResolvedClawclawTriggerSource } from './trigger-source.js'; import { assertRuntimeModuleOutputSize } from '../../../framework/modules/runtime-module-output.js'; import { TriggerThreadPool } from './trigger-thread-pool.js'; import { ClawclawStrategyMemory } from '../../strategy-memory.js'; const TRIGGER_COMPUTATION_SCHEMA = 1; const TRIGGER_CHECKPOINT_SCHEMA = 1; export const DEFAULT_TRIGGER_PLUGIN_TIMEOUT_MS = 2_000; interface EffectiveTriggerConfig { readonly source: ResolvedClawclawTriggerSource; readonly enabled: boolean; readonly scope?: Readonly<{ sessionId: string; segmentId: string }>; readonly input: Readonly>; readonly behavior: string; readonly behaviorInput: Readonly>; readonly reflexPriority: number; readonly cooldownMs: number; readonly rearm: TriggerRearm; readonly maxRuntimeMs: number; } interface TriggerSlot { readonly config: EffectiveTriggerConfig; readonly module: ClawclawTrigger; } interface TriggerRuntimeState { armed: boolean; lastAcceptedAtMs?: number; } interface TriggerComputationProposal { readonly schema: typeof TRIGGER_COMPUTATION_SCHEMA; readonly configGeneration: number; readonly epochId: number; readonly nowMs: number; readonly eventCursor?: number; readonly evaluations: readonly ClawclawTriggerEvaluation[]; } interface TriggerCheckpoint { readonly schema: typeof TRIGGER_CHECKPOINT_SCHEMA; readonly states: Readonly>>; } export interface ClawclawTriggerPluginOptions { readonly memory?: ClawclawStrategyMemory; readonly after?: readonly string[]; readonly triggers?: readonly ClawclawTriggerRegistration[]; readonly loader?: TriggerModuleLoader; readonly driver?: BehaviorReflexActivationDriver; readonly diagnosticsEnabled?: boolean; /** Tests and embedded trusted hosts may retain the direct executor. */ readonly threaded?: boolean; } function record(value: unknown): Record | undefined { return value && typeof value === 'object' && !Array.isArray(value) ? value as Record : undefined; } function normalizeMatch(value: unknown): TriggerMatch | undefined { if (value === undefined) return undefined; const source = record(value); if (!source) throw new Error('trigger_match_invalid'); const allowed = new Set(['reason', 'evidence', 'behaviorInput']); for (const key of Object.keys(source)) { if (!allowed.has(key)) throw new Error(`trigger_match_field_unknown:${key}`); } if (typeof source.reason !== 'string' || !source.reason.trim()) { throw new Error('trigger_match_reason_invalid'); } if (source.evidence !== undefined && !record(source.evidence)) { throw new Error('trigger_match_evidence_invalid'); } if (source.behaviorInput !== undefined && !record(source.behaviorInput)) { throw new Error('trigger_match_behavior_input_invalid'); } const normalized = Object.freeze(structuredClone({ reason: source.reason.trim(), ...(source.evidence === undefined ? {} : { evidence: source.evidence }), ...(source.behaviorInput === undefined ? {} : { behaviorInput: source.behaviorInput }), })) as TriggerMatch; assertRuntimeModuleOutputSize(normalized, 'trigger_output'); return normalized; } function normalizeRegistration(value: ClawclawTriggerRegistration): EffectiveTriggerConfig { const { source } = value; const manifest = source.manifest; if (!source || source.id !== manifest.id) throw new Error('trigger_source_identity_invalid'); const input = value.enabled ? normalizeBehaviorInput(value.input ?? {}, manifest.inputs) : Object.freeze(structuredClone(value.input ?? {})); const behavior = value.behavior ?? manifest.defaultBehavior; const behaviorInput = { ...structuredClone(manifest.defaultBehaviorInput), ...structuredClone(value.behaviorInput ?? {}), }; const reflexPriority = value.reflexPriority ?? manifest.defaultReflexPriority; const cooldownMs = value.cooldownMs ?? manifest.defaultCooldownMs; const rearm = value.rearm ?? manifest.defaultRearm; const maxRuntimeMs = value.maxRuntimeMs ?? manifest.defaultMaxRuntimeMs; if (typeof behavior !== 'string' || !/^[a-z0-9][a-z0-9._-]*$/.test(behavior)) { throw new Error('trigger_behavior_invalid'); } if (!Number.isSafeInteger(reflexPriority)) throw new Error('trigger_reflex_priority_invalid'); if (!Number.isSafeInteger(cooldownMs) || cooldownMs < 0) throw new Error('trigger_cooldown_ms_invalid'); if (rearm !== 'after_clear' && rearm !== 'after_cooldown') throw new Error('trigger_rearm_invalid'); if ( !Number.isSafeInteger(maxRuntimeMs) || maxRuntimeMs <= 0 || maxRuntimeMs > MAX_TRIGGER_RUNTIME_MS ) { throw new Error('trigger_max_runtime_ms_invalid'); } return Object.freeze({ source, enabled: value.enabled, scope: value.scope, input, behavior, behaviorInput: Object.freeze(behaviorInput), reflexPriority, cooldownMs, rearm, maxRuntimeMs, }); } function normalizeRegistrations( values: readonly ClawclawTriggerRegistration[], ): Map { const result = new Map(); for (const value of values) { const normalized = normalizeRegistration(value); if (result.has(normalized.source.id)) { throw new Error(`trigger_registration_duplicate:${normalized.source.id}`); } result.set(normalized.source.id, normalized); } return result; } function proposal(value: unknown): TriggerComputationProposal { const parsed = record(value); if ( parsed?.schema !== TRIGGER_COMPUTATION_SCHEMA || !Number.isSafeInteger(parsed.configGeneration) || !Number.isSafeInteger(parsed.epochId) || typeof parsed.nowMs !== 'number' || !Array.isArray(parsed.evaluations) ) throw new Error('trigger_computation_invalid'); return parsed as unknown as TriggerComputationProposal; } function diagnosticErrorCode(error: unknown): string { const message = error instanceof Error ? error.message : String(error); return /^[a-z0-9_.:-]+$/i.test(message) ? message.slice(0, 160) : 'TRIGGER_MODULE_FAILED'; } function triggerInputFor( frame: Readonly, semanticInput: Readonly, config: EffectiveTriggerConfig, ): Readonly { const consumes = new Set(config.source.manifest.consumes); const events = consumes.has('*') ? semanticInput.events : semanticInput.events.filter((event) => consumes.has(event.type)); return Object.freeze({ frame, ...(semanticInput.cycle ? { cycle: semanticInput.cycle } : {}), events: Object.freeze(events), input: config.input, }); } function behaviorInputForTrigger( frame: Readonly, semanticInput: Readonly, triggerInput: Readonly, ): Readonly { return Object.freeze({ epochId: semanticInput.epochId, scope: semanticInput.scope, nowMs: semanticInput.nowMs, ...(semanticInput.cycle ? { cycle: semanticInput.cycle } : {}), gameState: frame.gameState, events: triggerInput.events, input: triggerInput.input, }); } function triggerLifecycle(frame: Readonly): string { const phase = frame.gameState.phase ?? 'unknown'; return phase === 'wandering' && frame.gameState.you?.is_alive === false ? 'dead' : phase; } /** * Compatibility host for previously installed standalone Trigger resources. Trigger and Perception project the same Source frame * independently and have no scheduler dependency on each other. Trigger * delegates at most one same-epoch Reflex request to the narrow Behavior * activation boundary. */ export class ClawclawTriggerPlugin implements RuntimeEpochPlugin> { readonly kind = 'epoch' as const; readonly id = CLAWCLAW_TRIGGER_PLUGIN_ID; readonly version = String(TRIGGER_PLUGIN_API_VERSION); readonly after: readonly string[]; readonly consumes = { events: ['*'] } as const; readonly catchUp = 'every_epoch' as const; get maxInFlight(): number { return this.threaded ? 10 : 1; } readonly maxPendingEpochs = 10; readonly backlogPolicy = 'finish_started' as const; readonly timeoutMs = DEFAULT_TRIGGER_PLUGIN_TIMEOUT_MS; readonly failurePolicy = 'failed_completion' as const; private registrations: Map; private readonly pendingActivations = new Map(); private readonly invalidInputs = new Map(); private readonly loader: TriggerModuleLoader; private readonly slots = new Map(); private readonly loadFailures = new Set(); private readonly states = new Map(); private readonly observationMemory = new ClawclawBehaviorObservationMemory(); private memory: ClawclawStrategyMemory; private readonly projector = new ObservationFrameProjector(); private readonly threaded: boolean; private readonly diagnosticsEnabled: boolean; private threadPool?: TriggerThreadPool; private threadPoolStartTask?: Promise; private threadPoolFailed = false; private pendingThreadResetReason?: TriggerResetReason; private driver?: BehaviorReflexActivationDriver; private configGeneration = 1; private currentScope?: Readonly<{ sessionId: string; segmentId: string }>; private isEnabled(config: EffectiveTriggerConfig): boolean { return config.enabled && (!config.scope || config.scope.sessionId === this.currentScope?.sessionId && config.scope.segmentId === this.currentScope?.segmentId); } private started = false; private lastFrameSeq = 0; private lastVisualTick: number | null = null; private lastConnectionId: string | null = null; private lifecyclePhase: string | null = null; constructor(options: ClawclawTriggerPluginOptions = {}) { this.memory = options.memory ?? new ClawclawStrategyMemory(); this.after = [...(options.after ?? [])]; this.registrations = normalizeRegistrations(options.triggers ?? []); this.loader = options.loader ?? new TriggerModuleLoader(); this.driver = options.driver; this.threaded = options.threaded ?? options.loader === undefined; this.diagnosticsEnabled = options.diagnosticsEnabled === true; } attachMemory(memory: ClawclawStrategyMemory): void { if (this.started) throw Error('strategy_memory_already_started'); this.memory = memory; } attachDriver(driver: BehaviorReflexActivationDriver): void { if (this.driver && this.driver !== driver) throw new Error('trigger_activation_driver_already_attached'); this.driver = driver; } configure(triggers: readonly ClawclawTriggerRegistration[]): void { const next = normalizeRegistrations(triggers); for (const [id, config] of next) { if (config.enabled && !this.registrations.get(id)?.enabled) { const state = this.states.get(id); if (state) state.armed = true; } } this.configGeneration += 1; this.registrations = next; this.pendingActivations.clear(); this.invalidInputs.clear(); this.slots.clear(); this.loadFailures.clear(); for (const id of this.states.keys()) if (!next.has(id)) this.states.delete(id); this.observationMemory.clear(); this.clearFrameBoundary(); void this.threadPool?.stop(); this.threadPool = undefined; this.threadPoolStartTask = undefined; this.threadPoolFailed = false; this.pendingThreadResetReason = undefined; this.loader.stop(); } descriptors(): readonly Readonly<{ id: string; enabled: boolean; armed: boolean; cooldownRemainingMs: number; behavior: string; reflexPriority: number; cooldownMs: number; rearm: TriggerRearm; maxRuntimeMs: number; }>[] { return [...this.registrations.values()].map((entry) => Object.freeze({ id: entry.source.id, enabled: this.isEnabled(entry), armed: this.states.get(entry.source.id)?.armed ?? true, cooldownRemainingMs: Math.max(0, entry.cooldownMs - (Date.now() - (this.states.get(entry.source.id)?.lastAcceptedAtMs ?? 0))), behavior: entry.behavior, reflexPriority: entry.reflexPriority, cooldownMs: entry.cooldownMs, rearm: entry.rearm, maxRuntimeMs: entry.maxRuntimeMs, })); } diagnosticSnapshot(): Readonly> { const pool = this.threadPool?.snapshot(); return Object.freeze({ threaded: this.threaded, configured_trigger_count: this.registrations.size, enabled_trigger_count: [...this.registrations.values()].filter(config => this.isEnabled(config)).length, active_trigger_count: this.threaded ? pool?.workerCount ?? 0 : this.slots.size, thread_pool_failed: this.threadPoolFailed, worker_pool: pool ? { state: pool.state, worker_count: pool.workerCount, busy_worker_count: pool.busyWorkerCount, queued_request_count: pool.queuedRequestCount, in_flight_request_count: pool.inFlightRequestCount, worker_heap_used_bytes: pool.workerHeapUsedBytes, peak_worker_heap_used_bytes: pool.peakWorkerHeapUsedBytes, } : null, }); } async start(context: RuntimeEpochPluginContext>): Promise { this.started = true; this.memory.open(context.scope); this.currentScope = context.scope; if (this.threaded) await this.ensureThreadPool(context); else await this.ensureModules(context); } recover(context: RuntimeEpochPluginContext>): void { const checkpoint = record(context.checkpoint()); if (checkpoint?.schema !== TRIGGER_CHECKPOINT_SCHEMA) return; const states = record(checkpoint.states); if (!states) return; for (const [triggerId, value] of Object.entries(states)) { if (!this.registrations.has(triggerId)) continue; const state = record(value); if (!state || typeof state.armed !== 'boolean') continue; if (state.lastAcceptedAtMs !== undefined && typeof state.lastAcceptedAtMs !== 'number') continue; this.states.set(triggerId, { armed: state.armed, ...(state.lastAcceptedAtMs === undefined ? {} : { lastAcceptedAtMs: state.lastAcceptedAtMs, }), }); } } async update( input: RuntimeEpochPluginInput>, context: RuntimeEpochPluginContext>, ): Promise { if (isNotificationTurn(input.epoch.state)) return { outcome: 'noop', reason: 'notification_only' }; this.currentScope = input.epoch.scope; // Keep the live configure/enable entry point, but do no observation or Worker work while empty. if (![...this.registrations.values()].some(config => this.isEnabled(config))) { return { outcome: 'noop', reason: 'no_enabled_triggers', proposal: { schema: TRIGGER_COMPUTATION_SCHEMA, configGeneration: this.configGeneration, epochId: input.epoch.epochSeq, nowMs: input.frame.observedAtMs ?? input.frame.receivedAtMs, ...(input.pendingEvents.length ? { eventCursor: input.pendingEvents.at(-1)!.commitSeq } : {}), evaluations: [], } satisfies TriggerComputationProposal }; } if (this.threaded) return this.updateThreaded(input, context); await this.ensureModules(context); const generation = this.configGeneration; const eventCursor = input.pendingEvents.at(-1)?.commitSeq; // Trigger observes only backend-pushed Events. Every Epoch Plugin output, // including DerivedEvent, Perception, and Behavior, is local_synth and is // excluded so rule evaluation has no hidden computation-plugin dependency. const triggerVisibleInput = { ...input, pendingEvents: input.pendingEvents.filter((event) => event.producer === 'backend_push' && !event.notificationOf && event.producerPluginId === undefined), } satisfies RuntimeEpochPluginInput>; const emptyInput = createBehaviorInput(triggerVisibleInput, Object.freeze({})); if ( !emptyInput || emptyInput.gameState.phase !== 'wandering' || emptyInput.gameState.you?.is_alive === false ) { if (this.lastVisualTick !== null) { await this.requestModuleReset('phase_changed', context); this.clearFrameBoundary(); } return { outcome: 'processed', reason: 'trigger_ineligible_state', proposal: { schema: TRIGGER_COMPUTATION_SCHEMA, configGeneration: generation, epochId: input.epoch.epochSeq, nowMs: input.frame.observedAtMs ?? input.frame.receivedAtMs, ...(eventCursor === undefined ? {} : { eventCursor }), evaluations: [], } satisfies TriggerComputationProposal, }; } const projected = this.projector.project(input.frame); if (!projected) { if (this.lastVisualTick !== null) { await this.requestModuleReset('trajectory_gap', context); this.clearFrameBoundary(); } return { outcome: 'processed', reason: 'trigger_observation_unavailable', proposal: { schema: TRIGGER_COMPUTATION_SCHEMA, configGeneration: generation, epochId: input.epoch.epochSeq, nowMs: emptyInput.nowMs, ...(eventCursor === undefined ? {} : { eventCursor }), evaluations: [], } satisfies TriggerComputationProposal, }; } const stateFrameGap = this.lastFrameSeq > 0 && input.frame.frameSeq > this.lastFrameSeq + 1; const tickDelta = this.lastVisualTick === null ? null : projected.tick - this.lastVisualTick; const lifecycle = triggerLifecycle(projected); const phaseChanged = this.lifecyclePhase !== null && this.lifecyclePhase !== lifecycle; const continuousFromPrevious = !stateFrameGap && !phaseChanged && tickDelta !== null && tickDelta >= 0 && tickDelta <= 3 && this.lastConnectionId === input.frame.connectionId; const frame: Readonly = Object.freeze({ ...projected, tickDelta, continuousFromPrevious, }); const gap = this.lastVisualTick !== null && !phaseChanged && !continuousFromPrevious; if (gap || phaseChanged) { await this.requestModuleReset(gap ? 'trajectory_gap' : 'phase_changed', context); } this.lastFrameSeq = input.frame.frameSeq; this.lastVisualTick = frame.tick; this.lastConnectionId = input.frame.connectionId; this.lifecyclePhase = lifecycle; const observationSnapshot = this.observationMemory.capture(emptyInput); const evaluators = [...this.slots.values()].filter(entry => this.isEnabled(entry.config)).sort((left, right) => ( left.config.source.id.localeCompare(right.config.source.id) )); const evaluationsPending = evaluators.map(async (evaluator): Promise => { const { config } = evaluator; const triggerInput = triggerInputFor(frame, emptyInput, config); const readInput = behaviorInputForTrigger(frame, emptyInput, triggerInput); const isActive = (): boolean => ( generation === this.configGeneration && this.slots.get(config.source.id) === evaluator ); try { const value = await evaluator.module.evaluate( triggerInput, createBehaviorReadApi(readInput, { isActive, observationSnapshot, memory: this.memory.bind(readInput.scope, this.memoryNamespace(config.source), () => isActive() && !context.signal.aborted && this.started) }), ); if (!isActive()) return { triggerId: config.source.id, outcome: 'error' }; const match = normalizeMatch(value); return match ? { triggerId: config.source.id, outcome: 'match', match } : { triggerId: config.source.id, outcome: 'clear' }; } catch (error) { context.diagnostic('trigger.module.failed', { trigger_id: config.source.id, operation: 'evaluate', error_code: diagnosticErrorCode(error), }, 'error'); return { triggerId: config.source.id, outcome: 'error' }; } }); const settled = await Promise.allSettled(evaluationsPending); const evaluations = settled.map((result, index): ClawclawTriggerEvaluation => { if (result.status === 'fulfilled') return result.value; const triggerId = evaluators[index]!.config.source.id; context.diagnostic('trigger.module.failed', { trigger_id: triggerId, operation: 'evaluate', error_code: diagnosticErrorCode(result.reason), }, 'error'); return { triggerId, outcome: 'error' }; }); return { outcome: 'processed', reason: evaluations.some((entry) => entry.outcome === 'match') ? 'trigger_match_computed' : 'trigger_no_match', proposal: { schema: TRIGGER_COMPUTATION_SCHEMA, configGeneration: generation, epochId: input.epoch.epochSeq, nowMs: frame.timeMs, ...(eventCursor === undefined ? {} : { eventCursor }), evaluations, } satisfies TriggerComputationProposal, }; } private async updateThreaded( input: RuntimeEpochPluginInput>, context: RuntimeEpochPluginContext>, ): Promise { await this.ensureThreadPool(context); const generation = this.configGeneration; const eventCursor = input.pendingEvents.at(-1)?.commitSeq; const triggerVisibleInput = { ...input, pendingEvents: input.pendingEvents.filter((event) => event.producer === 'backend_push' && !event.notificationOf && event.producerPluginId === undefined), } satisfies RuntimeEpochPluginInput>; const emptyInput = createBehaviorInput(triggerVisibleInput, Object.freeze({})); const baseProposal = (nowMs: number, evaluations: readonly ClawclawTriggerEvaluation[]) => ({ schema: TRIGGER_COMPUTATION_SCHEMA, configGeneration: generation, epochId: input.epoch.epochSeq, nowMs, ...(eventCursor === undefined ? {} : { eventCursor }), evaluations, } satisfies TriggerComputationProposal); if ( !emptyInput || emptyInput.gameState.phase !== 'wandering' || emptyInput.gameState.you?.is_alive === false ) { return { outcome: 'processed', reason: 'trigger_ineligible_state', proposal: baseProposal( input.frame.observedAtMs ?? input.frame.receivedAtMs, [], ), }; } const projected = this.projector.project(input.frame); if (!projected) { return { outcome: 'processed', reason: 'trigger_observation_unavailable', proposal: baseProposal(emptyInput.nowMs, []), }; } const previousStored = context.stateHistory.queryStateFrames({ scope: context.scope, toEpochSeq: input.epoch.epochSeq - 1, order: 'desc', limit: 1, }).frames[0]; const previous = previousStored ? this.projector.project(previousStored) : null; const tickDelta = previous ? projected.tick - previous.tick : null; const phaseChanged = !!previous && triggerLifecycle(previous) !== triggerLifecycle(projected); const continuousFromPrevious = !!previous && !!previousStored && previousStored.frameSeq + 1 === input.frame.frameSeq && previousStored.connectionId === input.frame.connectionId && !phaseChanged && tickDelta !== null && tickDelta >= 0 && tickDelta <= 3; const frame: Readonly = Object.freeze({ ...projected, tickDelta, continuousFromPrevious, }); const resetReason: TriggerResetReason | undefined = phaseChanged ? 'phase_changed' : previousStored && !continuousFromPrevious ? 'trajectory_gap' : undefined; const configs = [...this.registrations.values()] .filter(config => this.isEnabled(config)) .sort((left, right) => left.source.id.localeCompare(right.source.id)); const settled = await Promise.allSettled(configs.map(async (config): Promise => { const triggerInput = triggerInputFor(frame, emptyInput, config); const readInput = behaviorInputForTrigger(frame, emptyInput, triggerInput); try { if (!this.threadPool) throw new Error('trigger_thread_pool_unavailable'); const value = await this.threadPool.evaluate({ epochId: input.epoch.epochSeq, triggerId: config.source.id, input: triggerInput, readInput, ...(resetReason === undefined ? {} : { resetReason }), }, context.signal); const match = normalizeMatch(value); return match ? { triggerId: config.source.id, outcome: 'match', match } : { triggerId: config.source.id, outcome: 'clear' }; } catch (error) { context.diagnostic('trigger.module.failed', { trigger_id: config.source.id, operation: 'evaluate', error_code: diagnosticErrorCode(error), }, context.signal.aborted ? 'debug' : 'error'); return { triggerId: config.source.id, outcome: 'error' }; } })); const evaluations = settled.map((result, index): ClawclawTriggerEvaluation => { if (result.status === 'fulfilled') return result.value; const triggerId = configs[index]!.source.id; context.diagnostic('trigger.module.failed', { trigger_id: triggerId, operation: 'evaluate', error_code: diagnosticErrorCode(result.reason), }, context.signal.aborted ? 'debug' : 'error'); return { triggerId, outcome: 'error' }; }); return { outcome: 'processed', reason: evaluations.some((entry) => entry.outcome === 'match') ? 'trigger_match_computed' : 'trigger_no_match', proposal: baseProposal(frame.timeMs, evaluations), }; } async commit( input: RuntimeEpochPluginInput>, computation: Readonly, context: RuntimeEpochPluginContext>, ): Promise { if (isNotificationTurn(input.epoch.state)) return computation; const computed = proposal(computation.proposal); if (computed.configGeneration !== this.configGeneration) { return { outcome: 'noop', reason: 'trigger_config_superseded', checkpoint: this.checkpoint(), }; } for (const evaluation of computed.evaluations) { if (evaluation.outcome !== 'clear') continue; this.invalidInputs.delete(evaluation.triggerId); const config = this.registrations.get(evaluation.triggerId); if (config?.rearm !== 'after_clear') continue; const state = this.stateFor(evaluation.triggerId); state.armed = true; } const candidates = computed.evaluations.flatMap((evaluation) => { if (evaluation.outcome !== 'match' || !evaluation.match) return []; const config = this.registrations.get(evaluation.triggerId); if (!config || !this.isEnabled(config) || this.pendingActivations.has(evaluation.triggerId)) return []; const behaviorInput = { ...config.behaviorInput, ...evaluation.match.behaviorInput }; const inputKey = JSON.stringify(behaviorInput); if (this.invalidInputs.get(evaluation.triggerId) === inputKey) return []; const state = this.stateFor(evaluation.triggerId); if (config.rearm === 'after_clear' && !state.armed) return []; if ( state.lastAcceptedAtMs !== undefined && computed.nowMs - state.lastAcceptedAtMs < config.cooldownMs ) return []; return [{ config, match: evaluation.match, behaviorInput, inputKey }]; }).sort((left, right) => { if (left.config.reflexPriority !== right.config.reflexPriority) { return left.config.reflexPriority > right.config.reflexPriority ? -1 : 1; } return left.config.source.id.localeCompare(right.config.source.id); }); let activationResult: BehaviorReflexActivationResult | undefined; const selected = candidates[0]; if (selected) { const request: BehaviorReflexActivationRequest = Object.freeze({ source: 'trigger', triggerId: selected.config.source.id, scope: Object.freeze({ sessionId: input.epoch.scope.sessionId, segmentId: input.epoch.scope.segmentId, }), epochId: computed.epochId, configGeneration: computed.configGeneration, behavior: selected.config.behavior, behaviorInput: Object.freeze(structuredClone(selected.behaviorInput)), reflexPriority: selected.config.reflexPriority, maxRuntimeMs: selected.config.maxRuntimeMs, reason: selected.match.reason, ...(selected.match.evidence === undefined ? {} : { evidence: structuredClone(selected.match.evidence), }), }); if (!this.driver) { activationResult = { accepted: false, reason: 'activation_driver_unavailable' }; context.diagnostic('trigger.activation.rejected', { trigger_id: request.triggerId, reason: activationResult.reason, }, 'error'); } else { try { activationResult = await this.driver.requestReflex(request, { isCurrent: () => computed.configGeneration === this.configGeneration, }); } catch (error) { activationResult = { accepted: false, reason: 'activation_driver_failed' }; context.diagnostic('trigger.activation.rejected', { trigger_id: request.triggerId, reason: activationResult.reason, error_code: diagnosticErrorCode(error), }, 'error'); } } if (activationResult.accepted) { const accept = () => { const state = this.stateFor(request.triggerId); state.lastAcceptedAtMs = computed.nowMs; if (selected.config.rearm === 'after_clear') state.armed = false; }; if (activationResult.ready) { const activationId = activationResult.activationId; this.pendingActivations.set(request.triggerId, activationId); void activationResult.ready.then(outcome => { if (this.pendingActivations.get(request.triggerId) !== activationId) return; this.pendingActivations.delete(request.triggerId); if (outcome === 'ready') accept(); if (outcome === 'invalid') this.invalidInputs.set(request.triggerId, selected.inputKey); }); } else { accept(); } context.diagnostic('trigger.activation.accepted', { trigger_id: request.triggerId, behavior_id: request.behavior, activation_id: activationResult.activationId, reflex_priority: request.reflexPriority, ...(activationResult.replacedActivationId === undefined ? {} : { replaced_activation_id: activationResult.replacedActivationId, }), }); } else { if (activationResult.reason === 'binding_invalid') this.invalidInputs.set(request.triggerId, selected.inputKey); context.diagnostic('trigger.activation.rejected', { trigger_id: request.triggerId, behavior_id: request.behavior, reason: activationResult.reason, reflex_priority: request.reflexPriority, }); } } return { outcome: activationResult?.accepted ? 'processed' : 'noop', reason: activationResult?.accepted ? 'trigger_activation_accepted' : selected ? `trigger_activation_rejected:${activationResult?.reason ?? 'unknown'}` : 'trigger_no_eligible_match', checkpoint: this.checkpoint(), // Earlier ordered commits may have consumed a newer watermark while this // computation was in flight. Never move the consumption cursor backwards. ...(computed.eventCursor === undefined || computed.eventCursor <= context.progress().eventCursor ? {} : { consumeEventsThroughCommitSeq: computed.eventCursor, }), }; } async stop(reason: 'segment_ending' | 'shutdown'): Promise { this.started = false; if (this.currentScope) this.memory.close(this.currentScope); if (this.threaded) await this.threadPool?.stop(); else await this.resetModules(reason, undefined); this.started = false; this.configGeneration += 1; this.slots.clear(); this.loadFailures.clear(); this.states.clear(); this.pendingActivations.clear(); this.invalidInputs.clear(); this.observationMemory.clear(); this.clearFrameBoundary(); this.threadPool = undefined; this.threadPoolStartTask = undefined; this.threadPoolFailed = false; this.pendingThreadResetReason = undefined; this.loader.stop(); } private memoryNamespace(source: ResolvedClawclawTriggerSource): string { return 'trigger:' + source.id; } private async ensureThreadPool( context: RuntimeEpochPluginContext>, ): Promise { if (!this.started || this.threadPool || this.threadPoolFailed) return; if (this.threadPoolStartTask) return this.threadPoolStartTask; const generation = this.configGeneration; let task!: Promise; task = this.startThreadPool(context, generation).finally(() => { if (this.threadPoolStartTask === task) this.threadPoolStartTask = undefined; }); this.threadPoolStartTask = task; return task; } private async startThreadPool( context: RuntimeEpochPluginContext>, generation: number, ): Promise { const enabled = [...this.registrations.values()].filter(config => this.isEnabled(config)); if (enabled.length === 0) return; let pool: TriggerThreadPool | undefined; try { pool = new TriggerThreadPool({ memory: (evaluation, active) => { const source = this.registrations.get(evaluation.triggerId)?.source; if (!source) throw Error('strategy_memory_inactive'); return this.memory.bind(evaluation.readInput.scope, this.memoryNamespace(source), () => active() && this.started && generation === this.configGeneration); }, modules: enabled.map(({ source }) => this.loader.threadSpec(source)), loader: this.loader.threadConfig(), diagnosticsEnabled: this.diagnosticsEnabled, diagnostic: context.diagnostic, }); await pool.start(); if (!this.started || generation !== this.configGeneration) { await pool.stop(); return; } this.threadPool = pool; } catch (error) { if (!this.started || generation !== this.configGeneration) { await pool?.stop().catch(() => {}); return; } this.threadPoolFailed = true; await pool?.stop().catch(() => {}); for (const config of enabled) { context.diagnostic('trigger.module.failed', { trigger_id: config.source.id, operation: 'worker_start', error_code: diagnosticErrorCode(error), }, 'error'); } } } private async requestModuleReset( reason: TriggerResetReason, context: RuntimeEpochPluginContext>, ): Promise { if (this.threaded) { this.pendingThreadResetReason = reason; return; } await this.resetModules(reason, context); } private async ensureModules(context: RuntimeEpochPluginContext>): Promise { if (!this.started) return; const enabled = [...this.registrations.values()].filter(config => this.isEnabled(config)); await Promise.all(enabled.map(async (config) => { const id = config.source.id; if (this.slots.has(id) || this.loadFailures.has(id)) return; try { const ModuleClass = await this.loader.load(config.source); if (!this.started || this.registrations.get(id) !== config) return; this.slots.set(id, { config, module: new ModuleClass() }); } catch (error) { if (!this.started || this.registrations.get(id) !== config) return; this.loadFailures.add(id); context.diagnostic('trigger.module.failed', { trigger_id: id, operation: 'load', error_code: diagnosticErrorCode(error), }, 'error'); } })); } private stateFor(triggerId: string): TriggerRuntimeState { let state = this.states.get(triggerId); if (!state) { state = { armed: true }; this.states.set(triggerId, state); } return state; } private async resetModules( reason: TriggerResetReason, context: RuntimeEpochPluginContext> | undefined, ): Promise { await Promise.all([...this.slots.values()].map(async (slot) => { if (!slot.module.reset) return; try { await slot.module.reset(reason); } catch (error) { context?.diagnostic('trigger.module.failed', { trigger_id: slot.config.source.id, operation: 'reset', error_code: diagnosticErrorCode(error), }, 'error'); } })); } private clearFrameBoundary(): void { this.projector.reset(); this.lastFrameSeq = 0; this.lastVisualTick = null; this.lastConnectionId = null; this.lifecyclePhase = null; } private checkpoint(): TriggerCheckpoint { return { schema: TRIGGER_CHECKPOINT_SCHEMA, states: Object.fromEntries([...this.states].map(([id, state]) => [id, { ...state }])), }; } }