@blackbelt-technology/pi-agent-dashboard 0.11.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 (337) hide show
  1. package/AGENTS.md +2 -0
  2. package/README.md +17 -12
  3. package/docs/architecture.md +973 -224
  4. package/package.json +29 -18
  5. package/packages/extension/package.json +16 -9
  6. package/packages/extension/src/bridge-context.ts +6 -0
  7. package/packages/extension/src/bridge-handlers/dispatch.ts +54 -69
  8. package/packages/extension/src/bridge-handlers/forwarders.ts +19 -42
  9. package/packages/extension/src/bridge-handlers/instance.ts +21 -12
  10. package/packages/extension/src/bridge-handlers/lifecycle.ts +84 -40
  11. package/packages/extension/src/bridge-shutdown.ts +44 -0
  12. package/packages/extension/src/bridge.ts +272 -260
  13. package/packages/extension/src/command-handler.ts +26 -31
  14. package/packages/extension/src/connection.ts +123 -31
  15. package/packages/extension/src/credential-guard.ts +300 -0
  16. package/packages/extension/src/custom-entry-forward.ts +27 -18
  17. package/packages/extension/src/default-model-apply.ts +83 -0
  18. package/packages/extension/src/flow-event-wiring.ts +19 -95
  19. package/packages/extension/src/followup-drain.ts +19 -5
  20. package/packages/extension/src/path-gate/decide.ts +68 -5
  21. package/packages/extension/src/path-gate/handler.ts +16 -8
  22. package/packages/extension/src/path-gate/index.ts +2 -2
  23. package/packages/extension/src/path-gate/roots.ts +15 -3
  24. package/packages/extension/src/path-gate/suppression.ts +3 -0
  25. package/packages/extension/src/pi-env.d.ts +8 -1
  26. package/packages/extension/src/pi-retry-settings.ts +11 -2
  27. package/packages/extension/src/plugin-event-forward-registry.ts +90 -14
  28. package/packages/extension/src/preview-path-link.ts +151 -0
  29. package/packages/extension/src/project-init/scaffold.ts +98 -35
  30. package/packages/extension/src/project-trust.ts +24 -15
  31. package/packages/extension/src/provider-model-cache.ts +118 -0
  32. package/packages/extension/src/provider-register.ts +428 -28
  33. package/packages/extension/src/retry-tracker.ts +90 -7
  34. package/packages/extension/src/role-manager.ts +4 -2
  35. package/packages/extension/src/role-model-tools.ts +21 -4
  36. package/packages/extension/src/server-auto-start.ts +68 -2
  37. package/packages/extension/src/server-launcher.ts +26 -8
  38. package/packages/extension/src/session-sync.ts +11 -12
  39. package/packages/extension/src/spawn-new-session.ts +22 -0
  40. package/packages/extension/src/steer-buffer.ts +164 -0
  41. package/packages/extension/src/stream-forward-buffer.ts +64 -15
  42. package/packages/extension/src/sudo-askpass/config-reader.ts +32 -0
  43. package/packages/extension/src/sudo-askpass/controller.ts +405 -0
  44. package/packages/extension/src/sudo-askpass/helper-script.ts +69 -0
  45. package/packages/extension/src/sudo-askpass/in-flight.ts +79 -0
  46. package/packages/extension/src/sudo-askpass/index.ts +11 -0
  47. package/packages/extension/src/sudo-askpass/install.ts +143 -0
  48. package/packages/extension/src/sudo-askpass/password-cache.ts +118 -0
  49. package/packages/extension/src/sudo-askpass/prompt-text.ts +55 -0
  50. package/packages/extension/src/sudo-askpass/protocol.ts +18 -0
  51. package/packages/extension/src/sudo-askpass/sudo-mask-registry.ts +52 -0
  52. package/packages/extension/src/terminal-reload.ts +19 -5
  53. package/packages/extension/src/tool-update-filter-registry.ts +210 -0
  54. package/packages/extension/src/vault-redaction.ts +4 -3
  55. package/packages/server/package.json +17 -14
  56. package/packages/server/src/access/access-denials.ts +8 -0
  57. package/packages/server/src/access/access-grants.ts +244 -58
  58. package/packages/server/src/access/access-plane.ts +7 -0
  59. package/packages/server/src/access/containment-gate.ts +66 -21
  60. package/packages/server/src/access/denial-hold.ts +3 -0
  61. package/packages/server/src/access/grant-coordinator.ts +17 -1
  62. package/packages/server/src/access/named-grant.ts +3 -0
  63. package/packages/server/src/access/pending-grant-registry.ts +32 -5
  64. package/packages/server/src/access/pi-trust-mirror-service.ts +7 -1
  65. package/packages/server/src/access/planes.ts +1 -0
  66. package/packages/server/src/access/verified-read.ts +24 -7
  67. package/packages/server/src/acp-bridge/acp-session-adapter.ts +10 -2
  68. package/packages/server/src/acp-bridge/server-requests.ts +10 -4
  69. package/packages/server/src/agent-events/agent-event-hub.ts +1 -1
  70. package/packages/server/src/auth/audit-log.ts +28 -0
  71. package/packages/server/src/auth/auth-plugin.ts +188 -15
  72. package/packages/server/src/auth/auth.ts +80 -0
  73. package/packages/server/src/auth/bridge-ticket-eligibility.ts +53 -10
  74. package/packages/server/src/auth/cors-origin.ts +14 -1
  75. package/packages/server/src/auth/credential-envelope.ts +233 -0
  76. package/packages/server/src/auth/credential-key-worker.d.mts +16 -0
  77. package/packages/server/src/auth/credential-key-worker.mjs +108 -0
  78. package/packages/server/src/auth/credential-key.ts +479 -0
  79. package/packages/server/src/auth/credential-migration.ts +162 -0
  80. package/packages/server/src/auth/csp-report-paths.ts +0 -5
  81. package/packages/server/src/auth/csp.ts +74 -36
  82. package/packages/server/src/auth/device-proof.ts +202 -0
  83. package/packages/server/src/auth/duplicate-cookie-gate.ts +271 -0
  84. package/packages/server/src/auth/host-admission.ts +7 -0
  85. package/packages/server/src/auth/host-gate.ts +13 -2
  86. package/packages/server/src/auth/localhost-guard.ts +50 -23
  87. package/packages/server/src/auth/locked-json-file.ts +68 -6
  88. package/packages/server/src/auth/models-json-store.ts +269 -0
  89. package/packages/server/src/auth/mutation-origin-gate.ts +5 -2
  90. package/packages/server/src/auth/node-guard.ts +36 -49
  91. package/packages/server/src/auth/plugin-credential-store.ts +81 -10
  92. package/packages/server/src/auth/provider-auth-storage.ts +208 -11
  93. package/packages/server/src/auth/provider-block-checks.ts +321 -0
  94. package/packages/server/src/auth/provider-host-detect.ts +151 -0
  95. package/packages/server/src/auth/provider-key-file.ts +71 -0
  96. package/packages/server/src/auth/provider-readiness.ts +91 -0
  97. package/packages/server/src/auth/route-tier-gate.ts +3 -2
  98. package/packages/server/src/auth/vertex-key-check.ts +140 -0
  99. package/packages/server/src/auth/ws-ticket.ts +1 -1
  100. package/packages/server/src/browse.ts +73 -20
  101. package/packages/server/src/browser-handlers/acp-guard.ts +1 -4
  102. package/packages/server/src/browser-handlers/directory-handler.ts +11 -24
  103. package/packages/server/src/browser-handlers/session-action-handler.ts +158 -62
  104. package/packages/server/src/browser-handlers/spawn-choice.ts +138 -1
  105. package/packages/server/src/browser-handlers/subscription-handler.ts +46 -1
  106. package/packages/server/src/build-plugin-send-prompt.ts +18 -0
  107. package/packages/server/src/cli/credentials-command.ts +555 -0
  108. package/packages/server/src/cli.ts +21 -16
  109. package/packages/server/src/config-api.ts +34 -38
  110. package/packages/server/src/config-snapshot.ts +149 -0
  111. package/packages/server/src/directory-service.ts +33 -14
  112. package/packages/server/src/embed-lifecycle/idle-reaper.ts +13 -3
  113. package/packages/server/src/event-wiring.ts +181 -101
  114. package/packages/server/src/git-worktree/ensure-worktree.ts +185 -0
  115. package/packages/server/src/git-worktree/git-operations.ts +1 -1
  116. package/packages/server/src/git-worktree/repo-lock.ts +42 -0
  117. package/packages/server/src/git-worktree/start-worktree-init.ts +151 -0
  118. package/packages/server/src/git-worktree/worktree-init.ts +5 -1
  119. package/packages/server/src/identity/http-road-classification.ts +5 -1
  120. package/packages/server/src/identity/identity-floor.ts +5 -2
  121. package/packages/server/src/identity/ws-message-scope.ts +10 -3
  122. package/packages/server/src/identity/ws-road-classification.ts +2 -1
  123. package/packages/server/src/lib/browse-roots.ts +13 -2
  124. package/packages/server/src/lib/content-disposition.ts +20 -0
  125. package/packages/server/src/lib/dashboard-state-guard.ts +304 -21
  126. package/packages/server/src/lib/eml.ts +2 -2
  127. package/packages/server/src/lib/frame-policy-probe.ts +308 -0
  128. package/packages/server/src/lib/frame-policy-test-seam.ts +99 -0
  129. package/packages/server/src/lib/frame-policy-verdict.ts +125 -0
  130. package/packages/server/src/lib/grep.ts +4 -1
  131. package/packages/server/src/lib/index-html.ts +2 -2
  132. package/packages/server/src/lib/mention-fuzzy-index.ts +263 -0
  133. package/packages/server/src/lib/office-preview.ts +47 -10
  134. package/packages/server/src/lib/path-containment.ts +45 -12
  135. package/packages/server/src/lib/resolve-file-mention.ts +230 -38
  136. package/packages/server/src/lib/resolve-mentions-batch.ts +143 -0
  137. package/packages/server/src/lib/writable-handler-target.ts +4 -0
  138. package/packages/server/src/lib/writable-md-target.ts +22 -0
  139. package/packages/server/src/lifecycle/boot-parent-liveness.ts +10 -25
  140. package/packages/server/src/lifecycle/credential-exit-barrier.ts +207 -0
  141. package/packages/server/src/lifecycle/exit-signal.ts +43 -0
  142. package/packages/server/src/live-server/capability-redact.ts +21 -5
  143. package/packages/server/src/live-server/live-capability.ts +416 -52
  144. package/packages/server/src/live-server/live-csp-report.ts +1 -1
  145. package/packages/server/src/live-server/live-csp.ts +64 -16
  146. package/packages/server/src/live-server/live-log.ts +5 -1
  147. package/packages/server/src/live-server/live-server-manager.ts +11 -0
  148. package/packages/server/src/live-server/live-server-proxy.ts +268 -52
  149. package/packages/server/src/live-server/live-static.ts +4 -1
  150. package/packages/server/src/live-server/preview-dispatch.ts +286 -0
  151. package/packages/server/src/live-server/preview-observe.ts +53 -0
  152. package/packages/server/src/live-server/preview-origin.ts +182 -0
  153. package/packages/server/src/live-server/preview-path-bridge.ts +70 -0
  154. package/packages/server/src/live-server/preview-path-store.ts +420 -0
  155. package/packages/server/src/live-server/preview-path.ts +40 -0
  156. package/packages/server/src/live-server/preview-pool.ts +385 -0
  157. package/packages/server/src/live-server/preview-preflight.ts +41 -0
  158. package/packages/server/src/live-server/preview-reserve.ts +44 -0
  159. package/packages/server/src/live-server/preview-tier.ts +217 -0
  160. package/packages/server/src/live-server/preview-viewers.ts +54 -0
  161. package/packages/server/src/live-server/preview-ws-registry.ts +43 -0
  162. package/packages/server/src/model-proxy/custom-provider-discovery.ts +4 -2
  163. package/packages/server/src/model-proxy/internal-auth-storage.ts +5 -1
  164. package/packages/server/src/model-proxy/internal-registry.ts +283 -21
  165. package/packages/server/src/model-proxy/models-block-apply.ts +291 -0
  166. package/packages/server/src/model-proxy/pi-models-validator.ts +164 -0
  167. package/packages/server/src/model-proxy/registry-singleton.ts +44 -9
  168. package/packages/server/src/model-proxy/server-model-runtime.ts +17 -0
  169. package/packages/server/src/openspec/readiness.ts +1 -1
  170. package/packages/server/src/package/provider-probe.ts +194 -5
  171. package/packages/server/src/pairing/browser-gateway.ts +140 -42
  172. package/packages/server/src/pairing/device-key-intake.ts +120 -0
  173. package/packages/server/src/pairing/paired-devices.ts +370 -8
  174. package/packages/server/src/pairing/pairing.ts +69 -7
  175. package/packages/server/src/pairing/{subagent-resync-routing.ts → resync-requester-registry.ts} +6 -10
  176. package/packages/server/src/pairing/ws-tier-gate.ts +74 -0
  177. package/packages/server/src/pending/pending-attach-registry.ts +15 -0
  178. package/packages/server/src/pending/pending-initial-prompt-registry.ts +15 -0
  179. package/packages/server/src/persistence/memory-event-store.ts +251 -296
  180. package/packages/server/src/persistence/preferences-store.ts +52 -2
  181. package/packages/server/src/pi/bridge-contention.ts +84 -2
  182. package/packages/server/src/pi/host-project-trust.ts +15 -9
  183. package/packages/server/src/pi/pi-gateway.ts +208 -21
  184. package/packages/server/src/pi/provisional-registration.ts +4 -1
  185. package/packages/server/src/pi/resource-toggle-trust.ts +17 -6
  186. package/packages/server/src/pi-agent-settings.ts +95 -301
  187. package/packages/server/src/pi-default-remirror.ts +89 -0
  188. package/packages/server/src/plugin-append-event.ts +35 -0
  189. package/packages/server/src/plugin-entry-stats.ts +61 -0
  190. package/packages/server/src/plugin-local-request.ts +207 -0
  191. package/packages/server/src/plugin-ownership.ts +111 -0
  192. package/packages/server/src/plugin-policy-registry.ts +297 -0
  193. package/packages/server/src/plugin-request-lane.ts +92 -16
  194. package/packages/server/src/preferences-relay.ts +20 -0
  195. package/packages/server/src/project-seed.ts +347 -0
  196. package/packages/server/src/push/push-transports/webhook-url.ts +8 -5
  197. package/packages/server/src/questions/question-store.ts +3 -2
  198. package/packages/server/src/routes/access-routes.ts +23 -6
  199. package/packages/server/src/routes/acme-routes.ts +14 -4
  200. package/packages/server/src/routes/agent-event-stream-routes.ts +1 -1
  201. package/packages/server/src/routes/file-routes.ts +327 -86
  202. package/packages/server/src/routes/file-write-binary-routes.ts +20 -4
  203. package/packages/server/src/routes/frame-policy-routes.ts +215 -0
  204. package/packages/server/src/routes/git-routes.ts +29 -78
  205. package/packages/server/src/routes/grep-routes.ts +26 -0
  206. package/packages/server/src/routes/live-server-routes.ts +198 -4
  207. package/packages/server/src/routes/models-introspection-routes.ts +1 -1
  208. package/packages/server/src/routes/openspec-routes.ts +17 -3
  209. package/packages/server/src/routes/pairing-routes.ts +200 -11
  210. package/packages/server/src/routes/pi-settings-routes.ts +2 -0
  211. package/packages/server/src/routes/preferences-auto-name-routes.ts +5 -2
  212. package/packages/server/src/routes/preferences-claude-compat-routes.ts +49 -0
  213. package/packages/server/src/routes/provider-auth-routes.ts +167 -9
  214. package/packages/server/src/routes/provider-override-routes.ts +158 -0
  215. package/packages/server/src/routes/provider-routes.ts +348 -86
  216. package/packages/server/src/routes/session-routes.ts +25 -22
  217. package/packages/server/src/routes/system-routes.ts +87 -39
  218. package/packages/server/src/rpc-keeper/keeper-manager.ts +196 -25
  219. package/packages/server/src/rpc-keeper/keeper.cjs +37 -23
  220. package/packages/server/src/runtime-overlay/extension-reload.ts +16 -10
  221. package/packages/server/src/runtime-overlay/runtime-stager.ts +4 -2
  222. package/packages/server/src/server.ts +512 -175
  223. package/packages/server/src/services/cli-service.ts +59 -10
  224. package/packages/server/src/services/secrets-resolver.ts +46 -30
  225. package/packages/server/src/session/custom-event-group-annotation.ts +3 -3
  226. package/packages/server/src/session/custom-event-group-resolver.ts +10 -5
  227. package/packages/server/src/session/death-reason.ts +11 -7
  228. package/packages/server/src/session/event-status-extraction.ts +5 -1
  229. package/packages/server/src/session/memory-session-manager.ts +24 -2
  230. package/packages/server/src/session/open-tool-calls.ts +81 -47
  231. package/packages/server/src/session/pid-target.ts +127 -0
  232. package/packages/server/src/session/replay-compaction.ts +18 -5
  233. package/packages/server/src/session/seed-discovered-history.ts +85 -0
  234. package/packages/server/src/session/server-pid-context.ts +14 -0
  235. package/packages/server/src/session/session-api.ts +78 -29
  236. package/packages/server/src/session/session-archive.ts +7 -0
  237. package/packages/server/src/session/session-bootstrap.ts +9 -54
  238. package/packages/server/src/session/session-load-worker-pool.ts +11 -1
  239. package/packages/server/src/session/session-load-worker.ts +22 -3
  240. package/packages/server/src/spawn-process/abort-spawned-run.ts +28 -9
  241. package/packages/server/src/spawn-process/acp-spawn.ts +8 -2
  242. package/packages/server/src/spawn-process/headless-pid-registry.ts +383 -72
  243. package/packages/server/src/spawn-process/link-register.ts +42 -0
  244. package/packages/server/src/spawn-process/plugin-spawn-choice.ts +48 -0
  245. package/packages/server/src/spawn-process/plugin-spawn-worktree.ts +290 -0
  246. package/packages/server/src/spawn-process/process-classifier.ts +8 -3
  247. package/packages/server/src/spawn-process/process-manager.ts +61 -6
  248. package/packages/server/src/spawn-process/restored-identity.ts +112 -0
  249. package/packages/server/src/spawn-process/session-terminator.ts +179 -18
  250. package/packages/server/src/spawn-process/spawn-env-contributors.ts +2 -1
  251. package/packages/server/src/spawn-process/spawn-failure-log.ts +9 -0
  252. package/packages/server/src/spawn-process/spawn-register-watchdog.ts +44 -19
  253. package/packages/server/src/sudo-credential/relay.ts +337 -0
  254. package/packages/server/src/terminal/terminal-gateway.ts +10 -0
  255. package/packages/server/src/tls/sources/acme/credentials.ts +3 -2
  256. package/packages/server/src/tls/sources/acme/runtime.ts +2 -1
  257. package/packages/server/src/vault/vault-delivery-hub.ts +17 -1
  258. package/packages/server/src/vault/vault-routes.ts +9 -2
  259. package/packages/server/src/vault/vault-store.ts +87 -24
  260. package/packages/server/vendor/xlsx/LICENSE +201 -0
  261. package/packages/server/vendor/xlsx/PROVENANCE.json +13 -0
  262. package/packages/server/vendor/xlsx/xlsx.d.mts +1065 -0
  263. package/packages/server/vendor/xlsx/xlsx.mjs +28228 -0
  264. package/packages/shared/package.json +4 -2
  265. package/packages/shared/src/agent-credential-files.ts +32 -0
  266. package/packages/shared/src/browser-protocol.ts +137 -57
  267. package/packages/shared/src/canvas-detect.ts +1 -1
  268. package/packages/shared/src/canvas-types.ts +2 -2
  269. package/packages/shared/src/config.ts +73 -136
  270. package/packages/shared/src/containment-guard.ts +14 -4
  271. package/packages/shared/src/credential-encryption.ts +87 -0
  272. package/packages/shared/src/custom-event-groups.ts +2 -0
  273. package/packages/shared/src/dashboard-plugin/claude-compat.ts +159 -0
  274. package/packages/shared/src/dashboard-plugin/host-api.ts +1 -1
  275. package/packages/shared/src/dashboard-plugin/manifest-types.ts +46 -0
  276. package/packages/shared/src/dashboard-plugin/plugin-status.ts +4 -3
  277. package/packages/shared/src/dashboard-plugin/replay-entry-types.ts +46 -0
  278. package/packages/shared/src/dashboard-plugin/slot-props.ts +2 -0
  279. package/packages/shared/src/dashboard-plugin/slot-types.ts +1 -1
  280. package/packages/shared/src/dashboard-plugin/ui-primitives.ts +11 -3
  281. package/packages/shared/src/device-key-proof.ts +309 -0
  282. package/packages/shared/src/event-forward-declaration.ts +85 -12
  283. package/packages/shared/src/forbidden-subjects.ts +126 -14
  284. package/packages/shared/src/heap-limits.ts +0 -30
  285. package/packages/shared/src/host-admission.ts +2 -1
  286. package/packages/shared/src/index.ts +7 -6
  287. package/packages/shared/src/live-server.ts +20 -0
  288. package/packages/shared/src/mcp/verb-tiers.generated.ts +1 -3
  289. package/packages/shared/src/models-json-reader.ts +41 -0
  290. package/packages/shared/src/network-denial-signal.ts +15 -0
  291. package/packages/shared/src/node-version.ts +63 -60
  292. package/packages/shared/src/pairing-knock-client.ts +92 -8
  293. package/packages/shared/src/pi-agent-settings-lock.ts +311 -0
  294. package/packages/shared/src/pi-path-compare.ts +31 -0
  295. package/packages/shared/src/pi-settings-schema.ts +52 -9
  296. package/packages/shared/src/pi-trust-mirror-snapshot.ts +16 -4
  297. package/packages/shared/src/pi-trust-mirror-types.ts +2 -0
  298. package/packages/shared/src/pi-trust-mirror.ts +18 -8
  299. package/packages/shared/src/pi-trust-resource-digest.ts +18 -12
  300. package/packages/shared/src/pid-namespace.ts +86 -0
  301. package/packages/shared/src/platform/native-ts-register.mjs +1 -1
  302. package/packages/shared/src/platform/process.ts +404 -1
  303. package/packages/shared/src/platform/resolve-pi-shell.ts +38 -9
  304. package/packages/shared/src/platform/spawn-runtime.ts +193 -7
  305. package/packages/shared/src/preview-egress.ts +56 -2
  306. package/packages/shared/src/preview-origins.ts +398 -0
  307. package/packages/shared/src/prompt-answer.ts +9 -5
  308. package/packages/shared/src/protocol.ts +147 -85
  309. package/packages/shared/src/provider-env-catalog.ts +413 -0
  310. package/packages/shared/src/provider-overrides.ts +112 -0
  311. package/packages/shared/src/question-types.ts +6 -0
  312. package/packages/shared/src/recommended-extensions.ts +79 -26
  313. package/packages/shared/src/renderer-by-ext.ts +5 -2
  314. package/packages/shared/src/rest-api.ts +93 -3
  315. package/packages/shared/src/role-schema.ts +24 -0
  316. package/packages/shared/src/route-tiers.ts +94 -3
  317. package/packages/shared/src/runtime-overlay/compat.ts +70 -6
  318. package/packages/shared/src/secret-patterns.ts +49 -0
  319. package/packages/shared/src/source-matching.ts +2 -2
  320. package/packages/shared/src/state-replay.ts +40 -24
  321. package/packages/shared/src/sudo-credential.ts +71 -0
  322. package/packages/shared/src/tool-path-resolve.ts +16 -1
  323. package/packages/shared/src/tool-registry/strategies.ts +1 -1
  324. package/packages/shared/src/tool-workdir.ts +56 -0
  325. package/packages/shared/src/trusted-types-mode.ts +72 -0
  326. package/packages/shared/src/types.ts +68 -109
  327. package/packages/shared/src/vertex-regions.ts +81 -0
  328. package/packages/shared/src/ws-message-tiers.ts +10 -3
  329. package/packages/extension/src/subagent-fanout-admission.ts +0 -234
  330. package/packages/extension/src/subagent-forward-sites.ts +0 -69
  331. package/packages/extension/src/subagent-frame-buffer.ts +0 -245
  332. package/packages/extension/src/subagent-frame-strip.ts +0 -109
  333. package/packages/extension/src/subagent-saturation.ts +0 -196
  334. package/packages/extension/src/subagent-tick-throttle.ts +0 -252
  335. package/packages/shared/src/anthropic-messages-source.ts +0 -8
  336. package/packages/shared/src/dashboard-plugin/anthropic-peer-names.ts +0 -9
  337. package/packages/shared/src/dashboard-plugin/subagent-types.ts +0 -219
@@ -38,12 +38,23 @@
38
38
  * each other's grants. The dashboard is one server per machine and the override
39
39
  * exists for tests, so no lock is taken; see design.md D-format-1.
40
40
  *
41
- * See change: add-access-grants-and-review.
41
+ * **Rows this build does not admit are preserved** (harden-agent-tool-guards D7). A persisted row
42
+ * that is now forbidden (a credential dir, or a directory containing one), unrecognised or of
43
+ * another scope is kept as a raw side list and written back verbatim after the admitted grants by
44
+ * BOTH writers (`recordGrant`, `revokeGrant`), so reverting the build restores it. The cap counts
45
+ * admitted grants only. Whole-file states: invalid JSON / no `grants` / `version !== 1` is moved aside
46
+ * to `<file>.corrupt-<UTC ts>` by `recordGrant` before a fresh store is written (`revokeGrant` writes
47
+ * nothing); a file over `GRANT_STORE_MAX_BYTES` is neither loaded nor rewritten.
48
+ *
49
+ * See change: add-access-grants-and-review; harden-agent-tool-guards.
42
50
  */
43
51
  import * as fs from "node:fs";
44
52
  import * as path from "node:path";
45
53
  import { getDashboardConfigDir } from "@blackbelt-technology/pi-dashboard-shared/dashboard-paths.js";
46
- import { isUngrantableSubject } from "./forbidden-subjects.js";
54
+ import {
55
+ forbiddenGrantSubjects,
56
+ isUngrantableSubject,
57
+ } from "./forbidden-subjects.js";
47
58
 
48
59
  /**
49
60
  * Notified after a PERSISTED grant is written or revoked. Feeds the pi-trust
@@ -84,6 +95,18 @@ export type GrantScope = "session" | "project";
84
95
  /** Which write path produced a grant (absent = the Access page's grant route). */
85
96
  type GrantVia = "prompt" | "agent-prompt" | "provision";
86
97
 
98
+ /**
99
+ * Access mode of a grant. A write grant admits reads AND allowlisted text-document
100
+ * writes under its subtree; a read grant (the default, stored with NO `mode` key)
101
+ * never admits a write. See change: fix-file-link-editor-routing (D2).
102
+ */
103
+ type GrantMode = "read" | "write";
104
+
105
+ /** The mode of an entry: only the exact string `"write"` is a write grant (fail closed). */
106
+ function modeOf(g: { mode?: unknown }): GrantMode {
107
+ return g.mode === "write" ? "write" : "read";
108
+ }
109
+
87
110
  /** One grant. Session-scoped grants carry the SAME four fields (D17) — not a bare Set. */
88
111
  export interface AccessGrant {
89
112
  /** Directory, realpath'd at grant time (D2). */
@@ -106,11 +129,25 @@ export interface AccessGrant {
106
129
  * page's grant route. Optional and additive: older builds spread it through.
107
130
  */
108
131
  via?: GrantVia;
132
+ /**
133
+ * `"write"` when the grant also admits allowlisted text-document WRITES under
134
+ * its subtree. Absent = read. Optional and additive on a `version: 1` store
135
+ * (like `via`): an older build spreads it through and treats the entry as a
136
+ * read grant. Derived server-side from the denial's `action`, never from a
137
+ * client field. See change: fix-file-link-editor-routing (D2).
138
+ */
139
+ mode?: "write";
109
140
  }
110
141
 
111
142
  /** D10: fixed cap, per scope. */
112
143
  export const GRANT_CAP_PER_SCOPE = 200;
113
144
 
145
+ /**
146
+ * Ceiling on the store file (1 MiB). Bounds the raw rows kept for write-back: a larger file is
147
+ * neither loaded nor rewritten (the write fails, the file stays untouched, one log line).
148
+ */
149
+ export const GRANT_STORE_MAX_BYTES = 1_048_576;
150
+
114
151
  interface StoreFile {
115
152
  version: 1;
116
153
  grants: AccessGrant[];
@@ -133,12 +170,24 @@ export function accessGrantsStorePath(): string {
133
170
  */
134
171
  let cache: AccessGrant[] | null = null;
135
172
  const sessionGrants: AccessGrant[] = [];
173
+ /**
174
+ * Rows of the loaded file this build does NOT admit (now-forbidden, unrecognised, wrong scope),
175
+ * as parsed. Written back verbatim after the admitted grants. Empty unless `storeState` is "ok".
176
+ */
177
+ let rawRejected: unknown[] = [];
178
+ /** "invalid" = bad JSON / no `grants` / `version !== 1`; "oversize" = over `GRANT_STORE_MAX_BYTES`. */
179
+ let storeState: "ok" | "invalid" | "oversize" = "ok";
180
+ /** Now-forbidden subjects already logged in this process (one line per subject). */
181
+ const loggedForbidden = new Set<string>();
136
182
 
137
183
  /** Test seam: drop the cache and the in-memory session grants (simulates restart). */
138
184
  export function __resetAccessGrants(): void {
139
185
  cache = null;
140
186
  sessionGrants.length = 0;
141
187
  loadCount = 0;
188
+ rawRejected = [];
189
+ storeState = "ok";
190
+ loggedForbidden.clear();
142
191
  }
143
192
 
144
193
  /** Test seam: how many times the store file has been read in this process. */
@@ -151,13 +200,20 @@ function emptyStore(): AccessGrant[] {
151
200
  return [];
152
201
  }
153
202
 
154
- /** Absent, unreadable or malformed → empty (never throws). */
155
- function loadFromDisk(): AccessGrant[] {
156
- loadCount += 1;
157
-
158
- let raw: string;
203
+ /**
204
+ * The store file's text, or `null` when there is none to parse (missing, unreadable, oversize). Oversize
205
+ * sets `storeState`: such a file is not loaded (zero raw rows retained) and never rewritten.
206
+ */
207
+ function readStoreText(file: string): string | null {
208
+ // A failing stat (missing / unreadable file) is left to the read below to report.
209
+ try {
210
+ if (fs.statSync(file).size > GRANT_STORE_MAX_BYTES) return markOversizeText();
211
+ } catch {
212
+ /* reported by the read */
213
+ }
159
214
  try {
160
- raw = fs.readFileSync(accessGrantsStorePath(), "utf8");
215
+ const raw = fs.readFileSync(file, "utf8");
216
+ return Buffer.byteLength(raw, "utf8") > GRANT_STORE_MAX_BYTES ? markOversizeText() : raw;
161
217
  } catch (err) {
162
218
  // A MISSING store is the ordinary first-run case and stays quiet. Any other
163
219
  // read failure is reported: an unreadable store empties the granted set, and
@@ -165,62 +221,147 @@ function loadFromDisk(): AccessGrant[] {
165
221
  if ((err as NodeJS.ErrnoException)?.code !== "ENOENT") {
166
222
  console.warn(`[access-grants] store unreadable: ${(err as Error)?.message}`);
167
223
  }
168
- return emptyStore();
224
+ return null;
169
225
  }
226
+ }
170
227
 
228
+ /** Parse the store file; `null` marks it invalid (bad JSON, no `grants`, or a version this build refuses). */
229
+ function parseStore(raw: string): StoreFile | null {
171
230
  let parsed: StoreFile;
172
231
  try {
173
232
  parsed = JSON.parse(raw) as StoreFile;
174
233
  } catch {
175
234
  console.warn("[access-grants] store is not valid JSON — treating as empty");
176
- return emptyStore();
235
+ return null;
177
236
  }
178
-
179
- if (!parsed || typeof parsed !== "object" || !Array.isArray(parsed.grants)) return emptyStore();
180
-
237
+ if (!parsed || typeof parsed !== "object" || !Array.isArray(parsed.grants)) return null;
181
238
  // Refuse an unknown version outright. Reading a future file as if it were v1
182
239
  // would misinterpret it silently; refusing empties the granted set, which
183
240
  // fails CLOSED (narrower, never wider) and is logged.
184
241
  if (parsed.version !== 1) {
185
242
  console.warn(`[access-grants] unknown store version ${String(parsed.version)} — refusing to read`);
186
- return emptyStore();
243
+ return null;
187
244
  }
245
+ return parsed;
246
+ }
188
247
 
189
- const valid = parsed.grants
190
- .filter(
191
- (g): g is AccessGrant =>
192
- !!g &&
193
- typeof g === "object" &&
194
- typeof g.subject === "string" &&
195
- g.subject.length > 0 &&
196
- // Only `project` scope is persisted. Accepting a `session` entry here
197
- // would resurrect it across restarts (contradicting "session = until
198
- // server restart") and leave it unrevocable through the scoped API,
199
- // which only touches the in-memory list.
200
- g.scope === "project" &&
201
- // `NaN`/`Infinity` pass a bare `typeof` check and would poison the
202
- // eviction sort, so require a finite number.
203
- typeof g.grantedAt === "number" &&
204
- Number.isFinite(g.grantedAt),
205
- )
206
- .map((g) => ({ ...g, origin: typeof g.origin === "string" ? g.origin : "unknown" }))
207
- // The forbidden filter must hold for values ALREADY ON DISK, not only for
208
- // ones arriving through `recordGrant`. The forbidden list grew during
209
- // planning, so a store legitimately written by an older build can contain a
210
- // subject this build must refuse; a store copied between machines can too
211
- // (a different `$HOME` yields a different `sensitive` set). Without this, a
212
- // single on-disk `"/"` admits every path on the machine.
213
- .filter((g) => !isUngrantableSubject(g.subject));
248
+ /**
249
+ * Split the file's rows into admitted grants and `rawRejected`. The forbidden filter must hold for values
250
+ * ALREADY ON DISK, not only for ones arriving through `recordGrant`. The forbidden list grew, so a store
251
+ * legitimately written by an older build can contain a subject this build must refuse; a store copied
252
+ * between machines can too (a different `$HOME` yields a different `sensitive` set). Without this, a single
253
+ * on-disk `"/"` admits every path on the machine. The sets are built once per load, not once per row.
254
+ */
255
+ function admitRows(rows: unknown[]): AccessGrant[] {
256
+ const sets = forbiddenGrantSubjects();
257
+ const valid: AccessGrant[] = [];
258
+ for (const g of rows) {
259
+ if (!isGrantShaped(g)) {
260
+ rawRejected.push(g);
261
+ } else if (isUngrantableSubject(g.subject, undefined, sets)) {
262
+ rawRejected.push(g);
263
+ logNowForbidden(g.subject);
264
+ } else {
265
+ const { mode: rawMode, ...rest } = g;
266
+ // Normalise `mode` fail-closed: only the exact string "write" survives (a hostile or
267
+ // hand-edited value of any other shape is a read grant). No rewrite happens on load.
268
+ valid.push({
269
+ ...rest,
270
+ origin: typeof g.origin === "string" ? g.origin : "unknown",
271
+ ...(rawMode === "write" ? { mode: "write" as const } : {}),
272
+ });
273
+ }
274
+ }
275
+ return valid;
276
+ }
214
277
 
278
+ /** Absent, unreadable or malformed → empty (never throws). Sets `rawRejected` / `storeState`. */
279
+ function loadFromDisk(): AccessGrant[] {
280
+ loadCount += 1;
281
+ rawRejected = [];
282
+ storeState = "ok";
283
+ const raw = readStoreText(accessGrantsStorePath());
284
+ if (raw === null) return emptyStore();
285
+ const parsed = parseStore(raw);
286
+ if (!parsed) return markInvalid();
287
+ const valid = admitRows(parsed.grants as unknown[]);
215
288
  // The cap is a property of the STORE, not of the write path: a hand-edited or
216
289
  // hostile file with 100k grants would otherwise be admitted in full, growing
217
- // the hot path's Set per request and memory without bound.
290
+ // the hot path's Set per request and memory without bound. It counts ADMITTED
291
+ // grants only (preserved rows do not cause eviction).
218
292
  // Load does not spare provisioned grants: the bound wins, so a hostile file
219
293
  // full of `via: "provision"` entries still cannot grow the Set.
220
294
  enforceCap(valid, "project");
221
295
  return valid;
222
296
  }
223
297
 
298
+ function markOversizeText(): null {
299
+ storeState = "oversize";
300
+ console.warn(`[access-grants] store exceeds ${GRANT_STORE_MAX_BYTES} bytes — not loaded, not rewritten`);
301
+ return null;
302
+ }
303
+
304
+ function markInvalid(): AccessGrant[] {
305
+ storeState = "invalid";
306
+ return emptyStore();
307
+ }
308
+
309
+ /** One log line per now-forbidden subject per process; the subject path only. */
310
+ function logNowForbidden(subject: string): void {
311
+ if (loggedForbidden.has(subject)) return;
312
+ loggedForbidden.add(subject);
313
+ console.warn(`[access-grants] grant subject=${JSON.stringify(subject)} is forbidden by this build: not admitted, kept in the store`);
314
+ }
315
+
316
+ /**
317
+ * A row this build can admit structurally. Only `project` scope is persisted: accepting a `session`
318
+ * entry would resurrect it across restarts (contradicting "session = until server restart") and
319
+ * leave it unrevocable through the scoped API. `NaN`/`Infinity` pass a bare `typeof` check and
320
+ * would poison the eviction sort, so `grantedAt` must be finite.
321
+ */
322
+ function isGrantShaped(g: unknown): g is AccessGrant {
323
+ if (!g || typeof g !== "object") return false;
324
+ const r = g as Record<string, unknown>;
325
+ return (
326
+ typeof r.subject === "string" &&
327
+ r.subject.length > 0 &&
328
+ r.scope === "project" &&
329
+ typeof r.grantedAt === "number" &&
330
+ Number.isFinite(r.grantedAt)
331
+ );
332
+ }
333
+
334
+ /** Serialise the store: admitted grants, then every preserved raw row, unchanged. */
335
+ function serializeStore(admitted: AccessGrant[]): string {
336
+ return JSON.stringify({ version: 1, grants: [...admitted, ...rawRejected] }, null, 2);
337
+ }
338
+
339
+ /**
340
+ * Whole-file states before a WRITE. `oversize` → refuse (file untouched). `invalid` → move the old
341
+ * file aside to `<file>.corrupt-<UTC ts>` (never overwrite it); a failed move refuses the write.
342
+ */
343
+ function prepareStoreWrite(): { ok: true } | { ok: false; error: string } {
344
+ const file = accessGrantsStorePath();
345
+ if (storeState === "oversize") {
346
+ console.warn(`[access-grants] store exceeds ${GRANT_STORE_MAX_BYTES} bytes — write refused`);
347
+ return { ok: false, error: "store too large" };
348
+ }
349
+ if (storeState === "invalid") {
350
+ const ts = new Date().toISOString().replace(/[-:]/g, "").replace(/\.\d+Z$/, "Z");
351
+ const aside = `${file}.corrupt-${ts}`;
352
+ try {
353
+ fs.renameSync(file, aside);
354
+ } catch (err) {
355
+ console.warn(`[access-grants] could not move the unusable store aside: ${(err as Error)?.message}`);
356
+ return { ok: false, error: "store unusable" };
357
+ }
358
+ console.warn(`[access-grants] unusable store moved aside to ${aside}`);
359
+ storeState = "ok";
360
+ rawRejected = [];
361
+ }
362
+ return { ok: true };
363
+ }
364
+
224
365
  /** Cached persisted grants. Never reads on a warm cache — this is the containment path. */
225
366
  function persisted(): AccessGrant[] {
226
367
  if (cache === null) cache = loadFromDisk();
@@ -274,6 +415,17 @@ export function grantedSubjects(): string[] {
274
415
  return [...seen];
275
416
  }
276
417
 
418
+ /**
419
+ * Subjects of WRITE grants only — the write predicate's input. `grantedSubjects()`
420
+ * (the read predicate) includes these (write ⊃ read); a read grant never appears here.
421
+ */
422
+ export function grantedWriteSubjects(): string[] {
423
+ const seen = new Set<string>();
424
+ for (const g of persisted()) if (modeOf(g) === "write") seen.add(g.subject);
425
+ for (const g of sessionGrants) if (modeOf(g) === "write") seen.add(g.subject);
426
+ return [...seen];
427
+ }
428
+
277
429
  /**
278
430
  * Evict oldest-by-`grantedAt` down to `GRANT_CAP_PER_SCOPE` for `scope` only.
279
431
  * Ties on `grantedAt` break by insertion order (array order), so eviction is
@@ -346,6 +498,8 @@ export interface RecordGrantInput {
346
498
  /** Set when the subject came from the denial's offered-ancestor ladder. */
347
499
  widenedFrom?: string;
348
500
  via?: GrantVia;
501
+ /** `"write"` records a write grant; anything else a read grant (no `mode` stored). */
502
+ mode?: GrantMode;
349
503
  /**
350
504
  * `false` = refuse with `{ok:false, error:"capacity"}` at the cap instead of
351
505
  * evicting the oldest grant (change: add-access-provisioning). Default `true`.
@@ -355,7 +509,8 @@ export interface RecordGrantInput {
355
509
  }
356
510
 
357
511
  /**
358
- * Record a grant. Idempotent on an already-granted subject.
512
+ * Record a grant. Idempotent per `(subject, scope, mode)`: a write grant is a second
513
+ * entry beside a read grant for the same directory, revocable independently.
359
514
  *
360
515
  * On a **write failure** the subject is left UNGRANTED and the failure is
361
516
  * returned, never thrown (D11): the request that triggered the denial still 403s
@@ -363,10 +518,16 @@ export interface RecordGrantInput {
363
518
  * did not stick.
364
519
  */
365
520
  /** A grant with its optional provenance fields set only when present. */
366
- function buildGrant(base: AccessGrant, widenedFrom: string | undefined, via: GrantVia | undefined): AccessGrant {
521
+ function buildGrant(
522
+ base: AccessGrant,
523
+ widenedFrom: string | undefined,
524
+ via: GrantVia | undefined,
525
+ mode: GrantMode,
526
+ ): AccessGrant {
367
527
  const grant: AccessGrant = { ...base };
368
528
  if (widenedFrom) grant.widenedFrom = widenedFrom;
369
529
  if (via) grant.via = via;
530
+ if (mode === "write") grant.mode = "write";
370
531
  return grant;
371
532
  }
372
533
 
@@ -375,6 +536,7 @@ export function recordGrant(input: RecordGrantInput): RecordGrantResult {
375
536
  const origin = input.origin ?? "unknown";
376
537
  const subject = normalizeGrantSubject(input.subject);
377
538
  const grantedAt = input.now ?? Date.now();
539
+ const mode: GrantMode = input.mode === "write" ? "write" : "read";
378
540
 
379
541
  // Defence in depth (design D15): the forbidden filter must run on the value
380
542
  // that is actually STORED, never on the caller's pre-normalization input.
@@ -394,9 +556,9 @@ export function recordGrant(input: RecordGrantInput): RecordGrantResult {
394
556
  : undefined;
395
557
 
396
558
  if (scope === "session") {
397
- const existing = sessionGrants.find((g) => g.subject === subject);
559
+ const existing = sessionGrants.find((g) => g.subject === subject && modeOf(g) === mode);
398
560
  if (existing) return { ok: true, grant: existing };
399
- const grant = buildGrant({ subject, scope, grantedAt, origin }, widen, input.via);
561
+ const grant = buildGrant({ subject, scope, grantedAt, origin }, widen, input.via, mode);
400
562
  sessionGrants.push(grant);
401
563
  if (!enforceCap(sessionGrants, "session", { protect: grant, evict: input.evict, spareProvisioned: true })) {
402
564
  sessionGrants.pop();
@@ -406,23 +568,38 @@ export function recordGrant(input: RecordGrantInput): RecordGrantResult {
406
568
  return { ok: true, grant };
407
569
  }
408
570
 
571
+ return recordProjectGrant(subject, mode, buildGrant({ subject, scope, grantedAt, origin }, widen, input.via, mode), input.evict);
572
+ }
573
+
574
+ /** The persisted (`project`) scope of `recordGrant`: cap, whole-file state, atomic write-back with the preserved rows. */
575
+ function recordProjectGrant(
576
+ subject: string,
577
+ mode: GrantMode,
578
+ grant: AccessGrant,
579
+ evict: boolean | undefined,
580
+ ): RecordGrantResult {
409
581
  const grants = [...persisted()];
410
- const existing = grants.find((g) => g.subject === subject);
582
+ const existing = grants.find((g) => g.subject === subject && modeOf(g) === mode);
411
583
  if (existing) return { ok: true, grant: existing };
412
- const grant = buildGrant({ subject, scope, grantedAt, origin }, widen, input.via);
413
584
  grants.push(grant);
414
- if (!enforceCap(grants, "project", { protect: grant, evict: input.evict, spareProvisioned: true })) {
585
+ if (!enforceCap(grants, "project", { protect: grant, evict, spareProvisioned: true })) {
415
586
  return { ok: false, error: "capacity" };
416
587
  }
417
588
 
418
- const file: StoreFile = { version: 1, grants };
589
+ const prepared = prepareStoreWrite();
590
+ if (!prepared.ok) return { ok: false, error: prepared.error };
419
591
  try {
420
- writeAtomic(accessGrantsStorePath(), JSON.stringify(file, null, 2));
592
+ // Serialization is inside the guard: a deeply nested preserved row can make JSON.stringify throw.
593
+ const text = serializeStore(grants);
594
+ if (Buffer.byteLength(text) > GRANT_STORE_MAX_BYTES) {
595
+ // The reader refuses a store over the ceiling: committing this would make every grant vanish on the next start.
596
+ console.warn(`[access-grants] store would exceed ${GRANT_STORE_MAX_BYTES} bytes — write refused`);
597
+ return { ok: false, error: "store too large" };
598
+ }
599
+ writeAtomic(accessGrantsStorePath(), text);
421
600
  } catch (err) {
422
601
  // Not recorded. Cache untouched, so the admitted set cannot widen (D11).
423
- console.warn(
424
- `[access-grants] failed to persist grant for ${subject}: ${(err as Error)?.message}`,
425
- );
602
+ console.warn(`[access-grants] failed to persist grant for ${subject}: ${(err as Error)?.message}`);
426
603
  return { ok: false, error: (err as Error)?.message ?? "write failed" };
427
604
  }
428
605
  cache = grants;
@@ -431,18 +608,24 @@ export function recordGrant(input: RecordGrantInput): RecordGrantResult {
431
608
  }
432
609
 
433
610
  /**
434
- * Revoke by subject, or by subject+scope. Returns whether anything was removed.
435
- * A persisted revoke invalidates the in-memory cache, which is what makes
611
+ * Revoke by subject, or by subject+scope, optionally by mode. Returns whether anything
612
+ * was removed. A persisted revoke invalidates the in-memory cache, which is what makes
436
613
  * revocation take effect on the next request with no restart (D16).
614
+ *
615
+ * `mode` omitted (`undefined`) removes every entry for the subject (today's behaviour);
616
+ * `"write"` / `"read"` remove only that mode's entry; any OTHER value removes nothing
617
+ * (callers that take it from a request validate first and answer 400).
437
618
  */
438
- export function revokeGrant(subject: string, scope?: GrantScope): boolean {
619
+ export function revokeGrant(subject: string, scope?: GrantScope, mode?: unknown): boolean {
620
+ if (mode !== undefined && mode !== "read" && mode !== "write") return false;
439
621
  const target = normalizeGrantSubject(subject);
622
+ const matches = (g: AccessGrant): boolean => g.subject === target && (mode === undefined || modeOf(g) === mode);
440
623
  let removed = false;
441
624
 
442
625
  if (scope !== "project") {
443
626
  let sessionRemoved = false;
444
627
  for (let i = sessionGrants.length - 1; i >= 0; i -= 1) {
445
- if (sessionGrants[i].subject === target) {
628
+ if (matches(sessionGrants[i])) {
446
629
  sessionGrants.splice(i, 1);
447
630
  removed = true;
448
631
  sessionRemoved = true;
@@ -453,10 +636,13 @@ export function revokeGrant(subject: string, scope?: GrantScope): boolean {
453
636
  if (scope === "session") return removed;
454
637
 
455
638
  const grants = persisted();
456
- const kept = grants.filter((g) => g.subject !== target);
639
+ const kept = grants.filter((g) => !matches(g));
457
640
  if (kept.length === grants.length) return removed;
641
+ // Nothing was admitted from an unusable / oversize file, so there is nothing to revoke (and
642
+ // `kept` can only differ from `grants` for a usable store): a revoke never writes such a file.
643
+ if (storeState !== "ok") return removed;
458
644
  try {
459
- writeAtomic(accessGrantsStorePath(), JSON.stringify({ version: 1, grants: kept } satisfies StoreFile, null, 2));
645
+ writeAtomic(accessGrantsStorePath(), serializeStore(kept));
460
646
  } catch (err) {
461
647
  console.warn(
462
648
  `[access-grants] failed to persist revoke for ${target}: ${(err as Error)?.message}`,
@@ -31,6 +31,11 @@ interface PlaneGrantRequest {
31
31
  ancestors: readonly string[];
32
32
  /** Which session's denial produced the grant. */
33
33
  origin: string;
34
+ /**
35
+ * What the denial was refused for, taken from the SERVER-held pending entry (never from a browser
36
+ * field). `"write"` makes the filesystem plane record a write-mode grant; other planes ignore it.
37
+ */
38
+ action?: "read" | "write";
34
39
  }
35
40
 
36
41
  type PlaneGrantResult =
@@ -175,6 +180,7 @@ export interface SettledVerdict {
175
180
  deniedSubject: string;
176
181
  ancestors: readonly string[];
177
182
  origin: string;
183
+ action?: "read" | "write";
178
184
  }
179
185
 
180
186
  export type PersistOutcome = { persisted: false } | ({ persisted: true } & PlaneGrantResult);
@@ -191,6 +197,7 @@ export async function persistVerdict(plane: AccessPlane, v: SettledVerdict): Pro
191
197
  deniedSubject: v.deniedSubject,
192
198
  ancestors: v.ancestors,
193
199
  origin: v.origin,
200
+ ...(v.action === "write" ? { action: "write" as const } : {}),
194
201
  });
195
202
  return { persisted: true, ...result };
196
203
  }
@@ -25,9 +25,9 @@
25
25
  import { lstat } from "node:fs/promises";
26
26
  import type { PathDecision } from "@blackbelt-technology/pi-dashboard-shared/containment-guard.js";
27
27
  import { currentCallerUnproven, dashboardStateRefuses } from "../lib/dashboard-state-guard.js";
28
- import { isAllowed, isGrantAdmitted } from "../lib/path-containment.js";
28
+ import { isAllowedReal, isGrantAdmittedReal } from "../lib/path-containment.js";
29
29
  import { recordPathDenial } from "./access-denials.js";
30
- import { grantedSubjects } from "./access-grants.js";
30
+ import { grantedSubjects, grantedWriteSubjects } from "./access-grants.js";
31
31
  import { offeredAncestorLadder } from "./ancestor-ladder.js";
32
32
  import { type HoldTarget, holdDenial } from "./denial-hold.js";
33
33
  import { isUngrantableSubject, realpathNearestAncestor } from "./forbidden-subjects.js";
@@ -75,8 +75,8 @@ async function remedySubject(resolved: string, kind: SubjectKind): Promise<strin
75
75
  export type ContainmentDecision = PathDecision;
76
76
 
77
77
  /** The one constructor of a {@link ContainmentDecision}. */
78
- function decision(resolved: string, allowed: boolean, viaGrant: boolean): ContainmentDecision {
79
- return { allowed, viaGrant, resolved } as ContainmentDecision;
78
+ function decision(resolved: string, allowed: boolean, viaGrant: boolean, real?: string): ContainmentDecision {
79
+ return { allowed, viaGrant, resolved, real } as ContainmentDecision;
80
80
  }
81
81
 
82
82
  /** The additive remedy fields carried beside an unchanged `error` string. */
@@ -204,10 +204,18 @@ function outcomeFor(resolution: Resolution, held: boolean): PromptOutcome {
204
204
  * the tests can attribute a refusal to the site that produced it.
205
205
  *
206
206
  * `allowGrant` (default `true`) lets a site declare that a grant must NOT admit
207
- * it. A grant is a READ remedy; `open-in-system` / `reveal-in-file-manager`
207
+ * it. A grant has an access MODE: a read grant is a READ remedy, and only a
208
+ * `mode:"write"` grant admits an allowlisted text-document write (`action:"write"`,
209
+ * `file-routes:write`). `open-in-system` / `reveal-in-file-manager`
208
210
  * spawn a local application instead, so they pass `false` and keep exactly the
209
211
  * pre-change `isAllowed`-only decision. Without this the grant layer silently
210
212
  * widened a read grant into an app-launch capability (task 4.5 review gate).
213
+ *
214
+ * `action:"write"` (change: fix-file-link-editor-routing, D2) selects the WRITE
215
+ * predicate end to end: layer ② (bound-checkout widening) is skipped, the grant
216
+ * layer reads `grantedWriteSubjects()` only, the denial is recorded and held with
217
+ * `action:"write"`, and the post-verdict re-evaluation is mode-specific. Absent or
218
+ * `"read"` is byte-identical to the pre-change behaviour.
211
219
  */
212
220
  export async function evaluateContainment(
213
221
  resolved: string,
@@ -239,6 +247,11 @@ export async function evaluateContainment(
239
247
  * See change: gate-changed-on-disk-by-content (D4).
240
248
  */
241
249
  quiet?: boolean;
250
+ /**
251
+ * `"write"` = the gate for a text-document WRITE (see above). Derived by the
252
+ * route, never from a request field.
253
+ */
254
+ action?: "read" | "write";
242
255
  },
243
256
  ): Promise<ContainmentDecision & { remedy?: ContainmentRemedy }> {
244
257
  // Dashboard secrets (token, identity key, config) are refused before anything else, with the
@@ -249,10 +262,14 @@ export async function evaluateContainment(
249
262
  // Layers ①/② first — untouched and still authoritative (design D1) — then the
250
263
  // grant layer, and only on a miss does the denial get recorded.
251
264
  let verdict: ContainmentDecision;
252
- if (await isAllowed(resolved, { anchors })) {
253
- verdict = decision(resolved, true, false);
254
- } else if ((opts.allowGrant ?? true) && (await isGrantAdmitted(resolved, grantedSubjects()))) {
255
- verdict = decision(resolved, true, true);
265
+ const write = opts.action === "write";
266
+ const layered = await isAllowedReal(resolved, { anchors, skipCheckoutRoots: write });
267
+ const grantReal =
268
+ layered.allowed || !(opts.allowGrant ?? true) ? null : await grantAdmittedReal(resolved, write);
269
+ if (layered.allowed) {
270
+ verdict = decision(resolved, true, false, layered.real);
271
+ } else if (grantReal !== null) {
272
+ verdict = decision(resolved, true, true, grantReal);
256
273
  } else {
257
274
  verdict = decision(resolved, false, false);
258
275
  }
@@ -278,7 +295,9 @@ export async function evaluateContainment(
278
295
  // recorded denial, the body and the dialog all derive from the one string a
279
296
  // grant would store (`/tmp` → `/private/tmp`). Resolving a symlink never
280
297
  // widens: it names the same resource (design D6).
281
- const subject = realpathNearestAncestor(await remedySubject(resolved, opts.subjectKind ?? "file"));
298
+ // The remedy names the REAL target's directory: for an in-cwd link to an outside file the lexical
299
+ // parent is the (already anchored) cwd, which no grant could usefully name.
300
+ const subject = realpathNearestAncestor(await remedySubject(layered.real, opts.subjectKind ?? "file"));
282
301
  let ancestors: string[] = [];
283
302
  try {
284
303
  ancestors = await offeredAncestorLadder(subject);
@@ -305,6 +324,7 @@ export async function evaluateContainment(
305
324
  site: opts.site,
306
325
  session: opts.session,
307
326
  ancestors,
327
+ ...(write ? { action: "write" as const } : {}),
308
328
  });
309
329
 
310
330
  const remedy: DenialRemedy = {
@@ -322,11 +342,17 @@ export async function evaluateContainment(
322
342
  const resolution: Resolution = currentCallerUnproven()
323
343
  ? { kind: "deny", reason: "ineligible" }
324
344
  : await holdDenial(
325
- { plane: "filesystem", rawSubject: entry.subject, ancestors, origin: opts.session ?? "unknown" },
345
+ {
346
+ plane: "filesystem",
347
+ rawSubject: entry.subject,
348
+ ancestors,
349
+ origin: opts.session ?? "unknown",
350
+ ...(write ? { action: "write" as const } : {}),
351
+ },
326
352
  opts.hold,
327
353
  );
328
- const reEvaluated = resolution.kind === "allow" && (await reEvaluate(resolved, anchors, resolution));
329
- if (reEvaluated) return decision(resolved, true, true);
354
+ const reEvaluated = resolution.kind === "allow" ? await reEvaluate(resolved, anchors, resolution, write) : null;
355
+ if (reEvaluated !== null) return decision(resolved, true, true, reEvaluated);
330
356
  if (opts.disclosure) remedy.promptOutcome = outcomeFor(resolution, opts.hold !== undefined);
331
357
  return { ...verdict, remedy };
332
358
  }
@@ -345,8 +371,12 @@ export async function decidePassive(
345
371
  anchors: string[],
346
372
  opts: { allowGrant: boolean; grantSubjects?: string[] },
347
373
  ): Promise<ContainmentDecision> {
348
- if (await isAllowed(resolved, { anchors })) return decision(resolved, true, false);
349
- if (opts.allowGrant && (await isGrantAdmitted(resolved, opts.grantSubjects ?? grantedSubjects()))) return decision(resolved, true, true);
374
+ const layered = await isAllowedReal(resolved, { anchors });
375
+ if (layered.allowed) return decision(resolved, true, false, layered.real);
376
+ if (opts.allowGrant) {
377
+ const grantReal = await isGrantAdmittedReal(resolved, opts.grantSubjects ?? grantedSubjects());
378
+ if (grantReal !== null) return decision(resolved, true, true, grantReal);
379
+ }
350
380
  return decision(resolved, false, false);
351
381
  }
352
382
 
@@ -366,10 +396,25 @@ async function reEvaluate(
366
396
  resolved: string,
367
397
  anchors: string[],
368
398
  resolution: Extract<Resolution, { kind: "allow" }>,
369
- ): Promise<boolean> {
370
- if (await isAllowed(resolved, { anchors })) return true;
371
- if (await isGrantAdmitted(resolved, grantedSubjects())) return true;
372
- if (resolution.verdict !== "allow-once") return false;
373
- if (isUngrantableSubject(resolution.subject)) return false;
374
- return isGrantAdmitted(resolved, [resolution.subject]);
399
+ write: boolean,
400
+ ): Promise<string | null> {
401
+ const layered = await isAllowedReal(resolved, { anchors, skipCheckoutRoots: write });
402
+ if (layered.allowed) return layered.real;
403
+ const stored = await grantAdmittedReal(resolved, write);
404
+ if (stored !== null) return stored;
405
+ if (resolution.verdict !== "allow-once") return null;
406
+ if (isUngrantableSubject(resolution.subject)) return null;
407
+ // The answered subject applies as a transient grant of the SAME mode as the denial: a write
408
+ // allow-once is checked against the write predicate and never persisted.
409
+ return isGrantAdmittedReal(resolved, [resolution.subject], { allowMissing: write });
410
+ }
411
+
412
+ /**
413
+ * The grant layer for one mode. Reads use `grantedSubjects()` (write ⊃ read) and refuse a path that
414
+ * does not resolve; a write uses `grantedWriteSubjects()` only and answers before any stat.
415
+ */
416
+ function grantAdmittedReal(resolved: string, write: boolean): Promise<string | null> {
417
+ return write
418
+ ? isGrantAdmittedReal(resolved, grantedWriteSubjects(), { allowMissing: true })
419
+ : isGrantAdmittedReal(resolved, grantedSubjects());
375
420
  }