@blackbelt-technology/pi-agent-dashboard 0.10.0 → 0.12.0

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 (474) hide show
  1. package/AGENTS.md +4 -2
  2. package/README.md +64 -18
  3. package/docs/architecture.md +2325 -270
  4. package/package.json +36 -20
  5. package/packages/extension/package.json +18 -9
  6. package/packages/extension/src/bridge-context.ts +6 -0
  7. package/packages/extension/src/bridge-handlers/dispatch.ts +109 -70
  8. package/packages/extension/src/bridge-handlers/forwarders.ts +19 -42
  9. package/packages/extension/src/bridge-handlers/instance.ts +31 -13
  10. package/packages/extension/src/bridge-handlers/lifecycle.ts +149 -66
  11. package/packages/extension/src/bridge-shutdown.ts +44 -0
  12. package/packages/extension/src/bridge-ticket-client.ts +61 -7
  13. package/packages/extension/src/bridge-tls-checks.ts +79 -0
  14. package/packages/extension/src/bridge.ts +309 -284
  15. package/packages/extension/src/canvas-tool.ts +2 -0
  16. package/packages/extension/src/command-handler.ts +106 -37
  17. package/packages/extension/src/connect-target.ts +23 -0
  18. package/packages/extension/src/connection.ts +153 -38
  19. package/packages/extension/src/credential-guard.ts +300 -0
  20. package/packages/extension/src/custom-entry-forward.ts +27 -18
  21. package/packages/extension/src/dashboard-http-origin.ts +88 -0
  22. package/packages/extension/src/default-model-apply.ts +83 -0
  23. package/packages/extension/src/dev-build.ts +11 -1
  24. package/packages/extension/src/flow-event-wiring.ts +19 -95
  25. package/packages/extension/src/followup-drain.ts +19 -5
  26. package/packages/extension/src/git-link-builder.ts +11 -2
  27. package/packages/extension/src/inbound-limits.ts +138 -0
  28. package/packages/extension/src/local-token-header.ts +77 -6
  29. package/packages/extension/src/model-refresh.ts +69 -0
  30. package/packages/extension/src/path-gate/decide.ts +68 -5
  31. package/packages/extension/src/path-gate/handler.ts +16 -8
  32. package/packages/extension/src/path-gate/index.ts +2 -2
  33. package/packages/extension/src/path-gate/roots.ts +15 -3
  34. package/packages/extension/src/path-gate/suppression.ts +3 -0
  35. package/packages/extension/src/pi-env.d.ts +8 -1
  36. package/packages/extension/src/pi-retry-settings.ts +11 -2
  37. package/packages/extension/src/pinned-endpoint.ts +44 -0
  38. package/packages/extension/src/plugin-event-forward-registry.ts +90 -14
  39. package/packages/extension/src/preview-path-link.ts +151 -0
  40. package/packages/extension/src/project-init/scaffold.ts +98 -35
  41. package/packages/extension/src/project-trust-live.ts +143 -0
  42. package/packages/extension/src/project-trust.ts +178 -30
  43. package/packages/extension/src/provider-model-cache.ts +118 -0
  44. package/packages/extension/src/provider-register.ts +487 -46
  45. package/packages/extension/src/remote-registration-gate.ts +21 -21
  46. package/packages/extension/src/remote-upgrade-preparer.ts +104 -0
  47. package/packages/extension/src/retry-tracker.ts +90 -7
  48. package/packages/extension/src/role-manager.ts +4 -2
  49. package/packages/extension/src/role-model-tools.ts +68 -10
  50. package/packages/extension/src/server-auto-start.ts +69 -3
  51. package/packages/extension/src/server-launcher.ts +26 -8
  52. package/packages/extension/src/server-proof-probe.ts +117 -0
  53. package/packages/extension/src/session-sync.ts +53 -24
  54. package/packages/extension/src/spawn-new-session.ts +22 -0
  55. package/packages/extension/src/steer-buffer.ts +164 -0
  56. package/packages/extension/src/stream-forward-buffer.ts +64 -15
  57. package/packages/extension/src/sudo-askpass/config-reader.ts +32 -0
  58. package/packages/extension/src/sudo-askpass/controller.ts +405 -0
  59. package/packages/extension/src/sudo-askpass/helper-script.ts +69 -0
  60. package/packages/extension/src/sudo-askpass/in-flight.ts +79 -0
  61. package/packages/extension/src/sudo-askpass/index.ts +11 -0
  62. package/packages/extension/src/sudo-askpass/install.ts +143 -0
  63. package/packages/extension/src/sudo-askpass/password-cache.ts +118 -0
  64. package/packages/extension/src/sudo-askpass/prompt-text.ts +55 -0
  65. package/packages/extension/src/sudo-askpass/protocol.ts +18 -0
  66. package/packages/extension/src/sudo-askpass/sudo-mask-registry.ts +52 -0
  67. package/packages/extension/src/terminal-reload.ts +19 -5
  68. package/packages/extension/src/tool-update-filter-registry.ts +210 -0
  69. package/packages/extension/src/vault-delivery.ts +11 -1
  70. package/packages/extension/src/vault-redaction.ts +4 -3
  71. package/packages/server/package.json +17 -14
  72. package/packages/server/src/access/access-denials.ts +8 -0
  73. package/packages/server/src/access/access-grants.ts +303 -64
  74. package/packages/server/src/access/access-health.ts +10 -0
  75. package/packages/server/src/access/access-plane.ts +12 -1
  76. package/packages/server/src/access/containment-gate.ts +113 -30
  77. package/packages/server/src/access/cwd-verdict.ts +3 -3
  78. package/packages/server/src/access/denial-hold.ts +3 -0
  79. package/packages/server/src/access/grant-coordinator.ts +17 -1
  80. package/packages/server/src/access/named-grant.ts +3 -0
  81. package/packages/server/src/access/pending-grant-registry.ts +32 -5
  82. package/packages/server/src/access/pi-trust-live.ts +244 -0
  83. package/packages/server/src/access/pi-trust-mirror-service.ts +50 -11
  84. package/packages/server/src/access/planes.ts +107 -1
  85. package/packages/server/src/access/preview-egress-store.ts +153 -0
  86. package/packages/server/src/access/prompt-channel.ts +5 -0
  87. package/packages/server/src/access/provisioning-wiring.ts +113 -0
  88. package/packages/server/src/access/provisioning.ts +763 -0
  89. package/packages/server/src/access/verified-read.ts +24 -7
  90. package/packages/server/src/access/yolo-session.ts +54 -2
  91. package/packages/server/src/acp-bridge/acp-session-adapter.ts +18 -5
  92. package/packages/server/src/acp-bridge/server-requests.ts +10 -4
  93. package/packages/server/src/agent-events/agent-event-hub.ts +158 -0
  94. package/packages/server/src/auth/audit-log.ts +108 -0
  95. package/packages/server/src/auth/auth-plugin.ts +230 -38
  96. package/packages/server/src/auth/auth.ts +104 -4
  97. package/packages/server/src/auth/bearer-auth.ts +52 -12
  98. package/packages/server/src/auth/bridge-ticket-eligibility.ts +53 -10
  99. package/packages/server/src/auth/cors-origin.ts +90 -30
  100. package/packages/server/src/auth/credential-envelope.ts +233 -0
  101. package/packages/server/src/auth/credential-key-worker.d.mts +16 -0
  102. package/packages/server/src/auth/credential-key-worker.mjs +108 -0
  103. package/packages/server/src/auth/credential-key.ts +479 -0
  104. package/packages/server/src/auth/credential-migration.ts +162 -0
  105. package/packages/server/src/auth/csp-report-paths.ts +26 -0
  106. package/packages/server/src/auth/csp-report-sink.ts +302 -0
  107. package/packages/server/src/auth/csp-report-store.ts +406 -0
  108. package/packages/server/src/auth/csp.ts +145 -11
  109. package/packages/server/src/auth/dashboard-credential-store.ts +4 -0
  110. package/packages/server/src/auth/dashboard-state-caller.ts +29 -0
  111. package/packages/server/src/auth/device-proof.ts +202 -0
  112. package/packages/server/src/auth/duplicate-cookie-gate.ts +271 -0
  113. package/packages/server/src/auth/host-admission.ts +7 -0
  114. package/packages/server/src/auth/host-gate.ts +13 -2
  115. package/packages/server/src/auth/local-proof-refusal-log.ts +89 -0
  116. package/packages/server/src/auth/local-proof.ts +69 -18
  117. package/packages/server/src/auth/localhost-guard.ts +98 -33
  118. package/packages/server/src/auth/locked-json-file.ts +68 -6
  119. package/packages/server/src/auth/models-json-store.ts +269 -0
  120. package/packages/server/src/auth/mutation-origin-gate.ts +5 -2
  121. package/packages/server/src/auth/nav-intent.ts +72 -0
  122. package/packages/server/src/auth/node-guard.ts +36 -49
  123. package/packages/server/src/auth/passkey/passkey-assets.ts +99 -0
  124. package/packages/server/src/auth/passkey/passkey-pages.ts +17 -81
  125. package/packages/server/src/auth/passkey/passkey-routes.ts +8 -0
  126. package/packages/server/src/auth/pi-legacy-credentials.ts +3 -0
  127. package/packages/server/src/auth/plugin-credential-store.ts +81 -10
  128. package/packages/server/src/auth/plugin-server-trust.ts +29 -0
  129. package/packages/server/src/auth/plugin-trust-store.ts +103 -0
  130. package/packages/server/src/auth/proven-tls.ts +45 -0
  131. package/packages/server/src/auth/provider-auth-storage.ts +214 -12
  132. package/packages/server/src/auth/provider-block-checks.ts +321 -0
  133. package/packages/server/src/auth/provider-host-detect.ts +151 -0
  134. package/packages/server/src/auth/provider-key-file.ts +71 -0
  135. package/packages/server/src/auth/provider-readiness.ts +91 -0
  136. package/packages/server/src/auth/radius-mcp.ts +1 -1
  137. package/packages/server/src/auth/request-principal.ts +32 -0
  138. package/packages/server/src/auth/route-tier-gate.ts +3 -2
  139. package/packages/server/src/auth/secret-rotation.ts +246 -0
  140. package/packages/server/src/auth/secure-origin.ts +56 -0
  141. package/packages/server/src/auth/serve-app-host.ts +111 -11
  142. package/packages/server/src/auth/vertex-key-check.ts +140 -0
  143. package/packages/server/src/auth/ws-ticket.ts +40 -2
  144. package/packages/server/src/auth/ws-upgrade-reject-log.ts +4 -1
  145. package/packages/server/src/browse.ts +73 -20
  146. package/packages/server/src/browser-handlers/acp-guard.ts +1 -4
  147. package/packages/server/src/browser-handlers/directory-handler.ts +34 -24
  148. package/packages/server/src/browser-handlers/folder-gate.ts +55 -0
  149. package/packages/server/src/browser-handlers/handler-context.ts +25 -2
  150. package/packages/server/src/browser-handlers/session-action-handler.ts +167 -63
  151. package/packages/server/src/browser-handlers/spawn-choice.ts +138 -1
  152. package/packages/server/src/browser-handlers/subscription-handler.ts +146 -3
  153. package/packages/server/src/browser-handlers/terminal-handler.ts +108 -10
  154. package/packages/server/src/build-plugin-send-prompt.ts +18 -0
  155. package/packages/server/src/canvas/canvas-accumulator.ts +35 -7
  156. package/packages/server/src/cli/credentials-command.ts +555 -0
  157. package/packages/server/src/cli.ts +229 -53
  158. package/packages/server/src/config-api.ts +53 -35
  159. package/packages/server/src/config-snapshot.ts +197 -1
  160. package/packages/server/src/directory-service.ts +193 -68
  161. package/packages/server/src/embed-lifecycle/idle-reaper.ts +13 -3
  162. package/packages/server/src/event-wiring.ts +322 -207
  163. package/packages/server/src/git-worktree/ensure-worktree.ts +185 -0
  164. package/packages/server/src/git-worktree/git-operations.ts +45 -11
  165. package/packages/server/src/git-worktree/redact-git-text.ts +124 -0
  166. package/packages/server/src/git-worktree/ref-arg.ts +39 -0
  167. package/packages/server/src/git-worktree/repo-lock.ts +42 -0
  168. package/packages/server/src/git-worktree/start-worktree-init.ts +151 -0
  169. package/packages/server/src/git-worktree/worktree-init-trust.ts +43 -1
  170. package/packages/server/src/git-worktree/worktree-init.ts +5 -1
  171. package/packages/server/src/identity/http-road-classification.ts +18 -2
  172. package/packages/server/src/identity/identity-floor.ts +5 -2
  173. package/packages/server/src/identity/ws-message-scope.ts +11 -3
  174. package/packages/server/src/identity/ws-road-classification.ts +3 -1
  175. package/packages/server/src/known-server-moves.ts +36 -15
  176. package/packages/server/src/lib/browse-roots.ts +129 -17
  177. package/packages/server/src/lib/client-dist.ts +36 -21
  178. package/packages/server/src/lib/content-disposition.ts +20 -0
  179. package/packages/server/src/lib/dashboard-state-guard.ts +513 -0
  180. package/packages/server/src/lib/diagram-render.ts +4 -6
  181. package/packages/server/src/lib/eml.ts +5 -10
  182. package/packages/server/src/lib/file-cwd-admission.ts +145 -0
  183. package/packages/server/src/lib/frame-policy-probe.ts +308 -0
  184. package/packages/server/src/lib/frame-policy-test-seam.ts +99 -0
  185. package/packages/server/src/lib/frame-policy-verdict.ts +125 -0
  186. package/packages/server/src/lib/grep-worker.ts +23 -0
  187. package/packages/server/src/lib/grep.ts +96 -7
  188. package/packages/server/src/lib/index-html.ts +81 -0
  189. package/packages/server/src/lib/mention-fuzzy-index.ts +263 -0
  190. package/packages/server/src/lib/office-preview.ts +49 -13
  191. package/packages/server/src/lib/path-containment.ts +50 -10
  192. package/packages/server/src/lib/resolve-file-mention.ts +234 -40
  193. package/packages/server/src/lib/resolve-mentions-batch.ts +143 -0
  194. package/packages/server/src/lib/route-admission.ts +80 -0
  195. package/packages/server/src/lib/writable-handler-target.ts +4 -0
  196. package/packages/server/src/lib/writable-md-target.ts +26 -0
  197. package/packages/server/src/lifecycle/boot-parent-liveness.ts +10 -25
  198. package/packages/server/src/lifecycle/credential-exit-barrier.ts +207 -0
  199. package/packages/server/src/lifecycle/exit-signal.ts +43 -0
  200. package/packages/server/src/lifecycle/recovery-server.ts +65 -18
  201. package/packages/server/src/live-server/capability-redact.ts +31 -0
  202. package/packages/server/src/live-server/live-browser-gate.ts +22 -0
  203. package/packages/server/src/live-server/live-capability.ts +615 -44
  204. package/packages/server/src/live-server/live-csp-report.ts +63 -0
  205. package/packages/server/src/live-server/live-csp.ts +141 -0
  206. package/packages/server/src/live-server/live-egress.ts +435 -0
  207. package/packages/server/src/live-server/live-exposure.ts +149 -0
  208. package/packages/server/src/live-server/live-log.ts +25 -0
  209. package/packages/server/src/live-server/live-origin-scan.ts +298 -0
  210. package/packages/server/src/live-server/live-server-manager.ts +220 -33
  211. package/packages/server/src/live-server/live-server-proxy.ts +411 -50
  212. package/packages/server/src/live-server/live-static.ts +231 -0
  213. package/packages/server/src/live-server/preview-dispatch.ts +286 -0
  214. package/packages/server/src/live-server/preview-observe.ts +53 -0
  215. package/packages/server/src/live-server/preview-origin.ts +182 -0
  216. package/packages/server/src/live-server/preview-path-bridge.ts +70 -0
  217. package/packages/server/src/live-server/preview-path-store.ts +420 -0
  218. package/packages/server/src/live-server/preview-path.ts +40 -0
  219. package/packages/server/src/live-server/preview-pool.ts +385 -0
  220. package/packages/server/src/live-server/preview-preflight.ts +41 -0
  221. package/packages/server/src/live-server/preview-reserve.ts +44 -0
  222. package/packages/server/src/live-server/preview-tier.ts +217 -0
  223. package/packages/server/src/live-server/preview-viewers.ts +54 -0
  224. package/packages/server/src/live-server/preview-ws-registry.ts +43 -0
  225. package/packages/server/src/model-proxy/custom-provider-discovery.ts +4 -2
  226. package/packages/server/src/model-proxy/internal-auth-storage.ts +5 -1
  227. package/packages/server/src/model-proxy/internal-registry.ts +283 -21
  228. package/packages/server/src/model-proxy/models-block-apply.ts +291 -0
  229. package/packages/server/src/model-proxy/pi-models-validator.ts +164 -0
  230. package/packages/server/src/model-proxy/registry-singleton.ts +44 -9
  231. package/packages/server/src/model-proxy/server-model-runtime.ts +17 -0
  232. package/packages/server/src/openspec/dependencies-file.ts +122 -0
  233. package/packages/server/src/openspec/openspec-change-watcher.ts +3 -1
  234. package/packages/server/src/openspec/openspec-dependency-inputs.ts +281 -0
  235. package/packages/server/src/openspec/openspec-poll-fs-helpers.ts +72 -26
  236. package/packages/server/src/openspec/openspec-poll-worker-pool.ts +48 -12
  237. package/packages/server/src/openspec/openspec-poll-worker.ts +95 -9
  238. package/packages/server/src/openspec/readiness.ts +1 -1
  239. package/packages/server/src/openspec/workflow-schema-status.ts +379 -0
  240. package/packages/server/src/openspec/workflow-schema.ts +141 -267
  241. package/packages/server/src/package/npm-search-proxy.ts +5 -2
  242. package/packages/server/src/package/provider-probe.ts +202 -7
  243. package/packages/server/src/pairing/browser-gateway.ts +325 -51
  244. package/packages/server/src/pairing/device-key-intake.ts +120 -0
  245. package/packages/server/src/pairing/device-token-services.ts +26 -0
  246. package/packages/server/src/pairing/paired-devices.ts +702 -27
  247. package/packages/server/src/pairing/pairing.ts +103 -11
  248. package/packages/server/src/pairing/{subagent-resync-routing.ts → resync-requester-registry.ts} +6 -10
  249. package/packages/server/src/pairing/socket-locality.ts +26 -0
  250. package/packages/server/src/pairing/ws-tier-gate.ts +74 -0
  251. package/packages/server/src/pending/pending-attach-registry.ts +15 -0
  252. package/packages/server/src/pending/pending-initial-prompt-registry.ts +15 -0
  253. package/packages/server/src/persistence/memory-event-store.ts +251 -296
  254. package/packages/server/src/persistence/preferences-store.ts +61 -2
  255. package/packages/server/src/pi/bridge-channel.ts +33 -0
  256. package/packages/server/src/pi/bridge-contention.ts +84 -2
  257. package/packages/server/src/pi/bridge-upgrade-auth.ts +18 -3
  258. package/packages/server/src/pi/gateway-listeners.ts +9 -3
  259. package/packages/server/src/pi/host-project-trust.ts +29 -15
  260. package/packages/server/src/pi/pi-gateway.ts +398 -41
  261. package/packages/server/src/pi/provisional-registration.ts +4 -1
  262. package/packages/server/src/pi/resource-toggle-trust.ts +18 -7
  263. package/packages/server/src/pi-agent-settings.ts +95 -301
  264. package/packages/server/src/pi-default-remirror.ts +89 -0
  265. package/packages/server/src/plugin-append-event.ts +35 -0
  266. package/packages/server/src/plugin-discovery-wiring.ts +142 -0
  267. package/packages/server/src/plugin-entry-stats.ts +61 -0
  268. package/packages/server/src/plugin-event-seam.ts +116 -4
  269. package/packages/server/src/plugin-local-request.ts +207 -0
  270. package/packages/server/src/plugin-ownership.ts +111 -0
  271. package/packages/server/src/plugin-policy-registry.ts +297 -0
  272. package/packages/server/src/plugin-request-lane.ts +92 -16
  273. package/packages/server/src/plugin-runtime-clients.ts +89 -0
  274. package/packages/server/src/preferences-relay.ts +20 -0
  275. package/packages/server/src/project-seed.ts +347 -0
  276. package/packages/server/src/push/push-transports/webhook-url.ts +8 -5
  277. package/packages/server/src/questions/question-store.ts +3 -2
  278. package/packages/server/src/routes/access-routes.ts +182 -15
  279. package/packages/server/src/routes/acme-routes.ts +14 -4
  280. package/packages/server/src/routes/agent-event-stream-routes.ts +137 -0
  281. package/packages/server/src/routes/canvas-types-routes.ts +20 -6
  282. package/packages/server/src/routes/csp-violations-routes.ts +162 -0
  283. package/packages/server/src/routes/file-routes.ts +640 -279
  284. package/packages/server/src/routes/file-write-binary-routes.ts +97 -24
  285. package/packages/server/src/routes/folder-project-routes.ts +18 -12
  286. package/packages/server/src/routes/frame-policy-routes.ts +215 -0
  287. package/packages/server/src/routes/git-routes.ts +340 -273
  288. package/packages/server/src/routes/grep-routes.ts +64 -14
  289. package/packages/server/src/routes/known-servers-routes.ts +189 -91
  290. package/packages/server/src/routes/live-server-routes.ts +572 -15
  291. package/packages/server/src/routes/local-proof-routes.ts +14 -0
  292. package/packages/server/src/routes/models-introspection-routes.ts +1 -1
  293. package/packages/server/src/routes/nav-intent-routes.ts +46 -0
  294. package/packages/server/src/routes/openspec-group-routes.ts +53 -44
  295. package/packages/server/src/routes/openspec-routes.ts +396 -31
  296. package/packages/server/src/routes/package-routes.ts +58 -10
  297. package/packages/server/src/routes/pairing-routes.ts +342 -17
  298. package/packages/server/src/routes/pi-settings-routes.ts +2 -0
  299. package/packages/server/src/routes/pi-trust-query-routes.ts +330 -0
  300. package/packages/server/src/routes/plugin-activation-routes.ts +59 -0
  301. package/packages/server/src/routes/plugin-runtime-client-routes.ts +149 -0
  302. package/packages/server/src/routes/preferences-auto-name-routes.ts +5 -2
  303. package/packages/server/src/routes/preferences-claude-compat-routes.ts +49 -0
  304. package/packages/server/src/routes/provider-auth-routes.ts +181 -10
  305. package/packages/server/src/routes/provider-override-routes.ts +158 -0
  306. package/packages/server/src/routes/provider-routes.ts +348 -86
  307. package/packages/server/src/routes/resource-activation-routes.ts +18 -4
  308. package/packages/server/src/routes/session-routes.ts +75 -25
  309. package/packages/server/src/routes/system-routes.ts +169 -52
  310. package/packages/server/src/routes/ui-link-base.ts +88 -0
  311. package/packages/server/src/rpc-keeper/keeper-manager.ts +196 -25
  312. package/packages/server/src/rpc-keeper/keeper.cjs +37 -23
  313. package/packages/server/src/runtime-overlay/extension-reload.ts +16 -10
  314. package/packages/server/src/runtime-overlay/runtime-io.ts +2 -9
  315. package/packages/server/src/runtime-overlay/runtime-stager.ts +4 -2
  316. package/packages/server/src/server.ts +1139 -291
  317. package/packages/server/src/services/cli-service.ts +59 -10
  318. package/packages/server/src/services/secrets-resolver.ts +46 -30
  319. package/packages/server/src/session/custom-event-group-annotation.ts +3 -3
  320. package/packages/server/src/session/custom-event-group-resolver.ts +10 -5
  321. package/packages/server/src/session/death-reason.ts +11 -7
  322. package/packages/server/src/session/event-status-extraction.ts +5 -1
  323. package/packages/server/src/session/hydration-state.ts +148 -0
  324. package/packages/server/src/session/memory-session-manager.ts +31 -2
  325. package/packages/server/src/session/open-tool-calls.ts +81 -47
  326. package/packages/server/src/session/pid-target.ts +127 -0
  327. package/packages/server/src/session/replay-compaction.ts +18 -5
  328. package/packages/server/src/session/replay-exit-controller.ts +221 -0
  329. package/packages/server/src/session/retained-transcript.ts +9 -2
  330. package/packages/server/src/session/seed-discovered-history.ts +85 -0
  331. package/packages/server/src/session/server-pid-context.ts +14 -0
  332. package/packages/server/src/session/session-api.ts +78 -29
  333. package/packages/server/src/session/session-archive.ts +7 -0
  334. package/packages/server/src/session/session-bootstrap.ts +9 -54
  335. package/packages/server/src/session/session-load-worker-pool.ts +11 -1
  336. package/packages/server/src/session/session-load-worker.ts +32 -4
  337. package/packages/server/src/spawn-process/abort-spawned-run.ts +28 -9
  338. package/packages/server/src/spawn-process/acp-spawn.ts +8 -2
  339. package/packages/server/src/spawn-process/headless-pid-registry.ts +393 -77
  340. package/packages/server/src/spawn-process/link-register.ts +42 -0
  341. package/packages/server/src/spawn-process/plugin-spawn-choice.ts +48 -0
  342. package/packages/server/src/spawn-process/plugin-spawn-worktree.ts +290 -0
  343. package/packages/server/src/spawn-process/process-classifier.ts +8 -3
  344. package/packages/server/src/spawn-process/process-manager.ts +61 -6
  345. package/packages/server/src/spawn-process/restored-identity.ts +112 -0
  346. package/packages/server/src/spawn-process/session-terminator.ts +179 -18
  347. package/packages/server/src/spawn-process/spawn-env-contributors.ts +2 -1
  348. package/packages/server/src/spawn-process/spawn-failure-log.ts +9 -0
  349. package/packages/server/src/spawn-process/spawn-register-watchdog.ts +44 -19
  350. package/packages/server/src/sudo-credential/relay.ts +337 -0
  351. package/packages/server/src/terminal/terminal-gateway.ts +10 -0
  352. package/packages/server/src/terminal/terminal-manager.ts +54 -46
  353. package/packages/server/src/tls/sources/acme/credentials.ts +3 -2
  354. package/packages/server/src/tls/sources/acme/runtime.ts +2 -1
  355. package/packages/server/src/tls/tls-bridge-route.ts +61 -0
  356. package/packages/server/src/tls/tls-config-validation.ts +2 -0
  357. package/packages/server/src/vault/device-expiry-sweep.ts +36 -0
  358. package/packages/server/src/vault/vault-delivery-hub.ts +172 -26
  359. package/packages/server/src/vault/vault-routes.ts +9 -2
  360. package/packages/server/src/vault/vault-store.ts +87 -24
  361. package/packages/server/src/watch-files-handler.ts +66 -0
  362. package/packages/server/vendor/xlsx/LICENSE +201 -0
  363. package/packages/server/vendor/xlsx/PROVENANCE.json +13 -0
  364. package/packages/server/vendor/xlsx/xlsx.d.mts +1065 -0
  365. package/packages/server/vendor/xlsx/xlsx.mjs +28228 -0
  366. package/packages/shared/package.json +4 -2
  367. package/packages/shared/src/agent-credential-files.ts +32 -0
  368. package/packages/shared/src/browser-protocol.ts +285 -59
  369. package/packages/shared/src/canvas-declare.ts +27 -0
  370. package/packages/shared/src/canvas-detect.ts +1 -1
  371. package/packages/shared/src/canvas-types.ts +2 -2
  372. package/packages/shared/src/config.ts +443 -187
  373. package/packages/shared/src/containment-guard.ts +45 -0
  374. package/packages/shared/src/credential-encryption.ts +87 -0
  375. package/packages/shared/src/custom-event-groups.ts +2 -0
  376. package/packages/shared/src/dashboard-plugin/claude-compat.ts +159 -0
  377. package/packages/shared/src/dashboard-plugin/event-type-owners.ts +50 -0
  378. package/packages/shared/src/dashboard-plugin/file-handler.ts +2 -0
  379. package/packages/shared/src/dashboard-plugin/host-api.ts +61 -0
  380. package/packages/shared/src/dashboard-plugin/host-fx-classes.ts +23 -0
  381. package/packages/shared/src/dashboard-plugin/host-import-map.ts +38 -0
  382. package/packages/shared/src/dashboard-plugin/index.ts +2 -0
  383. package/packages/shared/src/dashboard-plugin/manifest-types.ts +100 -1
  384. package/packages/shared/src/dashboard-plugin/plugin-status.ts +58 -3
  385. package/packages/shared/src/dashboard-plugin/replay-entry-types.ts +46 -0
  386. package/packages/shared/src/dashboard-plugin/slot-props.ts +47 -3
  387. package/packages/shared/src/dashboard-plugin/slot-types.ts +9 -1
  388. package/packages/shared/src/dashboard-plugin/ui-primitives.ts +39 -3
  389. package/packages/shared/src/device-key-proof.ts +309 -0
  390. package/packages/shared/src/display-prefs.ts +13 -0
  391. package/packages/shared/src/doctor-core.ts +94 -27
  392. package/packages/shared/src/event-forward-declaration.ts +85 -12
  393. package/packages/shared/src/forbidden-subjects.ts +126 -14
  394. package/packages/shared/src/heap-limits.ts +0 -30
  395. package/packages/shared/src/host-admission.ts +2 -1
  396. package/packages/shared/src/index.ts +7 -6
  397. package/packages/shared/src/live-server.ts +161 -0
  398. package/packages/shared/src/local-proof-signal.ts +16 -0
  399. package/packages/shared/src/loopback-host.ts +26 -0
  400. package/packages/shared/src/mcp/verb-tiers.generated.ts +176 -0
  401. package/packages/shared/src/mdns-discovery.ts +25 -6
  402. package/packages/shared/src/models-json-reader.ts +41 -0
  403. package/packages/shared/src/nav-intent.ts +29 -0
  404. package/packages/shared/src/network-denial-signal.ts +15 -0
  405. package/packages/shared/src/node-version.ts +63 -60
  406. package/packages/shared/src/openspec-dependencies.ts +760 -0
  407. package/packages/shared/src/openspec-poller.ts +3 -2
  408. package/packages/shared/src/pairing-knock-client.ts +135 -11
  409. package/packages/shared/src/pi-agent-settings-lock.ts +311 -0
  410. package/packages/shared/src/pi-path-compare.ts +31 -0
  411. package/packages/shared/src/pi-settings-schema.ts +52 -9
  412. package/packages/shared/src/pi-trust-live-query.ts +93 -0
  413. package/packages/shared/src/pi-trust-mirror-snapshot.ts +21 -11
  414. package/packages/shared/src/pi-trust-mirror-types.ts +38 -3
  415. package/packages/shared/src/pi-trust-mirror.ts +47 -11
  416. package/packages/shared/src/pi-trust-resource-digest.ts +261 -0
  417. package/packages/shared/src/pid-namespace.ts +86 -0
  418. package/packages/shared/src/platform/ensure-bundled-git.ts +57 -34
  419. package/packages/shared/src/platform/git-source.ts +88 -26
  420. package/packages/shared/src/platform/git.ts +14 -8
  421. package/packages/shared/src/platform/native-ts-register.mjs +1 -1
  422. package/packages/shared/src/platform/process.ts +452 -5
  423. package/packages/shared/src/platform/resolve-pi-shell.ts +105 -0
  424. package/packages/shared/src/platform/select-git-source.ts +7 -0
  425. package/packages/shared/src/platform/spawn-runtime.ts +193 -7
  426. package/packages/shared/src/plugin-route-cwd.ts +95 -0
  427. package/packages/shared/src/preview-egress.ts +192 -0
  428. package/packages/shared/src/preview-origins.ts +398 -0
  429. package/packages/shared/src/project-root.ts +16 -0
  430. package/packages/shared/src/prompt-answer.ts +9 -5
  431. package/packages/shared/src/protocol.ts +187 -86
  432. package/packages/shared/src/provider-env-catalog.ts +413 -0
  433. package/packages/shared/src/provider-overrides.ts +112 -0
  434. package/packages/shared/src/question-types.ts +6 -0
  435. package/packages/shared/src/recommended-extensions.ts +97 -26
  436. package/packages/shared/src/recovery-timing.ts +27 -0
  437. package/packages/shared/src/remote-credentials.ts +63 -0
  438. package/packages/shared/src/renderer-by-ext.ts +5 -2
  439. package/packages/shared/src/rest-api.ts +148 -11
  440. package/packages/shared/src/role-schema.ts +24 -0
  441. package/packages/shared/src/route-tiers.ts +149 -4
  442. package/packages/shared/src/runtime-overlay/archive-safety.d.mts +2 -0
  443. package/packages/shared/src/runtime-overlay/archive-safety.mjs +33 -0
  444. package/packages/shared/src/runtime-overlay/compat.ts +70 -6
  445. package/packages/shared/src/runtime-overlay/manifest.d.mts +7 -0
  446. package/packages/shared/src/runtime-overlay/manifest.mjs +22 -2
  447. package/packages/shared/src/safe-local-path.ts +24 -0
  448. package/packages/shared/src/sanitize-profiles.ts +98 -0
  449. package/packages/shared/src/secret-patterns.ts +49 -0
  450. package/packages/shared/src/server-launcher.ts +9 -1
  451. package/packages/shared/src/server-pinning.ts +55 -2
  452. package/packages/shared/src/server-routes.ts +462 -0
  453. package/packages/shared/src/session-ui-path.ts +11 -0
  454. package/packages/shared/src/source-matching.ts +2 -2
  455. package/packages/shared/src/state-replay.ts +40 -24
  456. package/packages/shared/src/sudo-credential.ts +71 -0
  457. package/packages/shared/src/tls-only-token.ts +16 -0
  458. package/packages/shared/src/tool-path-resolve.ts +16 -1
  459. package/packages/shared/src/tool-registry/definitions.ts +5 -5
  460. package/packages/shared/src/tool-registry/strategies.ts +13 -12
  461. package/packages/shared/src/tool-workdir.ts +56 -0
  462. package/packages/shared/src/trusted-types-mode.ts +72 -0
  463. package/packages/shared/src/types.ts +134 -109
  464. package/packages/shared/src/url-policy.ts +96 -0
  465. package/packages/shared/src/vault-delivery.ts +15 -0
  466. package/packages/shared/src/vertex-regions.ts +81 -0
  467. package/packages/shared/src/ws-message-tiers.ts +11 -3
  468. package/packages/extension/src/subagent-fanout-admission.ts +0 -234
  469. package/packages/extension/src/subagent-forward-sites.ts +0 -69
  470. package/packages/extension/src/subagent-frame-buffer.ts +0 -245
  471. package/packages/extension/src/subagent-frame-strip.ts +0 -109
  472. package/packages/extension/src/subagent-saturation.ts +0 -196
  473. package/packages/extension/src/subagent-tick-throttle.ts +0 -252
  474. package/packages/shared/src/anthropic-messages-source.ts +0 -8
@@ -8,13 +8,21 @@ import fs from "node:fs/promises";
8
8
  import { createRequire } from "node:module";
9
9
  import os from "node:os";
10
10
  import path from "node:path";
11
+ import type { CwdHoldDecision } from "@blackbelt-technology/dashboard-plugin-runtime/server";
11
12
  import { loadConfig } from "@blackbelt-technology/pi-dashboard-shared/config.js";
13
+ import { containmentAllows } from "@blackbelt-technology/pi-dashboard-shared/containment-guard.js";
14
+ import {
15
+ admissionAllows,
16
+ issueHeldAdmission,
17
+ releaseAdmission,
18
+ } from "@blackbelt-technology/pi-dashboard-shared/cwd-guard.js";
12
19
  import { DIGEST_CEILING_BYTES, fileKind } from "@blackbelt-technology/pi-dashboard-shared/file-kind.js";
13
20
  import { repairAsciiDoc } from "@blackbelt-technology/pi-dashboard-shared/markup-repair/asciidoc.js";
14
21
  import { realpathAsync } from "@blackbelt-technology/pi-dashboard-shared/platform/git.js";
22
+ import { ASCIIDOC_PROFILE, keepColWidthStyleOnly } from "@blackbelt-technology/pi-dashboard-shared/sanitize-profiles.js";
15
23
  import type { ApiResponse } from "@blackbelt-technology/pi-dashboard-shared/types.js";
16
24
  import type { FastifyInstance } from "fastify";
17
- import { type DenialRemedy, evaluateContainment } from "../access/containment-gate.js";
25
+ import { type DenialRemedy, decidePassive, evaluateContainment } from "../access/containment-gate.js";
18
26
  import { resolveCwdVerdict } from "../access/cwd-verdict.js";
19
27
  import { type HoldTarget, holdDenial } from "../access/denial-hold.js";
20
28
  import {
@@ -24,7 +32,9 @@ import {
24
32
  readFileVerifiedUtf8,
25
33
  VerifiedReadRefused,
26
34
  } from "../access/verified-read.js";
27
- import { canDiscloseAccessPosture } from "../auth/localhost-guard.js";
35
+ import type { LocalTrustContext } from "../auth/local-proof.js";
36
+ import { canDiscloseAccessPosture, isLocallyTrusted } from "../auth/localhost-guard.js";
37
+ import { requestPrincipalKey } from "../auth/request-principal.js";
28
38
  import {
29
39
  CreateProjectError,
30
40
  type CreateProjectReason,
@@ -34,15 +44,26 @@ import {
34
44
  listDirectories,
35
45
  parseFlagsQuery,
36
46
  } from "../browse.js";
37
- import { BROWSE_OUTSIDE_ROOTS_ERROR, isWithinBrowseRoots, resolveBrowseRoots } from "../lib/browse-roots.js";
38
47
  import { isImageUnderArtifactRoot } from "../lib/artifact-roots.js";
48
+ import {
49
+ BROWSE_OUTSIDE_ROOTS_ERROR,
50
+ type BrowseRootSources,
51
+ type BrowseRoots,
52
+ buildBrowseRootSources,
53
+ isWithinBrowseRoots,
54
+ resolveBrowseRoots,
55
+ } from "../lib/browse-roots.js";
56
+ import { contentDispositionAttachment } from "../lib/content-disposition.js";
57
+ import { ContainmentBindingRefused, DashboardStateRefused, openStateChecked, readFileStateChecked } from "../lib/dashboard-state-guard.js";
39
58
  import { decodeFileUri } from "../lib/decode-file-uri.js";
40
59
  import { renderDiagram } from "../lib/diagram-render.js";
41
60
  import { createDigestGate, type DigestGate, type DigestLane } from "../lib/digest-gate.js";
42
61
  import { EML_SIZE_CAP, loadParsedEml, toParseResult } from "../lib/eml.js";
62
+ import { admitFileCwd, CWD_UNAVAILABLE_FAILURE, cwdAnchors, type GateWire, releaseOnClose } from "../lib/file-cwd-admission.js";
43
63
  import { enumerateMdCandidates } from "../lib/md-candidates.js";
44
64
  import { extToContentType } from "../lib/mime-types.js";
45
65
  import {
66
+ convertBound,
46
67
  createDefaultDocxPdfEngine,
47
68
  type DocxPdfEngine,
48
69
  type DocxRenderMode,
@@ -54,24 +75,31 @@ import {
54
75
  renderPptx,
55
76
  resolveRowLimit,
56
77
  } from "../lib/office-preview.js";
57
- import { isAllowed, safeRealpath } from "../lib/path-containment.js";
78
+ import { safeRealpath } from "../lib/path-containment.js";
58
79
  import { loadPurify } from "../lib/purify.js";
80
+ import { admitRouteCwd, listKnownFolderCwds, type RouteAdmissionDeps } from "../lib/route-admission.js";
59
81
 
60
82
  /**
61
83
  * A gate failure. `error` is byte-identical to what the site returned before
62
84
  * this change; `reason`/`hint`/`subject`/`denialId` are ADDITIVE (design D7) so
63
85
  * the denial can name its remedy and bind a later grant to this refusal (D15).
64
86
  * `{ code, error }` stays INTERNAL — callers convert via `denialBody`.
87
+ * `code` is the HTTP status; the wire `code` string lives in `wire`.
65
88
  */
66
- type GateFailure = { code: number; error: string } & Partial<DenialRemedy>;
89
+ export type GateFailure = { code: number; error: string; wire?: GateWire } & Partial<DenialRemedy>;
67
90
 
68
91
  /**
69
92
  * The single conversion from a gate failure to the wire body. Every containment
70
93
  * caller uses this so the additive fields cannot drift between sites, and so
71
94
  * pre-existing fields stay byte-identical (task 3.2).
72
95
  */
73
- function denialBody(gate: GateFailure): ApiResponse {
96
+ export function denialBody(gate: GateFailure): ApiResponse {
74
97
  const body: Record<string, unknown> = { success: false, error: gate.error };
98
+ if (gate.wire !== undefined) {
99
+ body.code = gate.wire.code;
100
+ if (gate.wire.message !== undefined) body.message = gate.wire.message;
101
+ if (gate.wire.retryAfterMs !== undefined) body.retryAfterMs = gate.wire.retryAfterMs;
102
+ }
75
103
  if (gate.reason !== undefined) body.reason = gate.reason;
76
104
  if (gate.hint !== undefined) body.hint = gate.hint;
77
105
  if (gate.subject !== undefined) body.subject = gate.subject;
@@ -82,9 +110,33 @@ function denialBody(gate: GateFailure): ApiResponse {
82
110
  return body as unknown as ApiResponse;
83
111
  }
84
112
 
113
+ /**
114
+ * Reply with a gate failure: the status, `Retry-After: 1` on a 503 (an undecidable
115
+ * cwd admission), and the `denialBody`. Every caller of the file gate helpers uses
116
+ * this so the 503 contract cannot drift between sites. See change: core-file-cwd-admission (D3).
117
+ */
118
+ export function sendGateFailure(reply: import("fastify").FastifyReply, gate: GateFailure): ApiResponse {
119
+ reply.code(gate.code);
120
+ if (gate.code === 503) reply.header("Retry-After", "1");
121
+ return denialBody(gate);
122
+ }
123
+
85
124
  import { serializeWrite } from "../lib/file-write-lock.js";
86
- import { resolveFileMention } from "../lib/resolve-file-mention.js";
87
- import { isWritableMdTarget } from "../lib/writable-md-target.js";
125
+ import { getMentionFuzzyIndex, type MentionFuzzyIndex } from "../lib/mention-fuzzy-index.js";
126
+ import { type ContainmentMemo, resolveMentionTagged } from "../lib/resolve-file-mention.js";
127
+ import {
128
+ BATCH_BODY_LIMIT_BYTES,
129
+ BATCH_CONCURRENCY,
130
+ BATCH_RATE_PER_MINUTE,
131
+ type BatchResult,
132
+ createWindowLimiter,
133
+ formatBatchLog,
134
+ MAX_FIELD_CHARS,
135
+ mapConcurrent,
136
+ parseBatchBody,
137
+ toBatchResult,
138
+ } from "../lib/resolve-mentions-batch.js";
139
+ import { isTextDocWriteTarget, isWritableMdTarget } from "../lib/writable-md-target.js";
88
140
  import type { PreferencesStore } from "../persistence/preferences-store.js";
89
141
  import type { SessionManager } from "../session/memory-session-manager.js";
90
142
  import {
@@ -97,6 +149,23 @@ import {
97
149
  import { type FileHandlerDeps, registerFileWriteBinaryRoute } from "./file-write-binary-routes.js";
98
150
  import type { NetworkGuard } from "./route-deps.js";
99
151
 
152
+ /** Per-response sandbox for scriptable raw responses. See change: harden-raw-svg-responses. */
153
+ export const RAW_SANDBOX_CSP =
154
+ "sandbox; default-src 'none'; style-src 'unsafe-inline'; img-src data:; font-src data:; frame-ancestors 'self'";
155
+
156
+ const SCRIPTABLE_MEDIA_TYPES = new Set([
157
+ "text/html",
158
+ "image/svg+xml",
159
+ "application/xhtml+xml",
160
+ "application/xml",
161
+ "text/xml",
162
+ ]);
163
+
164
+ /** True when a browser would execute script from this `Content-Type` (params/case ignored). */
165
+ export function isScriptableMediaType(contentType: string): boolean {
166
+ return SCRIPTABLE_MEDIA_TYPES.has(contentType.split(";")[0].trim().toLowerCase());
167
+ }
168
+
100
169
  // Per-target write serialization. The optimistic mtime check + atomic rename
101
170
  // must run as one critical section per file, else two concurrent writes can
102
171
  // both read the same mtime, both pass, and the later rename clobbers the earlier
@@ -138,23 +207,32 @@ async function hashHandle(fh: import("node:fs/promises").FileHandle, signal: Abo
138
207
  }
139
208
 
140
209
  // Resolve + scope-validate a markdown target shared by the write + md-read
141
- // endpoints. Directory scope (cwd present) requires a known session; global
142
- // scope requires an absolute path. Returns the resolved abs path, or {code,error}
143
- // to map to a reply. Authorization (`isWritableMdTarget`) is applied by callers.
144
- // See change: directory-settings-page-and-scoped-md-editing.
145
- function resolveScopedMdPath(
146
- cwd: string | undefined,
210
+ // endpoints. Directory scope (cwd present) requires an admitted cwd (shared
211
+ // guard: session, pinned, workspace folder or a worktree / main checkout of a
212
+ // known repository); global scope (cwd absent: undefined, null or "") requires
213
+ // an absolute path. Any other cwd value that is not an absolute string is
214
+ // REFUSED — it never selects the global scope. Returns the resolved abs path
215
+ // plus the guarded `cwd` (undefined in global scope: the no-cwd branch hands the
216
+ // sinks a constant, never the request value), or a GateFailure. Authorization
217
+ // (`isWritableMdTarget`) is applied by callers.
218
+ // See change: directory-settings-page-and-scoped-md-editing, core-file-cwd-admission.
219
+ async function resolveScopedMdPath(
220
+ rawCwd: unknown,
147
221
  rawPath: string,
148
- sessionManager: SessionManager,
149
- ): { resolved: string } | { code: number; error: string } {
150
- if (cwd && !sessionManager.listAll().some((s) => s.cwd === cwd)) {
151
- return { code: 403, error: "unknown session path" };
152
- }
222
+ routeAdmission: RouteAdmissionDeps,
223
+ ): Promise<{ resolved: string; cwd: string | undefined } | GateFailure> {
153
224
  const decoded = decodeFileUri(rawPath);
154
- if (!cwd && !path.isAbsolute(decoded)) {
155
- return { code: 400, error: "global scope requires an absolute path" };
225
+ if (rawCwd === undefined || rawCwd === null || rawCwd === "") {
226
+ if (!path.isAbsolute(decoded)) return { code: 400, error: "global scope requires an absolute path" };
227
+ return { resolved: path.resolve(decoded), cwd: undefined };
228
+ }
229
+ const admitted = await admitFileCwd(rawCwd, routeAdmission);
230
+ if (!admitted.ok) return admitted.failure;
231
+ try {
232
+ return { resolved: path.resolve(admitted.cwd, decoded), cwd: admitted.cwd };
233
+ } finally {
234
+ admitted.release();
156
235
  }
157
- return { resolved: cwd ? path.resolve(cwd, decoded) : path.resolve(decoded) };
158
236
  }
159
237
 
160
238
  /** Discriminated outcome of an atomic markdown write. */
@@ -163,28 +241,62 @@ type MdWriteOutcome =
163
241
  | { code: 404 | 409 | 413 | 500; error: string };
164
242
 
165
243
  /** Parsed + authorized write request, or a {code,error} reply mapping. */
166
- type MdWritePrep = { resolved: string; content: string; mtime: number } | { code: number; error: string };
244
+ type MdWritePrep =
245
+ | {
246
+ resolved: string;
247
+ content: string;
248
+ mtime: number;
249
+ /** Set when a write-mode GRANT admitted an outside-cwd target: the real path the gate decided. */
250
+ gatedReal?: string;
251
+ }
252
+ | GateFailure;
167
253
 
168
254
  // Parse, scope-validate, and authorize a `POST /api/file/write` body. Keeps the
169
255
  // route handler trivial. Authorization is the `isWritableMdTarget` security
170
256
  // boundary. See change: directory-settings-page-and-scoped-md-editing.
257
+ //
258
+ // A text doc OUTSIDE the admitted cwd (directory scope only) is not a flat 403 any more: it goes to the
259
+ // write-mode containment gate (`evaluateContainment(..., {action:"write"})`), which admits it only through
260
+ // a WRITE grant or a fresh operator write prompt (allow once / always / deny). A read grant and the
261
+ // bound-checkout-root widening never admit a write. Global scope (no cwd) is unchanged.
262
+ // See change: fix-file-link-editor-routing (D2).
171
263
  async function prepareMdWrite(
172
264
  body: { cwd?: unknown; path?: unknown; content?: unknown; mtime?: unknown },
173
- sessionManager: SessionManager,
265
+ routeAdmission: RouteAdmissionDeps,
266
+ req: { request: import("fastify").FastifyRequest; reply: import("fastify").FastifyReply },
174
267
  ): Promise<MdWritePrep> {
175
- const cwd = typeof body.cwd === "string" && body.cwd ? body.cwd : undefined;
176
268
  const rawPath = typeof body.path === "string" ? body.path : "";
177
269
  const content = typeof body.content === "string" ? body.content : undefined;
178
270
  const mtime = typeof body.mtime === "number" ? body.mtime : undefined;
179
271
  if (!rawPath || content === undefined || mtime === undefined) {
180
272
  return { code: 400, error: "path, content and mtime are required" };
181
273
  }
182
- const target = resolveScopedMdPath(cwd, rawPath, sessionManager);
274
+ const target = await resolveScopedMdPath(body.cwd, rawPath, routeAdmission);
183
275
  if ("code" in target) return target;
184
- if (!(await isWritableMdTarget(target.resolved, { cwd }))) {
276
+ if (await isWritableMdTarget(target.resolved, { cwd: target.cwd })) {
277
+ return { resolved: target.resolved, content, mtime };
278
+ }
279
+ // Only the outside-cwd text-doc case reaches the gate: global scope, a non-text extension, a Mermaid
280
+ // source and a dashboard-state path all stay a plain 403 with no prompt.
281
+ if (target.cwd === undefined || !(await isTextDocWriteTarget(target.resolved))) {
185
282
  return { code: 403, error: "target is not a writable markdown file in scope" };
186
283
  }
187
- return { resolved: target.resolved, content, mtime };
284
+ // The gate runs BEFORE any stat (`performAtomicMdWrite`): a stat-first route would be an existence
285
+ // oracle for arbitrary outside paths.
286
+ const decision = await evaluateContainment(target.resolved, [target.cwd], {
287
+ site: "file-routes:write",
288
+ subjectKind: "file",
289
+ session: target.cwd,
290
+ hold: { request: req.request, reply: req.reply },
291
+ disclosure: canDiscloseAccessPosture(req.request),
292
+ action: "write",
293
+ });
294
+ // Only a GRANT-admitted decision proceeds: layer ① admitting a path `isWritableMdTarget` just refused
295
+ // would be a contradiction, so it fails closed.
296
+ if (!containmentAllows(decision, target.resolved) || !decision.viaGrant) {
297
+ return { code: 403, error: "path outside working directory — write not granted", ...decision.remedy };
298
+ }
299
+ return { resolved: target.resolved, content, mtime, gatedReal: decision.real };
188
300
  }
189
301
 
190
302
  // Atomic markdown write with optimistic-concurrency. Caller MUST run this inside
@@ -196,6 +308,7 @@ async function performAtomicMdWrite(
196
308
  resolved: string,
197
309
  content: string,
198
310
  mtime: number,
311
+ gatedReal?: string,
199
312
  ): Promise<MdWriteOutcome> {
200
313
  // Canonicalize to the realpath target: an in-scope symlink to an allowed
201
314
  // markdown file is authorized by `isWritableMdTarget` on its realpath, so we
@@ -209,6 +322,11 @@ async function performAtomicMdWrite(
209
322
  } catch {
210
323
  return { code: 404, error: "file not found" };
211
324
  }
325
+ // Re-bind: a target admitted by a write grant must still resolve to the path the gate decided. A symlink
326
+ // repointed during the operator hold (or after the gate) is refused with nothing written.
327
+ if (gatedReal !== undefined && real !== gatedReal) {
328
+ return { code: 409, error: "target changed while access was being decided" };
329
+ }
212
330
  // Full-precision mtime token: rounding could collapse two fast saves into one
213
331
  // token and let a stale write pass the 409 check.
214
332
  if (current.mtimeMs !== mtime) {
@@ -291,17 +409,8 @@ function convertAdocCapturingWarnings(source: string): { html: string; warnings:
291
409
  // asciidoctor `safe:"secure"` still passes raw HTML through (`+++…+++`,
292
410
  // `pass:[…]`), so the converted HTML is sanitized with DOMPurify before it is
293
411
  // returned. `style` survives only as asciidoctor's own `<col style="width: N%;">`
294
- // column widths. A module-scope hook function so `removeHook` matches by
295
- // identity. See change: sanitize-untrusted-rendered-content.
296
- const COL_WIDTH_STYLE_RE = /^\s*width:\s*[\d.]+%?;?\s*$/;
297
- function keepColWidthStyleOnly(
298
- node: { nodeName: string },
299
- data: { attrName: string; attrValue: string; keepAttr: boolean },
300
- ): void {
301
- if (data.attrName !== "style") return;
302
- const tag = node.nodeName.toLowerCase();
303
- if ((tag !== "col" && tag !== "colgroup") || !COL_WIDTH_STYLE_RE.test(data.attrValue)) data.keepAttr = false;
304
- }
412
+ // column widths (`keepColWidthStyleOnly`, shared with the client policy in
413
+ // sanitize-profiles.ts). See change: sanitize-untrusted-rendered-content.
305
414
 
306
415
  async function sanitizeAdocHtml(html: string): Promise<string> {
307
416
  const purify = await loadPurify();
@@ -312,10 +421,7 @@ async function sanitizeAdocHtml(html: string): Promise<string> {
312
421
  // no `await`, so it cannot interleave with another sanitize call.
313
422
  purify.addHook("uponSanitizeAttribute", keepColWidthStyleOnly);
314
423
  try {
315
- return purify.sanitize(html, {
316
- USE_PROFILES: { html: true },
317
- FORBID_TAGS: ["style", "form", "input", "button", "textarea", "select"],
318
- });
424
+ return purify.sanitize(html, ASCIIDOC_PROFILE);
319
425
  } finally {
320
426
  purify.removeHook("uponSanitizeAttribute", keepColWidthStyleOnly);
321
427
  }
@@ -325,24 +431,33 @@ async function sanitizeAdocHtml(html: string): Promise<string> {
325
431
  // `/api/file/raw` (known session + `isAllowed` against the cwd anchor), factored
326
432
  // so both new routes CALL it rather than re-implementing the containment logic
327
433
  // (design D5). Returns the resolved abs path or a {code,error} reply mapping.
328
- async function gateFilePath(
434
+ export async function gateFilePath(
329
435
  cwd: string | undefined,
330
436
  relPath: string | undefined,
331
- sessionManager: SessionManager,
332
- /** `disclosure`: the caller may see `promptOutcome` (`canDiscloseAccessPosture`). */
333
- opts: { allowGrant?: boolean; disclosure?: boolean } = {},
334
- ): Promise<{ resolved: string; viaGrant: boolean } | GateFailure> {
437
+ routeAdmission: RouteAdmissionDeps,
438
+ /**
439
+ * `disclosure`: the caller may see `promptOutcome` (`canDiscloseAccessPosture`).
440
+ * `quiet`: record no denial and raise no prompt (a per-request re-check on a static preview).
441
+ */
442
+ opts: { allowGrant?: boolean; disclosure?: boolean; quiet?: boolean } = {},
443
+ ): Promise<{ resolved: string; real: string; viaGrant: boolean } | GateFailure> {
335
444
  if (!cwd || !relPath) return { code: 400, error: "cwd and path parameters required" };
336
- if (!sessionManager.listAll().some((s) => s.cwd === cwd)) {
337
- return { code: 403, error: "unknown session path" };
445
+ const admitted = await admitFileCwd(cwd, routeAdmission);
446
+ if (!admitted.ok) return admitted.failure;
447
+ let resolved: string;
448
+ let decision: Awaited<ReturnType<typeof evaluateContainment>>;
449
+ try {
450
+ resolved = path.resolve(admitted.cwd, relPath);
451
+ decision = await evaluateContainment(resolved, cwdAnchors(admitted), {
452
+ site: "file-routes:gateFilePath",
453
+ allowGrant: opts.allowGrant,
454
+ disclosure: opts.disclosure,
455
+ ...(opts.quiet ? { quiet: true } : {}),
456
+ });
457
+ } finally {
458
+ admitted.release();
338
459
  }
339
- const resolved = path.resolve(cwd, relPath);
340
- const decision = await evaluateContainment(resolved, [cwd], {
341
- site: "file-routes:gateFilePath",
342
- allowGrant: opts.allowGrant,
343
- disclosure: opts.disclosure,
344
- });
345
- if (!decision.allowed) {
460
+ if (!containmentAllows(decision, resolved)) {
346
461
  return { code: 403, error: "path outside working directory", ...decision.remedy };
347
462
  }
348
463
  // `viaGrant` MUST be propagated: `assertRegularFile` and the handle-verified
@@ -350,7 +465,7 @@ async function gateFilePath(
350
465
  // `lstat` and therefore refuse an in-scope final-component SYMLINK that
351
466
  // layers ①/② admit. Dropping it turned "apply only on a grant" into
352
467
  // "apply always".
353
- return { resolved, viaGrant: decision.viaGrant };
468
+ return { resolved, real: decision.real, viaGrant: decision.viaGrant };
354
469
  }
355
470
 
356
471
  /**
@@ -366,33 +481,38 @@ async function gateReadPath(
366
481
  cwd: string | undefined,
367
482
  rawPath: string | undefined,
368
483
  req: {
369
- sessionManager: SessionManager;
484
+ routeAdmission: RouteAdmissionDeps;
370
485
  request: import("fastify").FastifyRequest;
371
486
  reply: import("fastify").FastifyReply;
372
487
  quiet?: boolean;
373
488
  },
374
- ): Promise<{ resolved: string; viaGrant: boolean; relPath: string } | GateFailure> {
489
+ ): Promise<{ resolved: string; real: string; viaGrant: boolean; relPath: string } | GateFailure> {
375
490
  const relPath = rawPath ? decodeFileUri(rawPath) : rawPath;
376
491
  if (!cwd || !relPath) return { code: 400, error: "cwd and path parameters required" };
377
- if (!req.sessionManager.listAll().some((s) => s.cwd === cwd)) {
378
- return { code: 403, error: "unknown session path" };
492
+ const admitted = await admitFileCwd(cwd, req.routeAdmission);
493
+ if (!admitted.ok) return admitted.failure;
494
+ let resolved: string;
495
+ let readDecision: Awaited<ReturnType<typeof evaluateContainment>>;
496
+ try {
497
+ resolved = path.resolve(admitted.cwd, relPath);
498
+ // Anchors include the fixed `~/.pi` allowlist so a resolved `~/.pi/…`
499
+ // mention (from `/api/file/resolve-mention`) previews without a 403 (D7).
500
+ readDecision = await evaluateContainment(resolved, [...cwdAnchors(admitted), homePiAnchor()], {
501
+ site: "file-routes:read",
502
+ ...(req.quiet ? { quiet: true } : { hold: { request: req.request, reply: req.reply } }),
503
+ disclosure: canDiscloseAccessPosture(req.request),
504
+ session: admitted.cwd,
505
+ // Polymorphic: this route serves files AND directories, so the remedy
506
+ // must name whichever the target is (task 4.5 round 2, B1).
507
+ subjectKind: "auto",
508
+ });
509
+ } finally {
510
+ admitted.release();
379
511
  }
380
- const resolved = path.resolve(cwd, relPath);
381
- // Anchors include the fixed `~/.pi` allowlist so a resolved `~/.pi/…`
382
- // mention (from `/api/file/resolve-mention`) previews without a 403 (D7).
383
- const readDecision = await evaluateContainment(resolved, [cwd, homePiAnchor()], {
384
- site: "file-routes:read",
385
- ...(req.quiet ? { quiet: true } : { hold: { request: req.request, reply: req.reply } }),
386
- disclosure: canDiscloseAccessPosture(req.request),
387
- session: cwd,
388
- // Polymorphic: this route serves files AND directories, so the remedy
389
- // must name whichever the target is (task 4.5 round 2, B1).
390
- subjectKind: "auto",
391
- });
392
- if (!readDecision.allowed) {
512
+ if (!containmentAllows(readDecision, resolved)) {
393
513
  return { code: 403, error: "path outside working directory", ...readDecision.remedy };
394
514
  }
395
- return { resolved, viaGrant: readDecision.viaGrant, relPath };
515
+ return { resolved, real: readDecision.real, viaGrant: readDecision.viaGrant, relPath };
396
516
  }
397
517
 
398
518
  const CREATE_PROJECT_STATUS: Record<CreateProjectReason, number> = {
@@ -430,10 +550,32 @@ export function registerFileRoutes(
430
550
  // Plugin file-handler registry/validator seams for `POST /api/file/write-binary`
431
551
  // (change: add-editor-pane-file-handlers). Absent → every handler save is refused (403).
432
552
  fileHandlers?: FileHandlerDeps;
553
+ // Browse confinement (change: harden-server-capability-bounds, D1/D2).
554
+ // `localTrust`: strict-mode context for `isLocallyTrusted`. `browseRootSources`:
555
+ // the two root sources only server.ts can read (worktree-init trust roots and
556
+ // project-scope access grants); pinned dirs, session cwds and workspace
557
+ // folders come from `preferencesStore` / `sessionManager`.
558
+ localTrust?: LocalTrustContext;
559
+ browseRootSources?: Pick<BrowseRootSources, "worktreeRoots" | "projectGrants">;
560
+ /** `browse.confineRemote` (default true). `false` = a remote caller browses like a local one. */
561
+ browseConfineRemote?: boolean;
562
+ /**
563
+ * Shared cwd admission (change: core-file-cwd-admission, D1): `knownCwds` is the live known-folder
564
+ * set (sessions ∪ pins ∪ workspace folders), `admitOptions` the host logger + test seams. Absent →
565
+ * the known set of this registrar's own `sessionManager` + `preferencesStore`.
566
+ */
567
+ routeAdmission?: RouteAdmissionDeps;
568
+ /** Tracked-file index behind mention recovery (change: rich-chat-links). Absent → the process-wide index. */
569
+ mentionFuzzyIndex?: MentionFuzzyIndex;
433
570
  },
434
571
  ) {
435
572
  const { sessionManager, preferencesStore, networkGuard } = deps;
436
- registerFileWriteBinaryRoute(fastify, { sessionManager, networkGuard, fileHandlers: deps.fileHandlers });
573
+ const mentionIndex = deps.mentionFuzzyIndex ?? getMentionFuzzyIndex();
574
+ const routeAdmission: RouteAdmissionDeps = {
575
+ ...deps.routeAdmission,
576
+ knownCwds: deps.routeAdmission?.knownCwds ?? (() => listKnownFolderCwds({ sessionManager, preferencesStore })),
577
+ };
578
+ registerFileWriteBinaryRoute(fastify, { sessionManager, networkGuard, fileHandlers: deps.fileHandlers, routeAdmission });
437
579
  const systemOpenCapable = deps.systemOpen?.capable ?? systemOpenCapability;
438
580
  const systemOpenRun = deps.systemOpen?.run ?? runOpener;
439
581
  const systemOpenPlatform = deps.systemOpen?.platform ?? process.platform;
@@ -454,18 +596,26 @@ export function registerFileRoutes(
454
596
  /** The caller may see `promptOutcome` (`canDiscloseAccessPosture`). */
455
597
  disclosure: boolean,
456
598
  ): Promise<
457
- | { resolved: string; ext: string; stat: import("node:fs").Stats; viaGrant: boolean }
599
+ | { resolved: string; real: string; ext: string; stat: import("node:fs").Stats; viaGrant: boolean }
458
600
  | GateFailure
459
601
  > {
460
602
  if (!cwd || !relPath) return { code: 400, error: "cwd and path parameters required" };
461
603
  const ext = path.extname(relPath).toLowerCase();
462
604
  if (!allowedExts.includes(ext)) return { code: 400, error: "renderer not supported for extension" };
463
- if (!sessionManager.listAll().some((s) => s.cwd === cwd)) {
464
- return { code: 403, error: "unknown session path" };
605
+ const admitted = await admitFileCwd(cwd, routeAdmission);
606
+ if (!admitted.ok) return admitted.failure;
607
+ let resolved: string;
608
+ let decision: Awaited<ReturnType<typeof evaluateContainment>>;
609
+ try {
610
+ resolved = path.resolve(admitted.cwd, relPath);
611
+ decision = await evaluateContainment(resolved, cwdAnchors(admitted), {
612
+ site: "file-routes:gateOfficeFile",
613
+ disclosure,
614
+ });
615
+ } finally {
616
+ admitted.release();
465
617
  }
466
- const resolved = path.resolve(cwd, relPath);
467
- const decision = await evaluateContainment(resolved, [cwd], { site: "file-routes:gateOfficeFile", disclosure });
468
- if (!decision.allowed) {
618
+ if (!containmentAllows(decision, resolved)) {
469
619
  return { code: 403, error: "path outside working directory", ...decision.remedy };
470
620
  }
471
621
  let stat: import("node:fs").Stats;
@@ -490,12 +640,31 @@ export function registerFileRoutes(
490
640
  throw err;
491
641
  }
492
642
  }
493
- return { resolved, ext, stat, viaGrant: decision.viaGrant };
643
+ return { resolved, real: decision.real, ext, stat, viaGrant: decision.viaGrant };
494
644
  }
495
645
 
496
- // Allowed browse roots: `$HOME` + current pinned dirs, recomputed per request
497
- // so a pin/unpin takes effect immediately. See change: harden-server-capability-bounds.
498
- const browseRoots = () => resolveBrowseRoots(preferencesStore.getPinnedDirectories());
646
+ // Browse confinement applies ONLY to requests that are not genuinely local
647
+ // (tunnel, LAN, relayed loopback). Returns the shared-root set to enforce, or
648
+ // `null` for a local request (unrestricted picker). Roots are recomputed per
649
+ // request so a pin / unpin / grant applies immediately.
650
+ // See change: harden-server-capability-bounds (D1, D2).
651
+ const browseRootSources = buildBrowseRootSources({
652
+ preferencesStore,
653
+ sessionManager,
654
+ worktreeRoots: deps.browseRootSources?.worktreeRoots,
655
+ projectGrants: deps.browseRootSources?.projectGrants,
656
+ });
657
+ async function confinedRoots(request: { ip: string; headers: Record<string, unknown> }): Promise<BrowseRoots | null> {
658
+ if (deps.browseConfineRemote === false) return null;
659
+ if (isLocallyTrusted({ ip: request.ip, headers: request.headers }, deps.localTrust)) return null;
660
+ return resolveBrowseRoots(browseRootSources);
661
+ }
662
+ const refuseOutsideRoots = (reply: { code(n: number): unknown }, route: string, requested: string) => {
663
+ // JSON.stringify: the path is caller-controlled, so a newline must not forge a log line.
664
+ console.warn(`[browse] refused ${route}: ${JSON.stringify(requested)} is outside the shared roots`);
665
+ reply.code(403);
666
+ return { success: false, error: BROWSE_OUTSIDE_ROOTS_ERROR } satisfies ApiResponse;
667
+ };
499
668
 
500
669
  // Directory browse endpoint.
501
670
  // `detect=1` opts into eager `.git` / `.pi` classification on every entry
@@ -503,27 +672,32 @@ export function registerFileRoutes(
503
672
  // Without `detect`, this is a single-readdir enumeration with no filesystem
504
673
  // probes — use `GET /api/browse/flags` to classify lazily.
505
674
  // See change: split-browse-flags.
506
- fastify.get<{ Querystring: { path?: string; q?: string; detect?: string } }>(
675
+ fastify.get<{ Querystring: { path?: string; q?: string; detect?: string; files?: string; hidden?: string; ext?: string } }>(
507
676
  "/api/browse",
508
677
  { preHandler: networkGuard },
509
678
  async (request, reply) => {
510
- // Confined to `$HOME` + pinned dirs (B8). No path → home, always allowed.
511
- // See change: harden-server-capability-bounds.
512
- const roots = await browseRoots();
679
+ const roots = await confinedRoots(request);
513
680
  const requested = request.query.path || undefined;
514
- if (requested && !(await isWithinBrowseRoots(requested, roots))) {
515
- reply.code(403);
516
- return { success: false, error: BROWSE_OUTSIDE_ROOTS_ERROR } satisfies ApiResponse;
681
+ if (roots && requested && !(await isWithinBrowseRoots(requested, roots))) {
682
+ return refuseOutsideRoots(reply, "GET /api/browse", requested);
517
683
  }
518
684
  try {
519
685
  const result = await listDirectories(
520
686
  requested,
521
687
  request.query.q || undefined,
522
- { detect: request.query.detect === "1" },
688
+ {
689
+ detect: request.query.detect === "1",
690
+ files: request.query.files === "1",
691
+ hidden: request.query.hidden === "1",
692
+ ext: request.query.ext || undefined,
693
+ // Independent of confinement: `browseConfineRemote=false` must not expose credential dirs.
694
+ excludeForbidden: !isLocallyTrusted({ ip: request.ip, headers: request.headers }, deps.localTrust),
695
+ },
523
696
  );
524
- // Never offer a `..` row that leads to a refused directory.
525
- if (result.parent && !(await isWithinBrowseRoots(result.parent, roots))) {
526
- result.parent = null;
697
+ if (roots) {
698
+ result.confined = true;
699
+ // Never offer a `..` row that leads to a refused directory.
700
+ if (result.parent && !(await isWithinBrowseRoots(result.parent, roots))) result.parent = null;
527
701
  }
528
702
  return { success: true, data: result } satisfies ApiResponse;
529
703
  } catch {
@@ -547,11 +721,10 @@ export function registerFileRoutes(
547
721
  reply.code(400);
548
722
  return { success: false, error: parsed.error } satisfies ApiResponse;
549
723
  }
550
- const roots = await browseRoots();
551
- for (const p of parsed.paths) {
552
- if (!(await isWithinBrowseRoots(p, roots))) {
553
- reply.code(403);
554
- return { success: false, error: BROWSE_OUTSIDE_ROOTS_ERROR } satisfies ApiResponse;
724
+ const roots = await confinedRoots(request);
725
+ if (roots) {
726
+ for (const p of parsed.paths) {
727
+ if (!(await isWithinBrowseRoots(p, roots))) return refuseOutsideRoots(reply, "GET /api/browse/flags", p);
555
728
  }
556
729
  }
557
730
  const flags = await classifyPaths(parsed.paths);
@@ -567,10 +740,10 @@ export function registerFileRoutes(
567
740
  const body = request.body ?? {};
568
741
  const parent = typeof body.parent === "string" ? body.parent : "";
569
742
  const name = typeof body.name === "string" ? body.name : "";
570
- // mkdir only inside `$HOME` + pinned dirs (B8). Checked before any fs write.
571
- if (parent && !(await isWithinBrowseRoots(parent, await browseRoots()))) {
572
- reply.code(403);
573
- return { success: false, error: BROWSE_OUTSIDE_ROOTS_ERROR } satisfies ApiResponse;
743
+ // A remote caller may create only inside the shared roots; checked before any fs write.
744
+ const roots = await confinedRoots(request);
745
+ if (roots && parent && !(await isWithinBrowseRoots(parent, roots))) {
746
+ return refuseOutsideRoots(reply, "POST /api/browse/mkdir", parent);
574
747
  }
575
748
  try {
576
749
  const newPath = await createDirectory(parent, name);
@@ -620,10 +793,9 @@ export function registerFileRoutes(
620
793
  "/api/file",
621
794
  { preHandler: networkGuard },
622
795
  async (request, reply) => {
623
- const gate = await gateReadPath(request.query.cwd, request.query.path, { sessionManager, request, reply });
796
+ const gate = await gateReadPath(request.query.cwd, request.query.path, { routeAdmission, request, reply });
624
797
  if ("code" in gate) {
625
- reply.code(gate.code);
626
- return denialBody(gate);
798
+ return sendGateFailure(reply, gate);
627
799
  }
628
800
  const { resolved } = gate;
629
801
 
@@ -648,18 +820,23 @@ export function registerFileRoutes(
648
820
  // two syscalls, so without it the path could be swapped for a symlink or
649
821
  // a FIFO in the gap. Layer ①/② reads keep the pre-existing open.
650
822
  const fh = gate.viaGrant
651
- ? await openVerifiedRegularFile(resolved)
652
- : await fs.open(resolved, "r");
823
+ ? await openVerifiedRegularFile(gate.real, { decidedReal: gate.real })
824
+ : await openStateChecked(gate.real, "r", { decidedReal: gate.real });
653
825
  let kindResult;
654
826
  let content: string | undefined;
827
+ // size/mtime come from the SAME checked handle as the content, so a link retargeted after the
828
+ // decision can never pair A's bytes with B's mtime (the editor's optimistic-concurrency token).
829
+ let handleStat: import("node:fs").Stats;
655
830
  try {
656
- const sniffLen = Math.min(1024, stat.size);
831
+ handleStat = await fh.stat();
832
+ const sniffLen = Math.min(1024, handleStat.size);
657
833
  const sniff = Buffer.alloc(sniffLen);
658
834
  if (sniffLen > 0) await fh.read(sniff, 0, sniffLen, 0);
659
835
  kindResult = fileKind(resolved, sniff);
660
836
  if (
661
837
  kindResult.viewer === "monaco" ||
662
838
  kindResult.viewer === "markdown" ||
839
+ kindResult.kind === "html" || // read-only Source tab (rich-chat-links)
663
840
  kindResult.editable === true
664
841
  ) {
665
842
  content = await fh.readFile("utf-8");
@@ -673,20 +850,21 @@ export function registerFileRoutes(
673
850
  type: "file",
674
851
  kind: kindResult.kind,
675
852
  mimeType: kindResult.mimeType,
676
- size: stat.size,
853
+ size: handleStat.size,
677
854
  // mtime drives the editor's optimistic-concurrency check on write.
678
855
  // Full precision: `/api/file/write` compares against raw `mtimeMs`,
679
856
  // so a rounded token 409s on every save on sub-ms filesystems.
680
857
  // See change: directory-settings-page-and-scoped-md-editing,
681
858
  // fix-editor-mtime-token-precision.
682
- mtime: stat.mtimeMs,
859
+ mtime: handleStat.mtimeMs,
683
860
  ...(content !== undefined ? { content } : {}),
684
861
  },
685
862
  } satisfies ApiResponse;
686
863
  } catch (err) {
687
- if (err instanceof VerifiedReadRefused) {
864
+ if (err instanceof VerifiedReadRefused || err instanceof DashboardStateRefused) {
688
865
  // A granted path whose file is not a regular file, or was swapped
689
- // between the check and the open. Refused in the site's existing
866
+ // between the check and the open (or a swap onto a dashboard secret).
867
+ // Refused in the site's existing
690
868
  // containment shape — deliberately no new user-facing string.
691
869
  reply.code(403);
692
870
  return { success: false, error: "path outside working directory" } satisfies ApiResponse;
@@ -710,15 +888,14 @@ export function registerFileRoutes(
710
888
  { preHandler: networkGuard },
711
889
  async (request, reply) => {
712
890
  const gate = await gateReadPath(request.query.cwd, request.query.path, {
713
- sessionManager,
891
+ routeAdmission,
714
892
  request,
715
893
  reply,
716
894
  quiet: true,
717
895
  });
718
896
  reply.header("Cache-Control", "no-store");
719
897
  if ("code" in gate) {
720
- reply.code(gate.code);
721
- return denialBody(gate);
898
+ return sendGateFailure(reply, gate);
722
899
  }
723
900
  const lane: DigestLane = request.query.purpose === "baseline" ? "baseline" : "verify";
724
901
  const ac = new AbortController();
@@ -730,8 +907,8 @@ export function registerFileRoutes(
730
907
  try {
731
908
  release = await digestGate.acquire(lane, ac.signal);
732
909
  const fh = gate.viaGrant
733
- ? await openVerifiedRegularFile(gate.resolved)
734
- : await fs.open(gate.resolved, fsConstants.O_RDONLY | (fsConstants.O_NONBLOCK ?? 0));
910
+ ? await openVerifiedRegularFile(gate.real, { decidedReal: gate.real })
911
+ : await openStateChecked(gate.real, fsConstants.O_RDONLY | (fsConstants.O_NONBLOCK ?? 0), { decidedReal: gate.real });
735
912
  try {
736
913
  const stat = await fh.stat();
737
914
  if (!stat.isFile()) {
@@ -748,7 +925,7 @@ export function registerFileRoutes(
748
925
  await fh.close();
749
926
  }
750
927
  } catch (err) {
751
- if (err instanceof VerifiedReadRefused) {
928
+ if (err instanceof VerifiedReadRefused || err instanceof DashboardStateRefused) {
752
929
  reply.code(403);
753
930
  return { success: false, error: "path outside working directory" } satisfies ApiResponse;
754
931
  }
@@ -804,16 +981,15 @@ export function registerFileRoutes(
804
981
  // `allowGrant: false` — a read grant must NOT authorize launching a local
805
982
  // application or revealing in the file manager. Those are a different
806
983
  // capability from reading, so the two spawn routes keep the pre-change
807
- // `isAllowed`-only decision (task 4.5 review gate, blocking #2).
808
- const gate = await gateFilePath(cwd, rawPath, sessionManager, {
984
+ // layers ①/② only decision (task 4.5 review gate, blocking #2).
985
+ const gate = await gateFilePath(cwd, rawPath, routeAdmission, {
809
986
  allowGrant: false,
810
987
  disclosure: canDiscloseAccessPosture(request),
811
988
  });
812
989
  if ("code" in gate) {
813
- reply.code(gate.code);
814
- return denialBody(gate);
990
+ return sendGateFailure(reply, gate);
815
991
  }
816
- const { cmd, args } = build(systemOpenPlatform, gate.resolved);
992
+ const { cmd, args } = build(systemOpenPlatform, gate.real);
817
993
  systemOpenRun(cmd, args);
818
994
  return { success: true, data: { spawned: true } };
819
995
  };
@@ -848,22 +1024,20 @@ export function registerFileRoutes(
848
1024
  return { success: false, error: "cwd and path parameters required" } satisfies ApiResponse;
849
1025
  }
850
1026
 
851
- if (!sessionManager.listAll().some((s) => s.cwd === cwd)) {
852
- reply.code(403);
853
- return { success: false, error: "unknown session path" } satisfies ApiResponse;
854
- }
1027
+ const admitted = await admitFileCwd(cwd, routeAdmission, { reply });
1028
+ if (!admitted.ok) return sendGateFailure(reply, admitted.failure);
855
1029
 
856
- const resolved = path.resolve(cwd, relPath);
857
- const treeDecision = await evaluateContainment(resolved, [cwd], {
1030
+ const resolved = path.resolve(admitted.cwd, relPath);
1031
+ const treeDecision = await evaluateContainment(resolved, cwdAnchors(admitted), {
858
1032
  site: "file-routes:tree",
859
1033
  hold: { request, reply },
860
1034
  disclosure: canDiscloseAccessPosture(request),
861
- session: cwd,
1035
+ session: admitted.cwd,
862
1036
  // Directory-only site: the remedy must name THIS directory, not its
863
1037
  // parent (task 4.5 review).
864
1038
  subjectKind: "directory",
865
1039
  });
866
- if (!treeDecision.allowed) {
1040
+ if (!containmentAllows(treeDecision, resolved)) {
867
1041
  reply.code(403);
868
1042
  return { success: false, error: "path outside working directory", ...treeDecision.remedy } as unknown as ApiResponse;
869
1043
  }
@@ -918,10 +1092,9 @@ export function registerFileRoutes(
918
1092
  // the handler still refuses content above the 256 MiB ceiling.
919
1093
  { preHandler: networkGuard, bodyLimit: 600 * 1024 * 1024 },
920
1094
  async (request, reply) => {
921
- const prep = await prepareMdWrite(request.body ?? {}, sessionManager);
1095
+ const prep = await prepareMdWrite(request.body ?? {}, routeAdmission, { request, reply });
922
1096
  if ("code" in prep) {
923
- reply.code(prep.code);
924
- return { success: false, error: prep.error } satisfies ApiResponse;
1097
+ return sendGateFailure(reply, prep);
925
1098
  }
926
1099
  // Critical section: stat → mtime check → write → rename runs serialized per
927
1100
  // target so the optimistic check is atomic w.r.t. a concurrent write.
@@ -929,7 +1102,7 @@ export function registerFileRoutes(
929
1102
  // cannot run two writes to one file at once. See change: add-editor-pane-file-handlers (D4).
930
1103
  const lockKey = await safeRealpath(prep.resolved);
931
1104
  const outcome = await serializeWrite(lockKey, () =>
932
- performAtomicMdWrite(prep.resolved, prep.content, prep.mtime),
1105
+ performAtomicMdWrite(prep.resolved, prep.content, prep.mtime, prep.gatedReal),
933
1106
  );
934
1107
  if (outcome.code !== 200) {
935
1108
  reply.code(outcome.code);
@@ -952,15 +1125,16 @@ export function registerFileRoutes(
952
1125
  "/api/file/md-candidates",
953
1126
  { preHandler: networkGuard },
954
1127
  async (request, reply) => {
955
- const cwd = request.query.cwd || undefined;
956
- if (cwd) {
957
- const allSessions = sessionManager.listAll();
958
- if (!allSessions.some((s) => s.cwd === cwd)) {
959
- reply.code(403);
960
- return { success: false, error: "unknown session path" } satisfies ApiResponse;
961
- }
962
- }
963
- const candidates = await enumerateMdCandidates({ cwd });
1128
+ // Absent (undefined / "") → global scope with a constant `{}`; any other value must be an
1129
+ // admitted absolute cwd. See change: core-file-cwd-admission (D1).
1130
+ const rawCwd: unknown = request.query.cwd;
1131
+ if (rawCwd === undefined || rawCwd === "") {
1132
+ const globalCandidates = await enumerateMdCandidates({});
1133
+ return { success: true, data: { candidates: globalCandidates } } satisfies ApiResponse;
1134
+ }
1135
+ const admitted = await admitFileCwd(rawCwd, routeAdmission, { reply });
1136
+ if (!admitted.ok) return sendGateFailure(reply, admitted.failure);
1137
+ const candidates = await enumerateMdCandidates({ cwd: admitted.cwd });
964
1138
  return { success: true, data: { candidates } } satisfies ApiResponse;
965
1139
  },
966
1140
  );
@@ -976,31 +1150,42 @@ export function registerFileRoutes(
976
1150
  "/api/file/md-read",
977
1151
  { preHandler: networkGuard },
978
1152
  async (request, reply) => {
979
- const cwd = request.query.cwd || undefined;
980
1153
  const rawPath = request.query.path;
981
1154
  if (!rawPath) {
982
1155
  reply.code(400);
983
1156
  return { success: false, error: "path parameter required" } satisfies ApiResponse;
984
1157
  }
985
- const target = resolveScopedMdPath(cwd, rawPath, sessionManager);
1158
+ const target = await resolveScopedMdPath(request.query.cwd, rawPath, routeAdmission);
986
1159
  if ("code" in target) {
987
- reply.code(target.code);
988
- return { success: false, error: target.error } satisfies ApiResponse;
1160
+ return sendGateFailure(reply, target);
989
1161
  }
990
1162
  const resolved = target.resolved;
991
- if (!(await isWritableMdTarget(resolved, { cwd }))) {
1163
+ if (!(await isWritableMdTarget(resolved, { cwd: target.cwd }))) {
992
1164
  reply.code(403);
993
1165
  return { success: false, error: "target is not a readable markdown file in scope" } satisfies ApiResponse;
994
1166
  }
995
1167
  try {
996
- const stat = await fs.stat(resolved);
997
- const content = await fs.readFile(resolved, "utf-8");
1168
+ // One checked handle for both the bytes and the mtime token, so they describe the same file
1169
+ // even under a swap (and the credential recheck covers the opened inode).
1170
+ const fh = await openStateChecked(resolved, "r");
1171
+ let content: string;
1172
+ let mtimeMs: number;
1173
+ try {
1174
+ content = await fh.readFile("utf-8");
1175
+ mtimeMs = (await fh.stat()).mtimeMs;
1176
+ } finally {
1177
+ await fh.close().catch(() => undefined);
1178
+ }
998
1179
  // Full-precision mtime token (matches the write-side conflict check).
999
1180
  return {
1000
1181
  success: true,
1001
- data: { content, mtime: stat.mtimeMs },
1182
+ data: { content, mtime: mtimeMs },
1002
1183
  } satisfies ApiResponse;
1003
- } catch {
1184
+ } catch (err) {
1185
+ if (err instanceof DashboardStateRefused) {
1186
+ reply.code(403);
1187
+ return { success: false, error: "path outside working directory" } satisfies ApiResponse;
1188
+ }
1004
1189
  reply.code(404);
1005
1190
  return { success: false, error: "not found" } satisfies ApiResponse;
1006
1191
  }
@@ -1024,21 +1209,12 @@ export function registerFileRoutes(
1024
1209
  reply.code(400);
1025
1210
  return { success: false, error: "cwd and path parameters required" } satisfies ApiResponse;
1026
1211
  }
1027
- const allSessions = sessionManager.listAll();
1028
- const knownCwds = new Set(allSessions.map((s) => s.cwd));
1029
- for (const dir of preferencesStore.getPinnedDirectories()) knownCwds.add(dir);
1030
- // The unknown-cwd denial may ask the operator (add-access-grant-dialog,
1031
- // task 6.2). An allow verdict authorises a RE-RUN of this same guard, never
1032
- // a skip: `allow-always` pinned the directory, so the live pinned set must
1033
- // now contain it; `allow-once` admits exactly the named directory, for this
1034
- // request only. Every other outcome returns the unchanged denial below.
1035
- const cwdAdmitted =
1036
- knownCwds.has(cwd) ||
1037
- (await unknownCwdVerdictAdmits(cwd, { request, reply }, () => [
1038
- ...sessionManager.listAll().map((s) => s.cwd),
1039
- ...preferencesStore.getPinnedDirectories(),
1040
- ]));
1041
- if (!cwdAdmitted) {
1212
+ // Admission (change: core-file-cwd-admission, D5). An absolute cwd is admitted through the
1213
+ // shared guard; a refusal may ask the operator (add-access-grant-dialog, task 6.2). An allow
1214
+ // verdict authorises a RE-RUN of the guard, never a skip: `allow-always` pinned the
1215
+ // directory so the live known set now contains it; `allow-once` admits exactly the named
1216
+ // directory, for this request only. An undecidable admission answers 503 and never prompts.
1217
+ const existsRefusal = (): ApiResponse => {
1042
1218
  reply.code(403);
1043
1219
  // Additive remedy fields beside the unchanged `"unknown cwd"` string
1044
1220
  // (design D7/D18); the known-cwd set already includes pinned
@@ -1048,10 +1224,24 @@ export function registerFileRoutes(
1048
1224
  // add-access-grants-and-review.
1049
1225
  return {
1050
1226
  success: false,
1227
+ code: "cwd_unknown",
1051
1228
  error: "unknown cwd",
1052
1229
  reason: "cwd is not a known session or pinned directory.",
1053
1230
  hint: "Pin this directory to allow it, or open a session rooted in it.",
1054
1231
  } as unknown as ApiResponse;
1232
+ };
1233
+ if (typeof cwd !== "string" || !path.isAbsolute(cwd)) return existsRefusal();
1234
+ let admitted = await admitFileCwd(cwd, routeAdmission, { error: "unknown cwd", reply });
1235
+ if (!admitted.ok && admitted.failure.code === 503) return sendGateFailure(reply, admitted.failure);
1236
+ if (!admitted.ok) {
1237
+ const decision = await unknownCwdVerdict(cwd, { request, reply }, routeAdmission);
1238
+ if (decision.kind === "indeterminate") return sendGateFailure(reply, CWD_UNAVAILABLE_FAILURE);
1239
+ const held = issueHeldAdmission(decision, cwd);
1240
+ if (held.kind !== "admit" || !admissionAllows(held, cwd)) return existsRefusal();
1241
+ const token = held.token;
1242
+ const release = (): void => releaseAdmission(token);
1243
+ releaseOnClose(reply, release);
1244
+ admitted = { ok: true, cwd, canonCwd: token.canonCwd, release };
1055
1245
  }
1056
1246
  // Anti-traversal: probePath MUST be inside cwd (or a pinned dir / repo
1057
1247
  // git root). Pinned-dir anchor is exists-only; not folded onto read/raw/render.
@@ -1064,16 +1254,16 @@ export function registerFileRoutes(
1064
1254
  return { success: false, error: "path outside cwd" } satisfies ApiResponse;
1065
1255
  }
1066
1256
  const resolved = path.resolve(probePath);
1067
- const anchors = [cwd, ...preferencesStore.getPinnedDirectories()];
1257
+ const anchors = [...cwdAnchors(admitted), ...preferencesStore.getPinnedDirectories()];
1068
1258
  const existsDecision = await evaluateContainment(resolved, anchors, {
1069
1259
  site: "file-routes:exists",
1070
1260
  hold: { request, reply },
1071
1261
  disclosure: canDiscloseAccessPosture(request),
1072
- session: cwd,
1262
+ session: admitted.cwd,
1073
1263
  // `fs.access` accepts files AND directories — polymorphic, see above.
1074
1264
  subjectKind: "auto",
1075
1265
  });
1076
- if (!existsDecision.allowed) {
1266
+ if (!containmentAllows(existsDecision, resolved)) {
1077
1267
  reply.code(403);
1078
1268
  return { success: false, error: "path outside cwd", ...existsDecision.remedy } as unknown as ApiResponse;
1079
1269
  }
@@ -1089,14 +1279,21 @@ export function registerFileRoutes(
1089
1279
 
1090
1280
  // Lazy file-mention resolver (change: server-side-file-mention-resolution).
1091
1281
  //
1092
- // Body `{ cwd, mention }` → `{ resolved, kind }` or `{ resolved: null }`.
1282
+ // Body `{ cwd, mention }` → `{ resolved, kind }`, `{ resolved, kind, outside: true }` (containment
1283
+ // failed: never statted, so the payload is independent of existence — change fix-file-link-editor-routing
1284
+ // D1) or `{ resolved: null }`.
1093
1285
  // `cwd` is UNTRUSTED request input and is gated against the known-session set
1094
1286
  // (mirrors `/api/file`, NOT the wider exists-only pinned set — design D2/F6/F7,
1095
1287
  // so a resolve never succeeds on a path the open route would 403) BEFORE any
1096
1288
  // resolution. `resolveFileMention` then expands `~/`, runs containment
1097
1289
  // (cwd + git-root + `~/.pi`) BEFORE `fs.stat`, and returns null for a
1098
1290
  // non-existent in-scope mention (never an error).
1099
- fastify.post<{ Body: { cwd?: unknown; mention?: unknown } }>(
1291
+ //
1292
+ // Opt-in recovery (change: rich-chat-links, design D3): `recover: true` (literal boolean) enables the producing
1293
+ // tool's directory (`toolCwd`, a string ≤ 1024 chars) and the tracked-file fuzzy fallback; without it the answer
1294
+ // is exactly the exact-only lookup. Every answer carries `state` (found | recovered | ambiguous | missing | gated);
1295
+ // recovery adds `via`, ambiguity adds `candidates` (and `resolved: null`).
1296
+ fastify.post<{ Body: { cwd?: unknown; mention?: unknown; recover?: unknown; toolCwd?: unknown } }>(
1100
1297
  "/api/file/resolve-mention",
1101
1298
  { preHandler: networkGuard },
1102
1299
  async (request, reply) => {
@@ -1107,15 +1304,98 @@ export function registerFileRoutes(
1107
1304
  reply.code(400);
1108
1305
  return { success: false, error: "cwd and mention are required" } satisfies ApiResponse;
1109
1306
  }
1110
- if (!sessionManager.listAll().some((s) => s.cwd === cwd)) {
1111
- reply.code(403);
1112
- return { success: false, error: "unknown session path" } satisfies ApiResponse;
1307
+ const toolCwd = typeof body.toolCwd === "string" && body.toolCwd !== "" ? body.toolCwd : undefined;
1308
+ if (toolCwd !== undefined && toolCwd.length > MAX_FIELD_CHARS) {
1309
+ reply.code(400);
1310
+ return { success: false, error: `toolCwd exceeds ${MAX_FIELD_CHARS} characters` } satisfies ApiResponse;
1311
+ }
1312
+ const admitted = await admitFileCwd(cwd, routeAdmission, { reply });
1313
+ if (!admitted.ok) return sendGateFailure(reply, admitted.failure);
1314
+ const result = await resolveMentionTagged(mention, {
1315
+ cwd: admitted.cwd,
1316
+ canonCwd: admitted.canonCwd,
1317
+ recover: body.recover === true,
1318
+ toolCwd,
1319
+ fuzzyIndex: mentionIndex,
1320
+ });
1321
+ return { success: true, data: result } satisfies ApiResponse;
1322
+ },
1323
+ );
1324
+
1325
+ // Batch mention resolver (change: rich-chat-links, design D3/D14). Body `{ cwd, items: [{ mention, toolCwd?,
1326
+ // reRooted? }] }` → `{ results }` in request order. Always recovers. Same network guard, tier (`observe`) and
1327
+ // `cwd` admission as the single route, and admission runs BEFORE any resolution. Bounds: 512 KB body (413),
1328
+ // any string field > 1024 chars (400, decided before any filesystem access), 200 resolved items per request
1329
+ // (the rest `unknown`), 60 requests/min per principal (429). `gated` items carry only their state.
1330
+ const batchLimiter = createWindowLimiter(BATCH_RATE_PER_MINUTE);
1331
+ fastify.post(
1332
+ "/api/file/resolve-mentions",
1333
+ { preHandler: networkGuard, bodyLimit: BATCH_BODY_LIMIT_BYTES },
1334
+ async (request, reply) => {
1335
+ const started = performance.now();
1336
+ const principal = requestPrincipalKey(request);
1337
+ // Without a real principal every local caller would share one bucket anyway; key by address.
1338
+ if (!batchLimiter.take(principal === "local-operator" ? `${principal}@${request.ip}` : principal)) {
1339
+ reply.code(429);
1340
+ return { success: false, error: "rate limited" } satisfies ApiResponse;
1341
+ }
1342
+ const parsed = parseBatchBody(request.body);
1343
+ if (!parsed.ok) {
1344
+ reply.code(400);
1345
+ return { success: false, error: parsed.error } satisfies ApiResponse;
1113
1346
  }
1114
- const result = await resolveFileMention(mention, { cwd });
1115
- return {
1116
- success: true,
1117
- data: result ? { resolved: result.resolved, kind: result.kind } : { resolved: null },
1118
- } satisfies ApiResponse;
1347
+ const admitted = await admitFileCwd(parsed.cwd, routeAdmission, { reply });
1348
+ if (!admitted.ok) return sendGateFailure(reply, admitted.failure);
1349
+
1350
+ const counters = { stats: 0 };
1351
+ const containmentMemo: ContainmentMemo = new Map();
1352
+ const fuzzy = { hit: 0, miss: 0, skipped: 0, buildMs: 0 };
1353
+ const fuzzyIndex: MentionFuzzyIndex = {
1354
+ clear: () => mentionIndex.clear(),
1355
+ lookup: async (c, m) => {
1356
+ const r = await mentionIndex.lookup(c, m);
1357
+ if (r.status === "skipped") fuzzy.skipped++;
1358
+ else {
1359
+ if (r.cached) fuzzy.hit++;
1360
+ else {
1361
+ fuzzy.miss++;
1362
+ fuzzy.buildMs = Math.max(fuzzy.buildMs, r.buildMs ?? 0);
1363
+ }
1364
+ }
1365
+ return r;
1366
+ },
1367
+ };
1368
+ const resolved = await mapConcurrent(parsed.items, BATCH_CONCURRENCY, async (item): Promise<BatchResult> =>
1369
+ toBatchResult(
1370
+ await resolveMentionTagged(item.mention, {
1371
+ cwd: admitted.cwd,
1372
+ canonCwd: admitted.canonCwd,
1373
+ recover: true,
1374
+ toolCwd: item.toolCwd,
1375
+ reRooted: item.reRooted,
1376
+ fuzzyIndex,
1377
+ counters,
1378
+ containmentMemo,
1379
+ }),
1380
+ ),
1381
+ );
1382
+ // Items past the cap are never materialised: one shared `unknown`, same order and length as the request.
1383
+ const overflow = parsed.total - parsed.items.length;
1384
+ const results: BatchResult[] = overflow > 0 ? resolved.concat(new Array<BatchResult>(overflow).fill({ state: "unknown" })) : resolved;
1385
+ const counts: Partial<Record<BatchResult["state"], number>> = {};
1386
+ for (const r of resolved) counts[r.state] = (counts[r.state] ?? 0) + 1;
1387
+ if (overflow > 0) counts.unknown = overflow;
1388
+ console.log(
1389
+ formatBatchLog({
1390
+ cwd: admitted.cwd,
1391
+ items: parsed.total,
1392
+ counts,
1393
+ fuzzy,
1394
+ stats: counters.stats,
1395
+ totalMs: performance.now() - started,
1396
+ }),
1397
+ );
1398
+ return { success: true, data: { results } } satisfies ApiResponse;
1119
1399
  },
1120
1400
  );
1121
1401
 
@@ -1134,8 +1414,9 @@ export function registerFileRoutes(
1134
1414
  // Streams the file bytes with `Content-Type` from extension, supports
1135
1415
  // HTTP Range so `<video>` seek works. Same cwd-allowlist + anti-traversal
1136
1416
  // gate as `/api/file`. Sets `Content-Disposition: inline` and a short
1137
- // private cache.
1138
- fastify.get<{ Querystring: { cwd?: string; path?: string } }>(
1417
+ // private cache. `download=1` switches to an attachment disposition
1418
+ // (change: add-file-download); nothing else about the route changes.
1419
+ fastify.get<{ Querystring: { cwd?: string; path?: string; download?: string } }>(
1139
1420
  "/api/file/raw",
1140
1421
  { preHandler: networkGuard },
1141
1422
  async (request, reply) => {
@@ -1146,13 +1427,11 @@ export function registerFileRoutes(
1146
1427
  return { success: false, error: "cwd and path parameters required" } satisfies ApiResponse;
1147
1428
  }
1148
1429
 
1149
- const allSessions = sessionManager.listAll();
1150
- if (!allSessions.some((s) => s.cwd === cwd)) {
1151
- reply.code(403);
1152
- return { success: false, error: "unknown session path" } satisfies ApiResponse;
1153
- }
1430
+ const admitted = await admitFileCwd(cwd, routeAdmission, { reply });
1431
+ if (!admitted.ok) return sendGateFailure(reply, admitted.failure);
1432
+ const rawAnchors = [...cwdAnchors(admitted), homePiAnchor()];
1154
1433
 
1155
- const resolved = path.resolve(cwd, relPath);
1434
+ const resolved = path.resolve(admitted.cwd, relPath);
1156
1435
  // Layers ①/② (cwd + git common root) serve any type. Layer ③ — artifact
1157
1436
  // roots — is image-only and real-path contained; it covers agent
1158
1437
  // screenshots that live outside every cwd and git root.
@@ -1163,19 +1442,26 @@ export function registerFileRoutes(
1163
1442
  // True only when the GRANT layer admitted this read — layers ①/② and the
1164
1443
  // artifact root do NOT get handle verification (task 2.8 scope).
1165
1444
  let viaGrant = false;
1166
- if (!(await isAllowed(resolved, { anchors: [cwd, homePiAnchor()] }))) {
1445
+ // The real path the admitting decision was made on; the open below is bound to it.
1446
+ // An artifact-root image carries no decision (real-path contained by its own check) → opens `resolved`.
1447
+ let decidedReal: string | undefined;
1448
+ const passiveDecision = await decidePassive(resolved, rawAnchors, { allowGrant: false });
1449
+ if (containmentAllows(passiveDecision, resolved)) {
1450
+ decidedReal = passiveDecision.real;
1451
+ } else {
1167
1452
  if (!(await isImageUnderArtifactRoot(resolved))) {
1168
- const rawDecision = await evaluateContainment(resolved, [cwd, homePiAnchor()], {
1453
+ const rawDecision = await evaluateContainment(resolved, rawAnchors, {
1169
1454
  site: "file-routes:raw",
1170
1455
  hold: { request, reply },
1171
1456
  disclosure: canDiscloseAccessPosture(request),
1172
- session: cwd,
1457
+ session: admitted.cwd,
1173
1458
  });
1174
- if (!rawDecision.allowed) {
1459
+ if (!containmentAllows(rawDecision, resolved)) {
1175
1460
  reply.code(403);
1176
1461
  return { success: false, error: "path outside working directory", ...rawDecision.remedy } as unknown as ApiResponse;
1177
1462
  }
1178
1463
  viaGrant = rawDecision.viaGrant;
1464
+ decidedReal = rawDecision.real;
1179
1465
  }
1180
1466
  }
1181
1467
 
@@ -1198,7 +1484,19 @@ export function registerFileRoutes(
1198
1484
  const size = stat.size;
1199
1485
 
1200
1486
  reply.header("Content-Type", contentType);
1201
- reply.header("Content-Disposition", "inline");
1487
+ reply.header(
1488
+ "Content-Disposition",
1489
+ request.query.download === "1" ? contentDispositionAttachment(path.basename(resolved)) : "inline",
1490
+ );
1491
+ // Scriptable media types (SVG/HTML/XML) opened directly would run with the
1492
+ // dashboard origin. Enforce an opaque-origin sandbox in EVERY dashboard CSP
1493
+ // mode, on 200/206/416 and every admission path. The baseline CSP hook
1494
+ // only adds a header that is absent, so this is never overwritten.
1495
+ // See change: harden-raw-svg-responses.
1496
+ if (isScriptableMediaType(contentType)) {
1497
+ reply.header("Content-Security-Policy", RAW_SANDBOX_CSP);
1498
+ reply.header("X-Content-Type-Options", "nosniff");
1499
+ }
1202
1500
  reply.header("Cache-Control", "private, max-age=60");
1203
1501
  reply.header("Accept-Ranges", "bytes");
1204
1502
 
@@ -1252,33 +1550,50 @@ export function registerFileRoutes(
1252
1550
 
1253
1551
  // A grant-admitted read additionally binds the bytes served to the inode
1254
1552
  // that was checked (design D14, task 2.8).
1553
+ // The media headers were set above; an open-time refusal answers JSON, so reset them (a JSON body under
1554
+ // the file's own content type is a 500) and keep the refusal out of caches.
1555
+ const openRefusal = (code: number, error: string): ApiResponse => {
1556
+ reply.code(code);
1557
+ reply.type("application/json; charset=utf-8");
1558
+ reply.header("Cache-Control", "no-store");
1559
+ reply.removeHeader("Accept-Ranges");
1560
+ reply.removeHeader("Content-Security-Policy");
1561
+ reply.removeHeader("Content-Disposition"); // `download=1` must not save the JSON refusal as the file
1562
+ return { success: false, error };
1563
+ };
1255
1564
  let grantedHandle: Awaited<ReturnType<typeof openVerifiedRegularFile>> | undefined;
1256
1565
  if (viaGrant) {
1257
1566
  try {
1258
- grantedHandle = await openVerifiedRegularFile(resolved);
1567
+ grantedHandle = await openVerifiedRegularFile(decidedReal ?? resolved, decidedReal ? { decidedReal } : {});
1259
1568
  } catch (err) {
1260
- if (err instanceof VerifiedReadRefused) {
1261
- reply.code(403);
1262
- return { success: false, error: "path outside working directory" } satisfies ApiResponse;
1263
- }
1264
- reply.code(404);
1265
- return { success: false, error: "not found" } satisfies ApiResponse;
1569
+ if (err instanceof VerifiedReadRefused) return openRefusal(403, "path outside working directory");
1570
+ return openRefusal(404, "not found");
1571
+ }
1572
+ }
1573
+
1574
+ // Non-grant reads open here so the handle can be checked against the always-refused dashboard
1575
+ // files before a single byte is streamed (the path check and the open are two syscalls).
1576
+ let rawHandle: Awaited<ReturnType<typeof openStateChecked>> | undefined;
1577
+ if (!grantedHandle) {
1578
+ try {
1579
+ rawHandle = await openStateChecked(decidedReal ?? resolved, "r", decidedReal ? { decidedReal } : {});
1580
+ } catch (err) {
1581
+ return err instanceof DashboardStateRefused
1582
+ ? openRefusal(403, "path outside working directory")
1583
+ : openRefusal(404, "not found");
1266
1584
  }
1267
1585
  }
1586
+ const servedHandle = grantedHandle ?? rawHandle!;
1268
1587
 
1269
1588
  if (range) {
1270
1589
  reply.code(206);
1271
1590
  reply.header("Content-Range", `bytes ${range.start}-${range.end}/${size}`);
1272
1591
  reply.header("Content-Length", String(range.end - range.start + 1));
1273
- return reply.send(
1274
- grantedHandle
1275
- ? grantedHandle.createReadStream({ start: range.start, end: range.end })
1276
- : createReadStream(resolved, { start: range.start, end: range.end }),
1277
- );
1592
+ return reply.send(servedHandle.createReadStream({ start: range.start, end: range.end }));
1278
1593
  }
1279
1594
 
1280
1595
  reply.header("Content-Length", String(size));
1281
- return reply.send(grantedHandle ? grantedHandle.createReadStream() : createReadStream(resolved));
1596
+ return reply.send(servedHandle.createReadStream());
1282
1597
  },
1283
1598
  );
1284
1599
 
@@ -1323,14 +1638,22 @@ export function registerFileRoutes(
1323
1638
  canDiscloseAccessPosture(request),
1324
1639
  );
1325
1640
  if ("code" in gate) {
1326
- reply.code(gate.code);
1327
- return denialBody(gate);
1641
+ return sendGateFailure(reply, gate);
1642
+ }
1643
+ let result: Awaited<ReturnType<typeof renderPptx>>;
1644
+ try {
1645
+ result = await renderPptx(
1646
+ gate.real,
1647
+ { mtimeMs: gate.stat.mtimeMs, size: gate.stat.size },
1648
+ { engine: docxPdfEngine },
1649
+ );
1650
+ } catch (err) {
1651
+ if (err instanceof ContainmentBindingRefused) {
1652
+ reply.code(403);
1653
+ return { success: false, error: "path outside working directory" } satisfies ApiResponse;
1654
+ }
1655
+ throw err;
1328
1656
  }
1329
- const result = await renderPptx(
1330
- gate.resolved,
1331
- { mtimeMs: gate.stat.mtimeMs, size: gate.stat.size },
1332
- { engine: docxPdfEngine },
1333
- );
1334
1657
  if (!result.success) {
1335
1658
  return { success: false, error: result.error } satisfies ApiResponse;
1336
1659
  }
@@ -1348,14 +1671,22 @@ export function registerFileRoutes(
1348
1671
  canDiscloseAccessPosture(request),
1349
1672
  );
1350
1673
  if ("code" in gate) {
1351
- reply.code(gate.code);
1352
- return denialBody(gate);
1674
+ return sendGateFailure(reply, gate);
1675
+ }
1676
+ let result: Awaited<ReturnType<typeof renderDocx>>;
1677
+ try {
1678
+ result = await renderDocx(
1679
+ gate.real,
1680
+ { mtimeMs: gate.stat.mtimeMs, size: gate.stat.size },
1681
+ { mode: docxRenderMode, engine: docxPdfEngine, caps: officeCaps },
1682
+ );
1683
+ } catch (err) {
1684
+ if (err instanceof ContainmentBindingRefused) {
1685
+ reply.code(403);
1686
+ return { success: false, error: "path outside working directory" } satisfies ApiResponse;
1687
+ }
1688
+ throw err;
1353
1689
  }
1354
- const result = await renderDocx(
1355
- gate.resolved,
1356
- { mtimeMs: gate.stat.mtimeMs, size: gate.stat.size },
1357
- { mode: docxRenderMode, engine: docxPdfEngine, caps: officeCaps },
1358
- );
1359
1690
  if (!result.success) {
1360
1691
  // Unrenderable tail (corrupt/password/library bug) → 200 + success:false
1361
1692
  // so the client maps it to FallbackPreview (design D5).
@@ -1365,20 +1696,17 @@ export function registerFileRoutes(
1365
1696
  return { success: true, data } satisfies ApiResponse;
1366
1697
  }
1367
1698
 
1368
- const allSessions = sessionManager.listAll();
1369
- if (!allSessions.some((s) => s.cwd === cwd)) {
1370
- reply.code(403);
1371
- return { success: false, error: "unknown session path" } satisfies ApiResponse;
1372
- }
1699
+ const admitted = await admitFileCwd(cwd, routeAdmission, { reply });
1700
+ if (!admitted.ok) return sendGateFailure(reply, admitted.failure);
1373
1701
 
1374
- const resolved = path.resolve(cwd, relPath);
1375
- const renderDecision = await evaluateContainment(resolved, [cwd, homePiAnchor()], {
1702
+ const resolved = path.resolve(admitted.cwd, relPath);
1703
+ const renderDecision = await evaluateContainment(resolved, [...cwdAnchors(admitted), homePiAnchor()], {
1376
1704
  site: "file-routes:render",
1377
1705
  hold: { request, reply },
1378
1706
  disclosure: canDiscloseAccessPosture(request),
1379
- session: cwd,
1707
+ session: admitted.cwd,
1380
1708
  });
1381
- if (!renderDecision.allowed) {
1709
+ if (!containmentAllows(renderDecision, resolved)) {
1382
1710
  reply.code(403);
1383
1711
  return { success: false, error: "path outside working directory", ...renderDecision.remedy } as unknown as ApiResponse;
1384
1712
  }
@@ -1398,7 +1726,7 @@ export function registerFileRoutes(
1398
1726
  // Verified against the open handle (design D14, task 2.8) — a granted
1399
1727
  // FIFO would otherwise block this read indefinitely.
1400
1728
  try {
1401
- source = await readFileVerifiedUtf8(resolved);
1729
+ source = await readFileVerifiedUtf8(renderDecision.real, { decidedReal: renderDecision.real });
1402
1730
  } catch (err) {
1403
1731
  if (err instanceof VerifiedReadRefused) {
1404
1732
  reply.code(403);
@@ -1409,8 +1737,12 @@ export function registerFileRoutes(
1409
1737
  }
1410
1738
  } else {
1411
1739
  try {
1412
- source = await fs.readFile(resolved, "utf-8");
1413
- } catch {
1740
+ source = await readFileStateChecked(renderDecision.real, "utf-8", { decidedReal: renderDecision.real });
1741
+ } catch (err) {
1742
+ if (err instanceof DashboardStateRefused) {
1743
+ reply.code(403);
1744
+ return { success: false, error: "path outside working directory" } satisfies ApiResponse;
1745
+ }
1414
1746
  reply.code(404);
1415
1747
  return { success: false, error: "not found" } satisfies ApiResponse;
1416
1748
  }
@@ -1454,17 +1786,26 @@ export function registerFileRoutes(
1454
1786
  canDiscloseAccessPosture(request),
1455
1787
  );
1456
1788
  if ("code" in gate) {
1457
- reply.code(gate.code);
1458
- return denialBody(gate);
1789
+ return sendGateFailure(reply, gate);
1459
1790
  }
1460
- const out = pdfCachePath(gate.resolved, gate.stat.mtimeMs, gate.stat.size);
1791
+ const out = pdfCachePath(gate.real, gate.stat.mtimeMs, gate.stat.size);
1461
1792
  try {
1462
1793
  await fs.access(out);
1463
1794
  } catch {
1464
1795
  try {
1796
+ // The converter takes a PATH, so the post-open (dev, ino) recheck runs immediately before it
1797
+ // to narrow the swap window. Residual: a swap after this checked open; the converter only
1798
+ // accepts .docx/.pptx and emits a PDF rendering, never the file bytes.
1799
+ // See change: close-security-map-high-findings (D1, F7).
1800
+ const guard = await openStateChecked(gate.real, "r", { decidedReal: gate.real });
1801
+ await guard.close().catch(() => undefined);
1465
1802
  await fs.mkdir(path.dirname(out), { recursive: true });
1466
- await docxPdfEngine.toPdf(gate.resolved, out);
1803
+ await convertBound(docxPdfEngine, gate.real, out);
1467
1804
  } catch (err) {
1805
+ if (err instanceof DashboardStateRefused) {
1806
+ reply.code(403);
1807
+ return { success: false, error: "path outside working directory" } satisfies ApiResponse;
1808
+ }
1468
1809
  reply.code(500);
1469
1810
  return {
1470
1811
  success: false,
@@ -1496,15 +1837,14 @@ export function registerFileRoutes(
1496
1837
  canDiscloseAccessPosture(request),
1497
1838
  );
1498
1839
  if ("code" in gate) {
1499
- reply.code(gate.code);
1500
- return denialBody(gate);
1840
+ return sendGateFailure(reply, gate);
1501
1841
  }
1502
1842
  let buffer: Buffer;
1503
1843
  if (gate.viaGrant) {
1504
1844
  // Read from the VERIFIED handle, so the bytes parsed are the bytes
1505
1845
  // checked (design D14, task 2.8) — not a third resolution of the path.
1506
1846
  try {
1507
- buffer = await readFileVerified(gate.resolved);
1847
+ buffer = await readFileVerified(gate.real, { decidedReal: gate.real });
1508
1848
  } catch (err) {
1509
1849
  if (err instanceof VerifiedReadRefused) {
1510
1850
  reply.code(403);
@@ -1515,8 +1855,12 @@ export function registerFileRoutes(
1515
1855
  }
1516
1856
  } else {
1517
1857
  try {
1518
- buffer = await fs.readFile(gate.resolved);
1519
- } catch {
1858
+ buffer = await readFileStateChecked(gate.real, undefined, { decidedReal: gate.real });
1859
+ } catch (err) {
1860
+ if (err instanceof DashboardStateRefused) {
1861
+ reply.code(403);
1862
+ return { success: false, error: "path outside working directory" } satisfies ApiResponse;
1863
+ }
1520
1864
  reply.code(404);
1521
1865
  return { success: false, error: "not found" } satisfies ApiResponse;
1522
1866
  }
@@ -1543,12 +1887,11 @@ export function registerFileRoutes(
1543
1887
  "/api/file/eml",
1544
1888
  { preHandler: networkGuard },
1545
1889
  async (request, reply) => {
1546
- const gate = await gateFilePath(request.query.cwd, request.query.path, sessionManager, {
1890
+ const gate = await gateFilePath(request.query.cwd, request.query.path, routeAdmission, {
1547
1891
  disclosure: canDiscloseAccessPosture(request),
1548
1892
  });
1549
1893
  if ("code" in gate) {
1550
- reply.code(gate.code);
1551
- return denialBody(gate);
1894
+ return sendGateFailure(reply, gate);
1552
1895
  }
1553
1896
  const ext = path.extname(request.query.path ?? "").toLowerCase();
1554
1897
  if (ext !== ".eml") {
@@ -1578,12 +1921,22 @@ export function registerFileRoutes(
1578
1921
  // previously followed — started failing 400. For a grant admission the
1579
1922
  // bytes now come from the VERIFIED handle, so the path is not resolved a
1580
1923
  // third time to race. (Found by the task 4.5 review gate.)
1581
- const parsed = gate.viaGrant
1582
- ? await loadParsedEml(gate.resolved, stat, await readFileVerified(gate.resolved))
1583
- : await loadParsedEml(gate.resolved, stat);
1924
+ // Both branches read through the bound opener (decided real path) and hand the bytes on, so
1925
+ // `lib/eml.ts` never re-resolves the pathname. See change: close-local-listener-and-egress-gaps.
1926
+ const parsed = await loadParsedEml(
1927
+ gate.resolved,
1928
+ stat,
1929
+ gate.viaGrant
1930
+ ? await readFileVerified(gate.real, { decidedReal: gate.real })
1931
+ : await readFileStateChecked(gate.real, undefined, { decidedReal: gate.real }),
1932
+ );
1584
1933
  const data = await toParseResult(parsed, { allowRemote: request.query.allowRemote === "1" });
1585
1934
  return { success: true, data } satisfies ApiResponse;
1586
1935
  } catch (err) {
1936
+ if (err instanceof DashboardStateRefused || (err instanceof VerifiedReadRefused && err.reason === "state-file")) {
1937
+ reply.code(403);
1938
+ return { success: false, error: "path outside working directory" } satisfies ApiResponse;
1939
+ }
1587
1940
  const msg = err instanceof Error ? err.message : "failed to parse EML";
1588
1941
  reply.code(400);
1589
1942
  return { success: false, error: msg } satisfies ApiResponse;
@@ -1602,12 +1955,11 @@ export function registerFileRoutes(
1602
1955
  "/api/file/eml-attachment",
1603
1956
  { preHandler: networkGuard },
1604
1957
  async (request, reply) => {
1605
- const gate = await gateFilePath(request.query.cwd, request.query.path, sessionManager, {
1958
+ const gate = await gateFilePath(request.query.cwd, request.query.path, routeAdmission, {
1606
1959
  disclosure: canDiscloseAccessPosture(request),
1607
1960
  });
1608
1961
  if ("code" in gate) {
1609
- reply.code(gate.code);
1610
- return denialBody(gate);
1962
+ return sendGateFailure(reply, gate);
1611
1963
  }
1612
1964
  if (path.extname(request.query.path ?? "").toLowerCase() !== ".eml") {
1613
1965
  reply.code(400);
@@ -1633,10 +1985,18 @@ export function registerFileRoutes(
1633
1985
  let parsed;
1634
1986
  try {
1635
1987
  // Same grant-only rule as the EML parse site above (task 4.5 review).
1636
- parsed = gate.viaGrant
1637
- ? await loadParsedEml(gate.resolved, stat, await readFileVerified(gate.resolved))
1638
- : await loadParsedEml(gate.resolved, stat);
1988
+ parsed = await loadParsedEml(
1989
+ gate.resolved,
1990
+ stat,
1991
+ gate.viaGrant
1992
+ ? await readFileVerified(gate.real, { decidedReal: gate.real })
1993
+ : await readFileStateChecked(gate.real, undefined, { decidedReal: gate.real }),
1994
+ );
1639
1995
  } catch (err) {
1996
+ if (err instanceof DashboardStateRefused || (err instanceof VerifiedReadRefused && err.reason === "state-file")) {
1997
+ reply.code(403);
1998
+ return { success: false, error: "path outside working directory" } satisfies ApiResponse;
1999
+ }
1640
2000
  const msg = err instanceof Error ? err.message : "failed to parse EML";
1641
2001
  reply.code(400);
1642
2002
  return { success: false, error: msg } satisfies ApiResponse;
@@ -1646,16 +2006,10 @@ export function registerFileRoutes(
1646
2006
  reply.code(404);
1647
2007
  return { success: false, error: "attachment index out of range" } satisfies ApiResponse;
1648
2008
  }
1649
- // Header-safe filename: strip CR/LF/quote (anti-injection), fold non-ASCII
1650
- // to `_` for the legacy `filename=`, and carry the exact name via RFC 5987
1651
- // `filename*` so UTF-8 names (e.g. Hungarian) survive.
1652
- const rawName = (att.filename || `attachment-${index}`).replace(/["\r\n]/g, "");
1653
- const asciiName = rawName.replace(/[^\x20-\x7e]/g, "_");
2009
+ // Header-safe attachment name (shared helper; see change: add-file-download).
2010
+ const rawName = att.filename || `attachment-${index}`;
1654
2011
  reply.header("Content-Type", att.contentType || "application/octet-stream");
1655
- reply.header(
1656
- "Content-Disposition",
1657
- `attachment; filename="${asciiName}"; filename*=UTF-8''${encodeURIComponent(rawName)}`,
1658
- );
2012
+ reply.header("Content-Disposition", contentDispositionAttachment(rawName));
1659
2013
  reply.header("X-Content-Type-Options", "nosniff");
1660
2014
  reply.header("Cache-Control", "private, max-age=60");
1661
2015
  reply.header("Content-Length", String(att.content.length));
@@ -1700,24 +2054,31 @@ export function registerFileRoutes(
1700
2054
  }
1701
2055
 
1702
2056
  /**
1703
- * Ask about an unknown-cwd denial and re-run the known-cwd guard on an allow
1704
- * verdict (add-access-grant-dialog, task 6.2). Resolves `false` for anything but
1705
- * an explicit allow that the re-run confirms. The re-run is the shared
1706
- * `resolveCwdVerdict` (canonical compare against sessions ∪ pins, allow-once
1707
- * real-path re-resolution) — the same rules plugin holds use.
1708
- * See change: harden-plugin-cwd-admission.
2057
+ * Ask about an unknown-cwd denial and re-run the shared guard on an allow verdict
2058
+ * (add-access-grant-dialog, task 6.2). Returns the post-verdict decision: `admit` only for an
2059
+ * explicit allow that the re-run confirms, `indeterminate` when the re-run cannot decide, else
2060
+ * `refuse`. The re-run is the shared `resolveCwdVerdict` (canonical compare against the known
2061
+ * set, allow-once real-path re-resolution, `rerunAlways` through `admitRouteCwd`) — the same
2062
+ * rules plugin holds use. See change: harden-plugin-cwd-admission, core-file-cwd-admission (D5).
1709
2063
  */
1710
- async function unknownCwdVerdictAdmits(
2064
+ async function unknownCwdVerdict(
1711
2065
  cwd: string,
1712
2066
  target: HoldTarget,
1713
- known: () => string[],
1714
- ): Promise<boolean> {
2067
+ routeAdmission: RouteAdmissionDeps,
2068
+ ): Promise<CwdHoldDecision> {
1715
2069
  // The subject is the REAL path, so an allow-once can later be compared strictly against
1716
2070
  // what the path means at release time. A cwd that does not resolve is never asked about:
1717
2071
  // the post-verdict re-run refuses it whatever the operator answers (and a pin for a
1718
2072
  // directory that is not there is meaningless) — the same rule the plugin seam applies.
1719
2073
  const real = await realpathAsync(path.resolve(cwd));
1720
- if (real.kind !== "ok") return false;
2074
+ if (real.kind !== "ok") return { kind: "refuse" };
1721
2075
  const resolution = await holdDenial({ plane: "cwd", rawSubject: real.path, origin: "file-routes:exists" }, target);
1722
- return (await resolveCwdVerdict(cwd, resolution, { known })).kind === "admit";
2076
+ return resolveCwdVerdict(cwd, resolution, {
2077
+ known: routeAdmission.knownCwds ?? (() => []),
2078
+ rerunAlways: async (canon) => {
2079
+ const admission = await admitRouteCwd(canon, routeAdmission);
2080
+ if (admission.kind === "admit") releaseAdmission(admission.token);
2081
+ return admission.kind;
2082
+ },
2083
+ });
1723
2084
  }