@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
package/src/doctor.js CHANGED
@@ -1,18 +1,22 @@
1
1
  import { execFileSync } from 'child_process'
2
- import { existsSync, readFileSync } from 'fs'
2
+ import { existsSync, readFileSync, realpathSync } from 'fs'
3
3
  import { dirname, isAbsolute, join, resolve } from 'path'
4
4
  import { fileURLToPath } from 'url'
5
- import { homedir } from 'os'
6
5
  import { createServer } from 'net'
7
- import { validateConfig } from './config.js'
6
+ import { validateConfig, resolveBinaryProvenanceMode, isBinarySignatureGateEnabled, mergeConfig } from './config.js'
8
7
  import { resolveBinary } from './utils/resolve-binary.js'
9
8
  import { verifyBinary as defaultVerifyBinary, BINARY_STATUS, describeBinaryHealth } from './utils/verify-binary.js'
9
+ import { resolveDeclaredMinVersion } from './utils/binary-version.js'
10
+ import { isShellShim, buildBinaryProvenanceOptions } from './utils/preflight.js'
11
+ import { verifyProvenance as defaultVerifyProvenance, PROVENANCE_STATUS } from './utils/verify-provenance.js'
10
12
  import { prepareSpawn } from './utils/win-spawn.js'
13
+ import { buildClaudeLaunchEnv } from './utils/spawn-env.js'
11
14
  import { cloudflaredInstallHint } from './platform.js'
12
- import { getProvider, DEFAULT_PROVIDER } from './providers.js'
15
+ import { getProvider, DEFAULT_PROVIDER, resolveDaemonDefaultProvider } from './providers.js'
13
16
  import { registerAnthropicCompatibleProviders } from './anthropic-compatible-session.js'
14
17
  import { registerOpenAiCompatibleProviders } from './openai-compatible-session.js'
15
18
  import { parseTunnelArg } from './tunnel/index.js'
19
+ import { CLOUDFLARED_CANDIDATES } from './tunnel/cloudflare.js'
16
20
  import { TESTED_CLAUDE_TUI_CLI_VERSION } from './claude-tui/tested-cli-version.js'
17
21
  import { detectSilentMeteredDefault } from './doctor-billing.js'
18
22
  import { keychainHealth } from './keychain.js'
@@ -20,9 +24,19 @@ import {
20
24
  billingClassForProvider,
21
25
  billingDetailForClass,
22
26
  isProgrammaticCreditEra,
27
+ programmaticCreditEraEnabled,
23
28
  PROGRAMMATIC_CREDIT_ERA_START,
24
29
  } from './billing-class.js'
25
30
  import { checkDependencies } from './utils/check-dependencies.js'
31
+ import { configPath } from './config-dir.js'
32
+ import { applyStrandedAck, detectStrandedState } from './config-dir-migration.js'
33
+ import { CLAUDE_LOGIN_COMMAND } from './utils/claude-login-command.js'
34
+ import { BinaryProvenanceLedger } from './binary-provenance-trust.js'
35
+ import { createLogger } from './logger.js'
36
+ import { countUserLevelChroxyHooks, userSettingsPath } from './permission-hook.js'
37
+ import { defaultClaudeConfigDir } from './utils/claude-config-dir.js'
38
+
39
+ const log = createLogger('doctor')
26
40
 
27
41
  // Resolve the server package root (the directory containing package.json
28
42
  // and node_modules) so dependency checks work regardless of where the
@@ -38,7 +52,9 @@ const SERVER_PKG_DIR = dirname(dirname(__filename))
38
52
  // tests/_setup.mjs redirecting CHROXY_CONFIG_DIR to a tmp dir — which would let
39
53
  // the named-tunnel routability probe (#5328) fire a live network request from
40
54
  // a maintainer's real config during the suite.
41
- const CONFIG_FILE = join(process.env.CHROXY_CONFIG_DIR || join(homedir(), '.chroxy'), 'config.json')
55
+ function configFile() {
56
+ return configPath('config.json')
57
+ }
42
58
 
43
59
  /**
44
60
  * Parse the leading `major.minor.patch` semver out of an arbitrary version
@@ -112,17 +128,54 @@ export function isBundledOrSupervisedContext() {
112
128
  /**
113
129
  * Resolve the list of providers to preflight check.
114
130
  *
131
+ * #8151 review round 2 (Critical 2) — the S6 version of this function (a
132
+ * hand-written copy of config.js's CLI > ENV > file > default precedence)
133
+ * was itself a regression outside Docker. It read `CHROXY_PROVIDERS`
134
+ * (plural) as a comma-separated list of PROVIDER NAMES — but
135
+ * `CHROXY_PROVIDERS` is a REAL, documented env var for `config.providers`
136
+ * (the anthropic-compatible/openai-compatible endpoint registrations: array
137
+ * OR object, see config.js's `CONFIG_SCHEMA` and `parseEnvValue`), not a
138
+ * provider roster. A daemon that set `CHROXY_PROVIDERS` to its own
139
+ * documented JSON-object form got that comma-split into garbage tokens here
140
+ * (3 bogus "names", `claude-sdk` never checked) — and even in the simple
141
+ * case, `CHROXY_PROVIDER=claude-sdk` with an unrelated `CHROXY_PROVIDERS`
142
+ * set made doctor check the WRONG provider while the daemon actually ran
143
+ * claude-sdk, because this function answered two different questions
144
+ * ("what provider does the daemon run" vs. "what is config.providers") with
145
+ * the same hand-rolled env read.
146
+ *
147
+ * Fixed by dropping this function's own env/file reads entirely and routing
148
+ * through the SAME shared loader `chroxy start`/`chroxy resume` use:
149
+ * `mergeConfig` (config.js) resolves CLI > ENV > file > default — including
150
+ * the `legacyCli` → `claude-cli` mapping — via its own
151
+ * `parseEnvValue`/`CONFIG_SCHEMA`-aware coercion (so `CHROXY_PROVIDERS`' object
152
+ * form is parsed as JSON, never comma-split, and is correctly ignored here
153
+ * since it feeds `merged.providers`, a field `resolveDaemonDefaultProvider`
154
+ * never reads). `resolveDaemonDefaultProvider` (providers.js) then reads
155
+ * `merged.provider` — the one function both doctor and the real daemon
156
+ * startup path share, so this can't drift from `chroxy start`'s own
157
+ * resolution again without touching shared code both paths run.
158
+ *
115
159
  * Precedence:
116
- * 1. Explicit `providers` option (array of provider names)
117
- * 2. `provider` field from loaded config file
118
- * 3. DEFAULT_PROVIDER (see providers.js)
160
+ * 1. Explicit `providers` option (array of provider names — doctor's own
161
+ * `--provider a,b` flag; unrelated to config.js's `providers` key)
162
+ * 2. Everything `mergeConfig` resolves for `provider` (ENV > file >
163
+ * default) — exactly one name, the one `chroxy start` would run.
119
164
  *
120
165
  * Returns an array of provider name strings.
166
+ *
167
+ * @param {object} args
168
+ * @param {string[]} [args.providers] - doctor's own explicit `--provider a,b`
169
+ * flag; still the highest-precedence override when present.
170
+ * @param {object|null} [args.parsedConfig] - the raw parsed config.json (or
171
+ * null/absent), fed to mergeConfig as the file tier.
121
172
  */
122
- function resolveProviders({ providers, configProvider }) {
173
+ function resolveProviders({ providers, parsedConfig }) {
123
174
  if (Array.isArray(providers) && providers.length > 0) return providers
124
- if (typeof configProvider === 'string' && configProvider.length > 0) return [configProvider]
125
- return [DEFAULT_PROVIDER]
175
+ const merged = mergeConfig({
176
+ fileConfig: parsedConfig && typeof parsedConfig === 'object' ? parsedConfig : {},
177
+ })
178
+ return [resolveDaemonDefaultProvider(merged)]
126
179
  }
127
180
 
128
181
  /**
@@ -141,6 +194,97 @@ function claudeTuiBinaryCandidates() {
141
194
  }
142
195
  }
143
196
 
197
+ /**
198
+ * Build a doctor `fail` check for a binary the opt-in provenance gate refused
199
+ * (#8041) — a `block`-mode hash mismatch or a failed signature-gate
200
+ * assessment. Doctor checks report status objects rather than throwing, so
201
+ * this is the doctor-shaped equivalent of `ProviderBinaryProvenanceError` /
202
+ * `TunnelBinaryProvenanceError`: same message shape (path, verdict status,
203
+ * message, remediation), returned instead of thrown. Always a hard `fail`
204
+ * regardless of whether the binary itself is `required` — a provenance
205
+ * refusal is a security decision (the daemon never downgrades it), not an
206
+ * advisory floor like a missing optional binary.
207
+ *
208
+ * @param {string} name - the doctor check's display name
209
+ * @param {string} resolved - the resolved absolute path that was refused
210
+ * @param {{ status: string, message?: string, remediation?: string }} verdict
211
+ * - the blocked verdict returned by `verifyProvenance`
212
+ * @returns {{ name: string, status: 'fail', message: string }}
213
+ */
214
+ function provenanceBlockedCheck(name, resolved, verdict) {
215
+ return {
216
+ name,
217
+ status: 'fail',
218
+ message: `${resolved} — provenance ${verdict.status}: ${verdict.message || 'failed provenance verification'}`
219
+ + `${verdict.remediation ? ` — ${verdict.remediation}` : ''}`,
220
+ }
221
+ }
222
+
223
+ /**
224
+ * #8223: the resolve -> health-check -> provenance-gate prelude shared by every
225
+ * doctor probe that EXECS `claude` (the claude-tui version pin and the login
226
+ * check), lifted out of `checkClaudeTuiCliVersion` unchanged so the two cannot
227
+ * drift on how the binary is vetted before it runs. Returns the path to exec and
228
+ * any pending warn-mode provenance advisory, or null when `claude` cannot be run
229
+ * (missing / quarantined / provenance-blocked) — the provider binary check
230
+ * already reports those, so a probe adds no second row for them.
231
+ *
232
+ * @param {object} deps - same shape as `checkClaudeTuiCliVersion`'s
233
+ * @param {string} probeLabel - names the probe in the provenance warn log
234
+ * @returns {{ execPath: string, provenanceAdvisory: string|null } | null}
235
+ */
236
+ function resolveClaudeProbeBinary({ candidates, resolveBinary: resolveClaudeBinary, verify, provenance, verifyProvenance }, probeLabel) {
237
+ const resolved = resolveClaudeBinary('claude', candidates)
238
+ // #8074 review C2: `verifyProvenance` must never run on an unresolved/
239
+ // not-found path — a bare, unresolved name (`resolveBinary` returns the
240
+ // bare name itself when nothing matched) would get hashed relative to the
241
+ // CURRENT WORKING DIRECTORY, mislabeling a missing `claude` as a
242
+ // provenance failure. So the #6708 health check gates the probe too, but —
243
+ // "at minimum when a gate is on" — ONLY when `provenance` is supplied: this
244
+ // function had NO health check at all before #8041 (unlike checkBinary),
245
+ // and every existing caller with the gate off relies on `exec` alone
246
+ // deciding pass/fail/missing, exactly as it always has. `null` here (not a
247
+ // fail row) matches this function's own documented contract: the provider
248
+ // binary check already surfaces a missing/quarantined claude.
249
+ let execPath = resolved
250
+ let provenanceAdvisory = null
251
+ if (provenance) {
252
+ const health = verify(resolved)
253
+ if (!health.ok) {
254
+ return null
255
+ }
256
+ execPath = health.path
257
+ // #8041: route the probe through the opt-in provenance gate — a
258
+ // `block`-mode hash mismatch or failed signature gate refuses the probe
259
+ // outright, and the binary at `execPath` is NEVER exec'd.
260
+ const verdict = verifyProvenance({
261
+ resolvedPath: health.path,
262
+ mode: provenance.mode,
263
+ signatureGate: provenance.signatureGate === true,
264
+ ledger: provenance.ledger || null,
265
+ })
266
+ if (verdict.blocked) {
267
+ // #8074 review S3: return null, not a second `fail` row — the SAME
268
+ // `claude` binary's own provider-preflight row (checkProvider, via
269
+ // checkBinary against the identical provenance options) already
270
+ // reports this exact refusal. Two rows for one blocked binary is
271
+ // confusing, not informative, and this function's docblock already
272
+ // promises "null when claude can't be run".
273
+ return null
274
+ }
275
+ if (
276
+ verdict.status === PROVENANCE_STATUS.HASH_MISMATCH
277
+ || verdict.status === PROVENANCE_STATUS.SIGNATURE_INVALID
278
+ || verdict.status === PROVENANCE_STATUS.UNREADABLE
279
+ ) {
280
+ log.warn(`Binary "claude" (${probeLabel} probe) provenance ${verdict.status}: ${verdict.message || ''} (allowed — mode=${provenance.mode})`)
281
+ provenanceAdvisory = `provenance ${verdict.status}: ${verdict.message || 'unverifiable'}`
282
+ + `${verdict.remediation ? ` — ${verdict.remediation}` : ''} (allowed — mode=${provenance.mode})`
283
+ }
284
+ }
285
+ return { execPath, provenanceAdvisory }
286
+ }
287
+
144
288
  /**
145
289
  * audit P1-3 / #5821: compare the installed claude CLI version against the
146
290
  * version chroxy's claude-tui form-driving was validated against
@@ -154,6 +298,14 @@ function claudeTuiBinaryCandidates() {
154
298
  * @param {(bin: string, args: string[]) => string} [deps.exec]
155
299
  * @param {string} [deps.tested]
156
300
  * @param {string[]} [deps.candidates] - fallback absolute paths for resolveBinary
301
+ * @param {(name: string, candidates: string[]) => string} [deps.resolveBinary] -
302
+ * injectable resolver (test seam; defaults to the real PATH/candidate resolve)
303
+ * @param {Function} [deps.verify] - binary health checker (injected in tests;
304
+ * #8074 review C2 — defaults to the real #6708 `verifyBinary`)
305
+ * @param {{ mode: string, signatureGate: boolean, ledger: object|null }|null} [deps.provenance]
306
+ * - #8041: opt-in provenance options bag (`buildBinaryProvenanceOptions`); null
307
+ * (the default) skips the gate entirely, matching pre-#8041 behaviour.
308
+ * @param {Function} [deps.verifyProvenance] - provenance checker (injected in tests)
157
309
  * @returns {{ name: string, status: 'pass'|'warn', message: string } | null}
158
310
  */
159
311
  export function checkClaudeTuiCliVersion(deps = {}) {
@@ -164,7 +316,7 @@ export function checkClaudeTuiCliVersion(deps = {}) {
164
316
  // win32-routing test exercises this default path directly.
165
317
  exec = (bin, args) => {
166
318
  const s = prepareSpawn(bin, args)
167
- return execFileSync(s.command, s.args, { encoding: 'utf-8', timeout: 5000, stdio: ['ignore', 'pipe', 'pipe'], ...s.options })
319
+ return execFileSync(s.command, s.args, { encoding: 'utf-8', timeout: 5000, stdio: ['ignore', 'pipe', 'pipe'], env: buildClaudeLaunchEnv(), ...s.options })
168
320
  },
169
321
  tested = TESTED_CLAUDE_TUI_CLI_VERSION,
170
322
  // #5871: resolve against the SAME candidate paths the claude-tui provider
@@ -173,10 +325,21 @@ export function checkClaudeTuiCliVersion(deps = {}) {
173
325
  // claude via its candidate list — exactly the bundled context where a
174
326
  // silent mis-drive would otherwise go unnoticed.
175
327
  candidates = claudeTuiBinaryCandidates(),
328
+ resolveBinary: resolveClaudeBinary = resolveBinary,
329
+ verify = defaultVerifyBinary,
330
+ provenance = null,
331
+ verifyProvenance = defaultVerifyProvenance,
176
332
  } = deps
333
+ const probe = resolveClaudeProbeBinary({ candidates, resolveBinary: resolveClaudeBinary, verify, provenance, verifyProvenance }, 'claude-tui driving')
334
+ if (!probe) return null
335
+ const { execPath, provenanceAdvisory } = probe
336
+ // #8074 round-2 review: EVERY row this probe returns carries a pending
337
+ // warn-mode advisory, not only the clean-baseline one — an earlier warn
338
+ // (unparseable version, baseline drift) must not swallow it.
339
+ const withAdvisory = (msg) => (provenanceAdvisory ? `${msg} — ${provenanceAdvisory}` : msg)
177
340
  let output
178
341
  try {
179
- output = exec(resolveBinary('claude', candidates), ['--version'])
342
+ output = exec(execPath, ['--version'])
180
343
  } catch {
181
344
  return null // claude missing/hung — the provider binary check surfaces that
182
345
  }
@@ -184,17 +347,105 @@ export function checkClaudeTuiCliVersion(deps = {}) {
184
347
  const found = parseLeadingSemver(output)
185
348
  const testedSemver = parseLeadingSemver(tested)
186
349
  if (found === null) {
187
- return { name: NAME, status: 'warn', message: `Could not parse 'claude --version'; TUI form-driving is validated against ${tested}` }
350
+ return { name: NAME, status: 'warn', message: withAdvisory(`Could not parse 'claude --version'; TUI form-driving is validated against ${tested}`) }
188
351
  }
189
352
  const foundStr = `${found[0]}.${found[1]}.${found[2]}`
190
353
  if (testedSemver && found[0] === testedSemver[0] && found[1] === testedSemver[1]) {
354
+ // #8074 review S1: a pending provenance advisory (warn mode) must not be
355
+ // silently absorbed into an otherwise-clean `pass` row.
356
+ if (provenanceAdvisory) {
357
+ return { name: NAME, status: 'warn', message: withAdvisory(`claude ${foundStr} matches the tested TUI-driving baseline (${tested})`) }
358
+ }
191
359
  return { name: NAME, status: 'pass', message: `claude ${foundStr} matches the tested TUI-driving baseline (${tested})` }
192
360
  }
193
361
  return {
194
362
  name: NAME,
195
363
  status: 'warn',
196
- message: `claude ${foundStr} differs from the tested TUI-driving baseline (${tested}) — chroxy drives the TUI by screen-scraping pinned keystrokes, so a CLI UI change can mis-drive AskUserQuestion forms silently. If question prompts misbehave, report it; re-validation will bump the baseline.`,
364
+ message: withAdvisory(`claude ${foundStr} differs from the tested TUI-driving baseline (${tested}) — chroxy drives the TUI by screen-scraping pinned keystrokes, so a CLI UI change can mis-drive AskUserQuestion forms silently. If question prompts misbehave, report it; re-validation will bump the baseline.`),
365
+ }
366
+ }
367
+
368
+ const CLAUDE_LOGIN_UNREADABLE_MESSAGE = `Could not read the login state from \`claude auth status --json\` — if a claude-tui session reports AUTH_REQUIRED, run \`${CLAUDE_LOGIN_COMMAND}\` on this host.`
369
+
370
+ /**
371
+ * #8223: report whether the `claude` on this host is logged in, from
372
+ * `claude auth status --json` — the same question claude-tui asks before it
373
+ * spawns a PTY. A logged-out host is otherwise discovered only when a session
374
+ * fails to start. Never `fail`s: a doctor failure blocks `chroxy start`, and
375
+ * "not logged in" is a state the operator fixes in a terminal, not a broken
376
+ * install.
377
+ *
378
+ * Rows: `pass` "Logged in (<authMethod>[, <subscriptionType>])" for an explicit
379
+ * `loggedIn: true`; `warn` for an explicit `loggedIn: false`, and `warn` when
380
+ * the status cannot be read (timeout, unparseable output, no `loggedIn` field).
381
+ * Returns null — no row — when `claude` cannot be run at all (missing,
382
+ * quarantined, provenance-blocked): the provider binary row already says so.
383
+ *
384
+ * `claude auth status` exits 1 when logged out but still prints its JSON, so a
385
+ * non-zero exit that carries stdout is read, not treated as unreadable. The
386
+ * probe runs with ANTHROPIC_API_KEY removed from its env the way claude-tui
387
+ * removes it from the PTY's, so it reports the subscription login rather than
388
+ * an API key that claude-tui would never use. An EXPIRED oauth token still
389
+ * reports `loggedIn: true`; only a live session's PTY scan sees expiry.
390
+ *
391
+ * @param {object} [deps] - same seams as `checkClaudeTuiCliVersion`, plus:
392
+ * @param {(bin: string, args: string[], opts: { env: object }) => string} [deps.exec]
393
+ * returns stdout; may throw an error carrying `status` + `stdout` (non-zero exit)
394
+ * @param {object} [deps.env] - environment the probe is derived from (default process.env)
395
+ * @returns {{ name: string, status: 'pass'|'warn', message: string } | null}
396
+ */
397
+ export function checkClaudeLogin(deps = {}) {
398
+ const {
399
+ // Same prepareSpawn routing as the version probe's default (#6484). The args
400
+ // are always the literal ['auth', 'status', '--json'] from the one call below.
401
+ exec = (bin, args, { env }) => {
402
+ const s = prepareSpawn(bin, args)
403
+ return execFileSync(s.command, s.args, { encoding: 'utf-8', timeout: 5000, stdio: ['ignore', 'pipe', 'pipe'], env, ...s.options })
404
+ },
405
+ candidates = claudeTuiBinaryCandidates(),
406
+ resolveBinary: resolveClaudeBinary = resolveBinary,
407
+ verify = defaultVerifyBinary,
408
+ provenance = null,
409
+ verifyProvenance = defaultVerifyProvenance,
410
+ env = process.env,
411
+ } = deps
412
+ const probe = resolveClaudeProbeBinary({ candidates, resolveBinary: resolveClaudeBinary, verify, provenance, verifyProvenance }, 'claude login')
413
+ if (!probe) return null
414
+
415
+ const NAME = 'Claude login'
416
+ const probeEnv = buildClaudeLaunchEnv(env)
417
+ delete probeEnv.ANTHROPIC_API_KEY
418
+
419
+ let stdout
420
+ try {
421
+ stdout = exec(probe.execPath, ['auth', 'status', '--json'], { env: probeEnv })
422
+ } catch (err) {
423
+ if (err?.code === 'ENOENT') return null // claude missing — the binary row says so
424
+ if (typeof err?.status === 'number' && typeof err.stdout === 'string') {
425
+ stdout = err.stdout // exit 1 = logged out, JSON still on stdout
426
+ } else {
427
+ return { name: NAME, status: 'warn', message: CLAUDE_LOGIN_UNREADABLE_MESSAGE }
428
+ }
197
429
  }
430
+
431
+ let status
432
+ try {
433
+ status = JSON.parse(String(stdout || ''))
434
+ } catch {
435
+ return { name: NAME, status: 'warn', message: CLAUDE_LOGIN_UNREADABLE_MESSAGE }
436
+ }
437
+ if (status?.loggedIn === true) {
438
+ const how = [status.authMethod, status.subscriptionType].filter((v) => typeof v === 'string' && v.length > 0)
439
+ return { name: NAME, status: 'pass', message: how.length > 0 ? `Logged in (${how.join(', ')})` : 'Logged in' }
440
+ }
441
+ if (status?.loggedIn === false) {
442
+ return {
443
+ name: NAME,
444
+ status: 'warn',
445
+ message: `Not logged in — run \`${CLAUDE_LOGIN_COMMAND}\` on this host. claude-tui needs it; claude-sdk needs it unless ANTHROPIC_API_KEY is set.`,
446
+ }
447
+ }
448
+ return { name: NAME, status: 'warn', message: CLAUDE_LOGIN_UNREADABLE_MESSAGE }
198
449
  }
199
450
 
200
451
  /**
@@ -274,6 +525,64 @@ export async function checkTunnelRoutability(deps = {}) {
274
525
  }
275
526
  }
276
527
 
528
+ /**
529
+ * #8263: warn about a chroxy permission-hook entry in the USER-LEVEL Claude
530
+ * settings. claude-tui children load that file as well as their per-session
531
+ * settings, so a stranded entry used to double every permission prompt. The
532
+ * hook script now stays inert for it inside a TUI child, so this is a hygiene
533
+ * warning, not a live fault. Read-only: the daemon does not sweep or clean the
534
+ * user-level file, because the entry may belong to a live claude-cli session of
535
+ * another daemon (#8350) — the operator removes it.
536
+ *
537
+ * A file that exists but cannot be read or parsed is reported too: "could not
538
+ * look" must not read the same as "nothing there" (a missing file is not an
539
+ * error, and still yields null).
540
+ *
541
+ * @param {{settingsPath?: string}} [deps]
542
+ * @returns {{ name: string, status: 'warn', message: string } | null} null when none found
543
+ */
544
+ export function checkUserLevelChroxyHook({ settingsPath } = {}) {
545
+ const { found, settingsPath: target, error } = countUserLevelChroxyHooks({ settingsPath })
546
+ const NAME = 'User-level permission hook'
547
+ if (error) {
548
+ return {
549
+ name: NAME,
550
+ status: 'warn',
551
+ message: `could not read user-level settings: ${error} (${target}) — a chroxy permission-hook entry there, if any, was not checked`,
552
+ }
553
+ }
554
+ if (found === 0) return null
555
+ return {
556
+ name: NAME,
557
+ status: 'warn',
558
+ message: `${found} chroxy permission-hook entr${found === 1 ? 'y' : 'ies'} in ${target} — fix: remove the hooks.PreToolUse entry that runs permission-hook.sh from that file by hand (only when no claude-cli session is running; it is ignored inside claude-tui sessions)`,
559
+ }
560
+ }
561
+
562
+ /**
563
+ * #8974: when a CLAUDE_CONFIG_DIR override is active, a chroxy permission-hook
564
+ * entry left in the DEFAULT `~/.claude/settings.json` (registered before the
565
+ * override was set, or by another daemon) is stranded: claude no longer loads
566
+ * that file for this profile. Report only; it is never removed here because
567
+ * another daemon may own it.
568
+ *
569
+ * @param {{activePath?: string, defaultPath?: string}} [deps]
570
+ * @returns {{ name: string, status: 'warn', message: string } | null}
571
+ */
572
+ export function checkStrandedDefaultHook({ activePath, defaultPath } = {}) {
573
+ const active = activePath ?? userSettingsPath()
574
+ const fallback = defaultPath ?? join(defaultClaudeConfigDir(), 'settings.json')
575
+ const canon = (p) => { try { return realpathSync(p) } catch { return resolve(p) } }
576
+ if (canon(active) === canon(fallback)) return null
577
+ const { found, error } = countUserLevelChroxyHooks({ settingsPath: fallback })
578
+ if (error || found === 0) return null
579
+ return {
580
+ name: 'Stranded permission hook',
581
+ status: 'warn',
582
+ message: `${found} chroxy permission-hook entr${found === 1 ? 'y' : 'ies'} in ${fallback}, which is not the active settings file (${active}) for this daemon's claude — fix: remove the hooks.PreToolUse entry that runs permission-hook.sh from that file by hand (only when no claude-cli session of another daemon is using it)`,
583
+ }
584
+ }
585
+
277
586
  /**
278
587
  * Run all preflight dependency checks and return results.
279
588
  *
@@ -290,9 +599,76 @@ export async function checkTunnelRoutability(deps = {}) {
290
599
  * Dependencies check. Defaults to the server package root. Relative paths are resolved to
291
600
  * absolute at call time so the check is fully decoupled from process.cwd(). Exposed so
292
601
  * tests can point the check at a temp directory without mutating process.cwd().
602
+ * @param {string|null} [options.tunnelMode] - #8116: override the named-tunnel mode used by
603
+ * the routability probe (step 5.6, #5328 WP-5.6). `undefined` (the default) reads it from
604
+ * doctor's own default config file, unchanged — `chroxy doctor` never passes this. Supplied
605
+ * (including `null`, meaning "no tunnel") it REPLACES the file-derived value entirely —
606
+ * `chroxy start` passes the MERGED config's own resolved tunnel mode (same seam shape as
607
+ * `binaryProvenanceMode`, #8074).
608
+ * @param {string|null} [options.tunnelHostname] - Same override shape as `tunnelMode`, for the
609
+ * named-tunnel hostname.
293
610
  * @returns {{ checks: Array<{ name: string, status: 'pass'|'warn'|'fail', message: string, provider?: string }>, passed: boolean, providers: string[] }}
294
611
  */
295
- export async function runDoctorChecks({ port, providers, verbose: _verbose, pkgDir = SERVER_PKG_DIR, now = Date.now(), tunnelProbe } = {}) {
612
+ export async function runDoctorChecks({
613
+ port, portProblem, configFilePath, providers, verbose: _verbose, pkgDir = SERVER_PKG_DIR, now = Date.now(),
614
+ tunnelProbe, detectStranded = detectStrandedState, platform = process.platform,
615
+ // #8116 — same seam shape as #8074's binaryProvenanceMode / #8115's
616
+ // providers: `undefined` (the default) means "read the named-tunnel
617
+ // coordinates for the routability probe (step 5.6 below) from doctor's own
618
+ // default config file", exactly as before — `chroxy doctor` (doctor-cmd.js)
619
+ // never passes these and is therefore unaffected. Supplied (even `null`,
620
+ // meaning "no tunnel"), they REPLACE the file-derived value entirely —
621
+ // `chroxy start` (server-cmd.js) passes both from the MERGED config it
622
+ // already resolved (-c <path> / --tunnel / --tunnel-hostname /
623
+ // CHROXY_TUNNEL* env), so the probe always targets the tunnel the daemon
624
+ // it's about to start actually uses, not whichever tunnel the default file
625
+ // happens to name.
626
+ tunnelMode: tunnelModeOverride,
627
+ tunnelHostname: tunnelHostnameOverride,
628
+ // #8041 — test seams for the opt-in binary-provenance gate applied to the
629
+ // cloudflared / provider-binary / claude-tui version probes below. All
630
+ // default to the real production resolution so `chroxy doctor` / `chroxy
631
+ // start` are unaffected:
632
+ // - `binaryProvenanceMode` / `binarySignatureGate` override the config +
633
+ // env resolution (`resolveBinaryProvenanceMode` / `isBinarySignatureGateEnabled`)
634
+ // entirely when supplied — a plain function-argument seam so a test can
635
+ // set the gate's mode WITHOUT resolving it from a real config file or
636
+ // `process.env`, exercising the gate logic directly. (#8074 review N4:
637
+ // this is not about test concurrency — this test runner's default is
638
+ // to run sibling `it()`s within one file SEQUENTIALLY; the seam exists
639
+ // so tests don't need a real config file at all, not to avoid a race.)
640
+ // - `binaryProvenanceLedger` overrides the lazily-constructed default-path
641
+ // ledger (undefined ⇒ construct one only when the gate resolves on,
642
+ // same as `resolveVerifiedClaudeBinary` in cli/session-cmd.js).
643
+ verifyProvenance = defaultVerifyProvenance,
644
+ binaryProvenanceLedger: binaryProvenanceLedgerOverride,
645
+ binaryProvenanceMode: binaryProvenanceModeOverride,
646
+ binarySignatureGate: binarySignatureGateOverride,
647
+ // #8074 review C3(c): test-only resolver override for the claude-tui
648
+ // version-pin probe specifically (see the call site below) — undefined in
649
+ // production, so `checkClaudeTuiCliVersion` uses its own real resolver.
650
+ claudeTuiResolveBinary,
651
+ // #8223 test seam: overrides for the claude login probe (step 5.7) — `exec`,
652
+ // `resolveBinary`, `verify`, `env`. Undefined in production, which uses the real
653
+ // ones; without it a test would resolve and exec a REAL `claude` on the host.
654
+ claudeLoginDeps = {},
655
+ // #8041 test seam: cloudflared's fallback candidate paths, so a test can
656
+ // point resolution at a fixture without depending on whether a REAL
657
+ // cloudflared happens to be installed at one of the fixed production
658
+ // candidates on the machine running the suite. Defaults to
659
+ // `CLOUDFLARED_CANDIDATES`, imported from `tunnel/cloudflare.js` (#8074
660
+ // review S2) rather than a second hand-kept copy — that module's own
661
+ // `_verifyCloudflaredProvenance` gates the daemon's tunnel spawn against
662
+ // this EXACT list, so doctor's pre-flight check and the daemon's real gate
663
+ // can never silently diverge on which paths count as "cloudflared".
664
+ cloudflaredCandidates = CLOUDFLARED_CANDIDATES,
665
+ // #8263: opt-in (`chroxy doctor` passes true) so `chroxy start`'s preflight and
666
+ // the unit tests never read the operator's real ~/.claude/settings.json.
667
+ // `userHookSettingsPath` is the test seam for that read.
668
+ checkUserLevelHook = false,
669
+ userHookSettingsPath,
670
+ strandedHookSettingsPath,
671
+ } = {}) {
296
672
  const checks = []
297
673
 
298
674
  // 1. Node.js version
@@ -306,28 +682,31 @@ export async function runDoctorChecks({ port, providers, verbose: _verbose, pkgD
306
682
  checks.push({ name: 'Node.js', status: 'fail', message: `v${nodeVersion} — Node 22 required` })
307
683
  }
308
684
 
309
- // 2. cloudflared
310
- checks.push(checkBinary('cloudflared', ['--version'], {
311
- parseVersion: (out) => out.trim().split('\n')[0],
312
- required: true,
313
- candidates: [
314
- '/opt/homebrew/bin/cloudflared',
315
- '/usr/local/bin/cloudflared',
316
- join(homedir(), '.local/bin/cloudflared'),
317
- ],
318
- installHint: cloudflaredInstallHint(),
319
- }))
320
-
321
- // 3. Load config (once) — used for both the Config check and provider resolution.
322
- let configProvider = null
685
+ // 2. Load config (once) — used for the Config check, provider resolution,
686
+ // AND (#8041) the binary-provenance gate below. Moved ahead of the
687
+ // cloudflared check (previously step 2) because that check now needs the
688
+ // gate's resolved mode/signatureGate before it can run.
323
689
  let configCheck = null
324
690
  // #5328 (WP-5.6): named-tunnel coordinates for the routability probe (step 5.6).
325
691
  let tunnelMode = null
326
692
  let tunnelHostname = null
327
- if (existsSync(CONFIG_FILE)) {
693
+ // #8041: the raw parsed config object, kept around (in addition to the
694
+ // narrower locals above) so resolveBinaryProvenanceMode /
695
+ // isBinarySignatureGateEnabled can read config.binaryProvenance the same
696
+ // way chroxy start / chroxy resume do. Stays null when the file is
697
+ // missing or fails to parse — both resolvers treat a missing
698
+ // `binaryProvenance` key as gate-off, matching every other check in this
699
+ // function's existing "a corrupt config degrades gracefully" behaviour
700
+ // rather than hard-failing doctor itself.
701
+ // #8233: `-c <path>` (configFilePath) replaces the default config.json for every
702
+ // check below that reads config.
703
+ const explicitConfig = typeof configFilePath === 'string' && configFilePath !== ''
704
+ const cfgFile = explicitConfig ? configFilePath : configFile()
705
+ let parsedConfig = null
706
+ if (existsSync(cfgFile)) {
328
707
  try {
329
- const config = JSON.parse(readFileSync(CONFIG_FILE, 'utf-8'))
330
- if (typeof config.provider === 'string') configProvider = config.provider
708
+ const config = JSON.parse(readFileSync(cfgFile, 'utf-8'))
709
+ parsedConfig = config
331
710
  // Normalize the tunnel mode through parseTunnelArg so aliases resolve —
332
711
  // e.g. `cloudflare:named` (a documented --tunnel form persisted verbatim)
333
712
  // maps to mode 'named' and isn't silently skipped by the routability
@@ -353,34 +732,162 @@ export async function runDoctorChecks({ port, providers, verbose: _verbose, pkgD
353
732
  registerOpenAiCompatibleProviders(config)
354
733
  const { valid, warnings } = validateConfig(config)
355
734
  if (valid) {
356
- configCheck = { name: 'Config', status: 'pass', message: CONFIG_FILE }
735
+ configCheck = { name: 'Config', status: 'pass', message: cfgFile }
357
736
  } else {
358
- configCheck = { name: 'Config', status: 'warn', message: `${CONFIG_FILE} — ${warnings.join('; ')}` }
737
+ configCheck = { name: 'Config', status: 'warn', message: `${cfgFile} — ${warnings.join('; ')}` }
359
738
  }
360
739
  } catch (err) {
361
740
  if (err instanceof SyntaxError) {
362
- configCheck = { name: 'Config', status: 'fail', message: `${CONFIG_FILE} — invalid JSON: ${err.message}` }
741
+ configCheck = { name: 'Config', status: 'fail', message: `${cfgFile} — invalid JSON: ${err.message}` }
363
742
  } else {
364
- configCheck = { name: 'Config', status: 'fail', message: `${CONFIG_FILE} — ${err.message}` }
743
+ configCheck = { name: 'Config', status: 'fail', message: `${cfgFile} — ${err.message}` }
365
744
  }
366
745
  }
746
+ } else if (explicitConfig) {
747
+ // `-c <path>` named a file that does not exist: fail naming THAT path, as `start` does.
748
+ configCheck = { name: 'Config', status: 'fail', message: `${cfgFile} — config file not found` }
367
749
  } else {
368
750
  configCheck = { name: 'Config', status: 'warn', message: `Not found — run 'chroxy init' to create` }
369
751
  }
370
752
 
371
- // 4. Provider-specific checks. Each configured provider contributes its
753
+ // #8116: an explicit override REPLACES the file-derived coordinates above,
754
+ // independently for mode and hostname (mirrors binaryProvenanceMode /
755
+ // binarySignatureGate's independent-override shape below) — `undefined`
756
+ // leaves the file-derived value in place, so `chroxy doctor` (which never
757
+ // supplies either) is byte-identical to before this issue.
758
+ if (tunnelModeOverride !== undefined) tunnelMode = tunnelModeOverride
759
+ if (tunnelHostnameOverride !== undefined) tunnelHostname = tunnelHostnameOverride
760
+
761
+ // 3. #8041 — resolve the opt-in binary-provenance gate ONCE, from the SAME
762
+ // config + env precedence `chroxy start` / `chroxy resume` use
763
+ // (resolveBinaryProvenanceMode / isBinarySignatureGateEnabled — env vars
764
+ // CHROXY_BINARY_PROVENANCE / CHROXY_BINARY_SIGNATURE_GATE outrank the
765
+ // config file), normalized through the SAME `buildBinaryProvenanceOptions`
766
+ // helper #8065 added (utils/preflight.js) so "the gate is off" is defined
767
+ // in exactly one place, not a second copy for doctor. The resolved bag is
768
+ // shared by the cloudflared check below, every provider's binary check
769
+ // (step 5), and the claude-tui version-pin probe (step 5.6) — one gate
770
+ // resolution, one ledger instance, not three.
771
+ //
772
+ // The ledger is opened lazily, and only when a gate is actually ON
773
+ // (#8065 review nitpick 3's rationale, reapplied here): a default
774
+ // `chroxy doctor` / `chroxy start` run with gates off must never touch —
775
+ // or warn about — the real `binary-trust.json`, since `buildBinaryProvenanceOptions`
776
+ // is about to discard it anyway (returns null when the gate is off).
777
+ const provenanceMode = binaryProvenanceModeOverride !== undefined
778
+ ? binaryProvenanceModeOverride
779
+ : resolveBinaryProvenanceMode(parsedConfig || {})
780
+ const provenanceSignatureGate = binarySignatureGateOverride !== undefined
781
+ ? binarySignatureGateOverride
782
+ : isBinarySignatureGateEnabled(parsedConfig || {})
783
+ const provenanceGateOn = provenanceMode !== 'off' || provenanceSignatureGate === true
784
+ const binaryProvenanceLedger = binaryProvenanceLedgerOverride !== undefined
785
+ ? binaryProvenanceLedgerOverride
786
+ : (provenanceGateOn ? new BinaryProvenanceLedger() : null)
787
+ const provenanceOptions = buildBinaryProvenanceOptions({
788
+ mode: provenanceMode,
789
+ signatureGate: provenanceSignatureGate,
790
+ ledger: binaryProvenanceLedger,
791
+ })
792
+
793
+ // 4. cloudflared. #8041: gated through the SAME opt-in provenance options
794
+ // the daemon's tunnel adapter uses (`_verifyCloudflaredProvenance`,
795
+ // tunnel/cloudflare.js) — a block-mode hash mismatch or failed signature
796
+ // gate now reports `fail` here WITHOUT ever exec'ing `cloudflared --version`.
797
+ checks.push(checkBinary('cloudflared', ['--version'], {
798
+ parseVersion: (out) => out.trim().split('\n')[0],
799
+ required: true,
800
+ candidates: cloudflaredCandidates,
801
+ installHint: cloudflaredInstallHint(),
802
+ provenance: provenanceOptions,
803
+ verifyProvenance,
804
+ }))
805
+
806
+ // #7240 — state stranded at ~/.chroxy by a CHROXY_CONFIG_DIR relocation.
807
+ // Computed before the Config check is pushed so the "Not found" branch above
808
+ // can be corrected: recommending `chroxy init` when the real cause is an
809
+ // unmoved config.json mints a fresh token and forces every device to re-pair,
810
+ // which is strictly worse than the problem it purports to fix.
811
+ let strandedCheck = null
812
+ try {
813
+ const raw = detectStranded()
814
+ // #7244 — entries the operator acknowledged with `chroxy config-dir ack`
815
+ // are dropped here; one that appeared afterwards is not, and still warns.
816
+ // The same helper the startup warning uses, so the two cannot disagree.
817
+ const stranded = applyStrandedAck(raw)
818
+ if (stranded.unreadable) {
819
+ strandedCheck = {
820
+ name: 'Config/state root',
821
+ status: 'warn',
822
+ message: `${stranded.target} — could not check ${stranded.source} for stranded state: ${stranded.unreadable}`,
823
+ }
824
+ } else if (stranded.stranded.length > 0) {
825
+ const sharp = stranded.highConsequence.length > 0
826
+ ? ` (including ${stranded.highConsequence.join(', ')})`
827
+ : ''
828
+ // Bounded: a relocated root can strand an arbitrary number of entries and
829
+ // doctor output is a single line per check. The high-consequence ones are
830
+ // named separately above, so the truncated tail never hides the sharp cases.
831
+ const MAX_NAMED = 8
832
+ const named = stranded.stranded.slice(0, MAX_NAMED).join(', ')
833
+ const rest = stranded.stranded.length - MAX_NAMED
834
+ strandedCheck = {
835
+ name: 'Config/state root',
836
+ status: 'warn',
837
+ message: `${stranded.target} (from CHROXY_CONFIG_DIR) — ${stranded.stranded.length} `
838
+ + `state ${stranded.stranded.length === 1 ? 'entry is' : 'entries are'} still at `
839
+ + `${stranded.source}${sharp}: ${named}${rest > 0 ? `, and ${rest} more` : ''}`
840
+ + (stranded.acknowledged.length > 0 ? ` (${stranded.acknowledged.length} more acknowledged earlier)` : '')
841
+ + ` — fix: chroxy config-dir migrate (or chroxy config-dir ack to keep this root on purpose)`,
842
+ }
843
+ } else {
844
+ // Read the root off the detection, NOT from configDir()/process.env
845
+ // directly: the detection is injectable, and a branch that bypasses the
846
+ // seam reports something the caller did not ask about — which also makes
847
+ // this message the one branch a test cannot pin.
848
+ const acked = stranded.acknowledged.length
849
+ strandedCheck = {
850
+ name: 'Config/state root',
851
+ status: 'pass',
852
+ message: `${stranded.target}${stranded.relocated ? ' (from CHROXY_CONFIG_DIR)' : ''}`
853
+ + (acked > 0
854
+ ? ` — ${acked} state ${acked === 1 ? 'entry' : 'entries'} at ${stranded.source} acknowledged (chroxy config-dir ack)`
855
+ : ''),
856
+ }
857
+ }
858
+ // Judged on the RAW detection, not the acknowledgement-filtered one: an
859
+ // acknowledged config.json is still absent from the root the daemon reads,
860
+ // so "run 'chroxy init'" would still be the wrong advice for a missing
861
+ // Config (#7244 — an acknowledgement quiets a warning, not a diagnosis).
862
+ if (raw.relocated && !raw.unreadable && raw.highConsequence.includes('config.json')) {
863
+ configCheck = {
864
+ name: 'Config',
865
+ status: 'fail',
866
+ message: `Not found at ${configPath('config.json')} — it is still at `
867
+ + `${join(raw.source, 'config.json')}. Do NOT run 'chroxy init' `
868
+ + `(it mints a fresh token and forces every device to re-pair) — `
869
+ + `run 'chroxy config-dir migrate' instead`,
870
+ }
871
+ }
872
+ } catch (err) {
873
+ strandedCheck = { name: 'Config/state root', status: 'warn', message: `Check failed: ${err.message}` }
874
+ }
875
+
876
+ // 5. Provider-specific checks. Each configured provider contributes its
372
877
  // own binary and credential checks. Providers not in the user's config
373
878
  // are skipped entirely — a Gemini-only install does NOT fail because
374
879
  // `claude` is missing (#2951).
375
- const resolvedProviders = resolveProviders({ providers, configProvider })
880
+ const resolvedProviders = resolveProviders({ providers, parsedConfig })
376
881
  for (const providerName of resolvedProviders) {
377
- const providerChecks = checkProvider(providerName)
882
+ const providerChecks = checkProvider(providerName, { platform, provenance: provenanceOptions, verifyProvenance })
378
883
  for (const c of providerChecks) checks.push(c)
379
884
  }
380
885
 
381
886
  // 5. Config check — appended after provider checks so per-provider
382
887
  // sections group together in the output report.
383
888
  checks.push(configCheck)
889
+ // #7240 — immediately after Config: the root is the context that explains it.
890
+ if (strandedCheck) checks.push(strandedCheck)
384
891
 
385
892
  // Credential storage (#6236). Surface WHERE the API token + credentials
386
893
  // actually live and whether the OS keychain is healthy — the #6235 fallback to
@@ -400,6 +907,16 @@ export async function runDoctorChecks({ port, providers, verbose: _verbose, pkgD
400
907
  : `file fallback — ${kh.detail}`,
401
908
  })
402
909
 
910
+ if (checkUserLevelHook) {
911
+ const hookCheck = checkUserLevelChroxyHook({ settingsPath: userHookSettingsPath })
912
+ if (hookCheck) checks.push(hookCheck)
913
+ // With a test-seamed user settings path and no stranded seam, skip: the
914
+ // fallback would read the developer's real ~/.claude.
915
+ const strandedCheck = (userHookSettingsPath === undefined || strandedHookSettingsPath !== undefined)
916
+ && checkStrandedDefaultHook({ activePath: userHookSettingsPath, defaultPath: strandedHookSettingsPath })
917
+ if (strandedCheck) checks.push(strandedCheck)
918
+ }
919
+
403
920
  // 5.6 Tunnel routability (#5328 WP-5.6). For a configured NAMED tunnel, probe
404
921
  // the hostname end-to-end so a broken DNS route / down tunnel is visible here
405
922
  // rather than only as a failed remote connection later. Skipped for quick /
@@ -439,15 +956,25 @@ export async function runDoctorChecks({ port, providers, verbose: _verbose, pkgD
439
956
  status: 'pass',
440
957
  message: `Default provider '${effectiveDefault}' — ${detail}`,
441
958
  })
442
- } else {
443
- // Pre-cutover: nothing meters yet, but surface the upcoming boundary and
444
- // what the default will bill once it lands.
959
+ } else if (programmaticCreditEraEnabled()) {
960
+ // Operator declared the era but the announced instant is still ahead:
961
+ // surface the upcoming boundary and what the default will bill once it
962
+ // lands.
445
963
  const cutover = new Date(PROGRAMMATIC_CREDIT_ERA_START).toISOString().slice(0, 10)
446
964
  checks.push({
447
965
  name: 'Billing',
448
966
  status: 'pass',
449
967
  message: `Default provider '${effectiveDefault}' — ${detail}. Programmatic-credit cutover: ${cutover}.`,
450
968
  })
969
+ } else {
970
+ // Era flag off (the default): the announced 2026-06-15 cutover was paused
971
+ // and never took effect (#7333), so naming that date would announce a
972
+ // change that is not scheduled. Say nothing about it (#8278).
973
+ checks.push({
974
+ name: 'Billing',
975
+ status: 'pass',
976
+ message: `Default provider '${effectiveDefault}' — ${detail}`,
977
+ })
451
978
  }
452
979
  }
453
980
 
@@ -458,10 +985,37 @@ export async function runDoctorChecks({ port, providers, verbose: _verbose, pkgD
458
985
  // version as a measured warning instead. Only meaningful when the default
459
986
  // provider actually drives the TUI.
460
987
  if (effectiveDefault === 'claude-tui') {
461
- const tuiCheck = checkClaudeTuiCliVersion()
988
+ // #8074 review C3(c): `claudeTuiResolveBinary` is a test-only seam
989
+ // (undefined in production, so `checkClaudeTuiCliVersion` falls back to
990
+ // its own real `resolveBinary`) — it lets a test point this probe's
991
+ // resolution at a fixture, so the provenance-gate WIRING between
992
+ // `runDoctorChecks` and `checkClaudeTuiCliVersion` (mutant R2: the probe
993
+ // called with `provenance` dropped) is testable hermetically, without
994
+ // depending on whether a real `claude` binary happens to resolve on the
995
+ // machine running the suite.
996
+ const tuiCheck = checkClaudeTuiCliVersion({
997
+ provenance: provenanceOptions,
998
+ verifyProvenance,
999
+ ...(claudeTuiResolveBinary ? { resolveBinary: claudeTuiResolveBinary } : {}),
1000
+ })
462
1001
  if (tuiCheck) checks.push(tuiCheck)
463
1002
  }
464
1003
 
1004
+ // 5.7 Claude login (#8223). claude-tui always needs the subscription login;
1005
+ // claude-sdk needs it unless ANTHROPIC_API_KEY supplies the credential, so a
1006
+ // BYOK-key host is not warned about a login it does not use. `claudeLoginDeps`
1007
+ // is the test seam (exec / resolver / env); production passes nothing.
1008
+ const needsClaudeLogin = resolvedProviders.includes('claude-tui')
1009
+ || (resolvedProviders.includes('claude-sdk') && !process.env.ANTHROPIC_API_KEY)
1010
+ if (needsClaudeLogin) {
1011
+ const loginCheck = checkClaudeLogin({
1012
+ provenance: provenanceOptions,
1013
+ verifyProvenance,
1014
+ ...claudeLoginDeps,
1015
+ })
1016
+ if (loginCheck) checks.push(loginCheck)
1017
+ }
1018
+
465
1019
  // 6. Dependencies
466
1020
  // Resolve deps relative to the server package, not process.cwd() — Tauri
467
1021
  // launches the server with cwd='/' under launchd, which would always
@@ -508,7 +1062,10 @@ export async function runDoctorChecks({ port, providers, verbose: _verbose, pkgD
508
1062
 
509
1063
  // 7. Port availability
510
1064
  const checkPort = port || 8765
511
- try {
1065
+ if (portProblem) {
1066
+ // A non-integer / out-of-range port must not reach listen(), which treats a string as a pipe path.
1067
+ checks.push({ name: 'Port', status: 'fail', message: portProblem })
1068
+ } else try {
512
1069
  await checkPortAvailable(checkPort)
513
1070
  checks.push({ name: 'Port', status: 'pass', message: `${checkPort} is available` })
514
1071
  } catch {
@@ -527,9 +1084,16 @@ export async function runDoctorChecks({ port, providers, verbose: _verbose, pkgD
527
1084
  * bad config is reported rather than silently ignored.
528
1085
  *
529
1086
  * @param {string} providerName
1087
+ * @param {object} [opts]
1088
+ * @param {string} [opts.platform] - defaults to `process.platform`; injectable
1089
+ * for tests exercising the `requiresDirectExec` shim refusal (#7986 review S2)
1090
+ * @param {{ mode: string, signatureGate: boolean, ledger: object|null }|null} [opts.provenance]
1091
+ * - #8041: opt-in provenance options (`buildBinaryProvenanceOptions`); forwarded
1092
+ * to `checkBinary`. null (the default) skips the gate entirely.
1093
+ * @param {Function} [opts.verifyProvenance] - provenance checker (injected in tests)
530
1094
  * @returns {Array<{ name: string, status: 'pass'|'warn'|'fail', message: string, provider: string }>}
531
1095
  */
532
- function checkProvider(providerName) {
1096
+ function checkProvider(providerName, { platform = process.platform, provenance = null, verifyProvenance = defaultVerifyProvenance } = {}) {
533
1097
  let ProviderClass
534
1098
  try {
535
1099
  ProviderClass = getProvider(providerName)
@@ -552,19 +1116,59 @@ function checkProvider(providerName) {
552
1116
 
553
1117
  const out = []
554
1118
  if (spec.binary) {
555
- const bin = checkBinary(spec.binary.name, spec.binary.args || ['--version'], {
556
- parseVersion: spec.binary.parseVersion || ((out) => out.trim().split('\n')[0]),
557
- required: true,
558
- candidates: spec.binary.candidates || [],
559
- installHint: spec.binary.installHint || `install ${spec.binary.name}`,
560
- // #3953: providers may declare a minimum binary version (e.g.
561
- // claude-channel needs `claude` ≥ 2.1.80 for the --channels MCP
562
- // transport). checkBinary parses the leading semver out of the
563
- // version output and fails when it's below the floor.
564
- minVersion: spec.binary.minVersion || null,
565
- })
566
- bin.provider = providerName
567
- out.push(bin)
1119
+ // #7986 review S2: a provider that declares `requiresDirectExec: true`
1120
+ // (the Agent SDK spawns its binary with no shell) can never run a
1121
+ // Windows npm shim (`claude.cmd`/`claude.bat`) — `chroxy start`'s own
1122
+ // preflight refuses it via ProviderBinaryUnsupportedError, but `doctor`
1123
+ // runs its OWN binary check (checkBinary, below) rather than
1124
+ // runProviderPreflight, so it needs the same refusal or it would report
1125
+ // a shim as a healthy "pass". Checked BEFORE the exec-for-version probe:
1126
+ // resolve the exact path the real spawn would use (the provider's live
1127
+ // `resolvedBinary` when it exposes one, else a fresh candidate resolve —
1128
+ // same preference order runProviderPreflight uses) and fail the row
1129
+ // outright when that path is a shell shim, without ever exec'ing it.
1130
+ let shimResolvedPath = null
1131
+ if (spec.binary.requiresDirectExec === true) {
1132
+ // Same guard runProviderPreflight uses: a subclass getter may throw.
1133
+ try {
1134
+ shimResolvedPath = ProviderClass.resolvedBinary
1135
+ } catch { /* fall through to a fresh candidate resolve */ }
1136
+ if (typeof shimResolvedPath !== 'string' || shimResolvedPath.length === 0) {
1137
+ shimResolvedPath = resolveBinary(spec.binary.name, spec.binary.candidates || [])
1138
+ }
1139
+ }
1140
+ if (shimResolvedPath !== null && isShellShim(shimResolvedPath, platform)) {
1141
+ out.push({
1142
+ name: spec.binary.name,
1143
+ status: 'fail',
1144
+ message: `${shimResolvedPath} — the ${spec.label || providerName} provider spawns ${spec.binary.name} directly without a shell, so it needs the native executable (for claude, \`claude.exe\` from the native installer), not an npm shim`,
1145
+ provider: providerName,
1146
+ })
1147
+ } else {
1148
+ const bin = checkBinary(spec.binary.name, spec.binary.args || ['--version'], {
1149
+ parseVersion: spec.binary.parseVersion || ((out) => out.trim().split('\n')[0]),
1150
+ required: true,
1151
+ candidates: spec.binary.candidates || [],
1152
+ installHint: spec.binary.installHint || `install ${spec.binary.name}`,
1153
+ // #3953: providers may declare a minimum binary version (e.g.
1154
+ // claude-channel needs `claude` ≥ 2.1.80 for the --channels MCP
1155
+ // transport). checkBinary parses the leading semver out of the
1156
+ // version output and fails when it's below the floor. The field may be
1157
+ // a thunk (claude-sdk derives its floor from the SDK, #7986), so it is
1158
+ // resolved through the same helper preflight uses, never read raw.
1159
+ minVersion: resolveDeclaredMinVersion(spec.binary.minVersion),
1160
+ // #8031: a soft, advisory floor — below it downgrades to `warn`
1161
+ // (never blocks server startup), same resolve helper as minVersion.
1162
+ recommendedVersion: resolveDeclaredMinVersion(spec.binary.recommendedVersion),
1163
+ updateHint: spec.binary.updateHint,
1164
+ // #8041: opt-in provenance gate, forwarded straight through to
1165
+ // checkBinary — see its docblock for the gate's shape.
1166
+ provenance,
1167
+ verifyProvenance,
1168
+ })
1169
+ bin.provider = providerName
1170
+ out.push(bin)
1171
+ }
568
1172
  }
569
1173
 
570
1174
  if (spec.credentials && Array.isArray(spec.credentials.envVars) && spec.credentials.envVars.length > 0) {
@@ -598,9 +1202,36 @@ function checkProvider(providerName) {
598
1202
  * on PATH — important for GUI-launched processes (e.g. Tauri) whose
599
1203
  * inherited PATH excludes user-local install dirs.
600
1204
  *
1205
+ * #8041: `provenance` is the opt-in provenance options bag
1206
+ * (`buildBinaryProvenanceOptions`, utils/preflight.js) — null (the default)
1207
+ * skips the gate entirely, byte-identical to pre-#8041 behaviour. When
1208
+ * supplied and enabled, the SAME `verifyProvenance` (utils/verify-provenance.js)
1209
+ * the daemon's `runProviderPreflight` and the tunnel adapter's
1210
+ * `_verifyCloudflaredProvenance` both call is run against `resolved`, BEFORE
1211
+ * the version-probe exec below: a `block`-mode hash mismatch or failed
1212
+ * signature gate returns a `fail` check and the binary is NEVER exec'd. A
1213
+ * `warn`-mode (or unverifiable-but-allowed) issue is logged and the check
1214
+ * proceeds to exec as normal.
1215
+ *
601
1216
  * Exported for tests — callers in production should use `runDoctorChecks`.
602
1217
  */
603
- export function checkBinary(name, args, { parseVersion, required, installHint, candidates = [], minVersion = null, verify = defaultVerifyBinary }) {
1218
+ export function checkBinary(name, args, {
1219
+ parseVersion, required, installHint, candidates = [], minVersion = null,
1220
+ recommendedVersion = null, updateHint = null, verify = defaultVerifyBinary,
1221
+ provenance = null, verifyProvenance = defaultVerifyProvenance,
1222
+ }) {
1223
+ // #8074 review N3: this re-resolves via `resolveBinary(name, candidates)`
1224
+ // rather than preferring `ProviderClass.resolvedBinary` the way
1225
+ // `runProviderPreflight` (and `checkProvider`'s own shim check, just above
1226
+ // in this file) do. That is a live parity ASSUMPTION, not a proof: every
1227
+ // provider's `resolvedBinary` getter today is `resolveBinary(spec.binary.name,
1228
+ // spec.binary.candidates)` — the identical call — so the two can't diverge
1229
+ // currently. If a provider ever overrides `resolvedBinary` with something
1230
+ // that does NOT reduce to that same call (e.g. a live, already-spawned
1231
+ // process's actual path), this check and the real spawn could gate/probe
1232
+ // different paths. Passing the pre-resolved path through would make that
1233
+ // parity structural instead of assumed; left as a comment (optional per
1234
+ // review) since no current provider does this.
604
1235
  const resolved = resolveBinary(name, candidates)
605
1236
  // #6708 — integrity gate BEFORE we try to exec for a version. A macOS
606
1237
  // Gatekeeper-quarantined binary keeps its X bit, and a present-but-non-
@@ -615,13 +1246,73 @@ export function checkBinary(name, args, { parseVersion, required, installHint, c
615
1246
  const { message } = describeBinaryHealth(health, { binary: name, installHint })
616
1247
  return { name, status: required ? 'fail' : 'warn', message }
617
1248
  }
1249
+ // #8041 — opt-in provenance gate, on the SAME healthy `resolved` path,
1250
+ // BEFORE the version-probe exec below. Fail-safe: a `block`-mode hash
1251
+ // mismatch or a failed signature gate reports `fail` here and returns
1252
+ // immediately — the try block below (the only exec in this function) never
1253
+ // runs. Always a hard `fail` (never downgraded by `required`) — see
1254
+ // `provenanceBlockedCheck`'s docblock.
1255
+ //
1256
+ // #8074 review C2: the gate must never run on a path `verify()` didn't
1257
+ // confirm healthy (i.e. `!health.ok` — NOT_FOUND, since QUARANTINED/
1258
+ // NOT_EXECUTABLE already returned above). `verifyProvenance`'s contract
1259
+ // assumes an otherwise-healthy, absolute, resolved path — the SAME
1260
+ // precondition `runProviderPreflight` and the tunnel adapter's
1261
+ // `_verifyCloudflaredProvenance` already honor ("provenance must not mask
1262
+ // 'cloudflared not installed'"). Skipping this check meant a bare,
1263
+ // unresolved name (`resolveBinary` returns the bare `name` itself when
1264
+ // nothing matched) got hashed relative to the CURRENT WORKING DIRECTORY —
1265
+ // mislabeling a genuinely missing binary as a provenance failure in block
1266
+ // mode ("provenance unreadable" instead of "Not found"), and in warn mode
1267
+ // could TOFU-pin a same-named file that happens to sit in cwd under that
1268
+ // bare, relative key — a path the real exec never runs, since its OWN
1269
+ // PATH lookup resolves independently. So: report the ordinary "Not found"
1270
+ // failure immediately, exactly as the exec's own catch block would below,
1271
+ // without ever calling `verifyProvenance` or attempting the exec.
1272
+ if (provenance && !health.ok) {
1273
+ return { name, status: required ? 'fail' : 'warn', message: `Not found — ${installHint}` }
1274
+ }
1275
+ // #8074 review S1: a warn-mode (or unverifiable-but-allowed) provenance
1276
+ // issue used to ONLY log — the doctor row itself stayed `pass`, so `chroxy
1277
+ // doctor`/`chroxy start` printed a clean "[ OK ]" for a binary whose
1278
+ // provenance just flagged an issue. `provenanceAdvisory` carries that note
1279
+ // through to the row built below (the check still execs normally and
1280
+ // reports the real version — warn mode is "surfaced but allowed", not
1281
+ // "skip the probe", matching every other warn-mode consumer of this gate)
1282
+ // rather than short-circuiting before the exec. `server-cmd.js` only
1283
+ // filters on `status === 'fail'`, so `chroxy start` still only stops on a
1284
+ // `block`-mode refusal above — this never blocks startup.
1285
+ let provenanceAdvisory = null
1286
+ if (provenance) {
1287
+ const verdict = verifyProvenance({
1288
+ resolvedPath: health.path,
1289
+ mode: provenance.mode,
1290
+ signatureGate: provenance.signatureGate === true,
1291
+ ledger: provenance.ledger || null,
1292
+ })
1293
+ if (verdict.blocked) {
1294
+ return provenanceBlockedCheck(name, health.path, verdict)
1295
+ }
1296
+ if (
1297
+ verdict.status === PROVENANCE_STATUS.HASH_MISMATCH
1298
+ || verdict.status === PROVENANCE_STATUS.SIGNATURE_INVALID
1299
+ || verdict.status === PROVENANCE_STATUS.UNREADABLE
1300
+ ) {
1301
+ log.warn(`Binary "${name}" provenance ${verdict.status}: ${verdict.message || ''} (allowed — mode=${provenance.mode})`)
1302
+ provenanceAdvisory = `provenance ${verdict.status}: ${verdict.message || 'unverifiable'}`
1303
+ + `${verdict.remediation ? ` — ${verdict.remediation}` : ''} (allowed — mode=${provenance.mode})`
1304
+ }
1305
+ }
1306
+ // #8074 round-2 review: every version row below carries the advisory — a
1307
+ // min/recommended-version warn or fail returning first must not drop it.
1308
+ const withAdvisory = (msg) => (provenanceAdvisory ? `${msg} — ${provenanceAdvisory}` : msg)
618
1309
  try {
619
1310
  // #6484 — a resolved `.cmd` shim (npm-only Windows host) can't be spawned
620
1311
  // directly on Node 24; route it through cmd.exe via prepareSpawn. No-op for
621
1312
  // a `.exe` and on POSIX, so non-Windows binary checks are unchanged.
622
1313
  const spawnSpec = prepareSpawn(resolved, args)
623
1314
  const output = execFileSync(spawnSpec.command, spawnSpec.args, {
624
- encoding: 'utf-8', timeout: 5000, stdio: ['ignore', 'pipe', 'pipe'], ...spawnSpec.options,
1315
+ encoding: 'utf-8', timeout: 5000, stdio: ['ignore', 'pipe', 'pipe'], env: buildClaudeLaunchEnv(), ...spawnSpec.options,
625
1316
  })
626
1317
  const message = parseVersion(output)
627
1318
  // #3953: when the provider declares a minimum version, parse the
@@ -629,23 +1320,49 @@ export function checkBinary(name, args, { parseVersion, required, installHint, c
629
1320
  // and fail the check below the floor. If the version can't be parsed
630
1321
  // we don't block the user — we surface a warn so a format change in
631
1322
  // the upstream CLI doesn't hard-fail an otherwise-working install.
1323
+ // #8031: `recommendedVersion` is a SOFT floor, checked with the same
1324
+ // parsed `found` — below it downgrades to `warn` regardless of
1325
+ // `required` (a soft check never aborts `chroxy start`), never `fail`.
1326
+ let found = null
1327
+ if (minVersion || recommendedVersion) {
1328
+ found = parseLeadingSemver(message)
1329
+ }
632
1330
  if (minVersion) {
633
- const found = parseLeadingSemver(message)
634
1331
  if (found === null) {
635
1332
  return {
636
1333
  name,
637
1334
  status: 'warn',
638
- message: `${message} — could not parse version to verify ≥ ${minVersion}`,
1335
+ message: withAdvisory(`${message} — could not parse version to verify ≥ ${minVersion}`),
639
1336
  }
640
1337
  }
641
1338
  if (compareSemver(found, minVersion) < 0) {
642
1339
  return {
643
1340
  name,
644
1341
  status: required ? 'fail' : 'warn',
645
- message: `${message} — requires ${name} ≥ ${minVersion}; ${installHint}`,
1342
+ message: withAdvisory(`${message} — requires ${name} ≥ ${minVersion}; ${installHint}`),
646
1343
  }
647
1344
  }
648
1345
  }
1346
+ // Only reached once the hard floor (if any) is satisfied. When ONLY
1347
+ // `recommendedVersion` is declared and `found` couldn't be parsed, this
1348
+ // is silently skipped — an unparseable version is not itself a defect
1349
+ // for a soft, advisory check (the hard-floor branch above already owns
1350
+ // the "could not parse" warning when a min is also declared). A
1351
+ // `recommendedVersion` that is itself unparseable is ignored the same
1352
+ // way: compareSemver fails CLOSED on a malformed floor, which is right
1353
+ // for minVersion but would turn a bad advisory into a spurious warn —
1354
+ // preflight gates this check on a parsed recommended version too.
1355
+ if (recommendedVersion && found !== null && parseLeadingSemver(recommendedVersion) !== null
1356
+ && compareSemver(found, recommendedVersion) < 0) {
1357
+ return {
1358
+ name,
1359
+ status: 'warn',
1360
+ message: withAdvisory(`${message} — older than the recommended ${name} ${recommendedVersion}; ${updateHint || installHint}`),
1361
+ }
1362
+ }
1363
+ if (provenanceAdvisory) {
1364
+ return { name, status: 'warn', message: withAdvisory(message) }
1365
+ }
649
1366
  return { name, status: 'pass', message }
650
1367
  } catch (err) {
651
1368
  if (err.killed || err.signal === 'SIGTERM') {