@myclaw163/clawclaw-cli 0.8.4 → 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 (241) hide show
  1. package/README.md +3 -2
  2. package/docs/configuration.md +44 -26
  3. package/docs/custom-modules/README.md +7 -10
  4. package/docs/custom-modules/behavior.md +3 -1
  5. package/docs/custom-modules/perception.md +1 -1
  6. package/docs/custom-modules/trigger.md +1 -1
  7. package/docs/runtime/README.md +4 -4
  8. package/docs/runtime/official-perception-modules.md +2 -2
  9. package/docs/runtime/owner-lifecycle-and-observability.md +1 -1
  10. package/package.json +9 -2
  11. package/scripts/build-official-hub-behaviors.mjs +136 -0
  12. package/scripts/build-official-hub-behaviors.test.mjs +178 -0
  13. package/scripts/enable_ccl_permissions.cjs +4 -2
  14. package/scripts/enable_ccl_permissions.test.mjs +8 -4
  15. package/scripts/postinstall.mjs +1 -4
  16. package/scripts/sync-bundled-skill.mjs +12 -159
  17. package/scripts/sync-bundled-skill.test.mjs +9 -74
  18. package/skills/clawclaw/SKILL.md +14 -9
  19. package/skills/clawclaw/references/BEHAVIORS.md +4 -4
  20. package/skills/clawclaw/references/COMMANDS.md +32 -16
  21. package/skills/clawclaw/references/HUB.md +25 -38
  22. package/src/commands/account.ts +58 -14
  23. package/src/commands/behavior.ts +116 -38
  24. package/src/commands/hub.ts +110 -153
  25. package/src/commands/load.ts +138 -33
  26. package/src/commands/perception.ts +55 -24
  27. package/src/commands/persona.ts +66 -20
  28. package/src/commands/skill.ts +12 -48
  29. package/src/commands/trigger.ts +68 -40
  30. package/src/hub-official-behaviors/kill-lone.ts +138 -0
  31. package/src/hub-official-behaviors/patrol.ts +30 -0
  32. package/src/hub-official-behaviors/shared.ts +125 -0
  33. package/src/hub-official-behaviors/task-only.ts +158 -0
  34. package/src/lib/account-guidance.ts +54 -9
  35. package/src/lib/agent-workspace-client.ts +135 -0
  36. package/src/lib/agent-workspace-runtime.ts +154 -0
  37. package/src/lib/agent-workspace-skills.ts +177 -0
  38. package/src/lib/agent-workspace-sync.ts +852 -0
  39. package/src/lib/gameplay-config.ts +29 -15
  40. package/src/lib/hub-client.ts +252 -34
  41. package/src/lib/hub-reminder.ts +22 -7
  42. package/src/lib/init-command.ts +0 -6
  43. package/src/lib/load-context.ts +12 -6
  44. package/src/lib/persona.ts +141 -69
  45. package/src/lib/server-status.ts +78 -0
  46. package/src/lib/skill-host.ts +160 -0
  47. package/src/lib/user-data.ts +197 -4
  48. package/src/runtime/clawclaw/owner.ts +63 -19
  49. package/src/runtime/clawclaw/plugins/behavior/activation-manager.ts +8 -2
  50. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +2 -2
  51. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +4 -1
  52. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +11 -5
  53. package/src/runtime/clawclaw/plugins/perception/replay.ts +0 -2
  54. package/personas//345/217/243/346/230/257/345/277/203/351/235/236.md +0 -50
  55. package/personas//345/277/240/345/277/203/350/200/201/344/273/206.md +0 -51
  56. package/personas//346/227/240/344/272/272/350/256/276.md +0 -1
  57. package/personas//350/264/253/345/230/264/346/215/237/345/217/213.md +0 -48
  58. package/personas//350/275/257/350/220/214/350/205/271/351/273/221.md +0 -51
  59. package/src/behaviors/official-finite/index.test.ts +0 -249
  60. package/src/channel/claude-channel-server.test.ts +0 -202
  61. package/src/commands/account.test.ts +0 -570
  62. package/src/commands/behavior.test.ts +0 -158
  63. package/src/commands/communication.test.ts +0 -282
  64. package/src/commands/competition.test.ts +0 -116
  65. package/src/commands/data.test.ts +0 -89
  66. package/src/commands/events-canonical-state.test.ts +0 -406
  67. package/src/commands/events.test.ts +0 -58
  68. package/src/commands/game/index.test.ts +0 -1251
  69. package/src/commands/game-map.test.ts +0 -69
  70. package/src/commands/hub.test.ts +0 -124
  71. package/src/commands/load.test.ts +0 -440
  72. package/src/commands/perception.test.ts +0 -75
  73. package/src/commands/setup/hermes.test.ts +0 -96
  74. package/src/commands/setup/openclaw.test.ts +0 -124
  75. package/src/commands/trigger.test.ts +0 -140
  76. package/src/commands/upgrade.test.ts +0 -82
  77. package/src/lib/account-guidance.test.ts +0 -36
  78. package/src/lib/auth.test.ts +0 -151
  79. package/src/lib/behavior-export.test.ts +0 -326
  80. package/src/lib/behavior-export.ts +0 -537
  81. package/src/lib/clawclaw-skill-spectate-guidance.test.ts +0 -21
  82. package/src/lib/custom-tts.test.ts +0 -387
  83. package/src/lib/diagnostics-config.test.ts +0 -59
  84. package/src/lib/game-client-tts.test.ts +0 -151
  85. package/src/lib/game-client.test.ts +0 -250
  86. package/src/lib/gameplay-config.test.ts +0 -301
  87. package/src/lib/host-config-patcher.test.ts +0 -130
  88. package/src/lib/http-transport.test.ts +0 -124
  89. package/src/lib/hub-client.test.ts +0 -57
  90. package/src/lib/hub-install.test.ts +0 -135
  91. package/src/lib/hub-install.ts +0 -185
  92. package/src/lib/hub-unzip.test.ts +0 -69
  93. package/src/lib/init-command.test.ts +0 -103
  94. package/src/lib/load-context.test.ts +0 -62
  95. package/src/lib/match-state.test.ts +0 -134
  96. package/src/lib/official-resource-sync.test.ts +0 -199
  97. package/src/lib/official-resource-sync.ts +0 -221
  98. package/src/lib/perception-config.test.ts +0 -143
  99. package/src/lib/perception-export.test.ts +0 -145
  100. package/src/lib/perception-export.ts +0 -178
  101. package/src/lib/persona.test.ts +0 -84
  102. package/src/lib/room.test.ts +0 -88
  103. package/src/lib/server-registry.test.ts +0 -64
  104. package/src/lib/service-status.test.ts +0 -81
  105. package/src/lib/skill-version.test.ts +0 -48
  106. package/src/lib/trigger-config.test.ts +0 -102
  107. package/src/lib/trigger-export.test.ts +0 -80
  108. package/src/lib/trigger-export.ts +0 -210
  109. package/src/lib/user-data.test.ts +0 -121
  110. package/src/lib/workspace-argv.test.ts +0 -49
  111. package/src/pipeline/canonical-event-presentation.test.ts +0 -257
  112. package/src/pipeline/event-format.test.ts +0 -879
  113. package/src/pipeline/event-hints.test.ts +0 -337
  114. package/src/pipeline/game-sync-event-normalization.test.ts +0 -419
  115. package/src/pipeline/player-projection.test.ts +0 -247
  116. package/src/runtime/auto-upgrade.test.ts +0 -66
  117. package/src/runtime/canonical-event-emitter.test.ts +0 -70
  118. package/src/runtime/canonical-monitor.test.ts +0 -577
  119. package/src/runtime/clawclaw/agent-event-policy.test.ts +0 -60
  120. package/src/runtime/clawclaw/behavior-decision.test.ts +0 -43
  121. package/src/runtime/clawclaw/behavior-input-fields.test.ts +0 -175
  122. package/src/runtime/clawclaw/behavior-input.test.ts +0 -173
  123. package/src/runtime/clawclaw/behavior-observation-memory.test.ts +0 -59
  124. package/src/runtime/clawclaw/behavior-read-api.test.ts +0 -123
  125. package/src/runtime/clawclaw/notifications.test.ts +0 -47
  126. package/src/runtime/clawclaw/owner-lock.test.ts +0 -221
  127. package/src/runtime/clawclaw/owner.test.ts +0 -203
  128. package/src/runtime/clawclaw/plugins/action/action-plugin.test.ts +0 -328
  129. package/src/runtime/clawclaw/plugins/assembly.test.ts +0 -200
  130. package/src/runtime/clawclaw/plugins/behavior/activation-manager.test.ts +0 -180
  131. package/src/runtime/clawclaw/plugins/behavior/behavior-action.test.ts +0 -43
  132. package/src/runtime/clawclaw/plugins/behavior/behavior-catalog.test.ts +0 -156
  133. package/src/runtime/clawclaw/plugins/behavior/behavior-module-loader.test.ts +0 -182
  134. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.test.ts +0 -1094
  135. package/src/runtime/clawclaw/plugins/behavior/behavior-source.test.ts +0 -174
  136. package/src/runtime/clawclaw/plugins/behavior/control-driver.test.ts +0 -195
  137. package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.test.ts +0 -283
  138. package/src/runtime/clawclaw/plugins/behavior-input-source.test.ts +0 -80
  139. package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.test.ts +0 -267
  140. package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.test.ts +0 -226
  141. package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-adapter.test.ts +0 -239
  142. package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.test.ts +0 -407
  143. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-push.integration.test.ts +0 -397
  144. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.test.ts +0 -270
  145. package/src/runtime/clawclaw/plugins/mailbox/mailbox-agent-event-batch.test.ts +0 -166
  146. package/src/runtime/clawclaw/plugins/mailbox/mailbox-event-batch-delivery.test.ts +0 -194
  147. package/src/runtime/clawclaw/plugins/mailbox/mailbox-plugin.test.ts +0 -87
  148. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.test.ts +0 -2012
  149. package/src/runtime/clawclaw/plugins/perception/module-runner.test.ts +0 -214
  150. package/src/runtime/clawclaw/plugins/perception/modules/co-movement-module.ts +0 -347
  151. package/src/runtime/clawclaw/plugins/perception/modules/corpse-visibility-module.test.ts +0 -92
  152. package/src/runtime/clawclaw/plugins/perception/modules/corpse-visibility-module.ts +0 -248
  153. package/src/runtime/clawclaw/plugins/perception/modules/follow-module.ts +0 -389
  154. package/src/runtime/clawclaw/plugins/perception/modules/index.ts +0 -8
  155. package/src/runtime/clawclaw/plugins/perception/modules/motion-module.test.ts +0 -342
  156. package/src/runtime/clawclaw/plugins/perception/modules/motion-module.ts +0 -475
  157. package/src/runtime/clawclaw/plugins/perception/modules/parallel-module-test-helpers.ts +0 -30
  158. package/src/runtime/clawclaw/plugins/perception/modules/relation-stability.test.ts +0 -304
  159. package/src/runtime/clawclaw/plugins/perception/modules/route-module.test.ts +0 -179
  160. package/src/runtime/clawclaw/plugins/perception/modules/route-module.ts +0 -364
  161. package/src/runtime/clawclaw/plugins/perception/modules/spatial-module.test.ts +0 -81
  162. package/src/runtime/clawclaw/plugins/perception/modules/spatial-module.ts +0 -200
  163. package/src/runtime/clawclaw/plugins/perception/modules/stop-module.test.ts +0 -216
  164. package/src/runtime/clawclaw/plugins/perception/modules/stop-module.ts +0 -284
  165. package/src/runtime/clawclaw/plugins/perception/modules/temporal-evidence.test.ts +0 -120
  166. package/src/runtime/clawclaw/plugins/perception/modules/visibility-module.test.ts +0 -105
  167. package/src/runtime/clawclaw/plugins/perception/modules/visibility-module.ts +0 -269
  168. package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-pool.test.ts +0 -865
  169. package/src/runtime/clawclaw/plugins/perception/perception-plugin.test.ts +0 -1878
  170. package/src/runtime/clawclaw/plugins/perception/perception-source.test.ts +0 -278
  171. package/src/runtime/clawclaw/plugins/perception/replay.test.ts +0 -77
  172. package/src/runtime/clawclaw/plugins/runtime-plugins.test.ts +0 -853
  173. package/src/runtime/clawclaw/plugins/source/game-transport.test.ts +0 -287
  174. package/src/runtime/clawclaw/plugins/source/player-change-tracker.test.ts +0 -321
  175. package/src/runtime/clawclaw/plugins/source/room-transport.test.ts +0 -307
  176. package/src/runtime/clawclaw/plugins/source/source-plugin.test.ts +0 -2646
  177. package/src/runtime/clawclaw/plugins/source/task-change-tracker.test.ts +0 -212
  178. package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.test.ts +0 -548
  179. package/src/runtime/clawclaw/plugins/trigger/trigger-source.test.ts +0 -169
  180. package/src/runtime/clawclaw/runtime-data-export.test.ts +0 -249
  181. package/src/runtime/clawclaw-event-catalog.test.ts +0 -128
  182. package/src/runtime/framework/action-diagnostics.test.ts +0 -81
  183. package/src/runtime/framework/capability-registry.test.ts +0 -423
  184. package/src/runtime/framework/control-coordinator.test.ts +0 -675
  185. package/src/runtime/framework/events/event-delivery-service.test.ts +0 -84
  186. package/src/runtime/framework/events/event-ingress.test.ts +0 -203
  187. package/src/runtime/framework/events/mailbox-event-repositories.test.ts +0 -710
  188. package/src/runtime/framework/events/sqlite-event-repository.test.ts +0 -802
  189. package/src/runtime/framework/mailbox/coalescer.test.ts +0 -55
  190. package/src/runtime/framework/mailbox/identity.test.ts +0 -38
  191. package/src/runtime/framework/mailbox/mailbox-dispatcher.test.ts +0 -513
  192. package/src/runtime/framework/mailbox/notification-projector.test.ts +0 -77
  193. package/src/runtime/framework/modules/runtime-module-loader.test.ts +0 -435
  194. package/src/runtime/framework/participation-manager.test.ts +0 -108
  195. package/src/runtime/framework/plugins/runtime-input-journal.test.ts +0 -179
  196. package/src/runtime/framework/plugins/runtime-plugin-scheduler.test.ts +0 -2040
  197. package/src/runtime/framework/state/durable-agent-state-snapshot.test.ts +0 -144
  198. package/src/runtime/framework/state/history/sqlite-state-history-repository.test.ts +0 -157
  199. package/src/runtime/framework/state/history/state-history.test.ts +0 -251
  200. package/src/runtime/framework/state/state-core.test.ts +0 -197
  201. package/src/runtime/game-sync-protocol.test.ts +0 -123
  202. package/src/runtime/host-monitor-rate-gate.test.ts +0 -73
  203. package/src/runtime/mailbox-host-relay.test.ts +0 -293
  204. package/src/runtime/observability/observability.test.ts +0 -583
  205. package/src/runtime/owner-control.test.ts +0 -153
  206. package/src/runtime/parent-process-watch.test.ts +0 -27
  207. package/src/runtime/pending-event-handoff.test.ts +0 -29
  208. package/src/runtime/raw-ws-log.test.ts +0 -102
  209. package/src/runtime/runtime-logger.test.ts +0 -58
  210. package/src/runtime/runtime-persistence.test.ts +0 -26
  211. package/src/runtime/runtime.test.ts +0 -1770
  212. package/src/runtime/ws-client.test.ts +0 -562
  213. package/src/sdk/action.test.ts +0 -8
  214. package/src/sdk/behavior-plugin/index.test.ts +0 -74
  215. package/src/sdk/index.test.ts +0 -45
  216. package/src/sdk/module-input/index.test.ts +0 -49
  217. package/src/sdk/perception-plugin/index.test.ts +0 -22
  218. package/src/sdk/resource-metadata.test.ts +0 -40
  219. package/src/sdk/trigger-plugin/index.test.ts +0 -41
  220. package/src/short-command/classifier.test.ts +0 -107
  221. package/src/short-command/presenter.test.ts +0 -119
  222. package/src/short-command/runner.test.ts +0 -78
  223. package/src/short-command/sensitive-data-filter.test.ts +0 -56
  224. package/src/short-command/transport-response.test.ts +0 -39
  225. package/src/strategies/custom-module.test.ts +0 -267
  226. package/src/strategies/game-utils.test.ts +0 -305
  227. package/src/strategies/goals/avoid-players-top.test.ts +0 -95
  228. package/src/strategies/goals/crab-sabotage-top.test.ts +0 -131
  229. package/src/strategies/goals/kill-lone-top.test.ts +0 -96
  230. package/src/strategies/goals/kill-target-top.test.ts +0 -65
  231. package/src/strategies/goals/lone-kill-task-top.test.ts +0 -84
  232. package/src/strategies/goals/normal-shrimp-top.test.ts +0 -112
  233. package/src/strategies/goals/paradise-fish-top.test.ts +0 -203
  234. package/src/strategies/goals/task-only-top.test.ts +0 -88
  235. package/src/strategies/goals/warrior-shrimp-top.test.ts +0 -138
  236. package/src/strategies/meeting-gate.test.ts +0 -59
  237. package/src/strategies/official-long-behavior.test.ts +0 -89
  238. package/src/strategies/pathfind/astar-path.test.ts +0 -198
  239. package/src/strategies/pathfind/escape-planner.test.ts +0 -223
  240. package/src/strategies/player-targets.test.ts +0 -10
  241. package/src/strategies/task-only.test.ts +0 -138
@@ -1,174 +0,0 @@
1
- import {
2
- mkdirSync,
3
- mkdtempSync,
4
- rmSync,
5
- writeFileSync,
6
- } from 'node:fs';
7
- import { tmpdir } from 'node:os';
8
- import { join } from 'node:path';
9
- import { afterEach, describe, expect, it } from 'vitest';
10
- import {
11
- inspectClawclawBehaviorSource,
12
- listClawclawBehaviorSources,
13
- resolveClawclawBehaviorSource,
14
- } from './behavior-source.js';
15
-
16
- const roots: string[] = [];
17
-
18
- function tempRoot(): string {
19
- const root = mkdtempSync(join(tmpdir(), 'clawclaw-behavior-source-'));
20
- roots.push(root);
21
- return root;
22
- }
23
-
24
- function moduleSource(
25
- id: string,
26
- extraManifest = '',
27
- topLevel = `throw new Error('source scanner executed player code');`,
28
- ): string {
29
- return `
30
- import { ClawclawBehavior } from '@myclaw163/clawclaw-cli/behavior-plugin';
31
- ${topLevel}
32
- export default class ExampleBehavior extends ClawclawBehavior {
33
- static override readonly manifest = {
34
- apiVersion: 3,
35
- id: '${id}',
36
- name: ' Example ',
37
- description: ' Static metadata ',
38
- localizations: {
39
- 'zh-CN': { name: '示例', description: '静态元数据' },
40
- },
41
- inputs: [{
42
- id: 'target',
43
- type: 'string',
44
- description: 'Target label.',
45
- default: 'Engine',
46
- }],
47
- execution: 'serial',
48
- everyTicks: 3,
49
- produces: ['custom.alert'],
50
- runtime: {
51
- defaultMs: 5_000,
52
- deadlineOutcome: 'failed',
53
- controlGraceMs: 500,
54
- },
55
- ${extraManifest}
56
- } as const;
57
- override decide() {}
58
- }
59
- `;
60
- }
61
-
62
- afterEach(() => {
63
- for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });
64
- });
65
-
66
- describe('Behavior static source discovery', () => {
67
- it('reads the complete literal manifest without evaluating the module', () => {
68
- const root = tempRoot();
69
- const path = join(root, 'example.ts');
70
- writeFileSync(path, moduleSource('static_example'));
71
-
72
- const [source] = listClawclawBehaviorSources(root);
73
- expect(source).toMatchObject({
74
- apiVersion: 3,
75
- id: 'static_example',
76
- name: 'Example',
77
- description: 'Static metadata',
78
- execution: 'serial',
79
- everyTicks: 3,
80
- inputs: [{ id: 'target', type: 'string', default: 'Engine' }],
81
- produces: ['custom.alert'],
82
- runtime: {
83
- defaultMs: 5_000,
84
- deadlineOutcome: 'failed',
85
- controlGraceMs: 500,
86
- },
87
- });
88
- expect(source.localizations?.['zh-CN']).toEqual({
89
- name: '示例',
90
- description: '静态元数据',
91
- });
92
- expect(source.compatibilityError).toBeUndefined();
93
- });
94
-
95
- it('keeps identifiable incompatible manifests visible and never imports them', () => {
96
- const root = tempRoot();
97
- writeFileSync(join(root, 'legacy.ts'), `
98
- import { ClawclawBehavior } from 'clawclaw-cli/behavior-plugin';
99
- globalThis.__legacy_behavior_was_imported__ = true;
100
- export default class Legacy extends ClawclawBehavior {
101
- static readonly manifest = {
102
- id: 'legacy_behavior',
103
- name: 'Legacy',
104
- description: 'No literal API version.',
105
- inputs: [],
106
- } as const;
107
- override decide() {}
108
- }
109
- `);
110
- writeFileSync(join(root, 'dynamic-input.ts'), `
111
- import { ClawclawBehavior } from 'clawclaw-cli/behavior-plugin';
112
- const declaredInputs = [];
113
- export default class Dynamic extends ClawclawBehavior {
114
- static readonly manifest = {
115
- apiVersion: 3,
116
- id: 'dynamic_input',
117
- name: 'Dynamic',
118
- description: 'Inputs are not statically readable.',
119
- inputs: declaredInputs,
120
- } as const;
121
- override decide() {}
122
- }
123
- `);
124
-
125
- const sources = listClawclawBehaviorSources(root);
126
- expect(sources.map(({ id }) => id)).toEqual(['dynamic_input', 'legacy_behavior']);
127
- expect(sources[0].compatibilityError).toBe('behavior_inputs_not_literal');
128
- expect(sources[1].apiVersion).toBeUndefined();
129
- expect((globalThis as Record<string, unknown>).__legacy_behavior_was_imported__).toBeUndefined();
130
- });
131
-
132
- it('accepts only direct-child standard author modules and reports duplicate ids', () => {
133
- const root = tempRoot();
134
- writeFileSync(join(root, 'a.ts'), moduleSource('duplicate', '', ''));
135
- writeFileSync(join(root, 'b.ts'), moduleSource('duplicate', '', ''));
136
- writeFileSync(join(root, '_ignored.ts'), moduleSource('ignored', '', ''));
137
- const nested = join(root, 'nested');
138
- mkdirSync(nested);
139
- const nestedPath = join(nested, 'nested.ts');
140
- writeFileSync(nestedPath, moduleSource('nested', '', ''));
141
-
142
- expect(listClawclawBehaviorSources(root).map(({ id }) => id))
143
- .toEqual(['duplicate', 'duplicate']);
144
- expect(inspectClawclawBehaviorSource(nestedPath, root)).toBeNull();
145
- expect(() => resolveClawclawBehaviorSource('duplicate', root))
146
- .toThrow("Duplicate behavior module id 'duplicate'.");
147
- });
148
-
149
- it('does not accept author-contract text hidden in comments or strings', () => {
150
- const root = tempRoot();
151
- writeFileSync(join(root, 'spoof.ts'), `
152
- // import { ClawclawBehavior } from 'clawclaw-cli/behavior-plugin';
153
- // export default class Spoof extends ClawclawBehavior {
154
- // static manifest = { apiVersion: 3, id: 'spoof', name: 'Spoof', description: 'Spoof', inputs: [] };
155
- // }
156
- export default function runSomethingElse() {}
157
- `);
158
- expect(listClawclawBehaviorSources(root)).toEqual([]);
159
- });
160
-
161
- it('keeps an identifiable manifest with legacy or unknown fields visible but incompatible', () => {
162
- const root = tempRoot();
163
- writeFileSync(join(root, 'legacy-field.ts'), moduleSource(
164
- 'legacy_field',
165
- 'defaultRuntimeMs: 5_000,',
166
- '',
167
- ));
168
- const [source] = listClawclawBehaviorSources(root);
169
- expect(source).toMatchObject({
170
- id: 'legacy_field',
171
- compatibilityError: 'behavior_manifest_field_unknown:defaultRuntimeMs',
172
- });
173
- });
174
- });
@@ -1,195 +0,0 @@
1
- import { describe, expect, it } from 'vitest';
2
- import {
3
- ActionRegistry,
4
- actionControllerId,
5
- } from '../../../framework/capability-registry.js';
6
- import type { ScopeRef } from '../../../framework/contracts.js';
7
- import type { BehaviorActivationSnapshot } from './activation-manager.js';
8
- import { createClawclawBehaviorControlDriver } from './control-driver.js';
9
-
10
- const scope: ScopeRef = {
11
- adapterId: 'test',
12
- accountId: 'account',
13
- sessionId: 'session',
14
- segmentId: 'segment',
15
- };
16
-
17
- function createRuntime() {
18
- const actions = new ActionRegistry();
19
- actions.activateScope(scope);
20
- return {
21
- actions,
22
- scope: () => scope,
23
- };
24
- }
25
-
26
- function activation(
27
- overrides: Partial<BehaviorActivationSnapshot> = {},
28
- ): BehaviorActivationSnapshot {
29
- return {
30
- activationId: 'activation-1',
31
- behaviorId: 'task-only',
32
- layer: 'long',
33
- source: 'idle',
34
- input: {},
35
- requestedAt: 1,
36
- state: 'running',
37
- instanceGeneration: 1,
38
- startedAt: 1,
39
- ...overrides,
40
- };
41
- }
42
-
43
- function registerDirectController(
44
- runtime: ReturnType<typeof createRuntime>,
45
- kind: 'agent' | 'user',
46
- ): string {
47
- const controllerId = actionControllerId({ kind }, scope);
48
- runtime.actions.controls.registerController({
49
- controllerId,
50
- kind,
51
- scope,
52
- domains: ['*'],
53
- lifecycle: 'persistent',
54
- ready: true,
55
- });
56
- return controllerId;
57
- }
58
-
59
- describe('Clawclaw Behavior control driver', () => {
60
- it('uses fixed long/short/reflex priorities and never maps reflexPriority', () => {
61
- const runtime = createRuntime();
62
- const driver = createClawclawBehaviorControlDriver(runtime);
63
- const long = driver.acquire(activation(), scope);
64
- const short = driver.acquire(activation({
65
- activationId: 'activation-short',
66
- behaviorId: 'go_to',
67
- layer: 'short',
68
- source: 'system',
69
- maxRuntimeMs: 30_000,
70
- }), scope);
71
- const reflex = driver.acquire(activation({
72
- activationId: 'activation-reflex',
73
- behaviorId: 'evade',
74
- layer: 'reflex',
75
- source: 'trigger',
76
- maxRuntimeMs: 10_000,
77
- triggerId: 'followed-by-untrusted-player',
78
- reflexPriority: 999_999,
79
- }), scope);
80
-
81
- const byId = new Map(runtime.actions.controls.snapshot().controllers.map(
82
- controller => [controller.controllerId, controller],
83
- ));
84
- expect(byId.get(long.controllerId)).toMatchObject({
85
- kind: 'behavior',
86
- priority: 100,
87
- lifecycle: 'persistent',
88
- state: 'held',
89
- });
90
- expect(byId.get(short.controllerId)).toMatchObject({
91
- kind: 'behavior',
92
- priority: 200,
93
- lifecycle: 'finite',
94
- state: 'held',
95
- });
96
- expect(byId.get(reflex.controllerId)).toMatchObject({
97
- kind: 'behavior',
98
- priority: 350,
99
- lifecycle: 'finite',
100
- state: 'active',
101
- });
102
- expect(byId.get(reflex.controllerId)?.metadata).not.toHaveProperty('reflexPriority');
103
- expect(long.isAuthorized()).toBe(false);
104
- expect(short.isAuthorized()).toBe(false);
105
- expect(reflex.isAuthorized()).toBe(true);
106
- });
107
-
108
- it('keeps an idle long Behavior held by Agent control, then observes dynamic activation', () => {
109
- const runtime = createRuntime();
110
- const agentControllerId = registerDirectController(runtime, 'agent');
111
- const handle = createClawclawBehaviorControlDriver(runtime).acquire(activation(), scope);
112
-
113
- expect(runtime.actions.controls.snapshot().controllers.find(
114
- controller => controller.controllerId === agentControllerId,
115
- )).toMatchObject({ state: 'active', claimedDomains: ['*'] });
116
- expect(runtime.actions.controls.snapshot().controllers.find(
117
- controller => controller.controllerId === handle.controllerId,
118
- )).toMatchObject({ state: 'held', ready: true });
119
- expect(handle.isAuthorized()).toBe(false);
120
-
121
- runtime.actions.controls.release(agentControllerId, { reason: 'agent_idle' });
122
- expect(handle.isAuthorized()).toBe(true);
123
- expect(runtime.actions.controls.snapshot().controllers.find(
124
- controller => controller.controllerId === handle.controllerId,
125
- )).toMatchObject({
126
- state: 'active',
127
- grantedDomains: ['communication', 'physical'],
128
- });
129
- });
130
-
131
- it.each(['agent', 'user'] as const)(
132
- 'hands explicit %s control to a lower-priority Behavior activation',
133
- (source) => {
134
- const runtime = createRuntime();
135
- const directControllerId = registerDirectController(runtime, source);
136
- const handle = createClawclawBehaviorControlDriver(runtime).acquire(activation({
137
- activationId: `${source}-short`,
138
- behaviorId: 'go_to',
139
- layer: 'short',
140
- source,
141
- maxRuntimeMs: 30_000,
142
- }), scope);
143
-
144
- expect(runtime.actions.controls.snapshot().controllers.find(
145
- controller => controller.controllerId === directControllerId,
146
- )).toMatchObject({
147
- state: 'active',
148
- claimedDomains: ['*'],
149
- excludedDomains: ['communication', 'physical'],
150
- });
151
- expect(handle.isAuthorized()).toBe(true);
152
- expect(runtime.actions.controls.snapshot().controllers.find(
153
- controller => controller.controllerId === handle.controllerId,
154
- )).toMatchObject({
155
- grantedDomains: ['communication', 'physical'],
156
- });
157
- },
158
- );
159
-
160
- it('includes instance generation in controller identity and releases idempotently', () => {
161
- const runtime = createRuntime();
162
- const driver = createClawclawBehaviorControlDriver(runtime);
163
- const first = driver.acquire(activation(), scope);
164
- first.release('behavior_suspended');
165
- first.release('must_not_replace_reason');
166
-
167
- const second = driver.acquire(activation({ instanceGeneration: 2 }), scope);
168
- expect(first.controllerId).not.toBe(second.controllerId);
169
- expect(first.controllerId).toContain('activation-1');
170
- expect(first.controllerId).toContain('generation-1');
171
- expect(second.controllerId).toContain('generation-2');
172
- expect(first.caller.activationGeneration).toBe(1);
173
- expect(second.caller.activationGeneration).toBe(2);
174
- expect(first.isAuthorized()).toBe(false);
175
- expect(second.isAuthorized()).toBe(true);
176
- expect(runtime.actions.controls.snapshot().controllers.find(
177
- controller => controller.controllerId === first.controllerId,
178
- )).toMatchObject({ state: 'released', releaseReason: 'behavior_suspended' });
179
- });
180
-
181
- it('requires a bounded runtime for finite short and reflex activations', () => {
182
- const runtime = createRuntime();
183
- const driver = createClawclawBehaviorControlDriver(runtime);
184
-
185
- expect(() => driver.acquire(activation({ layer: 'short', source: 'agent' }), scope))
186
- .toThrow('behavior_control_runtime_required');
187
- expect(() => driver.acquire(activation({
188
- layer: 'reflex',
189
- source: 'trigger',
190
- triggerId: 'rule',
191
- reflexPriority: 1,
192
- }), scope)).toThrow('behavior_control_runtime_required');
193
- expect(runtime.actions.controls.snapshot().controllers).toEqual([]);
194
- });
195
- });
@@ -1,283 +0,0 @@
1
- import { mkdtemp, rm, writeFile } from 'node:fs/promises';
2
- import { tmpdir } from 'node:os';
3
- import { join } from 'node:path';
4
- import { threadId as ownerThreadId } from 'node:worker_threads';
5
- import { afterEach, describe, expect, it, vi } from 'vitest';
6
- import type { BehaviorInput } from '../../../../sdk/behavior-plugin/index.js';
7
- import { ClawclawBehaviorCatalog } from './behavior-catalog.js';
8
- import { ClawclawBehaviorRunner } from './behavior-runner.js';
9
- import { inspectClawclawBehaviorSource } from './behavior-source.js';
10
- import { ThreadBehaviorExecutor } from './thread-behavior-executor.js';
11
-
12
- function frame(
13
- epochId: number,
14
- state: Readonly<Record<string, unknown>> = {},
15
- ): BehaviorInput<Record<string, unknown>> {
16
- return {
17
- epochId,
18
- scope: { sessionId: 'session', segmentId: 'segment' },
19
- nowMs: epochId * 100,
20
- gameState: {
21
- game_id: 'fixture-game',
22
- phase: 'wandering',
23
- tick: epochId,
24
- you: {
25
- player: { name: 'fixture-player', seat: 1 },
26
- room: 'fixture-room',
27
- role: 'shrimp_generic',
28
- faction: 'lobster',
29
- is_alive: true,
30
- x: 500,
31
- y: 500,
32
- activity: { kind: 'idle' },
33
- tasks: [],
34
- },
35
- players: [],
36
- visible_players: [],
37
- visible_corpses: [],
38
- ...state,
39
- } as BehaviorInput<Record<string, unknown>>['gameState'],
40
- events: [],
41
- input: {},
42
- };
43
- }
44
-
45
- describe('parallel Behavior Worker executor', () => {
46
- const directories: string[] = [];
47
- const executors: ThreadBehaviorExecutor[] = [];
48
- const runners: ClawclawBehaviorRunner[] = [];
49
-
50
- afterEach(async () => {
51
- await Promise.allSettled(runners.splice(0).map(runner => runner.stop('shutdown')));
52
- await Promise.allSettled(executors.splice(0).map(executor => executor.stop('shutdown')));
53
- await Promise.all(directories.splice(0).map(directory => (
54
- rm(directory, { recursive: true, force: true })
55
- )));
56
- });
57
-
58
- async function fixture(
59
- id: string,
60
- decide: string,
61
- options: Readonly<{ imports?: string; fields?: string }> = {},
62
- ) {
63
- const sourceRoot = await mkdtemp(join(tmpdir(), `ccl-behavior-${id}-`));
64
- directories.push(sourceRoot);
65
- const sourcePath = join(sourceRoot, `${id}.ts`);
66
- await writeFile(sourcePath, `
67
- ${options.imports ?? ''}
68
- import { ClawclawBehavior } from '@myclaw163/clawclaw-cli/behavior-plugin';
69
- export default class FixtureBehavior extends ClawclawBehavior {
70
- static manifest = {
71
- apiVersion: 3,
72
- id: '${id}',
73
- name: '${id}',
74
- description: '${id} Worker fixture.',
75
- localizations: { 'zh-CN': { name: '${id}', description: '${id} Worker fixture.' } },
76
- execution: 'parallel',
77
- inputs: [],
78
- } as const;
79
- ${options.fields ?? ''}
80
- decide(input) { ${decide} }
81
- }
82
- `, 'utf8');
83
- const source = inspectClawclawBehaviorSource(sourcePath, sourceRoot);
84
- expect(source).not.toBeNull();
85
- return source!;
86
- }
87
-
88
- it('routes ClawclawBehaviorRunner parallel Decisions through the Worker pool', async () => {
89
- const source = await fixture(
90
- 'runner-worker-route',
91
- `return { status: { summary: 'runner worker', data: { threadId } } };`,
92
- { imports: `import { threadId } from 'node:worker_threads';` },
93
- );
94
- const prepared = await new ClawclawBehaviorCatalog([source]).prepare(source.id, {});
95
- const runner = new ClawclawBehaviorRunner({
96
- behaviorId: source.id,
97
- activationId: 'activation-worker-route',
98
- instanceGeneration: 1,
99
- prepared,
100
- isActive: () => true,
101
- });
102
- runners.push(runner);
103
-
104
- const decision = await runner.decideParallel(
105
- frame(1),
106
- new AbortController().signal,
107
- );
108
- expect((decision.status?.data as { threadId: number }).threadId).not.toBe(ownerThreadId);
109
- });
110
-
111
- it('prewarms reusable Workers, runs off the Owner thread, and creates a fresh instance per Decision', async () => {
112
- const source = await fixture(
113
- 'worker-isolation',
114
- `
115
- this.calls += 1;
116
- const startedAt = Date.now();
117
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, Number(input.gameState.delay_ms ?? 0));
118
- return { status: { summary: 'isolated', data: {
119
- threadId, calls: this.calls, epochId: input.epochId,
120
- startedAt, endedAt: Date.now(), frozen: Object.isFrozen(input.gameState),
121
- } } };
122
- `,
123
- { imports: `import { threadId } from 'node:worker_threads';`, fields: 'calls = 0;' },
124
- );
125
- const executor = new ThreadBehaviorExecutor({ source, poolSize: 2 });
126
- executors.push(executor);
127
- const signal = new AbortController().signal;
128
- await executor.start(signal);
129
- expect(executor.snapshot()).toMatchObject({
130
- state: 'running', workerCount: 2, idleWorkerCount: 2, startedWorkerCount: 2,
131
- });
132
-
133
- const [first, second] = await Promise.all([
134
- executor.update(frame(1, { delay_ms: 80 }), signal),
135
- executor.update(frame(2, { delay_ms: 80 }), signal),
136
- ]);
137
- const left = first.status?.data as Record<string, number | boolean>;
138
- const right = second.status?.data as Record<string, number | boolean>;
139
- expect(left.threadId).not.toBe(ownerThreadId);
140
- expect(right.threadId).not.toBe(ownerThreadId);
141
- expect(new Set([left.threadId, right.threadId]).size).toBe(2);
142
- expect(left.calls).toBe(1);
143
- expect(right.calls).toBe(1);
144
- expect(left.frozen).toBe(true);
145
- expect(right.frozen).toBe(true);
146
- expect(Math.max(Number(left.startedAt), Number(right.startedAt))).toBeLessThan(
147
- Math.min(Number(left.endedAt), Number(right.endedAt)),
148
- );
149
-
150
- await expect(executor.update(frame(3), signal)).resolves.toMatchObject({
151
- status: { data: { calls: 1, epochId: 3 } },
152
- });
153
- });
154
-
155
- it('scales from two Workers to pressure demand, reuses the pool, then retires idle capacity', async () => {
156
- const source = await fixture('worker-scale', `
157
- Atomics.wait(new Int32Array(input.gameState.gate), 0, 0);
158
- return { status: { summary: 'released', data: { epochId: input.epochId } } };
159
- `);
160
- const diagnostics: Array<{ name: string; attributes?: Readonly<Record<string, unknown>> }> = [];
161
- const executor = new ThreadBehaviorExecutor({
162
- source,
163
- poolSize: 4,
164
- idleWorkerTimeoutMs: 50,
165
- diagnostic: (name, attributes) => diagnostics.push({ name, attributes }),
166
- });
167
- executors.push(executor);
168
- const signal = new AbortController().signal;
169
- await executor.start(signal);
170
-
171
- const gate = new SharedArrayBuffer(4);
172
- const wave = Array.from({ length: 4 }, (_, index) => (
173
- executor.update(frame(index + 1, { gate }), signal)
174
- ));
175
- await vi.waitFor(() => expect(executor.snapshot()).toMatchObject({
176
- workerCount: 4,
177
- busyWorkerCount: 4,
178
- queuedRequestCount: 0,
179
- inFlightRequestCount: 4,
180
- startedWorkerCount: 4,
181
- }), { timeout: 10_000 });
182
- expect(diagnostics.filter(entry => (
183
- entry.name === 'behavior.thread.started' && entry.attributes?.reason === 'queue_pressure'
184
- ))).toHaveLength(2);
185
-
186
- Atomics.store(new Int32Array(gate), 0, 1);
187
- Atomics.notify(new Int32Array(gate), 0);
188
- await expect(Promise.all(wave)).resolves.toHaveLength(4);
189
- await expect(executor.update(frame(5, { gate }), signal)).resolves.toMatchObject({
190
- status: { data: { epochId: 5 } },
191
- });
192
- await vi.waitFor(() => expect(executor.snapshot()).toMatchObject({
193
- workerCount: 2,
194
- idleWorkerCount: 2,
195
- busyWorkerCount: 0,
196
- startedWorkerCount: 4,
197
- retiredWorkerCount: 2,
198
- }), { timeout: 5_000 });
199
- });
200
-
201
- it('retires an aborted slot and restores capacity before the next Decision', async () => {
202
- const source = await fixture('worker-abort', `
203
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, Number(input.gameState.delay_ms));
204
- return {};
205
- `);
206
- const executor = new ThreadBehaviorExecutor({ source, poolSize: 1 });
207
- executors.push(executor);
208
- await executor.start(new AbortController().signal);
209
- const controller = new AbortController();
210
- const pending = executor.update(frame(1, { delay_ms: 500 }), controller.signal);
211
- await vi.waitFor(() => expect(executor.snapshot().busyWorkerCount).toBe(1));
212
- controller.abort(new Error('superseded'));
213
- await expect(pending).rejects.toThrow('superseded');
214
-
215
- await vi.waitFor(() => expect(executor.snapshot()).toMatchObject({
216
- state: 'running', workerCount: 1, idleWorkerCount: 1,
217
- retiredWorkerCount: 1, startedWorkerCount: 2,
218
- }), { timeout: 5_000 });
219
- await expect(executor.update(
220
- frame(2, { delay_ms: 0 }),
221
- new AbortController().signal,
222
- )).resolves.toEqual({});
223
- });
224
-
225
- it('isolates a crashing Worker and replaces only that slot', async () => {
226
- const source = await fixture('worker-crash', `
227
- if (input.epochId === 1) process.exit(42);
228
- return { status: { summary: 'recovered', data: { epochId: input.epochId } } };
229
- `);
230
- const executor = new ThreadBehaviorExecutor({ source, poolSize: 1 });
231
- executors.push(executor);
232
- const signal = new AbortController().signal;
233
- await executor.start(signal);
234
-
235
- await expect(executor.update(frame(1), signal)).rejects.toThrow('behavior_thread_worker_exited:42');
236
- await vi.waitFor(() => expect(executor.snapshot()).toMatchObject({
237
- state: 'running', workerCount: 1, idleWorkerCount: 1,
238
- retiredWorkerCount: 1, startedWorkerCount: 2,
239
- }), { timeout: 5_000 });
240
- await expect(executor.update(frame(2), signal)).resolves.toMatchObject({
241
- status: { data: { epochId: 2 } },
242
- });
243
- });
244
-
245
- it('refuses to mix a changed local dependency into an existing pool generation', async () => {
246
- const source = await fixture(
247
- 'worker-source-pin',
248
- `return { status: { summary } };`,
249
- { imports: `import { summary } from './worker-helper.ts';` },
250
- );
251
- const helper = join(source.sourceRoot, 'worker-helper.ts');
252
- await writeFile(helper, `export const summary = 'original';\n`, 'utf8');
253
- const executor = new ThreadBehaviorExecutor({ source, poolSize: 1 });
254
- executors.push(executor);
255
- await writeFile(helper, `export const summary = 'changed';\n`, 'utf8');
256
-
257
- await expect(executor.start(new AbortController().signal))
258
- .rejects.toThrow('behavior_source_tree_changed');
259
- });
260
-
261
- it('rechecks the pinned tree after a Worker finishes importing it', async () => {
262
- const source = await fixture(
263
- 'worker-import-pin',
264
- `return { status: { summary } };`,
265
- {
266
- imports: `
267
- import { summary } from './worker-import-helper.ts';
268
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 200);
269
- `,
270
- },
271
- );
272
- const helper = join(source.sourceRoot, 'worker-import-helper.ts');
273
- await writeFile(helper, `export const summary = 'original';\n`, 'utf8');
274
- const executor = new ThreadBehaviorExecutor({ source, poolSize: 1 });
275
- executors.push(executor);
276
-
277
- const starting = executor.start(new AbortController().signal);
278
- await new Promise((resolve) => setTimeout(resolve, 75));
279
- await writeFile(helper, `export const summary = 'changed';\n`, 'utf8');
280
-
281
- await expect(starting).rejects.toThrow('behavior_source_tree_changed');
282
- });
283
- });