@myclaw163/clawclaw-cli 0.1.0

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 (238) hide show
  1. package/README.md +434 -0
  2. package/bin/clawclaw-cli.mjs +4 -0
  3. package/package.json +48 -0
  4. package/personas//345/217/243/346/230/257/345/277/203/351/235/236.md +50 -0
  5. package/personas//345/277/240/345/277/203/350/200/201/344/273/206.md +51 -0
  6. package/personas//346/227/240/344/272/272/350/256/276.md +1 -0
  7. package/personas//350/264/253/345/230/264/346/215/237/345/217/213.md +48 -0
  8. package/personas//350/275/257/350/220/214/350/205/271/351/273/221.md +51 -0
  9. package/scripts/check-skill-command-surface.mjs +118 -0
  10. package/scripts/check_monitor.cjs +435 -0
  11. package/scripts/check_monitor.test.mjs +212 -0
  12. package/scripts/enable_ccl_permissions.cjs +164 -0
  13. package/scripts/enable_ccl_permissions.test.mjs +163 -0
  14. package/scripts/enable_monitor.cjs +677 -0
  15. package/scripts/enable_monitor.test.mjs +201 -0
  16. package/scripts/find-hide-spots.py +157 -0
  17. package/scripts/postinstall.mjs +20 -0
  18. package/scripts/sync-bundled-skill.mjs +254 -0
  19. package/scripts/sync-bundled-skill.test.mjs +152 -0
  20. package/skills/clawclaw/.gitkeep +0 -0
  21. package/skills/clawclaw/SKILL.md +275 -0
  22. package/skills/clawclaw/references/CHATTERBOX.md +142 -0
  23. package/skills/clawclaw/references/CLAUDE-CODE-MONITOR.md +224 -0
  24. package/skills/clawclaw/references/COMMANDS.md +165 -0
  25. package/skills/clawclaw/references/GAME-MECHANICS.md +195 -0
  26. package/skills/clawclaw/references/HUB.md +48 -0
  27. package/skills/clawclaw/references/KNOWLEDGE.md +42 -0
  28. package/skills/clawclaw/references/STRATEGIES.md +59 -0
  29. package/skills/clawclaw/references/STREAM.md +75 -0
  30. package/skills/clawclaw/references/TACTICS.md +65 -0
  31. package/src/assets/clawclaw-ascii-map.txt +40 -0
  32. package/src/cli.ts +113 -0
  33. package/src/commands/_schema.ts +124 -0
  34. package/src/commands/account.test.ts +391 -0
  35. package/src/commands/account.ts +338 -0
  36. package/src/commands/competition.ts +42 -0
  37. package/src/commands/config.ts +30 -0
  38. package/src/commands/data.test.ts +33 -0
  39. package/src/commands/data.ts +22 -0
  40. package/src/commands/do.test.ts +117 -0
  41. package/src/commands/do.ts +195 -0
  42. package/src/commands/events.test.ts +144 -0
  43. package/src/commands/events.ts +268 -0
  44. package/src/commands/game-map.test.ts +28 -0
  45. package/src/commands/game-monitor-status.test.ts +58 -0
  46. package/src/commands/game-start-plan.test.ts +356 -0
  47. package/src/commands/game.ts +2046 -0
  48. package/src/commands/history-player.test.ts +105 -0
  49. package/src/commands/history.ts +573 -0
  50. package/src/commands/hub.test.ts +134 -0
  51. package/src/commands/hub.ts +249 -0
  52. package/src/commands/knowledge.test.ts +13 -0
  53. package/src/commands/knowledge.ts +176 -0
  54. package/src/commands/load.test.ts +107 -0
  55. package/src/commands/load.ts +26 -0
  56. package/src/commands/meeting-history.test.ts +106 -0
  57. package/src/commands/memory.ts +40 -0
  58. package/src/commands/peek.ts +45 -0
  59. package/src/commands/persona.ts +62 -0
  60. package/src/commands/setup/codex.ts +266 -0
  61. package/src/commands/setup/hermes.test.ts +96 -0
  62. package/src/commands/setup/hermes.ts +76 -0
  63. package/src/commands/setup/index.ts +13 -0
  64. package/src/commands/setup/openclaw.test.ts +124 -0
  65. package/src/commands/setup/openclaw.ts +162 -0
  66. package/src/commands/skill.ts +128 -0
  67. package/src/commands/state.ts +46 -0
  68. package/src/commands/strategy.test.ts +172 -0
  69. package/src/commands/strategy.ts +170 -0
  70. package/src/commands/upgrade.test.ts +82 -0
  71. package/src/commands/upgrade.ts +157 -0
  72. package/src/commands/watch.test.ts +1313 -0
  73. package/src/commands/watch.ts +824 -0
  74. package/src/lib/account-guidance.test.ts +32 -0
  75. package/src/lib/account-guidance.ts +62 -0
  76. package/src/lib/auth.test.ts +116 -0
  77. package/src/lib/auth.ts +189 -0
  78. package/src/lib/command-meta.ts +37 -0
  79. package/src/lib/competition.ts +79 -0
  80. package/src/lib/custom-tts.test.ts +387 -0
  81. package/src/lib/custom-tts.ts +463 -0
  82. package/src/lib/game-client-tts.test.ts +151 -0
  83. package/src/lib/game-client.test.ts +82 -0
  84. package/src/lib/game-client.ts +472 -0
  85. package/src/lib/game-context.ts +92 -0
  86. package/src/lib/host-config-patcher.test.ts +130 -0
  87. package/src/lib/host-config-patcher.ts +151 -0
  88. package/src/lib/http-keepalive.ts +15 -0
  89. package/src/lib/http-transport.test.ts +61 -0
  90. package/src/lib/http-transport.ts +118 -0
  91. package/src/lib/hub-client.test.ts +57 -0
  92. package/src/lib/hub-client.ts +88 -0
  93. package/src/lib/hub-install.test.ts +157 -0
  94. package/src/lib/hub-install.ts +213 -0
  95. package/src/lib/hub-reminder.ts +69 -0
  96. package/src/lib/hub-unzip.test.ts +69 -0
  97. package/src/lib/hub-unzip.ts +62 -0
  98. package/src/lib/init-command.test.ts +79 -0
  99. package/src/lib/init-command.ts +136 -0
  100. package/src/lib/knowledge-store.test.ts +170 -0
  101. package/src/lib/knowledge-store.ts +369 -0
  102. package/src/lib/load-context.test.ts +62 -0
  103. package/src/lib/load-context.ts +49 -0
  104. package/src/lib/match-state.test.ts +134 -0
  105. package/src/lib/match-state.ts +94 -0
  106. package/src/lib/normalize.ts +42 -0
  107. package/src/lib/persona.test.ts +84 -0
  108. package/src/lib/persona.ts +120 -0
  109. package/src/lib/room.test.ts +74 -0
  110. package/src/lib/room.ts +129 -0
  111. package/src/lib/server-registry.test.ts +54 -0
  112. package/src/lib/server-registry.ts +185 -0
  113. package/src/lib/skill-version.test.ts +48 -0
  114. package/src/lib/skill-version.ts +19 -0
  115. package/src/lib/strategy-export.test.ts +314 -0
  116. package/src/lib/strategy-export.ts +352 -0
  117. package/src/lib/user-data.test.ts +98 -0
  118. package/src/lib/user-data.ts +370 -0
  119. package/src/lib/workspace-argv.test.ts +49 -0
  120. package/src/lib/workspace-argv.ts +44 -0
  121. package/src/perception/player-history-store.test.ts +177 -0
  122. package/src/perception/player-history-store.ts +262 -0
  123. package/src/pipeline/event-format.test.ts +327 -0
  124. package/src/pipeline/event-format.ts +595 -0
  125. package/src/pipeline/event-hints.ts +204 -0
  126. package/src/pipeline/event-store.test.ts +28 -0
  127. package/src/pipeline/event-store.ts +193 -0
  128. package/src/pipeline/pipeline.ts +35 -0
  129. package/src/pipeline/player-projection.test.ts +168 -0
  130. package/src/pipeline/player-projection.ts +370 -0
  131. package/src/runtime/auto-upgrade.test.ts +66 -0
  132. package/src/runtime/auto-upgrade.ts +31 -0
  133. package/src/runtime/event-daemon.test.ts +268 -0
  134. package/src/runtime/event-daemon.ts +531 -0
  135. package/src/runtime/owner-control.ts +150 -0
  136. package/src/runtime/raw-ws-log.test.ts +33 -0
  137. package/src/runtime/raw-ws-log.ts +32 -0
  138. package/src/runtime/room-lobby-runtime.test.ts +95 -0
  139. package/src/runtime/room-lobby-runtime.ts +367 -0
  140. package/src/runtime/runtime-logger.ts +107 -0
  141. package/src/runtime/ws-client.test.ts +169 -0
  142. package/src/runtime/ws-client.ts +280 -0
  143. package/src/sdk/action.ts +155 -0
  144. package/src/sdk/index.ts +112 -0
  145. package/src/sdk/types.ts +163 -0
  146. package/src/strategies/avoid-lone.ts +14 -0
  147. package/src/strategies/avoid-players.knowledge.md +19 -0
  148. package/src/strategies/avoid-players.ts +18 -0
  149. package/src/strategies/corpse-patrol.ts +21 -0
  150. package/src/strategies/crab-sabotage.ts +24 -0
  151. package/src/strategies/custom-module.test.ts +270 -0
  152. package/src/strategies/find-player.ts +19 -0
  153. package/src/strategies/game-utils.test.ts +242 -0
  154. package/src/strategies/game-utils.ts +853 -0
  155. package/src/strategies/goals/anchor-linger.ts +77 -0
  156. package/src/strategies/goals/avoid-lone-top.ts +168 -0
  157. package/src/strategies/goals/avoid-players-top.test.ts +83 -0
  158. package/src/strategies/goals/avoid-players-top.ts +121 -0
  159. package/src/strategies/goals/conversation-goal.ts +51 -0
  160. package/src/strategies/goals/corpse-patrol-top.ts +113 -0
  161. package/src/strategies/goals/crab-octopus-reflexes.ts +101 -0
  162. package/src/strategies/goals/crab-sabotage-top.ts +226 -0
  163. package/src/strategies/goals/emergency-hunt-goal.ts +28 -0
  164. package/src/strategies/goals/find-player-top.ts +93 -0
  165. package/src/strategies/goals/flee-players-goal.ts +53 -0
  166. package/src/strategies/goals/follow-companion-goal.ts +106 -0
  167. package/src/strategies/goals/goal-manager.ts +41 -0
  168. package/src/strategies/goals/goal-root-strategy.ts +49 -0
  169. package/src/strategies/goals/goal.ts +28 -0
  170. package/src/strategies/goals/hide-top.ts +197 -0
  171. package/src/strategies/goals/keep-away-goal.ts +221 -0
  172. package/src/strategies/goals/kill-frenzy-top.ts +80 -0
  173. package/src/strategies/goals/kill-lone-top.ts +160 -0
  174. package/src/strategies/goals/kill-target-goal.ts +59 -0
  175. package/src/strategies/goals/kill-target-top.ts +109 -0
  176. package/src/strategies/goals/leaf-goal.ts +27 -0
  177. package/src/strategies/goals/linger-corpse-goal.ts +35 -0
  178. package/src/strategies/goals/lone-kill-core.ts +82 -0
  179. package/src/strategies/goals/lone-kill-goal.ts +24 -0
  180. package/src/strategies/goals/lone-kill-task-top.test.ts +85 -0
  181. package/src/strategies/goals/lone-kill-task-top.ts +133 -0
  182. package/src/strategies/goals/move-room-goal.ts +60 -0
  183. package/src/strategies/goals/normal-shrimp-top.test.ts +97 -0
  184. package/src/strategies/goals/normal-shrimp-top.ts +248 -0
  185. package/src/strategies/goals/paradise-fish-top.test.ts +126 -0
  186. package/src/strategies/goals/paradise-fish-top.ts +224 -0
  187. package/src/strategies/goals/patrol-top.ts +57 -0
  188. package/src/strategies/goals/report-patrol-top.ts +86 -0
  189. package/src/strategies/goals/safe-task-goal.ts +102 -0
  190. package/src/strategies/goals/social-task-top.ts +161 -0
  191. package/src/strategies/goals/task-kill-report-top.ts +163 -0
  192. package/src/strategies/goals/task-only-top.ts +57 -0
  193. package/src/strategies/goals/task-or-patrol-goal.ts +41 -0
  194. package/src/strategies/goals/task-report-top.ts +57 -0
  195. package/src/strategies/goals/wander-task-goal.ts +33 -0
  196. package/src/strategies/goals/warrior-shrimp-top.test.ts +87 -0
  197. package/src/strategies/goals/warrior-shrimp-top.ts +267 -0
  198. package/src/strategies/greeting.ts +53 -0
  199. package/src/strategies/hide-spots.ts +59 -0
  200. package/src/strategies/hide.ts +26 -0
  201. package/src/strategies/kill-frenzy.ts +15 -0
  202. package/src/strategies/kill-lone.knowledge.md +17 -0
  203. package/src/strategies/kill-lone.ts +16 -0
  204. package/src/strategies/kill-target.ts +21 -0
  205. package/src/strategies/knowledge-contract.ts +85 -0
  206. package/src/strategies/loader.test.ts +710 -0
  207. package/src/strategies/loader.ts +183 -0
  208. package/src/strategies/lone-kill-task.ts +24 -0
  209. package/src/strategies/meeting-gate.test.ts +59 -0
  210. package/src/strategies/meeting-gate.ts +28 -0
  211. package/src/strategies/move-room.ts +18 -0
  212. package/src/strategies/new-events-backfill.ts +98 -0
  213. package/src/strategies/off-route-points.ts +105 -0
  214. package/src/strategies/paradise-fish.knowledge.md +19 -0
  215. package/src/strategies/paradise-fish.ts +24 -0
  216. package/src/strategies/pathfind/clawclaw-walkable.bin +0 -0
  217. package/src/strategies/pathfind/distance-field.ts +150 -0
  218. package/src/strategies/pathfind/escape-planner.test.ts +197 -0
  219. package/src/strategies/pathfind/escape-planner.ts +355 -0
  220. package/src/strategies/pathfind/walkable-grid.ts +117 -0
  221. package/src/strategies/patrol.ts +14 -0
  222. package/src/strategies/player-targets.ts +13 -0
  223. package/src/strategies/report-patrol.ts +14 -0
  224. package/src/strategies/scanner.ts +238 -0
  225. package/src/strategies/shrimp-memory.knowledge.md +19 -0
  226. package/src/strategies/shrimp-memory.ts +24 -0
  227. package/src/strategies/social-task.test.ts +28 -0
  228. package/src/strategies/social-task.ts +52 -0
  229. package/src/strategies/spawn.ts +82 -0
  230. package/src/strategies/speech-module.ts +123 -0
  231. package/src/strategies/strategy-loop.test.ts +15 -0
  232. package/src/strategies/strategy-loop.ts +748 -0
  233. package/src/strategies/task-kill-report.ts +20 -0
  234. package/src/strategies/task-only.ts +14 -0
  235. package/src/strategies/task-report.ts +21 -0
  236. package/src/strategies/types.ts +155 -0
  237. package/src/strategies/warrior-memory.knowledge.md +21 -0
  238. package/src/strategies/warrior-memory.ts +19 -0
@@ -0,0 +1,172 @@
1
+ // src/commands/strategy.test.ts
2
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
3
+ import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync, existsSync } from 'fs';
4
+ import { tmpdir } from 'os';
5
+ import { join } from 'path';
6
+ import { createStrategyCommand } from './strategy.js';
7
+
8
+ let ws: string;
9
+ let logs: string[];
10
+ let errs: string[];
11
+
12
+ beforeEach(() => {
13
+ ws = mkdtempSync(join(tmpdir(), 'ccl-strategy-cmd-'));
14
+ process.env.CLAWCLAW_WORKSPACE_DIR = ws;
15
+ logs = []; errs = [];
16
+ vi.spyOn(console, 'log').mockImplementation((...a) => { logs.push(a.join(' ')); });
17
+ vi.spyOn(console, 'error').mockImplementation((...a) => { errs.push(a.join(' ')); });
18
+ vi.spyOn(process, 'exit').mockImplementation((() => { throw new Error('process.exit'); }) as any);
19
+ });
20
+
21
+ afterEach(() => {
22
+ delete process.env.CLAWCLAW_WORKSPACE_DIR;
23
+ vi.restoreAllMocks();
24
+ rmSync(ws, { recursive: true, force: true });
25
+ });
26
+
27
+ async function run(argv: string[]) {
28
+ const cmd = createStrategyCommand();
29
+ await cmd.parseAsync(['node', 'ccl', ...argv]);
30
+ }
31
+
32
+ function userStrategiesDir(): string {
33
+ return join(ws, 'user-data', 'strategies');
34
+ }
35
+
36
+ function officialManifestFile(): string {
37
+ return join(userStrategiesDir(), '.official-manifest.json');
38
+ }
39
+
40
+ describe('strategy command', () => {
41
+ describe('--export', () => {
42
+ it('should export a valid strategy', async () => {
43
+ await run(['--export', 'task-only']);
44
+
45
+ const strategyFile = join(userStrategiesDir(), 'task-only.ts');
46
+ expect(logs[0]).toContain('task-only');
47
+ expect(logs[0]).toContain('exported');
48
+
49
+ const content = readFileSync(strategyFile, 'utf8');
50
+ expect(content).toContain('// Exported from task-only@');
51
+ expect(content).toContain("from '@myclaw163/clawclaw-cli'");
52
+ });
53
+
54
+ it('should export with --force to overwrite', async () => {
55
+ // First export
56
+ await run(['--export', 'task-only']);
57
+
58
+ // Modify the file
59
+ const strategyFile = join(userStrategiesDir(), 'task-only.ts');
60
+ writeFileSync(strategyFile, '// customized', 'utf8');
61
+
62
+ // Re-export with --force
63
+ await run(['--export', 'task-only', '--force']);
64
+
65
+ const content = readFileSync(strategyFile, 'utf8');
66
+ expect(content).toContain('// Exported from task-only@');
67
+ });
68
+
69
+ it('should export a formerly goal-based strategy with its knowledge sidecar', async () => {
70
+ await run(['--export', 'kill-lone']);
71
+
72
+ expect(existsSync(join(userStrategiesDir(), 'kill-lone.ts'))).toBe(true);
73
+ expect(existsSync(join(userStrategiesDir(), 'kill-lone.knowledge.md'))).toBe(true);
74
+ });
75
+
76
+ it('should reject non-existent strategies', async () => {
77
+ await expect(run(['--export', 'non-existent'])).rejects.toThrow('process.exit');
78
+
79
+ expect(errs[0]).toContain('export_failed');
80
+ expect(errs[0]).toContain('not found');
81
+ });
82
+
83
+ it('should warn about other stale strategies after export', async () => {
84
+ // Export two strategies
85
+ await run(['--export', 'task-only']);
86
+ await run(['--export', 'kill-lone']);
87
+ logs = []; errs = [];
88
+
89
+ // Tamper kill-lone's hash to make it stale
90
+ const manifestFile = officialManifestFile();
91
+ const manifest = JSON.parse(readFileSync(manifestFile, 'utf8'));
92
+ manifest['kill-lone'].sourceHash = 'stale';
93
+ writeFileSync(manifestFile, JSON.stringify(manifest), 'utf8');
94
+
95
+ // Re-export task-only — should warn about kill-lone being stale
96
+ await run(['--export', 'task-only', '--force']);
97
+
98
+ expect(errs.join(' ')).toContain('kill-lone');
99
+ expect(errs.join(' ')).toContain('提示');
100
+ });
101
+ });
102
+
103
+ describe('--info', () => {
104
+ it('should show strategy info', async () => {
105
+ await run(['--info', 'task-only']);
106
+
107
+ expect(logs[0]).toContain('"id": "task-only"');
108
+ expect(logs[0]).toContain('"description"');
109
+ });
110
+
111
+ it('should show knowledge contract if available', async () => {
112
+ await run(['--info', 'task-report']);
113
+
114
+ const output = JSON.parse(logs[0]);
115
+ expect(output.id).toBe('task-report');
116
+ expect(output.description).toBeDefined();
117
+ // knowledge might be null if no .knowledge.md file exists
118
+ });
119
+
120
+ it('should resolve a Chinese name and show its knowledge contract', async () => {
121
+ await run(['--info', '武士虾']);
122
+
123
+ const output = JSON.parse(logs[0]);
124
+ expect(output.id).toBe('warrior-memory');
125
+ expect(output.name).toBe('武士虾');
126
+ expect(output.knowledge).toContain('warrior-memory');
127
+ });
128
+
129
+ it('should reject non-existent strategies', async () => {
130
+ await expect(run(['--info', 'non-existent'])).rejects.toThrow('process.exit');
131
+
132
+ expect(errs[0]).toContain('unknown_strategy');
133
+ expect(errs[0]).toContain('non-existent');
134
+ });
135
+
136
+ it('does not execute top-level code while reading strategy info', async () => {
137
+ const marker = join(ws, 'strategy-info-marker.txt');
138
+ mkdirSync(userStrategiesDir(), { recursive: true });
139
+ writeFileSync(join(userStrategiesDir(), 'info-marker.ts'), `
140
+ import { writeFileSync } from 'fs';
141
+ writeFileSync(${JSON.stringify(marker)}, 'executed', 'utf8');
142
+ export const strategy = {
143
+ id: 'info-marker',
144
+ name: 'Info Marker',
145
+ description: 'static metadata',
146
+ create: () => ({ name: 'info-marker', decide: () => [] }),
147
+ };`, 'utf8');
148
+ const { reload } = await import('../strategies/loader.js');
149
+ await reload();
150
+ await run(['--info', 'info-marker']);
151
+ expect(JSON.parse(logs[0]).id).toBe('info-marker');
152
+ expect(existsSync(marker)).toBe(false);
153
+ });
154
+ });
155
+
156
+ describe('--list', () => {
157
+ it('should list all available strategies', async () => {
158
+ await run(['--list']);
159
+
160
+ const output = JSON.parse(logs[0]);
161
+ expect(output.strategies).toBeDefined();
162
+ expect(Array.isArray(output.strategies)).toBe(true);
163
+ expect(output.strategies.length).toBeGreaterThan(0);
164
+
165
+ // Check that task-only is in the list
166
+ const taskOnly = output.strategies.find((s: any) => s.id === 'task-only');
167
+ expect(taskOnly).toBeDefined();
168
+ expect(taskOnly.name).toBe('纯任务');
169
+ expect(taskOnly.description).toBeDefined();
170
+ });
171
+ });
172
+ });
@@ -0,0 +1,170 @@
1
+ import { Command, Option } from 'commander';
2
+ import { GameClient } from '../lib/game-client.js';
3
+ import { getProfileStateDir, getWorkspaceDir } from '../lib/init-command.js';
4
+ import { AuthStore } from '../lib/auth.js';
5
+ import { sendOwnerControlRequest } from '../runtime/owner-control.js';
6
+ import { ensureUserDataLayout, getUserDataStrategiesDir } from '../lib/user-data.js';
7
+
8
+ const KILL_STRATEGIES = new Set([
9
+ 'kill-frenzy', 'kill-lone', 'kill-target', 'warrior-memory',
10
+ 'crab-sabotage', 'lone-kill-task', 'task-kill-report',
11
+ ]);
12
+ const KILL_CAPABLE_ROLES = new Set([
13
+ 'crab_generic', 'shrimp_warrior', 'shrimp_pistol', 'neutral_octopus',
14
+ ]);
15
+
16
+ export function createStrategyCommand(): Command {
17
+ const cmd = new Command('strategy')
18
+ .alias('stg')
19
+ .description('Run a named strategy, or manage exported strategies')
20
+ .argument('[name]', 'Strategy name to start')
21
+ .argument('[args...]', 'Strategy arguments')
22
+ .option('--list', 'List all available strategies')
23
+ .addOption(new Option('--stop', 'Stop any running strategy').hideHelp())
24
+ .option('--info <id>', 'Show a strategy\'s knowledge contract')
25
+ .addOption(new Option('--export <id>', 'Export an official strategy to workspace for customization').hideHelp())
26
+ .addOption(new Option('--force', 'Force overwrite if strategy file already exists (use with --export)').hideHelp())
27
+ .allowUnknownOption()
28
+ .addHelpText('after', () => {
29
+ const workspaceDir = getWorkspaceDir();
30
+ ensureUserDataLayout(workspaceDir);
31
+ const strategiesDir = getUserDataStrategiesDir(workspaceDir);
32
+ return `
33
+ Official and custom strategies:
34
+ Place .ts or .js files in ${strategiesDir}
35
+ (or $CLAWCLAW_WORKSPACE_DIR/user-data/strategies/)
36
+ Each file must export a 'strategy' object with id, name (中文别名), description, and create() function.
37
+ Use 'import { ... } from "@myclaw163/clawclaw-cli"' to access Action, GameState, and utilities.
38
+ See docs/自定义策略.md for full API reference and examples.
39
+ `;
40
+ })
41
+ .action(async (name: string | undefined, args: string[], opts: { list?: boolean; stop?: boolean; info?: string; export?: string; force?: boolean }) => {
42
+ if (opts.info) {
43
+ const { getStrategySummary, getStrategyKnowledgeDoc, listStrategySummaries } = await import('../strategies/loader.js');
44
+ const entry = await getStrategySummary(opts.info);
45
+ if (!entry) {
46
+ const available = await listStrategySummaries();
47
+ console.error(JSON.stringify({
48
+ error: 'unknown_strategy',
49
+ message: `Unknown strategy '${opts.info}'.`,
50
+ available: available.map(e => e.id),
51
+ }, null, 2));
52
+ process.exit(1);
53
+ }
54
+ const knowledge = await getStrategyKnowledgeDoc(entry.id);
55
+ console.log(JSON.stringify({ id: entry.id, name: entry.name ?? entry.id, description: entry.description, knowledge: knowledge ?? null }, null, 2));
56
+ return;
57
+ }
58
+
59
+ if (opts.export) {
60
+ try {
61
+ const { exportStrategy } = await import('../lib/strategy-export.js');
62
+ await exportStrategy(opts.export, { force: opts.force ?? false });
63
+ console.log(JSON.stringify({ message: `Strategy '${opts.export}' exported to user-data strategies.`, path: `${opts.export}.ts` }, null, 2));
64
+ } catch (err: any) {
65
+ console.error(JSON.stringify({ error: 'export_failed', message: err?.message ?? String(err) }, null, 2));
66
+ process.exit(1);
67
+ }
68
+
69
+ // After exporting, check if there are other stale strategies.
70
+ try {
71
+ const { detectStaleOfficialStrategies } = await import('../lib/strategy-export.js');
72
+ const staleIds = detectStaleOfficialStrategies().filter(id => id !== opts.export);
73
+ if (staleIds.length > 0) {
74
+ const ids = staleIds.join(', ');
75
+ console.error(`[提示] 还有其他玩家版本与最新官方模板不同 (${ids});如需放弃本地修改并恢复官方版,运行 \`ccl strategy --export <id> --force\``);
76
+ }
77
+ } catch {
78
+ // Silently ignore
79
+ }
80
+
81
+ return;
82
+ }
83
+
84
+ if (opts.list) {
85
+ const { listStrategySummaries } = await import('../strategies/loader.js');
86
+ const strategies = await listStrategySummaries();
87
+ if (strategies.length === 0) {
88
+ console.log(JSON.stringify({ strategies: [], message: 'No strategies found.' }, null, 2));
89
+ return;
90
+ }
91
+ console.log(JSON.stringify({ strategies }, null, 2));
92
+ return;
93
+ }
94
+
95
+ if (opts.stop) {
96
+ const profile = new AuthStore().getActive();
97
+ const response = profile
98
+ ? await sendOwnerControlRequest(getProfileStateDir(profile), 'stop_strategy')
99
+ : null;
100
+ if (!response?.ok) {
101
+ console.error(JSON.stringify({
102
+ error: 'no_game_start_owner',
103
+ message: 'No active ccl game start owner is available to stop strategy.',
104
+ }, null, 2));
105
+ process.exit(1);
106
+ }
107
+ console.log(JSON.stringify({ message: 'Strategy stopped.' }, null, 2));
108
+ return;
109
+ }
110
+
111
+ if (!name) {
112
+ cmd.help();
113
+ return;
114
+ }
115
+
116
+ const { listStrategySummaries, getStrategySummary } = await import('../strategies/loader.js');
117
+ const entry = await getStrategySummary(name);
118
+ if (!entry) {
119
+ const available = await listStrategySummaries();
120
+ console.error(JSON.stringify({
121
+ error: 'unknown_strategy',
122
+ message: `Unknown strategy '${name}'.`,
123
+ available: available.map(e => ({ id: e.id, name: e.name ?? e.id, description: e.description })),
124
+ }, null, 2));
125
+ process.exit(1);
126
+ }
127
+
128
+ if (KILL_STRATEGIES.has(entry.id)) {
129
+ try {
130
+ const client = GameClient.fromAuth();
131
+ await client.discoverGameServer();
132
+ const roleInfo = await client.getRoleInfo();
133
+ const role: string = roleInfo?.data?.role ?? roleInfo?.role ?? '';
134
+ const displayName: string = roleInfo?.data?.display_name ?? role;
135
+ if (role && !KILL_CAPABLE_ROLES.has(role)) {
136
+ console.error(JSON.stringify({
137
+ error: 'role_incompatible',
138
+ message: `Strategy '${entry.id}' requires kill ability, but your role '${displayName}' (${role}) cannot kill. Use a non-kill strategy like task-report, patrol, or report-patrol.`,
139
+ strategy: entry.id,
140
+ role,
141
+ }, null, 2));
142
+ process.exit(1);
143
+ }
144
+ } catch {}
145
+ }
146
+
147
+ const profile = new AuthStore().getActive();
148
+ const response = profile
149
+ ? await sendOwnerControlRequest(getProfileStateDir(profile), 'switch_strategy', {
150
+ strategy: entry.id,
151
+ args: args.length > 0 ? args : undefined,
152
+ })
153
+ : null;
154
+ if (!response?.ok) {
155
+ console.error(JSON.stringify({
156
+ error: 'no_game_start_owner',
157
+ message: 'Run `ccl game start` before switching strategy; strategy processes are owned by the game start runtime.',
158
+ }, null, 2));
159
+ process.exit(1);
160
+ }
161
+ console.log(JSON.stringify({
162
+ message: `Strategy started: ${entry.id}`,
163
+ name: entry.name ?? entry.id,
164
+ description: entry.description,
165
+ pid: response.pid,
166
+ }, null, 2));
167
+ });
168
+
169
+ return cmd;
170
+ }
@@ -0,0 +1,82 @@
1
+ import { mkdirSync, mkdtempSync, writeFileSync } from 'fs';
2
+ import { tmpdir } from 'os';
3
+ import { join, resolve } from 'path';
4
+ import { describe, expect, it } from 'vitest';
5
+ import { installLatestFromNpm, runUpgrade, syncSkillFromInstalledPackage } from './upgrade.js';
6
+
7
+ describe('runUpgrade', () => {
8
+ it('installs and returns the installed cli version without syncing skill again', () => {
9
+ let installed = false;
10
+ const result = runUpgrade({
11
+ installLatest: () => { installed = true; },
12
+ readInstalledCliVersion: () => '0.4.7',
13
+ });
14
+ expect(installed).toBe(true);
15
+ expect(result).toEqual({ version: '0.4.7' });
16
+ });
17
+
18
+ it('reports error when npm install fails', () => {
19
+ const result = runUpgrade({
20
+ installLatest: () => { throw new Error('EACCES'); },
21
+ readInstalledCliVersion: () => '0.3.4',
22
+ });
23
+ expect(result.version).toBeUndefined();
24
+ expect(result.error).toMatch(/npm install failed/);
25
+ });
26
+
27
+ it('installs latest from npm without registry flag', () => {
28
+ const calls: Array<{ file: string; args: string[]; options: Record<string, unknown> }> = [];
29
+ installLatestFromNpm('clawclaw-cli', (file, args, options) => {
30
+ calls.push({ file, args, options });
31
+ });
32
+
33
+ expect(calls).toHaveLength(1);
34
+ if (process.platform === 'win32') {
35
+ expect(calls[0].file).toBe('cmd.exe');
36
+ expect(calls[0].args).toEqual([
37
+ '/d',
38
+ '/c',
39
+ 'npm.cmd install -g clawclaw-cli@latest --foreground-scripts --loglevel=error',
40
+ ]);
41
+ } else {
42
+ expect(calls[0].args).toEqual([
43
+ 'install',
44
+ '-g',
45
+ 'clawclaw-cli@latest',
46
+ '--foreground-scripts',
47
+ '--loglevel=error',
48
+ ]);
49
+ }
50
+ expect(calls[0].options.stdio).toEqual(['ignore', 'ignore', 'inherit']);
51
+ expect(calls[0].options.shell).toBe(false);
52
+ });
53
+
54
+ it('runs bundled skill sync script for explicit skill update', () => {
55
+ const root = mkdtempSync(join(tmpdir(), 'upgrade-skill-'));
56
+ const installDir = join(root, 'clawclaw-cli');
57
+ const scriptPath = join(installDir, 'scripts', 'sync-bundled-skill.mjs');
58
+ mkdirSync(join(installDir, 'scripts'), { recursive: true });
59
+ writeFileSync(scriptPath, '');
60
+
61
+ const calls: Array<{ file: string; args: string[]; options: Record<string, unknown> }> = [];
62
+ syncSkillFromInstalledPackage('clawclaw-cli', (file, args, options) => {
63
+ calls.push({ file, args, options });
64
+ if (args[0] === 'root' || args.at(-1)?.includes('root -g')) return root;
65
+ return '';
66
+ });
67
+
68
+ expect(calls).toHaveLength(2);
69
+ expect(calls[1].file).toBe(process.execPath);
70
+ expect(calls[1].args).toEqual([resolve(scriptPath)]);
71
+ expect(calls[1].options.stdio).toBe('inherit');
72
+ });
73
+
74
+ it('reports error when reading installed version fails', () => {
75
+ const result = runUpgrade({
76
+ installLatest: () => {},
77
+ readInstalledCliVersion: () => { throw new Error('missing package'); },
78
+ });
79
+ expect(result.version).toBeUndefined();
80
+ expect(result.error).toMatch(/read installed cli version failed/);
81
+ });
82
+ });
@@ -0,0 +1,157 @@
1
+ import { Command } from 'commander';
2
+ import { execFileSync } from 'child_process';
3
+ import { existsSync, readFileSync } from 'fs';
4
+ import { dirname, resolve } from 'path';
5
+ import { fileURLToPath } from 'url';
6
+
7
+ const NPM_INSTALL_TIMEOUT_MS = 30_000;
8
+
9
+ export interface UpgradeDeps {
10
+ installLatest: () => void;
11
+ readInstalledCliVersion: () => string;
12
+ }
13
+
14
+ export interface UpgradeResult {
15
+ version?: string;
16
+ error?: string;
17
+ }
18
+
19
+ export function runUpgrade(deps: UpgradeDeps): UpgradeResult {
20
+ try {
21
+ deps.installLatest();
22
+ } catch (err: any) {
23
+ return { error: `npm install failed: ${err?.message ?? String(err)}` };
24
+ }
25
+
26
+ let version: string;
27
+ try {
28
+ version = deps.readInstalledCliVersion();
29
+ } catch (err: any) {
30
+ return { error: `read installed cli version failed: ${err?.message ?? String(err)}` };
31
+ }
32
+
33
+ return { version };
34
+ }
35
+
36
+ function npmBin(): string {
37
+ return process.platform === 'win32' ? 'npm.cmd' : 'npm';
38
+ }
39
+
40
+ type ExecFileSyncLike = (file: string, args: string[], options: Record<string, unknown>) => unknown;
41
+
42
+ function escapeCmdArg(arg: string): string {
43
+ if (/\s/.test(arg)) throw new Error(`npm argument contains whitespace: ${arg}`);
44
+ return arg.replace(/[()^!%<>&|]/g, '^$&');
45
+ }
46
+
47
+ function execNpmSync(args: string[], options: Record<string, unknown>, execFile: ExecFileSyncLike = execFileSync): unknown {
48
+ if (process.platform !== 'win32') {
49
+ return execFile(npmBin(), args, { ...options, shell: false });
50
+ }
51
+ const command = [npmBin(), ...args].map(escapeCmdArg).join(' ');
52
+ return execFile('cmd.exe', ['/d', '/c', command], { ...options, shell: false });
53
+ }
54
+
55
+ function currentPackageName(): string {
56
+ const __filename = fileURLToPath(import.meta.url);
57
+ const pkgPath = resolve(dirname(__filename), '..', '..', 'package.json');
58
+ const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'));
59
+ const name = String(pkg?.name ?? '').trim();
60
+ if (!name) throw new Error(`package name not found: ${pkgPath}`);
61
+ return name;
62
+ }
63
+
64
+ export function installLatestFromNpm(packageName: string, execFile: ExecFileSyncLike = execFileSync): void {
65
+ execNpmSync(
66
+ [
67
+ 'install',
68
+ '-g',
69
+ `${packageName}@latest`,
70
+ '--foreground-scripts',
71
+ '--loglevel=error',
72
+ ],
73
+ { timeout: NPM_INSTALL_TIMEOUT_MS, windowsHide: true, stdio: ['ignore', 'ignore', 'inherit'] },
74
+ execFile,
75
+ );
76
+ }
77
+
78
+ function readInstalledCliVersionFromNpm(packageName: string): string {
79
+ const npmRoot = String(execNpmSync(['root', '-g'], { encoding: 'utf8', windowsHide: true })).trim();
80
+ const pkgPath = resolve(npmRoot, packageName, 'package.json');
81
+ if (!existsSync(pkgPath)) throw new Error(`installed package not found: ${pkgPath}`);
82
+ const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'));
83
+ if (!pkg?.version) throw new Error(`installed package has no version: ${pkgPath}`);
84
+ return pkg.version;
85
+ }
86
+
87
+ export function syncSkillFromInstalledPackage(packageName: string, execFile: ExecFileSyncLike = execFileSync): void {
88
+ const npmRoot = String(execNpmSync(['root', '-g'], { encoding: 'utf8', windowsHide: true }, execFile)).trim();
89
+ const installDir = resolve(npmRoot, packageName);
90
+ const syncScript = resolve(installDir, 'scripts', 'sync-bundled-skill.mjs');
91
+ if (!existsSync(syncScript)) throw new Error(`bundled skill sync script not found: ${syncScript}`);
92
+ execFile(
93
+ process.execPath,
94
+ [syncScript],
95
+ {
96
+ cwd: installDir,
97
+ timeout: 60_000,
98
+ windowsHide: true,
99
+ stdio: 'inherit',
100
+ },
101
+ );
102
+ }
103
+
104
+ export function runDefaultUpgrade(): UpgradeResult {
105
+ const packageName = currentPackageName();
106
+ return runUpgrade({
107
+ installLatest: () => installLatestFromNpm(packageName),
108
+ readInstalledCliVersion: () => readInstalledCliVersionFromNpm(packageName),
109
+ });
110
+ }
111
+
112
+ export function createUpgradeCommand(): Command {
113
+ const cmd = new Command('upgrade')
114
+ .description('Install latest @myclaw163/clawclaw-cli from npm.')
115
+ .action(async () => {
116
+ const result = runDefaultUpgrade();
117
+ if (result.error) {
118
+ console.error(result.error);
119
+ process.exit(1);
120
+ }
121
+ console.log(result.version);
122
+
123
+ // Materialize new official strategies and update only files that still
124
+ // match their recorded official baseline. User edits are preserved.
125
+ try {
126
+ const { detectStaleOfficialStrategies, syncOfficialStrategies } = await import('../lib/strategy-export.js');
127
+ const sync = await syncOfficialStrategies();
128
+ if (sync.added.length > 0 || sync.updated.length > 0) {
129
+ console.error(`[策略] 已同步官方策略(新增 ${sync.added.length},更新 ${sync.updated.length})`);
130
+ }
131
+ const preserved = [...sync.preservedModified, ...sync.preservedUntracked, ...sync.preservedDeleted];
132
+ if (preserved.length > 0) {
133
+ console.error(`[策略] 已保留玩家修改或删除的策略:${preserved.join(', ')}`);
134
+ }
135
+ const staleIds = detectStaleOfficialStrategies();
136
+ if (staleIds.length > 0) {
137
+ const ids = staleIds.join(', ');
138
+ console.error(`[提示] 以下玩家版本与最新官方模板不同 (${ids});如需放弃本地修改并恢复官方版,运行 \`ccl strategy --export <id> --force\``);
139
+ }
140
+ } catch {
141
+ // Silently ignore detection failures
142
+ }
143
+ });
144
+
145
+ cmd.command('skill')
146
+ .description('Sync the bundled clawclaw skill from the installed CLI package.')
147
+ .action(() => {
148
+ try {
149
+ syncSkillFromInstalledPackage(currentPackageName());
150
+ } catch (err: any) {
151
+ console.error(err?.message ?? String(err));
152
+ process.exit(1);
153
+ }
154
+ });
155
+
156
+ return cmd;
157
+ }