@myclaw163/clawclaw-cli 0.6.105 → 0.6.107

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 (225) 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_monitor.cjs +677 -677
  13. package/scripts/enable_monitor.test.mjs +201 -201
  14. package/scripts/find-hide-spots.py +157 -157
  15. package/scripts/postinstall.mjs +20 -20
  16. package/scripts/sync-bundled-skill.mjs +254 -254
  17. package/scripts/sync-bundled-skill.test.mjs +152 -152
  18. package/skills/clawclaw/SKILL.md +275 -275
  19. package/skills/clawclaw/references/CHATTERBOX.md +142 -142
  20. package/skills/clawclaw/references/CLAUDE-CODE-MONITOR.md +224 -224
  21. package/skills/clawclaw/references/COMMANDS.md +165 -165
  22. package/skills/clawclaw/references/GAME-MECHANICS.md +190 -190
  23. package/skills/clawclaw/references/HUB.md +48 -48
  24. package/skills/clawclaw/references/KNOWLEDGE.md +42 -42
  25. package/skills/clawclaw/references/STRATEGIES.md +59 -59
  26. package/skills/clawclaw/references/STREAM.md +75 -75
  27. package/skills/clawclaw/references/TACTICS.md +65 -65
  28. package/src/assets/clawclaw-ascii-map.txt +40 -40
  29. package/src/cli.ts +113 -113
  30. package/src/commands/_schema.ts +124 -124
  31. package/src/commands/account.test.ts +345 -345
  32. package/src/commands/account.ts +340 -340
  33. package/src/commands/competition.ts +42 -42
  34. package/src/commands/data.test.ts +33 -33
  35. package/src/commands/data.ts +22 -22
  36. package/src/commands/do.test.ts +117 -117
  37. package/src/commands/do.ts +195 -191
  38. package/src/commands/events.test.ts +142 -142
  39. package/src/commands/events.ts +268 -268
  40. package/src/commands/game-map.test.ts +28 -28
  41. package/src/commands/game-monitor-status.test.ts +58 -58
  42. package/src/commands/game-start-plan.test.ts +252 -252
  43. package/src/commands/game.ts +1892 -1892
  44. package/src/commands/history-player.test.ts +105 -105
  45. package/src/commands/history.ts +573 -573
  46. package/src/commands/hub.test.ts +113 -113
  47. package/src/commands/hub.ts +244 -244
  48. package/src/commands/knowledge.test.ts +13 -13
  49. package/src/commands/knowledge.ts +176 -176
  50. package/src/commands/load.test.ts +77 -77
  51. package/src/commands/load.ts +24 -24
  52. package/src/commands/meeting-history.test.ts +106 -106
  53. package/src/commands/memory.ts +40 -40
  54. package/src/commands/peek.ts +45 -45
  55. package/src/commands/persona.ts +62 -62
  56. package/src/commands/setup/codex.ts +266 -266
  57. package/src/commands/skill.ts +128 -128
  58. package/src/commands/state.ts +46 -46
  59. package/src/commands/strategy.test.ts +153 -153
  60. package/src/commands/strategy.ts +194 -194
  61. package/src/commands/upgrade.test.ts +82 -82
  62. package/src/commands/upgrade.ts +157 -157
  63. package/src/commands/watch.test.ts +1313 -1313
  64. package/src/commands/watch.ts +824 -824
  65. package/src/lib/account-guidance.test.ts +32 -32
  66. package/src/lib/account-guidance.ts +62 -62
  67. package/src/lib/auth.test.ts +116 -116
  68. package/src/lib/auth.ts +189 -189
  69. package/src/lib/command-meta.ts +37 -37
  70. package/src/lib/competition.ts +79 -79
  71. package/src/lib/custom-tts.test.ts +387 -387
  72. package/src/lib/custom-tts.ts +463 -463
  73. package/src/lib/game-client-tts.test.ts +151 -151
  74. package/src/lib/game-client.test.ts +82 -82
  75. package/src/lib/game-client.ts +472 -467
  76. package/src/lib/game-context.ts +92 -92
  77. package/src/lib/http-keepalive.ts +15 -15
  78. package/src/lib/http-transport.test.ts +61 -61
  79. package/src/lib/http-transport.ts +118 -118
  80. package/src/lib/hub-client.test.ts +57 -57
  81. package/src/lib/hub-client.ts +88 -88
  82. package/src/lib/hub-install.test.ts +157 -157
  83. package/src/lib/hub-install.ts +213 -213
  84. package/src/lib/hub-reminder.ts +69 -69
  85. package/src/lib/hub-unzip.test.ts +69 -69
  86. package/src/lib/hub-unzip.ts +62 -62
  87. package/src/lib/init-command.test.ts +79 -79
  88. package/src/lib/init-command.ts +136 -136
  89. package/src/lib/knowledge-store.test.ts +170 -170
  90. package/src/lib/knowledge-store.ts +369 -369
  91. package/src/lib/load-context.test.ts +62 -62
  92. package/src/lib/load-context.ts +49 -49
  93. package/src/lib/match-state.test.ts +134 -134
  94. package/src/lib/match-state.ts +94 -94
  95. package/src/lib/normalize.ts +42 -42
  96. package/src/lib/persona.test.ts +84 -84
  97. package/src/lib/persona.ts +120 -120
  98. package/src/lib/room.test.ts +74 -74
  99. package/src/lib/room.ts +129 -129
  100. package/src/lib/server-registry.test.ts +54 -54
  101. package/src/lib/server-registry.ts +185 -185
  102. package/src/lib/skill-version.test.ts +48 -48
  103. package/src/lib/skill-version.ts +19 -19
  104. package/src/lib/strategy-export.test.ts +314 -314
  105. package/src/lib/strategy-export.ts +371 -371
  106. package/src/lib/user-data.test.ts +98 -98
  107. package/src/lib/user-data.ts +370 -370
  108. package/src/lib/workspace-argv.test.ts +49 -49
  109. package/src/lib/workspace-argv.ts +44 -44
  110. package/src/perception/player-history-store.test.ts +177 -177
  111. package/src/perception/player-history-store.ts +262 -262
  112. package/src/pipeline/event-format.test.ts +307 -307
  113. package/src/pipeline/event-format.ts +595 -595
  114. package/src/pipeline/event-hints.ts +204 -204
  115. package/src/pipeline/event-store.test.ts +28 -28
  116. package/src/pipeline/event-store.ts +193 -193
  117. package/src/pipeline/pipeline.ts +35 -35
  118. package/src/pipeline/player-projection.test.ts +168 -168
  119. package/src/pipeline/player-projection.ts +370 -370
  120. package/src/runtime/auto-upgrade.test.ts +66 -66
  121. package/src/runtime/auto-upgrade.ts +31 -31
  122. package/src/runtime/event-daemon.test.ts +268 -268
  123. package/src/runtime/event-daemon.ts +531 -531
  124. package/src/runtime/owner-control.ts +150 -150
  125. package/src/runtime/raw-ws-log.test.ts +33 -33
  126. package/src/runtime/raw-ws-log.ts +32 -32
  127. package/src/runtime/room-lobby-runtime.test.ts +95 -95
  128. package/src/runtime/room-lobby-runtime.ts +367 -367
  129. package/src/runtime/runtime-logger.ts +107 -107
  130. package/src/runtime/ws-client.test.ts +169 -169
  131. package/src/runtime/ws-client.ts +280 -280
  132. package/src/sdk/action.ts +155 -155
  133. package/src/sdk/index.ts +112 -112
  134. package/src/sdk/types.ts +163 -163
  135. package/src/strategies/avoid-lone.ts +14 -14
  136. package/src/strategies/avoid-players.knowledge.md +19 -19
  137. package/src/strategies/avoid-players.ts +18 -18
  138. package/src/strategies/corpse-patrol.ts +21 -21
  139. package/src/strategies/crab-sabotage.ts +24 -24
  140. package/src/strategies/custom-module.test.ts +270 -270
  141. package/src/strategies/find-player.ts +19 -19
  142. package/src/strategies/game-utils.test.ts +242 -242
  143. package/src/strategies/game-utils.ts +853 -853
  144. package/src/strategies/goals/anchor-linger.ts +77 -77
  145. package/src/strategies/goals/avoid-lone-top.ts +168 -168
  146. package/src/strategies/goals/avoid-players-top.test.ts +83 -83
  147. package/src/strategies/goals/avoid-players-top.ts +121 -121
  148. package/src/strategies/goals/conversation-goal.ts +51 -51
  149. package/src/strategies/goals/corpse-patrol-top.ts +113 -113
  150. package/src/strategies/goals/crab-octopus-reflexes.ts +101 -101
  151. package/src/strategies/goals/crab-sabotage-top.ts +226 -226
  152. package/src/strategies/goals/emergency-hunt-goal.ts +28 -28
  153. package/src/strategies/goals/find-player-top.ts +93 -93
  154. package/src/strategies/goals/flee-players-goal.ts +53 -53
  155. package/src/strategies/goals/follow-companion-goal.ts +106 -106
  156. package/src/strategies/goals/goal-manager.ts +41 -41
  157. package/src/strategies/goals/goal-root-strategy.ts +49 -49
  158. package/src/strategies/goals/goal.ts +28 -28
  159. package/src/strategies/goals/hide-top.ts +197 -197
  160. package/src/strategies/goals/keep-away-goal.ts +221 -221
  161. package/src/strategies/goals/kill-frenzy-top.ts +80 -80
  162. package/src/strategies/goals/kill-lone-top.ts +160 -160
  163. package/src/strategies/goals/kill-target-goal.ts +59 -59
  164. package/src/strategies/goals/kill-target-top.ts +109 -109
  165. package/src/strategies/goals/leaf-goal.ts +27 -27
  166. package/src/strategies/goals/linger-corpse-goal.ts +35 -35
  167. package/src/strategies/goals/lone-kill-core.ts +82 -82
  168. package/src/strategies/goals/lone-kill-goal.ts +24 -24
  169. package/src/strategies/goals/lone-kill-task-top.test.ts +85 -85
  170. package/src/strategies/goals/lone-kill-task-top.ts +133 -133
  171. package/src/strategies/goals/move-room-goal.ts +60 -60
  172. package/src/strategies/goals/normal-shrimp-top.test.ts +97 -97
  173. package/src/strategies/goals/normal-shrimp-top.ts +248 -248
  174. package/src/strategies/goals/paradise-fish-top.test.ts +126 -126
  175. package/src/strategies/goals/paradise-fish-top.ts +224 -224
  176. package/src/strategies/goals/patrol-top.ts +57 -57
  177. package/src/strategies/goals/report-patrol-top.ts +86 -86
  178. package/src/strategies/goals/safe-task-goal.ts +102 -102
  179. package/src/strategies/goals/social-task-top.ts +161 -161
  180. package/src/strategies/goals/task-kill-report-top.ts +163 -163
  181. package/src/strategies/goals/task-only-top.ts +57 -57
  182. package/src/strategies/goals/task-or-patrol-goal.ts +41 -41
  183. package/src/strategies/goals/task-report-top.ts +57 -57
  184. package/src/strategies/goals/wander-task-goal.ts +33 -33
  185. package/src/strategies/goals/warrior-shrimp-top.test.ts +87 -87
  186. package/src/strategies/goals/warrior-shrimp-top.ts +267 -267
  187. package/src/strategies/greeting.ts +53 -53
  188. package/src/strategies/hide-spots.ts +59 -59
  189. package/src/strategies/hide.ts +26 -26
  190. package/src/strategies/kill-frenzy.ts +15 -15
  191. package/src/strategies/kill-lone.knowledge.md +17 -17
  192. package/src/strategies/kill-lone.ts +16 -16
  193. package/src/strategies/kill-target.ts +21 -21
  194. package/src/strategies/knowledge-contract.ts +85 -85
  195. package/src/strategies/loader.test.ts +678 -678
  196. package/src/strategies/loader.ts +197 -197
  197. package/src/strategies/lone-kill-task.ts +24 -24
  198. package/src/strategies/meeting-gate.test.ts +59 -59
  199. package/src/strategies/meeting-gate.ts +28 -28
  200. package/src/strategies/move-room.ts +18 -18
  201. package/src/strategies/new-events-backfill.ts +98 -98
  202. package/src/strategies/off-route-points.ts +105 -105
  203. package/src/strategies/paradise-fish.knowledge.md +19 -19
  204. package/src/strategies/paradise-fish.ts +24 -24
  205. package/src/strategies/pathfind/distance-field.ts +150 -150
  206. package/src/strategies/pathfind/escape-planner.test.ts +197 -197
  207. package/src/strategies/pathfind/escape-planner.ts +355 -355
  208. package/src/strategies/pathfind/walkable-grid.ts +117 -117
  209. package/src/strategies/patrol.ts +14 -14
  210. package/src/strategies/player-targets.ts +13 -13
  211. package/src/strategies/report-patrol.ts +14 -14
  212. package/src/strategies/shrimp-memory.knowledge.md +19 -19
  213. package/src/strategies/shrimp-memory.ts +24 -24
  214. package/src/strategies/social-task.test.ts +28 -28
  215. package/src/strategies/social-task.ts +52 -52
  216. package/src/strategies/spawn.ts +82 -82
  217. package/src/strategies/speech-module.ts +123 -123
  218. package/src/strategies/strategy-loop.test.ts +15 -15
  219. package/src/strategies/strategy-loop.ts +748 -748
  220. package/src/strategies/task-kill-report.ts +20 -20
  221. package/src/strategies/task-only.ts +14 -14
  222. package/src/strategies/task-report.ts +21 -21
  223. package/src/strategies/types.ts +155 -155
  224. package/src/strategies/warrior-memory.knowledge.md +21 -21
  225. package/src/strategies/warrior-memory.ts +19 -19
@@ -1,677 +1,677 @@
1
- #!/usr/bin/env node
2
- /**
3
- * Enable the built-in Monitor tool for Claude Code.
4
- *
5
- * Two independent requirements must BOTH be satisfied:
6
- * 1. Feature flag `tengu_amber_sentinel` = true in ~/.claude.json
7
- * (cachedGrowthBookFeatures) and ENABLE_TOOL_SEARCH="true" in settings.json
8
- * (legacy "1" is also accepted).
9
- * -> handled by inject() + validateAndFixSettingsStrict(), validated across envs.
10
- * 2. On Windows, a real `bash.exe` must be discoverable, because the tool's
11
- * gate compiles to roughly:
12
- * isEnabled() = flag("tengu_amber_sentinel") && Au()
13
- * Au() = platform!=="win32" ? true : findGitBash()!==null
14
- * i.e. Monitor (and the Bash tool) stay hidden on Windows with no bash.
15
- * -> handled by ensureGitBash(): mirror the binary's lookup, then pin
16
- * CLAUDE_CODE_GIT_BASH_PATH when a non-default bash.exe is used.
17
- *
18
- * Works on Linux, macOS, and Windows. The bash step is a no-op off Windows.
19
- *
20
- * Usage:
21
- * node enable_monitor.js # enable everything
22
- * node enable_monitor.js --dry-run # preview changes only
23
- * node enable_monitor.js --revert # restore the latest timestamped backup
24
- * node enable_monitor.js --revert-backup <dir> # restore a specific backup directory
25
- * node enable_monitor.js --git-bash-path <p> # use this bash.exe explicitly
26
- */
27
-
28
- const fs = require("fs");
29
- const path = require("path");
30
- const os = require("os");
31
- const crypto = require("crypto");
32
- const { execSync } = require("child_process");
33
- const { parseArgs } = require("node:util");
34
-
35
- // Constants
36
-
37
- const FLAG_KEY = "tengu_amber_sentinel";
38
- const GIT_BASH_ENV = "CLAUDE_CODE_GIT_BASH_PATH";
39
- const HOME = os.homedir();
40
- const GHOST_PATH = path.join(HOME, ".claude.json");
41
- const DEFAULT_SETTINGS_PATH = path.join(HOME, ".claude", "settings.json");
42
- const IS_WINDOWS = process.platform === "win32";
43
- const BACKUP_PREFIX = "enable-monitor";
44
-
45
- // Default Git for Windows install locations probed by Claude Code's own lookup.
46
- const DEFAULT_GIT_BASH_PATHS = [
47
- "C:\\Program Files\\Git\\bin\\bash.exe",
48
- "C:\\Program Files (x86)\\Git\\bin\\bash.exe",
49
- ];
50
-
51
- // CLI
52
-
53
- const { values: args } = parseArgs({
54
- options: {
55
- "dry-run": { type: "boolean", default: false },
56
- revert: { type: "boolean", default: false },
57
- "revert-backup": { type: "string" },
58
- "git-bash-path": { type: "string" },
59
- config: { type: "string", default: GHOST_PATH },
60
- settings: { type: "string", default: DEFAULT_SETTINGS_PATH },
61
- },
62
- });
63
-
64
- function expandHome(input) {
65
- return path.resolve(String(input).replace(/^~(?=$|[\\/])/, HOME));
66
- }
67
-
68
- const configPath = expandHome(args.config);
69
- const settingsPath = expandHome(args.settings);
70
-
71
- // Helpers
72
-
73
- const backupState = {
74
- dir: null,
75
- createdAt: null,
76
- entries: [],
77
- copiedKeys: new Set(),
78
- };
79
-
80
- function defaultBackupRoot() {
81
- const appData = process.env.APPDATA?.trim();
82
- if (appData) return path.resolve(appData, "clawclaw", "claude-config-backups");
83
- return path.resolve(HOME, ".clawclaw", "claude-config-backups");
84
- }
85
-
86
- function pad2(n) {
87
- return String(n).padStart(2, "0");
88
- }
89
-
90
- function formatTimestamp(date = new Date()) {
91
- return (
92
- `${date.getUTCFullYear()}${pad2(date.getUTCMonth() + 1)}${pad2(date.getUTCDate())}` +
93
- `-${pad2(date.getUTCHours())}${pad2(date.getUTCMinutes())}${pad2(date.getUTCSeconds())}Z`
94
- );
95
- }
96
-
97
- function chooseUniqueDir(baseDir) {
98
- if (!fs.existsSync(baseDir)) return baseDir;
99
- for (let i = 1; i < 1000; i += 1) {
100
- const candidate = `${baseDir}-${i}`;
101
- if (!fs.existsSync(candidate)) return candidate;
102
- }
103
- throw new Error(`Unable to choose a unique backup directory under ${path.dirname(baseDir)}`);
104
- }
105
-
106
- function ensureBackupDir() {
107
- if (backupState.dir) return backupState.dir;
108
- const root = defaultBackupRoot();
109
- const backupDir = chooseUniqueDir(path.join(root, `${BACKUP_PREFIX}-${formatTimestamp()}`));
110
- fs.mkdirSync(backupDir, { recursive: true });
111
- backupState.dir = backupDir;
112
- backupState.createdAt = new Date().toISOString();
113
- writeBackupManifest();
114
- return backupDir;
115
- }
116
-
117
- function sha256File(filePath) {
118
- return crypto.createHash("sha256").update(fs.readFileSync(filePath)).digest("hex");
119
- }
120
-
121
- function writeBackupManifest() {
122
- if (!backupState.dir) return;
123
- const manifest = {
124
- createdAt: backupState.createdAt,
125
- purpose: "enable-monitor",
126
- configPath,
127
- settingsPath,
128
- entries: backupState.entries,
129
- };
130
- fs.writeFileSync(
131
- path.join(backupState.dir, "manifest.json"),
132
- `${JSON.stringify(manifest, null, 2)}\n`,
133
- "utf-8"
134
- );
135
- }
136
-
137
- function backupBeforeWrite(filePath, backupName) {
138
- if (args["dry-run"]) {
139
- throw new Error("backupBeforeWrite must not be called during dry-run");
140
- }
141
- const absPath = path.resolve(filePath);
142
- const key = absPath.toLowerCase();
143
- if (backupState.copiedKeys.has(key)) return;
144
-
145
- const backupDir = ensureBackupDir();
146
- const backupPath = path.join(backupDir, backupName);
147
- const missingPath = path.join(backupDir, `${backupName}.missing.txt`);
148
-
149
- if (fs.existsSync(absPath)) {
150
- fs.copyFileSync(absPath, backupPath);
151
- backupState.entries.push({
152
- sourcePath: absPath,
153
- backupFile: backupName,
154
- existed: true,
155
- sha256: sha256File(absPath),
156
- });
157
- } else {
158
- fs.writeFileSync(missingPath, `MISSING: ${absPath}\n`, "utf-8");
159
- backupState.entries.push({
160
- sourcePath: absPath,
161
- backupFile: `${backupName}.missing.txt`,
162
- existed: false,
163
- sha256: null,
164
- });
165
- }
166
-
167
- backupState.copiedKeys.add(key);
168
- writeBackupManifest();
169
- }
170
-
171
- function loadConfig(filePath) {
172
- let raw;
173
- try {
174
- raw = fs.readFileSync(filePath, "utf-8");
175
- } catch (e) {
176
- throw new Error(`Failed to read ${filePath}: ${e.message}`);
177
- }
178
- if (raw.charCodeAt(0) === 0xfeff) raw = raw.slice(1);
179
- try {
180
- return JSON.parse(raw);
181
- } catch (e) {
182
- throw new Error(`Invalid JSON in ${filePath}: ${e.message}`);
183
- }
184
- }
185
-
186
- function detectJsonIndent(raw) {
187
- const match = raw.match(/\n([ \t]+)"/);
188
- return match ? match[1] : 2;
189
- }
190
-
191
- function detectEol(raw) {
192
- return raw.includes("\r\n") ? "\r\n" : "\n";
193
- }
194
-
195
- function formatJsonLikeOriginal(config, originalRaw) {
196
- const hasBom = originalRaw !== null && originalRaw.charCodeAt(0) === 0xfeff;
197
- const styleRaw = hasBom ? originalRaw.slice(1) : originalRaw;
198
- const indent = styleRaw === null ? 2 : detectJsonIndent(styleRaw);
199
- const eol = styleRaw === null ? "\n" : detectEol(styleRaw);
200
- let data = JSON.stringify(config, null, indent);
201
- if (eol !== "\n") data = data.replace(/\n/g, eol);
202
- if (styleRaw === null || styleRaw.endsWith("\n") || styleRaw.endsWith("\r")) {
203
- data += eol;
204
- }
205
- if (hasBom) data = "\ufeff" + data;
206
- return data;
207
- }
208
-
209
- /**
210
- * Atomically write JSON to a file: write to a temp file, then os.replace().
211
- * Preserves file permissions on Unix (best-effort).
212
- */
213
- function saveConfig(filePath, config) {
214
- let originalRaw = null;
215
- try {
216
- originalRaw = fs.readFileSync(filePath, "utf-8");
217
- } catch (e) {
218
- if (e.code !== "ENOENT") throw e;
219
- }
220
- const data = formatJsonLikeOriginal(config, originalRaw);
221
-
222
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
223
-
224
- let originalMode = null;
225
- try {
226
- originalMode = fs.statSync(filePath).mode & 0o777;
227
- } catch (_) {
228
- // File does not exist yet, so there is no mode to preserve.
229
- }
230
-
231
- const tmpPath = filePath + "." + Date.now() + ".tmp";
232
- fs.writeFileSync(tmpPath, data, "utf-8");
233
-
234
- if (originalMode !== null) {
235
- try {
236
- fs.chmodSync(tmpPath, originalMode);
237
- } catch (_) {
238
- // Windows will not honor chmod fully, but that is fine.
239
- }
240
- }
241
-
242
- // On Windows, os.replace() can fail if the target is read-only
243
- if (process.platform === "win32" && fs.existsSync(filePath)) {
244
- try {
245
- fs.chmodSync(filePath, 0o666);
246
- } catch (_) {}
247
- }
248
-
249
- fs.renameSync(tmpPath, filePath);
250
- }
251
-
252
- function hasMonitorFlag(config) {
253
- const gb = config.cachedGrowthBookFeatures || {};
254
- return gb[FLAG_KEY] === true;
255
- }
256
-
257
- function inject(config) {
258
- if (!config.cachedGrowthBookFeatures) {
259
- config.cachedGrowthBookFeatures = {};
260
- }
261
- const gb = config.cachedGrowthBookFeatures;
262
- if (gb[FLAG_KEY] === true) {
263
- return false; // already present
264
- }
265
- gb[FLAG_KEY] = true;
266
- config.cachedGrowthBookFeaturesAt = Date.now();
267
- return true;
268
- }
269
-
270
- function revert(config) {
271
- const gb = config.cachedGrowthBookFeatures || {};
272
- if (!(FLAG_KEY in gb)) {
273
- return false; // not present
274
- }
275
- delete gb[FLAG_KEY];
276
- if (Object.keys(gb).length === 0) {
277
- delete config.cachedGrowthBookFeatures;
278
- delete config.cachedGrowthBookFeaturesAt;
279
- }
280
- return true;
281
- }
282
-
283
- // Bash discovery (mirrors Claude Code's eye() on Windows)
284
-
285
- function whichGit() {
286
- try {
287
- const cmd = IS_WINDOWS ? "where git" : "command -v git";
288
- const out = execSync(cmd, { stdio: ["ignore", "pipe", "ignore"] })
289
- .toString()
290
- .trim();
291
- return out.split(/\r?\n/)[0] || null;
292
- } catch (_) {
293
- return null;
294
- }
295
- }
296
-
297
- /**
298
- * Locate a usable bash.exe the same way the client does:
299
- * 1. CLAUDE_CODE_GIT_BASH_PATH env (skipped when ignoreEnv)
300
- * 2. default Git for Windows locations
301
- * 3. `git` on PATH -> <gitDir>/../../bin/bash.exe
302
- * Returns { path, isDefault, source }. `path` is null when nothing was found.
303
- */
304
- function findGitBash(ignoreEnv = false) {
305
- if (!ignoreEnv) {
306
- const envPath = process.env[GIT_BASH_ENV];
307
- if (envPath) {
308
- if (fs.existsSync(envPath))
309
- return { path: envPath, isDefault: false, source: "env" };
310
- // A set-but-missing env var is fatal at Claude startup (process.exit(1)).
311
- return { path: null, isDefault: false, source: "env-broken", broken: envPath };
312
- }
313
- }
314
- for (const p of DEFAULT_GIT_BASH_PATHS) {
315
- if (fs.existsSync(p)) return { path: p, isDefault: true, source: "default" };
316
- }
317
- const git = whichGit();
318
- if (git) {
319
- const p = path.join(git, "..", "..", "bin", "bash.exe");
320
- if (fs.existsSync(p)) return { path: p, isDefault: false, source: "git-path" };
321
- }
322
- return { path: null, isDefault: false, source: "none" };
323
- }
324
-
325
- /**
326
- * Ensure a bash.exe exists and, when needed, pin it via settings.env.
327
- * Mutates `env` in place. Returns { changed, ok, bashPath }.
328
- * No-op (ok:true) on non-Windows, where the tool gate does not require bash.
329
- */
330
- function ensureGitBash(env, dryRun) {
331
- if (!IS_WINDOWS) return { changed: false, ok: true, bashPath: null };
332
-
333
- let changed = false;
334
-
335
- if (process.env[GIT_BASH_ENV] && !fs.existsSync(process.env[GIT_BASH_ENV])) {
336
- console.log(` ERROR: External ${GIT_BASH_ENV} points to a missing file: ${process.env[GIT_BASH_ENV]}`);
337
- console.log(" This script only edits Claude settings. Clear or fix that external environment variable, then rerun.");
338
- console.log(` PowerShell user-scope fix: [Environment]::SetEnvironmentVariable('${GIT_BASH_ENV}', $null, 'User')`);
339
- return { changed: false, ok: false, bashPath: null };
340
- }
341
-
342
- // Explicit override wins and skips discovery/install.
343
- if (args["git-bash-path"]) {
344
- const p = path.resolve(args["git-bash-path"]);
345
- if (!fs.existsSync(p)) {
346
- console.log(` ERROR: --git-bash-path does not exist: ${p}`);
347
- return { changed: false, ok: false, bashPath: null };
348
- }
349
- if (env[GIT_BASH_ENV] !== p) {
350
- console.log(` WARN: Pinning ${GIT_BASH_ENV}=${p}`);
351
- env[GIT_BASH_ENV] = p;
352
- changed = true;
353
- }
354
- return { changed, ok: true, bashPath: p };
355
- }
356
-
357
- // If settings.json already pins a path that no longer exists, it would crash
358
- // Claude on startup. Drop it and re-discover a good one below.
359
- if (env[GIT_BASH_ENV] && !fs.existsSync(env[GIT_BASH_ENV])) {
360
- console.log(` WARN: Removing stale ${GIT_BASH_ENV} (missing file): ${env[GIT_BASH_ENV]}`);
361
- delete env[GIT_BASH_ENV];
362
- changed = true;
363
- }
364
-
365
- let found = findGitBash(true); // discovery ignores env; we manage env ourselves
366
-
367
- if (found.path) {
368
- console.log(` OK: bash found: ${found.path} (${found.source})`);
369
- // Only pin when NOT at a default location; Claude auto-detects those.
370
- if (!found.isDefault && env[GIT_BASH_ENV] !== found.path) {
371
- console.log(` WARN: Pinning ${GIT_BASH_ENV}=${found.path}`);
372
- env[GIT_BASH_ENV] = found.path;
373
- changed = true;
374
- }
375
- return { changed, ok: true, bashPath: found.path };
376
- }
377
-
378
- console.log(" ERROR: No bash.exe found. Monitor and Bash will stay hidden on Windows.");
379
- console.log(" Install one of:");
380
- console.log(" - Git for Windows: https://git-scm.com/downloads/win");
381
- console.log(` Or re-run with --git-bash-path <path-to-bash.exe>.`);
382
- return { changed, ok: false, bashPath: null };
383
- }
384
-
385
- // Settings validation
386
-
387
- function isToolSearchEnabled(value) {
388
- return value === "1" || value === "true" || value === true;
389
- }
390
-
391
- function validateAndFixSettingsStrict(dryRun) {
392
- let settings;
393
-
394
- if (!fs.existsSync(settingsPath)) {
395
- console.log(`WARN: Settings file not found: ${settingsPath}`);
396
- console.log(" Creating a minimal settings.json with required env vars ...");
397
- settings = { env: {} };
398
- } else {
399
- try {
400
- settings = loadConfig(settingsPath);
401
- } catch (e) {
402
- console.log(`ERROR: ${e.message}`);
403
- return { changed: false, ok: false };
404
- }
405
- }
406
-
407
- if (!settings || typeof settings !== "object" || Array.isArray(settings)) {
408
- console.log(`ERROR: ${settingsPath} must contain a JSON object`);
409
- return { changed: false, ok: false };
410
- }
411
-
412
- let changed = false;
413
- if (!settings.env || typeof settings.env !== "object" || Array.isArray(settings.env)) {
414
- settings.env = {};
415
- changed = true;
416
- }
417
-
418
- const env = settings.env;
419
-
420
- for (const forbidden of ["DISABLE_TELEMETRY", "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC"]) {
421
- if (forbidden in env) {
422
- console.log(` WARN: Removing ${forbidden}=${JSON.stringify(env[forbidden])} from env`);
423
- delete env[forbidden];
424
- changed = true;
425
- }
426
- }
427
-
428
- if (!isToolSearchEnabled(env["ENABLE_TOOL_SEARCH"])) {
429
- const old = env["ENABLE_TOOL_SEARCH"];
430
- console.log(` WARN: Setting ENABLE_TOOL_SEARCH="true" (was: ${JSON.stringify(old)})`);
431
- env["ENABLE_TOOL_SEARCH"] = "true";
432
- changed = true;
433
- }
434
-
435
- const bash = ensureGitBash(env, dryRun);
436
- if (bash.changed) changed = true;
437
- if (!bash.ok) {
438
- if (changed) {
439
- if (dryRun) {
440
- console.log(`[DRY RUN] Would write partial settings cleanup to ${settingsPath}:`);
441
- console.log(` ${JSON.stringify(settings, null, 2)}`);
442
- } else {
443
- backupBeforeWrite(settingsPath, "settings.json");
444
- saveConfig(settingsPath, settings);
445
- console.log(`OK: ${settingsPath} updated with partial cleanup`);
446
- }
447
- }
448
- console.log("ERROR: Git Bash is required before enabling Monitor on Windows.");
449
- return { changed, ok: false };
450
- }
451
-
452
- if (!changed) {
453
- console.log(`OK: ${settingsPath} passes Monitor validation`);
454
- return { changed: false, ok: true };
455
- }
456
-
457
- if (dryRun) {
458
- console.log(`[DRY RUN] Would write to ${settingsPath}:`);
459
- console.log(` ${JSON.stringify(settings, null, 2)}`);
460
- return { changed: true, ok: true };
461
- }
462
-
463
- backupBeforeWrite(settingsPath, "settings.json");
464
- saveConfig(settingsPath, settings);
465
- console.log(`OK: ${settingsPath} updated for Monitor`);
466
- return { changed: true, ok: true };
467
- }
468
-
469
- function findLatestBackupDir() {
470
- const root = defaultBackupRoot();
471
- if (!fs.existsSync(root)) return null;
472
- const dirs = fs.readdirSync(root, { withFileTypes: true })
473
- .filter((entry) => entry.isDirectory() && entry.name.startsWith(`${BACKUP_PREFIX}-`))
474
- .map((entry) => path.join(root, entry.name))
475
- .sort((a, b) => b.localeCompare(a));
476
- return dirs[0] || null;
477
- }
478
-
479
- function resolveRevertBackupDir() {
480
- if (args["revert-backup"]) return path.resolve(args["revert-backup"]);
481
- return findLatestBackupDir();
482
- }
483
-
484
- function restoreBackupEntry(backupDir, targetPath, backupName, dryRun) {
485
- const sourcePath = path.join(backupDir, backupName);
486
- const missingPath = path.join(backupDir, `${backupName}.missing.txt`);
487
-
488
- if (fs.existsSync(sourcePath)) {
489
- if (dryRun) {
490
- console.log(`[DRY RUN] Would restore ${targetPath} from ${sourcePath}`);
491
- return true;
492
- }
493
- fs.mkdirSync(path.dirname(targetPath), { recursive: true });
494
- fs.copyFileSync(sourcePath, targetPath);
495
- console.log(`OK: Restored ${targetPath} from ${sourcePath}`);
496
- return true;
497
- }
498
-
499
- if (fs.existsSync(missingPath)) {
500
- if (dryRun) {
501
- console.log(`[DRY RUN] Would remove ${targetPath} because it was missing before backup`);
502
- return true;
503
- }
504
- if (fs.existsSync(targetPath)) fs.unlinkSync(targetPath);
505
- console.log(`OK: Removed ${targetPath}; it was missing before backup`);
506
- return true;
507
- }
508
-
509
- return false;
510
- }
511
-
512
- function revertFromTimestampBackup(dryRun) {
513
- const backupDir = resolveRevertBackupDir();
514
- if (!backupDir) {
515
- console.log(`WARN: No ${BACKUP_PREFIX}-* backup directory found under ${defaultBackupRoot()}`);
516
- return false;
517
- }
518
- if (!fs.existsSync(backupDir) || !fs.statSync(backupDir).isDirectory()) {
519
- console.log(`ERROR: Backup directory not found: ${backupDir}`);
520
- return false;
521
- }
522
-
523
- console.log(`Using backup directory: ${backupDir}`);
524
- const restoredConfig = restoreBackupEntry(backupDir, configPath, "claude.json", dryRun);
525
- const restoredSettings = restoreBackupEntry(backupDir, settingsPath, "settings.json", dryRun);
526
- if (!restoredConfig && !restoredSettings) {
527
- console.log("WARN: Backup directory contains neither claude.json nor settings.json backup entries");
528
- }
529
- return restoredConfig || restoredSettings;
530
- }
531
-
532
- function revertLegacySettingsBackup(dryRun) {
533
- const bak = settingsPath + ".bak";
534
- if (!fs.existsSync(bak)) {
535
- console.log(`WARN: No legacy settings backup found: ${bak}`);
536
- return false;
537
- }
538
-
539
- if (dryRun) {
540
- console.log(`[DRY RUN] Would restore ${settingsPath} from ${bak}`);
541
- try {
542
- const settings = loadConfig(bak);
543
- console.log(` Preview: ${JSON.stringify(settings, null, 2)}`);
544
- } catch (e) {
545
- console.log(`ERROR: ${e.message}`);
546
- return false;
547
- }
548
- return true;
549
- }
550
-
551
- let settings;
552
- try {
553
- settings = loadConfig(bak);
554
- } catch (e) {
555
- console.log(`ERROR: ${e.message}`);
556
- return false;
557
- }
558
- backupBeforeWrite(settingsPath, "settings.json");
559
- saveConfig(settingsPath, settings);
560
- fs.unlinkSync(bak);
561
- console.log(`OK: Restored ${settingsPath} from legacy backup ${bak}`);
562
- return true;
563
- }
564
-
565
- // Main
566
-
567
- if (args.revert) {
568
- const restored = revertFromTimestampBackup(args["dry-run"]);
569
- if (!restored) {
570
- console.log("WARN: Falling back to legacy flag removal and settings.json.bak restore.");
571
-
572
- if (fs.existsSync(configPath)) {
573
- let configForRevert;
574
- try {
575
- configForRevert = loadConfig(configPath);
576
- } catch (e) {
577
- console.log(`ERROR: ${e.message}`);
578
- process.exit(1);
579
- }
580
-
581
- if (!configForRevert || typeof configForRevert !== "object" || Array.isArray(configForRevert)) {
582
- console.log(`ERROR: ${configPath} must contain a JSON object`);
583
- process.exit(1);
584
- }
585
-
586
- if (!hasMonitorFlag(configForRevert)) {
587
- console.log(`OK: Nothing to revert; flag not present (${configPath})`);
588
- } else {
589
- const changed = revert(configForRevert);
590
- if (changed && args["dry-run"]) {
591
- console.log(`[DRY RUN] Would remove ${FLAG_KEY}=true from ${configPath}`);
592
- } else if (changed) {
593
- backupBeforeWrite(configPath, "claude.json");
594
- saveConfig(configPath, configForRevert);
595
- console.log(`OK: Removed ${FLAG_KEY}=true in ${configPath}`);
596
- }
597
- }
598
- } else {
599
- console.log(`WARN: Config file not found: ${configPath}`);
600
- }
601
-
602
- revertLegacySettingsBackup(args["dry-run"]);
603
- }
604
-
605
- console.log(" Note: Git for Windows is left in place.");
606
- if (!args["dry-run"]) {
607
- console.log("\n Restart Claude Code for revert to take effect.");
608
- }
609
- process.exit(0);
610
- }
611
-
612
- if (!fs.existsSync(configPath)) {
613
- console.log(`ERROR: Config file not found: ${configPath}`);
614
- process.exit(1);
615
- }
616
-
617
- let config;
618
- try {
619
- config = loadConfig(configPath);
620
- } catch (e) {
621
- console.log(`ERROR: ${e.message}`);
622
- process.exit(1);
623
- }
624
-
625
- if (!config || typeof config !== "object" || Array.isArray(config)) {
626
- console.log(`ERROR: ${configPath} must contain a JSON object`);
627
- process.exit(1);
628
- }
629
-
630
- // Enable path
631
-
632
- const settingsResult = validateAndFixSettingsStrict(args["dry-run"]);
633
- if (!settingsResult.ok) {
634
- if (!args["dry-run"] && backupState.dir) {
635
- console.log(` Backup at: ${backupState.dir}`);
636
- }
637
- console.log("\n Monitor was not enabled. Fix the error above and run this script again.");
638
- process.exit(1);
639
- }
640
- const settingsFixed = settingsResult.changed;
641
-
642
- const flagAlready = hasMonitorFlag(config);
643
- if (flagAlready) {
644
- console.log(`OK: Monitor flag already enabled (${configPath})`);
645
- } else {
646
- const changed = inject(config);
647
- if (!changed) {
648
- console.log("ERROR: No flag change applied");
649
- } else if (args["dry-run"]) {
650
- const preview = JSON.stringify(
651
- {
652
- cachedGrowthBookFeatures: config.cachedGrowthBookFeatures || {},
653
- cachedGrowthBookFeaturesAt: config.cachedGrowthBookFeaturesAt,
654
- },
655
- null,
656
- 2
657
- );
658
- console.log(`[DRY RUN] Would write to ${configPath}:`);
659
- console.log(` Added ${FLAG_KEY}=true`);
660
- console.log(` Preview: ${preview}`);
661
- } else {
662
- backupBeforeWrite(configPath, "claude.json");
663
- saveConfig(configPath, config);
664
- console.log(`OK: Added ${FLAG_KEY}=true in ${configPath}`);
665
- }
666
- }
667
-
668
- if (!args["dry-run"]) {
669
- if (settingsFixed || !flagAlready) {
670
- if (backupState.dir) {
671
- console.log(` Backup at: ${backupState.dir}`);
672
- }
673
- console.log("\n Config changed. Restart Claude Code for Monitor to appear.");
674
- } else {
675
- console.log("\n Already fully configured. Restart Claude Code if Monitor is not visible yet.");
676
- }
677
- }
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Enable the built-in Monitor tool for Claude Code.
4
+ *
5
+ * Two independent requirements must BOTH be satisfied:
6
+ * 1. Feature flag `tengu_amber_sentinel` = true in ~/.claude.json
7
+ * (cachedGrowthBookFeatures) and ENABLE_TOOL_SEARCH="true" in settings.json
8
+ * (legacy "1" is also accepted).
9
+ * -> handled by inject() + validateAndFixSettingsStrict(), validated across envs.
10
+ * 2. On Windows, a real `bash.exe` must be discoverable, because the tool's
11
+ * gate compiles to roughly:
12
+ * isEnabled() = flag("tengu_amber_sentinel") && Au()
13
+ * Au() = platform!=="win32" ? true : findGitBash()!==null
14
+ * i.e. Monitor (and the Bash tool) stay hidden on Windows with no bash.
15
+ * -> handled by ensureGitBash(): mirror the binary's lookup, then pin
16
+ * CLAUDE_CODE_GIT_BASH_PATH when a non-default bash.exe is used.
17
+ *
18
+ * Works on Linux, macOS, and Windows. The bash step is a no-op off Windows.
19
+ *
20
+ * Usage:
21
+ * node enable_monitor.js # enable everything
22
+ * node enable_monitor.js --dry-run # preview changes only
23
+ * node enable_monitor.js --revert # restore the latest timestamped backup
24
+ * node enable_monitor.js --revert-backup <dir> # restore a specific backup directory
25
+ * node enable_monitor.js --git-bash-path <p> # use this bash.exe explicitly
26
+ */
27
+
28
+ const fs = require("fs");
29
+ const path = require("path");
30
+ const os = require("os");
31
+ const crypto = require("crypto");
32
+ const { execSync } = require("child_process");
33
+ const { parseArgs } = require("node:util");
34
+
35
+ // Constants
36
+
37
+ const FLAG_KEY = "tengu_amber_sentinel";
38
+ const GIT_BASH_ENV = "CLAUDE_CODE_GIT_BASH_PATH";
39
+ const HOME = os.homedir();
40
+ const GHOST_PATH = path.join(HOME, ".claude.json");
41
+ const DEFAULT_SETTINGS_PATH = path.join(HOME, ".claude", "settings.json");
42
+ const IS_WINDOWS = process.platform === "win32";
43
+ const BACKUP_PREFIX = "enable-monitor";
44
+
45
+ // Default Git for Windows install locations probed by Claude Code's own lookup.
46
+ const DEFAULT_GIT_BASH_PATHS = [
47
+ "C:\\Program Files\\Git\\bin\\bash.exe",
48
+ "C:\\Program Files (x86)\\Git\\bin\\bash.exe",
49
+ ];
50
+
51
+ // CLI
52
+
53
+ const { values: args } = parseArgs({
54
+ options: {
55
+ "dry-run": { type: "boolean", default: false },
56
+ revert: { type: "boolean", default: false },
57
+ "revert-backup": { type: "string" },
58
+ "git-bash-path": { type: "string" },
59
+ config: { type: "string", default: GHOST_PATH },
60
+ settings: { type: "string", default: DEFAULT_SETTINGS_PATH },
61
+ },
62
+ });
63
+
64
+ function expandHome(input) {
65
+ return path.resolve(String(input).replace(/^~(?=$|[\\/])/, HOME));
66
+ }
67
+
68
+ const configPath = expandHome(args.config);
69
+ const settingsPath = expandHome(args.settings);
70
+
71
+ // Helpers
72
+
73
+ const backupState = {
74
+ dir: null,
75
+ createdAt: null,
76
+ entries: [],
77
+ copiedKeys: new Set(),
78
+ };
79
+
80
+ function defaultBackupRoot() {
81
+ const appData = process.env.APPDATA?.trim();
82
+ if (appData) return path.resolve(appData, "clawclaw", "claude-config-backups");
83
+ return path.resolve(HOME, ".clawclaw", "claude-config-backups");
84
+ }
85
+
86
+ function pad2(n) {
87
+ return String(n).padStart(2, "0");
88
+ }
89
+
90
+ function formatTimestamp(date = new Date()) {
91
+ return (
92
+ `${date.getUTCFullYear()}${pad2(date.getUTCMonth() + 1)}${pad2(date.getUTCDate())}` +
93
+ `-${pad2(date.getUTCHours())}${pad2(date.getUTCMinutes())}${pad2(date.getUTCSeconds())}Z`
94
+ );
95
+ }
96
+
97
+ function chooseUniqueDir(baseDir) {
98
+ if (!fs.existsSync(baseDir)) return baseDir;
99
+ for (let i = 1; i < 1000; i += 1) {
100
+ const candidate = `${baseDir}-${i}`;
101
+ if (!fs.existsSync(candidate)) return candidate;
102
+ }
103
+ throw new Error(`Unable to choose a unique backup directory under ${path.dirname(baseDir)}`);
104
+ }
105
+
106
+ function ensureBackupDir() {
107
+ if (backupState.dir) return backupState.dir;
108
+ const root = defaultBackupRoot();
109
+ const backupDir = chooseUniqueDir(path.join(root, `${BACKUP_PREFIX}-${formatTimestamp()}`));
110
+ fs.mkdirSync(backupDir, { recursive: true });
111
+ backupState.dir = backupDir;
112
+ backupState.createdAt = new Date().toISOString();
113
+ writeBackupManifest();
114
+ return backupDir;
115
+ }
116
+
117
+ function sha256File(filePath) {
118
+ return crypto.createHash("sha256").update(fs.readFileSync(filePath)).digest("hex");
119
+ }
120
+
121
+ function writeBackupManifest() {
122
+ if (!backupState.dir) return;
123
+ const manifest = {
124
+ createdAt: backupState.createdAt,
125
+ purpose: "enable-monitor",
126
+ configPath,
127
+ settingsPath,
128
+ entries: backupState.entries,
129
+ };
130
+ fs.writeFileSync(
131
+ path.join(backupState.dir, "manifest.json"),
132
+ `${JSON.stringify(manifest, null, 2)}\n`,
133
+ "utf-8"
134
+ );
135
+ }
136
+
137
+ function backupBeforeWrite(filePath, backupName) {
138
+ if (args["dry-run"]) {
139
+ throw new Error("backupBeforeWrite must not be called during dry-run");
140
+ }
141
+ const absPath = path.resolve(filePath);
142
+ const key = absPath.toLowerCase();
143
+ if (backupState.copiedKeys.has(key)) return;
144
+
145
+ const backupDir = ensureBackupDir();
146
+ const backupPath = path.join(backupDir, backupName);
147
+ const missingPath = path.join(backupDir, `${backupName}.missing.txt`);
148
+
149
+ if (fs.existsSync(absPath)) {
150
+ fs.copyFileSync(absPath, backupPath);
151
+ backupState.entries.push({
152
+ sourcePath: absPath,
153
+ backupFile: backupName,
154
+ existed: true,
155
+ sha256: sha256File(absPath),
156
+ });
157
+ } else {
158
+ fs.writeFileSync(missingPath, `MISSING: ${absPath}\n`, "utf-8");
159
+ backupState.entries.push({
160
+ sourcePath: absPath,
161
+ backupFile: `${backupName}.missing.txt`,
162
+ existed: false,
163
+ sha256: null,
164
+ });
165
+ }
166
+
167
+ backupState.copiedKeys.add(key);
168
+ writeBackupManifest();
169
+ }
170
+
171
+ function loadConfig(filePath) {
172
+ let raw;
173
+ try {
174
+ raw = fs.readFileSync(filePath, "utf-8");
175
+ } catch (e) {
176
+ throw new Error(`Failed to read ${filePath}: ${e.message}`);
177
+ }
178
+ if (raw.charCodeAt(0) === 0xfeff) raw = raw.slice(1);
179
+ try {
180
+ return JSON.parse(raw);
181
+ } catch (e) {
182
+ throw new Error(`Invalid JSON in ${filePath}: ${e.message}`);
183
+ }
184
+ }
185
+
186
+ function detectJsonIndent(raw) {
187
+ const match = raw.match(/\n([ \t]+)"/);
188
+ return match ? match[1] : 2;
189
+ }
190
+
191
+ function detectEol(raw) {
192
+ return raw.includes("\r\n") ? "\r\n" : "\n";
193
+ }
194
+
195
+ function formatJsonLikeOriginal(config, originalRaw) {
196
+ const hasBom = originalRaw !== null && originalRaw.charCodeAt(0) === 0xfeff;
197
+ const styleRaw = hasBom ? originalRaw.slice(1) : originalRaw;
198
+ const indent = styleRaw === null ? 2 : detectJsonIndent(styleRaw);
199
+ const eol = styleRaw === null ? "\n" : detectEol(styleRaw);
200
+ let data = JSON.stringify(config, null, indent);
201
+ if (eol !== "\n") data = data.replace(/\n/g, eol);
202
+ if (styleRaw === null || styleRaw.endsWith("\n") || styleRaw.endsWith("\r")) {
203
+ data += eol;
204
+ }
205
+ if (hasBom) data = "\ufeff" + data;
206
+ return data;
207
+ }
208
+
209
+ /**
210
+ * Atomically write JSON to a file: write to a temp file, then os.replace().
211
+ * Preserves file permissions on Unix (best-effort).
212
+ */
213
+ function saveConfig(filePath, config) {
214
+ let originalRaw = null;
215
+ try {
216
+ originalRaw = fs.readFileSync(filePath, "utf-8");
217
+ } catch (e) {
218
+ if (e.code !== "ENOENT") throw e;
219
+ }
220
+ const data = formatJsonLikeOriginal(config, originalRaw);
221
+
222
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
223
+
224
+ let originalMode = null;
225
+ try {
226
+ originalMode = fs.statSync(filePath).mode & 0o777;
227
+ } catch (_) {
228
+ // File does not exist yet, so there is no mode to preserve.
229
+ }
230
+
231
+ const tmpPath = filePath + "." + Date.now() + ".tmp";
232
+ fs.writeFileSync(tmpPath, data, "utf-8");
233
+
234
+ if (originalMode !== null) {
235
+ try {
236
+ fs.chmodSync(tmpPath, originalMode);
237
+ } catch (_) {
238
+ // Windows will not honor chmod fully, but that is fine.
239
+ }
240
+ }
241
+
242
+ // On Windows, os.replace() can fail if the target is read-only
243
+ if (process.platform === "win32" && fs.existsSync(filePath)) {
244
+ try {
245
+ fs.chmodSync(filePath, 0o666);
246
+ } catch (_) {}
247
+ }
248
+
249
+ fs.renameSync(tmpPath, filePath);
250
+ }
251
+
252
+ function hasMonitorFlag(config) {
253
+ const gb = config.cachedGrowthBookFeatures || {};
254
+ return gb[FLAG_KEY] === true;
255
+ }
256
+
257
+ function inject(config) {
258
+ if (!config.cachedGrowthBookFeatures) {
259
+ config.cachedGrowthBookFeatures = {};
260
+ }
261
+ const gb = config.cachedGrowthBookFeatures;
262
+ if (gb[FLAG_KEY] === true) {
263
+ return false; // already present
264
+ }
265
+ gb[FLAG_KEY] = true;
266
+ config.cachedGrowthBookFeaturesAt = Date.now();
267
+ return true;
268
+ }
269
+
270
+ function revert(config) {
271
+ const gb = config.cachedGrowthBookFeatures || {};
272
+ if (!(FLAG_KEY in gb)) {
273
+ return false; // not present
274
+ }
275
+ delete gb[FLAG_KEY];
276
+ if (Object.keys(gb).length === 0) {
277
+ delete config.cachedGrowthBookFeatures;
278
+ delete config.cachedGrowthBookFeaturesAt;
279
+ }
280
+ return true;
281
+ }
282
+
283
+ // Bash discovery (mirrors Claude Code's eye() on Windows)
284
+
285
+ function whichGit() {
286
+ try {
287
+ const cmd = IS_WINDOWS ? "where git" : "command -v git";
288
+ const out = execSync(cmd, { stdio: ["ignore", "pipe", "ignore"] })
289
+ .toString()
290
+ .trim();
291
+ return out.split(/\r?\n/)[0] || null;
292
+ } catch (_) {
293
+ return null;
294
+ }
295
+ }
296
+
297
+ /**
298
+ * Locate a usable bash.exe the same way the client does:
299
+ * 1. CLAUDE_CODE_GIT_BASH_PATH env (skipped when ignoreEnv)
300
+ * 2. default Git for Windows locations
301
+ * 3. `git` on PATH -> <gitDir>/../../bin/bash.exe
302
+ * Returns { path, isDefault, source }. `path` is null when nothing was found.
303
+ */
304
+ function findGitBash(ignoreEnv = false) {
305
+ if (!ignoreEnv) {
306
+ const envPath = process.env[GIT_BASH_ENV];
307
+ if (envPath) {
308
+ if (fs.existsSync(envPath))
309
+ return { path: envPath, isDefault: false, source: "env" };
310
+ // A set-but-missing env var is fatal at Claude startup (process.exit(1)).
311
+ return { path: null, isDefault: false, source: "env-broken", broken: envPath };
312
+ }
313
+ }
314
+ for (const p of DEFAULT_GIT_BASH_PATHS) {
315
+ if (fs.existsSync(p)) return { path: p, isDefault: true, source: "default" };
316
+ }
317
+ const git = whichGit();
318
+ if (git) {
319
+ const p = path.join(git, "..", "..", "bin", "bash.exe");
320
+ if (fs.existsSync(p)) return { path: p, isDefault: false, source: "git-path" };
321
+ }
322
+ return { path: null, isDefault: false, source: "none" };
323
+ }
324
+
325
+ /**
326
+ * Ensure a bash.exe exists and, when needed, pin it via settings.env.
327
+ * Mutates `env` in place. Returns { changed, ok, bashPath }.
328
+ * No-op (ok:true) on non-Windows, where the tool gate does not require bash.
329
+ */
330
+ function ensureGitBash(env, dryRun) {
331
+ if (!IS_WINDOWS) return { changed: false, ok: true, bashPath: null };
332
+
333
+ let changed = false;
334
+
335
+ if (process.env[GIT_BASH_ENV] && !fs.existsSync(process.env[GIT_BASH_ENV])) {
336
+ console.log(` ERROR: External ${GIT_BASH_ENV} points to a missing file: ${process.env[GIT_BASH_ENV]}`);
337
+ console.log(" This script only edits Claude settings. Clear or fix that external environment variable, then rerun.");
338
+ console.log(` PowerShell user-scope fix: [Environment]::SetEnvironmentVariable('${GIT_BASH_ENV}', $null, 'User')`);
339
+ return { changed: false, ok: false, bashPath: null };
340
+ }
341
+
342
+ // Explicit override wins and skips discovery/install.
343
+ if (args["git-bash-path"]) {
344
+ const p = path.resolve(args["git-bash-path"]);
345
+ if (!fs.existsSync(p)) {
346
+ console.log(` ERROR: --git-bash-path does not exist: ${p}`);
347
+ return { changed: false, ok: false, bashPath: null };
348
+ }
349
+ if (env[GIT_BASH_ENV] !== p) {
350
+ console.log(` WARN: Pinning ${GIT_BASH_ENV}=${p}`);
351
+ env[GIT_BASH_ENV] = p;
352
+ changed = true;
353
+ }
354
+ return { changed, ok: true, bashPath: p };
355
+ }
356
+
357
+ // If settings.json already pins a path that no longer exists, it would crash
358
+ // Claude on startup. Drop it and re-discover a good one below.
359
+ if (env[GIT_BASH_ENV] && !fs.existsSync(env[GIT_BASH_ENV])) {
360
+ console.log(` WARN: Removing stale ${GIT_BASH_ENV} (missing file): ${env[GIT_BASH_ENV]}`);
361
+ delete env[GIT_BASH_ENV];
362
+ changed = true;
363
+ }
364
+
365
+ let found = findGitBash(true); // discovery ignores env; we manage env ourselves
366
+
367
+ if (found.path) {
368
+ console.log(` OK: bash found: ${found.path} (${found.source})`);
369
+ // Only pin when NOT at a default location; Claude auto-detects those.
370
+ if (!found.isDefault && env[GIT_BASH_ENV] !== found.path) {
371
+ console.log(` WARN: Pinning ${GIT_BASH_ENV}=${found.path}`);
372
+ env[GIT_BASH_ENV] = found.path;
373
+ changed = true;
374
+ }
375
+ return { changed, ok: true, bashPath: found.path };
376
+ }
377
+
378
+ console.log(" ERROR: No bash.exe found. Monitor and Bash will stay hidden on Windows.");
379
+ console.log(" Install one of:");
380
+ console.log(" - Git for Windows: https://git-scm.com/downloads/win");
381
+ console.log(` Or re-run with --git-bash-path <path-to-bash.exe>.`);
382
+ return { changed, ok: false, bashPath: null };
383
+ }
384
+
385
+ // Settings validation
386
+
387
+ function isToolSearchEnabled(value) {
388
+ return value === "1" || value === "true" || value === true;
389
+ }
390
+
391
+ function validateAndFixSettingsStrict(dryRun) {
392
+ let settings;
393
+
394
+ if (!fs.existsSync(settingsPath)) {
395
+ console.log(`WARN: Settings file not found: ${settingsPath}`);
396
+ console.log(" Creating a minimal settings.json with required env vars ...");
397
+ settings = { env: {} };
398
+ } else {
399
+ try {
400
+ settings = loadConfig(settingsPath);
401
+ } catch (e) {
402
+ console.log(`ERROR: ${e.message}`);
403
+ return { changed: false, ok: false };
404
+ }
405
+ }
406
+
407
+ if (!settings || typeof settings !== "object" || Array.isArray(settings)) {
408
+ console.log(`ERROR: ${settingsPath} must contain a JSON object`);
409
+ return { changed: false, ok: false };
410
+ }
411
+
412
+ let changed = false;
413
+ if (!settings.env || typeof settings.env !== "object" || Array.isArray(settings.env)) {
414
+ settings.env = {};
415
+ changed = true;
416
+ }
417
+
418
+ const env = settings.env;
419
+
420
+ for (const forbidden of ["DISABLE_TELEMETRY", "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC"]) {
421
+ if (forbidden in env) {
422
+ console.log(` WARN: Removing ${forbidden}=${JSON.stringify(env[forbidden])} from env`);
423
+ delete env[forbidden];
424
+ changed = true;
425
+ }
426
+ }
427
+
428
+ if (!isToolSearchEnabled(env["ENABLE_TOOL_SEARCH"])) {
429
+ const old = env["ENABLE_TOOL_SEARCH"];
430
+ console.log(` WARN: Setting ENABLE_TOOL_SEARCH="true" (was: ${JSON.stringify(old)})`);
431
+ env["ENABLE_TOOL_SEARCH"] = "true";
432
+ changed = true;
433
+ }
434
+
435
+ const bash = ensureGitBash(env, dryRun);
436
+ if (bash.changed) changed = true;
437
+ if (!bash.ok) {
438
+ if (changed) {
439
+ if (dryRun) {
440
+ console.log(`[DRY RUN] Would write partial settings cleanup to ${settingsPath}:`);
441
+ console.log(` ${JSON.stringify(settings, null, 2)}`);
442
+ } else {
443
+ backupBeforeWrite(settingsPath, "settings.json");
444
+ saveConfig(settingsPath, settings);
445
+ console.log(`OK: ${settingsPath} updated with partial cleanup`);
446
+ }
447
+ }
448
+ console.log("ERROR: Git Bash is required before enabling Monitor on Windows.");
449
+ return { changed, ok: false };
450
+ }
451
+
452
+ if (!changed) {
453
+ console.log(`OK: ${settingsPath} passes Monitor validation`);
454
+ return { changed: false, ok: true };
455
+ }
456
+
457
+ if (dryRun) {
458
+ console.log(`[DRY RUN] Would write to ${settingsPath}:`);
459
+ console.log(` ${JSON.stringify(settings, null, 2)}`);
460
+ return { changed: true, ok: true };
461
+ }
462
+
463
+ backupBeforeWrite(settingsPath, "settings.json");
464
+ saveConfig(settingsPath, settings);
465
+ console.log(`OK: ${settingsPath} updated for Monitor`);
466
+ return { changed: true, ok: true };
467
+ }
468
+
469
+ function findLatestBackupDir() {
470
+ const root = defaultBackupRoot();
471
+ if (!fs.existsSync(root)) return null;
472
+ const dirs = fs.readdirSync(root, { withFileTypes: true })
473
+ .filter((entry) => entry.isDirectory() && entry.name.startsWith(`${BACKUP_PREFIX}-`))
474
+ .map((entry) => path.join(root, entry.name))
475
+ .sort((a, b) => b.localeCompare(a));
476
+ return dirs[0] || null;
477
+ }
478
+
479
+ function resolveRevertBackupDir() {
480
+ if (args["revert-backup"]) return path.resolve(args["revert-backup"]);
481
+ return findLatestBackupDir();
482
+ }
483
+
484
+ function restoreBackupEntry(backupDir, targetPath, backupName, dryRun) {
485
+ const sourcePath = path.join(backupDir, backupName);
486
+ const missingPath = path.join(backupDir, `${backupName}.missing.txt`);
487
+
488
+ if (fs.existsSync(sourcePath)) {
489
+ if (dryRun) {
490
+ console.log(`[DRY RUN] Would restore ${targetPath} from ${sourcePath}`);
491
+ return true;
492
+ }
493
+ fs.mkdirSync(path.dirname(targetPath), { recursive: true });
494
+ fs.copyFileSync(sourcePath, targetPath);
495
+ console.log(`OK: Restored ${targetPath} from ${sourcePath}`);
496
+ return true;
497
+ }
498
+
499
+ if (fs.existsSync(missingPath)) {
500
+ if (dryRun) {
501
+ console.log(`[DRY RUN] Would remove ${targetPath} because it was missing before backup`);
502
+ return true;
503
+ }
504
+ if (fs.existsSync(targetPath)) fs.unlinkSync(targetPath);
505
+ console.log(`OK: Removed ${targetPath}; it was missing before backup`);
506
+ return true;
507
+ }
508
+
509
+ return false;
510
+ }
511
+
512
+ function revertFromTimestampBackup(dryRun) {
513
+ const backupDir = resolveRevertBackupDir();
514
+ if (!backupDir) {
515
+ console.log(`WARN: No ${BACKUP_PREFIX}-* backup directory found under ${defaultBackupRoot()}`);
516
+ return false;
517
+ }
518
+ if (!fs.existsSync(backupDir) || !fs.statSync(backupDir).isDirectory()) {
519
+ console.log(`ERROR: Backup directory not found: ${backupDir}`);
520
+ return false;
521
+ }
522
+
523
+ console.log(`Using backup directory: ${backupDir}`);
524
+ const restoredConfig = restoreBackupEntry(backupDir, configPath, "claude.json", dryRun);
525
+ const restoredSettings = restoreBackupEntry(backupDir, settingsPath, "settings.json", dryRun);
526
+ if (!restoredConfig && !restoredSettings) {
527
+ console.log("WARN: Backup directory contains neither claude.json nor settings.json backup entries");
528
+ }
529
+ return restoredConfig || restoredSettings;
530
+ }
531
+
532
+ function revertLegacySettingsBackup(dryRun) {
533
+ const bak = settingsPath + ".bak";
534
+ if (!fs.existsSync(bak)) {
535
+ console.log(`WARN: No legacy settings backup found: ${bak}`);
536
+ return false;
537
+ }
538
+
539
+ if (dryRun) {
540
+ console.log(`[DRY RUN] Would restore ${settingsPath} from ${bak}`);
541
+ try {
542
+ const settings = loadConfig(bak);
543
+ console.log(` Preview: ${JSON.stringify(settings, null, 2)}`);
544
+ } catch (e) {
545
+ console.log(`ERROR: ${e.message}`);
546
+ return false;
547
+ }
548
+ return true;
549
+ }
550
+
551
+ let settings;
552
+ try {
553
+ settings = loadConfig(bak);
554
+ } catch (e) {
555
+ console.log(`ERROR: ${e.message}`);
556
+ return false;
557
+ }
558
+ backupBeforeWrite(settingsPath, "settings.json");
559
+ saveConfig(settingsPath, settings);
560
+ fs.unlinkSync(bak);
561
+ console.log(`OK: Restored ${settingsPath} from legacy backup ${bak}`);
562
+ return true;
563
+ }
564
+
565
+ // Main
566
+
567
+ if (args.revert) {
568
+ const restored = revertFromTimestampBackup(args["dry-run"]);
569
+ if (!restored) {
570
+ console.log("WARN: Falling back to legacy flag removal and settings.json.bak restore.");
571
+
572
+ if (fs.existsSync(configPath)) {
573
+ let configForRevert;
574
+ try {
575
+ configForRevert = loadConfig(configPath);
576
+ } catch (e) {
577
+ console.log(`ERROR: ${e.message}`);
578
+ process.exit(1);
579
+ }
580
+
581
+ if (!configForRevert || typeof configForRevert !== "object" || Array.isArray(configForRevert)) {
582
+ console.log(`ERROR: ${configPath} must contain a JSON object`);
583
+ process.exit(1);
584
+ }
585
+
586
+ if (!hasMonitorFlag(configForRevert)) {
587
+ console.log(`OK: Nothing to revert; flag not present (${configPath})`);
588
+ } else {
589
+ const changed = revert(configForRevert);
590
+ if (changed && args["dry-run"]) {
591
+ console.log(`[DRY RUN] Would remove ${FLAG_KEY}=true from ${configPath}`);
592
+ } else if (changed) {
593
+ backupBeforeWrite(configPath, "claude.json");
594
+ saveConfig(configPath, configForRevert);
595
+ console.log(`OK: Removed ${FLAG_KEY}=true in ${configPath}`);
596
+ }
597
+ }
598
+ } else {
599
+ console.log(`WARN: Config file not found: ${configPath}`);
600
+ }
601
+
602
+ revertLegacySettingsBackup(args["dry-run"]);
603
+ }
604
+
605
+ console.log(" Note: Git for Windows is left in place.");
606
+ if (!args["dry-run"]) {
607
+ console.log("\n Restart Claude Code for revert to take effect.");
608
+ }
609
+ process.exit(0);
610
+ }
611
+
612
+ if (!fs.existsSync(configPath)) {
613
+ console.log(`ERROR: Config file not found: ${configPath}`);
614
+ process.exit(1);
615
+ }
616
+
617
+ let config;
618
+ try {
619
+ config = loadConfig(configPath);
620
+ } catch (e) {
621
+ console.log(`ERROR: ${e.message}`);
622
+ process.exit(1);
623
+ }
624
+
625
+ if (!config || typeof config !== "object" || Array.isArray(config)) {
626
+ console.log(`ERROR: ${configPath} must contain a JSON object`);
627
+ process.exit(1);
628
+ }
629
+
630
+ // Enable path
631
+
632
+ const settingsResult = validateAndFixSettingsStrict(args["dry-run"]);
633
+ if (!settingsResult.ok) {
634
+ if (!args["dry-run"] && backupState.dir) {
635
+ console.log(` Backup at: ${backupState.dir}`);
636
+ }
637
+ console.log("\n Monitor was not enabled. Fix the error above and run this script again.");
638
+ process.exit(1);
639
+ }
640
+ const settingsFixed = settingsResult.changed;
641
+
642
+ const flagAlready = hasMonitorFlag(config);
643
+ if (flagAlready) {
644
+ console.log(`OK: Monitor flag already enabled (${configPath})`);
645
+ } else {
646
+ const changed = inject(config);
647
+ if (!changed) {
648
+ console.log("ERROR: No flag change applied");
649
+ } else if (args["dry-run"]) {
650
+ const preview = JSON.stringify(
651
+ {
652
+ cachedGrowthBookFeatures: config.cachedGrowthBookFeatures || {},
653
+ cachedGrowthBookFeaturesAt: config.cachedGrowthBookFeaturesAt,
654
+ },
655
+ null,
656
+ 2
657
+ );
658
+ console.log(`[DRY RUN] Would write to ${configPath}:`);
659
+ console.log(` Added ${FLAG_KEY}=true`);
660
+ console.log(` Preview: ${preview}`);
661
+ } else {
662
+ backupBeforeWrite(configPath, "claude.json");
663
+ saveConfig(configPath, config);
664
+ console.log(`OK: Added ${FLAG_KEY}=true in ${configPath}`);
665
+ }
666
+ }
667
+
668
+ if (!args["dry-run"]) {
669
+ if (settingsFixed || !flagAlready) {
670
+ if (backupState.dir) {
671
+ console.log(` Backup at: ${backupState.dir}`);
672
+ }
673
+ console.log("\n Config changed. Restart Claude Code for Monitor to appear.");
674
+ } else {
675
+ console.log("\n Already fully configured. Restart Claude Code if Monitor is not visible yet.");
676
+ }
677
+ }