@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
@@ -133,6 +133,45 @@ interface PreparedPerceptionFrame {
133
133
  readonly stored: StoredStateFrame<Record<string, any>>;
134
134
  readonly visual: PerceptionFrame | null;
135
135
  readonly analyses: readonly PerceptionModuleAnalysis[];
136
+ readonly analysisTiming: PerceptionAnalysisTiming;
137
+ }
138
+
139
+ interface PerceptionAnalysisTiming {
140
+ readonly workerQueueMs: number;
141
+ readonly workerRoundtripMs: number;
142
+ readonly moduleCpuSumMs: number;
143
+ readonly moduleCpuMaxMs: number;
144
+ readonly workerCount: number;
145
+ }
146
+
147
+ interface PerceptionFrameComputationTiming extends PerceptionAnalysisTiming {
148
+ readonly projectionMs: number;
149
+ readonly historyPrepareMs: number;
150
+ readonly updateTotalMs: number;
151
+ }
152
+
153
+ interface PerceptionFrameTimingWindow {
154
+ readonly startedAtMs: number;
155
+ readonly projectionMs: number[];
156
+ readonly historyPrepareMs: number[];
157
+ readonly workerQueueMs: number[];
158
+ readonly workerRoundtripMs: number[];
159
+ readonly moduleCpuSumMs: number[];
160
+ readonly moduleCpuMaxMs: number[];
161
+ readonly updateTotalMs: number[];
162
+ readonly commitMs: number[];
163
+ readonly totalMs: number[];
164
+ workerCountMax: number;
165
+ }
166
+
167
+ interface PerceptionFrameTimingSample extends PerceptionFrameComputationTiming {
168
+ readonly commitMs: number;
169
+ readonly totalMs: number;
170
+ }
171
+
172
+ interface CachedProjectedFrame {
173
+ readonly stored: Pick<StoredStateFrame<Record<string, any>>, 'frameSeq' | 'connectionId'>;
174
+ readonly visual: PerceptionFrame;
136
175
  }
137
176
 
138
177
  interface PerceptionModuleAnalysis {
@@ -152,6 +191,7 @@ interface PerceptionComputationProposal {
152
191
  readonly schema: 'clawclaw.perception-computation.v1';
153
192
  readonly visual: PerceptionFrame | null;
154
193
  readonly analyses: readonly PerceptionModuleAnalysis[];
194
+ readonly timing?: PerceptionFrameComputationTiming;
155
195
  }
156
196
 
157
197
  interface PerceptionCheckpoint {
@@ -331,6 +371,8 @@ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<strin
331
371
  private lastVisualFrame: PerceptionFrame | null = null;
332
372
  private lastConnectionId: string | null = null;
333
373
  private readonly analysisWindow: PerceptionFrame[] = [];
374
+ /** Bounded projection cache shared by overlapping epoch analyses. */
375
+ private readonly projectedFrameCache = new Map<number, CachedProjectedFrame>();
334
376
  private replayFromFrameSeq: number | null = null;
335
377
  private readonly moduleFailureReports = new Map<string, {
336
378
  lastReportedAtMs: number;
@@ -339,6 +381,7 @@ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<strin
339
381
  }>();
340
382
  private readonly moduleTimingWindows = new Map<string, PerceptionModuleTimingWindow>();
341
383
  private moduleTimingWindowStartedAt = performance.now();
384
+ private frameTimingWindow: PerceptionFrameTimingWindow = this.newFrameTimingWindow();
342
385
  private runnersStarted = false;
343
386
  private runnersStartTask?: Promise<void>;
344
387
  private runnersStartGeneration = 0;
@@ -405,15 +448,26 @@ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<strin
405
448
  input: RuntimeEpochPluginInput<Record<string, any>>,
406
449
  context: RuntimeEpochPluginContext<Record<string, any>>,
407
450
  ): Promise<RuntimeEpochPluginResult> {
451
+ const updateStartedAt = performance.now();
452
+ const projectionStartedAt = performance.now();
408
453
  const visual = this.projector.project(input.frame);
454
+ const projectionMs = elapsedMs(projectionStartedAt);
455
+ const historyStartedAt = performance.now();
409
456
  const analysisInput = visual && this.shouldAnalyze(input.frame)
410
457
  ? this.analysisInputFromHistory(input.frame, visual, context)
411
458
  : null;
459
+ const historyPrepareMs = elapsedMs(historyStartedAt);
412
460
  const prepared = await this.prepareFrame(input.frame, visual, context.signal, analysisInput);
413
461
  const proposal: PerceptionComputationProposal = {
414
462
  schema: PERCEPTION_COMPUTATION_SCHEMA,
415
463
  visual: prepared.visual,
416
464
  analyses: prepared.analyses,
465
+ timing: {
466
+ projectionMs,
467
+ historyPrepareMs,
468
+ ...prepared.analysisTiming,
469
+ updateTotalMs: elapsedMs(updateStartedAt),
470
+ },
417
471
  };
418
472
  return {
419
473
  outcome: 'processed',
@@ -428,11 +482,13 @@ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<strin
428
482
  context: RuntimeEpochPluginContext<Record<string, any>>,
429
483
  ): Promise<RuntimeEpochPluginResult> {
430
484
  const proposal = this.computationProposal(computation.proposal);
485
+ const commitStartedAt = performance.now();
431
486
  const previousFrameSeq = this.lastFrameSeq;
432
487
  const inspected = await this.inspectPreparedFrame({
433
488
  stored: input.frame,
434
489
  visual: proposal.visual,
435
490
  analyses: proposal.analyses,
491
+ analysisTiming: proposal.timing ?? this.emptyAnalysisTiming(),
436
492
  }, context.signal, context.diagnostic);
437
493
  if (input.frame.frameSeq > previousFrameSeq + 1) {
438
494
  context.diagnostic('perception.catchup_frames_dropped', {
@@ -446,6 +502,14 @@ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<strin
446
502
  });
447
503
  }
448
504
  const checkpoint = this.checkpointValue();
505
+ const commitMs = elapsedMs(commitStartedAt);
506
+ if (proposal.timing) {
507
+ this.recordFrameTiming({
508
+ ...proposal.timing,
509
+ commitMs,
510
+ totalMs: proposal.timing.updateTotalMs + commitMs,
511
+ }, context.diagnostic);
512
+ }
449
513
  return inspected.visual || inspected.proposals.length > 0
450
514
  ? {
451
515
  outcome: 'processed',
@@ -634,6 +698,7 @@ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<strin
634
698
  this.lastFrameSeq + 1,
635
699
  );
636
700
  this.flushModuleTimingWindows(context.diagnostic, true);
701
+ this.flushFrameTimingWindow(context.diagnostic, true);
637
702
  }
638
703
 
639
704
  stop(reason: 'segment_ending' | 'shutdown'): Promise<void> {
@@ -660,6 +725,7 @@ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<strin
660
725
  this.moduleFailureReports.clear();
661
726
  this.moduleTimingWindows.clear();
662
727
  this.moduleTimingWindowStartedAt = performance.now();
728
+ this.frameTimingWindow = this.newFrameTimingWindow();
663
729
  this.resetProjection();
664
730
  }
665
731
 
@@ -850,7 +916,7 @@ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<strin
850
916
  analysisInput: Readonly<PerceptionAnalysisInput> | null = null,
851
917
  ): Promise<PreparedPerceptionFrame> {
852
918
  if (!visual || !this.shouldAnalyze(stored)) {
853
- return { stored, visual, analyses: [] };
919
+ return { stored, visual, analyses: [], analysisTiming: this.emptyAnalysisTiming() };
854
920
  }
855
921
  const preparedVisual = analysisInput?.frame ?? visual;
856
922
  const analyzerInput = analysisInput ?? this.localAnalysisInput(stored, visual);
@@ -858,7 +924,14 @@ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<strin
858
924
  module.runner.execution === 'parallel_analysis'
859
925
  && this.shouldRunParallelModuleForFrame(module, stored.frameSeq)
860
926
  ));
861
- if (parallelModules.length === 0) return { stored, visual: preparedVisual, analyses: [] };
927
+ if (parallelModules.length === 0) {
928
+ return {
929
+ stored,
930
+ visual: preparedVisual,
931
+ analyses: [],
932
+ analysisTiming: this.emptyAnalysisTiming(),
933
+ };
934
+ }
862
935
  const analysisPool = this.analysisPool;
863
936
  if (!analysisPool) throw new Error('perception_analysis_pool_not_started');
864
937
  // Capture generations and module-specific history before submitting one
@@ -891,7 +964,19 @@ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<strin
891
964
  durationMs: result.durationMs,
892
965
  failure: result.failure,
893
966
  });
894
- return { stored, visual: preparedVisual, analyses };
967
+ const moduleDurations = batch.results.map((result) => result.durationMs);
968
+ return {
969
+ stored,
970
+ visual: preparedVisual,
971
+ analyses,
972
+ analysisTiming: {
973
+ workerQueueMs: batch.queueDurationMs,
974
+ workerRoundtripMs: Math.max(0, batch.durationMs - batch.queueDurationMs),
975
+ moduleCpuSumMs: moduleDurations.reduce((sum, duration) => sum + duration, 0),
976
+ moduleCpuMaxMs: Math.max(0, ...moduleDurations),
977
+ workerCount: batch.workerCount,
978
+ },
979
+ };
895
980
  } catch (error) {
896
981
  const failure = perceptionFailureDetails(error);
897
982
  const durationMs = elapsedMs(startedAt);
@@ -905,10 +990,27 @@ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<strin
905
990
  durationMs,
906
991
  failure,
907
992
  })),
993
+ analysisTiming: {
994
+ workerQueueMs: 0,
995
+ workerRoundtripMs: durationMs,
996
+ moduleCpuSumMs: 0,
997
+ moduleCpuMaxMs: 0,
998
+ workerCount: analysisPool.snapshot().workerCount,
999
+ },
908
1000
  };
909
1001
  }
910
1002
  }
911
1003
 
1004
+ private emptyAnalysisTiming(): PerceptionAnalysisTiming {
1005
+ return {
1006
+ workerQueueMs: 0,
1007
+ workerRoundtripMs: 0,
1008
+ moduleCpuSumMs: 0,
1009
+ moduleCpuMaxMs: 0,
1010
+ workerCount: this.analysisPool?.snapshot().workerCount ?? 0,
1011
+ };
1012
+ }
1013
+
912
1014
  private analysisInputForModule(
913
1015
  input: Readonly<PerceptionAnalysisInput>,
914
1016
  module: PerceptionModuleSlot,
@@ -947,6 +1049,24 @@ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<strin
947
1049
  currentVisual: PerceptionFrame,
948
1050
  context: RuntimeEpochPluginContext<Record<string, any>>,
949
1051
  ): PerceptionAnalysisInput {
1052
+ this.rememberProjectedFrame(stored, currentVisual);
1053
+ const cached = [...this.projectedFrameCache.values()]
1054
+ .filter((value) => value.stored.frameSeq <= stored.frameSeq)
1055
+ .sort((left, right) => left.stored.frameSeq - right.stored.frameSeq)
1056
+ .slice(-(PERCEPTION_ANALYSIS_WINDOW_FRAMES + 1));
1057
+ // The first frame after process recovery deliberately reads durable history
1058
+ // once. Normal overlapping epochs reuse projections already built by the
1059
+ // plugin and avoid re-querying/re-projecting the same ten frames per tick.
1060
+ const cacheIsContinuous = cached.every((value, index) => (
1061
+ index === 0 || value.stored.frameSeq === cached[index - 1]!.stored.frameSeq + 1
1062
+ ));
1063
+ if (
1064
+ cached.length > 1
1065
+ && cacheIsContinuous
1066
+ && cached.at(-1)?.stored.frameSeq === stored.frameSeq
1067
+ ) {
1068
+ return this.enrichAnalysisInput(cached);
1069
+ }
950
1070
  const projected = new Map<number, {
951
1071
  stored: StoredStateFrame<Record<string, any>>;
952
1072
  visual: PerceptionFrame;
@@ -966,7 +1086,10 @@ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<strin
966
1086
  const visual = candidate.frameSeq === stored.frameSeq
967
1087
  ? currentVisual
968
1088
  : this.projector.project(candidate);
969
- if (visual) projected.set(candidate.frameSeq, { stored: candidate, visual });
1089
+ if (visual) {
1090
+ projected.set(candidate.frameSeq, { stored: candidate, visual });
1091
+ this.rememberProjectedFrame(candidate, visual);
1092
+ }
970
1093
  if (projected.size >= PERCEPTION_ANALYSIS_WINDOW_FRAMES + 1) break;
971
1094
  }
972
1095
  beforeFrameSeq = page.frames.at(-1)!.frameSeq;
@@ -975,8 +1098,11 @@ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<strin
975
1098
  if (!projected.has(stored.frameSeq)) {
976
1099
  projected.set(stored.frameSeq, { stored, visual: currentVisual });
977
1100
  }
978
- const values = [...projected.values()]
979
- .sort((left, right) => left.stored.frameSeq - right.stored.frameSeq);
1101
+ const values = [...projected.values()].sort((left, right) => left.stored.frameSeq - right.stored.frameSeq);
1102
+ return this.enrichAnalysisInput(values);
1103
+ }
1104
+
1105
+ private enrichAnalysisInput(values: readonly CachedProjectedFrame[]): PerceptionAnalysisInput {
980
1106
  const enriched: PerceptionFrame[] = [];
981
1107
  values.forEach((value, index) => {
982
1108
  const previous = index > 0 ? values[index - 1] : undefined;
@@ -1000,6 +1126,18 @@ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<strin
1000
1126
  };
1001
1127
  }
1002
1128
 
1129
+ private rememberProjectedFrame(
1130
+ stored: Pick<StoredStateFrame<Record<string, any>>, 'frameSeq' | 'connectionId'>,
1131
+ visual: PerceptionFrame,
1132
+ ): void {
1133
+ this.projectedFrameCache.set(stored.frameSeq, { stored, visual });
1134
+ const maximum = PERCEPTION_ANALYSIS_WINDOW_FRAMES + this.maxInFlight + 2;
1135
+ while (this.projectedFrameCache.size > maximum) {
1136
+ const oldest = Math.min(...this.projectedFrameCache.keys());
1137
+ this.projectedFrameCache.delete(oldest);
1138
+ }
1139
+ }
1140
+
1003
1141
  private localAnalysisInput(
1004
1142
  stored: StoredStateFrame<Record<string, any>>,
1005
1143
  visual: PerceptionFrame,
@@ -1214,6 +1352,74 @@ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<strin
1214
1352
  }
1215
1353
  }
1216
1354
 
1355
+ private newFrameTimingWindow(): PerceptionFrameTimingWindow {
1356
+ return {
1357
+ startedAtMs: performance.now(),
1358
+ projectionMs: [],
1359
+ historyPrepareMs: [],
1360
+ workerQueueMs: [],
1361
+ workerRoundtripMs: [],
1362
+ moduleCpuSumMs: [],
1363
+ moduleCpuMaxMs: [],
1364
+ updateTotalMs: [],
1365
+ commitMs: [],
1366
+ totalMs: [],
1367
+ workerCountMax: 0,
1368
+ };
1369
+ }
1370
+
1371
+ private recordFrameTiming(
1372
+ sample: PerceptionFrameTimingSample,
1373
+ diagnostic: PerceptionDiagnostic | undefined,
1374
+ ): void {
1375
+ const window = this.frameTimingWindow;
1376
+ window.projectionMs.push(sample.projectionMs);
1377
+ window.historyPrepareMs.push(sample.historyPrepareMs);
1378
+ window.workerQueueMs.push(sample.workerQueueMs);
1379
+ window.workerRoundtripMs.push(sample.workerRoundtripMs);
1380
+ window.moduleCpuSumMs.push(sample.moduleCpuSumMs);
1381
+ window.moduleCpuMaxMs.push(sample.moduleCpuMaxMs);
1382
+ window.updateTotalMs.push(sample.updateTotalMs);
1383
+ window.commitMs.push(sample.commitMs);
1384
+ window.totalMs.push(sample.totalMs);
1385
+ window.workerCountMax = Math.max(window.workerCountMax, sample.workerCount);
1386
+ this.flushFrameTimingWindow(diagnostic);
1387
+ }
1388
+
1389
+ private flushFrameTimingWindow(
1390
+ diagnostic: PerceptionDiagnostic | undefined,
1391
+ force = false,
1392
+ ): void {
1393
+ const window = this.frameTimingWindow;
1394
+ if (!diagnostic || window.totalMs.length === 0) return;
1395
+ const windowMs = Math.max(0, performance.now() - window.startedAtMs);
1396
+ if (!force && windowMs < PERCEPTION_MODULE_TIMING_WINDOW_MS) return;
1397
+ diagnostic('perception.frame.timing_window', {
1398
+ window_ms: Math.round(windowMs),
1399
+ count: window.totalMs.length,
1400
+ projection_avg_ms: roundedAverage(window.projectionMs),
1401
+ projection_p95_ms: percentile95(window.projectionMs),
1402
+ history_prepare_avg_ms: roundedAverage(window.historyPrepareMs),
1403
+ history_prepare_p95_ms: percentile95(window.historyPrepareMs),
1404
+ worker_queue_avg_ms: roundedAverage(window.workerQueueMs),
1405
+ worker_queue_p95_ms: percentile95(window.workerQueueMs),
1406
+ worker_roundtrip_avg_ms: roundedAverage(window.workerRoundtripMs),
1407
+ worker_roundtrip_p95_ms: percentile95(window.workerRoundtripMs),
1408
+ module_cpu_sum_avg_ms: roundedAverage(window.moduleCpuSumMs),
1409
+ module_cpu_sum_p95_ms: percentile95(window.moduleCpuSumMs),
1410
+ module_cpu_max_p95_ms: percentile95(window.moduleCpuMaxMs),
1411
+ update_total_avg_ms: roundedAverage(window.updateTotalMs),
1412
+ update_total_p95_ms: percentile95(window.updateTotalMs),
1413
+ commit_avg_ms: roundedAverage(window.commitMs),
1414
+ commit_p95_ms: percentile95(window.commitMs),
1415
+ total_avg_ms: roundedAverage(window.totalMs),
1416
+ total_p95_ms: percentile95(window.totalMs),
1417
+ total_max_ms: Math.max(...window.totalMs),
1418
+ worker_count_max: window.workerCountMax,
1419
+ });
1420
+ this.frameTimingWindow = this.newFrameTimingWindow();
1421
+ }
1422
+
1217
1423
  private flushModuleTimingWindows(
1218
1424
  diagnostic: PerceptionDiagnostic | undefined,
1219
1425
  force = false,
@@ -1549,6 +1755,7 @@ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<strin
1549
1755
  this.lastVisualFrame = null;
1550
1756
  this.lastConnectionId = null;
1551
1757
  this.analysisWindow.length = 0;
1758
+ this.projectedFrameCache.clear();
1552
1759
  this.replayFromFrameSeq = null;
1553
1760
  }
1554
1761
 
@@ -17,13 +17,19 @@ export type ClawclawGameTransportStopReason =
17
17
  export interface ClawclawGameTransportOutcome {
18
18
  reason: ClawclawGameTransportStopReason;
19
19
  error?: unknown;
20
+ queueState?: Record<string, any>;
21
+ }
22
+
23
+ export interface ClawclawGameServerDiscoveryResult {
24
+ readonly routeChanged: boolean;
25
+ readonly queue?: Record<string, any>;
20
26
  }
21
27
 
22
28
  export interface ClawclawGameTransportClient {
23
29
  readonly wsConnected: boolean;
24
30
  readonly wsConnectionActive: boolean;
25
31
  readonly wsConnectionId: string | null;
26
- discoverGameServer(): Promise<boolean>;
32
+ discoverGameServer(): Promise<ClawclawGameServerDiscoveryResult>;
27
33
  connectWs(): Promise<boolean>;
28
34
  reconnectWsToGameServer(): Promise<void>;
29
35
  disconnectWs(options?: { preserveGameSyncResumeState?: boolean }): void;
@@ -46,6 +52,9 @@ export interface ClawclawGameTransportOptions {
46
52
  info: WsCloseInfo,
47
53
  ): Promise<ClawclawGameTransportStopReason | void> | ClawclawGameTransportStopReason | void;
48
54
  onConnectAttemptFailed(error: unknown): void;
55
+ onParticipationProbe?(
56
+ queue: Record<string, any>,
57
+ ): Promise<ClawclawGameTransportStopReason | void> | ClawclawGameTransportStopReason | void;
49
58
  onProtocolError(info: WsProtocolErrorInfo): void;
50
59
  onRecoveryStarted?(info: WsRecoveryStartedInfo): Promise<void> | void;
51
60
  routePollMs?: number;
@@ -194,8 +203,9 @@ export class ClawclawGameTransport implements ClawclawGameTransportPort {
194
203
  ) {
195
204
  this.connectAttemptActive = true;
196
205
  try {
197
- const routeChanged = await client.discoverGameServer();
198
- if (!routeChanged) await client.reconnectWsToGameServer();
206
+ const discovery = await client.discoverGameServer();
207
+ if (await this.applyParticipationProbe(discovery)) return;
208
+ if (!discovery.routeChanged) await client.reconnectWsToGameServer();
199
209
  } catch (error) {
200
210
  this.options.onConnectAttemptFailed(error);
201
211
  } finally {
@@ -213,7 +223,8 @@ export class ClawclawGameTransport implements ClawclawGameTransportPort {
213
223
  try {
214
224
  // This call is required even while WsClient is auto-reconnecting: the
215
225
  // authoritative GameServer route may have changed underneath it.
216
- await client.discoverGameServer();
226
+ const discovery = await client.discoverGameServer();
227
+ if (await this.applyParticipationProbe(discovery)) return;
217
228
  if (!client.wsConnectionActive) await client.connectWs();
218
229
  if (!client.wsConnectionActive) {
219
230
  this.options.onConnectAttemptFailed(new Error('Game WebSocket connection is unavailable.'));
@@ -225,6 +236,20 @@ export class ClawclawGameTransport implements ClawclawGameTransportPort {
225
236
  }
226
237
  }
227
238
 
239
+ private async applyParticipationProbe(
240
+ discovery: ClawclawGameServerDiscoveryResult,
241
+ ): Promise<boolean> {
242
+ if (!discovery.queue || !this.options.onParticipationProbe) return false;
243
+ // Preserve the per-attempt disconnect Event before a Lobby probe can end
244
+ // this transport generation.
245
+ await this.flush();
246
+ if (this.stopped) return true;
247
+ const reason = await this.options.onParticipationProbe(structuredClone(discovery.queue));
248
+ if (!reason) return false;
249
+ this.finish({ reason, queueState: structuredClone(discovery.queue) });
250
+ return true;
251
+ }
252
+
228
253
  private enqueue(operation: () => void | Promise<void>): void {
229
254
  if (this.stopped) return;
230
255
  this.operationTail = this.operationTail.then(async () => {
@@ -141,6 +141,9 @@ type GameAttachGate =
141
141
 
142
142
  type ReconciledTransport = 'game_ws' | 'room_ws';
143
143
 
144
+ const GAME_TERMINAL_SETTLEMENT_ATTEMPTS = 2;
145
+ const GAME_TERMINAL_SETTLEMENT_RETRY_MS = 250;
146
+
144
147
  interface SourceCoalescingBoundaryState {
145
148
  connected: boolean;
146
149
  ended: boolean;
@@ -1128,6 +1131,10 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
1128
1131
  this.requireRuntime().connectionLiveness(CLAWCLAW_GAME_WS_SOURCE.sourceId, connectionId, atMs);
1129
1132
  },
1130
1133
  onClose: (connectionId, info) => this.handleGameClose(connectionId, info),
1134
+ onParticipationProbe: (participation) => this.handleGameParticipationProbe(
1135
+ gameId,
1136
+ participation,
1137
+ ),
1131
1138
  onConnectAttemptFailed: (error) => {
1132
1139
  this.diagnostic('runtime.source.connect_failed', {
1133
1140
  transport: 'game_ws',
@@ -1180,10 +1187,156 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
1180
1187
  },
1181
1188
  };
1182
1189
  }
1190
+ if (outcome.reason === 'reconcile' && outcome.queueState) {
1191
+ const reconciledQueue = normalizeClawclawQueueState(outcome.queueState);
1192
+ await this.acceptQueueState(reconciledQueue);
1193
+ const status = queueStatus(reconciledQueue);
1194
+ if (status === 'not_in_queue') {
1195
+ return {
1196
+ kind: 'complete',
1197
+ completion: { reason: this.leaveRequested ? 'left' : 'not_participating' },
1198
+ };
1199
+ }
1200
+ return { kind: 'continue', queue: reconciledQueue };
1201
+ }
1183
1202
  await this.reconcileBackoff('game_ws', outcome.reason);
1184
1203
  return { kind: 'continue' };
1185
1204
  }
1186
1205
 
1206
+ private async handleGameParticipationProbe(
1207
+ gameId: string | undefined,
1208
+ value: Record<string, any>,
1209
+ ): Promise<ClawclawGameTransportStopReason | void> {
1210
+ if (!gameId) return;
1211
+ const queue = normalizeClawclawQueueState(value);
1212
+ const status = queueStatus(queue);
1213
+ if (status !== 'not_in_queue' && status !== 'in_room') return;
1214
+ if (this.leaveRequested) return 'reconcile';
1215
+
1216
+ let settlement: Record<string, any> | undefined;
1217
+ let settlementGameId: string | undefined;
1218
+ let settlementErrorCode: string | undefined;
1219
+ for (let attempt = 1; attempt <= GAME_TERMINAL_SETTLEMENT_ATTEMPTS; attempt += 1) {
1220
+ try {
1221
+ const candidate = unwrapData(await this.client.getSettlement());
1222
+ if (candidate && typeof candidate === 'object' && !Array.isArray(candidate)) {
1223
+ settlementGameId = typeof candidate.game_id === 'string' ? candidate.game_id : undefined;
1224
+ if (settlementGameId === gameId) {
1225
+ settlement = structuredClone(candidate);
1226
+ break;
1227
+ }
1228
+ settlementErrorCode = settlementGameId
1229
+ ? 'SETTLEMENT_GAME_ID_MISMATCH'
1230
+ : 'SETTLEMENT_GAME_ID_MISSING';
1231
+ } else {
1232
+ settlementErrorCode = 'SETTLEMENT_INVALID';
1233
+ }
1234
+ } catch (error) {
1235
+ settlementErrorCode = apiErrorCode(error) ?? 'SETTLEMENT_UNAVAILABLE';
1236
+ }
1237
+ if (attempt < GAME_TERMINAL_SETTLEMENT_ATTEMPTS) {
1238
+ await this.sleep(GAME_TERMINAL_SETTLEMENT_RETRY_MS, this.abortController.signal);
1239
+ }
1240
+ }
1241
+
1242
+ if (settlement) {
1243
+ await this.submitRecoveredGameOver(gameId, queue, settlement);
1244
+ return 'game_over';
1245
+ }
1246
+ await this.submitMissingGameTerminal(
1247
+ gameId,
1248
+ queue,
1249
+ settlementErrorCode ?? 'SETTLEMENT_UNAVAILABLE',
1250
+ settlementGameId,
1251
+ );
1252
+ return 'reconcile';
1253
+ }
1254
+
1255
+ private async submitRecoveredGameOver(
1256
+ gameId: string,
1257
+ queue: Record<string, any>,
1258
+ settlement: Record<string, any>,
1259
+ ): Promise<void> {
1260
+ const receivedAt = new Date().toISOString();
1261
+ const sourceSeq = `settlement:${gameId}`;
1262
+ const winningFaction = typeof settlement.winning_faction === 'string'
1263
+ ? settlement.winning_faction
1264
+ : undefined;
1265
+ const winReason = typeof settlement.win_reason === 'string'
1266
+ ? settlement.win_reason
1267
+ : undefined;
1268
+ this.currentStage = 'ended';
1269
+ this.currentTransport = 'lobby_http';
1270
+ this.currentConnection = 'connected';
1271
+ this.currentQueue = structuredClone(queue);
1272
+ await this.submit({
1273
+ scope: this.requireRuntime().currentSegment().scope,
1274
+ sourceId: CLAWCLAW_LOBBY_HTTP_SOURCE.sourceId,
1275
+ connectionId: 'lobby-http',
1276
+ sourceKey: `game-terminal-recovered:${gameId}`,
1277
+ sourceSeq,
1278
+ state: this.runtimeState('ending'),
1279
+ events: [{
1280
+ type: 'game_over_recovered',
1281
+ producer: 'local_synth',
1282
+ payload: {
1283
+ game_id: gameId,
1284
+ recovered: true,
1285
+ recovery_source: 'settlement_http',
1286
+ ...(winningFaction ? { winner: winningFaction, winning_faction: winningFaction } : {}),
1287
+ ...(winReason ? { reason: winReason, win_reason: winReason } : {}),
1288
+ ...(settlement.your_result && typeof settlement.your_result === 'object'
1289
+ ? { your_result: structuredClone(settlement.your_result) }
1290
+ : {}),
1291
+ ...(this.participationMode ? { game_mode: this.participationMode } : {}),
1292
+ },
1293
+ sourceEventId: `game-terminal-recovered:${gameId}`,
1294
+ sourceSeq,
1295
+ receivedAt,
1296
+ }],
1297
+ completeness: 'complete',
1298
+ receivedAt,
1299
+ });
1300
+ }
1301
+
1302
+ private async submitMissingGameTerminal(
1303
+ gameId: string,
1304
+ queue: Record<string, any>,
1305
+ settlementErrorCode: string,
1306
+ settlementGameId?: string,
1307
+ ): Promise<void> {
1308
+ const receivedAt = new Date().toISOString();
1309
+ const sourceSeq = `terminal-missing:${gameId}`;
1310
+ this.currentStage = 'ended';
1311
+ this.currentTransport = 'lobby_http';
1312
+ this.currentConnection = 'connected';
1313
+ this.currentQueue = structuredClone(queue);
1314
+ await this.submit({
1315
+ scope: this.requireRuntime().currentSegment().scope,
1316
+ sourceId: CLAWCLAW_LOBBY_HTTP_SOURCE.sourceId,
1317
+ connectionId: 'lobby-http',
1318
+ sourceKey: `game-terminal-missing:${gameId}`,
1319
+ sourceSeq,
1320
+ state: this.runtimeState('ending'),
1321
+ events: [{
1322
+ type: 'game_terminal_missing',
1323
+ producer: 'local_synth',
1324
+ payload: {
1325
+ game_id: gameId,
1326
+ queue_status: queueStatus(queue),
1327
+ settlement_error_code: settlementErrorCode,
1328
+ ...(settlementGameId ? { settlement_game_id: settlementGameId } : {}),
1329
+ ...(this.participationMode ? { game_mode: this.participationMode } : {}),
1330
+ },
1331
+ sourceEventId: `game-terminal-missing:${gameId}`,
1332
+ sourceSeq,
1333
+ receivedAt,
1334
+ }],
1335
+ completeness: 'complete',
1336
+ receivedAt,
1337
+ });
1338
+ }
1339
+
1187
1340
  private async waitForGameAttach(
1188
1341
  transport: ClawclawGameTransportPort,
1189
1342
  ): Promise<ClawclawGameTransportOutcome | undefined> {
@@ -17,6 +17,7 @@ import type {
17
17
  export interface ClawclawSourceClient extends ClawclawGameTransportClient {
18
18
  readonly lobbyAgentWsUrl: string;
19
19
  getQueueStatus(gameType?: string): Promise<any>;
20
+ getSettlement(): Promise<any>;
20
21
  joinQueue(options?: {
21
22
  gameType?: string;
22
23
  mode?: QueueMode;
@@ -12,6 +12,7 @@ import {
12
12
  } from '../clawclaw-event-catalog.js';
13
13
  import type { ClawclawPosition } from '../clawclaw-position.js';
14
14
  import { Runtime, type RuntimeOptions } from '../framework/runtime.js';
15
+ import { createMemoryFirstPersistence } from '../framework/persistence/memory-first-persistence.js';
15
16
  import {
16
17
  AtomicJsonAgentStateSnapshotStore,
17
18
  DurableAgentStateSnapshotObserver,
@@ -108,6 +109,25 @@ export function createClawclawRuntime(
108
109
  : configuredSnapshot ?? new AtomicJsonAgentStateSnapshotStore<Record<string, any>>(
109
110
  durableAgentStateSnapshotPath(getProfileRuntimeStateDir(profile)),
110
111
  );
112
+ const useDefaultPersistence = !runtimeOptions.eventRepository
113
+ && !runtimeOptions.stateHistoryRepository
114
+ && !runtimeOptions.inputJournal;
115
+ const persistence = useDefaultPersistence
116
+ ? createMemoryFirstPersistence<ClawclawPosition>({
117
+ eventLedgerPath: getProfileEventLedgerPath(profile),
118
+ stateHistoryPath: getProfileStateHistoryPath(profile),
119
+ inputJournalPath: getProfileInputJournalPath(profile),
120
+ onDegraded: (error, health) => runtimeOptions.observability?.error(
121
+ 'runtime.persistence.async_degraded',
122
+ error,
123
+ {
124
+ pending_operations: health.pendingOperations,
125
+ dropped_operations: health.droppedOperations,
126
+ },
127
+ { component: 'runtime.persistence' },
128
+ ),
129
+ })
130
+ : null;
111
131
 
112
132
  return new Runtime<ClawclawPosition>({
113
133
  ...runtimeOptions,
@@ -121,9 +141,17 @@ export function createClawclawRuntime(
121
141
  // Mailbox ACK adapters own independent durable lanes. Disabled and
122
142
  // acknowledgement:none adapters must not leave an unowned delivery row.
123
143
  initialEventConsumerIds: [],
124
- eventLedgerPath: getProfileEventLedgerPath(profile),
125
- stateHistoryPath: getProfileStateHistoryPath(profile),
126
- inputJournalPath: getProfileInputJournalPath(profile),
144
+ ...(persistence
145
+ ? {
146
+ eventRepository: persistence.eventRepository,
147
+ stateHistoryRepository: persistence.stateHistoryRepository,
148
+ inputJournal: persistence.inputJournal,
149
+ }
150
+ : {
151
+ eventLedgerPath: getProfileEventLedgerPath(profile),
152
+ stateHistoryPath: getProfileStateHistoryPath(profile),
153
+ inputJournalPath: getProfileInputJournalPath(profile),
154
+ }),
127
155
  currentStateFromRuntimeState: projectClawclawCurrentState,
128
156
  stateFreshnessPolicy,
129
157
  stateFreshnessPolicyResolver,
@@ -153,6 +153,8 @@ export const CLAWCLAW_LOCAL_AGENT_EVENT_TYPES = [
153
153
  'poll_error',
154
154
  'error',
155
155
  'game_start_failed',
156
+ 'game_over_recovered',
157
+ 'game_terminal_missing',
156
158
  'game_stream_disconnected',
157
159
  'game_stream_reconnected',
158
160
  'stop_requested',