@myclaw163/clawclaw-cli 0.8.3 → 0.8.5

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 (264) hide show
  1. package/README.md +4 -3
  2. package/docs/configuration.md +44 -26
  3. package/docs/custom-modules/README.md +7 -10
  4. package/docs/custom-modules/api-reference.md +3 -7
  5. package/docs/custom-modules/behavior.md +6 -4
  6. package/docs/custom-modules/perception.md +1 -1
  7. package/docs/custom-modules/trigger.md +1 -1
  8. package/docs/runtime/README.md +4 -4
  9. package/docs/runtime/official-perception-modules.md +2 -2
  10. package/docs/runtime/owner-lifecycle-and-observability.md +1 -1
  11. package/package.json +9 -2
  12. package/scripts/build-official-hub-behaviors.mjs +136 -0
  13. package/scripts/build-official-hub-behaviors.test.mjs +178 -0
  14. package/scripts/enable_ccl_permissions.cjs +4 -2
  15. package/scripts/enable_ccl_permissions.test.mjs +8 -4
  16. package/scripts/postinstall.mjs +1 -4
  17. package/scripts/sync-bundled-skill.mjs +12 -159
  18. package/scripts/sync-bundled-skill.test.mjs +9 -74
  19. package/skills/clawclaw/SKILL.md +18 -13
  20. package/skills/clawclaw/references/BEHAVIORS.md +4 -4
  21. package/skills/clawclaw/references/COMMANDS.md +33 -18
  22. package/skills/clawclaw/references/GAME-MECHANICS.md +16 -18
  23. package/skills/clawclaw/references/HUB.md +25 -38
  24. package/skills/clawclaw/references/STREAM.md +9 -11
  25. package/src/behaviors/official-finite/do-task.ts +70 -0
  26. package/src/behaviors/official-finite/index.ts +0 -3
  27. package/src/commands/account.ts +58 -14
  28. package/src/commands/behavior.ts +116 -38
  29. package/src/commands/hub.ts +110 -153
  30. package/src/commands/load.ts +138 -33
  31. package/src/commands/perception.ts +55 -24
  32. package/src/commands/persona.ts +66 -20
  33. package/src/commands/skill.ts +12 -48
  34. package/src/commands/trigger.ts +68 -40
  35. package/src/hub-official-behaviors/kill-lone.ts +138 -0
  36. package/src/hub-official-behaviors/patrol.ts +30 -0
  37. package/src/hub-official-behaviors/shared.ts +125 -0
  38. package/src/hub-official-behaviors/task-only.ts +158 -0
  39. package/src/lib/account-guidance.ts +54 -9
  40. package/src/lib/agent-workspace-client.ts +135 -0
  41. package/src/lib/agent-workspace-runtime.ts +154 -0
  42. package/src/lib/agent-workspace-skills.ts +177 -0
  43. package/src/lib/agent-workspace-sync.ts +852 -0
  44. package/src/lib/gameplay-config.ts +29 -15
  45. package/src/lib/hub-client.ts +252 -34
  46. package/src/lib/hub-reminder.ts +22 -7
  47. package/src/lib/init-command.ts +0 -6
  48. package/src/lib/load-context.ts +12 -6
  49. package/src/lib/persona.ts +141 -69
  50. package/src/lib/server-status.ts +78 -0
  51. package/src/lib/skill-host.ts +160 -0
  52. package/src/lib/user-data.ts +197 -4
  53. package/src/pipeline/event-format.ts +20 -4
  54. package/src/pipeline/event-hints.ts +20 -6
  55. package/src/pipeline/game-sync-event-normalization.ts +9 -0
  56. package/src/pipeline/role-display.ts +22 -0
  57. package/src/runtime/clawclaw/agent-ability-state.ts +1 -21
  58. package/src/runtime/clawclaw/agent-event-policy.ts +1 -0
  59. package/src/runtime/clawclaw/owner.ts +63 -19
  60. package/src/runtime/clawclaw/plugins/action/action-plugin.ts +8 -1
  61. package/src/runtime/clawclaw/plugins/action/automated-action-normalization.ts +0 -1
  62. package/src/runtime/clawclaw/plugins/behavior/activation-manager.ts +8 -2
  63. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +2 -2
  64. package/src/runtime/clawclaw/plugins/behavior/official-goal-behavior.ts +0 -9
  65. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +4 -1
  66. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +11 -5
  67. package/src/runtime/clawclaw/plugins/perception/replay.ts +0 -2
  68. package/src/runtime/clawclaw-event-catalog.ts +2 -0
  69. package/src/runtime/framework/action-diagnostics.ts +1 -0
  70. package/src/runtime/framework/modules/runtime-module-loader.ts +0 -1
  71. package/src/sdk/action.ts +8 -6
  72. package/src/sdk/behavior-plugin/index.ts +1 -2
  73. package/src/sdk/behavior-toolkit/model.ts +2 -0
  74. package/src/sdk/module-input/index.ts +0 -2
  75. package/src/strategies/goals/crab-sabotage-top.ts +5 -61
  76. package/src/strategies/types.ts +0 -6
  77. package/personas//345/217/243/346/230/257/345/277/203/351/235/236.md +0 -50
  78. package/personas//345/277/240/345/277/203/350/200/201/344/273/206.md +0 -51
  79. package/personas//346/227/240/344/272/272/350/256/276.md +0 -1
  80. package/personas//350/264/253/345/230/264/346/215/237/345/217/213.md +0 -48
  81. package/personas//350/275/257/350/220/214/350/205/271/351/273/221.md +0 -51
  82. package/src/behaviors/official-finite/index.test.ts +0 -202
  83. package/src/behaviors/official-finite/trigger-alarm.ts +0 -53
  84. package/src/channel/claude-channel-server.test.ts +0 -202
  85. package/src/commands/account.test.ts +0 -570
  86. package/src/commands/behavior.test.ts +0 -158
  87. package/src/commands/communication.test.ts +0 -282
  88. package/src/commands/competition.test.ts +0 -116
  89. package/src/commands/data.test.ts +0 -89
  90. package/src/commands/events-canonical-state.test.ts +0 -406
  91. package/src/commands/events.test.ts +0 -58
  92. package/src/commands/game/index.test.ts +0 -1251
  93. package/src/commands/game-map.test.ts +0 -69
  94. package/src/commands/hub.test.ts +0 -124
  95. package/src/commands/load.test.ts +0 -440
  96. package/src/commands/perception.test.ts +0 -75
  97. package/src/commands/setup/hermes.test.ts +0 -96
  98. package/src/commands/setup/openclaw.test.ts +0 -124
  99. package/src/commands/trigger.test.ts +0 -140
  100. package/src/commands/upgrade.test.ts +0 -82
  101. package/src/lib/account-guidance.test.ts +0 -36
  102. package/src/lib/auth.test.ts +0 -151
  103. package/src/lib/behavior-export.test.ts +0 -282
  104. package/src/lib/behavior-export.ts +0 -514
  105. package/src/lib/clawclaw-skill-spectate-guidance.test.ts +0 -21
  106. package/src/lib/custom-tts.test.ts +0 -387
  107. package/src/lib/diagnostics-config.test.ts +0 -59
  108. package/src/lib/game-client-tts.test.ts +0 -151
  109. package/src/lib/game-client.test.ts +0 -250
  110. package/src/lib/gameplay-config.test.ts +0 -301
  111. package/src/lib/host-config-patcher.test.ts +0 -130
  112. package/src/lib/http-transport.test.ts +0 -124
  113. package/src/lib/hub-client.test.ts +0 -57
  114. package/src/lib/hub-install.test.ts +0 -135
  115. package/src/lib/hub-install.ts +0 -185
  116. package/src/lib/hub-unzip.test.ts +0 -69
  117. package/src/lib/init-command.test.ts +0 -103
  118. package/src/lib/load-context.test.ts +0 -62
  119. package/src/lib/match-state.test.ts +0 -134
  120. package/src/lib/official-resource-sync.test.ts +0 -199
  121. package/src/lib/official-resource-sync.ts +0 -221
  122. package/src/lib/perception-config.test.ts +0 -143
  123. package/src/lib/perception-export.test.ts +0 -145
  124. package/src/lib/perception-export.ts +0 -178
  125. package/src/lib/persona.test.ts +0 -84
  126. package/src/lib/room.test.ts +0 -88
  127. package/src/lib/server-registry.test.ts +0 -64
  128. package/src/lib/service-status.test.ts +0 -81
  129. package/src/lib/skill-version.test.ts +0 -48
  130. package/src/lib/trigger-config.test.ts +0 -102
  131. package/src/lib/trigger-export.test.ts +0 -80
  132. package/src/lib/trigger-export.ts +0 -210
  133. package/src/lib/user-data.test.ts +0 -121
  134. package/src/lib/workspace-argv.test.ts +0 -49
  135. package/src/pipeline/canonical-event-presentation.test.ts +0 -255
  136. package/src/pipeline/event-format.test.ts +0 -828
  137. package/src/pipeline/event-hints.test.ts +0 -316
  138. package/src/pipeline/game-sync-event-normalization.test.ts +0 -371
  139. package/src/pipeline/player-projection.test.ts +0 -247
  140. package/src/runtime/auto-upgrade.test.ts +0 -66
  141. package/src/runtime/canonical-event-emitter.test.ts +0 -70
  142. package/src/runtime/canonical-monitor.test.ts +0 -577
  143. package/src/runtime/clawclaw/agent-event-policy.test.ts +0 -58
  144. package/src/runtime/clawclaw/behavior-decision.test.ts +0 -43
  145. package/src/runtime/clawclaw/behavior-input-fields.test.ts +0 -175
  146. package/src/runtime/clawclaw/behavior-input.test.ts +0 -173
  147. package/src/runtime/clawclaw/behavior-observation-memory.test.ts +0 -59
  148. package/src/runtime/clawclaw/behavior-read-api.test.ts +0 -123
  149. package/src/runtime/clawclaw/notifications.test.ts +0 -47
  150. package/src/runtime/clawclaw/owner-lock.test.ts +0 -221
  151. package/src/runtime/clawclaw/owner.test.ts +0 -203
  152. package/src/runtime/clawclaw/plugins/action/action-plugin.test.ts +0 -304
  153. package/src/runtime/clawclaw/plugins/assembly.test.ts +0 -200
  154. package/src/runtime/clawclaw/plugins/behavior/activation-manager.test.ts +0 -180
  155. package/src/runtime/clawclaw/plugins/behavior/behavior-action.test.ts +0 -40
  156. package/src/runtime/clawclaw/plugins/behavior/behavior-catalog.test.ts +0 -156
  157. package/src/runtime/clawclaw/plugins/behavior/behavior-module-loader.test.ts +0 -182
  158. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.test.ts +0 -1094
  159. package/src/runtime/clawclaw/plugins/behavior/behavior-source.test.ts +0 -174
  160. package/src/runtime/clawclaw/plugins/behavior/control-driver.test.ts +0 -195
  161. package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.test.ts +0 -283
  162. package/src/runtime/clawclaw/plugins/behavior-input-source.test.ts +0 -80
  163. package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.test.ts +0 -267
  164. package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.test.ts +0 -226
  165. package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-adapter.test.ts +0 -239
  166. package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.test.ts +0 -407
  167. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-push.integration.test.ts +0 -397
  168. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.test.ts +0 -270
  169. package/src/runtime/clawclaw/plugins/mailbox/mailbox-agent-event-batch.test.ts +0 -166
  170. package/src/runtime/clawclaw/plugins/mailbox/mailbox-event-batch-delivery.test.ts +0 -194
  171. package/src/runtime/clawclaw/plugins/mailbox/mailbox-plugin.test.ts +0 -87
  172. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.test.ts +0 -2012
  173. package/src/runtime/clawclaw/plugins/perception/module-runner.test.ts +0 -214
  174. package/src/runtime/clawclaw/plugins/perception/modules/co-movement-module.ts +0 -347
  175. package/src/runtime/clawclaw/plugins/perception/modules/corpse-visibility-module.test.ts +0 -92
  176. package/src/runtime/clawclaw/plugins/perception/modules/corpse-visibility-module.ts +0 -248
  177. package/src/runtime/clawclaw/plugins/perception/modules/follow-module.ts +0 -389
  178. package/src/runtime/clawclaw/plugins/perception/modules/index.ts +0 -8
  179. package/src/runtime/clawclaw/plugins/perception/modules/motion-module.test.ts +0 -342
  180. package/src/runtime/clawclaw/plugins/perception/modules/motion-module.ts +0 -475
  181. package/src/runtime/clawclaw/plugins/perception/modules/parallel-module-test-helpers.ts +0 -30
  182. package/src/runtime/clawclaw/plugins/perception/modules/relation-stability.test.ts +0 -304
  183. package/src/runtime/clawclaw/plugins/perception/modules/route-module.test.ts +0 -179
  184. package/src/runtime/clawclaw/plugins/perception/modules/route-module.ts +0 -364
  185. package/src/runtime/clawclaw/plugins/perception/modules/spatial-module.test.ts +0 -81
  186. package/src/runtime/clawclaw/plugins/perception/modules/spatial-module.ts +0 -200
  187. package/src/runtime/clawclaw/plugins/perception/modules/stop-module.test.ts +0 -216
  188. package/src/runtime/clawclaw/plugins/perception/modules/stop-module.ts +0 -284
  189. package/src/runtime/clawclaw/plugins/perception/modules/temporal-evidence.test.ts +0 -120
  190. package/src/runtime/clawclaw/plugins/perception/modules/visibility-module.test.ts +0 -105
  191. package/src/runtime/clawclaw/plugins/perception/modules/visibility-module.ts +0 -269
  192. package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-pool.test.ts +0 -865
  193. package/src/runtime/clawclaw/plugins/perception/perception-plugin.test.ts +0 -1878
  194. package/src/runtime/clawclaw/plugins/perception/perception-source.test.ts +0 -278
  195. package/src/runtime/clawclaw/plugins/perception/replay.test.ts +0 -77
  196. package/src/runtime/clawclaw/plugins/runtime-plugins.test.ts +0 -854
  197. package/src/runtime/clawclaw/plugins/source/game-transport.test.ts +0 -287
  198. package/src/runtime/clawclaw/plugins/source/player-change-tracker.test.ts +0 -321
  199. package/src/runtime/clawclaw/plugins/source/room-transport.test.ts +0 -307
  200. package/src/runtime/clawclaw/plugins/source/source-plugin.test.ts +0 -2646
  201. package/src/runtime/clawclaw/plugins/source/task-change-tracker.test.ts +0 -212
  202. package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.test.ts +0 -548
  203. package/src/runtime/clawclaw/plugins/trigger/trigger-source.test.ts +0 -169
  204. package/src/runtime/clawclaw/runtime-data-export.test.ts +0 -249
  205. package/src/runtime/clawclaw-event-catalog.test.ts +0 -126
  206. package/src/runtime/framework/action-diagnostics.test.ts +0 -81
  207. package/src/runtime/framework/capability-registry.test.ts +0 -423
  208. package/src/runtime/framework/control-coordinator.test.ts +0 -675
  209. package/src/runtime/framework/events/event-delivery-service.test.ts +0 -84
  210. package/src/runtime/framework/events/event-ingress.test.ts +0 -203
  211. package/src/runtime/framework/events/mailbox-event-repositories.test.ts +0 -710
  212. package/src/runtime/framework/events/sqlite-event-repository.test.ts +0 -802
  213. package/src/runtime/framework/mailbox/coalescer.test.ts +0 -55
  214. package/src/runtime/framework/mailbox/identity.test.ts +0 -38
  215. package/src/runtime/framework/mailbox/mailbox-dispatcher.test.ts +0 -513
  216. package/src/runtime/framework/mailbox/notification-projector.test.ts +0 -77
  217. package/src/runtime/framework/modules/runtime-module-loader.test.ts +0 -435
  218. package/src/runtime/framework/participation-manager.test.ts +0 -108
  219. package/src/runtime/framework/plugins/runtime-input-journal.test.ts +0 -179
  220. package/src/runtime/framework/plugins/runtime-plugin-scheduler.test.ts +0 -2040
  221. package/src/runtime/framework/state/durable-agent-state-snapshot.test.ts +0 -144
  222. package/src/runtime/framework/state/history/sqlite-state-history-repository.test.ts +0 -157
  223. package/src/runtime/framework/state/history/state-history.test.ts +0 -251
  224. package/src/runtime/framework/state/state-core.test.ts +0 -197
  225. package/src/runtime/game-sync-protocol.test.ts +0 -123
  226. package/src/runtime/host-monitor-rate-gate.test.ts +0 -73
  227. package/src/runtime/mailbox-host-relay.test.ts +0 -293
  228. package/src/runtime/observability/observability.test.ts +0 -583
  229. package/src/runtime/owner-control.test.ts +0 -153
  230. package/src/runtime/parent-process-watch.test.ts +0 -27
  231. package/src/runtime/pending-event-handoff.test.ts +0 -29
  232. package/src/runtime/raw-ws-log.test.ts +0 -102
  233. package/src/runtime/runtime-logger.test.ts +0 -58
  234. package/src/runtime/runtime-persistence.test.ts +0 -26
  235. package/src/runtime/runtime.test.ts +0 -1770
  236. package/src/runtime/ws-client.test.ts +0 -562
  237. package/src/sdk/behavior-plugin/index.test.ts +0 -74
  238. package/src/sdk/index.test.ts +0 -45
  239. package/src/sdk/module-input/index.test.ts +0 -49
  240. package/src/sdk/perception-plugin/index.test.ts +0 -22
  241. package/src/sdk/resource-metadata.test.ts +0 -40
  242. package/src/sdk/trigger-plugin/index.test.ts +0 -41
  243. package/src/short-command/classifier.test.ts +0 -107
  244. package/src/short-command/presenter.test.ts +0 -119
  245. package/src/short-command/runner.test.ts +0 -78
  246. package/src/short-command/sensitive-data-filter.test.ts +0 -56
  247. package/src/short-command/transport-response.test.ts +0 -39
  248. package/src/strategies/custom-module.test.ts +0 -268
  249. package/src/strategies/game-utils.test.ts +0 -306
  250. package/src/strategies/goals/avoid-players-top.test.ts +0 -96
  251. package/src/strategies/goals/crab-sabotage-top.test.ts +0 -145
  252. package/src/strategies/goals/kill-lone-top.test.ts +0 -97
  253. package/src/strategies/goals/kill-target-top.test.ts +0 -66
  254. package/src/strategies/goals/lone-kill-task-top.test.ts +0 -85
  255. package/src/strategies/goals/normal-shrimp-top.test.ts +0 -113
  256. package/src/strategies/goals/paradise-fish-top.test.ts +0 -204
  257. package/src/strategies/goals/task-only-top.test.ts +0 -89
  258. package/src/strategies/goals/warrior-shrimp-top.test.ts +0 -139
  259. package/src/strategies/meeting-gate.test.ts +0 -59
  260. package/src/strategies/official-long-behavior.test.ts +0 -89
  261. package/src/strategies/pathfind/astar-path.test.ts +0 -198
  262. package/src/strategies/pathfind/escape-planner.test.ts +0 -223
  263. package/src/strategies/player-targets.test.ts +0 -10
  264. package/src/strategies/task-only.test.ts +0 -138
@@ -1,1770 +0,0 @@
1
- import { describe, expect, it, vi } from 'vitest';
2
- import { Runtime } from './framework/runtime.js';
3
- import {
4
- CLAWCLAW_GAME_WS_SOURCE,
5
- CLAWCLAW_ROOM_WS_SOURCE,
6
- } from './clawclaw/plugins/source/source-transports.js';
7
- import type {
8
- RuntimeInputBatch,
9
- RuntimeEpochPlugin,
10
- RuntimeSourceContext,
11
- RuntimeSourcePlugin,
12
- } from './framework/plugins/index.js';
13
- import { MemoryRuntimeInputJournal } from './framework/plugins/index.js';
14
- import {
15
- DEFAULT_EVENT_CONSUMER_ID,
16
- MemoryEventRepository,
17
- } from './framework/events/index.js';
18
- import {
19
- MemoryStateHistoryRepository,
20
- type StateHistoryRepository,
21
- type TrajectoryRecord,
22
- } from './framework/state/index.js';
23
- import type { ClawclawPosition } from './clawclaw-position.js';
24
- import { createClawclawEventCatalog } from './clawclaw-event-catalog.js';
25
- import {
26
- CLAWCLAW_GAME_LIVENESS_SILENCE_MS,
27
- createClawclawRuntime,
28
- } from './clawclaw/runtime.js';
29
- import { projectClawclawCurrentState } from './clawclaw/runtime-state.js';
30
-
31
- interface TestInputMeta {
32
- connectionId: string;
33
- receivedAt?: string;
34
- sourceSeq?: number | string;
35
- sourceEventId?: string;
36
- delivery?: 'live' | 'replay';
37
- observedAt?: string;
38
- }
39
-
40
- function testInputBatch(
41
- scope: ReturnType<Runtime['scope']>,
42
- source: { sourceId: string },
43
- kind: 'state' | 'event',
44
- payload: Record<string, any>,
45
- meta: TestInputMeta,
46
- ): RuntimeInputBatch<Record<string, any>, Record<string, unknown>> {
47
- const receivedAt = meta.receivedAt ?? new Date().toISOString();
48
- const sourceKey = meta.sourceEventId
49
- ?? (meta.sourceSeq === undefined
50
- ? `${kind}:${meta.connectionId}:${receivedAt}`
51
- : `${kind}:${meta.connectionId}:${String(meta.sourceSeq)}`);
52
- const { type, ...eventPayload } = payload;
53
- return {
54
- scope,
55
- sourceId: source.sourceId,
56
- connectionId: meta.connectionId,
57
- sourceKey,
58
- sourceSeq: meta.sourceSeq,
59
- domainTick: kind === 'state' && typeof payload.tick === 'number' ? payload.tick : undefined,
60
- state: kind === 'state'
61
- ? payload
62
- : {
63
- schema: 'clawclaw.runtime-state.v1',
64
- stage: 'game',
65
- connection: 'connected',
66
- cause: 'backend_event',
67
- game_snapshot: { status: 'not_updated' },
68
- },
69
- events: kind === 'event'
70
- ? [{
71
- type,
72
- payload: eventPayload,
73
- sourceEventId: meta.sourceEventId,
74
- sourceSeq: meta.sourceSeq,
75
- observedAt: meta.observedAt,
76
- receivedAt,
77
- replayed: meta.delivery === 'replay',
78
- }]
79
- : [],
80
- completeness: meta.delivery === 'replay' ? 'best_effort' : 'complete',
81
- observedAt: meta.observedAt,
82
- receivedAt,
83
- };
84
- }
85
-
86
- function localEventInputBatch(
87
- scope: ReturnType<Runtime['scope']>,
88
- type: string,
89
- payload: Record<string, unknown>,
90
- sourceSeq: number,
91
- ): RuntimeInputBatch<Record<string, any>, Record<string, unknown>> {
92
- const receivedAt = new Date(1_000 + sourceSeq).toISOString();
93
- return {
94
- scope,
95
- sourceId: 'test.local-source',
96
- connectionId: 'test-local',
97
- sourceKey: `local:${sourceSeq}:${type}`,
98
- sourceSeq,
99
- state: {
100
- schema: 'clawclaw.runtime-state.v1',
101
- stage: 'matching',
102
- connection: 'disconnected',
103
- cause: 'local_event',
104
- game_snapshot: { status: 'unavailable' },
105
- },
106
- events: [{
107
- type,
108
- producer: 'local_synth',
109
- payload,
110
- sourceEventId: `local:${sourceSeq}:${type}`,
111
- sourceSeq,
112
- receivedAt,
113
- }],
114
- completeness: 'complete',
115
- receivedAt,
116
- };
117
- }
118
-
119
- async function submitTestInput(
120
- runtime: Runtime,
121
- batch: RuntimeInputBatch<Record<string, any>, Record<string, unknown>>,
122
- ): Promise<void> {
123
- await runtime.acceptInputBatch(batch);
124
- await runtime.flush();
125
- }
126
-
127
- function createRuntime() {
128
- const events = new MemoryEventRepository();
129
- const history = new MemoryStateHistoryRepository<ClawclawPosition>();
130
- const runtime = new Runtime({
131
- adapterId: 'clawclaw',
132
- accountId: 'account-1',
133
- eventCatalog: createClawclawEventCatalog(),
134
- eventRepository: events,
135
- stateHistoryRepository: history,
136
- currentStateFromRuntimeState: projectClawclawCurrentState,
137
- initialSegment: { kind: 'queue' },
138
- });
139
- return { runtime, events, history };
140
- }
141
-
142
- class FailingStateHistoryRepository implements StateHistoryRepository<ClawclawPosition> {
143
- readonly inner = new MemoryStateHistoryRepository<ClawclawPosition>();
144
- fail = true;
145
-
146
- openScope = this.inner.openScope.bind(this.inner);
147
- sealScope = this.inner.sealScope.bind(this.inner);
148
- markScopeIncomplete = this.inner.markScopeIncomplete.bind(this.inner);
149
- getScope = this.inner.getScope.bind(this.inner);
150
- appendStateFrame = this.inner.appendStateFrame.bind(this.inner);
151
- queryStateFrames = this.inner.queryStateFrames.bind(this.inner);
152
- latestStateFrame = this.inner.latestStateFrame.bind(this.inner);
153
- query = this.inner.query.bind(this.inner);
154
-
155
- append(records: TrajectoryRecord<ClawclawPosition>[]) {
156
- if (this.fail) throw new Error('disk unavailable');
157
- return this.inner.append(records);
158
- }
159
- }
160
-
161
- describe('Runtime', () => {
162
- it('loads Source and Epoch plugins through the two game-neutral plugin boundaries', async () => {
163
- const processedEpochs: number[] = [];
164
- let sourceContext: RuntimeSourceContext | null = null;
165
- let sourceStops = 0;
166
- const runtime = new Runtime({
167
- adapterId: 'test-game',
168
- accountId: 'test-account',
169
- eventCatalog: createClawclawEventCatalog(),
170
- eventRepository: new MemoryEventRepository(),
171
- stateHistoryRepository: new MemoryStateHistoryRepository(),
172
- runtimeEpochPlugins: [{
173
- kind: 'epoch',
174
- id: 'test.epoch',
175
- version: '1',
176
- update(input) {
177
- processedEpochs.push(input.epoch.epochSeq);
178
- return { outcome: 'noop', reason: 'framework_test' };
179
- },
180
- }],
181
- initialSegment: { kind: 'test' },
182
- });
183
- const source: RuntimeSourcePlugin = {
184
- kind: 'source',
185
- id: 'test.source',
186
- version: '1',
187
- start(context) {
188
- sourceContext = context;
189
- return { stop: () => { sourceStops += 1; } };
190
- },
191
- };
192
-
193
- await runtime.startSourcePlugin(source);
194
- expect(runtime.runtimePluginDescriptors()).toEqual([
195
- { kind: 'source', id: 'test.source', version: '1' },
196
- expect.objectContaining({ kind: 'epoch', id: 'test.epoch', version: '1' }),
197
- ]);
198
- await expect(runtime.startSourcePlugin(source)).rejects.toThrow(
199
- 'Duplicate Runtime Source Plugin id: test.source',
200
- );
201
- await sourceContext!.acceptInputBatch({
202
- scope: runtime.scope(),
203
- sourceId: 'test.source',
204
- connectionId: 'test-input',
205
- sourceKey: 'message-1',
206
- state: { stage: 'test' },
207
- events: [],
208
- completeness: 'complete',
209
- receivedAt: new Date(100).toISOString(),
210
- });
211
- await runtime.flush();
212
-
213
- expect(processedEpochs).toEqual([1]);
214
- await runtime.close();
215
- expect(sourceStops).toBe(1);
216
- });
217
-
218
- it('drains a Source terminal InputBatch as its own epoch before shutdown', async () => {
219
- const events = new MemoryEventRepository();
220
- let lifecycleFlushes = 0;
221
- const runtime = new Runtime({
222
- adapterId: 'test-game',
223
- accountId: 'terminal-account',
224
- eventCatalog: createClawclawEventCatalog(),
225
- eventRepository: events,
226
- stateHistoryRepository: new MemoryStateHistoryRepository(),
227
- runtimeEpochPlugins: [{
228
- kind: 'epoch',
229
- id: 'test.terminal-producer',
230
- version: '1',
231
- produces: { states: ['terminal.state'], events: ['strategy_alert'] },
232
- update(input) {
233
- if (input.epoch.state.stage !== 'ended') return { outcome: 'noop' };
234
- return {
235
- outcome: 'processed',
236
- states: [{ topic: 'terminal.state', value: { closed: true } }],
237
- events: [{
238
- type: 'strategy_alert',
239
- dedupeKey: 'terminal',
240
- payload: { closed: true },
241
- }],
242
- };
243
- },
244
- flush() {
245
- lifecycleFlushes += 1;
246
- },
247
- }],
248
- initialSegment: { kind: 'test' },
249
- });
250
- let sourceContext: RuntimeSourceContext | null = null;
251
- await runtime.startSourcePlugin({
252
- kind: 'source',
253
- id: 'test.source',
254
- version: '1',
255
- start(context) {
256
- sourceContext = context;
257
- return {
258
- stop: async () => {
259
- await context.acceptInputBatch({
260
- scope: context.currentSegment().scope,
261
- sourceId: 'test.source',
262
- connectionId: 'terminal-control',
263
- sourceKey: 'terminal-message',
264
- state: { stage: 'ended' },
265
- events: [],
266
- completeness: 'complete',
267
- receivedAt: new Date(100).toISOString(),
268
- });
269
- },
270
- };
271
- },
272
- });
273
- const scope = runtime.scope();
274
-
275
- await runtime.close();
276
-
277
- expect(runtime.inputJournal.epoch(1)?.state).toEqual({ stage: 'ended' });
278
- expect(runtime.inputJournal.pluginRecords(1)).toMatchObject([{
279
- epochSeq: 1,
280
- pluginId: 'test.terminal-producer',
281
- outcome: 'processed',
282
- stateCount: 1,
283
- eventCount: 1,
284
- }]);
285
- expect(runtime.inputJournal.states(1)).toMatchObject([{
286
- epochSeq: 1,
287
- pluginId: 'test.terminal-producer',
288
- topic: 'terminal.state',
289
- }]);
290
- expect(events.listCommittedEvents({
291
- sessionId: scope.sessionId,
292
- segmentId: scope.segmentId,
293
- types: ['strategy_alert'],
294
- })).toMatchObject([{
295
- epochSeq: 1,
296
- producerPluginId: 'test.terminal-producer',
297
- producerOutputIndex: 0,
298
- }]);
299
- expect(lifecycleFlushes).toBe(1);
300
- await expect(sourceContext!.acceptInputBatch({
301
- scope,
302
- sourceId: 'test.source',
303
- connectionId: 'late',
304
- sourceKey: 'late-message',
305
- state: { stage: 'late' },
306
- events: [],
307
- completeness: 'complete',
308
- receivedAt: new Date(200).toISOString(),
309
- })).rejects.toThrow('Runtime input is closed.');
310
- });
311
-
312
- it('stays idle until a Source submits another InputBatch', async () => {
313
- const events = new MemoryEventRepository();
314
- let lifecycleFlushes = 0;
315
- const runtime = new Runtime({
316
- adapterId: 'clawclaw',
317
- accountId: 'account-1',
318
- eventCatalog: createClawclawEventCatalog(),
319
- eventRepository: events,
320
- stateHistoryRepository: new MemoryStateHistoryRepository(),
321
- runtimeEpochPlugins: [{
322
- kind: 'epoch',
323
- id: 'periodic-test',
324
- version: '1',
325
- produces: { events: ['visual.player_moved'] },
326
- update(input) {
327
- if (input.epoch.state.cause !== 'max_latency') {
328
- return { outcome: 'noop', reason: 'waiting_for_source_input' };
329
- }
330
- return {
331
- outcome: 'processed',
332
- events: [{
333
- type: 'visual.player_moved',
334
- dedupeKey: 'source-timer:1',
335
- payload: { from_tick: 1, to_tick: 2, status: 'ongoing', text: 'moving' },
336
- }],
337
- };
338
- },
339
- flush() {
340
- lifecycleFlushes += 1;
341
- },
342
- }],
343
- initialSegment: { kind: 'game', identity: 'game-1' },
344
- });
345
- const scope = runtime.scope();
346
- await runtime.acceptInputBatch({
347
- scope,
348
- sourceId: 'test.source',
349
- connectionId: 'test-connection',
350
- sourceKey: 'test-input-1',
351
- state: { phase: 'wandering' },
352
- events: [],
353
- completeness: 'complete',
354
- receivedAt: new Date(100).toISOString(),
355
- });
356
- await runtime.flush();
357
- await new Promise((resolve) => setTimeout(resolve, 20));
358
- expect(lifecycleFlushes).toBe(0);
359
- expect(events.listCommittedEvents({
360
- sessionId: scope.sessionId,
361
- segmentId: scope.segmentId,
362
- types: ['visual.player_moved'],
363
- })).toHaveLength(0);
364
-
365
- await runtime.acceptInputBatch({
366
- scope,
367
- sourceId: 'test.source',
368
- connectionId: 'test-connection',
369
- sourceKey: 'source-timer-1',
370
- state: { cause: 'max_latency' },
371
- events: [],
372
- completeness: 'complete',
373
- receivedAt: new Date(200).toISOString(),
374
- });
375
- await runtime.flush();
376
- expect(events.listCommittedEvents({
377
- sessionId: scope.sessionId,
378
- segmentId: scope.segmentId,
379
- types: ['visual.player_moved'],
380
- })).toHaveLength(1);
381
- await runtime.close();
382
- });
383
-
384
- it('exposes active history writer degradation and logs only health transitions', async () => {
385
- const history = new FailingStateHistoryRepository();
386
- const log = vi.fn();
387
- const runtime = new Runtime<ClawclawPosition>({
388
- adapterId: 'clawclaw',
389
- accountId: 'account-1',
390
- eventCatalog: createClawclawEventCatalog(),
391
- eventRepository: new MemoryEventRepository(),
392
- stateHistoryRepository: history,
393
- historyObserverFactory: (writer) => ({
394
- onFrameAccepted(frame) {
395
- writer.enqueue([{
396
- recordId: `position-${frame.sourceKey}`,
397
- scope: frame.scope,
398
- connectionId: frame.connectionId,
399
- subjectId: 'self',
400
- subjectKind: 'self',
401
- kind: 'position',
402
- sourceType: 'backend_state',
403
- sourceKey: frame.sourceKey,
404
- receivedAtMs: frame.receivedAtMs,
405
- position: { x: 1, y: 2 },
406
- }]);
407
- },
408
- }),
409
- observability: {
410
- log,
411
- error: vi.fn(),
412
- flushWithin: vi.fn(async () => true),
413
- } as any,
414
- initialSegment: { kind: 'game', identity: 'game-1' },
415
- });
416
- const scope = runtime.scope();
417
- runtime.bindConnection(CLAWCLAW_GAME_WS_SOURCE.sourceId, 'history-ws');
418
- const ingest = (tick: number) => submitTestInput(runtime, testInputBatch(
419
- scope,
420
- CLAWCLAW_GAME_WS_SOURCE,
421
- 'state',
422
- { tick },
423
- { connectionId: 'history-ws', sourceSeq: tick },
424
- ));
425
-
426
- await ingest(1);
427
- await runtime.flush();
428
- expect(runtime.persistence.historyWriter).toMatchObject({
429
- status: 'degraded',
430
- queueDepth: 1,
431
- degradedScopes: [{
432
- scope: {
433
- adapterId: 'clawclaw',
434
- sessionId: scope.sessionId,
435
- segmentId: scope.segmentId,
436
- },
437
- queueDepth: 1,
438
- droppedRecordCount: 0,
439
- reason: 'disk unavailable',
440
- }],
441
- });
442
- expect(JSON.stringify(runtime.persistence.historyWriter)).not.toContain('account-1');
443
- const healthLogs = () => log.mock.calls.filter(
444
- (call) => call[1] === 'runtime.state_history.writer_health_changed',
445
- );
446
- expect(healthLogs()).toHaveLength(1);
447
- expect(healthLogs()[0][0]).toBe('warn');
448
- expect(healthLogs()[0][2]).toMatchObject({ status: 'degraded', queue_depth: 1 });
449
-
450
- await ingest(2);
451
- await runtime.flush();
452
- expect(healthLogs()).toHaveLength(1);
453
-
454
- history.fail = false;
455
- await runtime.flush();
456
- expect(runtime.persistence.historyWriter).toMatchObject({
457
- status: 'healthy',
458
- queueDepth: 0,
459
- degradedScopes: [],
460
- });
461
- expect(healthLogs()).toHaveLength(2);
462
- expect(healthLogs()[1][0]).toBe('info');
463
- expect(healthLogs()[1][2]).toMatchObject({ status: 'healthy', queue_depth: 0 });
464
- await runtime.close();
465
- });
466
-
467
- it('routes State and backend Events into separate planes', async () => {
468
- const { runtime, events } = createRuntime();
469
- const scope = runtime.scope();
470
- const connectionId = 'game-ws-1';
471
- runtime.bindConnection(CLAWCLAW_GAME_WS_SOURCE.sourceId, connectionId, 1_000);
472
-
473
- await submitTestInput(runtime, testInputBatch(
474
- scope,
475
- CLAWCLAW_GAME_WS_SOURCE,
476
- 'state',
477
- { tick: 7, phase: 'wandering', you: { name: 'A', x: 1, y: 2, is_alive: true } },
478
- { connectionId, sourceSeq: 7, receivedAt: new Date(1_100).toISOString() },
479
- ));
480
- await submitTestInput(runtime, testInputBatch(
481
- scope,
482
- CLAWCLAW_GAME_WS_SOURCE,
483
- 'event',
484
- { type: 'task_completed', task_name: 'wires', hint: 'backend hint', next_step: 'backend step' },
485
- { connectionId, sourceSeq: 8, receivedAt: new Date(1_200).toISOString() },
486
- ));
487
-
488
- expect(runtime.readState(1_300)).toMatchObject({
489
- state: { tick: 7, phase: 'wandering', you: { name: 'A', is_alive: true } },
490
- stateStatus: { status: 'fresh', semantics: 'latest_received' },
491
- });
492
- const current = events.currentScope({ adapterId: 'clawclaw', accountId: 'account-1' });
493
- expect(current).not.toBeNull();
494
- const row = events.latestEventByType(current!.session.sessionId, 'task_completed');
495
- expect(row?.payload).toEqual({ task_name: 'wires' });
496
- await runtime.close();
497
- });
498
-
499
- it('seals durable Event and State scopes whenever the local Owner Runtime closes', async () => {
500
- const { runtime, events, history } = createRuntime();
501
- const scope = runtime.scope();
502
-
503
- expect(events.currentScope({ adapterId: 'clawclaw', accountId: 'account-1' }))
504
- .toMatchObject({
505
- session: { status: 'open', isCurrent: true },
506
- segment: { status: 'open', isCurrent: true },
507
- });
508
- expect(history.getScope(scope)).toMatchObject({ status: 'OPEN', sealedAtMs: null });
509
-
510
- await runtime.close();
511
-
512
- expect(events.currentScope({ adapterId: 'clawclaw', accountId: 'account-1' })).toBeNull();
513
- expect(events.latestScope({ adapterId: 'clawclaw', accountId: 'account-1' }))
514
- .toMatchObject({
515
- session: { status: 'sealed', isCurrent: false },
516
- segment: { status: 'closed', isCurrent: false },
517
- });
518
- expect(history.getScope(scope)).toMatchObject({ status: 'SEALED' });
519
- });
520
-
521
- it('starts a new local session when backend status resumes the same game after Owner shutdown', async () => {
522
- const events = new MemoryEventRepository();
523
- const history = new MemoryStateHistoryRepository<ClawclawPosition>();
524
- const options = {
525
- adapterId: 'clawclaw',
526
- accountId: 'account-1',
527
- eventCatalog: createClawclawEventCatalog(),
528
- eventRepository: events,
529
- stateHistoryRepository: history,
530
- currentStateFromRuntimeState: projectClawclawCurrentState,
531
- initialSegment: { kind: 'game', identity: 'game-1' },
532
- resume: true,
533
- resumeKey: 'game-1',
534
- } as const;
535
- const first = new Runtime(options);
536
- const firstScope = first.scope();
537
-
538
- await first.close();
539
-
540
- expect(events.latestScope({ adapterId: 'clawclaw', accountId: 'account-1' }))
541
- .toMatchObject({
542
- session: { sessionId: firstScope.sessionId, status: 'sealed', isCurrent: false },
543
- segment: { segmentId: firstScope.segmentId, status: 'closed', isCurrent: false },
544
- });
545
- const resumed = new Runtime(options);
546
- const resumedScope = resumed.scope();
547
-
548
- expect(resumedScope.sessionId).not.toBe(firstScope.sessionId);
549
- expect(resumedScope.segmentId).not.toBe(firstScope.segmentId);
550
- expect(events.currentScope({ adapterId: 'clawclaw', accountId: 'account-1' }))
551
- .toMatchObject({
552
- session: { sessionId: resumedScope.sessionId, resumeKey: 'game-1', status: 'open' },
553
- segment: { segmentId: resumedScope.segmentId, scopeRef: 'game-1', status: 'open' },
554
- });
555
-
556
- await resumed.close();
557
- });
558
-
559
- it('still seals the local participation when another shutdown operation fails', async () => {
560
- const { runtime, events, history } = createRuntime();
561
- const scope = runtime.scope();
562
- await runtime.startSourcePlugin({
563
- kind: 'source',
564
- id: 'test.failing-stop-source',
565
- version: '1',
566
- start: () => ({
567
- stop: () => { throw new Error('source stop failed'); },
568
- }),
569
- });
570
- await expect(runtime.close()).rejects.toThrow('Runtime shutdown operation');
571
- expect(events.currentScope({ adapterId: 'clawclaw', accountId: 'account-1' })).toBeNull();
572
- expect(events.latestScope({ adapterId: 'clawclaw', accountId: 'account-1' }))
573
- .toMatchObject({
574
- session: { status: 'sealed', isCurrent: false },
575
- segment: { status: 'closed', isCurrent: false },
576
- });
577
- expect(history.getScope(scope)).toMatchObject({ status: 'SEALED' });
578
- });
579
-
580
- it('reads a bounded incremental strategy feed in the repository', async () => {
581
- const { runtime, events } = createRuntime();
582
- const scope = runtime.scope();
583
- await submitTestInput(runtime, localEventInputBatch(scope, 'joined', { ordinal: 1 }, 1));
584
- await submitTestInput(runtime, localEventInputBatch(scope, 'joined', { ordinal: 2 }, 2));
585
- await submitTestInput(runtime, localEventInputBatch(scope, 'joined', { ordinal: 3 }, 3));
586
- const list = vi.spyOn(events, 'listCommittedEvents');
587
-
588
- const feed = runtime.readReadyView(1, 1);
589
-
590
- expect(feed.events.map((event) => event.payload.ordinal)).toEqual([2]);
591
- expect(feed.throughCommitSeq).toBe(2);
592
- expect(feed.hasMore).toBe(true);
593
- expect(list).toHaveBeenCalledWith(expect.objectContaining({
594
- afterCommitSeq: 1,
595
- limit: 2,
596
- order: 'asc',
597
- }));
598
- await runtime.close();
599
- });
600
-
601
- it('publishes a finalized State and Event watermark only after its plugin epoch', async () => {
602
- let release!: () => void;
603
- const gate = new Promise<void>((resolve) => { release = resolve; });
604
- const events = new MemoryEventRepository();
605
- const runtime = new Runtime({
606
- adapterId: 'clawclaw',
607
- accountId: 'account-1',
608
- eventCatalog: createClawclawEventCatalog(),
609
- eventRepository: events,
610
- stateHistoryRepository: new MemoryStateHistoryRepository(),
611
- runtimeEpochPlugins: [{
612
- kind: 'epoch',
613
- id: 'delayed',
614
- version: '1',
615
- produces: { events: ['strategy_alert'] },
616
- async update(input) {
617
- await gate;
618
- return {
619
- outcome: 'processed',
620
- events: [{
621
- type: 'strategy_alert',
622
- dedupeKey: input.frame.sourceKey,
623
- payload: { tick: input.frame.backendTick },
624
- }],
625
- };
626
- },
627
- }],
628
- currentStateFromRuntimeState: (state) => state,
629
- initialSegment: { kind: 'game', identity: 'game-1' },
630
- });
631
- const scope = runtime.scope();
632
- const ingest = runtime.acceptInputBatch({
633
- scope,
634
- sourceId: CLAWCLAW_GAME_WS_SOURCE.sourceId,
635
- connectionId: 'ws',
636
- sourceKey: 'state:1',
637
- sourceSeq: 1,
638
- domainTick: 1,
639
- state: { tick: 1, phase: 'wandering' },
640
- events: [],
641
- completeness: 'complete',
642
- receivedAt: new Date(100).toISOString(),
643
- });
644
-
645
- expect(runtime.readReadyView()).toMatchObject({
646
- frameSeq: 0,
647
- eventWatermark: 0,
648
- state: { state: null },
649
- events: [],
650
- });
651
- release();
652
- await ingest;
653
- await runtime.flush();
654
- expect(runtime.readReadyView()).toMatchObject({
655
- frameSeq: 1,
656
- eventWatermark: 1,
657
- state: { state: { tick: 1 } },
658
- events: [{ type: 'strategy_alert', payload: { tick: 1 } }],
659
- });
660
- await runtime.close();
661
- });
662
-
663
- it('returns the immutable Ready View for one exact closed epoch', async () => {
664
- const runtime = new Runtime({
665
- adapterId: 'clawclaw',
666
- accountId: 'account-1',
667
- eventCatalog: createClawclawEventCatalog(),
668
- eventRepository: new MemoryEventRepository(),
669
- stateHistoryRepository: new MemoryStateHistoryRepository(),
670
- currentStateFromRuntimeState: (state) => state,
671
- initialSegment: { kind: 'game', identity: 'game-1' },
672
- });
673
- const scope = runtime.scope();
674
- const first = await runtime.acceptInputBatch({
675
- scope,
676
- sourceId: CLAWCLAW_GAME_WS_SOURCE.sourceId,
677
- connectionId: 'ws',
678
- sourceKey: 'exact:1',
679
- state: { tick: 1 },
680
- events: [{ type: 'role_assigned', payload: { role: 'shrimp_generic' } }],
681
- completeness: 'complete',
682
- receivedAt: new Date(100).toISOString(),
683
- });
684
- await runtime.acceptInputBatch({
685
- scope,
686
- sourceId: CLAWCLAW_GAME_WS_SOURCE.sourceId,
687
- connectionId: 'ws',
688
- sourceKey: 'exact:2',
689
- state: { tick: 2 },
690
- events: [{ type: 'speech', payload: { actor_name: '2', text: 'later' } }],
691
- completeness: 'complete',
692
- receivedAt: new Date(200).toISOString(),
693
- });
694
-
695
- const exact = await runtime.waitForEpochReadyView(first.epoch.epochSeq);
696
- await runtime.flush();
697
- expect(exact).toMatchObject({
698
- epochSeq: first.epoch.epochSeq,
699
- state: { state: { tick: 1 } },
700
- events: [{ type: 'role_assigned' }],
701
- eventWatermark: 1,
702
- });
703
- expect(runtime.readReadyView()).toMatchObject({
704
- epochSeq: 2,
705
- state: { state: { tick: 2 } },
706
- events: [{ type: 'role_assigned' }, { type: 'speech' }],
707
- eventWatermark: 2,
708
- });
709
- await runtime.close();
710
- });
711
-
712
- it('carries the latest plugin State across noop epochs within one Ready View scope', async () => {
713
- let updateCount = 0;
714
- const runtime = new Runtime({
715
- adapterId: 'clawclaw',
716
- accountId: 'account-1',
717
- eventCatalog: createClawclawEventCatalog(),
718
- eventRepository: new MemoryEventRepository(),
719
- stateHistoryRepository: new MemoryStateHistoryRepository(),
720
- currentStateFromRuntimeState: (state) => state,
721
- runtimeEpochPlugins: [{
722
- kind: 'epoch',
723
- id: 'clawclaw.behavior',
724
- version: '1',
725
- produces: { states: ['behavior.status'] },
726
- update() {
727
- updateCount += 1;
728
- if (updateCount > 1) {
729
- return { outcome: 'noop', reason: 'behavior_cadence_wait' };
730
- }
731
- return {
732
- outcome: 'processed',
733
- states: [{
734
- topic: 'behavior.status',
735
- value: { running: true, behavior: 'task-only', status: { summary: 'Going to engine.' } },
736
- }],
737
- };
738
- },
739
- }],
740
- initialSegment: { kind: 'game', identity: 'game-1' },
741
- });
742
- const scope = runtime.scope();
743
- const first = await runtime.acceptInputBatch({
744
- scope,
745
- sourceId: CLAWCLAW_GAME_WS_SOURCE.sourceId,
746
- connectionId: 'ws',
747
- sourceKey: 'plugin-state:1',
748
- sourceSeq: 1,
749
- domainTick: 100,
750
- state: { tick: 100, phase: 'wandering' },
751
- events: [],
752
- completeness: 'complete',
753
- receivedAt: new Date(100).toISOString(),
754
- });
755
- await runtime.acceptInputBatch({
756
- scope,
757
- sourceId: CLAWCLAW_GAME_WS_SOURCE.sourceId,
758
- connectionId: 'ws',
759
- sourceKey: 'plugin-state:2',
760
- sourceSeq: 2,
761
- domainTick: 105,
762
- state: { tick: 105, phase: 'wandering' },
763
- events: [],
764
- completeness: 'complete',
765
- receivedAt: new Date(200).toISOString(),
766
- });
767
- await runtime.flush();
768
-
769
- const firstReady = await runtime.waitForEpochReadyView(first.epoch.epochSeq);
770
- expect(firstReady.pluginStates['behavior.status']).toMatchObject({
771
- pluginId: 'clawclaw.behavior',
772
- value: { running: true, behavior: 'task-only', status: { summary: 'Going to engine.' } },
773
- updatedEpochSeq: 1,
774
- updatedDomainTick: 100,
775
- });
776
- expect(firstReady.pluginOutcomes['clawclaw.behavior']).toMatchObject({
777
- epochSeq: 1,
778
- domainTick: 100,
779
- outcome: 'processed',
780
- });
781
-
782
- const current = runtime.readReadyView();
783
- expect(current.pluginStates['behavior.status']).toMatchObject({
784
- updatedEpochSeq: 1,
785
- updatedDomainTick: 100,
786
- value: { running: true, behavior: 'task-only' },
787
- });
788
- expect(current.pluginOutcomes['clawclaw.behavior']).toMatchObject({
789
- epochSeq: 2,
790
- domainTick: 105,
791
- outcome: 'noop',
792
- reason: 'behavior_cadence_wait',
793
- });
794
- await runtime.activateSegment('game', 'game-2');
795
- expect(runtime.readReadyView()).toMatchObject({
796
- epochSeq: 0,
797
- pluginStates: {},
798
- pluginOutcomes: {},
799
- });
800
- await runtime.close();
801
- });
802
-
803
- it('never exposes an older segment as the Ready View of a newly activated segment', async () => {
804
- let release!: () => void;
805
- const gate = new Promise<void>((resolve) => { release = resolve; });
806
- const runtime = new Runtime({
807
- adapterId: 'clawclaw',
808
- accountId: 'account-1',
809
- eventCatalog: createClawclawEventCatalog(),
810
- eventRepository: new MemoryEventRepository(),
811
- stateHistoryRepository: new MemoryStateHistoryRepository(),
812
- runtimeEpochPlugins: [{
813
- kind: 'epoch',
814
- id: 'delayed-segment-plugin',
815
- version: '1',
816
- async update() {
817
- await gate;
818
- return { outcome: 'noop' };
819
- },
820
- }],
821
- currentStateFromRuntimeState: (state) => state,
822
- initialSegment: { kind: 'game', identity: 'game-1' },
823
- });
824
- const firstScope = runtime.scope();
825
- await runtime.acceptInputBatch({
826
- scope: firstScope,
827
- sourceId: CLAWCLAW_GAME_WS_SOURCE.sourceId,
828
- connectionId: 'ws-1',
829
- sourceKey: 'first-segment',
830
- sourceSeq: 1,
831
- state: { marker: 'first' },
832
- events: [{
833
- type: 'speech',
834
- payload: { actor_name: '2号', text: 'first' },
835
- sourceEventId: 'first-segment-event',
836
- sourceSeq: 1,
837
- }],
838
- completeness: 'complete',
839
- receivedAt: new Date(100).toISOString(),
840
- });
841
-
842
- release();
843
- const secondScope = await runtime.activateSegment('game', 'game-2');
844
- await runtime.acceptInputBatch({
845
- scope: secondScope,
846
- sourceId: CLAWCLAW_GAME_WS_SOURCE.sourceId,
847
- connectionId: 'ws-2',
848
- sourceKey: 'second-segment',
849
- sourceSeq: 1,
850
- state: { marker: 'second' },
851
- events: [{
852
- type: 'role_assigned',
853
- payload: { role: 'shrimp_generic' },
854
- sourceEventId: 'second-segment-event',
855
- sourceSeq: 1,
856
- }],
857
- completeness: 'complete',
858
- receivedAt: new Date(200).toISOString(),
859
- });
860
-
861
- expect(runtime.readReadyView()).toMatchObject({
862
- scope: { segmentId: secondScope.segmentId },
863
- epochSeq: 0,
864
- frameSeq: 0,
865
- state: { state: null },
866
- events: [],
867
- });
868
- await runtime.flush();
869
- expect(runtime.readReadyView()).toMatchObject({
870
- scope: { segmentId: secondScope.segmentId },
871
- epochSeq: 2,
872
- eventWatermark: 2,
873
- state: { state: { marker: 'second' } },
874
- });
875
- await runtime.close();
876
- });
877
-
878
- it('keeps an unknown backend fact but raises a catalog coverage alarm', async () => {
879
- const events = new MemoryEventRepository();
880
- const log = vi.fn();
881
- const runtime = new Runtime({
882
- adapterId: 'clawclaw',
883
- accountId: 'account-1',
884
- eventCatalog: createClawclawEventCatalog(),
885
- eventRepository: events,
886
- stateHistoryRepository: new MemoryStateHistoryRepository<ClawclawPosition>(),
887
- initialSegment: { kind: 'game', identity: 'game-1' },
888
- observability: {
889
- log,
890
- error: vi.fn(),
891
- flushWithin: vi.fn(async () => true),
892
- } as any,
893
- });
894
- const scope = runtime.scope();
895
- runtime.bindConnection(CLAWCLAW_GAME_WS_SOURCE.sourceId, 'unknown-event-ws');
896
-
897
- await submitTestInput(runtime, testInputBatch(
898
- scope,
899
- CLAWCLAW_GAME_WS_SOURCE,
900
- 'event',
901
- { type: 'future_backend_fact', value: 7 },
902
- { connectionId: 'unknown-event-ws', sourceEventId: 'future-1' },
903
- ));
904
-
905
- expect(events.latestEventByType(scope.sessionId, 'future_backend_fact', scope.segmentId))
906
- .toMatchObject({ producer: 'backend_push', deliveryClass: 'internal_only' });
907
- expect(log).toHaveBeenCalledWith(
908
- 'warn',
909
- 'runtime.backend_event.unregistered',
910
- expect.objectContaining({
911
- event_type: 'future_backend_fact',
912
- source_id: CLAWCLAW_GAME_WS_SOURCE.sourceId,
913
- }),
914
- expect.objectContaining({ component: 'runtime.event-catalog' }),
915
- );
916
- await runtime.close();
917
- });
918
-
919
- it('runs an Event-consuming Epoch Plugin only after its input Event commits', async () => {
920
- const events = new MemoryEventRepository();
921
- const runtime = new Runtime({
922
- adapterId: 'clawclaw',
923
- accountId: 'account-1',
924
- eventCatalog: createClawclawEventCatalog(),
925
- eventRepository: events,
926
- stateHistoryRepository: new MemoryStateHistoryRepository<ClawclawPosition>(),
927
- runtimeEpochPlugins: [{
928
- kind: 'epoch',
929
- id: 'test.task-followup',
930
- version: '1',
931
- consumes: { events: ['task_completed'] },
932
- produces: { events: ['strategy_alert'] },
933
- update(input) {
934
- const event = input.epochEvents.find((candidate) => candidate.type === 'task_completed');
935
- if (!event) return { outcome: 'noop', reason: 'no_task_completed' };
936
- return {
937
- outcome: 'processed',
938
- events: [{
939
- type: 'strategy_alert',
940
- dedupeKey: `task:${event.eventId}`,
941
- payload: { input_commit_seq: event.commitSeq },
942
- }],
943
- consumeEventsThroughCommitSeq: input.pendingEvents.at(-1)?.commitSeq,
944
- };
945
- },
946
- }],
947
- initialSegment: { kind: 'game', identity: 'game-1' },
948
- });
949
- const scope = runtime.scope();
950
- runtime.bindConnection(CLAWCLAW_GAME_WS_SOURCE.sourceId, 'game-ws-1');
951
-
952
- await submitTestInput(runtime, testInputBatch(
953
- scope,
954
- CLAWCLAW_GAME_WS_SOURCE,
955
- 'event',
956
- { type: 'task_completed', task_name: 'wires' },
957
- {
958
- connectionId: 'game-ws-1',
959
- sourceSeq: 1,
960
- sourceEventId: 'backend-task-1',
961
- },
962
- ));
963
-
964
- expect(events.listCommittedEvents({
965
- sessionId: scope.sessionId,
966
- segmentId: scope.segmentId,
967
- order: 'asc',
968
- }).map((event) => [event.type, event.commitSeq])).toEqual([
969
- ['task_completed', 1],
970
- ['strategy_alert', 2],
971
- ]);
972
- expect(runtime.runtimeEpochPluginDescriptors()).toMatchObject([{
973
- id: 'test.task-followup',
974
- produces: { events: ['strategy_alert'] },
975
- }]);
976
- await runtime.close();
977
- });
978
-
979
- it('allows multiple Epoch Plugins to produce the same Event topic', async () => {
980
- const events = new MemoryEventRepository();
981
- const runtime = new Runtime({
982
- adapterId: 'clawclaw',
983
- accountId: 'account-1',
984
- eventCatalog: createClawclawEventCatalog(),
985
- eventRepository: events,
986
- stateHistoryRepository: new MemoryStateHistoryRepository<ClawclawPosition>(),
987
- runtimeEpochPlugins: ['first', 'second'].map((id) => ({
988
- kind: 'epoch' as const,
989
- id: `test.${id}`,
990
- version: '1',
991
- produces: { events: ['strategy_alert'] },
992
- update: (input: any) => ({
993
- outcome: 'processed' as const,
994
- events: [{
995
- type: 'strategy_alert',
996
- dedupeKey: `${id}:${input.epoch.epochSeq}`,
997
- payload: { producer: id },
998
- }],
999
- }),
1000
- })),
1001
- initialSegment: { kind: 'game', identity: 'game-1' },
1002
- });
1003
-
1004
- await submitTestInput(runtime, testInputBatch(
1005
- runtime.scope(),
1006
- CLAWCLAW_GAME_WS_SOURCE,
1007
- 'state',
1008
- { tick: 1, phase: 'wandering' },
1009
- { connectionId: 'same-topic', sourceSeq: 1 },
1010
- ));
1011
-
1012
- const produced = events.listCommittedEvents({
1013
- sessionId: runtime.scope().sessionId,
1014
- segmentId: runtime.scope().segmentId,
1015
- types: ['strategy_alert'],
1016
- order: 'asc',
1017
- });
1018
- expect(produced.map((event) => event.payload.producer)).toEqual(['first', 'second']);
1019
- expect(produced.map((event) => [event.producerPluginId, event.producerOutputIndex]))
1020
- .toEqual([['test.first', 0], ['test.second', 0]]);
1021
- await runtime.close();
1022
- });
1023
-
1024
- it('passes the invocation epoch through plugin capability calls', async () => {
1025
- const inputJournal = new MemoryRuntimeInputJournal();
1026
- let releaseConsumer!: () => void;
1027
- let markConsumerStarted!: () => void;
1028
- const consumerGate = new Promise<void>((resolve) => { releaseConsumer = resolve; });
1029
- const consumerStarted = new Promise<void>((resolve) => { markConsumerStarted = resolve; });
1030
- const seen: Array<{ invocationEpoch: number; capabilityEpoch: number | undefined }> = [];
1031
- let unregister: (() => void) | undefined;
1032
- const runtime = new Runtime({
1033
- adapterId: 'clawclaw',
1034
- accountId: 'account-capability-epoch',
1035
- eventCatalog: createClawclawEventCatalog(),
1036
- eventRepository: new MemoryEventRepository(),
1037
- stateHistoryRepository: new MemoryStateHistoryRepository<ClawclawPosition>(),
1038
- inputJournal,
1039
- runtimeEpochPlugins: [{
1040
- kind: 'epoch',
1041
- id: 'test.capability-provider',
1042
- version: '1',
1043
- capabilities: { provides: ['test.epoch'] },
1044
- start(context) {
1045
- unregister = context.capabilities.provideObservation({
1046
- capability: 'test.epoch',
1047
- query: async (_request, queryScope, queryContext) => ({
1048
- scope: queryScope,
1049
- capability: 'test.epoch',
1050
- receivedAt: new Date().toISOString(),
1051
- freshness: 'fresh',
1052
- value: { epochSeq: queryContext.epochSeq },
1053
- }),
1054
- });
1055
- },
1056
- update: () => ({ outcome: 'noop' }),
1057
- stop: () => unregister?.(),
1058
- }, {
1059
- kind: 'epoch',
1060
- id: 'test.capability-consumer',
1061
- version: '1',
1062
- after: ['test.capability-provider'],
1063
- capabilities: { uses: ['test.epoch'] },
1064
- async update(input, context) {
1065
- if (input.epoch.epochSeq === 1) {
1066
- markConsumerStarted();
1067
- await consumerGate;
1068
- }
1069
- const observed = await context.capabilities.queryObservation<unknown, { epochSeq?: number }>(
1070
- 'test.epoch',
1071
- {},
1072
- );
1073
- seen.push({
1074
- invocationEpoch: input.epoch.epochSeq,
1075
- capabilityEpoch: observed.value.epochSeq,
1076
- });
1077
- return { outcome: 'noop' };
1078
- },
1079
- }],
1080
- initialSegment: { kind: 'game', identity: 'capability-epoch' },
1081
- });
1082
- const scope = runtime.scope();
1083
-
1084
- await runtime.acceptInputBatch(testInputBatch(
1085
- scope,
1086
- CLAWCLAW_GAME_WS_SOURCE,
1087
- 'state',
1088
- { tick: 1, phase: 'wandering' },
1089
- { connectionId: 'capability-ws', sourceSeq: 1 },
1090
- ));
1091
- await consumerStarted;
1092
- await runtime.acceptInputBatch(testInputBatch(
1093
- scope,
1094
- CLAWCLAW_GAME_WS_SOURCE,
1095
- 'state',
1096
- { tick: 2, phase: 'wandering' },
1097
- { connectionId: 'capability-ws', sourceSeq: 2 },
1098
- ));
1099
- await vi.waitFor(() => expect(
1100
- inputJournal.pluginProgress('test.capability-provider', scope).completedThroughEpochSeq,
1101
- ).toBe(2));
1102
- releaseConsumer();
1103
- await runtime.flush();
1104
-
1105
- expect(seen).toEqual([
1106
- { invocationEpoch: 1, capabilityEpoch: 1 },
1107
- { invocationEpoch: 2, capabilityEpoch: 2 },
1108
- ]);
1109
- await runtime.close();
1110
- });
1111
-
1112
- it('serializes concurrent backend ingress so derived facts follow commit order', async () => {
1113
- const events = new MemoryEventRepository();
1114
- let releaseFirst!: () => void;
1115
- let markFirstObserved!: () => void;
1116
- const firstBlocked = new Promise<void>((resolve) => { releaseFirst = resolve; });
1117
- const firstObserved = new Promise<void>((resolve) => { markFirstObserved = resolve; });
1118
- const runtime = new Runtime({
1119
- adapterId: 'clawclaw',
1120
- accountId: 'account-1',
1121
- eventCatalog: createClawclawEventCatalog(),
1122
- eventRepository: events,
1123
- stateHistoryRepository: new MemoryStateHistoryRepository<ClawclawPosition>(),
1124
- runtimeEpochPlugins: [{
1125
- kind: 'epoch',
1126
- id: 'test.concurrent-task-followup',
1127
- version: '1',
1128
- consumes: { events: ['task_completed'] },
1129
- produces: { events: ['strategy_alert'] },
1130
- async update(input) {
1131
- const event = input.epochEvents.find((candidate) => candidate.type === 'task_completed');
1132
- if (!event) return { outcome: 'noop', reason: 'no_task_completed' };
1133
- if (event.payload.order === 1) {
1134
- markFirstObserved();
1135
- await firstBlocked;
1136
- }
1137
- return {
1138
- outcome: 'processed',
1139
- events: [{
1140
- type: 'strategy_alert',
1141
- dedupeKey: `task:${event.eventId}`,
1142
- payload: { input_order: event.payload.order },
1143
- }],
1144
- consumeEventsThroughCommitSeq: input.pendingEvents.at(-1)?.commitSeq,
1145
- };
1146
- },
1147
- }],
1148
- initialSegment: { kind: 'game', identity: 'game-concurrent' },
1149
- });
1150
- const scope = runtime.scope();
1151
- runtime.bindConnection(CLAWCLAW_GAME_WS_SOURCE.sourceId, 'concurrent-ws');
1152
- const first = submitTestInput(runtime, testInputBatch(
1153
- scope,
1154
- CLAWCLAW_GAME_WS_SOURCE,
1155
- 'event',
1156
- { type: 'task_completed', order: 1 },
1157
- { connectionId: 'concurrent-ws', sourceSeq: 1, sourceEventId: 'task-1' },
1158
- ));
1159
- await firstObserved;
1160
- const second = submitTestInput(runtime, testInputBatch(
1161
- scope,
1162
- CLAWCLAW_GAME_WS_SOURCE,
1163
- 'event',
1164
- { type: 'task_completed', order: 2 },
1165
- { connectionId: 'concurrent-ws', sourceSeq: 2, sourceEventId: 'task-2' },
1166
- ));
1167
-
1168
- expect(events.listCommittedEvents({
1169
- sessionId: scope.sessionId,
1170
- segmentId: scope.segmentId,
1171
- order: 'asc',
1172
- }).map((event) => [event.type, event.payload.order ?? event.payload.input_order]))
1173
- .toEqual([
1174
- ['task_completed', 1],
1175
- ]);
1176
- releaseFirst();
1177
- await Promise.all([first, second]);
1178
-
1179
- expect(events.listCommittedEvents({
1180
- sessionId: scope.sessionId,
1181
- segmentId: scope.segmentId,
1182
- order: 'asc',
1183
- }).map((event) => [event.type, event.payload.order ?? event.payload.input_order]))
1184
- .toEqual([
1185
- ['task_completed', 1],
1186
- ['strategy_alert', 1],
1187
- ['task_completed', 2],
1188
- ['strategy_alert', 2],
1189
- ]);
1190
- await runtime.close();
1191
- });
1192
-
1193
- it('lets a plugin consume durable pending Events on the next epoch after restart', async () => {
1194
- const events = new MemoryEventRepository();
1195
- const history = new MemoryStateHistoryRepository<ClawclawPosition>();
1196
- const baseOptions = {
1197
- adapterId: 'clawclaw',
1198
- accountId: 'account-1',
1199
- eventCatalog: createClawclawEventCatalog(),
1200
- eventRepository: events,
1201
- stateHistoryRepository: history,
1202
- resumeKey: 'game-recovery-1',
1203
- initialSegment: { kind: 'game', identity: 'game-recovery-1' },
1204
- } as const;
1205
- const crashedOwner = new Runtime(baseOptions);
1206
- const originalScope = crashedOwner.scope();
1207
- crashedOwner.bindConnection(CLAWCLAW_GAME_WS_SOURCE.sourceId, 'before-crash');
1208
- await submitTestInput(crashedOwner, testInputBatch(
1209
- originalScope,
1210
- CLAWCLAW_GAME_WS_SOURCE,
1211
- 'event',
1212
- { type: 'task_completed', task_name: 'wires' },
1213
- {
1214
- connectionId: 'before-crash',
1215
- sourceSeq: 7,
1216
- sourceEventId: 'backend-before-crash',
1217
- },
1218
- ));
1219
-
1220
- const resumed = new Runtime({
1221
- ...baseOptions,
1222
- resume: true,
1223
- runtimeEpochPlugins: [{
1224
- kind: 'epoch',
1225
- id: 'test.recovered-task-followup',
1226
- version: '1',
1227
- consumes: { events: ['task_completed'] },
1228
- produces: { events: ['strategy_alert'] },
1229
- update(input) {
1230
- const proposals = input.pendingEvents.map((event) => ({
1231
- type: 'strategy_alert',
1232
- dedupeKey: `task:${event.eventId}`,
1233
- payload: { recovered_input_commit_seq: event.commitSeq },
1234
- }));
1235
- return proposals.length === 0
1236
- ? { outcome: 'noop', reason: 'no_pending_task' }
1237
- : {
1238
- outcome: 'processed',
1239
- events: proposals,
1240
- consumeEventsThroughCommitSeq: input.pendingEvents.at(-1)!.commitSeq,
1241
- };
1242
- },
1243
- }],
1244
- });
1245
- expect(resumed.scope()).toMatchObject(originalScope);
1246
-
1247
- resumed.bindConnection(CLAWCLAW_GAME_WS_SOURCE.sourceId, 'after-crash');
1248
- await submitTestInput(resumed, testInputBatch(
1249
- resumed.scope(),
1250
- CLAWCLAW_GAME_WS_SOURCE,
1251
- 'event',
1252
- { type: 'task_completed', task_name: 'wires' },
1253
- {
1254
- connectionId: 'after-crash',
1255
- sourceSeq: 7,
1256
- sourceEventId: 'backend-before-crash',
1257
- delivery: 'replay',
1258
- },
1259
- ));
1260
- expect(events.listCommittedEvents({
1261
- sessionId: originalScope.sessionId,
1262
- segmentId: originalScope.segmentId,
1263
- types: ['task_completed'],
1264
- })).toHaveLength(1);
1265
- expect(events.listCommittedEvents({
1266
- sessionId: originalScope.sessionId,
1267
- segmentId: originalScope.segmentId,
1268
- types: ['strategy_alert'],
1269
- })).toHaveLength(1);
1270
-
1271
- await resumed.close();
1272
- await crashedOwner.close();
1273
- });
1274
-
1275
- it('requeues accepted but unclosed epochs through the normal bounded scheduler on startup', async () => {
1276
- const events = new MemoryEventRepository();
1277
- const history = new MemoryStateHistoryRepository<ClawclawPosition>();
1278
- const inputJournal = new MemoryRuntimeInputJournal();
1279
- const baseOptions = {
1280
- adapterId: 'clawclaw',
1281
- accountId: 'account-recover-open',
1282
- eventCatalog: createClawclawEventCatalog(),
1283
- eventRepository: events,
1284
- stateHistoryRepository: history,
1285
- inputJournal,
1286
- resumeKey: 'game-open-epoch',
1287
- initialSegment: { kind: 'game', identity: 'game-open-epoch' },
1288
- } as const;
1289
- const interrupted = new Runtime(baseOptions);
1290
- const scope = interrupted.scope();
1291
- const accepted = inputJournal.accept({
1292
- scope,
1293
- sourceId: 'test.source',
1294
- connectionId: 'connection-before-crash',
1295
- sourceKey: 'accepted-before-crash',
1296
- sourceSeq: 1,
1297
- state: { marker: 'recover-me' },
1298
- events: [],
1299
- completeness: 'complete',
1300
- receivedAt: '2026-07-22T00:00:00.000Z',
1301
- }).epoch;
1302
- history.appendStateFrame({
1303
- epochSeq: accepted.epochSeq,
1304
- scope,
1305
- sourceId: accepted.sourceId,
1306
- connectionId: accepted.connectionId,
1307
- sourceKey: `runtime-epoch:${accepted.epochSeq}`,
1308
- sourceSeq: accepted.sourceSeq,
1309
- receivedAtMs: Date.parse(accepted.receivedAt),
1310
- state: accepted.state,
1311
- });
1312
- const processed: number[] = [];
1313
- const resumed = new Runtime({
1314
- ...baseOptions,
1315
- resume: true,
1316
- runtimeEpochPlugins: [{
1317
- kind: 'epoch',
1318
- id: 'test.recover-open-epoch',
1319
- version: '1',
1320
- update(input) {
1321
- processed.push(input.epoch.epochSeq);
1322
- return { outcome: 'noop', reason: 'recovered' };
1323
- },
1324
- }],
1325
- });
1326
-
1327
- await resumed.start();
1328
-
1329
- expect(processed).toEqual([accepted.epochSeq]);
1330
- expect(inputJournal.listOpen(scope)).toEqual([]);
1331
- expect(inputJournal.pluginProgress('test.recover-open-epoch', scope)).toMatchObject({
1332
- completedThroughEpochSeq: accepted.epochSeq,
1333
- });
1334
- expect(resumed.readReadyView()).toMatchObject({
1335
- epochSeq: accepted.epochSeq,
1336
- state: { state: { marker: 'recover-me' } },
1337
- });
1338
- await resumed.close();
1339
- await interrupted.close();
1340
- });
1341
-
1342
- it('retries unconsumed pending Events when a later epoch runs after plugin failure', async () => {
1343
- const events = new MemoryEventRepository();
1344
- let failFirst = true;
1345
- const runtime = new Runtime({
1346
- adapterId: 'clawclaw',
1347
- accountId: 'account-1',
1348
- eventCatalog: createClawclawEventCatalog(),
1349
- eventRepository: events,
1350
- stateHistoryRepository: new MemoryStateHistoryRepository<ClawclawPosition>(),
1351
- initialSegment: { kind: 'game', identity: 'game-retry' },
1352
- runtimeEpochPlugins: [{
1353
- kind: 'epoch',
1354
- id: 'test.retry-pending-events',
1355
- version: '1',
1356
- consumes: { events: ['task_completed'] },
1357
- produces: { events: ['strategy_alert'] },
1358
- update(input) {
1359
- if (input.pendingEvents.length === 0) return { outcome: 'noop', reason: 'no_pending_task' };
1360
- if (failFirst) {
1361
- failFirst = false;
1362
- throw new Error('temporary plugin failure');
1363
- }
1364
- return {
1365
- outcome: 'processed',
1366
- events: input.pendingEvents.map((event) => ({
1367
- type: 'strategy_alert',
1368
- dedupeKey: `task:${event.eventId}`,
1369
- payload: { input_order: event.payload.order },
1370
- })),
1371
- consumeEventsThroughCommitSeq: input.pendingEvents.at(-1)!.commitSeq,
1372
- };
1373
- },
1374
- }],
1375
- });
1376
- const scope = runtime.scope();
1377
- const connectionId = 'plugin-retry-ws';
1378
- runtime.bindConnection(CLAWCLAW_GAME_WS_SOURCE.sourceId, connectionId);
1379
-
1380
- await submitTestInput(runtime, testInputBatch(
1381
- scope,
1382
- CLAWCLAW_GAME_WS_SOURCE,
1383
- 'event',
1384
- { type: 'task_completed', order: 1 },
1385
- { connectionId, sourceEventId: 'retry-input-1', sourceSeq: 1 },
1386
- ));
1387
- expect(events.listCommittedEvents({
1388
- sessionId: scope.sessionId,
1389
- segmentId: scope.segmentId,
1390
- types: ['strategy_alert'],
1391
- })).toEqual([]);
1392
-
1393
- await submitTestInput(runtime, testInputBatch(
1394
- scope,
1395
- CLAWCLAW_GAME_WS_SOURCE,
1396
- 'event',
1397
- { type: 'task_completed', order: 2 },
1398
- { connectionId, sourceEventId: 'retry-input-2', sourceSeq: 2 },
1399
- ));
1400
- expect(events.listCommittedEvents({
1401
- sessionId: scope.sessionId,
1402
- segmentId: scope.segmentId,
1403
- types: ['strategy_alert'],
1404
- order: 'asc',
1405
- }).map((event) => event.payload.input_order)).toEqual([1, 2]);
1406
- await runtime.close();
1407
- });
1408
-
1409
- it('does not infer or load ClawClaw business plugins in the runtime factory', async () => {
1410
- const events = new MemoryEventRepository();
1411
- const runtime = createClawclawRuntime({
1412
- apiKey: 'producer-key',
1413
- runtimeAccountId: 'acct_bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb',
1414
- }, {
1415
- eventRepository: events,
1416
- stateHistoryRepository: new MemoryStateHistoryRepository<ClawclawPosition>(),
1417
- durableStateSnapshot: false,
1418
- initialSegment: { kind: 'room_lobby', identity: 'R2' },
1419
- });
1420
- expect(runtime.runtimeEpochPluginDescriptors()).toEqual([]);
1421
- expect(runtime.runtimePluginDescriptors()).toEqual([]);
1422
- expect(events.latestEventByType(runtime.scope().sessionId, 'room_ready_to_start'))
1423
- .toBeNull();
1424
-
1425
- await runtime.close();
1426
- });
1427
-
1428
- it('lets enabled ACK adapters create ClawClaw delivery lanes on demand', async () => {
1429
- const events = new MemoryEventRepository();
1430
- const commit = vi.spyOn(events, 'commitEvent');
1431
- const runtime = createClawclawRuntime({
1432
- apiKey: 'mailbox-lanes-key',
1433
- runtimeAccountId: 'acct_cccccccccccccccccccccccccccccccc',
1434
- }, {
1435
- eventRepository: events,
1436
- stateHistoryRepository: new MemoryStateHistoryRepository<ClawclawPosition>(),
1437
- durableStateSnapshot: false,
1438
- initialSegment: { kind: 'game', identity: 'game-mailbox-lanes' },
1439
- });
1440
- const scope = runtime.scope();
1441
- const connectionId = 'mailbox-lanes-ws';
1442
- runtime.bindConnection(CLAWCLAW_GAME_WS_SOURCE.sourceId, connectionId);
1443
-
1444
- await submitTestInput(runtime, testInputBatch(
1445
- scope,
1446
- CLAWCLAW_GAME_WS_SOURCE,
1447
- 'event',
1448
- { type: 'task_completed', task_name: 'wires' },
1449
- { connectionId, sourceSeq: 1, sourceEventId: 'mailbox-lanes-event' },
1450
- ));
1451
-
1452
- const event = events.latestEventByType(scope.sessionId, 'task_completed');
1453
- expect(event).not.toBeNull();
1454
- const committed = commit.mock.calls.find(([request]) => request.event.eventId === event!.eventId);
1455
- expect(committed?.[0].consumerIds).toEqual([]);
1456
-
1457
- events.ensureDeliveries(scope.sessionId, 'local-agent:desktop');
1458
- expect(events.delivery(event!.eventId, 'local-agent:desktop')).toMatchObject({
1459
- consumerId: 'local-agent:desktop',
1460
- detailState: 'pending',
1461
- });
1462
-
1463
- await runtime.close();
1464
- });
1465
-
1466
- it('resumes logical participation without restoring a physical connection', async () => {
1467
- const events = new MemoryEventRepository();
1468
- const history = new MemoryStateHistoryRepository<ClawclawPosition>();
1469
- const first = new Runtime({
1470
- adapterId: 'clawclaw',
1471
- accountId: 'account-1',
1472
- eventCatalog: createClawclawEventCatalog(),
1473
- eventRepository: events,
1474
- stateHistoryRepository: history,
1475
- resumeKey: 'room-A',
1476
- initialSegment: { kind: 'room_lobby', identity: 'room-A' },
1477
- });
1478
- const firstScope = first.scope();
1479
- first.bindConnection('clawclaw.room-ws', 'old-connection');
1480
- await first.flush();
1481
-
1482
- const resumed = new Runtime({
1483
- adapterId: 'clawclaw',
1484
- accountId: 'account-1',
1485
- eventCatalog: createClawclawEventCatalog(),
1486
- eventRepository: events,
1487
- stateHistoryRepository: history,
1488
- resume: true,
1489
- resumeKey: 'room-A',
1490
- initialSegment: { kind: 'room_lobby', identity: 'room-A' },
1491
- });
1492
- expect(resumed.scope()).toMatchObject({
1493
- sessionId: firstScope.sessionId,
1494
- segmentId: firstScope.segmentId,
1495
- });
1496
- expect(resumed.readState().stateStatus).toMatchObject({
1497
- status: 'unavailable',
1498
- connectionId: null,
1499
- });
1500
- expect(history.getScope(resumed.scope())?.historyComplete).toBe(false);
1501
- resumed.bindConnection('clawclaw.room-ws', 'new-connection');
1502
- await resumed.flush();
1503
- expect(history.query({ scope: resumed.scope(), limit: 20 }).records).toMatchObject([
1504
- { kind: 'stream_gap_started', attributes: { reason: 'owner_restart' } },
1505
- { kind: 'stream_gap_ended', connectionId: 'new-connection', attributes: { reason: 'owner_restart' } },
1506
- ]);
1507
- await first.close();
1508
- await resumed.close();
1509
- });
1510
-
1511
- it('resumes an unsealed room game by current game id and keeps unread Events pending', async () => {
1512
- const events = new MemoryEventRepository();
1513
- const history = new MemoryStateHistoryRepository<ClawclawPosition>();
1514
- const first = new Runtime({
1515
- adapterId: 'clawclaw',
1516
- accountId: 'account-room-game-restart',
1517
- eventCatalog: createClawclawEventCatalog(),
1518
- eventRepository: events,
1519
- stateHistoryRepository: history,
1520
- resumeKey: 'room-A',
1521
- initialSegment: { kind: 'room', identity: 'room-A' },
1522
- });
1523
- await first.activateSegment('game', 'game-A1');
1524
- const originalScope = first.scope();
1525
- first.bindConnection(CLAWCLAW_GAME_WS_SOURCE.sourceId, 'before-owner-restart');
1526
- await submitTestInput(first, testInputBatch(
1527
- originalScope,
1528
- CLAWCLAW_GAME_WS_SOURCE,
1529
- 'event',
1530
- { type: 'task_completed', task_name: 'wires' },
1531
- {
1532
- connectionId: 'before-owner-restart',
1533
- sourceSeq: 1,
1534
- sourceEventId: 'unread-before-owner-restart',
1535
- },
1536
- ));
1537
- const resumed = new Runtime({
1538
- adapterId: 'clawclaw',
1539
- accountId: 'account-room-game-restart',
1540
- eventCatalog: createClawclawEventCatalog(),
1541
- eventRepository: events,
1542
- stateHistoryRepository: history,
1543
- resume: true,
1544
- // Lobby /queue/status omits room_code while a room game is allocated.
1545
- // The authoritative game id therefore matches the current game segment.
1546
- initialSegment: { kind: 'game', identity: 'game-A1' },
1547
- });
1548
- expect(resumed.scope()).toMatchObject(originalScope);
1549
-
1550
- resumed.bindConnection(CLAWCLAW_GAME_WS_SOURCE.sourceId, 'after-owner-restart');
1551
- await submitTestInput(resumed, testInputBatch(
1552
- resumed.scope(),
1553
- CLAWCLAW_GAME_WS_SOURCE,
1554
- 'state',
1555
- { tick: 2, phase: 'wandering' },
1556
- { connectionId: 'after-owner-restart', sourceSeq: 2 },
1557
- ));
1558
- events.ensureDeliveries(resumed.scope().sessionId, DEFAULT_EVENT_CONSUMER_ID);
1559
- expect(events.listEvents({
1560
- sessionId: resumed.scope().sessionId,
1561
- types: ['task_completed'],
1562
- detailStates: ['pending'],
1563
- }, DEFAULT_EVENT_CONSUMER_ID).map((row) => row.event)).toMatchObject([
1564
- { type: 'task_completed', payload: { task_name: 'wires' } },
1565
- ]);
1566
-
1567
- await first.close();
1568
- await resumed.close();
1569
- });
1570
-
1571
- it('persists an adopted authoritative resume key and mode, then resumes only an exact match', async () => {
1572
- const events = new MemoryEventRepository();
1573
- const history = new MemoryStateHistoryRepository<ClawclawPosition>();
1574
- const first = new Runtime({
1575
- adapterId: 'clawclaw',
1576
- accountId: 'account-1',
1577
- eventCatalog: createClawclawEventCatalog(),
1578
- eventRepository: events,
1579
- stateHistoryRepository: history,
1580
- mode: 'match',
1581
- initialSegment: { kind: 'queue' },
1582
- });
1583
- first.adoptResumeKey('game-1');
1584
- await first.activateSegment('game', 'game-1');
1585
-
1586
- expect(events.currentScope({ adapterId: 'clawclaw', accountId: 'account-1' })?.session)
1587
- .toMatchObject({ resumeKey: 'game-1', mode: 'match' });
1588
-
1589
- const resumed = new Runtime({
1590
- adapterId: 'clawclaw',
1591
- accountId: 'account-1',
1592
- eventCatalog: createClawclawEventCatalog(),
1593
- eventRepository: events,
1594
- stateHistoryRepository: history,
1595
- resume: true,
1596
- resumeKey: 'game-1',
1597
- mode: 'match',
1598
- initialSegment: { kind: 'game', identity: 'game-1' },
1599
- });
1600
- expect(resumed.scope().sessionId).toBe(first.scope().sessionId);
1601
-
1602
- const mismatch = new Runtime({
1603
- adapterId: 'clawclaw',
1604
- accountId: 'account-1',
1605
- eventCatalog: createClawclawEventCatalog(),
1606
- eventRepository: events,
1607
- stateHistoryRepository: history,
1608
- resume: true,
1609
- resumeKey: 'game-2',
1610
- mode: 'match',
1611
- initialSegment: { kind: 'game', identity: 'game-2' },
1612
- });
1613
- expect(mismatch.scope().sessionId).not.toBe(resumed.scope().sessionId);
1614
-
1615
- await first.close();
1616
- await resumed.close();
1617
- await mismatch.close();
1618
- });
1619
-
1620
- it('does not attach a keyed resume request to an anonymous durable queue session', async () => {
1621
- const events = new MemoryEventRepository();
1622
- const history = new MemoryStateHistoryRepository<ClawclawPosition>();
1623
- const anonymous = new Runtime({
1624
- adapterId: 'clawclaw',
1625
- accountId: 'account-1',
1626
- eventCatalog: createClawclawEventCatalog(),
1627
- eventRepository: events,
1628
- stateHistoryRepository: history,
1629
- initialSegment: { kind: 'queue' },
1630
- });
1631
- const keyed = new Runtime({
1632
- adapterId: 'clawclaw',
1633
- accountId: 'account-1',
1634
- eventCatalog: createClawclawEventCatalog(),
1635
- eventRepository: events,
1636
- stateHistoryRepository: history,
1637
- resume: true,
1638
- resumeKey: 'game-1',
1639
- initialSegment: { kind: 'game', identity: 'game-1' },
1640
- });
1641
-
1642
- expect(keyed.scope().sessionId).not.toBe(anonymous.scope().sessionId);
1643
- expect(events.currentScope({ adapterId: 'clawclaw', accountId: 'account-1' })?.session.resumeKey)
1644
- .toBe('game-1');
1645
- await anonymous.close();
1646
- await keyed.close();
1647
- });
1648
-
1649
- it('keeps on-change Game State fresh from connection liveness, not snapshot age', async () => {
1650
- const events = new MemoryEventRepository();
1651
- const history = new MemoryStateHistoryRepository<ClawclawPosition>();
1652
- const runtime = createClawclawRuntime({
1653
- apiKey: 'test-key',
1654
- runtimeAccountId: 'acct_0123456789abcdef0123456789abcdef',
1655
- }, {
1656
- eventRepository: events,
1657
- stateHistoryRepository: history,
1658
- durableStateSnapshot: false,
1659
- initialSegment: { kind: 'game', identity: 'game-1' },
1660
- });
1661
- const scope = runtime.scope();
1662
- const connectionId = 'game-ws-1';
1663
- const receivedAtMs = 1_000;
1664
- runtime.bindConnection(CLAWCLAW_GAME_WS_SOURCE.sourceId, connectionId, receivedAtMs);
1665
- await submitTestInput(runtime, testInputBatch(
1666
- scope,
1667
- CLAWCLAW_GAME_WS_SOURCE,
1668
- 'state',
1669
- { tick: 1 },
1670
- { connectionId, receivedAt: new Date(receivedAtMs).toISOString() },
1671
- ));
1672
-
1673
- expect(runtime.readState(receivedAtMs + CLAWCLAW_GAME_LIVENESS_SILENCE_MS)).toMatchObject({
1674
- stateStatus: { status: 'fresh' },
1675
- });
1676
- expect(runtime.readState(receivedAtMs + CLAWCLAW_GAME_LIVENESS_SILENCE_MS + 1)).toMatchObject({
1677
- stateStatus: { status: 'stale', reason: 'liveness_timeout' },
1678
- });
1679
-
1680
- const muchLater = 100_000;
1681
- expect(runtime.connectionLiveness(CLAWCLAW_GAME_WS_SOURCE.sourceId, connectionId, muchLater)).toBe(true);
1682
- expect(runtime.readState(muchLater)).toMatchObject({
1683
- stateStatus: { status: 'fresh' },
1684
- });
1685
- await runtime.close();
1686
-
1687
- const custom = createClawclawRuntime({
1688
- apiKey: 'custom-key',
1689
- runtimeAccountId: 'acct_fedcba9876543210fedcba9876543210',
1690
- }, {
1691
- eventRepository: new MemoryEventRepository(),
1692
- stateHistoryRepository: new MemoryStateHistoryRepository<ClawclawPosition>(),
1693
- durableStateSnapshot: false,
1694
- stateFreshnessPolicy: { maxStateSilenceMs: 5_000 },
1695
- initialSegment: { kind: 'game', identity: 'game-2' },
1696
- });
1697
- const customScope = custom.scope();
1698
- custom.bindConnection(CLAWCLAW_GAME_WS_SOURCE.sourceId, connectionId, receivedAtMs);
1699
- await submitTestInput(custom, testInputBatch(
1700
- customScope,
1701
- CLAWCLAW_GAME_WS_SOURCE,
1702
- 'state',
1703
- { tick: 1 },
1704
- { connectionId, receivedAt: new Date(receivedAtMs).toISOString() },
1705
- ));
1706
- expect(custom.readState(receivedAtMs + 5_001)).toMatchObject({
1707
- stateStatus: { status: 'fresh' },
1708
- });
1709
- await custom.close();
1710
- });
1711
-
1712
- it('freezes Behavior Event declarations into the catalog before building the plugin graph', async () => {
1713
- const behaviorPlugin: RuntimeEpochPlugin<Record<string, any>> = {
1714
- kind: 'epoch',
1715
- id: 'test.behavior-events',
1716
- version: '1',
1717
- produces: { events: ['strategy.runtime_declared'] },
1718
- update: () => ({ outcome: 'noop' }),
1719
- };
1720
- const runtime = createClawclawRuntime({
1721
- apiKey: 'behavior-event-key',
1722
- runtimeAccountId: 'acct_bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb',
1723
- }, {
1724
- eventRepository: new MemoryEventRepository(),
1725
- stateHistoryRepository: new MemoryStateHistoryRepository<ClawclawPosition>(),
1726
- durableStateSnapshot: false,
1727
- initialSegment: { kind: 'game', identity: 'game-behavior-event' },
1728
- runtimeEpochPlugins: [behaviorPlugin],
1729
- behaviorEventTypes: ['strategy.runtime_declared'],
1730
- });
1731
-
1732
- await runtime.close();
1733
- });
1734
-
1735
- it('keeps on-change room State fresh from connection liveness, not snapshot age', async () => {
1736
- const runtime = createClawclawRuntime({
1737
- apiKey: 'room-key',
1738
- runtimeAccountId: 'acct_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
1739
- }, {
1740
- eventRepository: new MemoryEventRepository(),
1741
- stateHistoryRepository: new MemoryStateHistoryRepository<ClawclawPosition>(),
1742
- durableStateSnapshot: false,
1743
- initialSegment: { kind: 'room_lobby', identity: 'R1' },
1744
- });
1745
- const scope = runtime.scope();
1746
- runtime.bindConnection(CLAWCLAW_ROOM_WS_SOURCE.sourceId, 'room-c1', 1_000);
1747
- await submitTestInput(runtime, testInputBatch(
1748
- scope,
1749
- CLAWCLAW_ROOM_WS_SOURCE,
1750
- 'state',
1751
- { phase: 'room_waiting', room: { room_code: 'R1' } },
1752
- { connectionId: 'room-c1', receivedAt: new Date(1_100).toISOString() },
1753
- ));
1754
-
1755
- const muchLater = 100_000;
1756
- expect(muchLater - 1_100).toBeGreaterThan(CLAWCLAW_GAME_LIVENESS_SILENCE_MS);
1757
- expect(runtime.connectionLiveness(CLAWCLAW_ROOM_WS_SOURCE.sourceId, 'room-c1', muchLater)).toBe(true);
1758
- expect(runtime.readState(muchLater)).toMatchObject({
1759
- state: { phase: 'room_waiting', room: { room_code: 'R1' } },
1760
- stateStatus: { status: 'fresh' },
1761
- });
1762
-
1763
- runtime.connectionChanged(CLAWCLAW_ROOM_WS_SOURCE.sourceId, 'room-c1', 'reconnecting', muchLater + 1);
1764
- expect(runtime.readState(muchLater + 2)).toMatchObject({
1765
- stateStatus: { status: 'stale', reason: 'connection_reconnecting' },
1766
- });
1767
- expect(runtime.connectionScope(CLAWCLAW_ROOM_WS_SOURCE.sourceId, 'room-c1')).not.toBeNull();
1768
- await runtime.close();
1769
- });
1770
- });