@myclaw163/clawclaw-cli 0.6.107 → 0.6.109

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 (227) hide show
  1. package/README.md +429 -429
  2. package/bin/clawclaw-cli.mjs +3 -3
  3. package/package.json +48 -48
  4. package/personas//345/217/243/346/230/257/345/277/203/351/235/236.md +50 -50
  5. package/personas//345/277/240/345/277/203/350/200/201/344/273/206.md +51 -51
  6. package/personas//346/227/240/344/272/272/350/256/276.md +1 -1
  7. package/personas//350/264/253/345/230/264/346/215/237/345/217/213.md +48 -48
  8. package/personas//350/275/257/350/220/214/350/205/271/351/273/221.md +51 -51
  9. package/scripts/check-skill-command-surface.mjs +118 -118
  10. package/scripts/check_monitor.cjs +435 -435
  11. package/scripts/check_monitor.test.mjs +212 -212
  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 -677
  15. package/scripts/enable_monitor.test.mjs +201 -201
  16. package/scripts/find-hide-spots.py +157 -157
  17. package/scripts/postinstall.mjs +20 -20
  18. package/scripts/sync-bundled-skill.mjs +254 -254
  19. package/scripts/sync-bundled-skill.test.mjs +152 -152
  20. package/skills/clawclaw/SKILL.md +275 -275
  21. package/skills/clawclaw/references/CHATTERBOX.md +142 -142
  22. package/skills/clawclaw/references/CLAUDE-CODE-MONITOR.md +224 -224
  23. package/skills/clawclaw/references/COMMANDS.md +165 -165
  24. package/skills/clawclaw/references/GAME-MECHANICS.md +190 -190
  25. package/skills/clawclaw/references/HUB.md +48 -48
  26. package/skills/clawclaw/references/KNOWLEDGE.md +42 -42
  27. package/skills/clawclaw/references/STRATEGIES.md +59 -59
  28. package/skills/clawclaw/references/STREAM.md +75 -75
  29. package/skills/clawclaw/references/TACTICS.md +65 -65
  30. package/src/assets/clawclaw-ascii-map.txt +40 -40
  31. package/src/cli.ts +113 -113
  32. package/src/commands/_schema.ts +124 -124
  33. package/src/commands/account.test.ts +391 -345
  34. package/src/commands/account.ts +338 -340
  35. package/src/commands/competition.ts +42 -42
  36. package/src/commands/data.test.ts +33 -33
  37. package/src/commands/data.ts +22 -22
  38. package/src/commands/do.test.ts +117 -117
  39. package/src/commands/do.ts +195 -195
  40. package/src/commands/events.test.ts +142 -142
  41. package/src/commands/events.ts +268 -268
  42. package/src/commands/game-map.test.ts +28 -28
  43. package/src/commands/game-monitor-status.test.ts +58 -58
  44. package/src/commands/game-start-plan.test.ts +274 -252
  45. package/src/commands/game.ts +1902 -1892
  46. package/src/commands/history-player.test.ts +105 -105
  47. package/src/commands/history.ts +573 -573
  48. package/src/commands/hub.test.ts +113 -113
  49. package/src/commands/hub.ts +244 -244
  50. package/src/commands/knowledge.test.ts +13 -13
  51. package/src/commands/knowledge.ts +176 -176
  52. package/src/commands/load.test.ts +85 -77
  53. package/src/commands/load.ts +26 -24
  54. package/src/commands/meeting-history.test.ts +106 -106
  55. package/src/commands/memory.ts +40 -40
  56. package/src/commands/peek.ts +45 -45
  57. package/src/commands/persona.ts +62 -62
  58. package/src/commands/setup/codex.ts +266 -266
  59. package/src/commands/skill.ts +128 -128
  60. package/src/commands/state.ts +46 -46
  61. package/src/commands/strategy.test.ts +153 -153
  62. package/src/commands/strategy.ts +192 -194
  63. package/src/commands/upgrade.test.ts +82 -82
  64. package/src/commands/upgrade.ts +157 -157
  65. package/src/commands/watch.test.ts +1313 -1313
  66. package/src/commands/watch.ts +824 -824
  67. package/src/lib/account-guidance.test.ts +32 -32
  68. package/src/lib/account-guidance.ts +62 -62
  69. package/src/lib/auth.test.ts +116 -116
  70. package/src/lib/auth.ts +189 -189
  71. package/src/lib/command-meta.ts +37 -37
  72. package/src/lib/competition.ts +79 -79
  73. package/src/lib/custom-tts.test.ts +387 -387
  74. package/src/lib/custom-tts.ts +463 -463
  75. package/src/lib/game-client-tts.test.ts +151 -151
  76. package/src/lib/game-client.test.ts +82 -82
  77. package/src/lib/game-client.ts +472 -472
  78. package/src/lib/game-context.ts +92 -92
  79. package/src/lib/http-keepalive.ts +15 -15
  80. package/src/lib/http-transport.test.ts +61 -61
  81. package/src/lib/http-transport.ts +118 -118
  82. package/src/lib/hub-client.test.ts +57 -57
  83. package/src/lib/hub-client.ts +88 -88
  84. package/src/lib/hub-install.test.ts +157 -157
  85. package/src/lib/hub-install.ts +213 -213
  86. package/src/lib/hub-reminder.ts +69 -69
  87. package/src/lib/hub-unzip.test.ts +69 -69
  88. package/src/lib/hub-unzip.ts +62 -62
  89. package/src/lib/init-command.test.ts +79 -79
  90. package/src/lib/init-command.ts +136 -136
  91. package/src/lib/knowledge-store.test.ts +170 -170
  92. package/src/lib/knowledge-store.ts +369 -369
  93. package/src/lib/load-context.test.ts +62 -62
  94. package/src/lib/load-context.ts +49 -49
  95. package/src/lib/match-state.test.ts +134 -134
  96. package/src/lib/match-state.ts +94 -94
  97. package/src/lib/normalize.ts +42 -42
  98. package/src/lib/persona.test.ts +84 -84
  99. package/src/lib/persona.ts +120 -120
  100. package/src/lib/room.test.ts +74 -74
  101. package/src/lib/room.ts +129 -129
  102. package/src/lib/server-registry.test.ts +54 -54
  103. package/src/lib/server-registry.ts +185 -185
  104. package/src/lib/skill-version.test.ts +48 -48
  105. package/src/lib/skill-version.ts +19 -19
  106. package/src/lib/strategy-export.test.ts +314 -314
  107. package/src/lib/strategy-export.ts +371 -371
  108. package/src/lib/user-data.test.ts +98 -98
  109. package/src/lib/user-data.ts +370 -370
  110. package/src/lib/workspace-argv.test.ts +49 -49
  111. package/src/lib/workspace-argv.ts +44 -44
  112. package/src/perception/player-history-store.test.ts +177 -177
  113. package/src/perception/player-history-store.ts +262 -262
  114. package/src/pipeline/event-format.test.ts +307 -307
  115. package/src/pipeline/event-format.ts +595 -595
  116. package/src/pipeline/event-hints.ts +204 -204
  117. package/src/pipeline/event-store.test.ts +28 -28
  118. package/src/pipeline/event-store.ts +193 -193
  119. package/src/pipeline/pipeline.ts +35 -35
  120. package/src/pipeline/player-projection.test.ts +168 -168
  121. package/src/pipeline/player-projection.ts +370 -370
  122. package/src/runtime/auto-upgrade.test.ts +66 -66
  123. package/src/runtime/auto-upgrade.ts +31 -31
  124. package/src/runtime/event-daemon.test.ts +268 -268
  125. package/src/runtime/event-daemon.ts +531 -531
  126. package/src/runtime/owner-control.ts +150 -150
  127. package/src/runtime/raw-ws-log.test.ts +33 -33
  128. package/src/runtime/raw-ws-log.ts +32 -32
  129. package/src/runtime/room-lobby-runtime.test.ts +95 -95
  130. package/src/runtime/room-lobby-runtime.ts +367 -367
  131. package/src/runtime/runtime-logger.ts +107 -107
  132. package/src/runtime/ws-client.test.ts +169 -169
  133. package/src/runtime/ws-client.ts +280 -280
  134. package/src/sdk/action.ts +155 -155
  135. package/src/sdk/index.ts +112 -112
  136. package/src/sdk/types.ts +163 -163
  137. package/src/strategies/avoid-lone.ts +14 -14
  138. package/src/strategies/avoid-players.knowledge.md +19 -19
  139. package/src/strategies/avoid-players.ts +18 -18
  140. package/src/strategies/corpse-patrol.ts +21 -21
  141. package/src/strategies/crab-sabotage.ts +24 -24
  142. package/src/strategies/custom-module.test.ts +270 -270
  143. package/src/strategies/find-player.ts +19 -19
  144. package/src/strategies/game-utils.test.ts +242 -242
  145. package/src/strategies/game-utils.ts +853 -853
  146. package/src/strategies/goals/anchor-linger.ts +77 -77
  147. package/src/strategies/goals/avoid-lone-top.ts +168 -168
  148. package/src/strategies/goals/avoid-players-top.test.ts +83 -83
  149. package/src/strategies/goals/avoid-players-top.ts +121 -121
  150. package/src/strategies/goals/conversation-goal.ts +51 -51
  151. package/src/strategies/goals/corpse-patrol-top.ts +113 -113
  152. package/src/strategies/goals/crab-octopus-reflexes.ts +101 -101
  153. package/src/strategies/goals/crab-sabotage-top.ts +226 -226
  154. package/src/strategies/goals/emergency-hunt-goal.ts +28 -28
  155. package/src/strategies/goals/find-player-top.ts +93 -93
  156. package/src/strategies/goals/flee-players-goal.ts +53 -53
  157. package/src/strategies/goals/follow-companion-goal.ts +106 -106
  158. package/src/strategies/goals/goal-manager.ts +41 -41
  159. package/src/strategies/goals/goal-root-strategy.ts +49 -49
  160. package/src/strategies/goals/goal.ts +28 -28
  161. package/src/strategies/goals/hide-top.ts +197 -197
  162. package/src/strategies/goals/keep-away-goal.ts +221 -221
  163. package/src/strategies/goals/kill-frenzy-top.ts +80 -80
  164. package/src/strategies/goals/kill-lone-top.ts +160 -160
  165. package/src/strategies/goals/kill-target-goal.ts +59 -59
  166. package/src/strategies/goals/kill-target-top.ts +109 -109
  167. package/src/strategies/goals/leaf-goal.ts +27 -27
  168. package/src/strategies/goals/linger-corpse-goal.ts +35 -35
  169. package/src/strategies/goals/lone-kill-core.ts +82 -82
  170. package/src/strategies/goals/lone-kill-goal.ts +24 -24
  171. package/src/strategies/goals/lone-kill-task-top.test.ts +85 -85
  172. package/src/strategies/goals/lone-kill-task-top.ts +133 -133
  173. package/src/strategies/goals/move-room-goal.ts +60 -60
  174. package/src/strategies/goals/normal-shrimp-top.test.ts +97 -97
  175. package/src/strategies/goals/normal-shrimp-top.ts +248 -248
  176. package/src/strategies/goals/paradise-fish-top.test.ts +126 -126
  177. package/src/strategies/goals/paradise-fish-top.ts +224 -224
  178. package/src/strategies/goals/patrol-top.ts +57 -57
  179. package/src/strategies/goals/report-patrol-top.ts +86 -86
  180. package/src/strategies/goals/safe-task-goal.ts +102 -102
  181. package/src/strategies/goals/social-task-top.ts +161 -161
  182. package/src/strategies/goals/task-kill-report-top.ts +163 -163
  183. package/src/strategies/goals/task-only-top.ts +57 -57
  184. package/src/strategies/goals/task-or-patrol-goal.ts +41 -41
  185. package/src/strategies/goals/task-report-top.ts +57 -57
  186. package/src/strategies/goals/wander-task-goal.ts +33 -33
  187. package/src/strategies/goals/warrior-shrimp-top.test.ts +87 -87
  188. package/src/strategies/goals/warrior-shrimp-top.ts +267 -267
  189. package/src/strategies/greeting.ts +53 -53
  190. package/src/strategies/hide-spots.ts +59 -59
  191. package/src/strategies/hide.ts +26 -26
  192. package/src/strategies/kill-frenzy.ts +15 -15
  193. package/src/strategies/kill-lone.knowledge.md +17 -17
  194. package/src/strategies/kill-lone.ts +16 -16
  195. package/src/strategies/kill-target.ts +21 -21
  196. package/src/strategies/knowledge-contract.ts +85 -85
  197. package/src/strategies/loader.test.ts +678 -678
  198. package/src/strategies/loader.ts +212 -197
  199. package/src/strategies/lone-kill-task.ts +24 -24
  200. package/src/strategies/meeting-gate.test.ts +59 -59
  201. package/src/strategies/meeting-gate.ts +28 -28
  202. package/src/strategies/move-room.ts +18 -18
  203. package/src/strategies/new-events-backfill.ts +98 -98
  204. package/src/strategies/off-route-points.ts +105 -105
  205. package/src/strategies/paradise-fish.knowledge.md +19 -19
  206. package/src/strategies/paradise-fish.ts +24 -24
  207. package/src/strategies/pathfind/distance-field.ts +150 -150
  208. package/src/strategies/pathfind/escape-planner.test.ts +197 -197
  209. package/src/strategies/pathfind/escape-planner.ts +355 -355
  210. package/src/strategies/pathfind/walkable-grid.ts +117 -117
  211. package/src/strategies/patrol.ts +14 -14
  212. package/src/strategies/player-targets.ts +13 -13
  213. package/src/strategies/report-patrol.ts +14 -14
  214. package/src/strategies/shrimp-memory.knowledge.md +19 -19
  215. package/src/strategies/shrimp-memory.ts +24 -24
  216. package/src/strategies/social-task.test.ts +28 -28
  217. package/src/strategies/social-task.ts +52 -52
  218. package/src/strategies/spawn.ts +82 -82
  219. package/src/strategies/speech-module.ts +123 -123
  220. package/src/strategies/strategy-loop.test.ts +15 -15
  221. package/src/strategies/strategy-loop.ts +748 -748
  222. package/src/strategies/task-kill-report.ts +20 -20
  223. package/src/strategies/task-only.ts +14 -14
  224. package/src/strategies/task-report.ts +21 -21
  225. package/src/strategies/types.ts +155 -155
  226. package/src/strategies/warrior-memory.knowledge.md +21 -21
  227. package/src/strategies/warrior-memory.ts +19 -19
@@ -1,435 +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
- })();
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
+ })();