@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,716 @@
1
+ import { createHash } from 'crypto';
2
+ import { createRequire } from 'module';
3
+ import { mkdirSync } from 'fs';
4
+ import { dirname } from 'path';
5
+ import { loadNodeSqliteModule } from '../load-node-sqlite.js';
6
+ import { cloneCanonical, runtimeScopeKey } from '../state/types.js';
7
+ const localRequire = createRequire(import.meta.url);
8
+ function canonicalPayload(batch) {
9
+ return {
10
+ scope: batch.scope,
11
+ sourceId: batch.sourceId,
12
+ connectionId: batch.connectionId,
13
+ sourceKey: batch.sourceKey,
14
+ sourceSeq: batch.sourceSeq,
15
+ domainTick: batch.domainTick,
16
+ state: batch.state,
17
+ events: batch.events,
18
+ eventWatermark: batch.eventWatermark,
19
+ completeness: batch.completeness,
20
+ coalescing: batch.coalescing,
21
+ observedAt: batch.observedAt,
22
+ };
23
+ }
24
+ function payloadHash(batch) {
25
+ return createHash('sha256').update(JSON.stringify(canonicalPayload(batch))).digest('hex');
26
+ }
27
+ function assertOptionalSequence(value, field) {
28
+ if (value === undefined)
29
+ return;
30
+ if (typeof value === 'number' && Number.isFinite(value))
31
+ return;
32
+ if (typeof value === 'string' && value.length > 0)
33
+ return;
34
+ throw new TypeError(`Runtime InputBatch ${field} must be a finite number or non-empty string.`);
35
+ }
36
+ function assertOptionalTimestamp(value, field) {
37
+ if (value === undefined)
38
+ return;
39
+ if (typeof value !== 'string' || !Number.isFinite(Date.parse(value))) {
40
+ throw new TypeError(`Runtime InputBatch ${field} must be an ISO timestamp.`);
41
+ }
42
+ }
43
+ export function assertRuntimeInputBatch(batch) {
44
+ if (!batch || typeof batch !== 'object')
45
+ throw new TypeError('Runtime InputBatch is required.');
46
+ if (!batch.scope || typeof batch.scope !== 'object') {
47
+ throw new TypeError('Runtime InputBatch scope is required.');
48
+ }
49
+ for (const key of ['adapterId', 'accountId', 'sessionId', 'segmentId']) {
50
+ if (typeof batch.scope[key] !== 'string' || !batch.scope[key].trim()) {
51
+ throw new TypeError(`Runtime InputBatch scope.${key} is required.`);
52
+ }
53
+ }
54
+ if (batch.scope.segmentSeq !== undefined
55
+ && (!Number.isInteger(batch.scope.segmentSeq) || batch.scope.segmentSeq <= 0)) {
56
+ throw new TypeError('Runtime InputBatch scope.segmentSeq must be a positive integer.');
57
+ }
58
+ if (typeof batch.sourceId !== 'string' || !batch.sourceId.trim()) {
59
+ throw new TypeError('Runtime InputBatch sourceId is required.');
60
+ }
61
+ if (typeof batch.connectionId !== 'string' || !batch.connectionId.trim()) {
62
+ throw new TypeError('Runtime InputBatch connectionId is required.');
63
+ }
64
+ if (typeof batch.sourceKey !== 'string' || !batch.sourceKey.trim()) {
65
+ throw new TypeError('Runtime InputBatch sourceKey is required.');
66
+ }
67
+ assertOptionalSequence(batch.sourceSeq, 'sourceSeq');
68
+ assertOptionalSequence(batch.domainTick, 'domainTick');
69
+ assertOptionalSequence(batch.eventWatermark, 'eventWatermark');
70
+ if (!batch.state || typeof batch.state !== 'object' || Array.isArray(batch.state)) {
71
+ throw new TypeError('Runtime InputBatch requires one complete State object.');
72
+ }
73
+ if (!Array.isArray(batch.events))
74
+ throw new TypeError('Runtime InputBatch events must be an explicit array.');
75
+ for (const [index, event] of batch.events.entries()) {
76
+ if (!event || typeof event !== 'object' || Array.isArray(event)) {
77
+ throw new TypeError(`Runtime InputBatch Event ${index} must be an object.`);
78
+ }
79
+ if (typeof event.type !== 'string' || !event.type.trim()) {
80
+ throw new TypeError(`Runtime InputBatch Event ${index} requires type.`);
81
+ }
82
+ if (!event.payload || typeof event.payload !== 'object' || Array.isArray(event.payload)) {
83
+ throw new TypeError(`Runtime InputBatch Event ${index} requires an object payload.`);
84
+ }
85
+ if (event.producer !== undefined
86
+ && event.producer !== 'backend_push'
87
+ && event.producer !== 'local_synth') {
88
+ throw new TypeError(`Runtime InputBatch Event ${index} producer is invalid.`);
89
+ }
90
+ if (event.sourceEventId !== undefined
91
+ && (typeof event.sourceEventId !== 'string' || !event.sourceEventId.trim())) {
92
+ throw new TypeError(`Runtime InputBatch Event ${index} sourceEventId must be a non-empty string.`);
93
+ }
94
+ assertOptionalSequence(event.sourceSeq, `Event ${index} sourceSeq`);
95
+ assertOptionalTimestamp(event.observedAt, `Event ${index} observedAt`);
96
+ assertOptionalTimestamp(event.receivedAt, `Event ${index} receivedAt`);
97
+ if (event.replayed !== undefined && typeof event.replayed !== 'boolean') {
98
+ throw new TypeError(`Runtime InputBatch Event ${index} replayed must be a boolean.`);
99
+ }
100
+ if (event.checkpoint !== undefined && typeof event.checkpoint !== 'string') {
101
+ throw new TypeError(`Runtime InputBatch Event ${index} checkpoint must be a string.`);
102
+ }
103
+ }
104
+ if (batch.completeness !== 'complete' && batch.completeness !== 'best_effort') {
105
+ throw new TypeError('Runtime InputBatch completeness is invalid.');
106
+ }
107
+ if (batch.coalescing !== undefined
108
+ && batch.coalescing !== 'allowed'
109
+ && batch.coalescing !== 'forbidden') {
110
+ throw new TypeError('Runtime InputBatch coalescing is invalid.');
111
+ }
112
+ assertOptionalTimestamp(batch.observedAt, 'observedAt');
113
+ if (typeof batch.receivedAt !== 'string' || !Number.isFinite(Date.parse(batch.receivedAt))) {
114
+ throw new TypeError('Runtime InputBatch receivedAt must be an ISO timestamp.');
115
+ }
116
+ }
117
+ function sourceIdentity(batch) {
118
+ return [runtimeScopeKey(batch.scope), batch.sourceId, batch.sourceKey].join('\u001f');
119
+ }
120
+ export class RuntimeInputConflictError extends Error {
121
+ sourceId;
122
+ sourceKey;
123
+ constructor(sourceId, sourceKey) {
124
+ super(`Runtime input ${sourceId}/${sourceKey} was retried with different content.`);
125
+ this.sourceId = sourceId;
126
+ this.sourceKey = sourceKey;
127
+ this.name = 'RuntimeInputConflictError';
128
+ }
129
+ }
130
+ export class MemoryRuntimeInputJournal {
131
+ epochs = [];
132
+ epochsBySeq = new Map();
133
+ epochsByScope = new Map();
134
+ hashes = new Map();
135
+ byIdentity = new Map();
136
+ closed = new Set();
137
+ inputEventCommits = new Set();
138
+ eventWatermarks = new Map();
139
+ progress = new Map();
140
+ pluginOutcomeRecords = [];
141
+ pluginOutcomeRecordsByEpoch = new Map();
142
+ stateRecords = [];
143
+ stateRecordsByEpoch = new Map();
144
+ diagnosticCounts() {
145
+ return {
146
+ epochs: this.epochs.length,
147
+ closed_epochs: this.closed.size,
148
+ input_event_commits: this.inputEventCommits.size,
149
+ event_watermarks: this.eventWatermarks.size,
150
+ plugin_progress: this.progress.size,
151
+ plugin_records: this.pluginOutcomeRecords.length,
152
+ plugin_states: this.stateRecords.length,
153
+ };
154
+ }
155
+ nextEpochSeq = 1;
156
+ constructor(snapshot) {
157
+ if (!snapshot)
158
+ return;
159
+ for (const item of snapshot.epochs) {
160
+ const epoch = cloneCanonical(item.epoch);
161
+ const identity = sourceIdentity(epoch);
162
+ this.epochs.push(epoch);
163
+ this.indexEpoch(epoch);
164
+ this.byIdentity.set(identity, epoch);
165
+ this.hashes.set(identity, payloadHash(epoch));
166
+ if (item.closed)
167
+ this.closed.add(epoch.epochSeq);
168
+ if (item.inputEventsCommitted)
169
+ this.inputEventCommits.add(epoch.epochSeq);
170
+ if (item.eventWatermark > 0)
171
+ this.eventWatermarks.set(epoch.epochSeq, item.eventWatermark);
172
+ }
173
+ for (const item of snapshot.pluginProgress) {
174
+ this.progress.set(`${runtimeScopeKey(item.scope)}\u001f${item.progress.pluginId}`, cloneCanonical(item.progress));
175
+ }
176
+ for (const record of snapshot.pluginRecords)
177
+ this.indexPluginRecord(cloneCanonical(record));
178
+ for (const record of snapshot.states)
179
+ this.indexStateRecord(cloneCanonical(record));
180
+ this.nextEpochSeq = Math.max(snapshot.nextEpochSeq, 1);
181
+ }
182
+ snapshot() {
183
+ const scopeByKey = new Map();
184
+ for (const epoch of this.epochs)
185
+ scopeByKey.set(runtimeScopeKey(epoch.scope), epoch.scope);
186
+ const pluginProgress = [];
187
+ for (const [key, progress] of this.progress) {
188
+ const scopeKey = key.slice(0, key.lastIndexOf('\u001f'));
189
+ const scope = scopeByKey.get(scopeKey);
190
+ if (scope)
191
+ pluginProgress.push({ scope: cloneCanonical(scope), progress: cloneCanonical(progress) });
192
+ }
193
+ return cloneCanonical({
194
+ epochs: this.epochs.map((epoch) => ({
195
+ epoch,
196
+ closed: this.closed.has(epoch.epochSeq),
197
+ inputEventsCommitted: this.inputEventCommits.has(epoch.epochSeq),
198
+ eventWatermark: this.eventWatermarks.get(epoch.epochSeq) ?? 0,
199
+ })),
200
+ pluginProgress,
201
+ pluginRecords: this.pluginOutcomeRecords,
202
+ states: this.stateRecords,
203
+ nextEpochSeq: this.nextEpochSeq,
204
+ });
205
+ }
206
+ accept(batch) {
207
+ assertRuntimeInputBatch(batch);
208
+ const identity = sourceIdentity(batch);
209
+ const hash = payloadHash(batch);
210
+ const existing = this.byIdentity.get(identity);
211
+ if (existing) {
212
+ if (this.hashes.get(identity) !== hash)
213
+ throw new RuntimeInputConflictError(batch.sourceId, batch.sourceKey);
214
+ return { inserted: false, epoch: cloneCanonical(existing) };
215
+ }
216
+ const epoch = {
217
+ ...cloneCanonical(batch),
218
+ epochSeq: this.nextEpochSeq++,
219
+ };
220
+ this.epochs.push(epoch);
221
+ this.indexEpoch(epoch);
222
+ this.byIdentity.set(identity, epoch);
223
+ this.hashes.set(identity, hash);
224
+ return { inserted: true, epoch: cloneCanonical(epoch) };
225
+ }
226
+ epoch(epochSeq) {
227
+ const value = this.epochsBySeq.get(epochSeq);
228
+ return value ? cloneCanonical(value) : null;
229
+ }
230
+ list(scope, afterEpochSeq = 0, limit = 100) {
231
+ return (this.epochsByScope.get(runtimeScopeKey(scope)) ?? [])
232
+ .filter((item) => item.epochSeq > afterEpochSeq)
233
+ .slice(0, Math.max(1, Math.min(limit, 10_000)))
234
+ .map(cloneCanonical);
235
+ }
236
+ listOpen(scope, afterEpochSeq = 0, limit = 100) {
237
+ return (this.epochsByScope.get(runtimeScopeKey(scope)) ?? [])
238
+ .filter((item) => (item.epochSeq > afterEpochSeq
239
+ && !this.closed.has(item.epochSeq)))
240
+ .slice(0, Math.max(1, Math.min(limit, 10_000)))
241
+ .map(cloneCanonical);
242
+ }
243
+ markClosed(epochSeq, _closedAt, _durationMs) {
244
+ this.closed.add(epochSeq);
245
+ }
246
+ eventWatermarkThrough(scope, epochSeq) {
247
+ const epochs = this.epochsByScope.get(runtimeScopeKey(scope)) ?? [];
248
+ let maximum = 0;
249
+ for (const candidate of epochs) {
250
+ if (candidate.epochSeq > epochSeq)
251
+ break;
252
+ maximum = Math.max(maximum, this.eventWatermarks.get(candidate.epochSeq) ?? 0);
253
+ }
254
+ return maximum;
255
+ }
256
+ inputEventsCommitted(epochSeq) {
257
+ return this.inputEventCommits.has(epochSeq);
258
+ }
259
+ markInputEventsCommitted(epochSeq, eventWatermark) {
260
+ this.inputEventCommits.add(epochSeq);
261
+ this.eventWatermarks.set(epochSeq, Math.max(this.eventWatermarks.get(epochSeq) ?? 0, eventWatermark));
262
+ }
263
+ markEventWatermark(epochSeq, eventWatermark) {
264
+ this.eventWatermarks.set(epochSeq, Math.max(this.eventWatermarks.get(epochSeq) ?? 0, eventWatermark));
265
+ }
266
+ recordPlugin(record) {
267
+ const epochRecords = this.pluginOutcomeRecordsByEpoch.get(record.epochSeq) ?? [];
268
+ const index = epochRecords.findIndex((candidate) => (candidate.epochSeq === record.epochSeq && candidate.pluginId === record.pluginId));
269
+ const stored = cloneCanonical(record);
270
+ if (index >= 0) {
271
+ const previous = epochRecords[index];
272
+ epochRecords[index] = stored;
273
+ const allIndex = this.pluginOutcomeRecords.indexOf(previous);
274
+ if (allIndex >= 0)
275
+ this.pluginOutcomeRecords[allIndex] = stored;
276
+ }
277
+ else
278
+ this.indexPluginRecord(stored);
279
+ }
280
+ pluginRecords(epochSeq) {
281
+ return (this.pluginOutcomeRecordsByEpoch.get(epochSeq) ?? [])
282
+ .sort((a, b) => a.pluginId.localeCompare(b.pluginId))
283
+ .map(cloneCanonical);
284
+ }
285
+ pluginProgress(pluginId, scope) {
286
+ return cloneCanonical(this.progress.get(`${runtimeScopeKey(scope)}\u001f${pluginId}`) ?? {
287
+ pluginId,
288
+ completedThroughEpochSeq: 0,
289
+ eventCursor: 0,
290
+ updatedAt: new Date(0).toISOString(),
291
+ });
292
+ }
293
+ savePluginProgress(progress, scope) {
294
+ this.progress.set(`${runtimeScopeKey(scope)}\u001f${progress.pluginId}`, cloneCanonical(progress));
295
+ }
296
+ saveStates(records) {
297
+ for (const record of records) {
298
+ const epochRecords = this.stateRecordsByEpoch.get(record.epochSeq) ?? [];
299
+ const index = epochRecords.findIndex((candidate) => (candidate.pluginId === record.pluginId && candidate.topic === record.topic));
300
+ const stored = cloneCanonical(record);
301
+ if (index >= 0) {
302
+ const previous = epochRecords[index];
303
+ epochRecords[index] = stored;
304
+ const allIndex = this.stateRecords.indexOf(previous);
305
+ if (allIndex >= 0)
306
+ this.stateRecords[allIndex] = stored;
307
+ }
308
+ else
309
+ this.indexStateRecord(stored);
310
+ }
311
+ }
312
+ states(epochSeq) {
313
+ return (this.stateRecordsByEpoch.get(epochSeq) ?? []).map(cloneCanonical);
314
+ }
315
+ indexEpoch(epoch) {
316
+ this.epochsBySeq.set(epoch.epochSeq, epoch);
317
+ const key = runtimeScopeKey(epoch.scope);
318
+ const scoped = this.epochsByScope.get(key) ?? [];
319
+ scoped.push(epoch);
320
+ this.epochsByScope.set(key, scoped);
321
+ }
322
+ indexPluginRecord(record) {
323
+ this.pluginOutcomeRecords.push(record);
324
+ const rows = this.pluginOutcomeRecordsByEpoch.get(record.epochSeq) ?? [];
325
+ rows.push(record);
326
+ this.pluginOutcomeRecordsByEpoch.set(record.epochSeq, rows);
327
+ }
328
+ indexStateRecord(record) {
329
+ this.stateRecords.push(record);
330
+ const rows = this.stateRecordsByEpoch.get(record.epochSeq) ?? [];
331
+ rows.push(record);
332
+ this.stateRecordsByEpoch.set(record.epochSeq, rows);
333
+ }
334
+ }
335
+ function parseJson(value) {
336
+ if (typeof value !== 'string')
337
+ throw new Error('Runtime Input Journal contains invalid JSON.');
338
+ return JSON.parse(value);
339
+ }
340
+ function numberValue(value) {
341
+ return typeof value === 'bigint' ? Number(value) : Number(value ?? 0);
342
+ }
343
+ export class SqliteRuntimeInputJournal {
344
+ db;
345
+ constructor(path) {
346
+ const sqlite = loadNodeSqliteModule(localRequire);
347
+ if (typeof sqlite.DatabaseSync !== 'function')
348
+ throw new Error('node:sqlite is unavailable in this Node.js runtime');
349
+ if (path !== ':memory:')
350
+ mkdirSync(dirname(path), { recursive: true });
351
+ this.db = new sqlite.DatabaseSync(path);
352
+ this.initialize();
353
+ }
354
+ accept(batch) {
355
+ assertRuntimeInputBatch(batch);
356
+ const hash = payloadHash(batch);
357
+ const existing = this.findByIdentity(batch.scope, batch.sourceId, batch.sourceKey);
358
+ if (existing) {
359
+ if (String(existing.payload_hash) !== hash)
360
+ throw new RuntimeInputConflictError(batch.sourceId, batch.sourceKey);
361
+ return { inserted: false, epoch: this.fromRow(existing) };
362
+ }
363
+ const result = this.db.prepare(`
364
+ INSERT INTO runtime_epochs(
365
+ adapter_id, account_id, session_id, segment_id, segment_seq,
366
+ source_id, connection_id, source_key, source_seq_json, domain_tick_json,
367
+ state_json, events_json, event_watermark_json, completeness, coalescing,
368
+ observed_at, received_at, payload_hash, status
369
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'accepted')
370
+ `).run(batch.scope.adapterId, batch.scope.accountId, batch.scope.sessionId, batch.scope.segmentId, batch.scope.segmentSeq ?? null, batch.sourceId, batch.connectionId, batch.sourceKey, batch.sourceSeq === undefined ? null : JSON.stringify(batch.sourceSeq), batch.domainTick === undefined ? null : JSON.stringify(batch.domainTick), JSON.stringify(batch.state), JSON.stringify(batch.events), batch.eventWatermark === undefined ? null : JSON.stringify(batch.eventWatermark), batch.completeness, batch.coalescing ?? 'allowed', batch.observedAt ?? null, batch.receivedAt, hash);
371
+ const row = this.db.prepare('SELECT * FROM runtime_epochs WHERE epoch_seq = ?')
372
+ .get(numberValue(result.lastInsertRowid));
373
+ if (!row)
374
+ throw new Error('Runtime epoch was inserted but could not be read.');
375
+ return { inserted: true, epoch: this.fromRow(row) };
376
+ }
377
+ epoch(epochSeq) {
378
+ const row = this.db.prepare('SELECT * FROM runtime_epochs WHERE epoch_seq = ?').get(epochSeq);
379
+ return row ? this.fromRow(row) : null;
380
+ }
381
+ list(scope, afterEpochSeq = 0, limit = 100) {
382
+ return this.db.prepare(`
383
+ SELECT * FROM runtime_epochs
384
+ WHERE adapter_id = ? AND account_id = ? AND session_id = ? AND segment_id = ?
385
+ AND epoch_seq > ?
386
+ ORDER BY epoch_seq ASC LIMIT ?
387
+ `).all(scope.adapterId, scope.accountId, scope.sessionId, scope.segmentId, afterEpochSeq, Math.max(1, Math.min(limit, 10_000))).map((row) => this.fromRow(row));
388
+ }
389
+ listOpen(scope, afterEpochSeq = 0, limit = 100) {
390
+ return this.db.prepare(`
391
+ SELECT * FROM runtime_epochs
392
+ WHERE adapter_id = ? AND account_id = ? AND session_id = ? AND segment_id = ?
393
+ AND epoch_seq > ? AND status = 'accepted'
394
+ ORDER BY epoch_seq ASC LIMIT ?
395
+ `).all(scope.adapterId, scope.accountId, scope.sessionId, scope.segmentId, afterEpochSeq, Math.max(1, Math.min(limit, 10_000))).map((row) => this.fromRow(row));
396
+ }
397
+ markClosed(epochSeq, closedAt = new Date().toISOString(), durationMs) {
398
+ this.db.prepare(`
399
+ UPDATE runtime_epochs
400
+ SET status = 'closed', closed_at = ?, processing_duration_ms = ?
401
+ WHERE epoch_seq = ?
402
+ `).run(closedAt, durationMs ?? null, epochSeq);
403
+ }
404
+ inputEventsCommitted(epochSeq) {
405
+ const row = this.db.prepare('SELECT input_events_committed_at FROM runtime_epochs WHERE epoch_seq = ?')
406
+ .get(epochSeq);
407
+ return typeof row?.input_events_committed_at === 'string';
408
+ }
409
+ markInputEventsCommitted(epochSeq, eventWatermark, committedAt = new Date().toISOString()) {
410
+ this.db.prepare(`
411
+ UPDATE runtime_epochs
412
+ SET input_events_committed_at = ?,
413
+ event_commit_watermark = MAX(COALESCE(event_commit_watermark, 0), ?)
414
+ WHERE epoch_seq = ?
415
+ `).run(committedAt, eventWatermark, epochSeq);
416
+ }
417
+ eventWatermarkThrough(scope, epochSeq) {
418
+ const row = this.db.prepare(`
419
+ SELECT event_commit_watermark AS watermark
420
+ FROM runtime_epochs
421
+ WHERE adapter_id = ? AND account_id = ? AND session_id = ? AND segment_id = ?
422
+ AND epoch_seq <= ? AND event_commit_watermark IS NOT NULL
423
+ ORDER BY event_commit_watermark DESC
424
+ LIMIT 1
425
+ `).get(scope.adapterId, scope.accountId, scope.sessionId, scope.segmentId, epochSeq);
426
+ return numberValue(row?.watermark);
427
+ }
428
+ markEventWatermark(epochSeq, eventWatermark) {
429
+ this.db.prepare(`
430
+ UPDATE runtime_epochs
431
+ SET event_commit_watermark = MAX(COALESCE(event_commit_watermark, 0), ?)
432
+ WHERE epoch_seq = ?
433
+ `).run(eventWatermark, epochSeq);
434
+ }
435
+ recordPlugin(record) {
436
+ this.db.prepare(`
437
+ INSERT OR REPLACE INTO runtime_plugin_outcomes(
438
+ epoch_seq, plugin_id, invocation_id, outcome, reason, duration_ms,
439
+ state_count, event_count, event_cursor_before, event_cursor_after, recorded_at
440
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
441
+ `).run(record.epochSeq, record.pluginId, record.invocationId, record.outcome, record.reason ?? null, record.durationMs, record.stateCount, record.eventCount, record.eventCursorBefore, record.eventCursorAfter, record.recordedAt);
442
+ }
443
+ pluginRecords(epochSeq) {
444
+ return this.db.prepare(`
445
+ SELECT * FROM runtime_plugin_outcomes
446
+ WHERE epoch_seq = ?
447
+ ORDER BY plugin_id
448
+ `).all(epochSeq).map((row) => ({
449
+ epochSeq: numberValue(row.epoch_seq),
450
+ pluginId: String(row.plugin_id),
451
+ invocationId: String(row.invocation_id),
452
+ outcome: row.outcome,
453
+ ...(typeof row.reason === 'string' ? { reason: row.reason } : {}),
454
+ durationMs: numberValue(row.duration_ms),
455
+ stateCount: numberValue(row.state_count),
456
+ eventCount: numberValue(row.event_count),
457
+ eventCursorBefore: numberValue(row.event_cursor_before),
458
+ eventCursorAfter: numberValue(row.event_cursor_after),
459
+ recordedAt: String(row.recorded_at),
460
+ }));
461
+ }
462
+ pluginProgress(pluginId, scope) {
463
+ const row = this.db.prepare(`
464
+ SELECT * FROM runtime_plugin_progress
465
+ WHERE adapter_id = ? AND account_id = ? AND session_id = ? AND segment_id = ? AND plugin_id = ?
466
+ `).get(scope.adapterId, scope.accountId, scope.sessionId, scope.segmentId, pluginId);
467
+ return row ? {
468
+ pluginId,
469
+ completedThroughEpochSeq: numberValue(row.completed_through_epoch_seq),
470
+ eventCursor: numberValue(row.event_cursor),
471
+ ...(typeof row.checkpoint_json === 'string'
472
+ ? { checkpoint: parseJson(row.checkpoint_json) }
473
+ : {}),
474
+ updatedAt: String(row.updated_at),
475
+ } : {
476
+ pluginId,
477
+ completedThroughEpochSeq: 0,
478
+ eventCursor: 0,
479
+ updatedAt: new Date(0).toISOString(),
480
+ };
481
+ }
482
+ savePluginProgress(progress, scope) {
483
+ this.db.prepare(`
484
+ INSERT INTO runtime_plugin_progress(
485
+ adapter_id, account_id, session_id, segment_id, plugin_id,
486
+ completed_through_epoch_seq, event_cursor, checkpoint_json, updated_at
487
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
488
+ ON CONFLICT(adapter_id, account_id, session_id, segment_id, plugin_id)
489
+ DO UPDATE SET
490
+ completed_through_epoch_seq = excluded.completed_through_epoch_seq,
491
+ event_cursor = excluded.event_cursor,
492
+ checkpoint_json = excluded.checkpoint_json,
493
+ updated_at = excluded.updated_at
494
+ `).run(scope.adapterId, scope.accountId, scope.sessionId, scope.segmentId, progress.pluginId, progress.completedThroughEpochSeq, progress.eventCursor, progress.checkpoint === undefined ? null : JSON.stringify(progress.checkpoint), progress.updatedAt);
495
+ }
496
+ saveStates(records) {
497
+ const statement = this.db.prepare(`
498
+ INSERT OR REPLACE INTO runtime_plugin_states(epoch_seq, plugin_id, topic, value_json)
499
+ VALUES (?, ?, ?, ?)
500
+ `);
501
+ this.db.exec('BEGIN IMMEDIATE');
502
+ try {
503
+ for (const record of records) {
504
+ statement.run(record.epochSeq, record.pluginId, record.topic, JSON.stringify(record.value));
505
+ }
506
+ this.db.exec('COMMIT');
507
+ }
508
+ catch (error) {
509
+ this.db.exec('ROLLBACK');
510
+ throw error;
511
+ }
512
+ }
513
+ states(epochSeq) {
514
+ return this.db.prepare(`
515
+ SELECT epoch_seq, plugin_id, topic, value_json
516
+ FROM runtime_plugin_states WHERE epoch_seq = ? ORDER BY plugin_id, topic
517
+ `).all(epochSeq).map((row) => ({
518
+ epochSeq: numberValue(row.epoch_seq),
519
+ pluginId: String(row.plugin_id),
520
+ topic: String(row.topic),
521
+ value: parseJson(row.value_json),
522
+ }));
523
+ }
524
+ close() {
525
+ this.db.close();
526
+ }
527
+ /** Full startup image for the memory-primary runtime. This is never used on a hot tick. */
528
+ snapshot(scope) {
529
+ const where = scope === undefined ? '' : scope === null ? ' WHERE 0'
530
+ : ' WHERE adapter_id = ? AND account_id = ? AND session_id = ? AND segment_id = ?';
531
+ const params = scope ? [scope.adapterId, scope.accountId, scope.sessionId, scope.segmentId] : [];
532
+ const epochRows = this.db.prepare(`SELECT * FROM runtime_epochs${where} ORDER BY epoch_seq ASC`).all(...params);
533
+ const epochs = epochRows.map((row) => ({
534
+ epoch: this.fromRow(row),
535
+ closed: row.status === 'closed',
536
+ inputEventsCommitted: typeof row.input_events_committed_at === 'string',
537
+ eventWatermark: numberValue(row.event_commit_watermark),
538
+ }));
539
+ const pluginProgress = this.db.prepare(`SELECT * FROM runtime_plugin_progress${where}`).all(...params).map((row) => ({
540
+ scope: {
541
+ adapterId: String(row.adapter_id),
542
+ accountId: String(row.account_id),
543
+ sessionId: String(row.session_id),
544
+ segmentId: String(row.segment_id),
545
+ },
546
+ progress: {
547
+ pluginId: String(row.plugin_id),
548
+ completedThroughEpochSeq: numberValue(row.completed_through_epoch_seq),
549
+ eventCursor: numberValue(row.event_cursor),
550
+ ...(typeof row.checkpoint_json === 'string' ? { checkpoint: parseJson(row.checkpoint_json) } : {}),
551
+ updatedAt: String(row.updated_at),
552
+ },
553
+ }));
554
+ const pluginRecords = this.db.prepare(`SELECT * FROM runtime_plugin_outcomes
555
+ WHERE epoch_seq IN (SELECT epoch_seq FROM runtime_epochs${where}) ORDER BY epoch_seq, plugin_id`)
556
+ .all(...params).map((row) => ({
557
+ epochSeq: numberValue(row.epoch_seq),
558
+ pluginId: String(row.plugin_id),
559
+ invocationId: String(row.invocation_id),
560
+ outcome: row.outcome,
561
+ ...(typeof row.reason === 'string' ? { reason: row.reason } : {}),
562
+ durationMs: numberValue(row.duration_ms),
563
+ stateCount: numberValue(row.state_count),
564
+ eventCount: numberValue(row.event_count),
565
+ eventCursorBefore: numberValue(row.event_cursor_before),
566
+ eventCursorAfter: numberValue(row.event_cursor_after),
567
+ recordedAt: String(row.recorded_at),
568
+ }));
569
+ const states = this.db.prepare(`SELECT * FROM runtime_plugin_states
570
+ WHERE epoch_seq IN (SELECT epoch_seq FROM runtime_epochs${where}) ORDER BY epoch_seq, plugin_id, topic`)
571
+ .all(...params).map((row) => ({
572
+ epochSeq: numberValue(row.epoch_seq),
573
+ pluginId: String(row.plugin_id),
574
+ topic: String(row.topic),
575
+ value: parseJson(row.value_json),
576
+ }));
577
+ return {
578
+ epochs,
579
+ pluginProgress,
580
+ pluginRecords,
581
+ states,
582
+ nextEpochSeq: numberValue(this.db.prepare('SELECT MAX(epoch_seq) AS seq FROM runtime_epochs').get()?.seq) + 1,
583
+ };
584
+ }
585
+ findByIdentity(scope, sourceId, sourceKey) {
586
+ return this.db.prepare(`
587
+ SELECT * FROM runtime_epochs
588
+ WHERE adapter_id = ? AND account_id = ? AND session_id = ? AND segment_id = ?
589
+ AND source_id = ? AND source_key = ?
590
+ `).get(scope.adapterId, scope.accountId, scope.sessionId, scope.segmentId, sourceId, sourceKey);
591
+ }
592
+ fromRow(row) {
593
+ return cloneCanonical({
594
+ epochSeq: numberValue(row.epoch_seq),
595
+ scope: {
596
+ adapterId: String(row.adapter_id),
597
+ accountId: String(row.account_id),
598
+ sessionId: String(row.session_id),
599
+ segmentId: String(row.segment_id),
600
+ ...(row.segment_seq === null || row.segment_seq === undefined
601
+ ? {}
602
+ : { segmentSeq: numberValue(row.segment_seq) }),
603
+ },
604
+ sourceId: String(row.source_id),
605
+ connectionId: String(row.connection_id),
606
+ sourceKey: String(row.source_key),
607
+ ...(row.source_seq_json === null ? {} : { sourceSeq: parseJson(row.source_seq_json) }),
608
+ ...(row.domain_tick_json === null ? {} : { domainTick: parseJson(row.domain_tick_json) }),
609
+ state: parseJson(row.state_json),
610
+ events: parseJson(row.events_json),
611
+ ...(row.event_watermark_json === null
612
+ ? {}
613
+ : { eventWatermark: parseJson(row.event_watermark_json) }),
614
+ completeness: row.completeness,
615
+ ...(row.coalescing === 'forbidden' ? { coalescing: 'forbidden' } : {}),
616
+ ...(typeof row.observed_at === 'string' ? { observedAt: row.observed_at } : {}),
617
+ receivedAt: String(row.received_at),
618
+ });
619
+ }
620
+ initialize() {
621
+ this.db.exec(`
622
+ PRAGMA journal_mode = WAL;
623
+ CREATE TABLE IF NOT EXISTS runtime_epochs(
624
+ epoch_seq INTEGER PRIMARY KEY AUTOINCREMENT,
625
+ adapter_id TEXT NOT NULL,
626
+ account_id TEXT NOT NULL,
627
+ session_id TEXT NOT NULL,
628
+ segment_id TEXT NOT NULL,
629
+ segment_seq INTEGER,
630
+ source_id TEXT NOT NULL,
631
+ connection_id TEXT NOT NULL,
632
+ source_key TEXT NOT NULL,
633
+ source_seq_json TEXT,
634
+ domain_tick_json TEXT,
635
+ state_json TEXT NOT NULL,
636
+ events_json TEXT NOT NULL,
637
+ event_watermark_json TEXT,
638
+ completeness TEXT NOT NULL CHECK(completeness IN ('complete', 'best_effort')),
639
+ coalescing TEXT NOT NULL DEFAULT 'allowed' CHECK(coalescing IN ('allowed', 'forbidden')),
640
+ observed_at TEXT,
641
+ received_at TEXT NOT NULL,
642
+ payload_hash TEXT NOT NULL,
643
+ status TEXT NOT NULL CHECK(status IN ('accepted', 'closed')),
644
+ input_events_committed_at TEXT,
645
+ event_commit_watermark INTEGER,
646
+ closed_at TEXT,
647
+ processing_duration_ms INTEGER,
648
+ UNIQUE(adapter_id, account_id, session_id, segment_id, source_id, source_key)
649
+ );
650
+ CREATE INDEX IF NOT EXISTS runtime_epochs_scope_seq
651
+ ON runtime_epochs(adapter_id, account_id, session_id, segment_id, epoch_seq);
652
+ CREATE INDEX IF NOT EXISTS runtime_epochs_scope_event_watermark
653
+ ON runtime_epochs(
654
+ adapter_id, account_id, session_id, segment_id,
655
+ event_commit_watermark DESC, epoch_seq
656
+ );
657
+
658
+ CREATE TABLE IF NOT EXISTS runtime_plugin_outcomes(
659
+ epoch_seq INTEGER NOT NULL,
660
+ plugin_id TEXT NOT NULL,
661
+ invocation_id TEXT NOT NULL,
662
+ outcome TEXT NOT NULL CHECK(outcome IN ('processed', 'noop', 'failed', 'coalesced')),
663
+ reason TEXT,
664
+ duration_ms INTEGER NOT NULL,
665
+ state_count INTEGER NOT NULL,
666
+ event_count INTEGER NOT NULL,
667
+ event_cursor_before INTEGER NOT NULL,
668
+ event_cursor_after INTEGER NOT NULL,
669
+ recorded_at TEXT NOT NULL,
670
+ PRIMARY KEY(epoch_seq, plugin_id)
671
+ );
672
+
673
+ CREATE TABLE IF NOT EXISTS runtime_plugin_progress(
674
+ adapter_id TEXT NOT NULL,
675
+ account_id TEXT NOT NULL,
676
+ session_id TEXT NOT NULL,
677
+ segment_id TEXT NOT NULL,
678
+ plugin_id TEXT NOT NULL,
679
+ completed_through_epoch_seq INTEGER NOT NULL,
680
+ event_cursor INTEGER NOT NULL,
681
+ checkpoint_json TEXT,
682
+ updated_at TEXT NOT NULL,
683
+ PRIMARY KEY(adapter_id, account_id, session_id, segment_id, plugin_id)
684
+ );
685
+
686
+ CREATE TABLE IF NOT EXISTS runtime_plugin_states(
687
+ epoch_seq INTEGER NOT NULL,
688
+ plugin_id TEXT NOT NULL,
689
+ topic TEXT NOT NULL,
690
+ value_json TEXT NOT NULL,
691
+ PRIMARY KEY(epoch_seq, plugin_id, topic)
692
+ );
693
+
694
+ `);
695
+ const epochColumns = new Set(this.db.prepare('PRAGMA table_info(runtime_epochs)').all().map((row) => String(row.name)));
696
+ if (!epochColumns.has('segment_seq')) {
697
+ this.db.exec('ALTER TABLE runtime_epochs ADD COLUMN segment_seq INTEGER;');
698
+ }
699
+ if (!epochColumns.has('input_events_committed_at')) {
700
+ this.db.exec('ALTER TABLE runtime_epochs ADD COLUMN input_events_committed_at TEXT;');
701
+ }
702
+ if (!epochColumns.has('event_commit_watermark')) {
703
+ this.db.exec('ALTER TABLE runtime_epochs ADD COLUMN event_commit_watermark INTEGER;');
704
+ }
705
+ if (!epochColumns.has('coalescing')) {
706
+ this.db.exec("ALTER TABLE runtime_epochs ADD COLUMN coalescing TEXT NOT NULL DEFAULT 'allowed';");
707
+ }
708
+ if (!epochColumns.has('processing_duration_ms')) {
709
+ this.db.exec('ALTER TABLE runtime_epochs ADD COLUMN processing_duration_ms INTEGER;');
710
+ }
711
+ const progressColumns = new Set(this.db.prepare('PRAGMA table_info(runtime_plugin_progress)').all().map((row) => String(row.name)));
712
+ if (!progressColumns.has('checkpoint_json')) {
713
+ this.db.exec('ALTER TABLE runtime_plugin_progress ADD COLUMN checkpoint_json TEXT;');
714
+ }
715
+ }
716
+ }