@chroxy/server 0.11.0 → 0.11.10

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 (317) hide show
  1. package/CONFIG.md +204 -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 +954 -0
  12. package/src/activity-registry.js +110 -5
  13. package/src/agent-connections.js +293 -0
  14. package/src/agent-control/client.js +1616 -0
  15. package/src/agent-control/events.js +547 -0
  16. package/src/agent-control/local-connection.js +275 -0
  17. package/src/agent-control/mcp-server.js +545 -0
  18. package/src/anthropic-compatible-config.js +29 -4
  19. package/src/anthropic-compatible-session.js +15 -6
  20. package/src/anthropic-openai-shim.js +0 -1
  21. package/src/archive-continuation.js +164 -0
  22. package/src/assistant-response.js +24 -0
  23. package/src/auth-probes.js +120 -13
  24. package/src/background-shell-tracker.js +27 -0
  25. package/src/base-session.js +1203 -36
  26. package/src/bearer-recheck.js +49 -0
  27. package/src/billing-budget.js +19 -0
  28. package/src/billing-class.js +40 -7
  29. package/src/binary-provenance-trust.js +11 -5
  30. package/src/bound-client-policy.js +279 -0
  31. package/src/built-in-tools/bash-exec.js +46 -7
  32. package/src/built-in-tools/file-ops.js +69 -5
  33. package/src/built-in-tools/tool-transforms.js +1113 -13
  34. package/src/byok-compose-state.js +6 -9
  35. package/src/byok-credentials.js +2 -3
  36. package/src/byok-mcp-client.js +92 -7
  37. package/src/byok-mcp-config.js +628 -121
  38. package/src/byok-mcp-fleet.js +49 -7
  39. package/src/byok-mcp-oauth-store.js +18 -16
  40. package/src/byok-mcp-trust.js +3 -3
  41. package/src/byok-session.js +650 -175
  42. package/src/byok-tool-executor.js +2662 -26
  43. package/src/byok-tools.js +9 -2
  44. package/src/channels/chroxy-channel-server.js +2 -3
  45. package/src/checkpoint-manager.js +64 -46
  46. package/src/claude-channel-session.js +16 -10
  47. package/src/claude-model-catalog.js +131 -16
  48. package/src/claude-model-refresh.js +385 -0
  49. package/src/claude-model-request.js +103 -0
  50. package/src/claude-stream-parser.js +53 -3
  51. package/src/claude-tui/diagnostic-tail.js +83 -0
  52. package/src/claude-tui/form-driver.js +44 -7
  53. package/src/claude-tui/model-error.js +41 -0
  54. package/src/claude-tui/pty-driver.js +211 -88
  55. package/src/claude-tui/sanitize-question-payload.js +109 -0
  56. package/src/claude-tui/usage-limit.js +239 -0
  57. package/src/claude-tui-session.js +3513 -287
  58. package/src/claude-tui-tool-response.js +300 -0
  59. package/src/cli/agent-control-cmd.js +65 -0
  60. package/src/cli/config-cmd.js +4 -4
  61. package/src/cli/config-dir-cmd.js +234 -0
  62. package/src/cli/deploy-cmd.js +45 -10
  63. package/src/cli/doctor-cmd.js +7 -3
  64. package/src/cli/init-cmd.js +15 -16
  65. package/src/cli/providers-cmd.js +3 -3
  66. package/src/cli/schedule-cmd.js +68 -39
  67. package/src/cli/server-cmd.js +48 -1
  68. package/src/cli/service-cmd.js +33 -10
  69. package/src/cli/session-cmd.js +227 -74
  70. package/src/cli/shared.js +162 -11
  71. package/src/cli/tokens-cmd.js +4 -5
  72. package/src/cli/tunnel-cmd.js +255 -24
  73. package/src/cli/worktree-gc-cmd.js +2 -2
  74. package/src/cli-session.js +1066 -121
  75. package/src/cli.js +4 -0
  76. package/src/codex-app-server-client.js +36 -3
  77. package/src/codex-app-server-session.js +1454 -79
  78. package/src/codex-bundled-client.js +66 -0
  79. package/src/codex-model-catalog.js +548 -0
  80. package/src/codex-model-rejections.js +87 -0
  81. package/src/codex-native-resume.js +104 -0
  82. package/src/codex-protocol-capabilities.js +188 -0
  83. package/src/codex-session.js +450 -27
  84. package/src/config-dir-migration.js +444 -0
  85. package/src/config-dir.js +108 -0
  86. package/src/config.js +286 -26
  87. package/src/connection-authority.js +48 -0
  88. package/src/connection-info.js +5 -9
  89. package/src/connection-locality.js +60 -0
  90. package/src/container-liveness-monitor.js +189 -0
  91. package/src/continuation-metadata-worker.js +17 -0
  92. package/src/continuations.js +114 -0
  93. package/src/control-room/host-prune.js +5 -0
  94. package/src/control-room/integrations.js +7 -20
  95. package/src/control-room/skills-inventory.js +2 -2
  96. package/src/conversation-scanner.js +40 -18
  97. package/src/conversation-scope.js +59 -39
  98. package/src/conversation-search.js +24 -22
  99. package/src/credential-store.js +23 -19
  100. package/src/daemon-commit.js +92 -0
  101. package/src/daemon-idle-state.js +171 -0
  102. package/src/daemon-update-status.js +314 -0
  103. package/src/dashboard-build.js +70 -0
  104. package/src/declared-status.js +90 -0
  105. package/src/deepseek-credentials.js +2 -3
  106. package/src/dev-preview.js +169 -182
  107. package/src/device-preferences.js +2 -2
  108. package/src/diff-parser.js +87 -0
  109. package/src/discord-credentials.js +2 -3
  110. package/src/docker-byok-pool.js +3 -1
  111. package/src/docker-byok-session.js +678 -78
  112. package/src/docker-image-allowlist.js +23 -1
  113. package/src/docker-sdk-session.js +172 -3
  114. package/src/docker-session.js +284 -10
  115. package/src/doctor.js +767 -61
  116. package/src/edited-input.js +264 -0
  117. package/src/environment-manager.js +175 -36
  118. package/src/environments/authority.js +95 -0
  119. package/src/environments/backends/container-claude-spawn.js +94 -0
  120. package/src/environments/backends/docker.js +31 -10
  121. package/src/environments/backends/k8s.js +49 -24
  122. package/src/environments/destroy-with-sessions.js +142 -0
  123. package/src/event-ingest.js +118 -13
  124. package/src/event-normalizer.js +151 -233
  125. package/src/gemini-session.js +81 -5
  126. package/src/handler-utils.js +535 -68
  127. package/src/handlers/checkpoint-handlers.js +39 -4
  128. package/src/handlers/control-room-handlers.js +51 -11
  129. package/src/handlers/conversation-handlers.js +469 -56
  130. package/src/handlers/daemon-update-handlers.js +81 -0
  131. package/src/handlers/evaluator-handlers.js +14 -1
  132. package/src/handlers/feature-handlers.js +186 -69
  133. package/src/handlers/file-handlers.js +57 -13
  134. package/src/handlers/input-handlers.js +685 -48
  135. package/src/handlers/orchestration-handlers.js +3 -3
  136. package/src/handlers/scheduler-handlers.js +88 -14
  137. package/src/handlers/session-handlers.js +542 -20
  138. package/src/handlers/session-pr-status-handlers.js +283 -0
  139. package/src/handlers/session-pr-threads-handlers.js +247 -0
  140. package/src/handlers/settings-handlers.js +330 -42
  141. package/src/handlers/skills-handlers.js +13 -4
  142. package/src/handlers/summarize-handlers.js +32 -1
  143. package/src/handlers/survey-throttle.js +380 -0
  144. package/src/health-proof.js +40 -0
  145. package/src/history-page.js +104 -0
  146. package/src/http-routes.js +127 -8
  147. package/src/ide/search.js +24 -6
  148. package/src/ide/symbols.js +20 -6
  149. package/src/input-context.js +117 -0
  150. package/src/instruction-policy-compiler.js +229 -0
  151. package/src/instruction-policy.js +250 -0
  152. package/src/jsonl-reader.js +289 -82
  153. package/src/jsonl-subprocess-session.js +92 -8
  154. package/src/keychain.js +1 -1
  155. package/src/logger.js +63 -17
  156. package/src/mailbox-route.js +11 -22
  157. package/src/message-wire.js +386 -0
  158. package/src/model-discovery.js +43 -3
  159. package/src/models.js +1276 -174
  160. package/src/notification-prefs.js +12 -4
  161. package/src/notifications/discord-billing-sink.js +22 -5
  162. package/src/notifications/discord-ci-sink.js +243 -0
  163. package/src/notifications/discord-webhook-client.js +71 -0
  164. package/src/notifications/discord-webhook-sink.js +64 -23
  165. package/src/notifications/expo-push-sink.js +85 -6
  166. package/src/notifications/ready-body.js +16 -5
  167. package/src/ollama-session.js +34 -2
  168. package/src/orchestration/build-manager.js +9 -2
  169. package/src/orchestration/git-ops.js +41 -7
  170. package/src/orchestration/orchestration-manager.js +80 -33
  171. package/src/orchestration/permission-gate.js +13 -1
  172. package/src/orchestration/run-model.js +2 -1
  173. package/src/orchestration/turn-driver.js +44 -20
  174. package/src/orphan-reaper.js +413 -0
  175. package/src/outgoing-policy.js +183 -0
  176. package/src/pairing.js +92 -13
  177. package/src/path-hash-trust-ledger.js +642 -25
  178. package/src/permission-deadlines.js +82 -0
  179. package/src/permission-floor.js +1357 -42
  180. package/src/permission-hook.js +180 -69
  181. package/src/permission-manager.js +712 -83
  182. package/src/permission-mode-support.js +35 -0
  183. package/src/permission-resolver.js +122 -8
  184. package/src/permission-scope.js +43 -0
  185. package/src/platform.js +159 -43
  186. package/src/preview-ingress.js +54 -0
  187. package/src/preview-target.js +213 -0
  188. package/src/prompt-evaluator.js +34 -4
  189. package/src/provider-customization.js +180 -0
  190. package/src/providers.js +207 -4
  191. package/src/push.js +30 -4
  192. package/src/question-route-map.js +130 -0
  193. package/src/redaction.js +360 -8
  194. package/src/roster-broadcast.js +186 -0
  195. package/src/scheduled-task-store.js +318 -26
  196. package/src/scheduler.js +73 -3
  197. package/src/sdk-session.js +2060 -187
  198. package/src/server-cli/preview-shutdown.js +22 -0
  199. package/src/server-cli/push-notification-handler.js +11 -2
  200. package/src/server-cli/server-orchestrator.js +28 -5
  201. package/src/server-cli-child.js +33 -18
  202. package/src/server-cli.js +524 -38
  203. package/src/server-identity.js +15 -11
  204. package/src/service.js +396 -25
  205. package/src/session-archive-limits.js +15 -0
  206. package/src/session-archive.js +1029 -0
  207. package/src/session-busy-state.js +72 -0
  208. package/src/session-ci-watcher.js +926 -0
  209. package/src/session-context.js +7 -2
  210. package/src/session-manager.js +3491 -312
  211. package/src/session-message-history.js +722 -16
  212. package/src/session-pr-status.js +654 -0
  213. package/src/session-pr-threads.js +271 -0
  214. package/src/session-preset-trust.js +3 -3
  215. package/src/session-preset.js +10 -5
  216. package/src/session-state-persistence.js +94 -17
  217. package/src/session-timeout-manager.js +20 -0
  218. package/src/session-token-store.js +17 -8
  219. package/src/session-wake.js +240 -0
  220. package/src/shell-approval-info.js +2 -2
  221. package/src/shell-approval-store.js +3 -1
  222. package/src/skills-loader.js +7 -4
  223. package/src/skills-manager.js +2 -2
  224. package/src/skills-trust.js +95 -13
  225. package/src/skills-usage.js +2 -3
  226. package/src/snapshots-store.js +2 -3
  227. package/src/statusline.js +23 -11
  228. package/src/summarize-session.js +51 -4
  229. package/src/supervisor.js +22 -11
  230. package/src/sweep-stale-provider-dirs.js +95 -0
  231. package/src/thinking-level-wire.js +39 -0
  232. package/src/thinking-stream.js +179 -0
  233. package/src/tool-result.js +61 -0
  234. package/src/transcript-sources.js +109 -0
  235. package/src/transcript-tasks.js +372 -25
  236. package/src/trusted-file-read.js +302 -0
  237. package/src/tunnel/base.js +0 -8
  238. package/src/tunnel/cloudflare.js +34 -31
  239. package/src/tunnel/index.js +9 -0
  240. package/src/tunnel/preview.js +64 -0
  241. package/src/turn-outcome.js +137 -0
  242. package/src/usage-normalize.js +9 -5
  243. package/src/user-shell-session.js +59 -5
  244. package/src/utils/agent-sdk-version.js +107 -0
  245. package/src/utils/argv-safety.js +741 -0
  246. package/src/utils/auth-cause.js +60 -0
  247. package/src/utils/binary-package-manifest.js +597 -0
  248. package/src/utils/binary-version.js +224 -0
  249. package/src/utils/bounded-regex-worker.js +25 -0
  250. package/src/utils/bounded-regex.js +153 -0
  251. package/src/utils/claude-binary.js +43 -0
  252. package/src/utils/claude-config-dir.js +245 -0
  253. package/src/utils/claude-login-command.js +16 -0
  254. package/src/utils/claude-native-route.js +81 -0
  255. package/src/utils/componentwise-resolver.js +133 -37
  256. package/src/utils/deploy-control-files.js +87 -0
  257. package/src/utils/exec-failure-reason.js +21 -0
  258. package/src/utils/git-repo.js +42 -0
  259. package/src/utils/is-entry-point.js +137 -0
  260. package/src/utils/node-pty-probe.js +95 -0
  261. package/src/utils/node-pty-support.js +118 -0
  262. package/src/utils/opened-file-path.js +167 -0
  263. package/src/utils/path-containment.js +165 -0
  264. package/src/utils/permission-mode-sidecar.js +51 -0
  265. package/src/utils/preflight.js +360 -16
  266. package/src/utils/read-limiter.js +217 -0
  267. package/src/utils/regular-file.js +375 -0
  268. package/src/utils/safe-regex.js +113 -0
  269. package/src/utils/small-file.js +129 -0
  270. package/src/utils/spawn-env.js +189 -4
  271. package/src/utils/stale-session-dirs.js +182 -0
  272. package/src/utils/stat-identity.js +43 -0
  273. package/src/utils/verify-provenance.js +406 -13
  274. package/src/web-task-manager.js +256 -16
  275. package/src/worktree-gc.js +7 -2
  276. package/src/ws-auth.js +69 -21
  277. package/src/ws-broadcaster.js +14 -2
  278. package/src/ws-client-manager.js +16 -1
  279. package/src/ws-client-sender.js +7 -0
  280. package/src/ws-file-ops/browser.js +331 -58
  281. package/src/ws-file-ops/common.js +320 -14
  282. package/src/ws-file-ops/git.js +395 -42
  283. package/src/ws-file-ops/index.js +2 -0
  284. package/src/ws-file-ops/memory.js +137 -35
  285. package/src/ws-file-ops/open-nofollow.js +354 -0
  286. package/src/ws-file-ops/reader.js +571 -113
  287. package/src/ws-forwarding.js +329 -39
  288. package/src/ws-handler-context.js +70 -2
  289. package/src/ws-history.js +940 -172
  290. package/src/ws-message-handlers.js +17 -1
  291. package/src/ws-permissions.js +307 -37
  292. package/src/ws-schemas.js +5 -0
  293. package/src/ws-server.js +643 -96
  294. package/sidecar/node_modules/.package-lock.json +0 -29
  295. package/sidecar/node_modules/ws/LICENSE +0 -20
  296. package/sidecar/node_modules/ws/README.md +0 -548
  297. package/sidecar/node_modules/ws/browser.js +0 -8
  298. package/sidecar/node_modules/ws/index.js +0 -22
  299. package/sidecar/node_modules/ws/lib/buffer-util.js +0 -131
  300. package/sidecar/node_modules/ws/lib/constants.js +0 -19
  301. package/sidecar/node_modules/ws/lib/event-target.js +0 -292
  302. package/sidecar/node_modules/ws/lib/extension.js +0 -203
  303. package/sidecar/node_modules/ws/lib/limiter.js +0 -55
  304. package/sidecar/node_modules/ws/lib/permessage-deflate.js +0 -528
  305. package/sidecar/node_modules/ws/lib/receiver.js +0 -706
  306. package/sidecar/node_modules/ws/lib/sender.js +0 -602
  307. package/sidecar/node_modules/ws/lib/stream.js +0 -161
  308. package/sidecar/node_modules/ws/lib/subprotocol.js +0 -62
  309. package/sidecar/node_modules/ws/lib/validation.js +0 -152
  310. package/sidecar/node_modules/ws/lib/websocket-server.js +0 -554
  311. package/sidecar/node_modules/ws/lib/websocket.js +0 -1393
  312. package/sidecar/node_modules/ws/package.json +0 -70
  313. package/sidecar/node_modules/ws/wrapper.mjs +0 -21
  314. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  315. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  316. package/src/dashboard-next/dist/index.html +0 -13
  317. package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
@@ -17,17 +17,18 @@
17
17
  * so `auto`/`acceptEdits` on claude-tui read `.env` / `id_rsa` ungated. Keep the
18
18
  * floor HERE — never reimplement it in the shell hook or a second JS call site
19
19
  * (the #6986/#7001 lesson: divergent copies of a security check are how these
20
- * bugs happen). A leaf module by design (no logger, no EventEmitter, no rule
21
- * store) so an HTTP handler can import it without pulling in PermissionManager
20
+ * bugs happen). A leaf module by design (no EventEmitter, no rule
21
+ * store; its one sibling import is the config-dir resolver) so an HTTP handler can import it without pulling in PermissionManager
22
22
  * or joining its permission-rule-store import cycle — the same shape as
23
23
  * `redaction.js`, the sanitizer both paths already share.
24
24
  *
25
25
  * Everything here is PURE except the deliberate symlink resolution (realpath /
26
26
  * lstat), which FAILS CLOSED — see {@link isProtectedPathValue}.
27
27
  */
28
- import { realpathSync } from 'node:fs'
29
- import { resolve, relative, sep, isAbsolute, dirname, basename, join } from 'node:path'
28
+ import { realpathSync, lstatSync, statSync } from 'node:fs'
29
+ import path, { resolve, relative, sep, isAbsolute, dirname, basename, join } from 'node:path'
30
30
  import { resolveTargetComponentwiseSync } from './utils/componentwise-resolver.js'
31
+ import { claudeConfigDir, claudeHomeDir } from './utils/claude-config-dir.js'
31
32
 
32
33
  // #6794 — hardcoded protected-path floor. Even under lenient settings (auto /
33
34
  // acceptEdits / a broad `allow` rule) Chroxy must not SILENTLY auto-approve a
@@ -51,7 +52,7 @@ const PROTECTED_DIR_SEGMENTS = new Set(['.git', '.claude', '.vscode'])
51
52
  // is a common benign operation and must not prompt, but auto-reading a private
52
53
  // key or an env file under a broad `allow Read` must not silently succeed.
53
54
  //
54
- // Matched (case-insensitively, see isProtectedPathValue) at ANY path segment:
55
+ // Matched (as written and in canonical form, see canonicalName) at ANY path segment:
55
56
  // - `.env` or `.env.*` → env files (.env / .env.local / …)
56
57
  // - one of SECRET_FILE_EXACT → SSH keys, credential dotfiles
57
58
  // - a segment ending in an extension in SECRET_FILE_EXTENSIONS → PEM / keys /
@@ -61,8 +62,14 @@ const PROTECTED_DIR_SEGMENTS = new Set(['.git', '.claude', '.vscode'])
61
62
  const SECRET_FILE_EXACT = new Set([
62
63
  'id_rsa', 'id_dsa', 'id_ecdsa', 'id_ed25519', // SSH private keys
63
64
  '.npmrc', '.pgpass', '.netrc', // credential dotfiles
65
+ '.credentials.json', // claude's stored login, wherever its config dir is
64
66
  ])
65
67
  const SECRET_FILE_EXTENSIONS = ['.pem', '.key', '.p12', '.pfx']
68
+ // The env-file family: exactly `.env`, or `.env.` followed by anything. Named so
69
+ // the #7978 glob analysis below builds its templates from the same two spellings
70
+ // isSecretFileSegment tests, rather than from a second copy of them.
71
+ const ENV_FILE_NAME = '.env'
72
+ const ENV_FILE_PREFIX = '.env.'
66
73
 
67
74
  // Tool-input fields that name a filesystem target. Presence of one is what
68
75
  // makes a tool "path-carrying" for the floor (Write/Edit → file_path,
@@ -73,6 +80,48 @@ const SECRET_FILE_EXTENSIONS = ['.pem', '.key', '.p12', '.pfx']
73
80
  // path field (a path-redirect would let an edit slip past the protected floor).
74
81
  export const PROTECTED_PATH_INPUT_FIELDS = ['file_path', 'path', 'notebook_path']
75
82
 
83
+ /**
84
+ * The paths a patch-shaped `changes` array names: each member's `path`, and the
85
+ * destination of a rename (`kind.move_path`, the app-server `PatchChangeKind`
86
+ * shape). One extraction, used by the protected-path floor and by path-scoped
87
+ * rules, so both look at the same set of paths.
88
+ *
89
+ * `complete` is false when `changes` is not an array, or any member is not an
90
+ * object with a non-empty string `path` and a supported `kind` (`add`, `update`
91
+ * or `delete`, as a string or as `{ type }`), or carries a `move_path` that is
92
+ * neither absent/null nor a non-empty string. A caller that must see every path
93
+ * (a scoped rule) treats an incomplete list as no match; the floor uses the
94
+ * paths that are present.
95
+ * @param {*} changes
96
+ * @returns {{ complete: boolean, paths: string[] }}
97
+ */
98
+ // The change kinds the app-server passes, as a bare string (legacy) or as `type`.
99
+ const PATCH_CHANGE_KINDS = new Set(['add', 'update', 'delete'])
100
+
101
+ export function collectChangeTargets(changes) {
102
+ const paths = []
103
+ if (!Array.isArray(changes)) return { complete: false, paths }
104
+ let complete = true
105
+ for (const change of changes) {
106
+ if (!change || typeof change !== 'object') { complete = false; continue }
107
+ if (typeof change.path === 'string' && change.path.length > 0) paths.push(change.path)
108
+ else complete = false
109
+ const kind = change.kind
110
+ if (typeof kind === 'string') {
111
+ // The legacy bare-string form.
112
+ if (!PATCH_CHANGE_KINDS.has(kind)) complete = false
113
+ } else if (kind && typeof kind === 'object' && PATCH_CHANGE_KINDS.has(kind.type)) {
114
+ if (kind.move_path != null) {
115
+ if (typeof kind.move_path === 'string' && kind.move_path.length > 0) paths.push(kind.move_path)
116
+ else complete = false
117
+ }
118
+ } else {
119
+ complete = false
120
+ }
121
+ }
122
+ return { complete, paths }
123
+ }
124
+
76
125
  // #6803 — tools whose floor is SECRETS-ONLY (non-mutating reads). handlePermission
77
126
  // routes these through isSecretReadTarget (env files + key material) instead of
78
127
  // the full config-dir floor. EVERY OTHER path-carrying tool — the mutating ones
@@ -82,14 +131,14 @@ export const PROTECTED_PATH_INPUT_FIELDS = ['file_path', 'path', 'notebook_path'
82
131
  export const SECRET_READ_FLOOR_TOOLS = new Set(['Read', 'Glob', 'Grep'])
83
132
 
84
133
  /**
85
- * #6803 — is a single (already-lowercased) path segment a known secret FILE?
134
+ * #6803 — is a single path segment (lowercased as written, or canonical — see canonicalName) a known secret FILE?
86
135
  * Env files, SSH/credential dotfiles, and PEM/key/keystore extensions. Pure
87
136
  * string ops (no regex) so it can't be mangled by a later edit.
88
- * @param {string} seg a lowercased path segment
137
+ * @param {string} seg a lowercased or canonical path segment
89
138
  * @returns {boolean}
90
139
  */
91
140
  function isSecretFileSegment(seg) {
92
- if (seg === '.env' || seg.startsWith('.env.')) return true
141
+ if (seg === ENV_FILE_NAME || seg.startsWith(ENV_FILE_PREFIX)) return true
93
142
  if (SECRET_FILE_EXACT.has(seg)) return true
94
143
  for (const ext of SECRET_FILE_EXTENSIONS) {
95
144
  if (seg.length > ext.length && seg.endsWith(ext)) return true
@@ -110,26 +159,238 @@ function isSecretFileSegment(seg) {
110
159
  * the config dirs (`.claude/skills/*.md`, a secret-free `.vscode/settings.json`)
111
160
  * stay un-floored for reads per #6803's intent.
112
161
  *
113
- * Matched as a 2-/3-segment sequence anchored at index `i` of the (lowercased,
162
+ * Matched as a 2-/3-segment sequence anchored at index `i` of the (lowercased or canonical,
114
163
  * `..`-stripped) segment array, so any depth prefix (`sub/.git/config`) matches.
115
164
  * Pure string ops (no regex) — consistent with the rest of the floor.
116
- * @param {string[]} segments lowercased path segments
165
+ * @param {string[]} segments lowercased or canonical path segments
117
166
  * @param {number} i the current segment index
118
167
  * @returns {boolean}
119
168
  */
120
169
  function isCredentialConfigSegment(segments, i) {
121
- const seg = segments[i]
122
- // .git/config (PAT-embedded remote URLs) and .git/credentials (git store).
123
- if (seg === '.git' && (segments[i + 1] === 'config' || segments[i + 1] === 'credentials')) return true
124
- // XDG git: .config/git/config and .config/git/credentials.
125
- if (seg === '.config' && segments[i + 1] === 'git' &&
126
- (segments[i + 2] === 'config' || segments[i + 2] === 'credentials')) return true
170
+ // .git/config (PAT-embedded remote URLs), .git/credentials (git store), and
171
+ // the XDG equivalents under .config/git/.
172
+ for (const sequence of CREDENTIAL_CONFIG_SEQUENCES) {
173
+ if (sequence.every((name, k) => segments[i + k] === name)) return true
174
+ }
127
175
  // .claude/settings*.json (settings.json / settings.local.json — may hold keys).
128
176
  const child = segments[i + 1]
129
- if (seg === '.claude' && typeof child === 'string' && child.startsWith('settings') && child.endsWith('.json')) return true
177
+ if (segments[i] === CLAUDE_SETTINGS_DIR && typeof child === 'string' &&
178
+ child.startsWith(CLAUDE_SETTINGS_PREFIX) && child.endsWith(CLAUDE_SETTINGS_SUFFIX)) return true
130
179
  return false
131
180
  }
132
181
 
182
+ // The credential-dense config files above, as data (#7978) so the Grep glob
183
+ // analysis derives its templates from the same spellings this matcher uses.
184
+ const CREDENTIAL_CONFIG_SEQUENCES = [
185
+ ['.git', 'config'], ['.git', 'credentials'],
186
+ ['.config', 'git', 'config'], ['.config', 'git', 'credentials'],
187
+ ]
188
+ const CLAUDE_DIR = '.claude'
189
+ const CLAUDE_SETTINGS_DIR = CLAUDE_DIR
190
+ const CLAUDE_SETTINGS_PREFIX = 'settings'
191
+ const CLAUDE_SETTINGS_SUFFIX = '.json'
192
+
193
+ // The name a path segment carries: anything from a `:` on, and any trailing
194
+ // dots or spaces, are dropped. The trim is a scan from the end, not a regex,
195
+ // so a long run of dots or spaces costs linear time.
196
+ export function segmentName(seg) {
197
+ const colon = seg.indexOf(':')
198
+ const name = colon === -1 ? seg : seg.slice(0, colon)
199
+ let end = name.length
200
+ while (end > 0 && (name[end - 1] === '.' || name[end - 1] === ' ')) end--
201
+ return name.slice(0, end)
202
+ }
203
+
204
+ // The canonical form of a segment's name (see segmentName): folded wider than
205
+ // `toLowerCase()`. Compatibility forms are decomposed and combining marks
206
+ // removed, then each character is lower-, upper- and lower-cased again (so a
207
+ // capital or small sharp s becomes `ss`). An ASCII name is only lowercased.
208
+ // Each segment is also checked as written, so this form only adds matches.
209
+ const ASCII_NAME = /^[\x00-\x7f]*$/
210
+ export function canonicalName(name) {
211
+ if (ASCII_NAME.test(name)) return name.toLowerCase()
212
+ return [...name.normalize('NFKD').replace(/\p{M}/gu, '')]
213
+ .map((ch) => ch.toLowerCase().toUpperCase().toLowerCase())
214
+ .join('')
215
+ }
216
+
217
+ // canonicalName, computed once per name within one call: every target of a
218
+ // call that resolves through the same directories shares its names. Returns
219
+ // null, and the caller floors, for a name longer than FLOOR_MAX_NAME_LENGTH or
220
+ // once the call's distinct non-ASCII names pass FLOOR_MAX_CALL_CANONICAL
221
+ // characters. A resolved path's names include directory names and symlink
222
+ // text, which the call's byte budget does not count.
223
+ function _canonicalNameIn(name, call) {
224
+ let canonical = call.names.get(name)
225
+ if (canonical !== undefined) return canonical
226
+ if (name.length > FLOOR_MAX_NAME_LENGTH) return null
227
+ if (!ASCII_NAME.test(name)) {
228
+ call.canonical.left -= name.length
229
+ if (call.canonical.left < 0) return null
230
+ }
231
+ canonical = canonicalName(name)
232
+ call.names.set(name, canonical)
233
+ return canonical
234
+ }
235
+
236
+ // A segment whose name (see segmentName) is in the 8.3 short-name form
237
+ // (`CLAUDE~1`, `SETTIN~1.JSO`): up to six characters, `~`, digits, and an
238
+ // extension of up to three. It floors without a name comparison, under both floors.
239
+ const SHORT_NAME_SEGMENT = /^[^~.]{1,6}~\d+(\.[^.]{1,3})?$/
240
+
241
+ // #8741 — Claude Code's own worktrees live INSIDE the protected `.claude/` dir:
242
+ // `EnterWorktree` / `claude --worktree <name>` check one out at
243
+ // `<repo>/.claude/worktrees/<name>/`. Flooring `.claude` at any depth forced a
244
+ // prompt on every edit inside one; under Auto nobody answers and each cost the
245
+ // 300 s timeout. A worktree is a workspace like the cwd itself, so a target
246
+ // strictly inside `<cwd>/.claude/worktrees/<name>/` is scanned from `<name>` down:
247
+ // its own `.claude/settings*.json`, `.git`, `.env`, keys and config dirs still floor.
248
+ const CLAUDE_WORKTREES_DIR = 'worktrees'
249
+ // Claude Code accepts `[A-Za-z0-9._-]+` per `/`-separated name segment, refuses
250
+ // `.`, `..` and `.git`, and names the directory with each `/` written as `+`
251
+ // (`feature/auth` -> `feature+auth`). The floor also refuses a leading dot or
252
+ // `+`: a name starts with a letter, digit, `_` or `-`, so one that is itself a
253
+ // dotfile or a protected dir (`.claude`, `.git`, `.vscode`, `.env`) is never a root.
254
+ const CLAUDE_WORKTREE_NAME = /^[a-z0-9_-][a-z0-9._+-]*$/i
255
+ // The carve-out covers PLAIN names only: ASCII letters, digits, space and
256
+ // `._-@+()[]$`, not ending in a dot or a space. A path with any other component
257
+ // keeps the full scan, which costs a prompt, never access.
258
+ const PLAIN_COMPONENT = /^[A-Za-z0-9._@+()[\]$ -]*[A-Za-z0-9_@+()[\]$-]$/
259
+
260
+ /**
261
+ * #8741 — is `rel` (`relative(base, resolve(base, target))`, the path as
262
+ * written) strictly inside one of Claude Code's worktrees,
263
+ * `<base>/.claude/worktrees/<name>/`, by a path the scan reads as it is?
264
+ * `target` is the raw tool-input value. Decided ONCE, on the path as written,
265
+ * by {@link isProtectedPathValue}; the resolved pass keeps the carve-out only
266
+ * when its resolved path is that same path.
267
+ *
268
+ * Refused (the full scan applies) unless ALL of these hold:
269
+ * - the raw `target` has no `..` component;
270
+ * - split on the PLATFORM separator, every component of `rel` is a
271
+ * {@link PLAIN_COMPONENT}, the first two are exactly `.claude/worktrees`
272
+ * (as Claude Code spells them) and the third is a
273
+ * {@link CLAUDE_WORKTREE_NAME};
274
+ * - there is at least one component below `<name>` — the root itself, and
275
+ * anything directly in `worktrees/`, stays floored;
276
+ * - walking down from `.claude` with `lstat`, `.claude`, `.claude/worktrees`
277
+ * and `<name>` are real directories (`lstat` reports a symlink as not a
278
+ * directory), and no component below them that exists is a symlink. The
279
+ * first part is Claude Code's own condition for creating a worktree (a
280
+ * symlink at any of the three could redirect it); together they keep a path
281
+ * that only LOOKS like a worktree, or leaves one through a link, floored.
282
+ * On POSIX a non-directory among the first three also fails the next
283
+ * `lstat` with `ENOTDIR`, so a test can separate only the symlink half.
284
+ * `ENOENT` below `<name>` ends the walk, since nothing further exists yet; any
285
+ * other error refuses (fail closed). That refusal is also covered by the
286
+ * resolved pass, whose walk fails closed on the same error.
287
+ * @param {string} base
288
+ * @param {string} rel
289
+ * @param {string} target
290
+ * @returns {boolean}
291
+ */
292
+ function _insideClaudeWorktree(base, rel, target) {
293
+ if (target.split(/[/\\]+/).includes('..')) return false
294
+ const parts = rel.split(sep)
295
+ if (parts.length < 4 || !parts.every((part) => PLAIN_COMPONENT.test(part))) return false
296
+ if (parts[0] !== CLAUDE_DIR || parts[1] !== CLAUDE_WORKTREES_DIR) return false
297
+ if (!CLAUDE_WORKTREE_NAME.test(parts[2])) return false
298
+ let path = base
299
+ for (let k = 0; k < parts.length; k++) {
300
+ path = join(path, parts[k])
301
+ let stat
302
+ try {
303
+ stat = lstatSync(path)
304
+ } catch (err) {
305
+ return err.code === 'ENOENT' && k >= 3
306
+ }
307
+ // A root component must be a directory (a symlink is not one to `lstat`);
308
+ // below the root, no existing component may be a symlink.
309
+ if (k < 3 ? !stat.isDirectory() : stat.isSymbolicLink()) return false
310
+ }
311
+ return true
312
+ }
313
+
314
+ /**
315
+ * Is `path` an existing file with more than one hard link? A missing target is
316
+ * not; any other `lstat` error answers yes (fail closed).
317
+ * @param {string} path
318
+ * @returns {boolean}
319
+ */
320
+ function _hasOtherHardLinks(path) {
321
+ try {
322
+ const stat = lstatSync(path)
323
+ return stat.isFile() && stat.nlink > 1
324
+ } catch (err) {
325
+ return err.code !== 'ENOENT'
326
+ }
327
+ }
328
+
329
+ // The most a single path-tool target may be before the floor decides it
330
+ // without resolving it: longer than FLOOR_MAX_TARGET_BYTES (UTF-8), or with more
331
+ // than FLOOR_MAX_TARGET_COMPONENTS components (`/`- or `\`-separated, `.` and
332
+ // `..` included), it floors. Measured on 573,681 real paths, the deepest had 21
333
+ // components and the longest was 335 bytes; Linux's PATH_MAX is 4096 bytes.
334
+ // Exported so tests derive their inputs from the same numbers.
335
+ export const FLOOR_MAX_TARGET_BYTES = 4096
336
+ export const FLOOR_MAX_TARGET_COMPONENTS = 256
337
+ // And the most one tool call may carry: more than FLOOR_MAX_CALL_TARGETS path
338
+ // targets (path fields and `changes[]` members together), or more than
339
+ // FLOOR_MAX_CALL_COMPONENTS components across them, floors the call before any
340
+ // target is resolved. A patch touching hundreds of files is far below both.
341
+ export const FLOOR_MAX_CALL_TARGETS = 1024
342
+ export const FLOOR_MAX_CALL_COMPONENTS = 16384
343
+ // The call's symlink-resolving walks share one budget too: past
344
+ // FLOOR_MAX_CALL_WALK components walked across all its targets (those a symlink
345
+ // adds included), the call floors.
346
+ export const FLOOR_MAX_CALL_WALK = 16384
347
+ // Filesystem-identity lookups made for the configured Claude config directory in
348
+ // one call; past it the call floors. Separate from the walk so a large patch is
349
+ // not floored by this budget alone.
350
+ export const FLOOR_MAX_CALL_IDENTITY = 16384
351
+ // And more than FLOOR_MAX_CALL_BYTES UTF-8 bytes across one call's targets
352
+ // floors the call. A thousand-file patch of 250-byte absolute paths is about 250 KB.
353
+ export const FLOOR_MAX_CALL_BYTES = 262144
354
+ // A path name longer than FLOOR_MAX_NAME_LENGTH characters floors: no
355
+ // filesystem here accepts one. And more than FLOOR_MAX_CALL_CANONICAL characters
356
+ // of distinct non-ASCII names, from the targets and from what they resolve to,
357
+ // floors the call. Characters here are UTF-16 code units, as `length` counts them.
358
+ export const FLOOR_MAX_NAME_LENGTH = 255
359
+ export const FLOOR_MAX_CALL_CANONICAL = 65536
360
+
361
+ /**
362
+ * How many `/`- or `\`-separated components `target` has, counting no further
363
+ * than `limit` (so a huge target costs only as much as the bound it is checked
364
+ * against).
365
+ * @param {string} target
366
+ * @param {number} limit
367
+ * @returns {number}
368
+ */
369
+ function _componentCount(target, limit) {
370
+ let components = 0
371
+ let inName = false
372
+ for (let i = 0; i < target.length && components <= limit; i++) {
373
+ const code = target.charCodeAt(i)
374
+ if (code === 0x2f || code === 0x5c) {
375
+ inName = false
376
+ } else if (!inName) {
377
+ inName = true
378
+ components++
379
+ }
380
+ }
381
+ return components
382
+ }
383
+
384
+ /**
385
+ * Is `target` over either size bound? Linear in its length.
386
+ * @param {string} target
387
+ * @returns {boolean}
388
+ */
389
+ function _exceedsTargetBounds(target) {
390
+ if (Buffer.byteLength(target, 'utf8') > FLOOR_MAX_TARGET_BYTES) return true
391
+ return _componentCount(target, FLOOR_MAX_TARGET_COMPONENTS) > FLOOR_MAX_TARGET_COMPONENTS
392
+ }
393
+
133
394
  // #6851 — depth ceiling for the sync deepest-ancestor realpath walk. Absolute
134
395
  // paths never legitimately nest this deep; the cap only guards a pathological /
135
396
  // malicious tail (a to-be-created path with hundreds of nonexistent components
@@ -198,12 +459,227 @@ function realpathDeepestAncestorSync(absPath) {
198
459
  // walks is what keeps them from drifting again — #6928 was a bug present in BOTH
199
460
  // copies. Imported as `resolveTargetComponentwiseSync` at the top of this file.
200
461
 
462
+ /**
463
+ * The configured Claude config directory (CLAUDE_CONFIG_DIR, resolved and
464
+ * canonical exactly as `claudeConfigDir` resolves it) treated like `.claude`.
465
+ *
466
+ * A `.claude`-NAMED root needs nothing here: the segment rules already cover it
467
+ * wherever it sits. Any other name is recognised by its resolved location:
468
+ * - a dedicated root (the usual case): the full floor covers everything
469
+ * inside it, and both floors cover `settings*.json` directly inside it, as
470
+ * they do for `.claude/settings*.json`;
471
+ * - a root that is `$HOME` or an ancestor of it (the resolver accepts these):
472
+ * it is NOT floored wholesale, which would prompt for the whole home
473
+ * directory. Only the `settings*.json` files directly inside it floor.
474
+ * A root the resolver rejects (relative, `/`, an alias of `/`) never reaches
475
+ * here: it resolves to `~/.claude`, which the name rules already cover.
476
+ * Resolved once per call. Returns null when no extra rule applies.
477
+ * @param {{ configRoot?: object|null }} call
478
+ * @returns {{ root: string, broad: boolean }|null}
479
+ */
480
+ function _configRootRule(call) {
481
+ if (call.configRoot !== undefined) return call.configRoot
482
+ let root
483
+ let home
484
+ try {
485
+ root = (call.configDirFn ?? claudeConfigDir)()
486
+ home = claudeHomeDir()
487
+ } catch {
488
+ // The resolver itself failed: nothing can be said about the directory, so floor.
489
+ call.configRoot = { root: null, broad: false, anchor: null, anchorId: null, tail: [], anchorAncestorIds: null, failed: true }
490
+ return call.configRoot
491
+ }
492
+ let rule = null
493
+ if (basename(root).toLowerCase() !== CLAUDE_DIR) {
494
+ try { home = realpathSync.native(home) } catch { /* the raw home still gives a prefix test */ }
495
+ // `anchor` is the root, or its deepest EXISTING ancestor when the root is not
496
+ // created yet; `tail` are the missing pieces between them (lowercased).
497
+ rule = { root, broad: false, anchor: null, anchorId: null, tail: [], anchorAncestorIds: null, failed: false }
498
+ try {
499
+ // The root holds $HOME (is it, or an ancestor of it). Both are canonical
500
+ // (native realpath), so the spelling comparison is enough.
501
+ rule.broad = pathPiecesUnder(root, home, path) !== null
502
+ let anchor = root
503
+ const missing = []
504
+ for (;;) {
505
+ const id = _statId(anchor, call)
506
+ if (id !== undefined) { rule.anchor = anchor; rule.anchorId = id; break }
507
+ const parent = dirname(anchor)
508
+ if (parent === anchor) break
509
+ missing.push(basename(anchor).toLowerCase())
510
+ anchor = parent
511
+ }
512
+ rule.tail = missing.reverse()
513
+ } catch {
514
+ rule.failed = true
515
+ }
516
+ }
517
+ call.configRoot = rule
518
+ return rule
519
+ }
520
+
521
+ /** `p` followed by each ancestor, ending at the filesystem root. */
522
+ function _withAncestors(p) {
523
+ const chain = [p]
524
+ for (let parent = dirname(p); parent !== chain[chain.length - 1]; parent = dirname(parent)) chain.push(parent)
525
+ return chain
526
+ }
527
+
528
+ /**
529
+ * Which filesystem object is at `p`: a `device:inode` id; null when the
530
+ * filesystem reports inode 0 (identifies nothing); undefined when nothing is
531
+ * there (ENOENT / ENOTDIR). Any other error throws, and callers fail closed.
532
+ * Each distinct lookup is charged to the call's own identity budget
533
+ * ({@link FLOOR_MAX_CALL_IDENTITY}, separate from the component walk) and remembered for
534
+ * the rest of the call; running out of budget throws, so the call floors.
535
+ */
536
+ function _statId(p, call) {
537
+ if (call.ids.has(p)) return call.ids.get(p)
538
+ if (--call.idBudget.left < 0) throw Object.assign(new Error('floor: identity lookups exceed the call budget'), { code: 'EBUDGET' })
539
+ let id
540
+ try {
541
+ const st = (call.statFn ?? statSync)(p, { bigint: true })
542
+ id = st.ino === 0n ? null : `${st.dev}:${st.ino}`
543
+ } catch (err) {
544
+ if (err?.code !== 'ENOENT' && err?.code !== 'ENOTDIR') throw err
545
+ id = undefined
546
+ }
547
+ call.ids.set(p, id)
548
+ return id
549
+ }
550
+
551
+ /** A name the filesystem might treat as another (case, normalisation). */
552
+ function _sameName(a, b, call) {
553
+ if (a === b) return true
554
+ // Trailing dots and spaces, and a `:` suffix, are not part of a Windows name.
555
+ const ca = _canonicalNameIn(segmentName(a), call)
556
+ const cb = _canonicalNameIn(segmentName(b), call)
557
+ return ca === null || cb === null || ca === cb
558
+ }
559
+
560
+ /**
561
+ * The path pieces of `target` relative to `root` (both absolute), compared
562
+ * case-insensitively so a differently-cased spelling of one directory matches
563
+ * on a case-insensitive volume; null when `target` is not inside `root`.
564
+ * `[]` means the target is the root itself. `pathImpl` is injectable so the
565
+ * Windows spelling is testable from any host.
566
+ * @param {string} root
567
+ * @param {string} target
568
+ * @param {typeof path} pathImpl
569
+ * @returns {string[]|null}
570
+ */
571
+ export function pathPiecesUnder(root, target, pathImpl) {
572
+ const rel = pathImpl.relative(root.toLowerCase(), target.toLowerCase())
573
+ if (rel === '') return []
574
+ if (pathImpl.isAbsolute(rel) || rel === '..' || rel.startsWith('..' + pathImpl.sep)) return null
575
+ return rel.split(/[/\\]+/).filter((s) => s.length > 0)
576
+ }
577
+
578
+ /**
579
+ * How the absolute `real` relates to the configured root, by spelling first and
580
+ * then by filesystem object, so a name the filesystem treats as equivalent (a
581
+ * case or Unicode-normalisation variant, a second path) is recognised too. A
582
+ * root that is not created yet is matched through its deepest existing ancestor
583
+ * (by identity) plus the missing tail (by name).
584
+ * inside: the pieces of `real` below the root, or null when not inside it
585
+ * covers: `real` is the root or an ancestor of it (a search from there
586
+ * reaches the root)
587
+ * Throws on a stat error other than "nothing there", or when the call's budget
588
+ * is spent; callers fail closed.
589
+ */
590
+ function _rootRelation(rule, real, wantCovers, call) {
591
+ let inside = pathPiecesUnder(rule.root, real, path)
592
+ let covers = wantCovers && pathPiecesUnder(real, rule.root, path) !== null
593
+ if (rule.anchorId === null || rule.anchorId === undefined) return { inside, covers }
594
+ if (inside === null || (wantCovers && !covers)) {
595
+ // Top-down, so the first missing directory ends the walk: nothing below it exists.
596
+ for (const dir of _withAncestors(real).reverse()) {
597
+ const id = _statId(dir, call)
598
+ if (id === undefined) break
599
+ if (id !== rule.anchorId) continue
600
+ const rest = pathPiecesUnder(dir, real, path) ?? []
601
+ let k = 0
602
+ while (k < rest.length && k < rule.tail.length && _sameName(rest[k], rule.tail[k], call)) k++
603
+ if (k === rule.tail.length) {
604
+ if (inside === null) inside = rest.slice(k)
605
+ } else if (k === rest.length) {
606
+ covers = true // `real` is above the root, reached through directories not created yet
607
+ }
608
+ }
609
+ if (wantCovers && !covers) {
610
+ const realId = _statId(real, call)
611
+ if (realId) {
612
+ if (rule.anchorAncestorIds === null) {
613
+ rule.anchorAncestorIds = new Set()
614
+ for (const dir of _withAncestors(rule.anchor)) {
615
+ const id = _statId(dir, call)
616
+ if (id) rule.anchorAncestorIds.add(id)
617
+ }
618
+ }
619
+ covers = rule.anchorAncestorIds.has(realId)
620
+ }
621
+ }
622
+ }
623
+ return { inside, covers }
624
+ }
625
+
626
+ /**
627
+ * The verdict for a target `inside` the configured root (see
628
+ * {@link _configRootRule}): is it floored? `inside` are its pieces below the
629
+ * root. Dedicated root: everything under the full floor; `settings*.json`
630
+ * directly inside under both. Broad root (holds $HOME): only the latter.
631
+ * Exported so the Windows spelling can be tested from any host.
632
+ * @param {string[]} inside
633
+ * @param {boolean} broad
634
+ * @param {boolean} secretsOnly
635
+ * @param {object} call
636
+ * @returns {boolean}
637
+ */
638
+ export function configRootVerdict(inside, broad, secretsOnly, call) {
639
+ if (!broad && !secretsOnly) return true
640
+ if (inside.length === 0) return false
641
+ // The first piece sits where `.claude` has `settings*.json`: test it in the
642
+ // same two forms and with the same matcher as the `.claude` rule.
643
+ const first = segmentName(inside[0])
644
+ if (SHORT_NAME_SEGMENT.test(first)) return true
645
+ const canonical = _canonicalNameIn(first, call)
646
+ if (canonical === null) return true
647
+ return isCredentialConfigSegment([CLAUDE_DIR, first], 0) || isCredentialConfigSegment([CLAUDE_DIR, canonical], 0)
648
+ }
649
+
650
+ /**
651
+ * Does the already-resolved absolute `resolved` hit the configured config
652
+ * directory's rules? Applies whether or not the target sits in a workspace
653
+ * the worktree carve-out admits. Fails closed.
654
+ * @param {string} resolved
655
+ * @param {boolean} secretsOnly
656
+ * @param {object} call
657
+ * @returns {boolean}
658
+ */
659
+ function _hitsConfigRoot(resolved, secretsOnly, call) {
660
+ const rule = _configRootRule(call)
661
+ if (rule === null) return false
662
+ if (rule.failed) return true
663
+ try {
664
+ const { inside } = _rootRelation(rule, resolved, false, call)
665
+ if (inside === null) return false
666
+ return configRootVerdict(inside, rule.broad, secretsOnly, call)
667
+ } catch {
668
+ return true
669
+ }
670
+ }
671
+
201
672
  /**
202
673
  * #6851 — the pure segment scan, factored out of {@link isProtectedPathValue} so
203
674
  * the lexical pass and the symlink-resolved pass share ONE matcher. Given a
204
675
  * resolution `base` and an already-resolved absolute `resolved` target, applies
205
- * the #6806 relative-vs-absolute framing (below) and tests each segment. No fs
206
- * access — string ops only.
676
+ * the #6806 relative-vs-absolute framing (below) and tests each segment. String
677
+ * ops only.
678
+ *
679
+ * #8741 — when `carved` (see {@link isProtectedPathValue}), the target is
680
+ * strictly inside `<base>/.claude/worktrees/<name>/` and is scanned from
681
+ * `<name>` down, so the `.claude` and `worktrees` above the worktree are not
682
+ * counted while everything inside it is.
207
683
  *
208
684
  * #6806 — the discriminator is whether the resolved target stays INSIDE base's
209
685
  * own subtree:
@@ -218,9 +694,12 @@ function realpathDeepestAncestorSync(absPath) {
218
694
  * @param {string} base
219
695
  * @param {string} resolved an absolute path already resolved against base
220
696
  * @param {boolean} secretsOnly
697
+ * @param {boolean} carved `resolved` is inside a worktree the carve-out admits
698
+ * @param {{ names: Map<string, string>, canonical: { left: number } }} call
699
+ * the canonical names computed in this call, and the characters left to compute
221
700
  * @returns {boolean}
222
701
  */
223
- function _scanResolvedTarget(base, resolved, secretsOnly) {
702
+ function _scanResolvedTarget(base, resolved, secretsOnly, carved, call) {
224
703
  const rel = relative(base, resolved)
225
704
  // Target is inside base's own subtree when the relative path neither is nor
226
705
  // begins with `..` (and isn't a foreign absolute — a Windows cross-drive
@@ -232,10 +711,170 @@ function _scanResolvedTarget(base, resolved, secretsOnly) {
232
711
  // here, but a separator-agnostic split keeps the segment scan robust to any
233
712
  // foreign `\`/`/` that survives (and can never wrongly merge two segments — a
234
713
  // filename cannot contain a separator on the platform that produced it).
235
- const segments = scanned.split(/[/\\]+/)
236
- .filter((s) => s.length > 0 && s !== '..')
237
- .map((s) => s.toLowerCase())
238
- for (let i = 0; i < segments.length; i++) {
714
+ const pieces = scanned.split(/[/\\]+/).filter((s) => s.length > 0 && s !== '..')
715
+ const names = pieces.map(segmentName)
716
+ // #8741 — start the scan at `<name>`. `carved` means `rel` is a path
717
+ // `_insideClaudeWorktree` admitted: every native component is a
718
+ // PLAIN_COMPONENT (no separator of either kind, never empty or `..`), so its
719
+ // first three native components are also `pieces[0..2]`.
720
+ const start = carved ? 2 : 0
721
+ for (let i = start; i < names.length; i++) {
722
+ if (SHORT_NAME_SEGMENT.test(names[i])) return true
723
+ }
724
+ // Each segment is checked as written (lowercased) and in canonical form; a
725
+ // match in either floors, and so does a name with no canonical form computed.
726
+ const canonical = []
727
+ for (const name of names) {
728
+ const form = _canonicalNameIn(name, call)
729
+ if (form === null) return true
730
+ canonical.push(form)
731
+ }
732
+ return _matchesProtectedSegments(pieces.map((p) => p.toLowerCase()), start, secretsOnly) ||
733
+ _matchesProtectedSegments(canonical, start, secretsOnly) ||
734
+ _hitsConfigRoot(resolved, secretsOnly, call) ||
735
+ _hitsInboxSocketDir(resolved, call) ||
736
+ _isSessionsDir(resolved, call)
737
+ }
738
+
739
+ // Claude Code's inbox sockets live under this directory. It is matched by its
740
+ // absolute spelling, with and without the macOS `/private` prefix, and as a
741
+ // prefix: every path at or below it floors, under both floors. The real-path
742
+ // pass resolves `/tmp` to `/private/tmp` on macOS, so the second spelling is
743
+ // what a symlinked or relative route arrives as; on other hosts it is a literal.
744
+ const INBOX_SOCKET_DIR = 'cc-socks'
745
+ const INBOX_SOCKET_PREFIXES = [['tmp', INBOX_SOCKET_DIR], ['private', 'tmp', INBOX_SOCKET_DIR]]
746
+ const CLAUDE_SESSIONS_DIR = 'sessions'
747
+
748
+ /**
749
+ * A path resolved through its deepest existing ancestor. A component that is
750
+ * not a directory (ENOTDIR) means the path cannot exist, which is the same
751
+ * answer as a component that is missing: it names only itself.
752
+ * @param {string} p an absolute path
753
+ * @returns {string}
754
+ */
755
+ function _resolveRoot(p) {
756
+ try {
757
+ return realpathDeepestAncestorSync(p)
758
+ } catch (err) {
759
+ if (err?.code !== 'ENOTDIR') throw err
760
+ const parent = dirname(p)
761
+ if (parent === p) throw err
762
+ return join(_resolveRoot(parent), basename(p))
763
+ }
764
+ }
765
+
766
+ /**
767
+ * One protected directory set: each written path and its symlink-resolved
768
+ * form, so a root that is itself a link (or reached through one) is recognised
769
+ * from either side. `failed` is set when a path could not be resolved at all
770
+ * (for example EACCES on a parent); the written paths are still listed, and the
771
+ * caller then treats everything at or under them as the directory.
772
+ */
773
+ function _rootEntry(written, call) {
774
+ const resolveFn = call.resolveRootFn ?? _resolveRoot
775
+ const paths = new Set(written)
776
+ let failed = false
777
+ for (const p of written) {
778
+ try { paths.add(resolveFn(p)) } catch { failed = true }
779
+ }
780
+ return { paths: [...paths], failed }
781
+ }
782
+
783
+ /**
784
+ * The protected directories, resolved once per call. The sessions directory and
785
+ * the inbox directories are resolved independently, so a failure in one never
786
+ * reaches the other, and a failure affects only targets at or under that
787
+ * directory's written path (or a search reaching it), never an ordinary read.
788
+ * A config directory that cannot be determined at all names no sessions
789
+ * directory: the configured-root rule already decides for that case.
790
+ * @param {object} call
791
+ * @returns {{ sessions: { paths: string[], failed: boolean }, inbox: { paths: string[] } }}
792
+ */
793
+ function _protectedRoots(call) {
794
+ if (call.protectedRoots !== undefined) return call.protectedRoots
795
+ let sessions = { paths: [], failed: false }
796
+ try {
797
+ sessions = _rootEntry([join((call.configDirFn ?? claudeConfigDir)(), CLAUDE_SESSIONS_DIR)], call)
798
+ } catch { /* see above */ }
799
+ // The inbox roots are POSIX paths; there is nothing to resolve elsewhere.
800
+ const inbox = _rootEntry(call.inboxDirs ?? (sep === '/' ? ['/tmp/' + INBOX_SOCKET_DIR, '/private/tmp/' + INBOX_SOCKET_DIR] : []), call)
801
+ call.protectedRoots = { sessions, inbox: { paths: inbox.paths } }
802
+ return call.protectedRoots
803
+ }
804
+
805
+ /**
806
+ * Is the absolute `resolved` at or below an inbox socket directory? Compared
807
+ * case-insensitively, against the resolved form of each directory first (so a
808
+ * target of any depth, such as a root that resolves to `/sockets`, is judged),
809
+ * then in both the lowercased and the canonical spelling of each name. A name
810
+ * that cannot be canonicalised floors.
811
+ * @param {string} resolved
812
+ * @param {object} call
813
+ * @returns {boolean}
814
+ */
815
+ function _hitsInboxSocketDir(resolved, call) {
816
+ if (_protectedRoots(call).inbox.paths.some((root) => pathPiecesUnder(root, resolved, path) !== null)) return true
817
+ const raw = resolved.split(/[/\\]+/).filter((s) => s.length > 0 && s !== '..')
818
+ // A Windows drive (`C:`) is the root, not a directory name.
819
+ if (sep === '\\' && /^[A-Za-z]:$/.test(raw[0] ?? '')) raw.shift()
820
+ const pieces = raw.map(segmentName)
821
+ if (pieces.length < 2) return false
822
+ const lowered = pieces.map((p) => p.toLowerCase())
823
+ const canonical = []
824
+ for (const name of pieces) {
825
+ const form = _canonicalNameIn(name, call)
826
+ if (form === null) return true
827
+ canonical.push(form)
828
+ }
829
+ return INBOX_SOCKET_PREFIXES.some((prefix) =>
830
+ [lowered, canonical].some((names) => prefix.every((name, i) => names[i] === name)))
831
+ }
832
+
833
+ /**
834
+ * Is `resolved` the `sessions` directory of the configured Claude config
835
+ * directory itself, in either spelling? A search rooted there reaches every key
836
+ * file inside it, which the file-name rule alone does not see. A file inside it
837
+ * is judged by its own name, so ordinary files there are unaffected. When the
838
+ * directory could not be resolved, everything at or under its written path
839
+ * counts as it.
840
+ * @param {string} resolved
841
+ * @param {object} call
842
+ * @returns {boolean}
843
+ */
844
+ function _isSessionsDir(resolved, call) {
845
+ const { paths, failed } = _protectedRoots(call).sessions
846
+ return paths.some((root) => {
847
+ const inside = pathPiecesUnder(root, resolved, path)
848
+ return inside !== null && (failed || inside.length === 0)
849
+ })
850
+ }
851
+
852
+ /**
853
+ * Does a recursive content search rooted at the absolute `resolved`, strictly
854
+ * above the sessions directory, reach it? Claude Code's Grep passes `--hidden`
855
+ * (see the #7978 section), so a route through a dot-named directory counts:
856
+ * a search from `$HOME` reaches `~/.claude/sessions`.
857
+ * @param {string} resolved
858
+ * @param {object} call
859
+ * @returns {boolean}
860
+ */
861
+ function _searchReachesSessions(resolved, call) {
862
+ return _protectedRoots(call).sessions.paths.some((root) => {
863
+ const below = pathPiecesUnder(resolved, root, path)
864
+ return below !== null && below.length > 0
865
+ })
866
+ }
867
+
868
+ /**
869
+ * Does any segment from `start` on match the floor's names? `segments` are
870
+ * already in the form to compare (lowercased, or canonical).
871
+ * @param {string[]} segments
872
+ * @param {number} start
873
+ * @param {boolean} secretsOnly
874
+ * @returns {boolean}
875
+ */
876
+ function _matchesProtectedSegments(segments, start, secretsOnly) {
877
+ for (let i = start; i < segments.length; i++) {
239
878
  const seg = segments[i]
240
879
  // Secret files, and credential-dense config files, are floored under BOTH
241
880
  // the read and the write floor (PR #6873 review — the read floor must not
@@ -258,8 +897,10 @@ function _scanResolvedTarget(base, resolved, secretsOnly) {
258
897
  * TWO passes, ORed — a hit on EITHER floors the target:
259
898
  * (1) LEXICAL (the pre-#6851 floor, unchanged). `resolve()` absorbs absolute
260
899
  * paths, a leading `./`, and `..` traversal; the resolved path is scanned
261
- * segment-by-segment ({@link _scanResolvedTarget}). Pure string ops, no fs
262
- * access — fast, and every input the old floor flagged still flags.
900
+ * segment-by-segment ({@link _scanResolvedTarget}). String ops, plus the
901
+ * #8741 worktree lstat walk for a `.claude/worktrees/<name>/…` target —
902
+ * fast, and every input the old floor flagged still flags, except an
903
+ * ordinary file inside one of Claude Code's own worktrees.
263
904
  * (2) #6851/#6921 SYMLINK. The lexical pass is symlink-BLIND: because
264
905
  * `resolve()` collapses `..` textually, a symlink in cwd's PREFIX (the
265
906
  * chroxy agent worktree can live under a *symlink* to a real `.claude/`),
@@ -301,13 +942,26 @@ function _scanResolvedTarget(base, resolved, secretsOnly) {
301
942
  * the full (write) floor passes `secretsOnly = false`.
302
943
  * @param {string} target a path value from a tool input
303
944
  * @param {string} base the resolution base (session cwd)
304
- * @param {boolean} [secretsOnly] match only secret / credential files
945
+ * @param {boolean} secretsOnly match only secret / credential files
946
+ * @param {{ realBase: string|undefined, walk: { left: number }, names: Map<string, string>, canonical: { left: number } }} call
947
+ * state shared by one call's targets: the session cwd's real path once
948
+ * resolved, the walk budget left, the canonical names computed so far, and
949
+ * the characters of non-ASCII names left to compute
305
950
  * @returns {boolean}
306
951
  */
307
- function isProtectedPathValue(target, base, secretsOnly = false) {
952
+ function isProtectedPathValue(target, base, secretsOnly, call) {
953
+ // The work spent on one target is bounded before anything else runs.
954
+ if (_exceedsTargetBounds(target)) return true
955
+ // On POSIX `\` is a name character that both passes read as a separator, so
956
+ // a target holding one floors.
957
+ if (sep === '/' && target.includes('\\')) return true
308
958
  // (1) LEXICAL floor — pre-#6851 behavior, authoritative on a hit (no fs cost).
309
959
  const resolvedLexical = resolve(base, target)
310
- if (_scanResolvedTarget(base, resolvedLexical, secretsOnly)) return true
960
+ // #8741 — the worktree carve-out is decided once, on the path as written. An
961
+ // escaping relative path begins with `..` or is absolute, never `.claude`.
962
+ const lexicalRel = relative(base, resolvedLexical)
963
+ const carved = _insideClaudeWorktree(base, lexicalRel, target)
964
+ if (_scanResolvedTarget(base, resolvedLexical, secretsOnly, carved, call)) return true
311
965
  // (2) #6851/#6921 SYMLINK floor — resolve the real base, then walk the RAW
312
966
  // target component-by-component (open(2) semantics) and re-scan. A resolution
313
967
  // error FAILS CLOSED (return true → force the prompt). Runs only on a
@@ -324,12 +978,22 @@ function isProtectedPathValue(target, base, secretsOnly = false) {
324
978
  // (caught below → return true → force the prompt) instead of resolving
325
979
  // against process.cwd(). Wrapping in resolve() would defeat BOTH the guard
326
980
  // and the wrong-root framing it protects against.
327
- const realBase = realpathDeepestAncestorSync(base)
981
+ // Once per call: every target of one call shares the session cwd.
982
+ if (call.realBase === undefined) call.realBase = realpathDeepestAncestorSync(base)
983
+ const realBase = call.realBase
328
984
  // Pass the RAW `target` (its `..` intact) to the component walker, so a `..`
329
985
  // after a symlinked component climbs from the symlink's TARGET, not its
330
986
  // lexical parent. Do NOT pre-resolve() it — that would collapse the `..`.
331
- const realTarget = resolveTargetComponentwiseSync(realBase, target)
332
- return _scanResolvedTarget(realBase, realTarget, secretsOnly)
987
+ const realTarget = resolveTargetComponentwiseSync(realBase, target, call.walk)
988
+ // The carve-out survives only when the resolved path IS the written one. The
989
+ // written path held no symlink when `_insideClaudeWorktree` walked it, so
990
+ // this differs only if the path changed between the two walks; then the
991
+ // resolved target gets the full scan rather than an offset meant for another
992
+ // path.
993
+ const stillCarved = carved && relative(realBase, realTarget) === lexicalRel
994
+ if (_scanResolvedTarget(realBase, realTarget, secretsOnly, stillCarved, call)) return true
995
+ // Under the full floor, an existing target with more than one hard link floors.
996
+ return !secretsOnly && _hasOtherHardLinks(realTarget)
333
997
  } catch {
334
998
  return true
335
999
  }
@@ -362,10 +1026,13 @@ function isProtectedPathValue(target, base, secretsOnly = false) {
362
1026
  * prefix excluded). But a `..`-traversal back UP into that same `.claude`
363
1027
  * (`../../settings.local.json` → the real agent config) IS floored, because an
364
1028
  * above-cwd target is scanned as its resolved ABSOLUTE path (#6806). See
365
- * {@link isProtectedPathValue} for the full reconciliation.
1029
+ * {@link isProtectedPathValue} for the full reconciliation. A Claude Code
1030
+ * worktree BELOW cwd (`.claude/worktrees/<name>/…`) is a workspace too: its
1031
+ * ordinary files are not floored, its own config and secrets are (#8741,
1032
+ * {@link _insideClaudeWorktree}).
366
1033
  *
367
1034
  * Segment rules (a match on ANY segment floors the write; see
368
- * {@link isProtectedPathValue} for the lowercase rationale):
1035
+ * {@link canonicalName} for the forms segments are compared in):
369
1036
  * - a segment in {@link PROTECTED_DIR_SEGMENTS} (`.git` / `.claude` / `.vscode`)
370
1037
  * - a `.config` segment immediately followed by `git` (the XDG git-config dir)
371
1038
  * - a segment that is `.env` or starts with `.env.` (`.env` / `.env.local` / …)
@@ -404,28 +1071,454 @@ export function isSecretReadTarget(input, cwd) {
404
1071
  * resolving each against the session cwd, and tests it with {@link isProtectedPathValue}.
405
1072
  * `secretsOnly` selects the read floor (secret files) vs the full write floor
406
1073
  * (config dirs + secret files). ANY protected field/member floors the input.
1074
+ * The call as a whole is bounded too: more than FLOOR_MAX_CALL_TARGETS targets,
1075
+ * FLOOR_MAX_CALL_COMPONENTS components or FLOOR_MAX_CALL_BYTES bytes across them,
1076
+ * more than FLOOR_MAX_CALL_WALK components walked, or more than
1077
+ * FLOOR_MAX_CALL_CANONICAL characters of distinct non-ASCII names compared,
1078
+ * floors it.
407
1079
  * @param {object} input
408
1080
  * @param {string} [cwd]
409
1081
  * @param {boolean} secretsOnly
410
1082
  * @returns {boolean}
411
1083
  */
1084
+ function _newCall(statFn) {
1085
+ return {
1086
+ realBase: undefined,
1087
+ configRoot: undefined,
1088
+ walk: { left: FLOOR_MAX_CALL_WALK },
1089
+ idBudget: { left: FLOOR_MAX_CALL_IDENTITY },
1090
+ names: new Map(),
1091
+ canonical: { left: FLOOR_MAX_CALL_CANONICAL },
1092
+ ids: new Map(),
1093
+ statFn,
1094
+ }
1095
+ }
1096
+
412
1097
  function _matchesFloor(input, cwd, secretsOnly) {
413
1098
  if (!input || typeof input !== 'object') return false
414
1099
  const base = (typeof cwd === 'string' && cwd.length > 0) ? cwd : process.cwd()
1100
+ const targets = []
415
1101
  for (const field of PROTECTED_PATH_INPUT_FIELDS) {
416
1102
  if (typeof input[field] !== 'string' || input[field].length === 0) continue
417
- if (isProtectedPathValue(input[field], base, secretsOnly)) return true
1103
+ targets.push(input[field])
418
1104
  }
419
- // #6805/#6828 — walk the array-shaped per-file targets (codex apply_patch).
1105
+ // #6805/#6828 — the array-shaped per-file targets (codex apply_patch). Every
1106
+ // member counts toward the call's target budget, whatever it holds, so the
1107
+ // array is never enumerated past the budget.
420
1108
  if (Array.isArray(input.changes)) {
421
- for (const change of input.changes) {
422
- if (!change || typeof change.path !== 'string' || change.path.length === 0) continue
423
- if (isProtectedPathValue(change.path, base, secretsOnly)) return true
1109
+ if (targets.length + input.changes.length > FLOOR_MAX_CALL_TARGETS) return true
1110
+ for (const changePath of collectChangeTargets(input.changes).paths) targets.push(changePath)
1111
+ if (targets.length > FLOOR_MAX_CALL_TARGETS) return true
1112
+ }
1113
+ // The call's component and byte budgets, checked before any target is resolved.
1114
+ let components = 0
1115
+ let bytes = 0
1116
+ for (const target of targets) {
1117
+ components += _componentCount(target, FLOOR_MAX_CALL_COMPONENTS - components)
1118
+ if (components > FLOOR_MAX_CALL_COMPONENTS) return true
1119
+ bytes += Buffer.byteLength(target, 'utf8')
1120
+ if (bytes > FLOOR_MAX_CALL_BYTES) return true
1121
+ }
1122
+ const call = _newCall()
1123
+ for (const target of targets) {
1124
+ if (isProtectedPathValue(target, base, secretsOnly, call)) return true
1125
+ }
1126
+ return false
1127
+ }
1128
+
1129
+ // ---------------------------------------------------------------------------
1130
+ // #7978 — Grep's FILE-SELECTING `glob` field.
1131
+ //
1132
+ // The path fields above say WHERE a Grep searches; `glob` says WHICH FILES in
1133
+ // there it reads, and it is the stronger of the two. Every Grep implementation
1134
+ // Chroxy fronts runs ripgrep, and an include glob OVERRIDES ripgrep's ignore
1135
+ // rules: `rg --glob=.env -e X -- .` reads a gitignored `.env`, and so do `*`,
1136
+ // `**`, `sub/*`, `.e?v` and `*env*`. Claude Code's own Grep always passes
1137
+ // `--hidden`, so ripgrep's hidden-file filter is no barrier there; `.gitignore`
1138
+ // is the only one, and a glob walks straight through it. `*.json` is the
1139
+ // ordinary case, not the exotic one: it reads the `.claude/settings.local.json`
1140
+ // that Claude Code gitignores by default. Measured with ripgrep 15.2.0.
1141
+ //
1142
+ // Scanning only `path` therefore let `Grep({path: '.', glob: '.env'})` read
1143
+ // secrets while the floor answered "not floored", and a lenient mode then
1144
+ // auto-approved it.
1145
+ //
1146
+ // WHAT FLOORS. First, anything outside a small grammar floors unanalyzed:
1147
+ // ASCII letters, digits, `. _ - / !`, whitespace, `*`, `**`, `?`, and `{a,b}`
1148
+ // groups that hold at least one comma. A class, an escape, a single-alternative
1149
+ // or empty brace, or any non-ASCII character floors (GLOB_FLOOR_ANALYZABLE
1150
+ // says why). A glob inside the grammar is taken apart the way ripgrep takes it
1151
+ // (a pattern without a `/` matches a basename at any depth) and intersected with
1152
+ // TEMPLATES built from the floor's own name sets above. It floors when it can
1153
+ // match:
1154
+ // (a) an EXACT secret path, however it gets there: `.env`, SECRET_FILE_EXACT,
1155
+ // the CREDENTIAL_CONFIG_SEQUENCES, `.claude/settings{,.local}.json`, plus
1156
+ // the common real-world names in the two witness lists below. `*`, `**`,
1157
+ // `sub/*`, `*.json` and `*test*` all floor here;
1158
+ // (b) a member of a secret FAMILY — `.env.<tail>`, `<stem><secret ext>`,
1159
+ // `.claude/settings<mid>.json` — PROVIDED at least one character of the
1160
+ // family's defining part (`.env`, the extension, the settings skeleton) is
1161
+ // matched by something other than `*`/`**`. `.e?v.*`, `.env.????`,
1162
+ // `?.pem` and `*v.*` floor here.
1163
+ //
1164
+ // THE ONE ACCEPTED RESIDUAL, stated because (b) is where it lives. `*.ts` can
1165
+ // match `.env.ts`, a name the floor counts as a secret. It does so only by
1166
+ // letting `*` swallow the whole of `.env`, so it does not floor: a strictly
1167
+ // sound rule would floor every extension filter (`*.ts`, `*.py`) and prompt on
1168
+ // nearly every globbed Grep in a lenient mode. What still gets through is an
1169
+ // extension or stem filter aimed at a GITIGNORED secret whose name is none of
1170
+ // the witnesses — `*.ts` reading a gitignored `.env.ts`. The witness lists
1171
+ // exist to keep that set to unusual names. The same mechanism applies to a
1172
+ // DIRECTORY: `{*.d,*.conf}` can re-include a gitignored `.env.d/` and read its
1173
+ // `app.conf`, because `*` swallowed the `.env`.
1174
+ //
1175
+ // NOT COVERED, and not this field's job: a Grep with no glob reads every file
1176
+ // the ignore rules let through, secrets included when they are not gitignored.
1177
+ // That is the directory-grep limit of a path floor, unchanged here. Grep's
1178
+ // `type` field is not inspected because ripgrep's type filters RESPECT
1179
+ // `.gitignore` (measured: `-t sh` does not read a gitignored `.env`, though the
1180
+ // `sh` type lists it), so they select nothing a plain Grep does not. Glob's
1181
+ // `pattern` is not inspected either: it returns names, never contents.
1182
+
1183
+ /**
1184
+ * Tools whose input carries a file-selecting `glob` the floor inspects. The
1185
+ * shell hook's negative pre-filter keys on these NAMES (a `"Grep"` payload must
1186
+ * reach the daemon even with no path field) — tests/permission-hook-floor.test.js
1187
+ * asserts the hook matches every member.
1188
+ */
1189
+ export const GLOB_SELECTOR_FLOOR_TOOLS = new Set(['Grep'])
1190
+
1191
+ // Common real-world secret names that only a (b)-exempt glob — one that
1192
+ // constrains the tail or the stem, not the defining part — could otherwise
1193
+ // reach. Each must be a secret by the floor's OWN predicate (asserted in
1194
+ // tests/permission-floor-grep-glob.test.js), so this list can only ever add
1195
+ // floors to names the floor already protects; it cannot widen what counts as a
1196
+ // secret. Missing a name here reopens only the residual described above.
1197
+ const ENV_TAIL_WITNESSES = [
1198
+ 'local', 'development', 'production', 'test', 'staging', 'dev', 'prod',
1199
+ 'example', 'sample', 'ci', 'qa', 'uat', 'preview', 'backup', 'bak', 'old',
1200
+ 'secret', 'secrets', 'docker', 'development.local', 'production.local', 'test.local',
1201
+ ]
1202
+ const KEY_STEM_WITNESSES = ['server', 'private', 'privkey', 'key', 'cert', 'fullchain', 'tls', 'client', 'ca', 'id']
1203
+
1204
+ /**
1205
+ * The floor's secret-name sets, read-only, so tests can derive their corpus
1206
+ * from the floor instead of restating it (tests/permission-floor-grep-glob.test.js).
1207
+ */
1208
+ export const FLOOR_SECRET_NAMES = Object.freeze({
1209
+ envName: ENV_FILE_NAME,
1210
+ envPrefix: ENV_FILE_PREFIX,
1211
+ exact: Object.freeze([...SECRET_FILE_EXACT]),
1212
+ extensions: Object.freeze([...SECRET_FILE_EXTENSIONS]),
1213
+ credentialConfigPaths: Object.freeze(CREDENTIAL_CONFIG_SEQUENCES.map((sequence) => sequence.join('/'))),
1214
+ claudeSettings: Object.freeze({ dir: CLAUDE_SETTINGS_DIR, prefix: CLAUDE_SETTINGS_PREFIX, suffix: CLAUDE_SETTINGS_SUFFIX }),
1215
+ envTailWitnesses: Object.freeze([...ENV_TAIL_WITNESSES]),
1216
+ keyStemWitnesses: Object.freeze([...KEY_STEM_WITNESSES]),
1217
+ })
1218
+
1219
+ // Bounds on the analysis. Past any one the glob FLOORS (fail closed): a
1220
+ // pathological glob is not something to analyze at length on the hot path.
1221
+ // An ordinary glob visits ~10K search states (~1ms); the largest legitimate
1222
+ // shapes the caps allow visit ~450K (~9ms). A crafted glob can still multiply
1223
+ // states — `(**q)` repeated 330 times visited 5.8M (71ms, synchronous on the
1224
+ // daemon's event loop) — so one Grep call gets a shared STATE budget, and
1225
+ // running out of it floors (PR #7980 review).
1226
+ const GLOB_FLOOR_MAX_LENGTH = 1024
1227
+ const GLOB_FLOOR_MAX_ALTERNATIVES = 64
1228
+ const GLOB_FLOOR_MAX_EXPANDED_LENGTH = 4096
1229
+ export const GLOB_FLOOR_MAX_STATES = 1_000_000
1230
+
1231
+ let _globFloorTemplates = null
1232
+ let _globFloorTemplatesRootRelative = null
1233
+
1234
+ /**
1235
+ * The templates a Grep glob is intersected with, built once from the floor's
1236
+ * own sets. A template is a list of elements over a lowercased path:
1237
+ * { kind: 'lit', ch, core } one fixed character (`core`: part of a family's
1238
+ * defining text, see (b) above)
1239
+ * { kind: 'one' } exactly one non-`/` character
1240
+ * { kind: 'star', slash } any run of characters (`/` too when `slash`)
1241
+ * Every template also gets an any-directory-prefix variant, because a secret can
1242
+ * sit at any depth under the searched root.
1243
+ * `rootRelative` adds the `settings*.json` names bare (not behind `.claude/`),
1244
+ * for a search that reaches a configured Claude config directory whose name is
1245
+ * not `.claude` (see {@link _configRootRule}).
1246
+ * @param {boolean} [rootRelative]
1247
+ * @returns {{ elems: object[], requireCore: boolean }[]}
1248
+ */
1249
+ function globFloorTemplates(rootRelative = false) {
1250
+ const cached = rootRelative ? _globFloorTemplatesRootRelative : _globFloorTemplates
1251
+ if (cached) return cached
1252
+ const lit = (text, core) => [...text].map((ch) => ({ kind: 'lit', ch, core }))
1253
+ const oneOrMore = [{ kind: 'one' }, { kind: 'star', slash: false }]
1254
+ const base = []
1255
+ const exact = (path) => base.push({ elems: lit(path, false), requireCore: false })
1256
+
1257
+ exact(ENV_FILE_NAME)
1258
+ for (const name of SECRET_FILE_EXACT) exact(name)
1259
+ for (const sequence of CREDENTIAL_CONFIG_SEQUENCES) exact(sequence.join('/'))
1260
+ for (const name of ['', '.local']) {
1261
+ exact(`${CLAUDE_SETTINGS_DIR}/${CLAUDE_SETTINGS_PREFIX}${name}${CLAUDE_SETTINGS_SUFFIX}`)
1262
+ }
1263
+ for (const tail of ENV_TAIL_WITNESSES) exact(ENV_FILE_PREFIX + tail)
1264
+ for (const stem of KEY_STEM_WITNESSES) {
1265
+ for (const ext of SECRET_FILE_EXTENSIONS) exact(stem + ext)
1266
+ }
1267
+
1268
+ // Families. The `.` that ends ENV_FILE_PREFIX is a separator, not part of the
1269
+ // env-ness, so it is NOT core — otherwise `*.ts` would spell it and floor.
1270
+ base.push({
1271
+ elems: [...lit(ENV_FILE_NAME, true), ...lit('.', false), ...oneOrMore],
1272
+ requireCore: true,
1273
+ })
1274
+ for (const ext of SECRET_FILE_EXTENSIONS) {
1275
+ base.push({ elems: [...oneOrMore, ...lit(ext, true)], requireCore: true })
1276
+ }
1277
+ base.push({
1278
+ elems: [
1279
+ ...lit(`${CLAUDE_SETTINGS_DIR}/${CLAUDE_SETTINGS_PREFIX}`, true),
1280
+ { kind: 'star', slash: false },
1281
+ ...lit(CLAUDE_SETTINGS_SUFFIX, true),
1282
+ ],
1283
+ requireCore: true,
1284
+ })
1285
+
1286
+ if (rootRelative) {
1287
+ for (const name of ['', '.local']) exact(`${CLAUDE_SETTINGS_PREFIX}${name}${CLAUDE_SETTINGS_SUFFIX}`)
1288
+ base.push({
1289
+ elems: [...lit(CLAUDE_SETTINGS_PREFIX, true), { kind: 'star', slash: false }, ...lit(CLAUDE_SETTINGS_SUFFIX, true)],
1290
+ requireCore: true,
1291
+ })
1292
+ }
1293
+
1294
+ const anyDirectory = [{ kind: 'star', slash: true }, { kind: 'lit', ch: '/', core: false }]
1295
+ const built = base.flatMap((t) => [t, { elems: [...anyDirectory, ...t.elems], requireCore: t.requireCore }])
1296
+ if (rootRelative) _globFloorTemplatesRootRelative = built
1297
+ else _globFloorTemplates = built
1298
+ return built
1299
+ }
1300
+
1301
+ // The only characters the analysis models (PR #7980 review). Anything else in a
1302
+ // glob — a `[...]` class, a `\` escape, any non-ASCII character
1303
+ // (ripgrep trims trailing Unicode whitespace such as U+0085 that `\s` does not
1304
+ // match) — FLOORS without analysis. Four independent mismatches with ripgrep's
1305
+ // globset were found in exactly those constructs (a class matching `/`, `\`
1306
+ // being literal inside a class, chained ranges, a `,` inside a class inside a
1307
+ // brace group), so the parser does not try to be globset: it recognizes a small
1308
+ // grammar and refuses the rest. The ordinary filters (`*.ts`, `*.{ts,tsx}`,
1309
+ // `src/**/*.py`) are all inside it.
1310
+ // A `!` past the first character is a literal to ripgrep (only a LEADING `!`
1311
+ // negates, and classes are excluded), so it is kept.
1312
+ const GLOB_FLOOR_ANALYZABLE = /^[A-Za-z0-9._/*?{},!\- \t\n\r\v\f]*$/
1313
+ // Claude Code passes each whitespace/comma piece as its own --glob; past this
1314
+ // many pieces the call floors rather than analyze each one.
1315
+ const GLOB_FLOOR_MAX_PIECES = 32
1316
+
1317
+ /**
1318
+ * Expand `{a,b}` alternatives (nested too). Every `{` must close and hold at
1319
+ * least one top-level comma: ripgrep treats `{x}` and `{}` as a real
1320
+ * alternation (`{.env}` reads `.env`), so a brace this function cannot expand
1321
+ * is not "literal text" — the caller floors it. Returns null for an unmatched
1322
+ * or comma-less brace, a stray `}`, or past {@link GLOB_FLOOR_MAX_ALTERNATIVES}.
1323
+ * Runs only on {@link GLOB_FLOOR_ANALYZABLE} input, so there is no `[` or `\`
1324
+ * that could hide a brace or a comma.
1325
+ * @param {string} glob
1326
+ * @returns {string[] | null}
1327
+ */
1328
+ function expandGlobBraces(glob) {
1329
+ const open = glob.indexOf('{')
1330
+ if (open === -1) return glob.includes('}') ? null : [glob]
1331
+ if (glob.slice(0, open).includes('}')) return null
1332
+ let depth = 0
1333
+ const commas = []
1334
+ let close = -1
1335
+ for (let i = open; i < glob.length; i++) {
1336
+ const ch = glob[i]
1337
+ if (ch === '{') depth++
1338
+ else if (ch === '}') {
1339
+ depth--
1340
+ if (depth === 0) { close = i; break }
1341
+ } else if (ch === ',' && depth === 1) commas.push(i)
1342
+ }
1343
+ if (close === -1 || commas.length === 0) return null
1344
+ const head = glob.slice(0, open)
1345
+ const tail = glob.slice(close + 1)
1346
+ const bounds = [open, ...commas, close]
1347
+ const out = []
1348
+ for (let k = 0; k < bounds.length - 1; k++) {
1349
+ const expanded = expandGlobBraces(head + glob.slice(bounds[k] + 1, bounds[k + 1]) + tail)
1350
+ if (expanded === null) return null
1351
+ out.push(...expanded)
1352
+ if (out.length > GLOB_FLOOR_MAX_ALTERNATIVES) return null
1353
+ }
1354
+ return out
1355
+ }
1356
+
1357
+ /**
1358
+ * Tokenize one brace-free alternative of an analyzable glob: `*`, `**`, `?`
1359
+ * and literals. `**` anywhere is a cross-directory wildcard and swallows a
1360
+ * following `/` (so `a/**\/b` still matches `a/b`); treating a non-segment `**`
1361
+ * that way only ever admits more, i.e. floors more.
1362
+ * @param {string} glob
1363
+ * @returns {object[]}
1364
+ */
1365
+ function tokenizeGlob(glob) {
1366
+ const tokens = []
1367
+ for (let i = 0; i < glob.length; i++) {
1368
+ const ch = glob[i]
1369
+ if (ch === '*') {
1370
+ if (glob[i + 1] === '*') {
1371
+ i++
1372
+ while (glob[i + 1] === '*') i++
1373
+ if (glob[i + 1] === '/') i++
1374
+ // `**/**/` matches exactly what `**/` does; collapsing the run keeps a
1375
+ // 330-deep repetition from costing 20ms of search (PR #7980 review).
1376
+ if (tokens.length === 0 || tokens[tokens.length - 1].kind !== 'globstar') tokens.push({ kind: 'globstar' })
1377
+ } else {
1378
+ tokens.push({ kind: 'star' })
1379
+ }
1380
+ } else if (ch === '?') {
1381
+ tokens.push({ kind: 'any' })
1382
+ } else {
1383
+ tokens.push({ kind: 'lit', ch })
424
1384
  }
425
1385
  }
1386
+ return tokens
1387
+ }
1388
+
1389
+ /**
1390
+ * Can glob token `tok` consume the (lowercase) template character `ch`? The
1391
+ * floor lowercases names, so a literal admits `ch` when it lowercases to it.
1392
+ */
1393
+ function _tokenAdmits(tok, ch) {
1394
+ switch (tok.kind) {
1395
+ case 'lit': return tok.ch.toLowerCase() === ch
1396
+ case 'any': case 'star': return ch !== '/'
1397
+ case 'globstar': return true
1398
+ default: return true
1399
+ }
1400
+ }
1401
+
1402
+ /**
1403
+ * Is there a string that both the glob `tokens` and template `t` match — and,
1404
+ * when `t.requireCore`, one where some `core` character is consumed by a token
1405
+ * other than `*`/`**`? A search over (glob position, template position, core
1406
+ * seen) — at most (|tokens|+1) x (|template|+1) x 2 states. Every state visited
1407
+ * is charged to `budget`; past it the answer is null, which the caller floors.
1408
+ * @returns {boolean | null}
1409
+ */
1410
+ function _globMatchesTemplate(tokens, t, budget) {
1411
+ const elems = t.elems
1412
+ const G = tokens.length
1413
+ const T = elems.length
1414
+ const seen = new Uint8Array((G + 1) * (T + 1) * 2)
1415
+ const stack = [0, 0, 0]
1416
+ while (stack.length > 0) {
1417
+ const core = stack.pop()
1418
+ const ti = stack.pop()
1419
+ const gi = stack.pop()
1420
+ const key = (gi * (T + 1) + ti) * 2 + core
1421
+ if (seen[key]) continue
1422
+ seen[key] = 1
1423
+ if (--budget.left < 0) return null
1424
+ if (gi === G && ti === T && (core === 1 || !t.requireCore)) return true
1425
+ const g = gi < G ? tokens[gi] : null
1426
+ const e = ti < T ? elems[ti] : null
1427
+ const gRepeats = g !== null && (g.kind === 'star' || g.kind === 'globstar')
1428
+ // A wildcard on either side may match nothing.
1429
+ if (gRepeats) stack.push(gi + 1, ti, core)
1430
+ if (e !== null && e.kind === 'star') stack.push(gi, ti + 1, core)
1431
+ if (g === null || e === null) continue
1432
+ // Or both consume one character.
1433
+ let joint
1434
+ if (e.kind === 'lit') joint = _tokenAdmits(g, e.ch)
1435
+ else if (e.kind === 'star' && e.slash) joint = true
1436
+ else joint = g.kind !== 'lit' || g.ch !== '/'
1437
+ if (!joint) continue
1438
+ const nextCore = (core === 1 || (e.kind === 'lit' && e.core && !gRepeats)) ? 1 : 0
1439
+ stack.push(gRepeats ? gi : gi + 1, e.kind === 'star' ? ti : ti + 1, nextCore)
1440
+ }
426
1441
  return false
427
1442
  }
428
1443
 
1444
+ /**
1445
+ * #7978 — can a single ripgrep glob select a secret file? See the section
1446
+ * comment above for exactly what floors and the one accepted residual. Trailing
1447
+ * ASCII whitespace is trimmed, as ripgrep trims it; LEADING whitespace is kept,
1448
+ * because ripgrep keeps it (` !x` is a literal include, not an exclusion). A
1449
+ * leading `!` only excludes, so it never floors. Outside
1450
+ * {@link GLOB_FLOOR_ANALYZABLE}, with a brace that does not expand, past a size
1451
+ * cap, or once `budget` runs out, the glob floors without a full analysis.
1452
+ * @param {string} glob
1453
+ * @param {{ left: number }} [budget] search states left; shared across one Grep call
1454
+ * @param {boolean} [rootRelative] also match bare `settings*.json` (see {@link globFloorTemplates})
1455
+ * @returns {boolean}
1456
+ */
1457
+ export function globSelectsSecret(glob, budget = { left: GLOB_FLOOR_MAX_STATES }, rootRelative = false) {
1458
+ if (typeof glob !== 'string') return true
1459
+ if (glob.length > GLOB_FLOOR_MAX_LENGTH) return true
1460
+ const trimmed = glob.replace(/[ \t\n\r\v\f]+$/, '')
1461
+ if (trimmed.length === 0) return false
1462
+ if (trimmed.startsWith('!')) return false
1463
+ if (!GLOB_FLOOR_ANALYZABLE.test(trimmed)) return true
1464
+ const alternatives = expandGlobBraces(trimmed)
1465
+ if (alternatives === null) return true
1466
+ if (alternatives.reduce((sum, alt) => sum + alt.length, 0) > GLOB_FLOOR_MAX_EXPANDED_LENGTH) return true
1467
+ const templates = globFloorTemplates(rootRelative)
1468
+ for (let alt of alternatives) {
1469
+ // Anchors: ripgrep roots a leading `/` at the search root, and `./` names
1470
+ // the same place. Both only narrow where a match can sit; drop them.
1471
+ while (alt.startsWith('/') || alt.startsWith('./')) alt = alt.startsWith('/') ? alt.slice(1) : alt.slice(2)
1472
+ // A trailing `/` means "directories only", and ripgrep drops it BEFORE it
1473
+ // decides whether the glob is anchored: `.env/` behaves as `**/.env` and
1474
+ // re-includes a gitignored `.env/` directory for another piece to read
1475
+ // from (PR #7980 review). Drop it here too, before the same decision.
1476
+ while (alt.endsWith('/')) alt = alt.slice(0, -1)
1477
+ if (alt.length === 0) continue
1478
+ const tokens = tokenizeGlob(alt)
1479
+ // Without a `/`, ripgrep matches the basename at any depth: try the glob
1480
+ // both against a top-level name and behind an arbitrary directory.
1481
+ const variants = alt.includes('/')
1482
+ ? [tokens]
1483
+ : [tokens, [{ kind: 'globstar' }, { kind: 'lit', ch: '/' }, ...tokens]]
1484
+ for (const variant of variants) {
1485
+ for (const t of templates) {
1486
+ const hit = _globMatchesTemplate(variant, t, budget)
1487
+ if (hit !== false) return true
1488
+ }
1489
+ }
1490
+ }
1491
+ return false
1492
+ }
1493
+
1494
+ /**
1495
+ * #7978 — do a Grep input's `glob` values select a secret? Claude Code splits
1496
+ * the field on whitespace and then on commas (unless the piece holds a `{...}`
1497
+ * group) and passes each piece as its own `--glob`; the BYOK executor passes
1498
+ * the whole string as ONE `--glob`. Both readings are checked, and either one
1499
+ * flooring floors the input. A `glob` that is present but not a string floors:
1500
+ * the floor cannot say what an executor would make of it. So does one too long
1501
+ * to split, or one that splits into more than {@link GLOB_FLOOR_MAX_PIECES}.
1502
+ * @param {object} input
1503
+ * @returns {boolean}
1504
+ */
1505
+ function grepGlobFloored(input, rootRelative) {
1506
+ const glob = input.glob
1507
+ if (glob === undefined || glob === null) return false
1508
+ if (typeof glob !== 'string') return true
1509
+ if (glob.length > GLOB_FLOOR_MAX_LENGTH) return true
1510
+ const readings = new Set([glob])
1511
+ for (const piece of glob.split(/\s+/)) {
1512
+ if (piece.includes('{') && piece.includes('}')) readings.add(piece)
1513
+ else for (const part of piece.split(',')) readings.add(part)
1514
+ if (readings.size > GLOB_FLOOR_MAX_PIECES) return true
1515
+ }
1516
+ const budget = { left: GLOB_FLOOR_MAX_STATES }
1517
+ for (const reading of readings) {
1518
+ if (globSelectsSecret(reading, budget, rootRelative)) return true
1519
+ }
1520
+ return false
1521
+ }
429
1522
  /**
430
1523
  * #7004 — the floor decision for ONE (tool, input) pair: the tool-aware choice
431
1524
  * between the read floor and the full write floor, plus the predicate itself.
@@ -449,7 +1542,229 @@ function _matchesFloor(input, cwd, secretsOnly) {
449
1542
  * @returns {boolean} true when the target is floored (prompt required)
450
1543
  */
451
1544
  export function isFlooredTarget(toolName, input, cwd) {
452
- return SECRET_READ_FLOOR_TOOLS.has(toolName)
453
- ? isSecretReadTarget(input, cwd)
454
- : isProtectedPathTarget(input, cwd)
1545
+ // A patch whose change list is missing, malformed or empty names no paths the
1546
+ // floor can judge, so it always prompts.
1547
+ if (toolName === 'apply_patch' && !_hasCompleteChangeList(input)) return true
1548
+ if (!SECRET_READ_FLOOR_TOOLS.has(toolName)) return isProtectedPathTarget(input, cwd)
1549
+ if (isSecretReadTarget(input, cwd)) return true
1550
+ if (SEARCH_ROOT_TOOLS.has(toolName) && _searchRootFloored(toolName, input, cwd)) return true
1551
+ // #7978 — Grep's `glob` picks WHICH files it reads, overriding .gitignore.
1552
+ if (!GLOB_SELECTOR_FLOOR_TOOLS.has(toolName) || input === null || typeof input !== 'object') return false
1553
+ const reach = _searchReachToConfigRoot(input, cwd)
1554
+ if (grepGlobFloored(input, reach.near)) return true
1555
+ // No glob narrowing the search: a recursive Grep from the configured root, or
1556
+ // from a directory above it, reads the settings files inside it.
1557
+ return reach.covers && !globNarrowsSearch(input.glob)
1558
+ }
1559
+
1560
+ /**
1561
+ * Does a patch input carry a non-empty, well-formed `changes` array?
1562
+ * @param {object} input
1563
+ * @returns {boolean}
1564
+ */
1565
+ function _hasCompleteChangeList(input) {
1566
+ if (input === null || typeof input !== 'object') return false
1567
+ if (!Array.isArray(input.changes) || input.changes.length === 0) return false
1568
+ return collectChangeTargets(input.changes).complete
1569
+ }
1570
+
1571
+ /**
1572
+ * Can the Grep `glob` provably not select a `.key` file? True only when it has
1573
+ * at least one piece and every piece (judged alone, under each reading of the field,
1574
+ * see {@link grepGlobFloored}) is inside the analysable grammar and ends in a fixed
1575
+ * extension other than `key`: `*.js`, `src/**\/*.{js,ts}`. Anything else is
1576
+ * treated as able to select one, including `*`, `**`, `sessions/123*`,
1577
+ * `sessions/**`, `**\/*.key`, a class or escape, a directory (trailing `/`), and
1578
+ * a glob that only excludes. Case-insensitive on the extension.
1579
+ * @param {unknown} glob
1580
+ * @returns {boolean}
1581
+ */
1582
+ function globAvoidsKeyFiles(glob) {
1583
+ if (typeof glob !== 'string' || glob.length === 0 || glob.length > GLOB_FLOOR_MAX_LENGTH) return false
1584
+ // Any `!` can turn a piece into an exclusion under one reading of the field
1585
+ // and leave it an include under another, so none can be reasoned about.
1586
+ if (glob.includes('!')) return false
1587
+ const readings = new Set([glob])
1588
+ for (const piece of glob.split(/\s+/)) {
1589
+ if (piece.includes('{') && piece.includes('}')) readings.add(piece)
1590
+ else for (const part of piece.split(',')) readings.add(part)
1591
+ if (readings.size > GLOB_FLOOR_MAX_PIECES) return false
1592
+ }
1593
+ let judged = 0
1594
+ for (const reading of readings) {
1595
+ const trimmed = reading.replace(/[ \t\n\r\v\f]+$/, '')
1596
+ // Nothing is passed to ripgrep for an empty piece; each real one is judged alone.
1597
+ if (trimmed.length === 0) continue
1598
+ if (!GLOB_FLOOR_ANALYZABLE.test(trimmed)) return false
1599
+ const alternatives = expandGlobBraces(trimmed)
1600
+ if (alternatives === null) return false
1601
+ if (alternatives.reduce((sum, alt) => sum + alt.length, 0) > GLOB_FLOOR_MAX_EXPANDED_LENGTH) return false
1602
+ for (const alt of alternatives) {
1603
+ const last = alt.slice(alt.lastIndexOf('/') + 1)
1604
+ const dot = last.lastIndexOf('.')
1605
+ const ext = dot === -1 ? '' : last.slice(dot + 1)
1606
+ if (ext.length === 0 || /[*?]/.test(ext) || ext.toLowerCase() === 'key') return false
1607
+ }
1608
+ judged++
1609
+ }
1610
+ return judged > 0
1611
+ }
1612
+
1613
+ export const SEARCH_ROOT_TOOLS = new Set(['Grep', 'Glob'])
1614
+
1615
+ /**
1616
+ * The directory a Grep / Glob call searches from, as the executor reads it: its
1617
+ * `path`, or the session cwd (`'.'`) when `path` is absent, null or empty. Other fields
1618
+ * never stand in for it. Returns null when `path` is present but not a usable
1619
+ * string, so the caller fails closed.
1620
+ * @param {object} input
1621
+ * @returns {string|null}
1622
+ */
1623
+ export function effectiveSearchRoot(input) {
1624
+ const value = input?.path
1625
+ if (value === undefined || value === null || value === '') return '.'
1626
+ return typeof value === 'string' && value.length > 0 ? value : null
1627
+ }
1628
+
1629
+ /**
1630
+ * The paths to judge for a search call: its effective root, plus any other flat
1631
+ * path field it carries (which may add checks, never replace the root).
1632
+ * Returns null when the root is unusable.
1633
+ * @param {object} input
1634
+ * @returns {string[]|null}
1635
+ */
1636
+ function _searchTargets(input) {
1637
+ const root = effectiveSearchRoot(input)
1638
+ if (root === null) return null
1639
+ const targets = [root]
1640
+ for (const f of PROTECTED_PATH_INPUT_FIELDS) {
1641
+ if (f !== 'path' && typeof input[f] === 'string' && input[f].length > 0) targets.push(input[f])
1642
+ }
1643
+ return targets
1644
+ }
1645
+
1646
+ /**
1647
+ * Where a Grep / Glob searches, against the inbox socket and sessions rules.
1648
+ * A call with no path field searches from the session cwd, so the cwd stands
1649
+ * in for the missing root; a supplied root is judged in its written and its
1650
+ * symlink-resolved form. A Grep also floors from the sessions directory's
1651
+ * parent or an ancestor of it when it can reach it (see
1652
+ * {@link _searchReachesSessions}) and no `glob` narrows it. A Glob returns
1653
+ * names only, so it floors only when rooted in the directories themselves.
1654
+ * Fails closed.
1655
+ * @param {string} toolName
1656
+ * @param {object} input
1657
+ * @param {string} [cwd]
1658
+ * @returns {boolean}
1659
+ */
1660
+ function _searchRootFloored(toolName, input, cwd) {
1661
+ if (input === null || typeof input !== 'object') return false
1662
+ const base = (typeof cwd === 'string' && cwd.length > 0) ? cwd : process.cwd()
1663
+ const targets = _searchTargets(input)
1664
+ if (targets === null) return true
1665
+ const call = _newCall()
1666
+ try {
1667
+ const realBase = realpathDeepestAncestorSync(base)
1668
+ for (const target of targets) {
1669
+ const forms = [resolve(base, target), resolveTargetComponentwiseSync(realBase, target, call.walk)]
1670
+ for (const form of forms) {
1671
+ if (_hitsInboxSocketDir(form, call) || _isSessionsDir(form, call)) return true
1672
+ if (toolName === 'Grep' && !globAvoidsKeyFiles(input.glob) && _searchReachesSessions(form, call)) return true
1673
+ }
1674
+ }
1675
+ return false
1676
+ } catch {
1677
+ return true
1678
+ }
1679
+ }
1680
+
1681
+ /**
1682
+ * Does the Grep `glob` field restrict which files are searched? Absent, empty,
1683
+ * and exclusion-only (`!x`) globs do not.
1684
+ * @param {unknown} glob
1685
+ * @returns {boolean}
1686
+ */
1687
+ function globNarrowsSearch(glob) {
1688
+ if (glob === undefined || glob === null) return false
1689
+ if (typeof glob !== 'string') return true
1690
+ return glob.split(/[\s,]+/).some((piece) => piece.length > 0 && !piece.startsWith('!'))
1691
+ }
1692
+
1693
+ /**
1694
+ * How a Grep's search location relates to a configured Claude config directory
1695
+ * whose name is not `.claude`: `near` when it is inside it or reaches it, and
1696
+ * `covers` when it is the root or above it (so a recursive search reaches the
1697
+ * files directly inside it). `near` makes its `glob` also be tested against
1698
+ * bare `settings*.json`. Fails closed: a location that cannot be resolved
1699
+ * counts as both.
1700
+ * @param {object} input
1701
+ * @param {string} [cwd]
1702
+ * @param {Function} [statFn] injected `stat`, for tests
1703
+ * @returns {{ near: boolean, covers: boolean }}
1704
+ */
1705
+ function _searchReachToConfigRoot(input, cwd, statFn) {
1706
+ const call = _newCall(statFn)
1707
+ const rule = _configRootRule(call)
1708
+ if (rule === null) return { near: false, covers: false }
1709
+ if (rule.failed) return { near: true, covers: true }
1710
+ const base = (typeof cwd === 'string' && cwd.length > 0) ? cwd : process.cwd()
1711
+ const targets = _searchTargets(input)
1712
+ if (targets === null) return { near: true, covers: true }
1713
+ const reach = { near: false, covers: false }
1714
+ try {
1715
+ const realBase = realpathDeepestAncestorSync(base)
1716
+ for (const target of targets) {
1717
+ const real = resolveTargetComponentwiseSync(realBase, target, { left: FLOOR_MAX_CALL_WALK })
1718
+ const { inside, covers } = _rootRelation(rule, real, true, call)
1719
+ if (inside !== null || covers) reach.near = true
1720
+ if (covers) reach.covers = true
1721
+ }
1722
+ return reach
1723
+ } catch {
1724
+ return { near: true, covers: true }
1725
+ }
1726
+ }
1727
+
1728
+ /**
1729
+ * Internals exposed for tests only: they take an injected `stat` so the
1730
+ * fail-closed paths (a lookup that errors, a spent budget) can be driven
1731
+ * without making a real directory unreadable.
1732
+ */
1733
+ export const floorInternalsForTest = {
1734
+ sameName(a, b) {
1735
+ return _sameName(a, b, _newCall())
1736
+ },
1737
+ hitsConfigRoot(resolved, secretsOnly, statFn, budget, configDirFn) {
1738
+ const call = _newCall(statFn)
1739
+ call.configDirFn = configDirFn
1740
+ if (budget !== undefined) call.idBudget.left = budget
1741
+ // An array is evaluated within ONE call, sharing its lookups and budget.
1742
+ let hit = false
1743
+ for (const target of Array.isArray(resolved) ? resolved : [resolved]) {
1744
+ if (_hitsConfigRoot(target, secretsOnly, call)) hit = true
1745
+ }
1746
+ return hit
1747
+ },
1748
+ hitsInboxSocketDir(resolved, inboxDirs) {
1749
+ const call = _newCall()
1750
+ call.inboxDirs = inboxDirs
1751
+ return _hitsInboxSocketDir(resolved, call)
1752
+ },
1753
+ protectedRootVerdicts(resolved, { configDirFn, inboxDirs, resolveRootFn } = {}) {
1754
+ const call = _newCall()
1755
+ call.configDirFn = configDirFn
1756
+ call.inboxDirs = inboxDirs
1757
+ call.resolveRootFn = resolveRootFn
1758
+ return {
1759
+ inbox: _hitsInboxSocketDir(resolved, call),
1760
+ sessionsDir: _isSessionsDir(resolved, call),
1761
+ reaches: _searchReachesSessions(resolved, call),
1762
+ }
1763
+ },
1764
+ globAvoidsKeyFiles(glob) {
1765
+ return globAvoidsKeyFiles(glob)
1766
+ },
1767
+ searchReach(input, cwd, statFn) {
1768
+ return _searchReachToConfigRoot(input, cwd, statFn)
1769
+ },
455
1770
  }