@blackbelt-technology/pi-agent-dashboard 0.10.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 (255) hide show
  1. package/AGENTS.md +2 -2
  2. package/README.md +47 -6
  3. package/docs/architecture.md +1369 -63
  4. package/package.json +14 -9
  5. package/packages/extension/package.json +5 -3
  6. package/packages/extension/src/bridge-handlers/dispatch.ts +57 -3
  7. package/packages/extension/src/bridge-handlers/instance.ts +10 -1
  8. package/packages/extension/src/bridge-handlers/lifecycle.ts +65 -26
  9. package/packages/extension/src/bridge-ticket-client.ts +61 -7
  10. package/packages/extension/src/bridge-tls-checks.ts +79 -0
  11. package/packages/extension/src/bridge.ts +41 -28
  12. package/packages/extension/src/canvas-tool.ts +2 -0
  13. package/packages/extension/src/command-handler.ts +80 -6
  14. package/packages/extension/src/connect-target.ts +23 -0
  15. package/packages/extension/src/connection.ts +30 -7
  16. package/packages/extension/src/dashboard-http-origin.ts +88 -0
  17. package/packages/extension/src/dev-build.ts +11 -1
  18. package/packages/extension/src/git-link-builder.ts +11 -2
  19. package/packages/extension/src/inbound-limits.ts +138 -0
  20. package/packages/extension/src/local-token-header.ts +77 -6
  21. package/packages/extension/src/model-refresh.ts +69 -0
  22. package/packages/extension/src/pinned-endpoint.ts +44 -0
  23. package/packages/extension/src/project-trust-live.ts +143 -0
  24. package/packages/extension/src/project-trust.ts +159 -20
  25. package/packages/extension/src/provider-register.ts +59 -18
  26. package/packages/extension/src/remote-registration-gate.ts +21 -21
  27. package/packages/extension/src/remote-upgrade-preparer.ts +104 -0
  28. package/packages/extension/src/role-model-tools.ts +47 -6
  29. package/packages/extension/src/server-auto-start.ts +1 -1
  30. package/packages/extension/src/server-proof-probe.ts +117 -0
  31. package/packages/extension/src/session-sync.ts +42 -12
  32. package/packages/extension/src/vault-delivery.ts +11 -1
  33. package/packages/server/package.json +8 -8
  34. package/packages/server/src/access/access-grants.ts +61 -8
  35. package/packages/server/src/access/access-health.ts +10 -0
  36. package/packages/server/src/access/access-plane.ts +5 -1
  37. package/packages/server/src/access/containment-gate.ts +55 -17
  38. package/packages/server/src/access/cwd-verdict.ts +3 -3
  39. package/packages/server/src/access/pi-trust-live.ts +244 -0
  40. package/packages/server/src/access/pi-trust-mirror-service.ts +44 -11
  41. package/packages/server/src/access/planes.ts +106 -1
  42. package/packages/server/src/access/preview-egress-store.ts +153 -0
  43. package/packages/server/src/access/prompt-channel.ts +5 -0
  44. package/packages/server/src/access/provisioning-wiring.ts +113 -0
  45. package/packages/server/src/access/provisioning.ts +763 -0
  46. package/packages/server/src/access/yolo-session.ts +54 -2
  47. package/packages/server/src/acp-bridge/acp-session-adapter.ts +8 -3
  48. package/packages/server/src/agent-events/agent-event-hub.ts +158 -0
  49. package/packages/server/src/auth/audit-log.ts +80 -0
  50. package/packages/server/src/auth/auth-plugin.ts +44 -25
  51. package/packages/server/src/auth/auth.ts +24 -4
  52. package/packages/server/src/auth/bearer-auth.ts +52 -12
  53. package/packages/server/src/auth/cors-origin.ts +76 -29
  54. package/packages/server/src/auth/csp-report-paths.ts +31 -0
  55. package/packages/server/src/auth/csp-report-sink.ts +302 -0
  56. package/packages/server/src/auth/csp-report-store.ts +406 -0
  57. package/packages/server/src/auth/csp.ts +105 -9
  58. package/packages/server/src/auth/dashboard-credential-store.ts +4 -0
  59. package/packages/server/src/auth/dashboard-state-caller.ts +29 -0
  60. package/packages/server/src/auth/local-proof-refusal-log.ts +89 -0
  61. package/packages/server/src/auth/local-proof.ts +69 -18
  62. package/packages/server/src/auth/localhost-guard.ts +48 -10
  63. package/packages/server/src/auth/nav-intent.ts +72 -0
  64. package/packages/server/src/auth/passkey/passkey-assets.ts +99 -0
  65. package/packages/server/src/auth/passkey/passkey-pages.ts +17 -81
  66. package/packages/server/src/auth/passkey/passkey-routes.ts +8 -0
  67. package/packages/server/src/auth/pi-legacy-credentials.ts +3 -0
  68. package/packages/server/src/auth/plugin-server-trust.ts +29 -0
  69. package/packages/server/src/auth/plugin-trust-store.ts +103 -0
  70. package/packages/server/src/auth/proven-tls.ts +45 -0
  71. package/packages/server/src/auth/provider-auth-storage.ts +6 -1
  72. package/packages/server/src/auth/radius-mcp.ts +1 -1
  73. package/packages/server/src/auth/request-principal.ts +32 -0
  74. package/packages/server/src/auth/secret-rotation.ts +246 -0
  75. package/packages/server/src/auth/secure-origin.ts +56 -0
  76. package/packages/server/src/auth/serve-app-host.ts +111 -11
  77. package/packages/server/src/auth/ws-ticket.ts +39 -1
  78. package/packages/server/src/auth/ws-upgrade-reject-log.ts +4 -1
  79. package/packages/server/src/browser-handlers/directory-handler.ts +23 -0
  80. package/packages/server/src/browser-handlers/folder-gate.ts +55 -0
  81. package/packages/server/src/browser-handlers/handler-context.ts +25 -2
  82. package/packages/server/src/browser-handlers/session-action-handler.ts +9 -1
  83. package/packages/server/src/browser-handlers/subscription-handler.ts +100 -2
  84. package/packages/server/src/browser-handlers/terminal-handler.ts +108 -10
  85. package/packages/server/src/canvas/canvas-accumulator.ts +35 -7
  86. package/packages/server/src/cli.ts +210 -39
  87. package/packages/server/src/config-api.ts +23 -1
  88. package/packages/server/src/config-snapshot.ts +48 -1
  89. package/packages/server/src/directory-service.ts +160 -54
  90. package/packages/server/src/event-wiring.ts +143 -108
  91. package/packages/server/src/git-worktree/git-operations.ts +44 -10
  92. package/packages/server/src/git-worktree/redact-git-text.ts +124 -0
  93. package/packages/server/src/git-worktree/ref-arg.ts +39 -0
  94. package/packages/server/src/git-worktree/worktree-init-trust.ts +43 -1
  95. package/packages/server/src/identity/http-road-classification.ts +13 -1
  96. package/packages/server/src/identity/ws-message-scope.ts +1 -0
  97. package/packages/server/src/identity/ws-road-classification.ts +1 -0
  98. package/packages/server/src/known-server-moves.ts +36 -15
  99. package/packages/server/src/lib/browse-roots.ts +118 -17
  100. package/packages/server/src/lib/client-dist.ts +36 -21
  101. package/packages/server/src/lib/dashboard-state-guard.ts +230 -0
  102. package/packages/server/src/lib/diagram-render.ts +4 -6
  103. package/packages/server/src/lib/eml.ts +3 -8
  104. package/packages/server/src/lib/file-cwd-admission.ts +145 -0
  105. package/packages/server/src/lib/grep-worker.ts +23 -0
  106. package/packages/server/src/lib/grep.ts +93 -7
  107. package/packages/server/src/lib/index-html.ts +81 -0
  108. package/packages/server/src/lib/office-preview.ts +2 -3
  109. package/packages/server/src/lib/path-containment.ts +7 -0
  110. package/packages/server/src/lib/resolve-file-mention.ts +11 -9
  111. package/packages/server/src/lib/route-admission.ts +80 -0
  112. package/packages/server/src/lib/writable-md-target.ts +4 -0
  113. package/packages/server/src/lifecycle/recovery-server.ts +65 -18
  114. package/packages/server/src/live-server/capability-redact.ts +15 -0
  115. package/packages/server/src/live-server/live-browser-gate.ts +22 -0
  116. package/packages/server/src/live-server/live-capability.ts +224 -17
  117. package/packages/server/src/live-server/live-csp-report.ts +63 -0
  118. package/packages/server/src/live-server/live-csp.ts +93 -0
  119. package/packages/server/src/live-server/live-egress.ts +435 -0
  120. package/packages/server/src/live-server/live-exposure.ts +149 -0
  121. package/packages/server/src/live-server/live-log.ts +21 -0
  122. package/packages/server/src/live-server/live-origin-scan.ts +298 -0
  123. package/packages/server/src/live-server/live-server-manager.ts +209 -33
  124. package/packages/server/src/live-server/live-server-proxy.ts +162 -17
  125. package/packages/server/src/live-server/live-static.ts +228 -0
  126. package/packages/server/src/openspec/dependencies-file.ts +122 -0
  127. package/packages/server/src/openspec/openspec-change-watcher.ts +3 -1
  128. package/packages/server/src/openspec/openspec-dependency-inputs.ts +281 -0
  129. package/packages/server/src/openspec/openspec-poll-fs-helpers.ts +72 -26
  130. package/packages/server/src/openspec/openspec-poll-worker-pool.ts +48 -12
  131. package/packages/server/src/openspec/openspec-poll-worker.ts +95 -9
  132. package/packages/server/src/openspec/workflow-schema-status.ts +379 -0
  133. package/packages/server/src/openspec/workflow-schema.ts +141 -267
  134. package/packages/server/src/package/npm-search-proxy.ts +5 -2
  135. package/packages/server/src/package/provider-probe.ts +8 -2
  136. package/packages/server/src/pairing/browser-gateway.ts +188 -12
  137. package/packages/server/src/pairing/device-token-services.ts +26 -0
  138. package/packages/server/src/pairing/paired-devices.ts +335 -22
  139. package/packages/server/src/pairing/pairing.ts +34 -4
  140. package/packages/server/src/pairing/socket-locality.ts +26 -0
  141. package/packages/server/src/persistence/preferences-store.ts +9 -0
  142. package/packages/server/src/pi/bridge-channel.ts +33 -0
  143. package/packages/server/src/pi/bridge-upgrade-auth.ts +18 -3
  144. package/packages/server/src/pi/gateway-listeners.ts +9 -3
  145. package/packages/server/src/pi/host-project-trust.ts +14 -6
  146. package/packages/server/src/pi/pi-gateway.ts +191 -21
  147. package/packages/server/src/pi/resource-toggle-trust.ts +1 -1
  148. package/packages/server/src/plugin-discovery-wiring.ts +142 -0
  149. package/packages/server/src/plugin-event-seam.ts +116 -4
  150. package/packages/server/src/plugin-runtime-clients.ts +89 -0
  151. package/packages/server/src/routes/access-routes.ts +159 -9
  152. package/packages/server/src/routes/agent-event-stream-routes.ts +137 -0
  153. package/packages/server/src/routes/canvas-types-routes.ts +20 -6
  154. package/packages/server/src/routes/csp-violations-routes.ts +162 -0
  155. package/packages/server/src/routes/file-routes.ts +329 -209
  156. package/packages/server/src/routes/file-write-binary-routes.ts +77 -20
  157. package/packages/server/src/routes/folder-project-routes.ts +18 -12
  158. package/packages/server/src/routes/git-routes.ts +319 -203
  159. package/packages/server/src/routes/grep-routes.ts +38 -14
  160. package/packages/server/src/routes/known-servers-routes.ts +189 -91
  161. package/packages/server/src/routes/live-server-routes.ts +378 -15
  162. package/packages/server/src/routes/local-proof-routes.ts +14 -0
  163. package/packages/server/src/routes/nav-intent-routes.ts +46 -0
  164. package/packages/server/src/routes/openspec-group-routes.ts +53 -44
  165. package/packages/server/src/routes/openspec-routes.ts +379 -28
  166. package/packages/server/src/routes/package-routes.ts +58 -10
  167. package/packages/server/src/routes/pairing-routes.ts +146 -10
  168. package/packages/server/src/routes/pi-trust-query-routes.ts +330 -0
  169. package/packages/server/src/routes/plugin-activation-routes.ts +59 -0
  170. package/packages/server/src/routes/plugin-runtime-client-routes.ts +149 -0
  171. package/packages/server/src/routes/provider-auth-routes.ts +15 -2
  172. package/packages/server/src/routes/resource-activation-routes.ts +18 -4
  173. package/packages/server/src/routes/session-routes.ts +51 -4
  174. package/packages/server/src/routes/system-routes.ts +84 -15
  175. package/packages/server/src/routes/ui-link-base.ts +88 -0
  176. package/packages/server/src/runtime-overlay/runtime-io.ts +2 -9
  177. package/packages/server/src/server.ts +648 -137
  178. package/packages/server/src/session/hydration-state.ts +148 -0
  179. package/packages/server/src/session/memory-session-manager.ts +7 -0
  180. package/packages/server/src/session/replay-exit-controller.ts +221 -0
  181. package/packages/server/src/session/retained-transcript.ts +9 -2
  182. package/packages/server/src/session/session-load-worker.ts +11 -2
  183. package/packages/server/src/spawn-process/headless-pid-registry.ts +14 -9
  184. package/packages/server/src/terminal/terminal-manager.ts +54 -46
  185. package/packages/server/src/tls/tls-bridge-route.ts +61 -0
  186. package/packages/server/src/tls/tls-config-validation.ts +2 -0
  187. package/packages/server/src/vault/device-expiry-sweep.ts +36 -0
  188. package/packages/server/src/vault/vault-delivery-hub.ts +155 -25
  189. package/packages/server/src/watch-files-handler.ts +66 -0
  190. package/packages/shared/package.json +1 -1
  191. package/packages/shared/src/browser-protocol.ts +148 -2
  192. package/packages/shared/src/canvas-declare.ts +27 -0
  193. package/packages/shared/src/config.ts +372 -53
  194. package/packages/shared/src/containment-guard.ts +35 -0
  195. package/packages/shared/src/dashboard-plugin/anthropic-peer-names.ts +9 -0
  196. package/packages/shared/src/dashboard-plugin/event-type-owners.ts +50 -0
  197. package/packages/shared/src/dashboard-plugin/file-handler.ts +2 -0
  198. package/packages/shared/src/dashboard-plugin/host-api.ts +61 -0
  199. package/packages/shared/src/dashboard-plugin/host-fx-classes.ts +23 -0
  200. package/packages/shared/src/dashboard-plugin/host-import-map.ts +38 -0
  201. package/packages/shared/src/dashboard-plugin/index.ts +2 -0
  202. package/packages/shared/src/dashboard-plugin/manifest-types.ts +54 -1
  203. package/packages/shared/src/dashboard-plugin/plugin-status.ts +54 -0
  204. package/packages/shared/src/dashboard-plugin/slot-props.ts +45 -3
  205. package/packages/shared/src/dashboard-plugin/slot-types.ts +8 -0
  206. package/packages/shared/src/dashboard-plugin/subagent-types.ts +219 -0
  207. package/packages/shared/src/dashboard-plugin/ui-primitives.ts +28 -0
  208. package/packages/shared/src/display-prefs.ts +13 -0
  209. package/packages/shared/src/doctor-core.ts +94 -27
  210. package/packages/shared/src/live-server.ts +141 -0
  211. package/packages/shared/src/local-proof-signal.ts +16 -0
  212. package/packages/shared/src/loopback-host.ts +26 -0
  213. package/packages/shared/src/mcp/verb-tiers.generated.ts +178 -0
  214. package/packages/shared/src/mdns-discovery.ts +25 -6
  215. package/packages/shared/src/nav-intent.ts +29 -0
  216. package/packages/shared/src/openspec-dependencies.ts +760 -0
  217. package/packages/shared/src/openspec-poller.ts +3 -2
  218. package/packages/shared/src/pairing-knock-client.ts +44 -4
  219. package/packages/shared/src/pi-trust-live-query.ts +93 -0
  220. package/packages/shared/src/pi-trust-mirror-snapshot.ts +5 -7
  221. package/packages/shared/src/pi-trust-mirror-types.ts +36 -3
  222. package/packages/shared/src/pi-trust-mirror.ts +29 -3
  223. package/packages/shared/src/pi-trust-resource-digest.ts +255 -0
  224. package/packages/shared/src/platform/ensure-bundled-git.ts +57 -34
  225. package/packages/shared/src/platform/git-source.ts +88 -26
  226. package/packages/shared/src/platform/git.ts +14 -8
  227. package/packages/shared/src/platform/process.ts +48 -4
  228. package/packages/shared/src/platform/resolve-pi-shell.ts +76 -0
  229. package/packages/shared/src/platform/select-git-source.ts +7 -0
  230. package/packages/shared/src/plugin-route-cwd.ts +95 -0
  231. package/packages/shared/src/preview-egress.ts +138 -0
  232. package/packages/shared/src/project-root.ts +16 -0
  233. package/packages/shared/src/protocol.ts +40 -1
  234. package/packages/shared/src/recommended-extensions.ts +18 -0
  235. package/packages/shared/src/recovery-timing.ts +27 -0
  236. package/packages/shared/src/remote-credentials.ts +63 -0
  237. package/packages/shared/src/rest-api.ts +55 -8
  238. package/packages/shared/src/route-tiers.ts +55 -1
  239. package/packages/shared/src/runtime-overlay/archive-safety.d.mts +2 -0
  240. package/packages/shared/src/runtime-overlay/archive-safety.mjs +33 -0
  241. package/packages/shared/src/runtime-overlay/manifest.d.mts +7 -0
  242. package/packages/shared/src/runtime-overlay/manifest.mjs +22 -2
  243. package/packages/shared/src/safe-local-path.ts +24 -0
  244. package/packages/shared/src/sanitize-profiles.ts +98 -0
  245. package/packages/shared/src/server-launcher.ts +9 -1
  246. package/packages/shared/src/server-pinning.ts +55 -2
  247. package/packages/shared/src/server-routes.ts +462 -0
  248. package/packages/shared/src/session-ui-path.ts +11 -0
  249. package/packages/shared/src/tls-only-token.ts +16 -0
  250. package/packages/shared/src/tool-registry/definitions.ts +5 -5
  251. package/packages/shared/src/tool-registry/strategies.ts +12 -11
  252. package/packages/shared/src/types.ts +66 -0
  253. package/packages/shared/src/url-policy.ts +96 -0
  254. package/packages/shared/src/vault-delivery.ts +15 -0
  255. package/packages/shared/src/ws-message-tiers.ts +1 -0
@@ -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,13 @@ 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
46
  import { evaluateGate, type GateResult, hookDefHash, type InitProgress, readInitHook, runInitHook, type WorktreeInitHook } 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";
39
49
  import { mapInitStderrToHint } from "../git-worktree/worktree-init-errors.js";
40
50
  import type { WorktreeInitRegistry } from "../git-worktree/worktree-init-registry.js";
41
- import { getPiTrustMirror } from "../access/pi-trust-mirror-service.js";
42
51
  import { isTrusted, recordTrust } from "../git-worktree/worktree-init-trust.js";
52
+ import { admitRouteCwd, sendAdmissionUnavailable } from "../lib/route-admission.js";
43
53
  import type { BrowserGateway } from "../pairing/browser-gateway.js";
44
54
  import { safeRealpathSync } from "../resolve-path.js";
45
55
  import { activeSessionsUnder, activeSessionsUnderResolved, sessionsUnder } from "../session/active-sessions-in-cwd.js";
@@ -72,8 +82,47 @@ export interface GitRoutesDeps {
72
82
  * the final result either way). See change: generalize-worktree-init-hook.
73
83
  */
74
84
  worktreeInitRegistry?: WorktreeInitRegistry;
85
+ /**
86
+ * Live known-folder set (session cwds ∪ pinned directories) every `cwd` is admitted
87
+ * against. Absent → nothing is known (fail closed). See change: core-cwd-admission.
88
+ */
89
+ knownCwds?: () => string[];
90
+ /** `admitCwd` options: the host's throttled `onIndeterminate` logger + test seams. */
91
+ admitOptions?: AdmitCwdOptions;
92
+ /** Test seam: whole-`remove-batch` admission budget in ms (default 10 000). */
93
+ removeBatchAdmissionBudgetMs?: number;
75
94
  }
76
95
 
96
+ /** Admission result of one git-route `cwd`: the canonical cwd to operate on, or the reply body. */
97
+ type GitCwdCheck =
98
+ | { ok: true; cwd: string; token: AdmissionToken }
99
+ | { ok: false; body: ApiResponse; code: string };
100
+
101
+ /**
102
+ * B20: redact git-derived text against the root the operation ran in. `root` is captured by the
103
+ * caller at operation time (a `const`), never read at broadcast time.
104
+ * See change: harden-git-terminal-plugin-boundaries.
105
+ */
106
+ const redact = (text: unknown, root?: string): string => redactGitText(text, { root });
107
+ /** Redacted `err.message` (or a thrown string), falling back to `fallback`. */
108
+ const redactErr = (err: unknown, fallback: string, root?: string): string => redact(gitErrorText(err) || fallback, root);
109
+
110
+ /** B1r: the 400 `invalid_ref` envelope (no git process has started). */
111
+ function invalidRef(reply: FastifyReply, what: string): ApiResponse {
112
+ reply.code(400);
113
+ return { success: false, code: INVALID_REF_CODE, error: `invalid ${what}` };
114
+ }
115
+ /** A PRESENT optional ref/path field (absent/null/"" = not supplied) that fails validation. */
116
+ const presentInvalid = (v: unknown): boolean => !isMissingArg(v) && !isValidRefArg(v);
117
+
118
+ /** Whole-batch admission budget for `remove-batch` (design D1). */
119
+ const REMOVE_BATCH_ADMISSION_BUDGET_MS = 10_000;
120
+ /** A runner that never completes a probe: only a direct known-folder match can be admitted with it. */
121
+ const NO_DERIVATION_RUNNER: NonNullable<AdmitCwdOptions["runner"]> = async () => ({
122
+ ok: false,
123
+ error: { kind: "spawn-failure", message: "admission budget exhausted" },
124
+ });
125
+
77
126
  /**
78
127
  * Per-resolved-checkout cache of the gate result, with a short TTL.
79
128
  * Invalidated when a hook run starts/exits for that checkout.
@@ -158,6 +207,70 @@ function resolveBatchCap(v: unknown): number {
158
207
  export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps) {
159
208
  const { networkGuard, sessionManager, browserGateway, worktreeInitRegistry, sendToSession, commitDraftRelay, removeBatchCap: configuredRemoveBatchCap } = deps;
160
209
  const removeBatchCap = resolveBatchCap(configuredRemoveBatchCap);
210
+
211
+ /**
212
+ * Admit a request `cwd` (design D1): `admitRouteCwd`, then branch on
213
+ * `admissionAllows(admission, cwd)` HERE, on the unmodified request value, so static
214
+ * analysis keeps its modelled barrier. Returns the CANONICAL cwd — git runs on the
215
+ * realpath, so a later swap of the raw path cannot redirect the operation. The token is
216
+ * released when the response closes (success, error, throw or disconnect).
217
+ * No filesystem call touches the raw value outside the guard.
218
+ * See change: core-cwd-admission.
219
+ */
220
+ async function admitGitCwd(
221
+ raw: string,
222
+ reply: FastifyReply,
223
+ admitOptions: AdmitCwdOptions | undefined = deps.admitOptions,
224
+ ): Promise<GitCwdCheck> {
225
+ const admission = await admitRouteCwd(raw, { knownCwds: deps.knownCwds, admitOptions });
226
+ if (admission.kind === "indeterminate") {
227
+ return { ok: false, body: sendAdmissionUnavailable(reply), code: "cwd-admission-unavailable" };
228
+ }
229
+ if (admission.kind !== "admit" || !admissionAllows(admission, raw)) {
230
+ reply.code(400);
231
+ return {
232
+ ok: false,
233
+ code: "cwd_unknown",
234
+ body: {
235
+ success: false,
236
+ code: "cwd_unknown",
237
+ error: "cwd is not a known folder; pin the repository to allow git operations",
238
+ } satisfies ApiResponse,
239
+ };
240
+ }
241
+ const token = admission.token;
242
+ reply.raw.once("close", () => releaseAdmission(token));
243
+ // The client may have gone while admission ran (`close` already fired): release at once.
244
+ if (reply.raw.destroyed) releaseAdmission(token);
245
+ return { ok: true, cwd: token.canonCwd, token };
246
+ }
247
+
248
+ /**
249
+ * `admitGitCwd` plus the presence and directory checks of the worktree endpoints
250
+ * (`cwd_invalid`: `cwd required` / `cwd does not exist` / `cwd is not a directory`),
251
+ * the latter two only for an ADMITTED cwd. See change: add-worktree-spawn-dialog,
252
+ * core-cwd-admission.
253
+ */
254
+ async function validateCwd(raw: string | undefined, reply: FastifyReply): Promise<GitCwdCheck> {
255
+ if (!raw || typeof raw !== "string") {
256
+ reply.code(400);
257
+ return { ok: false, code: "cwd_invalid", body: { success: false, code: "cwd_invalid", error: "cwd required" } satisfies ApiResponse };
258
+ }
259
+ const admitted = await admitGitCwd(raw, reply);
260
+ if (!admitted.ok) return admitted;
261
+ const invalid = (error: string): GitCwdCheck => {
262
+ releaseAdmission(admitted.token);
263
+ reply.code(400);
264
+ return { ok: false, code: "cwd_invalid", body: { success: false, code: "cwd_invalid", error } satisfies ApiResponse };
265
+ };
266
+ try {
267
+ const stat = await fs.promises.stat(admitted.cwd);
268
+ if (!stat.isDirectory()) return invalid("cwd is not a directory");
269
+ } catch {
270
+ return invalid("cwd does not exist");
271
+ }
272
+ return admitted;
273
+ }
161
274
  /**
162
275
  * After a successful worktree Push / Open PR, force a PR-status probe on
163
276
  * every bridge whose session cwd is the worktree or inside it (realpath-
@@ -179,36 +292,44 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
179
292
  reply.code(400);
180
293
  return { success: false, code: "cwd_required", error: "cwd parameter required" } satisfies ApiResponse;
181
294
  }
182
- if (!isGitRepo(cwd)) {
295
+ const admitted = await admitGitCwd(cwd, reply);
296
+ if (!admitted.ok) return admitted.body;
297
+ if (!isGitRepo(admitted.cwd)) {
183
298
  return { success: false, code: "not_a_repo", error: "not a git repository" } satisfies ApiResponse;
184
299
  }
185
300
  try {
186
- const data = listBranches(cwd);
301
+ const data = listBranches(admitted.cwd);
187
302
  return { success: true, data } satisfies ApiResponse;
188
303
  } catch (err: any) {
189
- return { success: false, code: "list_branches_failed", error: err.message ?? "failed to list branches" } satisfies ApiResponse;
304
+ return { success: false, code: "list_branches_failed", error: redactErr(err, "failed to list branches", admitted.cwd) } satisfies ApiResponse;
190
305
  }
191
306
  },
192
307
  );
193
308
 
194
- fastify.post<{ Body: { cwd?: string; branch?: string; stash?: boolean } }>(
309
+ fastify.post<{ Body: { cwd?: string; branch?: unknown; stash?: boolean } }>(
195
310
  "/api/git/checkout",
196
311
  { preHandler: networkGuard },
197
312
  async (request, reply) => {
198
313
  const { cwd, branch, stash } = request.body ?? {};
199
- if (!cwd || !branch) {
314
+ // Missing (absent / null / "") keeps the existing code; a PRESENT invalid ref is `invalid_ref`
315
+ // (B1r) — checked before admission so nothing (not even a probe) runs for it.
316
+ if (!cwd || isMissingArg(branch)) {
200
317
  reply.code(400);
201
318
  return { success: false, code: "cwd_and_branch_required", error: "cwd and branch required" } satisfies ApiResponse;
202
319
  }
320
+ if (!isValidRefArg(branch)) return invalidRef(reply, "branch");
321
+ const admitted = await admitGitCwd(cwd, reply);
322
+ if (!admitted.ok) return admitted.body;
203
323
  try {
204
- const result = checkoutBranch(cwd, branch, stash ?? false);
324
+ const result = checkoutBranch(admitted.cwd, branch, stash ?? false);
205
325
  if (!result.success) {
206
326
  reply.code(409);
207
327
  return result;
208
328
  }
209
329
  return { success: true, data: { stashed: result.stashed } } satisfies ApiResponse;
210
330
  } catch (err: any) {
211
- return { success: false, code: "checkout_failed", error: err.message ?? "checkout failed" } satisfies ApiResponse;
331
+ if (err instanceof InvalidRefError) return invalidRef(reply, "branch");
332
+ return { success: false, code: "checkout_failed", error: redactErr(err, "checkout failed", admitted.cwd) } satisfies ApiResponse;
212
333
  }
213
334
  },
214
335
  );
@@ -222,11 +343,13 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
222
343
  reply.code(400);
223
344
  return { success: false, code: "cwd_required", error: "cwd required" } satisfies ApiResponse;
224
345
  }
346
+ const admitted = await admitGitCwd(cwd, reply);
347
+ if (!admitted.ok) return admitted.body;
225
348
  try {
226
- gitInit(cwd);
349
+ gitInit(admitted.cwd);
227
350
  return { success: true } satisfies ApiResponse;
228
351
  } catch (err: any) {
229
- return { success: false, code: "git_init_failed", error: err.message ?? "init failed" } satisfies ApiResponse;
352
+ return { success: false, code: "git_init_failed", error: redactErr(err, "init failed", admitted.cwd) } satisfies ApiResponse;
230
353
  }
231
354
  },
232
355
  );
@@ -239,11 +362,8 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
239
362
  "/api/git/status",
240
363
  { preHandler: networkGuard },
241
364
  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
- }
365
+ const validated = await validateCwd(request.query.cwd, reply);
366
+ if (!validated.ok) return validated.body;
247
367
  if (!isGitRepo(validated.cwd)) {
248
368
  return { success: false, code: "not_a_repo", error: "not a git repository" } satisfies ApiResponse;
249
369
  }
@@ -260,11 +380,8 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
260
380
  "/api/git/changed-files",
261
381
  { preHandler: networkGuard },
262
382
  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
- }
383
+ const validated = await validateCwd(request.query.cwd, reply);
384
+ if (!validated.ok) return validated.body;
268
385
  if (!isGitRepo(validated.cwd)) {
269
386
  return { success: false, code: "not_a_repo", error: "not a git repository" } satisfies ApiResponse;
270
387
  }
@@ -272,7 +389,7 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
272
389
  const files = await getChangedFiles(validated.cwd);
273
390
  return { success: true, data: files } satisfies ApiResponse;
274
391
  } catch (err: any) {
275
- return { success: false, code: "git_failed", error: err?.message ?? "failed to list changed files" } satisfies ApiResponse;
392
+ return { success: false, code: "git_failed", error: redactErr(err, "failed to list changed files", validated.cwd) } satisfies ApiResponse;
276
393
  }
277
394
  },
278
395
  );
@@ -285,11 +402,8 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
285
402
  { preHandler: networkGuard },
286
403
  async (request, reply) => {
287
404
  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
- }
405
+ const validated = await validateCwd(cwd, reply);
406
+ if (!validated.ok) return validated.body;
293
407
  if (typeof message !== "string" || !Array.isArray(files)) {
294
408
  reply.code(400);
295
409
  return { success: false, code: "bad_request", error: "message and files[] required" } satisfies ApiResponse;
@@ -312,9 +426,9 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
312
426
  } catch (err: any) {
313
427
  if (err instanceof GitCommitError) {
314
428
  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;
429
+ return { success: false, code: err.code, error: redact(err.message, validated.cwd) } satisfies ApiResponse;
316
430
  }
317
- return { success: false, code: "commit-failed", error: err?.message ?? "commit failed" } satisfies ApiResponse;
431
+ return { success: false, code: "commit-failed", error: redactErr(err, "commit failed", validated.cwd) } satisfies ApiResponse;
318
432
  }
319
433
  },
320
434
  );
@@ -326,11 +440,8 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
326
440
  { preHandler: networkGuard },
327
441
  async (request, reply) => {
328
442
  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
- }
443
+ const validated = await validateCwd(cwd, reply);
444
+ if (!validated.ok) return validated.body;
334
445
  // Every file must be a non-empty string (the diff is built per path).
335
446
  if (
336
447
  !Array.isArray(files) ||
@@ -372,11 +483,8 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
372
483
  "/api/git/head",
373
484
  { preHandler: networkGuard },
374
485
  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
- }
486
+ const validated = await validateCwd(request.query.cwd, reply);
487
+ if (!validated.ok) return validated.body;
380
488
  if (!isGitRepo(validated.cwd)) {
381
489
  return { success: false, code: "not_a_repo", error: "not a git repository" } satisfies ApiResponse;
382
490
  }
@@ -384,7 +492,7 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
384
492
  const head = readHead(validated.cwd);
385
493
  return { success: true, data: head } satisfies ApiResponse;
386
494
  } catch (err: any) {
387
- return { success: false, code: "git_failed", error: err?.message ?? "failed to read HEAD" } satisfies ApiResponse;
495
+ return { success: false, code: "git_failed", error: redactErr(err, "failed to read HEAD", validated.cwd) } satisfies ApiResponse;
388
496
  }
389
497
  },
390
498
  );
@@ -393,11 +501,8 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
393
501
  "/api/git/worktrees",
394
502
  { preHandler: networkGuard },
395
503
  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
- }
504
+ const validated = await validateCwd(request.query.cwd, reply);
505
+ if (!validated.ok) return validated.body;
401
506
  if (!isGitRepo(validated.cwd)) {
402
507
  return { success: false, code: "not_a_repo", error: "not a git repository" } satisfies ApiResponse;
403
508
  }
@@ -405,7 +510,7 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
405
510
  const worktrees = listWorktrees(validated.cwd);
406
511
  return { success: true, data: { worktrees } } satisfies ApiResponse;
407
512
  } catch (err: any) {
408
- return { success: false, code: "git_failed", error: err?.message ?? "failed to list worktrees" } satisfies ApiResponse;
513
+ return { success: false, code: "git_failed", error: redactErr(err, "failed to list worktrees", validated.cwd) } satisfies ApiResponse;
409
514
  }
410
515
  },
411
516
  );
@@ -418,11 +523,8 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
418
523
  "/api/git/worktree/init-status",
419
524
  { preHandler: networkGuard },
420
525
  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
- }
526
+ const validated = await validateCwd(request.query.cwd, reply);
527
+ if (!validated.ok) return validated.body;
426
528
  // Config root without a git assumption: a non-git dir with
427
529
  // `.pi/settings.json` resolves to itself so its declared hook is read.
428
530
  // See change: support-non-git-init-hook.
@@ -492,11 +594,8 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
492
594
  });
493
595
  }
494
596
  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
- }
597
+ const validated = await validateCwd(body.cwd, reply);
598
+ if (!validated.ok) return validated.body;
500
599
  // Config root without a git assumption; a `null` root means an
501
600
  // unconfigured non-git dir — reuse the existing no-hook envelope, not
502
601
  // `not_a_repo`. See change: support-non-git-init-hook.
@@ -530,9 +629,14 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
530
629
  );
531
630
  } catch (err) {
532
631
  reply.code(500);
533
- return { success: false, code: "trust_not_recorded", error: `trust not recorded: ${(err as Error)?.message ?? String(err)}` } satisfies ApiResponse;
632
+ return { success: false, code: "trust_not_recorded", error: `trust not recorded: ${redactErr(err, String(err), configRoot)}` } satisfies ApiResponse;
534
633
  }
535
634
  } else {
635
+ // "Until the dashboard restarts": the "also trust in pi" choice is held in
636
+ // memory with the entry and never written. See change: mirror-dashboard-trust-live-remote.
637
+ if (scope === "session" && typeof body.piTrust === "boolean") {
638
+ getPiTrustMirror()?.live?.setChoice("worktreeInit", configRoot, body.piTrust);
639
+ }
536
640
  recordTrust(configRoot, hash, scope);
537
641
  }
538
642
  }
@@ -573,8 +677,11 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
573
677
  sendIf({ type: "worktree_init_done", requestId: requestId ?? "", cwd, durationMs: runResult.durationMs });
574
678
  return { success: true, data: { ran: true, durationMs: runResult.durationMs } } satisfies ApiResponse;
575
679
  }
576
- const stderr = runResult.stderr ?? "";
577
- const hint = mapInitStderrToHint(stderr) ?? `init failed (${runResult.code ?? "unknown"})`;
680
+ // B20: the mapper sees the RAW stderr (so it can match paths); BOTH the mapped hint and the
681
+ // stderr are redacted AFTER mapping, against the checkout the hook ran in (`cwd`, captured above).
682
+ const rawStderr = runResult.stderr ?? "";
683
+ const hint = redact(mapInitStderrToHint(rawStderr) ?? `init failed (${runResult.code ?? "unknown"})`, cwd);
684
+ const stderr = redact(rawStderr, cwd);
578
685
  worktreeInitRegistry?.finishRun(cwd, "failed", runResult.code ?? "init_failed");
579
686
  sendIf({ type: "worktree_init_failed", requestId: requestId ?? "", cwd, code: runResult.code ?? "init_failed", message: hint, stderr });
580
687
  reply.code(500);
@@ -583,7 +690,7 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
583
690
  );
584
691
 
585
692
  fastify.post<{
586
- Body: { cwd?: string; base?: string; newBranch?: string; path?: string; force?: boolean };
693
+ Body: { cwd?: string; base?: unknown; newBranch?: unknown; path?: unknown; force?: boolean };
587
694
  }>(
588
695
  "/api/git/worktree",
589
696
  { preHandler: networkGuard },
@@ -593,42 +700,41 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
593
700
  // worktree-init hook (GET /init-status + POST /init). See change:
594
701
  // generalize-worktree-init-hook.
595
702
  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") {
703
+ // B1r: every PRESENT ref / branch / path is validated before admission or git. `base` absent /
704
+ // null / "" keeps the existing `cwd_invalid` envelope below; `newBranch` absent = checkout mode
705
+ // (a present `null` / "" / non-string is invalid); `path` absent / null / "" = default path.
706
+ // See change: harden-git-terminal-plugin-boundaries.
707
+ if (presentInvalid(body.base)) return invalidRef(reply, "base");
708
+ if (body.newBranch !== undefined && !isValidRefArg(body.newBranch)) return invalidRef(reply, "newBranch");
709
+ if (presentInvalid(body.path)) return invalidRef(reply, "path");
710
+ const validated = await validateCwd(body.cwd, reply);
711
+ if (!validated.ok) return validated.body;
712
+ if (!isValidRefArg(body.base)) {
602
713
  reply.code(400);
603
714
  return { success: false, code: "cwd_invalid", error: "base required" } satisfies ApiResponse;
604
715
  }
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
- }
716
+ // `newBranch` is optional: present → fork mode; absent → the server checks out the existing
717
+ // `base` ref (checkout mode). See change: worktree-checkout-existing-branch.
612
718
  const result = addWorktree({
613
719
  cwd: validated.cwd,
614
720
  base: body.base,
615
- ...(body.newBranch !== undefined ? { newBranch: body.newBranch } : {}),
616
- path: body.path,
721
+ ...(body.newBranch !== undefined ? { newBranch: body.newBranch as string } : {}),
722
+ path: typeof body.path === "string" && body.path.length > 0 ? body.path : undefined,
617
723
  force: body.force === true,
618
724
  });
619
725
  if (!result.ok) {
620
726
  const httpStatus =
621
727
  result.error === "branch_in_use" || result.error === "branch_exists" || result.error === "path_exists"
622
728
  ? 409
623
- : result.error === "not_a_repo" || result.error === "base_not_found"
729
+ : result.error === "not_a_repo" || result.error === "base_not_found" || result.error === "invalid_ref"
624
730
  ? 400
625
731
  : 500;
626
732
  reply.code(httpStatus);
627
733
  return {
628
734
  success: false,
629
735
  code: result.error,
630
- error: result.message,
631
- ...(result.stderr ? { stderr: result.stderr } : {}),
736
+ error: redact(result.message, validated.cwd),
737
+ ...(result.stderr ? { stderr: redact(result.stderr, validated.cwd) } : {}),
632
738
  ...(typeof result.orphanLikely === "boolean" ? { orphanLikely: result.orphanLikely } : {}),
633
739
  } satisfies ApiResponse;
634
740
  }
@@ -645,17 +751,16 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
645
751
  // Unblocks the worktree-spawn dialog when a previous failed attempt
646
752
  // left an orphan directory at the target path. Conservative refuse
647
753
  // rules — see `orphanCleanup` in `git-operations.ts`.
648
- fastify.post<{ Body: { cwd?: string; path?: string } }>(
754
+ fastify.post<{ Body: { cwd?: string; path?: unknown } }>(
649
755
  "/api/git/worktree/orphan-cleanup",
650
756
  { preHandler: networkGuard },
651
757
  async (request, reply) => {
652
758
  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") {
759
+ // B1r: a present option-like / control-character path is refused before admission or any fs/git work.
760
+ if (presentInvalid(body.path)) return invalidRef(reply, "path");
761
+ const validated = await validateCwd(body.cwd, reply);
762
+ if (!validated.ok) return validated.body;
763
+ if (!isValidRefArg(body.path)) {
659
764
  reply.code(400);
660
765
  return { success: false, code: "cwd_invalid", error: "path required" } satisfies ApiResponse;
661
766
  }
@@ -671,14 +776,14 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
671
776
  result.error === "too_many_files" ||
672
777
  result.error === "file_too_large"
673
778
  ? 409
674
- : result.error === "outside_repo" || result.error === "not_a_directory"
779
+ : result.error === "outside_repo" || result.error === "not_a_directory" || result.error === "invalid_ref"
675
780
  ? 400
676
781
  : 500;
677
782
  reply.code(httpStatus);
678
783
  return {
679
784
  success: false,
680
785
  code: result.error,
681
- error: result.message,
786
+ error: redact(result.message, validated.cwd),
682
787
  } satisfies ApiResponse;
683
788
  }
684
789
  return { success: true } satisfies ApiResponse;
@@ -721,11 +826,11 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
721
826
  { preHandler: networkGuard },
722
827
  async (request, reply) => {
723
828
  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
- }
829
+ // B1r: the worktree path being removed (`cwd`) is a caller-supplied git argument — an
830
+ // option-like / control-character value is refused before admission or git.
831
+ if (typeof body.cwd === "string" && presentInvalid(body.cwd)) return invalidRef(reply, "path");
832
+ const validated = await validateCwd(body.cwd, reply);
833
+ if (!validated.ok) return validated.body;
729
834
  // Removing the main worktree — or one whose main checkout cannot be
730
835
  // resolved — is a clean rejection, not a 500 from git (D3).
731
836
  const { verdict, mainPath } = classifyRemoval(validated.cwd);
@@ -771,7 +876,7 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
771
876
  success: false,
772
877
  code: result.code,
773
878
  error: result.code,
774
- ...(result.stderr ? { stderr: result.stderr } : {}),
879
+ ...(result.stderr ? { stderr: redact(result.stderr, validated.cwd) } : {}),
775
880
  } satisfies ApiResponse;
776
881
  }
777
882
  stampCwdMissing(validated.cwd);
@@ -801,45 +906,101 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
801
906
  }
802
907
  // Per-item containment + removal; never abort on first failure (design D4).
803
908
  // 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).
909
+ // decision against live git state — but AT MOST ONCE PER DISTINCT checkout
910
+ // per request: items whose canonical cwd is equal reuse the memoized
911
+ // classification (the spec forbids resolving the same cwd twice within one request).
912
+ //
913
+ // Admission (change: core-cwd-admission, D1): sequential, memoized per distinct RAW cwd
914
+ // (the token is bound to the exact string), under a whole-batch budget. Each admission
915
+ // gets `deadlineMs = min(cap, remaining)`; once the budget is spent only a direct
916
+ // known-folder match (no git derivation) can still be decided. Tokens are released in
917
+ // one `finally`; the envelope stays 200 with per-item codes.
807
918
  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);
919
+ const admissionMemo = new Map<string, Promise<GitCwdCheck>>();
920
+ const tokens: AdmissionToken[] = [];
921
+ const budgetMs = deps.removeBatchAdmissionBudgetMs ?? REMOVE_BATCH_ADMISSION_BUDGET_MS;
922
+ const capMs = deps.admitOptions?.deadlineMs ?? ADMISSION_DEADLINE_MS;
923
+ const startedAt = Date.now();
924
+ // A scratch reply: a refused/unavailable item must not set the batch's HTTP status.
925
+ const itemReply = { code: () => itemReply, header: () => itemReply, raw: { once: () => undefined } } as unknown as FastifyReply;
926
+ const admitItem = (raw: string): Promise<GitCwdCheck> => {
927
+ let pending = admissionMemo.get(raw);
928
+ if (!pending) {
929
+ const remaining = budgetMs - (Date.now() - startedAt);
930
+ const opts: AdmitCwdOptions =
931
+ remaining > 0
932
+ ? { ...deps.admitOptions, deadlineMs: Math.min(capMs, remaining) }
933
+ : { ...deps.admitOptions, runner: NO_DERIVATION_RUNNER };
934
+ pending = (async (): Promise<GitCwdCheck> => {
935
+ const checked = await admitGitCwd(raw, itemReply, opts);
936
+ if (!checked.ok) return checked;
937
+ tokens.push(checked.token);
938
+ const invalid = (error: string): GitCwdCheck => ({ ok: false, code: "cwd_invalid", body: { success: false, code: "cwd_invalid", error } });
939
+ try {
940
+ if (!(await fs.promises.stat(checked.cwd)).isDirectory()) return invalid("cwd is not a directory");
941
+ } catch {
942
+ return invalid("cwd does not exist");
943
+ }
944
+ return checked;
945
+ })();
946
+ admissionMemo.set(raw, pending);
815
947
  }
816
- const { verdict, mainPath } = classification;
817
- if (verdict !== "removable") {
818
- return {
948
+ return pending;
949
+ };
950
+ const results: Array<Record<string, unknown>> = [];
951
+ try {
952
+ for (const item of items) {
953
+ const rawCwd = item?.cwd;
954
+ if (typeof rawCwd === "string" && presentInvalid(rawCwd)) {
955
+ results.push({ cwd: "", ok: false, code: INVALID_REF_CODE });
956
+ continue;
957
+ }
958
+ const validated: GitCwdCheck =
959
+ !rawCwd || typeof rawCwd !== "string"
960
+ ? { ok: false, code: "cwd_invalid", body: { success: false, code: "cwd_invalid", error: "cwd required" } }
961
+ : await admitItem(rawCwd);
962
+ if (!validated.ok) {
963
+ results.push({ cwd: rawCwd ?? "", ok: false, code: validated.code });
964
+ continue;
965
+ }
966
+ let classification = classificationMemo.get(validated.cwd);
967
+ if (!classification) {
968
+ classification = classifyRemoval(validated.cwd);
969
+ classificationMemo.set(validated.cwd, classification);
970
+ }
971
+ const { verdict, mainPath } = classification;
972
+ if (verdict !== "removable") {
973
+ results.push({
974
+ cwd: validated.cwd,
975
+ ok: false,
976
+ code: verdict === "main" ? "is_main_worktree" : "main_checkout_unresolved",
977
+ });
978
+ continue;
979
+ }
980
+ const force = item.force === true;
981
+ if (sessionManager) {
982
+ const activeIds = activeSessionsUnder(validated.cwd, sessionManager.listAll());
983
+ if (activeIds.length > 0 && !force) {
984
+ results.push({ cwd: validated.cwd, ok: false, code: "active_sessions", sessionIds: activeIds });
985
+ continue;
986
+ }
987
+ }
988
+ const result = removeWorktree({
819
989
  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 };
990
+ force,
991
+ deleteBranch: item.deleteBranch === true,
992
+ mainPath,
993
+ });
994
+ if (!result.ok) {
995
+ results.push({ cwd: validated.cwd, ok: false, code: result.code, ...(result.stderr ? { stderr: redact(result.stderr, validated.cwd) } : {}) });
996
+ continue;
829
997
  }
998
+ stampCwdMissing(validated.cwd);
999
+ results.push({ cwd: validated.cwd, ok: true, code: "ok", ...result.data });
830
1000
  }
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
- });
1001
+ } finally {
1002
+ for (const t of tokens) releaseAdmission(t);
1003
+ }
843
1004
  return { success: true, data: { results } } satisfies ApiResponse;
844
1005
  },
845
1006
  );
@@ -848,11 +1009,8 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
848
1009
  "/api/git/worktree/prune",
849
1010
  { preHandler: networkGuard },
850
1011
  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
- }
1012
+ const validated = await validateCwd((request.body ?? {}).cwd, reply);
1013
+ if (!validated.ok) return validated.body;
856
1014
  const result = pruneWorktrees(validated.cwd);
857
1015
  if (!result.ok) {
858
1016
  reply.code(result.code === "not_a_worktree" ? 400 : 500);
@@ -867,11 +1025,8 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
867
1025
  { preHandler: networkGuard },
868
1026
  async (request, reply) => {
869
1027
  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
- }
1028
+ const validated = await validateCwd(body.cwd, reply);
1029
+ if (!validated.ok) return validated.body;
875
1030
  const baseHint = sessionManager
876
1031
  ? sessionManager.listAll().find((s) => s.cwd === validated.cwd)?.gitWorktreeBase
877
1032
  : undefined;
@@ -891,7 +1046,7 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
891
1046
  success: false,
892
1047
  code: result.code,
893
1048
  error: result.code,
894
- ...(result.stderr ? { stderr: result.stderr } : {}),
1049
+ ...(result.stderr ? { stderr: redact(result.stderr, validated.cwd) } : {}),
895
1050
  } satisfies ApiResponse;
896
1051
  }
897
1052
  return { success: true, data: result.data } satisfies ApiResponse;
@@ -903,11 +1058,8 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
903
1058
  { preHandler: networkGuard },
904
1059
  async (request, reply) => {
905
1060
  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
- }
1061
+ const validated = await validateCwd(body.cwd, reply);
1062
+ if (!validated.ok) return validated.body;
911
1063
  const result = pushBranch({
912
1064
  cwd: validated.cwd,
913
1065
  setUpstream: body.setUpstream !== false,
@@ -922,7 +1074,7 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
922
1074
  success: false,
923
1075
  code: result.code,
924
1076
  error: result.code,
925
- ...(result.stderr ? { stderr: result.stderr } : {}),
1077
+ ...(result.stderr ? { stderr: redact(result.stderr, validated.cwd) } : {}),
926
1078
  } satisfies ApiResponse;
927
1079
  }
928
1080
  requestPrRefresh(validated.cwd, "push");
@@ -935,11 +1087,8 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
935
1087
  { preHandler: networkGuard },
936
1088
  async (request, reply) => {
937
1089
  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
- }
1090
+ const validated = await validateCwd(body.cwd, reply);
1091
+ if (!validated.ok) return validated.body;
943
1092
  const ghResolved = getDefaultRegistry().resolve("gh");
944
1093
  if (!ghResolved.ok || !ghResolved.path) {
945
1094
  reply.code(400);
@@ -970,7 +1119,7 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
970
1119
  success: false,
971
1120
  code: result.code,
972
1121
  error: result.code,
973
- ...(result.stderr ? { stderr: result.stderr } : {}),
1122
+ ...(result.stderr ? { stderr: redact(result.stderr, validated.cwd) } : {}),
974
1123
  } satisfies ApiResponse;
975
1124
  }
976
1125
  requestPrRefresh(validated.cwd, "pr");
@@ -983,11 +1132,8 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
983
1132
  "/api/git/pull-requests",
984
1133
  { preHandler: networkGuard },
985
1134
  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
- }
1135
+ const validated = await validateCwd(request.query.cwd, reply);
1136
+ if (!validated.ok) return validated.body;
991
1137
  const ghResolved = getDefaultRegistry().resolve("gh");
992
1138
  if (!ghResolved.ok || !ghResolved.path) {
993
1139
  reply.code(400);
@@ -1004,7 +1150,7 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
1004
1150
  success: false,
1005
1151
  code: result.code,
1006
1152
  error: result.code,
1007
- ...(result.stderr ? { stderr: result.stderr } : {}),
1153
+ ...(result.stderr ? { stderr: redact(result.stderr, validated.cwd) } : {}),
1008
1154
  } satisfies ApiResponse;
1009
1155
  }
1010
1156
  return { success: true, data: result.data } satisfies ApiResponse;
@@ -1012,21 +1158,20 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
1012
1158
  );
1013
1159
 
1014
1160
  // ── Create worktree from PR (change: add-worktree-from-pull-request) ────
1015
- fastify.post<{ Body: { cwd?: string; prNumber?: number; path?: string } }>(
1161
+ fastify.post<{ Body: { cwd?: string; prNumber?: number; path?: unknown } }>(
1016
1162
  "/api/git/worktree/from-pr",
1017
1163
  { preHandler: networkGuard },
1018
1164
  async (request, reply) => {
1019
1165
  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
- }
1166
+ // B1r: a present option-like / control-character path is refused before admission or git.
1167
+ if (presentInvalid(body.path)) return invalidRef(reply, "path");
1168
+ const validated = await validateCwd(body.cwd, reply);
1169
+ if (!validated.ok) return validated.body;
1025
1170
  if (typeof body.prNumber !== "number" || !Number.isInteger(body.prNumber) || body.prNumber <= 0) {
1026
1171
  reply.code(400);
1027
1172
  return { success: false, code: "cwd_invalid", error: "prNumber required (positive integer)" } satisfies ApiResponse;
1028
1173
  }
1029
- const pathArg = typeof body.path === "string" && body.path.length > 0 ? body.path : undefined;
1174
+ const pathArg = isValidRefArg(body.path) ? body.path : undefined;
1030
1175
  const result = addWorktreeFromPr({
1031
1176
  cwd: validated.cwd,
1032
1177
  prNumber: body.prNumber,
@@ -1037,14 +1182,14 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
1037
1182
  result.error === "pr_not_found" ? 404
1038
1183
  : result.error === "gh_not_authed" ? 401
1039
1184
  : 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
1185
+ : result.error === "not_a_repo" || result.error === "base_not_found" || result.error === "invalid_ref" ? 400
1041
1186
  : 500;
1042
1187
  reply.code(httpStatus);
1043
1188
  return {
1044
1189
  success: false,
1045
1190
  code: result.error,
1046
- error: result.message,
1047
- ...(result.stderr ? { stderr: result.stderr } : {}),
1191
+ error: redact(result.message, validated.cwd),
1192
+ ...(result.stderr ? { stderr: redact(result.stderr, validated.cwd) } : {}),
1048
1193
  ...(typeof result.orphanLikely === "boolean" ? { orphanLikely: result.orphanLikely } : {}),
1049
1194
  } satisfies ApiResponse;
1050
1195
  }
@@ -1059,11 +1204,8 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
1059
1204
  "/api/git/worktree/diff-stat",
1060
1205
  { preHandler: networkGuard },
1061
1206
  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
- }
1207
+ const validated = await validateCwd(request.query.cwd, reply);
1208
+ if (!validated.ok) return validated.body;
1067
1209
  const baseHint = sessionManager
1068
1210
  ? sessionManager.listAll().find((s) => s.cwd === validated.cwd)?.gitWorktreeBase
1069
1211
  : undefined;
@@ -1075,7 +1217,7 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
1075
1217
  success: false,
1076
1218
  code: result.code,
1077
1219
  error: result.code,
1078
- ...(result.stderr ? { stderr: result.stderr } : {}),
1220
+ ...(result.stderr ? { stderr: redact(result.stderr, validated.cwd) } : {}),
1079
1221
  } satisfies ApiResponse;
1080
1222
  }
1081
1223
  return { success: true, data: result.data } satisfies ApiResponse;
@@ -1091,40 +1233,14 @@ export function registerGitRoutes(fastify: FastifyInstance, deps: GitRoutesDeps)
1091
1233
  reply.code(400);
1092
1234
  return { success: false, code: "cwd_required", error: "cwd required" } satisfies ApiResponse;
1093
1235
  }
1236
+ const admitted = await admitGitCwd(cwd, reply);
1237
+ if (!admitted.ok) return admitted.body;
1094
1238
  try {
1095
- const result = stashPop(cwd);
1239
+ const result = stashPop(admitted.cwd);
1096
1240
  return { success: true, data: result } satisfies ApiResponse;
1097
1241
  } catch (err: any) {
1098
- return { success: false, code: "stash_pop_failed", error: err.message ?? "stash pop failed" } satisfies ApiResponse;
1242
+ return { success: false, code: "stash_pop_failed", error: redactErr(err, "stash pop failed", admitted.cwd) } satisfies ApiResponse;
1099
1243
  }
1100
1244
  },
1101
1245
  );
1102
1246
  }
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
- }