@myclaw163/game-agent-runtime 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (204) hide show
  1. package/README.md +67 -2
  2. package/dist/framework/action-diagnostics.d.ts +11 -0
  3. package/dist/framework/action-diagnostics.js +67 -0
  4. package/dist/framework/capability-registry.d.ts +58 -0
  5. package/dist/framework/capability-registry.js +325 -0
  6. package/dist/framework/contracts.d.ts +121 -0
  7. package/dist/framework/contracts.js +2 -0
  8. package/dist/framework/control/control-scheduler.d.ts +69 -0
  9. package/dist/framework/control/control-scheduler.js +1016 -0
  10. package/dist/framework/control/domain-set.d.ts +18 -0
  11. package/dist/framework/control/domain-set.js +70 -0
  12. package/dist/framework/control/index.d.ts +3 -0
  13. package/dist/framework/control/index.js +3 -0
  14. package/dist/framework/control/types.d.ts +142 -0
  15. package/dist/framework/control/types.js +13 -0
  16. package/dist/framework/control-coordinator.d.ts +7 -0
  17. package/dist/framework/control-coordinator.js +7 -0
  18. package/dist/framework/events/event-catalog.d.ts +23 -0
  19. package/dist/framework/events/event-catalog.js +52 -0
  20. package/dist/framework/events/event-delivery-service.d.ts +33 -0
  21. package/dist/framework/events/event-delivery-service.js +165 -0
  22. package/dist/framework/events/event-ingress.d.ts +28 -0
  23. package/dist/framework/events/event-ingress.js +76 -0
  24. package/dist/framework/events/event-repository.d.ts +38 -0
  25. package/dist/framework/events/event-repository.js +20 -0
  26. package/dist/framework/events/index.d.ts +7 -0
  27. package/dist/framework/events/index.js +7 -0
  28. package/dist/framework/events/memory-event-repository.d.ts +77 -0
  29. package/dist/framework/events/memory-event-repository.js +909 -0
  30. package/dist/framework/events/runtime-resume.d.ts +11 -0
  31. package/dist/framework/events/runtime-resume.js +7 -0
  32. package/dist/framework/events/sqlite-event-repository.d.ts +94 -0
  33. package/dist/framework/events/sqlite-event-repository.js +2044 -0
  34. package/dist/framework/events/store-compatibility.d.ts +17 -0
  35. package/dist/framework/events/store-compatibility.js +17 -0
  36. package/dist/framework/events/types.d.ts +242 -0
  37. package/dist/framework/events/types.js +39 -0
  38. package/dist/framework/index.d.ts +7 -0
  39. package/dist/framework/index.js +7 -0
  40. package/dist/framework/load-node-sqlite.d.ts +5 -0
  41. package/dist/framework/load-node-sqlite.js +19 -0
  42. package/dist/framework/mailbox/coalescer.d.ts +30 -0
  43. package/dist/framework/mailbox/coalescer.js +45 -0
  44. package/dist/framework/mailbox/host-notification-sink.d.ts +31 -0
  45. package/dist/framework/mailbox/host-notification-sink.js +13 -0
  46. package/dist/framework/mailbox/identity.d.ts +15 -0
  47. package/dist/framework/mailbox/identity.js +28 -0
  48. package/dist/framework/mailbox/index.d.ts +7 -0
  49. package/dist/framework/mailbox/index.js +7 -0
  50. package/dist/framework/mailbox/mailbox-dispatcher.d.ts +65 -0
  51. package/dist/framework/mailbox/mailbox-dispatcher.js +242 -0
  52. package/dist/framework/mailbox/mailbox-repository.d.ts +17 -0
  53. package/dist/framework/mailbox/mailbox-repository.js +9 -0
  54. package/dist/framework/mailbox/notification-projector.d.ts +25 -0
  55. package/dist/framework/mailbox/notification-projector.js +50 -0
  56. package/dist/framework/mailbox/types.d.ts +128 -0
  57. package/dist/framework/mailbox/types.js +1 -0
  58. package/dist/framework/modules/runtime-module-loader-hooks.mjs +156 -0
  59. package/dist/framework/modules/runtime-module-loader.d.ts +14 -0
  60. package/dist/framework/modules/runtime-module-loader.js +64 -0
  61. package/dist/framework/modules/runtime-module-output.d.ts +7 -0
  62. package/dist/framework/modules/runtime-module-output.js +15 -0
  63. package/dist/framework/modules/runtime-module-worker-bootstrap.mjs +23 -0
  64. package/dist/framework/participation-manager.d.ts +94 -0
  65. package/dist/framework/participation-manager.js +185 -0
  66. package/dist/framework/persistence/async-sqlite-persistence-worker.d.ts +1 -0
  67. package/dist/framework/persistence/async-sqlite-persistence-worker.js +62 -0
  68. package/dist/framework/persistence/memory-first-persistence.d.ts +36 -0
  69. package/dist/framework/persistence/memory-first-persistence.js +459 -0
  70. package/dist/framework/plugins/contracts.d.ts +345 -0
  71. package/dist/framework/plugins/contracts.js +1 -0
  72. package/dist/framework/plugins/index.d.ts +4 -0
  73. package/dist/framework/plugins/index.js +4 -0
  74. package/dist/framework/plugins/runtime-event-identity.d.ts +3 -0
  75. package/dist/framework/plugins/runtime-event-identity.js +11 -0
  76. package/dist/framework/plugins/runtime-input-journal.d.ts +85 -0
  77. package/dist/framework/plugins/runtime-input-journal.js +716 -0
  78. package/dist/framework/plugins/runtime-plugin-scheduler.d.ts +188 -0
  79. package/dist/framework/plugins/runtime-plugin-scheduler.js +1660 -0
  80. package/dist/framework/runtime.d.ts +264 -0
  81. package/dist/framework/runtime.js +1811 -0
  82. package/dist/framework/serial-task-queue.d.ts +6 -0
  83. package/dist/framework/serial-task-queue.js +12 -0
  84. package/dist/framework/state/contracts.d.ts +30 -0
  85. package/dist/framework/state/contracts.js +1 -0
  86. package/dist/framework/state/current-state-store.d.ts +17 -0
  87. package/dist/framework/state/current-state-store.js +153 -0
  88. package/dist/framework/state/durable-agent-state-snapshot.d.ts +61 -0
  89. package/dist/framework/state/durable-agent-state-snapshot.js +162 -0
  90. package/dist/framework/state/freshness.d.ts +7 -0
  91. package/dist/framework/state/freshness.js +52 -0
  92. package/dist/framework/state/history/contracts.d.ts +133 -0
  93. package/dist/framework/state/history/contracts.js +1 -0
  94. package/dist/framework/state/history/history-writer.d.ts +55 -0
  95. package/dist/framework/state/history/history-writer.js +157 -0
  96. package/dist/framework/state/history/memory-state-history-repository.d.ts +25 -0
  97. package/dist/framework/state/history/memory-state-history-repository.js +199 -0
  98. package/dist/framework/state/history/sqlite-state-history-repository.d.ts +28 -0
  99. package/dist/framework/state/history/sqlite-state-history-repository.js +565 -0
  100. package/dist/framework/state/history/trajectory-projector.d.ts +53 -0
  101. package/dist/framework/state/history/trajectory-projector.js +130 -0
  102. package/dist/framework/state/index.d.ts +12 -0
  103. package/dist/framework/state/index.js +12 -0
  104. package/dist/framework/state/state-ingress.d.ts +18 -0
  105. package/dist/framework/state/state-ingress.js +68 -0
  106. package/dist/framework/state/state-provider.d.ts +11 -0
  107. package/dist/framework/state/state-provider.js +56 -0
  108. package/dist/framework/state/types.d.ts +107 -0
  109. package/dist/framework/state/types.js +19 -0
  110. package/dist/index.d.ts +1 -0
  111. package/dist/index.js +1 -0
  112. package/dist/mailbox/adapters/claude-channel-adapter.d.ts +34 -0
  113. package/dist/mailbox/adapters/claude-channel-adapter.js +71 -0
  114. package/dist/mailbox/adapters/claude-channel-socket.d.ts +56 -0
  115. package/dist/mailbox/adapters/claude-channel-socket.js +279 -0
  116. package/dist/mailbox/adapters/desktop-event-socket.d.ts +81 -0
  117. package/dist/mailbox/adapters/desktop-event-socket.js +339 -0
  118. package/dist/mailbox/agent-mailbox-coordinator.d.ts +104 -0
  119. package/dist/mailbox/agent-mailbox-coordinator.js +412 -0
  120. package/dist/mailbox/host-monitor-rate-gate.d.ts +60 -0
  121. package/dist/mailbox/host-monitor-rate-gate.js +93 -0
  122. package/dist/mailbox/mailbox-event-batch-delivery.d.ts +73 -0
  123. package/dist/mailbox/mailbox-event-batch-delivery.js +251 -0
  124. package/dist/mailbox/mailbox-host-relay.d.ts +52 -0
  125. package/dist/mailbox/mailbox-host-relay.js +299 -0
  126. package/dist/mailbox/mailbox-plugin.d.ts +56 -0
  127. package/dist/mailbox/mailbox-plugin.js +111 -0
  128. package/dist/mailbox/mailbox-service.d.ts +128 -0
  129. package/dist/mailbox/mailbox-service.js +582 -0
  130. package/dist/memory/contracts.d.ts +12 -0
  131. package/dist/memory/contracts.js +1 -0
  132. package/dist/memory/strategy-memory-rpc.d.ts +21 -0
  133. package/dist/memory/strategy-memory-rpc.js +86 -0
  134. package/dist/memory/strategy-memory.d.ts +15 -0
  135. package/dist/memory/strategy-memory.js +95 -0
  136. package/dist/observability/detail-capture.d.ts +25 -0
  137. package/dist/observability/detail-capture.js +136 -0
  138. package/dist/observability/index.d.ts +5 -0
  139. package/dist/observability/index.js +5 -0
  140. package/dist/observability/process-timing.d.ts +14 -0
  141. package/dist/observability/process-timing.js +56 -0
  142. package/dist/observability/recorder.d.ts +56 -0
  143. package/dist/observability/recorder.js +202 -0
  144. package/dist/observability/redaction.d.ts +30 -0
  145. package/dist/observability/redaction.js +166 -0
  146. package/dist/observability/reporter.d.ts +32 -0
  147. package/dist/observability/reporter.js +140 -0
  148. package/dist/observability/sinks.d.ts +36 -0
  149. package/dist/observability/sinks.js +121 -0
  150. package/dist/observability/types.d.ts +81 -0
  151. package/dist/observability/types.js +1 -0
  152. package/dist/owner/control-channel.d.ts +42 -0
  153. package/dist/owner/control-channel.js +188 -0
  154. package/dist/owner/parent-process-watch.d.ts +15 -0
  155. package/dist/owner/parent-process-watch.js +40 -0
  156. package/dist/owner/process-identity.d.ts +10 -0
  157. package/dist/owner/process-identity.js +65 -0
  158. package/dist/owner/runtime-lock.d.ts +5 -0
  159. package/dist/owner/runtime-lock.js +47 -0
  160. package/dist/perception/binding-resolution.d.ts +9 -0
  161. package/dist/perception/binding-resolution.js +14 -0
  162. package/dist/perception/contracts.d.ts +85 -0
  163. package/dist/perception/contracts.js +1 -0
  164. package/dist/perception/map-concurrent.d.ts +2 -0
  165. package/dist/perception/map-concurrent.js +12 -0
  166. package/dist/perception/perception-host.d.ts +114 -0
  167. package/dist/perception/perception-host.js +336 -0
  168. package/dist/perception/perception-worker-host.d.ts +11 -0
  169. package/dist/perception/perception-worker-host.js +44 -0
  170. package/dist/perception/perception-worker.d.ts +21 -0
  171. package/dist/perception/perception-worker.js +77 -0
  172. package/dist/perception/strategy-names.d.ts +7 -0
  173. package/dist/perception/strategy-names.js +22 -0
  174. package/dist/sdk/perception.d.ts +5 -0
  175. package/dist/sdk/perception.js +6 -0
  176. package/dist/sdk/strategy.d.ts +6 -0
  177. package/dist/sdk/strategy.js +3 -0
  178. package/dist/strategy/activation-manager.d.ts +105 -0
  179. package/dist/strategy/activation-manager.js +367 -0
  180. package/dist/strategy/behavior-decision-history.d.ts +20 -0
  181. package/dist/strategy/behavior-decision-history.js +59 -0
  182. package/dist/strategy/behavior-instance-snapshot.d.ts +31 -0
  183. package/dist/strategy/behavior-instance-snapshot.js +145 -0
  184. package/dist/strategy/contracts.d.ts +189 -0
  185. package/dist/strategy/contracts.js +1 -0
  186. package/dist/strategy/control-driver.d.ts +25 -0
  187. package/dist/strategy/control-driver.js +131 -0
  188. package/dist/strategy/in-process-runner.d.ts +25 -0
  189. package/dist/strategy/in-process-runner.js +40 -0
  190. package/dist/strategy/strategy-host.d.ts +165 -0
  191. package/dist/strategy/strategy-host.js +1456 -0
  192. package/dist/strategy/strategy-script-runner.d.ts +81 -0
  193. package/dist/strategy/strategy-script-runner.js +235 -0
  194. package/dist/strategy/strategy-worker-host.d.ts +27 -0
  195. package/dist/strategy/strategy-worker-host.js +96 -0
  196. package/dist/strategy/thread-strategy-executor.d.ts +120 -0
  197. package/dist/strategy/thread-strategy-executor.js +778 -0
  198. package/examples/grid-game.mjs +129 -0
  199. package/examples/grid-perception-worker.mjs +6 -0
  200. package/examples/grid-perception.mjs +12 -0
  201. package/examples/grid-strategy-worker.mjs +11 -0
  202. package/examples/grid-strategy.mjs +13 -0
  203. package/examples/run-grid-game.mjs +24 -0
  204. package/package.json +53 -4
@@ -0,0 +1,1811 @@
1
+ import { canResumeRuntimeScope } from './events/runtime-resume.js';
2
+ import { randomUUID as captureId } from 'node:crypto';
3
+ import { ActionRegistry, ObservationRegistry, } from './capability-registry.js';
4
+ import { actionFailureDiagnosticSeverity, summarizeActionError, } from './action-diagnostics.js';
5
+ import { EventIngress, MemoryEventRepository, SqliteEventRepository, } from './events/index.js';
6
+ import { MemoryRuntimeInputJournal, RuntimePluginScheduler, SqliteRuntimeInputJournal, assertRuntimeInputBatch, runtimeSourceEventId, } from './plugins/index.js';
7
+ import { ParticipationManager, } from './participation-manager.js';
8
+ import { CurrentStateStore, HistoryWriter, MemoryStateHistoryRepository, SqliteStateHistoryRepository, StateFreshnessEvaluator, StateIngress, StateProvider, } from './state/index.js';
9
+ import { performance } from 'node:perf_hooks';
10
+ import { randomUUID } from 'crypto';
11
+ export const RUNTIME_CYCLE_SOURCE_ID = 'runtime.processing-cycle';
12
+ const CLOSED_READY_ANCHOR_LIMIT = 256;
13
+ function runtimeScope(snapshot) {
14
+ return {
15
+ adapterId: snapshot.session.adapterId,
16
+ accountId: snapshot.session.accountId,
17
+ sessionId: snapshot.session.id,
18
+ segmentId: snapshot.segment.id,
19
+ segmentSeq: snapshot.segment.ordinal,
20
+ };
21
+ }
22
+ function eventSession(snapshot, current) {
23
+ return {
24
+ sessionId: snapshot.session.id,
25
+ adapterId: snapshot.session.adapterId,
26
+ accountId: snapshot.session.accountId,
27
+ resumeKey: snapshot.session.resumeKey,
28
+ mode: snapshot.session.mode,
29
+ status: snapshot.session.endedAt ? 'sealed' : 'open',
30
+ isCurrent: current,
31
+ openedAt: snapshot.session.startedAt,
32
+ sealedAt: snapshot.session.endedAt,
33
+ };
34
+ }
35
+ function eventSegment(segment, current) {
36
+ return {
37
+ segmentId: segment.id,
38
+ sessionId: segment.sessionId,
39
+ sequence: segment.ordinal,
40
+ kind: segment.kind,
41
+ scopeRef: segment.identity,
42
+ status: segment.endedAt ? 'closed' : 'open',
43
+ isCurrent: current,
44
+ openedAt: segment.startedAt,
45
+ closedAt: segment.endedAt,
46
+ };
47
+ }
48
+ function participationFromCurrent(scope) {
49
+ return {
50
+ session: {
51
+ id: scope.session.sessionId,
52
+ adapterId: scope.session.adapterId,
53
+ accountId: scope.session.accountId,
54
+ resumeKey: scope.session.resumeKey,
55
+ mode: scope.session.mode,
56
+ startedAt: scope.session.openedAt,
57
+ endedAt: scope.session.sealedAt,
58
+ },
59
+ segment: {
60
+ id: scope.segment.segmentId,
61
+ sessionId: scope.segment.sessionId,
62
+ kind: scope.segment.kind,
63
+ identity: scope.segment.scopeRef,
64
+ ordinal: scope.segment.sequence,
65
+ startedAt: scope.segment.openedAt,
66
+ endedAt: scope.segment.closedAt,
67
+ },
68
+ // A process restart always creates new physical connections. Never restore
69
+ // a connection id from durable logical participation state.
70
+ connections: {},
71
+ };
72
+ }
73
+ function sameScope(envelope, scope) {
74
+ return envelope.adapterId === scope.adapterId
75
+ && envelope.accountId === scope.accountId
76
+ && envelope.sessionId === scope.sessionId
77
+ && envelope.segmentId === scope.segmentId;
78
+ }
79
+ function milliseconds(value) {
80
+ if (!value)
81
+ return undefined;
82
+ const parsed = Date.parse(value);
83
+ return Number.isFinite(parsed) ? parsed : undefined;
84
+ }
85
+ /**
86
+ * Game-neutral coordinator for one participation. Source Plugins submit
87
+ * complete InputBatch values; Runtime persists them, assigns epoch_seq and
88
+ * drives the static Epoch Plugin graph.
89
+ */
90
+ export class Runtime {
91
+ adapterId;
92
+ accountId;
93
+ repository;
94
+ stateHistoryRepository;
95
+ inputJournal;
96
+ observations = new ObservationRegistry();
97
+ actions = new ActionRegistry();
98
+ eventCatalog;
99
+ eventIngress;
100
+ notificationRelays = new Map();
101
+ stateStore = new CurrentStateStore();
102
+ stateIngress;
103
+ stateProvider;
104
+ historyWriter;
105
+ stateObservers;
106
+ participation;
107
+ pluginScheduler;
108
+ connectionScopes = new Map();
109
+ sourcePlugins = new Map();
110
+ observability;
111
+ actionFailureSeverity;
112
+ currentStateFromRuntimeState;
113
+ persistenceBase;
114
+ lastHistoryWriterHealthSignature = null;
115
+ closed = false;
116
+ closing = false;
117
+ sourceInputOpen = true;
118
+ closePromise;
119
+ fatalError = null;
120
+ ownerRestartGapOpen = false;
121
+ readyState = null;
122
+ readyScope = null;
123
+ readyFrameSeq = 0;
124
+ readyEventWatermark = 0;
125
+ readyEpochSeq = 0;
126
+ readyPluginStates = {};
127
+ readyPluginOutcomes = {};
128
+ latestAcceptedEpochSeq = 0;
129
+ acceptedAgentStateByEpoch = new Map();
130
+ epochCompletions = new Map();
131
+ epochIntakeTimings = new Map();
132
+ closedReadyAnchors = new Map();
133
+ startPromise;
134
+ followUpInput;
135
+ readyObservers;
136
+ processingCadence;
137
+ cadenceTimer;
138
+ cadenceRun;
139
+ cadencePaused = false;
140
+ cadenceHasLiveInput = false;
141
+ cadenceId = 0;
142
+ cadenceNextAt = 0;
143
+ cadenceLatestInput;
144
+ cadenceLatestStateFrame;
145
+ cadenceProcessedInput = 0;
146
+ cadenceStateVersion = null;
147
+ cadenceInstanceId = randomUUID();
148
+ cadenceError;
149
+ cadenceRecoveryNeedsCycle = false;
150
+ constructor(options) {
151
+ this.actionFailureSeverity = options.actionFailureSeverity ?? actionFailureDiagnosticSeverity;
152
+ if (options.processingCadence && (!Number.isSafeInteger(options.processingCadence.intervalMs)
153
+ || options.processingCadence.intervalMs < 1 || options.processingCadence.intervalMs > 60_000)) {
154
+ throw new TypeError('Runtime processing interval must be an integer from 1 to 60000 ms.');
155
+ }
156
+ this.processingCadence = options.processingCadence;
157
+ this.followUpInput = options.followUpInput;
158
+ this.readyObservers = (options.runtimeEpochPlugins ?? []).filter(plugin => !!plugin.afterReady);
159
+ this.adapterId = options.adapterId;
160
+ this.accountId = options.accountId;
161
+ this.observability = options.observability;
162
+ const warnings = [];
163
+ if (options.eventRepository) {
164
+ this.repository = options.eventRepository;
165
+ }
166
+ else if (options.eventLedgerPath) {
167
+ const opened = SqliteEventRepository.open(options.eventLedgerPath, options.eventStoreCompatibility);
168
+ if (opened.ok) {
169
+ this.repository = opened.repository;
170
+ }
171
+ else {
172
+ const cause = opened.unavailable.cause
173
+ ? ` Cause: ${opened.unavailable.cause}`
174
+ : '';
175
+ throw new Error(`EVENT_LEDGER_${opened.unavailable.code}: ${opened.unavailable.message}${cause}`);
176
+ }
177
+ }
178
+ else {
179
+ // Pathless instances are useful to tests and embedded hosts that own
180
+ // both the runtime and every consumer. Production adapters should pass
181
+ // a durable repository or ledger path.
182
+ this.repository = new MemoryEventRepository();
183
+ }
184
+ let historyPersistence = 'memory';
185
+ if (options.stateHistoryRepository) {
186
+ this.stateHistoryRepository = options.stateHistoryRepository;
187
+ historyPersistence = options.stateHistoryRepository instanceof SqliteStateHistoryRepository
188
+ || options.stateHistoryRepository.persistenceKind === 'memory-first-sqlite'
189
+ ? 'sqlite'
190
+ : 'memory';
191
+ }
192
+ else if (options.stateHistoryPath) {
193
+ try {
194
+ this.stateHistoryRepository = new SqliteStateHistoryRepository(options.stateHistoryPath);
195
+ historyPersistence = 'sqlite';
196
+ }
197
+ catch (error) {
198
+ this.stateHistoryRepository = new MemoryStateHistoryRepository();
199
+ warnings.push(`STATE_HISTORY_SQLITE_UNAVAILABLE: ${error instanceof Error ? error.message : String(error)}`);
200
+ }
201
+ }
202
+ else {
203
+ this.stateHistoryRepository = new MemoryStateHistoryRepository();
204
+ }
205
+ let inputJournalPersistence = 'memory';
206
+ if (options.inputJournal) {
207
+ this.inputJournal = options.inputJournal;
208
+ inputJournalPersistence = options.inputJournal instanceof SqliteRuntimeInputJournal
209
+ || options.inputJournal.persistenceKind === 'memory-first-sqlite'
210
+ ? 'sqlite'
211
+ : 'memory';
212
+ }
213
+ else if (options.inputJournalPath) {
214
+ this.inputJournal = new SqliteRuntimeInputJournal(options.inputJournalPath);
215
+ inputJournalPersistence = 'sqlite';
216
+ }
217
+ else {
218
+ this.inputJournal = new MemoryRuntimeInputJournal();
219
+ }
220
+ const eventPersistence = this.repository instanceof SqliteEventRepository
221
+ || this.repository.persistenceKind === 'memory-first-sqlite'
222
+ ? 'sqlite'
223
+ : 'memory';
224
+ this.persistenceBase = {
225
+ events: eventPersistence,
226
+ stateHistory: historyPersistence,
227
+ inputJournal: inputJournalPersistence,
228
+ warnings,
229
+ };
230
+ this.currentStateFromRuntimeState = options.currentStateFromRuntimeState
231
+ ?? ((state) => structuredClone(state));
232
+ this.historyWriter = new HistoryWriter(this.stateHistoryRepository, {
233
+ onHealthChanged: (health) => this.onHistoryWriterHealthChanged(health),
234
+ });
235
+ const historyObserver = options.historyObserverFactory?.(this.historyWriter);
236
+ this.stateObservers = [...(options.stateObservers ?? [])];
237
+ this.stateIngress = new StateIngress(this.stateStore, [
238
+ ...(historyObserver ? [historyObserver] : []),
239
+ ...this.stateObservers,
240
+ ]);
241
+ this.stateProvider = new StateProvider(this.stateStore, new StateFreshnessEvaluator(options.stateFreshnessPolicy, options.stateFreshnessPolicyResolver), (snapshot) => snapshot.backendState);
242
+ this.eventCatalog = options.eventCatalog;
243
+ this.eventIngress = new EventIngress(this.repository, this.eventCatalog, {
244
+ consumerIds: options.initialEventConsumerIds,
245
+ notificationPolicy: options.notificationPolicy,
246
+ });
247
+ for (const plugin of options.runtimeEpochPlugins ?? []) {
248
+ if (plugin.notificationRelay)
249
+ this.notificationRelays.set(plugin.id, plugin.notificationRelay);
250
+ for (const output of plugin.produces?.events ?? []) {
251
+ const catalogEntry = options.eventCatalog.get(output);
252
+ if (!catalogEntry) {
253
+ throw new Error(`Runtime Epoch Plugin "${plugin.id}" output "${output}" `
254
+ + 'is not registered in the Event Catalog.');
255
+ }
256
+ if (catalogEntry.producer !== 'local_synth' && !plugin.notificationRelay?.sourceEvents) {
257
+ throw new Error(`Runtime Epoch Plugin "${plugin.id}" cannot own backend Event "${output}".`);
258
+ }
259
+ }
260
+ }
261
+ this.pluginScheduler = new RuntimePluginScheduler({
262
+ plugins: options.runtimeEpochPlugins,
263
+ inputJournal: this.inputJournal,
264
+ pluginStore: this.inputJournal,
265
+ stateHistory: this.stateHistoryRepository,
266
+ commitInputEvents: (work) => this.commitInputEvents(work),
267
+ listEvents: ({ scope, ...filter }) => this.repository.listCommittedEvents({
268
+ sessionId: scope.sessionId,
269
+ segmentId: scope.segmentId,
270
+ afterCommitSeq: filter.afterCommitSeq,
271
+ maxCommitSeq: filter.maxCommitSeq,
272
+ ...(filter.epochSeq === undefined ? {} : { epochSeq: filter.epochSeq }),
273
+ ...(filter.maxEpochSeq === undefined ? {} : { maxEpochSeq: filter.maxEpochSeq }),
274
+ ...(filter.types ? { types: [...filter.types] } : {}),
275
+ order: 'asc',
276
+ }),
277
+ publishEvent: (pluginId, epoch, proposal, proposalIndex) => this.eventIngress.publish(this.pluginEventInput(pluginId, epoch, proposal, proposalIndex)),
278
+ resolveEventDelivery: (decision) => this.repository.resolveEventDelivery(decision),
279
+ highWaterCommitSeq: (scope) => this.repository.highWaterCommitSeq(scope.sessionId),
280
+ currentSegment: () => {
281
+ const segment = this.currentSegment();
282
+ return {
283
+ kind: segment.kind,
284
+ ...(segment.identity === undefined ? {} : { identity: segment.identity }),
285
+ };
286
+ },
287
+ capabilitiesFor: (plugin, scope, signal, epochSeq) => this.pluginCapabilityAccess(plugin, scope, signal, epochSeq),
288
+ processingIntervalMs: this.processingCadence?.intervalMs,
289
+ onEpochClosed: (work, result) => this.onEpochClosed(work.epoch, work.frame.frameSeq, result),
290
+ onFatalError: (error, pluginId, scope) => {
291
+ this.fatalError = error instanceof Error ? error : new Error(String(error));
292
+ this.actions.beginStopping('runtime_plugin_fatal');
293
+ this.observability?.error('runtime.plugin.fatal', this.fatalError, {
294
+ plugin_id: pluginId,
295
+ }, { component: 'runtime.epoch', scope });
296
+ },
297
+ onDiagnostic: (name, attributes, scope, severity = 'debug') => {
298
+ this.observability?.log(severity, name, attributes, { component: 'runtime.epoch', scope });
299
+ },
300
+ });
301
+ const accountScope = { adapterId: this.adapterId, accountId: this.accountId };
302
+ const durableCurrent = this.repository.currentScope(accountScope);
303
+ const resumesBySessionKey = options.resumeKey !== undefined
304
+ && durableCurrent?.session.resumeKey === options.resumeKey;
305
+ const canResume = canResumeRuntimeScope(durableCurrent, options);
306
+ if (!canResume && durableCurrent)
307
+ this.sealDurableScope(durableCurrent);
308
+ this.participation = new ParticipationManager({
309
+ initial: canResume && durableCurrent ? participationFromCurrent(durableCurrent) : undefined,
310
+ onTransition: (transition) => this.persistTransition(transition),
311
+ });
312
+ if (!canResume) {
313
+ this.participation.openSession({
314
+ adapterId: this.adapterId,
315
+ accountId: this.accountId,
316
+ resumeKey: options.resumeKey,
317
+ mode: options.mode,
318
+ initialSegment: options.initialSegment,
319
+ });
320
+ }
321
+ else {
322
+ if (options.mode)
323
+ this.participation.updateMode(options.mode);
324
+ const restoredSegmentId = this.participation.requireSnapshot().segment.id;
325
+ const activated = this.participation.activateSegment(options.initialSegment.kind, options.initialSegment.identity);
326
+ if (activated.segment.id === restoredSegmentId) {
327
+ // A live-only source may have advanced while the owner was down. The
328
+ // logical segment resumes, but its history completeness cannot.
329
+ this.openStateScope(activated, false);
330
+ this.ownerRestartGapOpen = true;
331
+ this.enqueueOwnerRestartGap('stream_gap_started');
332
+ }
333
+ }
334
+ this.actions.activateScope(this.scope());
335
+ this.readyScope = this.scope();
336
+ this.readyState = this.readAgentState();
337
+ this.readyEventWatermark = this.repository.highWaterCommitSeq(this.scope().sessionId);
338
+ const scope = this.scope();
339
+ this.observability?.log('info', 'runtime.owner.started', {
340
+ adapter_id: this.adapterId,
341
+ persistence: this.persistence,
342
+ resumed: canResume,
343
+ resume_match: canResume
344
+ ? resumesBySessionKey ? 'session_key' : 'current_segment'
345
+ : 'none',
346
+ }, { component: 'runtime', scope });
347
+ for (const warning of warnings) {
348
+ this.observability?.log('warn', 'runtime.persistence.degraded', {
349
+ warning,
350
+ event_repository: eventPersistence,
351
+ state_history_repository: historyPersistence,
352
+ }, { component: 'runtime.persistence', scope });
353
+ }
354
+ }
355
+ /** Dynamic owner health; unlike the repository choice, writer health can change at runtime. */
356
+ get persistence() {
357
+ return {
358
+ ...this.persistenceBase,
359
+ warnings: [...this.persistenceBase.warnings],
360
+ historyWriter: this.historyWriterHealth(),
361
+ };
362
+ }
363
+ historyWriterHealth() {
364
+ return {
365
+ ...this.historyWriter.health(),
366
+ degradedScopes: this.historyWriter.degradedScopeHealth().map((entry) => {
367
+ const { accountId: _accountId, ...scope } = entry.scope;
368
+ return { ...entry, scope };
369
+ }),
370
+ };
371
+ }
372
+ scope() {
373
+ return runtimeScope(this.participation.requireSnapshot());
374
+ }
375
+ currentSegment() {
376
+ const snapshot = this.participation.requireSnapshot();
377
+ return {
378
+ scope: runtimeScope(snapshot),
379
+ kind: snapshot.segment.kind,
380
+ ...(snapshot.segment.identity === undefined ? {} : { identity: snapshot.segment.identity }),
381
+ };
382
+ }
383
+ publicScope() {
384
+ return this.publicScopeFor(this.scope());
385
+ }
386
+ publicScopeFor(runtimeScope) {
387
+ const { accountId: _accountId, ...scope } = runtimeScope;
388
+ return scope;
389
+ }
390
+ runtimeEpochPluginDescriptors() {
391
+ return this.pluginScheduler.descriptors();
392
+ }
393
+ /** Full-diagnostic, on-demand scheduler state; never sampled by default. */
394
+ runtimeEpochDiagnosticSnapshot() {
395
+ return this.pluginScheduler.diagnosticSnapshot(this.scope());
396
+ }
397
+ /** Full-only retained row counts; implementations without a hot cache report an empty object. */
398
+ runtimeRetainedRecordCounts() {
399
+ const counts = (value) => (value
400
+ ?.diagnosticCounts?.() ?? {});
401
+ return {
402
+ event_repository: counts(this.repository),
403
+ state_history: counts(this.stateHistoryRepository),
404
+ input_journal: counts(this.inputJournal),
405
+ };
406
+ }
407
+ runtimePersistenceDiagnostics() {
408
+ return this.repository
409
+ .persistenceHealth?.() ?? {};
410
+ }
411
+ runtimePluginDescriptors() {
412
+ return [
413
+ ...[...this.sourcePlugins.values()].map(({ plugin }) => ({
414
+ kind: 'source',
415
+ id: plugin.id,
416
+ version: plugin.version,
417
+ })),
418
+ ...this.pluginScheduler.descriptors(),
419
+ ];
420
+ }
421
+ /** Start the current scope's Epoch Plugin graph before external input arrives. */
422
+ async start() {
423
+ this.assertOpen();
424
+ if (!this.startPromise) {
425
+ const attempt = (async () => {
426
+ await this.pluginScheduler.activateScope(this.scope());
427
+ await this.recoverOpenEpochs();
428
+ if (this.processingCadence) {
429
+ this.restoreCadenceInputs();
430
+ await this.drainCadence(true);
431
+ this.armCadence();
432
+ }
433
+ else
434
+ await this.recoverPendingNotifications();
435
+ })();
436
+ this.startPromise = attempt.catch((error) => {
437
+ this.startPromise = undefined;
438
+ throw error;
439
+ });
440
+ }
441
+ await this.startPromise;
442
+ }
443
+ async startSourcePlugin(plugin) {
444
+ this.assertOpen();
445
+ if (plugin.kind !== 'source')
446
+ throw new TypeError(`Runtime Source Plugin ${plugin.id} has invalid kind.`);
447
+ if (!plugin.id?.trim())
448
+ throw new TypeError('Runtime Source Plugin id must not be empty.');
449
+ if (!plugin.version?.trim())
450
+ throw new TypeError(`Runtime Source Plugin ${plugin.id} version must not be empty.`);
451
+ if (this.sourcePlugins.has(plugin.id))
452
+ throw new Error(`Duplicate Runtime Source Plugin id: ${plugin.id}`);
453
+ if (this.pluginScheduler.descriptors().some((candidate) => candidate.id === plugin.id)) {
454
+ throw new Error(`Runtime Plugin id is shared by Source and Epoch Plugin: ${plugin.id}`);
455
+ }
456
+ await this.start();
457
+ const handle = await plugin.start(this);
458
+ if (!handle || typeof handle.stop !== 'function') {
459
+ throw new TypeError(`Runtime Source Plugin ${plugin.id} did not return a stop handle.`);
460
+ }
461
+ this.sourcePlugins.set(plugin.id, { plugin, handle });
462
+ }
463
+ closeActionScope(scope, reason) {
464
+ this.actions.closeScope(scope, reason);
465
+ }
466
+ async activateSegment(kind, identity) {
467
+ this.assertOpen();
468
+ const previous = this.scope();
469
+ const current = this.participation.requireSnapshot().segment;
470
+ const changesSegment = current.kind !== kind
471
+ || (identity !== undefined
472
+ && current.identity !== undefined
473
+ && current.identity !== identity);
474
+ if (changesSegment) {
475
+ this.pauseCadence();
476
+ await this.drainCadence(true);
477
+ await this.pluginScheduler.flush('segment_ending');
478
+ }
479
+ const next = runtimeScope(this.participation.activateSegment(kind, identity));
480
+ if (previous.segmentId !== next.segmentId) {
481
+ this.cadenceLatestInput = undefined;
482
+ this.cadenceLatestStateFrame = undefined;
483
+ this.cadenceProcessedInput = 0;
484
+ this.cadenceStateVersion = null;
485
+ this.cadenceHasLiveInput = false;
486
+ this.resetReadyView(next);
487
+ this.observability?.log('info', 'runtime.scope.switched', {
488
+ previous_segment_id: previous.segmentId,
489
+ previous_segment_seq: previous.segmentSeq,
490
+ segment_kind: kind,
491
+ has_identity: !!identity,
492
+ }, { component: 'runtime', scope: next });
493
+ }
494
+ if (changesSegment) {
495
+ this.cadencePaused = false;
496
+ this.armCadence();
497
+ }
498
+ return next;
499
+ }
500
+ adoptResumeKey(resumeKey) {
501
+ this.assertOpen();
502
+ return runtimeScope(this.participation.adoptResumeKey(resumeKey));
503
+ }
504
+ updateMode(mode) {
505
+ this.assertOpen();
506
+ return runtimeScope(this.participation.updateMode(mode));
507
+ }
508
+ bindConnection(sourceId, connectionId, atMs = Date.now()) {
509
+ this.assertOpen();
510
+ const key = this.connectionKey(sourceId, connectionId);
511
+ const current = this.scope();
512
+ const existing = this.connectionScopes.get(key);
513
+ if (existing) {
514
+ if (!sameScope(existing, current)) {
515
+ throw new Error('Connection is already frozen to a different runtime scope.');
516
+ }
517
+ if (this.participation.connectionId(sourceId) !== connectionId) {
518
+ throw new Error('Connection has already been superseded by a newer connection.');
519
+ }
520
+ return structuredClone(existing);
521
+ }
522
+ const snapshot = this.participation.bindConnection(sourceId, connectionId);
523
+ this.stateIngress.openScope(runtimeScope(snapshot), atMs);
524
+ this.stateIngress.connectionOpened(connectionId, atMs);
525
+ if (this.ownerRestartGapOpen) {
526
+ this.ownerRestartGapOpen = false;
527
+ this.enqueueOwnerRestartGap('stream_gap_ended', connectionId, atMs);
528
+ }
529
+ const scope = runtimeScope(snapshot);
530
+ this.connectionScopes.set(key, structuredClone(scope));
531
+ this.observability?.log('info', 'runtime.connection.bound', {
532
+ source_id: sourceId,
533
+ }, { component: 'runtime.transport', scope: { ...scope, connectionId } });
534
+ return scope;
535
+ }
536
+ /** Explicitly move a still-live physical connection to a new logical segment. */
537
+ rebindConnectionScope(sourceId, connectionId, atMs = Date.now()) {
538
+ this.assertOpen();
539
+ if (this.participation.connectionId(sourceId) !== connectionId) {
540
+ throw new Error('Only the active connection can be rebound to a new runtime scope.');
541
+ }
542
+ const scope = this.scope();
543
+ const key = this.connectionKey(sourceId, connectionId);
544
+ const existing = this.connectionScopes.get(key);
545
+ if (existing && sameScope(existing, scope))
546
+ return structuredClone(scope);
547
+ this.connectionScopes.set(key, structuredClone(scope));
548
+ this.stateIngress.openScope(scope, atMs);
549
+ this.stateIngress.connectionOpened(connectionId, atMs);
550
+ this.observability?.log('info', 'runtime.connection.scope_rebound', {
551
+ source_id: sourceId,
552
+ }, { component: 'runtime.transport', scope: { ...scope, connectionId } });
553
+ return structuredClone(scope);
554
+ }
555
+ connectionScope(sourceId, connectionId) {
556
+ const scope = this.connectionScopes.get(this.connectionKey(sourceId, connectionId));
557
+ return scope ? structuredClone(scope) : null;
558
+ }
559
+ isActiveConnection(sourceId, connectionId) {
560
+ return this.participation.connectionId(sourceId) === connectionId;
561
+ }
562
+ connectionChanged(sourceId, connectionId, state, atMs = Date.now()) {
563
+ if (this.closed || this.participation.connectionId(sourceId) !== connectionId)
564
+ return;
565
+ this.stateIngress.connectionChanged(connectionId, state, atMs);
566
+ const scope = this.scope();
567
+ this.observability?.log(state === 'connected' ? 'info' : 'warn', `runtime.connection.${state}`, { source_id: sourceId }, { component: 'runtime.transport', scope: { ...scope, connectionId } });
568
+ }
569
+ connectionLiveness(sourceId, connectionId, atMs = Date.now()) {
570
+ if (this.closed || this.participation.connectionId(sourceId) !== connectionId)
571
+ return false;
572
+ return this.stateIngress.livenessReceived(connectionId, atMs);
573
+ }
574
+ diagnostic(name, attributes = {}, severity = 'debug') {
575
+ this.observability?.log(severity, name, { ...attributes }, {
576
+ component: 'runtime.source',
577
+ scope: this.publicScope(),
578
+ });
579
+ }
580
+ /**
581
+ * The fixed Runtime intake boundary. Acceptance persists the complete input
582
+ * immediately; plugin work is queued independently so Source intake never
583
+ * waits for a slow Perception or Behavior invocation.
584
+ */
585
+ async acceptInputBatch(batch) {
586
+ this.assertSourceInputOpen();
587
+ const intakeStartedAtMs = performance.now();
588
+ const journalStartedAtMs = performance.now();
589
+ let acceptance;
590
+ try {
591
+ assertRuntimeInputBatch(batch);
592
+ if (!sameScope(batch.scope, this.scope())) {
593
+ throw new Error('Runtime InputBatch scope does not match the active participation segment.');
594
+ }
595
+ acceptance = this.inputJournal.accept(batch);
596
+ }
597
+ catch (error) {
598
+ this.observability?.error('runtime.input.rejected', error, {
599
+ source_id: batch?.sourceId,
600
+ source_key: batch?.sourceKey,
601
+ reason: error instanceof Error ? error.name : 'invalid_input',
602
+ }, { component: 'runtime.input', scope: this.publicScope() });
603
+ throw error;
604
+ }
605
+ const journalMs = Math.max(0, performance.now() - journalStartedAtMs);
606
+ if (!acceptance.inserted) {
607
+ this.observability?.log('debug', 'runtime.input.duplicate', {
608
+ source_id: batch.sourceId,
609
+ source_key: batch.sourceKey,
610
+ epoch_seq: acceptance.epoch.epochSeq,
611
+ }, { component: 'runtime.input', scope: this.publicScope() });
612
+ return acceptance;
613
+ }
614
+ const epoch = acceptance.epoch;
615
+ this.latestAcceptedEpochSeq = Math.max(this.latestAcceptedEpochSeq, epoch.epochSeq);
616
+ const historyStartedAtMs = performance.now();
617
+ const previousFrame = this.stateHistoryRepository.latestStateFrame(epoch.scope);
618
+ const frame = this.stateHistoryRepository.appendStateFrame({
619
+ epochSeq: epoch.epochSeq,
620
+ scope: epoch.scope,
621
+ sourceId: epoch.sourceId,
622
+ connectionId: epoch.connectionId,
623
+ sourceKey: `runtime-epoch:${epoch.epochSeq}`,
624
+ sourceSeq: epoch.sourceSeq,
625
+ backendTick: typeof epoch.domainTick === 'number' ? epoch.domainTick : undefined,
626
+ observedAtMs: milliseconds(epoch.observedAt),
627
+ receivedAtMs: milliseconds(epoch.receivedAt) ?? Date.now(),
628
+ state: epoch.state,
629
+ }).frame;
630
+ const historyMs = Math.max(0, performance.now() - historyStartedAtMs);
631
+ const stateProjectionStartedAtMs = performance.now();
632
+ const isCycle = this.processingCadence && epoch.sourceId === RUNTIME_CYCLE_SOURCE_ID;
633
+ const projectedState = isCycle || this.processingCadence?.isStateUpdate?.(epoch) === false
634
+ ? null : this.currentStateFromRuntimeState(epoch.state);
635
+ if (projectedState !== null) {
636
+ const current = this.stateIngress.snapshot();
637
+ if (current.meta.connectionId !== epoch.connectionId) {
638
+ this.stateIngress.connectionOpened(epoch.connectionId, milliseconds(epoch.receivedAt) ?? Date.now());
639
+ }
640
+ const applied = this.stateIngress.accept({
641
+ scope: epoch.scope,
642
+ sourceId: epoch.sourceId,
643
+ connectionId: epoch.connectionId,
644
+ payload: projectedState,
645
+ sourceKey: `runtime-epoch:${epoch.epochSeq}`,
646
+ sourceSeq: epoch.epochSeq,
647
+ backendTick: typeof epoch.domainTick === 'number' ? epoch.domainTick : undefined,
648
+ observedAtMs: milliseconds(epoch.observedAt),
649
+ receivedAtMs: milliseconds(epoch.receivedAt) ?? Date.now(),
650
+ });
651
+ if (!applied.accepted) {
652
+ throw new Error(`Runtime current-State projection was rejected: ${applied.reason}.`);
653
+ }
654
+ }
655
+ const currentState = this.readAgentState();
656
+ if (this.processingCadence && !isCycle) {
657
+ this.cadenceLatestInput = epoch;
658
+ if (projectedState !== null)
659
+ this.cadenceLatestStateFrame = frame;
660
+ this.cadenceHasLiveInput = true;
661
+ this.observability?.log('debug', 'runtime.input.accepted', {
662
+ epoch_seq: epoch.epochSeq, source_id: epoch.sourceId, domain_tick: epoch.domainTick,
663
+ event_count: epoch.events.length, processing: 'awaiting_cycle',
664
+ }, { component: 'runtime.input', scope: this.publicScope() });
665
+ return acceptance;
666
+ }
667
+ this.acceptedAgentStateByEpoch.set(epoch.epochSeq, structuredClone(currentState));
668
+ const stateProjectionMs = Math.max(0, performance.now() - stateProjectionStartedAtMs);
669
+ const intakeTotalMs = Math.max(0, performance.now() - intakeStartedAtMs);
670
+ this.epochIntakeTimings.set(epoch.epochSeq, {
671
+ startedAtMs: intakeStartedAtMs,
672
+ journalMs,
673
+ historyMs,
674
+ stateProjectionMs,
675
+ intakeTotalMs,
676
+ });
677
+ this.observability?.log('debug', 'runtime.input.accepted', {
678
+ source_id: epoch.sourceId,
679
+ source_seq: epoch.sourceSeq,
680
+ source_key: epoch.sourceKey,
681
+ epoch_seq: epoch.epochSeq,
682
+ domain_tick: epoch.domainTick,
683
+ event_count: epoch.events.length,
684
+ completeness: epoch.completeness,
685
+ coalescing: epoch.coalescing ?? 'allowed',
686
+ stage: typeof epoch.state.stage === 'string' ? epoch.state.stage : undefined,
687
+ cause: typeof epoch.state.cause === 'string' ? epoch.state.cause : undefined,
688
+ connection: typeof epoch.state.connection === 'string' ? epoch.state.connection : undefined,
689
+ game_snapshot_status: epoch.state.game_snapshot?.status,
690
+ journal_ms: Math.round(journalMs * 1_000) / 1_000,
691
+ state_history_ms: Math.round(historyMs * 1_000) / 1_000,
692
+ state_projection_ms: Math.round(stateProjectionMs * 1_000) / 1_000,
693
+ intake_total_ms: Math.round(intakeTotalMs * 1_000) / 1_000,
694
+ }, { component: 'runtime.input', scope: this.publicScope() });
695
+ const completion = this.pluginScheduler.enqueue({
696
+ epoch,
697
+ frame,
698
+ currentState,
699
+ previousState: previousFrame?.state ?? null,
700
+ epochEvents: [],
701
+ });
702
+ this.trackEpochCompletion(epoch.epochSeq, completion);
703
+ void completion.catch((error) => {
704
+ this.observability?.error('runtime.epoch.processing_failed', error, {
705
+ epoch_seq: epoch.epochSeq,
706
+ source_id: epoch.sourceId,
707
+ }, { component: 'runtime.epoch', scope: this.publicScope() });
708
+ });
709
+ return acceptance;
710
+ }
711
+ readState(nowMs = Date.now()) {
712
+ return this.stateProvider.read(this.scope(), nowMs);
713
+ }
714
+ /** Agent-safe State view. Internal account identity never crosses owner IPC. */
715
+ readAgentState(nowMs = Date.now()) {
716
+ const result = this.readState(nowMs);
717
+ const scope = result.stateStatus.scope;
718
+ return {
719
+ ...result,
720
+ stateStatus: {
721
+ ...result.stateStatus,
722
+ scope: scope ? this.publicScope() : null,
723
+ },
724
+ };
725
+ }
726
+ async queryObservation(capability, request, expectedScope) {
727
+ const scope = this.assertExpectedScope(expectedScope);
728
+ return this.observations.query(capability, request, scope);
729
+ }
730
+ async performAction(capability, action, expectedScope, caller, admission = {}) {
731
+ const scope = this.assertExpectedScope(expectedScope);
732
+ const startedAt = Date.now();
733
+ const detailId = this.observability?.captureEnabled('actions') ? captureId() : undefined;
734
+ if (detailId)
735
+ this.observability?.log('debug', 'runtime.detail.actions.requested', {
736
+ request_id: detailId, capability, caller, request: action,
737
+ }, { component: 'runtime.actions', scope });
738
+ try {
739
+ const result = await this.actions.perform(capability, action, scope, caller, {
740
+ ...admission,
741
+ latestAcceptedState: () => this.latestAcceptedActionState(scope),
742
+ });
743
+ if (detailId)
744
+ this.observability?.log('debug', 'runtime.detail.actions.receipt', {
745
+ request_id: detailId, capability, caller, action_id: result.actionId, result,
746
+ duration_ms: Date.now() - startedAt,
747
+ }, { component: 'runtime.actions', scope });
748
+ const attributes = {
749
+ capability,
750
+ caller_kind: caller.kind,
751
+ status: result.status,
752
+ ...(result.source ? { action_source: result.source } : {}),
753
+ ...(result.actionOutcome ? { action_outcome: result.actionOutcome } : {}),
754
+ duration_ms: Date.now() - startedAt,
755
+ };
756
+ const context = {
757
+ component: 'runtime.actions',
758
+ scope,
759
+ correlation: {
760
+ actionId: result.actionId,
761
+ ...(caller.kind === 'behavior' ? {
762
+ behaviorActivationId: caller.activationId,
763
+ behaviorActivationGeneration: caller.activationGeneration,
764
+ } : {}),
765
+ },
766
+ };
767
+ if (result.status === 'failure') {
768
+ const summary = summarizeActionError(result.error);
769
+ const severity = this.actionFailureSeverity(result);
770
+ if (severity === 'warn') {
771
+ this.observability?.log('warn', 'runtime.action.failed', {
772
+ ...attributes,
773
+ error_code: summary.code,
774
+ http_status: summary.httpStatus,
775
+ error_message_present: summary.messagePresent,
776
+ error_message_length: summary.messageLength,
777
+ }, context);
778
+ }
779
+ else {
780
+ this.observability?.error('runtime.action.failed', {
781
+ name: 'ActionFailure',
782
+ ...(summary.code ? { code: summary.code } : {}),
783
+ }, {
784
+ ...attributes,
785
+ error_code: summary.code,
786
+ http_status: summary.httpStatus,
787
+ error_message_present: summary.messagePresent,
788
+ error_message_length: summary.messageLength,
789
+ }, context);
790
+ }
791
+ }
792
+ else if (result.status === 'deferred') {
793
+ const summary = summarizeActionError(result.error);
794
+ this.observability?.log('info', 'runtime.action.deferred', {
795
+ ...attributes,
796
+ control_code: summary.code ?? 'CONTROL_DEFERRED',
797
+ }, context);
798
+ }
799
+ else {
800
+ this.observability?.log(result.status === 'partial' ? 'warn' : 'info', 'runtime.action.completed', attributes, context);
801
+ }
802
+ return result;
803
+ }
804
+ catch (error) {
805
+ const summary = summarizeActionError(error);
806
+ if (detailId)
807
+ this.observability?.log('debug', 'runtime.detail.actions.failed', {
808
+ request_id: detailId, capability, caller, error, duration_ms: Date.now() - startedAt,
809
+ }, { component: 'runtime.actions', scope });
810
+ this.observability?.error('runtime.action.failed', {
811
+ name: error instanceof Error ? error.name : 'ActionFailure',
812
+ ...(summary.code ? { code: summary.code } : {}),
813
+ }, {
814
+ capability,
815
+ caller_kind: caller.kind,
816
+ duration_ms: Date.now() - startedAt,
817
+ error_message_present: summary.messagePresent,
818
+ error_message_length: summary.messageLength,
819
+ }, {
820
+ component: 'runtime.actions',
821
+ scope,
822
+ correlation: caller.kind === 'behavior'
823
+ ? {
824
+ behaviorActivationId: caller.activationId,
825
+ behaviorActivationGeneration: caller.activationGeneration,
826
+ }
827
+ : undefined,
828
+ });
829
+ throw error;
830
+ }
831
+ }
832
+ /**
833
+ * Non-consuming view bounded by the latest fully closed epoch. Consumers
834
+ * get one State/Event position without changing any delivery cursor.
835
+ */
836
+ readReadyView(afterCommitSeq = 0, limit = 100) {
837
+ const scope = this.scope();
838
+ const readyForCurrentScope = !!this.readyScope && sameScope(this.readyScope, scope);
839
+ const boundedLimit = Math.max(1, Math.min(500, Math.trunc(limit) || 100));
840
+ const pending = this.repository.listCommittedEvents({
841
+ sessionId: scope.sessionId,
842
+ segmentId: scope.segmentId,
843
+ afterCommitSeq,
844
+ maxCommitSeq: readyForCurrentScope ? this.readyEventWatermark : 0,
845
+ maxEpochSeq: readyForCurrentScope ? this.readyEpochSeq : 0,
846
+ order: 'asc',
847
+ limit: boundedLimit + 1,
848
+ });
849
+ const events = pending.slice(0, boundedLimit);
850
+ return {
851
+ scope: this.publicScope(),
852
+ state: structuredClone(readyForCurrentScope ? this.readyState ?? this.readAgentState() : this.readAgentState()),
853
+ pluginStates: structuredClone(readyForCurrentScope ? this.readyPluginStates : {}),
854
+ pluginOutcomes: structuredClone(readyForCurrentScope ? this.readyPluginOutcomes : {}),
855
+ events,
856
+ throughCommitSeq: events.at(-1)?.commitSeq ?? afterCommitSeq,
857
+ frameSeq: readyForCurrentScope ? this.readyFrameSeq : 0,
858
+ eventWatermark: readyForCurrentScope ? this.readyEventWatermark : 0,
859
+ epochSeq: readyForCurrentScope ? this.readyEpochSeq : 0,
860
+ hasMore: pending.length > events.length,
861
+ };
862
+ }
863
+ /** Waits for one exact epoch and returns the immutable State/Event view closed at it. */
864
+ async waitForEpochReadyView(epochSeq, afterCommitSeq = 0, limit = 100) {
865
+ if (!Number.isInteger(epochSeq) || epochSeq <= 0) {
866
+ throw new TypeError('Runtime epochSeq must be a positive integer.');
867
+ }
868
+ if (this.processingCadence && this.inputJournal.epoch(epochSeq)?.sourceId !== RUNTIME_CYCLE_SOURCE_ID) {
869
+ if (this.readyEpochSeq < epochSeq)
870
+ await this.drainCadence(true);
871
+ if (this.readyEpochSeq < epochSeq)
872
+ throw new Error(`Runtime input ${epochSeq} is outside the current processing scope.`);
873
+ return this.readReadyView(afterCommitSeq, limit);
874
+ }
875
+ let anchor = this.closedReadyAnchors.get(epochSeq);
876
+ if (!anchor) {
877
+ const completion = this.epochCompletions.get(epochSeq);
878
+ if (!completion)
879
+ throw new Error(`Runtime epoch ${epochSeq} is not pending in this Runtime.`);
880
+ await completion;
881
+ anchor = this.closedReadyAnchors.get(epochSeq);
882
+ }
883
+ if (!anchor)
884
+ throw new Error(`Runtime epoch ${epochSeq} closed without a Ready View.`);
885
+ return this.readyViewFromAnchor(anchor, afterCommitSeq, limit);
886
+ }
887
+ async flush() {
888
+ await this.drainCadence(this.closing);
889
+ await this.pluginScheduler.waitForIdle();
890
+ await this.historyWriter.flush();
891
+ await Promise.all(this.stateObservers.map((observer) => observer.flush?.()));
892
+ }
893
+ close() {
894
+ if (!this.closePromise)
895
+ this.closePromise = this.closeInternal();
896
+ return this.closePromise;
897
+ }
898
+ async closeInternal() {
899
+ if (this.closed)
900
+ return;
901
+ this.closing = true;
902
+ this.pauseCadence();
903
+ const closingScope = this.scope();
904
+ const failures = [];
905
+ this.observability?.log('info', 'runtime.shutdown.started', {
906
+ latest_accepted_epoch_seq: this.latestAcceptedEpochSeq,
907
+ ready_epoch_seq: this.readyEpochSeq,
908
+ ready_event_watermark: this.readyEventWatermark,
909
+ }, { component: 'runtime.shutdown', scope: closingScope });
910
+ // Fence new side effects first. Already-admitted Actions may still return
911
+ // Source input, so Sources remain active until those Actions settle.
912
+ this.actions.beginStopping('runtime_closed');
913
+ const sources = [...this.sourcePlugins.values()].reverse();
914
+ try {
915
+ try {
916
+ await this.actions.waitForIdle();
917
+ }
918
+ catch (error) {
919
+ failures.push(error);
920
+ }
921
+ const sourceStops = await Promise.allSettled(sources.map(({ handle }) => Promise.resolve().then(() => handle.stop('shutdown'))));
922
+ for (const settlement of sourceStops) {
923
+ if (settlement.status === 'rejected')
924
+ failures.push(settlement.reason);
925
+ }
926
+ this.sourcePlugins.clear();
927
+ await this.drainCadence(true);
928
+ // Closing epochs can enqueue a host-owned notification turn. Drain those
929
+ // while intake is still open; they never execute a new game action.
930
+ await this.pluginScheduler.waitForIdle();
931
+ this.sourceInputOpen = false;
932
+ const terminalEpochSeq = this.latestAcceptedEpochSeq;
933
+ this.observability?.log('info', 'runtime.shutdown.drain_started', {
934
+ terminal_epoch_seq: terminalEpochSeq,
935
+ ready_epoch_seq: this.readyEpochSeq,
936
+ ready_event_watermark: this.readyEventWatermark,
937
+ }, { component: 'runtime.shutdown', scope: closingScope });
938
+ try {
939
+ await this.pluginScheduler.close();
940
+ }
941
+ catch (error) {
942
+ failures.push(error);
943
+ }
944
+ try {
945
+ await this.historyWriter.flush();
946
+ await Promise.all(this.stateObservers.map((observer) => observer.flush?.()));
947
+ await Promise.all(this.stateObservers.map((observer) => observer.close?.()));
948
+ }
949
+ catch (error) {
950
+ failures.push(error);
951
+ }
952
+ // A Runtime session is the lifetime of one local Owner, not the lifetime
953
+ // of the backend participation. A later Owner may recover the same room,
954
+ // queue, or game from authoritative backend status, but it must not leave
955
+ // this process's durable session/segment marked current after shutdown.
956
+ try {
957
+ this.participation.closeSession('owner_stopped');
958
+ }
959
+ catch (error) {
960
+ failures.push(error);
961
+ }
962
+ if (failures.length > 0) {
963
+ throw new AggregateError(failures, `${failures.length} Runtime shutdown operation(s) failed.`);
964
+ }
965
+ this.observability?.log('info', 'runtime.shutdown.drain_completed', {
966
+ terminal_epoch_seq: terminalEpochSeq,
967
+ ready_epoch_seq: this.readyEpochSeq,
968
+ ready_event_watermark: this.readyEventWatermark,
969
+ event_watermark: this.repository.highWaterCommitSeq(closingScope.sessionId, closingScope.segmentId),
970
+ }, { component: 'runtime.shutdown', scope: closingScope });
971
+ }
972
+ catch (error) {
973
+ this.observability?.error('runtime.shutdown.drain_incomplete', error, {
974
+ terminal_epoch_seq: this.latestAcceptedEpochSeq,
975
+ ready_epoch_seq: this.readyEpochSeq,
976
+ }, { component: 'runtime.shutdown', scope: closingScope });
977
+ throw error;
978
+ }
979
+ finally {
980
+ this.sourceInputOpen = false;
981
+ this.closing = false;
982
+ this.closed = true;
983
+ await this.stateHistoryRepository.close?.();
984
+ await this.inputJournal.close?.();
985
+ await this.repository.close?.();
986
+ this.observability?.log('info', 'runtime.owner.stopped', {
987
+ event_repository: this.persistence.events,
988
+ state_history_repository: this.persistence.stateHistory,
989
+ }, { component: 'runtime', scope: closingScope });
990
+ if (this.observability)
991
+ await this.observability.flushWithin(2_000).catch(() => false);
992
+ }
993
+ }
994
+ sourceEventInput(epoch, sourceEvent, index) {
995
+ if (typeof sourceEvent.type !== 'string' || !sourceEvent.type.trim()) {
996
+ throw new TypeError(`Runtime InputBatch Event ${index} requires type.`);
997
+ }
998
+ return {
999
+ epochSeq: epoch.epochSeq,
1000
+ type: sourceEvent.type,
1001
+ producer: sourceEvent.producer ?? 'backend_push',
1002
+ sessionId: epoch.scope.sessionId,
1003
+ segmentId: epoch.scope.segmentId,
1004
+ payload: sourceEvent.payload,
1005
+ occurredAt: sourceEvent.observedAt ?? epoch.observedAt,
1006
+ receivedAt: sourceEvent.receivedAt ?? epoch.receivedAt,
1007
+ eventId: runtimeSourceEventId(epoch, sourceEvent, index),
1008
+ source: {
1009
+ sourceId: epoch.sourceId,
1010
+ eventId: sourceEvent.sourceEventId,
1011
+ sequence: sourceEvent.sourceSeq,
1012
+ connectionId: epoch.connectionId,
1013
+ replayed: sourceEvent.replayed,
1014
+ checkpoint: sourceEvent.checkpoint,
1015
+ },
1016
+ };
1017
+ }
1018
+ pluginEventInput(pluginId, epoch, proposal, proposalIndex) {
1019
+ if (proposal.forwardEventId !== undefined) {
1020
+ const permission = this.notificationRelays.get(pluginId);
1021
+ const original = this.repository.eventById(proposal.forwardEventId);
1022
+ if (!permission || !original || original.notificationOf
1023
+ || original.type !== proposal.type
1024
+ || original.sessionId !== epoch.scope.sessionId || original.segmentId !== epoch.scope.segmentId
1025
+ || original.epochSeq === undefined || original.epochSeq > epoch.epochSeq
1026
+ || permission.previousEpochOnly && original.epochSeq >= epoch.epochSeq
1027
+ || (original.producerPluginId === undefined
1028
+ ? !permission.sourceEvents
1029
+ : !permission.producerPluginIds?.includes(original.producerPluginId))) {
1030
+ throw new Error(`Runtime Plugin ${pluginId} cannot forward this Event.`);
1031
+ }
1032
+ const eventId = JSON.stringify(['runtime-notification', epoch.scope.sessionId,
1033
+ epoch.scope.segmentId, pluginId, original.eventId]);
1034
+ return {
1035
+ epochSeq: epoch.epochSeq, eventId, type: original.type, producer: original.producer,
1036
+ producerPluginId: pluginId, producerOutputIndex: proposalIndex,
1037
+ sessionId: original.sessionId, segmentId: original.segmentId,
1038
+ notificationOf: original.eventId, payload: original.payload,
1039
+ notificationContent: proposal.notificationContent,
1040
+ wakeAgent: original.wakeAgent, occurredAt: original.occurredAt,
1041
+ receivedAt: new Date().toISOString(),
1042
+ source: { sourceId: `runtime-plugin:${pluginId}`, eventId: original.eventId,
1043
+ connectionId: original.connectionId, replayed: original.replayed },
1044
+ };
1045
+ }
1046
+ const eventId = this.epochEventId(epoch, pluginId, proposal, proposalIndex);
1047
+ return {
1048
+ epochSeq: epoch.epochSeq,
1049
+ type: proposal.type,
1050
+ producer: 'local_synth',
1051
+ producerPluginId: pluginId,
1052
+ producerOutputIndex: proposalIndex,
1053
+ sessionId: epoch.scope.sessionId,
1054
+ segmentId: epoch.scope.segmentId,
1055
+ wakeAgent: proposal.wakeAgent,
1056
+ payload: proposal.payload,
1057
+ notificationContent: proposal.notificationContent,
1058
+ occurredAt: proposal.occurredAt,
1059
+ receivedAt: new Date().toISOString(),
1060
+ eventId,
1061
+ source: {
1062
+ sourceId: `runtime-plugin:${pluginId}`,
1063
+ eventId,
1064
+ connectionId: epoch.connectionId,
1065
+ },
1066
+ };
1067
+ }
1068
+ pauseCadence() {
1069
+ this.cadencePaused = true;
1070
+ if (this.cadenceTimer)
1071
+ clearTimeout(this.cadenceTimer);
1072
+ this.cadenceTimer = undefined;
1073
+ }
1074
+ armCadence() {
1075
+ const cadence = this.processingCadence;
1076
+ if (!cadence || this.cadencePaused || this.closing || this.closed || this.cadenceTimer)
1077
+ return;
1078
+ const now = Date.now();
1079
+ if (this.cadenceNextAt <= now)
1080
+ this.cadenceNextAt = now + cadence.intervalMs;
1081
+ this.cadenceTimer = setTimeout(() => {
1082
+ this.cadenceTimer = undefined;
1083
+ void this.runProcessingCycle(false).catch(error => {
1084
+ this.cadenceError = error;
1085
+ this.pauseCadence();
1086
+ this.observability?.error('runtime.cycle.failed', error, {}, { component: 'runtime.cycle', scope: this.publicScope() });
1087
+ }).finally(() => {
1088
+ // Skip missed timer slots. A slow cycle never queues another invocation behind itself.
1089
+ const slots = Math.max(1, Math.floor((Date.now() - this.cadenceNextAt) / cadence.intervalMs) + 1);
1090
+ this.cadenceNextAt += slots * cadence.intervalMs;
1091
+ this.armCadence();
1092
+ });
1093
+ }, Math.max(0, this.cadenceNextAt - now));
1094
+ this.cadenceTimer.unref?.();
1095
+ }
1096
+ runProcessingCycle(notificationOnly) {
1097
+ if (this.cadenceRun)
1098
+ return this.cadenceRun;
1099
+ const cadence = this.processingCadence;
1100
+ const latest = this.cadenceLatestInput;
1101
+ if (!cadence || !latest || (!notificationOnly && !this.cadenceHasLiveInput))
1102
+ return Promise.resolve();
1103
+ if (this.cadenceError)
1104
+ return Promise.reject(this.cadenceError);
1105
+ const operation = (async () => {
1106
+ if (!sameScope(latest.scope, this.scope()))
1107
+ return;
1108
+ const nowMs = Date.now();
1109
+ const stateFrame = this.cadenceLatestStateFrame;
1110
+ const stateVersion = stateFrame?.epochSeq ?? null;
1111
+ const stateReceivedAtMs = stateFrame?.receivedAtMs ?? null;
1112
+ const cycle = {
1113
+ id: ++this.cadenceId, intervalMs: cadence.intervalMs, nowMs, notificationOnly,
1114
+ hasNewState: stateVersion !== null && stateVersion !== this.cadenceStateVersion,
1115
+ stateVersion, stateReceivedAtMs, stateAgeMs: stateReceivedAtMs === null ? null : Math.max(0, nowMs - stateReceivedAtMs),
1116
+ connectionState: this.readState(nowMs).stateStatus.connectionState,
1117
+ stateFrameSeq: stateFrame?.frameSeq ?? null, inputThroughEpoch: latest.epochSeq,
1118
+ };
1119
+ const state = cadence.createState({ latestInput: structuredClone(latest),
1120
+ latestStateFrame: stateFrame ? structuredClone(stateFrame) : null, cycle });
1121
+ // Acceptance is synchronous up to scheduler enqueue. Later Source input therefore
1122
+ // receives a newer epoch than this frozen computation, preserving Action safety.
1123
+ const accepted = await this.acceptInputBatch({ scope: latest.scope, sourceId: RUNTIME_CYCLE_SOURCE_ID,
1124
+ connectionId: latest.connectionId, sourceKey: `${this.cadenceInstanceId}:${cycle.id}`,
1125
+ ...(stateFrame?.backendTick === undefined ? {} : { domainTick: stateFrame.backendTick }),
1126
+ state: { ...state, cycle }, events: [], completeness: latest.completeness, coalescing: 'forbidden',
1127
+ receivedAt: new Date(nowMs).toISOString() });
1128
+ await this.epochCompletions.get(accepted.epoch.epochSeq);
1129
+ })();
1130
+ this.cadenceRun = operation;
1131
+ void operation.then(() => { if (this.cadenceRun === operation)
1132
+ this.cadenceRun = undefined; }, () => { if (this.cadenceRun === operation)
1133
+ this.cadenceRun = undefined; });
1134
+ return operation;
1135
+ }
1136
+ hasPendingRelayNotifications() {
1137
+ const scope = this.scope();
1138
+ for (const [pluginId, relay] of this.notificationRelays) {
1139
+ if (!relay.previousEpochOnly)
1140
+ continue;
1141
+ const cursor = this.inputJournal.pluginProgress(pluginId, scope).eventCursor;
1142
+ const types = new Set(this.pluginScheduler.descriptors().find(plugin => plugin.id === pluginId)?.consumes.events ?? []);
1143
+ if (this.repository.listCommittedEvents({ sessionId: scope.sessionId, segmentId: scope.segmentId,
1144
+ afterCommitSeq: cursor }).some(event => !event.notificationOf && event.producerPluginId
1145
+ && relay.producerPluginIds?.includes(event.producerPluginId) && (types.has('*') || types.has(event.type))))
1146
+ return true;
1147
+ }
1148
+ return false;
1149
+ }
1150
+ async drainCadence(notificationOnly) {
1151
+ if (!this.processingCadence)
1152
+ return;
1153
+ await this.cadenceRun;
1154
+ if (this.cadenceError)
1155
+ throw this.cadenceError;
1156
+ const pending = this.inputJournal.listOpen(this.scope(), 0, 1);
1157
+ if (this.cadenceLatestInput && (this.cadenceRecoveryNeedsCycle || this.cadenceLatestInput.epochSeq > this.cadenceProcessedInput || pending.length)) {
1158
+ await this.runProcessingCycle(notificationOnly);
1159
+ this.cadenceRecoveryNeedsCycle = false;
1160
+ }
1161
+ while (this.hasPendingRelayNotifications())
1162
+ await this.runProcessingCycle(true);
1163
+ }
1164
+ restoreCadenceInputs() {
1165
+ let beforeFrameSeq;
1166
+ let lastCycle;
1167
+ let lastNormalCycle;
1168
+ while (true) {
1169
+ const page = this.stateHistoryRepository.queryStateFrames({ scope: this.scope(), beforeFrameSeq, order: 'desc', limit: 100 });
1170
+ for (const frame of page.frames) {
1171
+ if (!frame.epochSeq)
1172
+ continue;
1173
+ this.latestAcceptedEpochSeq = Math.max(this.latestAcceptedEpochSeq, frame.epochSeq);
1174
+ if (frame.sourceId === RUNTIME_CYCLE_SOURCE_ID) {
1175
+ const info = frame.state.cycle;
1176
+ lastCycle ??= info;
1177
+ if (!info.notificationOnly)
1178
+ lastNormalCycle ??= info;
1179
+ continue;
1180
+ }
1181
+ this.cadenceLatestInput ??= this.inputJournal.epoch(frame.epochSeq) ?? undefined;
1182
+ if (!this.cadenceLatestStateFrame && this.projectSourceFrame(frame) !== null)
1183
+ this.cadenceLatestStateFrame = frame;
1184
+ }
1185
+ if ((this.cadenceLatestInput && this.cadenceLatestStateFrame && lastCycle && lastNormalCycle) || !page.page.hasMore || !page.frames.length)
1186
+ break;
1187
+ beforeFrameSeq = page.frames.at(-1).frameSeq;
1188
+ }
1189
+ if (lastCycle) {
1190
+ this.cadenceId = Math.max(this.cadenceId, lastCycle.id);
1191
+ this.cadenceProcessedInput = lastCycle.inputThroughEpoch;
1192
+ this.cadenceStateVersion = lastNormalCycle?.stateVersion ?? null;
1193
+ }
1194
+ }
1195
+ async commitInputEvents(work) {
1196
+ const { epoch } = work;
1197
+ if (this.processingCadence && epoch.sourceId === RUNTIME_CYCLE_SOURCE_ID) {
1198
+ const cycle = epoch.state.cycle;
1199
+ const committed = [];
1200
+ let after = this.cadenceRecoveryNeedsCycle ? 0 : this.cadenceProcessedInput;
1201
+ while (true) {
1202
+ const page = this.inputJournal.listOpen(epoch.scope, after, 500);
1203
+ if (!page.length)
1204
+ break;
1205
+ for (const source of page) {
1206
+ after = source.epochSeq;
1207
+ if (source.epochSeq > cycle.inputThroughEpoch)
1208
+ return committed;
1209
+ if (source.sourceId === RUNTIME_CYCLE_SOURCE_ID)
1210
+ continue;
1211
+ if (!this.inputJournal.inputEventsCommitted(source.epochSeq)) {
1212
+ for (const [index, event] of source.events.entries()) {
1213
+ const result = await this.eventIngress.publish(this.sourceEventInput(source, event, index));
1214
+ if (result.inserted)
1215
+ committed.push(result.event);
1216
+ }
1217
+ this.inputJournal.markInputEventsCommitted(source.epochSeq, this.repository.highWaterCommitSeq(source.scope.sessionId, source.scope.segmentId));
1218
+ }
1219
+ this.inputJournal.markClosed(source.epochSeq);
1220
+ }
1221
+ if (page.length < 500)
1222
+ break;
1223
+ }
1224
+ return committed;
1225
+ }
1226
+ const committedEvents = [];
1227
+ for (const [index, sourceEvent] of epoch.events.entries()) {
1228
+ if (!this.eventCatalog.get(sourceEvent.type)) {
1229
+ this.observability?.log('warn', 'runtime.backend_event.unregistered', {
1230
+ event_type: sourceEvent.type,
1231
+ source_id: epoch.sourceId,
1232
+ epoch_seq: epoch.epochSeq,
1233
+ }, { component: 'runtime.event-catalog', scope: this.publicScope() });
1234
+ }
1235
+ const committed = await this.eventIngress.publish(this.sourceEventInput(epoch, sourceEvent, index));
1236
+ if (committed.inserted)
1237
+ committedEvents.push(committed.event);
1238
+ }
1239
+ return committedEvents;
1240
+ }
1241
+ async recoverOpenEpochs() {
1242
+ const scope = this.scope();
1243
+ const openEpochs = [];
1244
+ let afterEpochSeq = 0;
1245
+ while (true) {
1246
+ const page = this.inputJournal.listOpen(scope, afterEpochSeq, 10_000);
1247
+ if (page.length === 0)
1248
+ break;
1249
+ openEpochs.push(...page);
1250
+ afterEpochSeq = page.at(-1).epochSeq;
1251
+ if (page.length < 10_000)
1252
+ break;
1253
+ }
1254
+ if (openEpochs.length === 0)
1255
+ return;
1256
+ const wanted = new Set(openEpochs.map((epoch) => epoch.epochSeq));
1257
+ const frameByEpoch = new Map();
1258
+ let afterFrameSeq = 0;
1259
+ while (wanted.size > 0) {
1260
+ const page = this.stateHistoryRepository.queryStateFrames({
1261
+ scope,
1262
+ afterFrameSeq,
1263
+ order: 'asc',
1264
+ limit: 10_000,
1265
+ });
1266
+ if (page.frames.length === 0)
1267
+ break;
1268
+ for (const frame of page.frames) {
1269
+ if (frame.epochSeq !== undefined && wanted.delete(frame.epochSeq)) {
1270
+ frameByEpoch.set(frame.epochSeq, frame);
1271
+ }
1272
+ }
1273
+ afterFrameSeq = page.frames.at(-1).frameSeq;
1274
+ if (!page.page.hasMore)
1275
+ break;
1276
+ }
1277
+ this.observability?.log('info', 'runtime.recovery.started', {
1278
+ open_epoch_count: openEpochs.length,
1279
+ first_epoch_seq: openEpochs[0].epochSeq,
1280
+ latest_epoch_seq: openEpochs.at(-1).epochSeq,
1281
+ }, { component: 'runtime.recovery', scope });
1282
+ const completions = openEpochs.map((epoch) => {
1283
+ this.latestAcceptedEpochSeq = Math.max(this.latestAcceptedEpochSeq, epoch.epochSeq);
1284
+ const existing = frameByEpoch.get(epoch.epochSeq);
1285
+ const frame = existing ?? this.stateHistoryRepository.appendStateFrame({
1286
+ epochSeq: epoch.epochSeq,
1287
+ scope: epoch.scope,
1288
+ sourceId: epoch.sourceId,
1289
+ connectionId: epoch.connectionId,
1290
+ sourceKey: `runtime-epoch:${epoch.epochSeq}`,
1291
+ sourceSeq: epoch.sourceSeq,
1292
+ backendTick: typeof epoch.domainTick === 'number' ? epoch.domainTick : undefined,
1293
+ observedAtMs: milliseconds(epoch.observedAt),
1294
+ receivedAtMs: milliseconds(epoch.receivedAt) ?? Date.now(),
1295
+ state: epoch.state,
1296
+ }).frame;
1297
+ if (this.processingCadence) {
1298
+ // A restarted Owner must not re-execute an old strategy decision before
1299
+ // Source reattaches. Preserve facts/progress and converge in one notification drain.
1300
+ this.cadenceRecoveryNeedsCycle = true;
1301
+ if (epoch.sourceId === RUNTIME_CYCLE_SOURCE_ID)
1302
+ this.inputJournal.markClosed(epoch.epochSeq);
1303
+ return Promise.resolve();
1304
+ }
1305
+ const previousState = this.stateHistoryRepository.queryStateFrames({
1306
+ scope,
1307
+ beforeFrameSeq: frame.frameSeq,
1308
+ order: 'desc',
1309
+ limit: 1,
1310
+ }).frames[0]?.state ?? null;
1311
+ const currentState = this.recoveredAgentState(epoch);
1312
+ this.acceptedAgentStateByEpoch.set(epoch.epochSeq, structuredClone(currentState));
1313
+ const completion = this.pluginScheduler.enqueue({
1314
+ epoch,
1315
+ frame,
1316
+ currentState,
1317
+ previousState,
1318
+ epochEvents: [],
1319
+ });
1320
+ this.trackEpochCompletion(epoch.epochSeq, completion);
1321
+ return completion;
1322
+ });
1323
+ await Promise.all(completions);
1324
+ this.observability?.log('info', 'runtime.recovery.completed', {
1325
+ recovered_epoch_count: openEpochs.length,
1326
+ ready_epoch_seq: this.readyEpochSeq,
1327
+ }, { component: 'runtime.recovery', scope });
1328
+ }
1329
+ /** Covers a crash between closing the producer epoch and accepting its follow-up. */
1330
+ async recoverPendingNotifications() {
1331
+ if (!this.followUpInput)
1332
+ return;
1333
+ const scope = this.scope();
1334
+ const latest = this.stateHistoryRepository.latestStateFrame(scope);
1335
+ if (!latest?.epochSeq)
1336
+ return;
1337
+ const epoch = this.inputJournal.epoch(latest.epochSeq);
1338
+ if (!epoch)
1339
+ return;
1340
+ const pending = new Map();
1341
+ for (const [pluginId, relay] of this.notificationRelays) {
1342
+ if (!relay.previousEpochOnly)
1343
+ continue;
1344
+ const cursor = this.inputJournal.pluginProgress(pluginId, scope).eventCursor;
1345
+ for (const event of this.repository.listCommittedEvents({ sessionId: scope.sessionId,
1346
+ segmentId: scope.segmentId, afterCommitSeq: cursor, order: 'asc' })) {
1347
+ if (!event.notificationOf && event.producerPluginId && relay.producerPluginIds?.includes(event.producerPluginId)) {
1348
+ pending.set(event.eventId, event);
1349
+ }
1350
+ }
1351
+ }
1352
+ if (!pending.size)
1353
+ return;
1354
+ const followUp = this.followUpInput(epoch, latest, [...pending.values()]);
1355
+ if (!followUp)
1356
+ return;
1357
+ await this.acceptInputBatch({ ...followUp, sourceKey: `recovery-notifications:${latest.epochSeq}` });
1358
+ await this.pluginScheduler.waitForIdle();
1359
+ }
1360
+ epochEventId(epoch, pluginId, proposal, proposalIndex) {
1361
+ const scope = proposal.dedupeScope === 'session'
1362
+ ? ['session', epoch.scope.sessionId]
1363
+ : ['segment', epoch.scope.sessionId, epoch.scope.segmentId];
1364
+ return JSON.stringify([
1365
+ 'runtime-epoch-plugin',
1366
+ pluginId,
1367
+ epoch.epochSeq,
1368
+ proposalIndex,
1369
+ ...scope,
1370
+ proposal.type,
1371
+ proposal.dedupeKey,
1372
+ ]);
1373
+ }
1374
+ projectSourceFrame(frame) {
1375
+ if (this.processingCadence && (frame.sourceId === RUNTIME_CYCLE_SOURCE_ID
1376
+ || this.processingCadence.isStateUpdate?.({ state: frame.state, sourceId: frame.sourceId ?? '' }) === false))
1377
+ return null;
1378
+ return this.currentStateFromRuntimeState(frame.state);
1379
+ }
1380
+ recoveredAgentState(epoch) {
1381
+ let afterFrameSeq;
1382
+ let projected = null;
1383
+ let observation;
1384
+ while (projected === null) {
1385
+ const page = this.stateHistoryRepository.queryStateFrames({
1386
+ scope: epoch.scope,
1387
+ toEpochSeq: epoch.epochSeq,
1388
+ ...(afterFrameSeq === undefined ? {} : { beforeFrameSeq: afterFrameSeq }),
1389
+ order: 'desc',
1390
+ limit: 1_000,
1391
+ });
1392
+ for (const candidate of page.frames) {
1393
+ projected = this.projectSourceFrame(candidate);
1394
+ if (projected !== null) {
1395
+ observation = candidate;
1396
+ break;
1397
+ }
1398
+ }
1399
+ if (projected !== null || !page.page.hasMore || page.frames.length === 0)
1400
+ break;
1401
+ afterFrameSeq = page.frames.at(-1).frameSeq;
1402
+ }
1403
+ const receivedAtMs = this.processingCadence && observation ? observation.receivedAtMs : milliseconds(epoch.receivedAt) ?? Date.now();
1404
+ return {
1405
+ state: projected === null ? null : structuredClone(projected),
1406
+ stateStatus: {
1407
+ status: projected === null ? 'unavailable' : 'fresh',
1408
+ semantics: 'latest_received',
1409
+ source: projected === null ? null : 'durable_snapshot',
1410
+ scope: this.publicScope(),
1411
+ connectionId: epoch.connectionId,
1412
+ connectionState: projected === null ? 'owner_unavailable' : 'connected',
1413
+ receivedAtMs,
1414
+ ageMs: Math.max(0, Date.now() - receivedAtMs),
1415
+ backendTick: this.processingCadence && observation ? observation.backendTick ?? null
1416
+ : typeof epoch.domainTick === 'number' ? epoch.domainTick : null,
1417
+ reason: projected === null ? 'state_not_available_at_epoch' : null,
1418
+ },
1419
+ ...(projected === null ? {
1420
+ stateError: {
1421
+ code: 'STATE_NOT_READY',
1422
+ message: 'No game-facing State exists at or before this Runtime epoch.',
1423
+ },
1424
+ } : {}),
1425
+ };
1426
+ }
1427
+ async onEpochClosed(epoch, frameSeq, result) {
1428
+ const finalizeStartedAtMs = performance.now();
1429
+ const isCurrentScope = sameScope(epoch.scope, this.scope());
1430
+ const acceptedState = this.acceptedAgentStateByEpoch.get(epoch.epochSeq)
1431
+ ?? this.recoveredAgentState(epoch);
1432
+ const previousAnchor = [...this.closedReadyAnchors.values()]
1433
+ .reverse()
1434
+ .find((candidate) => (candidate.epochSeq < epoch.epochSeq
1435
+ && sameScope(candidate.scope, epoch.scope)));
1436
+ const pluginStates = structuredClone(previousAnchor?.pluginStates ?? {});
1437
+ const domainTick = epoch.domainTick === undefined
1438
+ ? undefined
1439
+ : Number(epoch.domainTick);
1440
+ const normalizedDomainTick = domainTick !== undefined && Number.isFinite(domainTick)
1441
+ ? domainTick
1442
+ : undefined;
1443
+ for (const row of this.inputJournal.states(epoch.epochSeq)) {
1444
+ pluginStates[row.topic] = {
1445
+ pluginId: row.pluginId,
1446
+ topic: row.topic,
1447
+ value: structuredClone(row.value),
1448
+ updatedEpochSeq: epoch.epochSeq,
1449
+ ...(normalizedDomainTick === undefined ? {} : { updatedDomainTick: normalizedDomainTick }),
1450
+ };
1451
+ }
1452
+ const pluginOutcomes = Object.fromEntries(result.outcomes.map((outcome) => [
1453
+ outcome.pluginId,
1454
+ {
1455
+ pluginId: outcome.pluginId,
1456
+ epochSeq: epoch.epochSeq,
1457
+ ...(normalizedDomainTick === undefined ? {} : { domainTick: normalizedDomainTick }),
1458
+ outcome: outcome.outcome,
1459
+ ...(outcome.reason === undefined ? {} : { reason: outcome.reason }),
1460
+ },
1461
+ ]));
1462
+ const anchor = {
1463
+ scope: structuredClone(epoch.scope),
1464
+ state: structuredClone(acceptedState),
1465
+ pluginStates,
1466
+ pluginOutcomes,
1467
+ frameSeq,
1468
+ eventWatermark: result.eventWatermark,
1469
+ epochSeq: epoch.epochSeq,
1470
+ };
1471
+ this.closedReadyAnchors.set(epoch.epochSeq, anchor);
1472
+ while (this.closedReadyAnchors.size > CLOSED_READY_ANCHOR_LIMIT) {
1473
+ const oldest = this.closedReadyAnchors.keys().next().value;
1474
+ if (oldest === undefined)
1475
+ break;
1476
+ this.closedReadyAnchors.delete(oldest);
1477
+ }
1478
+ this.epochCompletions.delete(epoch.epochSeq);
1479
+ if (isCurrentScope) {
1480
+ this.readyScope = structuredClone(epoch.scope);
1481
+ this.readyEpochSeq = epoch.epochSeq;
1482
+ this.readyFrameSeq = frameSeq;
1483
+ this.readyState = structuredClone(acceptedState);
1484
+ this.readyPluginStates = structuredClone(pluginStates);
1485
+ this.readyPluginOutcomes = structuredClone(pluginOutcomes);
1486
+ this.readyEventWatermark = result.eventWatermark;
1487
+ }
1488
+ const closedEvents = isCurrentScope && (this.followUpInput || this.readyObservers.length)
1489
+ ? this.repository.listCommittedEvents({ sessionId: epoch.scope.sessionId, segmentId: epoch.scope.segmentId,
1490
+ ...(this.processingCadence ? { afterEpochSeq: previousAnchor?.epochSeq ?? 0, maxEpochSeq: epoch.epochSeq }
1491
+ : { epochSeq: epoch.epochSeq }), maxCommitSeq: result.eventWatermark, order: 'asc' }) : [];
1492
+ if (isCurrentScope && this.processingCadence && epoch.sourceId === RUNTIME_CYCLE_SOURCE_ID) {
1493
+ const cycle = epoch.state.cycle;
1494
+ this.cadenceProcessedInput = cycle.inputThroughEpoch;
1495
+ if (!cycle.notificationOnly)
1496
+ this.cadenceStateVersion = cycle.stateVersion;
1497
+ }
1498
+ if (isCurrentScope && this.followUpInput && !this.processingCadence) {
1499
+ const latest = this.stateHistoryRepository.latestStateFrame(epoch.scope);
1500
+ const followUp = latest && this.followUpInput(epoch, latest, closedEvents);
1501
+ if (followUp)
1502
+ await this.acceptInputBatch(followUp);
1503
+ }
1504
+ for (const acceptedEpochSeq of this.acceptedAgentStateByEpoch.keys()) {
1505
+ if (acceptedEpochSeq <= epoch.epochSeq)
1506
+ this.acceptedAgentStateByEpoch.delete(acceptedEpochSeq);
1507
+ }
1508
+ const intakeTiming = this.epochIntakeTimings.get(epoch.epochSeq);
1509
+ this.epochIntakeTimings.delete(epoch.epochSeq);
1510
+ const finalizeMs = Math.max(0, performance.now() - finalizeStartedAtMs);
1511
+ const totalMs = intakeTiming
1512
+ ? Math.max(0, performance.now() - intakeTiming.startedAtMs)
1513
+ : result.durationMs + finalizeMs;
1514
+ const longestPlugin = [...result.outcomes].sort((left, right) => right.durationMs - left.durationMs)[0];
1515
+ const persistenceHealth = this.repository.persistenceHealth?.();
1516
+ this.observability?.log('debug', 'runtime.view.ready', {
1517
+ epoch_seq: epoch.epochSeq,
1518
+ latest_epoch_seq: this.latestAcceptedEpochSeq,
1519
+ lag: Math.max(0, this.latestAcceptedEpochSeq - epoch.epochSeq),
1520
+ frame_seq: frameSeq,
1521
+ event_watermark: result.eventWatermark,
1522
+ current_scope: isCurrentScope,
1523
+ total_duration_ms: Math.round(totalMs * 1_000) / 1_000,
1524
+ received_to_ready_ms: Math.max(0, Date.now() - (milliseconds(epoch.receivedAt) ?? Date.now())),
1525
+ intake_duration_ms: Math.round((intakeTiming?.intakeTotalMs ?? 0) * 1_000) / 1_000,
1526
+ scheduler_duration_ms: Math.round(result.durationMs * 1_000) / 1_000,
1527
+ ready_view_finalize_ms: Math.round(finalizeMs * 1_000) / 1_000,
1528
+ longest_plugin_id: longestPlugin?.pluginId,
1529
+ longest_plugin_duration_ms: longestPlugin
1530
+ ? Math.round(longestPlugin.durationMs * 1_000) / 1_000
1531
+ : 0,
1532
+ persistence_pending_operations: persistenceHealth?.pendingOperations,
1533
+ persistence_degraded: persistenceHealth?.degraded,
1534
+ }, { component: 'runtime.view', scope: this.publicScope() });
1535
+ if (isCurrentScope) {
1536
+ for (const plugin of this.readyObservers) {
1537
+ const types = new Set(plugin.consumes?.events ?? []);
1538
+ try {
1539
+ plugin.afterReady({ scope: structuredClone(epoch.scope), epochSeq: epoch.epochSeq,
1540
+ eventWatermark: result.eventWatermark,
1541
+ events: structuredClone(closedEvents.filter(event => types.has('*') || types.has(event.type))) });
1542
+ }
1543
+ catch (error) {
1544
+ // Output failure cannot roll back or block an already published game view.
1545
+ this.observability?.error('runtime.ready_observer.failed', error, { plugin_id: plugin.id, epoch_seq: epoch.epochSeq }, { component: 'runtime.view', scope: this.publicScope() });
1546
+ }
1547
+ }
1548
+ }
1549
+ }
1550
+ resetReadyView(scope) {
1551
+ this.readyScope = structuredClone(scope);
1552
+ this.readyState = this.readAgentState();
1553
+ this.readyFrameSeq = 0;
1554
+ this.readyEventWatermark = 0;
1555
+ this.readyEpochSeq = 0;
1556
+ this.readyPluginStates = {};
1557
+ this.readyPluginOutcomes = {};
1558
+ }
1559
+ trackEpochCompletion(epochSeq, completion) {
1560
+ this.epochCompletions.set(epochSeq, completion);
1561
+ void completion.catch(() => {
1562
+ if (!this.closedReadyAnchors.has(epochSeq))
1563
+ this.epochCompletions.delete(epochSeq);
1564
+ });
1565
+ }
1566
+ readyViewFromAnchor(anchor, afterCommitSeq, limit) {
1567
+ const boundedLimit = Math.max(1, Math.min(500, Math.trunc(limit) || 100));
1568
+ const pending = this.repository.listCommittedEvents({
1569
+ sessionId: anchor.scope.sessionId,
1570
+ segmentId: anchor.scope.segmentId,
1571
+ afterCommitSeq,
1572
+ maxCommitSeq: anchor.eventWatermark,
1573
+ maxEpochSeq: anchor.epochSeq,
1574
+ order: 'asc',
1575
+ limit: boundedLimit + 1,
1576
+ });
1577
+ const events = pending.slice(0, boundedLimit);
1578
+ return {
1579
+ scope: this.publicScopeFor(anchor.scope),
1580
+ state: structuredClone(anchor.state),
1581
+ pluginStates: structuredClone(anchor.pluginStates),
1582
+ pluginOutcomes: structuredClone(anchor.pluginOutcomes),
1583
+ events,
1584
+ throughCommitSeq: events.at(-1)?.commitSeq ?? afterCommitSeq,
1585
+ frameSeq: anchor.frameSeq,
1586
+ eventWatermark: anchor.eventWatermark,
1587
+ epochSeq: anchor.epochSeq,
1588
+ hasMore: pending.length > events.length,
1589
+ };
1590
+ }
1591
+ pluginCapabilityAccess(plugin, scope, signal, epochSeq) {
1592
+ const provided = new Set(plugin.capabilities?.provides ?? []);
1593
+ const used = new Set(plugin.capabilities?.uses ?? []);
1594
+ const requireDeclared = (kind, capability) => {
1595
+ const declarations = kind === 'provide' ? provided : used;
1596
+ if (!declarations.has(capability)) {
1597
+ throw new Error(`Runtime Epoch Plugin ${plugin.id} did not declare capability ${kind} ${capability}.`);
1598
+ }
1599
+ };
1600
+ const requireCurrentScope = () => {
1601
+ if (!sameScope(scope, this.scope())) {
1602
+ throw new Error(`Runtime Epoch Plugin ${plugin.id} capability scope is no longer active.`);
1603
+ }
1604
+ };
1605
+ return Object.freeze({
1606
+ provideObservation: (provider) => {
1607
+ requireCurrentScope();
1608
+ requireDeclared('provide', provider.capability);
1609
+ const scopedProvider = {
1610
+ capability: provider.capability,
1611
+ query: (request, requestedScope, queryContext) => {
1612
+ if (!sameScope(scope, requestedScope) || !sameScope(scope, this.scope())) {
1613
+ throw new Error(`Runtime Epoch Plugin ${plugin.id} capability scope is no longer active.`);
1614
+ }
1615
+ return provider.query(request, requestedScope, queryContext);
1616
+ },
1617
+ };
1618
+ return this.observations.register(scopedProvider);
1619
+ },
1620
+ provideAction: (service) => {
1621
+ requireCurrentScope();
1622
+ requireDeclared('provide', service.capability);
1623
+ const scopedService = {
1624
+ capability: service.capability,
1625
+ ...(service.describeControl
1626
+ ? {
1627
+ describeControl: (action, requestedScope, caller) => service.describeControl(action, requestedScope, caller),
1628
+ }
1629
+ : {}),
1630
+ perform: (action, requestedScope, caller, actionContext) => {
1631
+ if (!sameScope(scope, requestedScope) || !sameScope(scope, this.scope())) {
1632
+ throw new Error(`Runtime Epoch Plugin ${plugin.id} capability scope is no longer active.`);
1633
+ }
1634
+ return service.perform(action, requestedScope, caller, actionContext);
1635
+ },
1636
+ };
1637
+ return this.actions.register(scopedService);
1638
+ },
1639
+ queryObservation: (capability, request) => {
1640
+ requireCurrentScope();
1641
+ requireDeclared('use', capability);
1642
+ const stateFrame = this.stateHistoryRepository.queryStateFrames({
1643
+ scope,
1644
+ fromEpochSeq: epochSeq,
1645
+ toEpochSeq: epochSeq,
1646
+ order: 'desc',
1647
+ limit: 1,
1648
+ }).frames[0];
1649
+ return this.observations.query(capability, request, scope, {
1650
+ epochSeq,
1651
+ ...(stateFrame === undefined ? {} : { stateFrame: structuredClone(stateFrame) }),
1652
+ });
1653
+ },
1654
+ performAction: (capability, action, caller = { kind: 'system', id: `runtime-plugin:${plugin.id}` }) => {
1655
+ requireCurrentScope();
1656
+ requireDeclared('use', capability);
1657
+ return this.actions.perform(capability, action, scope, caller, {
1658
+ isAuthorized: () => !signal.aborted && sameScope(scope, this.scope()),
1659
+ latestAcceptedState: () => this.latestAcceptedActionState(scope),
1660
+ });
1661
+ },
1662
+ });
1663
+ }
1664
+ latestAcceptedActionState(scope) {
1665
+ if (!sameScope(scope, this.scope()))
1666
+ return null;
1667
+ const frame = this.stateHistoryRepository.latestStateFrame(scope);
1668
+ if (!frame || frame.epochSeq === undefined)
1669
+ return null;
1670
+ return {
1671
+ epochSeq: frame.epochSeq,
1672
+ state: structuredClone(frame.state),
1673
+ };
1674
+ }
1675
+ persistTransition(transition) {
1676
+ if (transition.type === 'session_opened') {
1677
+ this.actions.activateScope(runtimeScope(transition.snapshot));
1678
+ this.repository.saveSession(eventSession(transition.snapshot, true));
1679
+ this.repository.saveSegment(eventSegment(transition.snapshot.segment, true));
1680
+ this.openStateScope(transition.snapshot);
1681
+ return;
1682
+ }
1683
+ if (transition.type === 'session_updated') {
1684
+ this.repository.saveSession(eventSession(transition.snapshot, true));
1685
+ return;
1686
+ }
1687
+ if (transition.type === 'segment_updated') {
1688
+ this.repository.saveSegment(eventSegment(transition.snapshot.segment, true));
1689
+ return;
1690
+ }
1691
+ if (transition.type === 'segment_changed') {
1692
+ this.actions.activateScope(runtimeScope(transition.snapshot));
1693
+ // Save the new current segment first: repository implementations use the
1694
+ // old current pointer to defer unread details into backlog atomically.
1695
+ this.repository.saveSegment(eventSegment(transition.snapshot.segment, true));
1696
+ if (transition.previous) {
1697
+ this.repository.saveSegment(eventSegment(transition.previous, false));
1698
+ const previousScope = {
1699
+ adapterId: transition.snapshot.session.adapterId,
1700
+ accountId: transition.snapshot.session.accountId,
1701
+ sessionId: transition.snapshot.session.id,
1702
+ segmentId: transition.previous.id,
1703
+ segmentSeq: transition.previous.ordinal,
1704
+ };
1705
+ this.stateHistoryRepository.sealScope(previousScope, Date.parse(transition.snapshot.segment.startedAt));
1706
+ }
1707
+ this.openStateScope(transition.snapshot);
1708
+ return;
1709
+ }
1710
+ if (transition.type === 'session_closed') {
1711
+ this.repository.saveSegment(eventSegment(transition.snapshot.segment, false));
1712
+ this.repository.saveSession(eventSession(transition.snapshot, false));
1713
+ this.stateHistoryRepository.sealScope(runtimeScope(transition.snapshot));
1714
+ }
1715
+ }
1716
+ openStateScope(snapshot, historyComplete = true) {
1717
+ const scope = runtimeScope(snapshot);
1718
+ const atMs = Date.parse(snapshot.segment.startedAt);
1719
+ this.stateIngress.openScope(scope, Number.isFinite(atMs) ? atMs : Date.now());
1720
+ this.historyWriter.openScope(scope, Number.isFinite(atMs) ? atMs : Date.now(), historyComplete);
1721
+ }
1722
+ connectionKey(sourceId, connectionId) {
1723
+ return `${sourceId}\u001f${connectionId}`;
1724
+ }
1725
+ enqueueOwnerRestartGap(kind, connectionId, atMs = Date.now()) {
1726
+ const record = {
1727
+ recordId: randomUUID(),
1728
+ scope: this.scope(),
1729
+ connectionId,
1730
+ subjectId: '__owner__',
1731
+ subjectKind: 'system',
1732
+ kind,
1733
+ sourceType: 'local_lifecycle',
1734
+ sourceKey: `owner-restart:${kind}:${atMs}`,
1735
+ receivedAtMs: atMs,
1736
+ attributes: { reason: 'owner_restart' },
1737
+ };
1738
+ this.historyWriter.enqueue([record]);
1739
+ }
1740
+ sealDurableScope(scope) {
1741
+ const now = new Date().toISOString();
1742
+ this.repository.saveSegment({
1743
+ ...scope.segment,
1744
+ status: 'closed',
1745
+ isCurrent: false,
1746
+ closedAt: scope.segment.closedAt ?? now,
1747
+ });
1748
+ this.repository.saveSession({
1749
+ ...scope.session,
1750
+ status: 'sealed',
1751
+ isCurrent: false,
1752
+ sealedAt: scope.session.sealedAt ?? now,
1753
+ });
1754
+ }
1755
+ assertOpen() {
1756
+ if (this.closed)
1757
+ throw new Error('Runtime is closed.');
1758
+ if (this.closing)
1759
+ throw new Error('Runtime is closing.');
1760
+ if (this.fatalError)
1761
+ throw this.fatalError;
1762
+ }
1763
+ assertSourceInputOpen() {
1764
+ if (this.closed || !this.sourceInputOpen)
1765
+ throw new Error('Runtime input is closed.');
1766
+ if (this.fatalError)
1767
+ throw this.fatalError;
1768
+ }
1769
+ assertExpectedScope(expected) {
1770
+ this.assertOpen();
1771
+ const scope = this.scope();
1772
+ if (scope.sessionId !== expected.sessionId || scope.segmentId !== expected.segmentId) {
1773
+ throw new Error('runtime_scope_changed');
1774
+ }
1775
+ return scope;
1776
+ }
1777
+ onHistoryWriterHealthChanged(health) {
1778
+ const degradedScopes = this.historyWriter.degradedScopeHealth();
1779
+ // Queue depth changes on normal frames, so it is intentionally excluded
1780
+ // from transition identity. A new affected scope or reason is a real
1781
+ // health transition and is emitted once.
1782
+ const signature = JSON.stringify({
1783
+ status: health.status,
1784
+ scopes: degradedScopes.map((entry) => ({
1785
+ scope: {
1786
+ adapterId: entry.scope.adapterId,
1787
+ sessionId: entry.scope.sessionId,
1788
+ segmentId: entry.scope.segmentId,
1789
+ segmentSeq: entry.scope.segmentSeq,
1790
+ },
1791
+ reason: entry.reason,
1792
+ })),
1793
+ });
1794
+ if (signature === this.lastHistoryWriterHealthSignature)
1795
+ return;
1796
+ const previous = this.lastHistoryWriterHealthSignature;
1797
+ this.lastHistoryWriterHealthSignature = signature;
1798
+ if (previous === null && health.status === 'healthy')
1799
+ return;
1800
+ const activeScope = degradedScopes[0]?.scope ?? this.scope();
1801
+ const { accountId: _accountId, ...scope } = activeScope;
1802
+ this.observability?.log(health.status === 'degraded' ? 'warn' : 'info', 'runtime.state_history.writer_health_changed', {
1803
+ status: health.status,
1804
+ reason: health.reason,
1805
+ queue_depth: health.queueDepth,
1806
+ dropped_record_count: health.droppedRecordCount,
1807
+ degraded_since_ms: health.degradedSinceMs,
1808
+ degraded_scope_count: degradedScopes.length,
1809
+ }, { component: 'runtime.state-history', scope });
1810
+ }
1811
+ }