@chroxy/server 0.11.0 → 0.11.11

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 (386) hide show
  1. package/CONFIG.md +206 -18
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +166 -11
  5. package/package.json +16 -12
  6. package/sidecar/Dockerfile +1 -1
  7. package/sidecar/PROTOCOL.md +9 -1
  8. package/sidecar/agent.js +102 -10
  9. package/sidecar/package-lock.json +3 -3
  10. package/src/acp-config.js +206 -0
  11. package/src/acp-session.js +958 -0
  12. package/src/activity-registry.js +110 -5
  13. package/src/agent-connections.js +304 -0
  14. package/src/agent-control/client.js +1645 -0
  15. package/src/agent-control/events.js +551 -0
  16. package/src/agent-control/local-connection.js +293 -0
  17. package/src/agent-control/mcp-server.js +547 -0
  18. package/src/anthropic-compatible-config.js +30 -4
  19. package/src/anthropic-compatible-session.js +15 -6
  20. package/src/anthropic-gemini-shim.js +444 -0
  21. package/src/anthropic-gemini-translate.js +1030 -0
  22. package/src/anthropic-openai-shim.js +0 -1
  23. package/src/archive-continuation.js +164 -0
  24. package/src/assistant-response.js +24 -0
  25. package/src/auth-probes.js +120 -13
  26. package/src/background-shell-tracker.js +27 -0
  27. package/src/base-session.js +1520 -36
  28. package/src/bearer-recheck.js +49 -0
  29. package/src/billing-budget.js +19 -0
  30. package/src/billing-class.js +40 -7
  31. package/src/binary-provenance-trust.js +11 -5
  32. package/src/bound-client-policy.js +291 -0
  33. package/src/built-in-tools/bash-exec.js +46 -7
  34. package/src/built-in-tools/file-ops.js +69 -5
  35. package/src/built-in-tools/tool-transforms.js +1113 -13
  36. package/src/byok-compose-state.js +6 -9
  37. package/src/byok-credentials.js +2 -3
  38. package/src/byok-mcp-client.js +92 -7
  39. package/src/byok-mcp-config.js +633 -122
  40. package/src/byok-mcp-fleet.js +49 -7
  41. package/src/byok-mcp-oauth-store.js +18 -16
  42. package/src/byok-mcp-trust.js +37 -23
  43. package/src/byok-session.js +707 -179
  44. package/src/byok-tool-executor.js +2742 -26
  45. package/src/byok-tools.js +9 -2
  46. package/src/channels/chroxy-channel-server.js +2 -3
  47. package/src/checkpoint-manager.js +64 -46
  48. package/src/claude-channel-session.js +16 -10
  49. package/src/claude-model-catalog.js +131 -16
  50. package/src/claude-model-refresh.js +385 -0
  51. package/src/claude-model-request.js +103 -0
  52. package/src/claude-setting-sources.js +74 -0
  53. package/src/claude-stream-parser.js +53 -3
  54. package/src/claude-tui/diagnostic-tail.js +83 -0
  55. package/src/claude-tui/form-driver.js +44 -7
  56. package/src/claude-tui/model-error.js +41 -0
  57. package/src/claude-tui/pty-driver.js +215 -88
  58. package/src/claude-tui/sanitize-question-payload.js +109 -0
  59. package/src/claude-tui/usage-limit.js +239 -0
  60. package/src/claude-tui-session.js +3563 -284
  61. package/src/claude-tui-tool-response.js +300 -0
  62. package/src/cli/agent-cmd.js +236 -0
  63. package/src/cli/agent-control-cmd.js +65 -0
  64. package/src/cli/config-cmd.js +4 -4
  65. package/src/cli/config-dir-cmd.js +234 -0
  66. package/src/cli/connection-state.js +54 -0
  67. package/src/cli/deploy-cmd.js +45 -10
  68. package/src/cli/doctor-cmd.js +7 -3
  69. package/src/cli/freshness-cmd.js +53 -0
  70. package/src/cli/init-cmd.js +15 -16
  71. package/src/cli/pages-cmd.js +6 -4
  72. package/src/cli/pair-code-cmd.js +7 -6
  73. package/src/cli/pair-discord-cmd.js +7 -6
  74. package/src/cli/providers-cmd.js +3 -3
  75. package/src/cli/schedule-cmd.js +91 -40
  76. package/src/cli/server-cmd.js +54 -1
  77. package/src/cli/service-cmd.js +33 -10
  78. package/src/cli/session-cmd.js +227 -74
  79. package/src/cli/shared.js +162 -11
  80. package/src/cli/shell-cmd.js +7 -4
  81. package/src/cli/status-cmd.js +19 -5
  82. package/src/cli/tokens-cmd.js +4 -5
  83. package/src/cli/tunnel-cmd.js +255 -24
  84. package/src/cli/worktree-gc-cmd.js +2 -2
  85. package/src/cli-session.js +1250 -126
  86. package/src/cli.js +8 -0
  87. package/src/codex-app-server-client.js +36 -3
  88. package/src/codex-app-server-session.js +1517 -81
  89. package/src/codex-bundled-client.js +66 -0
  90. package/src/codex-error-text.js +114 -0
  91. package/src/codex-model-catalog.js +548 -0
  92. package/src/codex-model-rejections.js +87 -0
  93. package/src/codex-native-resume.js +104 -0
  94. package/src/codex-protocol-capabilities.js +188 -0
  95. package/src/codex-session.js +450 -27
  96. package/src/config-dir-migration.js +449 -0
  97. package/src/config-dir.js +108 -0
  98. package/src/config.js +306 -26
  99. package/src/connection-authority.js +48 -0
  100. package/src/connection-info.js +78 -23
  101. package/src/connection-locality.js +60 -0
  102. package/src/container-liveness-monitor.js +189 -0
  103. package/src/continuation-metadata-worker.js +17 -0
  104. package/src/continuations.js +227 -0
  105. package/src/control-room/host-prune.js +5 -0
  106. package/src/control-room/integrations.js +7 -20
  107. package/src/control-room/skills-inventory.js +2 -2
  108. package/src/conversation-scanner.js +42 -39
  109. package/src/conversation-scope.js +59 -39
  110. package/src/conversation-search.js +28 -39
  111. package/src/credential-store.js +23 -19
  112. package/src/daemon-commit.js +92 -0
  113. package/src/daemon-idle-state.js +171 -0
  114. package/src/daemon-update-status.js +314 -0
  115. package/src/dashboard-build.js +70 -0
  116. package/src/declared-status.js +90 -0
  117. package/src/deepseek-credentials.js +2 -3
  118. package/src/dev-preview.js +170 -182
  119. package/src/device-preferences.js +2 -2
  120. package/src/diff-parser.js +87 -0
  121. package/src/discord-credentials.js +2 -3
  122. package/src/docker-byok-pool.js +3 -1
  123. package/src/docker-byok-session.js +678 -78
  124. package/src/docker-image-allowlist.js +23 -1
  125. package/src/docker-sdk-session.js +172 -3
  126. package/src/docker-session.js +294 -11
  127. package/src/doctor.js +781 -64
  128. package/src/durable-write.js +35 -0
  129. package/src/edited-input.js +264 -0
  130. package/src/environment-manager.js +175 -36
  131. package/src/environments/authority.js +101 -0
  132. package/src/environments/backends/container-claude-spawn.js +94 -0
  133. package/src/environments/backends/docker.js +31 -10
  134. package/src/environments/backends/k8s.js +49 -24
  135. package/src/environments/destroy-with-sessions.js +142 -0
  136. package/src/event-ingest.js +118 -13
  137. package/src/event-normalizer.js +186 -235
  138. package/src/folder-trust-wire.js +137 -0
  139. package/src/folder-trust-worker.js +17 -0
  140. package/src/folder-trust.js +1572 -0
  141. package/src/freshness/activity-meter.js +101 -0
  142. package/src/freshness/adapter.js +199 -0
  143. package/src/freshness/checks.js +239 -0
  144. package/src/freshness/config.js +98 -0
  145. package/src/freshness/core.js +185 -0
  146. package/src/freshness/derive.js +680 -0
  147. package/src/freshness/exchange.js +305 -0
  148. package/src/freshness/file-ledger.js +400 -0
  149. package/src/freshness/grade.js +81 -0
  150. package/src/freshness/hash.js +45 -0
  151. package/src/freshness/inbox.js +163 -0
  152. package/src/freshness/index.js +20 -0
  153. package/src/freshness/investigation.js +474 -0
  154. package/src/freshness/keys.js +177 -0
  155. package/src/freshness/ledger.js +122 -0
  156. package/src/freshness/outbox.js +131 -0
  157. package/src/freshness/policy.js +599 -0
  158. package/src/freshness/queue.js +843 -0
  159. package/src/freshness/read-errors.js +23 -0
  160. package/src/freshness/render.js +153 -0
  161. package/src/freshness/runtime.js +113 -0
  162. package/src/freshness/session-registry-adapter.js +161 -0
  163. package/src/freshness/state-file-adapter.js +167 -0
  164. package/src/freshness-runner/build-info.js +139 -0
  165. package/src/freshness-runner/cli.js +105 -0
  166. package/src/freshness-runner/run-tick.js +109 -0
  167. package/src/freshness-runner/stamp.js +57 -0
  168. package/src/freshness-sources/claude-transcript-adapter.js +211 -0
  169. package/src/freshness-sources/codex-transcript-adapter.js +33 -0
  170. package/src/freshness-sources/index.js +8 -0
  171. package/src/gemini-byok-session.js +292 -0
  172. package/src/gemini-credentials.js +67 -0
  173. package/src/gemini-key-safety.js +246 -0
  174. package/src/gemini-models.js +386 -0
  175. package/src/gemini-session.js +81 -5
  176. package/src/handler-utils.js +540 -80
  177. package/src/handlers/checkpoint-handlers.js +47 -4
  178. package/src/handlers/control-room-handlers.js +51 -11
  179. package/src/handlers/conversation-handlers.js +469 -56
  180. package/src/handlers/daemon-update-handlers.js +81 -0
  181. package/src/handlers/evaluator-handlers.js +14 -1
  182. package/src/handlers/feature-handlers.js +186 -69
  183. package/src/handlers/file-handlers.js +57 -13
  184. package/src/handlers/folder-trust-handlers.js +90 -0
  185. package/src/handlers/input-handlers.js +714 -48
  186. package/src/handlers/orchestration-handlers.js +3 -3
  187. package/src/handlers/principal-admin-handlers.js +229 -0
  188. package/src/handlers/principal-handlers.js +262 -0
  189. package/src/handlers/scheduler-handlers.js +92 -18
  190. package/src/handlers/session-handlers.js +551 -20
  191. package/src/handlers/session-pr-status-handlers.js +283 -0
  192. package/src/handlers/session-pr-threads-handlers.js +247 -0
  193. package/src/handlers/settings-handlers.js +372 -50
  194. package/src/handlers/skills-handlers.js +20 -4
  195. package/src/handlers/summarize-handlers.js +32 -1
  196. package/src/handlers/survey-throttle.js +380 -0
  197. package/src/health-proof.js +40 -0
  198. package/src/history-page.js +112 -0
  199. package/src/http-routes.js +127 -8
  200. package/src/ide/search.js +24 -6
  201. package/src/ide/symbols.js +20 -6
  202. package/src/input-context.js +117 -0
  203. package/src/instruction-policy-compiler.js +229 -0
  204. package/src/instruction-policy.js +250 -0
  205. package/src/jsonl-reader.js +378 -91
  206. package/src/jsonl-subprocess-session.js +96 -9
  207. package/src/keychain.js +1 -1
  208. package/src/logger.js +166 -30
  209. package/src/mailbox-route.js +113 -22
  210. package/src/message-wire.js +386 -0
  211. package/src/model-discovery.js +43 -3
  212. package/src/models.js +1276 -174
  213. package/src/notification-prefs.js +27 -4
  214. package/src/notifications/discord-billing-sink.js +22 -5
  215. package/src/notifications/discord-ci-sink.js +243 -0
  216. package/src/notifications/discord-webhook-client.js +71 -0
  217. package/src/notifications/discord-webhook-sink.js +64 -23
  218. package/src/notifications/expo-push-sink.js +85 -6
  219. package/src/notifications/ready-body.js +16 -5
  220. package/src/ollama-session.js +34 -2
  221. package/src/orchestration/build-manager.js +9 -2
  222. package/src/orchestration/git-ops.js +41 -7
  223. package/src/orchestration/orchestration-manager.js +112 -36
  224. package/src/orchestration/permission-gate.js +17 -2
  225. package/src/orchestration/run-model.js +2 -1
  226. package/src/orchestration/run-record.js +11 -0
  227. package/src/orchestration/turn-driver.js +185 -43
  228. package/src/orphan-reaper.js +470 -0
  229. package/src/outgoing-policy.js +189 -0
  230. package/src/pairing.js +92 -13
  231. package/src/path-hash-trust-ledger.js +642 -25
  232. package/src/permission-deadlines.js +82 -0
  233. package/src/permission-floor.js +1410 -43
  234. package/src/permission-hook.js +180 -69
  235. package/src/permission-manager.js +737 -89
  236. package/src/permission-mode-support.js +35 -0
  237. package/src/permission-resolved-by.js +89 -0
  238. package/src/permission-resolver.js +126 -8
  239. package/src/permission-scope.js +43 -0
  240. package/src/platform.js +315 -47
  241. package/src/preview-ingress.js +54 -0
  242. package/src/preview-target.js +213 -0
  243. package/src/principal-audit.js +189 -0
  244. package/src/principal-binding.js +25 -0
  245. package/src/principal-brakes.js +21 -0
  246. package/src/principal-effect.js +101 -0
  247. package/src/principal-journal.js +905 -0
  248. package/src/principal-kill-switch.js +183 -0
  249. package/src/principal-label.js +5 -0
  250. package/src/principal-pending-permissions.js +177 -0
  251. package/src/principal-policy.js +1094 -0
  252. package/src/principal-sessions-snapshot.js +208 -0
  253. package/src/principal-store.js +488 -0
  254. package/src/principal-subscriptions.js +283 -0
  255. package/src/prompt-evaluator.js +34 -4
  256. package/src/provider-customization.js +180 -0
  257. package/src/providers.js +209 -4
  258. package/src/push.js +30 -4
  259. package/src/question-route-map.js +130 -0
  260. package/src/redaction.js +531 -20
  261. package/src/roster-broadcast.js +186 -0
  262. package/src/scheduled-task-store.js +330 -26
  263. package/src/scheduler.js +368 -11
  264. package/src/sdk-session.js +2114 -188
  265. package/src/server-cli/preview-shutdown.js +22 -0
  266. package/src/server-cli/push-notification-handler.js +17 -3
  267. package/src/server-cli/server-orchestrator.js +28 -5
  268. package/src/server-cli-child.js +33 -18
  269. package/src/server-cli.js +553 -38
  270. package/src/server-identity.js +15 -11
  271. package/src/service.js +396 -25
  272. package/src/session-archive-limits.js +15 -0
  273. package/src/session-archive.js +1029 -0
  274. package/src/session-busy-state.js +72 -0
  275. package/src/session-ci-watcher.js +1099 -0
  276. package/src/session-context.js +7 -2
  277. package/src/session-manager.js +4062 -312
  278. package/src/session-message-history.js +841 -16
  279. package/src/session-name-allocator.js +685 -0
  280. package/src/session-pr-status.js +654 -0
  281. package/src/session-pr-threads.js +271 -0
  282. package/src/session-preset-trust.js +3 -3
  283. package/src/session-preset.js +10 -5
  284. package/src/session-state-persistence.js +94 -17
  285. package/src/session-timeout-manager.js +20 -0
  286. package/src/session-token-store.js +17 -8
  287. package/src/session-wake.js +240 -0
  288. package/src/shell-approval-info.js +2 -2
  289. package/src/shell-approval-store.js +3 -1
  290. package/src/skills-loader.js +7 -4
  291. package/src/skills-manager.js +2 -2
  292. package/src/skills-trust.js +95 -13
  293. package/src/skills-usage.js +2 -3
  294. package/src/snapshots-store.js +2 -3
  295. package/src/statusline.js +100 -29
  296. package/src/summarize-session.js +53 -4
  297. package/src/supervisor.js +22 -11
  298. package/src/sweep-stale-provider-dirs.js +95 -0
  299. package/src/thinking-level-wire.js +39 -0
  300. package/src/thinking-stream.js +179 -0
  301. package/src/tool-result.js +61 -0
  302. package/src/transcript-sources.js +109 -0
  303. package/src/transcript-tasks.js +372 -25
  304. package/src/trusted-file-read.js +302 -0
  305. package/src/tunnel/base.js +0 -8
  306. package/src/tunnel/cloudflare.js +34 -31
  307. package/src/tunnel/index.js +9 -0
  308. package/src/tunnel/preview.js +64 -0
  309. package/src/turn-outcome.js +140 -0
  310. package/src/usage-normalize.js +9 -5
  311. package/src/user-shell-session.js +59 -5
  312. package/src/utils/agent-sdk-version.js +107 -0
  313. package/src/utils/argv-safety.js +770 -0
  314. package/src/utils/auth-cause.js +60 -0
  315. package/src/utils/binary-package-manifest.js +639 -0
  316. package/src/utils/binary-version.js +224 -0
  317. package/src/utils/bounded-regex-worker.js +29 -0
  318. package/src/utils/bounded-regex.js +162 -0
  319. package/src/utils/claude-binary.js +43 -0
  320. package/src/utils/claude-config-dir.js +245 -0
  321. package/src/utils/claude-login-command.js +16 -0
  322. package/src/utils/claude-native-route.js +81 -0
  323. package/src/utils/componentwise-resolver.js +133 -37
  324. package/src/utils/deploy-control-files.js +87 -0
  325. package/src/utils/exec-failure-reason.js +21 -0
  326. package/src/utils/git-repo.js +42 -0
  327. package/src/utils/is-entry-point.js +137 -0
  328. package/src/utils/node-pty-probe.js +95 -0
  329. package/src/utils/node-pty-support.js +118 -0
  330. package/src/utils/opened-file-path.js +167 -0
  331. package/src/utils/path-containment.js +165 -0
  332. package/src/utils/permission-mode-sidecar.js +51 -0
  333. package/src/utils/pid-liveness.js +47 -0
  334. package/src/utils/preflight.js +360 -16
  335. package/src/utils/read-limiter.js +217 -0
  336. package/src/utils/regular-file.js +375 -0
  337. package/src/utils/safe-regex.js +113 -0
  338. package/src/utils/small-file.js +129 -0
  339. package/src/utils/spawn-env.js +189 -4
  340. package/src/utils/stale-session-dirs.js +182 -0
  341. package/src/utils/stat-identity.js +43 -0
  342. package/src/utils/verify-provenance.js +406 -13
  343. package/src/web-task-manager.js +297 -16
  344. package/src/worktree-gc.js +202 -6
  345. package/src/ws-auth.js +163 -31
  346. package/src/ws-broadcaster.js +49 -5
  347. package/src/ws-client-manager.js +24 -1
  348. package/src/ws-client-sender.js +7 -0
  349. package/src/ws-file-ops/browser.js +363 -58
  350. package/src/ws-file-ops/common.js +320 -14
  351. package/src/ws-file-ops/git.js +395 -42
  352. package/src/ws-file-ops/index.js +2 -0
  353. package/src/ws-file-ops/memory.js +137 -35
  354. package/src/ws-file-ops/open-nofollow.js +354 -0
  355. package/src/ws-file-ops/reader.js +571 -113
  356. package/src/ws-forwarding.js +349 -39
  357. package/src/ws-handler-context.js +88 -2
  358. package/src/ws-history.js +1010 -175
  359. package/src/ws-message-handlers.js +25 -1
  360. package/src/ws-permissions.js +307 -37
  361. package/src/ws-schemas.js +5 -0
  362. package/src/ws-server.js +885 -98
  363. package/sidecar/node_modules/.package-lock.json +0 -29
  364. package/sidecar/node_modules/ws/LICENSE +0 -20
  365. package/sidecar/node_modules/ws/README.md +0 -548
  366. package/sidecar/node_modules/ws/browser.js +0 -8
  367. package/sidecar/node_modules/ws/index.js +0 -22
  368. package/sidecar/node_modules/ws/lib/buffer-util.js +0 -131
  369. package/sidecar/node_modules/ws/lib/constants.js +0 -19
  370. package/sidecar/node_modules/ws/lib/event-target.js +0 -292
  371. package/sidecar/node_modules/ws/lib/extension.js +0 -203
  372. package/sidecar/node_modules/ws/lib/limiter.js +0 -55
  373. package/sidecar/node_modules/ws/lib/permessage-deflate.js +0 -528
  374. package/sidecar/node_modules/ws/lib/receiver.js +0 -706
  375. package/sidecar/node_modules/ws/lib/sender.js +0 -602
  376. package/sidecar/node_modules/ws/lib/stream.js +0 -161
  377. package/sidecar/node_modules/ws/lib/subprotocol.js +0 -62
  378. package/sidecar/node_modules/ws/lib/validation.js +0 -152
  379. package/sidecar/node_modules/ws/lib/websocket-server.js +0 -554
  380. package/sidecar/node_modules/ws/lib/websocket.js +0 -1393
  381. package/sidecar/node_modules/ws/package.json +0 -70
  382. package/sidecar/node_modules/ws/wrapper.mjs +0 -21
  383. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  384. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  385. package/src/dashboard-next/dist/index.html +0 -13
  386. package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
@@ -17,6 +17,7 @@ import {
17
17
  chmodSync,
18
18
  existsSync,
19
19
  lstatSync,
20
+ mkdirSync,
20
21
  readFileSync,
21
22
  realpathSync,
22
23
  renameSync,
@@ -24,11 +25,25 @@ import {
24
25
  unlinkSync,
25
26
  writeFileSync,
26
27
  } from 'node:fs'
27
- import { randomUUID } from 'node:crypto'
28
- import { homedir } from 'node:os'
28
+ import { createHash, randomUUID } from 'node:crypto'
29
29
  import { dirname, join } from 'node:path'
30
30
  import { lookup as dnsLookup } from 'node:dns/promises'
31
- import { fsyncForDurability, confirmRenameDurable } from './platform.js'
31
+ import { claudeGlobalConfigPath, parseClaudeConfigText } from './utils/claude-config-dir.js'
32
+ import { fsyncForDurability, confirmRenameDurable, stampWindowsAclStrict } from './platform.js'
33
+ import { createLogger } from './logger.js'
34
+ import {
35
+ MCP_SERVER_NAME_RE,
36
+ UNSAFE_MCP_KEYS,
37
+ containsMcpToolNamespaceSeparator,
38
+ isBlockedMetadataHost,
39
+ // #7030 — single-sourced from @chroxy/protocol/mcp-validation (the
40
+ // Zod-free subpath: this file has no other dependency on @chroxy/protocol
41
+ // and must not pull the Zod barrel into the ~/.claude.json parse path).
42
+ // Previously hand-duplicated in packages/dashboard/src/lib/mcp-server-
43
+ // validation.ts; #6986 and #7001 are what one-copy-drifts looks like.
44
+ } from '@chroxy/protocol/mcp-validation'
45
+
46
+ const log = createLogger('claude-config')
32
47
 
33
48
  /**
34
49
  * Defensive upper bound on the size of `~/.claude.json`. Today the file is
@@ -40,7 +55,7 @@ import { fsyncForDurability, confirmRenameDurable } from './platform.js'
40
55
  export const CLAUDE_CONFIG_MAX_BYTES = 10 * 1024 * 1024
41
56
 
42
57
  export function defaultClaudeConfigPath() {
43
- return process.env.CHROXY_CLAUDE_CONFIG || join(homedir(), '.claude.json')
58
+ return process.env.CHROXY_CLAUDE_CONFIG || claudeGlobalConfigPath()
44
59
  }
45
60
 
46
61
  /**
@@ -79,8 +94,12 @@ function coerceStringArray(value, { warnings, serverName }) {
79
94
  * explanation. `constructor` / `prototype` are plain own-property writes (no
80
95
  * setter) but are refused alongside it: a map key that shadows an object internal
81
96
  * is never a legitimate environment variable or HTTP header (#7001 review).
97
+ *
98
+ * #7030 — single-sourced as `UNSAFE_MCP_KEYS` from
99
+ * @chroxy/protocol/mcp-validation (imported above). Kept as a local alias so
100
+ * this stays a pure rename at every call site below.
82
101
  */
83
- const UNSAFE_MAP_KEYS = new Set(['__proto__', 'constructor', 'prototype'])
102
+ const UNSAFE_MAP_KEYS = UNSAFE_MCP_KEYS
84
103
 
85
104
  /**
86
105
  * Coerce an env object to string→string only. Pushes one warning per dropped
@@ -151,34 +170,12 @@ function coerceHeaders(value, { warnings, serverName }) {
151
170
  return headers
152
171
  }
153
172
 
154
- /**
155
- * True when a hostname (or a bare IP from dns.lookup) targets the cloud
156
- * metadata service / IPv4 link-local range — never a legitimate MCP server
157
- * (#6821, sharpest edge of #6834). Covers:
158
- * - 169.254.0.0/16 (link-local; the metadata endpoint 169.254.169.254
159
- * lives here). The WHATWG URL parser canonicalizes hex/decimal/octal
160
- * host tricks (0xa9fea9fe, 2852039166) to dotted-quad first, so a
161
- * literal-host check on the PARSED hostname catches those too.
162
- * - IPv4-mapped IPv6 forms of the same range: the URL parser serializes
163
- * them as hex groups (`::ffff:a9fe:xxxx`; a9fe == 169.254), dns.lookup
164
- * may return the dotted form (`::ffff:169.254.x.x`).
165
- * - fd00:ec2::254, the AWS IMDS IPv6 endpoint (URL-canonical compressed
166
- * form plus the expanded spelling).
167
- * Deliberately does NOT block loopback / RFC1918 generally — localhost MCP
168
- * servers are legitimate; the broader egress policy is #6834's scope.
169
- */
170
- export function isBlockedMetadataHost(hostname) {
171
- if (typeof hostname !== 'string' || hostname.length === 0) return false
172
- let h = hostname.toLowerCase()
173
- if (h.startsWith('[') && h.endsWith(']')) h = h.slice(1, -1)
174
- const v4 = h.match(/^(\d{1,3})\.(\d{1,3})\.\d{1,3}\.\d{1,3}$/)
175
- if (v4) return Number(v4[1]) === 169 && Number(v4[2]) === 254
176
- if (/^::ffff:a9fe:[0-9a-f]{1,4}$/.test(h)) return true
177
- const mapped = h.match(/^::ffff:(\d{1,3})\.(\d{1,3})\.\d{1,3}\.\d{1,3}$/)
178
- if (mapped) return Number(mapped[1]) === 169 && Number(mapped[2]) === 254
179
- if (h === 'fd00:ec2::254' || h === 'fd00:ec2:0:0:0:0:0:254') return true
180
- return false
181
- }
173
+ // #7030 — `isBlockedMetadataHost` is single-sourced from
174
+ // @chroxy/protocol/mcp-validation (imported above) and re-exported here so
175
+ // existing callers (`byok-mcp-client.js`, `byok-mcp-oauth.js`) are unaffected.
176
+ // See the shared module's doc comment for the full metadata-host rationale
177
+ // (169.254.0.0/16, IPv4-mapped IPv6 forms, the AWS IMDS IPv6 endpoint).
178
+ export { isBlockedMetadataHost }
182
179
 
183
180
  /**
184
181
  * Return a credential-stripped form of an MCP server url, safe to log or
@@ -511,10 +508,10 @@ export function loadClaudeMcpConfig(filePath = defaultClaudeConfigPath()) {
511
508
  const stat = statSync(filePath)
512
509
  if (stat.size > CLAUDE_CONFIG_MAX_BYTES) {
513
510
  const warning = `MCP config ${filePath} exceeds size cap (${stat.size} bytes > ${CLAUDE_CONFIG_MAX_BYTES} bytes); skipping load`
514
- console.warn(`[byok-mcp-config] ${warning}`)
511
+ log.warn(warning)
515
512
  return { servers: [], warnings: [warning], missing: false }
516
513
  }
517
- const raw = JSON.parse(readFileSync(filePath, 'utf8'))
514
+ const raw = parseClaudeConfigText(readFileSync(filePath, 'utf8'))
518
515
  return { ...parseClaudeMcpConfig(raw), missing: false }
519
516
  } catch (err) {
520
517
  return {
@@ -608,82 +605,288 @@ function resolveProjectBlock(raw, cwd) {
608
605
  }
609
606
 
610
607
  /**
611
- * Discover the CONFIGURED (not live-connected) MCP servers a Claude Code
612
- * session running in `cwd` would load. This is the honest fallback the
613
- * claude-tui provider uses (#6820): the interactive TUI communicates over a
614
- * PTY + hook payloads and exposes NO runtime MCP status, unlike the SDK/CLI
615
- * stream-json `system/init` event that carries live `mcp_servers` with real
616
- * connection status. So the TUI path can only report what the config DECLARES.
608
+ * #7939: closed vocabulary naming WHICH of the three config sources a
609
+ * discovered (or newly-added) MCP server came from. Threaded onto each spec
610
+ * `discoverMcpServerSpecs` returns and, from there, into the spawn-trust
611
+ * prompt payload (`requestMcpTrust`) — so a user approving a spawn can tell
612
+ * "my own machine-local config" from "a repository I just cloned" instead of
613
+ * every prompt looking identical regardless of provenance.
617
614
  *
618
- * Merges the three sources Claude Code itself reads, deduped by name (first
619
- * source wins on a name collision, matching read precedence):
620
- * 1. user/global scope — `mcpServers` at the root of `~/.claude.json`
621
- * 2. project scope — `projects[<realpath(cwd)>].mcpServers` in `~/.claude.json`
622
- * 3. project-local — `mcpServers` in `<cwd>/.mcp.json`
615
+ * Deliberately three fixed values, never a raw file path: a path is
616
+ * unbounded free-form text (and on the wire schema below is typed as a
617
+ * closed `z.enum`, not `z.string`), and the three values already say
618
+ * everything the prompt needs — "your machine", "this repo", or "your user
619
+ * profile".
623
620
  *
624
- * Never throws: each read is guarded and failures accumulate as warnings, so a
625
- * corrupt config can't take down session start.
621
+ * - LOCAL — `~/.claude.json` → `projects[<cwd>].mcpServers`.
622
+ * Claude Code's "Local" scope: private to this
623
+ * machine + cwd.
624
+ * - PROJECT_MCP_JSON — `<cwd>/.mcp.json`. Claude Code's "Project" scope:
625
+ * checked into the repo and shared with the team —
626
+ * REPO-CONTROLLED, so this is the value the trust
627
+ * prompt flags most visibly.
628
+ * - USER — `~/.claude.json` → root `mcpServers`. Claude Code's
629
+ * "User" scope: available across every project on
630
+ * this machine.
631
+ *
632
+ * Note the naming collision this deliberately avoids: the READ side's
633
+ * internal `source` strings below say "project config mcpServers" for the
634
+ * "Local" scope and "project .mcp.json mcpServers" for the "Project" scope
635
+ * (both use the word "project" for different things), while the WRITE side's
636
+ * `MCP_WRITE_SCOPES` calls the very same "Local" scope `'project'` (see
637
+ * `mcpWriteScopeToSource`). Neither internal vocabulary is fit to show a
638
+ * user — this enum is the one vocabulary both map onto.
639
+ */
640
+ export const MCP_SERVER_SOURCE = Object.freeze({
641
+ LOCAL: 'local',
642
+ PROJECT_MCP_JSON: 'project-mcp-json',
643
+ USER: 'user',
644
+ })
645
+
646
+ /** Ordered value list — for schema/enum construction and validation. */
647
+ export const MCP_SERVER_SOURCE_VALUES = Object.freeze(Object.values(MCP_SERVER_SOURCE))
648
+
649
+ /**
650
+ * Map an `addMcpServer` WRITE scope (`MCP_WRITE_SCOPES`: `'user' | 'project'`)
651
+ * onto the same `MCP_SERVER_SOURCE` vocabulary the READ side uses (#7939), so
652
+ * a spawn-trust prompt for a server the user is actively adding right now
653
+ * names its scope with the identical word a rediscovered one would carry
654
+ * after a restart.
655
+ *
656
+ * Write scope `'project'` targets `projects[<realpath(cwd)>].mcpServers`
657
+ * (see `prepareAddMcpServer` below) — the READ side's "Local" scope, NOT
658
+ * `.mcp.json` (which is not a writable scope at all; see the comment above
659
+ * `MCP_WRITE_SCOPES`). Write scope `'user'` (the default) targets the root
660
+ * `mcpServers` block — the READ side's "User" scope.
661
+ *
662
+ * @param {string} scope — an `MCP_WRITE_SCOPES` value
663
+ * @returns {string} an `MCP_SERVER_SOURCE` value
664
+ */
665
+ export function mcpWriteScopeToSource(scope) {
666
+ return scope === 'project' ? MCP_SERVER_SOURCE.LOCAL : MCP_SERVER_SOURCE.USER
667
+ }
668
+
669
+ /**
670
+ * #7028: the inverse of `mcpWriteScopeToSource` — map a READ-side
671
+ * `MCP_SERVER_SOURCE` onto the `MCP_WRITE_SCOPES` value that REMOVES a server
672
+ * defined there, for the `scope` field on each `mcp_servers` wire entry.
673
+ *
674
+ * The wire vocabulary is the write one on purpose: `remove_mcp_server` is
675
+ * scope-exact (a wrong scope reports `MCP_SERVER_NOT_FOUND`), and the field
676
+ * exists so a client can hand it straight back.
677
+ *
678
+ * - LOCAL → 'project' (`projects[<cwd>].mcpServers`)
679
+ * - USER → 'user' (root `mcpServers`)
680
+ * - PROJECT_MCP_JSON → undefined (`<cwd>/.mcp.json` is not a writable scope,
681
+ * so no remove could name it)
682
+ * - anything else → undefined (an unknown/absent source is never guessed)
683
+ *
684
+ * @param {string | undefined} source — an `MCP_SERVER_SOURCE` value, if known
685
+ * @returns {'user' | 'project' | undefined}
686
+ */
687
+ export function mcpSourceToWriteScope(source) {
688
+ if (source === MCP_SERVER_SOURCE.USER) return 'user'
689
+ if (source === MCP_SERVER_SOURCE.LOCAL) return 'project'
690
+ return undefined
691
+ }
692
+
693
+ /**
694
+ * Read the three MCP config sources Claude Code itself reads, in a single
695
+ * pass, in Claude Code's documented scope-precedence order (highest to
696
+ * lowest), per https://code.claude.com/docs/en/mcp, "Scope Hierarchy and
697
+ * Precedence" (read 2026-09-24): "When the same server is defined in more
698
+ * than one place, Claude Code connects to it once, using the definition
699
+ * from the highest-precedence source."
700
+ *
701
+ * 1. "Local" scope — `projects[<realpath(cwd)>].mcpServers` in
702
+ * `~/.claude.json`. Private to this cwd.
703
+ * 2. "Project" scope — `mcpServers` in `<cwd>/.mcp.json`, checked into the
704
+ * repo and shared with the team.
705
+ * 3. "User" scope — `mcpServers` at the root of `~/.claude.json`,
706
+ * available across every project on this machine.
707
+ *
708
+ * Both `discoverConfiguredMcpServers` (name-only, lenient, for claude-tui's
709
+ * display) and `discoverMcpServerSpecs` (full spec, exec-validated, for the
710
+ * BYOK spawn path) call this ONE function to enumerate sources, so the order
711
+ * a duplicated name resolves in can never drift between "what the user is
712
+ * told is configured" and "what actually spawns" — only the per-entry
713
+ * validation strictness differs between the two callers (#7112 review: a
714
+ * pre-#7112 version of this file had two independently-hand-rolled orderings
715
+ * that had drifted to be exact opposites of each other).
716
+ *
717
+ * Never throws: each read is guarded and a parse failure is reported via
718
+ * `warnings` on the returned object, so a corrupt config can't take down
719
+ * session start.
626
720
  *
627
721
  * @param {string} cwd — the session's working directory
628
- * @param {{ configPath?: string }} [opts]
629
- * @returns {{ servers: Array<{ name: string }>, warnings: string[] }}
722
+ * @param {string} configPath — resolved `~/.claude.json` path (or override)
723
+ * @returns {{ sources: Array<{ mcpServers: unknown, source: string }>, warnings: string[] }}
630
724
  */
631
- export function discoverConfiguredMcpServers(cwd, { configPath = defaultClaudeConfigPath() } = {}) {
725
+ function readMcpSourcesInPrecedenceOrder(cwd, configPath, { includeProjectFile = true } = {}) {
632
726
  const warnings = []
633
- const byName = new Map()
634
- const add = (names) => {
635
- for (const name of names) {
636
- if (!byName.has(name)) byName.set(name, { name })
637
- }
638
- }
727
+ const sources = []
639
728
 
640
729
  const readJson = (filePath, source) => {
641
730
  try {
642
731
  // statSync before readFileSync so a pathologically large file (see
643
- // CLAUDE_CONFIG_MAX_BYTES) doesn't block session start.
732
+ // CLAUDE_CONFIG_MAX_BYTES) doesn't block session start. statSync
733
+ // follows symlinks (as does readFileSync below), consistent with
734
+ // every other read in this file — see writeClaudeConfigAtomic's
735
+ // header comment for why WRITES are guarded but reads are not.
736
+ //
737
+ // isFile() guard: `.mcp.json` is repo-controlled, attacker-influenceable
738
+ // content (a cloned repo can make it a symlink to anything). A symlink
739
+ // to a FIFO or character device (e.g. `/dev/zero`) reports a `size` that
740
+ // is meaningless for this purpose — a FIFO with no writer hangs
741
+ // readFileSync indefinitely (before the trust gate even runs), and a
742
+ // device like `/dev/zero` has no real EOF, so the size cap above never
743
+ // triggers. Only a REGULAR file (following symlinks to their target,
744
+ // same as the size check) is ever read. Mirrors writeClaudeConfigAtomic's
745
+ // `target.isFile()` check on the write side.
644
746
  const stat = statSync(filePath)
747
+ if (!stat.isFile()) {
748
+ warnings.push(`MCP config ${filePath} is not a regular file; skipping load`)
749
+ return null
750
+ }
645
751
  if (stat.size > CLAUDE_CONFIG_MAX_BYTES) {
646
752
  warnings.push(
647
753
  `MCP config ${filePath} exceeds size cap (${stat.size} bytes > ${CLAUDE_CONFIG_MAX_BYTES} bytes); skipping load`,
648
754
  )
649
755
  return null
650
756
  }
651
- return JSON.parse(readFileSync(filePath, 'utf8'))
757
+ return parseClaudeConfigText(readFileSync(filePath, 'utf8'))
652
758
  } catch (err) {
653
- warnings.push(`${source}: failed to read ${filePath}: ${err?.message || String(err)}`)
759
+ warnings.push(`Failed to parse MCP config ${filePath} (${source}): ${err?.message || String(err)}`)
654
760
  return null
655
761
  }
656
762
  }
657
763
 
658
- // 1 + 2 — ~/.claude.json global root + project-scoped block.
764
+ let userRaw = null
659
765
  if (configPath && existsSync(configPath)) {
660
- const raw = readJson(configPath, 'user config')
661
- if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
662
- add(collectConfiguredNames(raw.mcpServers, { warnings, source: 'user config mcpServers' }))
663
- const projectBlock = resolveProjectBlock(raw, cwd)
664
- if (projectBlock && typeof projectBlock === 'object' && !Array.isArray(projectBlock)) {
665
- add(collectConfiguredNames(projectBlock.mcpServers, {
666
- warnings,
667
- source: 'project config mcpServers',
668
- }))
669
- }
766
+ userRaw = readJson(configPath, 'user config')
767
+ if (userRaw != null && (typeof userRaw !== 'object' || Array.isArray(userRaw))) {
768
+ userRaw = null
769
+ }
770
+ }
771
+
772
+ // 1 — "Local" scope (highest precedence): projects[<realpath(cwd)>].mcpServers.
773
+ if (userRaw) {
774
+ const projectBlock = resolveProjectBlock(userRaw, cwd)
775
+ if (projectBlock && typeof projectBlock === 'object' && !Array.isArray(projectBlock)) {
776
+ sources.push({
777
+ mcpServers: projectBlock.mcpServers,
778
+ source: 'project config mcpServers',
779
+ sourceKind: MCP_SERVER_SOURCE.LOCAL,
780
+ })
670
781
  }
671
782
  }
672
783
 
673
- // 3 — <cwd>/.mcp.json project-local.
674
- if (cwd) {
784
+ // 2 — "Project" scope: <cwd>/.mcp.json, checked into the repo. cwd may not
785
+ // exist (removed tmp dir, stale worktree) — join+existsSync just reports
786
+ // false rather than throwing.
787
+ if (cwd && includeProjectFile) {
675
788
  const mcpJsonPath = join(cwd, '.mcp.json')
676
789
  if (existsSync(mcpJsonPath)) {
677
790
  const raw = readJson(mcpJsonPath, 'project .mcp.json')
678
791
  if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
679
- add(collectConfiguredNames(raw.mcpServers, {
680
- warnings,
792
+ sources.push({
793
+ mcpServers: raw.mcpServers,
681
794
  source: 'project .mcp.json mcpServers',
682
- }))
795
+ sourceKind: MCP_SERVER_SOURCE.PROJECT_MCP_JSON,
796
+ })
683
797
  }
684
798
  }
685
799
  }
686
800
 
801
+ // 3 — "User" scope (lowest precedence): root mcpServers in ~/.claude.json.
802
+ if (userRaw) {
803
+ sources.push({
804
+ mcpServers: userRaw.mcpServers,
805
+ source: 'user config mcpServers',
806
+ sourceKind: MCP_SERVER_SOURCE.USER,
807
+ })
808
+ }
809
+
810
+ return { sources, warnings }
811
+ }
812
+
813
+ /**
814
+ * Discover the CONFIGURED (not live-connected) MCP servers a Claude Code
815
+ * session running in `cwd` would load. This is the honest fallback the
816
+ * claude-tui provider uses (#6820): the interactive TUI communicates over a
817
+ * PTY + hook payloads and exposes NO runtime MCP status, unlike the SDK/CLI
818
+ * stream-json `system/init` event that carries live `mcp_servers` with real
819
+ * connection status. So the TUI path can only report what the config DECLARES.
820
+ *
821
+ * Merges the three sources `readMcpSourcesInPrecedenceOrder` enumerates,
822
+ * deduped by name (first source wins on a name collision — see that
823
+ * function for the precedence order and why it is shared with
824
+ * `discoverMcpServerSpecs`). Entry validation here is deliberately LENIENT
825
+ * (any object counts as "configured", even one `discoverMcpServerSpecs`
826
+ * would reject as unspawnable) because this path is display-only visibility,
827
+ * not a spawn decision.
828
+ *
829
+ * Never throws: each read is guarded and failures accumulate as warnings, so a
830
+ * corrupt config can't take down session start.
831
+ *
832
+ * `includeProjectFile: false` leaves out `<cwd>/.mcp.json`, for a session
833
+ * that does not load project-scope settings (claude-setting-sources.js), so
834
+ * the list shows only servers that session can actually load.
835
+ *
836
+ * @param {string} cwd — the session's working directory
837
+ * @param {{ configPath?: string, includeProjectFile?: boolean }} [opts]
838
+ * @returns {{ servers: Array<{ name: string }>, warnings: string[] }}
839
+ */
840
+ export function discoverConfiguredMcpServers(cwd, { configPath = defaultClaudeConfigPath(), includeProjectFile = true } = {}) {
841
+ const { sources, warnings } = readMcpSourcesInPrecedenceOrder(cwd, configPath, { includeProjectFile })
842
+ const byName = new Map()
843
+ for (const { mcpServers, source } of sources) {
844
+ for (const name of collectConfiguredNames(mcpServers, { warnings, source })) {
845
+ if (!byName.has(name)) byName.set(name, { name })
846
+ }
847
+ }
848
+ return { servers: [...byName.values()], warnings }
849
+ }
850
+
851
+ /**
852
+ * #7112: `discoverConfiguredMcpServers` above returns declared NAMES only —
853
+ * built for claude-tui's read-only display, lenient about entry shape (any
854
+ * object counts). The BYOK spawn path (`byok-session.js`) needs full,
855
+ * SPAWNABLE specs: the same exec-oriented validation `parseClaudeMcpConfig`
856
+ * applies (command/url/transport disambiguation, arg/env coercion), resolved
857
+ * across the SAME three config sources, via the SAME
858
+ * `readMcpSourcesInPrecedenceOrder` ordering `discoverConfiguredMcpServers`
859
+ * uses — so the two can never independently drift on WHICH source wins a
860
+ * name collision again.
861
+ *
862
+ * Never throws: each source is read defensively and a parse failure
863
+ * accumulates as a warning, so a corrupt config can't take down session
864
+ * start (mirrors `discoverConfiguredMcpServers` / `loadClaudeMcpConfig`).
865
+ *
866
+ * #7939: every returned spec also carries `source` (an `MCP_SERVER_SOURCE`
867
+ * value) naming which of the three scopes it was resolved from — threaded
868
+ * through to the spawn-trust prompt so an approval can tell "my own config"
869
+ * from "a repository I just cloned" apart. Attached here (not inside
870
+ * `parseClaudeMcpConfig`, which is scope-agnostic and reused by the write
871
+ * path) so the dedup-by-name loop below tags each winning spec with the
872
+ * SAME source its winning `sources` entry carries — a spec picked from the
873
+ * "Local" scope is never mislabeled "User" just because `parseClaudeMcpConfig`
874
+ * doesn't know about scopes.
875
+ *
876
+ * @param {string} cwd — the session's working directory
877
+ * @param {{ configPath?: string }} [opts]
878
+ * @returns {{ servers: Array<object>, warnings: string[] }}
879
+ */
880
+ export function discoverMcpServerSpecs(cwd, { configPath = defaultClaudeConfigPath() } = {}) {
881
+ const { sources, warnings } = readMcpSourcesInPrecedenceOrder(cwd, configPath)
882
+ const byName = new Map()
883
+ for (const { mcpServers, sourceKind } of sources) {
884
+ const parsed = parseClaudeMcpConfig({ mcpServers })
885
+ for (const spec of parsed.servers) {
886
+ if (!byName.has(spec.name)) byName.set(spec.name, { ...spec, source: sourceKind })
887
+ }
888
+ warnings.push(...parsed.warnings)
889
+ }
687
890
  return { servers: [...byName.values()], warnings }
688
891
  }
689
892
 
@@ -727,8 +930,11 @@ export function discoverConfiguredMcpServers(cwd, { configPath = defaultClaudeCo
727
930
  * no `.` or `/` (so a name can never read as a path or traverse), no uppercase
728
931
  * (so two names can't collide case-insensitively), and no whitespace/control
729
932
  * characters (so a name can't be visually spoofed in the picker).
933
+ *
934
+ * #7030 — single-sourced from @chroxy/protocol/mcp-validation (imported
935
+ * above); re-exported here since nothing else in this file changes shape.
730
936
  */
731
- export const MCP_SERVER_NAME_RE = /^[a-z][a-z0-9_-]{0,63}$/
937
+ export { MCP_SERVER_NAME_RE }
732
938
 
733
939
  /**
734
940
  * Names that must never be used as an object key we assign into, regardless of
@@ -736,8 +942,12 @@ export const MCP_SERVER_NAME_RE = /^[a-z][a-z0-9_-]{0,63}$/
736
942
  * already refused by MCP_SERVER_NAME_RE (leading `_`), but `constructor` and
737
943
  * `prototype` are pure lowercase letters and WOULD pass it, so they are refused
738
944
  * explicitly here. Also applied on the removal path, which uses a laxer charset.
945
+ *
946
+ * #7030 — single-sourced as `UNSAFE_MCP_KEYS` (same Set as the env/headers
947
+ * check above); kept as a local alias so the name-specific call sites below
948
+ * read unchanged.
739
949
  */
740
- const UNSAFE_MCP_SERVER_NAMES = new Set(['__proto__', 'constructor', 'prototype'])
950
+ const UNSAFE_MCP_SERVER_NAMES = UNSAFE_MCP_KEYS
741
951
 
742
952
  /**
743
953
  * Upper bound on a removable name. Removal accepts a much laxer charset than
@@ -774,7 +984,7 @@ export function validateNewMcpServerName(name) {
774
984
  '(letters, digits, dash, underscore; must start with a letter, max 64 chars)',
775
985
  }
776
986
  }
777
- if (name.includes('__')) {
987
+ if (containsMcpToolNamespaceSeparator(name)) {
778
988
  return {
779
989
  ok: false,
780
990
  error:
@@ -872,14 +1082,16 @@ export function normalizeMcpServerConfig(name, config) {
872
1082
  * not an error — it is the first-write case and yields an empty object.
873
1083
  *
874
1084
  * @param {string} filePath
875
- * @returns {{ ok: true, raw: object, mode: number|null, existed: boolean } | { ok: false, error: string }}
1085
+ * @returns {{ ok: true, raw: object, mode: number|null, existed: boolean, hash: string|null } | { ok: false, error: string }}
1086
+ * `hash` is the sha256 of the bytes parsed (null for a missing file): the snapshot
1087
+ * identity `writeClaudeConfigAtomic`'s `expect` compares against (#8983).
876
1088
  */
877
1089
  export function readClaudeConfigForMutation(filePath) {
878
1090
  if (!filePath) return { ok: false, error: 'No Claude config path resolved' }
879
1091
  if (!existsSync(filePath)) {
880
1092
  // First write — we create the file. `mode: null` tells the writer to use a
881
1093
  // fresh-file default (0600) rather than preserving anything.
882
- return { ok: true, raw: {}, mode: null, existed: false }
1094
+ return { ok: true, raw: {}, mode: null, existed: false, hash: null }
883
1095
  }
884
1096
  let stat
885
1097
  try {
@@ -894,26 +1106,32 @@ export function readClaudeConfigForMutation(filePath) {
894
1106
  }
895
1107
  }
896
1108
  let text
1109
+ let hash
897
1110
  try {
898
- text = readFileSync(filePath, 'utf8')
1111
+ // Read BYTES and hash those, so the pre-rename re-check (which also hashes
1112
+ // bytes) compares like with like even for a file that is not valid UTF-8.
1113
+ const bytes = readFileSync(filePath)
1114
+ hash = hashConfigBytes(bytes)
1115
+ text = bytes.toString('utf8')
899
1116
  } catch (err) {
900
1117
  return { ok: false, error: `Cannot read ${filePath}: ${err?.message || String(err)}` }
901
1118
  }
902
1119
  let raw
903
1120
  try {
904
- raw = JSON.parse(text)
1121
+ raw = parseClaudeConfigText(text)
905
1122
  } catch {
906
1123
  // The parser's message can quote surrounding bytes (which may include a
907
1124
  // token from elsewhere in the file), so it is deliberately NOT echoed.
908
1125
  return {
909
1126
  ok: false,
1127
+ invalidJson: true,
910
1128
  error: `Config ${filePath} is not valid JSON; refusing to overwrite it. Fix or move the file, then retry.`,
911
1129
  }
912
1130
  }
913
1131
  if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
914
1132
  return { ok: false, error: `Config ${filePath} root must be a JSON object; refusing to overwrite it` }
915
1133
  }
916
- return { ok: true, raw, mode: stat.mode & 0o777, existed: true }
1134
+ return { ok: true, raw, mode: stat.mode & 0o777, existed: true, hash }
917
1135
  }
918
1136
 
919
1137
  /**
@@ -1072,10 +1290,34 @@ export function describeConfigModeSecretWarning({ filePath, mode, entry } = {})
1072
1290
  *
1073
1291
  * @param {string} filePath
1074
1292
  * @param {object} value — the full config object to serialize
1075
- * @param {{ mode: number|null }} opts — `null` mode = new file, use 0600
1293
+ * @param {{ mode: number|null, expect?: { path?: string, existed: boolean, hash: string|null, mode?: number|null }, _fsync?: Function }} opts — `null` mode = new file, use 0600.
1294
+ * `expect` (#8983) is the snapshot the value was merged from: when given, the destination is re-read just
1295
+ * before the rename and a `ClaudeConfigConflictError` is thrown (temp discarded, file untouched) if it differs.
1296
+ * Production code does not pass it directly — it goes through `updateClaudeConfig`, which owns the retry loop.
1297
+ * `_fsync` is a TEST-ONLY seam (#7070): `(target, { isDir }) => void`, the same
1298
+ * shape as `confirmRenameDurable`'s `fsync`, defaulting to the real
1299
+ * `fsyncForDurability`. BOTH the temp-file fsync and the post-rename directory
1300
+ * fsync (made by `confirmRenameDurable`) go through it, so a test can pin
1301
+ * their order and fail the directory one without a real disk fault. Production
1302
+ * callers never pass it.
1076
1303
  * @returns {{ durabilityUnconfirmed: string | null }}
1077
1304
  */
1078
- export function writeClaudeConfigAtomic(filePath, value, { mode }) {
1305
+ export function writeClaudeConfigAtomic(
1306
+ filePath,
1307
+ value,
1308
+ {
1309
+ mode,
1310
+ expect,
1311
+ _fsync = fsyncForDurability,
1312
+ _rename = renameSync,
1313
+ _isWindowsOverride,
1314
+ _sleep = sleepSyncMs,
1315
+ // TEST seam: the exec behind the DEFAULT fail-closed stamper, so a test reaches the
1316
+ // real `stampWindowsAclStrict` (rather than injecting `_stampAcl`) with tools mocked.
1317
+ _aclExec,
1318
+ _stampAcl = (target) => stampWindowsAclStrict(target, { _exec: _aclExec, _onWindows: true }),
1319
+ },
1320
+ ) {
1079
1321
  const resolved = resolveClaudeConfigWritePath(filePath)
1080
1322
  if (!resolved.ok) throw new Error(resolved.error)
1081
1323
  // Everything below targets the RESOLVED path: the sidecar has to live in the
@@ -1083,22 +1325,54 @@ export function writeClaudeConfigAtomic(filePath, value, { mode }) {
1083
1325
  // dotfiles target is frequently on a different one from $HOME), and the
1084
1326
  // dir-fsync has to be the target's directory too.
1085
1327
  const destPath = resolved.path
1328
+ const onWindows = _isWindowsOverride ?? process.platform === 'win32'
1329
+ // #8983: a snapshot taken against a different resolved path (the link was
1330
+ // retargeted since the read) is stale by definition — do not even write the temp.
1331
+ if (expect && expect.path !== undefined && expect.path !== destPath) {
1332
+ throw new ClaudeConfigConflictError(destPath, 'its symlink target changed since it was read')
1333
+ }
1086
1334
  const payload = `${JSON.stringify(value, null, 2)}\n`
1087
1335
  const targetMode = mode === null || mode === undefined ? 0o600 : mode
1088
1336
  // Per-call random suffix, NOT process.pid: concurrent sessions in one daemon
1089
1337
  // share a pid and would race for the same sidecar path (#3922).
1090
1338
  const tmpPath = `${destPath}.chroxy.${randomUUID()}.tmp`
1339
+ // Cleans up on a THROWN error. A process kill (SIGKILL / OOM / power loss) between
1340
+ // the temp write and the rename can still leave a `.chroxy.<uuid>.tmp` sidecar
1341
+ // beside the config: the destination is never truncated, but the orphan is not
1342
+ // reaped here. Failures other than "already gone" are logged, not swallowed.
1343
+ const discardTmp = () => {
1344
+ try {
1345
+ unlinkSync(tmpPath)
1346
+ } catch (err) {
1347
+ if (err?.code !== 'ENOENT') log.warn(`Failed to remove orphaned ${tmpPath}: ${err?.message || err}`)
1348
+ }
1349
+ }
1091
1350
  try {
1092
1351
  // `mode` is only honoured on create, and umask can strip bits from it — so
1093
1352
  // restate the exact mode afterwards. The intermediate mode can only ever be
1094
1353
  // TIGHTER than the target (umask removes bits, never adds), so there is no
1095
1354
  // window in which the temp file is more permissive than the destination
1096
1355
  // already was.
1097
- writeFileSync(tmpPath, payload, { mode: targetMode })
1098
- chmodSync(tmpPath, targetMode)
1099
- fsyncForDurability(tmpPath)
1356
+ if (onWindows) {
1357
+ // Numeric mode bits are meaningless on NTFS, and a fresh temp would inherit the
1358
+ // parent directory's (possibly broader) ACL. Create it EMPTY, stamp the
1359
+ // owner-only DACL, THEN write — so credentials in the document (env API keys,
1360
+ // OAuth material) never exist in a file readable beyond the owner. The DACL
1361
+ // survives the same-directory rename (same as `writeFileRestricted`). The
1362
+ // stamp is FAIL-CLOSED here (unlike writeFileRestricted's best-effort): a
1363
+ // failed stamp throws, the temp is discarded and the destination — possibly
1364
+ // already restricted — is left untouched rather than replaced by a file
1365
+ // carrying the parent's inherited ACL.
1366
+ writeFileSync(tmpPath, '')
1367
+ _stampAcl(tmpPath)
1368
+ writeFileSync(tmpPath, payload)
1369
+ } else {
1370
+ writeFileSync(tmpPath, payload, { mode: targetMode })
1371
+ chmodSync(tmpPath, targetMode)
1372
+ }
1373
+ _fsync(tmpPath, { isDir: false })
1100
1374
  } catch (err) {
1101
- try { unlinkSync(tmpPath) } catch { /* nothing to clean up */ }
1375
+ discardTmp()
1102
1376
  throw err
1103
1377
  }
1104
1378
  // A failing rename (EXDEV, FS quota, ACL) would otherwise leave the sidecar
@@ -1106,11 +1380,36 @@ export function writeClaudeConfigAtomic(filePath, value, { mode }) {
1106
1380
  // any `env` / `headers` the caller just supplied. Unlink it and re-throw the
1107
1381
  // ORIGINAL rename error, not a cleanup-side ENOENT. Same shape as the #4463 fix
1108
1382
  // in byok-mcp-trust.js `recordTrust`.
1109
- try {
1110
- renameSync(tmpPath, destPath)
1111
- } catch (err) {
1112
- try { unlinkSync(tmpPath) } catch { /* may already be gone */ }
1113
- throw err
1383
+ //
1384
+ // #8983 — OPTIMISTIC conflict detection (not an atomic compare-and-swap). `claude` (and a second daemon) take no lock of
1385
+ // ours, so the only way to avoid publishing a merge computed from a stale
1386
+ // snapshot is to re-read the destination IMMEDIATELY before the rename and
1387
+ // refuse if it is no longer what the merge started from. The check sits after
1388
+ // the (slow) temp write + fsync so what remains between it and the rename is a
1389
+ // pair of back-to-back syscalls. There is no cross-process lock and POSIX has no
1390
+ // "rename if unchanged", so a write landing in that residual window can still be
1391
+ // lost: this narrows the race to microseconds, it does not eliminate it.
1392
+ for (let attempt = 1; ; attempt++) {
1393
+ try {
1394
+ claudeConfigTestHooks.beforeVerify?.({ path: destPath })
1395
+ // Re-resolve the ORIGINAL path on every attempt (also after a Windows
1396
+ // backoff): a link retargeted, or a regular file swapped for a link with
1397
+ // identical bytes, would otherwise pass the content hash and be clobbered.
1398
+ verifyDestinationUnchanged(filePath, resolved)
1399
+ if (expect) verifyUnchanged(destPath, expect)
1400
+ _rename(tmpPath, destPath)
1401
+ break
1402
+ } catch (err) {
1403
+ // Windows: claude/AV/Windows Search can hold the destination open without
1404
+ // FILE_SHARE_DELETE, failing the replace with a transient EPERM/EACCES/
1405
+ // EBUSY/EEXIST. Bounded retry; the check runs again on the next pass.
1406
+ if (onWindows && err && WIN_RENAME_RETRY_CODES.has(err.code) && attempt < WIN_RENAME_ATTEMPTS) {
1407
+ _sleep(WIN_RENAME_BACKOFF_MS * attempt)
1408
+ continue
1409
+ }
1410
+ discardTmp()
1411
+ throw err
1412
+ }
1114
1413
  }
1115
1414
  // Make the rename itself durable, not just the bytes it points at.
1116
1415
  //
@@ -1122,7 +1421,159 @@ export function writeClaudeConfigAtomic(filePath, value, { mode }) {
1122
1421
  // trust write that had actually landed; the MCP add/remove paths reported a
1123
1422
  // failure for a config change that was on disk. Shared verdict now — report,
1124
1423
  // never throw — via the one implementation in platform.js.
1125
- return confirmRenameDurable(destPath, { durable: true })
1424
+ return confirmRenameDurable(destPath, { durable: true, fsync: _fsync })
1425
+ }
1426
+
1427
+ const WIN_RENAME_RETRY_CODES = new Set(['EPERM', 'EACCES', 'EBUSY', 'EEXIST'])
1428
+ const WIN_RENAME_ATTEMPTS = 4
1429
+ const WIN_RENAME_BACKOFF_MS = 25
1430
+
1431
+ function sleepSyncMs(ms) {
1432
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms)
1433
+ }
1434
+
1435
+ /** sha256 (hex) of a config file's raw bytes — the snapshot identity. */
1436
+ function hashConfigBytes(bytes) {
1437
+ return createHash('sha256').update(bytes).digest('hex')
1438
+ }
1439
+
1440
+ /**
1441
+ * TEST-ONLY seam (#8983): `beforeVerify({ path })` runs inside the writer after
1442
+ * the temp file is durable and just before the conflict check, i.e. at
1443
+ * the exact point a concurrent writer's update lands in the bug. A real caller
1444
+ * (register/unregister, trust pre-write, MCP add/remove) reaches the writer only
1445
+ * through `updateClaudeConfig`, so a test sets this to drive THAT caller end to
1446
+ * end rather than testing the helper in isolation. Production leaves it null.
1447
+ */
1448
+ export const claudeConfigTestHooks = { beforeVerify: null }
1449
+
1450
+ /**
1451
+ * Thrown when the destination no longer matches the snapshot a merge was
1452
+ * computed from. `updateClaudeConfig` retries on it; it escapes only once the
1453
+ * retry budget is spent (then as `exhausted: true`).
1454
+ */
1455
+ export class ClaudeConfigConflictError extends Error {
1456
+ constructor(path, why, { exhausted = false } = {}) {
1457
+ super(exhausted
1458
+ ? `${path} kept changing underneath the update (${why}); gave up after retrying so another writer's changes are not overwritten. Nothing was written.`
1459
+ : `${path} changed since it was read (${why})`)
1460
+ this.name = 'ClaudeConfigConflictError'
1461
+ this.code = 'CLAUDE_CONFIG_CONFLICT'
1462
+ this.exhausted = exhausted
1463
+ }
1464
+ }
1465
+
1466
+ // A regular file swapped for a symlink (even to identical bytes) changes the RESOLVED
1467
+ // path (the link's target), so the path comparison below is what catches it; a
1468
+ // separate regular-vs-symlink flag was tried and mutation-tested as redundant.
1469
+ function verifyDestinationUnchanged(filePath, initial) {
1470
+ const now = resolveClaudeConfigWritePath(filePath)
1471
+ if (!now.ok) throw new ClaudeConfigConflictError(filePath, `its symlink state changed and is now refused (${now.error})`)
1472
+ if (now.path !== initial.path) throw new ClaudeConfigConflictError(filePath, 'its symlink target changed since it was read')
1473
+ }
1474
+
1475
+ function verifyUnchanged(destPath, expect) {
1476
+ let bytes = null
1477
+ try {
1478
+ bytes = readFileSync(destPath)
1479
+ } catch (err) {
1480
+ if (err?.code !== 'ENOENT') {
1481
+ // Cannot prove it is unchanged — treat as a conflict, never as "fine".
1482
+ throw new ClaudeConfigConflictError(destPath, `re-read failed: ${err?.code || err?.message}`)
1483
+ }
1484
+ }
1485
+ if (bytes === null) {
1486
+ if (expect.existed) throw new ClaudeConfigConflictError(destPath, 'it was removed')
1487
+ return
1488
+ }
1489
+ if (!expect.existed) throw new ClaudeConfigConflictError(destPath, 'it was created by another writer')
1490
+ if (hashConfigBytes(bytes) !== expect.hash) throw new ClaudeConfigConflictError(destPath, 'its content changed')
1491
+ // A permission change with identical bytes (e.g. a concurrent `chmod 600`) is a
1492
+ // conflict too: the temp carries the snapshot's mode, and publishing it would
1493
+ // silently undo the tightening. The re-merge picks up the CURRENT mode.
1494
+ if (expect.mode !== null && expect.mode !== undefined) {
1495
+ let current = null
1496
+ try { current = statSync(destPath).mode & 0o777 } catch { /* raced away: the next attempt sorts it out */ }
1497
+ if (current !== expect.mode) throw new ClaudeConfigConflictError(destPath, 'its permissions changed')
1498
+ }
1499
+ }
1500
+
1501
+ const TORN_READ_PAUSE_MS = 20
1502
+ const CONFLICT_JITTER_MAX_MS = 8
1503
+
1504
+ /** Retry budget for `updateClaudeConfig` (#8983). Bounded: a file under constant churn must fail loudly, not spin. */
1505
+ export const CLAUDE_CONFIG_MAX_ATTEMPTS = 5
1506
+
1507
+ /**
1508
+ * #8983 — THE read-merge-write for claude's config files (`~/.claude.json`,
1509
+ * `<claude config dir>/settings.json`). Every site that mutates one of them goes
1510
+ * through here: the permission-hook register/unregister, the workspace-trust
1511
+ * pre-write, and MCP add/remove. A second, hand-rolled read-modify-write over
1512
+ * these files is the lost-update bug this exists to prevent (#7262 is the
1513
+ * shape: a guard wired to only some callers).
1514
+ *
1515
+ * Per attempt: resolve the (symlink-aware) destination → read + hash a snapshot
1516
+ * → run `mutate` on a FRESHLY parsed tree → write the temp file → re-read the
1517
+ * destination and refuse to rename if it is not the snapshot any more → rename.
1518
+ * A mismatch discards the temp file and re-runs the WHOLE merge on the new
1519
+ * content, up to `maxAttempts`; running out throws a loud
1520
+ * `ClaudeConfigConflictError` (`exhausted: true`) and leaves the file untouched.
1521
+ *
1522
+ * @param {string} filePath
1523
+ * @param {(raw: object, info: { existed: boolean, mode: number|null, attempt: number }) =>
1524
+ * ({ write?: boolean, value?: object, result?: any } | void)} mutate — mutate `raw` in
1525
+ * place (or return `value`); return `{ write: false, result }` to skip the write
1526
+ * (a no-op must not rewrite a file nor race anyone for nothing). Must be
1527
+ * synchronous and side-effect free apart from `raw`: it re-runs on conflict.
1528
+ * @param {{ maxAttempts?: number, createDir?: boolean, _fsync?: Function,
1529
+ * _rename?: Function, _isWindowsOverride?: boolean, _sleep?: Function }} [opts]
1530
+ * `createDir`: when the file does not exist yet, create its directory (0700) first.
1531
+ * @returns {{ ok: true, wrote: boolean, result: any, attempts: number,
1532
+ * durabilityUnconfirmed: string|null, path: string|null } | { ok: false, error: string }}
1533
+ * `ok: false` is a read/parse refusal (fail-closed, see `readClaudeConfigForMutation`).
1534
+ * A refused symlink, an I/O failure, or exhausted retries THROW.
1535
+ */
1536
+ export function updateClaudeConfig(filePath, mutate, opts = {}) {
1537
+ const { maxAttempts = CLAUDE_CONFIG_MAX_ATTEMPTS, createDir = false, ...writerOpts } = opts
1538
+ const sleep = writerOpts._sleep ?? sleepSyncMs
1539
+ let tornReadRetried = false
1540
+ let lastWhy = 'unknown'
1541
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
1542
+ const resolved = resolveClaudeConfigWritePath(filePath)
1543
+ if (!resolved.ok) throw new Error(resolved.error)
1544
+ let read = readClaudeConfigForMutation(resolved.path)
1545
+ if (!read.ok && read.invalidJson && !tornReadRetried) {
1546
+ // A writer that truncates then writes (rather than rename-replaces) can be
1547
+ // caught mid-write: the file parses as garbage for a moment. Re-read ONCE
1548
+ // after a short pause before treating it as genuinely invalid; if it still
1549
+ // is, fail closed exactly as before.
1550
+ tornReadRetried = true
1551
+ sleep(TORN_READ_PAUSE_MS)
1552
+ read = readClaudeConfigForMutation(resolved.path)
1553
+ }
1554
+ if (!read.ok) return read
1555
+ const out = mutate(read.raw, { existed: read.existed, mode: read.mode, attempt }) ?? {}
1556
+ if (out.write === false) {
1557
+ return { ok: true, wrote: false, result: out.result, attempts: attempt, durabilityUnconfirmed: null, path: null }
1558
+ }
1559
+ if (createDir && !read.existed) mkdirSync(dirname(resolved.path), { recursive: true, mode: 0o700 })
1560
+ try {
1561
+ const { durabilityUnconfirmed } = writeClaudeConfigAtomic(filePath, out.value ?? read.raw, {
1562
+ mode: read.mode,
1563
+ expect: { path: resolved.path, existed: read.existed, hash: read.hash, mode: read.mode },
1564
+ ...writerOpts,
1565
+ })
1566
+ return { ok: true, wrote: true, result: out.result, attempts: attempt, durabilityUnconfirmed, path: resolved.path }
1567
+ } catch (err) {
1568
+ if (!(err instanceof ClaudeConfigConflictError)) throw err
1569
+ lastWhy = err.message
1570
+ log.warn(`${lastWhy}; re-reading and re-merging (attempt ${attempt}/${maxAttempts})`)
1571
+ // Jittered pause so two contending writers do not retry in lockstep.
1572
+ if (attempt < maxAttempts) sleep(1 + Math.floor(Math.random() * CONFLICT_JITTER_MAX_MS))
1573
+ }
1574
+ }
1575
+ log.error(`config update of ${filePath} abandoned after ${maxAttempts} attempts: ${lastWhy}`)
1576
+ throw new ClaudeConfigConflictError(filePath, lastWhy, { exhausted: true })
1126
1577
  }
1127
1578
 
1128
1579
  /**
@@ -1191,14 +1642,53 @@ function prepareAddMcpServer({ name, config, scope = 'user', cwd, configPath = d
1191
1642
  const normalized = normalizeMcpServerConfig(validName.name, config)
1192
1643
  if (!normalized.ok) return { ok: false, error: normalized.error }
1193
1644
 
1194
- // Read-modify-write, synchronously and with no `await` in between, so the
1195
- // window in which a concurrent `claude` CLI edit could be lost is the syscall
1196
- // span rather than an event-loop turn. (A cross-process lock is not available
1197
- // — `claude` takes none — so narrowing the window is the honest ceiling.)
1645
+ const shadowed = findShadowingMcpScope({ name: validName.name, scope, cwd, configPath })
1646
+ if (shadowed) {
1647
+ return {
1648
+ ok: false,
1649
+ code: 'EXISTS',
1650
+ error: `An MCP server named '${validName.name}' is already defined in ${MCP_SOURCE_LABELS[shadowed]}, which takes precedence over ${MCP_SOURCE_LABELS[mcpWriteScopeToSource(scope)]}, so a server added here would never be used. ${shadowed === MCP_SERVER_SOURCE.PROJECT_MCP_JSON ? 'Chroxy cannot edit that file, so remove or rename the entry there by hand' : 'Remove or rename it there'}, or use a different name.`,
1651
+ }
1652
+ }
1653
+
1654
+ // DRY-RUN read (the plan path). The COMMIT re-runs `locateAddTarget` on a fresh
1655
+ // read inside `updateClaudeConfig`, which owns the conflict detection (#8983).
1198
1656
  const read = readClaudeConfigForMutation(configPath)
1199
1657
  if (!read.ok) return { ok: false, error: read.error }
1200
- const raw = read.raw
1658
+ const located = locateAddTarget(read.raw, { scope, cwd, validName, normalized })
1659
+ if (!located.ok) return located
1660
+ return { ...located, mode: read.mode, scope, name: validName.name, configPath }
1661
+ }
1662
+
1663
+ /** Human-readable scope names for add-time errors (#7962). */
1664
+ const MCP_SOURCE_LABELS = Object.freeze({
1665
+ [MCP_SERVER_SOURCE.LOCAL]: 'the local scope of this project',
1666
+ [MCP_SERVER_SOURCE.PROJECT_MCP_JSON]: 'the .mcp.json file in this repository',
1667
+ [MCP_SERVER_SOURCE.USER]: 'user scope',
1668
+ })
1669
+
1670
+ /** Precedence rank, highest first — the same order `readMcpSourcesInPrecedenceOrder` enumerates. */
1671
+ const MCP_SOURCE_RANK = Object.freeze({
1672
+ [MCP_SERVER_SOURCE.LOCAL]: 0,
1673
+ [MCP_SERVER_SOURCE.PROJECT_MCP_JSON]: 1,
1674
+ [MCP_SERVER_SOURCE.USER]: 2,
1675
+ })
1201
1676
 
1677
+ /**
1678
+ * #7962: the scope a server NAMED `name` currently spawns from, when that scope
1679
+ * outranks the write target. Resolved through `discoverMcpServerSpecs` (the spawn
1680
+ * path's own resolver) so "what wins" cannot drift from "what spawns". Returns an
1681
+ * `MCP_SERVER_SOURCE` value, or null when nothing outranks the target.
1682
+ */
1683
+ function findShadowingMcpScope({ name, scope, cwd, configPath }) {
1684
+ const winner = discoverMcpServerSpecs(cwd, { configPath }).servers.find((s) => s.name === name)
1685
+ if (!winner) return null
1686
+ const target = mcpWriteScopeToSource(scope)
1687
+ return MCP_SOURCE_RANK[winner.source] < MCP_SOURCE_RANK[target] ? winner.source : null
1688
+ }
1689
+
1690
+ /** Locate (creating if absent) the block an add targets in `raw`; refuse a duplicate / malformed shape. */
1691
+ function locateAddTarget(raw, { scope, cwd, validName, normalized }) {
1202
1692
  let block
1203
1693
  if (scope === 'user') {
1204
1694
  if (raw.mcpServers != null && (typeof raw.mcpServers !== 'object' || Array.isArray(raw.mcpServers))) {
@@ -1234,7 +1724,7 @@ function prepareAddMcpServer({ name, config, scope = 'user', cwd, configPath = d
1234
1724
  error: `An MCP server named '${validName.name}' already exists in ${scope} scope. Remove it first to replace it.`,
1235
1725
  }
1236
1726
  }
1237
- return { ok: true, raw, block, mode: read.mode, entry: normalized.entry, scope, name: validName.name, configPath }
1727
+ return { ok: true, raw, block, entry: normalized.entry }
1238
1728
  }
1239
1729
 
1240
1730
  /**
@@ -1277,14 +1767,28 @@ export function planAddMcpServerToConfig(opts = {}) {
1277
1767
  export function addMcpServerToConfig(opts = {}) {
1278
1768
  const prepared = prepareAddMcpServer(opts)
1279
1769
  if (!prepared.ok) return prepared.code ? { ok: false, error: prepared.error, code: prepared.code } : { ok: false, error: prepared.error }
1280
- prepared.block[prepared.name] = prepared.entry
1281
- writeClaudeConfigAtomic(prepared.configPath, prepared.raw, { mode: prepared.mode })
1770
+ // The commit re-locates the target on a FRESH read inside the conflict-detection
1771
+ // loop (#8983): the plan's tree is advisory and may be stale by now.
1772
+ const { scope = 'user', cwd } = opts
1773
+ const validName = { name: prepared.name }
1774
+ const normalized = { entry: prepared.entry }
1775
+ const updated = updateClaudeConfig(prepared.configPath, (raw, info) => {
1776
+ const located = locateAddTarget(raw, { scope, cwd, validName, normalized })
1777
+ if (!located.ok) return { write: false, result: located }
1778
+ located.block[prepared.name] = prepared.entry
1779
+ return { result: { mode: info.mode } }
1780
+ })
1781
+ if (!updated.ok) return { ok: false, error: updated.error }
1782
+ if (!updated.wrote) {
1783
+ const refused = updated.result
1784
+ return refused.code ? { ok: false, error: refused.error, code: refused.code } : { ok: false, error: refused.error }
1785
+ }
1282
1786
  // #7002: computed from the mode we just PRESERVED and the entry we just wrote,
1283
1787
  // so it only fires when Chroxy is the party that put secret material into a
1284
1788
  // group/world-readable file. Advisory — we still do not re-permission the file.
1285
1789
  const warning = describeConfigModeSecretWarning({
1286
1790
  filePath: prepared.configPath,
1287
- mode: prepared.mode,
1791
+ mode: updated.result.mode,
1288
1792
  entry: prepared.entry,
1289
1793
  })
1290
1794
  const result = { ok: true, entry: prepared.entry, scope: prepared.scope }
@@ -1306,9 +1810,11 @@ export function addMcpServerToConfig(opts = {}) {
1306
1810
  * @param {'user'|'project'} [opts.scope]
1307
1811
  * @param {string} [opts.cwd] — required for scope 'project'
1308
1812
  * @param {string} [opts.configPath]
1309
- * @returns {{ ok: true, found: boolean, scope: string } | { ok: false, error: string }}
1813
+ * @param {Function} [opts._fsync] — TEST-ONLY (#7070): forwarded to
1814
+ * `writeClaudeConfigAtomic`; see its `_fsync` doc. Production never passes it.
1815
+ * @returns {{ ok: true, found: boolean, scope: string, durabilityUnconfirmed?: string } | { ok: false, error: string }}
1310
1816
  */
1311
- export function removeMcpServerFromConfig({ name, scope = 'user', cwd, configPath = defaultClaudeConfigPath() } = {}) {
1817
+ export function removeMcpServerFromConfig({ name, scope = 'user', cwd, configPath = defaultClaudeConfigPath(), _fsync } = {}) {
1312
1818
  const validName = validateMcpServerNameForRemoval(name)
1313
1819
  if (!validName.ok) return { ok: false, error: validName.error }
1314
1820
  if (!MCP_WRITE_SCOPES.includes(scope)) {
@@ -1318,11 +1824,23 @@ export function removeMcpServerFromConfig({ name, scope = 'user', cwd, configPat
1318
1824
  return { ok: false, error: 'Project scope requires a session working directory' }
1319
1825
  }
1320
1826
 
1321
- const read = readClaudeConfigForMutation(configPath)
1322
- if (!read.ok) return { ok: false, error: read.error }
1323
- if (!read.existed) return { ok: true, found: false, scope }
1324
- const raw = read.raw
1827
+ const updated = updateClaudeConfig(configPath, (raw, info) => {
1828
+ if (!info.existed) return { write: false, result: { found: false } }
1829
+ return removeServerFromTree(raw, { name: validName.name, scope, cwd })
1830
+ }, { _fsync })
1831
+ if (!updated.ok) return { ok: false, error: updated.error }
1832
+ if (!updated.wrote) return { ok: true, found: false, scope }
1833
+ const durabilityUnconfirmed = updated.durabilityUnconfirmed ?? undefined
1834
+ // #7054/#7068: REMOVE is the load-bearing durable case — this write is durable
1835
+ // precisely so a capability REDUCTION cannot silently reappear after a power
1836
+ // loss. Dropping the caveat here would sever the only caller-visible signal on
1837
+ // the one path that exists to carry it, which is the same false-green #7068
1838
+ // had to undo on the token revoke. Propagate rather than swallow.
1839
+ return { ok: true, found: true, scope, ...(durabilityUnconfirmed ? { durabilityUnconfirmed } : {}) }
1840
+ }
1325
1841
 
1842
+ /** Delete `name` from the scope's server block in `raw`; `{ write: false }` when it is absent (a no-op remove must not rewrite the file). */
1843
+ function removeServerFromTree(raw, { name, scope, cwd }) {
1326
1844
  let block = null
1327
1845
  if (scope === 'user') {
1328
1846
  if (raw.mcpServers && typeof raw.mcpServers === 'object' && !Array.isArray(raw.mcpServers)) {
@@ -1339,18 +1857,11 @@ export function removeMcpServerFromConfig({ name, scope = 'user', cwd, configPat
1339
1857
  }
1340
1858
  }
1341
1859
  }
1342
- if (!block || !Object.prototype.hasOwnProperty.call(block, validName.name)) {
1860
+ if (!block || !Object.prototype.hasOwnProperty.call(block, name)) {
1343
1861
  // Nothing to do — and crucially, NO write. A no-op remove must not rewrite
1344
1862
  // the user's file (nor risk clobbering a concurrent edit for nothing).
1345
- return { ok: true, found: false, scope }
1863
+ return { write: false, result: { found: false } }
1346
1864
  }
1347
-
1348
- delete block[validName.name]
1349
- const { durabilityUnconfirmed } = writeClaudeConfigAtomic(configPath, raw, { mode: read.mode }) ?? {}
1350
- // #7054/#7068: REMOVE is the load-bearing durable case — this write is durable
1351
- // precisely so a capability REDUCTION cannot silently reappear after a power
1352
- // loss. Dropping the caveat here would sever the only caller-visible signal on
1353
- // the one path that exists to carry it, which is the same false-green #7068
1354
- // had to undo on the token revoke. Propagate rather than swallow.
1355
- return { ok: true, found: true, scope, ...(durabilityUnconfirmed ? { durabilityUnconfirmed } : {}) }
1865
+ delete block[name]
1866
+ return { result: { found: true } }
1356
1867
  }