@myclaw163/clawclaw-cli 0.7.8 → 0.7.9

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 (28) hide show
  1. package/docs/desktop-event-push.md +14 -2
  2. package/docs//350/207/252/345/256/232/344/271/211/346/204/237/347/237/245.md +15 -1
  3. package/package.json +1 -1
  4. package/src/pipeline/game-sync-event-normalization.test.ts +33 -0
  5. package/src/pipeline/game-sync-event-normalization.ts +52 -9
  6. package/src/runtime/clawclaw/owner.ts +8 -0
  7. package/src/runtime/clawclaw/plugins/assembly.test.ts +13 -0
  8. package/src/runtime/clawclaw/plugins/assembly.ts +10 -0
  9. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-push.integration.test.ts +17 -5
  10. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.test.ts +37 -3
  11. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.ts +49 -14
  12. package/src/runtime/clawclaw/plugins/perception/contracts.ts +1 -0
  13. package/src/runtime/clawclaw/plugins/perception/modules/co-movement-module.ts +16 -0
  14. package/src/runtime/clawclaw/plugins/perception/modules/follow-module.ts +16 -0
  15. package/src/runtime/clawclaw/plugins/perception/modules/motion-module.ts +16 -0
  16. package/src/runtime/clawclaw/plugins/perception/modules/route-module.ts +23 -0
  17. package/src/runtime/clawclaw/plugins/perception/modules/spatial-module.ts +16 -0
  18. package/src/runtime/clawclaw/plugins/perception/modules/stop-module.ts +16 -0
  19. package/src/runtime/clawclaw/plugins/perception/modules/visibility-module.ts +23 -0
  20. package/src/runtime/clawclaw/plugins/perception/perception-plugin.test.ts +19 -0
  21. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +41 -0
  22. package/src/runtime/clawclaw/plugins/perception/perception-source.test.ts +49 -0
  23. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +105 -5
  24. package/src/runtime/clawclaw/plugins/source/source-plugin.test.ts +174 -0
  25. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +146 -66
  26. package/src/runtime/framework/plugins/runtime-plugin-scheduler.test.ts +36 -0
  27. package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +0 -5
  28. package/src/sdk/perception-plugin/index.ts +8 -0
@@ -36,6 +36,22 @@ export class SpatialModule extends ClawclawParallelPerception<SpatialAnalysis> {
36
36
  },
37
37
  subjectScope: 'self_and_others',
38
38
  produces: ['visual.player_area_changed', 'visual.player_position_changed'],
39
+ eventMetadata: {
40
+ 'visual.player_area_changed': {
41
+ name: 'Player area changed',
42
+ description: 'Reports when a player enters another room or named area.',
43
+ localizations: {
44
+ 'zh-CN': { name: '区域变化', description: '玩家进入另一房间或位置区域。' },
45
+ },
46
+ },
47
+ 'visual.player_position_changed': {
48
+ name: 'Position within room changed',
49
+ description: 'Reports a coarse position change within the same room.',
50
+ localizations: {
51
+ 'zh-CN': { name: '房间内位置变化', description: '玩家在同一房间内的粗粒度方位发生变化。' },
52
+ },
53
+ },
54
+ },
39
55
  execution: 'parallel_analysis',
40
56
  boundaryBaseline: 'current_only',
41
57
  } as const;
@@ -57,6 +57,22 @@ export class StopModule extends ClawclawParallelPerception<StopAnalysis> {
57
57
  'visual.player_stopped',
58
58
  'visual.player_resumed',
59
59
  ],
60
+ eventMetadata: {
61
+ 'visual.player_stopped': {
62
+ name: 'Player stopped',
63
+ description: 'Reports when a player remains at one position long enough to confirm a stop.',
64
+ localizations: {
65
+ 'zh-CN': { name: '玩家停留', description: '玩家在同一位置持续停留达到确认阈值。' },
66
+ },
67
+ },
68
+ 'visual.player_resumed': {
69
+ name: 'Player resumed movement',
70
+ description: 'Reports when a player ends a confirmed stop and resumes moving.',
71
+ localizations: {
72
+ 'zh-CN': { name: '恢复移动', description: '玩家结束已确认的停留并恢复移动。' },
73
+ },
74
+ },
75
+ },
60
76
  execution: 'parallel_analysis',
61
77
  boundaryBaseline: 'current_only',
62
78
  } as const;
@@ -37,6 +37,29 @@ export class VisibilityModule extends ClawclawParallelPerception<VisibilityAnaly
37
37
  'visual.player_left',
38
38
  'visual.player_reappeared',
39
39
  ],
40
+ eventMetadata: {
41
+ 'visual.player_entered': {
42
+ name: 'Player entered view',
43
+ description: 'Reports when a player enters the observer\'s current field of view.',
44
+ localizations: {
45
+ 'zh-CN': { name: '进入视野', description: '玩家从不可见状态进入你的当前视野。' },
46
+ },
47
+ },
48
+ 'visual.player_left': {
49
+ name: 'Player left view',
50
+ description: 'Reports when a player disappears from the observer\'s current field of view.',
51
+ localizations: {
52
+ 'zh-CN': { name: '离开视野', description: '玩家从你的当前视野中消失。' },
53
+ },
54
+ },
55
+ 'visual.player_reappeared': {
56
+ name: 'Player reappeared',
57
+ description: 'Reports when a player returns shortly after leaving the observer\'s view.',
58
+ localizations: {
59
+ 'zh-CN': { name: '重新进入视野', description: '玩家短暂离开后重新出现在你的视野中。' },
60
+ },
61
+ },
62
+ },
40
63
  execution: 'parallel_analysis',
41
64
  boundaryBaseline: 'current_only',
42
65
  } as const;
@@ -355,6 +355,25 @@ describe('ClawClaw Perception plugin', () => {
355
355
  expect(plugin.localizedModuleDescriptors('en-US')).toEqual(expect.arrayContaining([
356
356
  expect.objectContaining({ id: 'visual.visibility', name: 'Visibility changes' }),
357
357
  ]));
358
+ expect(plugin.localizedEventDescriptors('zh-CN')).toHaveLength(16);
359
+ expect(plugin.localizedEventDescriptors('zh-CN')).toEqual(expect.arrayContaining([
360
+ {
361
+ type: 'visual.player_entered',
362
+ perceptionId: 'visual.visibility',
363
+ name: '进入视野',
364
+ description: '玩家从不可见状态进入你的当前视野。',
365
+ },
366
+ expect.objectContaining({
367
+ type: 'visual.player_moved',
368
+ perceptionId: 'visual.motion',
369
+ name: '玩家移动',
370
+ }),
371
+ ]));
372
+ expect(new ClawclawPerceptionPlugin({ modules: ['visual.motion'] })
373
+ .localizedEventDescriptors('zh-CN').map((event) => event.type)).toEqual([
374
+ 'visual.player_moved',
375
+ 'visual.player_motion_changed',
376
+ ]);
358
377
  });
359
378
 
360
379
  it('starts, analyzes, commits, and stops all seven official Worker modules together', async () => {
@@ -72,6 +72,13 @@ export interface PerceptionModuleDescriptor extends ClawclawPerceptionManifest {
72
72
  readonly pluginId: typeof CLAWCLAW_PERCEPTION_PLUGIN_ID;
73
73
  }
74
74
 
75
+ export interface LocalizedPerceptionEventDescriptor {
76
+ readonly type: string;
77
+ readonly perceptionId: string;
78
+ readonly name: string;
79
+ readonly description: string;
80
+ }
81
+
75
82
  export interface PerceptionFrameInspection {
76
83
  visual: VisualState | null;
77
84
  proposals: readonly RuntimeEventProposal[];
@@ -167,6 +174,25 @@ function nonEmpty(value: unknown): value is string {
167
174
  return typeof value === 'string' && value.trim().length > 0;
168
175
  }
169
176
 
177
+ function hasValidPerceptionEventMetadata(manifest: ClawclawPerceptionManifest): boolean {
178
+ const metadata = manifest.eventMetadata;
179
+ if (metadata === undefined) return true;
180
+ if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) return false;
181
+ const entries = Object.entries(metadata);
182
+ return (
183
+ entries.length === manifest.produces.length
184
+ && entries.every(([type, value]) => (
185
+ manifest.produces.includes(type)
186
+ && !!value
187
+ && typeof value === 'object'
188
+ && !Array.isArray(value)
189
+ && nonEmpty(value.name)
190
+ && nonEmpty(value.description)
191
+ && hasValidClawclawResourceLocalizations(value.localizations)
192
+ ))
193
+ );
194
+ }
195
+
170
196
  function moduleClass(instance: ClawclawPerception): ClawclawPerceptionClass {
171
197
  return instance.constructor as ClawclawPerceptionClass;
172
198
  }
@@ -214,6 +240,7 @@ export function validatePerceptionManifest(
214
240
  || manifest.produces.length === 0
215
241
  || manifest.produces.some((type) => !/^visual\.[a-z0-9_.-]+$/.test(type))
216
242
  || new Set(manifest.produces).size !== manifest.produces.length
243
+ || !hasValidPerceptionEventMetadata(manifest)
217
244
  || (manifest.execution !== undefined && manifest.execution !== 'parallel_analysis')
218
245
  || (
219
246
  manifest.boundaryBaseline !== undefined
@@ -780,6 +807,20 @@ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<strin
780
807
  return this.modules.map(({ manifest }) => resolveClawclawResourceMetadata(manifest, locale));
781
808
  }
782
809
 
810
+ localizedEventDescriptors(locale: string): LocalizedPerceptionEventDescriptor[] {
811
+ return this.modules.flatMap(({ manifest }) => manifest.produces.flatMap((type) => {
812
+ const metadata = manifest.eventMetadata?.[type];
813
+ if (!metadata) return [];
814
+ const localized = resolveClawclawResourceMetadata({ id: type, ...metadata }, locale);
815
+ return [{
816
+ type,
817
+ perceptionId: manifest.id,
818
+ name: localized.name,
819
+ description: localized.description,
820
+ }];
821
+ }));
822
+ }
823
+
783
824
  moduleStateSnapshot(): Record<string, unknown> {
784
825
  return Object.fromEntries(this.modules.map(({ manifest, runner }) => [
785
826
  manifest.id,
@@ -45,6 +45,18 @@ describe('ClawClaw perception source discovery', () => {
45
45
  },
46
46
  subjectScope: 'others',
47
47
  produces: ['visual.custom_linger'],
48
+ eventMetadata: {
49
+ 'visual.custom_linger': {
50
+ name: 'Player lingered',
51
+ description: 'Reports one confirmed long stay.',
52
+ localizations: {
53
+ 'zh-CN': {
54
+ name: '玩家长时间停留',
55
+ description: '玩家在一个位置长时间停留。',
56
+ },
57
+ },
58
+ },
59
+ },
48
60
  } as const;
49
61
  update() {}
50
62
  }
@@ -65,6 +77,18 @@ describe('ClawClaw perception source discovery', () => {
65
77
  },
66
78
  subjectScope: 'others',
67
79
  produces: ['visual.custom_linger'],
80
+ eventMetadata: {
81
+ 'visual.custom_linger': {
82
+ name: 'Player lingered',
83
+ description: 'Reports one confirmed long stay.',
84
+ localizations: {
85
+ 'zh-CN': {
86
+ name: '玩家长时间停留',
87
+ description: '玩家在一个位置长时间停留。',
88
+ },
89
+ },
90
+ },
91
+ },
68
92
  },
69
93
  }),
70
94
  ]);
@@ -80,6 +104,31 @@ describe('ClawClaw perception source discovery', () => {
80
104
  expect(listClawclawPerceptionSources(fixture.root)).toEqual([]);
81
105
  });
82
106
 
107
+ it('rejects event metadata that does not cover every produced event type', () => {
108
+ const fixture = workspace();
109
+ writeFileSync(join(fixture.perceptions, 'incomplete-events.ts'), `
110
+ import { ClawclawPerception } from '@myclaw163/clawclaw-cli/perception-plugin';
111
+ export default class IncompleteEvents extends ClawclawPerception {
112
+ static readonly manifest = {
113
+ id: 'visual.incomplete_events',
114
+ name: 'Incomplete events',
115
+ description: 'Declares incomplete event metadata.',
116
+ subjectScope: 'others',
117
+ produces: ['visual.first', 'visual.second'],
118
+ eventMetadata: {
119
+ 'visual.first': {
120
+ name: 'First event',
121
+ description: 'Describes only the first event.',
122
+ },
123
+ },
124
+ } as const;
125
+ update() {}
126
+ }
127
+ `);
128
+
129
+ expect(listClawclawPerceptionSources(fixture.root)).toEqual([]);
130
+ });
131
+
83
132
  it('discovers an explicitly parallel analyzer without executing it', () => {
84
133
  const fixture = workspace();
85
134
  writeFileSync(join(fixture.perceptions, 'parallel.ts'), `
@@ -16,6 +16,7 @@ import {
16
16
  getUserDataPerceptionsDir,
17
17
  } from '../../../../lib/user-data.js';
18
18
  import type {
19
+ ClawclawPerceptionEventMetadata,
19
20
  ClawclawPerceptionManifest,
20
21
  ClawclawResourceLocalizations,
21
22
  } from './contracts.js';
@@ -89,6 +90,66 @@ function balancedBlock(source: string, open: number, openChar: '{' | '[', closeC
89
90
  return null;
90
91
  }
91
92
 
93
+ function topLevelObjectPropertyBlock(source: string, property: string): string | null | undefined {
94
+ let depth = 0;
95
+ let quote: "'" | '"' | '`' | undefined;
96
+ let escaped = false;
97
+ let lineComment = false;
98
+ let blockComment = false;
99
+ for (let index = 0; index < source.length; index += 1) {
100
+ const char = source[index];
101
+ const next = source[index + 1];
102
+ if (lineComment) {
103
+ if (char === '\n' || char === '\r') lineComment = false;
104
+ continue;
105
+ }
106
+ if (blockComment) {
107
+ if (char === '*' && next === '/') {
108
+ blockComment = false;
109
+ index += 1;
110
+ }
111
+ continue;
112
+ }
113
+ if (quote) {
114
+ if (escaped) escaped = false;
115
+ else if (char === '\\') escaped = true;
116
+ else if (char === quote) quote = undefined;
117
+ continue;
118
+ }
119
+ if (char === '/' && next === '/') {
120
+ lineComment = true;
121
+ index += 1;
122
+ continue;
123
+ }
124
+ if (char === '/' && next === '*') {
125
+ blockComment = true;
126
+ index += 1;
127
+ continue;
128
+ }
129
+ if (char === "'" || char === '"' || char === '`') {
130
+ quote = char;
131
+ continue;
132
+ }
133
+ if (char === '{') {
134
+ depth += 1;
135
+ continue;
136
+ }
137
+ if (char === '}') {
138
+ depth -= 1;
139
+ continue;
140
+ }
141
+ if (depth !== 1 || !source.startsWith(property, index)) continue;
142
+ const before = source[index - 1] ?? '';
143
+ const afterName = source[index + property.length] ?? '';
144
+ if (/[A-Za-z0-9_$]/.test(before) || /[A-Za-z0-9_$]/.test(afterName)) continue;
145
+ const match = /^\s*:\s*\{/.exec(source.slice(index + property.length));
146
+ if (!match) continue;
147
+ const open = index + property.length + match[0].lastIndexOf('{');
148
+ return balancedBlock(source, open, '{', '}');
149
+ }
150
+ return undefined;
151
+ }
152
+
92
153
  function decodeString(raw: string): string | null {
93
154
  try {
94
155
  return JSON.parse(`"${raw.replace(/"/g, '\\"')}"`) as string;
@@ -143,11 +204,8 @@ function literalStringArray(source: string, property: string): string[] | null {
143
204
  function literalLocalizations(
144
205
  source: string,
145
206
  ): 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;
207
+ const block = topLevelObjectPropertyBlock(source, 'localizations');
208
+ if (block === undefined || block === null) return block;
151
209
  const values: Record<string, { name: string; description: string }> = {};
152
210
  const entry = /(["'\x60])((?:\\.|(?!\1)[\s\S])*)\1\s*:\s*\{/g;
153
211
  let cursor = 1;
@@ -170,6 +228,38 @@ function literalLocalizations(
170
228
  return values;
171
229
  }
172
230
 
231
+ function literalEventMetadata(
232
+ source: string,
233
+ ): Readonly<Record<string, ClawclawPerceptionEventMetadata>> | null | undefined {
234
+ const block = topLevelObjectPropertyBlock(source, 'eventMetadata');
235
+ if (block === undefined || block === null) return block;
236
+ const values: Record<string, ClawclawPerceptionEventMetadata> = {};
237
+ const entry = /(["'\x60])((?:\\.|(?!\1)[\s\S])*)\1\s*:\s*\{/g;
238
+ let cursor = 1;
239
+ let match: RegExpExecArray | null;
240
+ while ((match = entry.exec(block)) !== null) {
241
+ if (block.slice(cursor, match.index).replace(/[\s,]/g, '')) return null;
242
+ if (match[1] === '`' && match[2].includes('${')) return null;
243
+ const type = decodeString(match[2])?.trim();
244
+ const entryOpen = match.index + match[0].lastIndexOf('{');
245
+ const entryBlock = balancedBlock(block, entryOpen, '{', '}');
246
+ if (!type || !entryBlock || values[type]) return null;
247
+ const name = literalProperty(entryBlock, 'name')?.trim();
248
+ const description = literalProperty(entryBlock, 'description')?.trim();
249
+ const localizations = literalLocalizations(entryBlock);
250
+ if (!name || !description || localizations === null) return null;
251
+ values[type] = {
252
+ name,
253
+ description,
254
+ ...(localizations === undefined ? {} : { localizations }),
255
+ };
256
+ cursor = entryOpen + entryBlock.length;
257
+ entry.lastIndex = cursor;
258
+ }
259
+ if (block.slice(cursor, -1).replace(/[\s,]/g, '')) return null;
260
+ return values;
261
+ }
262
+
173
263
  function parseSource(sourcePath: string, sourceRoot: string): ResolvedClawclawPerceptionSource | null {
174
264
  let source: string;
175
265
  try {
@@ -197,6 +287,7 @@ function parseSource(sourcePath: string, sourceRoot: string): ResolvedClawclawPe
197
287
  const execution = literalProperty(manifestBlock, 'execution')?.trim();
198
288
  const boundaryBaseline = literalProperty(manifestBlock, 'boundaryBaseline')?.trim();
199
289
  const localizations = literalLocalizations(manifestBlock);
290
+ const eventMetadata = literalEventMetadata(manifestBlock);
200
291
  const parallelClass = classMatch[1] === 'ClawclawParallelPerception';
201
292
  if (
202
293
  !id
@@ -215,6 +306,14 @@ function parseSource(sourcePath: string, sourceRoot: string): ResolvedClawclawPe
215
306
  )
216
307
  || parallelClass !== (execution === 'parallel_analysis')
217
308
  || localizations === null
309
+ || eventMetadata === null
310
+ || (
311
+ eventMetadata !== undefined
312
+ && (
313
+ Object.keys(eventMetadata).length !== produces.length
314
+ || Object.keys(eventMetadata).some((type) => !produces.includes(type))
315
+ )
316
+ )
218
317
  ) return null;
219
318
 
220
319
  const manifest: ClawclawPerceptionManifest = {
@@ -224,6 +323,7 @@ function parseSource(sourcePath: string, sourceRoot: string): ResolvedClawclawPe
224
323
  ...(localizations === undefined ? {} : { localizations }),
225
324
  subjectScope: subjectScope as ClawclawPerceptionManifest['subjectScope'],
226
325
  produces,
326
+ ...(eventMetadata === undefined ? {} : { eventMetadata }),
227
327
  ...(execution ? { execution: 'parallel_analysis' as const } : {}),
228
328
  ...(boundaryBaseline ? { boundaryBaseline: 'current_only' as const } : {}),
229
329
  };
@@ -1253,6 +1253,180 @@ describe('ClawclawSourcePlugin lifecycle', () => {
1253
1253
  }
1254
1254
  });
1255
1255
 
1256
+ it('rejects one malformed GameSync Event without stopping Source or later frames', async () => {
1257
+ const { runtime, source, games, client } = await fixture([{
1258
+ status: 'allocated',
1259
+ mode: 'match',
1260
+ game_id: 'G-malformed-event',
1261
+ ws_url: 'wss://game.test/ws',
1262
+ }]);
1263
+ await waitUntil(() => games.length === 1, 'Game transport was not started.');
1264
+ const diagnostic = vi.spyOn(runtime, 'diagnostic');
1265
+
1266
+ const roster = (victimAlive: boolean) => ([
1267
+ { seat: 1, name: 'me', known_status: { is_alive: true } },
1268
+ { seat: 2, name: 'Killer', known_status: { is_alive: true } },
1269
+ {
1270
+ seat: 4,
1271
+ name: 'Victim',
1272
+ known_status: victimAlive
1273
+ ? { is_alive: true }
1274
+ : { is_alive: false, death_cause: 'killed' },
1275
+ },
1276
+ ]);
1277
+ await games[0].emit(gameStateFrame('game-1', 1, {
1278
+ tick: 1,
1279
+ phase: 'wandering',
1280
+ you: { player: { seat: 1, name: 'me' }, is_alive: true },
1281
+ players: roster(true),
1282
+ }));
1283
+ await games[0].emit(gameStateFrame('game-1', 2, {
1284
+ tick: 2,
1285
+ phase: 'wandering',
1286
+ you: { player: { seat: 1, name: 'me' }, is_alive: true },
1287
+ players: roster(false),
1288
+ }, [{
1289
+ event_id: 'role-valid-before',
1290
+ type: 'role_assigned',
1291
+ role: 'shrimp',
1292
+ }, {
1293
+ event_id: 'killed-malformed',
1294
+ tick: 2,
1295
+ type: 'killed',
1296
+ actor: { seat: 4, name: 'Victim' },
1297
+ killer: { kind: 'player', player: { seat: 2 } },
1298
+ }, {
1299
+ event_id: 'task-valid-after',
1300
+ type: 'task_assigned',
1301
+ task_name: 'wires',
1302
+ }]));
1303
+ await games[0].emit(gameStateFrame('game-1', 3, {
1304
+ tick: 3,
1305
+ phase: 'wandering',
1306
+ you: { player: { seat: 1, name: 'me' }, is_alive: true },
1307
+ players: roster(false),
1308
+ }));
1309
+ await runtime.flush();
1310
+
1311
+ const secondEpoch = runtime.inputJournal.list(runtime.scope(), 0, 100)
1312
+ .find((epoch) => epoch.domainTick === 2);
1313
+ expect(secondEpoch?.events).toEqual(expect.arrayContaining([
1314
+ expect.objectContaining({
1315
+ type: 'role_assigned', sourceEventId: 'role-valid-before', sourceSeq: '2:0',
1316
+ }),
1317
+ expect.objectContaining({
1318
+ type: 'task_assigned', sourceEventId: 'task-valid-after', sourceSeq: '2:2',
1319
+ }),
1320
+ expect.objectContaining({
1321
+ type: 'players_changed',
1322
+ payload: expect.objectContaining({
1323
+ changes: expect.arrayContaining([expect.objectContaining({
1324
+ change: 'died', name: 'Victim', cause: 'killed', killer: null,
1325
+ })]),
1326
+ }),
1327
+ }),
1328
+ ]));
1329
+ expect(secondEpoch?.events.some((event) => event.type === 'killed')).toBe(false);
1330
+ expect(diagnostic).toHaveBeenCalledWith(
1331
+ 'runtime.source.event_rejected',
1332
+ expect.objectContaining({
1333
+ source_id: CLAWCLAW_GAME_WS_SOURCE.sourceId,
1334
+ source_seq: 2,
1335
+ event_index: 1,
1336
+ event_type: 'killed',
1337
+ source_event_id: 'killed-malformed',
1338
+ error_code: 'GAME_SYNC_EVENT_NORMALIZATION_FAILED',
1339
+ error_name: 'TypeError',
1340
+ }),
1341
+ 'error',
1342
+ );
1343
+ expect(client.acknowledgeGameSync).toHaveBeenLastCalledWith('ack:game-1:3', false);
1344
+ expect(games[0].stoppedWith).toBeUndefined();
1345
+ expect(runtime.repository.latestEventByType(
1346
+ runtime.scope().sessionId,
1347
+ 'error',
1348
+ runtime.scope().segmentId,
1349
+ )?.payload).not.toMatchObject({ code: 'SOURCE_FAILED' });
1350
+
1351
+ await source.stop();
1352
+ await runtime.close();
1353
+ });
1354
+
1355
+ it('logs partial State loss, rejects an invalid tick, and accepts the next frame', async () => {
1356
+ const { runtime, source, games, client } = await fixture([{
1357
+ status: 'allocated',
1358
+ mode: 'match',
1359
+ game_id: 'G-malformed-frame',
1360
+ ws_url: 'wss://game.test/ws',
1361
+ }]);
1362
+ await waitUntil(() => games.length === 1, 'Game transport was not started.');
1363
+ const diagnostic = vi.spyOn(runtime, 'diagnostic');
1364
+
1365
+ await games[0].emit(gameStateFrame('game-1', 1, {
1366
+ tick: 1,
1367
+ phase: 'wandering',
1368
+ you: { player: { seat: 1, name: 'me' } },
1369
+ players: [{ seat: 1, name: 'me', known_status: { is_alive: true } }],
1370
+ }));
1371
+ await games[0].emit(gameStateFrame('game-1', 2, {
1372
+ tick: 2,
1373
+ phase: 'wandering',
1374
+ }));
1375
+
1376
+ const invalidTick = gameStateFrame('game-1', 3, {
1377
+ tick: 99,
1378
+ phase: 'wandering',
1379
+ });
1380
+ invalidTick.meta.domainTick = 3;
1381
+ await expect(games[0].emit(invalidTick)).resolves.toBeUndefined();
1382
+
1383
+ await games[0].emit(gameStateFrame('game-1', 4, {
1384
+ tick: 4,
1385
+ phase: 'wandering',
1386
+ you: { player: { seat: 1, name: 'me' } },
1387
+ players: [{ seat: 1, name: 'me', known_status: { is_alive: true } }],
1388
+ }));
1389
+ await runtime.flush();
1390
+
1391
+ const ticks = runtime.inputJournal.list(runtime.scope(), 0, 100)
1392
+ .map((epoch) => epoch.domainTick);
1393
+ expect(ticks).toEqual(expect.arrayContaining([1, 2, 4]));
1394
+ expect(ticks).not.toContain(3);
1395
+ expect(diagnostic).toHaveBeenCalledWith(
1396
+ 'runtime.source.state_degraded',
1397
+ expect.objectContaining({
1398
+ source_id: CLAWCLAW_GAME_WS_SOURCE.sourceId,
1399
+ source_seq: 2,
1400
+ error_code: 'GAME_SYNC_STATE_FIELDS_MISSING',
1401
+ missing_fields: ['players', 'you'],
1402
+ }),
1403
+ 'warn',
1404
+ );
1405
+ expect(diagnostic).toHaveBeenCalledWith(
1406
+ 'runtime.source.frame_rejected',
1407
+ expect.objectContaining({
1408
+ source_id: CLAWCLAW_GAME_WS_SOURCE.sourceId,
1409
+ source_seq: 3,
1410
+ error_code: 'GAME_SYNC_TICK_INVALID',
1411
+ reason: 'tick_mismatch',
1412
+ frame_tick: 3,
1413
+ state_tick: 99,
1414
+ }),
1415
+ 'error',
1416
+ );
1417
+ expect(client.acknowledgeGameSync).not.toHaveBeenCalledWith('ack:game-1:3', false);
1418
+ expect(client.acknowledgeGameSync).toHaveBeenLastCalledWith('ack:game-1:4', false);
1419
+ expect(games[0].stoppedWith).toBeUndefined();
1420
+ expect(runtime.repository.latestEventByType(
1421
+ runtime.scope().sessionId,
1422
+ 'error',
1423
+ runtime.scope().segmentId,
1424
+ )?.payload).not.toMatchObject({ code: 'SOURCE_FAILED' });
1425
+
1426
+ await source.stop();
1427
+ await runtime.close();
1428
+ });
1429
+
1256
1430
  it('keeps exile pending until a later authoritative State confirms death', async () => {
1257
1431
  const { runtime, source, games } = await fixture([{
1258
1432
  status: 'allocated',