@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
@@ -25,7 +25,6 @@
25
25
  * See change: add-editor-pane-file-handlers (D4).
26
26
  */
27
27
  import { createHash, randomBytes } from "node:crypto";
28
- import { createReadStream } from "node:fs";
29
28
  import fs from "node:fs/promises";
30
29
  import path from "node:path";
31
30
  import {
@@ -37,6 +36,7 @@ import {
37
36
  import type { PluginClaim } from "@blackbelt-technology/pi-dashboard-shared/dashboard-plugin/manifest-types.js";
38
37
  import { DIGEST_CEILING_BYTES, extOf } from "@blackbelt-technology/pi-dashboard-shared/file-kind.js";
39
38
  import type { FastifyInstance } from "fastify";
39
+ import { DashboardStateRefused, openStateChecked } from "../lib/dashboard-state-guard.js";
40
40
  import { admitFileCwd } from "../lib/file-cwd-admission.js";
41
41
  import { serializeWrite } from "../lib/file-write-lock.js";
42
42
  import { within } from "../lib/path-containment.js";
@@ -113,10 +113,20 @@ interface Query {
113
113
  const SHA1_RE = /^[0-9a-f]{40}$/;
114
114
  const MAX_COPY_ATTEMPTS = 99;
115
115
 
116
+ /**
117
+ * SHA-1 of `file`, read through the post-open (dev, ino) recheck so a hard link to a pi-agent
118
+ * credential file yields no hash (rejects `DashboardStateRefused`).
119
+ * See change: close-security-map-high-findings (D1, H6).
120
+ */
116
121
  async function sha1OfFile(file: string): Promise<string> {
117
122
  const hash = createHash("sha1");
118
- for await (const chunk of createReadStream(file))
119
- hash.update(chunk as Buffer);
123
+ const fh = await openStateChecked(file);
124
+ try {
125
+ for await (const chunk of fh.createReadStream({ autoClose: false }))
126
+ hash.update(chunk as Buffer);
127
+ } finally {
128
+ await fh.close().catch(() => {});
129
+ }
120
130
  return hash.digest("hex");
121
131
  }
122
132
 
@@ -164,7 +174,13 @@ async function overwrite(
164
174
  if (!current.isFile()) return fail(403, "target is not a regular file");
165
175
  if (current.size > DIGEST_CEILING_BYTES)
166
176
  return fail(409, "file too large to verify", { mtime: current.mtimeMs });
167
- const currentSha1 = await sha1OfFile(real).catch(() => null);
177
+ let currentSha1: string | null;
178
+ try {
179
+ currentSha1 = await sha1OfFile(real);
180
+ } catch (err) {
181
+ if (err instanceof DashboardStateRefused) return fail(403, "target is not a writable handler file in scope");
182
+ currentSha1 = null;
183
+ }
168
184
  if (currentSha1 === null) return fail(409, "file no longer exists");
169
185
  if (currentSha1 !== expectSha1) {
170
186
  return fail(409, "file changed on disk since it was loaded", {
@@ -0,0 +1,215 @@
1
+ /**
2
+ * `POST /api/web/frame-policy` — may the dashboard frame this origin?
3
+ *
4
+ * body { origin: "https://<host>" } (the target ORIGIN only — never a path or query)
5
+ * 200 { verdict: "allowed" | "refused" | "undetermined" | "ineligible" }
6
+ * 400 no/invalid body, or the request `Origin` is missing / not one of the dashboard's own
7
+ * 403 cross-site (mutation-origin gate) or tier below `control` (route tier gate)
8
+ * 429 30/min per principal, or 2 probes of that principal already in flight; 503 8 probes already in flight
9
+ *
10
+ * The outbound work (SSRF defence, DNS pinning, redirects, deadline) lives in
11
+ * `lib/frame-policy-probe.ts`; this module owns request gating, the per-principal
12
+ * cache, limits and host-only logging. The response carries the verdict and nothing
13
+ * else. See change: rich-chat-links (design D12, tasks 3.15).
14
+ */
15
+ import crypto from "node:crypto";
16
+ import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
17
+ import type { CorsOriginOptions } from "../auth/cors-origin.js";
18
+ import { requestPrincipalKey } from "../auth/request-principal.js";
19
+ import { createLookupGate, type ProbeDeps, type ProbeVerdict, probeFramePolicy } from "../lib/frame-policy-probe.js";
20
+ import { createWindowLimiter } from "../lib/resolve-mentions-batch.js";
21
+ import type { NetworkGuard } from "./route-deps.js";
22
+
23
+ export const FRAME_POLICY_RATE_PER_MINUTE = 30;
24
+ export const FRAME_POLICY_MAX_CONCURRENT = 8;
25
+ export const FRAME_POLICY_MAX_PER_PRINCIPAL = 2;
26
+ export const FRAME_POLICY_CACHE_ENTRIES = 500;
27
+ export const FRAME_POLICY_CACHE_TTL_MS = 10 * 60_000;
28
+ const BODY_LIMIT = 2 * 1024;
29
+ const MAX_ORIGIN_CHARS = 512;
30
+ const LOOPBACK_HOSTS = new Set(["127.0.0.1", "localhost", "[::1]"]);
31
+
32
+ export interface FramePolicyRoutesDeps {
33
+ networkGuard: NetworkGuard;
34
+ /** Live CORS/admission options (same object the mutation-origin gate and CORS use). */
35
+ corsOpts: () => CorsOriginOptions;
36
+ /** Dashboard-own non-loopback origins: tunnels, public base URLs, configured CORS origins. */
37
+ ownOrigins: () => readonly string[];
38
+ /** Ports this server serves browsers on (HTTP and TLS); a loopback Origin must carry one. */
39
+ ownPorts: () => readonly number[];
40
+ principalOf?: (request: FastifyRequest) => string;
41
+ /** Outbound seams + deadline; the defaults are the production transport. */
42
+ probe?: Partial<Pick<ProbeDeps, "lookup" | "request" | "deadlineMs">>;
43
+ now?: () => number;
44
+ }
45
+
46
+ function tryParseUrl(raw: string): URL | null {
47
+ try {
48
+ return new URL(raw);
49
+ } catch {
50
+ return null;
51
+ }
52
+ }
53
+
54
+ /** A loopback Origin is the dashboard's own only when it carries a port this server serves. */
55
+ function isOwnLoopbackPort(u: URL, ownPorts: readonly number[]): boolean {
56
+ const port = u.port || (u.protocol === "https:" ? "443" : "80");
57
+ return ownPorts.some((p) => String(p) === port);
58
+ }
59
+
60
+ function matchesOwnOrigin(origin: string, ownOrigins: readonly string[]): boolean {
61
+ // A malformed own origin is ignored.
62
+ return ownOrigins.some((own) => tryParseUrl(own)?.origin === origin);
63
+ }
64
+
65
+ /** The request's browser `Origin` when it is one of the dashboard's own, else null. */
66
+ function dashboardOriginOf(raw: unknown, ownPorts: readonly number[], ownOrigins: readonly string[]): string | null {
67
+ if (typeof raw !== "string" || !raw) return null;
68
+ const u = tryParseUrl(raw);
69
+ if (!u) return null;
70
+ if (u.origin === "null" || raw !== u.origin) return null; // a browser sends the serialised origin only
71
+ if ((u.protocol === "http:" || u.protocol === "https:") && LOOPBACK_HOSTS.has(u.hostname)) {
72
+ return isOwnLoopbackPort(u, ownPorts) ? u.origin : null;
73
+ }
74
+ return matchesOwnOrigin(u.origin, ownOrigins) ? u.origin : null;
75
+ }
76
+
77
+ /** Per-principal cache key, or null when the target origin did not parse (nothing to cache). */
78
+ function cacheKeyOf(principal: string, targetOrigin: string | null, dashboardOrigin: string): string | null {
79
+ return targetOrigin ? JSON.stringify([principal, targetOrigin, dashboardOrigin]) : null;
80
+ }
81
+
82
+ /** The body's `origin` when it is a non-empty string within the length cap, else null. */
83
+ function rawOriginOf(body: unknown): string | null {
84
+ const raw = (body as { origin?: unknown } | null)?.origin;
85
+ return typeof raw === "string" && raw && raw.length <= MAX_ORIGIN_CHARS ? raw : null;
86
+ }
87
+
88
+ /** Host (for logs) and canonical origin of the raw target; `"invalid"` / null when unparseable. */
89
+ function describeTarget(raw: string): { host: string; targetOrigin: string | null } {
90
+ const u = tryParseUrl(raw);
91
+ return u ? { host: u.hostname, targetOrigin: u.origin } : { host: "invalid", targetOrigin: null };
92
+ }
93
+
94
+ interface Rejection {
95
+ code: number;
96
+ error: string;
97
+ }
98
+
99
+ /** A request whose probe is about to run (all gates passed). */
100
+ interface ProbeCall {
101
+ raw: string;
102
+ dashboardOrigin: string;
103
+ bucket: string;
104
+ /** Cache key, or null when the target origin did not parse. */
105
+ key: string | null;
106
+ host: string;
107
+ started: number;
108
+ }
109
+
110
+ export function registerFramePolicyRoutes(fastify: FastifyInstance, deps: FramePolicyRoutesDeps): void {
111
+ const principalOf = deps.principalOf ?? requestPrincipalKey;
112
+ const now = deps.now ?? Date.now;
113
+ const limiter = createWindowLimiter(FRAME_POLICY_RATE_PER_MINUTE, now);
114
+ // Per-process salt: internal host names stay out of logs, repeated scans stay visible.
115
+ const salt = crypto.randomBytes(16);
116
+ const hashHost = (host: string): string => crypto.createHash("sha256").update(salt).update(host).digest("hex").slice(0, 12);
117
+ const cache = new Map<string, { verdict: ProbeVerdict; at: number }>();
118
+ let inflight = 0;
119
+ const inflightBy = new Map<string, number>();
120
+ // One gate per registration: outstanding DNS lookups (incl. abandoned ones) stay under the libuv pool size.
121
+ const lookupGate = createLookupGate();
122
+
123
+ const cacheGet = (key: string | null): ProbeVerdict | null => {
124
+ if (key === null) return null;
125
+ const hit = cache.get(key);
126
+ if (!hit) return null;
127
+ cache.delete(key);
128
+ if (now() - hit.at >= FRAME_POLICY_CACHE_TTL_MS) return null;
129
+ cache.set(key, hit); // most recently used
130
+ return hit.verdict;
131
+ };
132
+ const cacheSet = (key: string, verdict: ProbeVerdict): void => {
133
+ cache.delete(key);
134
+ cache.set(key, { verdict, at: now() });
135
+ if (cache.size > FRAME_POLICY_CACHE_ENTRIES) cache.delete(cache.keys().next().value as string);
136
+ };
137
+
138
+ /** Admission: the global and per-principal in-flight caps. Null = admitted. */
139
+ const inflightRejection = (bucket: string): Rejection | null => {
140
+ if (inflight >= FRAME_POLICY_MAX_CONCURRENT) return { code: 503, error: "busy" };
141
+ if ((inflightBy.get(bucket) ?? 0) >= FRAME_POLICY_MAX_PER_PRINCIPAL) {
142
+ return { code: 429, error: "too many probes in flight" };
143
+ }
144
+ return null;
145
+ };
146
+
147
+ const runProbe = async (call: ProbeCall): Promise<{ verdict: ProbeVerdict }> => {
148
+ const { raw, dashboardOrigin, bucket, key, host, started } = call;
149
+ inflight++;
150
+ inflightBy.set(bucket, (inflightBy.get(bucket) ?? 0) + 1);
151
+ try {
152
+ const result = await probeFramePolicy(raw, dashboardOrigin, {
153
+ ownOrigins: deps.ownOrigins(),
154
+ corsOpts: deps.corsOpts(),
155
+ lookupGate,
156
+ ...deps.probe,
157
+ });
158
+ // A transient `undetermined` is never cached, so "Try to embed" re-probes.
159
+ if (key && (result.verdict === "allowed" || result.verdict === "refused")) cacheSet(key, result.verdict);
160
+ console.log(formatLog(result.verdict, result.hops, now() - started, host, hashHost, false));
161
+ return { verdict: result.verdict };
162
+ } finally {
163
+ inflight--;
164
+ const left = (inflightBy.get(bucket) ?? 1) - 1;
165
+ if (left > 0) inflightBy.set(bucket, left);
166
+ else inflightBy.delete(bucket);
167
+ }
168
+ };
169
+
170
+ const rejectWith = (reply: FastifyReply, code: number, error: string) => {
171
+ reply.code(code);
172
+ return { success: false, error };
173
+ };
174
+
175
+ fastify.post(
176
+ "/api/web/frame-policy",
177
+ { preHandler: deps.networkGuard, bodyLimit: BODY_LIMIT },
178
+ async (request, reply) => {
179
+ const dashboardOrigin = dashboardOriginOf(request.headers.origin, deps.ownPorts(), deps.ownOrigins());
180
+ if (!dashboardOrigin) return rejectWith(reply, 400, "own browser Origin required");
181
+ const principal = principalOf(request);
182
+ // Without a real principal every local caller shares one bucket per address.
183
+ const bucket = principal === "local-operator" ? `${principal}@${request.ip}` : principal;
184
+ if (!limiter.take(bucket)) return rejectWith(reply, 429, "rate limited");
185
+ const raw = rawOriginOf(request.body);
186
+ if (raw === null) return rejectWith(reply, 400, "origin required");
187
+
188
+ const { host, targetOrigin } = describeTarget(raw);
189
+ const key = cacheKeyOf(principal, targetOrigin, dashboardOrigin);
190
+ const started = now();
191
+
192
+ const cached = cacheGet(key);
193
+ if (cached) {
194
+ console.log(formatLog(cached, 0, 0, host, hashHost, true));
195
+ return { verdict: cached };
196
+ }
197
+ const rejection = inflightRejection(bucket);
198
+ if (rejection) return rejectWith(reply, rejection.code, rejection.error);
199
+ return runProbe({ raw, dashboardOrigin, bucket, key, host, started });
200
+ },
201
+ );
202
+ }
203
+
204
+ /** One line: verdict, hops, ms. Host only (never path/query); `ineligible` logs a salted hash instead. */
205
+ function formatLog(
206
+ verdict: ProbeVerdict,
207
+ hops: number,
208
+ ms: number,
209
+ host: string,
210
+ hashHost: (h: string) => string,
211
+ cached: boolean,
212
+ ): string {
213
+ const who = verdict === "ineligible" ? `hostHash=${hashHost(host)}` : `host=${host}`;
214
+ return `[frame-policy] verdict=${verdict} hops=${hops} ms=${ms} ${who}${cached ? " cached=1" : ""}`;
215
+ }
@@ -43,10 +43,11 @@ import {
43
43
  type WorktreeRemovalVerdict,
44
44
  worktreeDiffStat,
45
45
  } from "../git-worktree/git-operations.js";
46
- import { evaluateGate, type GateResult, hookDefHash, type InitProgress, readInitHook, runInitHook, type WorktreeInitHook } from "../git-worktree/worktree-init.js";
46
+ import { hookDefHash, readInitHook } from "../git-worktree/worktree-init.js";
47
47
  import { gitErrorText, redactGitText } from "../git-worktree/redact-git-text.js";
48
48
  import { INVALID_REF_CODE, InvalidRefError, isMissingArg, isValidRefArg } from "../git-worktree/ref-arg.js";
49
- import { mapInitStderrToHint } from "../git-worktree/worktree-init-errors.js";
49
+ import { repoLockKey, withRepoLock } from "../git-worktree/repo-lock.js";
50
+ import { evaluateGateCached, startWorktreeInit } from "../git-worktree/start-worktree-init.js";
50
51
  import type { WorktreeInitRegistry } from "../git-worktree/worktree-init-registry.js";
51
52
  import { isTrusted, recordTrust } from "../git-worktree/worktree-init-trust.js";
52
53
  import { admitRouteCwd, sendAdmissionUnavailable } from "../lib/route-admission.js";
@@ -123,15 +124,6 @@ const NO_DERIVATION_RUNNER: NonNullable<AdmitCwdOptions["runner"]> = async () =>
123
124
  error: { kind: "spawn-failure", message: "admission budget exhausted" },
124
125
  });
125
126
 
126
- /**
127
- * Per-resolved-checkout cache of the gate result, with a short TTL.
128
- * Invalidated when a hook run starts/exits for that checkout.
129
- * See change: generalize-worktree-init-hook.
130
- */
131
- const GATE_CACHE_TTL_MS = 30 * 1000;
132
- const gateCache = new Map<string, { needsInit: boolean; evaluatedAt: number }>();
133
- function invalidateGateCache(checkoutPath: string) { gateCache.delete(checkoutPath); }
134
-
135
127
  /**
136
128
  * Per-artifact setup checklist for the init-status probe (change:
137
129
  * add-folder-action-banner, D5). A `stat` of a fixed five-entry list resolved at
@@ -168,27 +160,6 @@ function buildSetupChecklist(configRoot: string | null): SetupArtifact[] | undef
168
160
  }
169
161
  }
170
162
 
171
- /**
172
- * Last non-empty line of the progress tail, for the ghost preview. The tail is
173
- * the most recent <= 4KB of combined output; the chip shows only its final line.
174
- * See change: friendlier-worktree-init.
175
- */
176
- function lastLineOf(tail: string): string {
177
- const lines = tail.split(/\r?\n/);
178
- for (let i = lines.length - 1; i >= 0; i--) {
179
- const line = lines[i]?.trim();
180
- if (line) return line;
181
- }
182
- return "";
183
- }
184
- async function evaluateGateCached(checkoutPath: string, hook: WorktreeInitHook): Promise<GateResult> {
185
- const hit = gateCache.get(checkoutPath);
186
- if (hit && Date.now() - hit.evaluatedAt < GATE_CACHE_TTL_MS) return { needsInit: hit.needsInit };
187
- const res = await evaluateGate(checkoutPath, hook);
188
- gateCache.set(checkoutPath, { needsInit: res.needsInit, evaluatedAt: Date.now() });
189
- return res;
190
- }
191
-
192
163
  /**
193
164
  * Defensive clamp for the configured batch cap (D8). `DashboardConfig`
194
165
  * parsing already clamps (`clampRemoveBatchCap` in shared config), so a value
@@ -640,52 +611,30 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
640
611
  recordTrust(configRoot, hash, scope);
641
612
  }
642
613
  }
643
- if (!isTrusted(configRoot, hash)) {
644
- // Echo the hash so the client confirms with `confirmHash` without
645
- // re-implementing the canonical hash. See change: generalize-worktree-init-hook.
646
- return { success: false, code: "init_untrusted", data: { hook, hash } } satisfies ApiResponse;
647
- }
648
- // Re-trust case: the hook was edited (invalidating trust) but the gate is
649
- // already satisfied (`needsInit === false`). Granting trust should clear
650
- // the control WITHOUT re-running the hook. See change:
651
- // friendlier-worktree-init (folder-action-bar spec).
652
- const preGate = await evaluateGateCached(validated.cwd, hook);
653
- if (!preGate.needsInit) {
654
- return { success: true, data: { ran: false, skippedReason: "already_initialized" } } satisfies ApiResponse;
655
- }
614
+ // Trust is checked (never granted) and the run is driven by the shared starter, which the
615
+ // plugin-spawn hook also uses. No `skipIfRunning`: a click restarts a live run, as before.
616
+ // See change: add-plugin-spawn-worktree (design D6).
656
617
  const requestId = typeof body.requestId === "string" && body.requestId.length > 0 ? body.requestId : undefined;
657
- const cwd = validated.cwd;
658
- // Fan out to the legacy per-click requestId subscriber (if any) AND to
659
- // every cwd-keyed subscriber (refresh / second tab / auto-init).
660
- // See change: friendlier-worktree-init.
661
- const sendIf = (msg: any) => {
662
- if (worktreeInitRegistry) {
663
- if (requestId) worktreeInitRegistry.send(requestId, msg);
664
- worktreeInitRegistry.sendCwd(cwd, msg);
665
- }
666
- };
667
- worktreeInitRegistry?.startRun(cwd);
668
- const onProgress = (p: InitProgress) => {
669
- worktreeInitRegistry?.progressRun(cwd, lastLineOf(p.line), p.line);
670
- sendIf({ type: "worktree_init_progress", requestId: requestId ?? "", cwd, line: p.line });
671
- };
672
- invalidateGateCache(cwd);
673
- const runResult = await runInitHook(cwd, hook, onProgress);
674
- invalidateGateCache(cwd);
675
- if (runResult.ok) {
676
- worktreeInitRegistry?.finishRun(cwd, "done");
677
- sendIf({ type: "worktree_init_done", requestId: requestId ?? "", cwd, durationMs: runResult.durationMs });
678
- return { success: true, data: { ran: true, durationMs: runResult.durationMs } } satisfies ApiResponse;
618
+ const started = await startWorktreeInit(validated.cwd, { registry: worktreeInitRegistry, requestId });
619
+ switch (started.status) {
620
+ case "untrusted":
621
+ // Echo the hash so the client confirms with `confirmHash` without
622
+ // re-implementing the canonical hash. See change: generalize-worktree-init-hook.
623
+ return { success: false, code: "init_untrusted", data: { hook: started.hook, hash: started.hash } } satisfies ApiResponse;
624
+ case "no_hook":
625
+ return { success: true, data: { ran: false, skippedReason: "no_hook" } } satisfies ApiResponse;
626
+ case "already_initialized":
627
+ return { success: true, data: { ran: false, skippedReason: "already_initialized" } } satisfies ApiResponse;
628
+ case "done":
629
+ return { success: true, data: { ran: true, durationMs: started.durationMs } } satisfies ApiResponse;
630
+ case "failed":
631
+ reply.code(500);
632
+ return { success: false, code: "init_failed", error: started.hint, stderr: started.stderr } satisfies ApiResponse;
633
+ default:
634
+ // `already_running` is only returned under `skipIfRunning`, which this route never passes.
635
+ reply.code(500);
636
+ return { success: false, code: "init_failed", error: "init run state unexpected" } satisfies ApiResponse;
679
637
  }
680
- // B20: the mapper sees the RAW stderr (so it can match paths); BOTH the mapped hint and the
681
- // stderr are redacted AFTER mapping, against the checkout the hook ran in (`cwd`, captured above).
682
- const rawStderr = runResult.stderr ?? "";
683
- const hint = redact(mapInitStderrToHint(rawStderr) ?? `init failed (${runResult.code ?? "unknown"})`, cwd);
684
- const stderr = redact(rawStderr, cwd);
685
- worktreeInitRegistry?.finishRun(cwd, "failed", runResult.code ?? "init_failed");
686
- sendIf({ type: "worktree_init_failed", requestId: requestId ?? "", cwd, code: runResult.code ?? "init_failed", message: hint, stderr });
687
- reply.code(500);
688
- return { success: false, code: "init_failed", error: hint, stderr } satisfies ApiResponse;
689
638
  },
690
639
  );
691
640
 
@@ -715,13 +664,15 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
715
664
  }
716
665
  // `newBranch` is optional: present → fork mode; absent → the server checks out the existing
717
666
  // `base` ref (checkout mode). See change: worktree-checkout-existing-branch.
718
- const result = addWorktree({
667
+ // Serialized with plugin-spawn worktree creation for the same repository (design D4).
668
+ const addArgs = {
719
669
  cwd: validated.cwd,
720
670
  base: body.base,
721
671
  ...(body.newBranch !== undefined ? { newBranch: body.newBranch as string } : {}),
722
672
  path: typeof body.path === "string" && body.path.length > 0 ? body.path : undefined,
723
673
  force: body.force === true,
724
- });
674
+ };
675
+ const result = await withRepoLock(repoLockKey(validated.cwd), () => addWorktree(addArgs));
725
676
  if (!result.ok) {
726
677
  const httpStatus =
727
678
  result.error === "branch_in_use" || result.error === "branch_exists" || result.error === "path_exists"
@@ -10,12 +10,14 @@
10
10
  * See change: split-editor-workspace, core-file-cwd-admission.
11
11
  */
12
12
 
13
+ import fs from "node:fs/promises";
13
14
  import path from "node:path";
14
15
  import { containmentAllows } from "@blackbelt-technology/pi-dashboard-shared/containment-guard.js";
15
16
  import type { ApiResponse } from "@blackbelt-technology/pi-dashboard-shared/types.js";
16
17
  import type { FastifyInstance } from "fastify";
17
18
  import { grantedSubjects } from "../access/access-grants.js";
18
19
  import { decidePassive } from "../access/containment-gate.js";
20
+ import { alwaysRefusedIdentities, identityIsAlwaysRefused } from "../lib/dashboard-state-guard.js";
19
21
  import { admitFileCwd, cwdAnchors } from "../lib/file-cwd-admission.js";
20
22
  import { GrepTimeoutError, runGrep } from "../lib/grep.js";
21
23
  import type { RouteAdmissionDeps } from "../lib/route-admission.js";
@@ -95,6 +97,30 @@ export function registerGrepRoutes(
95
97
  );
96
98
  matches = contained.filter((m): m is NonNullable<typeof m> => m !== null);
97
99
 
100
+ // Gate 2b — identity: drop matches in a file whose (dev, ino) is an always-refused file (a hard
101
+ // link to a pi-agent credential, the token or the identity key is invisible to a path check).
102
+ // The identity list is built once per request; one `stat` per DISTINCT matched path.
103
+ // Residual: the JS walker has read such a file into memory by now (content is never returned).
104
+ // See change: close-security-map-high-findings (D1, G4).
105
+ if (matches.length > 0) {
106
+ const identities = await alwaysRefusedIdentities();
107
+ const verdicts = new Map<string, Promise<boolean>>();
108
+ const refusedByIdentity = (rel: string): Promise<boolean> => {
109
+ const abs = path.resolve(admitted.cwd, rel);
110
+ let v = verdicts.get(abs);
111
+ if (!v) {
112
+ v = fs.stat(abs).then(
113
+ (st) => identityIsAlwaysRefused(st, identities),
114
+ () => true, // cannot identify it: fail closed
115
+ );
116
+ verdicts.set(abs, v);
117
+ }
118
+ return v;
119
+ };
120
+ const keep = await Promise.all(matches.map(async (m) => !(await refusedByIdentity(m.path))));
121
+ matches = matches.filter((_, i) => keep[i]);
122
+ }
123
+
98
124
  return { success: true, data: { matches } } satisfies ApiResponse;
99
125
  },
100
126
  );