@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
@@ -1,13 +1,145 @@
1
- import { readFile, writeFile as fsWriteFile, stat, mkdir, realpath, open } from 'fs/promises'
1
+ import { stat, mkdir, realpath } from 'fs/promises'
2
+ import { stillAuthorized } from '../connection-authority.js'
2
3
  import { constants as fsConstants } from 'fs'
3
4
  import { resolve, normalize, extname } from 'path'
4
5
  import { execFile as execFileCb } from 'child_process'
5
6
  import { promisify } from 'util'
6
- import { parseDiff } from '../diff-parser.js'
7
+ import { GET_DIFF_BASE_MAX_LENGTH } from '@chroxy/protocol'
8
+ import { parseDiff, diffFileHeaderPaths } from '../diff-parser.js'
7
9
  import { GIT } from '../git.js'
10
+ import { openNoFollow } from './open-nofollow.js'
11
+ import { createLogger } from '../logger.js'
12
+ import { isSafeArgvValue } from '../utils/argv-safety.js'
13
+ import { isPathWithin } from '../utils/path-containment.js'
14
+ import { readPinnedHandle, readContainedBytes, assertRegularHandle } from '../utils/regular-file.js'
15
+ import { unresolvablePathError, isConfigDirOrDirectChild, fileOpErrorMessage, clientSafeError, CONFIG_DIR_REFUSAL } from './common.js'
16
+
17
+ /**
18
+ * #7957 — refuse a write target that is not a regular file, on the OPENED
19
+ * handle and before any byte is written. The text reaches the client verbatim,
20
+ * so it carries no path.
21
+ */
22
+ async function refuseNonRegular(fh) {
23
+ try {
24
+ await assertRegularHandle(fh)
25
+ } catch (err) {
26
+ if (err.code === 'ENOTREG') throw clientSafeError('Not a regular file')
27
+ throw err
28
+ }
29
+ }
8
30
 
9
31
  const execFileAsync = promisify(execFileCb)
10
32
 
33
+ // #8012 — the message read_file sends when the first `realpath()` failed with
34
+ // one of these codes for a path INSIDE the project. Any other code, or any
35
+ // path outside it, gets the generic denial instead (see unresolvablePathError).
36
+ const READ_UNRESOLVABLE_REASONS = {
37
+ EACCES: 'Permission denied',
38
+ EPERM: 'Permission denied',
39
+ ENOTDIR: 'File not found',
40
+ }
41
+
42
+ // #8016 — the same, for write_file and append_memory.
43
+ const WRITE_UNRESOLVABLE_REASONS = {
44
+ EACCES: 'Permission denied',
45
+ EPERM: 'Permission denied',
46
+ ENOTDIR: 'Not a directory',
47
+ }
48
+ const log = createLogger('ws')
49
+
50
+ // getDiff reads paths out of `git diff` output (parseDiff, diffFileHeaderPaths), and
51
+ // the config-directory rule is applied to those paths. A user's or repo's git config
52
+ // can change how a changed file is printed, so every `git diff` call pins what it
53
+ // reads. Settings not named here are not pinned.
54
+ // --src-prefix=a/ --dst-prefix=b/ the `a/` / `b/` header form; beats diff.noprefix,
55
+ // diff.mnemonicPrefix, diff.srcPrefix, diff.dstPrefix
56
+ // -c diff.relative=false paths from the repository root, not the cwd
57
+ // --no-ext-diff an external diff driver (diff.external, or a
58
+ // `diff=` attribute with diff.<name>.command) prints
59
+ // no `diff --git` header, so its output would land in
60
+ // the previous entry
61
+ // --no-color colour escapes start every header line
62
+ // Checked on git 2.55.0: each prefix key alone and all four together still print
63
+ // `a/` / `b/`; diff.relative=true from a subdirectory prints cwd-relative paths and
64
+ // drops files outside it, and `-c diff.relative=false` restores repo-root paths.
65
+ // Relative output is pinned with `-c` rather than `--no-relative` because the repo
66
+ // states no minimum git version and `--no-relative` needs git 2.28; a `-c` setting
67
+ // is accepted by every git (an unknown key is ignored). `-c` must come BEFORE the
68
+ // subcommand, so it is a separate piece of argv from the options after it.
69
+ const DIFF_PIN_CONFIG = ['-c', 'diff.relative=false']
70
+ const DIFF_HEADER_ARGS = ['--src-prefix=a/', '--dst-prefix=b/', '--no-ext-diff', '--no-color']
71
+ // Limits a diff to the directory git runs in (the session cwd). A fixed literal,
72
+ // never client input.
73
+ const DIFF_CWD_PATHSPEC = ['--', '.']
74
+
75
+ /**
76
+ * The supported authored layout has a thin CLAUDE.md importing cwd/AGENTS.md.
77
+ * Recognize only that entire adapter, never turn arbitrary @imports into writes.
78
+ * A bounded, symlink-refusing read cannot follow an external adapter or wait on
79
+ * a special file. Legacy project files (including in-bounds links) retain their
80
+ * existing append destination and the validation below.
81
+ */
82
+ async function projectMemoryFilename(cwdReal) {
83
+ let fh
84
+ try {
85
+ fh = await openNoFollow(resolve(cwdReal, 'CLAUDE.md'), fsConstants.O_RDONLY)
86
+ const st = await fh.stat()
87
+ if (!st.isFile() || st.size > 64) return 'CLAUDE.md'
88
+ const buffer = Buffer.alloc(65)
89
+ let length = 0
90
+ while (length < buffer.length) {
91
+ const { bytesRead } = await fh.read(buffer, length, buffer.length - length, length)
92
+ if (!bytesRead) break
93
+ length += bytesRead
94
+ }
95
+ const content = buffer.subarray(0, length).toString('utf8').trim()
96
+ return content === '@AGENTS.md' || content === '@./AGENTS.md' ? 'AGENTS.md' : 'CLAUDE.md'
97
+ } catch (err) {
98
+ // Missing legacy files are created by append; existing links are validated
99
+ // by the unchanged realpath/containment pipeline rather than read here.
100
+ if (err.code === 'ENOENT' || err.code === 'ELOOP') return 'CLAUDE.md'
101
+ throw err
102
+ } finally {
103
+ await fh?.close()
104
+ }
105
+ }
106
+
107
+ /**
108
+ * Longest `base` getDiff will hand to git. A revision is short — a full OID is
109
+ * 40 characters and a ref name far less — so this rejects nothing legitimate,
110
+ * and it bounds what could otherwise be spent per request: two `rev-parse`
111
+ * argvs, plus whatever git echoes back into an error message.
112
+ *
113
+ * #7870 — imported rather than redeclared: `GetDiffSchema` (packages/protocol)
114
+ * now rejects a `base` over this same length AT THE WIRE, before getDiff ever
115
+ * runs. This constant is the single source both layers read, so the two
116
+ * cannot drift the way a hand-copied number could. This gate stays anyway —
117
+ * it is the server's OWN, independent defense-in-depth boundary, correct even
118
+ * for a future caller that reaches getDiff by a path that skips schema
119
+ * validation (see packages/server/tests/ws-server-file-ops.test.js's direct
120
+ * `createReaderOps` calls, which exercise it without going over the wire).
121
+ */
122
+ const MAX_DIFF_BASE_LENGTH = GET_DIFF_BASE_MAX_LENGTH
123
+
124
+ /** Longest error detail written to the server log in one line (#7298). */
125
+ const MAX_LOGGED_ERROR_LENGTH = 500
126
+
127
+ /**
128
+ * Bound one error detail before it reaches the log.
129
+ *
130
+ * An `execFile` rejection's `message` carries the whole command line — which
131
+ * includes the client's own `base` — followed by the child's stderr, and
132
+ * neither is bounded by anything the caller controls. Logging it raw turns an
133
+ * oversized input into log amplification, so the log gets a prefix and the
134
+ * original length instead.
135
+ */
136
+ export function truncateForLog(message) {
137
+ const text = String(message ?? '')
138
+ return text.length > MAX_LOGGED_ERROR_LENGTH
139
+ ? `${text.slice(0, MAX_LOGGED_ERROR_LENGTH)}… (truncated, ${text.length} chars)`
140
+ : text
141
+ }
142
+
11
143
  /** Image extensions to MIME type mapping (module-level to avoid per-call allocation) */
12
144
  const IMAGE_MIME = {
13
145
  png: 'image/png',
@@ -25,9 +157,15 @@ const IMAGE_MIME = {
25
157
  * @param {Function} sendFn - (ws, message) => void
26
158
  * @param {Function} resolveSessionCwd - shared CWD resolver
27
159
  * @param {Function} validatePathWithinCwd - shared path validator
160
+ * @param {Function} [execImpl] - injectable promisified execFile seam (defaults to the
161
+ * real one; matches createGitOps' 5th arg, #7871). Every git invocation inside
162
+ * getDiff routes through this — `rev-parse --git-dir`, both `rev-parse --verify`
163
+ * calls, both `diff` calls, and `ls-files` — so the preflight failure branch
164
+ * (and the exit-128 classification, #7877) can be driven by tests without a
165
+ * real non-repo/permission-denied/timeout condition on the host.
28
166
  * @returns {Object} reader operation methods
29
167
  */
30
- export function createReaderOps(sendFn, resolveSessionCwd, validatePathWithinCwd) {
168
+ export function createReaderOps(sendFn, resolveSessionCwd, validatePathWithinCwd, execImpl = execFileAsync) {
31
169
 
32
170
  /**
33
171
  * Read file content at a given path within the session CWD.
@@ -84,9 +222,27 @@ export function createReaderOps(sendFn, resolveSessionCwd, validatePathWithinCwd
84
222
  // Before surfacing "File not found", enforce workspace boundary.
85
223
  // A nonexistent path outside the root must return Access denied to
86
224
  // avoid leaking filesystem existence information as an oracle.
87
- const cwdReal = await resolveSessionCwd(sessionCwd)
88
- const lexicallyWithinCwd = absPath.startsWith(cwdReal + '/') || absPath === cwdReal
89
- if (!lexicallyWithinCwd) {
225
+ //
226
+ // #8000 — decide it with the SAME canonical check the existing-file
227
+ // path uses below: realpath the deepest existing ancestor, compare
228
+ // against the realpath'd cwd. This used to be a LEXICAL compare of
229
+ // `absPath` (built from the cwd as given) against the realpath'd cwd,
230
+ // which was wrong both ways:
231
+ // - a cwd spelled non-canonically (through a symlink on POSIX, as an
232
+ // 8.3 short name on Windows) made a missing file INSIDE the
233
+ // project answer "Access denied";
234
+ // - `<cwd>/link-to-outside/missing` looked lexically inside and
235
+ // answered "File not found" — an existence oracle for the
236
+ // outside directory, through the link.
237
+ // A check that cannot be answered (ELOOP, EACCES on an ancestor)
238
+ // denies: "could not check" must never read as "not found".
239
+ let withinCwd = false
240
+ try {
241
+ ({ valid: withinCwd } = await validatePathWithinCwd(absPath, sessionCwd))
242
+ } catch {
243
+ withinCwd = false
244
+ }
245
+ if (!withinCwd) {
90
246
  send({
91
247
  type: 'file_content',
92
248
  path: absPath,
@@ -98,6 +254,24 @@ export function createReaderOps(sendFn, resolveSessionCwd, validatePathWithinCwd
98
254
  })
99
255
  return
100
256
  }
257
+ // Files directly in the config directory are daemon-managed state, so
258
+ // reads follow the same rule as writes: a missing name there answers
259
+ // the refusal an existing one does, never "File not found". Only
260
+ // reached once the path is known to be inside the project, where the
261
+ // deepest-ancestor walk has already resolved this same path; a check
262
+ // that cannot be answered denies, as it does for writes.
263
+ if (await isConfigDirOrDirectChild(absPath)) {
264
+ send({
265
+ type: 'file_content',
266
+ path: absPath,
267
+ content: null,
268
+ language: null,
269
+ size: null,
270
+ truncated: false,
271
+ error: CONFIG_DIR_REFUSAL,
272
+ })
273
+ return
274
+ }
101
275
  send({
102
276
  type: 'file_content',
103
277
  path: absPath,
@@ -109,7 +283,26 @@ export function createReaderOps(sendFn, resolveSessionCwd, validatePathWithinCwd
109
283
  })
110
284
  return
111
285
  }
112
- throw err
286
+ // #8012 — any OTHER failure (EACCES, EPERM, ENOTDIR, ELOOP, …) used to
287
+ // skip the containment check and reach the outer catch, which sent
288
+ // "Permission denied" for EACCES and Node's raw message — server path
289
+ // included — for the rest. For a path outside the project that told
290
+ // "blocked" apart from "readable" and "missing". Outside, or when the
291
+ // check cannot be answered (a cycle), the answer is now the same denial
292
+ // every outside path gets; only an in-project path keeps a specific
293
+ // message, and never the raw text.
294
+ const cwdReal = await resolveSessionCwd(sessionCwd).catch(() => null)
295
+ send({
296
+ type: 'file_content',
297
+ path: absPath,
298
+ content: null,
299
+ language: null,
300
+ size: null,
301
+ truncated: false,
302
+ error: await unresolvablePathError(err, absPath, cwdReal, READ_UNRESOLVABLE_REASONS,
303
+ 'Access denied: file reading is restricted to the project directory'),
304
+ })
305
+ return
113
306
  }
114
307
 
115
308
  const { valid } = await validatePathWithinCwd(resolvedAbsPath, sessionCwd)
@@ -126,6 +319,24 @@ export function createReaderOps(sendFn, resolveSessionCwd, validatePathWithinCwd
126
319
  return
127
320
  }
128
321
 
322
+ // The config directory itself and any file directly in it are
323
+ // daemon-managed state, so the file viewer treats reads the same way as
324
+ // writes. Checked on the resolved path (a symlink into the config directory
325
+ // is judged by where it lands) and BEFORE `stat`, so no size or type of a
326
+ // refused file is revealed.
327
+ if (await isConfigDirOrDirectChild(resolvedAbsPath)) {
328
+ send({
329
+ type: 'file_content',
330
+ path: absPath,
331
+ content: null,
332
+ language: null,
333
+ size: null,
334
+ truncated: false,
335
+ error: CONFIG_DIR_REFUSAL,
336
+ })
337
+ return
338
+ }
339
+
129
340
  const fileStat = await stat(resolvedAbsPath)
130
341
  if (fileStat.isDirectory()) {
131
342
  send({
@@ -153,15 +364,36 @@ export function createReaderOps(sendFn, resolveSessionCwd, validatePathWithinCwd
153
364
  return
154
365
  }
155
366
 
156
- // Open with O_NOFOLLOW to close the post-validation TOCTOU window:
157
- // if the file at resolvedAbsPath was replaced with a symlink between
158
- // validatePathWithinCwd() and this open(), the kernel rejects it (ELOOP).
367
+ // openNoFollow closes the post-validation TOCTOU window: if the file at
368
+ // resolvedAbsPath was replaced with a symlink between
369
+ // validatePathWithinCwd() and this open, it is rejected with ELOOP — by
370
+ // the kernel on POSIX (O_NOFOLLOW), by an lstat + fd-identity check on
371
+ // win32, where O_NOFOLLOW does not exist and the bare flag silently
372
+ // no-opped until #7280. See open-nofollow.js for the exact per-platform
373
+ // guarantee and the race it cannot close.
159
374
  let buf
160
375
  {
161
376
  let fh
162
377
  try {
163
- fh = await open(resolvedAbsPath, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW)
164
- buf = await fh.readFile()
378
+ fh = await openNoFollow(resolvedAbsPath, fsConstants.O_RDONLY)
379
+ // #7938 — `fileStat` above was taken BEFORE this open, so it can't
380
+ // see a FIFO/device swapped in during the TOCTOU window between
381
+ // that stat and this open. openNoFollow's O_NONBLOCK keeps the
382
+ // open from hanging on a planted FIFO with no writer, but the
383
+ // content must still not be read from anything but a regular file
384
+ // — re-check on the OPENED fd, which can't be raced the same way.
385
+ // The opened object must be the file this name denotes inside the
386
+ // project (parents included), within the size cap, and is read from
387
+ // the descriptor in bounded steps (utils/regular-file.js).
388
+ try {
389
+ buf = await readPinnedHandle(fh, resolvedAbsPath, await resolveSessionCwd(sessionCwd), 512 * 1024)
390
+ } catch (pinErr) {
391
+ // No path in the text: this reaches the client verbatim.
392
+ if (pinErr.code === 'ENOTREG') throw clientSafeError('Not a regular file')
393
+ if (pinErr.code === 'EFBIG') throw clientSafeError('File too large (max 512KB)')
394
+ if (pinErr.code === 'EACCES') throw Object.assign(new Error('pinned'), { code: 'ELOOP' })
395
+ throw pinErr
396
+ }
165
397
  } catch (openErr) {
166
398
  if (openErr.code === 'ELOOP') {
167
399
  // Symlink appeared at the canonical path after validation — reject
@@ -233,10 +465,8 @@ export function createReaderOps(sendFn, resolveSessionCwd, validatePathWithinCwd
233
465
  error: null,
234
466
  })
235
467
  } catch (err) {
236
- let errorMessage
237
- if (err.code === 'ENOENT') errorMessage = 'File not found'
238
- else if (err.code === 'EACCES') errorMessage = 'Permission denied'
239
- else errorMessage = err.message || 'Unknown error'
468
+ log.error(`read_file failed: ${truncateForLog(err.message)}`)
469
+ const errorMessage = fileOpErrorMessage(err, 'Operation failed', { ENOENT: 'File not found' })
240
470
 
241
471
  send({
242
472
  type: 'file_content',
@@ -251,7 +481,7 @@ export function createReaderOps(sendFn, resolveSessionCwd, validatePathWithinCwd
251
481
  }
252
482
 
253
483
  /** Write file content at a given path within the session CWD */
254
- async function writeFileContent(ws, requestedPath, content, sessionCwd) {
484
+ async function writeFileContent(ws, requestedPath, content, sessionCwd, isAuthorized) {
255
485
  if (!sessionCwd) {
256
486
  sendFn(ws, {
257
487
  type: 'write_file_result',
@@ -292,7 +522,8 @@ export function createReaderOps(sendFn, resolveSessionCwd, validatePathWithinCwd
292
522
  const absInCwd = normalize(resolve(cwdReal, requestedPath.trim()))
293
523
 
294
524
  // Determine whether the target file already exists so we can choose
295
- // between O_NOFOLLOW (existing) and parent-validated creation (new).
525
+ // between a symlink-refusing truncate (existing) and parent-validated
526
+ // creation (new).
296
527
  let resolvedTarget
297
528
  let fileExists = false
298
529
  try {
@@ -304,49 +535,68 @@ export function createReaderOps(sendFn, resolveSessionCwd, validatePathWithinCwd
304
535
  // Use the lexical path for the new-file case.
305
536
  resolvedTarget = absInCwd
306
537
  } else {
307
- throw err
308
- }
309
- }
310
-
311
- if (fileExists) {
312
- // Existing file: validate the resolved (symlink-followed) path
313
- const { valid: writeValid } = await validatePathWithinCwd(resolvedTarget, sessionCwd)
314
- if (!writeValid) {
315
- sendFn(ws, {
316
- type: 'write_file_result',
317
- path: requestedPath,
318
- error: 'Access denied: file writing is restricted to the project directory',
319
- })
320
- return
321
- }
322
- } else {
323
- // New file: validate the lexical path is within CWD
324
- const { valid: writeValid } = await validatePathWithinCwd(absInCwd, sessionCwd)
325
- if (!writeValid) {
538
+ // #8016 — any other failure used to reach the outer catch, which
539
+ // answered "Permission denied" (EACCES) or the raw Node message,
540
+ // server path included, even for a target outside the project.
326
541
  sendFn(ws, {
327
542
  type: 'write_file_result',
328
543
  path: requestedPath,
329
- error: 'Access denied: file writing is restricted to the project directory',
544
+ error: await unresolvablePathError(err, absInCwd, cwdReal, WRITE_UNRESOLVABLE_REASONS,
545
+ 'Access denied: file writing is restricted to the project directory'),
330
546
  })
331
547
  return
332
548
  }
333
549
  }
550
+
551
+ // Existing file: validate the resolved (symlink-followed) path. New file:
552
+ // validate the lexical path. A check that cannot be answered (a
553
+ // self-referential link's ELOOP, the depth ceiling, a file swapped
554
+ // between the two resolutions) denies rather than sending the helper's
555
+ // own text (#8016).
556
+ let writeValid = false
557
+ try {
558
+ ({ valid: writeValid } = await validatePathWithinCwd(fileExists ? resolvedTarget : absInCwd, sessionCwd))
559
+ } catch {
560
+ writeValid = false
561
+ }
562
+ if (!writeValid) {
563
+ sendFn(ws, {
564
+ type: 'write_file_result',
565
+ path: requestedPath,
566
+ error: 'Access denied: file writing is restricted to the project directory',
567
+ })
568
+ return
569
+ }
334
570
  absPath = fileExists ? resolvedTarget : absInCwd
335
571
 
572
+ // Generic file writes refuse the daemon's config directory, so the deploy
573
+ // control files can only be written through `daemon_update_action`. This runs
574
+ // BEFORE the mkdir below: a refused write must not create anything either.
575
+ if (await isConfigDirOrDirectChild(absPath)) {
576
+ sendFn(ws, { type: 'write_file_result', path: requestedPath, error: CONFIG_DIR_REFUSAL })
577
+ return
578
+ }
579
+
580
+ // Everything above waited; the requesting connection may have ended.
581
+ if (!stillAuthorized(isAuthorized)) return
582
+
336
583
  // Create parent directories if needed
337
584
  await mkdir(resolve(absPath, '..'), { recursive: true })
585
+ if (!stillAuthorized(isAuthorized)) return
338
586
 
339
- // Write the file using O_NOFOLLOW to close the post-validation TOCTOU
340
- // window: if a symlink is swapped in at absPath between validation and
341
- // this open(), the kernel rejects it with ELOOP.
587
+ // Write the file through openNoFollow to close the post-validation TOCTOU
588
+ // window: a symlink swapped in at absPath between validation and this
589
+ // open is rejected with ELOOP on every platform (#7280 — the bare
590
+ // O_NOFOLLOW flag this used to pass is undefined on win32 and ORed to 0).
342
591
  const data = Buffer.from(content || '', 'utf-8')
343
592
  {
344
593
  let fh
345
594
  try {
346
595
  const flags = fileExists
347
- ? fsConstants.O_WRONLY | fsConstants.O_NOFOLLOW | fsConstants.O_TRUNC
348
- : fsConstants.O_WRONLY | fsConstants.O_NOFOLLOW | fsConstants.O_CREAT | fsConstants.O_EXCL
349
- fh = await open(absPath, flags, 0o666)
596
+ ? fsConstants.O_WRONLY | fsConstants.O_TRUNC
597
+ : fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL
598
+ fh = await openNoFollow(absPath, flags, 0o666)
599
+ await refuseNonRegular(fh)
350
600
  await fh.writeFile(data)
351
601
  } catch (openErr) {
352
602
  if (openErr.code === 'ELOOP') {
@@ -362,7 +612,8 @@ export function createReaderOps(sendFn, resolveSessionCwd, validatePathWithinCwd
362
612
  // Race: file was created between our existence check and O_EXCL open.
363
613
  // Retry once using the existing-file path (O_TRUNC without O_EXCL).
364
614
  try {
365
- fh = await open(absPath, fsConstants.O_WRONLY | fsConstants.O_NOFOLLOW | fsConstants.O_TRUNC, 0o666)
615
+ fh = await openNoFollow(absPath, fsConstants.O_WRONLY | fsConstants.O_TRUNC, 0o666)
616
+ await refuseNonRegular(fh)
366
617
  await fh.writeFile(data)
367
618
  } catch (retryErr) {
368
619
  if (retryErr.code === 'ELOOP') {
@@ -389,9 +640,8 @@ export function createReaderOps(sendFn, resolveSessionCwd, validatePathWithinCwd
389
640
  error: null,
390
641
  })
391
642
  } catch (err) {
392
- let errorMessage
393
- if (err.code === 'EACCES') errorMessage = 'Permission denied'
394
- else errorMessage = err.message || 'Unknown error'
643
+ log.error(`write_file failed: ${truncateForLog(err.message)}`)
644
+ const errorMessage = fileOpErrorMessage(err)
395
645
 
396
646
  sendFn(ws, {
397
647
  type: 'write_file_result',
@@ -402,14 +652,16 @@ export function createReaderOps(sendFn, resolveSessionCwd, validatePathWithinCwd
402
652
  }
403
653
 
404
654
  /**
405
- * Append a single note line to the session cwd's project CLAUDE.md, creating
406
- * the file if it doesn't exist (#6861, epic #6760).
655
+ * Append a single note line to the session cwd's project memory. Thin Claude
656
+ * adapters route to authored AGENTS.md; legacy CLAUDE.md files are created
657
+ * when absent (#6861, epic #6760).
407
658
  *
408
- * The TARGET is chosen SERVER-side (`<cwd>/CLAUDE.md`) — the client sends only
659
+ * The TARGET is chosen SERVER-side (a fixed cwd filename) — the client sends only
409
660
  * the note text, never a path — so the write is path-confined BY CONSTRUCTION.
410
661
  * validatePathWithinCwd is still run for symlink-escape defence (a CLAUDE.md
411
- * symlinked out of the workspace is rejected), and the open uses O_NOFOLLOW to
412
- * close the post-validation TOCTOU window, matching writeFileContent above.
662
+ * symlinked out of the workspace is rejected), and the open goes through
663
+ * openNoFollow to close the post-validation TOCTOU window, matching
664
+ * writeFileContent above.
413
665
  *
414
666
  * The write uses O_APPEND (+ O_CREAT): each append lands atomically at EOF, so
415
667
  * concurrent appends can't lose a line and a crash can't truncate the file —
@@ -418,7 +670,7 @@ export function createReaderOps(sendFn, resolveSessionCwd, validatePathWithinCwd
418
670
  * is needed; a race there is benign (a stray/missing separator at worst — the
419
671
  * note line itself is always written atomically and in full).
420
672
  */
421
- async function appendMemory(ws, note, sessionCwd) {
673
+ async function appendMemory(ws, note, sessionCwd, isAuthorized) {
422
674
  if (!sessionCwd) {
423
675
  sendFn(ws, { type: 'append_memory_result', path: null, created: false, error: 'Memory is not available in this mode' })
424
676
  return
@@ -438,7 +690,8 @@ export function createReaderOps(sendFn, resolveSessionCwd, validatePathWithinCwd
438
690
  let absPath = null
439
691
  try {
440
692
  const cwdReal = await resolveSessionCwd(sessionCwd)
441
- const target = normalize(resolve(cwdReal, 'CLAUDE.md'))
693
+ const filename = await projectMemoryFilename(cwdReal)
694
+ const target = normalize(resolve(cwdReal, filename))
442
695
 
443
696
  // Resolve symlinks: if CLAUDE.md already exists, validate its real path;
444
697
  // if not, validate the lexical target (still inside cwd by construction).
@@ -448,11 +701,30 @@ export function createReaderOps(sendFn, resolveSessionCwd, validatePathWithinCwd
448
701
  resolvedTarget = await realpath(target)
449
702
  fileExists = true
450
703
  } catch (err) {
451
- if (err.code === 'ENOENT') resolvedTarget = target
452
- else throw err
704
+ if (err.code === 'ENOENT') {
705
+ if (filename === 'AGENTS.md') throw clientSafeError('Authored project memory AGENTS.md is missing')
706
+ resolvedTarget = target
707
+ } else {
708
+ // #8016 — a CLAUDE.md link whose target cannot be resolved: same
709
+ // answer as a target outside the project, never the raw text.
710
+ sendFn(ws, {
711
+ type: 'append_memory_result',
712
+ path: null,
713
+ created: false,
714
+ error: await unresolvablePathError(err, target, cwdReal, WRITE_UNRESOLVABLE_REASONS,
715
+ 'Access denied: memory is restricted to the project directory'),
716
+ })
717
+ return
718
+ }
453
719
  }
454
720
 
455
- const { valid } = await validatePathWithinCwd(fileExists ? resolvedTarget : target, sessionCwd)
721
+ // A check that cannot be answered denies (#8016).
722
+ let valid = false
723
+ try {
724
+ ({ valid } = await validatePathWithinCwd(fileExists ? resolvedTarget : target, sessionCwd))
725
+ } catch {
726
+ valid = false
727
+ }
456
728
  if (!valid) {
457
729
  sendFn(ws, {
458
730
  type: 'append_memory_result',
@@ -464,6 +736,15 @@ export function createReaderOps(sendFn, resolveSessionCwd, validatePathWithinCwd
464
736
  }
465
737
  absPath = fileExists ? resolvedTarget : target
466
738
 
739
+ // Same rule as write_file: generic writes refuse the config directory.
740
+ if (await isConfigDirOrDirectChild(absPath)) {
741
+ sendFn(ws, { type: 'append_memory_result', path: null, created: false, error: CONFIG_DIR_REFUSAL })
742
+ return
743
+ }
744
+
745
+ // Everything above waited; the requesting connection may have ended.
746
+ if (!stillAuthorized(isAuthorized)) return
747
+
467
748
  // Cheap tail check: does the existing file already end with a newline? If
468
749
  // not, prepend one so the note lands on its own line. Best-effort (a race
469
750
  // only affects the separator, never the note itself).
@@ -474,7 +755,15 @@ export function createReaderOps(sendFn, resolveSessionCwd, validatePathWithinCwd
474
755
  if (st.size > 0) {
475
756
  let rfh
476
757
  try {
477
- rfh = await open(absPath, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW)
758
+ // #7938 — openNoFollow's O_NONBLOCK keeps a FIFO raced in at this
759
+ // path from hanging the open. No post-open isFile() check here,
760
+ // deliberately: the read below is a positioned read (pread), and
761
+ // pread on a FIFO fails ESPIPE and on a directory EISDIR, both
762
+ // landing in the advisory catch exactly as a refusal would. A
763
+ // check could not change any outcome (a mutation deleting one
764
+ // survived every test for that reason), and the one byte read is
765
+ // never returned to the client — it only picks the separator.
766
+ rfh = await openNoFollow(absPath, fsConstants.O_RDONLY)
478
767
  const tail = Buffer.alloc(1)
479
768
  await rfh.read(tail, 0, 1, st.size - 1)
480
769
  needsLeadingNewline = tail[0] !== 0x0a
@@ -487,19 +776,27 @@ export function createReaderOps(sendFn, resolveSessionCwd, validatePathWithinCwd
487
776
  }
488
777
  }
489
778
 
779
+ if (!stillAuthorized(isAuthorized)) return
490
780
  const data = Buffer.from((needsLeadingNewline ? '\n' : '') + line + '\n', 'utf-8')
491
781
 
492
782
  // O_APPEND: atomic append at EOF (no lost-update / truncation window).
493
- // O_CREAT (WITHOUT O_EXCL) opens-or-creates, so there is no EEXIST race to
494
- // retry — a concurrent creator just means we append instead. O_NOFOLLOW
495
- // keeps the symlink-escape defence on the final component.
783
+ // Legacy files use O_CREAT without O_EXCL, so a concurrent creator just
784
+ // means we append instead. Authored rules must still exist at the open:
785
+ // a source removed by another operation must not be recreated as a note.
786
+ // openNoFollow keeps the symlink-escape defence on the final component, on win32 as
787
+ // well as POSIX (#7280).
496
788
  {
497
789
  let fh
498
790
  try {
499
- const flags = fsConstants.O_WRONLY | fsConstants.O_APPEND | fsConstants.O_CREAT | fsConstants.O_NOFOLLOW
500
- fh = await open(absPath, flags, 0o666)
791
+ let flags = fsConstants.O_WRONLY | fsConstants.O_APPEND
792
+ if (filename !== 'AGENTS.md') flags |= fsConstants.O_CREAT
793
+ fh = await openNoFollow(absPath, flags, 0o666)
794
+ await refuseNonRegular(fh)
501
795
  await fh.writeFile(data)
502
796
  } catch (openErr) {
797
+ if (openErr.code === 'ENOENT' && filename === 'AGENTS.md') {
798
+ throw clientSafeError('Authored project memory AGENTS.md is missing')
799
+ }
503
800
  if (openErr.code === 'ELOOP') {
504
801
  sendFn(ws, {
505
802
  type: 'append_memory_result',
@@ -517,15 +814,21 @@ export function createReaderOps(sendFn, resolveSessionCwd, validatePathWithinCwd
517
814
 
518
815
  sendFn(ws, { type: 'append_memory_result', path: absPath, created: !fileExists, error: null })
519
816
  } catch (err) {
520
- let errorMessage
521
- if (err.code === 'EACCES') errorMessage = 'Permission denied'
522
- else errorMessage = err.message || 'Unknown error'
817
+ log.error(`append_memory failed: ${truncateForLog(err.message)}`)
818
+ const errorMessage = fileOpErrorMessage(err)
523
819
  sendFn(ws, { type: 'append_memory_result', path: absPath, created: false, error: errorMessage })
524
820
  }
525
821
  }
526
822
 
527
- /** Get git diff for uncommitted changes in the session CWD */
528
- async function getDiff(ws, base, sessionCwd) {
823
+ /**
824
+ * Get git diff for uncommitted changes in the session CWD.
825
+ *
826
+ * `confineToCwd` (a session-scoped connection) limits the answer to files at or
827
+ * beneath the session's own directory. `git diff` reports the whole
828
+ * repository, and several sessions can share one repository, so without it the
829
+ * diff would include files belonging to a sibling's directory.
830
+ */
831
+ async function getDiff(ws, base, sessionCwd, { confineToCwd = false } = {}) {
529
832
  if (!sessionCwd) {
530
833
  sendFn(ws, {
531
834
  type: 'diff_result',
@@ -540,67 +843,173 @@ export function createReaderOps(sendFn, resolveSessionCwd, validatePathWithinCwd
540
843
 
541
844
  // Check if the directory is a git repository before running git commands
542
845
  try {
543
- await execFileAsync(GIT, ['rev-parse', '--git-dir'], {
846
+ // #7877 — LC_ALL/LANG=C: the classification below reads git's stderr
847
+ // for an English substring. Left to the daemon host's own locale, a
848
+ // translated "not a git repository" message would silently miss that
849
+ // substring and fall into the "other exit-128" branch on EVERY
850
+ // request from that host — exactly the per-request log spam #7862's
851
+ // review downgrade was trying to avoid. Forcing C here makes the
852
+ // classification locale-independent without touching any other git
853
+ // invocation in this function (none of the others string-match stderr).
854
+ await execImpl(GIT, ['rev-parse', '--git-dir'], {
544
855
  cwd: cwdReal,
545
856
  timeout: 5000,
857
+ env: { ...process.env, LC_ALL: 'C', LANG: 'C' },
546
858
  })
547
859
  } catch (revParseErr) {
548
860
  const stderr = (revParseErr.stderr || revParseErr.message || '').toLowerCase()
549
- const isNotGitRepo = stderr.includes('not a git repository') ||
550
- revParseErr.code === 128
861
+ // #7877 — git exits 128 for MANY fatals, not only "not a git
862
+ // repository": `fatal: detected dubious ownership in repository at
863
+ // '<path>'` (mounted volumes, container/worktree setups) is the one
864
+ // chroxy actually hits. The old `stderr.includes(...) || code === 128`
865
+ // OR'd every other 128 into the same bucket, so a dubious-ownership
866
+ // session was misreported to the client AND logged nowhere — the
867
+ // operator had no trace of the real cause.
868
+ //
869
+ // The client-facing contract is UNCHANGED here on purpose (still a
870
+ // fixed 'Not a git repository' for any exit-128, never raw stderr —
871
+ // #7298 must hold): the fix is that an "other 128" is now visible to
872
+ // the operator. `isOtherExit128Fatal` is exactly the case the old
873
+ // predicate swallowed: an exit-128 whose stderr, in the forced C
874
+ // locale above, does NOT actually say "not a git repository".
875
+ const isGenuineNotGitRepo = stderr.includes('not a git repository')
876
+ const isOtherExit128Fatal = !isGenuineNotGitRepo && revParseErr.code === 128
877
+ const isNotGitRepo = isGenuineNotGitRepo || isOtherExit128Fatal
878
+
879
+ if (isOtherExit128Fatal) {
880
+ // Routine-ish (dubious ownership, etc.) but worth an operator's
881
+ // attention — warn, not error, and not silence (#7877).
882
+ log.warn(`git rev-parse --git-dir exited 128 without a "not a git repository" message — classified as non-repo anyway: ${truncateForLog(revParseErr.message)}`)
883
+ } else if (!isNotGitRepo) {
884
+ // Only the genuinely UNEXPECTED failure (git missing, timeout,
885
+ // EACCES) logs at error level. "Not a git repository" is the
886
+ // ordinary state of a session whose cwd is not a checkout, and it
887
+ // arrives on every `get_diff` that session sends — logging it at
888
+ // error level buries the failures worth reading, which is the same
889
+ // defect as not logging at all (Copilot review of #7862).
890
+ log.error(`git rev-parse --git-dir failed: ${truncateForLog(revParseErr.message)}`)
891
+ }
551
892
  sendFn(ws, {
552
893
  type: 'diff_result',
553
894
  files: [],
554
- error: isNotGitRepo
555
- ? 'Not a git repository'
556
- : `Git error: ${revParseErr.message || 'unknown failure'}`,
895
+ error: isNotGitRepo ? 'Not a git repository' : 'Failed to run git diff',
557
896
  })
558
897
  return
559
898
  }
560
899
 
561
900
  const rawBase = (typeof base === 'string' && base.trim()) ? base.trim() : 'HEAD'
562
- // Validate ref name to prevent git flag injection
563
- const diffBase = /^[a-zA-Z0-9._\-\/~^@{}:]+$/.test(rawBase) ? rawBase : 'HEAD'
901
+ // #7290: `base` is client-controlled and UNVALIDATED on the wire —
902
+ // GetDiffSchema is `z.object({ type }).passthrough()` — and it lands in
903
+ // the REVISION slot of `git diff <base>`. The charset allowlist below
904
+ // used to be the only check, and it put `-` INSIDE its character class,
905
+ // so every single-token option passed it: `--stat`, `-p`, `--exit-code`,
906
+ // `--ext-diff`, and `-O<path>` — which makes git read <path> as a diff
907
+ // orderfile and report whether it could, straight back to the client,
908
+ // which at the time forwarded `err.message` verbatim (see #7298 below).
909
+ //
910
+ // isSafeArgvValue is the load-bearing half (it rejects the leading dash);
911
+ // the allowlist stays as a charset narrowing. A `--` separator canNOT
912
+ // substitute for either — see utils/argv-safety.js for the measurements.
913
+ // A git revision can never legitimately begin with `-`, so REJECTING is
914
+ // correct here; falling back to 'HEAD' preserves the pre-existing
915
+ // contract for any unusable base.
916
+ //
917
+ // #7298 — HALF 1 of 2. The charset above is a NARROWING, never a
918
+ // decision: it cannot tell a revision from a path, and `:` and `/` used
919
+ // to be members, so `HEAD:<path>` and a bare absolute path both reached
920
+ // git as revisions and git answered on the wire (measured, git 2.55.0):
921
+ //
922
+ // base='HEAD:/etc/passwd' -> fatal: path '/etc/passwd' exists on
923
+ // disk, but not in 'HEAD'
924
+ // base='HEAD:absent' -> fatal: path 'absent' does not exist in 'HEAD'
925
+ // base='/etc/passwd' -> fatal: '/etc/passwd' is outside
926
+ // repository at '<cwdReal>'
927
+ //
928
+ // — a filesystem-wide path-existence oracle, as the daemon user,
929
+ // escaping the session cwd, plus the workspace path itself.
930
+ //
931
+ // So RESOLVE the base instead of pattern-matching it: only a revision
932
+ // that names a real commit in THIS repo is ever handed to `git diff`,
933
+ // and everything else falls back to HEAD (the pre-existing contract for
934
+ // an unusable base) without git being asked the client's question at
935
+ // all. `rev-parse --verify --quiet` is silent on failure — it exits 1
936
+ // with empty stderr for every probe above — so the resolution step is
937
+ // not itself an oracle. `:` is dropped from the charset in the same
938
+ // change: `<rev>:<path>` names a BLOB, never a commit.
939
+ //
940
+ // Do NOT "harden" this by appending a `--` to the diff argv instead.
941
+ // That changes an unresolvable base's error to `fatal: bad revision`,
942
+ // which the old `unknown revision` recovery predicate missed — and `--`
943
+ // does not stop option parsing for a token that precedes it anyway
944
+ // (#7290, utils/argv-safety.js).
945
+ // The length bound is the third gate, and it is about COST rather than
946
+ // about the oracle: `base` is unconstrained on the wire (#7870), and
947
+ // every byte of it is spawned twice (both `rev-parse` calls) and can be
948
+ // echoed back into an error message. A revision is short, so nothing
949
+ // legitimate is rejected. Only the LENGTH is logged — never the value,
950
+ // which is the input this whole function exists to distrust.
951
+ if (rawBase.length > MAX_DIFF_BASE_LENGTH) {
952
+ log.warn(`get_diff base rejected: ${rawBase.length} chars exceeds the ${MAX_DIFF_BASE_LENGTH}-char limit`)
953
+ }
954
+ const candidate = (
955
+ rawBase.length <= MAX_DIFF_BASE_LENGTH &&
956
+ isSafeArgvValue(rawBase) &&
957
+ /^[a-zA-Z0-9._\-\/~^@{}]+$/.test(rawBase)
958
+ )
959
+ ? rawBase
960
+ : 'HEAD'
961
+
962
+ /** Resolve a revision to a commit OID, or null when it names no commit. */
963
+ const resolveCommit = async (rev) => {
964
+ try {
965
+ const { stdout } = await execImpl(
966
+ GIT, ['rev-parse', '--verify', '--quiet', `${rev}^{commit}`],
967
+ { cwd: cwdReal, timeout: 5000 }
968
+ )
969
+ return stdout.trim() || null
970
+ } catch {
971
+ return null
972
+ }
973
+ }
974
+
975
+ const headOid = await resolveCommit('HEAD')
976
+ // An unresolvable base is HEAD. HEAD itself is unresolvable only in a
977
+ // repo with no commits, where `git diff HEAD` used to fail into the
978
+ // `unknown revision` recovery — so go straight to the plain `git diff`
979
+ // that recovery ran, and drop the stderr-substring predicate with it.
980
+ const baseOid = candidate === 'HEAD'
981
+ ? headOid
982
+ : (await resolveCommit(candidate)) || headOid
983
+ const baseIsHead = baseOid === null || baseOid === headOid
564
984
 
565
985
  let diffOutput = ''
566
986
  try {
567
- const { stdout } = await execFileAsync(GIT, ['diff', diffBase], {
987
+ const { stdout } = await execImpl(GIT, [...DIFF_PIN_CONFIG, 'diff', ...DIFF_HEADER_ARGS, ...(baseOid ? [baseOid] : []), ...(confineToCwd ? DIFF_CWD_PATHSPEC : [])], {
568
988
  cwd: cwdReal,
569
989
  maxBuffer: 2 * 1024 * 1024,
570
990
  timeout: 10000,
571
991
  })
572
992
  diffOutput = stdout
573
993
  } catch (err) {
574
- if (err.message && err.message.includes('unknown revision')) {
575
- try {
576
- const { stdout } = await execFileAsync(GIT, ['diff'], {
577
- cwd: cwdReal,
578
- maxBuffer: 2 * 1024 * 1024,
579
- timeout: 10000,
580
- })
581
- diffOutput = stdout
582
- } catch (innerErr) {
583
- sendFn(ws, {
584
- type: 'diff_result',
585
- files: [],
586
- error: innerErr.message || 'Failed to run git diff',
587
- })
588
- return
589
- }
590
- } else {
591
- sendFn(ws, {
592
- type: 'diff_result',
593
- files: [],
594
- error: err.message || 'Failed to run git diff',
595
- })
596
- return
597
- }
994
+ // #7298 — HALF 2 of 2. Raw git stderr used to go to the client
995
+ // verbatim, which is what made every message above readable on the
996
+ // wire. Half 1 keeps the client's own string out of that stderr, but
997
+ // any git failure can name a path (the workspace, an object, a
998
+ // config), so the detail stays server-side and the wire gets a fixed
999
+ // string. Both halves are load-bearing; neither is redundant.
1000
+ log.error(`git diff failed: ${truncateForLog(err.message)}`)
1001
+ sendFn(ws, {
1002
+ type: 'diff_result',
1003
+ files: [],
1004
+ error: 'Failed to run git diff',
1005
+ })
1006
+ return
598
1007
  }
599
1008
 
600
- // Also get staged changes if diffBase is HEAD
601
- if (diffBase === 'HEAD') {
1009
+ // Also get staged changes if the effective base is HEAD
1010
+ if (baseIsHead) {
602
1011
  try {
603
- const { stdout: stagedOutput } = await execFileAsync(GIT, ['diff', '--cached', 'HEAD'], {
1012
+ const { stdout: stagedOutput } = await execImpl(GIT, [...DIFF_PIN_CONFIG, 'diff', ...DIFF_HEADER_ARGS, '--cached', 'HEAD', ...(confineToCwd ? DIFF_CWD_PATHSPEC : [])], {
604
1013
  cwd: cwdReal,
605
1014
  maxBuffer: 2 * 1024 * 1024,
606
1015
  timeout: 10000,
@@ -613,7 +1022,39 @@ export function createReaderOps(sendFn, resolveSessionCwd, validatePathWithinCwd
613
1022
  }
614
1023
  }
615
1024
 
616
- const files = diffOutput.trim() ? parseDiff(diffOutput) : []
1025
+ let files = diffOutput.trim() ? parseDiff(diffOutput) : []
1026
+
1027
+ // Files directly in the config directory are daemon-managed state, so the
1028
+ // diff view treats them the way the file viewer and generic writes do: a
1029
+ // changed one is left out of the reply, hunks and all, rather than listed by
1030
+ // name. `git diff` names files from the repository root (not the session
1031
+ // cwd), and an entry can touch more than one path (the source of a rename).
1032
+ // An entry with no placeable path is left out too: "could not check" must
1033
+ // never read as "not in the config directory".
1034
+ if (files.length > 0) {
1035
+ const { stdout: topOut } = await execImpl(GIT, ['rev-parse', '--show-toplevel'], {
1036
+ cwd: cwdReal,
1037
+ timeout: 5000,
1038
+ })
1039
+ const repoRoot = topOut.trim()
1040
+ if (!repoRoot) throw new Error('git rev-parse --show-toplevel printed nothing')
1041
+ const headerPaths = diffFileHeaderPaths(diffOutput)
1042
+ const shown = []
1043
+ for (let i = 0; i < files.length; i++) {
1044
+ const touched = headerPaths[i] ?? []
1045
+ let inConfigDir = touched.length === 0
1046
+ for (const p of touched) {
1047
+ if (await isConfigDirOrDirectChild(resolve(repoRoot, p))) { inConfigDir = true; break }
1048
+ }
1049
+ if (inConfigDir) continue
1050
+ // A confined reader keeps an entry only when EVERY path it touches (a
1051
+ // rename names two) is inside the session directory. The pathspec above
1052
+ // already limits what git reports; this does not trust it to.
1053
+ if (confineToCwd && !touched.every((p) => isPathWithin(resolve(repoRoot, p), cwdReal))) continue
1054
+ shown.push(files[i])
1055
+ }
1056
+ files = shown
1057
+ }
617
1058
 
618
1059
  // Deduplicate files that appear in both unstaged and staged diffs
619
1060
  const seen = new Map()
@@ -630,15 +1071,23 @@ export function createReaderOps(sendFn, resolveSessionCwd, validatePathWithinCwd
630
1071
 
631
1072
  // Discover untracked files (new files not yet staged)
632
1073
  try {
633
- const { stdout: untrackedOutput } = await execFileAsync(
1074
+ const { stdout: untrackedOutput } = await execImpl(
634
1075
  GIT, ['ls-files', '--others', '--exclude-standard'],
635
1076
  { cwd: cwdReal, maxBuffer: 512 * 1024, timeout: 5000 }
636
1077
  )
637
1078
  if (untrackedOutput.trim()) {
638
- const untrackedPaths = untrackedOutput.trim().split('\n')
639
- .filter(p => p && !seen.has(p))
640
- .sort()
641
- .slice(0, 10)
1079
+ // Files directly in the config directory are daemon-managed state and are left
1080
+ // out (as in the tracked-file filter above, and as a file outside the project
1081
+ // is left out in the loop below). They are dropped BEFORE the cap of ten, so a
1082
+ // config root that holds ten or more of them cannot fill the slots and hide
1083
+ // every ordinary file after them. `isConfigDirOrDirectChild` resolves symlinks,
1084
+ // so a link to such a file is dropped too.
1085
+ const untrackedPaths = []
1086
+ for (const p of untrackedOutput.trim().split('\n').filter(p => p && !seen.has(p)).sort()) {
1087
+ if (untrackedPaths.length >= 10) break
1088
+ if (await isConfigDirOrDirectChild(resolve(cwdReal, p))) continue
1089
+ untrackedPaths.push(p)
1090
+ }
642
1091
 
643
1092
  const MAX_UNTRACKED_SIZE = 50 * 1024
644
1093
  for (const filePath of untrackedPaths) {
@@ -654,7 +1103,8 @@ export function createReaderOps(sendFn, resolveSessionCwd, validatePathWithinCwd
654
1103
  lines = [{ type: 'context', content: `File too large to preview (${(fileStat.size / 1024).toFixed(1)} KB)` }]
655
1104
  additions = 0
656
1105
  } else {
657
- const buf = await readFile(validation.realPath)
1106
+ const buf = await readContainedBytes(validation.realPath, cwdReal, MAX_UNTRACKED_SIZE)
1107
+ if (buf === null) continue
658
1108
  const checkLen = Math.min(buf.length, 8192)
659
1109
  let isBinary = false
660
1110
  for (let i = 0; i < checkLen; i++) {
@@ -702,10 +1152,18 @@ export function createReaderOps(sendFn, resolveSessionCwd, validatePathWithinCwd
702
1152
  error: null,
703
1153
  })
704
1154
  } catch (err) {
1155
+ // #7298 — the last raw-message branch, and the one that names the
1156
+ // workspace without any help from the client: this catch wraps
1157
+ // `resolveSessionCwd`, whose `realpath()` throws
1158
+ // `ENOENT: no such file or directory, realpath '<cwdReal>'` when the
1159
+ // session cwd is gone (removed worktree, unmounted volume, rename).
1160
+ // That is the same `cwdReal` leak the issue is about, reachable by a
1161
+ // bound client sending a bare `get_diff` with no crafted base at all.
1162
+ log.error(`getDiff failed: ${truncateForLog(err.message)}`)
705
1163
  sendFn(ws, {
706
1164
  type: 'diff_result',
707
1165
  files: [],
708
- error: err.message || 'Unknown error',
1166
+ error: 'Failed to run git diff',
709
1167
  })
710
1168
  }
711
1169
  }