@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,865 +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 { afterEach, describe, expect, it, vi } from 'vitest';
5
- import type { PerceptionAnalysisInput, PerceptionFrame } from './contracts.js';
6
- import {
7
- PERCEPTION_ANALYSIS_IDLE_WORKER_TIMEOUT_MS,
8
- PerceptionAnalysisThreadPool,
9
- perceptionAnalysisWorkerStartModuleId,
10
- } from './perception-analysis-thread-pool.js';
11
- import { PerceptionModuleLoader } from './perception-module-loader.js';
12
- import { perceptionTestGameState } from './perception-test-fixtures.js';
13
- import { CLAWCLAW_PERCEPTION_SPATIAL_FACTS } from './spatial-facts.js';
14
-
15
- const frame: PerceptionFrame = {
16
- frameKey: 'pool-frame',
17
- frameSeq: 1,
18
- tick: 1,
19
- timeMs: 100,
20
- tickDelta: null,
21
- continuousFromPrevious: false,
22
- gameState: perceptionTestGameState(1),
23
- observation: {
24
- players: [{
25
- id: 'self:1',
26
- name: 'Observer',
27
- seat: 1,
28
- observer: true,
29
- alive: true,
30
- x: 900,
31
- y: 2200,
32
- room: '导航仓',
33
- }],
34
- corpses: [],
35
- visibleSetComplete: true,
36
- },
37
- };
38
- const input: PerceptionAnalysisInput = { frame, history: [], gapBefore: false };
39
-
40
- describe('PerceptionAnalysisThreadPool', () => {
41
- const pools: PerceptionAnalysisThreadPool[] = [];
42
- const roots: string[] = [];
43
-
44
- function sourceModule(loader: PerceptionModuleLoader, moduleId: string) {
45
- const root = mkdtempSync(join(tmpdir(), 'ccl-perception-thread-source-'));
46
- roots.push(root);
47
- const sourcePath = join(root, 'module.ts');
48
- writeFileSync(sourcePath, `
49
- import { ClawclawParallelPerception } from 'clawclaw-cli/perception-plugin';
50
- export default class extends ClawclawParallelPerception {
51
- static manifest = {
52
- apiVersion: 2,
53
- id: ${JSON.stringify(moduleId)}, name: 'Source module', description: 'Source-only Worker fixture.',
54
- subjectScope: 'others', produces: [${JSON.stringify(moduleId)}], execution: 'parallel_analysis',
55
- } as const;
56
- analyze() { return {}; }
57
- commit() { return []; }
58
- }
59
- `, 'utf8');
60
- const manifest = {
61
- apiVersion: 2 as const,
62
- id: moduleId,
63
- name: 'Source module',
64
- description: 'Source-only Worker fixture.',
65
- subjectScope: 'others' as const,
66
- produces: [moduleId],
67
- execution: 'parallel_analysis' as const,
68
- };
69
- return loader.threadSpec({
70
- ...manifest,
71
- manifest,
72
- sourcePath,
73
- sourceRoot: root,
74
- });
75
- }
76
-
77
- afterEach(async () => {
78
- vi.restoreAllMocks();
79
- vi.useRealTimers();
80
- await Promise.allSettled(pools.splice(0).map((pool) => pool.stop()));
81
- for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });
82
- });
83
-
84
- it('stops immediately while the adaptive pool is still starting', async () => {
85
- const loader = new PerceptionModuleLoader();
86
- const pool = new PerceptionAnalysisThreadPool({
87
- modules: [sourceModule(loader, 'visual.visibility')],
88
- loader: loader.threadConfig(),
89
- spatialFacts: CLAWCLAW_PERCEPTION_SPATIAL_FACTS,
90
- maxWorkers: 1,
91
- });
92
- pools.push(pool);
93
- const starting = pool.start().then(
94
- () => undefined,
95
- (error: unknown) => error,
96
- );
97
- const startedAt = performance.now();
98
-
99
- await pool.stop();
100
-
101
- expect(performance.now() - startedAt).toBeLessThan(2_000);
102
- expect(await starting).toBeInstanceOf(Error);
103
- expect(pool.snapshot()).toMatchObject({
104
- state: 'stopped',
105
- workerCount: 0,
106
- queuedBatchCount: 0,
107
- inFlightBatchCount: 0,
108
- });
109
- loader.stop();
110
- });
111
-
112
- it('attributes a Worker-only module load failure to its module id', async () => {
113
- const root = mkdtempSync(join(tmpdir(), 'ccl-perception-thread-bad-start-'));
114
- roots.push(root);
115
- const sourcePath = join(root, 'bad-start.ts');
116
- writeFileSync(sourcePath, `
117
- import { ClawclawParallelPerception } from 'clawclaw-cli/perception-plugin';
118
- throw new Error('expected_worker_only_load_failure');
119
- export default class BadStart extends ClawclawParallelPerception {
120
- static manifest = {
121
- apiVersion: 2,
122
- id: 'visual.bad_start', name: 'Bad start', description: 'Fails only in this Worker fixture.',
123
- subjectScope: 'others', produces: ['visual.bad_start'], execution: 'parallel_analysis',
124
- } as const;
125
- analyze() { return {}; }
126
- commit() { return []; }
127
- }
128
- `, 'utf8');
129
- const manifest = {
130
- apiVersion: 2 as const,
131
- id: 'visual.bad_start',
132
- name: 'Bad start',
133
- description: 'Fails only in this Worker fixture.',
134
- subjectScope: 'others' as const,
135
- produces: ['visual.bad_start'],
136
- execution: 'parallel_analysis' as const,
137
- };
138
- const loader = new PerceptionModuleLoader();
139
- const pool = new PerceptionAnalysisThreadPool({
140
- modules: [loader.threadSpec({
141
- ...manifest,
142
- manifest,
143
- sourcePath,
144
- sourceRoot: root,
145
- })],
146
- loader: loader.threadConfig(),
147
- spatialFacts: CLAWCLAW_PERCEPTION_SPATIAL_FACTS,
148
- maxWorkers: 1,
149
- });
150
- pools.push(pool);
151
-
152
- const error = await pool.start().then(
153
- () => undefined,
154
- (reason: unknown) => reason,
155
- );
156
-
157
- expect(error).toBeInstanceOf(Error);
158
- expect((error as Error).message).toBe('perception_analysis_worker_module_load_failed');
159
- expect(perceptionAnalysisWorkerStartModuleId(error)).toBe('visual.bad_start');
160
- loader.stop();
161
- });
162
-
163
- it('prewarms two Workers, scales to ten, and retires continuously idle excess under light traffic', async () => {
164
- const root = mkdtempSync(join(tmpdir(), 'ccl-perception-thread-scale-'));
165
- const sourcePath = join(root, 'pressure.ts');
166
- const releaseMarker = join(root, 'release');
167
- writeFileSync(sourcePath, `
168
- import { existsSync } from 'node:fs';
169
- import { ClawclawParallelPerception } from 'clawclaw-cli/perception-plugin';
170
- export default class Pressure extends ClawclawParallelPerception {
171
- static manifest = {
172
- apiVersion: 2,
173
- id: 'visual.pressure', name: 'Pressure', description: 'Scaling fixture.',
174
- subjectScope: 'others', produces: ['visual.pressure'], execution: 'parallel_analysis',
175
- } as const;
176
- async analyze() {
177
- while (!existsSync(${JSON.stringify(releaseMarker)})) {
178
- await new Promise((resolve) => setTimeout(resolve, 10));
179
- }
180
- return {};
181
- }
182
- commit() { return []; }
183
- }
184
- `, 'utf8');
185
- const manifest = {
186
- apiVersion: 2 as const,
187
- id: 'visual.pressure',
188
- name: 'Pressure',
189
- description: 'Scaling fixture.',
190
- subjectScope: 'others' as const,
191
- produces: ['visual.pressure'],
192
- execution: 'parallel_analysis' as const,
193
- };
194
- const loader = new PerceptionModuleLoader();
195
- const diagnostics: Array<{
196
- name: string;
197
- attributes?: Readonly<Record<string, unknown>>;
198
- severity?: string;
199
- }> = [];
200
- const pool = new PerceptionAnalysisThreadPool({
201
- modules: [loader.threadSpec({
202
- ...manifest,
203
- manifest,
204
- sourcePath,
205
- sourceRoot: root,
206
- })],
207
- loader: loader.threadConfig(),
208
- spatialFacts: CLAWCLAW_PERCEPTION_SPATIAL_FACTS,
209
- maxWorkers: 10,
210
- diagnostic: (name, attributes, severity) => diagnostics.push({ name, attributes, severity }),
211
- });
212
- pools.push(pool);
213
- try {
214
- await pool.start();
215
-
216
- expect(pool.snapshot()).toMatchObject({
217
- state: 'running',
218
- minWorkers: 2,
219
- maxWorkers: 10,
220
- workerCount: 2,
221
- idleWorkerCount: 2,
222
- startedWorkerCount: 2,
223
- retiredWorkerCount: 0,
224
- });
225
- expect(pool.snapshot().startupWorkerHeapUsedBytes).toBeGreaterThan(0);
226
- expect(diagnostics).toContainEqual({
227
- name: 'perception.analysis_pool.started',
228
- severity: 'info',
229
- attributes: expect.objectContaining({
230
- worker_count: 2,
231
- min_worker_count: 2,
232
- max_worker_count: 10,
233
- started_worker_count: 2,
234
- retired_worker_count: 0,
235
- duration_ms: expect.any(Number),
236
- worker_max_old_generation_mb: 64,
237
- startup_worker_heap_used_bytes: expect.any(Number),
238
- peak_worker_heap_used_bytes: expect.any(Number),
239
- }),
240
- });
241
-
242
- const batches = Array.from({ length: 10 }, () => pool.analyze(
243
- [{ moduleId: 'visual.pressure', input }],
244
- new AbortController().signal,
245
- ));
246
- await vi.waitFor(() => expect(pool.snapshot()).toMatchObject({
247
- workerCount: 10,
248
- busyWorkerCount: 10,
249
- queuedBatchCount: 0,
250
- inFlightBatchCount: 10,
251
- startedWorkerCount: 10,
252
- }), { timeout: 10_000 });
253
- await expect(pool.analyze(
254
- [{ moduleId: 'visual.pressure', input }],
255
- new AbortController().signal,
256
- )).rejects.toThrow('perception_analysis_window_full');
257
- expect(diagnostics.filter(({ name, attributes }) => (
258
- name === 'perception.analysis_worker.started' && attributes?.trigger === 'prewarm'
259
- ))).toHaveLength(2);
260
- expect(diagnostics.filter(({ name, severity }) => (
261
- name === 'perception.analysis_worker.started' && severity === 'info'
262
- ))).toHaveLength(10);
263
- expect(diagnostics.filter(({ name, attributes }) => (
264
- name === 'perception.analysis_worker.started' && attributes?.trigger === 'pressure'
265
- ))).toHaveLength(8);
266
-
267
- let idleNow = performance.now();
268
- vi.spyOn(performance, 'now').mockImplementation(() => idleNow);
269
- vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
270
- writeFileSync(releaseMarker, '', 'utf8');
271
- const results = await Promise.all(batches);
272
- expect(results.every(({ results: batchResults }) => (
273
- batchResults[0]?.outcome === 'fulfilled'
274
- ))).toBe(true);
275
- expect(pool.snapshot()).toMatchObject({
276
- workerCount: 10,
277
- idleWorkerCount: 10,
278
- queuedBatchCount: 0,
279
- inFlightBatchCount: 0,
280
- });
281
-
282
- // One Worker remains active every 100 ms. The other eight expanded
283
- // Workers must still accrue continuous idle time instead of having one
284
- // pool-wide timer reset by each new frame.
285
- const lightFrameCount = Math.ceil(
286
- PERCEPTION_ANALYSIS_IDLE_WORKER_TIMEOUT_MS / 100,
287
- ) + 5;
288
- const lightResults = [];
289
- for (let index = 0; index < lightFrameCount; index += 1) {
290
- lightResults.push(await pool.analyze(
291
- [{ moduleId: 'visual.pressure', input }],
292
- new AbortController().signal,
293
- ));
294
- idleNow += 100;
295
- await vi.advanceTimersByTimeAsync(100);
296
- }
297
- expect(lightResults).toHaveLength(lightFrameCount);
298
- expect(lightResults.every(({ results: batchResults }) => (
299
- batchResults[0]?.outcome === 'fulfilled'
300
- ))).toBe(true);
301
- vi.restoreAllMocks();
302
- vi.useRealTimers();
303
- await vi.waitFor(() => expect(pool.snapshot()).toMatchObject({
304
- workerCount: 2,
305
- idleWorkerCount: 2,
306
- startedWorkerCount: 10,
307
- retiredWorkerCount: 8,
308
- }), { timeout: 5_000 });
309
- expect(diagnostics.filter(({ name, attributes }) => (
310
- name === 'perception.analysis_worker.retired' && attributes?.reason === 'idle'
311
- ))).toHaveLength(8);
312
- expect(diagnostics.filter(({ name, attributes, severity }) => (
313
- name === 'perception.analysis_worker.retired'
314
- && attributes?.reason === 'idle'
315
- && severity === 'info'
316
- ))).toHaveLength(8);
317
-
318
- await pool.stop();
319
- expect(diagnostics).toContainEqual({
320
- name: 'perception.analysis_pool.stopped',
321
- severity: 'info',
322
- attributes: expect.objectContaining({
323
- worker_count: 0,
324
- min_worker_count: 2,
325
- max_worker_count: 10,
326
- started_worker_count: 10,
327
- retired_worker_count: 10,
328
- worker_heap_used_bytes: 0,
329
- peak_worker_heap_used_bytes: expect.any(Number),
330
- }),
331
- });
332
- } finally {
333
- vi.restoreAllMocks();
334
- vi.useRealTimers();
335
- await pool.stop();
336
- loader.stop();
337
- rmSync(root, { recursive: true, force: true });
338
- }
339
- }, 20_000);
340
-
341
- it('does not let an expiring idle timer retire Workers needed by new pressure', async () => {
342
- const root = mkdtempSync(join(tmpdir(), 'ccl-perception-thread-idle-race-'));
343
- const sourcePath = join(root, 'pressure.ts');
344
- const blockMarker = join(root, 'block');
345
- const releaseMarker = join(root, 'release');
346
- writeFileSync(sourcePath, `
347
- import { existsSync } from 'node:fs';
348
- import { ClawclawParallelPerception } from 'clawclaw-cli/perception-plugin';
349
- export default class Pressure extends ClawclawParallelPerception {
350
- static manifest = {
351
- apiVersion: 2,
352
- id: 'visual.pressure-race', name: 'Pressure race', description: 'Idle race fixture.',
353
- subjectScope: 'others', produces: ['visual.pressure-race'], execution: 'parallel_analysis',
354
- } as const;
355
- async analyze() {
356
- while (existsSync(${JSON.stringify(blockMarker)}) && !existsSync(${JSON.stringify(releaseMarker)})) {
357
- await new Promise((resolve) => setTimeout(resolve, 10));
358
- }
359
- return {};
360
- }
361
- commit() { return []; }
362
- }
363
- `, 'utf8');
364
- const manifest = {
365
- apiVersion: 2 as const,
366
- id: 'visual.pressure-race',
367
- name: 'Pressure race',
368
- description: 'Idle race fixture.',
369
- subjectScope: 'others' as const,
370
- produces: ['visual.pressure-race'],
371
- execution: 'parallel_analysis' as const,
372
- };
373
- const diagnostics: Array<{
374
- name: string;
375
- attributes?: Readonly<Record<string, unknown>>;
376
- severity?: string;
377
- }> = [];
378
- const loader = new PerceptionModuleLoader();
379
- const pool = new PerceptionAnalysisThreadPool({
380
- modules: [loader.threadSpec({
381
- ...manifest,
382
- manifest,
383
- sourcePath,
384
- sourceRoot: root,
385
- })],
386
- loader: loader.threadConfig(),
387
- spatialFacts: CLAWCLAW_PERCEPTION_SPATIAL_FACTS,
388
- maxWorkers: 4,
389
- diagnostic: (name, attributes, severity) => diagnostics.push({ name, attributes, severity }),
390
- });
391
- pools.push(pool);
392
- try {
393
- writeFileSync(blockMarker, '', 'utf8');
394
- await pool.start();
395
- const initialPressure = Array.from({ length: 4 }, () => pool.analyze(
396
- [{ moduleId: 'visual.pressure-race', input }],
397
- new AbortController().signal,
398
- ));
399
- await vi.waitFor(() => expect(pool.snapshot()).toMatchObject({
400
- workerCount: 4,
401
- busyWorkerCount: 4,
402
- inFlightBatchCount: 4,
403
- }), { timeout: 10_000 });
404
- let idleNow = performance.now();
405
- vi.spyOn(performance, 'now').mockImplementation(() => idleNow);
406
- vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
407
- writeFileSync(releaseMarker, '', 'utf8');
408
- await Promise.all(initialPressure);
409
- expect(pool.snapshot()).toMatchObject({ workerCount: 4, idleWorkerCount: 4 });
410
-
411
- rmSync(releaseMarker, { force: true });
412
- idleNow += PERCEPTION_ANALYSIS_IDLE_WORKER_TIMEOUT_MS - 100;
413
- await vi.advanceTimersByTimeAsync(PERCEPTION_ANALYSIS_IDLE_WORKER_TIMEOUT_MS - 100);
414
- const competingPressure = Array.from({ length: 4 }, () => pool.analyze(
415
- [{ moduleId: 'visual.pressure-race', input }],
416
- new AbortController().signal,
417
- ));
418
- await vi.advanceTimersByTimeAsync(0);
419
- expect(pool.snapshot()).toMatchObject({
420
- workerCount: 4,
421
- inFlightBatchCount: 4,
422
- });
423
-
424
- // The old idle deadline now expires while all four batches need the
425
- // existing capacity. Its callback must recompute demand and retire none.
426
- idleNow += 100;
427
- await vi.advanceTimersByTimeAsync(100);
428
- expect(pool.snapshot()).toMatchObject({
429
- workerCount: 4,
430
- inFlightBatchCount: 4,
431
- retiredWorkerCount: 0,
432
- });
433
- expect(diagnostics.filter(({ name, attributes }) => (
434
- name === 'perception.analysis_worker.retired' && attributes?.reason === 'idle'
435
- ))).toHaveLength(0);
436
-
437
- writeFileSync(releaseMarker, '', 'utf8');
438
- const results = await Promise.all(competingPressure);
439
- expect(results.every(({ results: batchResults }) => (
440
- batchResults[0]?.outcome === 'fulfilled'
441
- ))).toBe(true);
442
- vi.restoreAllMocks();
443
- vi.useRealTimers();
444
- } finally {
445
- vi.restoreAllMocks();
446
- vi.useRealTimers();
447
- await pool.stop();
448
- loader.stop();
449
- rmSync(root, { recursive: true, force: true });
450
- }
451
- });
452
-
453
- it('directly imports a custom analyzer and replaces only an aborted frame slot', async () => {
454
- const root = mkdtempSync(join(tmpdir(), 'ccl-perception-thread-abort-'));
455
- const sourcePath = join(root, 'slow.ts');
456
- mkdirSync(root, { recursive: true });
457
- writeFileSync(sourcePath, `
458
- import { ClawclawParallelPerception } from 'clawclaw-cli/perception-plugin';
459
- export default class Slow extends ClawclawParallelPerception {
460
- static manifest = {
461
- apiVersion: 2,
462
- id: 'visual.slow', name: 'Slow', description: 'Abort fixture.',
463
- subjectScope: 'others', produces: ['visual.slow'], execution: 'parallel_analysis',
464
- } as const;
465
- async analyze() { await new Promise((resolve) => setTimeout(resolve, 5000)); return {}; }
466
- commit() { return []; }
467
- }
468
- `, 'utf8');
469
- const manifest = {
470
- apiVersion: 2 as const,
471
- id: 'visual.slow',
472
- name: 'Slow',
473
- description: 'Abort fixture.',
474
- subjectScope: 'others' as const,
475
- produces: ['visual.slow'],
476
- execution: 'parallel_analysis' as const,
477
- };
478
- const loader = new PerceptionModuleLoader();
479
- const pool = new PerceptionAnalysisThreadPool({
480
- modules: [loader.threadSpec({
481
- ...manifest,
482
- manifest,
483
- sourcePath,
484
- sourceRoot: root,
485
- })],
486
- loader: loader.threadConfig(),
487
- spatialFacts: CLAWCLAW_PERCEPTION_SPATIAL_FACTS,
488
- maxWorkers: 1,
489
- });
490
- pools.push(pool);
491
- try {
492
- await pool.start();
493
- const controller = new AbortController();
494
- const analysis = pool.analyze(
495
- [{ moduleId: 'visual.slow', input }],
496
- controller.signal,
497
- );
498
- await vi.waitFor(() => expect(pool.snapshot().busyWorkerCount).toBe(1));
499
- controller.abort(new Error('stale_frame_aborted'));
500
- await expect(analysis).rejects.toThrow('stale_frame_aborted');
501
- await vi.waitFor(() => expect(pool.snapshot()).toMatchObject({
502
- workerCount: 1,
503
- idleWorkerCount: 1,
504
- startedWorkerCount: 2,
505
- retiredWorkerCount: 1,
506
- inFlightBatchCount: 0,
507
- }));
508
- } finally {
509
- await pool.stop();
510
- loader.stop();
511
- rmSync(root, { recursive: true, force: true });
512
- }
513
- });
514
-
515
- it('gives every same-frame module an independent immutable input and a fresh analyzer', async () => {
516
- const root = mkdtempSync(join(tmpdir(), 'ccl-perception-thread-isolation-'));
517
- const mutatorPath = join(root, 'mutator.ts');
518
- const observerPath = join(root, 'observer.ts');
519
- writeFileSync(mutatorPath, `
520
- import { ClawclawParallelPerception } from 'clawclaw-cli/perception-plugin';
521
- export default class Mutator extends ClawclawParallelPerception {
522
- static manifest = {
523
- apiVersion: 2,
524
- id: 'visual.mutator', name: 'Mutator', description: 'Mutation fixture.',
525
- subjectScope: 'others', produces: ['visual.mutator'], execution: 'parallel_analysis',
526
- } as const;
527
- analyze(input) { input.frame.observation.players[0].x = 9999; return {}; }
528
- commit() { return []; }
529
- }
530
- `, 'utf8');
531
- writeFileSync(observerPath, `
532
- import { ClawclawParallelPerception } from 'clawclaw-cli/perception-plugin';
533
- export default class Observer extends ClawclawParallelPerception {
534
- static manifest = {
535
- apiVersion: 2,
536
- id: 'visual.observer', name: 'Observer', description: 'Isolation fixture.',
537
- subjectScope: 'others', produces: ['visual.observer'], execution: 'parallel_analysis',
538
- } as const;
539
- calls = 0;
540
- analyze(input) { this.calls += 1; return { seen: input.frame.observation.players[0].x, calls: this.calls }; }
541
- commit() { return []; }
542
- }
543
- `, 'utf8');
544
- const loader = new PerceptionModuleLoader();
545
- const mutatorManifest = {
546
- apiVersion: 2 as const,
547
- id: 'visual.mutator', name: 'Mutator', description: 'Mutation fixture.',
548
- subjectScope: 'others' as const, produces: ['visual.mutator'], execution: 'parallel_analysis' as const,
549
- };
550
- const observerManifest = {
551
- apiVersion: 2 as const,
552
- id: 'visual.observer', name: 'Observer', description: 'Isolation fixture.',
553
- subjectScope: 'others' as const, produces: ['visual.observer'], execution: 'parallel_analysis' as const,
554
- };
555
- const pool = new PerceptionAnalysisThreadPool({
556
- modules: [
557
- loader.threadSpec({
558
- ...mutatorManifest,
559
- manifest: mutatorManifest,
560
- sourcePath: mutatorPath,
561
- sourceRoot: root,
562
- }),
563
- loader.threadSpec({
564
- ...observerManifest,
565
- manifest: observerManifest,
566
- sourcePath: observerPath,
567
- sourceRoot: root,
568
- }),
569
- ],
570
- loader: loader.threadConfig(),
571
- spatialFacts: CLAWCLAW_PERCEPTION_SPATIAL_FACTS,
572
- maxWorkers: 1,
573
- });
574
- pools.push(pool);
575
- try {
576
- await pool.start();
577
- const run = () => pool.analyze([
578
- { moduleId: 'visual.mutator', input },
579
- { moduleId: 'visual.observer', input },
580
- ], new AbortController().signal);
581
-
582
- const first = await run();
583
- const second = await run();
584
-
585
- expect(first.results).toMatchObject([
586
- { moduleId: 'visual.mutator', outcome: 'rejected' },
587
- {
588
- moduleId: 'visual.observer',
589
- outcome: 'fulfilled',
590
- analysis: { seen: 900, calls: 1 },
591
- },
592
- ]);
593
- expect(second.results).toMatchObject([
594
- { moduleId: 'visual.mutator', outcome: 'rejected' },
595
- {
596
- moduleId: 'visual.observer',
597
- outcome: 'fulfilled',
598
- analysis: { seen: 900, calls: 1 },
599
- },
600
- ]);
601
- expect(frame.observation.players[0]?.x).toBe(900);
602
- } finally {
603
- await pool.stop();
604
- loader.stop();
605
- rmSync(root, { recursive: true, force: true });
606
- }
607
- });
608
-
609
- it('rejects busy and queued batches and terminates their Worker on stop', async () => {
610
- const root = mkdtempSync(join(tmpdir(), 'ccl-perception-thread-stop-'));
611
- const sourcePath = join(root, 'slow.ts');
612
- const delayMarker = join(root, 'delay-replacement');
613
- writeFileSync(sourcePath, `
614
- import { existsSync } from 'node:fs';
615
- import { ClawclawParallelPerception } from 'clawclaw-cli/perception-plugin';
616
- if (existsSync(${JSON.stringify(delayMarker)})) {
617
- await new Promise((resolve) => setTimeout(resolve, 5000));
618
- }
619
- export default class SlowStop extends ClawclawParallelPerception {
620
- static manifest = {
621
- apiVersion: 2,
622
- id: 'visual.slow_stop', name: 'Slow stop', description: 'Stop fixture.',
623
- subjectScope: 'others', produces: ['visual.slow_stop'], execution: 'parallel_analysis',
624
- } as const;
625
- async analyze() { await new Promise((resolve) => setTimeout(resolve, 5000)); return {}; }
626
- commit() { return []; }
627
- }
628
- `, 'utf8');
629
- const manifest = {
630
- apiVersion: 2 as const,
631
- id: 'visual.slow_stop', name: 'Slow stop', description: 'Stop fixture.',
632
- subjectScope: 'others' as const, produces: ['visual.slow_stop'], execution: 'parallel_analysis' as const,
633
- };
634
- const loader = new PerceptionModuleLoader();
635
- const pool = new PerceptionAnalysisThreadPool({
636
- modules: [loader.threadSpec({
637
- ...manifest,
638
- manifest,
639
- sourcePath,
640
- sourceRoot: root,
641
- })],
642
- loader: loader.threadConfig(),
643
- spatialFacts: CLAWCLAW_PERCEPTION_SPATIAL_FACTS,
644
- maxWorkers: 2,
645
- });
646
- pools.push(pool);
647
- try {
648
- await pool.start();
649
- writeFileSync(delayMarker, '', 'utf8');
650
- const slot = [...(pool as any).slots][0];
651
- await (pool as any).retireSlot(slot, 'busy_queue_stop_test');
652
- await vi.waitFor(() => expect(pool.snapshot()).toMatchObject({
653
- workerCount: 2,
654
- idleWorkerCount: 1,
655
- }));
656
- const first = pool.analyze(
657
- [{ moduleId: 'visual.slow_stop', input }],
658
- new AbortController().signal,
659
- );
660
- const second = pool.analyze(
661
- [{ moduleId: 'visual.slow_stop', input }],
662
- new AbortController().signal,
663
- );
664
- const outcomes = Promise.allSettled([first, second]);
665
- await vi.waitFor(() => expect(pool.snapshot()).toMatchObject({
666
- busyWorkerCount: 1,
667
- queuedBatchCount: 1,
668
- inFlightBatchCount: 2,
669
- }));
670
- await expect(pool.analyze(
671
- [{ moduleId: 'visual.slow_stop', input }],
672
- new AbortController().signal,
673
- )).rejects.toThrow('perception_analysis_window_full');
674
- const startedAt = performance.now();
675
-
676
- await pool.stop();
677
-
678
- expect(performance.now() - startedAt).toBeLessThan(2_000);
679
- expect(await outcomes).toEqual([
680
- expect.objectContaining({ status: 'rejected' }),
681
- expect.objectContaining({ status: 'rejected' }),
682
- ]);
683
- expect(pool.snapshot()).toMatchObject({
684
- state: 'stopped',
685
- workerCount: 0,
686
- queuedBatchCount: 0,
687
- inFlightBatchCount: 0,
688
- });
689
- } finally {
690
- await pool.stop();
691
- loader.stop();
692
- rmSync(root, { recursive: true, force: true });
693
- }
694
- });
695
-
696
- it('replaces a crashed Worker even when diagnostic callbacks throw', async () => {
697
- const loader = new PerceptionModuleLoader();
698
- const pool = new PerceptionAnalysisThreadPool({
699
- modules: [sourceModule(loader, 'visual.visibility')],
700
- loader: loader.threadConfig(),
701
- spatialFacts: CLAWCLAW_PERCEPTION_SPATIAL_FACTS,
702
- maxWorkers: 1,
703
- diagnostic: () => {
704
- throw new Error('diagnostic_callback_failed');
705
- },
706
- });
707
- pools.push(pool);
708
- try {
709
- await pool.start();
710
- const slot = [...(pool as any).slots][0];
711
- await slot.worker.terminate();
712
- await vi.waitFor(() => expect(pool.snapshot()).toMatchObject({
713
- workerCount: 1,
714
- idleWorkerCount: 1,
715
- startedWorkerCount: 2,
716
- retiredWorkerCount: 1,
717
- }));
718
-
719
- await expect(pool.analyze(
720
- [{ moduleId: 'visual.visibility', input }],
721
- new AbortController().signal,
722
- )).resolves.toMatchObject({
723
- results: [{ moduleId: 'visual.visibility', outcome: 'fulfilled' }],
724
- });
725
- } finally {
726
- await pool.stop();
727
- loader.stop();
728
- }
729
- });
730
-
731
- it('interrupts a replacement Worker ready wait when stop begins', async () => {
732
- const root = mkdtempSync(join(tmpdir(), 'ccl-perception-thread-replacement-stop-'));
733
- const sourcePath = join(root, 'delayed-replacement.ts');
734
- const delayMarker = join(root, 'delay-next-start');
735
- writeFileSync(sourcePath, `
736
- import { existsSync } from 'node:fs';
737
- import { ClawclawParallelPerception } from 'clawclaw-cli/perception-plugin';
738
- if (existsSync(${JSON.stringify(delayMarker)})) {
739
- await new Promise((resolve) => setTimeout(resolve, 5000));
740
- }
741
- export default class DelayedReplacement extends ClawclawParallelPerception {
742
- static manifest = {
743
- apiVersion: 2,
744
- id: 'visual.delayed_replacement', name: 'Delayed replacement', description: 'Lifecycle fixture.',
745
- subjectScope: 'others', produces: ['visual.delayed_replacement'], execution: 'parallel_analysis',
746
- } as const;
747
- analyze() { return {}; }
748
- commit() { return []; }
749
- }
750
- `, 'utf8');
751
- const manifest = {
752
- apiVersion: 2 as const,
753
- id: 'visual.delayed_replacement', name: 'Delayed replacement', description: 'Lifecycle fixture.',
754
- subjectScope: 'others' as const, produces: ['visual.delayed_replacement'], execution: 'parallel_analysis' as const,
755
- };
756
- const loader = new PerceptionModuleLoader();
757
- const pool = new PerceptionAnalysisThreadPool({
758
- modules: [loader.threadSpec({
759
- ...manifest,
760
- manifest,
761
- sourcePath,
762
- sourceRoot: root,
763
- })],
764
- loader: loader.threadConfig(),
765
- spatialFacts: CLAWCLAW_PERCEPTION_SPATIAL_FACTS,
766
- maxWorkers: 1,
767
- });
768
- pools.push(pool);
769
- try {
770
- await pool.start();
771
- writeFileSync(delayMarker, '', 'utf8');
772
- const slot = [...(pool as any).slots][0];
773
- await (pool as any).retireSlot(slot, 'replacement_stop_test');
774
- await vi.waitFor(() => expect(pool.snapshot()).toMatchObject({
775
- workerCount: 1,
776
- idleWorkerCount: 0,
777
- }));
778
- const startedAt = performance.now();
779
-
780
- await pool.stop();
781
-
782
- expect(performance.now() - startedAt).toBeLessThan(2_000);
783
- expect(pool.snapshot()).toMatchObject({ state: 'stopped', workerCount: 0 });
784
- } finally {
785
- await pool.stop();
786
- loader.stop();
787
- rmSync(root, { recursive: true, force: true });
788
- }
789
- });
790
-
791
- it('keeps queued work pending across bounded replacement failures until stop', async () => {
792
- const root = mkdtempSync(join(tmpdir(), 'ccl-perception-thread-retry-'));
793
- const sourcePath = join(root, 'disappearing.ts');
794
- writeFileSync(sourcePath, `
795
- import { ClawclawParallelPerception } from 'clawclaw-cli/perception-plugin';
796
- export default class Disappearing extends ClawclawParallelPerception {
797
- static manifest = {
798
- apiVersion: 2,
799
- id: 'visual.disappearing', name: 'Disappearing', description: 'Retry fixture.',
800
- subjectScope: 'others', produces: ['visual.disappearing'], execution: 'parallel_analysis',
801
- } as const;
802
- analyze() { return {}; }
803
- commit() { return []; }
804
- }
805
- `, 'utf8');
806
- const manifest = {
807
- apiVersion: 2 as const,
808
- id: 'visual.disappearing', name: 'Disappearing', description: 'Retry fixture.',
809
- subjectScope: 'others' as const, produces: ['visual.disappearing'], execution: 'parallel_analysis' as const,
810
- };
811
- const diagnostics: string[] = [];
812
- const loader = new PerceptionModuleLoader();
813
- const pool = new PerceptionAnalysisThreadPool({
814
- modules: [loader.threadSpec({
815
- ...manifest,
816
- manifest,
817
- sourcePath,
818
- sourceRoot: root,
819
- })],
820
- loader: loader.threadConfig(),
821
- spatialFacts: CLAWCLAW_PERCEPTION_SPATIAL_FACTS,
822
- maxWorkers: 1,
823
- diagnostic: (name) => diagnostics.push(name),
824
- });
825
- pools.push(pool);
826
- try {
827
- await pool.start();
828
- rmSync(sourcePath);
829
- const slot = [...(pool as any).slots][0];
830
- await (pool as any).retireSlot(slot, 'replacement_retry_test');
831
- const analysis = pool.analyze(
832
- [{ moduleId: 'visual.disappearing', input }],
833
- new AbortController().signal,
834
- );
835
- let settled = false;
836
- const outcome = analysis.then(
837
- (value) => {
838
- settled = true;
839
- return value;
840
- },
841
- (error: unknown) => {
842
- settled = true;
843
- return error;
844
- },
845
- );
846
- await vi.waitFor(() => expect(diagnostics).toContain(
847
- 'perception.analysis_worker.replacement_failed',
848
- ));
849
- await new Promise((resolve) => setTimeout(resolve, 75));
850
- expect(settled).toBe(false);
851
- const startedAt = performance.now();
852
-
853
- await pool.stop();
854
-
855
- expect(performance.now() - startedAt).toBeLessThan(2_000);
856
- await expect(outcome).resolves.toMatchObject({
857
- message: 'perception_analysis_pool_stopped',
858
- });
859
- } finally {
860
- await pool.stop();
861
- loader.stop();
862
- rmSync(root, { recursive: true, force: true });
863
- }
864
- });
865
- });