@myclaw163/clawclaw-cli 0.8.3 → 0.8.5

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 (264) hide show
  1. package/README.md +4 -3
  2. package/docs/configuration.md +44 -26
  3. package/docs/custom-modules/README.md +7 -10
  4. package/docs/custom-modules/api-reference.md +3 -7
  5. package/docs/custom-modules/behavior.md +6 -4
  6. package/docs/custom-modules/perception.md +1 -1
  7. package/docs/custom-modules/trigger.md +1 -1
  8. package/docs/runtime/README.md +4 -4
  9. package/docs/runtime/official-perception-modules.md +2 -2
  10. package/docs/runtime/owner-lifecycle-and-observability.md +1 -1
  11. package/package.json +9 -2
  12. package/scripts/build-official-hub-behaviors.mjs +136 -0
  13. package/scripts/build-official-hub-behaviors.test.mjs +178 -0
  14. package/scripts/enable_ccl_permissions.cjs +4 -2
  15. package/scripts/enable_ccl_permissions.test.mjs +8 -4
  16. package/scripts/postinstall.mjs +1 -4
  17. package/scripts/sync-bundled-skill.mjs +12 -159
  18. package/scripts/sync-bundled-skill.test.mjs +9 -74
  19. package/skills/clawclaw/SKILL.md +18 -13
  20. package/skills/clawclaw/references/BEHAVIORS.md +4 -4
  21. package/skills/clawclaw/references/COMMANDS.md +33 -18
  22. package/skills/clawclaw/references/GAME-MECHANICS.md +16 -18
  23. package/skills/clawclaw/references/HUB.md +25 -38
  24. package/skills/clawclaw/references/STREAM.md +9 -11
  25. package/src/behaviors/official-finite/do-task.ts +70 -0
  26. package/src/behaviors/official-finite/index.ts +0 -3
  27. package/src/commands/account.ts +58 -14
  28. package/src/commands/behavior.ts +116 -38
  29. package/src/commands/hub.ts +110 -153
  30. package/src/commands/load.ts +138 -33
  31. package/src/commands/perception.ts +55 -24
  32. package/src/commands/persona.ts +66 -20
  33. package/src/commands/skill.ts +12 -48
  34. package/src/commands/trigger.ts +68 -40
  35. package/src/hub-official-behaviors/kill-lone.ts +138 -0
  36. package/src/hub-official-behaviors/patrol.ts +30 -0
  37. package/src/hub-official-behaviors/shared.ts +125 -0
  38. package/src/hub-official-behaviors/task-only.ts +158 -0
  39. package/src/lib/account-guidance.ts +54 -9
  40. package/src/lib/agent-workspace-client.ts +135 -0
  41. package/src/lib/agent-workspace-runtime.ts +154 -0
  42. package/src/lib/agent-workspace-skills.ts +177 -0
  43. package/src/lib/agent-workspace-sync.ts +852 -0
  44. package/src/lib/gameplay-config.ts +29 -15
  45. package/src/lib/hub-client.ts +252 -34
  46. package/src/lib/hub-reminder.ts +22 -7
  47. package/src/lib/init-command.ts +0 -6
  48. package/src/lib/load-context.ts +12 -6
  49. package/src/lib/persona.ts +141 -69
  50. package/src/lib/server-status.ts +78 -0
  51. package/src/lib/skill-host.ts +160 -0
  52. package/src/lib/user-data.ts +197 -4
  53. package/src/pipeline/event-format.ts +20 -4
  54. package/src/pipeline/event-hints.ts +20 -6
  55. package/src/pipeline/game-sync-event-normalization.ts +9 -0
  56. package/src/pipeline/role-display.ts +22 -0
  57. package/src/runtime/clawclaw/agent-ability-state.ts +1 -21
  58. package/src/runtime/clawclaw/agent-event-policy.ts +1 -0
  59. package/src/runtime/clawclaw/owner.ts +63 -19
  60. package/src/runtime/clawclaw/plugins/action/action-plugin.ts +8 -1
  61. package/src/runtime/clawclaw/plugins/action/automated-action-normalization.ts +0 -1
  62. package/src/runtime/clawclaw/plugins/behavior/activation-manager.ts +8 -2
  63. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +2 -2
  64. package/src/runtime/clawclaw/plugins/behavior/official-goal-behavior.ts +0 -9
  65. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +4 -1
  66. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +11 -5
  67. package/src/runtime/clawclaw/plugins/perception/replay.ts +0 -2
  68. package/src/runtime/clawclaw-event-catalog.ts +2 -0
  69. package/src/runtime/framework/action-diagnostics.ts +1 -0
  70. package/src/runtime/framework/modules/runtime-module-loader.ts +0 -1
  71. package/src/sdk/action.ts +8 -6
  72. package/src/sdk/behavior-plugin/index.ts +1 -2
  73. package/src/sdk/behavior-toolkit/model.ts +2 -0
  74. package/src/sdk/module-input/index.ts +0 -2
  75. package/src/strategies/goals/crab-sabotage-top.ts +5 -61
  76. package/src/strategies/types.ts +0 -6
  77. package/personas//345/217/243/346/230/257/345/277/203/351/235/236.md +0 -50
  78. package/personas//345/277/240/345/277/203/350/200/201/344/273/206.md +0 -51
  79. package/personas//346/227/240/344/272/272/350/256/276.md +0 -1
  80. package/personas//350/264/253/345/230/264/346/215/237/345/217/213.md +0 -48
  81. package/personas//350/275/257/350/220/214/350/205/271/351/273/221.md +0 -51
  82. package/src/behaviors/official-finite/index.test.ts +0 -202
  83. package/src/behaviors/official-finite/trigger-alarm.ts +0 -53
  84. package/src/channel/claude-channel-server.test.ts +0 -202
  85. package/src/commands/account.test.ts +0 -570
  86. package/src/commands/behavior.test.ts +0 -158
  87. package/src/commands/communication.test.ts +0 -282
  88. package/src/commands/competition.test.ts +0 -116
  89. package/src/commands/data.test.ts +0 -89
  90. package/src/commands/events-canonical-state.test.ts +0 -406
  91. package/src/commands/events.test.ts +0 -58
  92. package/src/commands/game/index.test.ts +0 -1251
  93. package/src/commands/game-map.test.ts +0 -69
  94. package/src/commands/hub.test.ts +0 -124
  95. package/src/commands/load.test.ts +0 -440
  96. package/src/commands/perception.test.ts +0 -75
  97. package/src/commands/setup/hermes.test.ts +0 -96
  98. package/src/commands/setup/openclaw.test.ts +0 -124
  99. package/src/commands/trigger.test.ts +0 -140
  100. package/src/commands/upgrade.test.ts +0 -82
  101. package/src/lib/account-guidance.test.ts +0 -36
  102. package/src/lib/auth.test.ts +0 -151
  103. package/src/lib/behavior-export.test.ts +0 -282
  104. package/src/lib/behavior-export.ts +0 -514
  105. package/src/lib/clawclaw-skill-spectate-guidance.test.ts +0 -21
  106. package/src/lib/custom-tts.test.ts +0 -387
  107. package/src/lib/diagnostics-config.test.ts +0 -59
  108. package/src/lib/game-client-tts.test.ts +0 -151
  109. package/src/lib/game-client.test.ts +0 -250
  110. package/src/lib/gameplay-config.test.ts +0 -301
  111. package/src/lib/host-config-patcher.test.ts +0 -130
  112. package/src/lib/http-transport.test.ts +0 -124
  113. package/src/lib/hub-client.test.ts +0 -57
  114. package/src/lib/hub-install.test.ts +0 -135
  115. package/src/lib/hub-install.ts +0 -185
  116. package/src/lib/hub-unzip.test.ts +0 -69
  117. package/src/lib/init-command.test.ts +0 -103
  118. package/src/lib/load-context.test.ts +0 -62
  119. package/src/lib/match-state.test.ts +0 -134
  120. package/src/lib/official-resource-sync.test.ts +0 -199
  121. package/src/lib/official-resource-sync.ts +0 -221
  122. package/src/lib/perception-config.test.ts +0 -143
  123. package/src/lib/perception-export.test.ts +0 -145
  124. package/src/lib/perception-export.ts +0 -178
  125. package/src/lib/persona.test.ts +0 -84
  126. package/src/lib/room.test.ts +0 -88
  127. package/src/lib/server-registry.test.ts +0 -64
  128. package/src/lib/service-status.test.ts +0 -81
  129. package/src/lib/skill-version.test.ts +0 -48
  130. package/src/lib/trigger-config.test.ts +0 -102
  131. package/src/lib/trigger-export.test.ts +0 -80
  132. package/src/lib/trigger-export.ts +0 -210
  133. package/src/lib/user-data.test.ts +0 -121
  134. package/src/lib/workspace-argv.test.ts +0 -49
  135. package/src/pipeline/canonical-event-presentation.test.ts +0 -255
  136. package/src/pipeline/event-format.test.ts +0 -828
  137. package/src/pipeline/event-hints.test.ts +0 -316
  138. package/src/pipeline/game-sync-event-normalization.test.ts +0 -371
  139. package/src/pipeline/player-projection.test.ts +0 -247
  140. package/src/runtime/auto-upgrade.test.ts +0 -66
  141. package/src/runtime/canonical-event-emitter.test.ts +0 -70
  142. package/src/runtime/canonical-monitor.test.ts +0 -577
  143. package/src/runtime/clawclaw/agent-event-policy.test.ts +0 -58
  144. package/src/runtime/clawclaw/behavior-decision.test.ts +0 -43
  145. package/src/runtime/clawclaw/behavior-input-fields.test.ts +0 -175
  146. package/src/runtime/clawclaw/behavior-input.test.ts +0 -173
  147. package/src/runtime/clawclaw/behavior-observation-memory.test.ts +0 -59
  148. package/src/runtime/clawclaw/behavior-read-api.test.ts +0 -123
  149. package/src/runtime/clawclaw/notifications.test.ts +0 -47
  150. package/src/runtime/clawclaw/owner-lock.test.ts +0 -221
  151. package/src/runtime/clawclaw/owner.test.ts +0 -203
  152. package/src/runtime/clawclaw/plugins/action/action-plugin.test.ts +0 -304
  153. package/src/runtime/clawclaw/plugins/assembly.test.ts +0 -200
  154. package/src/runtime/clawclaw/plugins/behavior/activation-manager.test.ts +0 -180
  155. package/src/runtime/clawclaw/plugins/behavior/behavior-action.test.ts +0 -40
  156. package/src/runtime/clawclaw/plugins/behavior/behavior-catalog.test.ts +0 -156
  157. package/src/runtime/clawclaw/plugins/behavior/behavior-module-loader.test.ts +0 -182
  158. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.test.ts +0 -1094
  159. package/src/runtime/clawclaw/plugins/behavior/behavior-source.test.ts +0 -174
  160. package/src/runtime/clawclaw/plugins/behavior/control-driver.test.ts +0 -195
  161. package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.test.ts +0 -283
  162. package/src/runtime/clawclaw/plugins/behavior-input-source.test.ts +0 -80
  163. package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.test.ts +0 -267
  164. package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.test.ts +0 -226
  165. package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-adapter.test.ts +0 -239
  166. package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.test.ts +0 -407
  167. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-push.integration.test.ts +0 -397
  168. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.test.ts +0 -270
  169. package/src/runtime/clawclaw/plugins/mailbox/mailbox-agent-event-batch.test.ts +0 -166
  170. package/src/runtime/clawclaw/plugins/mailbox/mailbox-event-batch-delivery.test.ts +0 -194
  171. package/src/runtime/clawclaw/plugins/mailbox/mailbox-plugin.test.ts +0 -87
  172. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.test.ts +0 -2012
  173. package/src/runtime/clawclaw/plugins/perception/module-runner.test.ts +0 -214
  174. package/src/runtime/clawclaw/plugins/perception/modules/co-movement-module.ts +0 -347
  175. package/src/runtime/clawclaw/plugins/perception/modules/corpse-visibility-module.test.ts +0 -92
  176. package/src/runtime/clawclaw/plugins/perception/modules/corpse-visibility-module.ts +0 -248
  177. package/src/runtime/clawclaw/plugins/perception/modules/follow-module.ts +0 -389
  178. package/src/runtime/clawclaw/plugins/perception/modules/index.ts +0 -8
  179. package/src/runtime/clawclaw/plugins/perception/modules/motion-module.test.ts +0 -342
  180. package/src/runtime/clawclaw/plugins/perception/modules/motion-module.ts +0 -475
  181. package/src/runtime/clawclaw/plugins/perception/modules/parallel-module-test-helpers.ts +0 -30
  182. package/src/runtime/clawclaw/plugins/perception/modules/relation-stability.test.ts +0 -304
  183. package/src/runtime/clawclaw/plugins/perception/modules/route-module.test.ts +0 -179
  184. package/src/runtime/clawclaw/plugins/perception/modules/route-module.ts +0 -364
  185. package/src/runtime/clawclaw/plugins/perception/modules/spatial-module.test.ts +0 -81
  186. package/src/runtime/clawclaw/plugins/perception/modules/spatial-module.ts +0 -200
  187. package/src/runtime/clawclaw/plugins/perception/modules/stop-module.test.ts +0 -216
  188. package/src/runtime/clawclaw/plugins/perception/modules/stop-module.ts +0 -284
  189. package/src/runtime/clawclaw/plugins/perception/modules/temporal-evidence.test.ts +0 -120
  190. package/src/runtime/clawclaw/plugins/perception/modules/visibility-module.test.ts +0 -105
  191. package/src/runtime/clawclaw/plugins/perception/modules/visibility-module.ts +0 -269
  192. package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-pool.test.ts +0 -865
  193. package/src/runtime/clawclaw/plugins/perception/perception-plugin.test.ts +0 -1878
  194. package/src/runtime/clawclaw/plugins/perception/perception-source.test.ts +0 -278
  195. package/src/runtime/clawclaw/plugins/perception/replay.test.ts +0 -77
  196. package/src/runtime/clawclaw/plugins/runtime-plugins.test.ts +0 -854
  197. package/src/runtime/clawclaw/plugins/source/game-transport.test.ts +0 -287
  198. package/src/runtime/clawclaw/plugins/source/player-change-tracker.test.ts +0 -321
  199. package/src/runtime/clawclaw/plugins/source/room-transport.test.ts +0 -307
  200. package/src/runtime/clawclaw/plugins/source/source-plugin.test.ts +0 -2646
  201. package/src/runtime/clawclaw/plugins/source/task-change-tracker.test.ts +0 -212
  202. package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.test.ts +0 -548
  203. package/src/runtime/clawclaw/plugins/trigger/trigger-source.test.ts +0 -169
  204. package/src/runtime/clawclaw/runtime-data-export.test.ts +0 -249
  205. package/src/runtime/clawclaw-event-catalog.test.ts +0 -126
  206. package/src/runtime/framework/action-diagnostics.test.ts +0 -81
  207. package/src/runtime/framework/capability-registry.test.ts +0 -423
  208. package/src/runtime/framework/control-coordinator.test.ts +0 -675
  209. package/src/runtime/framework/events/event-delivery-service.test.ts +0 -84
  210. package/src/runtime/framework/events/event-ingress.test.ts +0 -203
  211. package/src/runtime/framework/events/mailbox-event-repositories.test.ts +0 -710
  212. package/src/runtime/framework/events/sqlite-event-repository.test.ts +0 -802
  213. package/src/runtime/framework/mailbox/coalescer.test.ts +0 -55
  214. package/src/runtime/framework/mailbox/identity.test.ts +0 -38
  215. package/src/runtime/framework/mailbox/mailbox-dispatcher.test.ts +0 -513
  216. package/src/runtime/framework/mailbox/notification-projector.test.ts +0 -77
  217. package/src/runtime/framework/modules/runtime-module-loader.test.ts +0 -435
  218. package/src/runtime/framework/participation-manager.test.ts +0 -108
  219. package/src/runtime/framework/plugins/runtime-input-journal.test.ts +0 -179
  220. package/src/runtime/framework/plugins/runtime-plugin-scheduler.test.ts +0 -2040
  221. package/src/runtime/framework/state/durable-agent-state-snapshot.test.ts +0 -144
  222. package/src/runtime/framework/state/history/sqlite-state-history-repository.test.ts +0 -157
  223. package/src/runtime/framework/state/history/state-history.test.ts +0 -251
  224. package/src/runtime/framework/state/state-core.test.ts +0 -197
  225. package/src/runtime/game-sync-protocol.test.ts +0 -123
  226. package/src/runtime/host-monitor-rate-gate.test.ts +0 -73
  227. package/src/runtime/mailbox-host-relay.test.ts +0 -293
  228. package/src/runtime/observability/observability.test.ts +0 -583
  229. package/src/runtime/owner-control.test.ts +0 -153
  230. package/src/runtime/parent-process-watch.test.ts +0 -27
  231. package/src/runtime/pending-event-handoff.test.ts +0 -29
  232. package/src/runtime/raw-ws-log.test.ts +0 -102
  233. package/src/runtime/runtime-logger.test.ts +0 -58
  234. package/src/runtime/runtime-persistence.test.ts +0 -26
  235. package/src/runtime/runtime.test.ts +0 -1770
  236. package/src/runtime/ws-client.test.ts +0 -562
  237. package/src/sdk/behavior-plugin/index.test.ts +0 -74
  238. package/src/sdk/index.test.ts +0 -45
  239. package/src/sdk/module-input/index.test.ts +0 -49
  240. package/src/sdk/perception-plugin/index.test.ts +0 -22
  241. package/src/sdk/resource-metadata.test.ts +0 -40
  242. package/src/sdk/trigger-plugin/index.test.ts +0 -41
  243. package/src/short-command/classifier.test.ts +0 -107
  244. package/src/short-command/presenter.test.ts +0 -119
  245. package/src/short-command/runner.test.ts +0 -78
  246. package/src/short-command/sensitive-data-filter.test.ts +0 -56
  247. package/src/short-command/transport-response.test.ts +0 -39
  248. package/src/strategies/custom-module.test.ts +0 -268
  249. package/src/strategies/game-utils.test.ts +0 -306
  250. package/src/strategies/goals/avoid-players-top.test.ts +0 -96
  251. package/src/strategies/goals/crab-sabotage-top.test.ts +0 -145
  252. package/src/strategies/goals/kill-lone-top.test.ts +0 -97
  253. package/src/strategies/goals/kill-target-top.test.ts +0 -66
  254. package/src/strategies/goals/lone-kill-task-top.test.ts +0 -85
  255. package/src/strategies/goals/normal-shrimp-top.test.ts +0 -113
  256. package/src/strategies/goals/paradise-fish-top.test.ts +0 -204
  257. package/src/strategies/goals/task-only-top.test.ts +0 -89
  258. package/src/strategies/goals/warrior-shrimp-top.test.ts +0 -139
  259. package/src/strategies/meeting-gate.test.ts +0 -59
  260. package/src/strategies/official-long-behavior.test.ts +0 -89
  261. package/src/strategies/pathfind/astar-path.test.ts +0 -198
  262. package/src/strategies/pathfind/escape-planner.test.ts +0 -223
  263. package/src/strategies/player-targets.test.ts +0 -10
  264. package/src/strategies/task-only.test.ts +0 -138
@@ -1,1878 +0,0 @@
1
- import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
2
- import { tmpdir } from 'node:os';
3
- import { join } from 'node:path';
4
- import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
5
- import { syncOfficialPerceptions } from '../../../../lib/perception-export.js';
6
- import { createClawclawEventCatalog } from '../../../clawclaw-event-catalog.js';
7
- import { MemoryEventRepository } from '../../../framework/events/index.js';
8
- import type {
9
- RuntimeEpochPluginContext,
10
- RuntimeEpochPluginInput,
11
- } from '../../../framework/plugins/index.js';
12
- import { Runtime } from '../../../framework/runtime.js';
13
- import type { StoredStateFrame } from '../../../framework/state/history/contracts.js';
14
- import { MemoryStateHistoryRepository } from '../../../framework/state/history/memory-state-history-repository.js';
15
- import {
16
- CLAWCLAW_PERCEPTION_PLUGIN_ID,
17
- ClawclawPerceptionPlugin,
18
- } from './perception-plugin.js';
19
- import { ImportedLocalPerceptionModuleRunner } from './module-runner.js';
20
- import { ObservationFrameProjector } from '../../observation-frame-projector.js';
21
-
22
- function stored(
23
- frameSeq: number,
24
- tick: number,
25
- state: Record<string, any>,
26
- connectionId = 'ws',
27
- ): StoredStateFrame<Record<string, any>> {
28
- return {
29
- frameSeq,
30
- epochSeq: frameSeq,
31
- scope: {
32
- adapterId: 'clawclaw',
33
- accountId: 'account',
34
- sessionId: 'session',
35
- segmentId: 'game',
36
- },
37
- connectionId,
38
- sourceKey: `state:${frameSeq}`,
39
- backendTick: tick,
40
- observedAtMs: tick * 100,
41
- receivedAtMs: tick * 100,
42
- state: { tick, phase: 'wandering', ...state },
43
- };
44
- }
45
-
46
- function stateAt(tick: number, sevenX: number, nineX?: number) {
47
- return {
48
- players: [
49
- { seat: 1, name: 'Observer', known_status: { is_alive: true } },
50
- { seat: 7, name: 'Seven', known_status: { is_alive: true } },
51
- { seat: 9, name: 'Nine', known_status: { is_alive: true } },
52
- ],
53
- you: {
54
- player: { seat: 1, name: 'Observer' },
55
- x: 760,
56
- y: 2200,
57
- room: '导航仓',
58
- is_alive: true,
59
- },
60
- visible_players: [
61
- { player: { seat: 7, name: 'Seven' }, x: sevenX, y: 2200, room: '导航仓', distance: 140 },
62
- ...(nineX === undefined
63
- ? []
64
- : [{ player: { seat: 9, name: 'Nine' }, x: nineX, y: 2200, room: '导航仓', distance: 80 }]),
65
- ],
66
- visible_corpses: [],
67
- tick,
68
- };
69
- }
70
-
71
- const replayPlugins = new Set<ClawclawPerceptionPlugin>();
72
- const officialWorkspace = mkdtempSync(join(tmpdir(), 'ccl-perception-official-'));
73
-
74
- beforeAll(async () => {
75
- await syncOfficialPerceptions({ workspaceDir: officialWorkspace });
76
- vi.stubEnv('CLAWCLAW_WORKSPACE_DIR', officialWorkspace);
77
- });
78
-
79
- afterAll(() => {
80
- rmSync(officialWorkspace, { recursive: true, force: true });
81
- });
82
-
83
- function pluginFor(id: string) {
84
- const plugin = new ClawclawPerceptionPlugin({ modules: [id] });
85
- replayPlugins.add(plugin);
86
- return plugin;
87
- }
88
-
89
- afterEach(async () => {
90
- await Promise.allSettled([...replayPlugins].map((plugin) => plugin.stopForReplay()));
91
- replayPlugins.clear();
92
- vi.stubEnv('CLAWCLAW_WORKSPACE_DIR', officialWorkspace);
93
- });
94
-
95
- const journals = new WeakMap<
96
- ClawclawPerceptionPlugin,
97
- MemoryStateHistoryRepository<unknown, Record<string, any>>
98
- >();
99
-
100
- function pluginContext(
101
- plugin: ClawclawPerceptionPlugin,
102
- scope: StoredStateFrame<Record<string, any>>['scope'],
103
- completedThroughEpochSeq = 0,
104
- checkpoint?: unknown,
105
- diagnostic: RuntimeEpochPluginContext<Record<string, any>>['diagnostic'] = () => {},
106
- ): RuntimeEpochPluginContext<Record<string, any>> {
107
- let journal = journals.get(plugin);
108
- if (!journal) {
109
- journal = new MemoryStateHistoryRepository<unknown, Record<string, any>>();
110
- journal.openScope(scope);
111
- journals.set(plugin, journal);
112
- }
113
- return {
114
- scope,
115
- stateHistory: journal,
116
- currentSegment: () => ({ kind: 'game' }),
117
- checkpoint: () => checkpoint,
118
- progress: () => ({
119
- pluginId: plugin.id,
120
- completedThroughEpochSeq,
121
- eventCursor: 0,
122
- updatedAt: new Date().toISOString(),
123
- }),
124
- capabilities: {
125
- provideObservation: () => { throw new Error('unused'); },
126
- provideAction: () => { throw new Error('unused'); },
127
- queryObservation: () => Promise.reject(new Error('unused')),
128
- performAction: () => Promise.reject(new Error('unused')),
129
- },
130
- diagnostic,
131
- signal: new AbortController().signal,
132
- };
133
- }
134
-
135
- function epochInput(
136
- frame: StoredStateFrame<Record<string, any>>,
137
- previousState: Record<string, any> | null = null,
138
- ): RuntimeEpochPluginInput<Record<string, any>> {
139
- return {
140
- epoch: {
141
- epochSeq: frame.frameSeq,
142
- scope: frame.scope,
143
- sourceId: 'test',
144
- connectionId: frame.connectionId,
145
- sourceKey: frame.sourceKey,
146
- domainTick: frame.backendTick,
147
- state: frame.state,
148
- events: [],
149
- completeness: 'complete',
150
- receivedAt: new Date(frame.receivedAtMs).toISOString(),
151
- },
152
- frame,
153
- currentState: {
154
- state: frame.state,
155
- stateStatus: {
156
- status: 'fresh',
157
- semantics: 'latest_received',
158
- source: 'owner_memory',
159
- scope: frame.scope,
160
- connectionId: frame.connectionId,
161
- connectionState: 'connected',
162
- receivedAtMs: frame.receivedAtMs,
163
- ageMs: 0,
164
- backendTick: frame.backendTick ?? null,
165
- reason: null,
166
- },
167
- },
168
- previousState,
169
- epochEvents: [],
170
- pendingEvents: [],
171
- upstreamStates: {},
172
- };
173
- }
174
-
175
- async function updatePlugin(
176
- plugin: ClawclawPerceptionPlugin,
177
- input: RuntimeEpochPluginInput<Record<string, any>>,
178
- ) {
179
- await plugin.startForReplay();
180
- const context = pluginContext(plugin, input.frame.scope);
181
- const frame = journals.get(plugin)!.appendStateFrame(input.frame).frame;
182
- const committedInput = { ...input, frame };
183
- const computation = await plugin.update(committedInput, context);
184
- return plugin.commit(committedInput, computation, context);
185
- }
186
-
187
- describe('ClawClaw Perception plugin', () => {
188
- it('cannot resurrect runners when stop overlaps their startup', async () => {
189
- const plugin = new ClawclawPerceptionPlugin({
190
- modules: ['visual.visibility'],
191
- maxBackfillVisualFrames: 1,
192
- });
193
- replayPlugins.add(plugin);
194
- const starting = plugin.startForReplay().then(
195
- () => undefined,
196
- (error: unknown) => error,
197
- );
198
-
199
- await plugin.stopForReplay();
200
-
201
- await expect(starting).resolves.toMatchObject({
202
- message: 'perception_runners_start_cancelled',
203
- });
204
- expect((plugin as any).runnersStarted).toBe(false);
205
- expect((plugin as any).analysisPool).toBeUndefined();
206
-
207
- await plugin.startForReplay();
208
- expect((plugin as any).runnersStarted).toBe(true);
209
- expect((plugin as any).analysisPool.snapshot()).toMatchObject({
210
- state: 'running',
211
- workerCount: 1,
212
- });
213
- });
214
-
215
- it('isolates attributed and unattributed Worker startup failures while healthy modules stay active', async () => {
216
- const root = mkdtempSync(join(tmpdir(), 'ccl-perception-start-isolation-'));
217
- const perceptions = join(root, 'user-data', 'perceptions');
218
- mkdirSync(perceptions, { recursive: true });
219
- writeFileSync(join(perceptions, 'bad-start.ts'), `
220
- import { ClawclawPerception } from '@myclaw163/clawclaw-cli/perception-plugin';
221
- throw new Error('expected_runner_start_failure');
222
- export default class BadStart extends ClawclawPerception {
223
- static manifest = {
224
- apiVersion: 2,
225
- id: 'visual.bad_start', name: 'Bad start', description: 'Fails during direct import.',
226
- subjectScope: 'others', produces: ['visual.bad_start'],
227
- };
228
- update() { return []; }
229
- }
230
- `, 'utf8');
231
- writeFileSync(join(perceptions, 'worker-bad-start.ts'), `
232
- import { isMainThread } from 'node:worker_threads';
233
- import { ClawclawParallelPerception } from '@myclaw163/clawclaw-cli/perception-plugin';
234
- if (!isMainThread) throw new Error('expected_worker_start_failure');
235
- export default class WorkerBadStart extends ClawclawParallelPerception {
236
- static manifest = {
237
- apiVersion: 2,
238
- id: 'visual.worker_bad_start', name: 'Worker bad start',
239
- description: 'Loads on the owner thread but fails in a Worker.',
240
- subjectScope: 'others', produces: ['visual.worker_bad_start'],
241
- execution: 'parallel_analysis',
242
- };
243
- analyze(input) { return { frame_seq: input.frame.frameSeq }; }
244
- commit() { return []; }
245
- }
246
- `, 'utf8');
247
- writeFileSync(join(perceptions, 'worker-exit-start.ts'), `
248
- import { isMainThread } from 'node:worker_threads';
249
- import { ClawclawParallelPerception } from '@myclaw163/clawclaw-cli/perception-plugin';
250
- if (!isMainThread) process.exit(23);
251
- export default class WorkerExitStart extends ClawclawParallelPerception {
252
- static manifest = {
253
- apiVersion: 2,
254
- id: 'visual.worker_exit_start', name: 'Worker exit start',
255
- description: 'Exits before the Worker can attribute its startup failure.',
256
- subjectScope: 'others', produces: ['visual.worker_exit_start'],
257
- execution: 'parallel_analysis',
258
- };
259
- analyze(input) { return { frame_seq: input.frame.frameSeq }; }
260
- commit() { return []; }
261
- }
262
- `, 'utf8');
263
- writeFileSync(join(perceptions, 'healthy-start.ts'), `
264
- import { ClawclawPerception } from '@myclaw163/clawclaw-cli/perception-plugin';
265
- export default class HealthyStart extends ClawclawPerception {
266
- static manifest = {
267
- apiVersion: 2,
268
- id: 'visual.healthy_start', name: 'Healthy start',
269
- description: 'Keeps ordered perception alive when peers fail.',
270
- subjectScope: 'others', produces: ['visual.healthy_start'],
271
- };
272
- updates = 0;
273
- update(frame) {
274
- this.updates += 1;
275
- return [{
276
- type: 'visual.healthy_start', dedupeKey: 'healthy-start:' + frame.frameSeq,
277
- payload: { frame_seq: frame.frameSeq, updates: this.updates },
278
- }];
279
- }
280
- debugSnapshot() { return { updates: this.updates }; }
281
- }
282
- `, 'utf8');
283
- await syncOfficialPerceptions({ workspaceDir: root });
284
- const plugin = new ClawclawPerceptionPlugin({
285
- modules: [
286
- 'visual.bad_start',
287
- 'visual.worker_bad_start',
288
- 'visual.worker_exit_start',
289
- 'visual.healthy_start',
290
- 'visual.visibility',
291
- ],
292
- workspaceDir: root,
293
- });
294
- const diagnostics: Array<{
295
- name: string;
296
- attributes?: Readonly<Record<string, unknown>>;
297
- }> = [];
298
- const firstStored = stored(1, 1, stateAt(1, 900));
299
- const context = pluginContext(
300
- plugin,
301
- firstStored.scope,
302
- 0,
303
- undefined,
304
- (name, attributes) => diagnostics.push({ name, attributes }),
305
- );
306
-
307
- try {
308
- await expect(plugin.start(context)).resolves.toBeUndefined();
309
- expect(plugin.moduleDescriptors().map(({ id }) => id)).toEqual([
310
- 'visual.healthy_start',
311
- 'visual.visibility',
312
- ]);
313
- expect(plugin.localizedModuleDescriptors('en-US').map(({ id }) => id))
314
- .toEqual(['visual.healthy_start', 'visual.visibility']);
315
- expect(plugin.moduleStateSnapshot()).toMatchObject({
316
- 'visual.healthy_start': { updates: 0 },
317
- 'visual.visibility': {
318
- previous_tick: null,
319
- visible_player_ids: [],
320
- },
321
- });
322
- expect((plugin as any).analysisPool.snapshot()).toMatchObject({
323
- state: 'running',
324
- workerCount: 2,
325
- });
326
-
327
- const failures = diagnostics.filter(({ name }) => name === 'perception.module.failed');
328
- expect(failures).toEqual(expect.arrayContaining([
329
- expect.objectContaining({
330
- attributes: expect.objectContaining({
331
- module_id: 'visual.bad_start',
332
- operation: 'start',
333
- }),
334
- }),
335
- expect.objectContaining({
336
- attributes: expect.objectContaining({
337
- module_id: 'visual.worker_bad_start',
338
- operation: 'worker_start',
339
- }),
340
- }),
341
- expect.objectContaining({
342
- attributes: expect.objectContaining({
343
- module_id: 'visual.worker_exit_start',
344
- operation: 'worker_start',
345
- }),
346
- }),
347
- ]));
348
-
349
- const persisted = journals.get(plugin)!.appendStateFrame(firstStored).frame;
350
- const input = epochInput(persisted);
351
- const committed = await plugin.commit(input, await plugin.update(input, context), context);
352
- expect(committed.events).toEqual([
353
- expect.objectContaining({
354
- type: 'visual.healthy_start',
355
- payload: { frame_seq: 1, updates: 1 },
356
- }),
357
- ]);
358
- const second = journals.get(plugin)!.appendStateFrame(
359
- stored(2, 2, stateAt(2, 906, 840)),
360
- ).frame;
361
- const secondInput = epochInput(second);
362
- await plugin.commit(secondInput, await plugin.update(secondInput, context), context);
363
- const third = journals.get(plugin)!.appendStateFrame(
364
- stored(3, 3, stateAt(3, 912, 846)),
365
- ).frame;
366
- const thirdInput = epochInput(third);
367
- const thirdCommit = await plugin.commit(
368
- thirdInput,
369
- await plugin.update(thirdInput, context),
370
- context,
371
- );
372
- expect(thirdCommit.events).toEqual(expect.arrayContaining([
373
- expect.objectContaining({ type: 'visual.healthy_start' }),
374
- expect.objectContaining({ type: 'visual.player_entered' }),
375
- ]));
376
- expect(plugin.moduleStateSnapshot()).toMatchObject({
377
- 'visual.healthy_start': { updates: 3 },
378
- 'visual.visibility': { previous_tick: 3 },
379
- });
380
-
381
- await plugin.stopForReplay();
382
- expect(plugin.moduleDescriptors()).toEqual([]);
383
- expect(plugin.moduleStateSnapshot()).toEqual({});
384
-
385
- await expect(plugin.start(context)).resolves.toBeUndefined();
386
- expect(plugin.moduleDescriptors().map(({ id }) => id)).toEqual([
387
- 'visual.healthy_start',
388
- 'visual.visibility',
389
- ]);
390
- expect(plugin.moduleStateSnapshot()).toMatchObject({
391
- 'visual.healthy_start': { updates: 0 },
392
- 'visual.visibility': { previous_tick: null },
393
- });
394
- expect((plugin as any).analysisPool.snapshot()).toMatchObject({
395
- state: 'running',
396
- workerCount: 2,
397
- });
398
- } finally {
399
- await plugin.stopForReplay();
400
- rmSync(root, { recursive: true, force: true });
401
- }
402
- }, 20_000);
403
-
404
- it('caps the Runtime in-flight perception window at ten', () => {
405
- expect(() => new ClawclawPerceptionPlugin({ maxBackfillVisualFrames: 11 }))
406
- .toThrow('maxBackfillVisualFrames must be an integer between 1 and 10');
407
- expect(new ClawclawPerceptionPlugin({ maxBackfillVisualFrames: 10 }).maxInFlight).toBe(10);
408
- const official = new ClawclawPerceptionPlugin({
409
- modules: ['visual.visibility'],
410
- maxBackfillVisualFrames: 10,
411
- });
412
- expect(official.maxInFlight).toBe(10);
413
- expect(official.catchUp).toBe('every_epoch');
414
- });
415
-
416
- it('exposes a separate recovery deadline', () => {
417
- const plugin = new ClawclawPerceptionPlugin({ modules: ['visual.motion'] });
418
- expect(plugin.recoveryTimeoutMs).toBe(30_000);
419
- });
420
-
421
- it('aggregates every perception module duration into a compact lifecycle timing window', async () => {
422
- const plugin = new ClawclawPerceptionPlugin({
423
- modules: ['visual.visibility', 'visual.motion'],
424
- });
425
- const diagnostics: Array<{
426
- name: string;
427
- attributes?: Readonly<Record<string, unknown>>;
428
- }> = [];
429
- const frame = stored(1, 10, stateAt(10, 900));
430
- const context = pluginContext(
431
- plugin,
432
- frame.scope,
433
- 0,
434
- undefined,
435
- (name, attributes) => diagnostics.push({ name, attributes }),
436
- );
437
- const persisted = journals.get(plugin)!.appendStateFrame(frame).frame;
438
-
439
- await plugin.start(context);
440
- const input = epochInput(persisted);
441
- const computation = await plugin.update(input, context);
442
- await plugin.commit(input, computation, context);
443
- expect(diagnostics.some((entry) => entry.name === 'perception.module.timing_window'))
444
- .toBe(false);
445
- await plugin.flush('shutdown', context);
446
-
447
- const timings = diagnostics.filter((entry) => (
448
- entry.name === 'perception.module.timing_window'
449
- && entry.attributes?.operation === 'update'
450
- ));
451
- expect(timings).toHaveLength(2);
452
- expect(timings.map((entry) => entry.attributes?.module_id).sort()).toEqual([
453
- 'visual.motion',
454
- 'visual.visibility',
455
- ]);
456
- expect(timings).toEqual(expect.arrayContaining([
457
- expect.objectContaining({
458
- attributes: expect.objectContaining({
459
- count: 1,
460
- average_duration_ms: expect.any(Number),
461
- p95_duration_ms: expect.any(Number),
462
- max_duration_ms: expect.any(Number),
463
- failure_count: 0,
464
- event_count: expect.any(Number),
465
- }),
466
- }),
467
- ]));
468
- expect(JSON.stringify(timings)).not.toContain('visible_players');
469
- });
470
-
471
- it('projects self and visible players into one explicitly marked visual set', () => {
472
- const visual = new ObservationFrameProjector().project(stored(1, 10, stateAt(10, 900)));
473
- expect(visual?.gameState).toMatchObject({
474
- tick: 10,
475
- you: { player: { seat: 1, name: 'Observer' } },
476
- });
477
- expect(visual?.observation.players).toEqual(expect.arrayContaining([
478
- expect.objectContaining({ seat: 1, observer: true }),
479
- expect.objectContaining({ seat: 7, observer: false }),
480
- ]));
481
- expect(visual?.observation.visibleSetComplete).toBe(true);
482
- expect(visual).not.toHaveProperty('players');
483
- expect(visual).not.toHaveProperty('corpses');
484
- expect(visual).not.toHaveProperty('visibleSetComplete');
485
- expect(visual).not.toHaveProperty('phase');
486
- expect(visual).not.toHaveProperty('provenance');
487
- });
488
-
489
- it('uses packaged map geometry as the only room authority', () => {
490
- const visual = new ObservationFrameProjector().project(stored(1, 10, {
491
- players: [{ seat: 1, name: 'Observer', known_status: { is_alive: true } }],
492
- you: {
493
- player: { seat: 1, name: 'Observer' },
494
- x: -1,
495
- y: -1,
496
- room: '酒吧',
497
- is_alive: true,
498
- },
499
- visible_players: [],
500
- visible_corpses: [],
501
- }));
502
-
503
- expect(visual?.observation.players[0]?.room).toBeNull();
504
- });
505
-
506
- it('projects v2 visible_corpses and rejects legacy flat visual identities', () => {
507
- const projector = new ObservationFrameProjector();
508
- const visual = projector.project(stored(1, 10, {
509
- players: [
510
- { seat: 1, name: 'Observer', known_status: { is_alive: true } },
511
- { seat: 7, name: 'Seven', known_status: { is_alive: false } },
512
- ],
513
- you: {
514
- player: { seat: 1, name: 'Observer' },
515
- x: 760,
516
- y: 2200,
517
- room: '导航仓',
518
- is_alive: true,
519
- },
520
- visible_players: [],
521
- visible_corpses: [{
522
- corpse_id: 'body-7',
523
- player: { seat: 7, name: 'Seven' },
524
- x: 900,
525
- y: 2200,
526
- room: '导航仓',
527
- distance: 140,
528
- }],
529
- }));
530
- expect(visual?.observation.corpses).toEqual([expect.objectContaining({
531
- id: 'corpse:body-7',
532
- playerId: 'seat:7',
533
- name: 'Seven',
534
- seat: 7,
535
- })]);
536
-
537
- const anonymous = projector.project(stored(2, 11, {
538
- players: [{ seat: 1, name: 'Observer', known_status: { is_alive: true } }],
539
- you: {
540
- player: { seat: 1, name: 'Observer' },
541
- x: 760,
542
- y: 2200,
543
- is_alive: true,
544
- },
545
- visible_players: [],
546
- visible_corpses: [{
547
- corpse_id: 'anonymous-body',
548
- x: 900,
549
- y: 2200,
550
- room: '导航仓',
551
- }],
552
- }))?.observation.corpses[0];
553
- expect(anonymous).toMatchObject({
554
- id: 'corpse:anonymous-body',
555
- });
556
- expect(anonymous).not.toHaveProperty('name');
557
- expect(anonymous).not.toHaveProperty('seat');
558
-
559
- expect(projector.project(stored(3, 12, {
560
- you: { name: 'Observer', seat: 1, x: 760, y: 2200, is_alive: true },
561
- visible_players: [{ name: 'Seven', seat: 7, x: 900, y: 2200 }],
562
- nearby_corpses: [{ name: 'Seven', seat: 7, x: 900, y: 2200 }],
563
- }))).toBeNull();
564
- });
565
-
566
- it('marks the visual set complete only when both player and corpse sets are present', () => {
567
- const visual = new ObservationFrameProjector().project(stored(1, 10, {
568
- you: {
569
- player: { seat: 1, name: 'Observer' },
570
- x: 760,
571
- y: 2200,
572
- is_alive: true,
573
- },
574
- visible_players: [],
575
- }));
576
-
577
- expect(visual?.observation.visibleSetComplete).toBe(false);
578
- });
579
-
580
- it('hosts all materialized official modules through the shared source runner and preserves subject scopes', () => {
581
- const plugin = new ClawclawPerceptionPlugin();
582
- expect(plugin.id).toBe(CLAWCLAW_PERCEPTION_PLUGIN_ID);
583
- expect(plugin.moduleDescriptors()).toHaveLength(8);
584
- expect(new Set(plugin.moduleDescriptors().map((module) => module.pluginId))).toEqual(
585
- new Set([CLAWCLAW_PERCEPTION_PLUGIN_ID]),
586
- );
587
- expect(plugin.moduleDescriptors().every((module) => (
588
- module.execution === 'parallel_analysis'
589
- && module.boundaryBaseline === 'current_only'
590
- ))).toBe(true);
591
- expect((plugin as any).modules.every(({ runner }: any) => (
592
- runner instanceof ImportedLocalPerceptionModuleRunner
593
- ))).toBe(true);
594
- expect(plugin.moduleDescriptors()).toEqual(expect.arrayContaining([
595
- expect.objectContaining({ id: 'visual.visibility', subjectScope: 'others' }),
596
- expect.objectContaining({ id: 'visual.corpse_visibility', subjectScope: 'corpses' }),
597
- expect.objectContaining({ id: 'visual.motion', subjectScope: 'self_and_others' }),
598
- expect.objectContaining({ id: 'visual.follow', subjectScope: 'visible_pairs' }),
599
- ]));
600
- expect(plugin.localizedModuleDescriptors('zh-CN')).toEqual(expect.arrayContaining([
601
- {
602
- id: 'visual.visibility',
603
- name: '视野变化',
604
- description: '感知其他玩家进入、离开或短暂离开后重新出现在视野中。',
605
- },
606
- expect.objectContaining({ id: 'visual.motion', name: '玩家移动' }),
607
- ]));
608
- expect(plugin.localizedModuleDescriptors('en-US')).toEqual(expect.arrayContaining([
609
- expect.objectContaining({ id: 'visual.visibility', name: 'Visibility changes' }),
610
- ]));
611
- expect(plugin.localizedEventDescriptors('zh-CN')).toHaveLength(16);
612
- expect(plugin.localizedEventDescriptors('zh-CN')).toEqual(expect.arrayContaining([
613
- {
614
- type: 'visual.player_entered',
615
- perceptionId: 'visual.visibility',
616
- name: '进入视野',
617
- description: '玩家从不可见状态进入你的当前视野。',
618
- },
619
- expect.objectContaining({
620
- type: 'visual.player_moved',
621
- perceptionId: 'visual.motion',
622
- name: '玩家移动',
623
- }),
624
- ]));
625
- expect(new ClawclawPerceptionPlugin({ modules: ['visual.motion'] })
626
- .localizedEventDescriptors('zh-CN').map((event) => event.type)).toEqual([
627
- 'visual.player_moved',
628
- 'visual.player_motion_changed',
629
- ]);
630
- });
631
-
632
- it('starts, analyzes, commits, and stops all eight official Worker modules together', async () => {
633
- const plugin = new ClawclawPerceptionPlugin();
634
- replayPlugins.add(plugin);
635
- const outcomes = [];
636
- for (let tick = 1; tick <= 4; tick += 1) {
637
- outcomes.push(await updatePlugin(
638
- plugin,
639
- epochInput(stored(tick, tick, stateAt(tick, 900 + tick * 6, 840 + tick * 6))),
640
- ));
641
- }
642
-
643
- expect(outcomes).toHaveLength(4);
644
- expect(outcomes.every((outcome) => outcome.outcome === 'processed')).toBe(true);
645
- expect(Object.keys(plugin.moduleStateSnapshot()).sort()).toEqual([
646
- 'visual.co_movement',
647
- 'visual.corpse_visibility',
648
- 'visual.follow',
649
- 'visual.motion',
650
- 'visual.route',
651
- 'visual.spatial',
652
- 'visual.stop',
653
- 'visual.visibility',
654
- ]);
655
- }, 30_000);
656
-
657
- it('cuts on a tick gap without inventing movement across the gap', async () => {
658
- const plugin = new ClawclawPerceptionPlugin({
659
- modules: ['visual.motion'],
660
- });
661
- await plugin.inspectFrame(stored(1, 1, stateAt(1, 900)));
662
- const inspection = await plugin.inspectFrame(stored(2, 10, stateAt(10, 1_000)));
663
-
664
- expect(inspection.visual).toMatchObject({ tickDelta: 9, continuousFromPrevious: false });
665
- expect(inspection.proposals).toEqual([]);
666
- expect((await plugin.flushForEventsQuery()).events ?? []).toEqual([]);
667
- });
668
-
669
- it('replaces the latest motion sample for a same-tick State revision', async () => {
670
- const plugin = pluginFor('visual.motion');
671
- await plugin.inspectFrame(stored(1, 10, stateAt(10, 900)));
672
- const revision = await plugin.inspectFrame(stored(2, 10, stateAt(10, 905)));
673
-
674
- expect(revision.visual).toMatchObject({
675
- frameSeq: 2,
676
- tick: 10,
677
- tickDelta: 0,
678
- continuousFromPrevious: true,
679
- });
680
- expect(plugin.moduleStateSnapshot()).toMatchObject({
681
- 'visual.motion': {
682
- tracks: expect.arrayContaining([expect.objectContaining({ point_count: 1 })]),
683
- },
684
- });
685
- });
686
-
687
- it('finalizes visibility absence on the next distinct tick and invalidates relations', async () => {
688
- const plugin = new ClawclawPerceptionPlugin({
689
- modules: ['visual.co_movement', 'visual.visibility'],
690
- });
691
- const emitted = [];
692
- for (let tick = 1; tick <= 13; tick += 1) {
693
- emitted.push(...(await plugin.inspectFrame(stored(
694
- tick,
695
- tick,
696
- stateAt(tick, 900 + tick * 5, 840 + tick * 5),
697
- ))).proposals);
698
- }
699
- expect(emitted.map((proposal) => proposal.type)).toContain(
700
- 'visual.players_moving_together',
701
- );
702
-
703
- const revision = await plugin.inspectFrame(stored(14, 13, stateAt(13, 965)));
704
-
705
- expect(revision.visual).toMatchObject({ tick: 13, tickDelta: 0 });
706
- expect(revision.proposals).toEqual([]);
707
-
708
- const finalized = await plugin.inspectFrame(stored(15, 14, stateAt(14, 970)));
709
- expect(finalized.proposals.map((proposal) => proposal.type)).toContain('visual.player_left');
710
- expect(plugin.moduleStateSnapshot()).toMatchObject({
711
- 'visual.co_movement': {
712
- pairs: [],
713
- },
714
- });
715
- });
716
-
717
- it('keeps each module private state across updates', async () => {
718
- const plugin = pluginFor('visual.route');
719
- for (let tick = 1; tick <= 8; tick += 1) {
720
- const x = tick === 1 ? 900 : 910;
721
- await plugin.inspectFrame(stored(tick, tick, stateAt(tick, x)));
722
- }
723
- expect(plugin.moduleStateSnapshot()).toMatchObject({
724
- 'visual.route': {
725
- tracks: expect.arrayContaining([
726
- expect.objectContaining({ player_id: 'seat:7', start_tick: 7, path_length_px: 0 }),
727
- ]),
728
- },
729
- });
730
- });
731
-
732
- it('soft-cuts ongoing movement on ccl events without overlapping the next slice', async () => {
733
- const plugin = pluginFor('visual.motion');
734
- for (let tick = 1; tick <= 5; tick += 1) {
735
- await plugin.inspectFrame(stored(tick, tick, stateAt(tick, 900 + (tick - 1) * 6)));
736
- }
737
- const first = (await plugin.flushForEventsQuery()).events ?? [];
738
- expect(first).toMatchObject([{
739
- type: 'visual.player_moved',
740
- payload: { actors: [7], status: 'ongoing', from_tick: 1, to_tick: 4 },
741
- }]);
742
- expect((await plugin.flushForEventsQuery()).events ?? []).toEqual([]);
743
-
744
- for (let tick = 6; tick <= 9; tick += 1) {
745
- await plugin.inspectFrame(stored(tick, tick, stateAt(tick, 900 + (tick - 1) * 6)));
746
- }
747
- expect((await plugin.flushForEventsQuery()).events ?? []).toMatchObject([{
748
- payload: { actors: [7], status: 'ongoing', from_tick: 5, to_tick: 8 },
749
- }]);
750
- });
751
-
752
- it('hard-cuts the previous phase before the meeting frame enters module history', async () => {
753
- const plugin = pluginFor('visual.motion');
754
- for (let tick = 1; tick <= 5; tick += 1) {
755
- await plugin.inspectFrame(stored(tick, tick, stateAt(tick, 900 + (tick - 1) * 5)));
756
- }
757
- const meeting = stored(6, 6, { ...stateAt(6, 925), phase: 'meeting' });
758
- const result = await plugin.inspectFrame(meeting);
759
-
760
- expect(result.proposals).toMatchObject([{
761
- type: 'visual.player_moved',
762
- payload: { from_tick: 1, to_tick: 5 },
763
- }]);
764
- expect(result.proposals[0].payload).not.toHaveProperty('status');
765
- expect(result.visual?.continuousFromPrevious).toBe(false);
766
- expect(result.visual?.gameState.phase).toBe('meeting');
767
- expect(result.visual).not.toHaveProperty('phase');
768
- });
769
-
770
- it('hard-cuts the visual lifecycle when the observer dies without inventing a dead phase', async () => {
771
- const plugin = pluginFor('visual.motion');
772
- for (let tick = 1; tick <= 5; tick += 1) {
773
- await plugin.inspectFrame(stored(tick, tick, stateAt(tick, 900 + (tick - 1) * 5)));
774
- }
775
- const state = stateAt(6, 925);
776
- const result = await plugin.inspectFrame(stored(6, 6, {
777
- ...state,
778
- you: { ...state.you, is_alive: false },
779
- }));
780
-
781
- expect(result.proposals).toMatchObject([{
782
- type: 'visual.player_moved',
783
- payload: { from_tick: 1, to_tick: 5 },
784
- }]);
785
- expect(result.visual?.continuousFromPrevious).toBe(false);
786
- expect(result.visual?.gameState).toMatchObject({
787
- phase: 'wandering',
788
- you: { is_alive: false },
789
- });
790
- expect(result.visual).not.toHaveProperty('phase');
791
- });
792
-
793
- it('lets the module enforce its own maximum open-slice length', async () => {
794
- const plugin = pluginFor('visual.motion');
795
- const emitted = [];
796
- for (let tick = 1; tick <= 22; tick += 1) {
797
- const result = await plugin.inspectFrame(stored(tick, tick, stateAt(tick, 900 + (tick - 1) * 5)));
798
- emitted.push(...result.proposals);
799
- }
800
- expect(emitted).toEqual([expect.objectContaining({
801
- type: 'visual.player_moved',
802
- payload: expect.objectContaining({
803
- status: 'ongoing',
804
- from_tick: 1,
805
- to_tick: 19,
806
- }),
807
- })]);
808
- });
809
-
810
- it('flushes on the Source events-query boundary but ignores unrelated control input', async () => {
811
- const plugin = pluginFor('visual.motion');
812
- for (let tick = 1; tick <= 5; tick += 1) {
813
- await updatePlugin(plugin, epochInput(stored(tick, tick, stateAt(tick, 900 + (tick - 1) * 6))));
814
- }
815
- const controlFrame = stored(6, 5, {
816
- schema: 'clawclaw.runtime-state.v1',
817
- stage: 'game',
818
- connection: 'connected',
819
- cause: 'control',
820
- control: { type: 'strategy_parameters_updated' },
821
- game_snapshot: { status: 'not_updated' },
822
- });
823
- expect(await updatePlugin(plugin, epochInput(controlFrame))).toMatchObject({
824
- outcome: 'noop',
825
- reason: 'game_snapshot:not_updated',
826
- });
827
-
828
- const queryFrame = stored(7, 5, {
829
- schema: 'clawclaw.runtime-state.v1',
830
- stage: 'game',
831
- connection: 'connected',
832
- cause: 'agent_events_query',
833
- control: { type: 'events_query', request_id: 'query-1' },
834
- game_snapshot: { status: 'not_updated' },
835
- });
836
- expect(await updatePlugin(plugin, epochInput(queryFrame))).toMatchObject({
837
- outcome: 'processed',
838
- reason: 'events_requested',
839
- events: [expect.objectContaining({ type: 'visual.player_moved' })],
840
- });
841
- });
842
-
843
- it('runs materialized official motion analysis in a warm Worker pool and changes state only in ordered commit', async () => {
844
- const plugin = pluginFor('visual.motion');
845
- expect((plugin as any).modules[0].runner).toBeInstanceOf(ImportedLocalPerceptionModuleRunner);
846
- const scope = stored(1, 1, {}).scope;
847
- const context = pluginContext(plugin, scope);
848
- const journal = journals.get(plugin)!;
849
- const first = journal.appendStateFrame(stored(1, 1, stateAt(1, 900))).frame;
850
- const second = journal.appendStateFrame(stored(2, 2, stateAt(2, 906))).frame;
851
- const firstInput = epochInput(first);
852
- const secondInput = epochInput(second);
853
- await plugin.startForReplay();
854
- expect((plugin as any).analysisPool.snapshot()).toMatchObject({
855
- state: 'running',
856
- minWorkers: 2,
857
- maxWorkers: 10,
858
- workerCount: 2,
859
- idleWorkerCount: 2,
860
- startedWorkerCount: 2,
861
- });
862
- const [firstComputation, secondComputation] = await Promise.all([
863
- plugin.update(firstInput, context),
864
- plugin.update(secondInput, context),
865
- ]);
866
-
867
- expect(firstComputation).toMatchObject({
868
- outcome: 'processed',
869
- proposal: { schema: 'clawclaw.perception-computation.v1' },
870
- });
871
- expect(plugin.moduleStateSnapshot()).toMatchObject({
872
- 'visual.motion': { latest_tick: null, tracks: [] },
873
- });
874
- await plugin.commit(firstInput, firstComputation, context);
875
- expect(plugin.moduleStateSnapshot()).toMatchObject({
876
- 'visual.motion': { latest_tick: 1 },
877
- });
878
- await plugin.commit(secondInput, secondComputation, context);
879
- expect(plugin.moduleStateSnapshot()).toMatchObject({
880
- 'visual.motion': { latest_tick: 2 },
881
- });
882
- });
883
-
884
- it('lets frame N+1 analyze immutable frame N before frame N commits', async () => {
885
- const root = mkdtempSync(join(tmpdir(), 'ccl-perception-lookback-'));
886
- const perceptions = join(root, 'user-data', 'perceptions');
887
- mkdirSync(perceptions, { recursive: true });
888
- writeFileSync(join(perceptions, 'lookback.ts'), `
889
- import { ClawclawParallelPerception } from '@myclaw163/clawclaw-cli/perception-plugin';
890
- export default class Lookback extends ClawclawParallelPerception {
891
- static manifest = {
892
- apiVersion: 2,
893
- id: 'visual.lookback', name: 'Lookback', description: 'Checks immutable lookback.',
894
- subjectScope: 'others', produces: ['visual.lookback'], execution: 'parallel_analysis',
895
- };
896
- committed = 0;
897
- async analyze(input) {
898
- await new Promise((resolve) => setTimeout(resolve, input.frame.frameSeq === 1 ? 100 : 5));
899
- return {
900
- frame_seq: input.frame.frameSeq,
901
- history_frame_seqs: input.history.map((frame) => frame.frameSeq),
902
- tick_delta: input.frame.tickDelta,
903
- continuous: input.frame.continuousFromPrevious,
904
- };
905
- }
906
- commit(frame, analysis) {
907
- this.committed += 1;
908
- return [{
909
- type: 'visual.lookback', dedupeKey: 'lookback:' + frame.frameSeq,
910
- payload: { ...analysis, committed: this.committed },
911
- }];
912
- }
913
- reset() { this.committed = 0; }
914
- debugSnapshot() { return { committed: this.committed }; }
915
- }
916
- `, 'utf8');
917
- vi.stubEnv('CLAWCLAW_WORKSPACE_DIR', root);
918
- const plugin = new ClawclawPerceptionPlugin({ modules: ['visual.lookback'] });
919
- expect(plugin.maxInFlight).toBe(10);
920
- const oneFrameWindow = new ClawclawPerceptionPlugin({
921
- modules: ['visual.lookback'],
922
- maxBackfillVisualFrames: 1,
923
- });
924
- expect(oneFrameWindow.maxInFlight).toBe(1);
925
- expect(oneFrameWindow.catchUp).toBe('latest_only');
926
- const firstStored = stored(1, 1, stateAt(1, 900));
927
- const context = pluginContext(plugin, firstStored.scope);
928
- const journal = journals.get(plugin)!;
929
- const first = journal.appendStateFrame(firstStored).frame;
930
- const second = journal.appendStateFrame(stored(2, 2, stateAt(2, 906))).frame;
931
- const firstInput = epochInput(first);
932
- const secondInput = epochInput(second);
933
-
934
- try {
935
- await plugin.startForReplay();
936
- const firstWork = plugin.update(firstInput, context);
937
- const secondWork = plugin.update(secondInput, context);
938
- const [firstComputation, secondComputation] = await Promise.all([firstWork, secondWork]);
939
- expect(secondComputation.proposal).toMatchObject({
940
- analyses: [expect.objectContaining({
941
- outcome: 'fulfilled',
942
- analysis: {
943
- frame_seq: 2,
944
- history_frame_seqs: [1],
945
- tick_delta: 1,
946
- continuous: true,
947
- },
948
- })],
949
- });
950
- expect(plugin.moduleStateSnapshot()).toEqual({ 'visual.lookback': { committed: 0 } });
951
-
952
- await plugin.commit(firstInput, firstComputation, context);
953
- const committed = await plugin.commit(secondInput, secondComputation, context);
954
- expect(committed.events).toEqual([
955
- expect.objectContaining({ payload: expect.objectContaining({ committed: 2 }) }),
956
- ]);
957
-
958
- journal.appendStateFrame(stored(3, 3, stateAt(3, 912)));
959
- const fourth = journal.appendStateFrame(stored(4, 4, stateAt(4, 918))).frame;
960
- const fourthInput = epochInput(fourth);
961
- const fourthComputation = await plugin.update(fourthInput, context);
962
- expect(fourthComputation.proposal).toMatchObject({
963
- analyses: [expect.objectContaining({
964
- analysis: expect.objectContaining({ history_frame_seqs: [1, 2, 3] }),
965
- })],
966
- });
967
- const fifth = journal.appendStateFrame(stored(5, 5, stateAt(5, 924))).frame;
968
- const fifthInput = epochInput(fifth);
969
- // This result is already complete before frame 4 establishes the gap
970
- // boundary, so only a generation barrier can keep it off the reset reducer.
971
- const fifthComputation = await plugin.update(fifthInput, context);
972
- const gapCommit = await plugin.commit(fourthInput, fourthComputation, context);
973
- expect(gapCommit.events ?? []).toEqual([]);
974
- expect(plugin.moduleStateSnapshot()).toEqual({ 'visual.lookback': { committed: 0 } });
975
- expect((await plugin.commit(fifthInput, fifthComputation, context)).events ?? []).toEqual([]);
976
- expect(plugin.moduleStateSnapshot()).toEqual({ 'visual.lookback': { committed: 0 } });
977
-
978
- const sixth = journal.appendStateFrame(stored(6, 6, stateAt(6, 930))).frame;
979
- const sixthInput = epochInput(sixth);
980
- const sixthComputation = await plugin.update(sixthInput, context);
981
- const sixthCommit = await plugin.commit(sixthInput, sixthComputation, context);
982
- expect(sixthCommit.events ?? []).toEqual([]);
983
- expect(plugin.moduleStateSnapshot()).toEqual({ 'visual.lookback': { committed: 1 } });
984
-
985
- const seventh = journal.appendStateFrame(stored(7, 7, stateAt(7, 936))).frame;
986
- const seventhInput = epochInput(seventh);
987
- const seventhCommit = await plugin.commit(
988
- seventhInput,
989
- await plugin.update(seventhInput, context),
990
- context,
991
- );
992
- expect(seventhCommit.events).toEqual([
993
- expect.objectContaining({ payload: expect.objectContaining({
994
- frame_seq: 7,
995
- history_frame_seqs: [4, 5, 6],
996
- committed: 2,
997
- }) }),
998
- ]);
999
- } finally {
1000
- await plugin.stopForReplay();
1001
- vi.unstubAllEnvs();
1002
- rmSync(root, { recursive: true, force: true });
1003
- }
1004
- }, 20_000);
1005
-
1006
- it('invalidates already-computed later analyses after a module analyze failure', async () => {
1007
- const root = mkdtempSync(join(tmpdir(), 'ccl-perception-generation-'));
1008
- const perceptions = join(root, 'user-data', 'perceptions');
1009
- mkdirSync(perceptions, { recursive: true });
1010
- writeFileSync(join(perceptions, 'generation.ts'), `
1011
- import { ClawclawParallelPerception } from '@myclaw163/clawclaw-cli/perception-plugin';
1012
- export default class Generation extends ClawclawParallelPerception {
1013
- static manifest = {
1014
- apiVersion: 2,
1015
- id: 'visual.generation', name: 'Generation', description: 'Checks failure barriers.',
1016
- subjectScope: 'others', produces: ['visual.generation'], execution: 'parallel_analysis',
1017
- };
1018
- async analyze(input) {
1019
- if (input.frame.frameSeq === 1) throw new Error('expected_analysis_failure');
1020
- return {
1021
- frame_seq: input.frame.frameSeq,
1022
- history_frame_seqs: input.history.map((frame) => frame.frameSeq),
1023
- gap_before: input.gapBefore,
1024
- };
1025
- }
1026
- commit(frame, analysis) {
1027
- return [{
1028
- type: 'visual.generation', dedupeKey: 'generation:' + frame.frameSeq,
1029
- payload: analysis,
1030
- }];
1031
- }
1032
- }
1033
- `, 'utf8');
1034
- writeFileSync(join(perceptions, 'healthy.ts'), `
1035
- import { ClawclawParallelPerception } from '@myclaw163/clawclaw-cli/perception-plugin';
1036
- export default class Healthy extends ClawclawParallelPerception {
1037
- static manifest = {
1038
- apiVersion: 2,
1039
- id: 'visual.healthy', name: 'Healthy', description: 'Stays independent of peer failures.',
1040
- subjectScope: 'others', produces: ['visual.healthy'], execution: 'parallel_analysis',
1041
- };
1042
- analyze(input) { return { frame_seq: input.frame.frameSeq }; }
1043
- commit(frame, analysis) {
1044
- return [{
1045
- type: 'visual.healthy', dedupeKey: 'healthy:' + frame.frameSeq, payload: analysis,
1046
- }];
1047
- }
1048
- }
1049
- `, 'utf8');
1050
- vi.stubEnv('CLAWCLAW_WORKSPACE_DIR', root);
1051
- const plugin = new ClawclawPerceptionPlugin({
1052
- modules: ['visual.generation', 'visual.healthy'],
1053
- });
1054
- const firstStored = stored(1, 1, stateAt(1, 900));
1055
- const context = pluginContext(plugin, firstStored.scope);
1056
- const journal = journals.get(plugin)!;
1057
- const first = journal.appendStateFrame(firstStored).frame;
1058
- const second = journal.appendStateFrame(stored(2, 2, stateAt(2, 906))).frame;
1059
- const firstInput = epochInput(first);
1060
- const secondInput = epochInput(second);
1061
-
1062
- try {
1063
- await plugin.startForReplay();
1064
- const [firstComputation, secondComputation] = await Promise.all([
1065
- plugin.update(firstInput, context),
1066
- plugin.update(secondInput, context),
1067
- ]);
1068
- expect(firstComputation.proposal).toMatchObject({
1069
- analyses: expect.arrayContaining([expect.objectContaining({
1070
- moduleId: 'visual.generation', generation: 0, outcome: 'rejected',
1071
- })]),
1072
- });
1073
- expect(secondComputation.proposal).toMatchObject({
1074
- analyses: expect.arrayContaining([expect.objectContaining({
1075
- moduleId: 'visual.generation', generation: 0, outcome: 'fulfilled',
1076
- })]),
1077
- });
1078
-
1079
- expect((await plugin.commit(firstInput, firstComputation, context)).events).toEqual([
1080
- expect.objectContaining({ type: 'visual.healthy' }),
1081
- ]);
1082
- expect((await plugin.commit(secondInput, secondComputation, context)).events).toEqual([
1083
- expect.objectContaining({ type: 'visual.healthy' }),
1084
- ]);
1085
-
1086
- const third = journal.appendStateFrame(stored(3, 3, stateAt(3, 912))).frame;
1087
- const thirdInput = epochInput(third);
1088
- const thirdComputation = await plugin.update(thirdInput, context);
1089
- expect(thirdComputation.proposal).toMatchObject({
1090
- analyses: expect.arrayContaining([expect.objectContaining({
1091
- moduleId: 'visual.generation',
1092
- generation: 1,
1093
- analysis: {
1094
- frame_seq: 3,
1095
- history_frame_seqs: [2],
1096
- gap_before: true,
1097
- },
1098
- })]),
1099
- });
1100
- expect((await plugin.commit(thirdInput, thirdComputation, context)).events).toEqual([
1101
- expect.objectContaining({ type: 'visual.healthy' }),
1102
- ]);
1103
-
1104
- const fourth = journal.appendStateFrame(stored(4, 4, stateAt(4, 918))).frame;
1105
- const fourthInput = epochInput(fourth);
1106
- const fourthComputation = await plugin.update(fourthInput, context);
1107
- expect((await plugin.commit(fourthInput, fourthComputation, context)).events)
1108
- .toEqual(expect.arrayContaining([
1109
- expect.objectContaining({
1110
- type: 'visual.generation',
1111
- payload: expect.objectContaining({ history_frame_seqs: [2, 3] }),
1112
- }),
1113
- expect.objectContaining({ type: 'visual.healthy' }),
1114
- ]));
1115
- } finally {
1116
- await plugin.stopForReplay();
1117
- vi.unstubAllEnvs();
1118
- rmSync(root, { recursive: true, force: true });
1119
- }
1120
- }, 20_000);
1121
-
1122
- it('rebaselines after stale successors of a current-only hard boundary', async () => {
1123
- const root = mkdtempSync(join(tmpdir(), 'ccl-perception-boundary-successors-'));
1124
- const perceptions = join(root, 'user-data', 'perceptions');
1125
- mkdirSync(perceptions, { recursive: true });
1126
- writeFileSync(join(perceptions, 'boundary-successors.ts'), `
1127
- import { ClawclawParallelPerception } from '@myclaw163/clawclaw-cli/perception-plugin';
1128
- export default class BoundarySuccessors extends ClawclawParallelPerception {
1129
- static manifest = {
1130
- apiVersion: 2,
1131
- id: 'visual.boundary_successors', name: 'Boundary successors',
1132
- description: 'Rejects a bridge across discarded reducer frames.',
1133
- subjectScope: 'others', produces: ['visual.boundary_successors'],
1134
- execution: 'parallel_analysis', boundaryBaseline: 'current_only',
1135
- };
1136
- lastFrameSeq = null;
1137
- analyze(input) {
1138
- return { previous_frame_seq: input.history.at(-1)?.frameSeq ?? null };
1139
- }
1140
- commit(frame, analysis) {
1141
- const bridged = this.lastFrameSeq !== null
1142
- && analysis.previous_frame_seq !== this.lastFrameSeq;
1143
- this.lastFrameSeq = frame.frameSeq;
1144
- return bridged ? [{
1145
- type: 'visual.boundary_successors',
1146
- dedupeKey: 'bridge:' + frame.frameSeq,
1147
- payload: {
1148
- reducer_previous_frame_seq: this.lastFrameSeq,
1149
- analysis_previous_frame_seq: analysis.previous_frame_seq,
1150
- },
1151
- }] : [];
1152
- }
1153
- reset() { this.lastFrameSeq = null; }
1154
- debugSnapshot() { return { last_frame_seq: this.lastFrameSeq }; }
1155
- }
1156
- `, 'utf8');
1157
- vi.stubEnv('CLAWCLAW_WORKSPACE_DIR', root);
1158
- const plugin = new ClawclawPerceptionPlugin({ modules: ['visual.boundary_successors'] });
1159
- const firstStored = stored(1, 1, stateAt(1, 900));
1160
- const context = pluginContext(plugin, firstStored.scope);
1161
- const journal = journals.get(plugin)!;
1162
-
1163
- try {
1164
- await plugin.startForReplay();
1165
- const first = journal.appendStateFrame(firstStored).frame;
1166
- const firstInput = epochInput(first);
1167
- expect((await plugin.commit(
1168
- firstInput,
1169
- await plugin.update(firstInput, context),
1170
- context,
1171
- )).events ?? []).toEqual([]);
1172
-
1173
- journal.appendStateFrame(stored(2, 2, stateAt(2, 906)));
1174
- journal.appendStateFrame(stored(3, 3, stateAt(3, 912)));
1175
- const fourth = journal.appendStateFrame(stored(4, 4, stateAt(4, 918))).frame;
1176
- const fifth = journal.appendStateFrame(stored(5, 5, stateAt(5, 924))).frame;
1177
- const sixth = journal.appendStateFrame(stored(6, 6, stateAt(6, 930))).frame;
1178
- const fourthInput = epochInput(fourth);
1179
- const fifthInput = epochInput(fifth);
1180
- const sixthInput = epochInput(sixth);
1181
- const [fourthComputation, fifthComputation, sixthComputation] = await Promise.all([
1182
- plugin.update(fourthInput, context),
1183
- plugin.update(fifthInput, context),
1184
- plugin.update(sixthInput, context),
1185
- ]);
1186
-
1187
- expect((await plugin.commit(fourthInput, fourthComputation, context)).events ?? [])
1188
- .toEqual([]);
1189
- const seventh = journal.appendStateFrame(stored(7, 7, stateAt(7, 936))).frame;
1190
- const seventhInput = epochInput(seventh);
1191
- const seventhComputation = await plugin.update(seventhInput, context);
1192
-
1193
- expect((await plugin.commit(fifthInput, fifthComputation, context)).events ?? [])
1194
- .toEqual([]);
1195
- expect((await plugin.commit(sixthInput, sixthComputation, context)).events ?? [])
1196
- .toEqual([]);
1197
- expect((await plugin.commit(seventhInput, seventhComputation, context)).events ?? [])
1198
- .toEqual([]);
1199
- expect(plugin.moduleStateSnapshot()).toEqual({
1200
- 'visual.boundary_successors': { last_frame_seq: 7 },
1201
- });
1202
-
1203
- const eighth = journal.appendStateFrame(stored(8, 8, stateAt(8, 942))).frame;
1204
- const eighthInput = epochInput(eighth);
1205
- expect((await plugin.commit(
1206
- eighthInput,
1207
- await plugin.update(eighthInput, context),
1208
- context,
1209
- )).events ?? []).toEqual([]);
1210
- } finally {
1211
- await plugin.stopForReplay();
1212
- vi.unstubAllEnvs();
1213
- rmSync(root, { recursive: true, force: true });
1214
- }
1215
- }, 20_000);
1216
-
1217
- it('starts every parallel module fresh after restart regardless of its old failure floor', async () => {
1218
- const root = mkdtempSync(join(tmpdir(), 'ccl-perception-recovery-floor-'));
1219
- const perceptions = join(root, 'user-data', 'perceptions');
1220
- mkdirSync(perceptions, { recursive: true });
1221
- const transientPath = join(perceptions, 'transient.ts');
1222
- const transientSource = (fail: boolean) => `
1223
- import { ClawclawParallelPerception } from '@myclaw163/clawclaw-cli/perception-plugin';
1224
- export default class Transient extends ClawclawParallelPerception {
1225
- static manifest = {
1226
- apiVersion: 2,
1227
- id: 'visual.transient', name: 'Transient', description: 'Fails one live analysis.',
1228
- subjectScope: 'others', produces: ['visual.transient'], execution: 'parallel_analysis',
1229
- };
1230
- frames = [];
1231
- analyze(input) {
1232
- if (${fail ? 'input.frame.frameSeq === 2' : 'false'}) {
1233
- throw new Error('transient_analysis_failure');
1234
- }
1235
- return {
1236
- frame_seq: input.frame.frameSeq,
1237
- history_frame_seqs: input.history.map((frame) => frame.frameSeq),
1238
- };
1239
- }
1240
- commit(_frame, analysis) { this.frames.push(analysis); }
1241
- reset() { this.frames = []; }
1242
- debugSnapshot() { return { frames: this.frames }; }
1243
- }
1244
- `;
1245
- writeFileSync(transientPath, transientSource(true), 'utf8');
1246
- writeFileSync(join(perceptions, 'recovery-healthy.ts'), `
1247
- import { ClawclawParallelPerception } from '@myclaw163/clawclaw-cli/perception-plugin';
1248
- export default class RecoveryHealthy extends ClawclawParallelPerception {
1249
- static manifest = {
1250
- apiVersion: 2,
1251
- id: 'visual.recovery_healthy', name: 'Recovery healthy',
1252
- description: 'Keeps its original replay slice.',
1253
- subjectScope: 'others', produces: ['visual.recovery_healthy'], execution: 'parallel_analysis',
1254
- };
1255
- frames = [];
1256
- analyze(input) {
1257
- return {
1258
- frame_seq: input.frame.frameSeq,
1259
- history_frame_seqs: input.history.map((frame) => frame.frameSeq),
1260
- };
1261
- }
1262
- commit(_frame, analysis) { this.frames.push(analysis); }
1263
- reset() { this.frames = []; }
1264
- debugSnapshot() { return { frames: this.frames }; }
1265
- }
1266
- `, 'utf8');
1267
- vi.stubEnv('CLAWCLAW_WORKSPACE_DIR', root);
1268
- const modules = ['visual.recovery_healthy', 'visual.transient'];
1269
- const plugin = new ClawclawPerceptionPlugin({ modules });
1270
- let recovered: ClawclawPerceptionPlugin | undefined;
1271
- const firstStored = stored(1, 1, stateAt(1, 900));
1272
- const context = pluginContext(plugin, firstStored.scope);
1273
- const journal = journals.get(plugin)!;
1274
-
1275
- try {
1276
- await plugin.startForReplay();
1277
- const first = journal.appendStateFrame(firstStored).frame;
1278
- const firstInput = epochInput(first);
1279
- await plugin.commit(firstInput, await plugin.update(firstInput, context), context);
1280
-
1281
- const second = journal.appendStateFrame(stored(2, 2, stateAt(2, 906))).frame;
1282
- const secondInput = epochInput(second);
1283
- const failed = await plugin.commit(
1284
- secondInput,
1285
- await plugin.update(secondInput, context),
1286
- context,
1287
- );
1288
- expect(failed.checkpoint).toMatchObject({
1289
- schema: 'clawclaw.perception-checkpoint.v1',
1290
- replayFromFrameSeq: 1,
1291
- parallelModuleHistoryFloors: { 'visual.transient': 3 },
1292
- parallelModuleReducerReplayStarts: { 'visual.transient': null },
1293
- });
1294
- expect(plugin.moduleStateSnapshot()).toEqual({
1295
- 'visual.recovery_healthy': {
1296
- frames: [
1297
- expect.objectContaining({ frame_seq: 1 }),
1298
- expect.objectContaining({ frame_seq: 2 }),
1299
- ],
1300
- },
1301
- 'visual.transient': { frames: [] },
1302
- });
1303
-
1304
- const third = journal.appendStateFrame(stored(3, 3, stateAt(3, 912))).frame;
1305
- const thirdInput = epochInput(third);
1306
- await plugin.commit(thirdInput, await plugin.update(thirdInput, context), context);
1307
- const liveSnapshot = plugin.moduleStateSnapshot();
1308
- expect(liveSnapshot).toMatchObject({
1309
- 'visual.recovery_healthy': { frames: [{}, {}, {}] },
1310
- 'visual.transient': {
1311
- frames: [{ frame_seq: 3, history_frame_seqs: [] }],
1312
- },
1313
- });
1314
- await plugin.stopForReplay();
1315
-
1316
- writeFileSync(transientPath, transientSource(false), 'utf8');
1317
- recovered = new ClawclawPerceptionPlugin({ modules });
1318
- journals.set(recovered, journal);
1319
- const recoveryContext = pluginContext(recovered, first.scope, 2, failed.checkpoint);
1320
- await recovered.start(recoveryContext);
1321
- await recovered.recover(recoveryContext);
1322
- expect(recovered.moduleStateSnapshot()).toEqual({
1323
- 'visual.recovery_healthy': { frames: [] },
1324
- 'visual.transient': { frames: [] },
1325
- });
1326
-
1327
- await recovered.commit(
1328
- thirdInput,
1329
- await recovered.update(thirdInput, recoveryContext),
1330
- recoveryContext,
1331
- );
1332
- expect(recovered.moduleStateSnapshot()).toEqual({
1333
- 'visual.recovery_healthy': {
1334
- frames: [{ frame_seq: 3, history_frame_seqs: [] }],
1335
- },
1336
- 'visual.transient': {
1337
- frames: [{ frame_seq: 3, history_frame_seqs: [] }],
1338
- },
1339
- });
1340
- } finally {
1341
- await Promise.allSettled([
1342
- plugin.stopForReplay(),
1343
- ...(recovered ? [recovered.stopForReplay()] : []),
1344
- ]);
1345
- vi.unstubAllEnvs();
1346
- rmSync(root, { recursive: true, force: true });
1347
- }
1348
- }, 30_000);
1349
-
1350
- it('persists live reducer boundaries but starts a new boundary after process restart', async () => {
1351
- const root = mkdtempSync(join(tmpdir(), 'ccl-perception-reducer-replay-'));
1352
- const perceptions = join(root, 'user-data', 'perceptions');
1353
- mkdirSync(perceptions, { recursive: true });
1354
- const sourcePath = join(perceptions, 'replay-exact.ts');
1355
- const source = (failFirst: boolean) => `
1356
- import { ClawclawParallelPerception } from '@myclaw163/clawclaw-cli/perception-plugin';
1357
- export default class ReplayExact extends ClawclawParallelPerception {
1358
- static manifest = {
1359
- apiVersion: 2,
1360
- id: 'visual.replay_exact', name: 'Replay exact',
1361
- description: 'Records only frames that reached the reducer.',
1362
- subjectScope: 'others', produces: ['visual.replay_exact'], execution: 'parallel_analysis',
1363
- };
1364
- frames = [];
1365
- analyze(input) {
1366
- if (${failFirst ? 'input.frame.frameSeq === 1' : 'false'}) {
1367
- throw new Error('first_analysis_failed');
1368
- }
1369
- return { frame_seq: input.frame.frameSeq };
1370
- }
1371
- commit(frame) {
1372
- this.frames.push(frame.frameSeq);
1373
- return [{
1374
- type: 'visual.replay_exact',
1375
- dedupeKey: 'frame:' + frame.frameSeq,
1376
- payload: { frame_seq: frame.frameSeq },
1377
- }];
1378
- }
1379
- reset() { this.frames = []; }
1380
- debugSnapshot() { return { frames: this.frames }; }
1381
- }
1382
- `;
1383
- writeFileSync(sourcePath, source(true), 'utf8');
1384
- vi.stubEnv('CLAWCLAW_WORKSPACE_DIR', root);
1385
- const modules = ['visual.replay_exact'];
1386
- const plugin = new ClawclawPerceptionPlugin({ modules });
1387
- let failureRecovered: ClawclawPerceptionPlugin | undefined;
1388
- let gapLive: ClawclawPerceptionPlugin | undefined;
1389
- let gapBoundaryRecovered: ClawclawPerceptionPlugin | undefined;
1390
- let gapRecovered: ClawclawPerceptionPlugin | undefined;
1391
- const firstStored = stored(1, 1, stateAt(1, 900));
1392
- const context = pluginContext(plugin, firstStored.scope);
1393
- const journal = journals.get(plugin)!;
1394
-
1395
- try {
1396
- await plugin.startForReplay();
1397
- const frames = Array.from({ length: 10 }, (_value, index) => (
1398
- journal.appendStateFrame(stored(
1399
- index + 1,
1400
- index + 1,
1401
- stateAt(index + 1, 900 + index * 6),
1402
- )).frame
1403
- ));
1404
- const inputs = frames.map((value) => epochInput(value));
1405
- const computations = await Promise.all(inputs.map((input) => plugin.update(input, context)));
1406
- let checkpoint: unknown;
1407
- for (let index = 0; index < inputs.length; index += 1) {
1408
- checkpoint = (await plugin.commit(inputs[index]!, computations[index]!, context)).checkpoint;
1409
- }
1410
- expect(plugin.moduleStateSnapshot()).toEqual({ 'visual.replay_exact': { frames: [] } });
1411
- expect(checkpoint).toMatchObject({
1412
- parallelModuleHistoryFloors: { 'visual.replay_exact': 2 },
1413
- parallelModuleReducerReplayStarts: { 'visual.replay_exact': null },
1414
- parallelModuleBaselinePending: { 'visual.replay_exact': true },
1415
- });
1416
- await plugin.stopForReplay();
1417
-
1418
- writeFileSync(sourcePath, source(false), 'utf8');
1419
- failureRecovered = new ClawclawPerceptionPlugin({ modules });
1420
- journals.set(failureRecovered, journal);
1421
- const recoveryContext = pluginContext(failureRecovered, firstStored.scope, 10, checkpoint);
1422
- await failureRecovered.start(recoveryContext);
1423
- await failureRecovered.recover(recoveryContext);
1424
- expect(failureRecovered.moduleStateSnapshot()).toEqual({
1425
- 'visual.replay_exact': { frames: [] },
1426
- });
1427
-
1428
- const eleventh = journal.appendStateFrame(stored(11, 11, stateAt(11, 960))).frame;
1429
- const eleventhInput = epochInput(eleventh);
1430
- const afterRecovery = await failureRecovered.commit(
1431
- eleventhInput,
1432
- await failureRecovered.update(eleventhInput, recoveryContext),
1433
- recoveryContext,
1434
- );
1435
- expect(failureRecovered.moduleStateSnapshot()).toEqual({
1436
- 'visual.replay_exact': { frames: [11] },
1437
- });
1438
- expect(afterRecovery.checkpoint).toMatchObject({
1439
- parallelModuleHistoryFloors: { 'visual.replay_exact': 11 },
1440
- parallelModuleReducerReplayStarts: { 'visual.replay_exact': 11 },
1441
- parallelModuleBaselinePending: { 'visual.replay_exact': false },
1442
- });
1443
- await failureRecovered.stopForReplay();
1444
-
1445
- gapLive = new ClawclawPerceptionPlugin({ modules });
1446
- const gapContext = pluginContext(gapLive, firstStored.scope);
1447
- const gapJournal = journals.get(gapLive)!;
1448
- await gapLive.startForReplay();
1449
- const gapFirst = gapJournal.appendStateFrame(firstStored).frame;
1450
- const gapFirstInput = epochInput(gapFirst);
1451
- await gapLive.commit(
1452
- gapFirstInput,
1453
- await gapLive.update(gapFirstInput, gapContext),
1454
- gapContext,
1455
- );
1456
- gapJournal.appendStateFrame(stored(2, 2, stateAt(2, 906)));
1457
- gapJournal.appendStateFrame(stored(3, 3, stateAt(3, 912)));
1458
- const gapFourth = gapJournal.appendStateFrame(stored(4, 4, stateAt(4, 918))).frame;
1459
- const gapFourthInput = epochInput(gapFourth);
1460
- const gapBoundaryResult = await gapLive.commit(
1461
- gapFourthInput,
1462
- await gapLive.update(gapFourthInput, gapContext),
1463
- gapContext,
1464
- );
1465
- expect(gapLive.moduleStateSnapshot()).toEqual({
1466
- 'visual.replay_exact': { frames: [] },
1467
- });
1468
- expect(gapBoundaryResult.checkpoint).toMatchObject({
1469
- replayFromFrameSeq: 4,
1470
- parallelModuleHistoryFloors: { 'visual.replay_exact': 4 },
1471
- parallelModuleReducerReplayStarts: { 'visual.replay_exact': null },
1472
- parallelModuleBaselinePending: { 'visual.replay_exact': true },
1473
- });
1474
-
1475
- gapBoundaryRecovered = new ClawclawPerceptionPlugin({ modules });
1476
- journals.set(gapBoundaryRecovered, gapJournal);
1477
- const gapBoundaryRecoveryContext = pluginContext(
1478
- gapBoundaryRecovered,
1479
- firstStored.scope,
1480
- 4,
1481
- gapBoundaryResult.checkpoint,
1482
- );
1483
- await gapBoundaryRecovered.start(gapBoundaryRecoveryContext);
1484
- await gapBoundaryRecovered.recover(gapBoundaryRecoveryContext);
1485
- expect(gapBoundaryRecovered.moduleStateSnapshot()).toEqual({
1486
- 'visual.replay_exact': { frames: [] },
1487
- });
1488
-
1489
- const gapFifth = gapJournal.appendStateFrame(stored(5, 5, stateAt(5, 924))).frame;
1490
- const gapFifthInput = epochInput(gapFifth);
1491
- const liveFifthComputation = await gapLive.update(gapFifthInput, gapContext);
1492
- const recoveredFifthComputation = await gapBoundaryRecovered.update(
1493
- gapFifthInput,
1494
- gapBoundaryRecoveryContext,
1495
- );
1496
- const gapResult = await gapLive.commit(
1497
- gapFifthInput,
1498
- liveFifthComputation,
1499
- gapContext,
1500
- );
1501
- const recoveredGapResult = await gapBoundaryRecovered.commit(
1502
- gapFifthInput,
1503
- recoveredFifthComputation,
1504
- gapBoundaryRecoveryContext,
1505
- );
1506
- expect(gapLive.moduleStateSnapshot()).toEqual({
1507
- 'visual.replay_exact': { frames: [5] },
1508
- });
1509
- expect(gapBoundaryRecovered.moduleStateSnapshot()).toEqual(
1510
- gapLive.moduleStateSnapshot(),
1511
- );
1512
- expect(recoveredGapResult.events).toEqual(gapResult.events);
1513
- expect(gapResult.checkpoint).toMatchObject({
1514
- replayFromFrameSeq: 4,
1515
- parallelModuleHistoryFloors: { 'visual.replay_exact': 4 },
1516
- parallelModuleReducerReplayStarts: { 'visual.replay_exact': 5 },
1517
- parallelModuleBaselinePending: { 'visual.replay_exact': false },
1518
- });
1519
- await gapLive.stopForReplay();
1520
- await gapBoundaryRecovered.stopForReplay();
1521
-
1522
- gapRecovered = new ClawclawPerceptionPlugin({ modules });
1523
- journals.set(gapRecovered, gapJournal);
1524
- const gapRecoveryContext = pluginContext(
1525
- gapRecovered,
1526
- firstStored.scope,
1527
- 5,
1528
- gapResult.checkpoint,
1529
- );
1530
- await gapRecovered.start(gapRecoveryContext);
1531
- await gapRecovered.recover(gapRecoveryContext);
1532
- expect(gapRecovered.moduleStateSnapshot()).toEqual({
1533
- 'visual.replay_exact': { frames: [] },
1534
- });
1535
- } finally {
1536
- await Promise.allSettled([
1537
- plugin.stopForReplay(),
1538
- ...(failureRecovered ? [failureRecovered.stopForReplay()] : []),
1539
- ...(gapLive ? [gapLive.stopForReplay()] : []),
1540
- ...(gapBoundaryRecovered ? [gapBoundaryRecovered.stopForReplay()] : []),
1541
- ...(gapRecovered ? [gapRecovered.stopForReplay()] : []),
1542
- ]);
1543
- vi.unstubAllEnvs();
1544
- rmSync(root, { recursive: true, force: true });
1545
- }
1546
- }, 30_000);
1547
-
1548
- it('replaces a partially-mutated reducer and rejects its old-generation successors', async () => {
1549
- const root = mkdtempSync(join(tmpdir(), 'ccl-perception-reducer-reset-'));
1550
- const perceptions = join(root, 'user-data', 'perceptions');
1551
- mkdirSync(perceptions, { recursive: true });
1552
- writeFileSync(join(perceptions, 'reducer-reset.ts'), `
1553
- import { ClawclawParallelPerception } from '@myclaw163/clawclaw-cli/perception-plugin';
1554
- export default class ReducerReset extends ClawclawParallelPerception {
1555
- static manifest = {
1556
- apiVersion: 2,
1557
- id: 'visual.reducer_reset', name: 'Reducer reset', description: 'Checks dirty reducer reset.',
1558
- subjectScope: 'others', produces: ['visual.reducer_reset'], execution: 'parallel_analysis',
1559
- };
1560
- mutations = 0;
1561
- analyze(input) { return { frame_seq: input.frame.frameSeq }; }
1562
- commit(frame, analysis) {
1563
- this.mutations += 1;
1564
- if (frame.frameSeq === 1) throw new Error('expected_commit_failure');
1565
- return [{
1566
- type: 'visual.reducer_reset', dedupeKey: 'reducer-reset:' + frame.frameSeq,
1567
- payload: { ...analysis, mutations: this.mutations },
1568
- }];
1569
- }
1570
- reset() {
1571
- this.mutations = 100;
1572
- throw new Error('expected_reset_failure');
1573
- }
1574
- debugSnapshot() { return { mutations: this.mutations }; }
1575
- }
1576
- `, 'utf8');
1577
- vi.stubEnv('CLAWCLAW_WORKSPACE_DIR', root);
1578
- const plugin = new ClawclawPerceptionPlugin({ modules: ['visual.reducer_reset'] });
1579
- const firstStored = stored(1, 1, stateAt(1, 900));
1580
- const context = pluginContext(plugin, firstStored.scope);
1581
- const journal = journals.get(plugin)!;
1582
- const first = journal.appendStateFrame(firstStored).frame;
1583
- const second = journal.appendStateFrame(stored(2, 2, stateAt(2, 906))).frame;
1584
- const firstInput = epochInput(first);
1585
- const secondInput = epochInput(second);
1586
-
1587
- try {
1588
- await plugin.startForReplay();
1589
- const [firstComputation, secondComputation] = await Promise.all([
1590
- plugin.update(firstInput, context),
1591
- plugin.update(secondInput, context),
1592
- ]);
1593
- expect((await plugin.commit(firstInput, firstComputation, context)).events ?? []).toEqual([]);
1594
- expect((await plugin.commit(secondInput, secondComputation, context)).events ?? []).toEqual([]);
1595
-
1596
- const third = journal.appendStateFrame(stored(3, 3, stateAt(3, 912))).frame;
1597
- const thirdInput = epochInput(third);
1598
- const thirdComputation = await plugin.update(thirdInput, context);
1599
- expect((await plugin.commit(thirdInput, thirdComputation, context)).events ?? []).toEqual([]);
1600
- expect(plugin.moduleStateSnapshot()).toEqual({ 'visual.reducer_reset': { mutations: 1 } });
1601
-
1602
- const fourth = journal.appendStateFrame(stored(4, 4, stateAt(4, 918))).frame;
1603
- const fourthInput = epochInput(fourth);
1604
- const fourthComputation = await plugin.update(fourthInput, context);
1605
- expect((await plugin.commit(fourthInput, fourthComputation, context)).events).toEqual([
1606
- expect.objectContaining({
1607
- type: 'visual.reducer_reset',
1608
- payload: expect.objectContaining({ frame_seq: 4, mutations: 2 }),
1609
- }),
1610
- ]);
1611
- expect(plugin.moduleStateSnapshot()).toEqual({ 'visual.reducer_reset': { mutations: 2 } });
1612
- } finally {
1613
- await plugin.stopForReplay();
1614
- vi.unstubAllEnvs();
1615
- rmSync(root, { recursive: true, force: true });
1616
- }
1617
- }, 20_000);
1618
-
1619
- it('turns a skipped computation range into a hard trajectory boundary', async () => {
1620
- const plugin = new ClawclawPerceptionPlugin({
1621
- modules: ['visual.motion'],
1622
- maxBackfillVisualFrames: 5,
1623
- });
1624
- const scope = stored(1, 1, {}).scope;
1625
- const diagnostics: Array<{ name: string; attributes?: Readonly<Record<string, unknown>> }> = [];
1626
- const context = pluginContext(
1627
- plugin,
1628
- scope,
1629
- 0,
1630
- undefined,
1631
- (name, attributes) => diagnostics.push({ name, attributes }),
1632
- );
1633
- const journal = journals.get(plugin)!;
1634
- await plugin.start(context);
1635
- const first = journal.appendStateFrame(stored(1, 1, stateAt(1, 900))).frame;
1636
- const firstInput = epochInput(first);
1637
- const firstComputation = await plugin.update(firstInput, context);
1638
- await plugin.commit(firstInput, firstComputation, context);
1639
- let target = first;
1640
- for (let tick = 1; tick <= 8; tick += 1) {
1641
- if (tick === 1) continue;
1642
- target = journal.appendStateFrame(
1643
- stored(tick, tick, stateAt(tick, 900 + (tick - 1) * 5)),
1644
- ).frame;
1645
- }
1646
-
1647
- const targetInput = epochInput(target);
1648
- const targetComputation = await plugin.update(targetInput, context);
1649
- const result = await plugin.commit(targetInput, targetComputation, context);
1650
- expect(result.checkpoint).toEqual({
1651
- schema: 'clawclaw.perception-checkpoint.v1',
1652
- replayFromFrameSeq: 8,
1653
- parallelModuleHistoryFloors: { 'visual.motion': 8 },
1654
- parallelModuleReducerReplayStarts: { 'visual.motion': 8 },
1655
- parallelModuleBaselinePending: { 'visual.motion': false },
1656
- });
1657
- expect(plugin.moduleStateSnapshot()).toMatchObject({
1658
- 'visual.motion': {
1659
- latest_tick: 8,
1660
- tracks: expect.arrayContaining([expect.objectContaining({
1661
- point_count: 1,
1662
- from_tick: 8,
1663
- to_tick: 8,
1664
- })]),
1665
- },
1666
- });
1667
- expect(diagnostics).toContainEqual(expect.objectContaining({
1668
- name: 'perception.catchup_frames_dropped',
1669
- attributes: expect.objectContaining({
1670
- dropped_state_frame_count: 6,
1671
- retained_from_frame_seq: 8,
1672
- }),
1673
- }));
1674
-
1675
- const recovered = new ClawclawPerceptionPlugin({
1676
- modules: ['visual.motion'],
1677
- maxBackfillVisualFrames: 5,
1678
- });
1679
- journals.set(recovered, journal);
1680
- const recoveryContext = pluginContext(recovered, scope, 8, result.checkpoint);
1681
- await recovered.start(recoveryContext);
1682
- await recovered.recover(recoveryContext);
1683
- expect(recovered.moduleStateSnapshot()).toEqual({
1684
- 'visual.motion': { latest_tick: null, tracks: [] },
1685
- });
1686
-
1687
- const ninth = journal.appendStateFrame(stored(9, 9, stateAt(9, 940))).frame;
1688
- const ninthInput = epochInput(ninth);
1689
- const [liveNinthComputation, recoveredNinthComputation] = await Promise.all([
1690
- plugin.update(ninthInput, context),
1691
- recovered.update(ninthInput, recoveryContext),
1692
- ]);
1693
- const [liveNinth, recoveredNinth] = await Promise.all([
1694
- plugin.commit(ninthInput, liveNinthComputation, context),
1695
- recovered.commit(ninthInput, recoveredNinthComputation, recoveryContext),
1696
- ]);
1697
- expect(recoveredNinth.events ?? []).toEqual([]);
1698
- expect(recovered.moduleStateSnapshot()).toMatchObject({
1699
- 'visual.motion': {
1700
- latest_tick: 9,
1701
- tracks: expect.arrayContaining([
1702
- expect.objectContaining({ from_tick: 9, to_tick: 9 }),
1703
- ]),
1704
- },
1705
- });
1706
- expect(plugin.moduleStateSnapshot()).toMatchObject({
1707
- 'visual.motion': {
1708
- latest_tick: 9,
1709
- tracks: expect.arrayContaining([
1710
- expect.objectContaining({ from_tick: 8, to_tick: 9 }),
1711
- ]),
1712
- },
1713
- });
1714
- await Promise.all([plugin.stopForReplay(), recovered.stopForReplay()]);
1715
- });
1716
-
1717
- it('commits a query-cut Event with the aggregate Perception plugin id', async () => {
1718
- const events = new MemoryEventRepository();
1719
- const motion = pluginFor('visual.motion');
1720
- const runtime = new Runtime({
1721
- adapterId: 'clawclaw',
1722
- accountId: 'account',
1723
- eventCatalog: createClawclawEventCatalog({
1724
- visualEventDelivery: { 'visual.player_moved': 'monitor_and_events' },
1725
- }),
1726
- eventRepository: events,
1727
- stateHistoryRepository: new MemoryStateHistoryRepository(),
1728
- runtimeEpochPlugins: [motion],
1729
- initialSegment: { kind: 'game', identity: 'game-1' },
1730
- });
1731
- await runtime.start();
1732
- const scope = runtime.scope();
1733
-
1734
- for (let tick = 1; tick <= 5; tick += 1) {
1735
- const accepted = await runtime.acceptInputBatch({
1736
- scope,
1737
- sourceId: 'clawclaw.game-ws',
1738
- connectionId: 'game-ws-1',
1739
- sourceKey: `game:${tick}`,
1740
- sourceSeq: tick,
1741
- domainTick: tick,
1742
- state: {
1743
- schema: 'clawclaw.runtime-state.v1',
1744
- stage: 'game',
1745
- transport: 'game_ws',
1746
- connection: 'connected',
1747
- cause: 'game_snapshot',
1748
- game_snapshot: {
1749
- status: 'fresh',
1750
- state: { phase: 'wandering', ...stateAt(tick, 900 + (tick - 1) * 6) },
1751
- },
1752
- },
1753
- events: [],
1754
- completeness: 'complete',
1755
- receivedAt: new Date(tick * 100).toISOString(),
1756
- });
1757
- await runtime.waitForEpochReadyView(accepted.epoch.epochSeq);
1758
- }
1759
-
1760
- const query = await runtime.acceptInputBatch({
1761
- scope,
1762
- sourceId: 'clawclaw.local-control',
1763
- connectionId: 'game-ws-1',
1764
- sourceKey: 'events-query:1',
1765
- sourceSeq: 1,
1766
- state: {
1767
- schema: 'clawclaw.runtime-state.v1',
1768
- stage: 'game',
1769
- transport: 'game_ws',
1770
- connection: 'connected',
1771
- cause: 'agent_events_query',
1772
- control: { type: 'events_query', request_id: 'query-1' },
1773
- game_snapshot: { status: 'not_updated' },
1774
- },
1775
- events: [],
1776
- completeness: 'complete',
1777
- coalescing: 'forbidden',
1778
- receivedAt: new Date(600).toISOString(),
1779
- });
1780
- await runtime.waitForEpochReadyView(query.epoch.epochSeq);
1781
-
1782
- expect(events.listCommittedEvents({
1783
- sessionId: scope.sessionId,
1784
- segmentId: scope.segmentId,
1785
- types: ['visual.player_moved'],
1786
- })).toMatchObject([{
1787
- epochSeq: query.epoch.epochSeq,
1788
- producerPluginId: CLAWCLAW_PERCEPTION_PLUGIN_ID,
1789
- deliveryClass: 'monitor_and_events',
1790
- }]);
1791
- await runtime.close();
1792
- });
1793
-
1794
- it('keeps same-batch follow and co-movement as independently typed canonical facts', async () => {
1795
- const plugin = new ClawclawPerceptionPlugin({
1796
- modules: ['visual.co_movement', 'visual.follow'],
1797
- });
1798
- const emitted = [];
1799
- for (let tick = 1; tick <= 13; tick += 1) {
1800
- const frame = stored(tick, tick, stateAt(tick, 900 + tick * 5, 840 + tick * 5));
1801
- emitted.push(...(await plugin.inspectFrame(frame)).proposals);
1802
- }
1803
- expect(emitted).toContainEqual(expect.objectContaining({
1804
- type: 'visual.players_moving_together',
1805
- payload: expect.objectContaining({ actors: [7, 9] }),
1806
- }));
1807
- expect(emitted).toContainEqual(expect.objectContaining({
1808
- type: 'visual.following',
1809
- payload: expect.objectContaining({
1810
- actors: [9, 7],
1811
- }),
1812
- }));
1813
- });
1814
-
1815
- it('skips all persisted perception history and resumes from a fresh baseline', async () => {
1816
- const journal = new MemoryStateHistoryRepository<unknown, Record<string, any>>();
1817
- const scope = stored(1, 1, {}).scope;
1818
- journal.openScope(scope);
1819
- for (let tick = 1; tick <= 8; tick += 1) {
1820
- journal.appendStateFrame(stored(tick, tick, stateAt(tick, 900 + tick * 5)));
1821
- }
1822
- const plugin = new ClawclawPerceptionPlugin({
1823
- modules: ['visual.motion'],
1824
- });
1825
- replayPlugins.add(plugin);
1826
- journals.set(plugin, journal);
1827
- const diagnostics: Array<{
1828
- name: string;
1829
- attributes?: Readonly<Record<string, unknown>>;
1830
- }> = [];
1831
- const context = pluginContext(
1832
- plugin,
1833
- scope,
1834
- 8,
1835
- undefined,
1836
- (name, attributes) => diagnostics.push({ name, attributes }),
1837
- );
1838
- const query = vi.spyOn(journal, 'queryStateFrames');
1839
-
1840
- await plugin.start(context);
1841
- await plugin.recover(context);
1842
-
1843
- expect(query).toHaveBeenCalledTimes(1);
1844
- expect(query).toHaveBeenCalledWith(expect.objectContaining({
1845
- toEpochSeq: 8,
1846
- order: 'desc',
1847
- limit: 1,
1848
- }));
1849
- expect(plugin.moduleStateSnapshot()).toEqual({
1850
- 'visual.motion': { latest_tick: null, tracks: [] },
1851
- });
1852
- expect(diagnostics).toContainEqual(expect.objectContaining({
1853
- name: 'perception.recovery_history_skipped',
1854
- attributes: expect.objectContaining({
1855
- skipped_through_frame_seq: 8,
1856
- resume_from_frame_seq: 9,
1857
- }),
1858
- }));
1859
-
1860
- const ninth = journal.appendStateFrame(stored(9, 9, stateAt(9, 945))).frame;
1861
- const ninthInput = epochInput(ninth);
1862
- const result = await plugin.commit(
1863
- ninthInput,
1864
- await plugin.update(ninthInput, context),
1865
- context,
1866
- );
1867
- expect(result.events ?? []).toEqual([]);
1868
- expect(plugin.moduleStateSnapshot()).toMatchObject({
1869
- 'visual.motion': {
1870
- latest_tick: 9,
1871
- tracks: expect.arrayContaining([expect.objectContaining({
1872
- from_tick: 9,
1873
- to_tick: 9,
1874
- })]),
1875
- },
1876
- });
1877
- });
1878
- });