@myclaw163/clawclaw-cli 0.8.13 → 0.8.15

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 (68) hide show
  1. package/docs/custom-modules/perception.md +4 -4
  2. package/docs/runtime/README.md +1 -1
  3. package/docs/runtime/behavior-runtime.md +1 -1
  4. package/docs/runtime/official-perception-modules.md +23 -30
  5. package/docs/runtime/perception-replay.md +1 -1
  6. package/package.json +1 -1
  7. package/skills/clawclaw/SKILL.md +8 -4
  8. package/skills/clawclaw/references/BEHAVIORS.md +16 -1
  9. package/skills/clawclaw/references/CHANNELS.md +1 -1
  10. package/skills/clawclaw/references/COMMANDS.md +2 -2
  11. package/skills/clawclaw/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +310 -0
  12. package/skills/clawclaw/references/CUSTOM-MODULE-API.md +684 -0
  13. package/skills/clawclaw/references/CUSTOM-MODULES.md +125 -0
  14. package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +331 -0
  15. package/skills/clawclaw/references/STREAM.md +4 -2
  16. package/src/lib/game-client.ts +12 -4
  17. package/src/pipeline/event-format.ts +5 -0
  18. package/src/pipeline/event-hints.ts +10 -0
  19. package/src/runtime/clawclaw/agent-event-policy.ts +2 -0
  20. package/src/runtime/clawclaw/behavior-decision.ts +4 -1
  21. package/src/runtime/clawclaw/behavior-input.ts +5 -0
  22. package/src/runtime/clawclaw/owner.ts +64 -1
  23. package/src/runtime/clawclaw/plugins/action/action-plugin.ts +150 -18
  24. package/src/runtime/clawclaw/plugins/assembly.ts +4 -0
  25. package/src/runtime/clawclaw/plugins/behavior/behavior-action.ts +8 -0
  26. package/src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +35 -2
  27. package/src/runtime/clawclaw/plugins/behavior/behavior-catalog.ts +11 -7
  28. package/src/runtime/clawclaw/plugins/behavior/behavior-decision-history.ts +88 -0
  29. package/src/runtime/clawclaw/plugins/behavior/behavior-normalization.ts +3 -2
  30. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +201 -43
  31. package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +45 -9
  32. package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +170 -8
  33. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +5 -1
  34. package/src/runtime/clawclaw/plugins/perception/module-runner.ts +86 -89
  35. package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-pool.ts +157 -41
  36. package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-worker.ts +33 -9
  37. package/src/runtime/clawclaw/plugins/perception/perception-module-loader.ts +3 -1
  38. package/src/runtime/clawclaw/plugins/perception/perception-module-output.ts +30 -0
  39. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +327 -23
  40. package/src/runtime/clawclaw/plugins/perception/perception-reducer-thread-pool.ts +660 -0
  41. package/src/runtime/clawclaw/plugins/perception/perception-reducer-thread-worker.ts +262 -0
  42. package/src/runtime/clawclaw/plugins/source/game-transport.ts +29 -4
  43. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +153 -0
  44. package/src/runtime/clawclaw/plugins/source/types.ts +1 -0
  45. package/src/runtime/clawclaw/plugins/trigger/trigger-module-loader.ts +41 -12
  46. package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.ts +252 -20
  47. package/src/runtime/clawclaw/plugins/trigger/trigger-thread-pool.ts +496 -0
  48. package/src/runtime/clawclaw/plugins/trigger/trigger-thread-worker.ts +164 -0
  49. package/src/runtime/clawclaw/runtime.ts +31 -3
  50. package/src/runtime/clawclaw-event-catalog.ts +3 -0
  51. package/src/runtime/framework/events/event-repository.ts +1 -1
  52. package/src/runtime/framework/events/memory-event-repository.ts +71 -1
  53. package/src/runtime/framework/events/sqlite-event-repository.ts +23 -1
  54. package/src/runtime/framework/mailbox/types.ts +2 -0
  55. package/src/runtime/framework/modules/runtime-module-output.ts +24 -0
  56. package/src/runtime/framework/persistence/async-sqlite-persistence-worker.ts +58 -0
  57. package/src/runtime/framework/persistence/memory-first-persistence.ts +383 -0
  58. package/src/runtime/framework/plugins/contracts.ts +5 -2
  59. package/src/runtime/framework/plugins/runtime-input-journal.ts +185 -17
  60. package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +173 -34
  61. package/src/runtime/framework/runtime.ts +75 -4
  62. package/src/runtime/framework/state/history/contracts.ts +9 -1
  63. package/src/runtime/framework/state/history/memory-state-history-repository.ts +59 -7
  64. package/src/runtime/framework/state/history/sqlite-state-history-repository.ts +16 -0
  65. package/src/runtime/observability/redaction.ts +28 -1
  66. package/src/sdk/behavior-plugin/index.ts +5 -24
  67. package/src/sdk/module-input/index.ts +47 -0
  68. package/src/sdk/perception-plugin/index.ts +13 -8
@@ -159,9 +159,24 @@ export class RuntimeInputConflictError extends Error {
159
159
  }
160
160
  }
161
161
 
162
+ export interface RuntimeInputJournalSnapshot<TState = Record<string, unknown>, TEvent = Record<string, unknown>> {
163
+ epochs: Array<{
164
+ epoch: RuntimeEpoch<TState, TEvent>;
165
+ closed: boolean;
166
+ inputEventsCommitted: boolean;
167
+ eventWatermark: number;
168
+ }>;
169
+ pluginProgress: Array<{ scope: RuntimeScope; progress: RuntimeEpochPluginProgress }>;
170
+ pluginRecords: RuntimeEpochPluginRecord[];
171
+ states: RuntimeEpochStateRecord[];
172
+ nextEpochSeq: number;
173
+ }
174
+
162
175
  export class MemoryRuntimeInputJournal<TState = Record<string, unknown>, TEvent = Record<string, unknown>>
163
176
  implements RuntimePersistenceStore<TState, TEvent> {
164
177
  private readonly epochs: RuntimeEpoch<TState, TEvent>[] = [];
178
+ private readonly epochsBySeq = new Map<number, RuntimeEpoch<TState, TEvent>>();
179
+ private readonly epochsByScope = new Map<string, RuntimeEpoch<TState, TEvent>[]>();
165
180
  private readonly hashes = new Map<string, string>();
166
181
  private readonly byIdentity = new Map<string, RuntimeEpoch<TState, TEvent>>();
167
182
  private readonly closed = new Set<number>();
@@ -169,9 +184,67 @@ implements RuntimePersistenceStore<TState, TEvent> {
169
184
  private readonly eventWatermarks = new Map<number, number>();
170
185
  private readonly progress = new Map<string, RuntimeEpochPluginProgress>();
171
186
  private readonly pluginOutcomeRecords: RuntimeEpochPluginRecord[] = [];
187
+ private readonly pluginOutcomeRecordsByEpoch = new Map<number, RuntimeEpochPluginRecord[]>();
172
188
  private readonly stateRecords: RuntimeEpochStateRecord[] = [];
189
+ private readonly stateRecordsByEpoch = new Map<number, RuntimeEpochStateRecord[]>();
190
+
191
+ diagnosticCounts(): Readonly<Record<string, number>> {
192
+ return {
193
+ epochs: this.epochs.length,
194
+ closed_epochs: this.closed.size,
195
+ input_event_commits: this.inputEventCommits.size,
196
+ event_watermarks: this.eventWatermarks.size,
197
+ plugin_progress: this.progress.size,
198
+ plugin_records: this.pluginOutcomeRecords.length,
199
+ plugin_states: this.stateRecords.length,
200
+ };
201
+ }
173
202
  private nextEpochSeq = 1;
174
203
 
204
+ constructor(snapshot?: RuntimeInputJournalSnapshot<TState, TEvent>) {
205
+ if (!snapshot) return;
206
+ for (const item of snapshot.epochs) {
207
+ const epoch = cloneCanonical(item.epoch);
208
+ const identity = sourceIdentity(epoch);
209
+ this.epochs.push(epoch);
210
+ this.indexEpoch(epoch);
211
+ this.byIdentity.set(identity, epoch);
212
+ this.hashes.set(identity, payloadHash(epoch as RuntimeInputBatch));
213
+ if (item.closed) this.closed.add(epoch.epochSeq);
214
+ if (item.inputEventsCommitted) this.inputEventCommits.add(epoch.epochSeq);
215
+ if (item.eventWatermark > 0) this.eventWatermarks.set(epoch.epochSeq, item.eventWatermark);
216
+ }
217
+ for (const item of snapshot.pluginProgress) {
218
+ this.progress.set(`${runtimeScopeKey(item.scope)}\u001f${item.progress.pluginId}`, cloneCanonical(item.progress));
219
+ }
220
+ for (const record of snapshot.pluginRecords) this.indexPluginRecord(cloneCanonical(record));
221
+ for (const record of snapshot.states) this.indexStateRecord(cloneCanonical(record));
222
+ this.nextEpochSeq = Math.max(snapshot.nextEpochSeq, 1);
223
+ }
224
+
225
+ snapshot(): RuntimeInputJournalSnapshot<TState, TEvent> {
226
+ const scopeByKey = new Map<string, RuntimeScope>();
227
+ for (const epoch of this.epochs) scopeByKey.set(runtimeScopeKey(epoch.scope), epoch.scope);
228
+ const pluginProgress: RuntimeInputJournalSnapshot['pluginProgress'] = [];
229
+ for (const [key, progress] of this.progress) {
230
+ const scopeKey = key.slice(0, key.lastIndexOf('\u001f'));
231
+ const scope = scopeByKey.get(scopeKey);
232
+ if (scope) pluginProgress.push({ scope: cloneCanonical(scope), progress: cloneCanonical(progress) });
233
+ }
234
+ return cloneCanonical({
235
+ epochs: this.epochs.map((epoch) => ({
236
+ epoch,
237
+ closed: this.closed.has(epoch.epochSeq),
238
+ inputEventsCommitted: this.inputEventCommits.has(epoch.epochSeq),
239
+ eventWatermark: this.eventWatermarks.get(epoch.epochSeq) ?? 0,
240
+ })),
241
+ pluginProgress,
242
+ pluginRecords: this.pluginOutcomeRecords,
243
+ states: this.stateRecords,
244
+ nextEpochSeq: this.nextEpochSeq,
245
+ });
246
+ }
247
+
175
248
  accept(batch: RuntimeInputBatch<TState, TEvent>): RuntimeInputAcceptance<TState, TEvent> {
176
249
  assertRuntimeInputBatch(batch);
177
250
  const identity = sourceIdentity(batch);
@@ -186,28 +259,28 @@ implements RuntimePersistenceStore<TState, TEvent> {
186
259
  epochSeq: this.nextEpochSeq++,
187
260
  };
188
261
  this.epochs.push(epoch);
262
+ this.indexEpoch(epoch);
189
263
  this.byIdentity.set(identity, epoch);
190
264
  this.hashes.set(identity, hash);
191
265
  return { inserted: true, epoch: cloneCanonical(epoch) };
192
266
  }
193
267
 
194
268
  epoch(epochSeq: number): RuntimeEpoch<TState, TEvent> | null {
195
- const value = this.epochs.find((item) => item.epochSeq === epochSeq);
269
+ const value = this.epochsBySeq.get(epochSeq);
196
270
  return value ? cloneCanonical(value) : null;
197
271
  }
198
272
 
199
273
  list(scope: RuntimeScope, afterEpochSeq = 0, limit = 100): RuntimeEpoch<TState, TEvent>[] {
200
- return this.epochs
201
- .filter((item) => item.epochSeq > afterEpochSeq && sameRuntimeScope(item.scope, scope))
274
+ return (this.epochsByScope.get(runtimeScopeKey(scope)) ?? [])
275
+ .filter((item) => item.epochSeq > afterEpochSeq)
202
276
  .slice(0, Math.max(1, Math.min(limit, 10_000)))
203
277
  .map(cloneCanonical);
204
278
  }
205
279
 
206
280
  listOpen(scope: RuntimeScope, afterEpochSeq = 0, limit = 100): RuntimeEpoch<TState, TEvent>[] {
207
- return this.epochs
281
+ return (this.epochsByScope.get(runtimeScopeKey(scope)) ?? [])
208
282
  .filter((item) => (
209
283
  item.epochSeq > afterEpochSeq
210
- && sameRuntimeScope(item.scope, scope)
211
284
  && !this.closed.has(item.epochSeq)
212
285
  ))
213
286
  .slice(0, Math.max(1, Math.min(limit, 10_000)))
@@ -219,11 +292,13 @@ implements RuntimePersistenceStore<TState, TEvent> {
219
292
  }
220
293
 
221
294
  eventWatermarkThrough(scope: RuntimeScope, epochSeq: number): number {
222
- return this.epochs.reduce((watermark, epoch) => (
223
- epoch.epochSeq <= epochSeq && sameRuntimeScope(epoch.scope, scope)
224
- ? Math.max(watermark, this.eventWatermarks.get(epoch.epochSeq) ?? 0)
225
- : watermark
226
- ), 0);
295
+ const epochs = this.epochsByScope.get(runtimeScopeKey(scope)) ?? [];
296
+ let maximum = 0;
297
+ for (const candidate of epochs) {
298
+ if (candidate.epochSeq > epochSeq) break;
299
+ maximum = Math.max(maximum, this.eventWatermarks.get(candidate.epochSeq) ?? 0);
300
+ }
301
+ return maximum;
227
302
  }
228
303
 
229
304
  inputEventsCommitted(epochSeq: number): boolean {
@@ -240,16 +315,21 @@ implements RuntimePersistenceStore<TState, TEvent> {
240
315
  }
241
316
 
242
317
  recordPlugin(record: RuntimeEpochPluginRecord): void {
243
- const index = this.pluginOutcomeRecords.findIndex((candidate) => (
318
+ const epochRecords = this.pluginOutcomeRecordsByEpoch.get(record.epochSeq) ?? [];
319
+ const index = epochRecords.findIndex((candidate) => (
244
320
  candidate.epochSeq === record.epochSeq && candidate.pluginId === record.pluginId
245
321
  ));
246
- if (index >= 0) this.pluginOutcomeRecords[index] = cloneCanonical(record);
247
- else this.pluginOutcomeRecords.push(cloneCanonical(record));
322
+ const stored = cloneCanonical(record);
323
+ if (index >= 0) {
324
+ const previous = epochRecords[index];
325
+ epochRecords[index] = stored;
326
+ const allIndex = this.pluginOutcomeRecords.indexOf(previous);
327
+ if (allIndex >= 0) this.pluginOutcomeRecords[allIndex] = stored;
328
+ } else this.indexPluginRecord(stored);
248
329
  }
249
330
 
250
331
  pluginRecords(epochSeq: number): RuntimeEpochPluginRecord[] {
251
- return this.pluginOutcomeRecords
252
- .filter((record) => record.epochSeq === epochSeq)
332
+ return (this.pluginOutcomeRecordsByEpoch.get(epochSeq) ?? [])
253
333
  .sort((a, b) => a.pluginId.localeCompare(b.pluginId))
254
334
  .map(cloneCanonical);
255
335
  }
@@ -268,11 +348,45 @@ implements RuntimePersistenceStore<TState, TEvent> {
268
348
  }
269
349
 
270
350
  saveStates(records: readonly RuntimeEpochStateRecord[]): void {
271
- this.stateRecords.push(...records.map(cloneCanonical));
351
+ for (const record of records) {
352
+ const epochRecords = this.stateRecordsByEpoch.get(record.epochSeq) ?? [];
353
+ const index = epochRecords.findIndex((candidate) => (
354
+ candidate.pluginId === record.pluginId && candidate.topic === record.topic
355
+ ));
356
+ const stored = cloneCanonical(record);
357
+ if (index >= 0) {
358
+ const previous = epochRecords[index];
359
+ epochRecords[index] = stored;
360
+ const allIndex = this.stateRecords.indexOf(previous);
361
+ if (allIndex >= 0) this.stateRecords[allIndex] = stored;
362
+ } else this.indexStateRecord(stored);
363
+ }
272
364
  }
273
365
 
274
366
  states(epochSeq: number): RuntimeEpochStateRecord[] {
275
- return this.stateRecords.filter((row) => row.epochSeq === epochSeq).map(cloneCanonical);
367
+ return (this.stateRecordsByEpoch.get(epochSeq) ?? []).map(cloneCanonical);
368
+ }
369
+
370
+ private indexEpoch(epoch: RuntimeEpoch<TState, TEvent>): void {
371
+ this.epochsBySeq.set(epoch.epochSeq, epoch);
372
+ const key = runtimeScopeKey(epoch.scope);
373
+ const scoped = this.epochsByScope.get(key) ?? [];
374
+ scoped.push(epoch);
375
+ this.epochsByScope.set(key, scoped);
376
+ }
377
+
378
+ private indexPluginRecord(record: RuntimeEpochPluginRecord): void {
379
+ this.pluginOutcomeRecords.push(record);
380
+ const rows = this.pluginOutcomeRecordsByEpoch.get(record.epochSeq) ?? [];
381
+ rows.push(record);
382
+ this.pluginOutcomeRecordsByEpoch.set(record.epochSeq, rows);
383
+ }
384
+
385
+ private indexStateRecord(record: RuntimeEpochStateRecord): void {
386
+ this.stateRecords.push(record);
387
+ const rows = this.stateRecordsByEpoch.get(record.epochSeq) ?? [];
388
+ rows.push(record);
389
+ this.stateRecordsByEpoch.set(record.epochSeq, rows);
276
390
  }
277
391
 
278
392
  }
@@ -553,6 +667,60 @@ implements RuntimePersistenceStore<TState, TEvent> {
553
667
  this.db.close();
554
668
  }
555
669
 
670
+ /** Full startup image for the memory-primary runtime. This is never used on a hot tick. */
671
+ snapshot(): RuntimeInputJournalSnapshot<TState, TEvent> {
672
+ const epochRows = this.db.prepare('SELECT * FROM runtime_epochs ORDER BY epoch_seq ASC').all();
673
+ const epochs = epochRows.map((row) => ({
674
+ epoch: this.fromRow(row),
675
+ closed: row.status === 'closed',
676
+ inputEventsCommitted: typeof row.input_events_committed_at === 'string',
677
+ eventWatermark: numberValue(row.event_commit_watermark),
678
+ }));
679
+ const pluginProgress = this.db.prepare('SELECT * FROM runtime_plugin_progress').all().map((row) => ({
680
+ scope: {
681
+ adapterId: String(row.adapter_id),
682
+ accountId: String(row.account_id),
683
+ sessionId: String(row.session_id),
684
+ segmentId: String(row.segment_id),
685
+ },
686
+ progress: {
687
+ pluginId: String(row.plugin_id),
688
+ completedThroughEpochSeq: numberValue(row.completed_through_epoch_seq),
689
+ eventCursor: numberValue(row.event_cursor),
690
+ ...(typeof row.checkpoint_json === 'string' ? { checkpoint: parseJson(row.checkpoint_json) } : {}),
691
+ updatedAt: String(row.updated_at),
692
+ },
693
+ }));
694
+ const pluginRecords = this.db.prepare('SELECT * FROM runtime_plugin_outcomes ORDER BY epoch_seq, plugin_id')
695
+ .all().map((row) => ({
696
+ epochSeq: numberValue(row.epoch_seq),
697
+ pluginId: String(row.plugin_id),
698
+ invocationId: String(row.invocation_id),
699
+ outcome: row.outcome as RuntimeEpochPluginRecord['outcome'],
700
+ ...(typeof row.reason === 'string' ? { reason: row.reason } : {}),
701
+ durationMs: numberValue(row.duration_ms),
702
+ stateCount: numberValue(row.state_count),
703
+ eventCount: numberValue(row.event_count),
704
+ eventCursorBefore: numberValue(row.event_cursor_before),
705
+ eventCursorAfter: numberValue(row.event_cursor_after),
706
+ recordedAt: String(row.recorded_at),
707
+ }));
708
+ const states = this.db.prepare('SELECT * FROM runtime_plugin_states ORDER BY epoch_seq, plugin_id, topic')
709
+ .all().map((row) => ({
710
+ epochSeq: numberValue(row.epoch_seq),
711
+ pluginId: String(row.plugin_id),
712
+ topic: String(row.topic),
713
+ value: parseJson(row.value_json),
714
+ }));
715
+ return {
716
+ epochs,
717
+ pluginProgress,
718
+ pluginRecords,
719
+ states,
720
+ nextEpochSeq: (epochs.at(-1)?.epoch.epochSeq ?? 0) + 1,
721
+ };
722
+ }
723
+
556
724
  private findByIdentity(scope: RuntimeScope, sourceId: string, sourceKey: string) {
557
725
  return this.db.prepare(`
558
726
  SELECT * FROM runtime_epochs
@@ -88,6 +88,32 @@ export interface RuntimePluginSchedulerOptions<
88
88
  nowMs?: () => number;
89
89
  }
90
90
 
91
+ export interface RuntimePluginDiagnosticProgress {
92
+ readonly plugin_id: string;
93
+ readonly catch_up: RuntimeEpochPlugin<any, any>['catchUp'];
94
+ readonly max_in_flight: number;
95
+ readonly max_pending_epochs: number;
96
+ readonly completed_through_epoch_seq: number;
97
+ readonly ready_through_epoch_seq: number;
98
+ readonly lag_epoch_count: number;
99
+ readonly active_invocation_count: number;
100
+ readonly buffered_invocation_count: number;
101
+ readonly active_commit: boolean;
102
+ readonly paused: boolean;
103
+ }
104
+
105
+ export interface RuntimePluginSchedulerDiagnosticSnapshot {
106
+ readonly pending_epoch_count: number;
107
+ readonly oldest_pending_epoch_seq: number | null;
108
+ readonly newest_pending_epoch_seq: number | null;
109
+ readonly oldest_pending_age_ms: number;
110
+ readonly active_invocation_count: number;
111
+ readonly active_commit_count: number;
112
+ readonly buffered_invocation_count: number;
113
+ readonly input_event_commit_count: number;
114
+ readonly plugins: readonly RuntimePluginDiagnosticProgress[];
115
+ }
116
+
91
117
  interface PendingWork<TState, TEvent> {
92
118
  work: RuntimeEpochWork<TState, TEvent>;
93
119
  queuedAtMs: number;
@@ -167,6 +193,15 @@ function rounded(value: number): number {
167
193
  return Math.round(value * 1_000) / 1_000;
168
194
  }
169
195
 
196
+ function deepFreeze<T>(value: T, seen = new WeakSet<object>()): T {
197
+ if (!value || typeof value !== 'object' || Object.isFrozen(value)) return value;
198
+ const object = value as object;
199
+ if (seen.has(object)) return value;
200
+ seen.add(object);
201
+ for (const child of Object.values(object)) deepFreeze(child, seen);
202
+ return Object.freeze(value);
203
+ }
204
+
170
205
  function percentile(sorted: readonly number[], fraction: number): number {
171
206
  if (sorted.length === 0) return 0;
172
207
  return sorted[Math.max(0, Math.ceil(sorted.length * fraction) - 1)]!;
@@ -255,6 +290,19 @@ function normalizedMaxInFlight(plugin: RuntimeEpochPlugin<any, any>): number {
255
290
  return maxInFlight;
256
291
  }
257
292
 
293
+ function normalizedMaxPendingEpochs(
294
+ plugin: RuntimeEpochPlugin<any, any>,
295
+ fallback: number,
296
+ ): number {
297
+ const maxPendingEpochs = plugin.maxPendingEpochs ?? fallback;
298
+ if (!Number.isInteger(maxPendingEpochs) || maxPendingEpochs <= 0 || maxPendingEpochs > 10_000) {
299
+ throw new TypeError(
300
+ `Runtime Epoch Plugin ${plugin.id} maxPendingEpochs must be an integer between 1 and 10000.`,
301
+ );
302
+ }
303
+ return maxPendingEpochs;
304
+ }
305
+
258
306
  function pluginLayers<TState, TEvent>(
259
307
  plugins: readonly RuntimeEpochPlugin<TState, TEvent>[],
260
308
  ): RuntimeEpochPlugin<TState, TEvent>[][] {
@@ -269,6 +317,7 @@ function pluginLayers<TState, TEvent>(
269
317
  byId.set(plugin.id, plugin);
270
318
  normalizedFailurePolicy(plugin);
271
319
  normalizedMaxInFlight(plugin);
320
+ if (plugin.maxPendingEpochs !== undefined) normalizedMaxPendingEpochs(plugin, 1);
272
321
  for (const topic of plugin.produces?.states ?? []) {
273
322
  assertNonEmpty(topic, `Runtime Epoch Plugin ${plugin.id} State output`);
274
323
  const owner = stateOwners.get(topic);
@@ -385,7 +434,7 @@ export class RuntimeEpochPluginSupersededError extends Error {
385
434
  readonly pluginId: string,
386
435
  readonly epochSeq: number,
387
436
  readonly newerEpochSeq: number,
388
- readonly reasonCode: 'newer_epoch_available' | 'catch_up_limit' = 'newer_epoch_available',
437
+ readonly reasonCode: 'newer_epoch_available' | 'catch_up_limit' | 'required_epoch_boundary' = 'newer_epoch_available',
389
438
  ) {
390
439
  super(`Runtime Epoch Plugin "${pluginId}" epoch ${epochSeq} was superseded by epoch ${newerEpochSeq}.`);
391
440
  this.name = 'RuntimeEpochPluginSupersededError';
@@ -501,6 +550,7 @@ export class RuntimePluginScheduler<
501
550
  after: [...(plugin.after ?? [])],
502
551
  catchUp: plugin.catchUp ?? 'every_epoch',
503
552
  maxInFlight: normalizedMaxInFlight(plugin),
553
+ maxPendingEpochs: normalizedMaxPendingEpochs(plugin, this.maxCatchUpEpochs),
504
554
  consumes: cloneCanonical(plugin.consumes ?? {}),
505
555
  produces: cloneCanonical(plugin.produces ?? {}),
506
556
  capabilities: cloneCanonical(plugin.capabilities ?? {}),
@@ -512,6 +562,75 @@ export class RuntimePluginScheduler<
512
562
  }));
513
563
  }
514
564
 
565
+ /**
566
+ * Exact, on-demand scheduler state for full local diagnostics.
567
+ * The Owner calls this only while full observability is enabled so the
568
+ * per-plugin backlog scan has zero cost in the default runtime path.
569
+ */
570
+ diagnosticSnapshot(scope = this.activeScope ?? undefined): RuntimePluginSchedulerDiagnosticSnapshot {
571
+ const pending = scope
572
+ ? [...this.pending.values()].filter(({ work }) => (
573
+ runtimeScopeKey(work.epoch.scope) === runtimeScopeKey(scope)
574
+ ))
575
+ : [...this.pending.values()];
576
+ let oldest: PendingWork<TState, TEvent> | undefined;
577
+ let oldestEpochSeq: number | null = null;
578
+ let newestEpochSeq: number | null = null;
579
+ for (const entry of pending) {
580
+ if (!oldest || entry.queuedAtMs < oldest.queuedAtMs) oldest = entry;
581
+ const epochSeq = entry.work.epoch.epochSeq;
582
+ oldestEpochSeq = oldestEpochSeq === null ? epochSeq : Math.min(oldestEpochSeq, epochSeq);
583
+ newestEpochSeq = newestEpochSeq === null ? epochSeq : Math.max(newestEpochSeq, epochSeq);
584
+ }
585
+ const effectiveScope = scope ?? pending[0]?.work.epoch.scope;
586
+ const progressByPlugin = effectiveScope
587
+ ? new Map(this.plugins.map((plugin) => [
588
+ plugin.id,
589
+ this.pluginStore.pluginProgress(plugin.id, effectiveScope),
590
+ ]))
591
+ : new Map<string, ReturnType<RuntimePluginStore['pluginProgress']>>();
592
+ const latestEpochSeq = newestEpochSeq ?? 0;
593
+ const plugins = this.plugins.map((plugin): RuntimePluginDiagnosticProgress => {
594
+ const progress = progressByPlugin.get(plugin.id);
595
+ const completedThroughEpochSeq = progress?.completedThroughEpochSeq ?? 0;
596
+ const dependencies = (plugin.after ?? []).map((id) => (
597
+ progressByPlugin.get(id)?.completedThroughEpochSeq ?? 0
598
+ ));
599
+ const readyThroughEpochSeq = dependencies.length === 0
600
+ ? latestEpochSeq
601
+ : Math.min(latestEpochSeq, ...dependencies);
602
+ return {
603
+ plugin_id: plugin.id,
604
+ catch_up: plugin.catchUp ?? 'every_epoch',
605
+ max_in_flight: normalizedMaxInFlight(plugin),
606
+ max_pending_epochs: normalizedMaxPendingEpochs(plugin, this.maxCatchUpEpochs),
607
+ completed_through_epoch_seq: completedThroughEpochSeq,
608
+ ready_through_epoch_seq: readyThroughEpochSeq,
609
+ lag_epoch_count: pending.filter(({ work }) => (
610
+ work.epoch.epochSeq > completedThroughEpochSeq
611
+ )).length,
612
+ active_invocation_count: [...this.activeInvocations.values()]
613
+ .filter(({ pluginId }) => pluginId === plugin.id).length,
614
+ buffered_invocation_count: this.bufferedInvocations.get(plugin.id)?.size ?? 0,
615
+ active_commit: this.activeCommits.has(plugin.id),
616
+ paused: this.pausedPlugins.has(plugin.id),
617
+ };
618
+ });
619
+ return {
620
+ pending_epoch_count: pending.length,
621
+ oldest_pending_epoch_seq: oldestEpochSeq,
622
+ newest_pending_epoch_seq: newestEpochSeq,
623
+ oldest_pending_age_ms: oldest
624
+ ? Math.max(0, this.nowMs() - oldest.queuedAtMs)
625
+ : 0,
626
+ active_invocation_count: this.activeInvocations.size,
627
+ active_commit_count: this.activeCommits.size,
628
+ buffered_invocation_count: this.bufferedInvocationCount(),
629
+ input_event_commit_count: this.inputEventCommits.size,
630
+ plugins,
631
+ };
632
+ }
633
+
515
634
  async activateScope(scope: RuntimeScope): Promise<void> {
516
635
  if (this.activeScope && runtimeScopeKey(this.activeScope) === runtimeScopeKey(scope)) return;
517
636
  if (this.activeInvocations.size > 0 || this.activeCommits.size > 0 || this.bufferedInvocationCount() > 0) {
@@ -557,9 +676,12 @@ export class RuntimePluginScheduler<
557
676
  }
558
677
  this.ensureRecoveredRecords(work);
559
678
  const queuedAtMs = this.nowMs();
679
+ // Clone once at admission, then share the recursively immutable epoch core
680
+ // across plugins. Per-plugin inputs still own filtered Event/State views.
681
+ const immutableWork = deepFreeze(cloneCanonical(work));
560
682
  const completion = new Promise<RuntimeEpochExecutionResult>((resolve, reject) => {
561
683
  this.pending.set(work.epoch.epochSeq, {
562
- work: cloneCanonical(work),
684
+ work: immutableWork,
563
685
  queuedAtMs,
564
686
  resolve,
565
687
  reject,
@@ -668,7 +790,6 @@ export class RuntimePluginScheduler<
668
790
  let launched = 0;
669
791
  for (const plugin of this.plugins) {
670
792
  const maxInFlight = normalizedMaxInFlight(plugin);
671
- if (maxInFlight === 1 && this.scheduledInvocationCount(plugin.id) > 0) continue;
672
793
  let candidates = this.launchCandidates(plugin, scope);
673
794
  if (candidates.length === 0) continue;
674
795
  if (this.pausedPlugins.has(plugin.id)) {
@@ -686,14 +807,20 @@ export class RuntimePluginScheduler<
686
807
  continue;
687
808
  }
688
809
 
689
- if (maxInFlight > 1) {
690
- if ((plugin.catchUp ?? 'every_epoch') !== 'strict_ordered') {
691
- this.trimParallelBacklog(plugin, scope);
692
- }
810
+ if ((plugin.catchUp ?? 'every_epoch') !== 'strict_ordered') {
811
+ this.trimBoundedBacklog(plugin, scope);
693
812
  candidates = this.launchCandidates(plugin, scope);
813
+ if (candidates.length === 0) continue;
814
+ }
815
+ if (maxInFlight === 1 && this.scheduledInvocationCount(plugin.id) > 0) continue;
816
+
817
+ if (maxInFlight > 1) {
694
818
  const reorderCapacity = (plugin.catchUp ?? 'every_epoch') === 'strict_ordered'
695
819
  ? maxInFlight
696
- : Math.min(maxInFlight, this.maxCatchUpEpochs);
820
+ : Math.min(
821
+ maxInFlight,
822
+ normalizedMaxPendingEpochs(plugin, this.maxCatchUpEpochs),
823
+ );
697
824
  let slots = reorderCapacity - this.scheduledInvocationCount(plugin.id);
698
825
  for (const candidate of candidates) {
699
826
  if (slots <= 0) break;
@@ -707,9 +834,15 @@ export class RuntimePluginScheduler<
707
834
  const catchUp = plugin.catchUp ?? 'every_epoch';
708
835
  const count = this.catchUpCounts.get(plugin.id) ?? 0;
709
836
  const requiredIndex = candidates.findIndex((candidate) => forbidsCoalescing(candidate.work));
710
- const shouldJump = requiredIndex > 0
711
- || (requiredIndex < 0 && (catchUp === 'latest_only'
712
- || (catchUp === 'every_epoch' && count >= this.maxCatchUpEpochs && candidates.length > 1)));
837
+ const shouldJump = requiredIndex > 0 || (
838
+ requiredIndex < 0 && (
839
+ catchUp === 'latest_only' || (
840
+ catchUp === 'every_epoch'
841
+ && count >= normalizedMaxPendingEpochs(plugin, this.maxCatchUpEpochs)
842
+ && candidates.length > 1
843
+ )
844
+ )
845
+ );
713
846
  if (shouldJump && candidates.length > 1) {
714
847
  const targetIndex = requiredIndex >= 0 ? requiredIndex : candidates.length - 1;
715
848
  const skipped = candidates.slice(0, targetIndex);
@@ -770,12 +903,10 @@ export class RuntimePluginScheduler<
770
903
  // A parallel update may finish while an earlier ordered commit is still
771
904
  // performing effects. Apply the same catch-up window to those completed
772
905
  // proposals before granting the next commit lease; otherwise buffered
773
- // results can bypass trimParallelBacklog and replay an arbitrarily stale
906
+ // results can bypass trimBoundedBacklog and replay an arbitrarily stale
774
907
  // sequence of Actions after the head commit settles.
775
- if (normalizedMaxInFlight(plugin) > 1) {
776
- if ((plugin.catchUp ?? 'every_epoch') !== 'strict_ordered') {
777
- this.trimParallelBacklog(plugin, scope);
778
- }
908
+ if ((plugin.catchUp ?? 'every_epoch') !== 'strict_ordered') {
909
+ this.trimBoundedBacklog(plugin, scope);
779
910
  }
780
911
  if (this.activeCommits.has(plugin.id)) continue;
781
912
  const progress = this.pluginStore.pluginProgress(plugin.id, scope);
@@ -1308,24 +1439,32 @@ export class RuntimePluginScheduler<
1308
1439
  ));
1309
1440
  }
1310
1441
 
1311
- private trimParallelBacklog(
1442
+ private trimBoundedBacklog(
1312
1443
  plugin: RuntimeEpochPlugin<TState, TEvent>,
1313
1444
  scope: RuntimeScope,
1314
1445
  ): void {
1446
+ const maxInFlight = normalizedMaxInFlight(plugin);
1315
1447
  const catchUpWindow = Math.min(
1316
- normalizedMaxInFlight(plugin),
1317
- this.maxCatchUpEpochs,
1448
+ normalizedMaxPendingEpochs(
1449
+ plugin,
1450
+ maxInFlight > 1
1451
+ ? Math.min(maxInFlight, this.maxCatchUpEpochs)
1452
+ : this.maxCatchUpEpochs,
1453
+ ),
1454
+ 10_000,
1318
1455
  );
1319
1456
  while (true) {
1320
1457
  const ready = this.readyCandidates(plugin, scope);
1321
1458
  const earliest = ready[0];
1322
1459
  const latest = ready.at(-1);
1460
+ const requiredIndex = ready.findIndex(({ work }) => forbidsCoalescing(work));
1323
1461
  if (
1324
1462
  !earliest
1325
1463
  || !latest
1326
- || latest.work.epoch.epochSeq - earliest.work.epoch.epochSeq < catchUpWindow
1464
+ || ready.length <= catchUpWindow
1327
1465
  ) return;
1328
- if (forbidsCoalescing(earliest.work)) return;
1466
+ if (requiredIndex === 0 || forbidsCoalescing(earliest.work)) return;
1467
+ const reason = requiredIndex > 0 ? 'required_epoch_boundary' : 'catch_up_limit';
1329
1468
  // commit() is the atomic reducer/effect boundary. Once it has started we
1330
1469
  // must let it finish; only a completed proposal that has not obtained the
1331
1470
  // commit lease may be discarded.
@@ -1342,7 +1481,7 @@ export class RuntimePluginScheduler<
1342
1481
  || buffered.invocation.error !== undefined
1343
1482
  ) return;
1344
1483
  buffer.delete(earliest.work.epoch.epochSeq);
1345
- this.recordCoalesced(plugin, [earliest.work], 'catch_up_limit');
1484
+ this.recordCoalesced(plugin, [earliest.work], reason);
1346
1485
  continue;
1347
1486
  }
1348
1487
  const active = this.activeInvocations.get(
@@ -1354,12 +1493,12 @@ export class RuntimePluginScheduler<
1354
1493
  plugin.id,
1355
1494
  earliest.work.epoch.epochSeq,
1356
1495
  latest.work.epoch.epochSeq,
1357
- 'catch_up_limit',
1496
+ reason,
1358
1497
  ));
1359
1498
  }
1360
1499
  return;
1361
1500
  }
1362
- this.recordCoalesced(plugin, [earliest.work], 'catch_up_limit');
1501
+ this.recordCoalesced(plugin, [earliest.work], reason);
1363
1502
  }
1364
1503
  }
1365
1504
 
@@ -1459,17 +1598,17 @@ export class RuntimePluginScheduler<
1459
1598
  }
1460
1599
  const stateTopics = new Set(plugin.consumes?.states ?? []);
1461
1600
  const allStates = stateTopics.has('*');
1462
- return {
1463
- epoch: cloneCanonical(work.epoch),
1464
- frame: cloneCanonical(work.frame),
1465
- currentState: cloneCanonical(work.currentState),
1466
- previousState: cloneCanonical(work.previousState),
1467
- epochEvents: cloneCanonical(epochEvents.filter((event) => allEvents || eventTypes.has(event.type))),
1468
- pendingEvents: cloneCanonical([...pendingEvents.values()].sort((a, b) => a.commitSeq - b.commitSeq)),
1469
- upstreamStates: cloneCanonical(Object.fromEntries(
1601
+ return deepFreeze({
1602
+ epoch: work.epoch,
1603
+ frame: work.frame,
1604
+ currentState: work.currentState,
1605
+ previousState: work.previousState,
1606
+ epochEvents: epochEvents.filter((event) => allEvents || eventTypes.has(event.type)),
1607
+ pendingEvents: [...pendingEvents.values()].sort((a, b) => a.commitSeq - b.commitSeq),
1608
+ upstreamStates: Object.fromEntries(
1470
1609
  Object.entries(upstreamStates).filter(([topic]) => allStates || stateTopics.has(topic)),
1471
- )),
1472
- };
1610
+ ),
1611
+ });
1473
1612
  }
1474
1613
 
1475
1614
  private context(