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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (474) hide show
  1. package/AGENTS.md +4 -2
  2. package/README.md +64 -18
  3. package/docs/architecture.md +2325 -270
  4. package/package.json +36 -20
  5. package/packages/extension/package.json +18 -9
  6. package/packages/extension/src/bridge-context.ts +6 -0
  7. package/packages/extension/src/bridge-handlers/dispatch.ts +109 -70
  8. package/packages/extension/src/bridge-handlers/forwarders.ts +19 -42
  9. package/packages/extension/src/bridge-handlers/instance.ts +31 -13
  10. package/packages/extension/src/bridge-handlers/lifecycle.ts +149 -66
  11. package/packages/extension/src/bridge-shutdown.ts +44 -0
  12. package/packages/extension/src/bridge-ticket-client.ts +61 -7
  13. package/packages/extension/src/bridge-tls-checks.ts +79 -0
  14. package/packages/extension/src/bridge.ts +309 -284
  15. package/packages/extension/src/canvas-tool.ts +2 -0
  16. package/packages/extension/src/command-handler.ts +106 -37
  17. package/packages/extension/src/connect-target.ts +23 -0
  18. package/packages/extension/src/connection.ts +153 -38
  19. package/packages/extension/src/credential-guard.ts +300 -0
  20. package/packages/extension/src/custom-entry-forward.ts +27 -18
  21. package/packages/extension/src/dashboard-http-origin.ts +88 -0
  22. package/packages/extension/src/default-model-apply.ts +83 -0
  23. package/packages/extension/src/dev-build.ts +11 -1
  24. package/packages/extension/src/flow-event-wiring.ts +19 -95
  25. package/packages/extension/src/followup-drain.ts +19 -5
  26. package/packages/extension/src/git-link-builder.ts +11 -2
  27. package/packages/extension/src/inbound-limits.ts +138 -0
  28. package/packages/extension/src/local-token-header.ts +77 -6
  29. package/packages/extension/src/model-refresh.ts +69 -0
  30. package/packages/extension/src/path-gate/decide.ts +68 -5
  31. package/packages/extension/src/path-gate/handler.ts +16 -8
  32. package/packages/extension/src/path-gate/index.ts +2 -2
  33. package/packages/extension/src/path-gate/roots.ts +15 -3
  34. package/packages/extension/src/path-gate/suppression.ts +3 -0
  35. package/packages/extension/src/pi-env.d.ts +8 -1
  36. package/packages/extension/src/pi-retry-settings.ts +11 -2
  37. package/packages/extension/src/pinned-endpoint.ts +44 -0
  38. package/packages/extension/src/plugin-event-forward-registry.ts +90 -14
  39. package/packages/extension/src/preview-path-link.ts +151 -0
  40. package/packages/extension/src/project-init/scaffold.ts +98 -35
  41. package/packages/extension/src/project-trust-live.ts +143 -0
  42. package/packages/extension/src/project-trust.ts +178 -30
  43. package/packages/extension/src/provider-model-cache.ts +118 -0
  44. package/packages/extension/src/provider-register.ts +487 -46
  45. package/packages/extension/src/remote-registration-gate.ts +21 -21
  46. package/packages/extension/src/remote-upgrade-preparer.ts +104 -0
  47. package/packages/extension/src/retry-tracker.ts +90 -7
  48. package/packages/extension/src/role-manager.ts +4 -2
  49. package/packages/extension/src/role-model-tools.ts +68 -10
  50. package/packages/extension/src/server-auto-start.ts +69 -3
  51. package/packages/extension/src/server-launcher.ts +26 -8
  52. package/packages/extension/src/server-proof-probe.ts +117 -0
  53. package/packages/extension/src/session-sync.ts +53 -24
  54. package/packages/extension/src/spawn-new-session.ts +22 -0
  55. package/packages/extension/src/steer-buffer.ts +164 -0
  56. package/packages/extension/src/stream-forward-buffer.ts +64 -15
  57. package/packages/extension/src/sudo-askpass/config-reader.ts +32 -0
  58. package/packages/extension/src/sudo-askpass/controller.ts +405 -0
  59. package/packages/extension/src/sudo-askpass/helper-script.ts +69 -0
  60. package/packages/extension/src/sudo-askpass/in-flight.ts +79 -0
  61. package/packages/extension/src/sudo-askpass/index.ts +11 -0
  62. package/packages/extension/src/sudo-askpass/install.ts +143 -0
  63. package/packages/extension/src/sudo-askpass/password-cache.ts +118 -0
  64. package/packages/extension/src/sudo-askpass/prompt-text.ts +55 -0
  65. package/packages/extension/src/sudo-askpass/protocol.ts +18 -0
  66. package/packages/extension/src/sudo-askpass/sudo-mask-registry.ts +52 -0
  67. package/packages/extension/src/terminal-reload.ts +19 -5
  68. package/packages/extension/src/tool-update-filter-registry.ts +210 -0
  69. package/packages/extension/src/vault-delivery.ts +11 -1
  70. package/packages/extension/src/vault-redaction.ts +4 -3
  71. package/packages/server/package.json +17 -14
  72. package/packages/server/src/access/access-denials.ts +8 -0
  73. package/packages/server/src/access/access-grants.ts +303 -64
  74. package/packages/server/src/access/access-health.ts +10 -0
  75. package/packages/server/src/access/access-plane.ts +12 -1
  76. package/packages/server/src/access/containment-gate.ts +113 -30
  77. package/packages/server/src/access/cwd-verdict.ts +3 -3
  78. package/packages/server/src/access/denial-hold.ts +3 -0
  79. package/packages/server/src/access/grant-coordinator.ts +17 -1
  80. package/packages/server/src/access/named-grant.ts +3 -0
  81. package/packages/server/src/access/pending-grant-registry.ts +32 -5
  82. package/packages/server/src/access/pi-trust-live.ts +244 -0
  83. package/packages/server/src/access/pi-trust-mirror-service.ts +50 -11
  84. package/packages/server/src/access/planes.ts +107 -1
  85. package/packages/server/src/access/preview-egress-store.ts +153 -0
  86. package/packages/server/src/access/prompt-channel.ts +5 -0
  87. package/packages/server/src/access/provisioning-wiring.ts +113 -0
  88. package/packages/server/src/access/provisioning.ts +763 -0
  89. package/packages/server/src/access/verified-read.ts +24 -7
  90. package/packages/server/src/access/yolo-session.ts +54 -2
  91. package/packages/server/src/acp-bridge/acp-session-adapter.ts +18 -5
  92. package/packages/server/src/acp-bridge/server-requests.ts +10 -4
  93. package/packages/server/src/agent-events/agent-event-hub.ts +158 -0
  94. package/packages/server/src/auth/audit-log.ts +108 -0
  95. package/packages/server/src/auth/auth-plugin.ts +230 -38
  96. package/packages/server/src/auth/auth.ts +104 -4
  97. package/packages/server/src/auth/bearer-auth.ts +52 -12
  98. package/packages/server/src/auth/bridge-ticket-eligibility.ts +53 -10
  99. package/packages/server/src/auth/cors-origin.ts +90 -30
  100. package/packages/server/src/auth/credential-envelope.ts +233 -0
  101. package/packages/server/src/auth/credential-key-worker.d.mts +16 -0
  102. package/packages/server/src/auth/credential-key-worker.mjs +108 -0
  103. package/packages/server/src/auth/credential-key.ts +479 -0
  104. package/packages/server/src/auth/credential-migration.ts +162 -0
  105. package/packages/server/src/auth/csp-report-paths.ts +26 -0
  106. package/packages/server/src/auth/csp-report-sink.ts +302 -0
  107. package/packages/server/src/auth/csp-report-store.ts +406 -0
  108. package/packages/server/src/auth/csp.ts +145 -11
  109. package/packages/server/src/auth/dashboard-credential-store.ts +4 -0
  110. package/packages/server/src/auth/dashboard-state-caller.ts +29 -0
  111. package/packages/server/src/auth/device-proof.ts +202 -0
  112. package/packages/server/src/auth/duplicate-cookie-gate.ts +271 -0
  113. package/packages/server/src/auth/host-admission.ts +7 -0
  114. package/packages/server/src/auth/host-gate.ts +13 -2
  115. package/packages/server/src/auth/local-proof-refusal-log.ts +89 -0
  116. package/packages/server/src/auth/local-proof.ts +69 -18
  117. package/packages/server/src/auth/localhost-guard.ts +98 -33
  118. package/packages/server/src/auth/locked-json-file.ts +68 -6
  119. package/packages/server/src/auth/models-json-store.ts +269 -0
  120. package/packages/server/src/auth/mutation-origin-gate.ts +5 -2
  121. package/packages/server/src/auth/nav-intent.ts +72 -0
  122. package/packages/server/src/auth/node-guard.ts +36 -49
  123. package/packages/server/src/auth/passkey/passkey-assets.ts +99 -0
  124. package/packages/server/src/auth/passkey/passkey-pages.ts +17 -81
  125. package/packages/server/src/auth/passkey/passkey-routes.ts +8 -0
  126. package/packages/server/src/auth/pi-legacy-credentials.ts +3 -0
  127. package/packages/server/src/auth/plugin-credential-store.ts +81 -10
  128. package/packages/server/src/auth/plugin-server-trust.ts +29 -0
  129. package/packages/server/src/auth/plugin-trust-store.ts +103 -0
  130. package/packages/server/src/auth/proven-tls.ts +45 -0
  131. package/packages/server/src/auth/provider-auth-storage.ts +214 -12
  132. package/packages/server/src/auth/provider-block-checks.ts +321 -0
  133. package/packages/server/src/auth/provider-host-detect.ts +151 -0
  134. package/packages/server/src/auth/provider-key-file.ts +71 -0
  135. package/packages/server/src/auth/provider-readiness.ts +91 -0
  136. package/packages/server/src/auth/radius-mcp.ts +1 -1
  137. package/packages/server/src/auth/request-principal.ts +32 -0
  138. package/packages/server/src/auth/route-tier-gate.ts +3 -2
  139. package/packages/server/src/auth/secret-rotation.ts +246 -0
  140. package/packages/server/src/auth/secure-origin.ts +56 -0
  141. package/packages/server/src/auth/serve-app-host.ts +111 -11
  142. package/packages/server/src/auth/vertex-key-check.ts +140 -0
  143. package/packages/server/src/auth/ws-ticket.ts +40 -2
  144. package/packages/server/src/auth/ws-upgrade-reject-log.ts +4 -1
  145. package/packages/server/src/browse.ts +73 -20
  146. package/packages/server/src/browser-handlers/acp-guard.ts +1 -4
  147. package/packages/server/src/browser-handlers/directory-handler.ts +34 -24
  148. package/packages/server/src/browser-handlers/folder-gate.ts +55 -0
  149. package/packages/server/src/browser-handlers/handler-context.ts +25 -2
  150. package/packages/server/src/browser-handlers/session-action-handler.ts +167 -63
  151. package/packages/server/src/browser-handlers/spawn-choice.ts +138 -1
  152. package/packages/server/src/browser-handlers/subscription-handler.ts +146 -3
  153. package/packages/server/src/browser-handlers/terminal-handler.ts +108 -10
  154. package/packages/server/src/build-plugin-send-prompt.ts +18 -0
  155. package/packages/server/src/canvas/canvas-accumulator.ts +35 -7
  156. package/packages/server/src/cli/credentials-command.ts +555 -0
  157. package/packages/server/src/cli.ts +229 -53
  158. package/packages/server/src/config-api.ts +53 -35
  159. package/packages/server/src/config-snapshot.ts +197 -1
  160. package/packages/server/src/directory-service.ts +193 -68
  161. package/packages/server/src/embed-lifecycle/idle-reaper.ts +13 -3
  162. package/packages/server/src/event-wiring.ts +322 -207
  163. package/packages/server/src/git-worktree/ensure-worktree.ts +185 -0
  164. package/packages/server/src/git-worktree/git-operations.ts +45 -11
  165. package/packages/server/src/git-worktree/redact-git-text.ts +124 -0
  166. package/packages/server/src/git-worktree/ref-arg.ts +39 -0
  167. package/packages/server/src/git-worktree/repo-lock.ts +42 -0
  168. package/packages/server/src/git-worktree/start-worktree-init.ts +151 -0
  169. package/packages/server/src/git-worktree/worktree-init-trust.ts +43 -1
  170. package/packages/server/src/git-worktree/worktree-init.ts +5 -1
  171. package/packages/server/src/identity/http-road-classification.ts +18 -2
  172. package/packages/server/src/identity/identity-floor.ts +5 -2
  173. package/packages/server/src/identity/ws-message-scope.ts +11 -3
  174. package/packages/server/src/identity/ws-road-classification.ts +3 -1
  175. package/packages/server/src/known-server-moves.ts +36 -15
  176. package/packages/server/src/lib/browse-roots.ts +129 -17
  177. package/packages/server/src/lib/client-dist.ts +36 -21
  178. package/packages/server/src/lib/content-disposition.ts +20 -0
  179. package/packages/server/src/lib/dashboard-state-guard.ts +513 -0
  180. package/packages/server/src/lib/diagram-render.ts +4 -6
  181. package/packages/server/src/lib/eml.ts +5 -10
  182. package/packages/server/src/lib/file-cwd-admission.ts +145 -0
  183. package/packages/server/src/lib/frame-policy-probe.ts +308 -0
  184. package/packages/server/src/lib/frame-policy-test-seam.ts +99 -0
  185. package/packages/server/src/lib/frame-policy-verdict.ts +125 -0
  186. package/packages/server/src/lib/grep-worker.ts +23 -0
  187. package/packages/server/src/lib/grep.ts +96 -7
  188. package/packages/server/src/lib/index-html.ts +81 -0
  189. package/packages/server/src/lib/mention-fuzzy-index.ts +263 -0
  190. package/packages/server/src/lib/office-preview.ts +49 -13
  191. package/packages/server/src/lib/path-containment.ts +50 -10
  192. package/packages/server/src/lib/resolve-file-mention.ts +234 -40
  193. package/packages/server/src/lib/resolve-mentions-batch.ts +143 -0
  194. package/packages/server/src/lib/route-admission.ts +80 -0
  195. package/packages/server/src/lib/writable-handler-target.ts +4 -0
  196. package/packages/server/src/lib/writable-md-target.ts +26 -0
  197. package/packages/server/src/lifecycle/boot-parent-liveness.ts +10 -25
  198. package/packages/server/src/lifecycle/credential-exit-barrier.ts +207 -0
  199. package/packages/server/src/lifecycle/exit-signal.ts +43 -0
  200. package/packages/server/src/lifecycle/recovery-server.ts +65 -18
  201. package/packages/server/src/live-server/capability-redact.ts +31 -0
  202. package/packages/server/src/live-server/live-browser-gate.ts +22 -0
  203. package/packages/server/src/live-server/live-capability.ts +615 -44
  204. package/packages/server/src/live-server/live-csp-report.ts +63 -0
  205. package/packages/server/src/live-server/live-csp.ts +141 -0
  206. package/packages/server/src/live-server/live-egress.ts +435 -0
  207. package/packages/server/src/live-server/live-exposure.ts +149 -0
  208. package/packages/server/src/live-server/live-log.ts +25 -0
  209. package/packages/server/src/live-server/live-origin-scan.ts +298 -0
  210. package/packages/server/src/live-server/live-server-manager.ts +220 -33
  211. package/packages/server/src/live-server/live-server-proxy.ts +411 -50
  212. package/packages/server/src/live-server/live-static.ts +231 -0
  213. package/packages/server/src/live-server/preview-dispatch.ts +286 -0
  214. package/packages/server/src/live-server/preview-observe.ts +53 -0
  215. package/packages/server/src/live-server/preview-origin.ts +182 -0
  216. package/packages/server/src/live-server/preview-path-bridge.ts +70 -0
  217. package/packages/server/src/live-server/preview-path-store.ts +420 -0
  218. package/packages/server/src/live-server/preview-path.ts +40 -0
  219. package/packages/server/src/live-server/preview-pool.ts +385 -0
  220. package/packages/server/src/live-server/preview-preflight.ts +41 -0
  221. package/packages/server/src/live-server/preview-reserve.ts +44 -0
  222. package/packages/server/src/live-server/preview-tier.ts +217 -0
  223. package/packages/server/src/live-server/preview-viewers.ts +54 -0
  224. package/packages/server/src/live-server/preview-ws-registry.ts +43 -0
  225. package/packages/server/src/model-proxy/custom-provider-discovery.ts +4 -2
  226. package/packages/server/src/model-proxy/internal-auth-storage.ts +5 -1
  227. package/packages/server/src/model-proxy/internal-registry.ts +283 -21
  228. package/packages/server/src/model-proxy/models-block-apply.ts +291 -0
  229. package/packages/server/src/model-proxy/pi-models-validator.ts +164 -0
  230. package/packages/server/src/model-proxy/registry-singleton.ts +44 -9
  231. package/packages/server/src/model-proxy/server-model-runtime.ts +17 -0
  232. package/packages/server/src/openspec/dependencies-file.ts +122 -0
  233. package/packages/server/src/openspec/openspec-change-watcher.ts +3 -1
  234. package/packages/server/src/openspec/openspec-dependency-inputs.ts +281 -0
  235. package/packages/server/src/openspec/openspec-poll-fs-helpers.ts +72 -26
  236. package/packages/server/src/openspec/openspec-poll-worker-pool.ts +48 -12
  237. package/packages/server/src/openspec/openspec-poll-worker.ts +95 -9
  238. package/packages/server/src/openspec/readiness.ts +1 -1
  239. package/packages/server/src/openspec/workflow-schema-status.ts +379 -0
  240. package/packages/server/src/openspec/workflow-schema.ts +141 -267
  241. package/packages/server/src/package/npm-search-proxy.ts +5 -2
  242. package/packages/server/src/package/provider-probe.ts +202 -7
  243. package/packages/server/src/pairing/browser-gateway.ts +325 -51
  244. package/packages/server/src/pairing/device-key-intake.ts +120 -0
  245. package/packages/server/src/pairing/device-token-services.ts +26 -0
  246. package/packages/server/src/pairing/paired-devices.ts +702 -27
  247. package/packages/server/src/pairing/pairing.ts +103 -11
  248. package/packages/server/src/pairing/{subagent-resync-routing.ts → resync-requester-registry.ts} +6 -10
  249. package/packages/server/src/pairing/socket-locality.ts +26 -0
  250. package/packages/server/src/pairing/ws-tier-gate.ts +74 -0
  251. package/packages/server/src/pending/pending-attach-registry.ts +15 -0
  252. package/packages/server/src/pending/pending-initial-prompt-registry.ts +15 -0
  253. package/packages/server/src/persistence/memory-event-store.ts +251 -296
  254. package/packages/server/src/persistence/preferences-store.ts +61 -2
  255. package/packages/server/src/pi/bridge-channel.ts +33 -0
  256. package/packages/server/src/pi/bridge-contention.ts +84 -2
  257. package/packages/server/src/pi/bridge-upgrade-auth.ts +18 -3
  258. package/packages/server/src/pi/gateway-listeners.ts +9 -3
  259. package/packages/server/src/pi/host-project-trust.ts +29 -15
  260. package/packages/server/src/pi/pi-gateway.ts +398 -41
  261. package/packages/server/src/pi/provisional-registration.ts +4 -1
  262. package/packages/server/src/pi/resource-toggle-trust.ts +18 -7
  263. package/packages/server/src/pi-agent-settings.ts +95 -301
  264. package/packages/server/src/pi-default-remirror.ts +89 -0
  265. package/packages/server/src/plugin-append-event.ts +35 -0
  266. package/packages/server/src/plugin-discovery-wiring.ts +142 -0
  267. package/packages/server/src/plugin-entry-stats.ts +61 -0
  268. package/packages/server/src/plugin-event-seam.ts +116 -4
  269. package/packages/server/src/plugin-local-request.ts +207 -0
  270. package/packages/server/src/plugin-ownership.ts +111 -0
  271. package/packages/server/src/plugin-policy-registry.ts +297 -0
  272. package/packages/server/src/plugin-request-lane.ts +92 -16
  273. package/packages/server/src/plugin-runtime-clients.ts +89 -0
  274. package/packages/server/src/preferences-relay.ts +20 -0
  275. package/packages/server/src/project-seed.ts +347 -0
  276. package/packages/server/src/push/push-transports/webhook-url.ts +8 -5
  277. package/packages/server/src/questions/question-store.ts +3 -2
  278. package/packages/server/src/routes/access-routes.ts +182 -15
  279. package/packages/server/src/routes/acme-routes.ts +14 -4
  280. package/packages/server/src/routes/agent-event-stream-routes.ts +137 -0
  281. package/packages/server/src/routes/canvas-types-routes.ts +20 -6
  282. package/packages/server/src/routes/csp-violations-routes.ts +162 -0
  283. package/packages/server/src/routes/file-routes.ts +640 -279
  284. package/packages/server/src/routes/file-write-binary-routes.ts +97 -24
  285. package/packages/server/src/routes/folder-project-routes.ts +18 -12
  286. package/packages/server/src/routes/frame-policy-routes.ts +215 -0
  287. package/packages/server/src/routes/git-routes.ts +340 -273
  288. package/packages/server/src/routes/grep-routes.ts +64 -14
  289. package/packages/server/src/routes/known-servers-routes.ts +189 -91
  290. package/packages/server/src/routes/live-server-routes.ts +572 -15
  291. package/packages/server/src/routes/local-proof-routes.ts +14 -0
  292. package/packages/server/src/routes/models-introspection-routes.ts +1 -1
  293. package/packages/server/src/routes/nav-intent-routes.ts +46 -0
  294. package/packages/server/src/routes/openspec-group-routes.ts +53 -44
  295. package/packages/server/src/routes/openspec-routes.ts +396 -31
  296. package/packages/server/src/routes/package-routes.ts +58 -10
  297. package/packages/server/src/routes/pairing-routes.ts +342 -17
  298. package/packages/server/src/routes/pi-settings-routes.ts +2 -0
  299. package/packages/server/src/routes/pi-trust-query-routes.ts +330 -0
  300. package/packages/server/src/routes/plugin-activation-routes.ts +59 -0
  301. package/packages/server/src/routes/plugin-runtime-client-routes.ts +149 -0
  302. package/packages/server/src/routes/preferences-auto-name-routes.ts +5 -2
  303. package/packages/server/src/routes/preferences-claude-compat-routes.ts +49 -0
  304. package/packages/server/src/routes/provider-auth-routes.ts +181 -10
  305. package/packages/server/src/routes/provider-override-routes.ts +158 -0
  306. package/packages/server/src/routes/provider-routes.ts +348 -86
  307. package/packages/server/src/routes/resource-activation-routes.ts +18 -4
  308. package/packages/server/src/routes/session-routes.ts +75 -25
  309. package/packages/server/src/routes/system-routes.ts +169 -52
  310. package/packages/server/src/routes/ui-link-base.ts +88 -0
  311. package/packages/server/src/rpc-keeper/keeper-manager.ts +196 -25
  312. package/packages/server/src/rpc-keeper/keeper.cjs +37 -23
  313. package/packages/server/src/runtime-overlay/extension-reload.ts +16 -10
  314. package/packages/server/src/runtime-overlay/runtime-io.ts +2 -9
  315. package/packages/server/src/runtime-overlay/runtime-stager.ts +4 -2
  316. package/packages/server/src/server.ts +1139 -291
  317. package/packages/server/src/services/cli-service.ts +59 -10
  318. package/packages/server/src/services/secrets-resolver.ts +46 -30
  319. package/packages/server/src/session/custom-event-group-annotation.ts +3 -3
  320. package/packages/server/src/session/custom-event-group-resolver.ts +10 -5
  321. package/packages/server/src/session/death-reason.ts +11 -7
  322. package/packages/server/src/session/event-status-extraction.ts +5 -1
  323. package/packages/server/src/session/hydration-state.ts +148 -0
  324. package/packages/server/src/session/memory-session-manager.ts +31 -2
  325. package/packages/server/src/session/open-tool-calls.ts +81 -47
  326. package/packages/server/src/session/pid-target.ts +127 -0
  327. package/packages/server/src/session/replay-compaction.ts +18 -5
  328. package/packages/server/src/session/replay-exit-controller.ts +221 -0
  329. package/packages/server/src/session/retained-transcript.ts +9 -2
  330. package/packages/server/src/session/seed-discovered-history.ts +85 -0
  331. package/packages/server/src/session/server-pid-context.ts +14 -0
  332. package/packages/server/src/session/session-api.ts +78 -29
  333. package/packages/server/src/session/session-archive.ts +7 -0
  334. package/packages/server/src/session/session-bootstrap.ts +9 -54
  335. package/packages/server/src/session/session-load-worker-pool.ts +11 -1
  336. package/packages/server/src/session/session-load-worker.ts +32 -4
  337. package/packages/server/src/spawn-process/abort-spawned-run.ts +28 -9
  338. package/packages/server/src/spawn-process/acp-spawn.ts +8 -2
  339. package/packages/server/src/spawn-process/headless-pid-registry.ts +393 -77
  340. package/packages/server/src/spawn-process/link-register.ts +42 -0
  341. package/packages/server/src/spawn-process/plugin-spawn-choice.ts +48 -0
  342. package/packages/server/src/spawn-process/plugin-spawn-worktree.ts +290 -0
  343. package/packages/server/src/spawn-process/process-classifier.ts +8 -3
  344. package/packages/server/src/spawn-process/process-manager.ts +61 -6
  345. package/packages/server/src/spawn-process/restored-identity.ts +112 -0
  346. package/packages/server/src/spawn-process/session-terminator.ts +179 -18
  347. package/packages/server/src/spawn-process/spawn-env-contributors.ts +2 -1
  348. package/packages/server/src/spawn-process/spawn-failure-log.ts +9 -0
  349. package/packages/server/src/spawn-process/spawn-register-watchdog.ts +44 -19
  350. package/packages/server/src/sudo-credential/relay.ts +337 -0
  351. package/packages/server/src/terminal/terminal-gateway.ts +10 -0
  352. package/packages/server/src/terminal/terminal-manager.ts +54 -46
  353. package/packages/server/src/tls/sources/acme/credentials.ts +3 -2
  354. package/packages/server/src/tls/sources/acme/runtime.ts +2 -1
  355. package/packages/server/src/tls/tls-bridge-route.ts +61 -0
  356. package/packages/server/src/tls/tls-config-validation.ts +2 -0
  357. package/packages/server/src/vault/device-expiry-sweep.ts +36 -0
  358. package/packages/server/src/vault/vault-delivery-hub.ts +172 -26
  359. package/packages/server/src/vault/vault-routes.ts +9 -2
  360. package/packages/server/src/vault/vault-store.ts +87 -24
  361. package/packages/server/src/watch-files-handler.ts +66 -0
  362. package/packages/server/vendor/xlsx/LICENSE +201 -0
  363. package/packages/server/vendor/xlsx/PROVENANCE.json +13 -0
  364. package/packages/server/vendor/xlsx/xlsx.d.mts +1065 -0
  365. package/packages/server/vendor/xlsx/xlsx.mjs +28228 -0
  366. package/packages/shared/package.json +4 -2
  367. package/packages/shared/src/agent-credential-files.ts +32 -0
  368. package/packages/shared/src/browser-protocol.ts +285 -59
  369. package/packages/shared/src/canvas-declare.ts +27 -0
  370. package/packages/shared/src/canvas-detect.ts +1 -1
  371. package/packages/shared/src/canvas-types.ts +2 -2
  372. package/packages/shared/src/config.ts +443 -187
  373. package/packages/shared/src/containment-guard.ts +45 -0
  374. package/packages/shared/src/credential-encryption.ts +87 -0
  375. package/packages/shared/src/custom-event-groups.ts +2 -0
  376. package/packages/shared/src/dashboard-plugin/claude-compat.ts +159 -0
  377. package/packages/shared/src/dashboard-plugin/event-type-owners.ts +50 -0
  378. package/packages/shared/src/dashboard-plugin/file-handler.ts +2 -0
  379. package/packages/shared/src/dashboard-plugin/host-api.ts +61 -0
  380. package/packages/shared/src/dashboard-plugin/host-fx-classes.ts +23 -0
  381. package/packages/shared/src/dashboard-plugin/host-import-map.ts +38 -0
  382. package/packages/shared/src/dashboard-plugin/index.ts +2 -0
  383. package/packages/shared/src/dashboard-plugin/manifest-types.ts +100 -1
  384. package/packages/shared/src/dashboard-plugin/plugin-status.ts +58 -3
  385. package/packages/shared/src/dashboard-plugin/replay-entry-types.ts +46 -0
  386. package/packages/shared/src/dashboard-plugin/slot-props.ts +47 -3
  387. package/packages/shared/src/dashboard-plugin/slot-types.ts +9 -1
  388. package/packages/shared/src/dashboard-plugin/ui-primitives.ts +39 -3
  389. package/packages/shared/src/device-key-proof.ts +309 -0
  390. package/packages/shared/src/display-prefs.ts +13 -0
  391. package/packages/shared/src/doctor-core.ts +94 -27
  392. package/packages/shared/src/event-forward-declaration.ts +85 -12
  393. package/packages/shared/src/forbidden-subjects.ts +126 -14
  394. package/packages/shared/src/heap-limits.ts +0 -30
  395. package/packages/shared/src/host-admission.ts +2 -1
  396. package/packages/shared/src/index.ts +7 -6
  397. package/packages/shared/src/live-server.ts +161 -0
  398. package/packages/shared/src/local-proof-signal.ts +16 -0
  399. package/packages/shared/src/loopback-host.ts +26 -0
  400. package/packages/shared/src/mcp/verb-tiers.generated.ts +176 -0
  401. package/packages/shared/src/mdns-discovery.ts +25 -6
  402. package/packages/shared/src/models-json-reader.ts +41 -0
  403. package/packages/shared/src/nav-intent.ts +29 -0
  404. package/packages/shared/src/network-denial-signal.ts +15 -0
  405. package/packages/shared/src/node-version.ts +63 -60
  406. package/packages/shared/src/openspec-dependencies.ts +760 -0
  407. package/packages/shared/src/openspec-poller.ts +3 -2
  408. package/packages/shared/src/pairing-knock-client.ts +135 -11
  409. package/packages/shared/src/pi-agent-settings-lock.ts +311 -0
  410. package/packages/shared/src/pi-path-compare.ts +31 -0
  411. package/packages/shared/src/pi-settings-schema.ts +52 -9
  412. package/packages/shared/src/pi-trust-live-query.ts +93 -0
  413. package/packages/shared/src/pi-trust-mirror-snapshot.ts +21 -11
  414. package/packages/shared/src/pi-trust-mirror-types.ts +38 -3
  415. package/packages/shared/src/pi-trust-mirror.ts +47 -11
  416. package/packages/shared/src/pi-trust-resource-digest.ts +261 -0
  417. package/packages/shared/src/pid-namespace.ts +86 -0
  418. package/packages/shared/src/platform/ensure-bundled-git.ts +57 -34
  419. package/packages/shared/src/platform/git-source.ts +88 -26
  420. package/packages/shared/src/platform/git.ts +14 -8
  421. package/packages/shared/src/platform/native-ts-register.mjs +1 -1
  422. package/packages/shared/src/platform/process.ts +452 -5
  423. package/packages/shared/src/platform/resolve-pi-shell.ts +105 -0
  424. package/packages/shared/src/platform/select-git-source.ts +7 -0
  425. package/packages/shared/src/platform/spawn-runtime.ts +193 -7
  426. package/packages/shared/src/plugin-route-cwd.ts +95 -0
  427. package/packages/shared/src/preview-egress.ts +192 -0
  428. package/packages/shared/src/preview-origins.ts +398 -0
  429. package/packages/shared/src/project-root.ts +16 -0
  430. package/packages/shared/src/prompt-answer.ts +9 -5
  431. package/packages/shared/src/protocol.ts +187 -86
  432. package/packages/shared/src/provider-env-catalog.ts +413 -0
  433. package/packages/shared/src/provider-overrides.ts +112 -0
  434. package/packages/shared/src/question-types.ts +6 -0
  435. package/packages/shared/src/recommended-extensions.ts +97 -26
  436. package/packages/shared/src/recovery-timing.ts +27 -0
  437. package/packages/shared/src/remote-credentials.ts +63 -0
  438. package/packages/shared/src/renderer-by-ext.ts +5 -2
  439. package/packages/shared/src/rest-api.ts +148 -11
  440. package/packages/shared/src/role-schema.ts +24 -0
  441. package/packages/shared/src/route-tiers.ts +149 -4
  442. package/packages/shared/src/runtime-overlay/archive-safety.d.mts +2 -0
  443. package/packages/shared/src/runtime-overlay/archive-safety.mjs +33 -0
  444. package/packages/shared/src/runtime-overlay/compat.ts +70 -6
  445. package/packages/shared/src/runtime-overlay/manifest.d.mts +7 -0
  446. package/packages/shared/src/runtime-overlay/manifest.mjs +22 -2
  447. package/packages/shared/src/safe-local-path.ts +24 -0
  448. package/packages/shared/src/sanitize-profiles.ts +98 -0
  449. package/packages/shared/src/secret-patterns.ts +49 -0
  450. package/packages/shared/src/server-launcher.ts +9 -1
  451. package/packages/shared/src/server-pinning.ts +55 -2
  452. package/packages/shared/src/server-routes.ts +462 -0
  453. package/packages/shared/src/session-ui-path.ts +11 -0
  454. package/packages/shared/src/source-matching.ts +2 -2
  455. package/packages/shared/src/state-replay.ts +40 -24
  456. package/packages/shared/src/sudo-credential.ts +71 -0
  457. package/packages/shared/src/tls-only-token.ts +16 -0
  458. package/packages/shared/src/tool-path-resolve.ts +16 -1
  459. package/packages/shared/src/tool-registry/definitions.ts +5 -5
  460. package/packages/shared/src/tool-registry/strategies.ts +13 -12
  461. package/packages/shared/src/tool-workdir.ts +56 -0
  462. package/packages/shared/src/trusted-types-mode.ts +72 -0
  463. package/packages/shared/src/types.ts +134 -109
  464. package/packages/shared/src/url-policy.ts +96 -0
  465. package/packages/shared/src/vault-delivery.ts +15 -0
  466. package/packages/shared/src/vertex-regions.ts +81 -0
  467. package/packages/shared/src/ws-message-tiers.ts +11 -3
  468. package/packages/extension/src/subagent-fanout-admission.ts +0 -234
  469. package/packages/extension/src/subagent-forward-sites.ts +0 -69
  470. package/packages/extension/src/subagent-frame-buffer.ts +0 -245
  471. package/packages/extension/src/subagent-frame-strip.ts +0 -109
  472. package/packages/extension/src/subagent-saturation.ts +0 -196
  473. package/packages/extension/src/subagent-tick-throttle.ts +0 -252
  474. package/packages/shared/src/anthropic-messages-source.ts +0 -8
@@ -4,9 +4,18 @@
4
4
 
5
5
  import fs from "node:fs";
6
6
  import { join } from "node:path";
7
+ import {
8
+ ADMISSION_DEADLINE_MS,
9
+ type AdmissionToken,
10
+ type AdmitCwdOptions,
11
+ admissionAllows,
12
+ releaseAdmission,
13
+ } from "@blackbelt-technology/pi-dashboard-shared/cwd-guard.js";
14
+ import { checkoutRoots } from "@blackbelt-technology/pi-dashboard-shared/platform/git.js";
7
15
  import { getDefaultRegistry } from "@blackbelt-technology/pi-dashboard-shared/tool-registry/index.js";
8
16
  import type { ApiResponse } from "@blackbelt-technology/pi-dashboard-shared/types.js";
9
- import type { FastifyInstance } from "fastify";
17
+ import type { FastifyInstance, FastifyReply } from "fastify";
18
+ import { getPiTrustMirror } from "../access/pi-trust-mirror-service.js";
10
19
  import {
11
20
  addWorktree,
12
21
  addWorktreeFromPr,
@@ -34,12 +43,14 @@ import {
34
43
  type WorktreeRemovalVerdict,
35
44
  worktreeDiffStat,
36
45
  } from "../git-worktree/git-operations.js";
37
- import { checkoutRoots } from "@blackbelt-technology/pi-dashboard-shared/platform/git.js";
38
- import { evaluateGate, type GateResult, hookDefHash, type InitProgress, readInitHook, runInitHook, type WorktreeInitHook } from "../git-worktree/worktree-init.js";
39
- import { mapInitStderrToHint } from "../git-worktree/worktree-init-errors.js";
46
+ import { hookDefHash, readInitHook } from "../git-worktree/worktree-init.js";
47
+ import { gitErrorText, redactGitText } from "../git-worktree/redact-git-text.js";
48
+ import { INVALID_REF_CODE, InvalidRefError, isMissingArg, isValidRefArg } from "../git-worktree/ref-arg.js";
49
+ import { repoLockKey, withRepoLock } from "../git-worktree/repo-lock.js";
50
+ import { evaluateGateCached, startWorktreeInit } from "../git-worktree/start-worktree-init.js";
40
51
  import type { WorktreeInitRegistry } from "../git-worktree/worktree-init-registry.js";
41
- import { getPiTrustMirror } from "../access/pi-trust-mirror-service.js";
42
52
  import { isTrusted, recordTrust } from "../git-worktree/worktree-init-trust.js";
53
+ import { admitRouteCwd, sendAdmissionUnavailable } from "../lib/route-admission.js";
43
54
  import type { BrowserGateway } from "../pairing/browser-gateway.js";
44
55
  import { safeRealpathSync } from "../resolve-path.js";
45
56
  import { activeSessionsUnder, activeSessionsUnderResolved, sessionsUnder } from "../session/active-sessions-in-cwd.js";
@@ -72,16 +83,46 @@ export interface GitRoutesDeps {
72
83
  * the final result either way). See change: generalize-worktree-init-hook.
73
84
  */
74
85
  worktreeInitRegistry?: WorktreeInitRegistry;
86
+ /**
87
+ * Live known-folder set (session cwds ∪ pinned directories) every `cwd` is admitted
88
+ * against. Absent → nothing is known (fail closed). See change: core-cwd-admission.
89
+ */
90
+ knownCwds?: () => string[];
91
+ /** `admitCwd` options: the host's throttled `onIndeterminate` logger + test seams. */
92
+ admitOptions?: AdmitCwdOptions;
93
+ /** Test seam: whole-`remove-batch` admission budget in ms (default 10 000). */
94
+ removeBatchAdmissionBudgetMs?: number;
75
95
  }
76
96
 
97
+ /** Admission result of one git-route `cwd`: the canonical cwd to operate on, or the reply body. */
98
+ type GitCwdCheck =
99
+ | { ok: true; cwd: string; token: AdmissionToken }
100
+ | { ok: false; body: ApiResponse; code: string };
101
+
77
102
  /**
78
- * Per-resolved-checkout cache of the gate result, with a short TTL.
79
- * Invalidated when a hook run starts/exits for that checkout.
80
- * See change: generalize-worktree-init-hook.
103
+ * B20: redact git-derived text against the root the operation ran in. `root` is captured by the
104
+ * caller at operation time (a `const`), never read at broadcast time.
105
+ * See change: harden-git-terminal-plugin-boundaries.
81
106
  */
82
- const GATE_CACHE_TTL_MS = 30 * 1000;
83
- const gateCache = new Map<string, { needsInit: boolean; evaluatedAt: number }>();
84
- function invalidateGateCache(checkoutPath: string) { gateCache.delete(checkoutPath); }
107
+ const redact = (text: unknown, root?: string): string => redactGitText(text, { root });
108
+ /** Redacted `err.message` (or a thrown string), falling back to `fallback`. */
109
+ const redactErr = (err: unknown, fallback: string, root?: string): string => redact(gitErrorText(err) || fallback, root);
110
+
111
+ /** B1r: the 400 `invalid_ref` envelope (no git process has started). */
112
+ function invalidRef(reply: FastifyReply, what: string): ApiResponse {
113
+ reply.code(400);
114
+ return { success: false, code: INVALID_REF_CODE, error: `invalid ${what}` };
115
+ }
116
+ /** A PRESENT optional ref/path field (absent/null/"" = not supplied) that fails validation. */
117
+ const presentInvalid = (v: unknown): boolean => !isMissingArg(v) && !isValidRefArg(v);
118
+
119
+ /** Whole-batch admission budget for `remove-batch` (design D1). */
120
+ const REMOVE_BATCH_ADMISSION_BUDGET_MS = 10_000;
121
+ /** A runner that never completes a probe: only a direct known-folder match can be admitted with it. */
122
+ const NO_DERIVATION_RUNNER: NonNullable<AdmitCwdOptions["runner"]> = async () => ({
123
+ ok: false,
124
+ error: { kind: "spawn-failure", message: "admission budget exhausted" },
125
+ });
85
126
 
86
127
  /**
87
128
  * Per-artifact setup checklist for the init-status probe (change:
@@ -119,27 +160,6 @@ function buildSetupChecklist(configRoot: string | null): SetupArtifact[] | undef
119
160
  }
120
161
  }
121
162
 
122
- /**
123
- * Last non-empty line of the progress tail, for the ghost preview. The tail is
124
- * the most recent <= 4KB of combined output; the chip shows only its final line.
125
- * See change: friendlier-worktree-init.
126
- */
127
- function lastLineOf(tail: string): string {
128
- const lines = tail.split(/\r?\n/);
129
- for (let i = lines.length - 1; i >= 0; i--) {
130
- const line = lines[i]?.trim();
131
- if (line) return line;
132
- }
133
- return "";
134
- }
135
- async function evaluateGateCached(checkoutPath: string, hook: WorktreeInitHook): Promise<GateResult> {
136
- const hit = gateCache.get(checkoutPath);
137
- if (hit && Date.now() - hit.evaluatedAt < GATE_CACHE_TTL_MS) return { needsInit: hit.needsInit };
138
- const res = await evaluateGate(checkoutPath, hook);
139
- gateCache.set(checkoutPath, { needsInit: res.needsInit, evaluatedAt: Date.now() });
140
- return res;
141
- }
142
-
143
163
  /**
144
164
  * Defensive clamp for the configured batch cap (D8). `DashboardConfig`
145
165
  * parsing already clamps (`clampRemoveBatchCap` in shared config), so a value
@@ -158,6 +178,70 @@ function resolveBatchCap(v: unknown): number {
158
178
  export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps) {
159
179
  const { networkGuard, sessionManager, browserGateway, worktreeInitRegistry, sendToSession, commitDraftRelay, removeBatchCap: configuredRemoveBatchCap } = deps;
160
180
  const removeBatchCap = resolveBatchCap(configuredRemoveBatchCap);
181
+
182
+ /**
183
+ * Admit a request `cwd` (design D1): `admitRouteCwd`, then branch on
184
+ * `admissionAllows(admission, cwd)` HERE, on the unmodified request value, so static
185
+ * analysis keeps its modelled barrier. Returns the CANONICAL cwd — git runs on the
186
+ * realpath, so a later swap of the raw path cannot redirect the operation. The token is
187
+ * released when the response closes (success, error, throw or disconnect).
188
+ * No filesystem call touches the raw value outside the guard.
189
+ * See change: core-cwd-admission.
190
+ */
191
+ async function admitGitCwd(
192
+ raw: string,
193
+ reply: FastifyReply,
194
+ admitOptions: AdmitCwdOptions | undefined = deps.admitOptions,
195
+ ): Promise<GitCwdCheck> {
196
+ const admission = await admitRouteCwd(raw, { knownCwds: deps.knownCwds, admitOptions });
197
+ if (admission.kind === "indeterminate") {
198
+ return { ok: false, body: sendAdmissionUnavailable(reply), code: "cwd-admission-unavailable" };
199
+ }
200
+ if (admission.kind !== "admit" || !admissionAllows(admission, raw)) {
201
+ reply.code(400);
202
+ return {
203
+ ok: false,
204
+ code: "cwd_unknown",
205
+ body: {
206
+ success: false,
207
+ code: "cwd_unknown",
208
+ error: "cwd is not a known folder; pin the repository to allow git operations",
209
+ } satisfies ApiResponse,
210
+ };
211
+ }
212
+ const token = admission.token;
213
+ reply.raw.once("close", () => releaseAdmission(token));
214
+ // The client may have gone while admission ran (`close` already fired): release at once.
215
+ if (reply.raw.destroyed) releaseAdmission(token);
216
+ return { ok: true, cwd: token.canonCwd, token };
217
+ }
218
+
219
+ /**
220
+ * `admitGitCwd` plus the presence and directory checks of the worktree endpoints
221
+ * (`cwd_invalid`: `cwd required` / `cwd does not exist` / `cwd is not a directory`),
222
+ * the latter two only for an ADMITTED cwd. See change: add-worktree-spawn-dialog,
223
+ * core-cwd-admission.
224
+ */
225
+ async function validateCwd(raw: string | undefined, reply: FastifyReply): Promise<GitCwdCheck> {
226
+ if (!raw || typeof raw !== "string") {
227
+ reply.code(400);
228
+ return { ok: false, code: "cwd_invalid", body: { success: false, code: "cwd_invalid", error: "cwd required" } satisfies ApiResponse };
229
+ }
230
+ const admitted = await admitGitCwd(raw, reply);
231
+ if (!admitted.ok) return admitted;
232
+ const invalid = (error: string): GitCwdCheck => {
233
+ releaseAdmission(admitted.token);
234
+ reply.code(400);
235
+ return { ok: false, code: "cwd_invalid", body: { success: false, code: "cwd_invalid", error } satisfies ApiResponse };
236
+ };
237
+ try {
238
+ const stat = await fs.promises.stat(admitted.cwd);
239
+ if (!stat.isDirectory()) return invalid("cwd is not a directory");
240
+ } catch {
241
+ return invalid("cwd does not exist");
242
+ }
243
+ return admitted;
244
+ }
161
245
  /**
162
246
  * After a successful worktree Push / Open PR, force a PR-status probe on
163
247
  * every bridge whose session cwd is the worktree or inside it (realpath-
@@ -179,36 +263,44 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
179
263
  reply.code(400);
180
264
  return { success: false, code: "cwd_required", error: "cwd parameter required" } satisfies ApiResponse;
181
265
  }
182
- if (!isGitRepo(cwd)) {
266
+ const admitted = await admitGitCwd(cwd, reply);
267
+ if (!admitted.ok) return admitted.body;
268
+ if (!isGitRepo(admitted.cwd)) {
183
269
  return { success: false, code: "not_a_repo", error: "not a git repository" } satisfies ApiResponse;
184
270
  }
185
271
  try {
186
- const data = listBranches(cwd);
272
+ const data = listBranches(admitted.cwd);
187
273
  return { success: true, data } satisfies ApiResponse;
188
274
  } catch (err: any) {
189
- return { success: false, code: "list_branches_failed", error: err.message ?? "failed to list branches" } satisfies ApiResponse;
275
+ return { success: false, code: "list_branches_failed", error: redactErr(err, "failed to list branches", admitted.cwd) } satisfies ApiResponse;
190
276
  }
191
277
  },
192
278
  );
193
279
 
194
- fastify.post<{ Body: { cwd?: string; branch?: string; stash?: boolean } }>(
280
+ fastify.post<{ Body: { cwd?: string; branch?: unknown; stash?: boolean } }>(
195
281
  "/api/git/checkout",
196
282
  { preHandler: networkGuard },
197
283
  async (request, reply) => {
198
284
  const { cwd, branch, stash } = request.body ?? {};
199
- if (!cwd || !branch) {
285
+ // Missing (absent / null / "") keeps the existing code; a PRESENT invalid ref is `invalid_ref`
286
+ // (B1r) — checked before admission so nothing (not even a probe) runs for it.
287
+ if (!cwd || isMissingArg(branch)) {
200
288
  reply.code(400);
201
289
  return { success: false, code: "cwd_and_branch_required", error: "cwd and branch required" } satisfies ApiResponse;
202
290
  }
291
+ if (!isValidRefArg(branch)) return invalidRef(reply, "branch");
292
+ const admitted = await admitGitCwd(cwd, reply);
293
+ if (!admitted.ok) return admitted.body;
203
294
  try {
204
- const result = checkoutBranch(cwd, branch, stash ?? false);
295
+ const result = checkoutBranch(admitted.cwd, branch, stash ?? false);
205
296
  if (!result.success) {
206
297
  reply.code(409);
207
298
  return result;
208
299
  }
209
300
  return { success: true, data: { stashed: result.stashed } } satisfies ApiResponse;
210
301
  } catch (err: any) {
211
- return { success: false, code: "checkout_failed", error: err.message ?? "checkout failed" } satisfies ApiResponse;
302
+ if (err instanceof InvalidRefError) return invalidRef(reply, "branch");
303
+ return { success: false, code: "checkout_failed", error: redactErr(err, "checkout failed", admitted.cwd) } satisfies ApiResponse;
212
304
  }
213
305
  },
214
306
  );
@@ -222,11 +314,13 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
222
314
  reply.code(400);
223
315
  return { success: false, code: "cwd_required", error: "cwd required" } satisfies ApiResponse;
224
316
  }
317
+ const admitted = await admitGitCwd(cwd, reply);
318
+ if (!admitted.ok) return admitted.body;
225
319
  try {
226
- gitInit(cwd);
320
+ gitInit(admitted.cwd);
227
321
  return { success: true } satisfies ApiResponse;
228
322
  } catch (err: any) {
229
- return { success: false, code: "git_init_failed", error: err.message ?? "init failed" } satisfies ApiResponse;
323
+ return { success: false, code: "git_init_failed", error: redactErr(err, "init failed", admitted.cwd) } satisfies ApiResponse;
230
324
  }
231
325
  },
232
326
  );
@@ -239,11 +333,8 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
239
333
  "/api/git/status",
240
334
  { preHandler: networkGuard },
241
335
  async (request, reply) => {
242
- const validated = validateCwd(request.query.cwd);
243
- if (!validated.ok) {
244
- reply.code(400);
245
- return { success: false, code: validated.code, error: validated.message } satisfies ApiResponse;
246
- }
336
+ const validated = await validateCwd(request.query.cwd, reply);
337
+ if (!validated.ok) return validated.body;
247
338
  if (!isGitRepo(validated.cwd)) {
248
339
  return { success: false, code: "not_a_repo", error: "not a git repository" } satisfies ApiResponse;
249
340
  }
@@ -260,11 +351,8 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
260
351
  "/api/git/changed-files",
261
352
  { preHandler: networkGuard },
262
353
  async (request, reply) => {
263
- const validated = validateCwd(request.query.cwd);
264
- if (!validated.ok) {
265
- reply.code(400);
266
- return { success: false, code: validated.code, error: validated.message } satisfies ApiResponse;
267
- }
354
+ const validated = await validateCwd(request.query.cwd, reply);
355
+ if (!validated.ok) return validated.body;
268
356
  if (!isGitRepo(validated.cwd)) {
269
357
  return { success: false, code: "not_a_repo", error: "not a git repository" } satisfies ApiResponse;
270
358
  }
@@ -272,7 +360,7 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
272
360
  const files = await getChangedFiles(validated.cwd);
273
361
  return { success: true, data: files } satisfies ApiResponse;
274
362
  } catch (err: any) {
275
- return { success: false, code: "git_failed", error: err?.message ?? "failed to list changed files" } satisfies ApiResponse;
363
+ return { success: false, code: "git_failed", error: redactErr(err, "failed to list changed files", validated.cwd) } satisfies ApiResponse;
276
364
  }
277
365
  },
278
366
  );
@@ -285,11 +373,8 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
285
373
  { preHandler: networkGuard },
286
374
  async (request, reply) => {
287
375
  const { cwd, message, files } = request.body ?? {};
288
- const validated = validateCwd(cwd);
289
- if (!validated.ok) {
290
- reply.code(400);
291
- return { success: false, code: validated.code, error: validated.message } satisfies ApiResponse;
292
- }
376
+ const validated = await validateCwd(cwd, reply);
377
+ if (!validated.ok) return validated.body;
293
378
  if (typeof message !== "string" || !Array.isArray(files)) {
294
379
  reply.code(400);
295
380
  return { success: false, code: "bad_request", error: "message and files[] required" } satisfies ApiResponse;
@@ -312,9 +397,9 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
312
397
  } catch (err: any) {
313
398
  if (err instanceof GitCommitError) {
314
399
  reply.code(err.code === "path-escape" || err.code === "no-files" || err.code === "empty-message" ? 400 : 409);
315
- return { success: false, code: err.code, error: err.message } satisfies ApiResponse;
400
+ return { success: false, code: err.code, error: redact(err.message, validated.cwd) } satisfies ApiResponse;
316
401
  }
317
- return { success: false, code: "commit-failed", error: err?.message ?? "commit failed" } satisfies ApiResponse;
402
+ return { success: false, code: "commit-failed", error: redactErr(err, "commit failed", validated.cwd) } satisfies ApiResponse;
318
403
  }
319
404
  },
320
405
  );
@@ -326,11 +411,8 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
326
411
  { preHandler: networkGuard },
327
412
  async (request, reply) => {
328
413
  const { cwd, files, sessionId } = request.body ?? {};
329
- const validated = validateCwd(cwd);
330
- if (!validated.ok) {
331
- reply.code(400);
332
- return { success: false, code: validated.code, error: validated.message } satisfies ApiResponse;
333
- }
414
+ const validated = await validateCwd(cwd, reply);
415
+ if (!validated.ok) return validated.body;
334
416
  // Every file must be a non-empty string (the diff is built per path).
335
417
  if (
336
418
  !Array.isArray(files) ||
@@ -372,11 +454,8 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
372
454
  "/api/git/head",
373
455
  { preHandler: networkGuard },
374
456
  async (request, reply) => {
375
- const validated = validateCwd(request.query.cwd);
376
- if (!validated.ok) {
377
- reply.code(400);
378
- return { success: false, code: validated.code, error: validated.message } satisfies ApiResponse;
379
- }
457
+ const validated = await validateCwd(request.query.cwd, reply);
458
+ if (!validated.ok) return validated.body;
380
459
  if (!isGitRepo(validated.cwd)) {
381
460
  return { success: false, code: "not_a_repo", error: "not a git repository" } satisfies ApiResponse;
382
461
  }
@@ -384,7 +463,7 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
384
463
  const head = readHead(validated.cwd);
385
464
  return { success: true, data: head } satisfies ApiResponse;
386
465
  } catch (err: any) {
387
- return { success: false, code: "git_failed", error: err?.message ?? "failed to read HEAD" } satisfies ApiResponse;
466
+ return { success: false, code: "git_failed", error: redactErr(err, "failed to read HEAD", validated.cwd) } satisfies ApiResponse;
388
467
  }
389
468
  },
390
469
  );
@@ -393,11 +472,8 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
393
472
  "/api/git/worktrees",
394
473
  { preHandler: networkGuard },
395
474
  async (request, reply) => {
396
- const validated = validateCwd(request.query.cwd);
397
- if (!validated.ok) {
398
- reply.code(400);
399
- return { success: false, code: validated.code, error: validated.message } satisfies ApiResponse;
400
- }
475
+ const validated = await validateCwd(request.query.cwd, reply);
476
+ if (!validated.ok) return validated.body;
401
477
  if (!isGitRepo(validated.cwd)) {
402
478
  return { success: false, code: "not_a_repo", error: "not a git repository" } satisfies ApiResponse;
403
479
  }
@@ -405,7 +481,7 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
405
481
  const worktrees = listWorktrees(validated.cwd);
406
482
  return { success: true, data: { worktrees } } satisfies ApiResponse;
407
483
  } catch (err: any) {
408
- return { success: false, code: "git_failed", error: err?.message ?? "failed to list worktrees" } satisfies ApiResponse;
484
+ return { success: false, code: "git_failed", error: redactErr(err, "failed to list worktrees", validated.cwd) } satisfies ApiResponse;
409
485
  }
410
486
  },
411
487
  );
@@ -418,11 +494,8 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
418
494
  "/api/git/worktree/init-status",
419
495
  { preHandler: networkGuard },
420
496
  async (request, reply) => {
421
- const validated = validateCwd(request.query.cwd);
422
- if (!validated.ok) {
423
- reply.code(400);
424
- return { success: false, code: validated.code, error: validated.message } satisfies ApiResponse;
425
- }
497
+ const validated = await validateCwd(request.query.cwd, reply);
498
+ if (!validated.ok) return validated.body;
426
499
  // Config root without a git assumption: a non-git dir with
427
500
  // `.pi/settings.json` resolves to itself so its declared hook is read.
428
501
  // See change: support-non-git-init-hook.
@@ -492,11 +565,8 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
492
565
  });
493
566
  }
494
567
  const body = request.body ?? {};
495
- const validated = validateCwd(body.cwd);
496
- if (!validated.ok) {
497
- reply.code(400);
498
- return { success: false, code: validated.code, error: validated.message } satisfies ApiResponse;
499
- }
568
+ const validated = await validateCwd(body.cwd, reply);
569
+ if (!validated.ok) return validated.body;
500
570
  // Config root without a git assumption; a `null` root means an
501
571
  // unconfigured non-git dir — reuse the existing no-hook envelope, not
502
572
  // `not_a_repo`. See change: support-non-git-init-hook.
@@ -530,60 +600,46 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
530
600
  );
531
601
  } catch (err) {
532
602
  reply.code(500);
533
- return { success: false, code: "trust_not_recorded", error: `trust not recorded: ${(err as Error)?.message ?? String(err)}` } satisfies ApiResponse;
603
+ return { success: false, code: "trust_not_recorded", error: `trust not recorded: ${redactErr(err, String(err), configRoot)}` } satisfies ApiResponse;
534
604
  }
535
605
  } else {
606
+ // "Until the dashboard restarts": the "also trust in pi" choice is held in
607
+ // memory with the entry and never written. See change: mirror-dashboard-trust-live-remote.
608
+ if (scope === "session" && typeof body.piTrust === "boolean") {
609
+ getPiTrustMirror()?.live?.setChoice("worktreeInit", configRoot, body.piTrust);
610
+ }
536
611
  recordTrust(configRoot, hash, scope);
537
612
  }
538
613
  }
539
- if (!isTrusted(configRoot, hash)) {
540
- // Echo the hash so the client confirms with `confirmHash` without
541
- // re-implementing the canonical hash. See change: generalize-worktree-init-hook.
542
- return { success: false, code: "init_untrusted", data: { hook, hash } } satisfies ApiResponse;
543
- }
544
- // Re-trust case: the hook was edited (invalidating trust) but the gate is
545
- // already satisfied (`needsInit === false`). Granting trust should clear
546
- // the control WITHOUT re-running the hook. See change:
547
- // friendlier-worktree-init (folder-action-bar spec).
548
- const preGate = await evaluateGateCached(validated.cwd, hook);
549
- if (!preGate.needsInit) {
550
- return { success: true, data: { ran: false, skippedReason: "already_initialized" } } satisfies ApiResponse;
551
- }
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).
552
617
  const requestId = typeof body.requestId === "string" && body.requestId.length > 0 ? body.requestId : undefined;
553
- const cwd = validated.cwd;
554
- // Fan out to the legacy per-click requestId subscriber (if any) AND to
555
- // every cwd-keyed subscriber (refresh / second tab / auto-init).
556
- // See change: friendlier-worktree-init.
557
- const sendIf = (msg: any) => {
558
- if (worktreeInitRegistry) {
559
- if (requestId) worktreeInitRegistry.send(requestId, msg);
560
- worktreeInitRegistry.sendCwd(cwd, msg);
561
- }
562
- };
563
- worktreeInitRegistry?.startRun(cwd);
564
- const onProgress = (p: InitProgress) => {
565
- worktreeInitRegistry?.progressRun(cwd, lastLineOf(p.line), p.line);
566
- sendIf({ type: "worktree_init_progress", requestId: requestId ?? "", cwd, line: p.line });
567
- };
568
- invalidateGateCache(cwd);
569
- const runResult = await runInitHook(cwd, hook, onProgress);
570
- invalidateGateCache(cwd);
571
- if (runResult.ok) {
572
- worktreeInitRegistry?.finishRun(cwd, "done");
573
- sendIf({ type: "worktree_init_done", requestId: requestId ?? "", cwd, durationMs: runResult.durationMs });
574
- 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;
575
637
  }
576
- const stderr = runResult.stderr ?? "";
577
- const hint = mapInitStderrToHint(stderr) ?? `init failed (${runResult.code ?? "unknown"})`;
578
- worktreeInitRegistry?.finishRun(cwd, "failed", runResult.code ?? "init_failed");
579
- sendIf({ type: "worktree_init_failed", requestId: requestId ?? "", cwd, code: runResult.code ?? "init_failed", message: hint, stderr });
580
- reply.code(500);
581
- return { success: false, code: "init_failed", error: hint, stderr } satisfies ApiResponse;
582
638
  },
583
639
  );
584
640
 
585
641
  fastify.post<{
586
- Body: { cwd?: string; base?: string; newBranch?: string; path?: string; force?: boolean };
642
+ Body: { cwd?: string; base?: unknown; newBranch?: unknown; path?: unknown; force?: boolean };
587
643
  }>(
588
644
  "/api/git/worktree",
589
645
  { preHandler: networkGuard },
@@ -593,42 +649,43 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
593
649
  // worktree-init hook (GET /init-status + POST /init). See change:
594
650
  // generalize-worktree-init-hook.
595
651
  const body = request.body ?? {};
596
- const validated = validateCwd(body.cwd);
597
- if (!validated.ok) {
598
- reply.code(400);
599
- return { success: false, code: validated.code, error: validated.message } satisfies ApiResponse;
600
- }
601
- if (!body.base || typeof body.base !== "string") {
652
+ // B1r: every PRESENT ref / branch / path is validated before admission or git. `base` absent /
653
+ // null / "" keeps the existing `cwd_invalid` envelope below; `newBranch` absent = checkout mode
654
+ // (a present `null` / "" / non-string is invalid); `path` absent / null / "" = default path.
655
+ // See change: harden-git-terminal-plugin-boundaries.
656
+ if (presentInvalid(body.base)) return invalidRef(reply, "base");
657
+ if (body.newBranch !== undefined && !isValidRefArg(body.newBranch)) return invalidRef(reply, "newBranch");
658
+ if (presentInvalid(body.path)) return invalidRef(reply, "path");
659
+ const validated = await validateCwd(body.cwd, reply);
660
+ if (!validated.ok) return validated.body;
661
+ if (!isValidRefArg(body.base)) {
602
662
  reply.code(400);
603
663
  return { success: false, code: "cwd_invalid", error: "base required" } satisfies ApiResponse;
604
664
  }
605
- // `newBranch` is optional. When present it must be a string (fork
606
- // mode); when absent the server checks out the existing `base` ref
607
- // (checkout mode). See change: worktree-checkout-existing-branch.
608
- if (body.newBranch !== undefined && typeof body.newBranch !== "string") {
609
- reply.code(400);
610
- return { success: false, code: "cwd_invalid", error: "newBranch must be a string" } satisfies ApiResponse;
611
- }
612
- const result = addWorktree({
665
+ // `newBranch` is optional: present → fork mode; absent → the server checks out the existing
666
+ // `base` ref (checkout mode). See change: worktree-checkout-existing-branch.
667
+ // Serialized with plugin-spawn worktree creation for the same repository (design D4).
668
+ const addArgs = {
613
669
  cwd: validated.cwd,
614
670
  base: body.base,
615
- ...(body.newBranch !== undefined ? { newBranch: body.newBranch } : {}),
616
- path: body.path,
671
+ ...(body.newBranch !== undefined ? { newBranch: body.newBranch as string } : {}),
672
+ path: typeof body.path === "string" && body.path.length > 0 ? body.path : undefined,
617
673
  force: body.force === true,
618
- });
674
+ };
675
+ const result = await withRepoLock(repoLockKey(validated.cwd), () => addWorktree(addArgs));
619
676
  if (!result.ok) {
620
677
  const httpStatus =
621
678
  result.error === "branch_in_use" || result.error === "branch_exists" || result.error === "path_exists"
622
679
  ? 409
623
- : result.error === "not_a_repo" || result.error === "base_not_found"
680
+ : result.error === "not_a_repo" || result.error === "base_not_found" || result.error === "invalid_ref"
624
681
  ? 400
625
682
  : 500;
626
683
  reply.code(httpStatus);
627
684
  return {
628
685
  success: false,
629
686
  code: result.error,
630
- error: result.message,
631
- ...(result.stderr ? { stderr: result.stderr } : {}),
687
+ error: redact(result.message, validated.cwd),
688
+ ...(result.stderr ? { stderr: redact(result.stderr, validated.cwd) } : {}),
632
689
  ...(typeof result.orphanLikely === "boolean" ? { orphanLikely: result.orphanLikely } : {}),
633
690
  } satisfies ApiResponse;
634
691
  }
@@ -645,17 +702,16 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
645
702
  // Unblocks the worktree-spawn dialog when a previous failed attempt
646
703
  // left an orphan directory at the target path. Conservative refuse
647
704
  // rules — see `orphanCleanup` in `git-operations.ts`.
648
- fastify.post<{ Body: { cwd?: string; path?: string } }>(
705
+ fastify.post<{ Body: { cwd?: string; path?: unknown } }>(
649
706
  "/api/git/worktree/orphan-cleanup",
650
707
  { preHandler: networkGuard },
651
708
  async (request, reply) => {
652
709
  const body = request.body ?? {};
653
- const validated = validateCwd(body.cwd);
654
- if (!validated.ok) {
655
- reply.code(400);
656
- return { success: false, code: validated.code, error: validated.message } satisfies ApiResponse;
657
- }
658
- if (!body.path || typeof body.path !== "string") {
710
+ // B1r: a present option-like / control-character path is refused before admission or any fs/git work.
711
+ if (presentInvalid(body.path)) return invalidRef(reply, "path");
712
+ const validated = await validateCwd(body.cwd, reply);
713
+ if (!validated.ok) return validated.body;
714
+ if (!isValidRefArg(body.path)) {
659
715
  reply.code(400);
660
716
  return { success: false, code: "cwd_invalid", error: "path required" } satisfies ApiResponse;
661
717
  }
@@ -671,14 +727,14 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
671
727
  result.error === "too_many_files" ||
672
728
  result.error === "file_too_large"
673
729
  ? 409
674
- : result.error === "outside_repo" || result.error === "not_a_directory"
730
+ : result.error === "outside_repo" || result.error === "not_a_directory" || result.error === "invalid_ref"
675
731
  ? 400
676
732
  : 500;
677
733
  reply.code(httpStatus);
678
734
  return {
679
735
  success: false,
680
736
  code: result.error,
681
- error: result.message,
737
+ error: redact(result.message, validated.cwd),
682
738
  } satisfies ApiResponse;
683
739
  }
684
740
  return { success: true } satisfies ApiResponse;
@@ -721,11 +777,11 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
721
777
  { preHandler: networkGuard },
722
778
  async (request, reply) => {
723
779
  const body = request.body ?? {};
724
- const validated = validateCwd(body.cwd);
725
- if (!validated.ok) {
726
- reply.code(400);
727
- return { success: false, code: validated.code, error: validated.message } satisfies ApiResponse;
728
- }
780
+ // B1r: the worktree path being removed (`cwd`) is a caller-supplied git argument — an
781
+ // option-like / control-character value is refused before admission or git.
782
+ if (typeof body.cwd === "string" && presentInvalid(body.cwd)) return invalidRef(reply, "path");
783
+ const validated = await validateCwd(body.cwd, reply);
784
+ if (!validated.ok) return validated.body;
729
785
  // Removing the main worktree — or one whose main checkout cannot be
730
786
  // resolved — is a clean rejection, not a 500 from git (D3).
731
787
  const { verdict, mainPath } = classifyRemoval(validated.cwd);
@@ -771,7 +827,7 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
771
827
  success: false,
772
828
  code: result.code,
773
829
  error: result.code,
774
- ...(result.stderr ? { stderr: result.stderr } : {}),
830
+ ...(result.stderr ? { stderr: redact(result.stderr, validated.cwd) } : {}),
775
831
  } satisfies ApiResponse;
776
832
  }
777
833
  stampCwdMissing(validated.cwd);
@@ -801,45 +857,101 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
801
857
  }
802
858
  // Per-item containment + removal; never abort on first failure (design D4).
803
859
  // Classification is PER ITEM (D7): each item is an independent delete
804
- // decision against live git state — but AT MOST ONCE PER DISTINCT cwd
805
- // per request: duplicate cwds reuse the memoized classification (the
806
- // spec forbids resolving the same cwd twice within one request).
860
+ // decision against live git state — but AT MOST ONCE PER DISTINCT checkout
861
+ // per request: items whose canonical cwd is equal reuse the memoized
862
+ // classification (the spec forbids resolving the same cwd twice within one request).
863
+ //
864
+ // Admission (change: core-cwd-admission, D1): sequential, memoized per distinct RAW cwd
865
+ // (the token is bound to the exact string), under a whole-batch budget. Each admission
866
+ // gets `deadlineMs = min(cap, remaining)`; once the budget is spent only a direct
867
+ // known-folder match (no git derivation) can still be decided. Tokens are released in
868
+ // one `finally`; the envelope stays 200 with per-item codes.
807
869
  const classificationMemo = new Map<string, { verdict: WorktreeRemovalVerdict; mainPath?: string }>();
808
- const results = items.map((item) => {
809
- const validated = validateCwd(item?.cwd);
810
- if (!validated.ok) return { cwd: item?.cwd ?? "", ok: false, code: "cwd_invalid" };
811
- let classification = classificationMemo.get(validated.cwd);
812
- if (!classification) {
813
- classification = classifyRemoval(validated.cwd);
814
- classificationMemo.set(validated.cwd, classification);
870
+ const admissionMemo = new Map<string, Promise<GitCwdCheck>>();
871
+ const tokens: AdmissionToken[] = [];
872
+ const budgetMs = deps.removeBatchAdmissionBudgetMs ?? REMOVE_BATCH_ADMISSION_BUDGET_MS;
873
+ const capMs = deps.admitOptions?.deadlineMs ?? ADMISSION_DEADLINE_MS;
874
+ const startedAt = Date.now();
875
+ // A scratch reply: a refused/unavailable item must not set the batch's HTTP status.
876
+ const itemReply = { code: () => itemReply, header: () => itemReply, raw: { once: () => undefined } } as unknown as FastifyReply;
877
+ const admitItem = (raw: string): Promise<GitCwdCheck> => {
878
+ let pending = admissionMemo.get(raw);
879
+ if (!pending) {
880
+ const remaining = budgetMs - (Date.now() - startedAt);
881
+ const opts: AdmitCwdOptions =
882
+ remaining > 0
883
+ ? { ...deps.admitOptions, deadlineMs: Math.min(capMs, remaining) }
884
+ : { ...deps.admitOptions, runner: NO_DERIVATION_RUNNER };
885
+ pending = (async (): Promise<GitCwdCheck> => {
886
+ const checked = await admitGitCwd(raw, itemReply, opts);
887
+ if (!checked.ok) return checked;
888
+ tokens.push(checked.token);
889
+ const invalid = (error: string): GitCwdCheck => ({ ok: false, code: "cwd_invalid", body: { success: false, code: "cwd_invalid", error } });
890
+ try {
891
+ if (!(await fs.promises.stat(checked.cwd)).isDirectory()) return invalid("cwd is not a directory");
892
+ } catch {
893
+ return invalid("cwd does not exist");
894
+ }
895
+ return checked;
896
+ })();
897
+ admissionMemo.set(raw, pending);
815
898
  }
816
- const { verdict, mainPath } = classification;
817
- if (verdict !== "removable") {
818
- return {
899
+ return pending;
900
+ };
901
+ const results: Array<Record<string, unknown>> = [];
902
+ try {
903
+ for (const item of items) {
904
+ const rawCwd = item?.cwd;
905
+ if (typeof rawCwd === "string" && presentInvalid(rawCwd)) {
906
+ results.push({ cwd: "", ok: false, code: INVALID_REF_CODE });
907
+ continue;
908
+ }
909
+ const validated: GitCwdCheck =
910
+ !rawCwd || typeof rawCwd !== "string"
911
+ ? { ok: false, code: "cwd_invalid", body: { success: false, code: "cwd_invalid", error: "cwd required" } }
912
+ : await admitItem(rawCwd);
913
+ if (!validated.ok) {
914
+ results.push({ cwd: rawCwd ?? "", ok: false, code: validated.code });
915
+ continue;
916
+ }
917
+ let classification = classificationMemo.get(validated.cwd);
918
+ if (!classification) {
919
+ classification = classifyRemoval(validated.cwd);
920
+ classificationMemo.set(validated.cwd, classification);
921
+ }
922
+ const { verdict, mainPath } = classification;
923
+ if (verdict !== "removable") {
924
+ results.push({
925
+ cwd: validated.cwd,
926
+ ok: false,
927
+ code: verdict === "main" ? "is_main_worktree" : "main_checkout_unresolved",
928
+ });
929
+ continue;
930
+ }
931
+ const force = item.force === true;
932
+ if (sessionManager) {
933
+ const activeIds = activeSessionsUnder(validated.cwd, sessionManager.listAll());
934
+ if (activeIds.length > 0 && !force) {
935
+ results.push({ cwd: validated.cwd, ok: false, code: "active_sessions", sessionIds: activeIds });
936
+ continue;
937
+ }
938
+ }
939
+ const result = removeWorktree({
819
940
  cwd: validated.cwd,
820
- ok: false,
821
- code: verdict === "main" ? "is_main_worktree" : "main_checkout_unresolved",
822
- };
823
- }
824
- const force = item.force === true;
825
- if (sessionManager) {
826
- const activeIds = activeSessionsUnder(validated.cwd, sessionManager.listAll());
827
- if (activeIds.length > 0 && !force) {
828
- return { cwd: validated.cwd, ok: false, code: "active_sessions", sessionIds: activeIds };
941
+ force,
942
+ deleteBranch: item.deleteBranch === true,
943
+ mainPath,
944
+ });
945
+ if (!result.ok) {
946
+ results.push({ cwd: validated.cwd, ok: false, code: result.code, ...(result.stderr ? { stderr: redact(result.stderr, validated.cwd) } : {}) });
947
+ continue;
829
948
  }
949
+ stampCwdMissing(validated.cwd);
950
+ results.push({ cwd: validated.cwd, ok: true, code: "ok", ...result.data });
830
951
  }
831
- const result = removeWorktree({
832
- cwd: validated.cwd,
833
- force,
834
- deleteBranch: item.deleteBranch === true,
835
- mainPath,
836
- });
837
- if (!result.ok) {
838
- return { cwd: validated.cwd, ok: false, code: result.code, ...(result.stderr ? { stderr: result.stderr } : {}) };
839
- }
840
- stampCwdMissing(validated.cwd);
841
- return { cwd: validated.cwd, ok: true, code: "ok", ...result.data };
842
- });
952
+ } finally {
953
+ for (const t of tokens) releaseAdmission(t);
954
+ }
843
955
  return { success: true, data: { results } } satisfies ApiResponse;
844
956
  },
845
957
  );
@@ -848,11 +960,8 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
848
960
  "/api/git/worktree/prune",
849
961
  { preHandler: networkGuard },
850
962
  async (request, reply) => {
851
- const validated = validateCwd((request.body ?? {}).cwd);
852
- if (!validated.ok) {
853
- reply.code(400);
854
- return { success: false, code: validated.code, error: validated.message } satisfies ApiResponse;
855
- }
963
+ const validated = await validateCwd((request.body ?? {}).cwd, reply);
964
+ if (!validated.ok) return validated.body;
856
965
  const result = pruneWorktrees(validated.cwd);
857
966
  if (!result.ok) {
858
967
  reply.code(result.code === "not_a_worktree" ? 400 : 500);
@@ -867,11 +976,8 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
867
976
  { preHandler: networkGuard },
868
977
  async (request, reply) => {
869
978
  const body = request.body ?? {};
870
- const validated = validateCwd(body.cwd);
871
- if (!validated.ok) {
872
- reply.code(400);
873
- return { success: false, code: validated.code, error: validated.message } satisfies ApiResponse;
874
- }
979
+ const validated = await validateCwd(body.cwd, reply);
980
+ if (!validated.ok) return validated.body;
875
981
  const baseHint = sessionManager
876
982
  ? sessionManager.listAll().find((s) => s.cwd === validated.cwd)?.gitWorktreeBase
877
983
  : undefined;
@@ -891,7 +997,7 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
891
997
  success: false,
892
998
  code: result.code,
893
999
  error: result.code,
894
- ...(result.stderr ? { stderr: result.stderr } : {}),
1000
+ ...(result.stderr ? { stderr: redact(result.stderr, validated.cwd) } : {}),
895
1001
  } satisfies ApiResponse;
896
1002
  }
897
1003
  return { success: true, data: result.data } satisfies ApiResponse;
@@ -903,11 +1009,8 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
903
1009
  { preHandler: networkGuard },
904
1010
  async (request, reply) => {
905
1011
  const body = request.body ?? {};
906
- const validated = validateCwd(body.cwd);
907
- if (!validated.ok) {
908
- reply.code(400);
909
- return { success: false, code: validated.code, error: validated.message } satisfies ApiResponse;
910
- }
1012
+ const validated = await validateCwd(body.cwd, reply);
1013
+ if (!validated.ok) return validated.body;
911
1014
  const result = pushBranch({
912
1015
  cwd: validated.cwd,
913
1016
  setUpstream: body.setUpstream !== false,
@@ -922,7 +1025,7 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
922
1025
  success: false,
923
1026
  code: result.code,
924
1027
  error: result.code,
925
- ...(result.stderr ? { stderr: result.stderr } : {}),
1028
+ ...(result.stderr ? { stderr: redact(result.stderr, validated.cwd) } : {}),
926
1029
  } satisfies ApiResponse;
927
1030
  }
928
1031
  requestPrRefresh(validated.cwd, "push");
@@ -935,11 +1038,8 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
935
1038
  { preHandler: networkGuard },
936
1039
  async (request, reply) => {
937
1040
  const body = request.body ?? {};
938
- const validated = validateCwd(body.cwd);
939
- if (!validated.ok) {
940
- reply.code(400);
941
- return { success: false, code: validated.code, error: validated.message } satisfies ApiResponse;
942
- }
1041
+ const validated = await validateCwd(body.cwd, reply);
1042
+ if (!validated.ok) return validated.body;
943
1043
  const ghResolved = getDefaultRegistry().resolve("gh");
944
1044
  if (!ghResolved.ok || !ghResolved.path) {
945
1045
  reply.code(400);
@@ -970,7 +1070,7 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
970
1070
  success: false,
971
1071
  code: result.code,
972
1072
  error: result.code,
973
- ...(result.stderr ? { stderr: result.stderr } : {}),
1073
+ ...(result.stderr ? { stderr: redact(result.stderr, validated.cwd) } : {}),
974
1074
  } satisfies ApiResponse;
975
1075
  }
976
1076
  requestPrRefresh(validated.cwd, "pr");
@@ -983,11 +1083,8 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
983
1083
  "/api/git/pull-requests",
984
1084
  { preHandler: networkGuard },
985
1085
  async (request, reply) => {
986
- const validated = validateCwd(request.query.cwd);
987
- if (!validated.ok) {
988
- reply.code(400);
989
- return { success: false, code: validated.code, error: validated.message } satisfies ApiResponse;
990
- }
1086
+ const validated = await validateCwd(request.query.cwd, reply);
1087
+ if (!validated.ok) return validated.body;
991
1088
  const ghResolved = getDefaultRegistry().resolve("gh");
992
1089
  if (!ghResolved.ok || !ghResolved.path) {
993
1090
  reply.code(400);
@@ -1004,7 +1101,7 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
1004
1101
  success: false,
1005
1102
  code: result.code,
1006
1103
  error: result.code,
1007
- ...(result.stderr ? { stderr: result.stderr } : {}),
1104
+ ...(result.stderr ? { stderr: redact(result.stderr, validated.cwd) } : {}),
1008
1105
  } satisfies ApiResponse;
1009
1106
  }
1010
1107
  return { success: true, data: result.data } satisfies ApiResponse;
@@ -1012,21 +1109,20 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
1012
1109
  );
1013
1110
 
1014
1111
  // ── Create worktree from PR (change: add-worktree-from-pull-request) ────
1015
- fastify.post<{ Body: { cwd?: string; prNumber?: number; path?: string } }>(
1112
+ fastify.post<{ Body: { cwd?: string; prNumber?: number; path?: unknown } }>(
1016
1113
  "/api/git/worktree/from-pr",
1017
1114
  { preHandler: networkGuard },
1018
1115
  async (request, reply) => {
1019
1116
  const body = request.body ?? {};
1020
- const validated = validateCwd(body.cwd);
1021
- if (!validated.ok) {
1022
- reply.code(400);
1023
- return { success: false, code: validated.code, error: validated.message } satisfies ApiResponse;
1024
- }
1117
+ // B1r: a present option-like / control-character path is refused before admission or git.
1118
+ if (presentInvalid(body.path)) return invalidRef(reply, "path");
1119
+ const validated = await validateCwd(body.cwd, reply);
1120
+ if (!validated.ok) return validated.body;
1025
1121
  if (typeof body.prNumber !== "number" || !Number.isInteger(body.prNumber) || body.prNumber <= 0) {
1026
1122
  reply.code(400);
1027
1123
  return { success: false, code: "cwd_invalid", error: "prNumber required (positive integer)" } satisfies ApiResponse;
1028
1124
  }
1029
- const pathArg = typeof body.path === "string" && body.path.length > 0 ? body.path : undefined;
1125
+ const pathArg = isValidRefArg(body.path) ? body.path : undefined;
1030
1126
  const result = addWorktreeFromPr({
1031
1127
  cwd: validated.cwd,
1032
1128
  prNumber: body.prNumber,
@@ -1037,14 +1133,14 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
1037
1133
  result.error === "pr_not_found" ? 404
1038
1134
  : result.error === "gh_not_authed" ? 401
1039
1135
  : result.error === "branch_in_use" || result.error === "branch_exists" || result.error === "path_exists" ? 409
1040
- : result.error === "not_a_repo" || result.error === "base_not_found" ? 400
1136
+ : result.error === "not_a_repo" || result.error === "base_not_found" || result.error === "invalid_ref" ? 400
1041
1137
  : 500;
1042
1138
  reply.code(httpStatus);
1043
1139
  return {
1044
1140
  success: false,
1045
1141
  code: result.error,
1046
- error: result.message,
1047
- ...(result.stderr ? { stderr: result.stderr } : {}),
1142
+ error: redact(result.message, validated.cwd),
1143
+ ...(result.stderr ? { stderr: redact(result.stderr, validated.cwd) } : {}),
1048
1144
  ...(typeof result.orphanLikely === "boolean" ? { orphanLikely: result.orphanLikely } : {}),
1049
1145
  } satisfies ApiResponse;
1050
1146
  }
@@ -1059,11 +1155,8 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
1059
1155
  "/api/git/worktree/diff-stat",
1060
1156
  { preHandler: networkGuard },
1061
1157
  async (request, reply) => {
1062
- const validated = validateCwd(request.query.cwd);
1063
- if (!validated.ok) {
1064
- reply.code(400);
1065
- return { success: false, code: validated.code, error: validated.message } satisfies ApiResponse;
1066
- }
1158
+ const validated = await validateCwd(request.query.cwd, reply);
1159
+ if (!validated.ok) return validated.body;
1067
1160
  const baseHint = sessionManager
1068
1161
  ? sessionManager.listAll().find((s) => s.cwd === validated.cwd)?.gitWorktreeBase
1069
1162
  : undefined;
@@ -1075,7 +1168,7 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
1075
1168
  success: false,
1076
1169
  code: result.code,
1077
1170
  error: result.code,
1078
- ...(result.stderr ? { stderr: result.stderr } : {}),
1171
+ ...(result.stderr ? { stderr: redact(result.stderr, validated.cwd) } : {}),
1079
1172
  } satisfies ApiResponse;
1080
1173
  }
1081
1174
  return { success: true, data: result.data } satisfies ApiResponse;
@@ -1091,40 +1184,14 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
1091
1184
  reply.code(400);
1092
1185
  return { success: false, code: "cwd_required", error: "cwd required" } satisfies ApiResponse;
1093
1186
  }
1187
+ const admitted = await admitGitCwd(cwd, reply);
1188
+ if (!admitted.ok) return admitted.body;
1094
1189
  try {
1095
- const result = stashPop(cwd);
1190
+ const result = stashPop(admitted.cwd);
1096
1191
  return { success: true, data: result } satisfies ApiResponse;
1097
1192
  } catch (err: any) {
1098
- return { success: false, code: "stash_pop_failed", error: err.message ?? "stash pop failed" } satisfies ApiResponse;
1193
+ return { success: false, code: "stash_pop_failed", error: redactErr(err, "stash pop failed", admitted.cwd) } satisfies ApiResponse;
1099
1194
  }
1100
1195
  },
1101
1196
  );
1102
1197
  }
1103
-
1104
- /**
1105
- * Validate and realpath a cwd query / body parameter for the worktree
1106
- * endpoints. Returns either `{ ok: true, cwd }` (realpath-resolved) or
1107
- * `{ ok: false, code, message }` with a stable error code.
1108
- *
1109
- * See change: add-worktree-spawn-dialog.
1110
- */
1111
- function validateCwd(raw: string | undefined):
1112
- | { ok: true; cwd: string }
1113
- | { ok: false; code: "cwd_invalid"; message: string } {
1114
- // (Field names: `code` is the stable classifier consumed by clients;
1115
- // `message` is the human-readable string surfaced on the wire as
1116
- // ApiResponse.error.)
1117
- if (!raw || typeof raw !== "string") {
1118
- return { ok: false, code: "cwd_invalid", message: "cwd required" };
1119
- }
1120
- const resolved = safeRealpathSync(raw);
1121
- try {
1122
- const stat = fs.statSync(resolved);
1123
- if (!stat.isDirectory()) {
1124
- return { ok: false, code: "cwd_invalid", message: "cwd is not a directory" };
1125
- }
1126
- } catch {
1127
- return { ok: false, code: "cwd_invalid", message: "cwd does not exist" };
1128
- }
1129
- return { ok: true, cwd: resolved };
1130
- }