@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
@@ -5,6 +5,20 @@
5
5
  import { realpathSync } from "node:fs";
6
6
  import fs from "node:fs/promises";
7
7
  import path from "node:path";
8
+ import { DEFAULT_OPENSPEC_POLL, type OpenSpecPollConfig } from "@blackbelt-technology/pi-dashboard-shared/config.js";
9
+ import {
10
+ type AdmitCwdOptions,
11
+ admissionAllows,
12
+ releaseAdmission,
13
+ } from "@blackbelt-technology/pi-dashboard-shared/cwd-guard.js";
14
+ import {
15
+ type DeclaredDependencies,
16
+ type FileStat,
17
+ KEBAB_ID_REGEX,
18
+ MAX_DEPENDENCIES_BYTES,
19
+ MAX_REASON_CHARS,
20
+ serializeDependencies,
21
+ } from "@blackbelt-technology/pi-dashboard-shared/openspec-dependencies.js";
8
22
  import {
9
23
  configListAsync,
10
24
  configListOrAsync,
@@ -17,13 +31,20 @@ import {
17
31
  workflowSetSignature,
18
32
  writeOpenSpecConfigFile,
19
33
  } from "@blackbelt-technology/pi-dashboard-shared/platform/openspec.js";
20
- import { getDefaultRegistry } from "@blackbelt-technology/pi-dashboard-shared/tool-registry/index.js";
21
- import { DEFAULT_OPENSPEC_POLL, type OpenSpecPollConfig } from "@blackbelt-technology/pi-dashboard-shared/config.js";
34
+ import { isPortableProjectName } from "@blackbelt-technology/pi-dashboard-shared/project-name.js";
22
35
  import type { Semaphore } from "@blackbelt-technology/pi-dashboard-shared/semaphore.js";
23
36
  import { inferPlatform, pathKey } from "@blackbelt-technology/pi-dashboard-shared/session-group-path.js";
37
+ import { getDefaultRegistry } from "@blackbelt-technology/pi-dashboard-shared/tool-registry/index.js";
24
38
  import type { ApiResponse, OpenSpecConfig } from "@blackbelt-technology/pi-dashboard-shared/types.js";
25
- import type { FastifyInstance } from "fastify";
39
+ import type { FastifyInstance, FastifyReply } from "fastify";
26
40
  import { type DirectoryService, hasOpenSpecRoot } from "../directory-service.js";
41
+ import {
42
+ admitRouteCwd,
43
+ listKnownFolderCwds,
44
+ type RouteAdmissionDeps,
45
+ sendAdmissionUnavailable,
46
+ } from "../lib/route-admission.js";
47
+ import { readDeclared, writeDependenciesFile } from "../openspec/dependencies-file.js";
27
48
  import { currentGlobalWorkflowSignature } from "../openspec/global-signature.js";
28
49
  import { scanOpenSpecArchive } from "../openspec/openspec-archive.js";
29
50
  import {
@@ -35,16 +56,19 @@ import {
35
56
  } from "../openspec/openspec-tasks.js";
36
57
  import {
37
58
  inspectSchema,
59
+ resolveDeps,
38
60
  runWorkflowSchemaAction,
39
61
  type WorkflowSchemaAction,
40
62
  type WorkflowSchemaDeps,
41
63
  type WorkflowSchemaRequest,
42
64
  type WorkflowSchemaResult,
43
65
  type WorkflowSchemaStamp,
66
+ writeGuard,
44
67
  } from "../openspec/workflow-schema.js";
45
68
  import type { PreferencesStore } from "../persistence/preferences-store.js";
46
69
  import { type FolderCommandsResult, resolveFolderCommands } from "../pi/folder-commands.js";
47
70
  import { isWithinFolder, joinSkillProvenance, type SkillReporter, sessionCommandRegistry } from "../pi/session-skill-registry.js";
71
+ import { safeRealpathSync } from "../resolve-path.js";
48
72
  import type { SessionManager } from "../session/memory-session-manager.js";
49
73
  import type { NetworkGuard } from "./route-deps.js";
50
74
 
@@ -115,6 +139,79 @@ function canonicalPath(cwd: string): string {
115
139
  }
116
140
  }
117
141
 
142
+ /** Opt-out by exact `pathKey`, on the request spelling AND the canonical cwd (a symlink spelling cannot slip past). */
143
+ function isOptedOut(cwd: string, canonCwd: string, optOutDirectories: readonly string[]): boolean {
144
+ if (optOutDirectories.length === 0) return false;
145
+ const platform = inferPlatform([cwd, canonCwd, ...optOutDirectories]);
146
+ const keys = new Set(optOutDirectories.flatMap((d) => [pathKey(d, platform), pathKey(safeRealpathSync(d), platform)]));
147
+ return keys.has(pathKey(cwd, platform)) || keys.has(pathKey(canonCwd, platform));
148
+ }
149
+
150
+ type OpenSpecAdmission =
151
+ | { kind: "ok"; cwd: string; canonCwd: string }
152
+ | { kind: "refused" }
153
+ | { kind: "unavailable"; body: unknown };
154
+
155
+ /**
156
+ * Core cwd admission for the openspec routes (change: core-cwd-admission, D1/D4):
157
+ * `admitRouteCwd`, then the branch on `admissionAllows(admission, cwd)` right here, on the
158
+ * UNMODIFIED request value, so static analysis keeps its modelled barrier. The helpers hand back
159
+ * that guarded raw `cwd` (openspec signatures, broadcasts and opt-out keys stay raw) and the
160
+ * canonical cwd for the symlink-proof comparisons. The token is released when the response
161
+ * closes (success, error, throw or disconnect).
162
+ */
163
+ export function createOpenSpecAdmission(routeAdmission: RouteAdmissionDeps, globalOpenSpecDir: string) {
164
+ /** Whether `cwd` (raw or canonical) is the directory whose `openspec/` is the global OpenSpec config dir. */
165
+ function isGlobalOpenSpecParent(cwd: string, canonCwd: string): boolean {
166
+ const canonGlobal = path.join(safeRealpathSync(path.dirname(globalOpenSpecDir)), path.basename(globalOpenSpecDir));
167
+ return (
168
+ path.join(cwd, "openspec") === globalOpenSpecDir ||
169
+ path.join(canonCwd, "openspec") === globalOpenSpecDir ||
170
+ path.join(canonCwd, "openspec") === canonGlobal
171
+ );
172
+ }
173
+
174
+ /** Admit `raw`. `refused` leaves the reply untouched (the caller answers); `unavailable` has set the 503. */
175
+ async function admitOpenSpecCwd(raw: string, reply: FastifyReply): Promise<OpenSpecAdmission> {
176
+ const admission = await admitRouteCwd(raw, routeAdmission);
177
+ if (admission.kind === "indeterminate") return { kind: "unavailable", body: sendAdmissionUnavailable(reply) };
178
+ if (admission.kind !== "admit" || !admissionAllows(admission, raw)) return { kind: "refused" };
179
+ const token = admission.token;
180
+ reply.raw.once("close", () => releaseAdmission(token));
181
+ // The client may have gone while admission ran (`close` already fired): release at once.
182
+ if (reply.raw.destroyed) releaseAdmission(token);
183
+ return { kind: "ok", cwd: raw, canonCwd: token.canonCwd };
184
+ }
185
+
186
+ /**
187
+ * Admission for a site that did NOT refuse unknown cwds before this change: not admitted, or the
188
+ * global OpenSpec config dir → 403 `cwd_unknown` (design D4).
189
+ */
190
+ async function admitUngatedCwd(
191
+ raw: string,
192
+ reply: FastifyReply,
193
+ ): Promise<{ ok: true; cwd: string } | { ok: false; body: unknown }> {
194
+ const adm = await admitOpenSpecCwd(raw, reply);
195
+ if (adm.kind === "unavailable") return { ok: false, body: adm.body };
196
+ if (adm.kind === "refused" || isGlobalOpenSpecParent(raw, adm.canonCwd)) {
197
+ reply.code(403);
198
+ return {
199
+ ok: false,
200
+ body: {
201
+ success: false,
202
+ code: "cwd_unknown",
203
+ error: "cwd not allowed",
204
+ reason: "cwd is not a known session or pinned directory.",
205
+ hint: "Pin this directory to allow it, or open a session rooted in it.",
206
+ },
207
+ };
208
+ }
209
+ return { ok: true, cwd: adm.cwd };
210
+ }
211
+
212
+ return { admitOpenSpecCwd, admitUngatedCwd, isGlobalOpenSpecParent };
213
+ }
214
+
118
215
  export function registerOpenSpecRoutes(
119
216
  fastify: FastifyInstance,
120
217
  deps: {
@@ -136,6 +233,14 @@ export function registerOpenSpecRoutes(
136
233
  spawnSemaphore?: Semaphore;
137
234
  /** Test seam: overrides for the workflow-schema module's collaborators (CLI, fs, clock…). */
138
235
  workflowSchemaDeps?: Partial<WorkflowSchemaDeps>;
236
+ /**
237
+ * Live known-folder set (session cwds ∪ pinned directories, unfiltered) every caller-supplied
238
+ * `cwd` is admitted against. Absent → the same set from `sessionManager` + `preferencesStore`.
239
+ * See change: core-cwd-admission.
240
+ */
241
+ knownFolderCwds?: () => string[];
242
+ /** `admitCwd` options: the host's throttled `onIndeterminate` logger + test seams. */
243
+ admitOptions?: AdmitCwdOptions;
139
244
  },
140
245
  ) {
141
246
  const { sessionManager, preferencesStore, directoryService, networkGuard, onOpenSpecChanged, piGateway } = deps;
@@ -156,7 +261,9 @@ export function registerOpenSpecRoutes(
156
261
  // omitted, run `openspec config list` in any known project (or process
157
262
  // cwd) so the Settings section can read the global config without a cwd.
158
263
  // See change: add-openspec-profile-settings.
159
- const cwd = request.query.cwd ?? knownCwds()[0] ?? process.cwd();
264
+ const resolved = await resolveConfigCwd(request.query.cwd, reply);
265
+ if (!resolved.ok) return resolved.body;
266
+ const cwd = resolved.cwd;
160
267
  const now = Date.now();
161
268
  const cached = configCache.get(cwd);
162
269
  if (cached && now - cached.ts < CONFIG_TTL_MS) {
@@ -207,6 +314,33 @@ export function registerOpenSpecRoutes(
207
314
  // See change: add-openspec-profile-settings.
208
315
  const GLOBAL_OPENSPEC_DIR = path.dirname(openSpecConfigFilePath()); // ~/.config/openspec
209
316
 
317
+ // Core cwd admission (change: core-cwd-admission, D1/D4): see `createOpenSpecAdmission`.
318
+ const { admitOpenSpecCwd, admitUngatedCwd, isGlobalOpenSpecParent } = createOpenSpecAdmission(
319
+ {
320
+ knownCwds: deps.knownFolderCwds ?? (() => listKnownFolderCwds({ sessionManager, preferencesStore })),
321
+ admitOptions: deps.admitOptions,
322
+ },
323
+ GLOBAL_OPENSPEC_DIR,
324
+ );
325
+
326
+ /**
327
+ * The cwd of the global-config routes: a caller-supplied cwd is admitted; with none, the
328
+ * server-chosen fallback (`knownCwds()[0] ?? process.cwd()`) is kept and not re-admitted.
329
+ */
330
+ async function resolveConfigCwd(
331
+ requested: unknown,
332
+ reply: FastifyReply,
333
+ ): Promise<{ ok: true; cwd: string } | { ok: false; body: unknown }> {
334
+ if (typeof requested === "string" && requested.length > 0) return admitUngatedCwd(requested, reply);
335
+ return { ok: true, cwd: knownCwds()[0] ?? process.cwd() };
336
+ }
337
+
338
+ /** A request path segment (a change name) joined under the cwd by a lib: a single portable segment only. */
339
+ const invalidName = (reply: FastifyReply) => {
340
+ reply.code(400);
341
+ return { success: false, code: "invalid_name", error: "invalid change name" };
342
+ };
343
+
210
344
  // True when `workflows` is exactly the EXPANDED_WORKFLOWS set (order-agnostic).
211
345
  // Used to re-surface a custom-persisted expanded profile as the "expanded"
212
346
  // alias on read. See change: fix-openspec-expanded-profile-update.
@@ -276,7 +410,9 @@ export function registerOpenSpecRoutes(
276
410
  return { success: false, error: "invalid profile" } satisfies ApiResponse;
277
411
  }
278
412
  // cwd is only needed for the `core` preset invocation (CLI runs in a dir).
279
- const cwd = body.cwd ?? knownCwds()[0] ?? process.cwd();
413
+ const resolved = await resolveConfigCwd(body.cwd, reply);
414
+ if (!resolved.ok) return resolved.body;
415
+ const cwd = resolved.cwd;
280
416
 
281
417
  if (profile === "core") {
282
418
  const res = configProfile({ cwd, preset: "core" });
@@ -315,7 +451,16 @@ export function registerOpenSpecRoutes(
315
451
  { preHandler: networkGuard },
316
452
  async (request, reply) => {
317
453
  const body = request.body ?? {};
318
- const targets = body.all ? knownCwds() : body.cwd ? [body.cwd] : [];
454
+ let targets: string[];
455
+ if (body.all) {
456
+ targets = knownCwds(); // server-chosen list: not re-admitted
457
+ } else if (typeof body.cwd === "string" && body.cwd.length > 0) {
458
+ const admitted = await admitUngatedCwd(body.cwd, reply);
459
+ if (!admitted.ok) return admitted.body;
460
+ targets = [admitted.cwd];
461
+ } else {
462
+ targets = [];
463
+ }
319
464
  if (targets.length === 0) {
320
465
  reply.code(400);
321
466
  return { success: false, error: "cwd or all required" } satisfies ApiResponse;
@@ -456,19 +601,18 @@ export function registerOpenSpecRoutes(
456
601
  if (b.changes !== undefined && !(Array.isArray(b.changes) && b.changes.every((c) => typeof c === "string"))) {
457
602
  return fail(400, "changes must be an array of strings");
458
603
  }
459
- const cwd = b.cwd;
460
-
461
- if (!knownInitTargets().includes(cwd)) {
604
+ // Admission first (the modelled guard; indeterminate → 503), then the EXISTING exact
605
+ // membership / opt-out / global-dir gates with their existing refusals — no widening.
606
+ const adm = await admitOpenSpecCwd(b.cwd, reply);
607
+ if (adm.kind === "unavailable") return adm.body;
608
+ if (adm.kind === "refused" || !knownInitTargets().includes(adm.cwd) || isGlobalOpenSpecParent(adm.cwd, adm.canonCwd)) {
462
609
  return fail(400, "cwd is not a known session or pinned directory", "untracked");
463
610
  }
611
+ const cwd = adm.cwd;
464
612
  const cfg = gateConfig();
465
613
  if (cfg.enabled === false) return fail(400, "OpenSpec is disabled", "openspec_disabled");
466
- if (cfg.optOutDirectories.length > 0) {
467
- const platform = inferPlatform([cwd, ...cfg.optOutDirectories]);
468
- const key = pathKey(cwd, platform);
469
- if (cfg.optOutDirectories.some((d) => pathKey(d, platform) === key)) {
470
- return fail(400, "OpenSpec is opted out for this directory", "opted_out");
471
- }
614
+ if (isOptedOut(cwd, adm.canonCwd, cfg.optOutDirectories)) {
615
+ return fail(400, "OpenSpec is opted out for this directory", "opted_out");
472
616
  }
473
617
 
474
618
  // Only now touch the filesystem.
@@ -506,19 +650,205 @@ export function registerOpenSpecRoutes(
506
650
  },
507
651
  );
508
652
 
653
+ // ── Change dependencies (add-openspec-change-dependencies) ───────────
654
+ //
655
+ // GET/PUT /api/openspec/dependencies?cwd=&change= — one change's
656
+ // `dependencies.yaml`. Gate order (answers carry `reason`): request shape →
657
+ // tracked → enabled → not opted out → `openspec/` exists → not on the
658
+ // fallback path → a cached `status --all` result → change in that result.
659
+ // PUT then: write guard + containment → per-cwd lock → `expected` precondition
660
+ // → atomic write.
661
+ type DepGate = { ok: true; cwd: string; real: string; change: string } | { ok: false };
662
+
663
+ const depFail = (reply: import("fastify").FastifyReply, code: number, reason: string, error: string) => {
664
+ reply.code(code);
665
+ return { success: false, error, reason } satisfies ApiResponse & { reason: string };
666
+ };
667
+
668
+ /** Gates 2–8 of the dependencies endpoints (gate 1, request validity, runs before). */
669
+ async function depGates(requestCwd: string, change: string, reply: import("fastify").FastifyReply): Promise<DepGate | { ok: false; body: unknown }> {
670
+ const respond = (code: number, reason: string, error: string) => ({ ok: false as const, body: depFail(reply, code, reason, error) });
671
+ // Admission is the modelled guard (indeterminate → 503); the exact membership / opt-out
672
+ // gates and their refusals are unchanged. The gate hands back the guarded raw cwd.
673
+ const adm = await admitOpenSpecCwd(requestCwd, reply);
674
+ if (adm.kind === "unavailable") return { ok: false, body: adm.body };
675
+ if (adm.kind === "refused" || !knownInitTargets().includes(adm.cwd) || isGlobalOpenSpecParent(adm.cwd, adm.canonCwd)) {
676
+ return respond(403, "cwd-not-tracked", "cwd is not a known session or pinned directory");
677
+ }
678
+ const cwd = adm.cwd;
679
+ const cfg = gateConfig();
680
+ if (cfg.enabled === false) return respond(403, "openspec-disabled", "OpenSpec is disabled");
681
+ if (isOptedOut(cwd, adm.canonCwd, cfg.optOutDirectories)) {
682
+ return respond(403, "opted-out", "OpenSpec is opted out for this directory");
683
+ }
684
+ let real: string;
685
+ try {
686
+ real = realpathSync.native(cwd);
687
+ } catch {
688
+ return respond(404, "no-openspec-dir", "cwd does not exist");
689
+ }
690
+ const hasOpenspec = await fs
691
+ .stat(path.join(real, "openspec"))
692
+ .then((st) => st.isDirectory())
693
+ .catch(() => false);
694
+ if (!hasOpenspec) return respond(404, "no-openspec-dir", "no openspec/ directory in cwd");
695
+ if (directoryService.getOpenSpecPollMode(cwd) === "fallback") {
696
+ return respond(409, "status-all-unsupported", "this OpenSpec CLI has no `status --all`; dependencies are not computed");
697
+ }
698
+ const data = directoryService.getOpenSpecData(cwd);
699
+ if (!data || !data.initialized || directoryService.getOpenSpecPollMode(cwd) !== "all") {
700
+ return respond(503, "pending", "no OpenSpec status result is cached for this directory yet");
701
+ }
702
+ if (!data.changes.some((c) => c.name === change)) return respond(404, "unknown-change", `no active change named ${change}`);
703
+ return { ok: true, cwd, real, change };
704
+ }
705
+
706
+ fastify.get<{ Querystring: { cwd?: string; change?: string } }>(
707
+ "/api/openspec/dependencies",
708
+ { preHandler: networkGuard },
709
+ async (request, reply) => {
710
+ const { cwd, change } = request.query ?? {};
711
+ if (typeof cwd !== "string" || !cwd || typeof change !== "string" || !KEBAB_ID_REGEX.test(change) || !isPortableProjectName(change)) {
712
+ return depFail(reply, 400, "invalid-request", "cwd and a valid change name are required");
713
+ }
714
+ const gate = await depGates(cwd, change, reply);
715
+ if (!gate.ok) return "body" in gate ? gate.body : undefined;
716
+ const entry = directoryService.getOpenSpecData(gate.cwd)?.changes.find((c) => c.name === change);
717
+ const read = await readDeclared(gate.real, change);
718
+ return {
719
+ success: true,
720
+ data: {
721
+ dependencies: entry?.dependencies ?? null,
722
+ declared: read.declared,
723
+ declaredError: read.declaredError,
724
+ file: read.file,
725
+ },
726
+ } satisfies ApiResponse;
727
+ },
728
+ );
729
+
730
+ /** Whole-body validation of the PUT (gate 1). Returns the parsed declaration or an error message. */
731
+ function parseDependenciesPut(
732
+ body: unknown,
733
+ ): { ok: true; cwd: string; change: string; declared: DeclaredDependencies; expected: FileStat | null } | { ok: false; error: string } {
734
+ if (!body || typeof body !== "object" || Array.isArray(body)) return { ok: false, error: "JSON object body required" };
735
+ if (Buffer.byteLength(JSON.stringify(body), "utf8") > MAX_DEPENDENCIES_BYTES) return { ok: false, error: "body exceeds 64 KiB" };
736
+ const b = body as Record<string, unknown>;
737
+ if (typeof b.cwd !== "string" || !b.cwd) return { ok: false, error: "cwd required" };
738
+ if (typeof b.change !== "string" || !KEBAB_ID_REGEX.test(b.change) || !isPortableProjectName(b.change)) return { ok: false, error: "change must be a valid change name" };
739
+ const change = b.change;
740
+ const names = (v: unknown, key: string): string[] | string => {
741
+ if (!Array.isArray(v)) return `${key} must be a list`;
742
+ const out: string[] = [];
743
+ for (const n of v) {
744
+ if (typeof n !== "string" || !KEBAB_ID_REGEX.test(n)) return `${key} has an invalid change name`;
745
+ if (n === change) return `${key} must not name the change itself`;
746
+ if (!out.includes(n)) out.push(n);
747
+ }
748
+ return out;
749
+ };
750
+ if (!Array.isArray(b.blockedBy)) return { ok: false, error: "blockedBy must be a list" };
751
+ const blockedBy: DeclaredDependencies["blockedBy"] = [];
752
+ for (const item of b.blockedBy) {
753
+ const rec = typeof item === "string" ? { change: item } : (item as { change?: unknown; reason?: unknown } | null);
754
+ if (!rec || typeof rec !== "object" || typeof rec.change !== "string" || !KEBAB_ID_REGEX.test(rec.change)) {
755
+ return { ok: false, error: "blockedBy has an invalid change name" };
756
+ }
757
+ if (rec.change === change) return { ok: false, error: "blockedBy must not name the change itself" };
758
+ const reason = (rec as { reason?: unknown }).reason;
759
+ if (reason !== undefined && reason !== null && (typeof reason !== "string" || reason.length > MAX_REASON_CHARS)) {
760
+ return { ok: false, error: `reason must be a string of at most ${MAX_REASON_CHARS} characters` };
761
+ }
762
+ if (blockedBy.some((x) => x.change === rec.change)) continue;
763
+ blockedBy.push(typeof reason === "string" && reason !== "" ? { change: rec.change, reason } : { change: rec.change });
764
+ }
765
+ const notBlockedBy = names(b.notBlockedBy, "notBlockedBy");
766
+ if (typeof notBlockedBy === "string") return { ok: false, error: notBlockedBy };
767
+ const related = names(b.related, "related");
768
+ if (typeof related === "string") return { ok: false, error: related };
769
+ if (!("expected" in b)) return { ok: false, error: "expected is required (null or { mtimeMs, size })" };
770
+ let expected: FileStat | null = null;
771
+ if (b.expected !== null) {
772
+ const e = b.expected as { mtimeMs?: unknown; size?: unknown };
773
+ if (!e || typeof e !== "object" || typeof e.mtimeMs !== "number" || typeof e.size !== "number") {
774
+ return { ok: false, error: "expected must be null or { mtimeMs, size }" };
775
+ }
776
+ expected = { mtimeMs: e.mtimeMs, size: e.size };
777
+ }
778
+ return { ok: true, cwd: b.cwd, change, declared: { blockedBy, notBlockedBy, related }, expected };
779
+ }
780
+
781
+ fastify.put<{ Body: unknown }>(
782
+ "/api/openspec/dependencies",
783
+ { preHandler: networkGuard },
784
+ async (request, reply) => {
785
+ const parsed = parseDependenciesPut(request.body);
786
+ if (!parsed.ok) return depFail(reply, 400, "invalid-request", parsed.error);
787
+ const { change, declared, expected } = parsed;
788
+ const gate = await depGates(parsed.cwd, change, reply);
789
+ if (!gate.ok) return "body" in gate ? gate.body : undefined;
790
+ const cwd = gate.cwd; // the admission-bound request value
791
+
792
+ // Same root verification as every workflow-schema write.
793
+ // The guard spawns `status --all`; bound it by the shared spawn semaphore like every other CLI spawn.
794
+ const guard = () => writeGuard(cwd, resolveDeps(deps.workflowSchemaDeps));
795
+ const guarded = await (deps.spawnSemaphore ? deps.spawnSemaphore.run(guard) : guard());
796
+ if ("error" in guarded) return depFail(reply, 403, "write-refused", guarded.error);
797
+
798
+ // Shared per-cwd lock (keyed by the canonical cwd, so symlinked spellings collide).
799
+ const lockKey = gate.real; // canonical cwd from the gates; never re-resolved after they answered
800
+ if (inFlightInits.has(lockKey)) {
801
+ return depFail(reply, 409, "locked", "an OpenSpec init or workflow-schema action is already in flight for this directory");
802
+ }
803
+ inFlightInits.add(lockKey);
804
+ try {
805
+ const out = await writeDependenciesFile({
806
+ root: guarded.root,
807
+ change,
808
+ content: serializeDependencies(declared),
809
+ expected,
810
+ });
811
+ if (!out.ok) return depFail(reply, out.status, out.reason, out.error);
812
+ request.log.info(
813
+ {
814
+ event: "openspec.dependencies",
815
+ cwd,
816
+ change,
817
+ blockedBy: declared.blockedBy.length,
818
+ notBlockedBy: declared.notBlockedBy.length,
819
+ related: declared.related.length,
820
+ },
821
+ "openspec dependencies written",
822
+ );
823
+ // The watcher would pick the write up; refresh now so the board updates promptly.
824
+ void directoryService
825
+ .refreshOpenSpec(cwd)
826
+ .then(() => onOpenSpecChanged?.(cwd))
827
+ .catch(() => undefined);
828
+ return { success: true, data: { file: out.file } } satisfies ApiResponse;
829
+ } finally {
830
+ inFlightInits.delete(lockKey);
831
+ }
832
+ },
833
+ );
834
+
509
835
  fastify.post<{ Body: { cwd?: string; confirm?: boolean } }>(
510
836
  "/api/openspec/init",
511
837
  { preHandler: networkGuard },
512
838
  async (request, reply) => {
513
- const cwd = request.body?.cwd;
514
- if (!cwd) {
839
+ const requestCwd = request.body?.cwd;
840
+ if (!requestCwd) {
515
841
  reply.code(400);
516
842
  return { success: false, error: "cwd required" } satisfies ApiResponse;
517
843
  }
518
- if (!knownInitTargets().includes(cwd)) {
844
+ // Admission (modelled guard; indeterminate → 503), then the existing exact membership.
845
+ const adm = await admitOpenSpecCwd(requestCwd, reply);
846
+ if (adm.kind === "unavailable") return adm.body;
847
+ if (adm.kind === "refused" || !knownInitTargets().includes(adm.cwd) || isGlobalOpenSpecParent(adm.cwd, adm.canonCwd)) {
519
848
  reply.code(400);
520
849
  return { success: false, error: "cwd is not a known session or pinned directory" } satisfies ApiResponse;
521
850
  }
851
+ const cwd = adm.cwd;
522
852
 
523
853
  // Overwrite confirmation. Two coarse triggers, both deliberate:
524
854
  // 1. <cwd>/openspec/ presence — the spec's minimum contract.
@@ -674,12 +1004,14 @@ export function registerOpenSpecRoutes(
674
1004
  "/api/openspec-archive",
675
1005
  { preHandler: networkGuard },
676
1006
  async (request, reply) => {
677
- const cwd = request.query.cwd;
678
- if (!cwd) {
1007
+ const requestCwd = request.query.cwd;
1008
+ if (!requestCwd) {
679
1009
  reply.code(400);
680
1010
  return { success: false, error: "Missing cwd" } satisfies ApiResponse;
681
1011
  }
682
- const data = await scanOpenSpecArchive(cwd);
1012
+ const admitted = await admitUngatedCwd(requestCwd, reply);
1013
+ if (!admitted.ok) return admitted.body;
1014
+ const data = await scanOpenSpecArchive(admitted.cwd);
683
1015
  return { success: true, data } satisfies ApiResponse;
684
1016
  },
685
1017
  );
@@ -692,7 +1024,14 @@ export function registerOpenSpecRoutes(
692
1024
  // cwd optional: the global Settings resource pages read only the
693
1025
  // global scope (cwd-independent), so they omit it and the server scans
694
1026
  // relative to its own cwd. See change: resources-card-tabs.
695
- const cwd = request.query.cwd ?? process.cwd();
1027
+ let cwd: string;
1028
+ if (typeof request.query.cwd === "string" && request.query.cwd.length > 0) {
1029
+ const admitted = await admitUngatedCwd(request.query.cwd, reply);
1030
+ if (!admitted.ok) return admitted.body;
1031
+ cwd = admitted.cwd;
1032
+ } else {
1033
+ cwd = process.cwd();
1034
+ }
696
1035
  // Bootstrap gate removed under change: eliminate-electron-runtime-install
697
1036
  // (task 3.5). pi/openspec/tsx ship as regular npm deps; pi-resources
698
1037
  // endpoint is unconditionally available.
@@ -732,11 +1071,15 @@ export function registerOpenSpecRoutes(
732
1071
  "/api/pi-resources/commands",
733
1072
  { preHandler: networkGuard },
734
1073
  async (request, reply) => {
735
- const cwd = request.query.cwd;
736
- if (typeof cwd !== "string" || cwd.length === 0 || !path.isAbsolute(cwd)) {
1074
+ const requestCwd = request.query.cwd;
1075
+ // Shape check BEFORE admission: a relative cwd is never resolved against the server's cwd.
1076
+ if (typeof requestCwd !== "string" || requestCwd.length === 0 || !path.isAbsolute(requestCwd)) {
737
1077
  reply.code(400);
738
1078
  return { success: false, error: "cwd must be an absolute path" } satisfies ApiResponse;
739
1079
  }
1080
+ const admitted = await admitUngatedCwd(requestCwd, reply);
1081
+ if (!admitted.ok) return admitted.body;
1082
+ const cwd = admitted.cwd;
740
1083
  let scan: Awaited<ReturnType<typeof directoryService.refreshPiResources>> | undefined;
741
1084
  try {
742
1085
  const cached = directoryService.getPiResources(cwd);
@@ -803,11 +1146,15 @@ export function registerOpenSpecRoutes(
803
1146
  "/api/openspec/tasks",
804
1147
  { preHandler: networkGuard },
805
1148
  async (request, reply) => {
806
- const { cwd, change } = request.query;
807
- if (!cwd || !change) {
1149
+ const { cwd: requestCwd, change } = request.query;
1150
+ if (!requestCwd || typeof change !== "string") {
808
1151
  reply.code(400);
809
1152
  return { success: false, error: "cwd and change query params required" } satisfies ApiResponse;
810
1153
  }
1154
+ const admitted = await admitUngatedCwd(requestCwd, reply);
1155
+ if (!admitted.ok) return admitted.body;
1156
+ const cwd = admitted.cwd;
1157
+ if (!isPortableProjectName(change)) return invalidName(reply);
811
1158
  try {
812
1159
  const tasks = await readTasks(cwd, change);
813
1160
  const groups = Array.from(new Set(tasks.map((t) => t.group).filter((g) => g.length > 0)));
@@ -830,9 +1177,9 @@ export function registerOpenSpecRoutes(
830
1177
  { preHandler: networkGuard },
831
1178
  async (request, reply) => {
832
1179
  const body = request.body ?? {};
833
- const { cwd, change, id, done, line } = body;
1180
+ const { cwd: requestCwd, change, id, done, line } = body;
834
1181
  if (
835
- typeof cwd !== "string" ||
1182
+ typeof requestCwd !== "string" ||
836
1183
  typeof change !== "string" ||
837
1184
  typeof id !== "string" ||
838
1185
  typeof done !== "boolean" ||
@@ -841,6 +1188,10 @@ export function registerOpenSpecRoutes(
841
1188
  reply.code(400);
842
1189
  return { success: false, error: "invalid body" } satisfies ApiResponse;
843
1190
  }
1191
+ const admitted = await admitUngatedCwd(requestCwd, reply);
1192
+ if (!admitted.ok) return admitted.body;
1193
+ const cwd = admitted.cwd;
1194
+ if (!isPortableProjectName(change)) return invalidName(reply);
844
1195
  try {
845
1196
  const task = await toggleTask(cwd, change, id, done, line);
846
1197
  // Fire-and-forget: refresh cache + broadcast openspec_update.