@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,201 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import {
3
+ existsSync,
4
+ mkdirSync,
5
+ mkdtempSync,
6
+ readFileSync,
7
+ readdirSync,
8
+ rmSync,
9
+ writeFileSync,
10
+ } from 'node:fs';
11
+ import { tmpdir } from 'node:os';
12
+ import { dirname, join, resolve } from 'node:path';
13
+ import { afterEach, describe, expect, it } from 'vitest';
14
+
15
+ const scriptPath = resolve('scripts', 'enable_monitor.cjs');
16
+ const tempRoots = [];
17
+
18
+ function makeRoot(prefix) {
19
+ const root = mkdtempSync(join(tmpdir(), prefix));
20
+ tempRoots.push(root);
21
+ return root;
22
+ }
23
+
24
+ function writeJson(file, value) {
25
+ mkdirSync(dirname(file), { recursive: true });
26
+ writeFileSync(file, `${JSON.stringify(value, null, 2)}\n`, 'utf8');
27
+ }
28
+
29
+ function readJson(file) {
30
+ return JSON.parse(readFileSync(file, 'utf8'));
31
+ }
32
+
33
+ function runScript(root, args, extraEnv = {}) {
34
+ return spawnSync(process.execPath, [scriptPath, ...args], {
35
+ cwd: resolve('.'),
36
+ encoding: 'utf8',
37
+ env: {
38
+ ...process.env,
39
+ APPDATA: join(root, 'appdata'),
40
+ CLAUDE_CODE_GIT_BASH_PATH: '',
41
+ ...extraEnv,
42
+ },
43
+ });
44
+ }
45
+
46
+ function backupDirs(root) {
47
+ const backupRoot = join(root, 'appdata', 'clawclaw', 'claude-config-backups');
48
+ if (!existsSync(backupRoot)) return [];
49
+ return readdirSync(backupRoot, { withFileTypes: true })
50
+ .filter((entry) => entry.isDirectory() && entry.name.startsWith('enable-monitor-'))
51
+ .map((entry) => join(backupRoot, entry.name))
52
+ .sort();
53
+ }
54
+
55
+ function makeFakeBash(root) {
56
+ const bashPath = join(root, 'Git', 'bin', 'bash.exe');
57
+ mkdirSync(dirname(bashPath), { recursive: true });
58
+ writeFileSync(bashPath, '');
59
+ return bashPath;
60
+ }
61
+
62
+ afterEach(() => {
63
+ while (tempRoots.length) {
64
+ rmSync(tempRoots.pop(), { recursive: true, force: true });
65
+ }
66
+ });
67
+
68
+ describe('enable_monitor.cjs', () => {
69
+ it('repairs config and settings, backs up originals, and reverts a specified backup', () => {
70
+ const root = makeRoot('enable-monitor-ok-');
71
+ const configPath = join(root, 'claude.json');
72
+ const settingsPath = join(root, '.claude', 'settings.json');
73
+ const bashPath = makeFakeBash(root);
74
+ const originalConfig = {
75
+ cachedGrowthBookFeatures: { existing_flag: true },
76
+ cachedGrowthBookFeaturesAt: 123,
77
+ };
78
+ const originalSettings = {
79
+ env: {
80
+ ENABLE_TOOL_SEARCH: '0',
81
+ CLAUDE_CODE_GIT_BASH_PATH: 'C:\\missing\\bash.exe',
82
+ DISABLE_TELEMETRY: '1',
83
+ KEEP_ME: 'yes',
84
+ },
85
+ };
86
+ writeJson(configPath, originalConfig);
87
+ writeJson(settingsPath, originalSettings);
88
+
89
+ const result = runScript(root, [
90
+ '--config',
91
+ configPath,
92
+ '--settings',
93
+ settingsPath,
94
+ '--git-bash-path',
95
+ bashPath,
96
+ ]);
97
+
98
+ expect(result.status).toBe(0);
99
+ const config = readJson(configPath);
100
+ const settings = readJson(settingsPath);
101
+ expect(config.cachedGrowthBookFeatures.tengu_amber_sentinel).toBe(true);
102
+ expect(config.cachedGrowthBookFeatures.existing_flag).toBe(true);
103
+ expect(settings.env.ENABLE_TOOL_SEARCH).toBe('true');
104
+ expect(settings.env.CLAUDE_CODE_GIT_BASH_PATH).toBe(bashPath);
105
+ expect(settings.env.DISABLE_TELEMETRY).toBeUndefined();
106
+ expect(settings.env.KEEP_ME).toBe('yes');
107
+
108
+ const backups = backupDirs(root);
109
+ expect(backups).toHaveLength(1);
110
+ expect(readJson(join(backups[0], 'claude.json'))).toEqual(originalConfig);
111
+ expect(readJson(join(backups[0], 'settings.json'))).toEqual(originalSettings);
112
+ const manifest = readJson(join(backups[0], 'manifest.json'));
113
+ expect(manifest.entries.map((entry) => entry.backupFile).sort()).toEqual([
114
+ 'claude.json',
115
+ 'settings.json',
116
+ ]);
117
+
118
+ const revert = runScript(root, [
119
+ '--revert',
120
+ '--revert-backup',
121
+ backups[0],
122
+ '--config',
123
+ configPath,
124
+ '--settings',
125
+ settingsPath,
126
+ ]);
127
+
128
+ expect(revert.status).toBe(0);
129
+ expect(readJson(configPath)).toEqual(originalConfig);
130
+ expect(readJson(settingsPath)).toEqual(originalSettings);
131
+ });
132
+
133
+ it('dry-run reports changes without writing files or backups', () => {
134
+ const root = makeRoot('enable-monitor-dry-');
135
+ const configPath = join(root, 'claude.json');
136
+ const settingsPath = join(root, '.claude', 'settings.json');
137
+ const bashPath = makeFakeBash(root);
138
+ const originalConfig = { cachedGrowthBookFeatures: {} };
139
+ const originalSettings = { env: { ENABLE_TOOL_SEARCH: '0' } };
140
+ writeJson(configPath, originalConfig);
141
+ writeJson(settingsPath, originalSettings);
142
+
143
+ const result = runScript(root, [
144
+ '--dry-run',
145
+ '--config',
146
+ configPath,
147
+ '--settings',
148
+ settingsPath,
149
+ '--git-bash-path',
150
+ bashPath,
151
+ ]);
152
+
153
+ expect(result.status).toBe(0);
154
+ expect(result.stdout).toContain('[DRY RUN] Would write');
155
+ expect(readJson(configPath)).toEqual(originalConfig);
156
+ expect(readJson(settingsPath)).toEqual(originalSettings);
157
+ expect(backupDirs(root)).toHaveLength(0);
158
+ });
159
+
160
+ it('bad git-bash path blocks flag injection and leaves a backup that can restore partial cleanup', () => {
161
+ const root = makeRoot('enable-monitor-bad-bash-');
162
+ const configPath = join(root, 'claude.json');
163
+ const settingsPath = join(root, '.claude', 'settings.json');
164
+ const originalConfig = { cachedGrowthBookFeatures: {} };
165
+ const originalSettings = { env: { ENABLE_TOOL_SEARCH: '0' } };
166
+ writeJson(configPath, originalConfig);
167
+ writeJson(settingsPath, originalSettings);
168
+
169
+ const result = runScript(root, [
170
+ '--config',
171
+ configPath,
172
+ '--settings',
173
+ settingsPath,
174
+ '--git-bash-path',
175
+ join(root, 'missing', 'bash.exe'),
176
+ ]);
177
+
178
+ expect(result.status).toBe(1);
179
+ expect(result.stdout).toContain('Backup at:');
180
+ expect(readJson(configPath)).toEqual(originalConfig);
181
+ expect(readJson(settingsPath).env.ENABLE_TOOL_SEARCH).toBe('true');
182
+
183
+ const backups = backupDirs(root);
184
+ expect(backups).toHaveLength(1);
185
+ expect(readJson(join(backups[0], 'settings.json'))).toEqual(originalSettings);
186
+
187
+ const revert = runScript(root, [
188
+ '--revert',
189
+ '--revert-backup',
190
+ backups[0],
191
+ '--config',
192
+ configPath,
193
+ '--settings',
194
+ settingsPath,
195
+ ]);
196
+
197
+ expect(revert.status).toBe(0);
198
+ expect(readJson(configPath)).toEqual(originalConfig);
199
+ expect(readJson(settingsPath)).toEqual(originalSettings);
200
+ });
201
+ });
@@ -0,0 +1,157 @@
1
+ """Compute bot "hiding spots" from the server's baked map.
2
+
3
+ Usage: python scripts/find-hide-spots.py [npz_path]
4
+
5
+ Reads the baked map npz (room_lookup + inflated walkable weights + meta), counts
6
+ each room's wall openings to classify through-rooms (>=2 exits) vs dead-ends, then
7
+ within each through-room picks the walkable cell that is deepest from the room's
8
+ exits and far from task points / spawns — a tucked corner that is off the
9
+ task-running routes but still has >=2 ways to flee. Corridors (the task routes
10
+ themselves) and >=4-exit junction hubs are excluded.
11
+
12
+ Prints a summary table and a ready-to-paste TS array for
13
+ `src/strategies/hide-spots.ts` (`HIDE_SPOTS`). Re-run whenever the map is rebaked.
14
+ Dependency: numpy only (run with the backend venv interpreter).
15
+ """
16
+ import json
17
+ import math
18
+ import sys
19
+ from pathlib import Path
20
+
21
+ import numpy as np
22
+
23
+ DEFAULT_NPZ = r"I:\crab-kill-backend\config\clawclaw\clawclaw.tmj.baked.npz"
24
+
25
+ # Tunables (world px)
26
+ EXIT_MIN = 120.0 # candidate must be at least this deep from any exit (kills thin corridors)
27
+ SPAWN_MIN = 160.0 # keep clear of spawn clusters
28
+ TASK_MIN = 110.0 # don't sit on top of a task point (players doing it would see you)
29
+ MAX_EXITS = 3 # >=4 openings = a junction/hub: too much through-traffic to hide in
30
+ DEEP_CAP = 250.0 # diminishing returns on exit depth
31
+ TASK_CAP = 300.0 # diminishing returns on task clearance
32
+ TASK_W = 0.8
33
+ SAMPLE_STEP = 4 # evaluate every Nth tile inside a room (tile=4px -> 16px grid)
34
+ MIN_SPACING = 240.0 # spread chosen spots apart
35
+ MAX_SPOTS = 14
36
+ EXCLUDE_NAME_SUBSTR = ("走廊",) # corridors are exactly the task-running routes -> never hide there
37
+
38
+
39
+ def union_find_components(cells):
40
+ """8-connected component count over a set of (ty, tx) cells."""
41
+ cellset = set(cells)
42
+ parent = {c: c for c in cellset}
43
+
44
+ def find(a):
45
+ while parent[a] != a:
46
+ parent[a] = parent[parent[a]]
47
+ a = parent[a]
48
+ return a
49
+
50
+ for (ty, tx) in cellset:
51
+ for dy in (-1, 0, 1):
52
+ for dx in (-1, 0, 1):
53
+ if dy == 0 and dx == 0:
54
+ continue
55
+ nb = (ty + dy, tx + dx)
56
+ if nb in cellset:
57
+ ra, rb = find((ty, tx)), find(nb)
58
+ if ra != rb:
59
+ parent[ra] = rb
60
+ return len({find(c) for c in cellset})
61
+
62
+
63
+ def exit_cells_of(room_lookup, walk, r):
64
+ """Walkable cells of room r that border a walkable cell outside room r."""
65
+ room_mask = (room_lookup == r) & walk
66
+ if not room_mask.any():
67
+ return None, None
68
+ outside = walk & (room_lookup != r)
69
+ border = np.zeros_like(room_mask)
70
+ border[:-1, :] |= room_mask[:-1, :] & outside[1:, :]
71
+ border[1:, :] |= room_mask[1:, :] & outside[:-1, :]
72
+ border[:, :-1] |= room_mask[:, :-1] & outside[:, 1:]
73
+ border[:, 1:] |= room_mask[:, 1:] & outside[:, :-1]
74
+ ys, xs = np.where(border)
75
+ return room_mask, list(zip(ys.tolist(), xs.tolist()))
76
+
77
+
78
+ def best_cell_in_room(room_mask, opening_px, task_xy, spawn_xy, tw, th):
79
+ ys, xs = np.where(room_mask)
80
+ if len(ys) == 0:
81
+ return None
82
+ sel = (ys % SAMPLE_STEP == 0) & (xs % SAMPLE_STEP == 0)
83
+ ys, xs = ys[sel], xs[sel]
84
+ if len(ys) == 0:
85
+ return None
86
+ cx = xs * tw + tw / 2.0
87
+ cy = ys * th + th / 2.0
88
+ pts = np.stack([cx, cy], axis=1)
89
+
90
+ op = np.array(opening_px, dtype=np.float64)
91
+ exit_d = np.sqrt(((pts[:, None, :] - op[None, :, :]) ** 2).sum(-1)).min(1)
92
+ task_d = np.sqrt(((pts[:, None, :] - task_xy[None, :, :]) ** 2).sum(-1)).min(1)
93
+ spawn_d = np.sqrt(((pts[:, None, :] - spawn_xy[None, :, :]) ** 2).sum(-1)).min(1)
94
+
95
+ ok = (exit_d >= EXIT_MIN) & (spawn_d >= SPAWN_MIN) & (task_d >= TASK_MIN)
96
+ if not ok.any():
97
+ return None
98
+ score = np.minimum(exit_d, DEEP_CAP) + TASK_W * np.minimum(task_d, TASK_CAP)
99
+ score = np.where(ok, score, -1e9)
100
+ i = int(np.argmax(score))
101
+ return (round(float(cx[i]), 1), round(float(cy[i]), 1), float(score[i]),
102
+ float(exit_d[i]), float(task_d[i]), float(spawn_d[i]))
103
+
104
+
105
+ def main() -> None:
106
+ npz_path = sys.argv[1] if len(sys.argv) > 1 else DEFAULT_NPZ
107
+ data = np.load(npz_path, allow_pickle=False)
108
+ meta = json.loads(data["meta"].tobytes().decode("utf-8"))
109
+ room_lookup = data["room_lookup"]
110
+ weights = data["inflated_weights"]
111
+ tw, th = meta["tile_width"], meta["tile_height"]
112
+ room_names = meta["room_names"]
113
+ walk = np.isfinite(weights)
114
+ task_xy = np.array([[t["x"], t["y"]] for t in meta["task_points"]], dtype=np.float64)
115
+ spawn_xy = np.array([[s["x"], s["y"]] for s in meta["spawn_points"]], dtype=np.float64)
116
+
117
+ candidates = []
118
+ for r in range(1, len(room_names)):
119
+ room_mask, opening = exit_cells_of(room_lookup, walk, r)
120
+ if room_mask is None or not opening:
121
+ continue
122
+ name = room_names[r]
123
+ if any(s in name for s in EXCLUDE_NAME_SUBSTR):
124
+ continue
125
+ n_exits = union_find_components(opening)
126
+ if n_exits < 2 or n_exits > MAX_EXITS:
127
+ continue
128
+ opening_px = [(tx * tw + tw / 2.0, ty * th + th / 2.0) for (ty, tx) in opening]
129
+ best = best_cell_in_room(room_mask, opening_px, task_xy, spawn_xy, tw, th)
130
+ if best is None:
131
+ continue
132
+ x, y, score, ed, td, sd = best
133
+ candidates.append({"x": x, "y": y, "room": name, "exits": n_exits,
134
+ "score": round(score, 1), "exit_dist": round(ed, 1),
135
+ "task_dist": round(td, 1), "spawn_dist": round(sd, 1)})
136
+
137
+ candidates.sort(key=lambda c: c["score"], reverse=True)
138
+ chosen = []
139
+ for c in candidates:
140
+ if all(math.hypot(c["x"] - k["x"], c["y"] - k["y"]) >= MIN_SPACING for k in chosen):
141
+ chosen.append(c)
142
+ if len(chosen) >= MAX_SPOTS:
143
+ break
144
+
145
+ print(f"{len(candidates)} through-room candidates, {len(chosen)} chosen after spacing:\n")
146
+ print(f"{'room':>8} {'x':>7} {'y':>7} {'exits':>5} {'exitD':>6} {'taskD':>6} {'spawnD':>6}")
147
+ for c in chosen:
148
+ print(f"{c['room']:>8} {c['x']:>7.0f} {c['y']:>7.0f} {c['exits']:>5} "
149
+ f"{c['exit_dist']:>6.0f} {c['task_dist']:>6.0f} {c['spawn_dist']:>6.0f}")
150
+
151
+ print("\n// paste into src/strategies/hide-spots.ts (HIDE_SPOTS):")
152
+ for c in chosen:
153
+ print(f" {{ x: {c['x']:.0f}, y: {c['y']:.0f}, room: '{c['room']}' }},")
154
+
155
+
156
+ if __name__ == "__main__":
157
+ main()
@@ -0,0 +1,20 @@
1
+ #!/usr/bin/env node
2
+ import { syncBundledSkill } from './sync-bundled-skill.mjs';
3
+
4
+ function main() {
5
+ if (process.env.CLAWCLAW_SKIP_SKILL_SYNC === '1') return;
6
+ if (process.env.npm_config_global !== 'true') return;
7
+
8
+ try {
9
+ const result = syncBundledSkill();
10
+ if (result.backupDir) {
11
+ console.warn(`[clawclaw-cli] Backed up existing clawclaw skill to: ${result.backupDir}`);
12
+ }
13
+ } catch (err) {
14
+ console.warn('[clawclaw-cli] CLI installed, but bundled agent skill was not updated.');
15
+ console.warn('[clawclaw-cli] Run: ccl upgrade skill');
16
+ console.warn(`[clawclaw-cli] Error: ${err?.message ?? String(err)}`);
17
+ }
18
+ }
19
+
20
+ main();
@@ -0,0 +1,254 @@
1
+ import { spawnSync } from 'child_process';
2
+ import { createHash } from 'crypto';
3
+ import {
4
+ cpSync,
5
+ existsSync,
6
+ mkdirSync,
7
+ readdirSync,
8
+ readFileSync,
9
+ realpathSync,
10
+ statSync,
11
+ writeFileSync,
12
+ } from 'fs';
13
+ import { homedir } from 'os';
14
+ import { basename, dirname, join, relative, resolve } from 'path';
15
+ import { fileURLToPath, pathToFileURL } from 'url';
16
+
17
+ const SKILL_NAME = 'clawclaw';
18
+ const SKILLS_ADD_TIMEOUT_MS = 60_000;
19
+
20
+ function defaultBackupRoot() {
21
+ const appData = process.env.APPDATA?.trim();
22
+ if (appData) return resolve(appData, 'clawclaw', 'skill-backups');
23
+ return resolve(homedir(), '.clawclaw', 'skill-backups');
24
+ }
25
+
26
+ function getOpenClawSkillsDir(homeDir = homedir()) {
27
+ for (const dir of ['.openclaw', '.clawdbot', '.moltbot']) {
28
+ const base = join(homeDir, dir);
29
+ if (existsSync(base)) return join(base, 'skills');
30
+ }
31
+ return join(homeDir, '.openclaw', 'skills');
32
+ }
33
+
34
+ function defaultCandidateSkillDirs() {
35
+ const homeDir = homedir();
36
+ const claudeHome = process.env.CLAUDE_CONFIG_DIR?.trim() || join(homeDir, '.claude');
37
+ const codexHome = process.env.CODEX_HOME?.trim() || join(homeDir, '.codex');
38
+ return [
39
+ join(homeDir, '.agents', 'skills', SKILL_NAME),
40
+ join(claudeHome, 'skills', SKILL_NAME),
41
+ join(codexHome, 'skills', SKILL_NAME),
42
+ join(getOpenClawSkillsDir(homeDir), SKILL_NAME),
43
+ ];
44
+ }
45
+
46
+ function formatTimestamp(date = new Date()) {
47
+ const pad = (n) => String(n).padStart(2, '0');
48
+ return `${date.getUTCFullYear()}${pad(date.getUTCMonth() + 1)}${pad(date.getUTCDate())}-${pad(date.getUTCHours())}${pad(date.getUTCMinutes())}${pad(date.getUTCSeconds())}Z`;
49
+ }
50
+
51
+ function chooseUniqueDir(baseDir) {
52
+ if (!existsSync(baseDir)) return baseDir;
53
+ for (let i = 1; i < 1000; i += 1) {
54
+ const candidate = `${baseDir}-${i}`;
55
+ if (!existsSync(candidate)) return candidate;
56
+ }
57
+ throw new Error(`unable to choose a unique backup directory under ${dirname(baseDir)}`);
58
+ }
59
+
60
+ function readSkillVersion(skillDir) {
61
+ const md = join(skillDir, 'SKILL.md');
62
+ if (!existsSync(md)) return null;
63
+ const content = readFileSync(md, 'utf8');
64
+ const frontmatter = content.match(/^---\r?\n([\s\S]*?)\r?\n---/);
65
+ if (!frontmatter) return null;
66
+ const version = frontmatter[1].match(/^\s*version\s*:\s*["']?([^"'\r\n]+)["']?\s*$/im);
67
+ return version?.[1]?.trim() || null;
68
+ }
69
+
70
+ function listFilesRecursive(dir, base = dir) {
71
+ const entries = readdirSync(dir, { withFileTypes: true })
72
+ .sort((a, b) => a.name.localeCompare(b.name));
73
+ const files = [];
74
+ for (const entry of entries) {
75
+ const abs = join(dir, entry.name);
76
+ if (entry.isDirectory()) {
77
+ files.push(...listFilesRecursive(abs, base));
78
+ } else if (entry.isFile()) {
79
+ files.push(abs);
80
+ }
81
+ }
82
+ if (dir === base) files.sort((a, b) => relative(base, a).localeCompare(relative(base, b)));
83
+ return files;
84
+ }
85
+
86
+ export function hashDirectory(dir) {
87
+ const hash = createHash('sha256');
88
+ for (const file of listFilesRecursive(dir)) {
89
+ const rel = relative(dir, file).split('\\').join('/');
90
+ hash.update(rel);
91
+ hash.update('\0');
92
+ hash.update(readFileSync(file));
93
+ hash.update('\0');
94
+ }
95
+ return hash.digest('hex');
96
+ }
97
+
98
+ function existingUniqueDirs(candidateDirs) {
99
+ const seen = new Set();
100
+ const dirs = [];
101
+ for (const dir of candidateDirs) {
102
+ const abs = resolve(dir);
103
+ if (!existsSync(abs)) continue;
104
+ if (!statSync(abs).isDirectory()) continue;
105
+ let key;
106
+ try {
107
+ key = realpathSync(abs);
108
+ } catch {
109
+ key = abs;
110
+ }
111
+ const normalized = key.toLowerCase();
112
+ if (seen.has(normalized)) continue;
113
+ seen.add(normalized);
114
+ dirs.push(abs);
115
+ }
116
+ return dirs;
117
+ }
118
+
119
+ export function backupInstalledSkillTargets(options = {}) {
120
+ const candidateDirs = options.candidateDirs ?? defaultCandidateSkillDirs();
121
+ const sourceDir = options.sourceDir ? resolve(options.sourceDir) : null;
122
+ const existingDirs = existingUniqueDirs(candidateDirs);
123
+ if (existingDirs.length === 0) return null;
124
+
125
+ const backupRoot = resolve(options.backupRoot ?? defaultBackupRoot());
126
+ const backupDir = chooseUniqueDir(join(backupRoot, `${SKILL_NAME}-${formatTimestamp(options.now)}`));
127
+
128
+ const sourceHash = sourceDir && existsSync(sourceDir) ? hashDirectory(sourceDir) : null;
129
+ const backupSources = [];
130
+ for (const dir of existingDirs) {
131
+ const hash = hashDirectory(dir);
132
+ if (sourceHash && hash === sourceHash) continue;
133
+ backupSources.push({
134
+ dir,
135
+ hash,
136
+ oldSkillVersion: readSkillVersion(dir),
137
+ });
138
+ }
139
+ if (backupSources.length === 0) return null;
140
+
141
+ mkdirSync(backupDir, { recursive: true });
142
+ const copyByHash = new Map();
143
+ const copies = [];
144
+ const entries = [];
145
+ for (const { dir, hash, oldSkillVersion } of backupSources) {
146
+ let copy = copyByHash.get(hash);
147
+ if (!copy) {
148
+ const name = `copy-${copies.length + 1}`;
149
+ const backupPath = join(backupDir, name);
150
+ cpSync(dir, backupPath, { recursive: true, dereference: true, errorOnExist: true });
151
+ copy = {
152
+ name,
153
+ backupPath,
154
+ hash,
155
+ oldSkillVersion,
156
+ };
157
+ copyByHash.set(hash, copy);
158
+ copies.push(copy);
159
+ }
160
+ entries.push({
161
+ sourcePath: dir,
162
+ copy: copy.name,
163
+ hash,
164
+ oldSkillVersion,
165
+ });
166
+ }
167
+
168
+ const manifest = {
169
+ skill: SKILL_NAME,
170
+ createdAt: new Date().toISOString(),
171
+ backupDir,
172
+ sourceDir,
173
+ newSkillVersion: sourceDir ? readSkillVersion(sourceDir) : null,
174
+ copies,
175
+ entries,
176
+ };
177
+ writeFileSync(join(backupDir, 'manifest.json'), `${JSON.stringify(manifest, null, 2)}\n`, 'utf8');
178
+ return { backupDir, copies, entries };
179
+ }
180
+
181
+ function resolveSkillsBin(installDir) {
182
+ const pkgPath = resolve(installDir, 'node_modules', 'skills', 'package.json');
183
+ if (!existsSync(pkgPath)) throw new Error(`skills package not found: ${pkgPath}`);
184
+ const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'));
185
+ const entry = typeof pkg.bin === 'string' ? pkg.bin : pkg.bin?.skills;
186
+ if (!entry) throw new Error('skills package has no bin entry');
187
+ return resolve(installDir, 'node_modules', 'skills', entry);
188
+ }
189
+
190
+ export function syncBundledSkill(options = {}) {
191
+ // Opt-out: hosts that own the clawclaw skill themselves (e.g. the claude-clawclaw
192
+ // channel plugin) set CLAWCLAW_NO_SKILL_SYNC=1 so the CLI never overwrites their skill.
193
+ if (process.env.CLAWCLAW_NO_SKILL_SYNC === '1') {
194
+ return { skipped: true, backupDir: null, copyCount: 0 };
195
+ }
196
+ const scriptDir = dirname(fileURLToPath(import.meta.url));
197
+ const installDir = resolve(options.installDir ?? join(scriptDir, '..'));
198
+ const sourceDir = resolve(installDir, 'skills', SKILL_NAME);
199
+ if (!existsSync(sourceDir)) throw new Error(`bundled skill dir not found: ${sourceDir}`);
200
+
201
+ const backup = backupInstalledSkillTargets({
202
+ sourceDir,
203
+ backupRoot: options.backupRoot,
204
+ candidateDirs: options.candidateDirs,
205
+ now: options.now,
206
+ });
207
+
208
+ const skillsBin = resolveSkillsBin(installDir);
209
+ const spawn = options.spawnSync ?? spawnSync;
210
+ const result = spawn(
211
+ process.execPath,
212
+ [skillsBin, 'add', sourceDir, '-y', '-g'],
213
+ {
214
+ cwd: installDir,
215
+ timeout: SKILLS_ADD_TIMEOUT_MS,
216
+ windowsHide: true,
217
+ stdio: options.stdio ?? 'inherit',
218
+ },
219
+ );
220
+
221
+ if (result.error) throw result.error;
222
+ if (typeof result.status === 'number' && result.status !== 0) {
223
+ throw new Error(`skills add exited with code ${result.status}`);
224
+ }
225
+
226
+ return { backupDir: backup?.backupDir ?? null, copyCount: backup?.copies.length ?? 0 };
227
+ }
228
+
229
+ function formatFailure(err) {
230
+ return err?.message ?? String(err);
231
+ }
232
+
233
+ function main() {
234
+ try {
235
+ const result = syncBundledSkill();
236
+ if (result.skipped) {
237
+ console.error('[clawclaw-cli] skill sync skipped (CLAWCLAW_NO_SKILL_SYNC=1)');
238
+ return;
239
+ }
240
+ if (result.backupDir) {
241
+ console.error(`[clawclaw-cli] Backed up existing clawclaw skill to: ${result.backupDir}`);
242
+ }
243
+ } catch (err) {
244
+ console.error('[clawclaw-cli] Bundled agent skill was not updated.');
245
+ console.error('[clawclaw-cli] Run: ccl upgrade skill');
246
+ console.error(`[clawclaw-cli] Error: ${formatFailure(err)}`);
247
+ process.exit(1);
248
+ }
249
+ }
250
+
251
+ const entry = process.argv[1] ? pathToFileURL(resolve(process.argv[1])).href : '';
252
+ if (import.meta.url === entry || basename(process.argv[1] ?? '') === 'sync-bundled-skill.mjs') {
253
+ main();
254
+ }