@blackbelt-technology/pi-agent-dashboard 0.9.0 → 0.11.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 (576) hide show
  1. package/AGENTS.md +2 -2
  2. package/README.md +85 -11
  3. package/docs/architecture.md +3020 -116
  4. package/package.json +31 -18
  5. package/packages/extension/package.json +10 -8
  6. package/packages/extension/src/ask-user-tool.ts +65 -3
  7. package/packages/extension/src/auto-session-namer.ts +190 -50
  8. package/packages/extension/src/bridge-handlers/dispatch.ts +504 -0
  9. package/packages/extension/src/bridge-handlers/forwarders.ts +616 -0
  10. package/packages/extension/src/bridge-handlers/instance.ts +229 -0
  11. package/packages/extension/src/bridge-handlers/lifecycle.ts +1069 -0
  12. package/packages/extension/src/bridge-handlers/ui-prompt-patch.ts +198 -0
  13. package/packages/extension/src/bridge-identity-log.ts +45 -0
  14. package/packages/extension/src/bridge-ticket-client.ts +61 -7
  15. package/packages/extension/src/bridge-tls-checks.ts +79 -0
  16. package/packages/extension/src/bridge.ts +517 -2534
  17. package/packages/extension/src/canvas-tool.ts +2 -0
  18. package/packages/extension/src/command-handler.ts +259 -16
  19. package/packages/extension/src/connect-target.ts +23 -0
  20. package/packages/extension/src/connection.ts +294 -24
  21. package/packages/extension/src/dashboard-context-injector.ts +26 -47
  22. package/packages/extension/src/dashboard-http-origin.ts +88 -0
  23. package/packages/extension/src/dev-build.ts +11 -1
  24. package/packages/extension/src/empty-actionable-guard.ts +8 -3
  25. package/packages/extension/src/flow-event-wiring.ts +1 -1
  26. package/packages/extension/src/followup-buffer.ts +1 -1
  27. package/packages/extension/src/followup-drain.ts +79 -0
  28. package/packages/extension/src/git-link-builder.ts +11 -2
  29. package/packages/extension/src/inbound-limits.ts +138 -0
  30. package/packages/extension/src/local-token-header.ts +232 -17
  31. package/packages/extension/src/message-update-coalescer.ts +3 -1
  32. package/packages/extension/src/model-refresh.ts +88 -0
  33. package/packages/extension/src/multiselect-list.ts +6 -2
  34. package/packages/extension/src/multiselect-polyfill.ts +2 -2
  35. package/packages/extension/src/openspec-cli-shim.ts +1 -1
  36. package/packages/extension/src/path-gate/decide.ts +15 -41
  37. package/packages/extension/src/path-gate/grant-cache.ts +3 -1
  38. package/packages/extension/src/path-gate/handler.ts +51 -2
  39. package/packages/extension/src/path-gate/index.ts +12 -1
  40. package/packages/extension/src/path-gate/resolve.ts +6 -124
  41. package/packages/extension/src/path-gate/roots.ts +4 -1
  42. package/packages/extension/src/path-gate/suppression.ts +4 -1
  43. package/packages/extension/src/path-gate/yolo-link.ts +104 -0
  44. package/packages/extension/src/pinned-endpoint.ts +44 -0
  45. package/packages/extension/src/plugin-event-forward-registry.ts +200 -0
  46. package/packages/extension/src/project-trust-live.ts +143 -0
  47. package/packages/extension/src/project-trust.ts +258 -25
  48. package/packages/extension/src/prompt-expander.ts +5 -1
  49. package/packages/extension/src/prompt-meta.ts +64 -0
  50. package/packages/extension/src/provider-register.ts +146 -38
  51. package/packages/extension/src/remote-registration-gate.ts +21 -21
  52. package/packages/extension/src/remote-upgrade-preparer.ts +104 -0
  53. package/packages/extension/src/role-manager.ts +5 -4
  54. package/packages/extension/src/role-model-tools.ts +47 -6
  55. package/packages/extension/src/server-auto-start.ts +13 -6
  56. package/packages/extension/src/server-launcher.ts +11 -13
  57. package/packages/extension/src/server-proof-probe.ts +117 -0
  58. package/packages/extension/src/session-move.ts +19 -0
  59. package/packages/extension/src/session-sync.ts +73 -50
  60. package/packages/extension/src/spawn-token.ts +46 -0
  61. package/packages/extension/src/stream-forward-buffer.ts +161 -0
  62. package/packages/extension/src/subagent-frame-buffer.ts +6 -2
  63. package/packages/extension/src/subagent-tick-throttle.ts +3 -1
  64. package/packages/extension/src/vault-delivery.ts +404 -0
  65. package/packages/extension/src/vault-forwarder.ts +128 -0
  66. package/packages/extension/src/vault-masker.ts +165 -0
  67. package/packages/extension/src/vault-redaction.ts +181 -0
  68. package/packages/extension/src/vcs-info.ts +5 -2
  69. package/packages/server/bin/pi-dashboard.mjs +26 -89
  70. package/packages/server/package.json +29 -15
  71. package/packages/server/src/access/access-grants.ts +79 -8
  72. package/packages/server/src/access/access-health.ts +10 -0
  73. package/packages/server/src/access/access-plane.ts +5 -1
  74. package/packages/server/src/access/agent-confirm-registry.ts +31 -13
  75. package/packages/server/src/access/agent-grant.ts +1 -1
  76. package/packages/server/src/access/agent-yolo.ts +91 -0
  77. package/packages/server/src/access/containment-gate.ts +82 -17
  78. package/packages/server/src/access/cwd-admission-log.ts +46 -0
  79. package/packages/server/src/access/cwd-verdict.ts +144 -0
  80. package/packages/server/src/access/grant-coordinator.ts +3 -1
  81. package/packages/server/src/access/pi-trust-live.ts +244 -0
  82. package/packages/server/src/access/pi-trust-mirror-service.ts +407 -0
  83. package/packages/server/src/access/planes.ts +116 -2
  84. package/packages/server/src/access/preview-egress-store.ts +153 -0
  85. package/packages/server/src/access/prompt-channel.ts +5 -0
  86. package/packages/server/src/access/provisioning-wiring.ts +113 -0
  87. package/packages/server/src/access/provisioning.ts +763 -0
  88. package/packages/server/src/access/refusal-ledger.ts +6 -6
  89. package/packages/server/src/access/yolo-session.ts +127 -14
  90. package/packages/server/src/acp-bridge/acp-connection.ts +225 -0
  91. package/packages/server/src/acp-bridge/acp-restore.ts +41 -0
  92. package/packages/server/src/acp-bridge/acp-session-adapter.ts +549 -0
  93. package/packages/server/src/acp-bridge/child-env.ts +73 -0
  94. package/packages/server/src/acp-bridge/event-log.ts +194 -0
  95. package/packages/server/src/acp-bridge/gateway-client.ts +136 -0
  96. package/packages/server/src/acp-bridge/local-bridge-socket.ts +67 -0
  97. package/packages/server/src/acp-bridge/local-host.ts +132 -0
  98. package/packages/server/src/acp-bridge/main.ts +118 -0
  99. package/packages/server/src/acp-bridge/models.ts +33 -0
  100. package/packages/server/src/acp-bridge/permission-bridge.ts +106 -0
  101. package/packages/server/src/acp-bridge/server-requests.ts +136 -0
  102. package/packages/server/src/acp-bridge/session-state.ts +127 -0
  103. package/packages/server/src/addons/addon-toggle-restore.ts +110 -0
  104. package/packages/server/src/addons/addons-catalog.ts +408 -0
  105. package/packages/server/src/addons/addons-folder-service.ts +347 -0
  106. package/packages/server/src/addons/addons-folder.ts +310 -0
  107. package/packages/server/src/addons/addons-service.ts +470 -0
  108. package/packages/server/src/addons/package-contents.ts +99 -0
  109. package/packages/server/src/addons/settings-entries.ts +120 -0
  110. package/packages/server/src/agent-events/agent-event-hub.ts +158 -0
  111. package/packages/server/src/attachments/fit-worker-pool.ts +12 -17
  112. package/packages/server/src/auth/approval-refusal.ts +87 -0
  113. package/packages/server/src/auth/audit-log.ts +80 -0
  114. package/packages/server/src/auth/auth-plugin.ts +329 -97
  115. package/packages/server/src/auth/auth.ts +102 -11
  116. package/packages/server/src/auth/bearer-auth.ts +74 -12
  117. package/packages/server/src/auth/cors-origin.ts +86 -29
  118. package/packages/server/src/auth/csp-report-paths.ts +31 -0
  119. package/packages/server/src/auth/csp-report-sink.ts +302 -0
  120. package/packages/server/src/auth/csp-report-store.ts +406 -0
  121. package/packages/server/src/auth/csp.ts +111 -9
  122. package/packages/server/src/auth/dashboard-credential-store.ts +4 -0
  123. package/packages/server/src/auth/dashboard-state-caller.ts +29 -0
  124. package/packages/server/src/auth/host-admission.ts +26 -0
  125. package/packages/server/src/auth/host-gate.ts +6 -1
  126. package/packages/server/src/auth/local-credential.ts +258 -0
  127. package/packages/server/src/auth/local-proof-refusal-log.ts +89 -0
  128. package/packages/server/src/auth/local-proof.ts +76 -22
  129. package/packages/server/src/auth/local-token.ts +16 -0
  130. package/packages/server/src/auth/localhost-guard.ts +298 -17
  131. package/packages/server/src/auth/nav-intent.ts +72 -0
  132. package/packages/server/src/auth/network-trust-telemetry.ts +126 -0
  133. package/packages/server/src/auth/node-guard.ts +43 -0
  134. package/packages/server/src/auth/operate-required.ts +126 -0
  135. package/packages/server/src/auth/passkey/challenge-store.ts +90 -0
  136. package/packages/server/src/auth/passkey/passkey-assets.ts +99 -0
  137. package/packages/server/src/auth/passkey/passkey-log.ts +34 -0
  138. package/packages/server/src/auth/passkey/passkey-pages.ts +109 -0
  139. package/packages/server/src/auth/passkey/passkey-routes.ts +232 -0
  140. package/packages/server/src/auth/passkey/passkey-service.ts +247 -0
  141. package/packages/server/src/auth/passkey/phone-signin.ts +211 -0
  142. package/packages/server/src/auth/passkey/requester.ts +83 -0
  143. package/packages/server/src/auth/passkey/rp-context.ts +98 -0
  144. package/packages/server/src/auth/passkey/user-directory.ts +348 -0
  145. package/packages/server/src/auth/pi-legacy-credentials.ts +324 -0
  146. package/packages/server/src/auth/plugin-server-trust.ts +29 -0
  147. package/packages/server/src/auth/plugin-trust-store.ts +103 -0
  148. package/packages/server/src/auth/proven-tls.ts +45 -0
  149. package/packages/server/src/auth/provider-auth-registry.ts +35 -1
  150. package/packages/server/src/auth/provider-auth-storage.ts +61 -9
  151. package/packages/server/src/auth/radius-mcp.ts +1 -1
  152. package/packages/server/src/auth/radius-override.ts +13 -0
  153. package/packages/server/src/auth/request-principal.ts +32 -0
  154. package/packages/server/src/auth/route-tier-gate.ts +27 -11
  155. package/packages/server/src/auth/runtime-provider-catalogue.ts +107 -0
  156. package/packages/server/src/auth/scan-legacy-provider-ids.ts +80 -0
  157. package/packages/server/src/auth/secret-rotation.ts +246 -0
  158. package/packages/server/src/auth/secure-origin.ts +56 -0
  159. package/packages/server/src/auth/serve-app-host.ts +197 -0
  160. package/packages/server/src/auth/trust-mode-boot.ts +93 -0
  161. package/packages/server/src/auth/trust-mode.ts +83 -0
  162. package/packages/server/src/auth/ws-ticket.ts +39 -1
  163. package/packages/server/src/auth/ws-upgrade-reject-log.ts +4 -1
  164. package/packages/server/src/auto-name-outcome-store.ts +4 -1
  165. package/packages/server/src/browse.ts +114 -2
  166. package/packages/server/src/browser-handlers/acp-guard.ts +79 -0
  167. package/packages/server/src/browser-handlers/directory-handler.ts +151 -6
  168. package/packages/server/src/browser-handlers/folder-gate.ts +55 -0
  169. package/packages/server/src/browser-handlers/handler-context.ts +25 -2
  170. package/packages/server/src/browser-handlers/session-action-handler.ts +138 -63
  171. package/packages/server/src/browser-handlers/session-meta-handler.ts +16 -6
  172. package/packages/server/src/browser-handlers/spawn-choice.ts +99 -0
  173. package/packages/server/src/browser-handlers/subscription-handler.ts +100 -2
  174. package/packages/server/src/browser-handlers/terminal-handler.ts +108 -10
  175. package/packages/server/src/canvas/canvas-accumulator.ts +35 -7
  176. package/packages/server/src/cli.ts +1063 -106
  177. package/packages/server/src/config-api.ts +166 -2
  178. package/packages/server/src/config-snapshot.ts +53 -1
  179. package/packages/server/src/directory-service.ts +545 -36
  180. package/packages/server/src/embed-lifecycle/caps.ts +35 -4
  181. package/packages/server/src/embed-lifecycle/embed-lifecycle-controller.ts +45 -4
  182. package/packages/server/src/embed-lifecycle/idle-reaper.ts +195 -20
  183. package/packages/server/src/embed-lifecycle/lifecycle-metrics.ts +38 -0
  184. package/packages/server/src/embed-lifecycle/plugin-session-close.ts +123 -0
  185. package/packages/server/src/embed-lifecycle/quiescence.ts +29 -3
  186. package/packages/server/src/embed-lifecycle/reclaim-give-up.ts +54 -0
  187. package/packages/server/src/event-wiring.ts +349 -141
  188. package/packages/server/src/file-watch-manager.ts +187 -39
  189. package/packages/server/src/git-worktree/git-operations.ts +60 -15
  190. package/packages/server/src/git-worktree/redact-git-text.ts +124 -0
  191. package/packages/server/src/git-worktree/ref-arg.ts +39 -0
  192. package/packages/server/src/git-worktree/worktree-init-trust.ts +91 -6
  193. package/packages/server/src/git-worktree/worktree-init.ts +7 -56
  194. package/packages/server/src/identity/host-resources.ts +3 -0
  195. package/packages/server/src/identity/http-road-classification.ts +31 -1
  196. package/packages/server/src/identity/identity-registration-tracker.ts +4 -1
  197. package/packages/server/src/identity/plugin-identity.ts +19 -0
  198. package/packages/server/src/identity/policy-registry.ts +4 -1
  199. package/packages/server/src/identity/resolver-registry.ts +12 -3
  200. package/packages/server/src/identity/ws-message-scope.ts +10 -0
  201. package/packages/server/src/identity/ws-road-classification.ts +10 -0
  202. package/packages/server/src/known-server-moves.ts +196 -0
  203. package/packages/server/src/lib/browse-roots.ts +137 -0
  204. package/packages/server/src/lib/client-dist.ts +36 -21
  205. package/packages/server/src/lib/dashboard-state-guard.ts +230 -0
  206. package/packages/server/src/lib/diagram-render.ts +4 -6
  207. package/packages/server/src/lib/digest-gate.ts +82 -0
  208. package/packages/server/src/lib/eml.ts +3 -8
  209. package/packages/server/src/lib/file-cwd-admission.ts +145 -0
  210. package/packages/server/src/lib/file-write-lock.ts +24 -0
  211. package/packages/server/src/lib/folder-project.ts +439 -0
  212. package/packages/server/src/lib/grep-worker.ts +23 -0
  213. package/packages/server/src/lib/grep.ts +93 -7
  214. package/packages/server/src/lib/index-html.ts +81 -0
  215. package/packages/server/src/lib/office-preview.ts +2 -3
  216. package/packages/server/src/lib/path-containment.ts +7 -0
  217. package/packages/server/src/lib/purify.ts +13 -5
  218. package/packages/server/src/lib/resolve-file-mention.ts +11 -9
  219. package/packages/server/src/lib/route-admission.ts +80 -0
  220. package/packages/server/src/lib/writable-handler-target.ts +66 -0
  221. package/packages/server/src/lib/writable-md-target.ts +16 -1
  222. package/packages/server/src/lifecycle/classify-dashboard-port.ts +134 -0
  223. package/packages/server/src/lifecycle/home-lock.ts +344 -130
  224. package/packages/server/src/lifecycle/home-rendezvous.ts +41 -11
  225. package/packages/server/src/lifecycle/recovery-server.ts +129 -6
  226. package/packages/server/src/lifecycle/stop-ownership.ts +97 -11
  227. package/packages/server/src/live-server/capability-redact.ts +15 -0
  228. package/packages/server/src/live-server/live-browser-gate.ts +22 -0
  229. package/packages/server/src/live-server/live-capability.ts +461 -0
  230. package/packages/server/src/live-server/live-csp-report.ts +63 -0
  231. package/packages/server/src/live-server/live-csp.ts +93 -0
  232. package/packages/server/src/live-server/live-egress.ts +435 -0
  233. package/packages/server/src/live-server/live-exposure.ts +149 -0
  234. package/packages/server/src/live-server/live-log.ts +21 -0
  235. package/packages/server/src/live-server/live-origin-scan.ts +298 -0
  236. package/packages/server/src/live-server/live-server-manager.ts +209 -33
  237. package/packages/server/src/live-server/live-server-proxy.ts +326 -34
  238. package/packages/server/src/live-server/live-static.ts +228 -0
  239. package/packages/server/src/metrics/eventloop-spike-metrics.ts +2 -2
  240. package/packages/server/src/model-proxy/internal-auth-storage.ts +27 -26
  241. package/packages/server/src/model-proxy/internal-registry.ts +6 -0
  242. package/packages/server/src/model-proxy/server-model-runtime.ts +6 -0
  243. package/packages/server/src/openspec/dependencies-file.ts +122 -0
  244. package/packages/server/src/openspec/openspec-change-watcher.ts +111 -16
  245. package/packages/server/src/openspec/openspec-dependency-inputs.ts +281 -0
  246. package/packages/server/src/openspec/openspec-poll-fs-helpers.ts +189 -11
  247. package/packages/server/src/openspec/openspec-poll-worker-pool.ts +126 -35
  248. package/packages/server/src/openspec/openspec-poll-worker.ts +286 -44
  249. package/packages/server/src/openspec/proposal-attach-naming.ts +5 -3
  250. package/packages/server/src/openspec/readiness.ts +9 -0
  251. package/packages/server/src/openspec/workflow-schema-status.ts +379 -0
  252. package/packages/server/src/openspec/workflow-schema.ts +1002 -0
  253. package/packages/server/src/package/installed-package-enricher.ts +38 -3
  254. package/packages/server/src/package/npm-search-proxy.ts +5 -2
  255. package/packages/server/src/package/package-health-scanner.ts +133 -0
  256. package/packages/server/src/package/package-manager-wrapper.ts +18 -2
  257. package/packages/server/src/package/provider-catalogue-cache.ts +17 -3
  258. package/packages/server/src/package/provider-probe.ts +13 -5
  259. package/packages/server/src/pairing/browser-gateway.ts +292 -16
  260. package/packages/server/src/pairing/device-token-services.ts +26 -0
  261. package/packages/server/src/pairing/knock-admission.ts +277 -0
  262. package/packages/server/src/pairing/paired-devices.ts +335 -22
  263. package/packages/server/src/pairing/pairing.ts +188 -31
  264. package/packages/server/src/pairing/socket-locality.ts +26 -0
  265. package/packages/server/src/pairing/subagent-resync-routing.ts +4 -1
  266. package/packages/server/src/pairing/ws-tier-gate.ts +34 -0
  267. package/packages/server/src/peer-servers.ts +77 -0
  268. package/packages/server/src/pending/pending-plugin-ref-registry.ts +57 -2
  269. package/packages/server/src/persistence/boot-state.ts +48 -1
  270. package/packages/server/src/persistence/memory-event-store.ts +216 -237
  271. package/packages/server/src/persistence/meta-persistence.ts +12 -1
  272. package/packages/server/src/persistence/preferences-store.ts +125 -7
  273. package/packages/server/src/pi/bridge-channel.ts +33 -0
  274. package/packages/server/src/pi/bridge-upgrade-auth.ts +48 -22
  275. package/packages/server/src/pi/folder-commands.ts +141 -0
  276. package/packages/server/src/pi/gateway-listeners.ts +9 -3
  277. package/packages/server/src/pi/gateway-socket-bind.ts +9 -3
  278. package/packages/server/src/pi/gateway-transport-policy.ts +13 -0
  279. package/packages/server/src/pi/host-project-trust.ts +166 -33
  280. package/packages/server/src/pi/pi-gateway.ts +283 -29
  281. package/packages/server/src/pi/pi-resource-scanner.ts +15 -0
  282. package/packages/server/src/pi/resource-activation-toggle.ts +6 -0
  283. package/packages/server/src/pi/resource-toggle-trust.ts +34 -2
  284. package/packages/server/src/pi/session-skill-registry.ts +13 -3
  285. package/packages/server/src/pi/settings-write-lock.ts +32 -0
  286. package/packages/server/src/pi/trust-challenges.ts +38 -0
  287. package/packages/server/src/pi-agent-settings.ts +701 -100
  288. package/packages/server/src/pi-settings-themes.ts +104 -0
  289. package/packages/server/src/plugin-discovery-wiring.ts +142 -0
  290. package/packages/server/src/plugin-event-seam.ts +116 -4
  291. package/packages/server/src/plugin-runtime-clients.ts +89 -0
  292. package/packages/server/src/questions/brief-generator.ts +138 -0
  293. package/packages/server/src/questions/brief-model.ts +55 -0
  294. package/packages/server/src/questions/brief-policy.ts +36 -0
  295. package/packages/server/src/questions/brief-prompt.ts +92 -0
  296. package/packages/server/src/questions/brief-runtime.ts +50 -0
  297. package/packages/server/src/questions/question-answer.ts +55 -0
  298. package/packages/server/src/questions/question-broadcast.ts +106 -0
  299. package/packages/server/src/questions/question-files.ts +128 -0
  300. package/packages/server/src/questions/question-routes.ts +126 -0
  301. package/packages/server/src/questions/question-snapshot.ts +150 -0
  302. package/packages/server/src/questions/question-stack.ts +57 -0
  303. package/packages/server/src/questions/question-store.ts +477 -0
  304. package/packages/server/src/routes/access-prompt-routes.ts +5 -3
  305. package/packages/server/src/routes/access-routes.ts +274 -6
  306. package/packages/server/src/routes/acme-routes.ts +190 -0
  307. package/packages/server/src/routes/acp-routes.ts +16 -0
  308. package/packages/server/src/routes/addons-routes.ts +221 -0
  309. package/packages/server/src/routes/agent-event-stream-routes.ts +137 -0
  310. package/packages/server/src/routes/canvas-types-routes.ts +20 -6
  311. package/packages/server/src/routes/csp-violations-routes.ts +162 -0
  312. package/packages/server/src/routes/file-routes.ts +620 -209
  313. package/packages/server/src/routes/file-write-binary-routes.ts +530 -0
  314. package/packages/server/src/routes/folder-project-routes.ts +105 -0
  315. package/packages/server/src/routes/git-routes.ts +334 -203
  316. package/packages/server/src/routes/grep-routes.ts +38 -14
  317. package/packages/server/src/routes/known-servers-routes.ts +433 -55
  318. package/packages/server/src/routes/live-server-routes.ts +438 -7
  319. package/packages/server/src/routes/local-proof-routes.ts +26 -7
  320. package/packages/server/src/routes/mermaid-repair-routes.ts +254 -0
  321. package/packages/server/src/routes/model-proxy-routes.ts +4 -2
  322. package/packages/server/src/routes/nav-intent-routes.ts +46 -0
  323. package/packages/server/src/routes/openspec-group-routes.ts +53 -44
  324. package/packages/server/src/routes/openspec-routes.ts +636 -55
  325. package/packages/server/src/routes/package-health-routes.ts +140 -0
  326. package/packages/server/src/routes/package-routes.ts +86 -11
  327. package/packages/server/src/routes/pairing-routes.ts +303 -33
  328. package/packages/server/src/routes/pi-retry-routes.ts +18 -2
  329. package/packages/server/src/routes/pi-settings-routes.ts +264 -0
  330. package/packages/server/src/routes/pi-trust-query-routes.ts +330 -0
  331. package/packages/server/src/routes/plugin-activation-routes.ts +146 -27
  332. package/packages/server/src/routes/plugin-runtime-client-routes.ts +149 -0
  333. package/packages/server/src/routes/provider-auth-routes.ts +37 -7
  334. package/packages/server/src/routes/provider-routes.ts +29 -0
  335. package/packages/server/src/routes/resource-activation-routes.ts +33 -35
  336. package/packages/server/src/routes/session-routes.ts +100 -9
  337. package/packages/server/src/routes/system-routes.ts +286 -33
  338. package/packages/server/src/routes/tls-routes.ts +55 -0
  339. package/packages/server/src/routes/ui-link-base.ts +88 -0
  340. package/packages/server/src/routes/user-routes.ts +192 -0
  341. package/packages/server/src/runtime-overlay/runtime-io.ts +2 -9
  342. package/packages/server/src/runtime-overlay/runtime-stager.ts +15 -2
  343. package/packages/server/src/runtime-overlay/runtime-update-checker.ts +11 -2
  344. package/packages/server/src/server.ts +1537 -246
  345. package/packages/server/src/services/attached-driver.ts +175 -0
  346. package/packages/server/src/services/change-notifier.ts +55 -0
  347. package/packages/server/src/services/cli-service.ts +450 -0
  348. package/packages/server/src/services/command-runner.ts +92 -0
  349. package/packages/server/src/services/definitions-store.ts +121 -0
  350. package/packages/server/src/services/driver.ts +112 -0
  351. package/packages/server/src/services/health.ts +94 -0
  352. package/packages/server/src/services/leases.ts +117 -0
  353. package/packages/server/src/services/log-text.ts +97 -0
  354. package/packages/server/src/services/native-driver.ts +283 -0
  355. package/packages/server/src/services/oci-driver.ts +590 -0
  356. package/packages/server/src/services/output-capture.ts +183 -0
  357. package/packages/server/src/services/paths.ts +82 -0
  358. package/packages/server/src/services/ports.ts +26 -0
  359. package/packages/server/src/services/routes.ts +140 -0
  360. package/packages/server/src/services/runtime-detect.ts +108 -0
  361. package/packages/server/src/services/secret-delivery.ts +61 -0
  362. package/packages/server/src/services/secrets-resolver.ts +145 -0
  363. package/packages/server/src/services/secrets-store.ts +137 -0
  364. package/packages/server/src/services/service-manager.ts +1565 -0
  365. package/packages/server/src/services/start-record.ts +66 -0
  366. package/packages/server/src/services/state-machine.ts +241 -0
  367. package/packages/server/src/session/archive-sweeper.ts +92 -3
  368. package/packages/server/src/session/custom-event-group-matcher.ts +4 -3
  369. package/packages/server/src/session/hydration-state.ts +148 -0
  370. package/packages/server/src/session/in-flight-tool-calls.ts +74 -0
  371. package/packages/server/src/session/memory-session-manager.ts +60 -0
  372. package/packages/server/src/session/name-provenance.ts +102 -0
  373. package/packages/server/src/session/open-tool-calls.ts +15 -6
  374. package/packages/server/src/session/replay-exit-controller.ts +221 -0
  375. package/packages/server/src/session/retained-transcript.ts +9 -2
  376. package/packages/server/src/session/session-api.ts +47 -12
  377. package/packages/server/src/session/session-archive.ts +56 -4
  378. package/packages/server/src/session/session-diff-cache.ts +11 -4
  379. package/packages/server/src/session/session-load-worker-pool.ts +4 -3
  380. package/packages/server/src/session/session-load-worker.ts +11 -2
  381. package/packages/server/src/session/session-scanner.ts +73 -3
  382. package/packages/server/src/session/session-to-meta.ts +15 -0
  383. package/packages/server/src/spawn-process/abort-spawned-run.ts +55 -0
  384. package/packages/server/src/spawn-process/acp-spawn.ts +131 -0
  385. package/packages/server/src/spawn-process/headless-pid-registry.ts +14 -9
  386. package/packages/server/src/spawn-process/process-manager.ts +164 -30
  387. package/packages/server/src/spawn-process/restart-helper.ts +9 -8
  388. package/packages/server/src/spawn-process/server-pid.ts +16 -7
  389. package/packages/server/src/spawn-process/session-terminator.ts +218 -0
  390. package/packages/server/src/spawn-process/spawn-env-contributors.ts +159 -0
  391. package/packages/server/src/spawn-process/spawn-register-watchdog.ts +10 -1
  392. package/packages/server/src/terminal/terminal-manager.ts +75 -1
  393. package/packages/server/src/tls/cert-files.ts +228 -0
  394. package/packages/server/src/tls/cert-manager.ts +703 -0
  395. package/packages/server/src/tls/cert-store.ts +69 -0
  396. package/packages/server/src/tls/source-registry.ts +71 -0
  397. package/packages/server/src/tls/sources/acme/accounts.ts +76 -0
  398. package/packages/server/src/tls/sources/acme/acme-source.ts +508 -0
  399. package/packages/server/src/tls/sources/acme/config-projection.ts +34 -0
  400. package/packages/server/src/tls/sources/acme/credentials.ts +185 -0
  401. package/packages/server/src/tls/sources/acme/dns.ts +303 -0
  402. package/packages/server/src/tls/sources/acme/e2e-overrides.ts +49 -0
  403. package/packages/server/src/tls/sources/acme/entry.ts +180 -0
  404. package/packages/server/src/tls/sources/acme/gc.ts +78 -0
  405. package/packages/server/src/tls/sources/acme/runtime.ts +51 -0
  406. package/packages/server/src/tls/sources/acme/solvers/acme-dns.ts +154 -0
  407. package/packages/server/src/tls/sources/acme/solvers/cloudflare.ts +147 -0
  408. package/packages/server/src/tls/sources/acme/types.ts +72 -0
  409. package/packages/server/src/tls/sources/tailscale-cert.ts +172 -0
  410. package/packages/server/src/tls/tls-bridge-route.ts +61 -0
  411. package/packages/server/src/tls/tls-config-validation.ts +94 -0
  412. package/packages/server/src/tls/tls-listener.ts +351 -0
  413. package/packages/server/src/tls/types.ts +80 -0
  414. package/packages/server/src/tunnel/tunnel-block-events.ts +4 -1
  415. package/packages/server/src/tunnel/tunnel-core.ts +4 -1
  416. package/packages/server/src/tunnel/tunnel-endpoints.ts +4 -0
  417. package/packages/server/src/tunnel-providers/tailscale.ts +27 -6
  418. package/packages/server/src/vault/device-expiry-sweep.ts +36 -0
  419. package/packages/server/src/vault/vault-bindings.ts +101 -0
  420. package/packages/server/src/vault/vault-delivery-hub.ts +424 -0
  421. package/packages/server/src/vault/vault-grants.ts +260 -0
  422. package/packages/server/src/vault/vault-import.ts +161 -0
  423. package/packages/server/src/vault/vault-permissions.ts +39 -0
  424. package/packages/server/src/vault/vault-plugin-read.ts +64 -0
  425. package/packages/server/src/vault/vault-projects.ts +156 -0
  426. package/packages/server/src/vault/vault-routes.ts +277 -0
  427. package/packages/server/src/vault/vault-store.ts +371 -0
  428. package/packages/server/src/watch-files-handler.ts +66 -0
  429. package/packages/shared/package.json +5 -2
  430. package/packages/shared/src/acp/acp-config.ts +123 -0
  431. package/packages/shared/src/acp/normalize-v1.ts +92 -0
  432. package/packages/shared/src/acp/paths.ts +36 -0
  433. package/packages/shared/src/acp/to-dashboard-events.ts +533 -0
  434. package/packages/shared/src/acp/update-model.ts +574 -0
  435. package/packages/shared/src/anthropic-messages-source.ts +8 -0
  436. package/packages/shared/src/bind-reachability.ts +21 -2
  437. package/packages/shared/src/boot-state.ts +6 -0
  438. package/packages/shared/src/browser-host-identity.ts +49 -0
  439. package/packages/shared/src/browser-host-ipc.ts +107 -0
  440. package/packages/shared/src/browser-protocol.ts +533 -73
  441. package/packages/shared/src/canonical-subject.ts +27 -2
  442. package/packages/shared/src/canvas-declare.ts +27 -0
  443. package/packages/shared/src/card-sections.ts +185 -1
  444. package/packages/shared/src/chrome-profiles.ts +188 -0
  445. package/packages/shared/src/config.ts +817 -51
  446. package/packages/shared/src/containment-guard.ts +35 -0
  447. package/packages/shared/src/custom-event-groups.ts +5 -2
  448. package/packages/shared/src/cwd-guard.ts +381 -1
  449. package/packages/shared/src/dashboard-paths.ts +12 -0
  450. package/packages/shared/src/dashboard-plugin/anthropic-peer-names.ts +9 -0
  451. package/packages/shared/src/dashboard-plugin/editor-pane-tab.ts +26 -0
  452. package/packages/shared/src/dashboard-plugin/event-type-owners.ts +50 -0
  453. package/packages/shared/src/dashboard-plugin/file-handler.ts +73 -0
  454. package/packages/shared/src/dashboard-plugin/host-api.ts +61 -0
  455. package/packages/shared/src/dashboard-plugin/host-fx-classes.ts +23 -0
  456. package/packages/shared/src/dashboard-plugin/host-import-map.ts +38 -0
  457. package/packages/shared/src/dashboard-plugin/index.ts +9 -3
  458. package/packages/shared/src/dashboard-plugin/manifest-types.ts +160 -3
  459. package/packages/shared/src/dashboard-plugin/plugin-status.ts +54 -0
  460. package/packages/shared/src/dashboard-plugin/project-identity.ts +42 -0
  461. package/packages/shared/src/dashboard-plugin/project-markers.ts +60 -0
  462. package/packages/shared/src/dashboard-plugin/slot-props.ts +139 -2
  463. package/packages/shared/src/dashboard-plugin/slot-types.ts +72 -4
  464. package/packages/shared/src/dashboard-plugin/subagent-types.ts +219 -0
  465. package/packages/shared/src/dashboard-plugin/ui-primitives.ts +50 -3
  466. package/packages/shared/src/dashboard-starter.ts +30 -0
  467. package/packages/shared/src/display-name.ts +42 -0
  468. package/packages/shared/src/display-prefs.ts +13 -0
  469. package/packages/shared/src/doctor-core.ts +119 -134
  470. package/packages/shared/src/enabled-models-match.ts +47 -0
  471. package/packages/shared/src/event-forward-declaration.ts +187 -0
  472. package/packages/shared/src/file-kind.ts +54 -2
  473. package/packages/shared/src/git-worktree-helpers.ts +8 -4
  474. package/packages/shared/src/grammar-types.ts +3 -1
  475. package/packages/shared/src/host-admission.ts +2 -1
  476. package/packages/shared/src/host-port.ts +34 -0
  477. package/packages/shared/src/launcher-origin.ts +26 -0
  478. package/packages/shared/src/live-server.ts +141 -0
  479. package/packages/shared/src/local-credential-proof.ts +219 -0
  480. package/packages/shared/src/local-proof-signal.ts +16 -0
  481. package/packages/shared/src/loopback-host.ts +26 -0
  482. package/packages/shared/src/markup-repair/asciidoc.ts +130 -0
  483. package/packages/shared/src/markup-repair/types.ts +13 -0
  484. package/packages/shared/src/mcp/verb-tiers.generated.ts +178 -0
  485. package/packages/shared/src/md-table-cell.ts +11 -0
  486. package/packages/shared/src/mdns-discovery.ts +414 -45
  487. package/packages/shared/src/models-json-reader.ts +6 -0
  488. package/packages/shared/src/nav-intent.ts +29 -0
  489. package/packages/shared/src/openspec-dependencies.ts +760 -0
  490. package/packages/shared/src/openspec-design-evidence.ts +25 -1
  491. package/packages/shared/src/openspec-poller.ts +213 -11
  492. package/packages/shared/src/openspec-status-all.ts +393 -0
  493. package/packages/shared/src/operate-required.ts +29 -0
  494. package/packages/shared/src/pairing-knock-client.ts +301 -0
  495. package/packages/shared/src/pairing-knock.ts +71 -0
  496. package/packages/shared/src/pairing-refusal.ts +32 -0
  497. package/packages/shared/src/path-containment-guard-name.ts +8 -0
  498. package/packages/shared/src/pi-settings-keys.ts +9 -0
  499. package/packages/shared/src/pi-settings-schema.ts +285 -0
  500. package/packages/shared/src/pi-trust-live-query.ts +93 -0
  501. package/packages/shared/src/pi-trust-mirror-snapshot.ts +198 -0
  502. package/packages/shared/src/pi-trust-mirror-types.ts +90 -0
  503. package/packages/shared/src/pi-trust-mirror.ts +354 -0
  504. package/packages/shared/src/pi-trust-resource-digest.ts +255 -0
  505. package/packages/shared/src/platform/binary-lookup.ts +2 -194
  506. package/packages/shared/src/platform/ensure-bundled-git.ts +57 -34
  507. package/packages/shared/src/platform/git-source.ts +88 -26
  508. package/packages/shared/src/platform/git.ts +210 -4
  509. package/packages/shared/src/platform/native-ts-hooks.mjs +93 -40
  510. package/packages/shared/src/platform/native-ts-register.mjs +22 -10
  511. package/packages/shared/src/platform/native-ts-tier.d.mts +1 -0
  512. package/packages/shared/src/platform/native-ts-tier.mjs +17 -0
  513. package/packages/shared/src/platform/node-spawn.ts +1 -2
  514. package/packages/shared/src/platform/openspec.ts +129 -31
  515. package/packages/shared/src/platform/process-scan.ts +199 -1
  516. package/packages/shared/src/platform/process.ts +99 -4
  517. package/packages/shared/src/platform/resolve-pi-shell.ts +76 -0
  518. package/packages/shared/src/platform/runner.ts +46 -2
  519. package/packages/shared/src/platform/select-git-source.ts +7 -0
  520. package/packages/shared/src/platform/spawn-mechanism.ts +14 -2
  521. package/packages/shared/src/platform/ts-loader-select.d.mts +1 -7
  522. package/packages/shared/src/platform/ts-loader-select.mjs +14 -43
  523. package/packages/shared/src/plugin-bridge-register.ts +24 -1
  524. package/packages/shared/src/plugin-route-cwd.ts +95 -0
  525. package/packages/shared/src/preview-egress.ts +138 -0
  526. package/packages/shared/src/project-name.ts +42 -0
  527. package/packages/shared/src/project-root.ts +16 -0
  528. package/packages/shared/src/prompt-answer.ts +183 -0
  529. package/packages/shared/src/protocol.ts +172 -8
  530. package/packages/shared/src/question-types.ts +73 -0
  531. package/packages/shared/src/recommended-extensions.ts +98 -23
  532. package/packages/shared/src/recovery-timing.ts +39 -0
  533. package/packages/shared/src/redaction.ts +50 -0
  534. package/packages/shared/src/remote-credentials.ts +63 -0
  535. package/packages/shared/src/rest-api.ts +533 -3
  536. package/packages/shared/src/role-config-disk.ts +23 -0
  537. package/packages/shared/src/role-schema.ts +79 -0
  538. package/packages/shared/src/route-tiers.ts +181 -0
  539. package/packages/shared/src/runtime-overlay/archive-safety.d.mts +2 -0
  540. package/packages/shared/src/runtime-overlay/archive-safety.mjs +33 -0
  541. package/packages/shared/src/runtime-overlay/manifest.d.mts +7 -0
  542. package/packages/shared/src/runtime-overlay/manifest.mjs +22 -2
  543. package/packages/shared/src/runtime-overlay/materialize-plugins.d.mts +17 -0
  544. package/packages/shared/src/runtime-overlay/materialize-plugins.mjs +119 -8
  545. package/packages/shared/src/safe-local-path.ts +24 -0
  546. package/packages/shared/src/sanitize-profiles.ts +98 -0
  547. package/packages/shared/src/server-identity.ts +51 -15
  548. package/packages/shared/src/server-launcher.ts +21 -34
  549. package/packages/shared/src/server-pinning.ts +136 -2
  550. package/packages/shared/src/server-routes.ts +462 -0
  551. package/packages/shared/src/services/offers.ts +114 -0
  552. package/packages/shared/src/services/schema.ts +628 -0
  553. package/packages/shared/src/services/status.ts +169 -0
  554. package/packages/shared/src/session-meta.ts +59 -2
  555. package/packages/shared/src/session-name.ts +8 -0
  556. package/packages/shared/src/session-ui-path.ts +11 -0
  557. package/packages/shared/src/skill-block-parser.ts +14 -0
  558. package/packages/shared/src/source-matching.ts +5 -1
  559. package/packages/shared/src/state-replay.ts +19 -0
  560. package/packages/shared/src/terminal-safe.ts +24 -0
  561. package/packages/shared/src/tls-only-token.ts +16 -0
  562. package/packages/shared/src/tls-status.ts +69 -0
  563. package/packages/shared/src/tool-path-resolve.ts +243 -0
  564. package/packages/shared/src/tool-registry/definitions.ts +31 -9
  565. package/packages/shared/src/tool-registry/index.ts +2 -2
  566. package/packages/shared/src/tool-registry/pi-tools.ts +32 -3
  567. package/packages/shared/src/tool-registry/strategies.ts +12 -11
  568. package/packages/shared/src/tunnel-provider.ts +3 -2
  569. package/packages/shared/src/types.ts +170 -9
  570. package/packages/shared/src/url-policy.ts +96 -0
  571. package/packages/shared/src/vault-delivery.ts +88 -0
  572. package/packages/shared/src/vault-origin.ts +51 -0
  573. package/packages/shared/src/vault-project-key.ts +53 -0
  574. package/packages/shared/src/worktree-init-hook.ts +69 -0
  575. package/packages/shared/src/ws-message-tiers.ts +136 -0
  576. package/tsconfig.base.json +1 -0
@@ -7,15 +7,25 @@
7
7
  * new paths get an `fs.watch`, gone paths are closed. `clearConnection` tears
8
8
  * every watcher for a disconnected browser down so no file descriptors leak.
9
9
  *
10
- * Best-effort: `fs.watch` is path-based. On Linux (inotify) a rename-in-place
11
- * edit (tmp + rename) can detach the watch from the new inode, so a later
12
- * change may not fire. The banner is a hint, not a guarantee; the pane's manual
13
- * refresh stays authoritative.
10
+ * `fs.watch` is path-based but binds to the inode, so an atomic replace
11
+ * (tmp + `rename`: the pane's own Save, formatters, `git checkout`) leaves the
12
+ * watcher on the old inode and later changes would go unseen. On a `rename`
13
+ * event the entry therefore re-attaches SYNCHRONOUSLY to the path (only if it
14
+ * is a regular file); a path that is missing (delete + quick re-create) is
15
+ * retried at 100/300/600/1000 ms, then the key is dropped. A path replaced by a
16
+ * non-regular file (directory, FIFO) drops the key at once. `change` events
17
+ * never re-attach (no fd churn). Every event is still only a *candidate*: the
18
+ * client verifies it against a content digest before showing the banner.
14
19
  *
15
- * See change: split-editor-workspace.
20
+ * Timers (retry + debounce) live on the per-key entry and are cancelled by
21
+ * reconcile-removal / `clearConnection`, so no retry can resurrect a dropped
22
+ * key. Handlers act only on the watcher instance the entry still holds, so a
23
+ * stale `error`/event from a replaced watcher never touches its successor.
24
+ *
25
+ * See change: split-editor-workspace, gate-changed-on-disk-by-content (D5).
16
26
  */
17
27
 
18
- import { type FSWatcher, watch } from "node:fs";
28
+ import { type FSWatcher, statSync, watch } from "node:fs";
19
29
  import path from "node:path";
20
30
 
21
31
  /** Synchronous logical containment: `abs` equals or sits under `cwd`. */
@@ -42,25 +52,171 @@ export interface FileWatchManager {
42
52
  clearConnection(ws: object): void;
43
53
  /** Total live `fs.watch` handles (tests / diagnostics). */
44
54
  activeWatchCount(): number;
55
+ /** Pending retry + debounce timers on held keys (tests / diagnostics). */
56
+ pendingTimerCount(): number;
57
+ }
58
+
59
+ /** Test seams: the `fs.watch` factory. */
60
+ export interface FileWatchManagerDeps {
61
+ watchFn?: typeof watch;
45
62
  }
46
63
 
47
64
  const CHANGE_DEBOUNCE_MS = 40;
65
+ /** Delays (ms after the `rename`) at which a missing path is retried before the key is dropped. */
66
+ const REATTACH_RETRY_DELAYS_MS = [100, 300, 600, 1000] as const;
67
+
68
+ type PathState = "file" | "other" | "missing";
69
+
70
+ function pathState(abs: string): PathState {
71
+ try {
72
+ return statSync(abs).isFile() ? "file" : "other";
73
+ } catch {
74
+ return "missing";
75
+ }
76
+ }
77
+
78
+ /**
79
+ * One watched (connection, session, path) key: the live `fs.watch` handle plus
80
+ * the retry and debounce timers that belong to it. `drop` is invoked when the
81
+ * key must leave the manager's map (retries exhausted, non-regular file,
82
+ * watcher error); `release` frees the handle + retry timer, `cancel` also
83
+ * silences a pending debounce so nothing fires after a teardown.
84
+ */
85
+ class WatchedFile {
86
+ private watcher: FSWatcher | null = null;
87
+ private retryTimer: NodeJS.Timeout | null = null;
88
+ private debounceTimer: NodeJS.Timeout | null = null;
89
+ private cancelled = false;
90
+
91
+ private readonly abs: string;
92
+ private readonly watchFn: typeof watch;
93
+ private readonly emit: () => void;
94
+ private readonly drop: (self: WatchedFile) => void;
48
95
 
49
- export function createFileWatchManager(): FileWatchManager {
50
- // ws → keyString → FSWatcher. keyString = `${sessionId}\u0000${relPath}`.
51
- const byConnection = new Map<object, Map<string, FSWatcher>>();
96
+ constructor(abs: string, watchFn: typeof watch, emit: () => void, drop: (self: WatchedFile) => void) {
97
+ this.abs = abs;
98
+ this.watchFn = watchFn;
99
+ this.emit = emit;
100
+ this.drop = drop;
101
+ }
102
+
103
+ hasWatcher(): boolean {
104
+ return this.watcher !== null;
105
+ }
106
+
107
+ pendingTimers(): number {
108
+ return (this.retryTimer ? 1 : 0) + (this.debounceTimer ? 1 : 0);
109
+ }
110
+
111
+ /** Bind a fresh watcher to the path. Throws if the path cannot be watched. */
112
+ attach(): void {
113
+ const watcher = this.watchFn(this.abs, (eventType) => {
114
+ if (this.watcher !== watcher) return; // stale instance
115
+ if (eventType === "rename") this.reattach();
116
+ this.scheduleChange();
117
+ });
118
+ watcher.on("error", () => {
119
+ // Act only on the instance still held: an old watcher's late `error`
120
+ // must not close its re-attached successor.
121
+ if (this.watcher === watcher) this.drop(this);
122
+ });
123
+ this.watcher = watcher;
124
+ }
125
+
126
+ /** Free the handle + retry timer; a pending debounce still fires once. */
127
+ release(): void {
128
+ if (this.retryTimer) clearTimeout(this.retryTimer);
129
+ this.retryTimer = null;
130
+ this.closeHandle();
131
+ }
132
+
133
+ /** Explicit teardown: release AND cancel the debounce. */
134
+ cancel(): void {
135
+ this.cancelled = true;
136
+ if (this.debounceTimer) clearTimeout(this.debounceTimer);
137
+ this.debounceTimer = null;
138
+ this.release();
139
+ }
140
+
141
+ private closeHandle(): void {
142
+ const w = this.watcher;
143
+ this.watcher = null;
144
+ try {
145
+ w?.close();
146
+ } catch {
147
+ /* already closed */
148
+ }
149
+ }
150
+
151
+ private scheduleChange(): void {
152
+ if (this.debounceTimer) return; // debounce a burst of events into one
153
+ this.debounceTimer = setTimeout(() => {
154
+ this.debounceTimer = null;
155
+ if (!this.cancelled) this.emit();
156
+ }, CHANGE_DEBOUNCE_MS);
157
+ }
158
+
159
+ /** `rename`: the old inode is gone — bind to whatever is at the path now. */
160
+ private reattach(): void {
161
+ if (this.retryTimer) clearTimeout(this.retryTimer);
162
+ this.retryTimer = null;
163
+ this.closeHandle();
164
+ const state = pathState(this.abs);
165
+ if (state === "other") return this.drop(this); // never watch a directory / FIFO
166
+ if (state === "file" && this.tryAttach()) return;
167
+ this.retry(0);
168
+ }
169
+
170
+ private tryAttach(): boolean {
171
+ try {
172
+ this.attach();
173
+ return true;
174
+ } catch {
175
+ return false; // vanished between stat and watch
176
+ }
177
+ }
178
+
179
+ /** Retry a missing path at the bounded delays, then drop the key. */
180
+ private retry(attempt: number): void {
181
+ if (attempt >= REATTACH_RETRY_DELAYS_MS.length) return this.drop(this);
182
+ const prev = attempt === 0 ? 0 : REATTACH_RETRY_DELAYS_MS[attempt - 1];
183
+ this.retryTimer = setTimeout(() => {
184
+ this.retryTimer = null;
185
+ const state = pathState(this.abs);
186
+ if (state === "other") return this.drop(this);
187
+ if (state === "file" && this.tryAttach()) return this.scheduleChange(); // re-created: have the client re-verify
188
+ this.retry(attempt + 1);
189
+ }, REATTACH_RETRY_DELAYS_MS[attempt] - prev);
190
+ }
191
+ }
192
+
193
+ export function createFileWatchManager(deps: FileWatchManagerDeps = {}): FileWatchManager {
194
+ const watchFn = deps.watchFn ?? watch;
195
+ // ws → keyString → entry. keyString = `${sessionId}\u0000${relPath}`.
196
+ const byConnection = new Map<object, Map<string, WatchedFile>>();
52
197
 
53
198
  const keyOf = (k: WatchKey) => `${k.sessionId}\u0000${k.relPath}`;
54
199
 
55
- function closeWatcher(map: Map<string, FSWatcher>, keyString: string): void {
56
- const w = map.get(keyString);
57
- if (w) {
58
- try {
59
- w.close();
60
- } catch {
61
- /* already closed */
62
- }
63
- map.delete(keyString);
200
+ function closeEntry(map: Map<string, WatchedFile>, keyString: string): void {
201
+ map.get(keyString)?.cancel();
202
+ map.delete(keyString);
203
+ }
204
+
205
+ function addWatch(
206
+ map: Map<string, WatchedFile>,
207
+ keyString: string,
208
+ abs: string,
209
+ emit: () => void,
210
+ ): void {
211
+ const entry = new WatchedFile(abs, watchFn, emit, (self) => {
212
+ self.release();
213
+ if (map.get(keyString) === self) map.delete(keyString);
214
+ });
215
+ try {
216
+ entry.attach();
217
+ map.set(keyString, entry);
218
+ } catch {
219
+ /* file vanished / unwatchable — skip */
64
220
  }
65
221
  }
66
222
 
@@ -71,51 +227,43 @@ export function createFileWatchManager(): FileWatchManager {
71
227
  map = new Map();
72
228
  byConnection.set(ws, map);
73
229
  }
230
+ const held = map;
74
231
 
75
232
  // Desired keys for THIS session (other sessions on the same ws untouched).
76
233
  const desired = new Set(relPaths.map((rel) => keyOf({ sessionId, relPath: rel })));
77
234
 
78
235
  // Remove watchers for this session's paths that are no longer desired.
79
236
  const sessionPrefix = `${sessionId}\u0000`;
80
- for (const existing of [...map.keys()]) {
81
- if (existing.startsWith(sessionPrefix) && !desired.has(existing)) {
82
- closeWatcher(map, existing);
83
- }
237
+ for (const existing of [...held.keys()]) {
238
+ if (existing.startsWith(sessionPrefix) && !desired.has(existing)) closeEntry(held, existing);
84
239
  }
85
240
 
86
241
  // Add watchers for newly-desired paths (synchronous, cwd-contained).
87
242
  for (const rel of relPaths) {
88
243
  const keyString = keyOf({ sessionId, relPath: rel });
89
- if (map.has(keyString)) continue; // already watched
244
+ if (held.has(keyString)) continue; // already watched
90
245
  const abs = path.resolve(cwd, rel);
91
246
  if (!withinCwd(abs, cwd)) continue; // never watch outside cwd
92
- let timer: NodeJS.Timeout | null = null;
93
- try {
94
- const watcher = watch(abs, () => {
95
- if (timer) return; // debounce a burst of events into one
96
- timer = setTimeout(() => {
97
- timer = null;
98
- onChange(sessionId, rel);
99
- }, CHANGE_DEBOUNCE_MS);
100
- });
101
- watcher.on("error", () => closeWatcher(map!, keyString));
102
- map.set(keyString, watcher);
103
- } catch {
104
- /* file vanished / unwatchable — skip */
105
- }
247
+ addWatch(held, keyString, abs, () => onChange(sessionId, rel));
106
248
  }
107
249
  },
108
250
 
109
251
  clearConnection(ws) {
110
252
  const map = byConnection.get(ws);
111
253
  if (!map) return;
112
- for (const key of [...map.keys()]) closeWatcher(map, key);
254
+ for (const key of [...map.keys()]) closeEntry(map, key);
113
255
  byConnection.delete(ws);
114
256
  },
115
257
 
116
258
  activeWatchCount() {
117
259
  let n = 0;
118
- for (const map of byConnection.values()) n += map.size;
260
+ for (const map of byConnection.values()) for (const e of map.values()) if (e.hasWatcher()) n++;
261
+ return n;
262
+ },
263
+
264
+ pendingTimerCount() {
265
+ let n = 0;
266
+ for (const map of byConnection.values()) for (const e of map.values()) n += e.pendingTimers();
119
267
  return n;
120
268
  },
121
269
  };
@@ -11,6 +11,7 @@ import { execFile as nodeExecFile } from "node:child_process"; // ban:child_proc
11
11
  import fs from "node:fs";
12
12
  import path from "node:path";
13
13
  import { promisify } from "node:util";
14
+ import { collapseCheckRollup } from "@blackbelt-technology/pi-dashboard-shared/platform/check-rollup.js";
14
15
  import { type ChildProcess, execFileSync, spawn, spawnSync } from "@blackbelt-technology/pi-dashboard-shared/platform/exec.js";
15
16
  import {
16
17
  checkoutRoots,
@@ -18,7 +19,6 @@ import {
18
19
  gitStatusV2,
19
20
  hasGitPathSegment,
20
21
  } from "@blackbelt-technology/pi-dashboard-shared/platform/git.js";
21
- import { collapseCheckRollup } from "@blackbelt-technology/pi-dashboard-shared/platform/check-rollup.js";
22
22
  import { samePath } from "@blackbelt-technology/pi-dashboard-shared/platform/paths.js";
23
23
  import type { GitChangedFile, GitCommitResult } from "@blackbelt-technology/pi-dashboard-shared/rest-api.js";
24
24
  import type { GitStatus } from "@blackbelt-technology/pi-dashboard-shared/types.js";
@@ -27,6 +27,8 @@ import type { GitStatus } from "@blackbelt-technology/pi-dashboard-shared/types.
27
27
  // are otherwise un-spyable). `pruneWorktrees` calls `self.resolveMainPath`.
28
28
  // See change: support-non-git-init-hook.
29
29
  import * as self from "./git-operations.js";
30
+ import { redactGitText } from "./redact-git-text.js";
31
+ import { assertRefArg, isValidRefArg } from "./ref-arg.js";
30
32
  import {
31
33
  ensureWorktreeExcludeLine,
32
34
  isOrphanWorktreePath,
@@ -201,8 +203,15 @@ export function getGitStatus(cwd: string): GitStatus | undefined {
201
203
  * so the route can surface it to the dialog without string-matching stderr.
202
204
  */
203
205
  export class GitCommitError extends Error {
206
+ public code: | "not-a-repo"
207
+ | "path-escape"
208
+ | "no-files"
209
+ | "empty-message"
210
+ | "stage-failed"
211
+ | "commit-failed";
212
+
204
213
  constructor(
205
- public code:
214
+ code:
206
215
  | "not-a-repo"
207
216
  | "path-escape"
208
217
  | "no-files"
@@ -212,6 +221,7 @@ export class GitCommitError extends Error {
212
221
  message: string,
213
222
  ) {
214
223
  super(message);
224
+ this.code = code;
215
225
  this.name = "GitCommitError";
216
226
  }
217
227
  }
@@ -317,12 +327,12 @@ export async function commitFiles(opts: {
317
327
 
318
328
  const staged = await runGitCapture(["add", "--", ...safePaths], cwd);
319
329
  if (staged.code !== 0) {
320
- throw new GitCommitError("stage-failed", staged.stderr.trim() || "git add failed");
330
+ throw new GitCommitError("stage-failed", redactGitText(staged.stderr.trim() || "git add failed", { root: cwd }));
321
331
  }
322
332
 
323
333
  const committed = await runGitCapture(["commit", "-F", "-", "--", ...safePaths], cwd, message);
324
334
  if (committed.code !== 0) {
325
- throw new GitCommitError("commit-failed", committed.stderr.trim() || "git commit failed");
335
+ throw new GitCommitError("commit-failed", redactGitText(committed.stderr.trim() || "git commit failed", { root: cwd }));
326
336
  }
327
337
 
328
338
  const head = await runGitCapture(["rev-parse", "HEAD"], cwd);
@@ -346,7 +356,7 @@ export async function getChangedFiles(cwd: string): Promise<GitChangedFile[]> {
346
356
  // Propagate a real git failure instead of masking it as "no changes". A
347
357
  // clean tree still exits 0 with empty stdout → `[]` below.
348
358
  if (statusRes.code !== 0) {
349
- throw new GitCommitError("not-a-repo", statusRes.stderr.trim() || "git status failed");
359
+ throw new GitCommitError("not-a-repo", redactGitText(statusRes.stderr.trim() || "git status failed", { root: cwd }));
350
360
  }
351
361
 
352
362
  const files: GitChangedFile[] = [];
@@ -431,8 +441,10 @@ export function listBranches(cwd: string): BranchInfo {
431
441
 
432
442
  const localBranches: BranchInfo["branches"] = [];
433
443
  for (const line of rawLocal.split("\n").filter(Boolean)) {
434
- const isCurrent = line.includes("*");
435
- const name = line.replace("*", "").trim();
444
+ // `%(HEAD)` appends `*` for the current branch (git forbids `*` in ref names).
445
+ const t = line.trim();
446
+ const isCurrent = t.endsWith("*");
447
+ const name = (isCurrent ? t.slice(0, -1) : t).trim();
436
448
  if (!name) continue;
437
449
  localBranches.push({ name, isRemote: false, isCurrent });
438
450
  }
@@ -442,7 +454,8 @@ export function listBranches(cwd: string): BranchInfo {
442
454
 
443
455
  const remoteBranches: BranchInfo["branches"] = [];
444
456
  for (const line of rawRemote.split("\n").filter(Boolean)) {
445
- const name = line.replace("*", "").trim();
457
+ const t = line.trim();
458
+ const name = (t.endsWith("*") ? t.slice(0, -1) : t).trim();
446
459
  // Skip HEAD pointers like "origin/HEAD"
447
460
  if (name.endsWith("/HEAD")) continue;
448
461
  // Skip remote branches that have a local counterpart
@@ -469,12 +482,24 @@ export interface CheckoutDirty {
469
482
  files: string[];
470
483
  }
471
484
 
472
- /** Checkout a branch. Returns dirty info if working tree is dirty and stash=false. */
485
+ /**
486
+ * Checkout a branch. Returns dirty info if working tree is dirty and stash=false.
487
+ * Throws `InvalidRefError` (before ANY git process starts) when `branch`, or the local name
488
+ * derived from it by stripping the remote prefix, is not a safe positional git argument.
489
+ * See change: harden-git-terminal-plugin-boundaries (B1r).
490
+ */
473
491
  export function checkoutBranch(
474
492
  cwd: string,
475
493
  branch: string,
476
494
  stash: boolean
477
495
  ): CheckoutResult | CheckoutDirty {
496
+ assertRefArg(branch, "branch");
497
+ // Check if this is a remote branch that needs a local tracking branch
498
+ const isRemote = branch.includes("/");
499
+ const localName = isRemote ? branch.replace(/^[^/]+\//, "") : branch;
500
+ // The derived name reaches `git checkout [-b] <localName>`: validate it too (`origin/-x`, `origin/`).
501
+ if (isRemote) assertRefArg(localName, "local branch name");
502
+
478
503
  // Already on this branch?
479
504
  const headRef = tryRun(["git", "rev-parse", "--abbrev-ref", "HEAD"], cwd);
480
505
  if (headRef === branch) return { success: true };
@@ -491,10 +516,7 @@ export function checkoutBranch(
491
516
  stashed = true;
492
517
  }
493
518
 
494
- // Check if this is a remote branch that needs a local tracking branch
495
- const isRemote = branch.includes("/");
496
519
  if (isRemote) {
497
- const localName = branch.replace(/^[^/]+\//, "");
498
520
  // Check if local branch exists
499
521
  const localExists = tryRun(["git", "rev-parse", "--verify", `refs/heads/${localName}`], cwd);
500
522
  if (!localExists) {
@@ -680,6 +702,8 @@ export function pruneWorktrees(
680
702
  export type AddWorktreeError =
681
703
  | "not_a_repo"
682
704
  | "cwd_invalid"
705
+ /** A caller-supplied ref / path is option-like or has control characters (B1r). */
706
+ | "invalid_ref"
683
707
  | "branch_in_use"
684
708
  | "branch_exists"
685
709
  | "path_exists"
@@ -711,6 +735,10 @@ export interface AddWorktreeFailure {
711
735
  orphanLikely?: boolean;
712
736
  }
713
737
 
738
+ function invalidRef(what: string): { ok: false; error: "invalid_ref"; message: string } {
739
+ return { ok: false, error: "invalid_ref", message: `invalid ${what}` };
740
+ }
741
+
714
742
  export interface AddWorktreeOptions {
715
743
  /** Cwd inside the parent repo (any worktree's path resolves to the same parent). */
716
744
  cwd: string;
@@ -739,6 +767,12 @@ export interface AddWorktreeOptions {
739
767
  */
740
768
  export function addWorktree(opts: AddWorktreeOptions): AddWorktreeSuccess | AddWorktreeFailure {
741
769
  const { cwd, base, newBranch, force } = opts;
770
+ // B1r: every caller-supplied argument is validated before any git process starts. `path` is
771
+ // optional (absent → derived default); `newBranch` absent → checkout mode.
772
+ // See change: harden-git-terminal-plugin-boundaries.
773
+ if (!isValidRefArg(base)) return invalidRef("base");
774
+ if (newBranch !== undefined && !isValidRefArg(newBranch)) return invalidRef("newBranch");
775
+ if (opts.path !== undefined && opts.path !== "" && !isValidRefArg(opts.path)) return invalidRef("path");
742
776
  // Checkout mode = no newBranch. `base` is the existing branch ref to
743
777
  // check out. See change: worktree-checkout-existing-branch.
744
778
  const checkoutMode = newBranch === undefined;
@@ -769,6 +803,8 @@ export function addWorktree(opts: AddWorktreeOptions): AddWorktreeSuccess | AddW
769
803
  // branch name (bare name triggers DWIM for remote-only refs); fork mode
770
804
  // forks from `base`.
771
805
  const checkoutCommitish = resolvedBranch;
806
+ // The derived local name (`origin/-x` → `-x`) reaches git as a positional argument too.
807
+ if (!isValidRefArg(resolvedBranch)) return invalidRef("derived branch name");
772
808
  // Derive worktree path when not supplied. Fork mode slugs the new
773
809
  // branch name; checkout mode slugs the local name of the base ref so
774
810
  // `origin/foo` lands at `.worktrees/foo`, not `.worktrees/origin-foo`.
@@ -1264,7 +1300,8 @@ export function resolveDefaultBase(
1264
1300
 
1265
1301
  /** `resolveDefaultBase` that throws `GitMissingError` instead of swallowing a missing binary. */
1266
1302
  function resolveDefaultBaseStrict(cwd: string, hint?: string): string | null {
1267
- if (hint && tryRunStrict(["git", "rev-parse", "--verify", hint], cwd)) return hint;
1303
+ // B1r: a stored hint is untrusted (WS-supplied) — an option-like hint is ignored, never passed to git.
1304
+ if (isValidRefArg(hint) && tryRunStrict(["git", "rev-parse", "--verify", hint], cwd)) return hint;
1268
1305
  for (const name of BASE_FALLBACKS) {
1269
1306
  if (tryRunStrict(["git", "rev-parse", "--verify", `refs/heads/${name}`], cwd)) return name;
1270
1307
  }
@@ -1304,8 +1341,8 @@ export function resolveRemoteBase(
1304
1341
  /** `resolveRemoteBase` that throws `GitMissingError` instead of swallowing a missing binary. */
1305
1342
  function resolveRemoteBaseStrict(cwd: string, hint?: string): string | null {
1306
1343
  const stripOrigin = (n: string) => n.replace(/^origin\//, "");
1307
- const hintBare = hint ? stripOrigin(hint) : undefined;
1308
- if (hintBare && tryRunStrict(["git", "rev-parse", "--verify", `refs/remotes/origin/${hintBare}`], cwd)) {
1344
+ const hintBare = isValidRefArg(hint) ? stripOrigin(hint) : undefined;
1345
+ if (isValidRefArg(hintBare) && tryRunStrict(["git", "rev-parse", "--verify", `refs/remotes/origin/${hintBare}`], cwd)) {
1309
1346
  return hintBare;
1310
1347
  }
1311
1348
  for (const name of BASE_FALLBACKS) {
@@ -1634,6 +1671,7 @@ function computeOrphanLikely(cwd: string, worktreePath: string, mainPath?: strin
1634
1671
  }
1635
1672
 
1636
1673
  export type OrphanCleanupError =
1674
+ | "invalid_ref"
1637
1675
  | "outside_repo"
1638
1676
  | "not_a_directory"
1639
1677
  | "not_orphan"
@@ -1690,6 +1728,11 @@ export function orphanCleanup(
1690
1728
  const maxFiles = opts.maxFiles ?? 20;
1691
1729
  const maxFileSize = opts.maxFileSize ?? 1_048_576; // 1 MB
1692
1730
 
1731
+ // B1r: an option-like / control-character path is refused before anything touches git or the fs.
1732
+ if (!isValidRefArg(targetPath)) {
1733
+ return { ok: false, error: "invalid_ref", message: "invalid path" };
1734
+ }
1735
+
1693
1736
  // ── (i) Resolve the anchor: the RESOLVED main checkout (D6) — an orphan
1694
1737
  // can be cleaned from any worktree of the repo. `null` is a refusal.
1695
1738
  const repoRoot = resolveMainPath(cwd);
@@ -1944,6 +1987,8 @@ export function addWorktreeFromPr(opts: {
1944
1987
  path?: string;
1945
1988
  }): AddWorktreeFromPrSuccess | AddWorktreeFromPrFailure {
1946
1989
  const { cwd, prNumber } = opts;
1990
+ // B1r: an option-like `path` is refused before any git process starts.
1991
+ if (opts.path !== undefined && opts.path !== "" && !isValidRefArg(opts.path)) return invalidRef("path");
1947
1992
  // D2: one resolution proves repo-ness and anchors the derived path. The
1948
1993
  // refusal happens BEFORE any fetch — an unresolvable checkout never
1949
1994
  // touches the network.
@@ -0,0 +1,124 @@
1
+ /**
2
+ * Redaction of git-derived text (error / message / stderr) before it reaches a client.
3
+ *
4
+ * Rules, applied in this order:
5
+ * 1. strip URL userinfo from `http(s)://user:pw@host` (password-less `user@` too);
6
+ * `ssh://user:pw@host` keeps the user, drops the password; scp-form is untouched;
7
+ * 2. mask specific token shapes only (`sk-`, `ghp_`, `github_pat_`, `glpat-`, `Bearer`) to
8
+ * their prefix + `***` — deliberately NOT a generic long-blob rule, so 40-hex commit SHAs
9
+ * survive;
10
+ * 3. absolute paths under the operation's repository root become repo-relative (root → `.`);
11
+ * 4. absolute paths under the home directory become `~/…`;
12
+ * 5. any other absolute path (POSIX or drive-letter) becomes `<path>`.
13
+ *
14
+ * Pure and linear-time: every pattern is anchored on a literal prefix and uses bounded or
15
+ * single-pass character classes (no nested quantifiers). Never throws.
16
+ *
17
+ * See change: harden-git-terminal-plugin-boundaries (B20).
18
+ */
19
+
20
+ import os from "node:os";
21
+
22
+ export interface RedactContext {
23
+ /** The repository / worktree root the git operation ran in. Captured at operation time. */
24
+ root?: string;
25
+ /** Home directory (default: `os.homedir()`). Pass `""` to disable the `~` rule. */
26
+ home?: string;
27
+ }
28
+
29
+ /** `http(s)://[userinfo@]host` — userinfo runs to the LAST `@` of the authority (a raw `@` may sit in a password). */
30
+ const HTTP_USERINFO = /(https?:\/\/)[^\s/]*@/gi;
31
+ /** `ssh://user:password@host` → `ssh://user@host`. */
32
+ const SSH_PASSWORD = /(ssh:\/\/[^\s/:@]*):[^\s/]*@/gi;
33
+ /** Token shapes: prefix + >= 20 `[A-Za-z0-9_-]`, with a non-word character (or start) before the prefix. */
34
+ const TOKEN = /(?<![A-Za-z0-9_])(sk-|ghp_|github_pat_|glpat-)[A-Za-z0-9_-]{20,}/g;
35
+ const BEARER = /\b(Bearer)[ \t]+[A-Za-z0-9._~+/=-]+/gi;
36
+ /**
37
+ * An absolute path: POSIX `/…` after start / whitespace / an opening or quoting character (never
38
+ * after `:` or a word character, so `https://host/x`, `git@h:o/r.git` and `a/b` are not paths), or a
39
+ * drive-letter `D:\…` / `D:/…`. The body stops at whitespace, quotes, brackets and `:` so a
40
+ * `path:line:col` suffix survives.
41
+ */
42
+ const ABS_PATH =
43
+ /(?<=^|[\s"'`(\[{=,;<>|]|file:\/\/)\/[^\s"'`<>|*?:,;()[\]{}]*|(?<![A-Za-z0-9_])[A-Za-z]:[\\/][^\s"'`<>|*?:,;()[\]{}]*/g;
44
+ const TRAILING_PUNCT = /[.!?]+$/;
45
+
46
+ function stripTrailingSep(p: string): string {
47
+ return p.length > 1 ? p.replace(/[\\/]+$/, "") || p.slice(0, 1) : p;
48
+ }
49
+
50
+ /** If `p` is `base` or lies inside it, the remainder (without a leading separator); else `undefined`. */
51
+ function under(p: string, base: string | undefined): string | undefined {
52
+ if (!base) return undefined;
53
+ const b = stripTrailingSep(base);
54
+ if (b.length === 0) return undefined;
55
+ const windows = /^[A-Za-z]:/.test(b) || b.includes("\\");
56
+ const norm = (s: string) => (windows ? s.replace(/\\/g, "/").toLowerCase() : s);
57
+ const np = norm(p);
58
+ const nb = norm(b);
59
+ if (np === nb) return "";
60
+ const prefix = nb.endsWith("/") ? nb : `${nb}/`;
61
+ if (np.startsWith(prefix)) return p.slice(prefix.length);
62
+ return undefined;
63
+ }
64
+
65
+ function redactPath(p: string, root: string | undefined, home: string | undefined): string {
66
+ const rel = under(p, root);
67
+ if (rel !== undefined) return rel === "" ? "." : rel;
68
+ const homeRel = under(p, home);
69
+ if (homeRel !== undefined) return homeRel === "" ? "~" : `~/${homeRel}`;
70
+ return "<path>";
71
+ }
72
+
73
+ /** Best-effort text of an unknown thrown value (Error → message, string as is, else empty). */
74
+ export function gitErrorText(err: unknown): string {
75
+ if (typeof err === "string") return err;
76
+ if (err && typeof err === "object") {
77
+ const m = (err as { message?: unknown }).message;
78
+ if (typeof m === "string") return m;
79
+ }
80
+ return "";
81
+ }
82
+
83
+ function toText(input: unknown): string {
84
+ if (input === undefined || input === null) return "";
85
+ if (typeof input === "string") return input;
86
+ if (Buffer.isBuffer(input)) return input.toString("utf-8");
87
+ if (input instanceof Error) return input.message ?? "";
88
+ return gitErrorText(input);
89
+ }
90
+
91
+ function homeDir(ctx: RedactContext): string | undefined {
92
+ if (ctx.home !== undefined) return ctx.home || undefined;
93
+ try {
94
+ return os.homedir() || undefined;
95
+ } catch {
96
+ return undefined;
97
+ }
98
+ }
99
+
100
+ /** Redact `input` per the module rules. Never throws; `""`/nullish → `""`. */
101
+ export function redactGitText(input: unknown, ctx: RedactContext = {}): string {
102
+ try {
103
+ let text = toText(input);
104
+ if (text.length === 0) return "";
105
+ const root = ctx.root || undefined;
106
+ const home = homeDir(ctx);
107
+ if (text.includes("://")) {
108
+ text = text.replace(HTTP_USERINFO, "$1").replace(SSH_PASSWORD, "$1@");
109
+ }
110
+ text = text.replace(TOKEN, "$1***").replace(BEARER, "$1 ***");
111
+ if (text.includes("/") || text.includes(":\\")) {
112
+ text = text.replace(ABS_PATH, (match) => {
113
+ const tail = TRAILING_PUNCT.exec(match)?.[0] ?? "";
114
+ const body = tail ? match.slice(0, match.length - tail.length) : match;
115
+ if (body.length <= 1) return match; // a lone "/" is not a path
116
+ return redactPath(body, root, home) + tail;
117
+ });
118
+ }
119
+ return text;
120
+ } catch {
121
+ // Fail closed: never echo the unredacted text if redaction itself failed.
122
+ return "";
123
+ }
124
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Validator for caller-supplied git arguments (refs, commit-ishes, new branch names, base hints,
3
+ * worktree paths). A PRESENT value must be a non-empty string that does not begin with `-` and
4
+ * contains no C0 control character (0x00–0x1F) or DEL (0x7F); otherwise it could be parsed by git
5
+ * as an option (`--upload-pack=…`, `--orphan=…`) or smuggle a line break.
6
+ *
7
+ * The validator IS the control — no `--end-of-options`. Precedent: `packages/kb/src/sources.ts`.
8
+ *
9
+ * See change: harden-git-terminal-plugin-boundaries (B1r).
10
+ */
11
+
12
+ /** Stable error `code` carried by `InvalidRefError` and the HTTP 400 body. */
13
+ export const INVALID_REF_CODE = "invalid_ref";
14
+
15
+ export class InvalidRefError extends Error {
16
+ readonly code = INVALID_REF_CODE;
17
+ constructor(message = "invalid git ref") {
18
+ super(message);
19
+ this.name = "InvalidRefError";
20
+ }
21
+ }
22
+
23
+ const CONTROL_CHARS = /[\u0000-\u001f\u007f]/;
24
+
25
+ /** True iff `v` is a string safe to hand to git as a positional ref/path argument. */
26
+ export function isValidRefArg(v: unknown): v is string {
27
+ return typeof v === "string" && v.length > 0 && v.charCodeAt(0) !== 0x2d && !CONTROL_CHARS.test(v);
28
+ }
29
+
30
+ /** Returns `v` when valid, else throws `InvalidRefError`. */
31
+ export function assertRefArg(v: unknown, label = "ref"): string {
32
+ if (!isValidRefArg(v)) throw new InvalidRefError(`invalid ${label}`);
33
+ return v;
34
+ }
35
+
36
+ /** A required field that is absent, `null` or `""` (the endpoint's existing "missing parameter" case). */
37
+ export function isMissingArg(v: unknown): boolean {
38
+ return v === undefined || v === null || v === "";
39
+ }