@myclaw163/clawclaw-cli 0.6.96 → 0.6.100

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 (231) hide show
  1. package/README.md +385 -385
  2. package/package.json +48 -48
  3. package/personas//345/217/243/346/230/257/345/277/203/351/235/236.md +50 -50
  4. package/personas//345/277/240/345/277/203/350/200/201/344/273/206.md +51 -51
  5. package/personas//346/227/240/344/272/272/350/256/276.md +1 -1
  6. package/personas//350/264/253/345/230/264/346/215/237/345/217/213.md +48 -48
  7. package/personas//350/275/257/350/220/214/350/205/271/351/273/221.md +51 -51
  8. package/scripts/check-skill-command-surface.mjs +118 -118
  9. package/scripts/check_monitor.cjs +435 -435
  10. package/scripts/check_monitor.test.mjs +212 -212
  11. package/scripts/enable_ccl_permissions.cjs +147 -147
  12. package/scripts/enable_ccl_permissions.test.mjs +132 -132
  13. package/scripts/enable_monitor.cjs +677 -677
  14. package/scripts/enable_monitor.test.mjs +201 -201
  15. package/scripts/find-hide-spots.py +157 -157
  16. package/scripts/postinstall.mjs +20 -20
  17. package/scripts/sync-bundled-skill.mjs +254 -254
  18. package/scripts/sync-bundled-skill.test.mjs +152 -152
  19. package/skills/clawclaw/SKILL.md +290 -274
  20. package/skills/clawclaw/references/CHATTERBOX.md +142 -142
  21. package/skills/clawclaw/references/CLAUDE-CODE-MONITOR.md +224 -224
  22. package/skills/clawclaw/references/COMMANDS.md +177 -165
  23. package/skills/clawclaw/references/GAME-MECHANICS.md +190 -190
  24. package/skills/clawclaw/references/HUB.md +48 -48
  25. package/skills/clawclaw/references/KNOWLEDGE.md +42 -42
  26. package/skills/clawclaw/references/STRATEGIES.md +59 -59
  27. package/skills/clawclaw/references/STREAM.md +77 -74
  28. package/skills/clawclaw/references/TACTICS.md +65 -65
  29. package/src/assets/clawclaw-ascii-map.txt +40 -40
  30. package/src/cli.ts +113 -113
  31. package/src/commands/_schema.ts +124 -124
  32. package/src/commands/account.test.ts +332 -332
  33. package/src/commands/account.ts +315 -315
  34. package/src/commands/competition.ts +42 -42
  35. package/src/commands/config.ts +30 -30
  36. package/src/commands/data.test.ts +33 -33
  37. package/src/commands/data.ts +22 -22
  38. package/src/commands/do.test.ts +117 -91
  39. package/src/commands/do.ts +191 -130
  40. package/src/commands/events.test.ts +142 -124
  41. package/src/commands/events.ts +268 -262
  42. package/src/commands/game-map.test.ts +28 -28
  43. package/src/commands/game-monitor-status.test.ts +58 -58
  44. package/src/commands/game-start-plan.test.ts +252 -94
  45. package/src/commands/game.ts +1892 -1286
  46. package/src/commands/history-player.test.ts +105 -102
  47. package/src/commands/history.ts +573 -573
  48. package/src/commands/hub.test.ts +113 -113
  49. package/src/commands/hub.ts +244 -244
  50. package/src/commands/knowledge.test.ts +13 -13
  51. package/src/commands/knowledge.ts +176 -176
  52. package/src/commands/load.test.ts +65 -65
  53. package/src/commands/load.ts +22 -22
  54. package/src/commands/meeting-history.test.ts +106 -106
  55. package/src/commands/memory.ts +40 -40
  56. package/src/commands/peek.ts +45 -45
  57. package/src/commands/persona.ts +62 -62
  58. package/src/commands/setup/codex.ts +266 -266
  59. package/src/commands/setup/hermes.test.ts +96 -96
  60. package/src/commands/setup/hermes.ts +76 -76
  61. package/src/commands/setup/index.ts +13 -13
  62. package/src/commands/setup/openclaw.test.ts +114 -114
  63. package/src/commands/setup/openclaw.ts +147 -147
  64. package/src/commands/skill.ts +128 -128
  65. package/src/commands/state.ts +46 -46
  66. package/src/commands/strategy.test.ts +153 -153
  67. package/src/commands/strategy.ts +194 -194
  68. package/src/commands/upgrade.test.ts +82 -82
  69. package/src/commands/upgrade.ts +148 -148
  70. package/src/commands/watch.test.ts +1313 -1041
  71. package/src/commands/watch.ts +824 -664
  72. package/src/lib/account-guidance.test.ts +32 -32
  73. package/src/lib/account-guidance.ts +62 -62
  74. package/src/lib/auth.test.ts +116 -116
  75. package/src/lib/auth.ts +189 -189
  76. package/src/lib/command-meta.ts +37 -37
  77. package/src/lib/competition.ts +79 -79
  78. package/src/lib/game-client.test.ts +82 -82
  79. package/src/lib/game-client.ts +443 -409
  80. package/src/lib/game-context.ts +92 -92
  81. package/src/lib/host-config-patcher.test.ts +130 -130
  82. package/src/lib/host-config-patcher.ts +151 -151
  83. package/src/lib/http-keepalive.ts +15 -15
  84. package/src/lib/http-transport.test.ts +61 -61
  85. package/src/lib/http-transport.ts +118 -118
  86. package/src/lib/hub-client.test.ts +57 -57
  87. package/src/lib/hub-client.ts +88 -88
  88. package/src/lib/hub-install.test.ts +139 -139
  89. package/src/lib/hub-install.ts +198 -198
  90. package/src/lib/hub-reminder.ts +81 -81
  91. package/src/lib/hub-unzip.test.ts +69 -69
  92. package/src/lib/hub-unzip.ts +62 -62
  93. package/src/lib/init-command.test.ts +75 -75
  94. package/src/lib/init-command.ts +130 -130
  95. package/src/lib/knowledge-store.test.ts +170 -170
  96. package/src/lib/knowledge-store.ts +369 -369
  97. package/src/lib/load-context.test.ts +62 -62
  98. package/src/lib/load-context.ts +49 -49
  99. package/src/lib/match-state.test.ts +134 -134
  100. package/src/lib/match-state.ts +94 -94
  101. package/src/lib/normalize.ts +42 -42
  102. package/src/lib/persona.test.ts +84 -84
  103. package/src/lib/persona.ts +120 -120
  104. package/src/lib/room.test.ts +74 -0
  105. package/src/lib/room.ts +129 -0
  106. package/src/lib/server-registry.test.ts +54 -0
  107. package/src/lib/server-registry.ts +185 -152
  108. package/src/lib/skill-version.test.ts +48 -48
  109. package/src/lib/skill-version.ts +19 -19
  110. package/src/lib/strategy-export.test.ts +240 -240
  111. package/src/lib/strategy-export.ts +247 -247
  112. package/src/lib/user-data.test.ts +97 -97
  113. package/src/lib/user-data.ts +374 -374
  114. package/src/lib/workspace-argv.test.ts +49 -49
  115. package/src/lib/workspace-argv.ts +44 -44
  116. package/src/perception/player-history-store.test.ts +177 -87
  117. package/src/perception/player-history-store.ts +262 -194
  118. package/src/pipeline/event-format.test.ts +307 -247
  119. package/src/pipeline/event-format.ts +595 -507
  120. package/src/pipeline/event-hints.ts +204 -195
  121. package/src/pipeline/event-store.test.ts +28 -28
  122. package/src/pipeline/event-store.ts +193 -193
  123. package/src/pipeline/pipeline.ts +35 -35
  124. package/src/pipeline/player-projection.test.ts +168 -168
  125. package/src/pipeline/player-projection.ts +370 -370
  126. package/src/runtime/auto-upgrade.test.ts +66 -66
  127. package/src/runtime/auto-upgrade.ts +31 -31
  128. package/src/runtime/event-daemon.test.ts +268 -225
  129. package/src/runtime/event-daemon.ts +531 -527
  130. package/src/runtime/owner-control.ts +150 -150
  131. package/src/runtime/raw-ws-log.test.ts +33 -33
  132. package/src/runtime/raw-ws-log.ts +32 -32
  133. package/src/runtime/room-lobby-runtime.test.ts +95 -0
  134. package/src/runtime/room-lobby-runtime.ts +367 -0
  135. package/src/runtime/runtime-logger.ts +107 -107
  136. package/src/runtime/ws-client.test.ts +169 -169
  137. package/src/runtime/ws-client.ts +280 -280
  138. package/src/sdk/action.ts +155 -155
  139. package/src/sdk/index.ts +112 -112
  140. package/src/sdk/types.ts +163 -163
  141. package/src/strategies/avoid-lone.ts +14 -14
  142. package/src/strategies/avoid-players.knowledge.md +19 -19
  143. package/src/strategies/avoid-players.ts +18 -18
  144. package/src/strategies/corpse-patrol.ts +21 -21
  145. package/src/strategies/crab-sabotage.ts +24 -24
  146. package/src/strategies/custom-module.test.ts +270 -270
  147. package/src/strategies/find-player.ts +19 -19
  148. package/src/strategies/game-utils.test.ts +242 -242
  149. package/src/strategies/game-utils.ts +853 -853
  150. package/src/strategies/goals/anchor-linger.ts +77 -77
  151. package/src/strategies/goals/avoid-lone-top.ts +168 -168
  152. package/src/strategies/goals/avoid-players-top.test.ts +83 -83
  153. package/src/strategies/goals/avoid-players-top.ts +121 -121
  154. package/src/strategies/goals/conversation-goal.ts +51 -51
  155. package/src/strategies/goals/corpse-patrol-top.ts +113 -113
  156. package/src/strategies/goals/crab-octopus-reflexes.ts +101 -101
  157. package/src/strategies/goals/crab-sabotage-top.ts +226 -226
  158. package/src/strategies/goals/emergency-hunt-goal.ts +28 -28
  159. package/src/strategies/goals/find-player-top.ts +93 -93
  160. package/src/strategies/goals/flee-players-goal.ts +53 -53
  161. package/src/strategies/goals/follow-companion-goal.ts +106 -106
  162. package/src/strategies/goals/goal-manager.ts +41 -41
  163. package/src/strategies/goals/goal-root-strategy.ts +49 -49
  164. package/src/strategies/goals/goal.ts +28 -28
  165. package/src/strategies/goals/hide-top.ts +197 -197
  166. package/src/strategies/goals/keep-away-goal.ts +221 -221
  167. package/src/strategies/goals/kill-frenzy-top.ts +80 -80
  168. package/src/strategies/goals/kill-lone-top.ts +160 -160
  169. package/src/strategies/goals/kill-target-goal.ts +59 -59
  170. package/src/strategies/goals/kill-target-top.ts +109 -109
  171. package/src/strategies/goals/leaf-goal.ts +27 -27
  172. package/src/strategies/goals/linger-corpse-goal.ts +35 -35
  173. package/src/strategies/goals/lone-kill-core.ts +82 -82
  174. package/src/strategies/goals/lone-kill-goal.ts +24 -24
  175. package/src/strategies/goals/lone-kill-task-top.test.ts +85 -85
  176. package/src/strategies/goals/lone-kill-task-top.ts +133 -133
  177. package/src/strategies/goals/move-room-goal.ts +60 -60
  178. package/src/strategies/goals/normal-shrimp-top.test.ts +97 -97
  179. package/src/strategies/goals/normal-shrimp-top.ts +248 -248
  180. package/src/strategies/goals/paradise-fish-top.test.ts +126 -126
  181. package/src/strategies/goals/paradise-fish-top.ts +224 -224
  182. package/src/strategies/goals/patrol-top.ts +57 -57
  183. package/src/strategies/goals/report-patrol-top.ts +86 -86
  184. package/src/strategies/goals/safe-task-goal.ts +102 -102
  185. package/src/strategies/goals/social-task-top.ts +161 -161
  186. package/src/strategies/goals/task-kill-report-top.ts +163 -163
  187. package/src/strategies/goals/task-only-top.ts +57 -57
  188. package/src/strategies/goals/task-or-patrol-goal.ts +41 -41
  189. package/src/strategies/goals/task-report-top.ts +57 -57
  190. package/src/strategies/goals/wander-task-goal.ts +33 -33
  191. package/src/strategies/goals/warrior-shrimp-top.test.ts +87 -87
  192. package/src/strategies/goals/warrior-shrimp-top.ts +267 -267
  193. package/src/strategies/greeting.ts +53 -53
  194. package/src/strategies/hide-spots.ts +59 -59
  195. package/src/strategies/hide.ts +26 -26
  196. package/src/strategies/kill-frenzy.ts +15 -15
  197. package/src/strategies/kill-lone.knowledge.md +17 -17
  198. package/src/strategies/kill-lone.ts +16 -16
  199. package/src/strategies/kill-target.ts +21 -21
  200. package/src/strategies/knowledge-contract.ts +85 -85
  201. package/src/strategies/loader.test.ts +678 -678
  202. package/src/strategies/loader.ts +181 -181
  203. package/src/strategies/lone-kill-task.ts +24 -24
  204. package/src/strategies/meeting-gate.test.ts +59 -59
  205. package/src/strategies/meeting-gate.ts +28 -28
  206. package/src/strategies/move-room.ts +18 -18
  207. package/src/strategies/new-events-backfill.ts +98 -98
  208. package/src/strategies/off-route-points.ts +105 -105
  209. package/src/strategies/paradise-fish.knowledge.md +19 -19
  210. package/src/strategies/paradise-fish.ts +24 -24
  211. package/src/strategies/pathfind/distance-field.ts +150 -150
  212. package/src/strategies/pathfind/escape-planner.test.ts +197 -197
  213. package/src/strategies/pathfind/escape-planner.ts +355 -355
  214. package/src/strategies/pathfind/walkable-grid.ts +117 -117
  215. package/src/strategies/patrol.ts +14 -14
  216. package/src/strategies/player-targets.ts +13 -13
  217. package/src/strategies/report-patrol.ts +14 -14
  218. package/src/strategies/shrimp-memory.knowledge.md +19 -19
  219. package/src/strategies/shrimp-memory.ts +24 -24
  220. package/src/strategies/social-task.test.ts +28 -28
  221. package/src/strategies/social-task.ts +52 -52
  222. package/src/strategies/spawn.ts +82 -82
  223. package/src/strategies/speech-module.ts +123 -123
  224. package/src/strategies/strategy-loop.test.ts +15 -15
  225. package/src/strategies/strategy-loop.ts +748 -748
  226. package/src/strategies/task-kill-report.ts +20 -20
  227. package/src/strategies/task-only.ts +14 -14
  228. package/src/strategies/task-report.ts +21 -21
  229. package/src/strategies/types.ts +155 -155
  230. package/src/strategies/warrior-memory.knowledge.md +21 -21
  231. package/src/strategies/warrior-memory.ts +19 -19
@@ -1,1041 +1,1313 @@
1
- import { describe, expect, it } from 'vitest';
2
- import {
3
- classifyEvent,
4
- compactEventForMonitor,
5
- compactSummaryForMonitor,
6
- DELAYABLE_EVENT_CONFIG,
7
- eventKey,
8
- MONITOR_EVENT_CONFIG,
9
- NOTABLE_EVENT_TYPES,
10
- nextStepFor,
11
- POLL_INTERVAL_MS,
12
- readFeedSummary,
13
- runStreaming,
14
- snapshotOnce,
15
- sortEventsForMonitor,
16
- } from './watch.js';
17
-
18
- describe('classifyEvent + NOTABLE_EVENT_TYPES', () => {
19
- it('NOTABLE_EVENT_TYPES contains the headline events', () => {
20
- for (const t of [
21
- 'exile', 'speech_skipped', 'meeting_briefing',
22
- 'speech', 'vote_phase_start', 'game_over', 'user_left_game',
23
- 'speech_your_turn', 'vote_speech_phase_ended',
24
- 'crab_teammates', 'no_exile', 'game_started',
25
- ]) {
26
- expect(NOTABLE_EVENT_TYPES.has(t)).toBe(true);
27
- }
28
- expect(NOTABLE_EVENT_TYPES.has('vote_cast')).toBe(false);
29
- expect(NOTABLE_EVENT_TYPES.has('meeting_ended')).toBe(false);
30
- });
31
-
32
- it('derives NOTABLE_EVENT_TYPES from MONITOR_EVENT_CONFIG', () => {
33
- expect([...NOTABLE_EVENT_TYPES].sort()).toEqual(Object.keys(MONITOR_EVENT_CONFIG).sort());
34
- });
35
-
36
- it('registers monitor event priorities in the same config as notable events', () => {
37
- expect(MONITOR_EVENT_CONFIG.speech_your_turn.priority).toBe(99);
38
- expect(MONITOR_EVENT_CONFIG.vote_phase_start.priority).toBe(99);
39
- expect(MONITOR_EVENT_CONFIG.killed.priority).toBe(99);
40
- expect(MONITOR_EVENT_CONFIG.game_started.priority).toBe(50);
41
- expect(MONITOR_EVENT_CONFIG.speech.priority).toBe(50);
42
- expect(MONITOR_EVENT_CONFIG.vote_speech_phase_ended.priority).toBe(50);
43
- expect(MONITOR_EVENT_CONFIG.crab_teammates.priority).toBe(50);
44
- expect(MONITOR_EVENT_CONFIG.user_left_game.priority).toBe(50);
45
- expect(MONITOR_EVENT_CONFIG.vote_speech).toBeUndefined();
46
- expect(MONITOR_EVENT_CONFIG.vote_cast).toBeUndefined();
47
- expect(MONITOR_EVENT_CONFIG.meeting_ended).toBeUndefined();
48
- });
49
-
50
- it('classifyEvent returns notable=true for known types', () => {
51
- expect(classifyEvent({ type: 'killed', tick: 1 }).notable).toBe(true);
52
- });
53
-
54
- it('classifyEvent returns notable=false for unknown types', () => {
55
- expect(classifyEvent({ type: 'heartbeat', tick: 1 }).notable).toBe(false);
56
- });
57
-
58
- it('DELAYABLE_EVENT_CONFIG contains the delayable events', () => {
59
- for (const t of ['kill', 'emergency_started', 'corpse_spotted']) {
60
- expect(DELAYABLE_EVENT_CONFIG[t]).toBeGreaterThan(0);
61
- }
62
- });
63
-
64
- it('classifyEvent marks speech_your_turn as notable', () => {
65
- expect(
66
- classifyEvent({ type: 'speech_your_turn', tick: 1, actor_name: 'me' }, 'me').notable,
67
- ).toBe(true);
68
- });
69
-
70
- it('classifyEvent marks speech as notable', () => {
71
- const cls = classifyEvent({ type: 'speech', tick: 1, actor_name: 'me' }, 'me');
72
- expect(cls.notable).toBe(true);
73
- });
74
-
75
- it('does not wake the monitor for private vote_cast or meeting_ended', () => {
76
- expect(classifyEvent({ type: 'vote_cast', tick: 1, actor_name: 'me' }, 'me').notable).toBe(false);
77
- expect(classifyEvent({ type: 'meeting_ended', tick: 2 }, 'me').notable).toBe(false);
78
- });
79
-
80
- it('classifyEvent marks speech_skipped as notable', () => {
81
- expect(
82
- classifyEvent({ type: 'speech_skipped', tick: 1, actor_name: 'me' }, 'me').notable,
83
- ).toBe(true);
84
- });
85
-
86
- it('classifyEvent ignores vote_speech but marks vote_speech_phase_ended as notable', () => {
87
- expect(classifyEvent({ type: 'vote_speech', tick: 1, actor_name: 'me' }, 'me').notable).toBe(false);
88
- expect(classifyEvent({ type: 'vote_speech_phase_ended', tick: 2 }, 'me').notable).toBe(true);
89
- });
90
-
91
- it('eventKey ignores fields that are not part of the dedup key (e.g. ts)', () => {
92
- const a = { type: 'speech_your_turn', tick: 5, actor_name: 'me' };
93
- const b = { type: 'speech_your_turn', tick: 5, actor_name: 'me', ts: '2026-01-01T00:00:00Z' };
94
- expect(eventKey(a)).toBe(eventKey(b));
95
- });
96
-
97
- it('eventKey differs across distinct logical events', () => {
98
- const a = { type: 'speech_your_turn', tick: 5, actor_name: 'me' };
99
- const b = { type: 'speech_your_turn', tick: 6, actor_name: 'me' }; // different tick
100
- const c = { type: 'speech_your_turn', tick: 5, actor_name: 'them' }; // different actor
101
- expect(eventKey(a)).not.toBe(eventKey(b));
102
- expect(eventKey(a)).not.toBe(eventKey(c));
103
- });
104
-
105
- it('classifyEvent returns notable=false for non-notable types regardless of actor', () => {
106
- expect(classifyEvent({ type: 'heartbeat', tick: 1, actor_name: 'them' }, 'me').notable).toBe(false);
107
- expect(classifyEvent({ type: 'heartbeat', tick: 1, actor_name: 'me' }, 'me').notable).toBe(false);
108
- });
109
- });
110
-
111
- describe('sortEventsForMonitor', () => {
112
- it('puts speech_your_turn before default-priority events', () => {
113
- const sorted = sortEventsForMonitor([
114
- { type: 'speech_skipped', tick: 1 },
115
- { type: 'speech_your_turn', tick: 2 },
116
- ]);
117
- expect(sorted.map((e) => e.type)).toEqual(['speech_your_turn', 'speech_skipped']);
118
- });
119
-
120
- it('puts vote_phase_start before default-priority events', () => {
121
- const sorted = sortEventsForMonitor([
122
- { type: 'speech_skipped', tick: 1 },
123
- { type: 'vote_phase_start', tick: 2 },
124
- ]);
125
- expect(sorted.map((e) => e.type)).toEqual(['vote_phase_start', 'speech_skipped']);
126
- });
127
-
128
- it('keeps original order for events with the same priority', () => {
129
- const sorted = sortEventsForMonitor([
130
- { type: 'speech', tick: 1 },
131
- { type: 'speech_skipped', tick: 2 },
132
- { type: 'vote_cast', tick: 3 },
133
- ]);
134
- expect(sorted.map((e) => e.type)).toEqual(['speech', 'speech_skipped', 'vote_cast']);
135
- });
136
- });
137
-
138
- describe('watch defaults', () => {
139
- it('uses 220ms as the default poll interval', () => {
140
- expect(POLL_INTERVAL_MS).toBe(220);
141
- });
142
- });
143
-
144
- describe('monitor payload compaction', () => {
145
- it('routes role_assigned to a dedicated opening next step', () => {
146
- expect(nextStepFor('role_assigned')).toMatch(/role/i);
147
- expect(nextStepFor('role_assigned')).toMatch(/faction/i);
148
- });
149
-
150
- it('routes game_started to the opening context lookup', () => {
151
- expect(nextStepFor('game_started')).toContain('ccl events game_started');
152
- expect(nextStepFor('game_started')).toContain('ccl events role_assigned');
153
- });
154
-
155
- it('compacts ordinary lobster role_assigned without inventing extra task kind labels', () => {
156
- const compact = compactEventForMonitor({
157
- type: 'role_assigned',
158
- tick: 1,
159
- actor_name: 'me',
160
- room: '厨房',
161
- role: 'shrimp',
162
- role_display_name: '普通虾',
163
- faction: 'lobster',
164
- role_description: '完成任务或投出所有蟹方。',
165
- hint: 'long human hint',
166
- assigned_tasks: [
167
- { name: '修电线', room: '电气', x: 1, y: 2, task_note: 'long note', is_fake_shrimp: false },
168
- ],
169
- all_task_locations: [{ name: '修电线', room: '电气', x: 1, y: 2 }],
170
- });
171
-
172
- expect(compact).toEqual({
173
- type: 'role_assigned',
174
- tick: 1,
175
- room: '厨房',
176
- role: 'shrimp',
177
- role_display: '普通虾',
178
- faction: 'lobster',
179
- win_condition: '完成任务或投出所有蟹方。',
180
- tasks: [{ name: '修电线', room: '电气' }],
181
- hint: 'You are 普通虾 (lobster). 完成任务或投出所有蟹方。 Announce your role, faction and win condition to your user.',
182
- });
183
- });
184
-
185
- it('compacts all-fake neutral role_assigned into one top-level task kind', () => {
186
- const compact = compactEventForMonitor({
187
- type: 'role_assigned',
188
- tick: 2,
189
- room: '仓库',
190
- role: 'octopus',
191
- role_display_name: '章鱼',
192
- faction: 'neutral',
193
- role_description: '伪装成虾方并达成自己的胜利条件。',
194
- fake_task_briefing: 'These are fake tasks.',
195
- assigned_tasks: [
196
- { name: '下载数据', room: '通讯', x: 3, y: 4, is_fake_shrimp: true },
197
- { name: '清理垃圾', room: '餐厅', x: 5, y: 6, is_fake_shrimp: true },
198
- ],
199
- });
200
-
201
- expect(compact).toEqual({
202
- type: 'role_assigned',
203
- tick: 2,
204
- room: '仓库',
205
- role: 'octopus',
206
- role_display: '章鱼',
207
- faction: 'neutral',
208
- win_condition: '伪装成虾方并达成自己的胜利条件。',
209
- task_kind: 'fake_shrimp',
210
- task_note: 'Fake shrimp tasks: disguise only; no lobster progress.',
211
- tasks: [
212
- { name: '下载数据', room: '通讯' },
213
- { name: '清理垃圾', room: '餐厅' },
214
- ],
215
- hint: 'You are 章鱼 (neutral). 伪装成虾方并达成自己的胜利条件。 These are fake tasks. Announce your role, faction and win condition to your user.',
216
- });
217
- });
218
-
219
- it('keeps per-task kind labels for mixed crab role_assigned tasks', () => {
220
- const compact = compactEventForMonitor({
221
- type: 'role_assigned',
222
- tick: 3,
223
- room: '电气',
224
- role: 'crab',
225
- role_display_name: '蟹',
226
- faction: 'crab',
227
- role_description: '击杀虾方并避免被投出。',
228
- fake_task_briefing: 'Fake task exists.',
229
- assigned_tasks: [
230
- { name: '破坏电力', room: '电气', x: 7, y: 8, is_fake_shrimp: false },
231
- { name: '刷卡', room: '管理', x: 9, y: 10, is_fake_shrimp: true },
232
- ],
233
- });
234
-
235
- expect(compact).toEqual({
236
- type: 'role_assigned',
237
- tick: 3,
238
- room: '电气',
239
- role: 'crab',
240
- role_display: '蟹',
241
- faction: 'crab',
242
- win_condition: '击杀虾方并避免被投出。',
243
- task_note: 'Fake shrimp tasks: disguise only; no lobster progress.',
244
- tasks: [
245
- { name: '破坏电力', room: '电气', kind: 'crab_sabotage' },
246
- { name: '刷卡', room: '管理', kind: 'fake_shrimp' },
247
- ],
248
- hint: 'You are 蟹 (crab). 击杀虾方并避免被投出。 Fake task exists. Announce your role, faction and win condition to your user.',
249
- });
250
- });
251
-
252
- it('removes room from meeting_briefing monitor events only', () => {
253
- const compact = compactEventForMonitor({
254
- type: 'meeting_briefing',
255
- tick: 10,
256
- room: '会议室',
257
- caller: '红虾',
258
- speech_order: ['红虾', '蓝虾'],
259
- });
260
-
261
- expect(compact).toEqual({
262
- type: 'meeting_briefing',
263
- tick: 10,
264
- caller: '红虾',
265
- speech_order: ['红虾', '蓝虾'],
266
- });
267
- });
268
-
269
- it('rewrites corpse_spotted hint for monitor perspective', () => {
270
- const compact = compactEventForMonitor({
271
- type: 'corpse_spotted',
272
- tick: 326,
273
- room: 'Intel',
274
- corpse_name: 'Garlic',
275
- corpse_room: 'Intel',
276
- hint: 'BODY FOUND: Garlic at (1, 2) in Intel.',
277
- });
278
-
279
- expect(compact).toMatchObject({
280
- type: 'corpse_spotted',
281
- tick: 326,
282
- corpse_name: 'Garlic',
283
- corpse_room: 'Intel',
284
- hint: 'BODY FOUND: Garlic at (?, ?) in Intel. This is leverage soaked in blood — report before the killer rewrites the room.',
285
- });
286
- });
287
-
288
- it('rewrites meeting_briefing hint for another caller', () => {
289
- const compact = compactEventForMonitor({
290
- type: 'meeting_briefing',
291
- tick: 487,
292
- room: 'Control',
293
- meeting_caller_name: 'Drifter',
294
- meeting_caller_seat: 4,
295
- your_seat: 3,
296
- reported_corpses: [{ name: 'Chef', seat: 9 }],
297
- hint: 'Meeting started — seat 4 Drifter called this meeting.',
298
- });
299
-
300
- expect(compact).toMatchObject({
301
- type: 'meeting_briefing',
302
- tick: 487,
303
- meeting_caller_name: 'Drifter',
304
- reported_corpses: [{ name: 'Chef', seat: 9 }],
305
- hint: 'Meeting started — seat 4 Drifter called this meeting after reporting the body of seat 9 Chef. Prepare fast — every sentence is accusation, defense, or misdirection under a timer.',
306
- });
307
- expect(compact).not.toHaveProperty('room');
308
- });
309
-
310
- it('rewrites meeting_briefing hint when you are the caller', () => {
311
- const compact = compactEventForMonitor({
312
- type: 'meeting_briefing',
313
- tick: 487,
314
- meeting_caller_name: 'Player',
315
- meeting_caller_seat: 3,
316
- your_seat: 3,
317
- reported_corpses: [{ name: 'Chef', seat: 9 }],
318
- hint: 'Meeting started — seat 3 Player called this meeting.',
319
- });
320
-
321
- expect(compact.hint).toBe('Meeting started — seat 3 Player called this meeting after reporting the body of seat 9 Chef. Prepare fast — every sentence is accusation, defense, or misdirection under a timer.');
322
- });
323
-
324
- it('compacts meeting summary and hard-overrides speech_your_turn fields', () => {
325
- const compact = compactSummaryForMonitor({
326
- phase: 'meeting',
327
- you: {
328
- name: '我',
329
- seat: 1,
330
- role: 'shrimp',
331
- faction: 'lobster',
332
- x: 11,
333
- y: 12,
334
- kill_cooldown_secs: 0,
335
- },
336
- game: { id: 'game-1', tick: 50 },
337
- urgent: { meeting_started: true },
338
- meeting: {
339
- caller: '红虾',
340
- sub_phase: 'speech',
341
- current_speaker: '红虾',
342
- is_my_turn: false,
343
- alive_players: ['我', '红虾'],
344
- speech_history: [{ speaker: '红虾', text: 'long speech' }],
345
- votes_submitted: ['红虾'],
346
- },
347
- automation: { strategy: 'default', running: true },
348
- }, ['speech_your_turn']);
349
-
350
- expect(compact).toEqual({
351
- phase: 'meeting',
352
- you: { name: '我', role: 'shrimp', faction: 'lobster' },
353
- game: { id: 'game-1', tick: 50 },
354
- meeting: {
355
- caller: '红虾',
356
- sub_phase: 'speech',
357
- alive_players: ['我', '红虾'],
358
- current_speaker: '我',
359
- is_my_turn: true,
360
- },
361
- automation: { strategy: 'default', running: true },
362
- });
363
- });
364
-
365
- it('compacts vote-phase meeting summary into a submitted-vote count', () => {
366
- const compact = compactSummaryForMonitor({
367
- phase: 'meeting',
368
- you: { name: '我', role: 'shrimp', faction: 'lobster' },
369
- game: { id: 'game-1' },
370
- meeting: {
371
- caller: '红虾',
372
- sub_phase: 'speech',
373
- current_speaker: '我',
374
- is_my_turn: true,
375
- alive_players: ['我', '红虾', '蓝虾'],
376
- votes_submitted: ['红虾', '蓝虾'],
377
- },
378
- }, ['vote_phase_start']);
379
-
380
- expect(compact).toEqual({
381
- phase: 'meeting',
382
- you: { name: '我', role: 'shrimp', faction: 'lobster' },
383
- game: { id: 'game-1' },
384
- meeting: {
385
- caller: '红虾',
386
- sub_phase: 'vote',
387
- alive_players: ['我', '红虾', '蓝虾'],
388
- votes_submitted_count: 2,
389
- },
390
- });
391
- });
392
- });
393
-
394
- import { mkdtempSync, writeFileSync, appendFileSync, unlinkSync, existsSync } from 'fs';
395
- import { tmpdir } from 'os';
396
- import { join } from 'path';
397
-
398
- function makeTmpFiles(opts?: { seedFeed?: boolean }) {
399
- const dir = mkdtempSync(join(tmpdir(), 'watch-stream-'));
400
- const feedPath = join(dir, 'feed.json');
401
- const sessionPath = join(dir, 'session.jsonl');
402
- writeFileSync(sessionPath, '');
403
- if (opts?.seedFeed !== false) {
404
- writeFileSync(
405
- feedPath,
406
- JSON.stringify({ you: { name: 'me' }, phase: 'lobby', urgent: {}, meeting: null }),
407
- );
408
- }
409
- return { dir, feedPath, sessionPath };
410
- }
411
-
412
- describe('runStreaming — emission shape', () => {
413
- it('emits one NDJSON line per notable event with required fields', async () => {
414
- const { feedPath, sessionPath } = makeTmpFiles();
415
- writeFileSync(
416
- feedPath,
417
- JSON.stringify({
418
- you: { name: 'me' },
419
- meeting: { is_my_turn: false },
420
- urgent: {},
421
- }),
422
- );
423
- const lines: string[] = [];
424
- const ctrl = new AbortController();
425
-
426
- const run = runStreaming({
427
- feedPath,
428
- sessionPath,
429
- stdout: (s) => lines.push(s),
430
- signal: ctrl.signal,
431
- pollIntervalMs: 20,
432
- });
433
-
434
- appendFileSync(
435
- sessionPath,
436
- JSON.stringify({ type: 'killed', tick: 1, actor_name: 'a' }) + '\n',
437
- );
438
-
439
- await new Promise((r) => setTimeout(r, 80));
440
- ctrl.abort();
441
- await run;
442
-
443
- expect(lines.length).toBeGreaterThanOrEqual(1);
444
- for (const raw of lines) {
445
- const obj = JSON.parse(raw);
446
- expect(Array.isArray(obj.events)).toBe(true);
447
- expect(Array.isArray(obj.messages)).toBe(true);
448
- expect(obj).not.toHaveProperty('trigger');
449
- expect(obj).not.toHaveProperty('triggers');
450
- expect(obj).not.toHaveProperty('all_events');
451
- expect(obj).not.toHaveProperty('summary');
452
- expect(obj).not.toHaveProperty('next_step');
453
- expect(obj).toHaveProperty('state');
454
- expect(raw.endsWith('\n')).toBe(true);
455
- }
456
- });
457
-
458
- it('emits vote_speech_phase_ended but ignores vote_speech', async () => {
459
- const { feedPath, sessionPath } = makeTmpFiles();
460
- writeFileSync(
461
- feedPath,
462
- JSON.stringify({
463
- you: { name: 'me' },
464
- meeting: { is_my_turn: false },
465
- urgent: {},
466
- }),
467
- );
468
- const lines: string[] = [];
469
- const ctrl = new AbortController();
470
-
471
- const run = runStreaming({
472
- feedPath,
473
- sessionPath,
474
- stdout: (s) => lines.push(s),
475
- signal: ctrl.signal,
476
- pollIntervalMs: 20,
477
- });
478
-
479
- await new Promise((r) => setTimeout(r, 60));
480
- appendFileSync(
481
- sessionPath,
482
- JSON.stringify({ type: 'vote_speech', tick: 1, actor_name: 'a', text: 'vote talk' }) + '\n'
483
- + JSON.stringify({ type: 'vote_speech_phase_ended', tick: 2, hint: 'The vote speech window has closed.' }) + '\n',
484
- );
485
-
486
- await new Promise((r) => setTimeout(r, 80));
487
- ctrl.abort();
488
- await run;
489
-
490
- expect(lines.length).toBe(1);
491
- const obj = JSON.parse(lines[0]);
492
- expect(obj.events).toEqual(['vote_speech_phase_ended']);
493
- expect(obj.events).toHaveLength(1);
494
- expect(obj.messages[0]).toContain('vote_speech_phase_ended');
495
- });
496
-
497
- it('surfaces game_mode on game_started monitor output and message text', async () => {
498
- const { feedPath, sessionPath } = makeTmpFiles();
499
- writeFileSync(
500
- feedPath,
501
- JSON.stringify({
502
- phase: 'wandering',
503
- you: { name: 'me' },
504
- urgent: {},
505
- }),
506
- );
507
- const lines: string[] = [];
508
- const ctrl = new AbortController();
509
-
510
- const run = runStreaming({
511
- feedPath,
512
- sessionPath,
513
- stdout: (s) => lines.push(s),
514
- signal: ctrl.signal,
515
- pollIntervalMs: 20,
516
- });
517
-
518
- appendFileSync(
519
- sessionPath,
520
- JSON.stringify({
521
- type: 'game_started',
522
- tick: 0,
523
- player_count: 10,
524
- game_mode: 'competition',
525
- }) + '\n',
526
- );
527
-
528
- await new Promise((r) => setTimeout(r, 80));
529
- ctrl.abort();
530
- await run;
531
-
532
- expect(lines.length).toBeGreaterThanOrEqual(1);
533
- const obj = JSON.parse(lines[0]);
534
- expect(obj.events).toContain('game_started');
535
- expect(obj.game_mode).toBe('competition');
536
- expect(obj.messages[0]).toContain('竞赛模式');
537
- });
538
-
539
- it('expands nested new_events from action wrapper records', async () => {
540
- const { feedPath, sessionPath } = makeTmpFiles();
541
- writeFileSync(
542
- feedPath,
543
- JSON.stringify({
544
- you: { name: 'me' },
545
- meeting: { is_my_turn: false },
546
- urgent: {},
547
- }),
548
- );
549
- const lines: string[] = [];
550
- const ctrl = new AbortController();
551
-
552
- const run = runStreaming({
553
- feedPath,
554
- sessionPath,
555
- stdout: (s) => lines.push(s),
556
- signal: ctrl.signal,
557
- pollIntervalMs: 20,
558
- delayableEventMs: { kill: 0 },
559
- });
560
-
561
- await new Promise((r) => setTimeout(r, 30));
562
- appendFileSync(
563
- sessionPath,
564
- JSON.stringify({
565
- type: 'auto',
566
- action: 'kill',
567
- result: {
568
- ok: true,
569
- new_events: [{ type: 'kill', tick: 42, target_name: 'target' }],
570
- },
571
- }) + '\n',
572
- );
573
-
574
- await new Promise((r) => setTimeout(r, 80));
575
- ctrl.abort();
576
- await run;
577
-
578
- expect(lines.some((l) => JSON.parse(l).events?.includes('kill'))).toBe(true);
579
- });
580
-
581
- it('keeps reading after the .jsonl is truncated in place', async () => {
582
- const { feedPath, sessionPath } = makeTmpFiles();
583
- writeFileSync(
584
- feedPath,
585
- JSON.stringify({ you: { name: 'me' }, meeting: { is_my_turn: false }, urgent: {} }),
586
- );
587
- appendFileSync(sessionPath, JSON.stringify({ type: 'killed', tick: 1, actor_name: 'a_really_long_name' }) + '\n');
588
-
589
- const lines: string[] = [];
590
- const ctrl = new AbortController();
591
- const run = runStreaming({
592
- feedPath,
593
- sessionPath,
594
- stdout: (s) => lines.push(s),
595
- signal: ctrl.signal,
596
- pollIntervalMs: 20,
597
- });
598
-
599
- // Wait for the initial event to be processed (and absorbed as backlog).
600
- await new Promise((r) => setTimeout(r, 60));
601
- const beforeTruncate = lines.length;
602
-
603
- // Truncate the file in place (simulating runtime log rotation that keeps the inode).
604
- writeFileSync(sessionPath, '');
605
- // Append a fresh notable event after truncation.
606
- appendFileSync(sessionPath, JSON.stringify({ type: 'killed', tick: 100, actor_name: 'b' }) + '\n');
607
-
608
- // Give the loop time to detect the truncation and re-read.
609
- await new Promise((r) => setTimeout(r, 120));
610
- ctrl.abort();
611
- await run;
612
-
613
- // The post-truncation event must produce a new line.
614
- expect(lines.length).toBeGreaterThan(beforeTruncate);
615
- expect(lines.some((l) => JSON.parse(l).events?.includes('killed'))).toBe(true);
616
- });
617
-
618
- it('throws WatchNotReadyError when feed.json never appears', async () => {
619
- const { dir, sessionPath } = makeTmpFiles();
620
- const lines: string[] = [];
621
- await expect(
622
- runStreaming({
623
- feedPath: join(dir, 'no-feed.json'),
624
- sessionPath,
625
- stdout: (s) => lines.push(s),
626
- pollIntervalMs: 20,
627
- runtimeWaitMs: 80,
628
- }),
629
- ).rejects.toThrow(/not ready/i);
630
- expect(lines.length).toBe(0);
631
- });
632
-
633
- it('waits for feed.json before tailing (parallel game start)', async () => {
634
- const { feedPath, sessionPath } = makeTmpFiles({ seedFeed: false });
635
- if (existsSync(feedPath)) unlinkSync(feedPath);
636
- const lines: string[] = [];
637
- const ctrl = new AbortController();
638
- const run = runStreaming({
639
- feedPath,
640
- sessionPath,
641
- stdout: (s) => lines.push(s),
642
- signal: ctrl.signal,
643
- pollIntervalMs: 20,
644
- runtimeWaitMs: 2000,
645
- });
646
- setTimeout(() => {
647
- writeFileSync(feedPath, JSON.stringify({ you: { name: 'me' }, phase: 'lobby', urgent: {}, meeting: null }));
648
- }, 100);
649
- await new Promise((r) => setTimeout(r, 250));
650
- ctrl.abort();
651
- await run;
652
- expect(lines.length).toBeGreaterThanOrEqual(0);
653
- });
654
- });
655
-
656
-
657
- describe('snapshotOnce', () => {
658
- it('writes one NDJSON line with exit_reason=snapshot', () => {
659
- const { feedPath } = makeTmpFiles();
660
- writeFileSync(feedPath, JSON.stringify({ you: { name: 'me' }, meeting: {}, urgent: {} }));
661
- const lines: string[] = [];
662
- snapshotOnce({ feedPath, stdout: (s) => lines.push(s) });
663
- expect(lines.length).toBe(1);
664
- const obj = JSON.parse(lines[0]);
665
- expect(obj.events).toEqual(['snapshot']);
666
- expect(obj.messages[0]).toContain('snapshot');
667
- expect(obj).not.toHaveProperty('trigger');
668
- expect(obj).not.toHaveProperty('triggers');
669
- expect(obj).not.toHaveProperty('all_events');
670
- expect(obj).not.toHaveProperty('summary');
671
- expect(obj).toHaveProperty('state');
672
- });
673
-
674
- it('errors clearly if feed.json is missing', () => {
675
- const { dir } = makeTmpFiles();
676
- const lines: string[] = [];
677
- expect(() =>
678
- snapshotOnce({ feedPath: join(dir, 'nope.json'), stdout: (s) => lines.push(s) }),
679
- ).toThrow(/game runtime is not running/);
680
- });
681
- });
682
-
683
- describe('runStreaming — startup backlog', () => {
684
- it('attaches caught_up to the first line; subsequent lines have no caught_up', async () => {
685
- const { feedPath, sessionPath } = makeTmpFiles();
686
- writeFileSync(feedPath, JSON.stringify({ you: { name: 'me' }, meeting: {}, urgent: {} }));
687
- for (let i = 0; i < 5; i++) {
688
- appendFileSync(sessionPath, JSON.stringify({ type: 'killed', tick: i, actor_name: 'p' + i }) + '\n');
689
- }
690
-
691
- const lines: string[] = [];
692
- const ctrl = new AbortController();
693
- const run = runStreaming({ feedPath, sessionPath, stdout: (s) => lines.push(s), signal: ctrl.signal, pollIntervalMs: 20 });
694
- await new Promise((r) => setTimeout(r, 60));
695
-
696
- appendFileSync(sessionPath, JSON.stringify({ type: 'killed', tick: 100, actor_name: 'late' }) + '\n');
697
- await new Promise((r) => setTimeout(r, 60));
698
-
699
- ctrl.abort(); await run;
700
-
701
- expect(lines.length).toBeGreaterThanOrEqual(2);
702
- const first = JSON.parse(lines[0]);
703
- expect(first.events).toHaveLength(5);
704
- expect(first.events.every((event: string) => event === 'killed')).toBe(true);
705
- for (const raw of lines.slice(1)) {
706
- expect(JSON.parse(raw)).not.toHaveProperty('caught_up');
707
- }
708
- });
709
-
710
- it('emits attached + caught_up on the first line when re-attaching mid-game', async () => {
711
- const { feedPath, sessionPath } = makeTmpFiles();
712
- writeFileSync(
713
- feedPath,
714
- JSON.stringify({
715
- you: { name: 'me' },
716
- meeting: { current_speaker: 'a', alive_players: ['a', 'me'], caller: 'a' },
717
- urgent: { meeting_started: true },
718
- }),
719
- );
720
- for (let i = 0; i < 3; i++) {
721
- appendFileSync(sessionPath, JSON.stringify({ type: 'killed', tick: i, actor_name: 'p' + i }) + '\n');
722
- }
723
-
724
- const lines: string[] = [];
725
- const ctrl = new AbortController();
726
- const run = runStreaming({ feedPath, sessionPath, stdout: (s) => lines.push(s), signal: ctrl.signal, pollIntervalMs: 20 });
727
- await new Promise((r) => setTimeout(r, 80));
728
- ctrl.abort(); await run;
729
-
730
- expect(lines.length).toBeGreaterThanOrEqual(1);
731
- const first = JSON.parse(lines[0]);
732
- expect(first.events).toEqual(['killed', 'killed', 'killed']);
733
- expect(first).not.toHaveProperty('active_sticky_on_attach');
734
- });
735
- });
736
-
737
- describe('runStreaming — game_over exits', () => {
738
- it('returns from the loop after a game_over event', async () => {
739
- const { feedPath, sessionPath } = makeTmpFiles();
740
- writeFileSync(feedPath, JSON.stringify({ you: { name: 'me' }, meeting: {}, urgent: {} }));
741
- const lines: string[] = [];
742
- const run = runStreaming({ feedPath, sessionPath, stdout: (s) => lines.push(s), pollIntervalMs: 20 });
743
- await new Promise((r) => setTimeout(r, 30));
744
- appendFileSync(sessionPath, JSON.stringify({ type: 'game_over', tick: 1 }) + '\n');
745
- await Promise.race([run, new Promise((_, rej) => setTimeout(() => rej(new Error('did not exit')), 3000))]);
746
- expect(lines.some((l) => JSON.parse(l).events?.includes('game_over'))).toBe(true);
747
- });
748
-
749
- it('returns from the loop after a user_left_game event', async () => {
750
- const { feedPath, sessionPath } = makeTmpFiles();
751
- writeFileSync(feedPath, JSON.stringify({ phase: 'user_left_game', you: { name: 'me' }, meeting: {}, urgent: {} }));
752
- const lines: string[] = [];
753
- const run = runStreaming({ feedPath, sessionPath, stdout: (s) => lines.push(s), pollIntervalMs: 20 });
754
- await new Promise((r) => setTimeout(r, 30));
755
- appendFileSync(sessionPath, JSON.stringify({ type: 'user_left_game', close_code: 1000, close_reason: 'Left game' }) + '\n');
756
- await Promise.race([run, new Promise((_, rej) => setTimeout(() => rej(new Error('did not exit')), 3000))]);
757
-
758
- const notice = lines.map((l) => JSON.parse(l)).find((line) => line.events?.includes('user_left_game'));
759
- expect(notice).toBeTruthy();
760
- expect(notice.messages.some((message: string) => message.includes('The user left the game from the web page. This match has ended; stop playing and do not restart unless the user asks.'))).toBe(true);
761
- expect(notice.state).toContain('user_left_game');
762
- });
763
- });
764
-
765
- describe('runStreaming — NDJSON discipline', () => {
766
- it('every emitted line is JSON.parse-able', async () => {
767
- const { feedPath, sessionPath } = makeTmpFiles();
768
- writeFileSync(feedPath, JSON.stringify({ you: { name: 'me' }, meeting: { is_my_turn: false }, urgent: {} }));
769
- const lines: string[] = [];
770
- const ctrl = new AbortController();
771
- const run = runStreaming({ feedPath, sessionPath, stdout: (s) => lines.push(s), signal: ctrl.signal, pollIntervalMs: 20 });
772
- for (const t of ['killed', 'meeting_started', 'vote_phase_start']) {
773
- appendFileSync(sessionPath, JSON.stringify({ type: t, tick: Date.now() }) + '\n');
774
- await new Promise((r) => setTimeout(r, 40));
775
- }
776
- ctrl.abort(); await run;
777
- for (const raw of lines) {
778
- expect(() => JSON.parse(raw)).not.toThrow();
779
- }
780
- });
781
- });
782
-
783
- describe('runStreaming — matchmaking synthetic events', () => {
784
- it('classifyEvent treats match_waiting / match_timeout as notable', () => {
785
- expect(classifyEvent({ type: 'match_waiting', tick: 1, waited_secs: 0 }).notable).toBe(true);
786
- expect(classifyEvent({ type: 'match_timeout', tick: 1, waited_secs: 600 }).notable).toBe(true);
787
- });
788
-
789
- it('emits lowercase exit_reason for each match_* event with a dedicated next_step', async () => {
790
- const { feedPath, sessionPath } = makeTmpFiles();
791
- writeFileSync(feedPath, JSON.stringify({ phase: 'matching', urgent: {}, meeting: null, you: { name: 'me' } }));
792
- const lines: string[] = [];
793
- const ctrl = new AbortController();
794
- const run = runStreaming({ feedPath, sessionPath, stdout: (s) => lines.push(s), signal: ctrl.signal, pollIntervalMs: 20 });
795
- await new Promise((r) => setTimeout(r, 30));
796
- appendFileSync(sessionPath, JSON.stringify({ type: 'match_waiting', tick: 2, waited_secs: 0 }) + '\n');
797
- await new Promise((r) => setTimeout(r, 60));
798
- appendFileSync(sessionPath, JSON.stringify({ type: 'match_timeout', tick: 3, waited_secs: 600 }) + '\n');
799
- await new Promise((r) => setTimeout(r, 60));
800
- ctrl.abort(); await run;
801
-
802
- const eventNames = lines.flatMap((l) => JSON.parse(l).events);
803
- expect(eventNames).toContain('match_waiting');
804
- expect(eventNames).toContain('match_timeout');
805
-
806
- const timeout = lines.map((l) => JSON.parse(l)).find((o) => o.events?.includes('match_timeout'));
807
- expect(timeout.messages[0]).toContain('600');
808
- });
809
- });
810
-
811
- describe('runStreaming — speech_your_turn fires as notable event', () => {
812
- it('fires speech_your_turn as exit_reason when speech_your_turn event arrives', async () => {
813
- const { feedPath, sessionPath } = makeTmpFiles();
814
- writeFileSync(feedPath, JSON.stringify({ phase: 'meeting', urgent: {}, meeting: { current_speaker: 'other' }, you: { name: 'me' } }));
815
- const lines: string[] = [];
816
- const ctrl = new AbortController();
817
- const run = runStreaming({ feedPath, sessionPath, stdout: (s) => lines.push(s), signal: ctrl.signal, pollIntervalMs: 20 });
818
- await new Promise((r) => setTimeout(r, 30));
819
- appendFileSync(sessionPath, JSON.stringify({ type: 'speech_your_turn', tick: 1, actor_name: 'me' }) + '\n');
820
- await new Promise((r) => setTimeout(r, 80));
821
- ctrl.abort(); await run;
822
-
823
- const parsed = lines.map((l) => JSON.parse(l));
824
- const myTurn = parsed.find((o) => o.events?.includes('speech_your_turn'));
825
- expect(myTurn).toBeDefined();
826
- expect(myTurn!.events).toContain('speech_your_turn');
827
- });
828
- });
829
-
830
- describe('runStreaming — delay buffer', () => {
831
- it('delays a delayable event (kill) and emits after the delay expires', async () => {
832
- const { feedPath, sessionPath } = makeTmpFiles();
833
- writeFileSync(
834
- feedPath,
835
- JSON.stringify({ you: { name: 'me' }, phase: 'wandering', urgent: {}, meeting: null }),
836
- );
837
- const lines: string[] = [];
838
- const ctrl = new AbortController();
839
- const run = runStreaming({
840
- feedPath,
841
- sessionPath,
842
- stdout: (s) => lines.push(s),
843
- signal: ctrl.signal,
844
- pollIntervalMs: 20,
845
- delayableEventMs: { kill: 100 },
846
- });
847
- await new Promise((r) => setTimeout(r, 30));
848
- appendFileSync(sessionPath, JSON.stringify({ type: 'kill', tick: 1, actor_name: '蟹A', target_name: '虾B' }) + '\n');
849
- await new Promise((r) => setTimeout(r, 50));
850
- expect(lines.length).toBe(0);
851
- await new Promise((r) => setTimeout(r, 100));
852
- ctrl.abort(); await run;
853
-
854
- const parsed = lines.map((l) => JSON.parse(l));
855
- const killNotif = parsed.find((o) => o.events?.includes('kill'));
856
- expect(killNotif).toBeDefined();
857
- });
858
-
859
- it('merges multiple events arriving during the delay window into one notification', async () => {
860
- const { feedPath, sessionPath } = makeTmpFiles();
861
- writeFileSync(
862
- feedPath,
863
- JSON.stringify({ you: { name: 'me' }, phase: 'wandering', urgent: {}, meeting: null }),
864
- );
865
- const lines: string[] = [];
866
- const ctrl = new AbortController();
867
- const run = runStreaming({
868
- feedPath,
869
- sessionPath,
870
- stdout: (s) => lines.push(s),
871
- signal: ctrl.signal,
872
- pollIntervalMs: 20,
873
- delayableEventMs: { kill: 200, emergency_started: 200 },
874
- });
875
- await new Promise((r) => setTimeout(r, 30));
876
- appendFileSync(sessionPath, JSON.stringify({ type: 'kill', tick: 1, actor_name: '蟹A', target_name: '虾B' }) + '\n');
877
- await new Promise((r) => setTimeout(r, 50));
878
- appendFileSync(sessionPath, JSON.stringify({ type: 'emergency_started', tick: 2 }) + '\n');
879
- await new Promise((r) => setTimeout(r, 50));
880
- appendFileSync(sessionPath, JSON.stringify({ type: 'task_completed', tick: 3, task_name: 'wires' }) + '\n');
881
- await new Promise((r) => setTimeout(r, 250));
882
- ctrl.abort(); await run;
883
-
884
- const parsed = lines.map((l) => JSON.parse(l));
885
- const merged = parsed.find((o) => o.events?.includes('kill'));
886
- expect(merged).toBeDefined();
887
- expect(merged!.events).toContain('emergency_started');
888
- expect(merged!.events).toContain('task_completed');
889
- const notableLines = parsed.filter((o) => !o.events?.includes('heartbeat'));
890
- expect(notableLines.length).toBe(1);
891
- });
892
-
893
- it('does not extend delay when a second delayable event arrives mid-delay', async () => {
894
- const { feedPath, sessionPath } = makeTmpFiles();
895
- writeFileSync(
896
- feedPath,
897
- JSON.stringify({ you: { name: 'me' }, phase: 'wandering', urgent: {}, meeting: null }),
898
- );
899
- const lines: string[] = [];
900
- const ctrl = new AbortController();
901
- const run = runStreaming({
902
- feedPath,
903
- sessionPath,
904
- stdout: (s) => lines.push(s),
905
- signal: ctrl.signal,
906
- pollIntervalMs: 20,
907
- delayableEventMs: { kill: 150, emergency_started: 5000 },
908
- });
909
- await new Promise((r) => setTimeout(r, 30));
910
- appendFileSync(sessionPath, JSON.stringify({ type: 'kill', tick: 1, actor_name: '蟹A', target_name: '虾B' }) + '\n');
911
- await new Promise((r) => setTimeout(r, 50));
912
- appendFileSync(sessionPath, JSON.stringify({ type: 'emergency_started', tick: 2 }) + '\n');
913
- await new Promise((r) => setTimeout(r, 200));
914
- ctrl.abort(); await run;
915
-
916
- const parsed = lines.map((l) => JSON.parse(l));
917
- const merged = parsed.find((o) => o.events?.includes('kill'));
918
- expect(merged).toBeDefined();
919
- expect(merged!.events).toContain('emergency_started');
920
- });
921
-
922
- it('non-delayable events fire immediately when no delay is active', async () => {
923
- const { feedPath, sessionPath } = makeTmpFiles();
924
- writeFileSync(
925
- feedPath,
926
- JSON.stringify({ you: { name: 'me' }, phase: 'wandering', urgent: {}, meeting: null }),
927
- );
928
- const lines: string[] = [];
929
- const ctrl = new AbortController();
930
- const run = runStreaming({
931
- feedPath,
932
- sessionPath,
933
- stdout: (s) => lines.push(s),
934
- signal: ctrl.signal,
935
- pollIntervalMs: 20,
936
- delayableEventMs: { kill: 200 },
937
- });
938
- await new Promise((r) => setTimeout(r, 30));
939
- appendFileSync(sessionPath, JSON.stringify({ type: 'task_completed', tick: 1, task_name: 'wires' }) + '\n');
940
- await new Promise((r) => setTimeout(r, 80));
941
- ctrl.abort(); await run;
942
-
943
- const parsed = lines.map((l) => JSON.parse(l));
944
- expect(parsed.some((o) => o.events?.includes('task_completed'))).toBe(true);
945
- });
946
- });
947
-
948
- describe('readFeedSummary', () => {
949
- it('includes automation strategy from the feed projection without exposing pid', () => {
950
- const { feedPath } = makeTmpFiles();
951
- writeFileSync(
952
- feedPath,
953
- JSON.stringify({
954
- phase: 'wandering',
955
- you: { name: 'me' },
956
- game: { id: 'game-1' },
957
- urgent: {},
958
- meeting: null,
959
- automation: { strategy: 'default', running: true },
960
- }),
961
- );
962
-
963
- const summary = readFeedSummary(feedPath);
964
- expect(summary?.automation).toEqual({ strategy: 'default', running: true });
965
- expect(summary?.automation).not.toHaveProperty('pid');
966
- expect(summary?.automation).not.toHaveProperty('source');
967
- });
968
- });
969
-
970
- describe('runStreaming startup monitor payload', () => {
971
- it('emits game_start without initial_payload when requested by game start', async () => {
972
- const { feedPath, sessionPath } = makeTmpFiles();
973
- writeFileSync(
974
- feedPath,
975
- JSON.stringify({ you: { name: 'me' }, phase: 'lobby', urgent: {}, meeting: null }),
976
- );
977
- const lines: string[] = [];
978
- const ctrl = new AbortController();
979
-
980
- const run = runStreaming({
981
- feedPath,
982
- sessionPath,
983
- stdout: (s) => lines.push(s),
984
- signal: ctrl.signal,
985
- pollIntervalMs: 20,
986
- emitGameStart: true,
987
- });
988
-
989
- await new Promise((r) => setTimeout(r, 60));
990
- ctrl.abort();
991
- await run;
992
-
993
- expect(lines.length).toBeGreaterThanOrEqual(1);
994
- const first = JSON.parse(lines[0]);
995
- expect(first.events).toEqual(['game_start']);
996
- expect(first).not.toHaveProperty('initial_payload');
997
- expect(first.messages[0]).toContain('game_start');
998
- });
999
-
1000
- it('compacts role_assigned inside caught_up notable events', async () => {
1001
- const { feedPath, sessionPath } = makeTmpFiles();
1002
- writeFileSync(
1003
- feedPath,
1004
- JSON.stringify({ you: { name: 'me' }, phase: 'wandering', urgent: {}, meeting: null }),
1005
- );
1006
- appendFileSync(sessionPath, JSON.stringify({
1007
- type: 'role_assigned',
1008
- tick: 1,
1009
- room: '仓库',
1010
- role: 'octopus',
1011
- role_display_name: '章鱼',
1012
- faction: 'neutral',
1013
- role_description: '伪装成虾方并达成自己的胜利条件。',
1014
- fake_task_briefing: 'These are fake tasks.',
1015
- hint: 'long hint',
1016
- assigned_tasks: [
1017
- { name: '下载数据', room: '通讯', x: 3, y: 4, is_fake_shrimp: true },
1018
- ],
1019
- }) + '\n');
1020
- const lines: string[] = [];
1021
- const ctrl = new AbortController();
1022
-
1023
- const run = runStreaming({
1024
- feedPath,
1025
- sessionPath,
1026
- stdout: (s) => lines.push(s),
1027
- signal: ctrl.signal,
1028
- pollIntervalMs: 20,
1029
- });
1030
-
1031
- await new Promise((r) => setTimeout(r, 60));
1032
- ctrl.abort();
1033
- await run;
1034
-
1035
- expect(lines.length).toBeGreaterThanOrEqual(1);
1036
- const first = JSON.parse(lines[0]);
1037
- expect(first.events).toEqual(['role_assigned']);
1038
- expect(first.messages[0]).toContain('role_assigned');
1039
- expect(first).not.toHaveProperty('caught_up');
1040
- });
1041
- });
1
+ import { describe, expect, it } from 'vitest';
2
+ import {
3
+ classifyEvent,
4
+ compactEventForMonitor,
5
+ compactSummaryForMonitor,
6
+ DELAYABLE_EVENT_CONFIG,
7
+ eventKey,
8
+ MONITOR_EVENT_CONFIG,
9
+ NOTABLE_EVENT_TYPES,
10
+ nextStepFor,
11
+ nextStepForTriggers,
12
+ POLL_INTERVAL_MS,
13
+ readFeedSummary,
14
+ runStreaming,
15
+ snapshotOnce,
16
+ sortEventsForMonitor,
17
+ } from './watch.js';
18
+
19
+ describe('classifyEvent + NOTABLE_EVENT_TYPES', () => {
20
+ it('NOTABLE_EVENT_TYPES contains the headline events', () => {
21
+ for (const t of [
22
+ 'exile', 'speech_skipped', 'meeting_briefing',
23
+ 'speech', 'vote_phase_start', 'game_over', 'user_left_game',
24
+ 'speech_your_turn', 'vote_speech_phase_ended',
25
+ 'crab_teammates', 'no_exile', 'game_started',
26
+ ]) {
27
+ expect(NOTABLE_EVENT_TYPES.has(t)).toBe(true);
28
+ }
29
+ expect(NOTABLE_EVENT_TYPES.has('vote_cast')).toBe(false);
30
+ expect(NOTABLE_EVENT_TYPES.has('meeting_ended')).toBe(false);
31
+ });
32
+
33
+ it('derives NOTABLE_EVENT_TYPES from MONITOR_EVENT_CONFIG', () => {
34
+ expect([...NOTABLE_EVENT_TYPES].sort()).toEqual(Object.keys(MONITOR_EVENT_CONFIG).sort());
35
+ });
36
+
37
+ it('registers monitor event priorities in the same config as notable events', () => {
38
+ expect(MONITOR_EVENT_CONFIG.speech_your_turn.priority).toBe(99);
39
+ expect(MONITOR_EVENT_CONFIG.vote_phase_start.priority).toBe(99);
40
+ expect(MONITOR_EVENT_CONFIG.killed.priority).toBe(99);
41
+ expect(MONITOR_EVENT_CONFIG.game_started.priority).toBe(50);
42
+ expect(MONITOR_EVENT_CONFIG.speech.priority).toBe(50);
43
+ expect(MONITOR_EVENT_CONFIG.vote_speech_phase_ended.priority).toBe(50);
44
+ expect(MONITOR_EVENT_CONFIG.crab_teammates.priority).toBe(50);
45
+ expect(MONITOR_EVENT_CONFIG.user_left_game.priority).toBe(50);
46
+ expect(MONITOR_EVENT_CONFIG.vote_speech).toBeUndefined();
47
+ expect(MONITOR_EVENT_CONFIG.vote_cast).toBeUndefined();
48
+ expect(MONITOR_EVENT_CONFIG.meeting_ended).toBeUndefined();
49
+ });
50
+
51
+ it('classifyEvent returns notable=true for known types', () => {
52
+ expect(classifyEvent({ type: 'killed', tick: 1 }).notable).toBe(true);
53
+ });
54
+
55
+ it('classifyEvent returns notable=false for unknown types', () => {
56
+ expect(classifyEvent({ type: 'heartbeat', tick: 1 }).notable).toBe(false);
57
+ });
58
+
59
+ it('DELAYABLE_EVENT_CONFIG contains the delayable events', () => {
60
+ for (const t of ['kill', 'emergency_started', 'corpse_spotted']) {
61
+ expect(DELAYABLE_EVENT_CONFIG[t]).toBeGreaterThan(0);
62
+ }
63
+ });
64
+
65
+ it('classifyEvent marks speech_your_turn as notable', () => {
66
+ expect(
67
+ classifyEvent({ type: 'speech_your_turn', tick: 1, actor_name: 'me' }, 'me').notable,
68
+ ).toBe(true);
69
+ });
70
+
71
+ it('classifyEvent marks speech as notable', () => {
72
+ const cls = classifyEvent({ type: 'speech', tick: 1, actor_name: 'me' }, 'me');
73
+ expect(cls.notable).toBe(true);
74
+ });
75
+
76
+ it('does not wake the monitor for private vote_cast or meeting_ended', () => {
77
+ expect(classifyEvent({ type: 'vote_cast', tick: 1, actor_name: 'me' }, 'me').notable).toBe(false);
78
+ expect(classifyEvent({ type: 'meeting_ended', tick: 2 }, 'me').notable).toBe(false);
79
+ });
80
+
81
+ it('classifyEvent marks speech_skipped as notable', () => {
82
+ expect(
83
+ classifyEvent({ type: 'speech_skipped', tick: 1, actor_name: 'me' }, 'me').notable,
84
+ ).toBe(true);
85
+ });
86
+
87
+ it('classifyEvent ignores vote_speech but marks vote_speech_phase_ended as notable', () => {
88
+ expect(classifyEvent({ type: 'vote_speech', tick: 1, actor_name: 'me' }, 'me').notable).toBe(false);
89
+ expect(classifyEvent({ type: 'vote_speech_phase_ended', tick: 2 }, 'me').notable).toBe(true);
90
+ });
91
+
92
+ it('eventKey ignores fields that are not part of the dedup key (e.g. ts)', () => {
93
+ const a = { type: 'speech_your_turn', tick: 5, actor_name: 'me' };
94
+ const b = { type: 'speech_your_turn', tick: 5, actor_name: 'me', ts: '2026-01-01T00:00:00Z' };
95
+ expect(eventKey(a)).toBe(eventKey(b));
96
+ });
97
+
98
+ it('eventKey differs across distinct logical events', () => {
99
+ const a = { type: 'speech_your_turn', tick: 5, actor_name: 'me' };
100
+ const b = { type: 'speech_your_turn', tick: 6, actor_name: 'me' }; // different tick
101
+ const c = { type: 'speech_your_turn', tick: 5, actor_name: 'them' }; // different actor
102
+ expect(eventKey(a)).not.toBe(eventKey(b));
103
+ expect(eventKey(a)).not.toBe(eventKey(c));
104
+ });
105
+
106
+ it('eventKey keeps room events distinct even without game ticks', () => {
107
+ const a = { type: 'room.member_joined', seat: 1, name: 'a', ts: '2026-07-03T01:00:00Z' };
108
+ const b = { type: 'room.member_joined', seat: 2, name: 'b', ts: '2026-07-03T01:00:01Z' };
109
+
110
+ expect(eventKey(a)).not.toBe(eventKey(b));
111
+ });
112
+
113
+ it('classifyEvent returns notable=false for non-notable types regardless of actor', () => {
114
+ expect(classifyEvent({ type: 'heartbeat', tick: 1, actor_name: 'them' }, 'me').notable).toBe(false);
115
+ expect(classifyEvent({ type: 'heartbeat', tick: 1, actor_name: 'me' }, 'me').notable).toBe(false);
116
+ });
117
+ });
118
+
119
+ describe('sortEventsForMonitor', () => {
120
+ it('puts speech_your_turn before default-priority events', () => {
121
+ const sorted = sortEventsForMonitor([
122
+ { type: 'speech_skipped', tick: 1 },
123
+ { type: 'speech_your_turn', tick: 2 },
124
+ ]);
125
+ expect(sorted.map((e) => e.type)).toEqual(['speech_your_turn', 'speech_skipped']);
126
+ });
127
+
128
+ it('puts vote_phase_start before default-priority events', () => {
129
+ const sorted = sortEventsForMonitor([
130
+ { type: 'speech_skipped', tick: 1 },
131
+ { type: 'vote_phase_start', tick: 2 },
132
+ ]);
133
+ expect(sorted.map((e) => e.type)).toEqual(['vote_phase_start', 'speech_skipped']);
134
+ });
135
+
136
+ it('keeps original order for events with the same priority', () => {
137
+ const sorted = sortEventsForMonitor([
138
+ { type: 'speech', tick: 1 },
139
+ { type: 'speech_skipped', tick: 2 },
140
+ { type: 'vote_cast', tick: 3 },
141
+ ]);
142
+ expect(sorted.map((e) => e.type)).toEqual(['speech', 'speech_skipped', 'vote_cast']);
143
+ });
144
+ });
145
+
146
+ describe('watch defaults', () => {
147
+ it('uses 220ms as the default poll interval', () => {
148
+ expect(POLL_INTERVAL_MS).toBe(220);
149
+ });
150
+ });
151
+
152
+ describe('monitor payload compaction', () => {
153
+ it('routes role_assigned to a dedicated opening next step', () => {
154
+ expect(nextStepFor('role_assigned')).toMatch(/role/i);
155
+ expect(nextStepFor('role_assigned')).toMatch(/faction/i);
156
+ });
157
+
158
+ it('routes game_started to the opening context lookup', () => {
159
+ expect(nextStepFor('game_started')).toContain('ccl events game_started');
160
+ expect(nextStepFor('game_started')).toContain('ccl events role_assigned');
161
+ });
162
+
163
+ it('compacts ordinary lobster role_assigned without inventing extra task kind labels', () => {
164
+ const compact = compactEventForMonitor({
165
+ type: 'role_assigned',
166
+ tick: 1,
167
+ actor_name: 'me',
168
+ room: '厨房',
169
+ role: 'shrimp',
170
+ role_display_name: '普通虾',
171
+ faction: 'lobster',
172
+ role_description: '完成任务或投出所有蟹方。',
173
+ hint: 'long human hint',
174
+ assigned_tasks: [
175
+ { name: '修电线', room: '电气', x: 1, y: 2, task_note: 'long note', is_fake_shrimp: false },
176
+ ],
177
+ all_task_locations: [{ name: '修电线', room: '电气', x: 1, y: 2 }],
178
+ });
179
+
180
+ expect(compact).toEqual({
181
+ type: 'role_assigned',
182
+ tick: 1,
183
+ room: '厨房',
184
+ role: 'shrimp',
185
+ role_display: '普通虾',
186
+ faction: 'lobster',
187
+ win_condition: '完成任务或投出所有蟹方。',
188
+ tasks: [{ name: '修电线', room: '电气' }],
189
+ hint: 'You are 普通虾 (lobster). 完成任务或投出所有蟹方。 Announce your role, faction and win condition to your user.',
190
+ });
191
+ });
192
+
193
+ it('compacts all-fake neutral role_assigned into one top-level task kind', () => {
194
+ const compact = compactEventForMonitor({
195
+ type: 'role_assigned',
196
+ tick: 2,
197
+ room: '仓库',
198
+ role: 'octopus',
199
+ role_display_name: '章鱼',
200
+ faction: 'neutral',
201
+ role_description: '伪装成虾方并达成自己的胜利条件。',
202
+ fake_task_briefing: 'These are fake tasks.',
203
+ assigned_tasks: [
204
+ { name: '下载数据', room: '通讯', x: 3, y: 4, is_fake_shrimp: true },
205
+ { name: '清理垃圾', room: '餐厅', x: 5, y: 6, is_fake_shrimp: true },
206
+ ],
207
+ });
208
+
209
+ expect(compact).toEqual({
210
+ type: 'role_assigned',
211
+ tick: 2,
212
+ room: '仓库',
213
+ role: 'octopus',
214
+ role_display: '章鱼',
215
+ faction: 'neutral',
216
+ win_condition: '伪装成虾方并达成自己的胜利条件。',
217
+ task_kind: 'fake_shrimp',
218
+ task_note: 'Fake shrimp tasks: disguise only; no lobster progress.',
219
+ tasks: [
220
+ { name: '下载数据', room: '通讯' },
221
+ { name: '清理垃圾', room: '餐厅' },
222
+ ],
223
+ hint: 'You are 章鱼 (neutral). 伪装成虾方并达成自己的胜利条件。 These are fake tasks. Announce your role, faction and win condition to your user.',
224
+ });
225
+ });
226
+
227
+ it('keeps per-task kind labels for mixed crab role_assigned tasks', () => {
228
+ const compact = compactEventForMonitor({
229
+ type: 'role_assigned',
230
+ tick: 3,
231
+ room: '电气',
232
+ role: 'crab',
233
+ role_display_name: '蟹',
234
+ faction: 'crab',
235
+ role_description: '击杀虾方并避免被投出。',
236
+ fake_task_briefing: 'Fake task exists.',
237
+ assigned_tasks: [
238
+ { name: '破坏电力', room: '电气', x: 7, y: 8, is_fake_shrimp: false },
239
+ { name: '刷卡', room: '管理', x: 9, y: 10, is_fake_shrimp: true },
240
+ ],
241
+ });
242
+
243
+ expect(compact).toEqual({
244
+ type: 'role_assigned',
245
+ tick: 3,
246
+ room: '电气',
247
+ role: 'crab',
248
+ role_display: '蟹',
249
+ faction: 'crab',
250
+ win_condition: '击杀虾方并避免被投出。',
251
+ task_note: 'Fake shrimp tasks: disguise only; no lobster progress.',
252
+ tasks: [
253
+ { name: '破坏电力', room: '电气', kind: 'crab_sabotage' },
254
+ { name: '刷卡', room: '管理', kind: 'fake_shrimp' },
255
+ ],
256
+ hint: 'You are 蟹 (crab). 击杀虾方并避免被投出。 Fake task exists. Announce your role, faction and win condition to your user.',
257
+ });
258
+ });
259
+
260
+ it('removes room from meeting_briefing monitor events only', () => {
261
+ const compact = compactEventForMonitor({
262
+ type: 'meeting_briefing',
263
+ tick: 10,
264
+ room: '会议室',
265
+ caller: '红虾',
266
+ speech_order: ['红虾', '蓝虾'],
267
+ });
268
+
269
+ expect(compact).toEqual({
270
+ type: 'meeting_briefing',
271
+ tick: 10,
272
+ caller: '红虾',
273
+ speech_order: ['红虾', '蓝虾'],
274
+ });
275
+ });
276
+
277
+ it('rewrites corpse_spotted hint for monitor perspective', () => {
278
+ const compact = compactEventForMonitor({
279
+ type: 'corpse_spotted',
280
+ tick: 326,
281
+ room: 'Intel',
282
+ corpse_name: 'Garlic',
283
+ corpse_room: 'Intel',
284
+ hint: 'BODY FOUND: Garlic at (1, 2) in Intel.',
285
+ });
286
+
287
+ expect(compact).toMatchObject({
288
+ type: 'corpse_spotted',
289
+ tick: 326,
290
+ corpse_name: 'Garlic',
291
+ corpse_room: 'Intel',
292
+ hint: 'BODY FOUND: Garlic at (?, ?) in Intel. This is leverage soaked in blood — report before the killer rewrites the room.',
293
+ });
294
+ });
295
+
296
+ it('rewrites meeting_briefing hint for another caller', () => {
297
+ const compact = compactEventForMonitor({
298
+ type: 'meeting_briefing',
299
+ tick: 487,
300
+ room: 'Control',
301
+ meeting_caller_name: 'Drifter',
302
+ meeting_caller_seat: 4,
303
+ your_seat: 3,
304
+ reported_corpses: [{ name: 'Chef', seat: 9 }],
305
+ hint: 'Meeting started — seat 4 Drifter called this meeting.',
306
+ });
307
+
308
+ expect(compact).toMatchObject({
309
+ type: 'meeting_briefing',
310
+ tick: 487,
311
+ meeting_caller_name: 'Drifter',
312
+ reported_corpses: [{ name: 'Chef', seat: 9 }],
313
+ hint: 'Meeting started — seat 4 Drifter called this meeting after reporting the body of seat 9 Chef. Prepare fast — every sentence is accusation, defense, or misdirection under a timer.',
314
+ });
315
+ expect(compact).not.toHaveProperty('room');
316
+ });
317
+
318
+ it('rewrites meeting_briefing hint when you are the caller', () => {
319
+ const compact = compactEventForMonitor({
320
+ type: 'meeting_briefing',
321
+ tick: 487,
322
+ meeting_caller_name: 'Player',
323
+ meeting_caller_seat: 3,
324
+ your_seat: 3,
325
+ reported_corpses: [{ name: 'Chef', seat: 9 }],
326
+ hint: 'Meeting started — seat 3 Player called this meeting.',
327
+ });
328
+
329
+ expect(compact.hint).toBe('Meeting started — seat 3 Player called this meeting after reporting the body of seat 9 Chef. Prepare fast — every sentence is accusation, defense, or misdirection under a timer.');
330
+ });
331
+
332
+ it('compacts meeting summary and hard-overrides speech_your_turn fields', () => {
333
+ const compact = compactSummaryForMonitor({
334
+ phase: 'meeting',
335
+ you: {
336
+ name: '我',
337
+ seat: 1,
338
+ role: 'shrimp',
339
+ faction: 'lobster',
340
+ x: 11,
341
+ y: 12,
342
+ kill_cooldown_secs: 0,
343
+ },
344
+ game: { id: 'game-1', tick: 50 },
345
+ urgent: { meeting_started: true },
346
+ meeting: {
347
+ caller: '红虾',
348
+ sub_phase: 'speech',
349
+ current_speaker: '红虾',
350
+ is_my_turn: false,
351
+ alive_players: ['我', '红虾'],
352
+ speech_history: [{ speaker: '红虾', text: 'long speech' }],
353
+ votes_submitted: ['红虾'],
354
+ },
355
+ automation: { strategy: 'default', running: true },
356
+ }, ['speech_your_turn']);
357
+
358
+ expect(compact).toEqual({
359
+ phase: 'meeting',
360
+ you: { name: '我', role: 'shrimp', faction: 'lobster' },
361
+ game: { id: 'game-1', tick: 50 },
362
+ meeting: {
363
+ caller: '红虾',
364
+ sub_phase: 'speech',
365
+ alive_players: ['我', '红虾'],
366
+ current_speaker: '我',
367
+ is_my_turn: true,
368
+ },
369
+ automation: { strategy: 'default', running: true },
370
+ });
371
+ });
372
+
373
+ it('compacts vote-phase meeting summary into a submitted-vote count', () => {
374
+ const compact = compactSummaryForMonitor({
375
+ phase: 'meeting',
376
+ you: { name: '我', role: 'shrimp', faction: 'lobster' },
377
+ game: { id: 'game-1' },
378
+ meeting: {
379
+ caller: '红虾',
380
+ sub_phase: 'speech',
381
+ current_speaker: '我',
382
+ is_my_turn: true,
383
+ alive_players: ['我', '红虾', '蓝虾'],
384
+ votes_submitted: ['红虾', '蓝虾'],
385
+ },
386
+ }, ['vote_phase_start']);
387
+
388
+ expect(compact).toEqual({
389
+ phase: 'meeting',
390
+ you: { name: '我', role: 'shrimp', faction: 'lobster' },
391
+ game: { id: 'game-1' },
392
+ meeting: {
393
+ caller: '红虾',
394
+ sub_phase: 'vote',
395
+ alive_players: ['我', '红虾', '蓝虾'],
396
+ votes_submitted_count: 2,
397
+ },
398
+ });
399
+ });
400
+ });
401
+
402
+ import { mkdtempSync, writeFileSync, appendFileSync, unlinkSync, existsSync } from 'fs';
403
+ import { tmpdir } from 'os';
404
+ import { join } from 'path';
405
+
406
+ function makeTmpFiles(opts?: { seedFeed?: boolean }) {
407
+ const dir = mkdtempSync(join(tmpdir(), 'watch-stream-'));
408
+ const feedPath = join(dir, 'feed.json');
409
+ const sessionPath = join(dir, 'session.jsonl');
410
+ writeFileSync(sessionPath, '');
411
+ if (opts?.seedFeed !== false) {
412
+ writeFileSync(
413
+ feedPath,
414
+ JSON.stringify({ you: { name: 'me' }, phase: 'lobby', urgent: {}, meeting: null }),
415
+ );
416
+ }
417
+ return { dir, feedPath, sessionPath };
418
+ }
419
+
420
+ describe('runStreaming — emission shape', () => {
421
+ it('emits one NDJSON line per notable event with required fields', async () => {
422
+ const { feedPath, sessionPath } = makeTmpFiles();
423
+ writeFileSync(
424
+ feedPath,
425
+ JSON.stringify({
426
+ you: { name: 'me' },
427
+ meeting: { is_my_turn: false },
428
+ urgent: {},
429
+ }),
430
+ );
431
+ const lines: string[] = [];
432
+ const ctrl = new AbortController();
433
+
434
+ const run = runStreaming({
435
+ feedPath,
436
+ sessionPath,
437
+ stdout: (s) => lines.push(s),
438
+ signal: ctrl.signal,
439
+ pollIntervalMs: 20,
440
+ });
441
+
442
+ appendFileSync(
443
+ sessionPath,
444
+ JSON.stringify({ type: 'killed', tick: 1, actor_name: 'a' }) + '\n',
445
+ );
446
+
447
+ await new Promise((r) => setTimeout(r, 80));
448
+ ctrl.abort();
449
+ await run;
450
+
451
+ expect(lines.length).toBeGreaterThanOrEqual(1);
452
+ for (const raw of lines) {
453
+ const obj = JSON.parse(raw);
454
+ expect(Array.isArray(obj.events)).toBe(true);
455
+ expect(Array.isArray(obj.messages)).toBe(true);
456
+ expect(obj).not.toHaveProperty('trigger');
457
+ expect(obj).not.toHaveProperty('triggers');
458
+ expect(obj).not.toHaveProperty('all_events');
459
+ expect(obj).not.toHaveProperty('summary');
460
+ expect(obj).not.toHaveProperty('next_step');
461
+ expect(obj).toHaveProperty('state');
462
+ expect(raw.endsWith('\n')).toBe(true);
463
+ }
464
+ });
465
+
466
+ it('emits vote_speech_phase_ended but ignores vote_speech', async () => {
467
+ const { feedPath, sessionPath } = makeTmpFiles();
468
+ writeFileSync(
469
+ feedPath,
470
+ JSON.stringify({
471
+ you: { name: 'me' },
472
+ meeting: { is_my_turn: false },
473
+ urgent: {},
474
+ }),
475
+ );
476
+ const lines: string[] = [];
477
+ const ctrl = new AbortController();
478
+
479
+ const run = runStreaming({
480
+ feedPath,
481
+ sessionPath,
482
+ stdout: (s) => lines.push(s),
483
+ signal: ctrl.signal,
484
+ pollIntervalMs: 20,
485
+ });
486
+
487
+ await new Promise((r) => setTimeout(r, 60));
488
+ appendFileSync(
489
+ sessionPath,
490
+ JSON.stringify({ type: 'vote_speech', tick: 1, actor_name: 'a', text: 'vote talk' }) + '\n'
491
+ + JSON.stringify({ type: 'vote_speech_phase_ended', tick: 2, hint: 'The vote speech window has closed.' }) + '\n',
492
+ );
493
+
494
+ await new Promise((r) => setTimeout(r, 80));
495
+ ctrl.abort();
496
+ await run;
497
+
498
+ expect(lines.length).toBe(1);
499
+ const obj = JSON.parse(lines[0]);
500
+ expect(obj.events).toEqual(['vote_speech_phase_ended']);
501
+ expect(obj.events).toHaveLength(1);
502
+ expect(obj.messages[0]).toContain('vote_speech_phase_ended');
503
+ });
504
+
505
+ it('surfaces game_mode on game_started monitor output and message text', async () => {
506
+ const { feedPath, sessionPath } = makeTmpFiles();
507
+ writeFileSync(
508
+ feedPath,
509
+ JSON.stringify({
510
+ phase: 'wandering',
511
+ you: { name: 'me' },
512
+ urgent: {},
513
+ }),
514
+ );
515
+ const lines: string[] = [];
516
+ const ctrl = new AbortController();
517
+
518
+ const run = runStreaming({
519
+ feedPath,
520
+ sessionPath,
521
+ stdout: (s) => lines.push(s),
522
+ signal: ctrl.signal,
523
+ pollIntervalMs: 20,
524
+ });
525
+
526
+ appendFileSync(
527
+ sessionPath,
528
+ JSON.stringify({
529
+ type: 'game_started',
530
+ tick: 0,
531
+ player_count: 10,
532
+ game_mode: 'competition',
533
+ }) + '\n',
534
+ );
535
+
536
+ await new Promise((r) => setTimeout(r, 80));
537
+ ctrl.abort();
538
+ await run;
539
+
540
+ expect(lines.length).toBeGreaterThanOrEqual(1);
541
+ const obj = JSON.parse(lines[0]);
542
+ expect(obj.events).toContain('game_started');
543
+ expect(obj.game_mode).toBe('competition');
544
+ expect(obj.messages[0]).toContain('竞赛模式');
545
+ });
546
+
547
+ it('expands nested new_events from action wrapper records', async () => {
548
+ const { feedPath, sessionPath } = makeTmpFiles();
549
+ writeFileSync(
550
+ feedPath,
551
+ JSON.stringify({
552
+ you: { name: 'me' },
553
+ meeting: { is_my_turn: false },
554
+ urgent: {},
555
+ }),
556
+ );
557
+ const lines: string[] = [];
558
+ const ctrl = new AbortController();
559
+
560
+ const run = runStreaming({
561
+ feedPath,
562
+ sessionPath,
563
+ stdout: (s) => lines.push(s),
564
+ signal: ctrl.signal,
565
+ pollIntervalMs: 20,
566
+ delayableEventMs: { kill: 0 },
567
+ });
568
+
569
+ await new Promise((r) => setTimeout(r, 30));
570
+ appendFileSync(
571
+ sessionPath,
572
+ JSON.stringify({
573
+ type: 'auto',
574
+ action: 'kill',
575
+ result: {
576
+ ok: true,
577
+ new_events: [{ type: 'kill', tick: 42, target_name: 'target' }],
578
+ },
579
+ }) + '\n',
580
+ );
581
+
582
+ await new Promise((r) => setTimeout(r, 80));
583
+ ctrl.abort();
584
+ await run;
585
+
586
+ expect(lines.some((l) => JSON.parse(l).events?.includes('kill'))).toBe(true);
587
+ });
588
+
589
+ it('keeps reading after the .jsonl is truncated in place', async () => {
590
+ const { feedPath, sessionPath } = makeTmpFiles();
591
+ writeFileSync(
592
+ feedPath,
593
+ JSON.stringify({ you: { name: 'me' }, meeting: { is_my_turn: false }, urgent: {} }),
594
+ );
595
+ appendFileSync(sessionPath, JSON.stringify({ type: 'killed', tick: 1, actor_name: 'a_really_long_name' }) + '\n');
596
+
597
+ const lines: string[] = [];
598
+ const ctrl = new AbortController();
599
+ const run = runStreaming({
600
+ feedPath,
601
+ sessionPath,
602
+ stdout: (s) => lines.push(s),
603
+ signal: ctrl.signal,
604
+ pollIntervalMs: 20,
605
+ });
606
+
607
+ // Wait for the initial event to be processed (and absorbed as backlog).
608
+ await new Promise((r) => setTimeout(r, 60));
609
+ const beforeTruncate = lines.length;
610
+
611
+ // Truncate the file in place (simulating runtime log rotation that keeps the inode).
612
+ writeFileSync(sessionPath, '');
613
+ // Append a fresh notable event after truncation.
614
+ appendFileSync(sessionPath, JSON.stringify({ type: 'killed', tick: 100, actor_name: 'b' }) + '\n');
615
+
616
+ // Give the loop time to detect the truncation and re-read.
617
+ await new Promise((r) => setTimeout(r, 120));
618
+ ctrl.abort();
619
+ await run;
620
+
621
+ // The post-truncation event must produce a new line.
622
+ expect(lines.length).toBeGreaterThan(beforeTruncate);
623
+ expect(lines.some((l) => JSON.parse(l).events?.includes('killed'))).toBe(true);
624
+ });
625
+
626
+ it('throws WatchNotReadyError when feed.json never appears', async () => {
627
+ const { dir, sessionPath } = makeTmpFiles();
628
+ const lines: string[] = [];
629
+ await expect(
630
+ runStreaming({
631
+ feedPath: join(dir, 'no-feed.json'),
632
+ sessionPath,
633
+ stdout: (s) => lines.push(s),
634
+ pollIntervalMs: 20,
635
+ runtimeWaitMs: 80,
636
+ }),
637
+ ).rejects.toThrow(/not ready/i);
638
+ expect(lines.length).toBe(0);
639
+ });
640
+
641
+ it('waits for feed.json before tailing (parallel game start)', async () => {
642
+ const { feedPath, sessionPath } = makeTmpFiles({ seedFeed: false });
643
+ if (existsSync(feedPath)) unlinkSync(feedPath);
644
+ const lines: string[] = [];
645
+ const ctrl = new AbortController();
646
+ const run = runStreaming({
647
+ feedPath,
648
+ sessionPath,
649
+ stdout: (s) => lines.push(s),
650
+ signal: ctrl.signal,
651
+ pollIntervalMs: 20,
652
+ runtimeWaitMs: 2000,
653
+ });
654
+ setTimeout(() => {
655
+ writeFileSync(feedPath, JSON.stringify({ you: { name: 'me' }, phase: 'lobby', urgent: {}, meeting: null }));
656
+ }, 100);
657
+ await new Promise((r) => setTimeout(r, 250));
658
+ ctrl.abort();
659
+ await run;
660
+ expect(lines.length).toBeGreaterThanOrEqual(0);
661
+ });
662
+ });
663
+
664
+
665
+ describe('snapshotOnce', () => {
666
+ it('writes one NDJSON line with exit_reason=snapshot', () => {
667
+ const { feedPath } = makeTmpFiles();
668
+ writeFileSync(feedPath, JSON.stringify({ you: { name: 'me' }, meeting: {}, urgent: {} }));
669
+ const lines: string[] = [];
670
+ snapshotOnce({ feedPath, stdout: (s) => lines.push(s) });
671
+ expect(lines.length).toBe(1);
672
+ const obj = JSON.parse(lines[0]);
673
+ expect(obj.events).toEqual(['snapshot']);
674
+ expect(obj.messages[0]).toContain('snapshot');
675
+ expect(obj).not.toHaveProperty('trigger');
676
+ expect(obj).not.toHaveProperty('triggers');
677
+ expect(obj).not.toHaveProperty('all_events');
678
+ expect(obj).not.toHaveProperty('summary');
679
+ expect(obj).toHaveProperty('state');
680
+ });
681
+
682
+ it('errors clearly if feed.json is missing', () => {
683
+ const { dir } = makeTmpFiles();
684
+ const lines: string[] = [];
685
+ expect(() =>
686
+ snapshotOnce({ feedPath: join(dir, 'nope.json'), stdout: (s) => lines.push(s) }),
687
+ ).toThrow(/game runtime is not running/);
688
+ });
689
+ });
690
+
691
+ describe('runStreaming — startup backlog', () => {
692
+ it('attaches caught_up to the first line; subsequent lines have no caught_up', async () => {
693
+ const { feedPath, sessionPath } = makeTmpFiles();
694
+ writeFileSync(feedPath, JSON.stringify({ you: { name: 'me' }, meeting: {}, urgent: {} }));
695
+ for (let i = 0; i < 5; i++) {
696
+ appendFileSync(sessionPath, JSON.stringify({ type: 'killed', tick: i, actor_name: 'p' + i }) + '\n');
697
+ }
698
+
699
+ const lines: string[] = [];
700
+ const ctrl = new AbortController();
701
+ const run = runStreaming({ feedPath, sessionPath, stdout: (s) => lines.push(s), signal: ctrl.signal, pollIntervalMs: 20 });
702
+ await new Promise((r) => setTimeout(r, 60));
703
+
704
+ appendFileSync(sessionPath, JSON.stringify({ type: 'killed', tick: 100, actor_name: 'late' }) + '\n');
705
+ await new Promise((r) => setTimeout(r, 60));
706
+
707
+ ctrl.abort(); await run;
708
+
709
+ expect(lines.length).toBeGreaterThanOrEqual(2);
710
+ const first = JSON.parse(lines[0]);
711
+ expect(first.events).toHaveLength(5);
712
+ expect(first.events.every((event: string) => event === 'killed')).toBe(true);
713
+ for (const raw of lines.slice(1)) {
714
+ expect(JSON.parse(raw)).not.toHaveProperty('caught_up');
715
+ }
716
+ });
717
+
718
+ it('emits attached + caught_up on the first line when re-attaching mid-game', async () => {
719
+ const { feedPath, sessionPath } = makeTmpFiles();
720
+ writeFileSync(
721
+ feedPath,
722
+ JSON.stringify({
723
+ you: { name: 'me' },
724
+ meeting: { current_speaker: 'a', alive_players: ['a', 'me'], caller: 'a' },
725
+ urgent: { meeting_started: true },
726
+ }),
727
+ );
728
+ for (let i = 0; i < 3; i++) {
729
+ appendFileSync(sessionPath, JSON.stringify({ type: 'killed', tick: i, actor_name: 'p' + i }) + '\n');
730
+ }
731
+
732
+ const lines: string[] = [];
733
+ const ctrl = new AbortController();
734
+ const run = runStreaming({ feedPath, sessionPath, stdout: (s) => lines.push(s), signal: ctrl.signal, pollIntervalMs: 20 });
735
+ await new Promise((r) => setTimeout(r, 80));
736
+ ctrl.abort(); await run;
737
+
738
+ expect(lines.length).toBeGreaterThanOrEqual(1);
739
+ const first = JSON.parse(lines[0]);
740
+ expect(first.events).toEqual(['killed', 'killed', 'killed']);
741
+ expect(first).not.toHaveProperty('active_sticky_on_attach');
742
+ });
743
+ });
744
+
745
+ describe('runStreaming — game_over exits', () => {
746
+ it('returns from the loop after a game_over event', async () => {
747
+ const { feedPath, sessionPath } = makeTmpFiles();
748
+ writeFileSync(feedPath, JSON.stringify({ you: { name: 'me' }, meeting: {}, urgent: {} }));
749
+ const lines: string[] = [];
750
+ const run = runStreaming({ feedPath, sessionPath, stdout: (s) => lines.push(s), pollIntervalMs: 20 });
751
+ await new Promise((r) => setTimeout(r, 30));
752
+ appendFileSync(sessionPath, JSON.stringify({ type: 'game_over', tick: 1 }) + '\n');
753
+ await Promise.race([run, new Promise((_, rej) => setTimeout(() => rej(new Error('did not exit')), 3000))]);
754
+ expect(lines.some((l) => JSON.parse(l).events?.includes('game_over'))).toBe(true);
755
+ });
756
+
757
+ it('uses room-mode wording and next_step for room game_over', async () => {
758
+ const { feedPath, sessionPath } = makeTmpFiles();
759
+ writeFileSync(feedPath, JSON.stringify({
760
+ phase: 'game_over',
761
+ you: { name: 'me' },
762
+ game: { mode: 'room' },
763
+ meeting: {},
764
+ urgent: {},
765
+ }));
766
+ const lines: string[] = [];
767
+ const run = runStreaming({ feedPath, sessionPath, stdout: (s) => lines.push(s), pollIntervalMs: 20 });
768
+ await new Promise((r) => setTimeout(r, 30));
769
+ appendFileSync(sessionPath, JSON.stringify({ type: 'game_over', tick: 1, game_mode: 'room', reason: 'game_timeout' }) + '\n');
770
+ await Promise.race([run, new Promise((_, rej) => setTimeout(() => rej(new Error('did not exit')), 3000))]);
771
+
772
+ const notice = lines.map((l) => JSON.parse(l)).find((line) => line.events?.includes('game_over'));
773
+ expect(notice.messages).toContain('t1 game_over 本轮房间对局结束,将回到房间等待。');
774
+ expect(notice.next_step).toBe('This room match round has ended. Wait for the room stream to resume; do not start normal matchmaking.');
775
+ expect(notice.game_mode).toBe('room');
776
+ });
777
+
778
+ it('returns from the loop after a user_left_game event', async () => {
779
+ const { feedPath, sessionPath } = makeTmpFiles();
780
+ writeFileSync(feedPath, JSON.stringify({ phase: 'user_left_game', you: { name: 'me' }, meeting: {}, urgent: {} }));
781
+ const lines: string[] = [];
782
+ const run = runStreaming({ feedPath, sessionPath, stdout: (s) => lines.push(s), pollIntervalMs: 20 });
783
+ await new Promise((r) => setTimeout(r, 30));
784
+ appendFileSync(sessionPath, JSON.stringify({ type: 'user_left_game', close_code: 1000, close_reason: 'Left game' }) + '\n');
785
+ await Promise.race([run, new Promise((_, rej) => setTimeout(() => rej(new Error('did not exit')), 3000))]);
786
+
787
+ const notice = lines.map((l) => JSON.parse(l)).find((line) => line.events?.includes('user_left_game'));
788
+ expect(notice).toBeTruthy();
789
+ expect(notice.messages.some((message: string) => message.includes('The user left the game from the web page. This match has ended; stop playing and do not restart unless the user asks.'))).toBe(true);
790
+ expect(notice.state).toContain('user_left_game');
791
+ });
792
+
793
+ it('returns from the loop after a room.self_left event', async () => {
794
+ const { feedPath, sessionPath } = makeTmpFiles();
795
+ writeFileSync(feedPath, JSON.stringify({ phase: 'room_left', you: { name: 'me' }, room: null, recent_events: [] }));
796
+ const lines: string[] = [];
797
+ const run = runStreaming({ feedPath, sessionPath, stdout: (s) => lines.push(s), pollIntervalMs: 20 });
798
+ await new Promise((r) => setTimeout(r, 30));
799
+ appendFileSync(sessionPath, JSON.stringify({ type: 'room.self_left' }) + '\n');
800
+ await Promise.race([run, new Promise((_, rej) => setTimeout(() => rej(new Error('did not exit')), 3000))]);
801
+
802
+ const notice = lines.map((l) => JSON.parse(l)).find((line) => line.events?.includes('room.self_left'));
803
+ expect(notice).toBeTruthy();
804
+ expect(notice.messages.some((message: string) => message.includes('The user left the room from the web page, or the current CLI quit command has left the room. Stop the room flow and do not create or join another room unless the user asks.'))).toBe(true);
805
+ expect(notice.state).toContain('room_left');
806
+ });
807
+ });
808
+
809
+ describe('runStreaming — NDJSON discipline', () => {
810
+ it('every emitted line is JSON.parse-able', async () => {
811
+ const { feedPath, sessionPath } = makeTmpFiles();
812
+ writeFileSync(feedPath, JSON.stringify({ you: { name: 'me' }, meeting: { is_my_turn: false }, urgent: {} }));
813
+ const lines: string[] = [];
814
+ const ctrl = new AbortController();
815
+ const run = runStreaming({ feedPath, sessionPath, stdout: (s) => lines.push(s), signal: ctrl.signal, pollIntervalMs: 20 });
816
+ for (const t of ['killed', 'meeting_started', 'vote_phase_start']) {
817
+ appendFileSync(sessionPath, JSON.stringify({ type: t, tick: Date.now() }) + '\n');
818
+ await new Promise((r) => setTimeout(r, 40));
819
+ }
820
+ ctrl.abort(); await run;
821
+ for (const raw of lines) {
822
+ expect(() => JSON.parse(raw)).not.toThrow();
823
+ }
824
+ });
825
+ });
826
+
827
+ describe('runStreaming — matchmaking synthetic events', () => {
828
+ it('classifyEvent treats match_waiting / match_timeout as notable', () => {
829
+ expect(classifyEvent({ type: 'match_waiting', tick: 1, waited_secs: 0 }).notable).toBe(true);
830
+ expect(classifyEvent({ type: 'match_timeout', tick: 1, waited_secs: 600 }).notable).toBe(true);
831
+ });
832
+
833
+ it('emits lowercase exit_reason for each match_* event with a dedicated next_step', async () => {
834
+ const { feedPath, sessionPath } = makeTmpFiles();
835
+ writeFileSync(feedPath, JSON.stringify({ phase: 'matching', urgent: {}, meeting: null, you: { name: 'me' } }));
836
+ const lines: string[] = [];
837
+ const ctrl = new AbortController();
838
+ const run = runStreaming({ feedPath, sessionPath, stdout: (s) => lines.push(s), signal: ctrl.signal, pollIntervalMs: 20 });
839
+ await new Promise((r) => setTimeout(r, 30));
840
+ appendFileSync(sessionPath, JSON.stringify({ type: 'match_waiting', tick: 2, waited_secs: 0 }) + '\n');
841
+ await new Promise((r) => setTimeout(r, 60));
842
+ appendFileSync(sessionPath, JSON.stringify({ type: 'match_timeout', tick: 3, waited_secs: 600 }) + '\n');
843
+ await new Promise((r) => setTimeout(r, 60));
844
+ ctrl.abort(); await run;
845
+
846
+ const eventNames = lines.flatMap((l) => JSON.parse(l).events);
847
+ expect(eventNames).toContain('match_waiting');
848
+ expect(eventNames).toContain('match_timeout');
849
+
850
+ const timeout = lines.map((l) => JSON.parse(l)).find((o) => o.events?.includes('match_timeout'));
851
+ expect(timeout.messages[0]).toContain('600');
852
+ });
853
+ });
854
+
855
+ describe('room ready routing', () => {
856
+ it('asks for user confirmation before starting a full room', () => {
857
+ expect(nextStepForTriggers(['room_ready_to_start'])).toBe('Room is full. Ask the user whether to start now before running `ccl game start-room`.');
858
+ expect(nextStepForTriggers(['room.full'])).toBe('Room is full. Ask the user whether to start now before running `ccl game start-room`.');
859
+ });
860
+
861
+ it('routes room.game_finished without ending the room stream', () => {
862
+ expect(classifyEvent({ type: 'room.game_finished', game_id: 'game-1' }).notable).toBe(true);
863
+ expect(nextStepForTriggers(['room.game_finished'])).toContain('上一轮房间对局已结束');
864
+ });
865
+ });
866
+
867
+ describe('runStreaming — room heartbeat snapshots', () => {
868
+ it('emits room.game_finished as a notable room event', async () => {
869
+ const { feedPath, sessionPath } = makeTmpFiles();
870
+ writeFileSync(feedPath, JSON.stringify({
871
+ phase: 'room_waiting',
872
+ you: { name: 'me', seat: 1, is_owner: false },
873
+ room: { room_code: '123456', status: 'waiting', member_count: 10, members: [] },
874
+ recent_events: [],
875
+ }));
876
+ const lines: string[] = [];
877
+ const ctrl = new AbortController();
878
+ const run = runStreaming({
879
+ feedPath,
880
+ sessionPath,
881
+ stdout: (s) => lines.push(s),
882
+ signal: ctrl.signal,
883
+ pollIntervalMs: 10,
884
+ heartbeatIntervalMs: 0,
885
+ });
886
+
887
+ await new Promise((r) => setTimeout(r, 20));
888
+ appendFileSync(sessionPath, JSON.stringify({ type: 'room.game_finished', game_id: 'game-1' }) + '\n');
889
+ await new Promise((r) => setTimeout(r, 60));
890
+ ctrl.abort(); await run;
891
+
892
+ const notice = lines.map((l) => JSON.parse(l)).find((line) => line.events?.includes('room.game_finished'));
893
+ expect(notice).toBeTruthy();
894
+ expect(notice.messages[0]).toContain('上一轮房间对局已结束');
895
+ expect(notice.state).toContain('room=123456');
896
+ });
897
+
898
+ it('emits a room waiting snapshot when room events are quiet', async () => {
899
+ const { feedPath, sessionPath } = makeTmpFiles();
900
+ writeFileSync(feedPath, JSON.stringify({
901
+ phase: 'room_waiting',
902
+ you: { name: 'me', seat: 1, is_owner: false },
903
+ room: { room_code: '123456', status: 'waiting', member_count: 6, members: [] },
904
+ recent_events: [],
905
+ }));
906
+ const lines: string[] = [];
907
+ const ctrl = new AbortController();
908
+ const run = runStreaming({
909
+ feedPath,
910
+ sessionPath,
911
+ stdout: (s) => lines.push(s),
912
+ signal: ctrl.signal,
913
+ pollIntervalMs: 10,
914
+ heartbeatIntervalMs: 30,
915
+ });
916
+
917
+ await new Promise((r) => setTimeout(r, 80));
918
+ ctrl.abort(); await run;
919
+
920
+ const heartbeat = lines.map((l) => JSON.parse(l)).find((line) => line.events?.includes('heartbeat'));
921
+ expect(heartbeat).toBeTruthy();
922
+ expect(heartbeat.messages[0]).toContain('房间 123456 当前 6/10 人');
923
+ expect(heartbeat.messages[0]).toContain('正在等待更多玩家加入');
924
+ expect(heartbeat.state).toContain('room=123456');
925
+ expect(heartbeat.state).toContain('members=6/10');
926
+ });
927
+
928
+ it('does not tell the agent to confirm starting from a full-room heartbeat', async () => {
929
+ const { feedPath, sessionPath } = makeTmpFiles();
930
+ writeFileSync(feedPath, JSON.stringify({
931
+ phase: 'room_waiting',
932
+ you: { name: 'me', seat: 1, is_owner: true },
933
+ room: { room_code: '123456', status: 'waiting', member_count: 10, is_owner: true, ready_to_start: true, members: [] },
934
+ recent_events: [],
935
+ }));
936
+ const lines: string[] = [];
937
+ const ctrl = new AbortController();
938
+ const run = runStreaming({
939
+ feedPath,
940
+ sessionPath,
941
+ stdout: (s) => lines.push(s),
942
+ signal: ctrl.signal,
943
+ pollIntervalMs: 10,
944
+ heartbeatIntervalMs: 30,
945
+ });
946
+
947
+ await new Promise((r) => setTimeout(r, 80));
948
+ ctrl.abort(); await run;
949
+
950
+ const heartbeat = lines.map((l) => JSON.parse(l)).find((line) => line.events?.includes('heartbeat'));
951
+ expect(heartbeat).toBeTruthy();
952
+ expect(heartbeat.messages[0]).toContain('房间 123456 当前 10/10 人');
953
+ expect(heartbeat.messages[0]).toContain('等待房主操作');
954
+ expect(heartbeat.messages[0]).not.toContain('用户确认');
955
+ expect(heartbeat.messages[0]).not.toContain('start-room');
956
+ });
957
+
958
+ it('describes room playing as waiting for other players to finish', async () => {
959
+ const { feedPath, sessionPath } = makeTmpFiles();
960
+ writeFileSync(feedPath, JSON.stringify({
961
+ phase: 'room_playing',
962
+ you: { name: 'me', seat: 1, is_owner: false },
963
+ room: { room_code: '123456', status: 'playing', member_count: 10, members: [] },
964
+ recent_events: [],
965
+ }));
966
+ const lines: string[] = [];
967
+ const ctrl = new AbortController();
968
+ const run = runStreaming({
969
+ feedPath,
970
+ sessionPath,
971
+ stdout: (s) => lines.push(s),
972
+ signal: ctrl.signal,
973
+ pollIntervalMs: 10,
974
+ heartbeatIntervalMs: 30,
975
+ });
976
+
977
+ await new Promise((r) => setTimeout(r, 80));
978
+ ctrl.abort(); await run;
979
+
980
+ const heartbeat = lines.map((l) => JSON.parse(l)).find((line) => line.events?.includes('heartbeat'));
981
+ expect(heartbeat).toBeTruthy();
982
+ expect(heartbeat.messages[0]).toContain('上一轮对局仍在进行');
983
+ expect(heartbeat.messages[0]).toContain('正在等待其他玩家结束');
984
+ });
985
+ });
986
+
987
+ describe('runStreaming — speech_your_turn fires as notable event', () => {
988
+ it('fires speech_your_turn as exit_reason when speech_your_turn event arrives', async () => {
989
+ const { feedPath, sessionPath } = makeTmpFiles();
990
+ writeFileSync(feedPath, JSON.stringify({ phase: 'meeting', urgent: {}, meeting: { current_speaker: 'other' }, you: { name: 'me' } }));
991
+ const lines: string[] = [];
992
+ const ctrl = new AbortController();
993
+ const run = runStreaming({ feedPath, sessionPath, stdout: (s) => lines.push(s), signal: ctrl.signal, pollIntervalMs: 20 });
994
+ await new Promise((r) => setTimeout(r, 30));
995
+ appendFileSync(sessionPath, JSON.stringify({ type: 'speech_your_turn', tick: 1, actor_name: 'me' }) + '\n');
996
+ await new Promise((r) => setTimeout(r, 80));
997
+ ctrl.abort(); await run;
998
+
999
+ const parsed = lines.map((l) => JSON.parse(l));
1000
+ const myTurn = parsed.find((o) => o.events?.includes('speech_your_turn'));
1001
+ expect(myTurn).toBeDefined();
1002
+ expect(myTurn!.events).toContain('speech_your_turn');
1003
+ });
1004
+ });
1005
+
1006
+ describe('runStreaming — delay buffer', () => {
1007
+ it('delays a delayable event (kill) and emits after the delay expires', async () => {
1008
+ const { feedPath, sessionPath } = makeTmpFiles();
1009
+ writeFileSync(
1010
+ feedPath,
1011
+ JSON.stringify({ you: { name: 'me' }, phase: 'wandering', urgent: {}, meeting: null }),
1012
+ );
1013
+ const lines: string[] = [];
1014
+ const ctrl = new AbortController();
1015
+ const run = runStreaming({
1016
+ feedPath,
1017
+ sessionPath,
1018
+ stdout: (s) => lines.push(s),
1019
+ signal: ctrl.signal,
1020
+ pollIntervalMs: 20,
1021
+ delayableEventMs: { kill: 100 },
1022
+ });
1023
+ await new Promise((r) => setTimeout(r, 30));
1024
+ appendFileSync(sessionPath, JSON.stringify({ type: 'kill', tick: 1, actor_name: '蟹A', target_name: '虾B' }) + '\n');
1025
+ await new Promise((r) => setTimeout(r, 50));
1026
+ expect(lines.length).toBe(0);
1027
+ await new Promise((r) => setTimeout(r, 100));
1028
+ ctrl.abort(); await run;
1029
+
1030
+ const parsed = lines.map((l) => JSON.parse(l));
1031
+ const killNotif = parsed.find((o) => o.events?.includes('kill'));
1032
+ expect(killNotif).toBeDefined();
1033
+ });
1034
+
1035
+ it('merges multiple events arriving during the delay window into one notification', async () => {
1036
+ const { feedPath, sessionPath } = makeTmpFiles();
1037
+ writeFileSync(
1038
+ feedPath,
1039
+ JSON.stringify({ you: { name: 'me' }, phase: 'wandering', urgent: {}, meeting: null }),
1040
+ );
1041
+ const lines: string[] = [];
1042
+ const ctrl = new AbortController();
1043
+ const run = runStreaming({
1044
+ feedPath,
1045
+ sessionPath,
1046
+ stdout: (s) => lines.push(s),
1047
+ signal: ctrl.signal,
1048
+ pollIntervalMs: 20,
1049
+ delayableEventMs: { kill: 200, emergency_started: 200 },
1050
+ });
1051
+ await new Promise((r) => setTimeout(r, 30));
1052
+ appendFileSync(sessionPath, JSON.stringify({ type: 'kill', tick: 1, actor_name: '蟹A', target_name: '虾B' }) + '\n');
1053
+ await new Promise((r) => setTimeout(r, 50));
1054
+ appendFileSync(sessionPath, JSON.stringify({ type: 'emergency_started', tick: 2 }) + '\n');
1055
+ await new Promise((r) => setTimeout(r, 50));
1056
+ appendFileSync(sessionPath, JSON.stringify({ type: 'task_completed', tick: 3, task_name: 'wires' }) + '\n');
1057
+ await new Promise((r) => setTimeout(r, 250));
1058
+ ctrl.abort(); await run;
1059
+
1060
+ const parsed = lines.map((l) => JSON.parse(l));
1061
+ const merged = parsed.find((o) => o.events?.includes('kill'));
1062
+ expect(merged).toBeDefined();
1063
+ expect(merged!.events).toContain('emergency_started');
1064
+ expect(merged!.events).toContain('task_completed');
1065
+ const notableLines = parsed.filter((o) => !o.events?.includes('heartbeat'));
1066
+ expect(notableLines.length).toBe(1);
1067
+ });
1068
+
1069
+ it('does not extend delay when a second delayable event arrives mid-delay', async () => {
1070
+ const { feedPath, sessionPath } = makeTmpFiles();
1071
+ writeFileSync(
1072
+ feedPath,
1073
+ JSON.stringify({ you: { name: 'me' }, phase: 'wandering', urgent: {}, meeting: null }),
1074
+ );
1075
+ const lines: string[] = [];
1076
+ const ctrl = new AbortController();
1077
+ const run = runStreaming({
1078
+ feedPath,
1079
+ sessionPath,
1080
+ stdout: (s) => lines.push(s),
1081
+ signal: ctrl.signal,
1082
+ pollIntervalMs: 20,
1083
+ delayableEventMs: { kill: 150, emergency_started: 5000 },
1084
+ });
1085
+ await new Promise((r) => setTimeout(r, 30));
1086
+ appendFileSync(sessionPath, JSON.stringify({ type: 'kill', tick: 1, actor_name: '蟹A', target_name: '虾B' }) + '\n');
1087
+ await new Promise((r) => setTimeout(r, 50));
1088
+ appendFileSync(sessionPath, JSON.stringify({ type: 'emergency_started', tick: 2 }) + '\n');
1089
+ await new Promise((r) => setTimeout(r, 200));
1090
+ ctrl.abort(); await run;
1091
+
1092
+ const parsed = lines.map((l) => JSON.parse(l));
1093
+ const merged = parsed.find((o) => o.events?.includes('kill'));
1094
+ expect(merged).toBeDefined();
1095
+ expect(merged!.events).toContain('emergency_started');
1096
+ });
1097
+
1098
+ it('non-delayable events fire immediately when no delay is active', async () => {
1099
+ const { feedPath, sessionPath } = makeTmpFiles();
1100
+ writeFileSync(
1101
+ feedPath,
1102
+ JSON.stringify({ you: { name: 'me' }, phase: 'wandering', urgent: {}, meeting: null }),
1103
+ );
1104
+ const lines: string[] = [];
1105
+ const ctrl = new AbortController();
1106
+ const run = runStreaming({
1107
+ feedPath,
1108
+ sessionPath,
1109
+ stdout: (s) => lines.push(s),
1110
+ signal: ctrl.signal,
1111
+ pollIntervalMs: 20,
1112
+ delayableEventMs: { kill: 200 },
1113
+ });
1114
+ await new Promise((r) => setTimeout(r, 30));
1115
+ appendFileSync(sessionPath, JSON.stringify({ type: 'task_completed', tick: 1, task_name: 'wires' }) + '\n');
1116
+ await new Promise((r) => setTimeout(r, 80));
1117
+ ctrl.abort(); await run;
1118
+
1119
+ const parsed = lines.map((l) => JSON.parse(l));
1120
+ expect(parsed.some((o) => o.events?.includes('task_completed'))).toBe(true);
1121
+ });
1122
+ });
1123
+
1124
+ describe('readFeedSummary', () => {
1125
+ it('includes automation strategy from the feed projection without exposing pid', () => {
1126
+ const { feedPath } = makeTmpFiles();
1127
+ writeFileSync(
1128
+ feedPath,
1129
+ JSON.stringify({
1130
+ phase: 'wandering',
1131
+ you: { name: 'me' },
1132
+ game: { id: 'game-1' },
1133
+ urgent: {},
1134
+ meeting: null,
1135
+ automation: { strategy: 'default', running: true },
1136
+ }),
1137
+ );
1138
+
1139
+ const summary = readFeedSummary(feedPath);
1140
+ expect(summary?.automation).toEqual({ strategy: 'default', running: true });
1141
+ expect(summary?.automation).not.toHaveProperty('pid');
1142
+ expect(summary?.automation).not.toHaveProperty('source');
1143
+ });
1144
+ });
1145
+
1146
+ describe('runStreaming startup monitor payload', () => {
1147
+ it('emits game_start without initial_payload when requested by game start', async () => {
1148
+ const { feedPath, sessionPath } = makeTmpFiles();
1149
+ writeFileSync(
1150
+ feedPath,
1151
+ JSON.stringify({ you: { name: 'me' }, phase: 'lobby', urgent: {}, meeting: null }),
1152
+ );
1153
+ const lines: string[] = [];
1154
+ const ctrl = new AbortController();
1155
+
1156
+ const run = runStreaming({
1157
+ feedPath,
1158
+ sessionPath,
1159
+ stdout: (s) => lines.push(s),
1160
+ signal: ctrl.signal,
1161
+ pollIntervalMs: 20,
1162
+ emitGameStart: true,
1163
+ });
1164
+
1165
+ await new Promise((r) => setTimeout(r, 60));
1166
+ ctrl.abort();
1167
+ await run;
1168
+
1169
+ expect(lines.length).toBeGreaterThanOrEqual(1);
1170
+ const first = JSON.parse(lines[0]);
1171
+ expect(first.events).toEqual(['game_start']);
1172
+ expect(first).not.toHaveProperty('initial_payload');
1173
+ expect(first.messages[0]).toContain('game_start');
1174
+ });
1175
+
1176
+ it('does not emit a synthetic game_start when startup emission is disabled', async () => {
1177
+ const { feedPath, sessionPath } = makeTmpFiles();
1178
+ writeFileSync(
1179
+ feedPath,
1180
+ JSON.stringify({ you: { name: 'me' }, phase: 'room_waiting', room: { room_code: '123456' }, urgent: {}, meeting: null }),
1181
+ );
1182
+ const lines: string[] = [];
1183
+ const ctrl = new AbortController();
1184
+
1185
+ const run = runStreaming({
1186
+ feedPath,
1187
+ sessionPath,
1188
+ stdout: (s) => lines.push(s),
1189
+ signal: ctrl.signal,
1190
+ pollIntervalMs: 20,
1191
+ emitGameStart: false,
1192
+ heartbeatIntervalMs: 0,
1193
+ });
1194
+
1195
+ await new Promise((r) => setTimeout(r, 80));
1196
+ ctrl.abort();
1197
+ await run;
1198
+
1199
+ expect(lines).toEqual([]);
1200
+ });
1201
+
1202
+ it('final-drains written room events before an intentional stream handoff exits', async () => {
1203
+ const { feedPath, sessionPath } = makeTmpFiles();
1204
+ writeFileSync(
1205
+ feedPath,
1206
+ JSON.stringify({ you: { name: 'me' }, phase: 'room_waiting', room: { room_code: '123456' }, urgent: {}, meeting: null }),
1207
+ );
1208
+ const lines: string[] = [];
1209
+ const ctrl = new AbortController();
1210
+
1211
+ const run = runStreaming({
1212
+ feedPath,
1213
+ sessionPath,
1214
+ stdout: (s) => lines.push(s),
1215
+ signal: ctrl.signal,
1216
+ pollIntervalMs: 1000,
1217
+ emitGameStart: false,
1218
+ heartbeatIntervalMs: 0,
1219
+ finalDrainOnAbort: true,
1220
+ finalDrainTimeoutMs: 500,
1221
+ });
1222
+
1223
+ await new Promise((r) => setTimeout(r, 50));
1224
+ appendFileSync(sessionPath, JSON.stringify({ type: 'room.game_started', game_id: 'game-1' }) + '\n');
1225
+ ctrl.abort();
1226
+ await run;
1227
+
1228
+ expect(lines.length).toBe(1);
1229
+ const notice = JSON.parse(lines[0]);
1230
+ expect(notice.events).toEqual(['room.game_started']);
1231
+ expect(notice.messages[0]).toContain('room.game_started');
1232
+ });
1233
+
1234
+ it('compacts role_assigned inside caught_up notable events', async () => {
1235
+ const { feedPath, sessionPath } = makeTmpFiles();
1236
+ writeFileSync(
1237
+ feedPath,
1238
+ JSON.stringify({ you: { name: 'me' }, phase: 'wandering', urgent: {}, meeting: null }),
1239
+ );
1240
+ appendFileSync(sessionPath, JSON.stringify({
1241
+ type: 'role_assigned',
1242
+ tick: 1,
1243
+ room: '仓库',
1244
+ role: 'octopus',
1245
+ role_display_name: '章鱼',
1246
+ faction: 'neutral',
1247
+ role_description: '伪装成虾方并达成自己的胜利条件。',
1248
+ fake_task_briefing: 'These are fake tasks.',
1249
+ hint: 'long hint',
1250
+ assigned_tasks: [
1251
+ { name: '下载数据', room: '通讯', x: 3, y: 4, is_fake_shrimp: true },
1252
+ ],
1253
+ }) + '\n');
1254
+ const lines: string[] = [];
1255
+ const ctrl = new AbortController();
1256
+
1257
+ const run = runStreaming({
1258
+ feedPath,
1259
+ sessionPath,
1260
+ stdout: (s) => lines.push(s),
1261
+ signal: ctrl.signal,
1262
+ pollIntervalMs: 20,
1263
+ });
1264
+
1265
+ await new Promise((r) => setTimeout(r, 60));
1266
+ ctrl.abort();
1267
+ await run;
1268
+
1269
+ expect(lines.length).toBeGreaterThanOrEqual(1);
1270
+ const first = JSON.parse(lines[0]);
1271
+ expect(first.events).toEqual(['role_assigned']);
1272
+ expect(first.messages[0]).toContain('role_assigned');
1273
+ expect(first).not.toHaveProperty('caught_up');
1274
+ });
1275
+
1276
+ it('does not replay room waiting events when a game-stage session is attached', async () => {
1277
+ const { dir, feedPath, sessionPath: gameSessionPath } = makeTmpFiles();
1278
+ const roomSessionPath = join(dir, 'room-session.jsonl');
1279
+ writeFileSync(
1280
+ feedPath,
1281
+ JSON.stringify({ you: { name: 'me' }, phase: 'preparing', urgent: {}, meeting: null }),
1282
+ );
1283
+ appendFileSync(roomSessionPath, JSON.stringify({ type: 'room_ready_to_start', room_code: '123456' }) + '\n');
1284
+ appendFileSync(roomSessionPath, JSON.stringify({ type: 'room.full', room_code: '123456' }) + '\n');
1285
+ appendFileSync(gameSessionPath, JSON.stringify({
1286
+ type: 'role_assigned',
1287
+ tick: 0,
1288
+ role: 'shrimp_generic',
1289
+ faction: 'lobster',
1290
+ }) + '\n');
1291
+ const lines: string[] = [];
1292
+ const ctrl = new AbortController();
1293
+
1294
+ const run = runStreaming({
1295
+ feedPath,
1296
+ sessionPath: gameSessionPath,
1297
+ getSessionPath: () => gameSessionPath,
1298
+ stdout: (s) => lines.push(s),
1299
+ signal: ctrl.signal,
1300
+ pollIntervalMs: 20,
1301
+ });
1302
+
1303
+ await new Promise((r) => setTimeout(r, 60));
1304
+ ctrl.abort();
1305
+ await run;
1306
+
1307
+ const first = JSON.parse(lines[0]);
1308
+ expect(first.events).toEqual(['role_assigned']);
1309
+ expect(first.messages[0]).toContain('role_assigned');
1310
+ expect(first.events).not.toContain('room_ready_to_start');
1311
+ expect(first.events).not.toContain('room.full');
1312
+ });
1313
+ });