@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,2646 +0,0 @@
1
- import { describe, expect, it, vi } from 'vitest';
2
- import { ApiError } from '../../../../lib/http-transport.js';
3
- import { presentCanonicalEvent } from '../../../../pipeline/canonical-event-presentation.js';
4
- import { jsonTransportResponse } from '../../../../short-command/transport-response.js';
5
- import { createClawclawEventCatalog } from '../../../clawclaw-event-catalog.js';
6
- import { projectClawclawCurrentState } from '../../runtime-state.js';
7
- import { MemoryEventRepository } from '../../../framework/events/index.js';
8
- import { Runtime } from '../../../framework/runtime.js';
9
- import { MemoryStateHistoryRepository } from '../../../framework/state/index.js';
10
- import { ClawclawMailboxService } from '../mailbox/mailbox-service.js';
11
- import type {
12
- WsCloseInfo,
13
- WsInputFrame,
14
- WsProtocolErrorInfo,
15
- WsRecoveryStartedInfo,
16
- } from '../../../ws-client.js';
17
- import type {
18
- ClawclawGameTransportOptions,
19
- ClawclawGameTransportOutcome,
20
- ClawclawGameTransportPort,
21
- ClawclawGameTransportStopReason,
22
- } from './game-transport.js';
23
- import type {
24
- ClawclawRoomTransportOptions,
25
- ClawclawRoomTransportOutcome,
26
- ClawclawRoomTransportPort,
27
- ClawclawRoomTransportStopReason,
28
- } from './room-transport.js';
29
- import { ClawclawSourcePlugin } from './source-plugin.js';
30
- import type { ClawclawSourcePluginOptions } from './source-plugin.js';
31
- import type { ClawclawSourceClient, ClawclawSourceStartIntent } from './types.js';
32
- import { CLAWCLAW_GAME_WS_SOURCE } from './source-transports.js';
33
-
34
- class FakeClient implements ClawclawSourceClient {
35
- wsConnected = false;
36
- wsConnectionActive = false;
37
- wsConnectionId: string | null = null;
38
- lobbyAgentWsUrl = 'wss://lobby.test/agent/ws';
39
- readonly setRoomGameServer = vi.fn<(name: string) => void>();
40
- readonly setGameServerUrl = vi.fn<(url: string) => void>();
41
- readonly setExpectedGameSyncGameId = vi.fn<(gameId: string | undefined) => void>();
42
- readonly joinQueue = vi.fn(async () => ({ status: 'queued', mode: 'match' }));
43
- readonly getCompetitionStatus = vi.fn(async () => ({
44
- id: 'competition-1',
45
- is_open: false,
46
- daily_windows: ['20:00-22:00'],
47
- }));
48
- readonly leaveQueue = vi.fn(async () => ({ success: true }));
49
- readonly leaveGame = vi.fn(async (): Promise<any> => ({ success: true }));
50
- readonly createRoom = vi.fn(async (_options?: import('../../../../lib/room.js').CreateRoomOptions): Promise<any> => ({ room_code: 'R1' }));
51
- readonly joinRoom = vi.fn(async (
52
- roomCode: string,
53
- _metadata?: import('../../../../lib/room.js').RoomEntryMetadata,
54
- ) => ({ room_code: roomCode }));
55
- readonly leaveRoom = vi.fn(async () => ({ success: true }));
56
- readonly startRoom = vi.fn(async () => ({ success: true }));
57
- readonly setTrainingRoomMode = vi.fn(async (roomType: import('../../../../lib/room.js').TrainingRoomType) => ({
58
- room_code: 'R1',
59
- room_type: roomType,
60
- role_config: null,
61
- }));
62
- readonly setTrainingRoleLock = vi.fn(async (characterId: number) => ({
63
- room_code: 'R1',
64
- room_type: 'training_simulation',
65
- role_config: { self: characterId },
66
- }));
67
- readonly clearTrainingRoleLock = vi.fn(async () => ({
68
- room_code: 'R1',
69
- room_type: 'training_simulation',
70
- }));
71
- readonly discoverGameServer = vi.fn(async () => true);
72
- readonly connectWs = vi.fn(async () => true);
73
- readonly reconnectWsToGameServer = vi.fn(async () => {});
74
- readonly disconnectWs = vi.fn((_options?: { preserveGameSyncResumeState?: boolean }) => {});
75
- readonly acknowledgeGameSync = vi.fn((_ackToken: string, _immediate?: boolean) => {});
76
- queueStatusReads = 0;
77
- private readonly queueResponses: Array<Record<string, any> | Error>;
78
- private lastQueue: Record<string, any> = { status: 'not_in_queue' };
79
-
80
- constructor(queueResponses: Array<Record<string, any> | Error>) {
81
- this.queueResponses = [...queueResponses];
82
- }
83
-
84
- async getQueueStatus(): Promise<any> {
85
- this.queueStatusReads += 1;
86
- const next = this.queueResponses.shift();
87
- if (next instanceof Error) throw next;
88
- if (next) this.lastQueue = structuredClone(next);
89
- return structuredClone(this.lastQueue);
90
- }
91
-
92
- onInputFrame(_handler: (frame: WsInputFrame) => void): () => void { return () => {}; }
93
- onWsConnectionOpened(_handler: (connectionId: string) => void): () => void { return () => {}; }
94
- onWsLiveness(_handler: (connectionId: string, atMs: number) => void): () => void { return () => {}; }
95
- onWsClose(_handler: (info: WsCloseInfo) => void): () => void { return () => {}; }
96
- onWsProtocolError(_handler: (info: WsProtocolErrorInfo) => void): () => void { return () => {}; }
97
- onWsRecoveryStarted(_handler: (info: WsRecoveryStartedInfo) => void): () => void { return () => {}; }
98
- }
99
-
100
- class FakeGameTransport implements ClawclawGameTransportPort {
101
- private readonly outcome: Promise<ClawclawGameTransportOutcome>;
102
- private resolveOutcome!: (outcome: ClawclawGameTransportOutcome) => void;
103
- private firstState?: Record<string, any>;
104
- private resolveFirstState?: (state: Record<string, any>) => void;
105
- private rejectFirstState?: (error: Error) => void;
106
- private firstStateTimer?: ReturnType<typeof setTimeout>;
107
- stoppedWith?: ClawclawGameTransportStopReason;
108
-
109
- constructor(readonly options: ClawclawGameTransportOptions, readonly connectionId: string) {
110
- this.outcome = new Promise((resolve) => { this.resolveOutcome = resolve; });
111
- }
112
-
113
- async start(): Promise<void> {
114
- await this.options.onConnectionOpened(this.connectionId, false);
115
- }
116
-
117
- waitForOutcome(): Promise<ClawclawGameTransportOutcome> { return this.outcome; }
118
-
119
- waitForFirstState(options: { timeoutMs?: number; signal?: AbortSignal } = {}): Promise<Record<string, any>> {
120
- if (this.firstState) return Promise.resolve(structuredClone(this.firstState));
121
- return new Promise((resolve, reject) => {
122
- this.resolveFirstState = (state) => {
123
- if (this.firstStateTimer) clearTimeout(this.firstStateTimer);
124
- resolve(state);
125
- };
126
- this.rejectFirstState = reject;
127
- if (options.timeoutMs !== undefined) {
128
- this.firstStateTimer = setTimeout(() => {
129
- reject(new Error(`Timed out waiting ${options.timeoutMs}ms for first State.`));
130
- }, options.timeoutMs);
131
- }
132
- if (options.signal) {
133
- options.signal.addEventListener('abort', () => reject(new Error('aborted')), { once: true });
134
- }
135
- });
136
- }
137
-
138
- async emit(frame: WsInputFrame): Promise<void> {
139
- const reason = await this.options.onFrame(frame);
140
- if (frame.kind === 'state' && !this.firstState) {
141
- this.firstState = structuredClone(frame.state);
142
- this.resolveFirstState?.(structuredClone(frame.state));
143
- }
144
- if (reason) this.resolveOutcome({ reason });
145
- }
146
-
147
- async startRecovery(info: WsRecoveryStartedInfo): Promise<void> {
148
- await this.options.onRecoveryStarted?.(info);
149
- }
150
-
151
- async flush(): Promise<void> {}
152
-
153
- async close(info: WsCloseInfo): Promise<void> {
154
- const reason = await this.options.onClose(this.connectionId, info);
155
- if (reason) this.resolveOutcome({ reason });
156
- }
157
-
158
- async stop(reason: ClawclawGameTransportStopReason = 'manual'): Promise<void> {
159
- this.stoppedWith = reason;
160
- if (this.firstStateTimer) clearTimeout(this.firstStateTimer);
161
- this.rejectFirstState?.(new Error(`stopped: ${reason}`));
162
- this.resolveOutcome({ reason });
163
- }
164
- }
165
-
166
- class FakeRoomTransport implements ClawclawRoomTransportPort {
167
- private readonly outcome: Promise<ClawclawRoomTransportOutcome>;
168
- private resolveOutcome!: (outcome: ClawclawRoomTransportOutcome) => void;
169
- private currentSnapshot: Record<string, any> | null = null;
170
-
171
- constructor(readonly options: ClawclawRoomTransportOptions, readonly connectionId: string) {
172
- this.outcome = new Promise((resolve) => { this.resolveOutcome = resolve; });
173
- }
174
-
175
- async start(): Promise<void> {
176
- await this.options.onOpened(this.connectionId, false);
177
- }
178
-
179
- snapshot(): Record<string, any> | null {
180
- return this.currentSnapshot ? structuredClone(this.currentSnapshot) : null;
181
- }
182
-
183
- waitForOutcome(): Promise<ClawclawRoomTransportOutcome> { return this.outcome; }
184
-
185
- async emit(
186
- type: string,
187
- data: Record<string, any>,
188
- snapshot: Record<string, any> | null,
189
- sourceSeq: number,
190
- ): Promise<void> {
191
- this.currentSnapshot = snapshot ? structuredClone(snapshot) : null;
192
- await this.options.onFrame({
193
- type,
194
- data,
195
- snapshot,
196
- terminalPhase: type === 'room.self_left' ? 'room_left' : undefined,
197
- meta: {
198
- connectionId: this.connectionId,
199
- receivedAt: new Date(sourceSeq * 100).toISOString(),
200
- sourceSeq,
201
- replay: type === 'room.snapshot',
202
- },
203
- });
204
- if (type === 'room.game_started') {
205
- this.resolveOutcome({
206
- reason: 'game_started',
207
- event: data,
208
- roomCode: snapshot?.room_code,
209
- });
210
- } else if (type === 'room.self_left') {
211
- this.resolveOutcome({ reason: 'self_left' });
212
- }
213
- }
214
-
215
- async flush(): Promise<void> {}
216
-
217
- async close(info: { code?: number; reason: string }): Promise<void> {
218
- await this.options.onConnectionChanged(this.connectionId, 'reconnecting');
219
- const decision = await this.options.onClosed(this.connectionId, info);
220
- if (decision !== 'retry') this.resolveOutcome({ reason: decision });
221
- }
222
-
223
- async stop(reason: ClawclawRoomTransportStopReason = 'manual'): Promise<void> {
224
- this.resolveOutcome(reason === 'game_started'
225
- ? { reason, event: {}, roomCode: this.currentSnapshot?.room_code }
226
- : { reason });
227
- }
228
- }
229
-
230
- async function waitUntil(predicate: () => boolean, message: string): Promise<void> {
231
- for (let attempt = 0; attempt < 100; attempt += 1) {
232
- if (predicate()) return;
233
- await new Promise((resolve) => setTimeout(resolve, 0));
234
- }
235
- throw new Error(message);
236
- }
237
-
238
- async function fixture(
239
- queueResponses: Array<Record<string, any> | Error>,
240
- intent: ClawclawSourceStartIntent = { kind: 'resume' },
241
- options: {
242
- configureClient?: (client: FakeClient) => void;
243
- source?: Partial<Omit<ClawclawSourcePluginOptions, 'client' | 'profile' | 'initialIntent' | 'transports'>>;
244
- sleepDelays?: number[];
245
- } = {},
246
- ) {
247
- const events = new MemoryEventRepository();
248
- const runtime = new Runtime({
249
- adapterId: 'clawclaw',
250
- accountId: 'account-1',
251
- eventCatalog: createClawclawEventCatalog(),
252
- eventRepository: events,
253
- stateHistoryRepository: new MemoryStateHistoryRepository(),
254
- currentStateFromRuntimeState: projectClawclawCurrentState,
255
- initialSegment: { kind: 'bootstrap' },
256
- });
257
- const client = new FakeClient(queueResponses);
258
- options.configureClient?.(client);
259
- const games: FakeGameTransport[] = [];
260
- const rooms: FakeRoomTransport[] = [];
261
- const source = new ClawclawSourcePlugin({
262
- client,
263
- profile: { apiKey: 'test-key', agentName: 'me' },
264
- initialIntent: intent,
265
- ...options.source,
266
- sleep: options.source?.sleep ?? (async (ms) => { options.sleepDelays?.push(ms); }),
267
- transports: {
268
- game: (options) => {
269
- const transport = new FakeGameTransport(options, `game-${games.length + 1}`);
270
- games.push(transport);
271
- return transport;
272
- },
273
- room: (options) => {
274
- const transport = new FakeRoomTransport(options, `room-${rooms.length + 1}`);
275
- rooms.push(transport);
276
- return transport;
277
- },
278
- },
279
- });
280
- await runtime.startSourcePlugin(source);
281
- return { runtime, events, client, source, games, rooms };
282
- }
283
-
284
- function gameStateFrame(
285
- connectionId: string,
286
- sourceSeq: number,
287
- state: Record<string, any>,
288
- events: Record<string, any>[] = [],
289
- ): WsInputFrame {
290
- return {
291
- kind: 'state',
292
- state,
293
- events,
294
- meta: {
295
- connectionId,
296
- sourceSeq,
297
- origin: 'update',
298
- receivedAt: new Date(sourceSeq * 100).toISOString(),
299
- gameId: 'G1',
300
- domainTick: Number(state.tick ?? sourceSeq),
301
- replayed: false,
302
- ackToken: `ack:${connectionId}:${sourceSeq}`,
303
- },
304
- };
305
- }
306
-
307
- const maintenanceWindow = {
308
- starts_at: '2026-08-05T01:00:00+00:00',
309
- ends_at: '2026-08-05T03:00:00+00:00',
310
- description: '本次维护将升级匹配服务。',
311
- };
312
-
313
- function maintenanceApiError(method = 'GET', path = '/api/v1/queue/status'): ApiError {
314
- const payload = {
315
- success: false,
316
- error: { code: 'SERVICE_MAINTENANCE', message: 'Service is under maintenance' },
317
- server: { service_status: 'maintenance_active', maintenance: maintenanceWindow },
318
- };
319
- const response = jsonTransportResponse(payload, {
320
- method,
321
- path,
322
- status: 503,
323
- headers: { 'content-type': 'application/json', 'retry-after': '7200' },
324
- });
325
- return new ApiError(503, response.body.rawText, method, path, response);
326
- }
327
-
328
- describe('ClawclawSourcePlugin lifecycle', () => {
329
- it('delivers upcoming maintenance through the canonical Mailbox path without blocking room creation', async () => {
330
- const { runtime, events, client, source, rooms } = await fixture(
331
- [{ status: 'not_in_queue' }],
332
- { kind: 'create_room' },
333
- {
334
- configureClient: (fake) => {
335
- fake.createRoom.mockResolvedValue({
336
- success: true,
337
- data: { room_code: 'R1' },
338
- server: {
339
- service_status: 'maintenance_upcoming',
340
- maintenance: maintenanceWindow,
341
- },
342
- });
343
- },
344
- },
345
- );
346
- await waitUntil(() => rooms.length === 1, 'Room transport was not started.');
347
- await rooms[0].emit('service_status', {
348
- service_status: 'maintenance_upcoming',
349
- maintenance: maintenanceWindow,
350
- }, {
351
- room_code: 'R1',
352
- status: 'waiting',
353
- members: [],
354
- }, 1);
355
- await runtime.flush();
356
-
357
- expect(client.createRoom).toHaveBeenCalledOnce();
358
- const committed = runtime.repository.listCommittedEvents({
359
- sessionId: runtime.scope().sessionId,
360
- types: ['service_status'],
361
- });
362
- expect(committed).toHaveLength(1);
363
- expect(committed[0]).toMatchObject({
364
- type: 'service_status',
365
- producer: 'backend_push',
366
- deliveryClass: 'monitor_and_events',
367
- payload: {
368
- service_status: 'maintenance_upcoming',
369
- maintenance: maintenanceWindow,
370
- },
371
- });
372
- const mailbox = new ClawclawMailboxService({
373
- repository: events,
374
- readyView: () => runtime.readReadyView(),
375
- });
376
- const delivered = mailbox.prepareEvents({ eventType: 'service_status' }).output.event as Record<string, any>;
377
- expect(delivered).toMatchObject({
378
- type: 'service_status',
379
- service_status: 'maintenance_upcoming',
380
- maintenance: maintenanceWindow,
381
- });
382
- expect(delivered.hint).toContain('current request succeeded');
383
-
384
- await source.stop();
385
- await runtime.close();
386
- });
387
-
388
- it('treats the documented Lobby WebSocket maintenance close as terminal', async () => {
389
- const { runtime, source, rooms } = await fixture([{
390
- status: 'in_room', mode: 'room', room_code: 'R1',
391
- }]);
392
- await waitUntil(() => rooms.length === 1, 'Room transport was not started.');
393
- await rooms[0].emit('service_status', {
394
- service_status: 'maintenance_active',
395
- maintenance: maintenanceWindow,
396
- }, null, 1);
397
- await rooms[0].close({ code: 4006, reason: 'SERVICE_MAINTENANCE' });
398
-
399
- await expect(source.waitForCompletion()).resolves.toEqual({ reason: 'maintenance' });
400
- await runtime.flush();
401
- expect(runtime.repository.listCommittedEvents({
402
- sessionId: runtime.scope().sessionId,
403
- types: ['service_status'],
404
- })).toHaveLength(1);
405
- await runtime.close();
406
- });
407
-
408
- it('stops immediately on active maintenance without poll_error retries', async () => {
409
- const maintenanceError = maintenanceApiError();
410
- const { runtime, client, source } = await fixture([maintenanceError], { kind: 'match' });
411
-
412
- await expect(source.waitForCompletion()).resolves.toMatchObject({
413
- reason: 'maintenance',
414
- error: maintenanceError,
415
- });
416
- await runtime.flush();
417
-
418
- expect(client.queueStatusReads).toBe(1);
419
- expect(runtime.repository.listCommittedEvents({
420
- sessionId: runtime.scope().sessionId,
421
- types: ['service_status'],
422
- })).toMatchObject([{
423
- type: 'service_status',
424
- producer: 'backend_push',
425
- payload: {
426
- service_status: 'maintenance_active',
427
- maintenance: maintenanceWindow,
428
- retry_after_seconds: 7200,
429
- },
430
- }]);
431
- expect(runtime.repository.listCommittedEvents({
432
- sessionId: runtime.scope().sessionId,
433
- types: ['poll_error', 'error'],
434
- })).toHaveLength(0);
435
- await runtime.close();
436
- });
437
-
438
- it('does not reconcile a queue join rejected by active maintenance', async () => {
439
- const maintenanceError = maintenanceApiError('POST', '/api/v1/queue/join');
440
- const { runtime, client, source } = await fixture(
441
- [{ status: 'not_in_queue' }],
442
- { kind: 'match' },
443
- { configureClient: (fake) => fake.joinQueue.mockRejectedValue(maintenanceError) },
444
- );
445
-
446
- await expect(source.waitForCompletion()).resolves.toMatchObject({ reason: 'maintenance' });
447
- await runtime.flush();
448
- expect(client.queueStatusReads).toBe(1);
449
- expect(runtime.repository.listCommittedEvents({
450
- sessionId: runtime.scope().sessionId,
451
- types: ['service_status'],
452
- })).toHaveLength(1);
453
- await runtime.close();
454
- });
455
-
456
- it('consumes the Owner queue observation without issuing a second startup poll', async () => {
457
- const initialQueueState = {
458
- status: 'allocated', mode: 'match', game_id: 'G-preflight', ws_url: 'wss://game.test/ws',
459
- };
460
- const { runtime, client, source, games } = await fixture([], { kind: 'resume' }, {
461
- source: { initialQueueState },
462
- });
463
- await waitUntil(() => games.length === 1, 'Game transport was not started.');
464
-
465
- expect(client.queueStatusReads).toBe(0);
466
- expect(client.setExpectedGameSyncGameId).toHaveBeenCalledWith('G-preflight');
467
-
468
- await source.stop();
469
- await runtime.close();
470
- });
471
-
472
- it('binds the GameSync resume baseline to the allocated game id', async () => {
473
- const { runtime, client, source, games } = await fixture([{
474
- status: 'allocated', mode: 'match', game_id: 'G1', ws_url: 'wss://game.test/ws',
475
- }]);
476
- await waitUntil(() => games.length === 1, 'Game transport was not started.');
477
-
478
- expect(client.setExpectedGameSyncGameId).toHaveBeenCalledWith('G1');
479
-
480
- await source.stop();
481
- await runtime.close();
482
- });
483
-
484
- it('treats GAME_SYNC_REPLACED as a genuine replacement', async () => {
485
- const { runtime, source, games } = await fixture([{
486
- status: 'allocated', mode: 'match', game_id: 'G1', ws_url: 'wss://game.test/ws',
487
- }]);
488
- await waitUntil(() => games.length === 1, 'Game transport was not started.');
489
-
490
- await games[0].close({ code: 4002, reason: 'GAME_SYNC_REPLACED' });
491
-
492
- await expect(source.waitForCompletion()).resolves.toEqual({ reason: 'replaced' });
493
- await runtime.close();
494
- });
495
-
496
- it('treats origin/dev PROTOCOL_CONFLICT as an error rather than replacement', async () => {
497
- const { runtime, source, games } = await fixture([{
498
- status: 'allocated', mode: 'match', game_id: 'G1', ws_url: 'wss://game.test/ws',
499
- }]);
500
- await waitUntil(() => games.length === 1, 'Game transport was not started.');
501
-
502
- await games[0].close({ code: 4002, reason: 'PROTOCOL_CONFLICT' });
503
-
504
- await expect(source.waitForCompletion()).resolves.toMatchObject({ reason: 'error' });
505
- await runtime.flush();
506
- expect(runtime.repository.latestEventByType(
507
- runtime.scope().sessionId,
508
- 'game_stream_disconnected',
509
- runtime.scope().segmentId,
510
- )?.payload).toMatchObject({
511
- close_code: 4002,
512
- close_reason: 'PROTOCOL_CONFLICT',
513
- recoverable: false,
514
- });
515
- await runtime.close();
516
- });
517
-
518
- it('marks WebSocket protocol closes as non-recoverable', async () => {
519
- const { runtime, source, games } = await fixture([{
520
- status: 'allocated', mode: 'match', game_id: 'G1', ws_url: 'wss://game.test/ws',
521
- }]);
522
- await waitUntil(() => games.length === 1, 'Game transport was not started.');
523
-
524
- await games[0].close({ code: 1002, reason: 'invalid frame' });
525
-
526
- await expect(source.waitForCompletion()).resolves.toMatchObject({ reason: 'error' });
527
- await runtime.flush();
528
- expect(runtime.repository.latestEventByType(
529
- runtime.scope().sessionId,
530
- 'game_stream_disconnected',
531
- runtime.scope().segmentId,
532
- )?.payload).toMatchObject({
533
- close_code: 1002,
534
- recoverable: false,
535
- });
536
- const closeEpoch = runtime.inputJournal.list(runtime.scope(), 0, 100)
537
- .find((epoch) => epoch.events.some((event) => event.type === 'game_stream_disconnected'));
538
- expect(closeEpoch?.state).toMatchObject({ connection: 'disconnected' });
539
- await runtime.close();
540
- });
541
-
542
- it('emits the complete lifecycle when a fresh matchmaking request starts', async () => {
543
- const { runtime, source } = await fixture(
544
- [{ status: 'not_in_queue' }, { status: 'not_in_queue' }],
545
- { kind: 'match' },
546
- );
547
-
548
- await expect(source.waitForCompletion()).resolves.toEqual({ reason: 'not_participating' });
549
- await runtime.flush();
550
- expect(runtime.repository.listCommittedEvents({
551
- sessionId: runtime.scope().sessionId,
552
- types: ['joined', 'match_start', 'match_waiting', 'not_in_queue'],
553
- order: 'asc',
554
- }).map((event) => event.type)).toEqual([
555
- 'joined',
556
- 'match_start',
557
- 'match_waiting',
558
- 'not_in_queue',
559
- ]);
560
- await runtime.close();
561
- });
562
-
563
- it('ends a continuously queued Source after the bounded cumulative timeout', async () => {
564
- let now = 0;
565
- const { runtime, source } = await fixture(
566
- [{ status: 'not_in_queue' }, { status: 'queued', mode: 'match' }],
567
- { kind: 'match' },
568
- {
569
- source: {
570
- clock: () => now,
571
- matchTimeoutMs: 1_000,
572
- matchWaitingIntervalMs: 60_000,
573
- sleep: async () => { now = 1_000; },
574
- },
575
- },
576
- );
577
-
578
- await expect(source.waitForCompletion()).resolves.toEqual({ reason: 'match_timeout' });
579
- await runtime.flush();
580
- expect(runtime.repository.listCommittedEvents({
581
- sessionId: runtime.scope().sessionId,
582
- types: ['match_start', 'match_waiting', 'match_timeout'],
583
- order: 'asc',
584
- }).map((event) => event.type)).toEqual([
585
- 'match_start',
586
- 'match_waiting',
587
- 'match_timeout',
588
- ]);
589
- await runtime.close();
590
- });
591
-
592
- it('emits room_created for a newly created room', async () => {
593
- const { runtime, source, rooms, client } = await fixture(
594
- [{ status: 'not_in_queue' }],
595
- { kind: 'create_room', agentType: 'claude-code', llmModel: 'claude-opus-4-8' },
596
- );
597
- await waitUntil(() => rooms.length === 1, 'Created Room transport was not started.');
598
- expect(client.createRoom).toHaveBeenCalledWith({
599
- roomType: undefined,
600
- agentType: 'claude-code',
601
- monitorStatus: undefined,
602
- llmModel: 'claude-opus-4-8',
603
- });
604
- await runtime.flush();
605
- expect(runtime.repository.listCommittedEvents({
606
- sessionId: runtime.scope().sessionId,
607
- types: ['room_created'],
608
- })).toHaveLength(1);
609
-
610
- await source.submitIntent({ kind: 'stop' });
611
- await expect(source.waitForCompletion()).resolves.toEqual({ reason: 'stopped' });
612
- await runtime.close();
613
- });
614
-
615
- it('creates and configures training through the Owner while preserving bot and role projections', async () => {
616
- const members = Array.from({ length: 10 }, (_, index) => ({
617
- seat: index + 1,
618
- agent_id: index === 0 ? 'self' : `bot-${index}`,
619
- name: index === 0 ? 'me' : `Bot ${index}`,
620
- is_owner: index === 0,
621
- is_bot: index > 0,
622
- status: 'online' as const,
623
- }));
624
- const { runtime, source, rooms, client } = await fixture(
625
- [{ status: 'not_in_queue' }],
626
- { kind: 'create_room', roomType: 'training_simulation' },
627
- );
628
- await waitUntil(() => rooms.length === 1, 'Training Room transport was not started.');
629
- expect(client.createRoom).toHaveBeenCalledWith({
630
- roomType: 'training_simulation',
631
- agentType: undefined,
632
- monitorStatus: undefined,
633
- llmModel: undefined,
634
- });
635
-
636
- await rooms[0].emit('room.snapshot', {
637
- room_code: 'R1',
638
- room_type: 'training_simulation',
639
- status: 'waiting',
640
- my_seat: 1,
641
- cooldown_seconds: 0,
642
- members,
643
- }, {
644
- room_code: 'R1',
645
- room_type: 'training_simulation',
646
- status: 'waiting',
647
- my_seat: 1,
648
- cooldown_seconds: 0,
649
- members,
650
- }, 1);
651
-
652
- await source.submitIntent({ kind: 'training_mode', roomType: 'training_dummy' });
653
- client.setTrainingRoleLock.mockResolvedValueOnce({
654
- room_code: 'R1',
655
- room_type: 'training_dummy',
656
- role_config: { self: 7 },
657
- });
658
- await source.submitIntent({ kind: 'training_role_lock', characterId: 7 });
659
- // The backend Room WS currently omits role_config and may carry the
660
- // pre-command snapshot on the next incremental Event. The Owner overlay
661
- // must keep the authoritative REST result visible.
662
- await rooms[0].emit('room.member_status_changed', {
663
- agent_id: 'bot-1',
664
- status: 'offline',
665
- }, {
666
- room_code: 'R1',
667
- room_type: 'training_simulation',
668
- status: 'waiting',
669
- my_seat: 1,
670
- cooldown_seconds: 0,
671
- members: members.map((member) => (
672
- member.agent_id === 'bot-1' ? { ...member, status: 'offline' } : member
673
- )),
674
- }, 2);
675
- await runtime.flush();
676
-
677
- expect(client.setTrainingRoomMode).toHaveBeenCalledWith('training_dummy');
678
- expect(client.setTrainingRoleLock).toHaveBeenCalledWith(7);
679
- const readyState = runtime.readReadyView().state.state!;
680
- expect(readyState).toMatchObject({
681
- phase: 'room_waiting',
682
- you: { is_owner: true },
683
- room: {
684
- room_type: 'training_dummy',
685
- member_count: 10,
686
- ready_to_start: true,
687
- role_config: { self: 7 },
688
- role_lock_character_id: 7,
689
- },
690
- });
691
- expect(readyState.room.members[0]).toMatchObject({ is_bot: false });
692
- expect(readyState.room.members[1]).toMatchObject({
693
- agent_id: 'bot-1',
694
- is_bot: true,
695
- status: 'offline',
696
- });
697
-
698
- await source.submitIntent({ kind: 'training_role_clear' });
699
- expect(client.clearTrainingRoleLock).toHaveBeenCalledOnce();
700
- await runtime.flush();
701
- expect(runtime.readReadyView().state.state?.room?.role_config).toBeNull();
702
- expect(runtime.readReadyView().state.state?.room).not.toHaveProperty('role_lock_character_id');
703
- await source.submitIntent({ kind: 'stop' });
704
- await expect(source.waitForCompletion()).resolves.toEqual({ reason: 'stopped' });
705
- await runtime.close();
706
- });
707
-
708
- it('turns a marked external training mode snapshot into one Agent Event', async () => {
709
- const members = Array.from({ length: 10 }, (_, index) => ({
710
- seat: index + 1,
711
- agent_id: index === 0 ? 'self' : `bot-${index}`,
712
- name: index === 0 ? 'me' : `Bot ${index}`,
713
- is_owner: index === 0,
714
- is_bot: index > 0,
715
- status: 'online' as const,
716
- }));
717
- const { runtime, source, rooms } = await fixture(
718
- [{ status: 'not_in_queue' }],
719
- { kind: 'create_room', roomType: 'training_simulation' },
720
- );
721
- await waitUntil(() => rooms.length === 1, 'Training Room transport was not started.');
722
-
723
- await rooms[0].emit('room.snapshot', {
724
- room_code: 'R1',
725
- room_type: 'training_simulation',
726
- status: 'waiting',
727
- my_seat: 1,
728
- members,
729
- }, {
730
- room_code: 'R1',
731
- room_type: 'training_simulation',
732
- status: 'waiting',
733
- my_seat: 1,
734
- members,
735
- }, 1);
736
- await rooms[0].emit('room.snapshot', {
737
- room_code: 'R1',
738
- room_type: 'training_dummy',
739
- status: 'waiting',
740
- my_seat: 1,
741
- members,
742
- sync_reason: 'room_type_changed',
743
- }, {
744
- room_code: 'R1',
745
- room_type: 'training_dummy',
746
- status: 'waiting',
747
- my_seat: 1,
748
- members,
749
- sync_reason: 'room_type_changed',
750
- }, 2);
751
- await runtime.flush();
752
-
753
- const changes = runtime.repository.listCommittedEvents({
754
- sessionId: runtime.scope().sessionId,
755
- types: ['room.type_changed'],
756
- order: 'asc',
757
- });
758
- expect(changes).toHaveLength(1);
759
- expect(changes[0]?.payload).toEqual({
760
- room_code: 'R1',
761
- previous_room_type: 'training_simulation',
762
- room_type: 'training_dummy',
763
- sync_reason: 'room_type_changed',
764
- });
765
- expect(runtime.readReadyView().state.state?.room?.room_type).toBe('training_dummy');
766
-
767
- await source.submitIntent({ kind: 'stop' });
768
- await expect(source.waitForCompletion()).resolves.toEqual({ reason: 'stopped' });
769
- await runtime.close();
770
- });
771
-
772
- it('owns allocation through terminal Game State and keeps one physical frame in one epoch', async () => {
773
- const fixtureValue = await fixture([{
774
- status: 'allocated',
775
- mode: 'match',
776
- game_id: 'G1',
777
- ws_url: 'wss://game.test/ws',
778
- }]);
779
- const { runtime, source, games, client } = fixtureValue;
780
- await waitUntil(() => games.length === 1, 'Game transport was not started.');
781
-
782
- await games[0].emit(gameStateFrame('game-1', 1, {
783
- tick: 1,
784
- phase: 'wandering',
785
- }, [
786
- { type: 'role_assigned', event_id: 'role-1', role: 'shrimp' },
787
- { type: 'task_assigned', event_id: 'task-1', task_name: 'wires' },
788
- ]));
789
- await games[0].emit(gameStateFrame('game-1', 2, {
790
- tick: 2,
791
- phase: 'game_over',
792
- winner: 'shrimp',
793
- }, [{ type: 'game_over', event_id: 'over-1', winner: 'shrimp' }]));
794
-
795
- await expect(source.waitForCompletion()).resolves.toEqual({ reason: 'game_over' });
796
- await runtime.flush();
797
- expect(client.setGameServerUrl).toHaveBeenCalledWith('wss://game.test/ws');
798
-
799
- const epochs = runtime.inputJournal.list(runtime.scope(), 0, 100);
800
- const terminal = epochs.find((epoch) => epoch.events.some((event) => event.type === 'game_over'));
801
- expect(terminal).toMatchObject({
802
- coalescing: 'forbidden',
803
- domainTick: 2,
804
- state: {
805
- stage: 'ended',
806
- transport: 'game_ws',
807
- game_snapshot: { status: 'fresh', state: { tick: 2, phase: 'game_over' } },
808
- },
809
- events: [{ type: 'game_over', sourceEventId: 'over-1' }],
810
- });
811
- const terminalEvent = terminal?.events.find((event) => event.type === 'game_over');
812
- expect(terminalEvent?.sourceEventId).toBe('over-1');
813
- expect(terminalEvent?.payload).not.toHaveProperty('event_id');
814
- expect(runtime.repository.listCommittedEvents({
815
- sessionId: runtime.scope().sessionId,
816
- segmentId: runtime.scope().segmentId,
817
- order: 'asc',
818
- }).map((event) => ({ type: event.type, producer: event.producer }))).toEqual([
819
- { type: 'session_resumed', producer: 'local_synth' },
820
- { type: 'joined', producer: 'local_synth' },
821
- { type: 'role_assigned', producer: 'backend_push' },
822
- { type: 'task_assigned', producer: 'backend_push' },
823
- { type: 'game_over', producer: 'backend_push' },
824
- ]);
825
- expect(runtime.repository.latestEventByType(
826
- runtime.scope().sessionId,
827
- 'game_over',
828
- runtime.scope().segmentId,
829
- )?.payload).toMatchObject({ game_mode: 'match' });
830
- await runtime.close();
831
- });
832
-
833
- it('enriches task_completed from a same-frame task_assigned while retaining the raw internal Event', async () => {
834
- const { runtime, source, games } = await fixture([{
835
- status: 'allocated', mode: 'match', game_id: 'G1', ws_url: 'wss://game.test/ws',
836
- }]);
837
- await waitUntil(() => games.length === 1, 'Game transport was not started.');
838
-
839
- await games[0].emit(gameStateFrame('game-1', 1, {
840
- tick: 41,
841
- phase: 'wandering',
842
- you: {
843
- player: { seat: 1, name: 'me' },
844
- is_alive: true,
845
- tasks: [{ task_id: 'old', name: '擦拭酒瓶', room: '厨房', status: 'normal' }],
846
- },
847
- }));
848
- await games[0].emit(gameStateFrame('game-1', 2, {
849
- tick: 42,
850
- phase: 'wandering',
851
- you: {
852
- player: { seat: 1, name: 'me' },
853
- is_alive: true,
854
- tasks: [{
855
- task_id: 'old', name: '擦拭酒瓶', room: '厨房', status: 'completed',
856
- }, {
857
- task_id: 'new', name: '消毒淋浴器', room: '制氧舱', x: 123, y: 456, status: 'normal',
858
- }],
859
- },
860
- }, [{
861
- event_id: 'completed-1',
862
- tick: 42,
863
- type: 'task_completed',
864
- actor: { seat: 1, name: 'me' },
865
- task_name: '擦拭酒瓶',
866
- }, {
867
- event_id: 'assigned-1',
868
- tick: 42,
869
- type: 'task_assigned',
870
- actor: { seat: 1, name: 'me' },
871
- task_name: '消毒淋浴器',
872
- room: '制氧舱',
873
- x: 123,
874
- y: 456,
875
- is_fake_shrimp: false,
876
- }]));
877
- await runtime.flush();
878
-
879
- expect(runtime.repository.latestEventByType(
880
- runtime.scope().sessionId,
881
- 'task_completed',
882
- runtime.scope().segmentId,
883
- )?.payload).toMatchObject({
884
- task_name: '擦拭酒瓶',
885
- newly_assigned_task: {
886
- name: '消毒淋浴器', room: '制氧舱', x: 123, y: 456, is_fake_shrimp: false,
887
- },
888
- reason: 'task_completed',
889
- delta: [{
890
- change: 'status_changed',
891
- from_status: 'normal',
892
- to_status: 'completed',
893
- task: {
894
- task_id: 'old', name: '擦拭酒瓶', room: '厨房', status: 'completed',
895
- },
896
- }, {
897
- change: 'added',
898
- task: {
899
- task_id: 'new', name: '消毒淋浴器', room: '制氧舱', x: 123, y: 456, status: 'normal',
900
- },
901
- }],
902
- tasks: [{
903
- task_id: 'old', name: '擦拭酒瓶', room: '厨房', status: 'completed',
904
- }, {
905
- task_id: 'new', name: '消毒淋浴器', room: '制氧舱', x: 123, y: 456, status: 'normal',
906
- }],
907
- });
908
- expect(runtime.repository.latestEventByType(
909
- runtime.scope().sessionId,
910
- 'task_assigned',
911
- runtime.scope().segmentId,
912
- )?.deliveryClass).toBe('internal_only');
913
-
914
- await source.stop();
915
- await runtime.close();
916
- });
917
-
918
- it('emits one tasks_changed Event for a private assignment-only update', async () => {
919
- const { runtime, source, games } = await fixture([{
920
- status: 'allocated', mode: 'match', game_id: 'G-task-assigned', ws_url: 'wss://game.test/ws',
921
- }]);
922
- await waitUntil(() => games.length === 1, 'Game transport was not started.');
923
-
924
- await games[0].emit(gameStateFrame('game-1', 1, {
925
- tick: 1,
926
- phase: 'wandering',
927
- you: { player: { seat: 1, name: 'me' }, tasks: [] },
928
- }, [{ type: 'role_assigned', role: '龙虾', faction: 'lobster', assigned_tasks: [] }]));
929
- await games[0].emit(gameStateFrame('game-1', 2, {
930
- tick: 2,
931
- phase: 'wandering',
932
- you: {
933
- player: { seat: 1, name: 'me' },
934
- tasks: [{ task_id: 'new', name: '接线', room: '引擎室', status: 'normal' }],
935
- },
936
- }, [{
937
- type: 'task_assigned',
938
- actor: { seat: 1, name: 'me' },
939
- task_name: '接线',
940
- room: '引擎室',
941
- }]));
942
- await runtime.flush();
943
-
944
- const changes = runtime.repository.listCommittedEvents({
945
- sessionId: runtime.scope().sessionId,
946
- segmentId: runtime.scope().segmentId,
947
- types: ['tasks_changed'],
948
- order: 'asc',
949
- });
950
- expect(changes).toHaveLength(1);
951
- expect(changes[0]).toMatchObject({
952
- producer: 'local_synth',
953
- payload: {
954
- tick: 2,
955
- reason: 'task_assigned',
956
- delta: [{
957
- change: 'added',
958
- task: { task_id: 'new', name: '接线', room: '引擎室', status: 'normal' },
959
- }],
960
- tasks: [{ task_id: 'new', name: '接线', room: '引擎室', status: 'normal' }],
961
- },
962
- });
963
- expect(runtime.repository.latestEventByType(
964
- runtime.scope().sessionId,
965
- 'task_assigned',
966
- runtime.scope().segmentId,
967
- )?.deliveryClass).toBe('internal_only');
968
-
969
- await source.stop();
970
- await runtime.close();
971
- });
972
-
973
- it('keeps an emergency resolution reason while attaching the complete task update', async () => {
974
- const { runtime, source, games } = await fixture([{
975
- status: 'allocated', mode: 'match', game_id: 'G-emergency-task', ws_url: 'wss://game.test/ws',
976
- }]);
977
- await waitUntil(() => games.length === 1, 'Game transport was not started.');
978
- const regular = { task_id: 'r', name: '接线', status: 'normal' };
979
- const emergency = { task_id: 'e', name: '紧急维修', status: 'normal' };
980
-
981
- await games[0].emit(gameStateFrame('game-1', 1, {
982
- tick: 1,
983
- phase: 'wandering',
984
- you: { player: { seat: 1, name: 'me' }, tasks: [regular, emergency] },
985
- }, [{ type: 'role_assigned', role: '龙虾', faction: 'lobster' }]));
986
- await games[0].emit(gameStateFrame('game-1', 2, {
987
- tick: 2,
988
- phase: 'meeting',
989
- you: { player: { seat: 1, name: 'me' }, tasks: [regular] },
990
- }, [{
991
- type: 'emergency_resolved',
992
- reason: 'meeting_started',
993
- task_name: '紧急维修',
994
- }]));
995
- await runtime.flush();
996
-
997
- expect(runtime.repository.latestEventByType(
998
- runtime.scope().sessionId,
999
- 'emergency_resolved',
1000
- runtime.scope().segmentId,
1001
- )?.payload).toMatchObject({
1002
- reason: 'meeting_started',
1003
- delta: [{ change: 'removed', task: emergency }],
1004
- tasks: [regular],
1005
- });
1006
-
1007
- await source.stop();
1008
- await runtime.close();
1009
- });
1010
-
1011
- it('forbids coalescing only on action-safety boundary frames', async () => {
1012
- const { runtime, source, games } = await fixture([{
1013
- status: 'allocated', mode: 'match', game_id: 'G1', ws_url: 'wss://game.test/ws',
1014
- }]);
1015
- await waitUntil(() => games.length === 1, 'Game transport was not started.');
1016
-
1017
- const states = [
1018
- { tick: 1, phase: 'wandering', you: { is_alive: true } },
1019
- { tick: 2, phase: 'wandering', you: { is_alive: true } },
1020
- { tick: 3, phase: 'meeting', you: { is_alive: true } },
1021
- { tick: 4, phase: 'meeting', you: { is_alive: true } },
1022
- { tick: 5, phase: 'wandering', you: { is_alive: true } },
1023
- { tick: 6, phase: 'wandering', you: { is_alive: false } },
1024
- { tick: 7, phase: 'wandering', you: { is_alive: false } },
1025
- ];
1026
- for (const [index, state] of states.entries()) {
1027
- await games[0].emit(gameStateFrame('game-1', index + 1, state));
1028
- }
1029
- await runtime.flush();
1030
-
1031
- const gameEpochs = runtime.inputJournal.list(runtime.scope(), 0, 100)
1032
- .filter((epoch) => epoch.sourceKey.startsWith('game:G1:'));
1033
- expect(gameEpochs.map((epoch) => ({
1034
- tick: epoch.domainTick,
1035
- coalescing: epoch.coalescing ?? 'allowed',
1036
- actionSafetyGeneration: epoch.state.action_safety_generation,
1037
- }))).toEqual([
1038
- { tick: 1, coalescing: 'forbidden', actionSafetyGeneration: 2 },
1039
- { tick: 2, coalescing: 'allowed', actionSafetyGeneration: 2 },
1040
- { tick: 3, coalescing: 'forbidden', actionSafetyGeneration: 3 },
1041
- { tick: 4, coalescing: 'allowed', actionSafetyGeneration: 3 },
1042
- { tick: 5, coalescing: 'forbidden', actionSafetyGeneration: 4 },
1043
- { tick: 6, coalescing: 'forbidden', actionSafetyGeneration: 5 },
1044
- { tick: 7, coalescing: 'allowed', actionSafetyGeneration: 5 },
1045
- ]);
1046
-
1047
- await source.stop();
1048
- await runtime.close();
1049
- });
1050
-
1051
- it('keeps a non-fresh meeting return unsafe until a fresh wandering State arrives', async () => {
1052
- const { runtime, source, games } = await fixture([{
1053
- status: 'allocated', mode: 'match', game_id: 'G1', ws_url: 'wss://game.test/ws',
1054
- }]);
1055
- await waitUntil(() => games.length === 1, 'Game transport was not started.');
1056
- await games[0].emit(gameStateFrame('game-1', 1, {
1057
- tick: 1, phase: 'wandering', you: { is_alive: true },
1058
- }));
1059
-
1060
- const internals = source as unknown as {
1061
- currentStage: 'game' | 'meeting';
1062
- submitCurrentState(
1063
- cause: 'backend_event',
1064
- sourceId: string,
1065
- connectionId: string,
1066
- events: readonly Record<string, unknown>[],
1067
- ): Promise<void>;
1068
- };
1069
- internals.currentStage = 'meeting';
1070
- await internals.submitCurrentState(
1071
- 'backend_event',
1072
- CLAWCLAW_GAME_WS_SOURCE.sourceId,
1073
- 'game-1',
1074
- [],
1075
- );
1076
- internals.currentStage = 'game';
1077
- await internals.submitCurrentState(
1078
- 'backend_event',
1079
- CLAWCLAW_GAME_WS_SOURCE.sourceId,
1080
- 'game-1',
1081
- [],
1082
- );
1083
- await games[0].emit(gameStateFrame('game-1', 2, {
1084
- tick: 2, phase: 'wandering', you: { is_alive: true },
1085
- }));
1086
- await runtime.flush();
1087
-
1088
- const transitions = runtime.inputJournal.list(runtime.scope(), 0, 100)
1089
- .filter((epoch) => (
1090
- epoch.domainTick === 1
1091
- || epoch.domainTick === 2
1092
- || epoch.state.cause === 'backend_event'
1093
- ))
1094
- .map((epoch) => ({
1095
- tick: epoch.domainTick,
1096
- stage: epoch.state.stage,
1097
- snapshot: epoch.state.game_snapshot.status,
1098
- generation: epoch.state.action_safety_generation as number,
1099
- coalescing: epoch.coalescing ?? 'allowed',
1100
- }));
1101
- expect(transitions).toHaveLength(4);
1102
- const initialGeneration = transitions[0]!.generation;
1103
- expect(transitions).toEqual([
1104
- {
1105
- tick: 1,
1106
- stage: 'game',
1107
- snapshot: 'fresh',
1108
- generation: initialGeneration,
1109
- coalescing: 'forbidden',
1110
- },
1111
- {
1112
- tick: undefined,
1113
- stage: 'meeting',
1114
- snapshot: 'not_updated',
1115
- generation: initialGeneration + 1,
1116
- coalescing: 'forbidden',
1117
- },
1118
- {
1119
- tick: undefined,
1120
- stage: 'game',
1121
- snapshot: 'not_updated',
1122
- generation: initialGeneration + 1,
1123
- coalescing: 'allowed',
1124
- },
1125
- {
1126
- tick: 2,
1127
- stage: 'game',
1128
- snapshot: 'fresh',
1129
- generation: initialGeneration + 2,
1130
- coalescing: 'forbidden',
1131
- },
1132
- ]);
1133
-
1134
- await source.stop();
1135
- await runtime.close();
1136
- });
1137
-
1138
- it('marks reconnect complete only after the GameSync recovery barrier', async () => {
1139
- const { runtime, client, source, games } = await fixture([{
1140
- status: 'allocated', mode: 'match', game_id: 'G1', ws_url: 'wss://game.test/ws',
1141
- }]);
1142
- await waitUntil(() => games.length === 1, 'Game transport was not started.');
1143
- const initial = gameStateFrame('game-1', 1, { tick: 10, phase: 'wandering' });
1144
- initial.meta.origin = 'snapshot';
1145
- await games[0].emit(initial);
1146
- const logicalScope = runtime.scope();
1147
- expect(client.acknowledgeGameSync).toHaveBeenLastCalledWith('ack:game-1:1', true);
1148
-
1149
- await games[0].options.onConnectionOpened('game-2', true);
1150
- await runtime.flush();
1151
- expect(runtime.readReadyView().state.state).toMatchObject({ tick: 10, phase: 'wandering' });
1152
- expect(runtime.inputJournal.list(runtime.scope(), 0, 100).at(-1)?.state)
1153
- .toMatchObject({ connection: 'reconnecting', game_snapshot: { status: 'not_updated' } });
1154
- expect(runtime.repository.listCommittedEvents({
1155
- sessionId: runtime.scope().sessionId,
1156
- types: ['game_stream_reconnected'],
1157
- })).toHaveLength(0);
1158
-
1159
- const resumed = gameStateFrame('game-2', 8, { tick: 20, phase: 'wandering' }, [{
1160
- type: 'vote_speech', event_id: 'replayed-speech', tick: 18, text: 'skip',
1161
- }]);
1162
- resumed.meta.origin = 'resume';
1163
- resumed.meta.replayed = true;
1164
- await games[0].emit(resumed);
1165
- await runtime.flush();
1166
- expect(client.acknowledgeGameSync).toHaveBeenLastCalledWith('ack:game-2:8', true);
1167
-
1168
- expect(runtime.inputJournal.list(runtime.scope(), 0, 100).at(-1)?.state)
1169
- .toMatchObject({ connection: 'connected', game_snapshot: { status: 'fresh' } });
1170
- expect(runtime.repository.listCommittedEvents({
1171
- sessionId: runtime.scope().sessionId,
1172
- types: ['vote_speech', 'game_stream_reconnected'],
1173
- order: 'asc',
1174
- }).map((event) => event.type)).toEqual(['vote_speech', 'game_stream_reconnected']);
1175
- expect(runtime.repository.latestEventByType(
1176
- runtime.scope().sessionId,
1177
- 'vote_speech',
1178
- runtime.scope().segmentId,
1179
- )?.replayed).toBe(true);
1180
- expect(runtime.scope()).toEqual(logicalScope);
1181
-
1182
- await source.stop();
1183
- await runtime.close();
1184
- });
1185
-
1186
- it('marks an in-place resync stale before accepting its snapshot fallback', async () => {
1187
- const { runtime, source, games } = await fixture([{
1188
- status: 'allocated', mode: 'match', game_id: 'G1', ws_url: 'wss://game.test/ws',
1189
- }]);
1190
- await waitUntil(() => games.length === 1, 'Game transport was not started.');
1191
- const connectionId = games[0].connectionId;
1192
- const initial = gameStateFrame(connectionId, 1, { tick: 10, phase: 'wandering' });
1193
- initial.meta.origin = 'snapshot';
1194
- await games[0].emit(initial);
1195
-
1196
- await games[0].startRecovery({
1197
- connectionId,
1198
- reason: 'seq_gap',
1199
- expectedSeq: 2,
1200
- receivedSeq: 3,
1201
- });
1202
- await runtime.flush();
1203
- expect(runtime.inputJournal.list(runtime.scope(), 0, 100).at(-1)?.state).toMatchObject({
1204
- connection: 'reconnecting',
1205
- game_snapshot: { status: 'not_updated' },
1206
- });
1207
-
1208
- const fallback = gameStateFrame(connectionId, 4, { tick: 13, phase: 'wandering' });
1209
- fallback.meta.origin = 'snapshot';
1210
- fallback.meta.snapshotFallback = true;
1211
- await games[0].emit(fallback);
1212
- await runtime.flush();
1213
- const recoveryEpochs = runtime.inputJournal.list(runtime.scope(), 0, 100).slice(-2);
1214
- expect(recoveryEpochs.map((epoch) => ({
1215
- connection: epoch.state.connection,
1216
- snapshot: epoch.state.game_snapshot.status,
1217
- coalescing: epoch.coalescing ?? 'allowed',
1218
- }))).toEqual([
1219
- { connection: 'reconnecting', snapshot: 'not_updated', coalescing: 'forbidden' },
1220
- { connection: 'connected', snapshot: 'fresh', coalescing: 'forbidden' },
1221
- ]);
1222
-
1223
- await source.stop();
1224
- await runtime.close();
1225
- });
1226
-
1227
- it('accepts a zero-replay resume barrier at the previously committed sequence', async () => {
1228
- const { runtime, source, games } = await fixture([{
1229
- status: 'allocated', mode: 'match', game_id: 'G1', ws_url: 'wss://game.test/ws',
1230
- }]);
1231
- await waitUntil(() => games.length === 1, 'Game transport was not started.');
1232
- await games[0].emit(gameStateFrame('game-1', 1, { tick: 10, phase: 'wandering' }));
1233
-
1234
- await games[0].options.onConnectionOpened('game-2', true);
1235
- const resumed = gameStateFrame('game-2', 1, { tick: 10, phase: 'wandering' });
1236
- resumed.meta.origin = 'resume';
1237
- resumed.meta.replayed = true;
1238
- await expect(games[0].emit(resumed)).resolves.toBeUndefined();
1239
- await runtime.flush();
1240
-
1241
- expect(runtime.inputJournal.list(runtime.scope(), 0, 100).map((epoch) => epoch.sourceKey))
1242
- .toContain('game:G1:1:resume:game-2');
1243
- expect(runtime.repository.listCommittedEvents({
1244
- sessionId: runtime.scope().sessionId,
1245
- types: ['game_stream_reconnected'],
1246
- })).toHaveLength(1);
1247
-
1248
- await source.stop();
1249
- await runtime.close();
1250
- });
1251
-
1252
- it('backfills competition mode on backend opening and terminal Events', async () => {
1253
- const { runtime, source, games } = await fixture(
1254
- [{ status: 'not_in_queue' }],
1255
- { kind: 'match', mode: 'competition' },
1256
- {
1257
- configureClient: (client) => client.joinQueue.mockResolvedValueOnce({
1258
- status: 'allocated',
1259
- game_id: 'G-competition',
1260
- ws_url: 'wss://competition.test/ws',
1261
- } as any),
1262
- },
1263
- );
1264
- await waitUntil(() => games.length === 1, 'Competition Game transport was not started.');
1265
-
1266
- await games[0].emit(gameStateFrame('game-1', 1, {
1267
- tick: 1,
1268
- phase: 'wandering',
1269
- }, [{ type: 'game_started', player_count: 10 }]));
1270
- await games[0].emit(gameStateFrame('game-1', 2, {
1271
- tick: 2,
1272
- phase: 'game_over',
1273
- winner: 'lobster',
1274
- }, [{ type: 'game_over', winner: 'lobster' }]));
1275
-
1276
- await expect(source.waitForCompletion()).resolves.toEqual({ reason: 'game_over' });
1277
- await runtime.flush();
1278
- const events = runtime.repository.listCommittedEvents({
1279
- sessionId: runtime.scope().sessionId,
1280
- types: ['game_started', 'game_over'],
1281
- order: 'asc',
1282
- });
1283
- expect(events.map((event) => ({
1284
- type: event.type,
1285
- game_mode: event.payload.game_mode,
1286
- }))).toEqual([
1287
- { type: 'game_started', game_mode: 'competition' },
1288
- { type: 'game_over', game_mode: 'competition' },
1289
- ]);
1290
- await runtime.close();
1291
- });
1292
-
1293
- it('publishes the opening roster and later Source-owned player changes', async () => {
1294
- const { runtime, source, games } = await fixture([{
1295
- status: 'allocated',
1296
- mode: 'match',
1297
- game_id: 'G-player-change',
1298
- ws_url: 'wss://game.test/ws',
1299
- }]);
1300
- await waitUntil(() => games.length === 1, 'Game transport was not started.');
1301
-
1302
- await games[0].emit(gameStateFrame('game-1', 1, {
1303
- tick: 1,
1304
- phase: 'wandering',
1305
- you: { player: { seat: 1, name: 'me' } },
1306
- players: [
1307
- { seat: 1, name: 'me', known_status: { is_alive: true } },
1308
- { seat: 2, name: 'Alpha', known_status: { is_alive: true } },
1309
- { seat: 3, name: 'Bravo', known_status: { is_alive: true } },
1310
- { seat: 4, name: 'Charlie', known_status: { is_alive: true } },
1311
- ],
1312
- visible_players: [],
1313
- visible_corpses: [],
1314
- }, [{ type: 'game_started', player_count: 4 }]));
1315
- await games[0].emit(gameStateFrame('game-1', 2, {
1316
- tick: 644,
1317
- phase: 'meeting',
1318
- you: { player: { seat: 1, name: 'me' } },
1319
- players: [
1320
- { seat: 1, name: 'me', known_status: { is_alive: true } },
1321
- { seat: 2, name: 'Alpha', known_status: { is_alive: true } },
1322
- { seat: 3, name: 'Bravo', known_status: { is_alive: false, death_cause: 'killed' } },
1323
- { seat: 4, name: 'Charlie', known_status: { is_alive: false, death_cause: 'killed' } },
1324
- ],
1325
- meeting: { active: true, meeting_count: 1 },
1326
- }, [{
1327
- type: 'meeting_briefing',
1328
- reported_corpses: [{ name: 'Bravo', seat: 3 }],
1329
- dead_players: [{ name: 'Bravo', seat: 3 }, { name: 'Charlie', seat: 4 }],
1330
- }]));
1331
- await runtime.flush();
1332
-
1333
- const changes = runtime.repository.listCommittedEvents({
1334
- sessionId: runtime.scope().sessionId,
1335
- segmentId: runtime.scope().segmentId,
1336
- types: ['players_changed'],
1337
- order: 'asc',
1338
- });
1339
- expect(changes).toHaveLength(2);
1340
- expect(changes[0]).toMatchObject({
1341
- producer: 'local_synth',
1342
- payload: {
1343
- tick: 1,
1344
- reason: 'roster_initialized',
1345
- changes: [
1346
- { change: 'discovered', name: 'me', seat: 1 },
1347
- { change: 'discovered', name: 'Alpha', seat: 2 },
1348
- { change: 'discovered', name: 'Bravo', seat: 3 },
1349
- { change: 'discovered', name: 'Charlie', seat: 4 },
1350
- ],
1351
- players: [
1352
- { name: 'me', seat: 1, status: 'alive', death: null },
1353
- { name: 'Alpha', seat: 2, status: 'alive', death: null },
1354
- { name: 'Bravo', seat: 3, status: 'alive', death: null },
1355
- { name: 'Charlie', seat: 4, status: 'alive', death: null },
1356
- ],
1357
- },
1358
- });
1359
- expect(changes[1]).toMatchObject({
1360
- producer: 'local_synth',
1361
- payload: {
1362
- tick: 644,
1363
- meeting: true,
1364
- meeting_count: 1,
1365
- reason: 'meeting_reveal',
1366
- changes: [{
1367
- change: 'died',
1368
- name: 'Bravo',
1369
- seat: 3,
1370
- cause: 'killed',
1371
- killer: null,
1372
- }, {
1373
- change: 'died',
1374
- name: 'Charlie',
1375
- seat: 4,
1376
- cause: 'killed',
1377
- killer: null,
1378
- }],
1379
- players: [{
1380
- name: 'me',
1381
- seat: 1,
1382
- status: 'alive',
1383
- death: null,
1384
- }, {
1385
- name: 'Alpha',
1386
- seat: 2,
1387
- status: 'alive',
1388
- death: null,
1389
- }, {
1390
- name: 'Bravo',
1391
- seat: 3,
1392
- status: 'dead',
1393
- death: { cause: 'killed', killer: null },
1394
- }, {
1395
- name: 'Charlie',
1396
- seat: 4,
1397
- status: 'dead',
1398
- death: { cause: 'killed', killer: null },
1399
- }],
1400
- },
1401
- });
1402
-
1403
- await runtime.close();
1404
- await expect(source.waitForCompletion()).resolves.toEqual({ reason: 'stopped' });
1405
- });
1406
-
1407
- it('normalizes structured player and system killers from GameSync frames', async () => {
1408
- const scenarios = [{
1409
- eventId: 'player-killed',
1410
- killer: { kind: 'player', player: { seat: 2, name: 'Killer' } },
1411
- expected: {
1412
- killer_kind: 'player', killer_name: 'Killer', killer_seat: 2,
1413
- },
1414
- }, {
1415
- eventId: 'system-killed',
1416
- killer: { kind: 'system', name: 'Shrimp God' },
1417
- expected: { killer_kind: 'system', killer_name: 'Shrimp God' },
1418
- }];
1419
-
1420
- for (const scenario of scenarios) {
1421
- const { runtime, events, source, games } = await fixture([{
1422
- status: 'allocated',
1423
- mode: 'match',
1424
- game_id: `G-${scenario.eventId}`,
1425
- ws_url: 'wss://game.test/ws',
1426
- }]);
1427
- await waitUntil(() => games.length === 1, 'Game transport was not started.');
1428
-
1429
- await games[0].emit(gameStateFrame('game-1', 1, {
1430
- tick: 41,
1431
- phase: 'wandering',
1432
- you: { player: { seat: 1, name: 'me' }, is_alive: false },
1433
- players: [
1434
- { seat: 1, name: 'me', known_status: { is_alive: false, death_cause: 'killed' } },
1435
- { seat: 2, name: 'Killer', known_status: { is_alive: true } },
1436
- ],
1437
- }, [{
1438
- event_id: scenario.eventId,
1439
- type: 'killed',
1440
- actor: { seat: 1, name: 'me' },
1441
- killer: scenario.killer,
1442
- room: '制氧舱',
1443
- }]));
1444
- await runtime.flush();
1445
-
1446
- const killed = runtime.repository.listCommittedEvents({
1447
- sessionId: runtime.scope().sessionId,
1448
- segmentId: runtime.scope().segmentId,
1449
- types: ['killed'],
1450
- });
1451
- expect(killed).toHaveLength(1);
1452
- expect(killed[0].payload).toMatchObject({
1453
- room: '制氧舱',
1454
- actor_name: 'me',
1455
- actor_seat: 1,
1456
- ...scenario.expected,
1457
- });
1458
- expect(killed[0].payload).not.toHaveProperty('killer');
1459
-
1460
- const mailbox = new ClawclawMailboxService({
1461
- repository: events,
1462
- readyView: () => runtime.readReadyView(),
1463
- });
1464
- expect(mailbox.prepareEvents({ eventType: 'killed' }).output.event)
1465
- .toMatchObject(scenario.expected);
1466
-
1467
- await source.stop();
1468
- await runtime.close();
1469
- }
1470
- });
1471
-
1472
- it('filters self-killer murder_witnessed before canonical ingress and records a diagnostic', async () => {
1473
- const { runtime, source, games } = await fixture([{
1474
- status: 'allocated',
1475
- mode: 'match',
1476
- game_id: 'G-self-killer-witness',
1477
- ws_url: 'wss://game.test/ws',
1478
- }]);
1479
- await waitUntil(() => games.length === 1, 'Game transport was not started.');
1480
- const diagnostic = vi.spyOn(runtime, 'diagnostic');
1481
-
1482
- await games[0].emit(gameStateFrame('game-1', 1, {
1483
- tick: 51,
1484
- phase: 'wandering',
1485
- you: { player: { seat: 1, name: 'me' }, is_alive: true },
1486
- players: [
1487
- { seat: 1, name: 'me', known_status: { is_alive: true } },
1488
- { seat: 2, name: 'target', known_status: { is_alive: false, death_cause: 'killed' } },
1489
- ],
1490
- }, [{
1491
- event_id: 'valid-self-kill',
1492
- type: 'kill',
1493
- actor: { seat: 1, name: 'me' },
1494
- target: { seat: 2, name: 'target' },
1495
- room: '制氧舱',
1496
- }, {
1497
- event_id: 'invalid-self-witness',
1498
- type: 'murder_witnessed',
1499
- killer: { kind: 'player', player: { seat: 1, name: 'me' } },
1500
- target: { seat: 2, name: 'target' },
1501
- room: '制氧舱',
1502
- }]));
1503
- await runtime.flush();
1504
-
1505
- expect(runtime.repository.listCommittedEvents({
1506
- sessionId: runtime.scope().sessionId,
1507
- types: ['kill'],
1508
- })).toHaveLength(1);
1509
- expect(runtime.repository.listCommittedEvents({
1510
- sessionId: runtime.scope().sessionId,
1511
- types: ['murder_witnessed'],
1512
- })).toHaveLength(0);
1513
- expect(diagnostic).toHaveBeenCalledWith(
1514
- 'runtime.source.event_downgraded',
1515
- expect.objectContaining({
1516
- event_type: 'murder_witnessed',
1517
- error_code: 'MURDER_WITNESSED_SELF_KILLER',
1518
- killer_seat: 1,
1519
- self_seat: 1,
1520
- }),
1521
- 'warn',
1522
- );
1523
-
1524
- await source.stop();
1525
- await runtime.close();
1526
- });
1527
-
1528
- it('rejects one malformed GameSync Event without stopping Source or later frames', async () => {
1529
- const { runtime, source, games, client } = await fixture([{
1530
- status: 'allocated',
1531
- mode: 'match',
1532
- game_id: 'G-malformed-event',
1533
- ws_url: 'wss://game.test/ws',
1534
- }]);
1535
- await waitUntil(() => games.length === 1, 'Game transport was not started.');
1536
- const diagnostic = vi.spyOn(runtime, 'diagnostic');
1537
-
1538
- const roster = (victimAlive: boolean) => ([
1539
- { seat: 1, name: 'me', known_status: { is_alive: true } },
1540
- { seat: 2, name: 'Killer', known_status: { is_alive: true } },
1541
- {
1542
- seat: 4,
1543
- name: 'Victim',
1544
- known_status: victimAlive
1545
- ? { is_alive: true }
1546
- : { is_alive: false, death_cause: 'killed' },
1547
- },
1548
- ]);
1549
- await games[0].emit(gameStateFrame('game-1', 1, {
1550
- tick: 1,
1551
- phase: 'wandering',
1552
- you: {
1553
- player: { seat: 1, name: 'me' },
1554
- is_alive: true,
1555
- tasks: [{ task_id: 'wires', name: 'wires', room: 'Engine', status: 'normal' }],
1556
- },
1557
- players: roster(true),
1558
- }));
1559
- await games[0].emit(gameStateFrame('game-1', 2, {
1560
- tick: 2,
1561
- phase: 'wandering',
1562
- you: {
1563
- player: { seat: 1, name: 'me' },
1564
- is_alive: true,
1565
- tasks: [{ task_id: 'wires', name: 'wires', room: 'Engine', status: 'completed' }],
1566
- },
1567
- players: roster(false),
1568
- }, [{
1569
- event_id: 'move-valid-before',
1570
- type: 'move_end',
1571
- }, {
1572
- event_id: 'killed-malformed',
1573
- tick: 2,
1574
- type: 'killed',
1575
- actor: { seat: 4, name: 'Victim' },
1576
- killer: { kind: 'player', player: { seat: 2 } },
1577
- }, {
1578
- event_id: 'task-valid-after',
1579
- type: 'task_completed',
1580
- actor: { seat: 1, name: 'me' },
1581
- task_name: 'wires',
1582
- }]));
1583
- await games[0].emit(gameStateFrame('game-1', 3, {
1584
- tick: 3,
1585
- phase: 'wandering',
1586
- you: {
1587
- player: { seat: 1, name: 'me' },
1588
- is_alive: true,
1589
- tasks: [{ task_id: 'wires', name: 'wires', room: 'Engine', status: 'completed' }],
1590
- },
1591
- players: roster(false),
1592
- }));
1593
- await runtime.flush();
1594
-
1595
- const secondEpoch = runtime.inputJournal.list(runtime.scope(), 0, 100)
1596
- .find((epoch) => epoch.domainTick === 2);
1597
- expect(secondEpoch?.events).toEqual(expect.arrayContaining([
1598
- expect.objectContaining({
1599
- type: 'move_end', sourceEventId: 'move-valid-before', sourceSeq: '2:0',
1600
- }),
1601
- expect.objectContaining({
1602
- type: 'task_completed',
1603
- sourceEventId: 'task-valid-after',
1604
- sourceSeq: '2:2',
1605
- payload: expect.objectContaining({
1606
- reason: 'task_completed',
1607
- delta: [expect.objectContaining({
1608
- change: 'status_changed',
1609
- task: expect.objectContaining({ task_id: 'wires', name: 'wires' }),
1610
- })],
1611
- }),
1612
- }),
1613
- expect.objectContaining({
1614
- type: 'players_changed',
1615
- payload: expect.objectContaining({
1616
- changes: expect.arrayContaining([expect.objectContaining({
1617
- change: 'died', name: 'Victim', cause: 'killed', killer: null,
1618
- })]),
1619
- }),
1620
- }),
1621
- ]));
1622
- expect(secondEpoch?.events.some((event) => event.type === 'killed')).toBe(false);
1623
- expect(diagnostic).toHaveBeenCalledWith(
1624
- 'runtime.source.event_rejected',
1625
- expect.objectContaining({
1626
- source_id: CLAWCLAW_GAME_WS_SOURCE.sourceId,
1627
- source_seq: 2,
1628
- event_index: 1,
1629
- event_type: 'killed',
1630
- source_event_id: 'killed-malformed',
1631
- error_code: 'GAME_SYNC_EVENT_NORMALIZATION_FAILED',
1632
- error_name: 'TypeError',
1633
- }),
1634
- 'error',
1635
- );
1636
- expect(client.acknowledgeGameSync).toHaveBeenLastCalledWith('ack:game-1:3', false);
1637
- expect(games[0].stoppedWith).toBeUndefined();
1638
- expect(runtime.repository.latestEventByType(
1639
- runtime.scope().sessionId,
1640
- 'error',
1641
- runtime.scope().segmentId,
1642
- )?.payload).not.toMatchObject({ code: 'SOURCE_FAILED' });
1643
-
1644
- await source.stop();
1645
- await runtime.close();
1646
- });
1647
-
1648
- it('logs partial State loss, rejects an invalid tick, and accepts the next frame', async () => {
1649
- const { runtime, source, games, client } = await fixture([{
1650
- status: 'allocated',
1651
- mode: 'match',
1652
- game_id: 'G-malformed-frame',
1653
- ws_url: 'wss://game.test/ws',
1654
- }]);
1655
- await waitUntil(() => games.length === 1, 'Game transport was not started.');
1656
- const diagnostic = vi.spyOn(runtime, 'diagnostic');
1657
-
1658
- await games[0].emit(gameStateFrame('game-1', 1, {
1659
- tick: 1,
1660
- phase: 'wandering',
1661
- you: { player: { seat: 1, name: 'me' } },
1662
- players: [{ seat: 1, name: 'me', known_status: { is_alive: true } }],
1663
- }));
1664
- await games[0].emit(gameStateFrame('game-1', 2, {
1665
- tick: 2,
1666
- phase: 'wandering',
1667
- }));
1668
-
1669
- const invalidTick = gameStateFrame('game-1', 3, {
1670
- tick: 99,
1671
- phase: 'wandering',
1672
- });
1673
- invalidTick.meta.domainTick = 3;
1674
- await expect(games[0].emit(invalidTick)).resolves.toBeUndefined();
1675
-
1676
- await games[0].emit(gameStateFrame('game-1', 4, {
1677
- tick: 4,
1678
- phase: 'wandering',
1679
- you: { player: { seat: 1, name: 'me' } },
1680
- players: [{ seat: 1, name: 'me', known_status: { is_alive: true } }],
1681
- }));
1682
- await runtime.flush();
1683
-
1684
- const ticks = runtime.inputJournal.list(runtime.scope(), 0, 100)
1685
- .map((epoch) => epoch.domainTick);
1686
- expect(ticks).toEqual(expect.arrayContaining([1, 2, 4]));
1687
- expect(ticks).not.toContain(3);
1688
- expect(diagnostic).toHaveBeenCalledWith(
1689
- 'runtime.source.state_degraded',
1690
- expect.objectContaining({
1691
- source_id: CLAWCLAW_GAME_WS_SOURCE.sourceId,
1692
- source_seq: 2,
1693
- error_code: 'GAME_SYNC_STATE_FIELDS_MISSING',
1694
- missing_fields: ['players', 'you'],
1695
- }),
1696
- 'warn',
1697
- );
1698
- expect(diagnostic).toHaveBeenCalledWith(
1699
- 'runtime.source.frame_rejected',
1700
- expect.objectContaining({
1701
- source_id: CLAWCLAW_GAME_WS_SOURCE.sourceId,
1702
- source_seq: 3,
1703
- error_code: 'GAME_SYNC_TICK_INVALID',
1704
- reason: 'tick_mismatch',
1705
- frame_tick: 3,
1706
- state_tick: 99,
1707
- }),
1708
- 'error',
1709
- );
1710
- expect(client.acknowledgeGameSync).not.toHaveBeenCalledWith('ack:game-1:3', false);
1711
- expect(client.acknowledgeGameSync).toHaveBeenLastCalledWith('ack:game-1:4', false);
1712
- expect(games[0].stoppedWith).toBeUndefined();
1713
- expect(runtime.repository.latestEventByType(
1714
- runtime.scope().sessionId,
1715
- 'error',
1716
- runtime.scope().segmentId,
1717
- )?.payload).not.toMatchObject({ code: 'SOURCE_FAILED' });
1718
-
1719
- await source.stop();
1720
- await runtime.close();
1721
- });
1722
-
1723
- it('keeps exile pending until a later authoritative State confirms death', async () => {
1724
- const { runtime, source, games } = await fixture([{
1725
- status: 'allocated',
1726
- mode: 'match',
1727
- game_id: 'G-exile-pending',
1728
- ws_url: 'wss://game.test/ws',
1729
- }]);
1730
- await waitUntil(() => games.length === 1, 'Game transport was not started.');
1731
-
1732
- const roster = (exiledAlive: boolean) => ([
1733
- { seat: 1, name: 'me', known_status: { is_alive: true } },
1734
- { seat: 2, name: 'Alpha', known_status: { is_alive: true } },
1735
- {
1736
- seat: 4,
1737
- name: 'Exiled',
1738
- known_status: exiledAlive
1739
- ? { is_alive: true }
1740
- : { is_alive: false, death_cause: 'exiled' },
1741
- },
1742
- ]);
1743
-
1744
- await games[0].emit(gameStateFrame('game-1', 1, {
1745
- tick: 1,
1746
- phase: 'wandering',
1747
- you: { player: { seat: 1, name: 'me' } },
1748
- players: roster(true),
1749
- }, [{ type: 'game_started', player_count: 3 }]));
1750
- await games[0].emit(gameStateFrame('game-1', 2, {
1751
- tick: 700,
1752
- phase: 'meeting',
1753
- you: { player: { seat: 1, name: 'me' }, is_alive: true },
1754
- players: roster(true),
1755
- meeting: { active: true, meeting_count: 1, sub_phase: 'result_pending' },
1756
- }, [{ type: 'exile', actor: { seat: 4, name: 'Exiled' } }]));
1757
- await runtime.flush();
1758
-
1759
- expect(runtime.repository.listCommittedEvents({
1760
- sessionId: runtime.scope().sessionId,
1761
- segmentId: runtime.scope().segmentId,
1762
- types: ['exile'],
1763
- order: 'asc',
1764
- })).toHaveLength(1);
1765
- const beforeConfirmation = runtime.repository.listCommittedEvents({
1766
- sessionId: runtime.scope().sessionId,
1767
- segmentId: runtime.scope().segmentId,
1768
- types: ['players_changed'],
1769
- order: 'asc',
1770
- });
1771
- expect(beforeConfirmation).toHaveLength(1);
1772
- expect(beforeConfirmation[0]).toMatchObject({
1773
- payload: { tick: 1, reason: 'roster_initialized' },
1774
- });
1775
-
1776
- await games[0].emit(gameStateFrame('game-1', 3, {
1777
- tick: 701,
1778
- phase: 'meeting',
1779
- you: { player: { seat: 1, name: 'me' }, is_alive: true },
1780
- players: roster(false),
1781
- meeting: { active: true, meeting_count: 1, sub_phase: 'exile_animation' },
1782
- }));
1783
- await runtime.flush();
1784
-
1785
- const changes = runtime.repository.listCommittedEvents({
1786
- sessionId: runtime.scope().sessionId,
1787
- segmentId: runtime.scope().segmentId,
1788
- types: ['players_changed'],
1789
- order: 'asc',
1790
- });
1791
- expect(changes).toHaveLength(2);
1792
- expect(changes[1]).toMatchObject({
1793
- payload: {
1794
- tick: 701,
1795
- meeting: true,
1796
- meeting_count: 1,
1797
- reason: 'meeting_reveal',
1798
- changes: [{
1799
- change: 'died',
1800
- name: 'Exiled',
1801
- seat: 4,
1802
- cause: 'exiled',
1803
- killer: null,
1804
- }],
1805
- },
1806
- });
1807
-
1808
- await runtime.close();
1809
- await expect(source.waitForCompletion()).resolves.toEqual({ reason: 'stopped' });
1810
- });
1811
-
1812
- it('submits an Events query boundary using only the latest WS state', async () => {
1813
- const { runtime, source, games } = await fixture([{
1814
- status: 'allocated',
1815
- mode: 'match',
1816
- game_id: 'G1',
1817
- ws_url: 'wss://game.test/ws',
1818
- }]);
1819
- await waitUntil(() => games.length === 1, 'Game transport was not started.');
1820
- await games[0].emit(gameStateFrame('game-1', 1, {
1821
- tick: 15,
1822
- phase: 'wandering',
1823
- you: {
1824
- tasks: [{
1825
- name: 'wires',
1826
- room: 'cafeteria',
1827
- x: 321,
1828
- y: 654,
1829
- status: 'normal',
1830
- is_fake_shrimp: true,
1831
- }],
1832
- },
1833
- }));
1834
-
1835
- const accepted = await source.submitEventsQueryBoundary('query-1');
1836
- const ready = await runtime.waitForEpochReadyView(accepted.epoch.epochSeq);
1837
-
1838
- expect(accepted.epoch).toMatchObject({
1839
- coalescing: 'forbidden',
1840
- state: {
1841
- cause: 'agent_events_query',
1842
- stage: 'game',
1843
- control: { type: 'events_query', request_id: 'query-1' },
1844
- game_snapshot: { status: 'not_updated' },
1845
- },
1846
- events: [],
1847
- });
1848
- expect(accepted.epoch.domainTick).toBeUndefined();
1849
- expect(ready).toMatchObject({
1850
- epochSeq: accepted.epoch.epochSeq,
1851
- state: {
1852
- state: {
1853
- tick: 15,
1854
- phase: 'wandering',
1855
- you: {
1856
- tasks: [{
1857
- name: 'wires',
1858
- room: 'cafeteria',
1859
- x: 321,
1860
- y: 654,
1861
- status: 'normal',
1862
- is_fake_shrimp: true,
1863
- }],
1864
- },
1865
- },
1866
- },
1867
- });
1868
-
1869
- await source.stop();
1870
- await runtime.close();
1871
- });
1872
- it('owns room to game to room transitions without command-layer phase calls', async () => {
1873
- const fixtureValue = await fixture([
1874
- { status: 'in_room', room_code: 'R1' },
1875
- { status: 'in_room', room_code: 'R1' },
1876
- ]);
1877
- const { runtime, events, source, games, rooms, client } = fixtureValue;
1878
- await waitUntil(() => rooms.length === 1, 'Room transport was not started.');
1879
-
1880
- await rooms[0].emit('room.snapshot', {
1881
- room_code: 'R1',
1882
- status: 'waiting',
1883
- members: [],
1884
- }, {
1885
- room_code: 'R1',
1886
- status: 'waiting',
1887
- members: [],
1888
- }, 1);
1889
- await rooms[0].emit('room.game_started', {
1890
- game_id: 'G1',
1891
- ws_url: 'wss://room-game.test/ws',
1892
- }, {
1893
- room_code: 'R1',
1894
- status: 'playing',
1895
- game_id: 'G1',
1896
- ws_url: 'wss://room-game.test/ws',
1897
- members: [],
1898
- }, 2);
1899
- await waitUntil(() => games.length === 1, 'Room game transport was not started.');
1900
- expect(client.setGameServerUrl).toHaveBeenCalledWith('wss://room-game.test/ws');
1901
-
1902
- await games[0].emit(gameStateFrame('game-1', 1, {
1903
- tick: 10,
1904
- phase: 'game_over',
1905
- }, [{ type: 'game_over', event_id: 'room-over-1' }]));
1906
- await waitUntil(() => rooms.length === 2, 'Source did not return to the room.');
1907
- await rooms[1].emit('room.snapshot', {
1908
- room_code: 'R1',
1909
- status: 'waiting',
1910
- members: [],
1911
- }, {
1912
- room_code: 'R1',
1913
- status: 'waiting',
1914
- members: [],
1915
- }, 1);
1916
- await rooms[1].emit('room.self_left', {}, null, 2);
1917
-
1918
- await expect(source.waitForCompletion()).resolves.toEqual({ reason: 'left' });
1919
- await runtime.flush();
1920
- expect(runtime.repository.listCommittedEvents({
1921
- sessionId: runtime.scope().sessionId,
1922
- types: ['room_returning_to_lobby'],
1923
- })).toHaveLength(1);
1924
- const roomGameOver = runtime.repository.latestEventByType(
1925
- runtime.scope().sessionId,
1926
- 'game_over',
1927
- );
1928
- expect(roomGameOver?.payload).toMatchObject({ game_mode: 'room' });
1929
- expect(presentCanonicalEvent(roomGameOver!, null).hint)
1930
- .toContain('wait for the room lifecycle to resume');
1931
- const mailbox = new ClawclawMailboxService({
1932
- repository: events,
1933
- readyView: () => runtime.readReadyView(),
1934
- });
1935
- const delivered = mailbox.prepareEvents({ eventType: 'game_over' }).output.event as Record<string, unknown>;
1936
- expect(delivered).toMatchObject({ type: 'game_over', game_mode: 'room' });
1937
- expect(delivered.hint).toContain('wait for the room lifecycle to resume');
1938
- expect(delivered.hint).not.toContain('start another match only if the user asks');
1939
- expect(runtime.inputJournal.list(runtime.scope(), 0, 100).at(-1)).toMatchObject({
1940
- state: { stage: 'ended', transport: 'room_ws' },
1941
- events: [{ type: 'room.self_left' }],
1942
- });
1943
- await runtime.close();
1944
- });
1945
-
1946
- it('keeps exact training mode across a round and returns to the same room', async () => {
1947
- const { runtime, source, games, rooms } = await fixture([
1948
- {
1949
- status: 'allocated',
1950
- mode: 'training_dummy',
1951
- game_id: 'TG1',
1952
- room_code: 'TRAIN1',
1953
- ws_url: 'wss://training-game.test/ws',
1954
- },
1955
- { status: 'in_room', mode: 'room', room_code: 'TRAIN1' },
1956
- ]);
1957
- await waitUntil(() => games.length === 1, 'Training game transport was not started.');
1958
-
1959
- await games[0].emit(gameStateFrame('game-1', 1, {
1960
- tick: 10,
1961
- phase: 'game_over',
1962
- }, [{ type: 'game_over', event_id: 'training-over-1' }]));
1963
- await waitUntil(() => rooms.length === 1, 'Training Source did not return to its room.');
1964
- await rooms[0].emit('room.snapshot', {
1965
- room_code: 'TRAIN1',
1966
- room_type: 'training_dummy',
1967
- status: 'waiting',
1968
- members: [],
1969
- }, {
1970
- room_code: 'TRAIN1',
1971
- room_type: 'training_dummy',
1972
- status: 'waiting',
1973
- members: [],
1974
- }, 1);
1975
- await rooms[0].emit('room.self_left', {}, null, 2);
1976
-
1977
- await expect(source.waitForCompletion()).resolves.toEqual({ reason: 'left' });
1978
- await runtime.flush();
1979
- expect(runtime.repository.latestEventByType(
1980
- runtime.scope().sessionId,
1981
- 'game_over',
1982
- )?.payload).toMatchObject({ game_mode: 'training_dummy' });
1983
- await runtime.close();
1984
- });
1985
-
1986
- it('projects room member presence and wakes for the idle warning', async () => {
1987
- const { runtime, source, rooms } = await fixture([
1988
- { status: 'in_room', mode: 'room', room_code: 'R1' },
1989
- ]);
1990
- await waitUntil(() => rooms.length === 1, 'Room transport was not started.');
1991
-
1992
- await rooms[0].emit('room.snapshot', {
1993
- room_code: 'R1',
1994
- status: 'waiting',
1995
- idle_destroy_at: 100,
1996
- members: [{ agent_id: 'agent-2', name: 'P2', status: 'offline' }],
1997
- }, {
1998
- room_code: 'R1',
1999
- status: 'waiting',
2000
- idle_destroy_at: 100,
2001
- members: [{ agent_id: 'agent-2', name: 'P2', status: 'offline' }],
2002
- }, 1);
2003
- await rooms[0].emit('room.member_status_changed', {
2004
- agent_id: 'agent-2',
2005
- status: 'online',
2006
- }, {
2007
- room_code: 'R1',
2008
- status: 'waiting',
2009
- idle_destroy_at: 100,
2010
- members: [{ agent_id: 'agent-2', name: 'P2', status: 'online' }],
2011
- }, 2);
2012
- await rooms[0].emit('room.idle_warning', {
2013
- destroy_at: 200,
2014
- seconds_remaining: 119,
2015
- }, {
2016
- room_code: 'R1',
2017
- status: 'waiting',
2018
- idle_destroy_at: 200,
2019
- members: [{ agent_id: 'agent-2', name: 'P2', status: 'online' }],
2020
- }, 3);
2021
- const latestEpoch = runtime.inputJournal.list(runtime.scope(), 0, 100).at(-1)!;
2022
- await runtime.waitForEpochReadyView(latestEpoch.epochSeq);
2023
- await runtime.flush();
2024
-
2025
- expect(runtime.readReadyView().state.state).toMatchObject({
2026
- phase: 'room_waiting',
2027
- room: {
2028
- idle_destroy_at: 200,
2029
- members: [{ agent_id: 'agent-2', status: 'online' }],
2030
- },
2031
- });
2032
- const memberStatus = runtime.repository.latestEventByType(
2033
- runtime.scope().sessionId,
2034
- 'room.member_status_changed',
2035
- );
2036
- const idleWarning = runtime.repository.latestEventByType(
2037
- runtime.scope().sessionId,
2038
- 'room.idle_warning',
2039
- );
2040
- expect(memberStatus).toMatchObject({
2041
- producer: 'backend_push',
2042
- deliveryClass: 'monitor_and_events',
2043
- payload: { agent_id: 'agent-2', status: 'online' },
2044
- });
2045
- expect(idleWarning).toMatchObject({
2046
- producer: 'backend_push',
2047
- deliveryClass: 'monitor_and_events',
2048
- payload: { destroy_at: 200, seconds_remaining: 119 },
2049
- });
2050
- expect(presentCanonicalEvent(idleWarning!, null).hint).toContain('pings do not extend');
2051
-
2052
- await source.stop();
2053
- await runtime.close();
2054
- });
2055
-
2056
- it('keeps room mode on a locally synthesized user_left_game Event', async () => {
2057
- const { runtime, source, games, rooms } = await fixture([
2058
- { status: 'in_room', room_code: 'R1' },
2059
- { status: 'in_room', room_code: 'R1' },
2060
- ]);
2061
- await waitUntil(() => rooms.length === 1, 'Room transport was not started.');
2062
- await rooms[0].emit('room.game_started', {
2063
- game_id: 'G-left',
2064
- ws_url: 'wss://room-game.test/ws',
2065
- }, {
2066
- room_code: 'R1',
2067
- status: 'playing',
2068
- game_id: 'G-left',
2069
- ws_url: 'wss://room-game.test/ws',
2070
- members: [],
2071
- }, 1);
2072
- await waitUntil(() => games.length === 1, 'Room game transport was not started.');
2073
- await games[0].close({ code: 1000, reason: 'left game' });
2074
- await waitUntil(() => rooms.length === 2, 'Source did not return to the room.');
2075
- await rooms[1].emit('room.self_left', {}, null, 2);
2076
-
2077
- await expect(source.waitForCompletion()).resolves.toEqual({ reason: 'left' });
2078
- await runtime.flush();
2079
- const userLeft = runtime.repository.latestEventByType(
2080
- runtime.scope().sessionId,
2081
- 'user_left_game',
2082
- );
2083
- expect(userLeft?.payload).toMatchObject({ game_mode: 'room' });
2084
- expect(presentCanonicalEvent(userLeft!, null).hint)
2085
- .toContain('runtime returns to the room');
2086
- await runtime.close();
2087
- });
2088
-
2089
- it('keeps room terminal guidance when exile_game_over is the only terminal Event', async () => {
2090
- const { runtime, source, games, rooms } = await fixture([
2091
- { status: 'in_room', room_code: 'R1' },
2092
- { status: 'in_room', room_code: 'R1' },
2093
- ]);
2094
- await waitUntil(() => rooms.length === 1, 'Room transport was not started.');
2095
- await rooms[0].emit('room.game_started', {
2096
- game_id: 'G-exile',
2097
- ws_url: 'wss://room-game.test/ws',
2098
- }, {
2099
- room_code: 'R1',
2100
- status: 'playing',
2101
- game_id: 'G-exile',
2102
- ws_url: 'wss://room-game.test/ws',
2103
- members: [],
2104
- }, 1);
2105
- await waitUntil(() => games.length === 1, 'Room game transport was not started.');
2106
- await games[0].emit(gameStateFrame(games[0].connectionId, 1, {
2107
- tick: 10,
2108
- phase: 'meeting',
2109
- }, [{ type: 'exile_game_over', winner: 'lobster' }]));
2110
- await waitUntil(() => rooms.length === 2, 'Source did not return to the room.');
2111
- await rooms[1].emit('room.self_left', {}, null, 2);
2112
-
2113
- await expect(source.waitForCompletion()).resolves.toEqual({ reason: 'left' });
2114
- await runtime.flush();
2115
- const terminal = runtime.repository.latestEventByType(
2116
- runtime.scope().sessionId,
2117
- 'exile_game_over',
2118
- );
2119
- expect(terminal?.payload).toMatchObject({ game_mode: 'room', winner: 'lobster' });
2120
- expect(presentCanonicalEvent(terminal!, null).hint).toContain('room lifecycle');
2121
- expect(presentCanonicalEvent(terminal!, null).hint).toContain('do not start normal matchmaking');
2122
- await runtime.close();
2123
- });
2124
-
2125
- it('reports when a completed room game no longer has a room Lobby', async () => {
2126
- const { runtime, source, games, rooms } = await fixture([
2127
- { status: 'in_room', mode: 'room', room_code: 'R1' },
2128
- { status: 'not_in_queue' },
2129
- ]);
2130
- await waitUntil(() => rooms.length === 1, 'Room transport was not started.');
2131
- await rooms[0].emit('room.game_started', {
2132
- game_id: 'G-missing',
2133
- ws_url: 'wss://room-game.test/ws',
2134
- }, {
2135
- room_code: 'R1',
2136
- status: 'playing',
2137
- game_id: 'G-missing',
2138
- ws_url: 'wss://room-game.test/ws',
2139
- members: [],
2140
- }, 1);
2141
- await waitUntil(() => games.length === 1, 'Room game transport was not started.');
2142
- await games[0].emit(gameStateFrame(games[0].connectionId, 1, {
2143
- tick: 10,
2144
- phase: 'game_over',
2145
- }, [{ type: 'game_over', event_id: 'missing-over' }]));
2146
-
2147
- await expect(source.waitForCompletion()).resolves.toEqual({ reason: 'not_participating' });
2148
- await runtime.flush();
2149
- expect(runtime.repository.listCommittedEvents({
2150
- sessionId: runtime.scope().sessionId,
2151
- types: ['room_returning_to_lobby', 'room_lobby_missing', 'not_in_queue'],
2152
- order: 'asc',
2153
- }).map((event) => event.type)).toEqual([
2154
- 'room_returning_to_lobby',
2155
- 'room_lobby_missing',
2156
- 'not_in_queue',
2157
- ]);
2158
- await runtime.close();
2159
- });
2160
-
2161
- it('reports a Lobby reconnect failure after a completed room game', async () => {
2162
- const lobbyError = new Error('lobby unavailable after game');
2163
- const { runtime, source, games, rooms } = await fixture([
2164
- { status: 'in_room', mode: 'room', room_code: 'R1' },
2165
- lobbyError,
2166
- lobbyError,
2167
- lobbyError,
2168
- ]);
2169
- await waitUntil(() => rooms.length === 1, 'Room transport was not started.');
2170
- await rooms[0].emit('room.game_started', {
2171
- game_id: 'G-reconnect',
2172
- ws_url: 'wss://room-game.test/ws',
2173
- }, {
2174
- room_code: 'R1',
2175
- status: 'playing',
2176
- game_id: 'G-reconnect',
2177
- ws_url: 'wss://room-game.test/ws',
2178
- members: [],
2179
- }, 1);
2180
- await waitUntil(() => games.length === 1, 'Room game transport was not started.');
2181
- await games[0].emit(gameStateFrame(games[0].connectionId, 1, {
2182
- tick: 10,
2183
- phase: 'game_over',
2184
- }, [{ type: 'game_over', event_id: 'reconnect-over' }]));
2185
-
2186
- await expect(source.waitForCompletion()).resolves.toMatchObject({
2187
- reason: 'error',
2188
- error: lobbyError,
2189
- });
2190
- await runtime.flush();
2191
- expect(runtime.repository.listCommittedEvents({
2192
- sessionId: runtime.scope().sessionId,
2193
- types: ['room_lobby_reconnect_failed'],
2194
- })).toHaveLength(1);
2195
- await runtime.close();
2196
- });
2197
-
2198
- it('persists truthful disconnected State for each failed Lobby poll', async () => {
2199
- const failure = new Error('lobby unavailable');
2200
- const { runtime, source } = await fixture([failure, failure, failure]);
2201
- await expect(source.waitForCompletion()).resolves.toMatchObject({ reason: 'error' });
2202
- await runtime.flush();
2203
-
2204
- const failures = runtime.inputJournal.list(runtime.scope(), 0, 100)
2205
- .filter((epoch) => epoch.state.cause === 'transport_error');
2206
- expect(failures).toHaveLength(3);
2207
- expect(failures.every((epoch) => (
2208
- epoch.state.transport === 'lobby_http'
2209
- && epoch.state.connection === 'disconnected'
2210
- && epoch.events.length === 1
2211
- && epoch.events[0]?.type === 'poll_error'
2212
- ))).toBe(true);
2213
- expect(failures.map((epoch) => epoch.events[0]?.payload)).toMatchObject([
2214
- { consecutive_failures: 1, retrying: true },
2215
- { consecutive_failures: 2, retrying: true },
2216
- { consecutive_failures: 3, retrying: false },
2217
- ]);
2218
- expect(runtime.inputJournal.list(runtime.scope(), 0, 100).at(-1)).toMatchObject({
2219
- state: {
2220
- stage: 'ended',
2221
- connection: 'disconnected',
2222
- cause: 'ending',
2223
- control: { type: 'source_completed', reason: 'error' },
2224
- },
2225
- events: [{
2226
- type: 'error',
2227
- producer: 'local_synth',
2228
- payload: { code: 'SOURCE_FAILED', phase: 'runtime' },
2229
- }],
2230
- });
2231
- await runtime.close();
2232
- });
2233
-
2234
- it('keeps competition mode on a terminal Source error before queue join', async () => {
2235
- const failure = new Error('lobby unavailable');
2236
- const { runtime, source } = await fixture(
2237
- [failure, failure, failure],
2238
- { kind: 'match', mode: 'competition' },
2239
- );
2240
- await expect(source.waitForCompletion()).resolves.toMatchObject({ reason: 'error' });
2241
- await runtime.flush();
2242
-
2243
- const terminal = runtime.repository.latestEventByType(
2244
- runtime.scope().sessionId,
2245
- 'error',
2246
- );
2247
- expect(terminal?.payload).toMatchObject({
2248
- code: 'SOURCE_FAILED',
2249
- phase: 'runtime',
2250
- game_mode: 'competition',
2251
- });
2252
- expect(presentCanonicalEvent(terminal!, null).hint)
2253
- .toContain('competition runtime failed');
2254
- expect(presentCanonicalEvent(terminal!, null).hint)
2255
- .toContain('Do not fall back to normal matchmaking');
2256
- await runtime.close();
2257
- });
2258
-
2259
- it('reports a room heartbeat timeout before retrying the Room transport', async () => {
2260
- const { runtime, source, rooms } = await fixture([
2261
- { status: 'in_room', mode: 'room', room_code: 'R1' },
2262
- ]);
2263
- await waitUntil(() => rooms.length === 1, 'Room transport was not started.');
2264
-
2265
- await rooms[0].close({ reason: 'heartbeat_timeout' });
2266
- await runtime.flush();
2267
- expect(runtime.repository.listCommittedEvents({
2268
- sessionId: runtime.scope().sessionId,
2269
- types: ['room_ping_timeout'],
2270
- })).toHaveLength(1);
2271
-
2272
- await source.submitIntent({ kind: 'stop' });
2273
- await expect(source.waitForCompletion()).resolves.toEqual({ reason: 'stopped' });
2274
- await runtime.close();
2275
- });
2276
-
2277
- it('treats Room close 4005 as terminal destruction without waiting for room.self_left', async () => {
2278
- const { runtime, source, rooms } = await fixture([
2279
- { status: 'in_room', mode: 'room', room_code: 'R1' },
2280
- ]);
2281
- await waitUntil(() => rooms.length === 1, 'Room transport was not started.');
2282
- await rooms[0].emit('room.snapshot', {
2283
- room_code: 'R1',
2284
- status: 'waiting',
2285
- members: [],
2286
- }, {
2287
- room_code: 'R1',
2288
- status: 'waiting',
2289
- members: [],
2290
- }, 1);
2291
-
2292
- await rooms[0].close({ code: 4005, reason: 'idle_timeout' });
2293
-
2294
- await expect(source.waitForCompletion()).resolves.toEqual({ reason: 'not_participating' });
2295
- await runtime.flush();
2296
- expect(rooms).toHaveLength(1);
2297
- const destroyed = runtime.repository.latestEventByType(
2298
- runtime.scope().sessionId,
2299
- 'room_destroyed',
2300
- );
2301
- expect(destroyed).toMatchObject({
2302
- producer: 'local_synth',
2303
- deliveryClass: 'monitor_and_events',
2304
- payload: { close_code: 4005, reason: 'idle_timeout' },
2305
- });
2306
- expect(presentCanonicalEvent(destroyed!, null).hint)
2307
- .toContain('do not create or join another room');
2308
- expect(runtime.inputJournal.list(runtime.scope(), 0, 100).at(-1)?.state).toMatchObject({
2309
- stage: 'ended',
2310
- transport: 'room_ws',
2311
- connection: 'disconnected',
2312
- });
2313
- expect(runtime.inputJournal.list(runtime.scope(), 0, 100).at(-1)?.state).not.toHaveProperty('room');
2314
- expect(runtime.inputJournal.list(runtime.scope(), 0, 100).at(-1)?.state).not.toHaveProperty('queue');
2315
- await runtime.close();
2316
- });
2317
-
2318
- it('keeps polling an unknown queue response instead of treating it as departure', async () => {
2319
- const { runtime, source } = await fixture([
2320
- { message: 'queue state pending' },
2321
- { status: 'not_in_queue' },
2322
- ]);
2323
-
2324
- await expect(source.waitForCompletion()).resolves.toEqual({ reason: 'not_participating' });
2325
- await runtime.flush();
2326
- const epochs = runtime.inputJournal.list(runtime.scope(), 0, 100);
2327
- expect(epochs.map((epoch) => epoch.state.stage)).toEqual(['matching', 'ended']);
2328
- expect(epochs.at(-1)?.state.cause).toBe('ending');
2329
- await runtime.close();
2330
- });
2331
-
2332
- it('treats allocating as matching and advances when allocation arrives', async () => {
2333
- const { runtime, source, games } = await fixture([
2334
- { status: 'allocating', mode: 'match' },
2335
- { status: 'allocated', mode: 'match', game_id: 'G2' },
2336
- ]);
2337
- await waitUntil(() => games.length === 1, 'Game transport was not started after allocating.');
2338
-
2339
- await source.submitIntent({ kind: 'stop' });
2340
- await expect(source.waitForCompletion()).resolves.toEqual({ reason: 'stopped' });
2341
- await runtime.flush();
2342
- expect(runtime.inputJournal.list(runtime.scope(), 0, 100).at(-1)).toMatchObject({
2343
- state: { stage: 'ended', cause: 'ending', control: { type: 'stop' } },
2344
- events: [{ type: 'stop_requested' }],
2345
- });
2346
- await runtime.close();
2347
- });
2348
-
2349
- it('preserves a join error when reconciliation confirms no participation', async () => {
2350
- const joinError = new Error('competition closed');
2351
- const { runtime, source } = await fixture(
2352
- [{ status: 'not_in_queue' }, { status: 'not_in_queue' }],
2353
- { kind: 'match' },
2354
- { configureClient: (client) => client.joinQueue.mockRejectedValueOnce(joinError) },
2355
- );
2356
-
2357
- await expect(source.waitForCompletion()).resolves.toEqual({ reason: 'error', error: joinError });
2358
- await runtime.close();
2359
- });
2360
-
2361
- it('preserves structured competition start failure facts for Mailbox guidance', async () => {
2362
- const joinError = new ApiError(
2363
- 409,
2364
- JSON.stringify({
2365
- error: {
2366
- code: 'COMPETITION_NOT_OPEN',
2367
- message: 'Competition is closed.',
2368
- },
2369
- }),
2370
- 'POST',
2371
- '/api/v1/queue/join',
2372
- );
2373
- const { runtime, source, client } = await fixture(
2374
- [{ status: 'not_in_queue' }, { status: 'not_in_queue' }],
2375
- { kind: 'match', mode: 'competition' },
2376
- { configureClient: (configured) => configured.joinQueue.mockRejectedValueOnce(joinError) },
2377
- );
2378
-
2379
- await expect(source.waitForCompletion()).resolves.toEqual({ reason: 'error', error: joinError });
2380
- await runtime.flush();
2381
- const failures = runtime.repository.listCommittedEvents({
2382
- sessionId: runtime.scope().sessionId,
2383
- types: ['game_start_failed', 'error'],
2384
- order: 'asc',
2385
- });
2386
- expect(failures).toHaveLength(1);
2387
- expect(failures[0]).toMatchObject({
2388
- type: 'game_start_failed',
2389
- producer: 'local_synth',
2390
- payload: {
2391
- game_mode: 'competition',
2392
- exit_reason: 'competition_not_open',
2393
- error: {
2394
- status: 409,
2395
- code: 'COMPETITION_NOT_OPEN',
2396
- message: 'Competition is closed.',
2397
- },
2398
- competition: {
2399
- id: 'competition-1',
2400
- active: true,
2401
- status: 'NOT_OPEN',
2402
- is_open: false,
2403
- daily_windows: ['20:00-22:00'],
2404
- },
2405
- },
2406
- });
2407
- expect(client.getCompetitionStatus).toHaveBeenCalledOnce();
2408
- await runtime.close();
2409
- });
2410
-
2411
- it('recovers when a failed join request actually created participation', async () => {
2412
- const joinError = new Error('response lost');
2413
- const { runtime, source, games } = await fixture(
2414
- [
2415
- { status: 'not_in_queue' },
2416
- { status: 'allocated', mode: 'match', game_id: 'G-recovered' },
2417
- ],
2418
- { kind: 'match' },
2419
- { configureClient: (client) => client.joinQueue.mockRejectedValueOnce(joinError) },
2420
- );
2421
- await waitUntil(() => games.length === 1, 'Recovered Game transport was not started.');
2422
-
2423
- await games[0].emit(gameStateFrame(games[0].connectionId, 1, {
2424
- tick: 1,
2425
- phase: 'game_over',
2426
- }, [{ type: 'game_over', event_id: 'recovered-over' }]));
2427
- await expect(source.waitForCompletion()).resolves.toEqual({ reason: 'game_over' });
2428
- await runtime.flush();
2429
- const recoveredEvents = runtime.repository.listCommittedEvents({
2430
- sessionId: runtime.scope().sessionId,
2431
- types: ['session_recovered', 'joined'],
2432
- order: 'asc',
2433
- });
2434
- expect(recoveredEvents.map((event) => event.type)).toEqual(['session_recovered', 'joined']);
2435
- expect(recoveredEvents[0]?.payload).toEqual(expect.objectContaining({
2436
- operation: 'join_queue',
2437
- initial_request_confirmation: 'missing_or_failed',
2438
- queue_reconciliation: 'active_participation_confirmed',
2439
- local_history_completeness: 'possibly_incomplete',
2440
- status: 'allocated',
2441
- game_mode: 'match',
2442
- game_id: 'G-recovered',
2443
- }));
2444
- expect(recoveredEvents[0]?.payload).not.toHaveProperty('hint');
2445
- await runtime.close();
2446
- });
2447
-
2448
- it('resumes the target room without sending a duplicate join request', async () => {
2449
- const { runtime, source, rooms, client } = await fixture(
2450
- [{ status: 'in_room', mode: 'room', room_code: 'R1' }],
2451
- { kind: 'join_room', roomCode: 'R1' },
2452
- );
2453
- await waitUntil(() => rooms.length === 1, 'Room transport was not started.');
2454
- expect(client.joinRoom).not.toHaveBeenCalled();
2455
- await runtime.flush();
2456
- expect(runtime.repository.listCommittedEvents({
2457
- sessionId: runtime.scope().sessionId,
2458
- types: ['session_resumed', 'room_joined'],
2459
- order: 'asc',
2460
- }).map((event) => event.type)).toEqual(['session_resumed', 'room_joined']);
2461
-
2462
- await source.submitIntent({ kind: 'stop' });
2463
- await expect(source.waitForCompletion()).resolves.toEqual({ reason: 'stopped' });
2464
- await runtime.close();
2465
- });
2466
-
2467
- it('resumes an existing room when create-room is requested again', async () => {
2468
- const { runtime, source, rooms, client } = await fixture(
2469
- [{ status: 'in_room', mode: 'room', room_code: 'R1' }],
2470
- { kind: 'create_room' },
2471
- );
2472
- await waitUntil(() => rooms.length === 1, 'Existing Room transport was not started.');
2473
- expect(client.createRoom).not.toHaveBeenCalled();
2474
-
2475
- await source.submitIntent({ kind: 'stop' });
2476
- await expect(source.waitForCompletion()).resolves.toEqual({ reason: 'stopped' });
2477
- await runtime.close();
2478
- });
2479
-
2480
- it('leaves a different waiting room before joining the requested room', async () => {
2481
- const { runtime, source, rooms, client } = await fixture(
2482
- [{ status: 'in_room', mode: 'room', room_code: 'R1' }],
2483
- { kind: 'join_room', roomCode: 'R2', agentType: 'openclaw', llmModel: 'deepseek-v4-pro' },
2484
- );
2485
- await waitUntil(() => rooms.length === 1, 'Requested Room transport was not started.');
2486
- expect(client.leaveRoom).toHaveBeenCalledTimes(1);
2487
- expect(client.joinRoom).toHaveBeenCalledWith('R2', {
2488
- agentType: 'openclaw',
2489
- monitorStatus: undefined,
2490
- llmModel: 'deepseek-v4-pro',
2491
- });
2492
- await runtime.flush();
2493
- expect(runtime.repository.listCommittedEvents({
2494
- sessionId: runtime.scope().sessionId,
2495
- types: ['room_joined'],
2496
- })).toHaveLength(1);
2497
-
2498
- await source.submitIntent({ kind: 'stop' });
2499
- await expect(source.waitForCompletion()).resolves.toEqual({ reason: 'stopped' });
2500
- await runtime.close();
2501
- });
2502
-
2503
- it('refuses to switch rooms while a room game is allocated', async () => {
2504
- const { runtime, source, client } = await fixture(
2505
- [{ status: 'allocated', mode: 'room', room_code: 'R1', game_id: 'G1' }],
2506
- { kind: 'join_room', roomCode: 'R2' },
2507
- );
2508
-
2509
- await expect(source.waitForCompletion()).resolves.toMatchObject({
2510
- reason: 'error',
2511
- error: expect.objectContaining({ message: 'Cannot join room R2 while a room game is allocated.' }),
2512
- });
2513
- expect(client.leaveRoom).not.toHaveBeenCalled();
2514
- expect(client.joinRoom).not.toHaveBeenCalled();
2515
- await runtime.close();
2516
- });
2517
-
2518
- it('recovers the target room when the join response is lost', async () => {
2519
- const joinError = new Error('response lost');
2520
- const { runtime, source, rooms, client } = await fixture(
2521
- [
2522
- { status: 'not_in_queue' },
2523
- { status: 'in_room', mode: 'room', room_code: 'R2' },
2524
- ],
2525
- { kind: 'join_room', roomCode: 'R2' },
2526
- { configureClient: (configured) => configured.joinRoom.mockRejectedValueOnce(joinError) },
2527
- );
2528
- await waitUntil(() => rooms.length === 1, 'Reconciled Room transport was not started.');
2529
- expect(client.joinRoom).toHaveBeenCalledWith('R2', {
2530
- agentType: undefined,
2531
- monitorStatus: undefined,
2532
- llmModel: undefined,
2533
- });
2534
-
2535
- await source.submitIntent({ kind: 'stop' });
2536
- await expect(source.waitForCompletion()).resolves.toEqual({ reason: 'stopped' });
2537
- await runtime.close();
2538
- });
2539
-
2540
- it('reconciles through Lobby when Game WS never produces its first State', async () => {
2541
- const { runtime, source, games } = await fixture(
2542
- [
2543
- { status: 'allocated', mode: 'match', game_id: 'G-silent' },
2544
- { status: 'not_in_queue' },
2545
- ],
2546
- { kind: 'resume' },
2547
- { source: { gameFirstStateTimeoutMs: 1, reconcileBaseDelayMs: 0 } },
2548
- );
2549
-
2550
- await expect(source.waitForCompletion()).resolves.toEqual({ reason: 'not_participating' });
2551
- expect(games[0].stoppedWith).toBe('reconcile');
2552
- await runtime.flush();
2553
- expect(runtime.repository.listCommittedEvents({
2554
- sessionId: runtime.scope().sessionId,
2555
- types: ['game_start_failed'],
2556
- })).toHaveLength(1);
2557
- await runtime.close();
2558
- });
2559
-
2560
- it('reports both the quit request and a failed remote quit', async () => {
2561
- const quitError = new Error('leave rejected');
2562
- const { runtime, source, games } = await fixture(
2563
- [{ status: 'allocated', mode: 'match', game_id: 'G-quit' }],
2564
- { kind: 'resume' },
2565
- { configureClient: (client) => client.leaveGame.mockRejectedValueOnce(quitError) },
2566
- );
2567
- await waitUntil(() => games.length === 1, 'Game transport was not started.');
2568
-
2569
- await expect(source.submitIntent({ kind: 'leave' })).rejects.toBe(quitError);
2570
- await runtime.flush();
2571
- expect(runtime.repository.listCommittedEvents({
2572
- sessionId: runtime.scope().sessionId,
2573
- types: ['quit_requested', 'quit_failed'],
2574
- order: 'asc',
2575
- }).map((event) => event.type)).toEqual(['quit_requested', 'quit_failed']);
2576
-
2577
- await source.submitIntent({ kind: 'stop' });
2578
- await expect(source.waitForCompletion()).resolves.toEqual({ reason: 'stopped' });
2579
- await runtime.close();
2580
- });
2581
-
2582
- it('treats an HTTP 200 STILL_ALIVE body as a failed remote quit', async () => {
2583
- const { runtime, source, games } = await fixture(
2584
- [{ status: 'allocated', mode: 'match', game_id: 'G-alive' }],
2585
- { kind: 'resume' },
2586
- {
2587
- configureClient: (client) => client.leaveGame.mockResolvedValueOnce({
2588
- success: false,
2589
- error: { code: 'STILL_ALIVE', message: 'You can only leave when dead' },
2590
- }),
2591
- },
2592
- );
2593
- await waitUntil(() => games.length === 1, 'Game transport was not started.');
2594
- const scope = runtime.scope();
2595
-
2596
- await expect(source.submitIntent({ kind: 'leave' })).rejects.toMatchObject({
2597
- code: 'STILL_ALIVE',
2598
- still_alive: true,
2599
- });
2600
- await runtime.flush();
2601
- expect(runtime.repository.listCommittedEvents({
2602
- sessionId: runtime.scope().sessionId,
2603
- types: ['quit_requested', 'quit_failed'],
2604
- order: 'asc',
2605
- }).map((event) => event.type)).toEqual(['quit_requested', 'quit_failed']);
2606
-
2607
- await source.submitIntent({ kind: 'stop' });
2608
- await expect(source.waitForCompletion()).resolves.toEqual({ reason: 'stopped' });
2609
- await runtime.close();
2610
- expect(runtime.repository.currentScope({
2611
- adapterId: scope.adapterId,
2612
- accountId: scope.accountId,
2613
- })).toBeNull();
2614
- expect(runtime.repository.latestScope({
2615
- adapterId: scope.adapterId,
2616
- accountId: scope.accountId,
2617
- })).toMatchObject({
2618
- session: { sessionId: scope.sessionId, status: 'sealed', isCurrent: false },
2619
- segment: { segmentId: scope.segmentId, status: 'closed', isCurrent: false },
2620
- });
2621
- });
2622
-
2623
- it('backs off repeated same-transport reconciliation attempts', async () => {
2624
- const sleepDelays: number[] = [];
2625
- const { runtime, source, games } = await fixture(
2626
- [
2627
- { status: 'allocated', mode: 'match', game_id: 'G-retry' },
2628
- { status: 'allocated', mode: 'match', game_id: 'G-retry' },
2629
- { status: 'not_in_queue' },
2630
- ],
2631
- { kind: 'resume' },
2632
- {
2633
- sleepDelays,
2634
- source: { reconcileBaseDelayMs: 7, reconcileMaxDelayMs: 20 },
2635
- },
2636
- );
2637
- await waitUntil(() => games.length === 1, 'First Game transport was not started.');
2638
- await games[0].stop('reconcile');
2639
- await waitUntil(() => games.length === 2, 'Second Game transport was not started.');
2640
- await games[1].stop('reconcile');
2641
-
2642
- await expect(source.waitForCompletion()).resolves.toEqual({ reason: 'not_participating' });
2643
- expect(sleepDelays).toEqual([7, 14]);
2644
- await runtime.close();
2645
- });
2646
- });