@myclaw163/clawclaw-cli 0.7.4 → 0.7.6

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 (35) hide show
  1. package/docs/desktop-event-push.md +120 -0
  2. package/docs/runtime/events-and-state.md +1 -1
  3. package/package.json +3 -1
  4. package/skills/clawclaw/SKILL.md +9 -9
  5. package/skills/clawclaw/references/GAME-MECHANICS.md +2 -2
  6. package/src/assets/clawclaw-spatial-model.txt +142 -0
  7. package/src/commands/game/index.test.ts +167 -1
  8. package/src/commands/game/index.ts +124 -35
  9. package/src/commands/game-map.test.ts +8 -4
  10. package/src/lib/game-client.test.ts +15 -0
  11. package/src/lib/game-client.ts +4 -0
  12. package/src/lib/game-context.ts +6 -6
  13. package/src/lib/participation-status.ts +113 -0
  14. package/src/pipeline/canonical-event-presentation.test.ts +5 -4
  15. package/src/pipeline/event-format.test.ts +17 -0
  16. package/src/pipeline/event-format.ts +15 -1
  17. package/src/pipeline/game-sync-event-normalization.test.ts +58 -1
  18. package/src/pipeline/game-sync-event-normalization.ts +51 -0
  19. package/src/runtime/clawclaw/owner.ts +56 -3
  20. package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.test.ts +189 -0
  21. package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.ts +532 -0
  22. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-push.integration.test.ts +339 -0
  23. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.test.ts +207 -0
  24. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.ts +372 -0
  25. package/src/runtime/clawclaw/plugins/mailbox/index.ts +3 -0
  26. package/src/runtime/clawclaw/plugins/mailbox/mailbox-agent-event-batch.test.ts +166 -0
  27. package/src/runtime/clawclaw/plugins/mailbox/mailbox-event-batch-delivery.test.ts +194 -0
  28. package/src/runtime/clawclaw/plugins/mailbox/mailbox-event-batch-delivery.ts +262 -0
  29. package/src/runtime/clawclaw/plugins/mailbox/mailbox-plugin.ts +28 -0
  30. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.test.ts +49 -0
  31. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +77 -259
  32. package/src/runtime/clawclaw/plugins/runtime-plugins.test.ts +5 -0
  33. package/src/runtime/clawclaw/plugins/source/source-plugin.test.ts +52 -0
  34. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +4 -3
  35. package/src/assets/clawclaw-ascii-map.txt +0 -40
@@ -15,19 +15,33 @@ import {
15
15
  unwrapData,
16
16
  type TrainingRoomType,
17
17
  } from '../../lib/room.js';
18
+ import { queryGameParticipationStatus } from '../../lib/participation-status.js';
18
19
  import { setMeta } from '../../lib/command-meta.js';
19
20
  import { ShortCommandRunner } from '../../short-command/runner.js';
20
21
  import { createProcessCanonicalEventEmitter } from '../../runtime/canonical-event-emitter.js';
21
22
  import { runClawclawOwner } from '../../runtime/clawclaw/owner.js';
22
23
  import { ClawclawHostNotificationRoute } from '../../runtime/clawclaw/notifications.js';
24
+ import {
25
+ normalizeDesktopEventSocketPath,
26
+ validateDesktopEventToken,
27
+ type DesktopEventSocketConfig,
28
+ } from '../../runtime/clawclaw/plugins/mailbox/index.js';
23
29
  import { sendProfileOwnerControlRequest } from '../../runtime/owner-control.js';
24
30
 
25
31
  type GameCommandClient = Pick<
26
32
  GameClient,
27
- 'getQueueStatus' | 'leaveGame' | 'leaveRoom' | 'leaveQueue' | 'startRoom'
33
+ 'getQueueStatus' | 'getRoomStatus' | 'leaveGame' | 'leaveRoom' | 'leaveQueue' | 'startRoom'
28
34
  >;
29
35
  type GameOwnerIntent = Parameters<typeof runClawclawOwner>[0]['intent'];
30
- type GameOwnerRunOptions = { forceExistingRuntime?: boolean };
36
+ type GameOwnerRunOptions = {
37
+ forceExistingRuntime?: boolean;
38
+ desktopEvents?: DesktopEventSocketConfig;
39
+ };
40
+
41
+ interface DesktopEventCliOptions {
42
+ desktopEventSocket?: string;
43
+ desktopEventToken?: string;
44
+ }
31
45
 
32
46
  interface GameCommandIo {
33
47
  writeStdout(text: string): void;
@@ -60,6 +74,33 @@ function positiveCharacterId(value: string): number {
60
74
  return parsed;
61
75
  }
62
76
 
77
+ function addDesktopEventOptions(command: Command): Command {
78
+ return command
79
+ .addOption(new Option('--desktop-event-socket <path>').hideHelp())
80
+ .addOption(new Option('--desktop-event-token <nonce>').hideHelp());
81
+ }
82
+
83
+ function desktopEventConfig(
84
+ options: DesktopEventCliOptions,
85
+ ): DesktopEventSocketConfig | undefined {
86
+ const hasSocket = typeof options.desktopEventSocket === 'string';
87
+ const hasToken = typeof options.desktopEventToken === 'string';
88
+ if (hasSocket !== hasToken) {
89
+ throw new InvalidArgumentError(
90
+ '--desktop-event-socket and --desktop-event-token must be provided together.',
91
+ );
92
+ }
93
+ if (!hasSocket || !hasToken) return undefined;
94
+ try {
95
+ return {
96
+ socketPath: normalizeDesktopEventSocketPath(options.desktopEventSocket!),
97
+ token: validateDesktopEventToken(options.desktopEventToken!),
98
+ };
99
+ } catch (error) {
100
+ throw new InvalidArgumentError(error instanceof Error ? error.message : String(error));
101
+ }
102
+ }
103
+
63
104
  async function runTrainingControl(
64
105
  type: 'training_mode' | 'training_role_lock' | 'training_role_clear',
65
106
  payload: Record<string, any>,
@@ -121,7 +162,9 @@ async function runOwner(
121
162
  profile,
122
163
  intent,
123
164
  forceExistingRuntime: options.forceExistingRuntime,
124
- notificationHost: notifications,
165
+ ...(options.desktopEvents
166
+ ? { desktopEvents: options.desktopEvents }
167
+ : { notificationHost: notifications }),
125
168
  });
126
169
  if (completion.reason === 'error') process.exitCode = 1;
127
170
  } catch (error) {
@@ -402,24 +445,38 @@ async function quitParticipation(dependencies: GameCommandDependencies = {}): Pr
402
445
  ), 1);
403
446
  }
404
447
 
448
+ async function showParticipationStatus(
449
+ dependencies: GameCommandDependencies = {},
450
+ ): Promise<void> {
451
+ (dependencies.activeProfile ?? activeProfile)();
452
+ const client = (dependencies.clientFactory ?? (() => GameClient.fromAuth()))();
453
+ const io = dependencies.io ?? processGameCommandIo;
454
+ const status = await queryGameParticipationStatus(client);
455
+ io.writeStdout(`${JSON.stringify(status, null, 2)}\n`);
456
+ io.setExitCode(status.status === 'unknown' ? 1 : 0);
457
+ }
458
+
405
459
  export function createGameCommand(dependencies: GameCommandDependencies = {}): Command {
406
460
  const game = new Command('game').description('Game participation and inspection');
407
461
  const ownerRunner = dependencies.ownerRunner ?? runOwner;
408
462
 
409
- const start = game
463
+ const start = addDesktopEventOptions(game
410
464
  .command('start')
411
465
  .alias('s')
412
466
  .description('Run the ClawClaw Source until the current participation ends.')
413
467
  .requiredOption('--agent-type <platform>')
414
468
  .option('--llm-model <model>')
415
469
  .option('--force', 'replace an existing local runtime process before starting')
416
- .addOption(new Option('--competition').hideHelp())
470
+ .addOption(new Option('--competition').hideHelp()))
417
471
  .action(async (opts: {
418
472
  agentType: string;
419
473
  llmModel?: string;
420
474
  competition?: boolean;
421
475
  force?: boolean;
476
+ desktopEventSocket?: string;
477
+ desktopEventToken?: string;
422
478
  }) => {
479
+ const desktopEvents = desktopEventConfig(opts);
423
480
  await ownerRunner({
424
481
  kind: 'match',
425
482
  mode: opts.competition ? 'competition' : 'match',
@@ -427,63 +484,90 @@ export function createGameCommand(dependencies: GameCommandDependencies = {}): C
427
484
  llmModel: opts.llmModel,
428
485
  }, {
429
486
  forceExistingRuntime: opts.force === true,
487
+ ...(desktopEvents ? { desktopEvents } : {}),
430
488
  });
431
489
  });
432
490
 
433
- const createRoom = game
491
+ const createRoom = addDesktopEventOptions(game
434
492
  .command('create-room')
435
493
  .description('Create a room and run its Source lifecycle.')
436
494
  .requiredOption('--agent-type <platform>')
437
495
  .option('--llm-model <model>')
438
- .option('--force', 'replace an existing local runtime process before starting')
439
- .action(async (opts: { agentType: string; llmModel?: string; force?: boolean }) => ownerRunner({
440
- kind: 'create_room',
441
- agentType: opts.agentType,
442
- llmModel: opts.llmModel,
443
- }, {
444
- forceExistingRuntime: opts.force === true,
445
- }));
446
-
447
- const joinRoom = game
496
+ .option('--force', 'replace an existing local runtime process before starting'))
497
+ .action(async (opts: {
498
+ agentType: string;
499
+ llmModel?: string;
500
+ force?: boolean;
501
+ desktopEventSocket?: string;
502
+ desktopEventToken?: string;
503
+ }) => {
504
+ const desktopEvents = desktopEventConfig(opts);
505
+ return ownerRunner({
506
+ kind: 'create_room',
507
+ agentType: opts.agentType,
508
+ llmModel: opts.llmModel,
509
+ }, {
510
+ forceExistingRuntime: opts.force === true,
511
+ ...(desktopEvents ? { desktopEvents } : {}),
512
+ });
513
+ });
514
+
515
+ const joinRoom = addDesktopEventOptions(game
448
516
  .command('join-room')
449
517
  .description('Join a room and run its Source lifecycle.')
450
518
  .argument('<room_code>')
451
519
  .requiredOption('--agent-type <platform>')
452
520
  .option('--llm-model <model>')
453
- .option('--force', 'replace an existing local runtime process before starting')
454
- .action(async (roomCode: string, opts: { agentType: string; llmModel?: string; force?: boolean }) => ownerRunner({
455
- kind: 'join_room',
456
- roomCode,
457
- agentType: opts.agentType,
458
- llmModel: opts.llmModel,
459
- }, {
460
- forceExistingRuntime: opts.force === true,
461
- }));
521
+ .option('--force', 'replace an existing local runtime process before starting'))
522
+ .action(async (roomCode: string, opts: {
523
+ agentType: string;
524
+ llmModel?: string;
525
+ force?: boolean;
526
+ desktopEventSocket?: string;
527
+ desktopEventToken?: string;
528
+ }) => {
529
+ const desktopEvents = desktopEventConfig(opts);
530
+ return ownerRunner({
531
+ kind: 'join_room',
532
+ roomCode,
533
+ agentType: opts.agentType,
534
+ llmModel: opts.llmModel,
535
+ }, {
536
+ forceExistingRuntime: opts.force === true,
537
+ ...(desktopEvents ? { desktopEvents } : {}),
538
+ });
539
+ });
462
540
 
463
541
  const training = game
464
542
  .command('training')
465
543
  .description('Create and configure a bot-filled training room.');
466
544
 
467
- const trainingCreate = training
545
+ const trainingCreate = addDesktopEventOptions(training
468
546
  .command('create')
469
547
  .description('Create a training room and run its Source lifecycle.')
470
548
  .requiredOption('--mode <simulation|dummy>', 'training ruleset', trainingRoomType)
471
549
  .requiredOption('--agent-type <platform>')
472
550
  .option('--llm-model <model>')
473
- .option('--force', 'replace an existing local runtime process before starting')
551
+ .option('--force', 'replace an existing local runtime process before starting'))
474
552
  .action(async (opts: {
475
553
  mode: TrainingRoomType;
476
554
  agentType: string;
477
555
  llmModel?: string;
478
556
  force?: boolean;
479
- }) => ownerRunner({
480
- kind: 'create_room',
481
- roomType: opts.mode,
482
- agentType: opts.agentType,
483
- llmModel: opts.llmModel,
484
- }, {
485
- forceExistingRuntime: opts.force === true,
486
- }));
557
+ desktopEventSocket?: string;
558
+ desktopEventToken?: string;
559
+ }) => {
560
+ const desktopEvents = desktopEventConfig(opts);
561
+ return ownerRunner({
562
+ kind: 'create_room',
563
+ roomType: opts.mode,
564
+ agentType: opts.agentType,
565
+ llmModel: opts.llmModel,
566
+ }, {
567
+ forceExistingRuntime: opts.force === true,
568
+ ...(desktopEvents ? { desktopEvents } : {}),
569
+ });
570
+ });
487
571
 
488
572
  training
489
573
  .command('mode')
@@ -515,6 +599,11 @@ export function createGameCommand(dependencies: GameCommandDependencies = {}): C
515
599
  .description('Start a round in the current training room.')
516
600
  .action(() => startCurrentRoom(dependencies, 'ccl game training start'));
517
601
 
602
+ game
603
+ .command('status')
604
+ .description('Show the current backend participation status.')
605
+ .action(() => showParticipationStatus(dependencies));
606
+
518
607
  game
519
608
  .command('quit')
520
609
  .description('Leave the active queue, room, or game.')
@@ -24,13 +24,16 @@ describe('summarizeGameMap', () => {
24
24
  { name: '破坏', room: '控制室', x: 3, y: 4 },
25
25
  ]);
26
26
  expect(summary).not.toHaveProperty('ascii_map');
27
+ expect(summary).not.toHaveProperty('spatial_model');
27
28
  });
28
29
 
29
- it('includes packaged ASCII map only with --ascii', () => {
30
+ it('includes the packaged spatial model with --ascii', () => {
30
31
  const summary = summarizeGameMap(mapData, { ascii: true });
31
- expect(typeof summary.ascii_map).toBe('string');
32
- expect(summary.ascii_map).toContain('酒吧');
33
- expect(summary.ascii_map).toContain('5号走廊');
32
+ expect(typeof summary.spatial_model).toBe('string');
33
+ expect(summary.spatial_model).toContain('# ClawClaw 地图空间模型');
34
+ expect(summary.spatial_model).toContain('房间图例(小写=房间)');
35
+ expect(summary.spatial_model).not.toContain('从 clawclaw.tmj 推导');
36
+ expect(summary).not.toHaveProperty('ascii_map');
34
37
  expect(summary).not.toHaveProperty('corridors');
35
38
  });
36
39
  });
@@ -61,5 +64,6 @@ describe('packaged frontend map', () => {
61
64
  expect(summary.source.authority).toBe('frontend');
62
65
  expect(summary.rooms).toHaveLength(21);
63
66
  expect(summary).not.toHaveProperty('ascii_map');
67
+ expect(summary).not.toHaveProperty('spatial_model');
64
68
  });
65
69
  });
@@ -82,6 +82,21 @@ describe('GameClient.joinQueue X-Monitor-Status / X-LLM-Model', () => {
82
82
  });
83
83
 
84
84
  describe('GameClient room entry metadata', () => {
85
+ it('gets the current room status from the lobby', async () => {
86
+ let captured: any;
87
+ vi.stubGlobal('fetch', vi.fn(async (url: string, init: any) => {
88
+ captured = { url, method: init.method };
89
+ return new Response('{"success":true,"data":{"room_type":"casual"}}', { status: 200 });
90
+ }));
91
+
92
+ await makeClient().getRoomStatus();
93
+
94
+ expect(captured).toEqual({
95
+ url: 'https://lobby.example/api/v1/room/status',
96
+ method: 'GET',
97
+ });
98
+ });
99
+
85
100
  it('sends agent/model headers while preserving create-room request bodies', async () => {
86
101
  const calls: Array<{ url: string; headers: Record<string, string>; body?: string }> = [];
87
102
  vi.stubGlobal('fetch', vi.fn(async (url: string, init: any) => {
@@ -350,6 +350,10 @@ export class GameClient {
350
350
  return this.http.post('/api/v1/room/join', { room_code: roomCode }, agentMetadataHeaders(metadata));
351
351
  }
352
352
 
353
+ async getRoomStatus(): Promise<any> {
354
+ return this.http.get('/api/v1/room/status');
355
+ }
356
+
353
357
  async leaveRoom(): Promise<any> {
354
358
  return this.http.post('/api/v1/room/leave');
355
359
  }
@@ -47,9 +47,9 @@ export function taskLocations(mapData: any): { lobster: any[]; crab: any[] } {
47
47
  return output;
48
48
  }
49
49
 
50
- export function loadAsciiMapAsset(): string | null {
50
+ export function loadSpatialModelAsset(): string | null {
51
51
  try {
52
- return readFileSync(new URL('../assets/clawclaw-ascii-map.txt', import.meta.url), 'utf8').trimEnd();
52
+ return readFileSync(new URL('../assets/clawclaw-spatial-model.txt', import.meta.url), 'utf8').trimEnd();
53
53
  } catch {
54
54
  return null;
55
55
  }
@@ -74,12 +74,12 @@ export function summarizeLocalClawclawMap(opts?: { ascii?: boolean }): any {
74
74
  spawn_points: map.spawn_points,
75
75
  };
76
76
  return opts?.ascii
77
- ? { ...output, ascii_map: loadAsciiMapAsset() }
77
+ ? { ...output, spatial_model: loadSpatialModelAsset() }
78
78
  : output;
79
79
  }
80
80
 
81
81
  export function buildLocalGameStartedEnrichment(): Record<string, any> {
82
- return { map: { ascii_map: loadAsciiMapAsset() } };
82
+ return { map: loadSpatialModelAsset() };
83
83
  }
84
84
 
85
85
  export function summarizeGameMap(mapData: any, opts?: { ascii?: boolean }): any {
@@ -90,7 +90,7 @@ export function summarizeGameMap(mapData: any, opts?: { ascii?: boolean }): any
90
90
  })) ?? [],
91
91
  task_locations: taskLocations(mapData),
92
92
  };
93
- if (opts?.ascii) output.ascii_map = loadAsciiMapAsset();
93
+ if (opts?.ascii) output.spatial_model = loadSpatialModelAsset();
94
94
  return output;
95
95
  }
96
96
 
@@ -116,6 +116,6 @@ export function buildGameStartedEnrichment(mapData: any): Record<string, any> {
116
116
  return cleanObject({
117
117
  players: players.length > 0 ? players : undefined,
118
118
  all_seats: players.length > 0 ? seatMapFromPlayers(players) : undefined,
119
- map: summarizeGameMap(mapData, { ascii: true }),
119
+ map: loadSpatialModelAsset(),
120
120
  });
121
121
  }
@@ -0,0 +1,113 @@
1
+ import {
2
+ isTrainingRoomMode,
3
+ normalizeRoomSnapshot,
4
+ queueMode,
5
+ queueRoomCode,
6
+ queueStatus,
7
+ unwrapData,
8
+ } from './room.js';
9
+
10
+ export const GAME_STATUS_SCHEMA = 'ccl.game-status.v1' as const;
11
+
12
+ export type GameParticipationState =
13
+ | 'idle'
14
+ | 'matching'
15
+ | 'friend_room'
16
+ | 'training_room'
17
+ | 'in_game'
18
+ | 'room'
19
+ | 'unknown';
20
+
21
+ export interface GameParticipationStatus {
22
+ schema: typeof GAME_STATUS_SCHEMA;
23
+ status: GameParticipationState;
24
+ queue_status: string | null;
25
+ mode?: string;
26
+ room_code?: string;
27
+ room_type?: string;
28
+ room_status?: string;
29
+ game_id?: string;
30
+ }
31
+
32
+ export interface ParticipationStatusClient {
33
+ getQueueStatus(gameType?: string): Promise<any>;
34
+ getRoomStatus(): Promise<any>;
35
+ }
36
+
37
+ function stringField(value: unknown): string | undefined {
38
+ return typeof value === 'string' && value.length > 0 ? value : undefined;
39
+ }
40
+
41
+ function withOptionalFields(
42
+ value: GameParticipationStatus,
43
+ fields: Partial<Pick<
44
+ GameParticipationStatus,
45
+ 'mode' | 'room_code' | 'room_type' | 'room_status' | 'game_id'
46
+ >>,
47
+ ): GameParticipationStatus {
48
+ if (fields.mode !== undefined) value.mode = fields.mode;
49
+ if (fields.room_code !== undefined) value.room_code = fields.room_code;
50
+ if (fields.room_type !== undefined) value.room_type = fields.room_type;
51
+ if (fields.room_status !== undefined) value.room_status = fields.room_status;
52
+ if (fields.game_id !== undefined) value.game_id = fields.game_id;
53
+ return value;
54
+ }
55
+
56
+ /**
57
+ * Query the backend-owned participation state.
58
+ *
59
+ * Queue status is authoritative for idle/matching/game participation. A room
60
+ * lookup is needed only while in a room because queue status intentionally
61
+ * does not preserve the room type.
62
+ */
63
+ export async function queryGameParticipationStatus(
64
+ client: ParticipationStatusClient,
65
+ ): Promise<GameParticipationStatus> {
66
+ const queueResult = await client.getQueueStatus('clawclaw');
67
+ const queue = unwrapData(queueResult);
68
+ const currentQueueStatus = queueStatus(queueResult) ?? null;
69
+ const mode = queueMode(queueResult);
70
+ const roomCode = queueRoomCode(queueResult);
71
+ const base = (status: GameParticipationState): GameParticipationStatus =>
72
+ withOptionalFields({
73
+ schema: GAME_STATUS_SCHEMA,
74
+ status,
75
+ queue_status: currentQueueStatus,
76
+ }, {
77
+ mode,
78
+ room_code: roomCode,
79
+ });
80
+
81
+ if (currentQueueStatus === 'not_in_queue') return base('idle');
82
+
83
+ if (
84
+ currentQueueStatus === 'queued'
85
+ || currentQueueStatus === 'already_in_queue'
86
+ || currentQueueStatus === 'allocating'
87
+ ) {
88
+ return base('matching');
89
+ }
90
+
91
+ if (currentQueueStatus === 'allocated') {
92
+ return withOptionalFields(base('in_game'), {
93
+ game_id: stringField(queue?.game_id),
94
+ });
95
+ }
96
+
97
+ if (currentQueueStatus === 'in_room') {
98
+ const room = normalizeRoomSnapshot(await client.getRoomStatus());
99
+ const roomType = stringField(room.room_type);
100
+ const status: GameParticipationState = isTrainingRoomMode(roomType)
101
+ ? 'training_room'
102
+ : roomType === 'casual'
103
+ ? 'friend_room'
104
+ : 'room';
105
+ return withOptionalFields(base(status), {
106
+ room_code: stringField(room.room_code) ?? roomCode,
107
+ room_type: roomType,
108
+ room_status: stringField(room.status),
109
+ });
110
+ }
111
+
112
+ return base('unknown');
113
+ }
@@ -95,7 +95,7 @@ describe('canonical Agent Event presentation', () => {
95
95
  expect(presented).not.toHaveProperty('win_condition');
96
96
  });
97
97
 
98
- it('replaces backend game map data with only the packaged ASCII map', () => {
98
+ it('replaces backend game map data with the packaged spatial model directly', () => {
99
99
  const presented = presentCanonicalEvent(canonical('game_started', {
100
100
  tick: 0,
101
101
  player_count: 10,
@@ -104,9 +104,10 @@ describe('canonical Agent Event presentation', () => {
104
104
  }), null);
105
105
 
106
106
  expect(presented.players).toEqual([{ name: 'Alpha', seat: 1 }]);
107
- expect(Object.keys(presented.map)).toEqual(['ascii_map']);
108
- expect(presented.map.ascii_map).toContain('酒吧');
109
- expect(presented.map.ascii_map).toContain('5号走廊');
107
+ expect(typeof presented.map).toBe('string');
108
+ expect(presented.map).toContain('# ClawClaw 地图空间模型');
109
+ expect(presented.map).toContain('房间图例(小写=房间)');
110
+ expect(presented.map).not.toContain('从 clawclaw.tmj 推导');
110
111
  });
111
112
 
112
113
  it('omits hint for backend speech facts without dropping their original text', () => {
@@ -268,6 +268,23 @@ describe('event-format', () => {
268
268
  }
269
269
  });
270
270
 
271
+ it('mentions a newly assigned task only when task_completed carries one', () => {
272
+ expect(formatEventMessage({
273
+ type: 'task_completed',
274
+ task_name: '擦拭酒瓶',
275
+ newly_assigned_task: {
276
+ name: '消毒淋浴器',
277
+ room: '制氧舱',
278
+ x: 123,
279
+ y: 456,
280
+ },
281
+ })).toContain('任务完成:擦拭酒瓶;新分配任务:消毒淋浴器(制氧舱)');
282
+ expect(formatEventMessage({
283
+ type: 'task_completed',
284
+ task_name: '擦拭酒瓶',
285
+ })).toBe('tick=null task_completed 任务完成:擦拭酒瓶。');
286
+ });
287
+
271
288
  it('formats room presence and idle lifecycle Events', () => {
272
289
  expect(formatEventMessage({
273
290
  type: 'room.member_status_changed', agent_id: 'agent-2', status: 'online',
@@ -363,7 +363,21 @@ function shortBody(event: Record<string, any>, ctx: EventFormatContext): string
363
363
  return `你误杀了${playerLabel(event.target_name, firstNumber(event, ['target_seat', 'target_player_seat']), ctx)},武士虾自爆出局。`;
364
364
  case 'task_completed': {
365
365
  const fakeNote = event.is_fake_shrimp ? '(伪装)' : '';
366
- return `任务完成:${firstString(event, ['task_name'])}${fakeNote}。`;
366
+ const assigned = event.newly_assigned_task;
367
+ const assignedTask = assigned && typeof assigned === 'object' && !Array.isArray(assigned)
368
+ ? assigned as Record<string, any>
369
+ : null;
370
+ const assignedName = assignedTask ? firstString(assignedTask, ['name', 'task_name'], '') : '';
371
+ const assignedDetails = assignedTask
372
+ ? [
373
+ stringValue(assignedTask.room),
374
+ assignedTask.is_fake_shrimp === true ? '伪装' : undefined,
375
+ ].filter((value): value is string => value !== undefined)
376
+ : [];
377
+ const assignmentText = assignedName
378
+ ? `;新分配任务:${assignedName}${assignedDetails.length > 0 ? `(${assignedDetails.join(',')})` : ''}`
379
+ : '';
380
+ return `任务完成:${firstString(event, ['task_name'])}${fakeNote}${assignmentText}。`;
367
381
  }
368
382
  case 'task_sabotaged':
369
383
  return `破坏任务完成:${firstString(event, ['task_name'])}(${firstString(event, ['room'])})。`;
@@ -1,7 +1,10 @@
1
1
  import { describe, expect, it } from 'vitest';
2
2
  import type { CanonicalEvent } from '../runtime/framework/events/index.js';
3
3
  import { presentCanonicalEvent } from './canonical-event-presentation.js';
4
- import { normalizeGameSyncEvent } from './game-sync-event-normalization.js';
4
+ import {
5
+ normalizeGameSyncEvent,
6
+ normalizeGameSyncEvents,
7
+ } from './game-sync-event-normalization.js';
5
8
 
6
9
  function canonical(event: Record<string, any>): CanonicalEvent {
7
10
  const { type, ...payload } = event;
@@ -23,6 +26,60 @@ function canonical(event: Record<string, any>): CanonicalEvent {
23
26
  }
24
27
 
25
28
  describe('GameSync v2 Event normalization', () => {
29
+ it('enriches a task completion with its same-frame newly assigned task', () => {
30
+ const normalized = normalizeGameSyncEvents([{
31
+ event_id: 'completed-1',
32
+ tick: 42,
33
+ type: 'task_completed',
34
+ actor: { seat: 1, name: 'self' },
35
+ task_name: '擦拭酒瓶',
36
+ }, {
37
+ event_id: 'assigned-1',
38
+ tick: 42,
39
+ type: 'task_assigned',
40
+ actor: { seat: 1, name: 'self' },
41
+ task_name: '消毒淋浴器',
42
+ room: '制氧舱',
43
+ x: 123,
44
+ y: 456,
45
+ is_fake_shrimp: false,
46
+ }]);
47
+
48
+ expect(normalized[0]).toMatchObject({
49
+ type: 'task_completed',
50
+ task_name: '擦拭酒瓶',
51
+ newly_assigned_task: {
52
+ name: '消毒淋浴器',
53
+ room: '制氧舱',
54
+ x: 123,
55
+ y: 456,
56
+ is_fake_shrimp: false,
57
+ },
58
+ });
59
+ expect(normalized[1]).toMatchObject({
60
+ type: 'task_assigned',
61
+ task_name: '消毒淋浴器',
62
+ });
63
+ });
64
+
65
+ it('does not enrich a task completion without a same-tick assignment for the same player', () => {
66
+ const normalized = normalizeGameSyncEvents([{
67
+ event_id: 'completed-1',
68
+ tick: 42,
69
+ type: 'task_completed',
70
+ actor: { seat: 1, name: 'self' },
71
+ task_name: '擦拭酒瓶',
72
+ }, {
73
+ event_id: 'assigned-other',
74
+ tick: 43,
75
+ type: 'task_assigned',
76
+ actor: { seat: 1, name: 'self' },
77
+ task_name: '消毒淋浴器',
78
+ }]);
79
+
80
+ expect(normalized[0]).not.toHaveProperty('newly_assigned_task');
81
+ });
82
+
26
83
  it('projects actor and target PlayerRefs to the established canonical fields', () => {
27
84
  const wire = {
28
85
  event_id: '68a339d7-c5f6-4eef-8f40-b8779ca8bfcc',
@@ -213,3 +213,54 @@ export function normalizeGameSyncEvent(value: unknown): Record<string, any> {
213
213
 
214
214
  return normalized;
215
215
  }
216
+
217
+ function taskEventActorKey(event: Record<string, any>): string | null {
218
+ if (Number.isInteger(event.actor_seat)) return `seat:${String(event.actor_seat)}`;
219
+ return typeof event.actor_name === 'string' && event.actor_name.length > 0
220
+ ? `name:${event.actor_name}`
221
+ : null;
222
+ }
223
+
224
+ function newlyAssignedTask(event: Record<string, any>): Record<string, any> | null {
225
+ if (typeof event.task_name !== 'string' || event.task_name.length === 0) return null;
226
+ return {
227
+ name: event.task_name,
228
+ ...(typeof event.room === 'string' && event.room.length > 0 ? { room: event.room } : {}),
229
+ ...(typeof event.x === 'number' && Number.isFinite(event.x) ? { x: event.x } : {}),
230
+ ...(typeof event.y === 'number' && Number.isFinite(event.y) ? { y: event.y } : {}),
231
+ ...(typeof event.is_fake_shrimp === 'boolean'
232
+ ? { is_fake_shrimp: event.is_fake_shrimp }
233
+ : {}),
234
+ };
235
+ }
236
+
237
+ /**
238
+ * Normalize one GameSync frame and enrich a completed task with its private,
239
+ * same-frame replacement assignment. The raw task_assigned Event remains in
240
+ * the batch for internal consumers; Agent delivery is still owned by the
241
+ * Event Catalog.
242
+ */
243
+ export function normalizeGameSyncEvents(values: readonly unknown[]): Record<string, any>[] {
244
+ const normalized = values.map((value) => normalizeGameSyncEvent(value));
245
+ const claimedAssignments = new Set<number>();
246
+
247
+ return normalized.map((event, index) => {
248
+ if (event.type !== 'task_completed' || !Number.isInteger(event.tick)) return event;
249
+ const actorKey = taskEventActorKey(event);
250
+ if (!actorKey) return event;
251
+
252
+ const assignmentIndex = normalized.findIndex((candidate, candidateIndex) => (
253
+ candidateIndex > index
254
+ && !claimedAssignments.has(candidateIndex)
255
+ && candidate.type === 'task_assigned'
256
+ && candidate.tick === event.tick
257
+ && taskEventActorKey(candidate) === actorKey
258
+ ));
259
+ if (assignmentIndex < 0) return event;
260
+
261
+ const task = newlyAssignedTask(normalized[assignmentIndex]);
262
+ if (!task) return event;
263
+ claimedAssignments.add(assignmentIndex);
264
+ return { ...event, newly_assigned_task: task };
265
+ });
266
+ }