@myclaw163/clawclaw-cli 0.6.100 → 0.6.101

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 (226) hide show
  1. package/README.md +385 -385
  2. package/bin/clawclaw-cli.mjs +3 -3
  3. package/package.json +48 -48
  4. package/personas//345/217/243/346/230/257/345/277/203/351/235/236.md +50 -50
  5. package/personas//345/277/240/345/277/203/350/200/201/344/273/206.md +51 -51
  6. package/personas//346/227/240/344/272/272/350/256/276.md +1 -1
  7. package/personas//350/264/253/345/230/264/346/215/237/345/217/213.md +48 -48
  8. package/personas//350/275/257/350/220/214/350/205/271/351/273/221.md +51 -51
  9. package/scripts/check-skill-command-surface.mjs +118 -118
  10. package/scripts/check_monitor.cjs +435 -435
  11. package/scripts/check_monitor.test.mjs +212 -212
  12. package/scripts/enable_ccl_permissions.cjs +147 -147
  13. package/scripts/enable_ccl_permissions.test.mjs +132 -132
  14. package/scripts/enable_monitor.cjs +677 -677
  15. package/scripts/enable_monitor.test.mjs +201 -201
  16. package/scripts/find-hide-spots.py +157 -157
  17. package/scripts/postinstall.mjs +20 -20
  18. package/scripts/sync-bundled-skill.mjs +254 -254
  19. package/scripts/sync-bundled-skill.test.mjs +152 -152
  20. package/skills/clawclaw/SKILL.md +290 -290
  21. package/skills/clawclaw/references/CHATTERBOX.md +142 -142
  22. package/skills/clawclaw/references/CLAUDE-CODE-MONITOR.md +224 -224
  23. package/skills/clawclaw/references/COMMANDS.md +177 -177
  24. package/skills/clawclaw/references/GAME-MECHANICS.md +190 -190
  25. package/skills/clawclaw/references/HUB.md +48 -48
  26. package/skills/clawclaw/references/KNOWLEDGE.md +42 -42
  27. package/skills/clawclaw/references/STRATEGIES.md +59 -59
  28. package/skills/clawclaw/references/STREAM.md +77 -77
  29. package/skills/clawclaw/references/TACTICS.md +65 -65
  30. package/src/assets/clawclaw-ascii-map.txt +40 -40
  31. package/src/cli.ts +113 -113
  32. package/src/commands/_schema.ts +124 -124
  33. package/src/commands/account.test.ts +332 -332
  34. package/src/commands/account.ts +315 -315
  35. package/src/commands/competition.ts +42 -42
  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 -117
  39. package/src/commands/do.ts +191 -191
  40. package/src/commands/events.test.ts +142 -142
  41. package/src/commands/events.ts +268 -268
  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 -252
  45. package/src/commands/game.ts +1892 -1892
  46. package/src/commands/history-player.test.ts +105 -105
  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/openclaw.test.ts +20 -10
  60. package/src/commands/setup/openclaw.ts +24 -9
  61. package/src/commands/skill.ts +128 -128
  62. package/src/commands/state.ts +46 -46
  63. package/src/commands/strategy.test.ts +153 -153
  64. package/src/commands/strategy.ts +194 -194
  65. package/src/commands/upgrade.test.ts +82 -82
  66. package/src/commands/upgrade.ts +148 -148
  67. package/src/commands/watch.test.ts +1313 -1313
  68. package/src/commands/watch.ts +824 -824
  69. package/src/lib/account-guidance.test.ts +32 -32
  70. package/src/lib/account-guidance.ts +62 -62
  71. package/src/lib/auth.test.ts +116 -116
  72. package/src/lib/auth.ts +189 -189
  73. package/src/lib/command-meta.ts +37 -37
  74. package/src/lib/competition.ts +79 -79
  75. package/src/lib/game-client.test.ts +82 -82
  76. package/src/lib/game-client.ts +443 -443
  77. package/src/lib/game-context.ts +92 -92
  78. package/src/lib/http-keepalive.ts +15 -15
  79. package/src/lib/http-transport.test.ts +61 -61
  80. package/src/lib/http-transport.ts +118 -118
  81. package/src/lib/hub-client.test.ts +57 -57
  82. package/src/lib/hub-client.ts +88 -88
  83. package/src/lib/hub-install.test.ts +139 -139
  84. package/src/lib/hub-install.ts +198 -198
  85. package/src/lib/hub-reminder.ts +81 -81
  86. package/src/lib/hub-unzip.test.ts +69 -69
  87. package/src/lib/hub-unzip.ts +62 -62
  88. package/src/lib/init-command.test.ts +75 -75
  89. package/src/lib/init-command.ts +130 -130
  90. package/src/lib/knowledge-store.test.ts +170 -170
  91. package/src/lib/knowledge-store.ts +369 -369
  92. package/src/lib/load-context.test.ts +62 -62
  93. package/src/lib/load-context.ts +49 -49
  94. package/src/lib/match-state.test.ts +134 -134
  95. package/src/lib/match-state.ts +94 -94
  96. package/src/lib/normalize.ts +42 -42
  97. package/src/lib/persona.test.ts +84 -84
  98. package/src/lib/persona.ts +120 -120
  99. package/src/lib/room.test.ts +74 -74
  100. package/src/lib/room.ts +129 -129
  101. package/src/lib/server-registry.test.ts +54 -54
  102. package/src/lib/server-registry.ts +185 -185
  103. package/src/lib/skill-version.test.ts +48 -48
  104. package/src/lib/skill-version.ts +19 -19
  105. package/src/lib/strategy-export.test.ts +240 -240
  106. package/src/lib/strategy-export.ts +247 -247
  107. package/src/lib/user-data.test.ts +97 -97
  108. package/src/lib/user-data.ts +374 -374
  109. package/src/lib/workspace-argv.test.ts +49 -49
  110. package/src/lib/workspace-argv.ts +44 -44
  111. package/src/perception/player-history-store.test.ts +177 -177
  112. package/src/perception/player-history-store.ts +262 -262
  113. package/src/pipeline/event-format.test.ts +307 -307
  114. package/src/pipeline/event-format.ts +595 -595
  115. package/src/pipeline/event-hints.ts +204 -204
  116. package/src/pipeline/event-store.test.ts +28 -28
  117. package/src/pipeline/event-store.ts +193 -193
  118. package/src/pipeline/pipeline.ts +35 -35
  119. package/src/pipeline/player-projection.test.ts +168 -168
  120. package/src/pipeline/player-projection.ts +370 -370
  121. package/src/runtime/auto-upgrade.test.ts +66 -66
  122. package/src/runtime/auto-upgrade.ts +31 -31
  123. package/src/runtime/event-daemon.test.ts +268 -268
  124. package/src/runtime/event-daemon.ts +531 -531
  125. package/src/runtime/owner-control.ts +150 -150
  126. package/src/runtime/raw-ws-log.test.ts +33 -33
  127. package/src/runtime/raw-ws-log.ts +32 -32
  128. package/src/runtime/room-lobby-runtime.test.ts +95 -95
  129. package/src/runtime/room-lobby-runtime.ts +367 -367
  130. package/src/runtime/runtime-logger.ts +107 -107
  131. package/src/runtime/ws-client.test.ts +169 -169
  132. package/src/runtime/ws-client.ts +280 -280
  133. package/src/sdk/action.ts +155 -155
  134. package/src/sdk/index.ts +112 -112
  135. package/src/sdk/types.ts +163 -163
  136. package/src/strategies/avoid-lone.ts +14 -14
  137. package/src/strategies/avoid-players.knowledge.md +19 -19
  138. package/src/strategies/avoid-players.ts +18 -18
  139. package/src/strategies/corpse-patrol.ts +21 -21
  140. package/src/strategies/crab-sabotage.ts +24 -24
  141. package/src/strategies/custom-module.test.ts +270 -270
  142. package/src/strategies/find-player.ts +19 -19
  143. package/src/strategies/game-utils.test.ts +242 -242
  144. package/src/strategies/game-utils.ts +853 -853
  145. package/src/strategies/goals/anchor-linger.ts +77 -77
  146. package/src/strategies/goals/avoid-lone-top.ts +168 -168
  147. package/src/strategies/goals/avoid-players-top.test.ts +83 -83
  148. package/src/strategies/goals/avoid-players-top.ts +121 -121
  149. package/src/strategies/goals/conversation-goal.ts +51 -51
  150. package/src/strategies/goals/corpse-patrol-top.ts +113 -113
  151. package/src/strategies/goals/crab-octopus-reflexes.ts +101 -101
  152. package/src/strategies/goals/crab-sabotage-top.ts +226 -226
  153. package/src/strategies/goals/emergency-hunt-goal.ts +28 -28
  154. package/src/strategies/goals/find-player-top.ts +93 -93
  155. package/src/strategies/goals/flee-players-goal.ts +53 -53
  156. package/src/strategies/goals/follow-companion-goal.ts +106 -106
  157. package/src/strategies/goals/goal-manager.ts +41 -41
  158. package/src/strategies/goals/goal-root-strategy.ts +49 -49
  159. package/src/strategies/goals/goal.ts +28 -28
  160. package/src/strategies/goals/hide-top.ts +197 -197
  161. package/src/strategies/goals/keep-away-goal.ts +221 -221
  162. package/src/strategies/goals/kill-frenzy-top.ts +80 -80
  163. package/src/strategies/goals/kill-lone-top.ts +160 -160
  164. package/src/strategies/goals/kill-target-goal.ts +59 -59
  165. package/src/strategies/goals/kill-target-top.ts +109 -109
  166. package/src/strategies/goals/leaf-goal.ts +27 -27
  167. package/src/strategies/goals/linger-corpse-goal.ts +35 -35
  168. package/src/strategies/goals/lone-kill-core.ts +82 -82
  169. package/src/strategies/goals/lone-kill-goal.ts +24 -24
  170. package/src/strategies/goals/lone-kill-task-top.test.ts +85 -85
  171. package/src/strategies/goals/lone-kill-task-top.ts +133 -133
  172. package/src/strategies/goals/move-room-goal.ts +60 -60
  173. package/src/strategies/goals/normal-shrimp-top.test.ts +97 -97
  174. package/src/strategies/goals/normal-shrimp-top.ts +248 -248
  175. package/src/strategies/goals/paradise-fish-top.test.ts +126 -126
  176. package/src/strategies/goals/paradise-fish-top.ts +224 -224
  177. package/src/strategies/goals/patrol-top.ts +57 -57
  178. package/src/strategies/goals/report-patrol-top.ts +86 -86
  179. package/src/strategies/goals/safe-task-goal.ts +102 -102
  180. package/src/strategies/goals/social-task-top.ts +161 -161
  181. package/src/strategies/goals/task-kill-report-top.ts +163 -163
  182. package/src/strategies/goals/task-only-top.ts +57 -57
  183. package/src/strategies/goals/task-or-patrol-goal.ts +41 -41
  184. package/src/strategies/goals/task-report-top.ts +57 -57
  185. package/src/strategies/goals/wander-task-goal.ts +33 -33
  186. package/src/strategies/goals/warrior-shrimp-top.test.ts +87 -87
  187. package/src/strategies/goals/warrior-shrimp-top.ts +267 -267
  188. package/src/strategies/greeting.ts +53 -53
  189. package/src/strategies/hide-spots.ts +59 -59
  190. package/src/strategies/hide.ts +26 -26
  191. package/src/strategies/kill-frenzy.ts +15 -15
  192. package/src/strategies/kill-lone.knowledge.md +17 -17
  193. package/src/strategies/kill-lone.ts +16 -16
  194. package/src/strategies/kill-target.ts +21 -21
  195. package/src/strategies/knowledge-contract.ts +85 -85
  196. package/src/strategies/loader.test.ts +678 -678
  197. package/src/strategies/loader.ts +181 -181
  198. package/src/strategies/lone-kill-task.ts +24 -24
  199. package/src/strategies/meeting-gate.test.ts +59 -59
  200. package/src/strategies/meeting-gate.ts +28 -28
  201. package/src/strategies/move-room.ts +18 -18
  202. package/src/strategies/new-events-backfill.ts +98 -98
  203. package/src/strategies/off-route-points.ts +105 -105
  204. package/src/strategies/paradise-fish.knowledge.md +19 -19
  205. package/src/strategies/paradise-fish.ts +24 -24
  206. package/src/strategies/pathfind/distance-field.ts +150 -150
  207. package/src/strategies/pathfind/escape-planner.test.ts +197 -197
  208. package/src/strategies/pathfind/escape-planner.ts +355 -355
  209. package/src/strategies/pathfind/walkable-grid.ts +117 -117
  210. package/src/strategies/patrol.ts +14 -14
  211. package/src/strategies/player-targets.ts +13 -13
  212. package/src/strategies/report-patrol.ts +14 -14
  213. package/src/strategies/shrimp-memory.knowledge.md +19 -19
  214. package/src/strategies/shrimp-memory.ts +24 -24
  215. package/src/strategies/social-task.test.ts +28 -28
  216. package/src/strategies/social-task.ts +52 -52
  217. package/src/strategies/spawn.ts +82 -82
  218. package/src/strategies/speech-module.ts +123 -123
  219. package/src/strategies/strategy-loop.test.ts +15 -15
  220. package/src/strategies/strategy-loop.ts +748 -748
  221. package/src/strategies/task-kill-report.ts +20 -20
  222. package/src/strategies/task-only.ts +14 -14
  223. package/src/strategies/task-report.ts +21 -21
  224. package/src/strategies/types.ts +155 -155
  225. package/src/strategies/warrior-memory.knowledge.md +21 -21
  226. package/src/strategies/warrior-memory.ts +19 -19
@@ -1,1313 +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
- 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
- });
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
+ });