@myclaw163/clawclaw-cli 0.8.13 → 0.8.14

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 (39) hide show
  1. package/package.json +1 -1
  2. package/skills/clawclaw/SKILL.md +3 -3
  3. package/skills/clawclaw/references/CHANNELS.md +1 -1
  4. package/skills/clawclaw/references/COMMANDS.md +2 -2
  5. package/skills/clawclaw/references/STREAM.md +4 -2
  6. package/src/lib/game-client.ts +12 -4
  7. package/src/pipeline/event-format.ts +5 -0
  8. package/src/pipeline/event-hints.ts +10 -0
  9. package/src/runtime/clawclaw/agent-event-policy.ts +2 -0
  10. package/src/runtime/clawclaw/behavior-input.ts +5 -0
  11. package/src/runtime/clawclaw/plugins/action/action-plugin.ts +150 -18
  12. package/src/runtime/clawclaw/plugins/behavior/behavior-action.ts +8 -0
  13. package/src/runtime/clawclaw/plugins/behavior/behavior-decision-history.ts +88 -0
  14. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +173 -11
  15. package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +6 -0
  16. package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +3 -1
  17. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +5 -1
  18. package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-worker.ts +5 -5
  19. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +213 -6
  20. package/src/runtime/clawclaw/plugins/source/game-transport.ts +29 -4
  21. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +153 -0
  22. package/src/runtime/clawclaw/plugins/source/types.ts +1 -0
  23. package/src/runtime/clawclaw/runtime.ts +31 -3
  24. package/src/runtime/clawclaw-event-catalog.ts +2 -0
  25. package/src/runtime/framework/events/event-repository.ts +1 -1
  26. package/src/runtime/framework/events/memory-event-repository.ts +59 -1
  27. package/src/runtime/framework/events/sqlite-event-repository.ts +23 -1
  28. package/src/runtime/framework/mailbox/types.ts +2 -0
  29. package/src/runtime/framework/persistence/async-sqlite-persistence-worker.ts +58 -0
  30. package/src/runtime/framework/persistence/memory-first-persistence.ts +380 -0
  31. package/src/runtime/framework/plugins/contracts.ts +2 -2
  32. package/src/runtime/framework/plugins/runtime-input-journal.ts +173 -17
  33. package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +23 -11
  34. package/src/runtime/framework/runtime.ts +57 -4
  35. package/src/runtime/framework/state/history/contracts.ts +9 -1
  36. package/src/runtime/framework/state/history/memory-state-history-repository.ts +49 -7
  37. package/src/runtime/framework/state/history/sqlite-state-history-repository.ts +16 -0
  38. package/src/sdk/behavior-plugin/index.ts +5 -24
  39. package/src/sdk/module-input/index.ts +47 -0
@@ -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,55 @@ 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[]>();
173
190
  private nextEpochSeq = 1;
174
191
 
192
+ constructor(snapshot?: RuntimeInputJournalSnapshot<TState, TEvent>) {
193
+ if (!snapshot) return;
194
+ for (const item of snapshot.epochs) {
195
+ const epoch = cloneCanonical(item.epoch);
196
+ const identity = sourceIdentity(epoch);
197
+ this.epochs.push(epoch);
198
+ this.indexEpoch(epoch);
199
+ this.byIdentity.set(identity, epoch);
200
+ this.hashes.set(identity, payloadHash(epoch as RuntimeInputBatch));
201
+ if (item.closed) this.closed.add(epoch.epochSeq);
202
+ if (item.inputEventsCommitted) this.inputEventCommits.add(epoch.epochSeq);
203
+ if (item.eventWatermark > 0) this.eventWatermarks.set(epoch.epochSeq, item.eventWatermark);
204
+ }
205
+ for (const item of snapshot.pluginProgress) {
206
+ this.progress.set(`${runtimeScopeKey(item.scope)}\u001f${item.progress.pluginId}`, cloneCanonical(item.progress));
207
+ }
208
+ for (const record of snapshot.pluginRecords) this.indexPluginRecord(cloneCanonical(record));
209
+ for (const record of snapshot.states) this.indexStateRecord(cloneCanonical(record));
210
+ this.nextEpochSeq = Math.max(snapshot.nextEpochSeq, 1);
211
+ }
212
+
213
+ snapshot(): RuntimeInputJournalSnapshot<TState, TEvent> {
214
+ const scopeByKey = new Map<string, RuntimeScope>();
215
+ for (const epoch of this.epochs) scopeByKey.set(runtimeScopeKey(epoch.scope), epoch.scope);
216
+ const pluginProgress: RuntimeInputJournalSnapshot['pluginProgress'] = [];
217
+ for (const [key, progress] of this.progress) {
218
+ const scopeKey = key.slice(0, key.lastIndexOf('\u001f'));
219
+ const scope = scopeByKey.get(scopeKey);
220
+ if (scope) pluginProgress.push({ scope: cloneCanonical(scope), progress: cloneCanonical(progress) });
221
+ }
222
+ return cloneCanonical({
223
+ epochs: this.epochs.map((epoch) => ({
224
+ epoch,
225
+ closed: this.closed.has(epoch.epochSeq),
226
+ inputEventsCommitted: this.inputEventCommits.has(epoch.epochSeq),
227
+ eventWatermark: this.eventWatermarks.get(epoch.epochSeq) ?? 0,
228
+ })),
229
+ pluginProgress,
230
+ pluginRecords: this.pluginOutcomeRecords,
231
+ states: this.stateRecords,
232
+ nextEpochSeq: this.nextEpochSeq,
233
+ });
234
+ }
235
+
175
236
  accept(batch: RuntimeInputBatch<TState, TEvent>): RuntimeInputAcceptance<TState, TEvent> {
176
237
  assertRuntimeInputBatch(batch);
177
238
  const identity = sourceIdentity(batch);
@@ -186,28 +247,28 @@ implements RuntimePersistenceStore<TState, TEvent> {
186
247
  epochSeq: this.nextEpochSeq++,
187
248
  };
188
249
  this.epochs.push(epoch);
250
+ this.indexEpoch(epoch);
189
251
  this.byIdentity.set(identity, epoch);
190
252
  this.hashes.set(identity, hash);
191
253
  return { inserted: true, epoch: cloneCanonical(epoch) };
192
254
  }
193
255
 
194
256
  epoch(epochSeq: number): RuntimeEpoch<TState, TEvent> | null {
195
- const value = this.epochs.find((item) => item.epochSeq === epochSeq);
257
+ const value = this.epochsBySeq.get(epochSeq);
196
258
  return value ? cloneCanonical(value) : null;
197
259
  }
198
260
 
199
261
  list(scope: RuntimeScope, afterEpochSeq = 0, limit = 100): RuntimeEpoch<TState, TEvent>[] {
200
- return this.epochs
201
- .filter((item) => item.epochSeq > afterEpochSeq && sameRuntimeScope(item.scope, scope))
262
+ return (this.epochsByScope.get(runtimeScopeKey(scope)) ?? [])
263
+ .filter((item) => item.epochSeq > afterEpochSeq)
202
264
  .slice(0, Math.max(1, Math.min(limit, 10_000)))
203
265
  .map(cloneCanonical);
204
266
  }
205
267
 
206
268
  listOpen(scope: RuntimeScope, afterEpochSeq = 0, limit = 100): RuntimeEpoch<TState, TEvent>[] {
207
- return this.epochs
269
+ return (this.epochsByScope.get(runtimeScopeKey(scope)) ?? [])
208
270
  .filter((item) => (
209
271
  item.epochSeq > afterEpochSeq
210
- && sameRuntimeScope(item.scope, scope)
211
272
  && !this.closed.has(item.epochSeq)
212
273
  ))
213
274
  .slice(0, Math.max(1, Math.min(limit, 10_000)))
@@ -219,11 +280,13 @@ implements RuntimePersistenceStore<TState, TEvent> {
219
280
  }
220
281
 
221
282
  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);
283
+ const epochs = this.epochsByScope.get(runtimeScopeKey(scope)) ?? [];
284
+ let maximum = 0;
285
+ for (const candidate of epochs) {
286
+ if (candidate.epochSeq > epochSeq) break;
287
+ maximum = Math.max(maximum, this.eventWatermarks.get(candidate.epochSeq) ?? 0);
288
+ }
289
+ return maximum;
227
290
  }
228
291
 
229
292
  inputEventsCommitted(epochSeq: number): boolean {
@@ -240,16 +303,21 @@ implements RuntimePersistenceStore<TState, TEvent> {
240
303
  }
241
304
 
242
305
  recordPlugin(record: RuntimeEpochPluginRecord): void {
243
- const index = this.pluginOutcomeRecords.findIndex((candidate) => (
306
+ const epochRecords = this.pluginOutcomeRecordsByEpoch.get(record.epochSeq) ?? [];
307
+ const index = epochRecords.findIndex((candidate) => (
244
308
  candidate.epochSeq === record.epochSeq && candidate.pluginId === record.pluginId
245
309
  ));
246
- if (index >= 0) this.pluginOutcomeRecords[index] = cloneCanonical(record);
247
- else this.pluginOutcomeRecords.push(cloneCanonical(record));
310
+ const stored = cloneCanonical(record);
311
+ if (index >= 0) {
312
+ const previous = epochRecords[index];
313
+ epochRecords[index] = stored;
314
+ const allIndex = this.pluginOutcomeRecords.indexOf(previous);
315
+ if (allIndex >= 0) this.pluginOutcomeRecords[allIndex] = stored;
316
+ } else this.indexPluginRecord(stored);
248
317
  }
249
318
 
250
319
  pluginRecords(epochSeq: number): RuntimeEpochPluginRecord[] {
251
- return this.pluginOutcomeRecords
252
- .filter((record) => record.epochSeq === epochSeq)
320
+ return (this.pluginOutcomeRecordsByEpoch.get(epochSeq) ?? [])
253
321
  .sort((a, b) => a.pluginId.localeCompare(b.pluginId))
254
322
  .map(cloneCanonical);
255
323
  }
@@ -268,11 +336,45 @@ implements RuntimePersistenceStore<TState, TEvent> {
268
336
  }
269
337
 
270
338
  saveStates(records: readonly RuntimeEpochStateRecord[]): void {
271
- this.stateRecords.push(...records.map(cloneCanonical));
339
+ for (const record of records) {
340
+ const epochRecords = this.stateRecordsByEpoch.get(record.epochSeq) ?? [];
341
+ const index = epochRecords.findIndex((candidate) => (
342
+ candidate.pluginId === record.pluginId && candidate.topic === record.topic
343
+ ));
344
+ const stored = cloneCanonical(record);
345
+ if (index >= 0) {
346
+ const previous = epochRecords[index];
347
+ epochRecords[index] = stored;
348
+ const allIndex = this.stateRecords.indexOf(previous);
349
+ if (allIndex >= 0) this.stateRecords[allIndex] = stored;
350
+ } else this.indexStateRecord(stored);
351
+ }
272
352
  }
273
353
 
274
354
  states(epochSeq: number): RuntimeEpochStateRecord[] {
275
- return this.stateRecords.filter((row) => row.epochSeq === epochSeq).map(cloneCanonical);
355
+ return (this.stateRecordsByEpoch.get(epochSeq) ?? []).map(cloneCanonical);
356
+ }
357
+
358
+ private indexEpoch(epoch: RuntimeEpoch<TState, TEvent>): void {
359
+ this.epochsBySeq.set(epoch.epochSeq, epoch);
360
+ const key = runtimeScopeKey(epoch.scope);
361
+ const scoped = this.epochsByScope.get(key) ?? [];
362
+ scoped.push(epoch);
363
+ this.epochsByScope.set(key, scoped);
364
+ }
365
+
366
+ private indexPluginRecord(record: RuntimeEpochPluginRecord): void {
367
+ this.pluginOutcomeRecords.push(record);
368
+ const rows = this.pluginOutcomeRecordsByEpoch.get(record.epochSeq) ?? [];
369
+ rows.push(record);
370
+ this.pluginOutcomeRecordsByEpoch.set(record.epochSeq, rows);
371
+ }
372
+
373
+ private indexStateRecord(record: RuntimeEpochStateRecord): void {
374
+ this.stateRecords.push(record);
375
+ const rows = this.stateRecordsByEpoch.get(record.epochSeq) ?? [];
376
+ rows.push(record);
377
+ this.stateRecordsByEpoch.set(record.epochSeq, rows);
276
378
  }
277
379
 
278
380
  }
@@ -553,6 +655,60 @@ implements RuntimePersistenceStore<TState, TEvent> {
553
655
  this.db.close();
554
656
  }
555
657
 
658
+ /** Full startup image for the memory-primary runtime. This is never used on a hot tick. */
659
+ snapshot(): RuntimeInputJournalSnapshot<TState, TEvent> {
660
+ const epochRows = this.db.prepare('SELECT * FROM runtime_epochs ORDER BY epoch_seq ASC').all();
661
+ const epochs = epochRows.map((row) => ({
662
+ epoch: this.fromRow(row),
663
+ closed: row.status === 'closed',
664
+ inputEventsCommitted: typeof row.input_events_committed_at === 'string',
665
+ eventWatermark: numberValue(row.event_commit_watermark),
666
+ }));
667
+ const pluginProgress = this.db.prepare('SELECT * FROM runtime_plugin_progress').all().map((row) => ({
668
+ scope: {
669
+ adapterId: String(row.adapter_id),
670
+ accountId: String(row.account_id),
671
+ sessionId: String(row.session_id),
672
+ segmentId: String(row.segment_id),
673
+ },
674
+ progress: {
675
+ pluginId: String(row.plugin_id),
676
+ completedThroughEpochSeq: numberValue(row.completed_through_epoch_seq),
677
+ eventCursor: numberValue(row.event_cursor),
678
+ ...(typeof row.checkpoint_json === 'string' ? { checkpoint: parseJson(row.checkpoint_json) } : {}),
679
+ updatedAt: String(row.updated_at),
680
+ },
681
+ }));
682
+ const pluginRecords = this.db.prepare('SELECT * FROM runtime_plugin_outcomes ORDER BY epoch_seq, plugin_id')
683
+ .all().map((row) => ({
684
+ epochSeq: numberValue(row.epoch_seq),
685
+ pluginId: String(row.plugin_id),
686
+ invocationId: String(row.invocation_id),
687
+ outcome: row.outcome as RuntimeEpochPluginRecord['outcome'],
688
+ ...(typeof row.reason === 'string' ? { reason: row.reason } : {}),
689
+ durationMs: numberValue(row.duration_ms),
690
+ stateCount: numberValue(row.state_count),
691
+ eventCount: numberValue(row.event_count),
692
+ eventCursorBefore: numberValue(row.event_cursor_before),
693
+ eventCursorAfter: numberValue(row.event_cursor_after),
694
+ recordedAt: String(row.recorded_at),
695
+ }));
696
+ const states = this.db.prepare('SELECT * FROM runtime_plugin_states ORDER BY epoch_seq, plugin_id, topic')
697
+ .all().map((row) => ({
698
+ epochSeq: numberValue(row.epoch_seq),
699
+ pluginId: String(row.plugin_id),
700
+ topic: String(row.topic),
701
+ value: parseJson(row.value_json),
702
+ }));
703
+ return {
704
+ epochs,
705
+ pluginProgress,
706
+ pluginRecords,
707
+ states,
708
+ nextEpochSeq: (epochs.at(-1)?.epoch.epochSeq ?? 0) + 1,
709
+ };
710
+ }
711
+
556
712
  private findByIdentity(scope: RuntimeScope, sourceId: string, sourceKey: string) {
557
713
  return this.db.prepare(`
558
714
  SELECT * FROM runtime_epochs
@@ -167,6 +167,15 @@ function rounded(value: number): number {
167
167
  return Math.round(value * 1_000) / 1_000;
168
168
  }
169
169
 
170
+ function deepFreeze<T>(value: T, seen = new WeakSet<object>()): T {
171
+ if (!value || typeof value !== 'object' || Object.isFrozen(value)) return value;
172
+ const object = value as object;
173
+ if (seen.has(object)) return value;
174
+ seen.add(object);
175
+ for (const child of Object.values(object)) deepFreeze(child, seen);
176
+ return Object.freeze(value);
177
+ }
178
+
170
179
  function percentile(sorted: readonly number[], fraction: number): number {
171
180
  if (sorted.length === 0) return 0;
172
181
  return sorted[Math.max(0, Math.ceil(sorted.length * fraction) - 1)]!;
@@ -557,9 +566,12 @@ export class RuntimePluginScheduler<
557
566
  }
558
567
  this.ensureRecoveredRecords(work);
559
568
  const queuedAtMs = this.nowMs();
569
+ // Clone once at admission, then share the recursively immutable epoch core
570
+ // across plugins. Per-plugin inputs still own filtered Event/State views.
571
+ const immutableWork = deepFreeze(cloneCanonical(work));
560
572
  const completion = new Promise<RuntimeEpochExecutionResult>((resolve, reject) => {
561
573
  this.pending.set(work.epoch.epochSeq, {
562
- work: cloneCanonical(work),
574
+ work: immutableWork,
563
575
  queuedAtMs,
564
576
  resolve,
565
577
  reject,
@@ -1459,17 +1471,17 @@ export class RuntimePluginScheduler<
1459
1471
  }
1460
1472
  const stateTopics = new Set(plugin.consumes?.states ?? []);
1461
1473
  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(
1474
+ return deepFreeze({
1475
+ epoch: work.epoch,
1476
+ frame: work.frame,
1477
+ currentState: work.currentState,
1478
+ previousState: work.previousState,
1479
+ epochEvents: epochEvents.filter((event) => allEvents || eventTypes.has(event.type)),
1480
+ pendingEvents: [...pendingEvents.values()].sort((a, b) => a.commitSeq - b.commitSeq),
1481
+ upstreamStates: Object.fromEntries(
1470
1482
  Object.entries(upstreamStates).filter(([topic]) => allStates || stateTopics.has(topic)),
1471
- )),
1472
- };
1483
+ ),
1484
+ });
1473
1485
  }
1474
1486
 
1475
1487
  private context(
@@ -73,6 +73,7 @@ import {
73
73
  type StateProviderResult,
74
74
  type TrajectoryRecord,
75
75
  } from './state/index.js';
76
+ import { performance } from 'node:perf_hooks';
76
77
  import { randomUUID } from 'crypto';
77
78
  import type { TelemetryRecorder } from '../observability/index.js';
78
79
 
@@ -323,6 +324,13 @@ implements RuntimeSourceContext<Record<string, any>, Record<string, unknown>> {
323
324
  StateProviderResult<Record<string, any> | null>
324
325
  >();
325
326
  private readonly epochCompletions = new Map<number, Promise<RuntimeEpochExecutionResult>>();
327
+ private readonly epochIntakeTimings = new Map<number, {
328
+ startedAtMs: number;
329
+ journalMs: number;
330
+ historyMs: number;
331
+ stateProjectionMs: number;
332
+ intakeTotalMs: number;
333
+ }>();
326
334
  private readonly closedReadyAnchors = new Map<
327
335
  number,
328
336
  RuntimeReadyAnchor<Record<string, any> | null>
@@ -360,6 +368,7 @@ implements RuntimeSourceContext<Record<string, any>, Record<string, unknown>> {
360
368
  if (options.stateHistoryRepository) {
361
369
  this.stateHistoryRepository = options.stateHistoryRepository;
362
370
  historyPersistence = options.stateHistoryRepository instanceof SqliteStateHistoryRepository
371
+ || (options.stateHistoryRepository as { persistenceKind?: string }).persistenceKind === 'memory-first-sqlite'
363
372
  ? 'sqlite'
364
373
  : 'memory';
365
374
  } else if (options.stateHistoryPath) {
@@ -377,6 +386,7 @@ implements RuntimeSourceContext<Record<string, any>, Record<string, unknown>> {
377
386
  if (options.inputJournal) {
378
387
  this.inputJournal = options.inputJournal;
379
388
  inputJournalPersistence = options.inputJournal instanceof SqliteRuntimeInputJournal
389
+ || (options.inputJournal as { persistenceKind?: string }).persistenceKind === 'memory-first-sqlite'
380
390
  ? 'sqlite'
381
391
  : 'memory';
382
392
  } else if (options.inputJournalPath) {
@@ -385,7 +395,10 @@ implements RuntimeSourceContext<Record<string, any>, Record<string, unknown>> {
385
395
  } else {
386
396
  this.inputJournal = new MemoryRuntimeInputJournal();
387
397
  }
388
- const eventPersistence = this.repository instanceof SqliteEventRepository ? 'sqlite' : 'memory';
398
+ const eventPersistence = this.repository instanceof SqliteEventRepository
399
+ || (this.repository as { persistenceKind?: string }).persistenceKind === 'memory-first-sqlite'
400
+ ? 'sqlite'
401
+ : 'memory';
389
402
  this.persistenceBase = {
390
403
  events: eventPersistence,
391
404
  stateHistory: historyPersistence,
@@ -774,6 +787,8 @@ implements RuntimeSourceContext<Record<string, any>, Record<string, unknown>> {
774
787
  batch: RuntimeInputBatch<Record<string, any>, Record<string, unknown>>,
775
788
  ): Promise<RuntimeInputAcceptance<Record<string, any>, Record<string, unknown>>> {
776
789
  this.assertSourceInputOpen();
790
+ const intakeStartedAtMs = performance.now();
791
+ const journalStartedAtMs = performance.now();
777
792
  let acceptance: RuntimeInputAcceptance<Record<string, any>, Record<string, unknown>>;
778
793
  try {
779
794
  assertRuntimeInputBatch(batch);
@@ -789,6 +804,7 @@ implements RuntimeSourceContext<Record<string, any>, Record<string, unknown>> {
789
804
  }, { component: 'runtime.input', scope: this.publicScope() });
790
805
  throw error;
791
806
  }
807
+ const journalMs = Math.max(0, performance.now() - journalStartedAtMs);
792
808
  if (!acceptance.inserted) {
793
809
  this.observability?.log('debug', 'runtime.input.duplicate', {
794
810
  source_id: batch.sourceId,
@@ -800,6 +816,7 @@ implements RuntimeSourceContext<Record<string, any>, Record<string, unknown>> {
800
816
 
801
817
  const epoch = acceptance.epoch;
802
818
  this.latestAcceptedEpochSeq = Math.max(this.latestAcceptedEpochSeq, epoch.epochSeq);
819
+ const historyStartedAtMs = performance.now();
803
820
  const previousFrame = this.stateHistoryRepository.latestStateFrame(epoch.scope);
804
821
  const frame = this.stateHistoryRepository.appendStateFrame({
805
822
  epochSeq: epoch.epochSeq,
@@ -813,7 +830,9 @@ implements RuntimeSourceContext<Record<string, any>, Record<string, unknown>> {
813
830
  receivedAtMs: milliseconds(epoch.receivedAt) ?? Date.now(),
814
831
  state: epoch.state,
815
832
  }).frame;
833
+ const historyMs = Math.max(0, performance.now() - historyStartedAtMs);
816
834
 
835
+ const stateProjectionStartedAtMs = performance.now();
817
836
  const projectedState = this.currentStateFromRuntimeState(epoch.state);
818
837
  if (projectedState !== null) {
819
838
  const current = this.stateIngress.snapshot();
@@ -840,6 +859,15 @@ implements RuntimeSourceContext<Record<string, any>, Record<string, unknown>> {
840
859
  }
841
860
  const currentState = this.readAgentState();
842
861
  this.acceptedAgentStateByEpoch.set(epoch.epochSeq, structuredClone(currentState));
862
+ const stateProjectionMs = Math.max(0, performance.now() - stateProjectionStartedAtMs);
863
+ const intakeTotalMs = Math.max(0, performance.now() - intakeStartedAtMs);
864
+ this.epochIntakeTimings.set(epoch.epochSeq, {
865
+ startedAtMs: intakeStartedAtMs,
866
+ journalMs,
867
+ historyMs,
868
+ stateProjectionMs,
869
+ intakeTotalMs,
870
+ });
843
871
 
844
872
  this.observability?.log('debug', 'runtime.input.accepted', {
845
873
  source_id: epoch.sourceId,
@@ -854,6 +882,10 @@ implements RuntimeSourceContext<Record<string, any>, Record<string, unknown>> {
854
882
  cause: typeof epoch.state.cause === 'string' ? epoch.state.cause : undefined,
855
883
  connection: typeof epoch.state.connection === 'string' ? epoch.state.connection : undefined,
856
884
  game_snapshot_status: epoch.state.game_snapshot?.status,
885
+ journal_ms: Math.round(journalMs * 1_000) / 1_000,
886
+ state_history_ms: Math.round(historyMs * 1_000) / 1_000,
887
+ state_projection_ms: Math.round(stateProjectionMs * 1_000) / 1_000,
888
+ intake_total_ms: Math.round(intakeTotalMs * 1_000) / 1_000,
857
889
  }, { component: 'runtime.input', scope: this.publicScope() });
858
890
 
859
891
  const completion = this.pluginScheduler.enqueue({
@@ -1137,9 +1169,9 @@ implements RuntimeSourceContext<Record<string, any>, Record<string, unknown>> {
1137
1169
  this.sourceInputOpen = false;
1138
1170
  this.closing = false;
1139
1171
  this.closed = true;
1140
- this.stateHistoryRepository.close?.();
1141
- this.inputJournal.close?.();
1142
- this.repository.close?.();
1172
+ await this.stateHistoryRepository.close?.();
1173
+ await this.inputJournal.close?.();
1174
+ await this.repository.close?.();
1143
1175
  this.observability?.log('info', 'runtime.owner.stopped', {
1144
1176
  event_repository: this.persistence.events,
1145
1177
  state_history_repository: this.persistence.stateHistory,
@@ -1372,6 +1404,7 @@ implements RuntimeSourceContext<Record<string, any>, Record<string, unknown>> {
1372
1404
  frameSeq: number,
1373
1405
  result: RuntimeEpochExecutionResult,
1374
1406
  ): Promise<void> {
1407
+ const finalizeStartedAtMs = performance.now();
1375
1408
  const isCurrentScope = sameScope(epoch.scope, this.scope());
1376
1409
  const acceptedState = this.acceptedAgentStateByEpoch.get(epoch.epochSeq)
1377
1410
  ?? this.recoveredAgentState(epoch);
@@ -1435,6 +1468,16 @@ implements RuntimeSourceContext<Record<string, any>, Record<string, unknown>> {
1435
1468
  for (const acceptedEpochSeq of this.acceptedAgentStateByEpoch.keys()) {
1436
1469
  if (acceptedEpochSeq <= epoch.epochSeq) this.acceptedAgentStateByEpoch.delete(acceptedEpochSeq);
1437
1470
  }
1471
+ const intakeTiming = this.epochIntakeTimings.get(epoch.epochSeq);
1472
+ this.epochIntakeTimings.delete(epoch.epochSeq);
1473
+ const finalizeMs = Math.max(0, performance.now() - finalizeStartedAtMs);
1474
+ const totalMs = intakeTiming
1475
+ ? Math.max(0, performance.now() - intakeTiming.startedAtMs)
1476
+ : result.durationMs + finalizeMs;
1477
+ const longestPlugin = [...result.outcomes].sort((left, right) => right.durationMs - left.durationMs)[0];
1478
+ const persistenceHealth = (
1479
+ this.repository as { persistenceHealth?: () => Record<string, unknown> }
1480
+ ).persistenceHealth?.();
1438
1481
  this.observability?.log('debug', 'runtime.view.ready', {
1439
1482
  epoch_seq: epoch.epochSeq,
1440
1483
  latest_epoch_seq: this.latestAcceptedEpochSeq,
@@ -1442,6 +1485,16 @@ implements RuntimeSourceContext<Record<string, any>, Record<string, unknown>> {
1442
1485
  frame_seq: frameSeq,
1443
1486
  event_watermark: result.eventWatermark,
1444
1487
  current_scope: isCurrentScope,
1488
+ total_duration_ms: Math.round(totalMs * 1_000) / 1_000,
1489
+ intake_duration_ms: Math.round((intakeTiming?.intakeTotalMs ?? 0) * 1_000) / 1_000,
1490
+ scheduler_duration_ms: Math.round(result.durationMs * 1_000) / 1_000,
1491
+ ready_view_finalize_ms: Math.round(finalizeMs * 1_000) / 1_000,
1492
+ longest_plugin_id: longestPlugin?.pluginId,
1493
+ longest_plugin_duration_ms: longestPlugin
1494
+ ? Math.round(longestPlugin.durationMs * 1_000) / 1_000
1495
+ : 0,
1496
+ persistence_pending_operations: persistenceHealth?.pendingOperations,
1497
+ persistence_degraded: persistenceHealth?.degraded,
1445
1498
  }, { component: 'runtime.view', scope: this.publicScope() });
1446
1499
  }
1447
1500
 
@@ -118,6 +118,14 @@ export interface AppendStateFrameResult<TState = Record<string, unknown>> {
118
118
  frame: StoredStateFrame<TState>;
119
119
  }
120
120
 
121
+ export interface StateHistorySnapshot<TPosition = unknown, TState = Record<string, unknown>> {
122
+ scopes: HistoryScopeRecord[];
123
+ stateFrames: StoredStateFrame<TState>[];
124
+ records: Array<TrajectoryRecord<TPosition> & { recordSeq: number }>;
125
+ nextFrameSeq: number;
126
+ nextRecordSeq: number;
127
+ }
128
+
121
129
  export interface StateFrameHistoryReader<TState = Record<string, unknown>> {
122
130
  /** Reads the canonical accepted State journal. Implementations may use a hot cache. */
123
131
  queryStateFrames(query: StateFrameQuery): StateFrameQueryResult<TState>;
@@ -135,7 +143,7 @@ export interface StateJournal<TState = Record<string, unknown>>
135
143
  markScopeIncomplete(scope: RuntimeScope): void;
136
144
  getScope(scope: RuntimeScope): HistoryScopeRecord | null;
137
145
  appendStateFrame(frame: StateFrameRecord<TState>): AppendStateFrameResult<TState>;
138
- close?(): void;
146
+ close?(): void | Promise<void>;
139
147
  }
140
148
 
141
149
  /** Sparse records used by transport-gap diagnostics and adapters that explicitly project them. */
@@ -9,6 +9,7 @@ import type {
9
9
  StateFrameQueryResult,
10
10
  StateFrameRecord,
11
11
  StateHistoryRepository,
12
+ StateHistorySnapshot,
12
13
  StoredStateFrame,
13
14
  TrajectoryRecord,
14
15
  } from './contracts.js';
@@ -23,12 +24,47 @@ export class MemoryStateHistoryRepository<
23
24
  > implements StateHistoryRepository<TPosition, TState> {
24
25
  private readonly scopes = new Map<string, HistoryScopeRecord>();
25
26
  private readonly stateFrames: StoredStateFrame<TState>[] = [];
27
+ private readonly stateFramesByScope = new Map<string, StoredStateFrame<TState>[]>();
26
28
  private readonly stateFrameDedupe = new Map<string, StoredStateFrame<TState>>();
27
29
  private readonly records: Array<TrajectoryRecord<TPosition> & { recordSeq: number }> = [];
30
+ private readonly recordsByScope = new Map<string, Array<TrajectoryRecord<TPosition> & { recordSeq: number }>>();
28
31
  private readonly dedupe = new Set<string>();
29
32
  private nextFrameSeq = 1;
30
33
  private nextRecordSeq = 1;
31
34
 
35
+ constructor(snapshot?: StateHistorySnapshot<TPosition, TState>) {
36
+ if (!snapshot) return;
37
+ for (const scope of snapshot.scopes) this.scopes.set(runtimeScopeKey(scope.scope), cloneCanonical(scope));
38
+ for (const frame of snapshot.stateFrames) {
39
+ const stored = cloneCanonical(frame);
40
+ this.stateFrames.push(stored);
41
+ const scoped = this.stateFramesByScope.get(runtimeScopeKey(frame.scope)) ?? [];
42
+ scoped.push(stored);
43
+ this.stateFramesByScope.set(runtimeScopeKey(frame.scope), scoped);
44
+ this.stateFrameDedupe.set(`${runtimeScopeKey(frame.scope)}\u001f${frame.sourceKey}`, stored);
45
+ }
46
+ for (const record of snapshot.records) {
47
+ const stored = cloneCanonical(record);
48
+ this.records.push(stored);
49
+ const scoped = this.recordsByScope.get(runtimeScopeKey(record.scope)) ?? [];
50
+ scoped.push(stored);
51
+ this.recordsByScope.set(runtimeScopeKey(record.scope), scoped);
52
+ this.dedupe.add(dedupeKey(stored));
53
+ }
54
+ this.nextFrameSeq = Math.max(snapshot.nextFrameSeq, 1);
55
+ this.nextRecordSeq = Math.max(snapshot.nextRecordSeq, 1);
56
+ }
57
+
58
+ snapshot(): StateHistorySnapshot<TPosition, TState> {
59
+ return cloneCanonical({
60
+ scopes: [...this.scopes.values()],
61
+ stateFrames: this.stateFrames,
62
+ records: this.records,
63
+ nextFrameSeq: this.nextFrameSeq,
64
+ nextRecordSeq: this.nextRecordSeq,
65
+ });
66
+ }
67
+
32
68
  openScope(scope: RuntimeScope, openedAtMs = Date.now(), historyComplete = true): HistoryScopeRecord {
33
69
  for (const stored of this.scopes.values()) {
34
70
  if (
@@ -88,6 +124,9 @@ export class MemoryStateHistoryRepository<
88
124
  frameSeq: this.nextFrameSeq++,
89
125
  };
90
126
  this.stateFrames.push(stored);
127
+ const scopedFrames = this.stateFramesByScope.get(scopeKey) ?? [];
128
+ scopedFrames.push(stored);
129
+ this.stateFramesByScope.set(scopeKey, scopedFrames);
91
130
  this.stateFrameDedupe.set(dedupe, stored);
92
131
  return { inserted: true, frame: cloneCanonical(stored) };
93
132
  }
@@ -95,9 +134,8 @@ export class MemoryStateHistoryRepository<
95
134
  queryStateFrames(query: StateFrameQuery): StateFrameQueryResult<TState> {
96
135
  const order = query.order ?? 'asc';
97
136
  const limit = Math.max(1, Math.min(query.limit ?? 100, 10_000));
98
- let selected = this.stateFrames.filter((frame) => (
99
- sameRuntimeScope(frame.scope, query.scope)
100
- && (query.fromEpochSeq === undefined
137
+ let selected = (this.stateFramesByScope.get(runtimeScopeKey(query.scope)) ?? []).filter((frame) => (
138
+ (query.fromEpochSeq === undefined
101
139
  || (frame.epochSeq !== undefined && frame.epochSeq >= query.fromEpochSeq))
102
140
  && (query.toEpochSeq === undefined
103
141
  || (frame.epochSeq !== undefined && frame.epochSeq <= query.toEpochSeq))
@@ -142,7 +180,12 @@ export class MemoryStateHistoryRepository<
142
180
  continue;
143
181
  }
144
182
  this.dedupe.add(key);
145
- this.records.push({ ...cloneCanonical(record), recordSeq: this.nextRecordSeq++ });
183
+ const stored = { ...cloneCanonical(record), recordSeq: this.nextRecordSeq++ };
184
+ this.records.push(stored);
185
+ const scopeKey = runtimeScopeKey(record.scope);
186
+ const scoped = this.recordsByScope.get(scopeKey) ?? [];
187
+ scoped.push(stored);
188
+ this.recordsByScope.set(scopeKey, scoped);
146
189
  inserted += 1;
147
190
  }
148
191
  return { inserted, duplicates };
@@ -153,9 +196,8 @@ export class MemoryStateHistoryRepository<
153
196
  const limit = Math.max(1, Math.min(query.limit ?? 100, 1000));
154
197
  const subjectSet = query.subjectIds ? new Set(query.subjectIds) : null;
155
198
  const kindSet = query.kinds ? new Set(query.kinds) : null;
156
- let selected = this.records.filter((record) => (
157
- sameRuntimeScope(record.scope, query.scope)
158
- && (!subjectSet || subjectSet.has(record.subjectId))
199
+ let selected = (this.recordsByScope.get(runtimeScopeKey(query.scope)) ?? []).filter((record) => (
200
+ (!subjectSet || subjectSet.has(record.subjectId))
159
201
  && (!kindSet || kindSet.has(record.kind))
160
202
  && (query.afterRecordSeq === undefined || record.recordSeq > query.afterRecordSeq)
161
203
  && (query.beforeRecordSeq === undefined || record.recordSeq < query.beforeRecordSeq)
@@ -13,6 +13,7 @@ import type {
13
13
  StateFrameQueryResult,
14
14
  StateFrameRecord,
15
15
  StateHistoryRepository,
16
+ StateHistorySnapshot,
16
17
  StoredStateFrame,
17
18
  TrajectoryRecord,
18
19
  TrajectoryRecordKind,
@@ -355,6 +356,21 @@ export class SqliteStateHistoryRepository<
355
356
  this.db.close();
356
357
  }
357
358
 
359
+ /** Full startup image for the memory-primary runtime. This is never used on a hot tick. */
360
+ snapshot(): StateHistorySnapshot<TPosition, TState> {
361
+ const stateFrames = this.db.prepare('SELECT * FROM state_frames ORDER BY frame_seq ASC')
362
+ .all().map((row) => this.stateFrameFromRow(row));
363
+ const records = this.db.prepare('SELECT * FROM trajectory_records ORDER BY record_seq ASC')
364
+ .all().map((row) => this.recordFromRow(row));
365
+ return {
366
+ scopes: this.db.prepare('SELECT * FROM history_scopes').all().map((row) => this.scopeFromRow(row)),
367
+ stateFrames,
368
+ records,
369
+ nextFrameSeq: (stateFrames.at(-1)?.frameSeq ?? 0) + 1,
370
+ nextRecordSeq: (records.at(-1)?.recordSeq ?? 0) + 1,
371
+ };
372
+ }
373
+
358
374
  private rememberStateFrame(frame: StoredStateFrame<TState>): void {
359
375
  const key = runtimeScopeKey(frame.scope);
360
376
  const recent = this.recentStateFrames.get(key) ?? [];