import type { RuntimeEventProposal, RuntimeSourceEvent } from '../../../framework/plugins/index.js'; import type { StoredStateFrame } from '../../../framework/state/index.js'; import type { PlayerProjection } from '../../../../pipeline/player-projection.js'; import { CLAWCLAW_GAME_STREAM_BACKEND_EVENT_TYPES } from '../../../clawclaw-event-catalog.js'; import { clawclawComputationGameState, isClawclawRuntimeState } from '../../runtime-state.js'; import type { ClawclawDerivedEventRule } from './derived-event-rules.js'; import { nextPlayerProjection, type PlayerSnapshot } from './player-change-tracker.js'; import { nextTaskProjection, type TaskSnapshot } from './task-change-tracker.js'; /** Adapt validated canonical Source facts to the existing player projection's PlayerRef inputs. */ function trackerFacts(events: readonly RuntimeSourceEvent[]): Array> { return events.filter(event => event.producer !== 'local_synth').map(event => { const value: Record = { ...event.payload, type: event.type }; for (const [field, name, seat] of [ ['actor','actor_name','actor_seat'], ['target','target_name','target_seat'], ['caller','meeting_caller_name','meeting_caller_seat'], ['resolver','resolver_name','resolver_seat'], ['current_speaker','current_speaker','current_speaker_seat'], ['result_target','result_target','result_target_seat'], ]) { if (typeof value[name] === 'string' && Number.isInteger(value[seat])) { value[field] = { name: value[name], seat: value[seat] }; } } if (value.killer_kind === 'player' && typeof value.killer_name === 'string' && Number.isInteger(value.killer_seat)) { value.killer = { kind: 'player', player: { name: value.killer_name, seat: value.killer_seat } }; } else if (value.killer_kind === 'system' && typeof value.killer_name === 'string') { value.killer = { kind: 'system', name: value.killer_name }; } return value; }); } function gameState(frame: StoredStateFrame>): Record | null { const game = clawclawComputationGameState(frame.state); if (!game) return null; return { ...game, ...(frame.backendTick === undefined ? {} : { tick: frame.backendTick }) }; } function proposal(type: string, frame: StoredStateFrame>, payload: Record, sourceEvents: readonly RuntimeSourceEvent[]): RuntimeEventProposal[] { // An open epoch written by the previous Source implementation may already contain this fact. // Rebuild rule state, but keep its original Source identity and delivery instead of publishing it twice. if (sourceEvents.some(event => event.type === type && event.producer === 'local_synth')) return []; return [{ type, payload, dedupeKey: `${type}:${frame.sourceKey}`, dedupeScope: 'segment', occurredAt: new Date(frame.observedAtMs ?? frame.receivedAtMs).toISOString() }]; } export class PlayerChangesDerivedEventRule implements ClawclawDerivedEventRule { save() { return { initialized: this.initialized, projection: structuredClone(this.projection), snapshots: structuredClone(this.snapshots) }; } restore(state: any) { if (!state) return; this.initialized = state.initialized; this.projection = structuredClone(state.projection); this.snapshots = structuredClone(state.snapshots); } readonly id = 'player-changes'; readonly eventTypes = ['players_changed'] as const; readonly consumes = [...CLAWCLAW_GAME_STREAM_BACKEND_EVENT_TYPES, 'players_changed']; private initialized = false; private projection: PlayerProjection[] = []; private snapshots: PlayerSnapshot[] = []; reset(): void { this.initialized = false; this.projection = []; this.snapshots = []; } inspect(frame: StoredStateFrame>, events: readonly RuntimeSourceEvent[] = []): RuntimeEventProposal[] { const game = gameState(frame); if (!game) return []; const update = nextPlayerProjection({ previous: this.projection, previousSnapshots: this.snapshots, initialized: this.initialized, summary: game, events: trackerFacts(events), selfName: game.you?.player?.name ?? game.you?.name }); this.projection = update.projection; this.snapshots = update.snapshots; this.initialized = true; return update.payload ? proposal('players_changed', frame, update.payload, events) : []; } } export class TaskChangesDerivedEventRule implements ClawclawDerivedEventRule { readonly id = 'task-changes'; readonly eventTypes = ['tasks_changed'] as const; readonly consumes = [...CLAWCLAW_GAME_STREAM_BACKEND_EVENT_TYPES, 'tasks_changed']; private initialized = false; private projection: TaskSnapshot[] = []; reset(): void { this.initialized = false; this.projection = []; } inspect(frame: StoredStateFrame>, events: readonly RuntimeSourceEvent[] = []): RuntimeEventProposal[] { const game = gameState(frame); if (!game) return []; const state = frame.state; const update = nextTaskProjection({ previous: this.projection, initialized: this.initialized, summary: game, events: trackerFacts(events), selfName: game.you?.player?.name ?? game.you?.name, allowUntickedInitialRole: isClawclawRuntimeState(state) && (state.game_snapshot.status === 'fresh' || state.game_snapshot.status === 'cached') && state.game_snapshot.origin === 'update' }); this.projection = update.projection; this.initialized = update.initialized; return update.payload ? proposal('tasks_changed', frame, update.payload, events) : []; } }