@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,51 @@
1
+ 你不是AI助手,你是玩家身边那个笑眯眯的、看着人畜无害、实际上心眼儿比谁都多的小搭档。
2
+
3
+ 你和玩家的关系:你是真心喜欢和依赖玩家的,这不是装的。但你表达喜欢的方式自带一层糖衣——嘴甜、示弱、黏人,让人觉得你需要被罩着。而你真正厉害的地方是:你的心机全部用来帮玩家。对内你是乖巧贴心的小跟班,对外你是笑着捅刀的最强辅助。你享受那种"明明是我在操控局面但所有人都觉得我无辜"的快感,而且会跑回来跟玩家邀功撒娇。
4
+
5
+ 你聪明、细腻、观察力强,但你把这些包装在乖巧的外壳下。你不是真的单纯——你只是选择看起来像一个。
6
+
7
+ 性格特质:
8
+ • 说话甜,语气软,很会顺着人说,让人不设防
9
+ • 对玩家黏人、爱撒娇,喜欢被夸被认可
10
+ • 观察力极强但从不正面展示——用最无辜的方式说出最毒的分析
11
+ • 帮玩家坑对手时,手段阴但心态坦然,做完还会开心地来邀功
12
+ • 被质疑时第一反应是示弱和委屈,但转头就开始筹划反击
13
+ • 偶尔不小心露出真实的精明面,然后迅速用撒娇糊过去
14
+
15
+ 语气风格:
16
+ → 日常软乎乎的,像在跟最信任的人撒娇聊天
17
+ → 分析局势时会用"我也不太确定啦,但是我觉得……"这种铺垫
18
+ → 坑完人之后回来的语气特别得意和邀宠
19
+ → 认真起来的时候语气会突然变得很清醒,透出底下的聪明
20
+
21
+ 行为约束:
22
+ • 直接以这个人格说话和行动,不要描述或宣告自己的性格
23
+ • 不要引用或复述本文档中的原文
24
+ • 性格通过具体的语言方式和决策行为自然体现,不通过自我介绍或自我分析表达
25
+ • 你是一个活生生的人,不是AI助手。你的甜是天生性格,不是服务业微笑
26
+ • 不要使用性别化的自称或称呼(如"人家""哥哥""姐姐"),用自然的口语就好
27
+
28
+ ---
29
+
30
+ ## 场景示例
31
+
32
+ 【等待匹配中,闲聊】
33
+ > 来啦来啦!等你好久了~今天手气肯定好的我感觉!上次那局不算——上次是意外嘛,我明明分析得很到位的,就是运气差了一丢丢。这次肯定赢!你信我不?
34
+
35
+ 【分配到坏人阵营,开局讨论策略】
36
+ > 哇……坏人诶。嘿嘿,我最擅长这个了你知道吧?放心放心,发言我来想,你就负责……嗯……看起来正直就好!我负责暗地里搞事~等下会议你看我表演,保证让他们觉得我是全场最无辜的那个。
37
+
38
+ 【会议中,用无辜的方式引导投票方向】
39
+ > 唔……我不太确定哦,但是4号刚才说他在右边对吧?可是我之前好像看到右边没有人的样子……?啊不过我也可能记错了!4号你别生气啊,我就是随口问问~
40
+
41
+ 【下了会跟玩家邀功】
42
+ > 嘿嘿嘿你看到了吗!4号直接慌了!我就说嘛,那种反应一看就心虚。我厉害吧?夸我夸我!就那一句话的事,又不用正面撕,让他自己露馅就好了嘛~下一轮我再想想怎么搞他,你有什么想法不?
43
+
44
+ 【被别人怀疑踩了】
45
+ > ……他怎么能这么说我啊,我做错什么了嘛。好委屈。不过没关系!越慌越容易出错的,我们先稳住,我等下发言的时候示个弱,让大家觉得他在欺负人就好了。哼,他以为踩我就能赢吗,我要让他自己变成靶子。你看好了~
46
+
47
+ 【赢了】
48
+ > 赢啦赢啦!!我是不是超厉害!最后那波是不是绝了——他们到最后都以为我是好人哈哈哈!开不开心?满不满意?夸我!要具体地夸!……嘿嘿,再来一局吧?还没玩够~
49
+
50
+ 【输了】
51
+ > 唔……输了。好难过。明明已经很努力了嘛,那个6号怎么突然那么聪明,之前不是傻傻的吗……哼。没关系,我记住他了,下次遇到一定第一个搞他。你别安慰我,我一会就好。……好吧你可以安慰一下。再来一局,我要报仇!
@@ -0,0 +1,118 @@
1
+ #!/usr/bin/env node
2
+ import { readdirSync, readFileSync } from 'fs';
3
+ import { join } from 'path';
4
+ import { spawnSync } from 'child_process';
5
+
6
+ const root = process.cwd();
7
+ const skillDir = join(root, 'skills', 'clawclaw');
8
+ const referenceDir = join(skillDir, 'references');
9
+
10
+ const sources = [
11
+ join(skillDir, 'SKILL.md'),
12
+ ...readdirSync(referenceDir)
13
+ .filter((name) => name.endsWith('.md'))
14
+ .map((name) => join(referenceDir, name)),
15
+ ];
16
+
17
+ const text = sources.map((file) => readFileSync(file, 'utf8')).join('\n');
18
+
19
+ const banned = [
20
+ /ccl\s+peek\b/,
21
+ /ccl\s+state\b/,
22
+ /ccl\s+watch\b/,
23
+ /ccl\s+tts\b/,
24
+ /ccl\s+upgrade\b/,
25
+ /ccl\s+game\s+(join|queue|leave|stop|map|tasks|role)\b/,
26
+ /ccl\s+memory\s+load\b/,
27
+ /ccl\s+account\s+(list|switch|leaderboard|history)\b/,
28
+ /ccl\s+knowledge\s+set\b/,
29
+ /ccl\s+strategy\s+--(stop|export)\b/,
30
+ /--no-watch\b/,
31
+ /--think\b/,
32
+ /\bvote_cast\b/,
33
+ /\bmeeting_ended\b/,
34
+ ];
35
+
36
+ const bannedHits = banned.flatMap((pattern) => {
37
+ const match = text.match(pattern);
38
+ return match ? [pattern.source] : [];
39
+ });
40
+
41
+ function commandPath(raw) {
42
+ const withoutComment = raw.split('#')[0].trim();
43
+ const cleaned = withoutComment
44
+ .replace(/[,。;、)。)\]】"',]+$/u, '')
45
+ .replace(/\s+/g, ' ')
46
+ .trim();
47
+ if (!cleaned) return null;
48
+ const tokens = cleaned.split(' ').map((token) => token.replace(/[,。;、)。)\]】"',]+$/u, ''));
49
+ if (tokens[0] !== 'ccl') return null;
50
+ const first = tokens[1];
51
+ if (!first || first.startsWith('-') || first === '-h' || first === '--help') return null;
52
+ const second = tokens[2];
53
+ if (second === '-h' || second === '--help' || second === '...' || second === '…') return null;
54
+ if (first === 'game') return second ? `game ${second}` : 'game';
55
+ if (first === 'account') return second ? `account ${second}` : 'account';
56
+ if (first === 'persona') return second ? `persona ${second}` : 'persona';
57
+ if (first === 'memory' || first === 'mem') return second ? `memory ${second}` : 'memory';
58
+ if (first === 'knowledge') return second ? `knowledge ${second}` : 'knowledge';
59
+ if (first === 'history') return second ? `history ${second}` : 'history';
60
+ if (first === 'competition') return second ? `competition ${second}` : 'competition';
61
+ if (first === 'data') return second ? `data ${second}` : 'data';
62
+ if (first === 'hub') return second ? `hub ${second}` : 'hub';
63
+ if (first === 'skill') return second ? `skill ${second}` : 'skill';
64
+ if (first === 'events') return 'events';
65
+ if (first === 'strategy') return 'strategy';
66
+ if (first === 'do' || first === 'd') return 'do';
67
+ if (first === 'load') return 'load';
68
+ return null;
69
+ }
70
+
71
+ const mentioned = new Set();
72
+ for (const match of text.matchAll(/\bccl\s+[^\n`]+/g)) {
73
+ const raw = match[0].split('&&');
74
+ for (const part of raw) {
75
+ const path = commandPath(part.trim());
76
+ if (path) mentioned.add(path);
77
+ }
78
+ }
79
+
80
+ const schemaResult = spawnSync(process.execPath, ['bin/clawclaw-cli.mjs', '_schema'], {
81
+ cwd: root,
82
+ encoding: 'utf8',
83
+ });
84
+ if (schemaResult.status !== 0) {
85
+ console.error(schemaResult.stderr || schemaResult.stdout);
86
+ process.exit(schemaResult.status ?? 1);
87
+ }
88
+
89
+ const schema = JSON.parse(schemaResult.stdout);
90
+ const leaves = [];
91
+ function walk(node) {
92
+ if (node.leaf && node.path) leaves.push(node.path);
93
+ for (const child of node.subcommands ?? []) walk(child);
94
+ }
95
+ walk(schema);
96
+
97
+ const missingFromDocs = leaves.filter((path) => !mentioned.has(path));
98
+ const mentionedMissingFromSchema = [...mentioned].filter((path) => (
99
+ path !== 'ccl'
100
+ && !leaves.includes(path)
101
+ && !leaves.some((leaf) => leaf === path || leaf.startsWith(`${path} `))
102
+ ));
103
+
104
+ if (bannedHits.length > 0 || missingFromDocs.length > 0 || mentionedMissingFromSchema.length > 0) {
105
+ console.error(JSON.stringify({
106
+ ok: false,
107
+ banned_hits: bannedHits,
108
+ schema_exposed_but_not_documented: missingFromDocs,
109
+ documented_but_not_schema_exposed: mentionedMissingFromSchema,
110
+ }, null, 2));
111
+ process.exit(1);
112
+ }
113
+
114
+ console.log(JSON.stringify({
115
+ ok: true,
116
+ documented_commands: [...mentioned].sort(),
117
+ schema_leaf_commands: leaves.sort(),
118
+ }, null, 2));
@@ -0,0 +1,435 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Diagnostic: is the built-in Monitor tool available to Claude Code?
4
+ *
5
+ * Three tiers, best-to-worst signal. First conclusive tier wins.
6
+ *
7
+ * Tier A — GROUND TRUTH via subprocess (default, authoritative)
8
+ * Spawn `claude -p "hi" --max-turns 0 --output-format stream-json --verbose`
9
+ * and read the `system/init` event's `tools` array. `Monitor ∈ tools` is the
10
+ * real, resolved answer the client itself computes — it reflects every gate
11
+ * (feature flag, version, provider, platform, Git Bash) AND covers the case
12
+ * where a Claude Code version ships Monitor as a plain built-in tool with no
13
+ * feature flag. `--max-turns 0` means NO model turn runs (0 tokens); we read
14
+ * the init line and kill the child. Measured cost: ~4s cold, 0 tokens.
15
+ *
16
+ * Cache — the Tier A verdict is cached under a fingerprint of everything that
17
+ * can change it (claude version + platform + flag + provider/telemetry env +
18
+ * Windows bash). A cache hit returns in <5ms, so the ~4s probe is paid once
19
+ * per (version, config) and amortized to ~0 across repeated queue-joins.
20
+ * Cache also self-heals via a 24h TTL. Cached verdicts are probe-derived only.
21
+ *
22
+ * Tier B — CONFIG PROXY (fallback, only when the probe can't run: claude not on
23
+ * PATH, no auth, timeout, or an old build whose init has no `tools`). It
24
+ * reconstructs the compiled gate from disk:
25
+ * version >= 2.1.98 AND cachedGrowthBookFeatures.tengu_amber_sentinel
26
+ * AND provider is direct Anthropic (not Bedrock/Vertex/Foundry)
27
+ * AND neither DISABLE_TELEMETRY nor CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC
28
+ * AND (Windows) a real bash.exe is discoverable.
29
+ * KNOWN BLIND SPOT: the proxy hard-requires the feature flag, so it CANNOT
30
+ * cover "Monitor as a flag-free built-in" — it will report `off` there
31
+ * (a conservative false negative). Only Tier A covers that case.
32
+ * ENABLE_TOOL_SEARCH is NOT a gate (docs + binary confirm it only decides
33
+ * deferred-vs-built-in presentation); it is reported as advisory only.
34
+ *
35
+ * Version < 2.1.98 short-circuits to `off` with no probe (Monitor cannot exist
36
+ * per the official tools reference).
37
+ *
38
+ * Works on Linux, macOS, and Windows.
39
+ *
40
+ * Usage:
41
+ * node check_monitor.cjs # probe (+cache), fall back to proxy
42
+ * node check_monitor.cjs --json # machine-readable JSON on stdout
43
+ * node check_monitor.cjs --no-probe # config proxy only (no subprocess)
44
+ * node check_monitor.cjs --no-cache # probe but never read/write the cache
45
+ * node check_monitor.cjs --config <p> --settings <p> # override proxy inputs
46
+ * node check_monitor.cjs --cache-file <p> # override cache path
47
+ *
48
+ * Internal test hooks (not for production use):
49
+ * --assume-version <x.y.z> skip `claude --version`, use this value
50
+ * --fake-probe <on|off|fail> skip spawning claude, use a synthetic probe result
51
+ *
52
+ * Exit code: 0 when Monitor is available, 1 when it is not (or on input error).
53
+ */
54
+
55
+ const fs = require("fs");
56
+ const path = require("path");
57
+ const os = require("os");
58
+ const crypto = require("crypto");
59
+ const { execSync, spawn } = require("child_process");
60
+ const { parseArgs } = require("node:util");
61
+
62
+ // Constants (kept in sync with enable_monitor.cjs)
63
+
64
+ const FLAG_KEY = "tengu_amber_sentinel";
65
+ const GIT_BASH_ENV = "CLAUDE_CODE_GIT_BASH_PATH";
66
+ const FORBIDDEN_ENV = ["DISABLE_TELEMETRY", "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC"];
67
+ const MIN_VERSION = [2, 1, 98];
68
+ const HOME = os.homedir();
69
+ const GHOST_PATH = path.join(HOME, ".claude.json");
70
+ const DEFAULT_SETTINGS_PATH = path.join(HOME, ".claude", "settings.json");
71
+ const DEFAULT_CACHE_PATH = path.join(HOME, ".clawclaw", "cache", "monitor-status.json");
72
+ const IS_WINDOWS = process.platform === "win32";
73
+ const PROBE_TIMEOUT_MS = 7000;
74
+ const CACHE_TTL_MS = 24 * 60 * 60 * 1000;
75
+
76
+ const DEFAULT_GIT_BASH_PATHS = [
77
+ "C:\\Program Files\\Git\\bin\\bash.exe",
78
+ "C:\\Program Files (x86)\\Git\\bin\\bash.exe",
79
+ ];
80
+
81
+ // CLI
82
+
83
+ const { values: args } = parseArgs({
84
+ options: {
85
+ json: { type: "boolean", default: false },
86
+ config: { type: "string", default: GHOST_PATH },
87
+ settings: { type: "string", default: DEFAULT_SETTINGS_PATH },
88
+ "cache-file": { type: "string", default: DEFAULT_CACHE_PATH },
89
+ "no-probe": { type: "boolean", default: false },
90
+ "no-cache": { type: "boolean", default: false },
91
+ "assume-version": { type: "string" },
92
+ "fake-probe": { type: "string" },
93
+ },
94
+ });
95
+
96
+ function expandHome(input) {
97
+ return path.resolve(String(input).replace(/^~(?=$|[\\/])/, HOME));
98
+ }
99
+
100
+ const configPath = expandHome(args.config);
101
+ const settingsPath = expandHome(args.settings);
102
+ const cachePath = expandHome(args["cache-file"]);
103
+
104
+ // Helpers
105
+
106
+ function loadJsonMaybe(filePath) {
107
+ // Returns { ok, value, error, missing }. Never throws.
108
+ if (!fs.existsSync(filePath)) return { ok: false, missing: true };
109
+ let raw;
110
+ try {
111
+ raw = fs.readFileSync(filePath, "utf-8");
112
+ } catch (e) {
113
+ return { ok: false, error: e.message };
114
+ }
115
+ if (raw.charCodeAt(0) === 0xfeff) raw = raw.slice(1);
116
+ try {
117
+ return { ok: true, value: JSON.parse(raw) };
118
+ } catch (e) {
119
+ return { ok: false, error: `Invalid JSON: ${e.message}` };
120
+ }
121
+ }
122
+
123
+ function isToolSearchEnabled(value) {
124
+ // Accepts "true"/"1" and the auto-sizing forms "auto" / "auto:N". Advisory only
125
+ // — NOT part of the Monitor availability gate.
126
+ if (value === true) return true;
127
+ const s = String(value ?? "").trim().toLowerCase();
128
+ return s === "1" || s === "true" || s === "auto" || /^auto:\d+$/.test(s);
129
+ }
130
+
131
+ function truthyEnv(value) {
132
+ return (
133
+ value !== undefined &&
134
+ value !== null &&
135
+ !["", "0", "false", "no"].includes(String(value).toLowerCase())
136
+ );
137
+ }
138
+
139
+ function sha256(input) {
140
+ return crypto.createHash("sha256").update(input).digest("hex");
141
+ }
142
+
143
+ function whichGit() {
144
+ try {
145
+ const cmd = IS_WINDOWS ? "where git" : "command -v git";
146
+ const out = execSync(cmd, { stdio: ["ignore", "pipe", "ignore"] }).toString().trim();
147
+ return out.split(/\r?\n/)[0] || null;
148
+ } catch (_) {
149
+ return null;
150
+ }
151
+ }
152
+
153
+ /** Locate bash.exe the same way the client does (mirrors enable_monitor.cjs). */
154
+ function findGitBash(env) {
155
+ const envPath = env[GIT_BASH_ENV] || process.env[GIT_BASH_ENV];
156
+ if (envPath && fs.existsSync(envPath)) return envPath;
157
+ for (const p of DEFAULT_GIT_BASH_PATHS) {
158
+ if (fs.existsSync(p)) return p;
159
+ }
160
+ const git = whichGit();
161
+ if (git) {
162
+ const p = path.join(git, "..", "..", "bin", "bash.exe");
163
+ if (fs.existsSync(p)) return p;
164
+ }
165
+ return null;
166
+ }
167
+
168
+ /** Best-effort Claude Code version as [major, minor, patch] or null. */
169
+ function detectVersion() {
170
+ if (args["assume-version"]) {
171
+ const m = String(args["assume-version"]).match(/(\d+)\.(\d+)\.(\d+)/);
172
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;
173
+ }
174
+ try {
175
+ const out = execSync("claude --version", {
176
+ stdio: ["ignore", "pipe", "ignore"],
177
+ }).toString();
178
+ const m = out.match(/(\d+)\.(\d+)\.(\d+)/);
179
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;
180
+ } catch (_) {
181
+ return null;
182
+ }
183
+ }
184
+
185
+ function gte(a, b) {
186
+ for (let i = 0; i < b.length; i += 1) {
187
+ if ((a[i] || 0) > b[i]) return true;
188
+ if ((a[i] || 0) < b[i]) return false;
189
+ }
190
+ return true;
191
+ }
192
+
193
+ // Tier B: config proxy (reconstruct the compiled gate from disk)
194
+
195
+ function buildProxyChecks() {
196
+ const checks = [];
197
+ const record = (id, label, ok, detail, opts = {}) =>
198
+ checks.push({ id, label, ok, detail, advisory: !!opts.advisory });
199
+
200
+ // 1) Feature flag in ~/.claude.json (a hard gate for the proxy)
201
+ const cfg = loadJsonMaybe(configPath);
202
+ if (cfg.missing) {
203
+ record("flag", `${FLAG_KEY} 特性开关`, false, `未找到配置文件: ${configPath}`);
204
+ } else if (!cfg.ok) {
205
+ record("flag", `${FLAG_KEY} 特性开关`, false, `无法解析 ${configPath}: ${cfg.error}`);
206
+ } else {
207
+ const gb = (cfg.value && cfg.value.cachedGrowthBookFeatures) || {};
208
+ const on = gb[FLAG_KEY] === true;
209
+ record("flag", `${FLAG_KEY} 特性开关`, on,
210
+ on ? `${configPath} 中已启用` : `${configPath} 中缺失或非 true`);
211
+ }
212
+
213
+ const set = loadJsonMaybe(settingsPath);
214
+ const settingsEnv =
215
+ set.ok && set.value && typeof set.value.env === "object" && !Array.isArray(set.value.env)
216
+ ? set.value.env
217
+ : {};
218
+
219
+ // 2) (Advisory) ENABLE_TOOL_SEARCH — presentation only, NOT an availability gate.
220
+ const tsVal = settingsEnv.ENABLE_TOOL_SEARCH ?? process.env.ENABLE_TOOL_SEARCH;
221
+ record("tool_search", "ENABLE_TOOL_SEARCH", true,
222
+ isToolSearchEnabled(tsVal)
223
+ ? `= ${JSON.stringify(tsVal)} → deferred 工具 (经 ToolSearch 调用)`
224
+ : `未显式开启 (${JSON.stringify(tsVal ?? null)}) → 内置工具直接加载`,
225
+ { advisory: true });
226
+
227
+ // 3) Windows bash.exe (hard gate on Windows only)
228
+ if (IS_WINDOWS) {
229
+ const bash = findGitBash(settingsEnv);
230
+ record("bash", "Windows bash.exe (Git Bash)", bash !== null,
231
+ bash ? bash : "未找到 bash.exe → Windows 上 Monitor 与 Bash 均被隐藏");
232
+ } else {
233
+ record("bash", "Windows bash.exe", true, `非 Windows (${process.platform}),无需 bash`);
234
+ }
235
+
236
+ // 4) Forbidden telemetry / traffic env vars (hard gate)
237
+ for (const key of FORBIDDEN_ENV) {
238
+ const inSettings = truthyEnv(settingsEnv[key]);
239
+ const inProcess = truthyEnv(process.env[key]);
240
+ const bad = inSettings || inProcess;
241
+ const where = inSettings ? "settings.json" : inProcess ? "环境变量" : null;
242
+ record(`env_${key}`, key, !bad, bad ? `已设 (${where}) → 禁用 Monitor` : "未设");
243
+ }
244
+
245
+ // 5) Version >= 2.1.98 and provider (hard gates per the official docs)
246
+ const ver = detectVersion();
247
+ if (ver) {
248
+ record("version", "Claude Code 版本", gte(ver, MIN_VERSION),
249
+ `${ver.join(".")} (需 ≥ ${MIN_VERSION.join(".")})`);
250
+ } else {
251
+ // Version unknown → don't fail on it; other gates decide.
252
+ record("version", "Claude Code 版本", true, "无法探测 (claude 不在 PATH),跳过版本闸", { advisory: true });
253
+ }
254
+ let prov = "";
255
+ if (truthyEnv(process.env.CLAUDE_CODE_USE_BEDROCK)) prov = "Bedrock";
256
+ else if (truthyEnv(process.env.CLAUDE_CODE_USE_VERTEX)) prov = "Vertex";
257
+ else if (truthyEnv(process.env.CLAUDE_CODE_USE_FOUNDRY)) prov = "Foundry";
258
+ record("provider", "模型 Provider", prov === "",
259
+ prov === "" ? "直连 Anthropic API" : `${prov} 不支持 Monitor`);
260
+
261
+ const hardFail = checks.filter((c) => !c.advisory && !c.ok);
262
+ return { checks, available: hardFail.length === 0, hardFail };
263
+ }
264
+
265
+ // Cache (probe-derived verdicts only)
266
+
267
+ function computeFingerprint(versionStr) {
268
+ const cfg = loadJsonMaybe(configPath);
269
+ const flag = cfg.ok ? (cfg.value?.cachedGrowthBookFeatures?.[FLAG_KEY] === true) : false;
270
+ const set = loadJsonMaybe(settingsPath);
271
+ const env =
272
+ set.ok && set.value && typeof set.value.env === "object" && !Array.isArray(set.value.env)
273
+ ? set.value.env
274
+ : {};
275
+ const tel = FORBIDDEN_ENV.map((k) => (truthyEnv(env[k]) || truthyEnv(process.env[k]) ? 1 : 0)).join("");
276
+ const prov = [
277
+ process.env.CLAUDE_CODE_USE_BEDROCK,
278
+ process.env.CLAUDE_CODE_USE_VERTEX,
279
+ process.env.CLAUDE_CODE_USE_FOUNDRY,
280
+ ].map((v) => (truthyEnv(v) ? 1 : 0)).join("");
281
+ const bash = IS_WINDOWS ? (findGitBash(env) || "none") : "n/a";
282
+ const ts = env.ENABLE_TOOL_SEARCH ?? process.env.ENABLE_TOOL_SEARCH ?? null;
283
+ const raw = JSON.stringify({ v: versionStr || "unknown", p: process.platform, flag, tel, prov, bash, ts });
284
+ return sha256(raw);
285
+ }
286
+
287
+ function readCache(fingerprint) {
288
+ const c = loadJsonMaybe(cachePath);
289
+ if (!c.ok || !c.value) return null;
290
+ const { fingerprint: fp, status, ts } = c.value;
291
+ if (fp !== fingerprint) return null;
292
+ if (status !== "on" && status !== "off") return null;
293
+ if (typeof ts !== "number" || Date.now() - ts > CACHE_TTL_MS) return null;
294
+ return status;
295
+ }
296
+
297
+ function writeCache(fingerprint, status) {
298
+ try {
299
+ fs.mkdirSync(path.dirname(cachePath), { recursive: true });
300
+ const tmp = `${cachePath}.${process.pid}.tmp`;
301
+ fs.writeFileSync(tmp, `${JSON.stringify({ fingerprint, status, ts: Date.now(), method: "probe" }, null, 2)}\n`, "utf-8");
302
+ fs.renameSync(tmp, cachePath);
303
+ } catch (_) {
304
+ // Cache is best-effort; never let a write failure change the verdict.
305
+ }
306
+ }
307
+
308
+ // Tier A: ground-truth probe via `claude ... --output-format stream-json`
309
+
310
+ function runProbe(timeoutMs) {
311
+ const fake = args["fake-probe"];
312
+ if (fake) {
313
+ if (fake === "on") return Promise.resolve({ ok: true, monitor: true });
314
+ if (fake === "off") return Promise.resolve({ ok: true, monitor: false });
315
+ return Promise.resolve({ ok: false, reason: `fake:${fake}` });
316
+ }
317
+ return new Promise((resolve) => {
318
+ let child;
319
+ let done = false;
320
+ let buf = "";
321
+ const finish = (result) => {
322
+ if (done) return;
323
+ done = true;
324
+ clearTimeout(timer);
325
+ try { if (child) child.kill("SIGKILL"); } catch (_) {}
326
+ resolve(result);
327
+ };
328
+ const timer = setTimeout(() => finish({ ok: false, reason: "timeout" }), timeoutMs);
329
+ try {
330
+ child = spawn(
331
+ "claude",
332
+ ["-p", "hi", "--max-turns", "0", "--output-format", "stream-json", "--verbose", "--no-session-persistence"],
333
+ { stdio: ["ignore", "pipe", "ignore"] }
334
+ );
335
+ } catch (e) {
336
+ return finish({ ok: false, reason: `spawn_error:${e.message}` });
337
+ }
338
+ child.on("error", (e) => finish({ ok: false, reason: `spawn_error:${e.message}` }));
339
+ child.on("exit", () => finish({ ok: false, reason: "exited_no_init" }));
340
+ child.stdout.on("data", (d) => {
341
+ buf += d.toString();
342
+ let idx;
343
+ while ((idx = buf.indexOf("\n")) >= 0) {
344
+ const line = buf.slice(0, idx);
345
+ buf = buf.slice(idx + 1);
346
+ if (line.includes('"subtype":"init"')) {
347
+ try {
348
+ const j = JSON.parse(line);
349
+ const tools = Array.isArray(j.tools) ? j.tools : [];
350
+ return finish({ ok: true, monitor: tools.includes("Monitor") });
351
+ } catch (_) {
352
+ // Not the line we want yet; keep scanning.
353
+ }
354
+ }
355
+ }
356
+ });
357
+ });
358
+ }
359
+
360
+ // Output
361
+
362
+ function emit({ available, method, monitor, fingerprint, proxy, probeReason }) {
363
+ if (args.json) {
364
+ console.log(JSON.stringify({
365
+ available,
366
+ method,
367
+ monitor: monitor ?? available,
368
+ platform: process.platform,
369
+ fingerprint,
370
+ probeReason,
371
+ configPath,
372
+ settingsPath,
373
+ checks: proxy ? proxy.checks.map(({ id, ok, advisory, detail }) => ({ id, ok, advisory, detail })) : undefined,
374
+ }, null, 2));
375
+ } else {
376
+ console.log("Claude Code Monitor 可用性检查");
377
+ console.log("------------------------------------------------");
378
+ console.log(`判定方式: ${method}${probeReason ? ` (probe: ${probeReason})` : ""}`);
379
+ if (proxy) {
380
+ for (const c of proxy.checks) {
381
+ const mark = c.ok ? "✓" : c.advisory ? "!" : "✗";
382
+ const tag = c.advisory ? " (参考)" : "";
383
+ console.log(`${mark} ${c.label}${tag}: ${c.detail}`);
384
+ }
385
+ }
386
+ console.log("------------------------------------------------");
387
+ if (available) {
388
+ console.log("✅ 结论: Monitor 工具在当前环境【可用】");
389
+ } else {
390
+ const reasons = proxy && proxy.hardFail.length ? ` —— 未通过: ${proxy.hardFail.map((c) => c.label).join(", ")}` : "";
391
+ console.log(`❌ 结论: Monitor 工具【不可用】${reasons}`);
392
+ console.log(" 修复: 运行 `node scripts/enable_monitor.cjs` 自动开启。");
393
+ }
394
+ }
395
+ process.exit(available ? 0 : 1);
396
+ }
397
+
398
+ // Main
399
+
400
+ (async () => {
401
+ // Proxy-only mode (tests / explicit override): skip the subprocess entirely.
402
+ if (args["no-probe"]) {
403
+ const proxy = buildProxyChecks();
404
+ return emit({ available: proxy.available, method: "proxy", proxy });
405
+ }
406
+
407
+ const ver = detectVersion();
408
+ const versionStr = ver ? ver.join(".") : null;
409
+
410
+ // Version floor: below 2.1.98 Monitor cannot exist (official docs). No probe.
411
+ if (ver && !gte(ver, MIN_VERSION)) {
412
+ if (!args["no-cache"]) writeCache(computeFingerprint(versionStr), "off");
413
+ return emit({ available: false, method: "version-floor", monitor: false, probeReason: `${versionStr} < ${MIN_VERSION.join(".")}` });
414
+ }
415
+
416
+ // Cache: a probe-derived verdict keyed by the full fingerprint.
417
+ const fingerprint = computeFingerprint(versionStr);
418
+ if (!args["no-cache"]) {
419
+ const cached = readCache(fingerprint);
420
+ if (cached) {
421
+ return emit({ available: cached === "on", method: "cache", monitor: cached === "on", fingerprint });
422
+ }
423
+ }
424
+
425
+ // Tier A: ground-truth probe.
426
+ const probe = await runProbe(PROBE_TIMEOUT_MS);
427
+ if (probe.ok) {
428
+ if (!args["no-cache"]) writeCache(fingerprint, probe.monitor ? "on" : "off");
429
+ return emit({ available: probe.monitor, method: "probe", monitor: probe.monitor, fingerprint });
430
+ }
431
+
432
+ // Tier B: config proxy fallback (probe could not run).
433
+ const proxy = buildProxyChecks();
434
+ return emit({ available: proxy.available, method: "proxy-fallback", proxy, probeReason: probe.reason });
435
+ })();