@myclaw163/clawclaw-cli 0.7.6 → 0.7.8

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 (51) hide show
  1. package/docs/desktop-event-push.md +37 -3
  2. package/docs/runtime/README.md +1 -0
  3. package/docs/runtime/official-perception-modules.md +346 -0
  4. package/package.json +1 -1
  5. package/src/commands/game/index.ts +1 -1
  6. package/src/lib/service-status.test.ts +56 -0
  7. package/src/lib/service-status.ts +111 -0
  8. package/src/pipeline/event-format.test.ts +26 -0
  9. package/src/pipeline/event-format.ts +22 -1
  10. package/src/pipeline/event-hints.test.ts +18 -3
  11. package/src/pipeline/event-hints.ts +11 -0
  12. package/src/pipeline/game-sync-event-normalization.test.ts +54 -1
  13. package/src/pipeline/game-sync-event-normalization.ts +39 -6
  14. package/src/pipeline/player-projection.test.ts +19 -2
  15. package/src/pipeline/player-projection.ts +17 -2
  16. package/src/runtime/clawclaw/agent-event-policy.test.ts +4 -0
  17. package/src/runtime/clawclaw/agent-event-policy.ts +1 -0
  18. package/src/runtime/clawclaw/owner.ts +6 -0
  19. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-push.integration.test.ts +24 -0
  20. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.test.ts +29 -0
  21. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.ts +39 -0
  22. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.test.ts +71 -0
  23. package/src/runtime/clawclaw/plugins/perception/contracts.ts +4 -0
  24. package/src/runtime/clawclaw/plugins/perception/modules/co-movement-module.ts +6 -0
  25. package/src/runtime/clawclaw/plugins/perception/modules/follow-module.ts +6 -0
  26. package/src/runtime/clawclaw/plugins/perception/modules/motion-module.ts +6 -0
  27. package/src/runtime/clawclaw/plugins/perception/modules/route-module.ts +6 -0
  28. package/src/runtime/clawclaw/plugins/perception/modules/spatial-module.ts +6 -0
  29. package/src/runtime/clawclaw/plugins/perception/modules/stop-module.ts +6 -0
  30. package/src/runtime/clawclaw/plugins/perception/modules/visibility-module.ts +6 -0
  31. package/src/runtime/clawclaw/plugins/perception/perception-plugin.test.ts +11 -0
  32. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +8 -0
  33. package/src/runtime/clawclaw/plugins/perception/perception-source.test.ts +12 -0
  34. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +37 -1
  35. package/src/runtime/clawclaw/plugins/source/room-transport.ts +2 -1
  36. package/src/runtime/clawclaw/plugins/source/source-plugin.test.ts +214 -1
  37. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +109 -21
  38. package/src/runtime/clawclaw/plugins/source/types.ts +1 -0
  39. package/src/runtime/clawclaw/plugins/strategy/examples/task-only-strategy.ts +6 -0
  40. package/src/runtime/clawclaw/plugins/strategy/strategy-executor-types.ts +4 -0
  41. package/src/runtime/clawclaw/plugins/strategy/strategy-module-loader.ts +4 -0
  42. package/src/runtime/clawclaw/plugins/strategy/strategy-plugin.test.ts +36 -0
  43. package/src/runtime/clawclaw/plugins/strategy/strategy-plugin.ts +13 -0
  44. package/src/runtime/clawclaw/plugins/strategy/strategy-source.test.ts +22 -0
  45. package/src/runtime/clawclaw/plugins/strategy/strategy-source.ts +46 -16
  46. package/src/runtime/clawclaw-event-catalog.test.ts +2 -0
  47. package/src/runtime/clawclaw-event-catalog.ts +1 -0
  48. package/src/sdk/perception-plugin/index.ts +14 -0
  49. package/src/sdk/resource-metadata.test.ts +40 -0
  50. package/src/sdk/resource-metadata.ts +63 -0
  51. package/src/sdk/strategy-plugin/index.ts +14 -0
@@ -526,6 +526,77 @@ describe('ClawClaw Mailbox Event query', () => {
526
526
  expect(repository.delivery(completed.eventId, 'local-agent')?.detailState).not.toBe('not_applicable');
527
527
  });
528
528
 
529
+ it('presents player and system killers through both Monitor and ccl events', async () => {
530
+ const { repository, ingress, service, setReady } = fixture();
531
+ const playerKilled = await publish(ingress, {
532
+ eventId: 'player-killed',
533
+ type: 'killed',
534
+ segmentId: 'room-1',
535
+ epochSeq: 1,
536
+ payload: {
537
+ tick: 41,
538
+ room: '制氧舱',
539
+ actor_name: 'victim',
540
+ actor_seat: 4,
541
+ killer_kind: 'player',
542
+ killer_name: '某蟹',
543
+ killer_seat: 1,
544
+ },
545
+ });
546
+ const systemKilled = await publish(ingress, {
547
+ eventId: 'system-killed',
548
+ type: 'killed',
549
+ segmentId: 'room-1',
550
+ epochSeq: 2,
551
+ payload: {
552
+ tick: 42,
553
+ room: '制氧舱',
554
+ actor_name: 'victim',
555
+ actor_seat: 4,
556
+ killer_kind: 'system',
557
+ killer_name: 'Shrimp God',
558
+ },
559
+ });
560
+ setReady(readyView('room-1', 2, systemKilled.commitSeq, { phase: 'wandering', tick: 42 }));
561
+
562
+ expect(service.prepareMonitor(true)).toBe(2);
563
+ const broker = new MailboxRelayBroker(repository, 'short');
564
+ const claim = broker.handle({
565
+ type: 'mailbox_claim',
566
+ relay_id: 'relay-structured-killers',
567
+ mode: 'short',
568
+ });
569
+ const payloads = claim?.claim?.items.map((item: any) => item.payload) ?? [];
570
+ const monitor = service.composeMonitor(payloads);
571
+ expect(monitor).toMatchObject({ events: ['killed', 'killed'] });
572
+ expect(monitor.messages).toEqual(expect.arrayContaining([
573
+ expect.stringContaining('被1号某蟹击杀'),
574
+ expect.stringContaining('被Shrimp God击杀'),
575
+ ]));
576
+ expect(JSON.stringify(monitor)).not.toContain('?号Shrimp God');
577
+
578
+ const events = service.prepareEvents().output.events as Array<Record<string, unknown>>;
579
+ expect(events).toEqual(expect.arrayContaining([
580
+ expect.objectContaining({
581
+ type: 'killed',
582
+ tick: 41,
583
+ killer_kind: 'player',
584
+ killer_name: '某蟹',
585
+ killer_seat: 1,
586
+ hint: 'YOU ARE DEAD: seat 1 某蟹 removed you from play.',
587
+ }),
588
+ expect.objectContaining({
589
+ type: 'killed',
590
+ tick: 42,
591
+ killer_kind: 'system',
592
+ killer_name: 'Shrimp God',
593
+ hint: 'YOU ARE DEAD: Shrimp God removed you from play.',
594
+ }),
595
+ ]));
596
+ expect(repository.delivery(playerKilled.eventId, 'local-agent')?.detailState)
597
+ .not.toBe('not_applicable');
598
+ });
599
+
529
600
  it('adds the latest structured Strategy status only to ccl events State', async () => {
530
601
  const { ingress, service, setReady } = fixture();
531
602
  const event = await publish(ingress, {
@@ -2,8 +2,12 @@ export {
2
2
  ClawclawPerception,
3
3
  ClawclawParallelPerception,
4
4
  PERCEPTION_PLUGIN_API_VERSION,
5
+ hasValidClawclawResourceLocalizations,
6
+ resolveClawclawResourceMetadata,
5
7
  } from '../../../../sdk/perception-plugin/index.js';
6
8
  export type {
9
+ ClawclawResolvedResourceMetadata,
10
+ ClawclawResourceLocalizations,
7
11
  ClawclawPerceptionClass,
8
12
  ClawclawPerceptionManifest,
9
13
  PerceptionApi,
@@ -57,6 +57,12 @@ export class CoMovementModule extends ClawclawParallelPerception<CoMovementAnaly
57
57
  id: 'visual.co_movement',
58
58
  name: 'Co-movement',
59
59
  description: 'Reports visible player pairs moving close together in the same direction.',
60
+ localizations: {
61
+ 'zh-CN': {
62
+ name: '共同移动',
63
+ description: '感知同时可见的玩家对近距离同方向稳定移动。',
64
+ },
65
+ },
60
66
  subjectScope: 'visible_pairs',
61
67
  produces: [
62
68
  'visual.players_moving_together',
@@ -64,6 +64,12 @@ export class FollowModule extends ClawclawParallelPerception<FollowAnalysis> {
64
64
  id: 'visual.follow',
65
65
  name: 'Following',
66
66
  description: 'Reports a stable front/back following relation between visible players.',
67
+ localizations: {
68
+ 'zh-CN': {
69
+ name: '跟随关系',
70
+ description: '感知同时可见玩家之间稳定的前后跟随关系。',
71
+ },
72
+ },
67
73
  subjectScope: 'visible_pairs',
68
74
  produces: ['visual.following', 'visual.following_ended'],
69
75
  execution: 'parallel_analysis',
@@ -80,6 +80,12 @@ export class MotionModule extends ClawclawParallelPerception<MotionAnalysis> {
80
80
  id: 'visual.motion',
81
81
  name: 'Player movement',
82
82
  description: 'Reports movement slices and meaningful direction changes for self and visible players.',
83
+ localizations: {
84
+ 'zh-CN': {
85
+ name: '玩家移动',
86
+ description: '感知自己和可见玩家的连续移动片段及显著方向变化。',
87
+ },
88
+ },
83
89
  subjectScope: 'self_and_others',
84
90
  produces: ['visual.player_moved', 'visual.player_motion_changed'],
85
91
  execution: 'parallel_analysis',
@@ -60,6 +60,12 @@ export class RouteModule extends ClawclawParallelPerception<RouteAnalysis> {
60
60
  id: 'visual.route',
61
61
  name: 'Route shape',
62
62
  description: 'Reports turns, reversals, and repeated local direction changes.',
63
+ localizations: {
64
+ 'zh-CN': {
65
+ name: '路线形态',
66
+ description: '感知转弯、折返和连续多次局部方向变化。',
67
+ },
68
+ },
63
69
  subjectScope: 'self_and_others',
64
70
  produces: [
65
71
  'visual.player_turned',
@@ -28,6 +28,12 @@ export class SpatialModule extends ClawclawParallelPerception<SpatialAnalysis> {
28
28
  id: 'visual.spatial',
29
29
  name: 'Spatial changes',
30
30
  description: 'Reports verified room transitions and movement between coarse room regions.',
31
+ localizations: {
32
+ 'zh-CN': {
33
+ name: '空间变化',
34
+ description: '感知已验证的房间切换和房间内粗粒度方位变化。',
35
+ },
36
+ },
31
37
  subjectScope: 'self_and_others',
32
38
  produces: ['visual.player_area_changed', 'visual.player_position_changed'],
33
39
  execution: 'parallel_analysis',
@@ -46,6 +46,12 @@ export class StopModule extends ClawclawParallelPerception<StopAnalysis> {
46
46
  id: 'visual.stop',
47
47
  name: 'Player stops',
48
48
  description: 'Reports stable stops and confirmed movement resumption.',
49
+ localizations: {
50
+ 'zh-CN': {
51
+ name: '玩家停留',
52
+ description: '感知自己和可见玩家的稳定停留及确认恢复移动。',
53
+ },
54
+ },
49
55
  subjectScope: 'self_and_others',
50
56
  produces: [
51
57
  'visual.player_stopped',
@@ -25,6 +25,12 @@ export class VisibilityModule extends ClawclawParallelPerception<VisibilityAnaly
25
25
  id: 'visual.visibility',
26
26
  name: 'Visibility changes',
27
27
  description: 'Reports other players entering, leaving, or quickly reappearing in view.',
28
+ localizations: {
29
+ 'zh-CN': {
30
+ name: '视野变化',
31
+ description: '感知其他玩家进入、离开或短暂离开后重新出现在视野中。',
32
+ },
33
+ },
28
34
  subjectScope: 'others',
29
35
  produces: [
30
36
  'visual.player_entered',
@@ -344,6 +344,17 @@ describe('ClawClaw Perception plugin', () => {
344
344
  expect.objectContaining({ id: 'visual.motion', subjectScope: 'self_and_others' }),
345
345
  expect.objectContaining({ id: 'visual.follow', subjectScope: 'visible_pairs' }),
346
346
  ]));
347
+ expect(plugin.localizedModuleDescriptors('zh-CN')).toEqual(expect.arrayContaining([
348
+ {
349
+ id: 'visual.visibility',
350
+ name: '视野变化',
351
+ description: '感知其他玩家进入、离开或短暂离开后重新出现在视野中。',
352
+ },
353
+ expect.objectContaining({ id: 'visual.motion', name: '玩家移动' }),
354
+ ]));
355
+ expect(plugin.localizedModuleDescriptors('en-US')).toEqual(expect.arrayContaining([
356
+ expect.objectContaining({ id: 'visual.visibility', name: 'Visibility changes' }),
357
+ ]));
347
358
  });
348
359
 
349
360
  it('starts, analyzes, commits, and stops all seven official Worker modules together', async () => {
@@ -13,6 +13,9 @@ import { isClawclawRuntimeState } from '../../runtime-state.js';
13
13
  import {
14
14
  PERCEPTION_PLUGIN_API_VERSION,
15
15
  ClawclawPerception,
16
+ hasValidClawclawResourceLocalizations,
17
+ resolveClawclawResourceMetadata,
18
+ type ClawclawResolvedResourceMetadata,
16
19
  type ClawclawPerceptionClass,
17
20
  type ClawclawPerceptionManifest,
18
21
  type PerceptionApi,
@@ -205,6 +208,7 @@ export function validatePerceptionManifest(
205
208
  || !/^[a-z0-9][a-z0-9._-]*$/.test(manifest.id)
206
209
  || !nonEmpty(manifest.name)
207
210
  || !nonEmpty(manifest.description)
211
+ || !hasValidClawclawResourceLocalizations(manifest.localizations)
208
212
  || !['others', 'self_and_others', 'visible_pairs', 'corpses'].includes(manifest.subjectScope)
209
213
  || !Array.isArray(manifest.produces)
210
214
  || manifest.produces.length === 0
@@ -772,6 +776,10 @@ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<strin
772
776
  }));
773
777
  }
774
778
 
779
+ localizedModuleDescriptors(locale: string): ClawclawResolvedResourceMetadata[] {
780
+ return this.modules.map(({ manifest }) => resolveClawclawResourceMetadata(manifest, locale));
781
+ }
782
+
775
783
  moduleStateSnapshot(): Record<string, unknown> {
776
784
  return Object.fromEntries(this.modules.map(({ manifest, runner }) => [
777
785
  manifest.id,
@@ -37,6 +37,12 @@ describe('ClawClaw perception source discovery', () => {
37
37
  id: 'visual.custom_linger',
38
38
  name: 'Custom linger',
39
39
  description: 'Reports a long stay.',
40
+ localizations: {
41
+ 'zh-CN': {
42
+ name: '长时间停留',
43
+ description: '感知玩家长时间停留。',
44
+ },
45
+ },
40
46
  subjectScope: 'others',
41
47
  produces: ['visual.custom_linger'],
42
48
  } as const;
@@ -51,6 +57,12 @@ describe('ClawClaw perception source discovery', () => {
51
57
  id: 'visual.custom_linger',
52
58
  name: 'Custom linger',
53
59
  description: 'Reports a long stay.',
60
+ localizations: {
61
+ 'zh-CN': {
62
+ name: '长时间停留',
63
+ description: '感知玩家长时间停留。',
64
+ },
65
+ },
54
66
  subjectScope: 'others',
55
67
  produces: ['visual.custom_linger'],
56
68
  },
@@ -15,7 +15,10 @@ import {
15
15
  ensureUserDataLayout,
16
16
  getUserDataPerceptionsDir,
17
17
  } from '../../../../lib/user-data.js';
18
- import type { ClawclawPerceptionManifest } from './contracts.js';
18
+ import type {
19
+ ClawclawPerceptionManifest,
20
+ ClawclawResourceLocalizations,
21
+ } from './contracts.js';
19
22
 
20
23
  export const MAX_PERCEPTION_FILES = 512;
21
24
  const MAX_PERCEPTION_SOURCE_BYTES = 2 * 1024 * 1024;
@@ -137,6 +140,36 @@ function literalStringArray(source: string, property: string): string[] | null {
137
140
  return residue.length === 0 ? values : null;
138
141
  }
139
142
 
143
+ function literalLocalizations(
144
+ source: string,
145
+ ): ClawclawResourceLocalizations | null | undefined {
146
+ const property = /\blocalizations\s*:\s*\{/m.exec(source);
147
+ if (!property) return undefined;
148
+ const open = property.index + property[0].lastIndexOf('{');
149
+ const block = balancedBlock(source, open, '{', '}');
150
+ if (!block) return null;
151
+ const values: Record<string, { name: string; description: string }> = {};
152
+ const entry = /(["'\x60])((?:\\.|(?!\1)[\s\S])*)\1\s*:\s*\{/g;
153
+ let cursor = 1;
154
+ let match: RegExpExecArray | null;
155
+ while ((match = entry.exec(block)) !== null) {
156
+ if (block.slice(cursor, match.index).replace(/[\s,]/g, '')) return null;
157
+ if (match[1] === '`' && match[2].includes('${')) return null;
158
+ const locale = decodeString(match[2])?.trim();
159
+ const entryOpen = match.index + match[0].lastIndexOf('{');
160
+ const entryBlock = balancedBlock(block, entryOpen, '{', '}');
161
+ if (!locale || !entryBlock || values[locale]) return null;
162
+ const name = literalProperty(entryBlock, 'name')?.trim();
163
+ const description = literalProperty(entryBlock, 'description')?.trim();
164
+ if (!name || !description) return null;
165
+ values[locale] = { name, description };
166
+ cursor = entryOpen + entryBlock.length;
167
+ entry.lastIndex = cursor;
168
+ }
169
+ if (block.slice(cursor, -1).replace(/[\s,]/g, '')) return null;
170
+ return values;
171
+ }
172
+
140
173
  function parseSource(sourcePath: string, sourceRoot: string): ResolvedClawclawPerceptionSource | null {
141
174
  let source: string;
142
175
  try {
@@ -163,6 +196,7 @@ function parseSource(sourcePath: string, sourceRoot: string): ResolvedClawclawPe
163
196
  const produces = literalStringArray(manifestBlock, 'produces');
164
197
  const execution = literalProperty(manifestBlock, 'execution')?.trim();
165
198
  const boundaryBaseline = literalProperty(manifestBlock, 'boundaryBaseline')?.trim();
199
+ const localizations = literalLocalizations(manifestBlock);
166
200
  const parallelClass = classMatch[1] === 'ClawclawParallelPerception';
167
201
  if (
168
202
  !id
@@ -180,12 +214,14 @@ function parseSource(sourcePath: string, sourceRoot: string): ResolvedClawclawPe
180
214
  && (execution !== 'parallel_analysis' || boundaryBaseline !== 'current_only')
181
215
  )
182
216
  || parallelClass !== (execution === 'parallel_analysis')
217
+ || localizations === null
183
218
  ) return null;
184
219
 
185
220
  const manifest: ClawclawPerceptionManifest = {
186
221
  id,
187
222
  name,
188
223
  description,
224
+ ...(localizations === undefined ? {} : { localizations }),
189
225
  subjectScope: subjectScope as ClawclawPerceptionManifest['subjectScope'],
190
226
  produces,
191
227
  ...(execution ? { execution: 'parallel_analysis' as const } : {}),
@@ -16,6 +16,7 @@ export type ClawclawRoomTransportStopReason =
16
16
  | 'game_started'
17
17
  | 'self_left'
18
18
  | 'room_destroyed'
19
+ | 'maintenance'
19
20
  | 'reconcile'
20
21
  | 'replaced'
21
22
  | 'fatal'
@@ -31,7 +32,7 @@ export interface ClawclawRoomCloseInfo {
31
32
  reason: string;
32
33
  }
33
34
 
34
- export type ClawclawRoomCloseDecision = 'retry' | 'room_destroyed' | 'reconcile' | 'replaced' | 'fatal';
35
+ export type ClawclawRoomCloseDecision = 'retry' | 'room_destroyed' | 'maintenance' | 'reconcile' | 'replaced' | 'fatal';
35
36
 
36
37
  export interface ClawclawRoomTransportFrameMeta {
37
38
  connectionId: string;
@@ -1,6 +1,7 @@
1
1
  import { describe, expect, it, vi } from 'vitest';
2
2
  import { ApiError } from '../../../../lib/http-transport.js';
3
3
  import { presentCanonicalEvent } from '../../../../pipeline/canonical-event-presentation.js';
4
+ import { jsonTransportResponse } from '../../../../short-command/transport-response.js';
4
5
  import { createClawclawEventCatalog } from '../../../clawclaw-event-catalog.js';
5
6
  import { projectClawclawCurrentState } from '../../runtime-state.js';
6
7
  import { MemoryEventRepository } from '../../../framework/events/index.js';
@@ -46,7 +47,7 @@ class FakeClient implements ClawclawSourceClient {
46
47
  }));
47
48
  readonly leaveQueue = vi.fn(async () => ({ success: true }));
48
49
  readonly leaveGame = vi.fn(async (): Promise<any> => ({ success: true }));
49
- readonly createRoom = vi.fn(async (_options?: import('../../../../lib/room.js').CreateRoomOptions) => ({ room_code: 'R1' }));
50
+ readonly createRoom = vi.fn(async (_options?: import('../../../../lib/room.js').CreateRoomOptions): Promise<any> => ({ room_code: 'R1' }));
50
51
  readonly joinRoom = vi.fn(async (
51
52
  roomCode: string,
52
53
  _metadata?: import('../../../../lib/room.js').RoomEntryMetadata,
@@ -303,7 +304,154 @@ function gameStateFrame(
303
304
  };
304
305
  }
305
306
 
307
+ const maintenanceWindow = {
308
+ starts_at: '2026-08-05T01:00:00+00:00',
309
+ ends_at: '2026-08-05T03:00:00+00:00',
310
+ };
311
+
312
+ function maintenanceApiError(method = 'GET', path = '/api/v1/queue/status'): ApiError {
313
+ const payload = {
314
+ success: false,
315
+ error: { code: 'SERVICE_MAINTENANCE', message: 'Service is under maintenance' },
316
+ server: { service_status: 'maintenance_active', maintenance: maintenanceWindow },
317
+ };
318
+ const response = jsonTransportResponse(payload, {
319
+ method,
320
+ path,
321
+ status: 503,
322
+ headers: { 'content-type': 'application/json', 'retry-after': '7200' },
323
+ });
324
+ return new ApiError(503, response.body.rawText, method, path, response);
325
+ }
326
+
306
327
  describe('ClawclawSourcePlugin lifecycle', () => {
328
+ it('delivers upcoming maintenance through the canonical Mailbox path without blocking room creation', async () => {
329
+ const { runtime, events, client, source, rooms } = await fixture(
330
+ [{ status: 'not_in_queue' }],
331
+ { kind: 'create_room' },
332
+ {
333
+ configureClient: (fake) => {
334
+ fake.createRoom.mockResolvedValue({
335
+ success: true,
336
+ data: { room_code: 'R1' },
337
+ server: {
338
+ service_status: 'maintenance_upcoming',
339
+ maintenance: maintenanceWindow,
340
+ },
341
+ });
342
+ },
343
+ },
344
+ );
345
+ await waitUntil(() => rooms.length === 1, 'Room transport was not started.');
346
+ await rooms[0].emit('service_status', {
347
+ service_status: 'maintenance_upcoming',
348
+ maintenance: maintenanceWindow,
349
+ }, {
350
+ room_code: 'R1',
351
+ status: 'waiting',
352
+ members: [],
353
+ }, 1);
354
+ await runtime.flush();
355
+
356
+ expect(client.createRoom).toHaveBeenCalledOnce();
357
+ const committed = runtime.repository.listCommittedEvents({
358
+ sessionId: runtime.scope().sessionId,
359
+ types: ['service_status'],
360
+ });
361
+ expect(committed).toHaveLength(1);
362
+ expect(committed[0]).toMatchObject({
363
+ type: 'service_status',
364
+ producer: 'backend_push',
365
+ deliveryClass: 'monitor_and_events',
366
+ payload: {
367
+ service_status: 'maintenance_upcoming',
368
+ maintenance: maintenanceWindow,
369
+ },
370
+ });
371
+ const mailbox = new ClawclawMailboxService({
372
+ repository: events,
373
+ readyView: () => runtime.readReadyView(),
374
+ });
375
+ const delivered = mailbox.prepareEvents({ eventType: 'service_status' }).output.event as Record<string, any>;
376
+ expect(delivered).toMatchObject({
377
+ type: 'service_status',
378
+ service_status: 'maintenance_upcoming',
379
+ maintenance: maintenanceWindow,
380
+ });
381
+ expect(delivered.hint).toContain('current request succeeded');
382
+
383
+ await source.stop();
384
+ await runtime.close();
385
+ });
386
+
387
+ it('treats the documented Lobby WebSocket maintenance close as terminal', async () => {
388
+ const { runtime, source, rooms } = await fixture([{
389
+ status: 'in_room', mode: 'room', room_code: 'R1',
390
+ }]);
391
+ await waitUntil(() => rooms.length === 1, 'Room transport was not started.');
392
+ await rooms[0].emit('service_status', {
393
+ service_status: 'maintenance_active',
394
+ maintenance: maintenanceWindow,
395
+ }, null, 1);
396
+ await rooms[0].close({ code: 4006, reason: 'SERVICE_MAINTENANCE' });
397
+
398
+ await expect(source.waitForCompletion()).resolves.toEqual({ reason: 'maintenance' });
399
+ await runtime.flush();
400
+ expect(runtime.repository.listCommittedEvents({
401
+ sessionId: runtime.scope().sessionId,
402
+ types: ['service_status'],
403
+ })).toHaveLength(1);
404
+ await runtime.close();
405
+ });
406
+
407
+ it('stops immediately on active maintenance without poll_error retries', async () => {
408
+ const maintenanceError = maintenanceApiError();
409
+ const { runtime, client, source } = await fixture([maintenanceError], { kind: 'match' });
410
+
411
+ await expect(source.waitForCompletion()).resolves.toMatchObject({
412
+ reason: 'maintenance',
413
+ error: maintenanceError,
414
+ });
415
+ await runtime.flush();
416
+
417
+ expect(client.queueStatusReads).toBe(1);
418
+ expect(runtime.repository.listCommittedEvents({
419
+ sessionId: runtime.scope().sessionId,
420
+ types: ['service_status'],
421
+ })).toMatchObject([{
422
+ type: 'service_status',
423
+ producer: 'backend_push',
424
+ payload: {
425
+ service_status: 'maintenance_active',
426
+ maintenance: maintenanceWindow,
427
+ retry_after_seconds: 7200,
428
+ },
429
+ }]);
430
+ expect(runtime.repository.listCommittedEvents({
431
+ sessionId: runtime.scope().sessionId,
432
+ types: ['poll_error', 'error'],
433
+ })).toHaveLength(0);
434
+ await runtime.close();
435
+ });
436
+
437
+ it('does not reconcile a queue join rejected by active maintenance', async () => {
438
+ const maintenanceError = maintenanceApiError('POST', '/api/v1/queue/join');
439
+ const { runtime, client, source } = await fixture(
440
+ [{ status: 'not_in_queue' }],
441
+ { kind: 'match' },
442
+ { configureClient: (fake) => fake.joinQueue.mockRejectedValue(maintenanceError) },
443
+ );
444
+
445
+ await expect(source.waitForCompletion()).resolves.toMatchObject({ reason: 'maintenance' });
446
+ await runtime.flush();
447
+ expect(client.queueStatusReads).toBe(1);
448
+ expect(runtime.repository.listCommittedEvents({
449
+ sessionId: runtime.scope().sessionId,
450
+ types: ['service_status'],
451
+ })).toHaveLength(1);
452
+ await runtime.close();
453
+ });
454
+
307
455
  it('consumes the Owner queue observation without issuing a second startup poll', async () => {
308
456
  const initialQueueState = {
309
457
  status: 'allocated', mode: 'match', game_id: 'G-preflight', ws_url: 'wss://game.test/ws',
@@ -1040,6 +1188,71 @@ describe('ClawclawSourcePlugin lifecycle', () => {
1040
1188
  await expect(source.waitForCompletion()).resolves.toEqual({ reason: 'stopped' });
1041
1189
  });
1042
1190
 
1191
+ it('normalizes structured player and system killers from GameSync frames', async () => {
1192
+ const scenarios = [{
1193
+ eventId: 'player-killed',
1194
+ killer: { kind: 'player', player: { seat: 2, name: 'Killer' } },
1195
+ expected: {
1196
+ killer_kind: 'player', killer_name: 'Killer', killer_seat: 2,
1197
+ },
1198
+ }, {
1199
+ eventId: 'system-killed',
1200
+ killer: { kind: 'system', name: 'Shrimp God' },
1201
+ expected: { killer_kind: 'system', killer_name: 'Shrimp God' },
1202
+ }];
1203
+
1204
+ for (const scenario of scenarios) {
1205
+ const { runtime, events, source, games } = await fixture([{
1206
+ status: 'allocated',
1207
+ mode: 'match',
1208
+ game_id: `G-${scenario.eventId}`,
1209
+ ws_url: 'wss://game.test/ws',
1210
+ }]);
1211
+ await waitUntil(() => games.length === 1, 'Game transport was not started.');
1212
+
1213
+ await games[0].emit(gameStateFrame('game-1', 1, {
1214
+ tick: 41,
1215
+ phase: 'wandering',
1216
+ you: { player: { seat: 1, name: 'me' }, is_alive: false },
1217
+ players: [
1218
+ { seat: 1, name: 'me', known_status: { is_alive: false, death_cause: 'killed' } },
1219
+ { seat: 2, name: 'Killer', known_status: { is_alive: true } },
1220
+ ],
1221
+ }, [{
1222
+ event_id: scenario.eventId,
1223
+ type: 'killed',
1224
+ actor: { seat: 1, name: 'me' },
1225
+ killer: scenario.killer,
1226
+ room: '制氧舱',
1227
+ }]));
1228
+ await runtime.flush();
1229
+
1230
+ const killed = runtime.repository.listCommittedEvents({
1231
+ sessionId: runtime.scope().sessionId,
1232
+ segmentId: runtime.scope().segmentId,
1233
+ types: ['killed'],
1234
+ });
1235
+ expect(killed).toHaveLength(1);
1236
+ expect(killed[0].payload).toMatchObject({
1237
+ room: '制氧舱',
1238
+ actor_name: 'me',
1239
+ actor_seat: 1,
1240
+ ...scenario.expected,
1241
+ });
1242
+ expect(killed[0].payload).not.toHaveProperty('killer');
1243
+
1244
+ const mailbox = new ClawclawMailboxService({
1245
+ repository: events,
1246
+ readyView: () => runtime.readReadyView(),
1247
+ });
1248
+ expect(mailbox.prepareEvents({ eventType: 'killed' }).output.event)
1249
+ .toMatchObject(scenario.expected);
1250
+
1251
+ await source.stop();
1252
+ await runtime.close();
1253
+ }
1254
+ });
1255
+
1043
1256
  it('keeps exile pending until a later authoritative State confirms death', async () => {
1044
1257
  const { runtime, source, games } = await fixture([{
1045
1258
  status: 'allocated',