@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,124 +0,0 @@
1
- // src/lib/http-transport.test.ts
2
- import { describe, it, expect, vi, afterEach } from 'vitest';
3
- import { HttpTransport, ApiError } from './http-transport.js';
4
-
5
- const registry: any = { baseUrlFor: () => 'https://hub.example' };
6
-
7
- afterEach(() => { vi.restoreAllMocks(); });
8
-
9
- describe('HttpTransport.getBytes', () => {
10
- it('returns response bytes as a Buffer', async () => {
11
- const bytes = new Uint8Array([1, 2, 3, 4]);
12
- vi.stubGlobal('fetch', vi.fn(async () => new Response(bytes, { status: 200 })));
13
- const t = new HttpTransport('key', registry);
14
- const buf = await t.getBytes('/api/v1/hub/x');
15
- expect(Buffer.isBuffer(buf)).toBe(true);
16
- expect([...buf]).toEqual([1, 2, 3, 4]);
17
- });
18
-
19
- it('throws ApiError on non-ok', async () => {
20
- vi.stubGlobal('fetch', vi.fn(async () => new Response('nope', { status: 404 })));
21
- const t = new HttpTransport('key', registry);
22
- await expect(t.getBytes('/api/v1/hub/x')).rejects.toBeInstanceOf(ApiError);
23
- });
24
- });
25
-
26
- describe('HttpTransport extraHeaders', () => {
27
- it('merges extraHeaders into request() headers', async () => {
28
- let captured: any;
29
- vi.stubGlobal('fetch', vi.fn(async (_url: string, init: any) => { captured = init.headers; return new Response('{}', { status: 200 }); }));
30
- const t = new HttpTransport('key', registry, { 'X-Hub-Auth-Type': 'clawkey' });
31
- await t.request('GET', '/x');
32
- expect(captured['X-Hub-Auth-Type']).toBe('clawkey');
33
- expect(captured['Authorization']).toBe('Bearer key');
34
- });
35
- it('merges extraHeaders into getBytes() headers', async () => {
36
- let captured: any;
37
- vi.stubGlobal('fetch', vi.fn(async (_url: string, init: any) => { captured = init.headers; return new Response(new Uint8Array([1]), { status: 200 }); }));
38
- const t = new HttpTransport('key', registry, { 'X-Hub-Auth-Type': 'clawkey' });
39
- await t.getBytes('/x');
40
- expect(captured['X-Hub-Auth-Type']).toBe('clawkey');
41
- });
42
- });
43
-
44
- describe('HttpTransport per-request headers', () => {
45
- it('merges per-request headers into request() headers', async () => {
46
- let captured: any;
47
- vi.stubGlobal('fetch', vi.fn(async (_url: string, init: any) => { captured = init.headers; return new Response('{}', { status: 200 }); }));
48
- const t = new HttpTransport('key', registry);
49
- await t.post('/api/v1/queue/join', { game_type: 'clawclaw' }, { 'X-Agent-Type': 'claude-code' });
50
- expect(captured['X-Agent-Type']).toBe('claude-code');
51
- expect(captured['Authorization']).toBe('Bearer key');
52
- });
53
-
54
- it('per-request headers override extraHeaders', async () => {
55
- let captured: any;
56
- vi.stubGlobal('fetch', vi.fn(async (_url: string, init: any) => { captured = init.headers; return new Response('{}', { status: 200 }); }));
57
- const t = new HttpTransport('key', registry, { 'X-Agent-Type': 'default' });
58
- await t.request('POST', '/x', undefined, { 'X-Agent-Type': 'override' });
59
- expect(captured['X-Agent-Type']).toBe('override');
60
- });
61
- });
62
-
63
- describe('HttpTransport structured responses', () => {
64
- it('returns non-2xx JSON intact from requestRaw for short-command classification', async () => {
65
- vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({
66
- success: false,
67
- error: { code: 'NOPE', message: 'upstream message' },
68
- }), {
69
- status: 409,
70
- headers: { 'content-type': 'application/json', 'x-request-id': 'req-1' },
71
- })));
72
- const t = new HttpTransport('key', registry);
73
-
74
- await expect(t.requestRaw('POST', '/x', {})).resolves.toMatchObject({
75
- status: 409,
76
- requestId: 'req-1',
77
- body: { kind: 'json', value: { success: false, error: { code: 'NOPE' } } },
78
- });
79
- });
80
-
81
- it('keeps legacy request throwing ApiError with the structured response attached', async () => {
82
- vi.stubGlobal('fetch', vi.fn(async () => new Response('{"error":"nope"}', {
83
- status: 401,
84
- headers: { 'content-type': 'application/json' },
85
- })));
86
- const t = new HttpTransport('key', registry);
87
-
88
- const error = await t.request('GET', '/x').catch((value) => value);
89
- expect(error).toBeInstanceOf(ApiError);
90
- expect(error.response).toMatchObject({ status: 401, body: { kind: 'json' } });
91
- });
92
- });
93
-
94
- describe('HttpTransport owner cancellation', () => {
95
- it('combines the request timeout with the owner AbortSignal', async () => {
96
- const owner = new AbortController();
97
- let requestSignal: AbortSignal | undefined;
98
- vi.stubGlobal('fetch', vi.fn(async (_url: string, init: RequestInit) => {
99
- requestSignal = init.signal as AbortSignal;
100
- return new Response('{}', { status: 200 });
101
- }));
102
- const transport = new HttpTransport('key', registry, {}, owner.signal);
103
-
104
- await transport.requestRaw('GET', '/x');
105
- owner.abort(new Error('owner_stopping'));
106
-
107
- expect(requestSignal?.aborted).toBe(true);
108
- });
109
-
110
- it('combines a caller per-request AbortSignal', async () => {
111
- const request = new AbortController();
112
- let fetchSignal: AbortSignal | undefined;
113
- vi.stubGlobal('fetch', vi.fn(async (_url: string, init: RequestInit) => {
114
- fetchSignal = init.signal as AbortSignal;
115
- return new Response('{}', { status: 200 });
116
- }));
117
- const transport = new HttpTransport('key', registry);
118
-
119
- await transport.get('/api/v1/queue/status', request.signal);
120
- request.abort(new Error('compat_poll_stopped'));
121
-
122
- expect(fetchSignal?.aborted).toBe(true);
123
- });
124
- });
@@ -1,57 +0,0 @@
1
- import { describe, it, expect } from 'vitest';
2
- import { HubClient, parseResourceRef } from './hub-client.js';
3
-
4
- function fakeTransport() {
5
- const calls: any[] = [];
6
- const transport: any = {
7
- calls,
8
- async get(path: string) {
9
- calls.push(['GET', path]);
10
- if (path.includes('/resources/')) return { data: { id: 'abc', type: 'strategy', title: 'T' } };
11
- return { data: { items: [], total: 0, pagination: { mode: 'page', page: 1, limit: 20, hasMore: false } } };
12
- },
13
- async getBytes(path: string) { calls.push(['GETBYTES', path]); return Buffer.from('raw'); },
14
- };
15
- return transport;
16
- }
17
-
18
- describe('parseResourceRef', () => {
19
- it('splits type/id', () => {
20
- expect(parseResourceRef('strategy/ab12cd')).toEqual({ type: 'strategy', id: 'ab12cd' });
21
- expect(parseResourceRef('skill/xyz')).toEqual({ type: 'skill', id: 'xyz' });
22
- expect(parseResourceRef('persona/abc')).toEqual({ type: 'persona', id: 'abc' });
23
- });
24
- it('rejects bad type', () => {
25
- expect(() => parseResourceRef('plugin/abc')).toThrow(/invalid resource ref/);
26
- });
27
- it('rejects missing id', () => {
28
- expect(() => parseResourceRef('strategy/')).toThrow(/invalid resource ref/);
29
- });
30
- });
31
-
32
- describe('HubClient', () => {
33
- it('list builds query and unwraps data', async () => {
34
- const t = fakeTransport();
35
- const res = await new HubClient(t).list({ type: 'skill', sort: 'downloads', q: '抢刀', limit: 10 });
36
- expect(t.calls[0][1]).toBe('/api/client/v1/resources?type=skill&q=%E6%8A%A2%E5%88%80&sort=downloads&limit=10');
37
- expect(res.total).toBe(0);
38
- expect(res.items).toEqual([]);
39
- });
40
- it('list with no opts hits bare endpoint', async () => {
41
- const t = fakeTransport();
42
- await new HubClient(t).list();
43
- expect(t.calls[0][1]).toBe('/api/client/v1/resources');
44
- });
45
- it('getResource builds typed path and unwraps data', async () => {
46
- const t = fakeTransport();
47
- const d = await new HubClient(t).getResource('strategy', 'ab12');
48
- expect(t.calls[0]).toEqual(['GET', '/api/client/v1/resources/strategy/ab12']);
49
- expect(d.id).toBe('abc');
50
- });
51
- it('downloadArtifact hits the /download endpoint (encoding id)', async () => {
52
- const t = fakeTransport();
53
- const buf = await new HubClient(t).downloadArtifact('skill', 'xy z');
54
- expect(t.calls[0]).toEqual(['GETBYTES', '/api/client/v1/resources/skill/xy%20z/download']);
55
- expect(Buffer.isBuffer(buf)).toBe(true);
56
- });
57
- });
@@ -1,135 +0,0 @@
1
- import { describe, it, expect, beforeEach, afterEach } from 'vitest';
2
- import { mkdtempSync, rmSync, existsSync, readFileSync, mkdirSync, writeFileSync } from 'fs';
3
- import { tmpdir } from 'os';
4
- import { join } from 'path';
5
- import { placementRelPath, slugify, installResource, uninstallResource, listInstalled, readLockfile, readPersonaLockfile } from './hub-install.js';
6
- import { ensureUserDataLayout, getUserDataHubStrategyLockfile } from './user-data.js';
7
- import type { ResourceDetail } from './hub-client.js';
8
-
9
- let ws: string;
10
- beforeEach(() => { ws = mkdtempSync(join(tmpdir(), 'ccl-ws-')); process.env.CLAWCLAW_WORKSPACE_DIR = ws; });
11
- afterEach(() => { delete process.env.CLAWCLAW_WORKSPACE_DIR; rmSync(ws, { recursive: true, force: true }); });
12
-
13
- function detail(over: Partial<ResourceDetail>): ResourceDetail {
14
- return {
15
- id: 'ab12', type: 'strategy', title: 'Aggressive Kill', description: 'd',
16
- creator: 'alice', creatorType: 'clawkey', creatorDisplayName: 'Alice', creatorAvatarUrl: null,
17
- fileName: 'kill.ts', stats: { downloadCount: 0, starCount: 0, commentCount: 0 },
18
- downloadUrl: '', likedByMe: false, createdAt: '', updatedAt: '',
19
- artifact: { fileName: 'kill.ts', downloadUrl: '' }, ...over,
20
- };
21
- }
22
-
23
- function u16(n: number): Buffer { const b = Buffer.alloc(2); b.writeUInt16LE(n); return b; }
24
- function u32(n: number): Buffer { const b = Buffer.alloc(4); b.writeUInt32LE(n >>> 0); return b; }
25
- function storeZip(files: Record<string, string>): Buffer {
26
- const locals: Buffer[] = [], centrals: Buffer[] = []; let off = 0; const names = Object.keys(files);
27
- for (const name of names) {
28
- const raw = Buffer.from(files[name], 'utf8'); const nb = Buffer.from(name, 'utf8');
29
- const local = Buffer.concat([u32(0x04034b50), u16(20), u16(0), u16(0), u16(0), u16(0), u32(0), u32(raw.length), u32(raw.length), u16(nb.length), u16(0), nb, raw]);
30
- const central = Buffer.concat([u32(0x02014b50), u16(20), u16(20), u16(0), u16(0), u16(0), u16(0), u32(0), u32(raw.length), u32(raw.length), u16(nb.length), u16(0), u16(0), u16(0), u16(0), u32(0), u32(off), nb]);
31
- locals.push(local); centrals.push(central); off += local.length;
32
- }
33
- const lp = Buffer.concat(locals), cd = Buffer.concat(centrals);
34
- const eocd = Buffer.concat([u32(0x06054b50), u16(0), u16(0), u16(names.length), u16(names.length), u32(cd.length), u32(lp.length), u16(0)]);
35
- return Buffer.concat([lp, cd, eocd]);
36
- }
37
-
38
- describe('slugify', () => {
39
- it('kebabs a title', () => { expect(slugify('Aggressive Kill!')).toBe('aggressive-kill'); });
40
- });
41
-
42
- describe('placementRelPath', () => {
43
- it('rejects legacy strategy placement', () => {
44
- expect(() => placementRelPath(detail({}))).toThrow(/not compatible with Behavior API v3/);
45
- });
46
- it('skill → skills/<slug>', () => {
47
- expect(placementRelPath(detail({ type: 'skill', title: 'Cool Helper' })).split('\\').join('/')).toBe('skills/cool-helper');
48
- });
49
- it('persona → personas/<fileName>', () => {
50
- expect(placementRelPath(detail({ type: 'persona', fileName: 'shy-persona.md' })).split('\\').join('/')).toBe('personas/shy-persona.md');
51
- });
52
- it('persona falls back to <id>.md when no fileName', () => {
53
- expect(placementRelPath(detail({ type: 'persona', fileName: undefined })).split('\\').join('/')).toBe('personas/ab12.md');
54
- });
55
- it('rejects unsafe id', () => {
56
- expect(() => placementRelPath(detail({ id: '..' }))).toThrow(/unsafe id/);
57
- });
58
- });
59
-
60
- describe('installResource (strategy)', () => {
61
- it('rejects the legacy package before creating a strategies directory', () => {
62
- expect(() => installResource(detail({}), Buffer.from('legacy strategy'))).toThrow(/not compatible with Behavior API v3/);
63
- expect(existsSync(join(ws, 'user-data', 'strategies'))).toBe(false);
64
- });
65
- });
66
-
67
- describe('installResource (skill)', () => {
68
- it('unzips into skills/<slug>', () => {
69
- const zip = storeZip({ 'SKILL.md': '# skill', 'refs/a.md': 'A' });
70
- const res = installResource(detail({ id: 'sk1', type: 'skill', title: 'My Skill', fileName: 'pkg.zip' }), zip);
71
- expect(res.installedPath.split('\\').join('/')).toContain('skills/my-skill');
72
- expect(readFileSync(join(res.installedPath, 'SKILL.md'), 'utf8')).toBe('# skill');
73
- expect(readFileSync(join(res.installedPath, 'refs', 'a.md'), 'utf8')).toBe('A');
74
- });
75
- it('rejects zip path traversal', () => {
76
- const zip = storeZip({ '../evil.md': 'x' });
77
- expect(() => installResource(detail({ id: 'sk2', type: 'skill', title: 'T' }), zip)).toThrow(/unsafe path/);
78
- });
79
- });
80
-
81
- describe('installResource (persona)', () => {
82
- it('writes .md file to personas/ + lockfile', () => {
83
- const res = installResource(detail({ type: 'persona', title: 'My Persona', fileName: 'my-persona.md' }), Buffer.from('# persona content'));
84
- expect(existsSync(res.installedPath)).toBe(true);
85
- expect(res.installedPath.split('\\').join('/')).toContain('personas/my-persona.md');
86
- expect(readFileSync(res.installedPath, 'utf8')).toBe('# persona content');
87
- expect(readPersonaLockfile()['persona/ab12'].title).toBe('My Persona');
88
- });
89
- });
90
-
91
- describe('lockfile merge isolation', () => {
92
- it('installing a skill preserves persona entries and vice versa', () => {
93
- // Install a persona first
94
- installResource(detail({ type: 'persona', id: 'p1', title: 'P1' }), Buffer.from('p'));
95
- // Then install a skill
96
- const zip = storeZip({ 'SKILL.md': '# s' });
97
- installResource(detail({ id: 'sk1', type: 'skill', title: 'My Skill', fileName: 'pkg.zip' }), zip);
98
- // Both should be in the merged lockfile
99
- const all = listInstalled();
100
- expect(all.map(e => `${e.type}/${e.id}`).sort()).toEqual(['persona/p1', 'skill/sk1']);
101
- // Uninstall skill — persona should survive
102
- uninstallResource('skill/sk1');
103
- expect(listInstalled().map(e => `${e.type}/${e.id}`)).toEqual(['persona/p1']);
104
- });
105
- });
106
-
107
- describe('uninstall / list', () => {
108
- it('still lists and removes an existing legacy strategy install', () => {
109
- ensureUserDataLayout(ws);
110
- const legacyPath = join(ws, 'user-data', 'strategies', 'legacy.ts');
111
- mkdirSync(join(ws, 'user-data', 'strategies'), { recursive: true });
112
- writeFileSync(legacyPath, 'legacy strategy', 'utf8');
113
- writeFileSync(getUserDataHubStrategyLockfile(ws), JSON.stringify({
114
- 'strategy/ab12': {
115
- type: 'strategy', id: 'ab12', title: 'Aggressive Kill',
116
- path: 'strategies/legacy.ts', installedAt: 'now',
117
- },
118
- }), 'utf8');
119
- expect(listInstalled().map(e => `${e.type}/${e.id}`)).toEqual(['strategy/ab12']);
120
- const r = uninstallResource('strategy/ab12');
121
- expect(r.removed).toBe(true);
122
- expect(r.path).toBe(legacyPath);
123
- expect(existsSync(legacyPath)).toBe(false);
124
- expect(listInstalled()).toEqual([]);
125
- });
126
-
127
- it('uninstalls persona and removes from lockfile', () => {
128
- installResource(detail({ type: 'persona', id: 'p2', title: 'P2' }), Buffer.from('p'));
129
- expect(listInstalled().map(e => `${e.type}/${e.id}`)).toContain('persona/p2');
130
- const r = uninstallResource('persona/p2');
131
- expect(r.removed).toBe(true);
132
- expect(existsSync(r.path!)).toBe(false);
133
- expect(listInstalled()).toEqual([]);
134
- });
135
- });
@@ -1,185 +0,0 @@
1
- // src/lib/hub-install.ts
2
- import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'fs';
3
- import { dirname, join } from 'path';
4
- import { getWorkspaceDir } from './init-command.js';
5
- import type { ResourceType, ResourceDetail } from './hub-client.js';
6
- import { unzip } from './hub-unzip.js';
7
- import {
8
- ensureUserDataLayout,
9
- getUserDataDir,
10
- getUserDataHubStrategyLockfile,
11
- } from './user-data.js';
12
-
13
- export interface InstalledEntry { type: ResourceType; id: string; title: string; path: string; installedAt: string; contentHash?: string; }
14
- export type Lockfile = Record<string, InstalledEntry>; // keyed by "<type>/<id>"
15
-
16
- export function hubDir(): string { return join(getWorkspaceDir(), 'hub'); }
17
- export function lockfilePath(): string { return join(hubDir(), 'installed.json'); }
18
- export function strategyLockfilePath(): string { return getUserDataHubStrategyLockfile(getWorkspaceDir()); }
19
-
20
- function readJsonLockfile(p: string): Lockfile {
21
- if (!existsSync(p)) return {};
22
- try {
23
- return JSON.parse(readFileSync(p, 'utf8')) as Lockfile;
24
- } catch {
25
- console.error(`warning: hub lockfile at ${p} is unreadable or corrupt; treating as empty (installed packages may not be tracked)`);
26
- return {};
27
- }
28
- }
29
-
30
- export function readSkillLockfile(): Lockfile {
31
- return Object.fromEntries(
32
- Object.entries(readJsonLockfile(lockfilePath())).filter(([, entry]) => entry.type === 'skill'),
33
- );
34
- }
35
-
36
- export function readPersonaLockfile(): Lockfile {
37
- return Object.fromEntries(
38
- Object.entries(readJsonLockfile(lockfilePath())).filter(([, entry]) => entry.type === 'persona'),
39
- );
40
- }
41
-
42
- export function readStrategyLockfile(): Lockfile {
43
- ensureUserDataLayout(getWorkspaceDir());
44
- return Object.fromEntries(
45
- Object.entries(readJsonLockfile(strategyLockfilePath())).filter(([, entry]) => entry.type === 'strategy'),
46
- );
47
- }
48
-
49
- export function readLockfile(): Lockfile {
50
- return { ...readSkillLockfile(), ...readPersonaLockfile(), ...readStrategyLockfile() };
51
- }
52
-
53
- /** Merge entries of the given types into hub/installed.json, preserving entries of other types. */
54
- function writeWorkspaceLockfile(lock: Lockfile, types: Set<string>): void {
55
- const existing = readJsonLockfile(lockfilePath());
56
- const preserved = Object.fromEntries(
57
- Object.entries(existing).filter(([, e]) => !types.has(e.type)),
58
- );
59
- const merged = { ...preserved, ...lock };
60
- mkdirSync(hubDir(), { recursive: true });
61
- writeFileSync(lockfilePath(), JSON.stringify(merged, null, 2) + '\n', 'utf8');
62
- }
63
-
64
- function writeSkillLockfile(lock: Lockfile): void {
65
- writeWorkspaceLockfile(lock, new Set(['skill']));
66
- }
67
-
68
- function writePersonaLockfile(lock: Lockfile): void {
69
- writeWorkspaceLockfile(lock, new Set(['persona']));
70
- }
71
-
72
- function writeStrategyLockfile(lock: Lockfile): void {
73
- const p = strategyLockfilePath();
74
- mkdirSync(dirname(p), { recursive: true });
75
- writeFileSync(p, JSON.stringify(lock, null, 2) + '\n', 'utf8');
76
- }
77
-
78
- export function writeLockfile(lock: Lockfile): void {
79
- writeSkillLockfile(Object.fromEntries(Object.entries(lock).filter(([, entry]) => entry.type === 'skill')));
80
- writePersonaLockfile(Object.fromEntries(Object.entries(lock).filter(([, entry]) => entry.type === 'persona')));
81
- writeStrategyLockfile(Object.fromEntries(Object.entries(lock).filter(([, entry]) => entry.type === 'strategy')));
82
- }
83
-
84
- function assertSafeSegment(label: string, s: string): void {
85
- if (!s || s === '.' || s === '..' || /[\\/:\0]/.test(s)) {
86
- throw new Error(`unsafe ${label} segment: '${s}'`);
87
- }
88
- }
89
-
90
- export function slugify(title: string): string {
91
- return title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
92
- }
93
-
94
- /** Install path relative to the workspace for supported Hub resource types. */
95
- export function placementRelPath(detail: { type: ResourceType; id: string; title: string; fileName?: string }): string {
96
- assertSafeSegment('id', detail.id);
97
- if (detail.type === 'strategy') {
98
- throw new Error('Legacy Hub strategy packages are not compatible with Behavior API v3');
99
- }
100
- if (detail.type === 'persona') {
101
- const name = detail.fileName || `${detail.id}.md`;
102
- assertSafeSegment('persona name', name);
103
- return join('personas', name);
104
- }
105
- const slug = slugify(detail.title) || detail.id;
106
- assertSafeSegment('skill dir', slug);
107
- return join('skills', slug);
108
- }
109
-
110
- function makeRef(type: ResourceType, id: string): string { return `${type}/${id}`; }
111
-
112
- export interface InstallResult { ref: string; type: ResourceType; id: string; title: string; installedPath: string; }
113
-
114
- export function installResource(detail: ResourceDetail, artifact: Buffer, opts: { force?: boolean } = {}): InstallResult {
115
- if (detail.type === 'strategy') {
116
- throw new Error('Legacy Hub strategy packages are not compatible with Behavior API v3');
117
- }
118
- const ws = getWorkspaceDir();
119
- ensureUserDataLayout(ws);
120
- const ref = makeRef(detail.type, detail.id);
121
- const relPath = placementRelPath(detail);
122
- const absPath = join(ws, relPath);
123
- const lock = detail.type === 'persona' ? readPersonaLockfile()
124
- : readSkillLockfile();
125
- const tracked = lock[ref] !== undefined;
126
-
127
- if (detail.type === 'persona') {
128
- if (existsSync(absPath) && !tracked && !opts.force) {
129
- throw new Error(`${relPath} already exists and is not tracked by hub; re-run with --force to overwrite`);
130
- }
131
- mkdirSync(join(ws, 'personas'), { recursive: true });
132
- writeFileSync(absPath, artifact);
133
- } else {
134
- if (existsSync(absPath) && !tracked && !opts.force) {
135
- throw new Error(`skills/${slugify(detail.title) || detail.id} already exists and is not tracked by hub; re-run with --force to overwrite`);
136
- }
137
- const entries = unzip(artifact);
138
- for (const e of entries) {
139
- if (e.path.includes('..') || e.path.startsWith('/') || /^[A-Za-z]:/.test(e.path)) {
140
- throw new Error(`unsafe path in skill archive: ${e.path}`);
141
- }
142
- }
143
- // Non-atomic by design: entries are decoded and validated before writing.
144
- if (existsSync(absPath)) rmSync(absPath, { recursive: true, force: true });
145
- mkdirSync(absPath, { recursive: true });
146
- for (const e of entries) {
147
- const target = join(absPath, e.path);
148
- mkdirSync(dirname(target), { recursive: true });
149
- writeFileSync(target, e.content);
150
- }
151
- }
152
-
153
- lock[ref] = {
154
- type: detail.type,
155
- id: detail.id,
156
- title: detail.title,
157
- path: relPath.split('\\').join('/'),
158
- installedAt: new Date().toISOString(),
159
- };
160
- if (detail.type === 'persona') writePersonaLockfile(lock);
161
- else writeSkillLockfile(lock);
162
- return { ref, type: detail.type, id: detail.id, title: detail.title, installedPath: absPath };
163
- }
164
-
165
- export function uninstallResource(ref: string): { removed: boolean; path?: string } {
166
- const type = ref.split('/')[0] as ResourceType;
167
- const lock = type === 'strategy' ? readStrategyLockfile()
168
- : type === 'persona' ? readPersonaLockfile()
169
- : readSkillLockfile();
170
- const entry = lock[ref];
171
- if (!entry) return { removed: false };
172
- const ws = getWorkspaceDir();
173
- const rootDir = type === 'strategy' ? getUserDataDir(ws) : ws;
174
- const abs = join(rootDir, entry.path);
175
- if (existsSync(abs)) rmSync(abs, { recursive: true, force: true });
176
- delete lock[ref];
177
- if (type === 'strategy') writeStrategyLockfile(lock);
178
- else if (type === 'persona') writePersonaLockfile(lock);
179
- else writeSkillLockfile(lock);
180
- return { removed: true, path: abs };
181
- }
182
-
183
- export function listInstalled(): InstalledEntry[] {
184
- return Object.values(readLockfile());
185
- }
@@ -1,69 +0,0 @@
1
- // src/lib/hub-unzip.test.ts
2
- import { describe, it, expect } from 'vitest';
3
- import { deflateRawSync } from 'zlib';
4
- import { unzip } from './hub-unzip.js';
5
-
6
- function u16(n: number): Buffer { const b = Buffer.alloc(2); b.writeUInt16LE(n); return b; }
7
- function u32(n: number): Buffer { const b = Buffer.alloc(4); b.writeUInt32LE(n >>> 0); return b; }
8
-
9
- // Independent minimal ZIP encoder (lays bytes by hand; does NOT use production code).
10
- function buildZip(files: Record<string, string>, opts: { deflate?: boolean } = {}): Buffer {
11
- const deflate = !!opts.deflate;
12
- const locals: Buffer[] = [];
13
- const centrals: Buffer[] = [];
14
- let offset = 0;
15
- const names = Object.keys(files);
16
- for (const name of names) {
17
- const raw = Buffer.from(files[name], 'utf8');
18
- const data = deflate && raw.length ? deflateRawSync(raw) : raw;
19
- const method = deflate && raw.length ? 8 : 0;
20
- const nameBuf = Buffer.from(name, 'utf8');
21
- const local = Buffer.concat([
22
- u32(0x04034b50), u16(20), u16(0), u16(method), u16(0), u16(0),
23
- u32(0), u32(data.length), u32(raw.length), u16(nameBuf.length), u16(0),
24
- nameBuf, data,
25
- ]);
26
- const central = Buffer.concat([
27
- u32(0x02014b50), u16(20), u16(20), u16(0), u16(method), u16(0), u16(0),
28
- u32(0), u32(data.length), u32(raw.length),
29
- u16(nameBuf.length), u16(0), u16(0), u16(0), u16(0), u32(0), u32(offset),
30
- nameBuf,
31
- ]);
32
- locals.push(local);
33
- centrals.push(central);
34
- offset += local.length;
35
- }
36
- const localPart = Buffer.concat(locals);
37
- const cd = Buffer.concat(centrals);
38
- const eocd = Buffer.concat([
39
- u32(0x06054b50), u16(0), u16(0), u16(names.length), u16(names.length),
40
- u32(cd.length), u32(localPart.length), u16(0),
41
- ]);
42
- return Buffer.concat([localPart, cd, eocd]);
43
- }
44
-
45
- describe('unzip', () => {
46
- it('extracts stored (uncompressed) entries', () => {
47
- const z = buildZip({ 'SKILL.md': '# hi', 'dir/sub.ts': 'export const x = 1;' });
48
- const files = unzip(z);
49
- const map = Object.fromEntries(files.map(f => [f.path, f.content.toString('utf8')]));
50
- expect(map['SKILL.md']).toBe('# hi');
51
- expect(map['dir/sub.ts']).toBe('export const x = 1;');
52
- });
53
-
54
- it('extracts deflated entries', () => {
55
- const z = buildZip({ 'a.txt': 'hello hello hello world world world' }, { deflate: true });
56
- const files = unzip(z);
57
- expect(files[0].content.toString('utf8')).toBe('hello hello hello world world world');
58
- });
59
-
60
- it('skips directory entries', () => {
61
- const z = buildZip({ 'dir/': '', 'dir/a.ts': 'A' });
62
- const files = unzip(z);
63
- expect(files.map(f => f.path)).toEqual(['dir/a.ts']);
64
- });
65
-
66
- it('throws on a non-zip buffer', () => {
67
- expect(() => unzip(Buffer.alloc(40))).toThrow(/not a zip|EOCD/i);
68
- });
69
- });
@@ -1,103 +0,0 @@
1
- import { describe, expect, it } from 'vitest';
2
- import { join, resolve } from 'path';
3
- import { mkdtempSync } from 'fs';
4
- import { tmpdir } from 'os';
5
- import {
6
- CLAWCLAW_WORKSPACE_DIR,
7
- getRuntimeAccountId,
8
- getWorkspaceConfigFile,
9
- resolveWorkspaceDir,
10
- } from './init-command.js';
11
-
12
- describe('resolveWorkspaceDir', () => {
13
- it('uses an absolute env override as-is', () => {
14
- expect(
15
- resolveWorkspaceDir({
16
- env: { [CLAWCLAW_WORKSPACE_DIR]: 'D:\\workspaces\\clawclaw' },
17
- platform: 'win32',
18
- homeDir: 'C:\\Users\\test',
19
- cwd: 'C:\\repo',
20
- }),
21
- ).toBe('D:\\workspaces\\clawclaw');
22
- });
23
-
24
- it('resolves a relative env override against cwd', () => {
25
- const cwd = 'C:\\repo\\project';
26
- expect(
27
- resolveWorkspaceDir({
28
- env: { [CLAWCLAW_WORKSPACE_DIR]: 'tmp/clawclaw-workspace' },
29
- platform: 'linux',
30
- homeDir: '/home/test',
31
- cwd,
32
- }),
33
- ).toBe(resolve(cwd, 'tmp/clawclaw-workspace'));
34
- });
35
-
36
- it('ignores a blank env override', () => {
37
- expect(
38
- resolveWorkspaceDir({
39
- env: {
40
- [CLAWCLAW_WORKSPACE_DIR]: ' ',
41
- APPDATA: 'C:\\Users\\test\\AppData\\Roaming',
42
- },
43
- platform: 'win32',
44
- homeDir: 'C:\\Users\\test',
45
- cwd: 'C:\\repo',
46
- }),
47
- ).toBe('C:\\Users\\test\\AppData\\Roaming\\clawclaw');
48
- });
49
-
50
- it('uses APPDATA on win32 when override is not set', () => {
51
- expect(
52
- resolveWorkspaceDir({
53
- env: { APPDATA: 'D:\\AppData' },
54
- platform: 'win32',
55
- homeDir: 'C:\\Users\\test',
56
- cwd: 'C:\\repo',
57
- }),
58
- ).toBe('D:\\AppData\\clawclaw');
59
- });
60
-
61
- it('falls back to home/AppData/Roaming on win32 when APPDATA is missing', () => {
62
- expect(
63
- resolveWorkspaceDir({
64
- env: {},
65
- platform: 'win32',
66
- homeDir: 'C:\\Users\\test',
67
- cwd: 'C:\\repo',
68
- }),
69
- ).toBe('C:\\Users\\test\\AppData\\Roaming\\clawclaw');
70
- });
71
-
72
- it('uses the non-win32 default path when override is not set', () => {
73
- expect(
74
- resolveWorkspaceDir({
75
- env: {},
76
- platform: 'linux',
77
- homeDir: '/home/test',
78
- cwd: '/repo/project',
79
- }),
80
- ).toBe(join('/home/test', '.clawclaw'));
81
- });
82
-
83
- it('resolves the shared workspace config path without assuming its contents', () => {
84
- expect(getWorkspaceConfigFile('/tmp/clawclaw')).toBe(join('/tmp/clawclaw', 'config.json'));
85
- });
86
-
87
- it('derives a stable non-secret runtime account identity', () => {
88
- const apiKey = 'secret-api-key-value';
89
- const stateDir = mkdtempSync(join(tmpdir(), 'ccl-account-id-'));
90
- const first = getRuntimeAccountId({ apiKey }, stateDir);
91
- expect(first).toBe(getRuntimeAccountId({ apiKey }, stateDir));
92
- expect(first).toMatch(/^acct_[a-f0-9]{32}$/);
93
- expect(first).not.toContain(apiKey);
94
- });
95
-
96
- it('prefers the profile-persisted identity across credential paths', () => {
97
- const runtimeAccountId = 'acct_0123456789abcdef0123456789abcdef';
98
- expect(getRuntimeAccountId({ apiKey: 'old', runtimeAccountId }, mkdtempSync(join(tmpdir(), 'ccl-old-'))))
99
- .toBe(runtimeAccountId);
100
- expect(getRuntimeAccountId({ apiKey: 'new', runtimeAccountId }, mkdtempSync(join(tmpdir(), 'ccl-new-'))))
101
- .toBe(runtimeAccountId);
102
- });
103
- });