@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
@@ -37,6 +37,7 @@ import {
37
37
  type TrackedExtras,
38
38
  } from "@blackbelt-technology/pi-dashboard-shared/openspec-status-all.js";
39
39
  import type { OpenSpecChange, OpenSpecData } from "@blackbelt-technology/pi-dashboard-shared/types.js";
40
+ import { computeDependencies, summarizeDependencyGraph } from "./openspec-dependency-inputs.js";
40
41
  import {
41
42
  effectiveMtimeOr,
42
43
  type ProbeRequest,
@@ -44,6 +45,7 @@ import {
44
45
  perChangeArtifactPaths,
45
46
  probeTrackedPaths,
46
47
  } from "./openspec-poll-fs-helpers.js";
48
+ import { computeSchemaStatus, type SchemaStatusResult } from "./workflow-schema-status.js";
47
49
 
48
50
  export type { ProbeRequest, ProbeResponse };
49
51
  export { probeTrackedPaths };
@@ -215,6 +217,11 @@ export type StatusAllBuildResponse =
215
217
  cwdStamp: number | undefined;
216
218
  /** Tracked extras per change for the next probe and the watcher filter. */
217
219
  extras: Record<string, TrackedExtras>;
220
+ /**
221
+ * Capability ids touched by an active delta, stored with the gate stamp:
222
+ * the next probe stats their main-spec paths. See change: add-openspec-change-dependencies.
223
+ */
224
+ capabilityIds: string[];
218
225
  };
219
226
 
220
227
  function sameExtras(a: TrackedExtras | undefined, b: TrackedExtras | undefined): boolean {
@@ -297,7 +304,39 @@ export async function buildFromStatusAll(req: StatusAllBuildRequest): Promise<St
297
304
  for (const name of rec.needNewSetStamp) rec.stampMtimes[name] = reprobe.changes[name];
298
305
  }
299
306
 
300
- const data = finishPayload({ initialized: true, changes: rec.changes }, hasOpenspecDir, groupAssignments);
307
+ // Dependency graph: always recomputed from the files read in THIS build, for
308
+ // every change — including racy ones whose other fields keep the previous
309
+ // entry — so `blocks` / `blockedBy` stay inverse within one payload.
310
+ const dep = await computeDependencies(
311
+ openspecDir,
312
+ rec.changes.map((c) => c.name),
313
+ post.changes,
314
+ );
315
+ if (debugEnabled()) {
316
+ // eslint-disable-next-line no-console
317
+ console.debug(summarizeDependencyGraph(dep.graph, dep.ms));
318
+ }
319
+ const changes = rec.changes.map((c) => ({ ...c, dependencies: dep.graph[c.name] }));
320
+
321
+ // The cwd-level stamp must cover the paths the NEXT probe will stat; when the
322
+ // touched capability set moved, re-take the cwd-level mtime over the new set.
323
+ const prevCaps = probeReq.capabilityIds ? [...probeReq.capabilityIds].sort().join("\n") : null;
324
+ let cwdStamp = pre.cwdMtime === post.cwdMtime ? pre.cwdMtime : undefined;
325
+ if (cwdStamp !== undefined && prevCaps !== dep.capabilityIds.join("\n")) {
326
+ const restamp = (await probeTrackedPaths({ openspecDir, extras: built.extras, capabilityIds: dep.capabilityIds })).cwdMtime;
327
+ // The new stamp is taken AFTER the main-spec reads it covers. A spec sync landing in between would be inside
328
+ // the stamp but missing from the graph, and the next gated tick would reuse the stale payload. Re-read once
329
+ // (warm: per-file parses are cached); keep the stamp only if the graph did not move.
330
+ const again = await computeDependencies(
331
+ openspecDir,
332
+ rec.changes.map((c) => c.name),
333
+ post.changes,
334
+ );
335
+ const same = again.capabilityIds.join("\n") === dep.capabilityIds.join("\n") && JSON.stringify(again.graph) === JSON.stringify(dep.graph);
336
+ cwdStamp = same ? restamp : undefined;
337
+ }
338
+
339
+ const data = finishPayload({ initialized: true, changes }, hasOpenspecDir, groupAssignments);
301
340
  return {
302
341
  cwd,
303
342
  kind: "ok",
@@ -305,15 +344,67 @@ export async function buildFromStatusAll(req: StatusAllBuildRequest): Promise<St
305
344
  serialized: JSON.stringify(data),
306
345
  stampMtimes: rec.stampMtimes,
307
346
  racyNames: rec.racyNames,
308
- cwdStamp: pre.cwdMtime === post.cwdMtime ? pre.cwdMtime : undefined,
347
+ cwdStamp,
309
348
  extras: built.extras,
349
+ capabilityIds: dep.capabilityIds,
310
350
  };
311
351
  }
312
352
 
353
+ // ── `schemaStatus` request ──────────────────────────────────────────
354
+ //
355
+ // Filesystem part of `OpenSpecData.workflowSchema`, computed on every poll tick
356
+ // (gate hit or not). The main thread resolves the CLI-dependent inputs and runs
357
+ // the `newer`/`conflict` `schema validate` for the returned fingerprint.
358
+ // See change: move-workflow-schema-status-to-poll-worker.
359
+
360
+ export interface SchemaStatusRequest {
361
+ cwd: string;
362
+ /** Resolved CLI version; `""` when unknown. */
363
+ localVersion: string;
364
+ /** `<openspec package>/schemas`, `null` = unknown. Resolved on main. */
365
+ packageSchemasDir: string | null;
366
+ /** User-level schemas dir. Resolved on main. */
367
+ userSchemasDir: string;
368
+ }
369
+
370
+ export type SchemaStatusResponse = SchemaStatusResult;
371
+
372
+ /** The whole worker body of the `schemaStatus` request (also the default in-process implementation). */
373
+ export function computeSchemaStatusFor(req: SchemaStatusRequest): Promise<SchemaStatusResponse> {
374
+ return computeSchemaStatus(req.cwd, {
375
+ localVersion: req.localVersion,
376
+ packageSchemasDir: req.packageSchemasDir,
377
+ userSchemasDirPath: req.userSchemasDir,
378
+ fingerprint: "when-needed",
379
+ });
380
+ }
381
+
313
382
  // ── Worker bootstrap ────────────────────────────────────────────────
314
383
  // Only runs when this module is loaded as the entry of a `worker_threads`
315
384
  // Worker. Direct imports (tests, in-process fallback) skip this block.
316
- export type PollWorkerKind = "derive" | "probe" | "build";
385
+ export type PollWorkerKind = "derive" | "probe" | "build" | "schemaStatus";
386
+
387
+ /**
388
+ * Run one request body. Exhaustive over the request kind: an unknown kind
389
+ * rejects instead of silently running another request's body.
390
+ */
391
+ export async function handlePollWorkerMessage(kind: PollWorkerKind | undefined, payload: unknown): Promise<unknown> {
392
+ switch (kind) {
393
+ case undefined: // legacy messages without a kind are `derive`
394
+ case "derive":
395
+ return deriveAndSerialize(payload as PollWorkerRequest);
396
+ case "probe":
397
+ return probeTrackedPaths(payload as ProbeRequest);
398
+ case "build":
399
+ return buildFromStatusAll(payload as StatusAllBuildRequest);
400
+ case "schemaStatus":
401
+ return computeSchemaStatusFor(payload as SchemaStatusRequest);
402
+ default: {
403
+ const unknownKind: never = kind;
404
+ throw new Error(`unknown poll worker request kind: ${String(unknownKind)}`);
405
+ }
406
+ }
407
+ }
317
408
 
318
409
  if (!isMainThread && parentPort !== null) {
319
410
  parentPort.on(
@@ -325,12 +416,7 @@ if (!isMainThread && parentPort !== null) {
325
416
  }
326
417
  const { id, kind, payload } = msg as { id: number; kind?: PollWorkerKind; payload: unknown };
327
418
  try {
328
- const response =
329
- kind === "probe"
330
- ? await probeTrackedPaths(payload as ProbeRequest)
331
- : kind === "build"
332
- ? await buildFromStatusAll(payload as StatusAllBuildRequest)
333
- : deriveAndSerialize(payload as PollWorkerRequest);
419
+ const response = await handlePollWorkerMessage(kind, payload);
334
420
  parentPort!.postMessage({ id, ok: true, response });
335
421
  } catch (err) {
336
422
  parentPort!.postMessage({
@@ -0,0 +1,379 @@
1
+ /**
2
+ * Worker-safe, filesystem-only status of the dashboard-managed OpenSpec
3
+ * workflow schema `pi-spec-driven`: config read, stamp parse + component-wise
4
+ * comparison, schema resolution, change enumeration and `.openspec.yaml`
5
+ * stats. Never spawns the CLI and imports no CLI recipe, semaphore or
6
+ * `workflow-schema.ts`, so the poll worker can load it cheaply.
7
+ *
8
+ * `workflow-schema.ts` imports these helpers back (generation, actions, REST),
9
+ * so the poll path and the writing path share one implementation.
10
+ *
11
+ * See changes: add-pi-spec-driven-schema, move-workflow-schema-status-to-poll-worker.
12
+ */
13
+ import crypto from "node:crypto";
14
+ import type { Dirent, Stats } from "node:fs";
15
+ import fsp from "node:fs/promises";
16
+ import path from "node:path";
17
+ import { mapLimit } from "@blackbelt-technology/pi-dashboard-shared/openspec-status-all.js";
18
+ import type {
19
+ OpenSpecWorkflowSchemaStatus,
20
+ WorkflowSchemaGenerated,
21
+ } from "@blackbelt-technology/pi-dashboard-shared/types.js";
22
+ import semver from "semver";
23
+ import YAML from "yaml";
24
+
25
+ export const CURRENT_PATCH = 2;
26
+ /** First patch whose schema carries the required `dependencies` artifact (see change: add-openspec-change-dependencies). */
27
+ const DEPENDENCIES_PATCH = 2;
28
+ export const WORKFLOW_SCHEMA_NAME = "pi-spec-driven";
29
+ export const STAMP_KEY = "x-pi-dashboard";
30
+ const KEBAB = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
31
+ /** Max in-flight `.openspec.yaml` reads per status computation. */
32
+ const CHANGE_READ_LIMIT = 16;
33
+
34
+ // ── Small helpers ───────────────────────────────────────────────────────────
35
+
36
+ export function errCode(err: unknown): string | undefined {
37
+ return (err as NodeJS.ErrnoException | null)?.code;
38
+ }
39
+
40
+ export function isKebabCaseName(name: unknown): name is string {
41
+ return typeof name === "string" && KEBAB.test(name);
42
+ }
43
+
44
+ export async function lstatOrNull(p: string): Promise<Stats | null> {
45
+ try {
46
+ return await fsp.lstat(p);
47
+ } catch {
48
+ return null;
49
+ }
50
+ }
51
+
52
+ export const schemasDirOf = (root: string): string => path.join(root, "openspec", "schemas");
53
+ export const schemaDirOf = (root: string): string => path.join(schemasDirOf(root), WORKFLOW_SCHEMA_NAME);
54
+ export const changesDirOf = (root: string): string => path.join(root, "openspec", "changes");
55
+
56
+ // ── Fingerprint, stamp, comparison ──────────────────────────────────────────
57
+
58
+ /** sha256 over every file's relative path + content hash (symlinks by target). `null` when `dir` is absent. */
59
+ export async function fingerprintDir(dir: string): Promise<string | null> {
60
+ if (!(await lstatOrNull(dir))) return null;
61
+ const lines: string[] = [];
62
+ const walk = async (d: string): Promise<void> => {
63
+ const entries = (await fsp.readdir(d, { withFileTypes: true })).sort((a, b) => (a.name < b.name ? -1 : 1));
64
+ for (const e of entries) {
65
+ const full = path.join(d, e.name);
66
+ const r = path.relative(dir, full).split(path.sep).join("/");
67
+ if (e.isDirectory()) {
68
+ lines.push(`${r}/`);
69
+ await walk(full);
70
+ } else if (e.isSymbolicLink()) {
71
+ lines.push(`${r}\0L:${await fsp.readlink(full)}`);
72
+ } else {
73
+ lines.push(`${r}\0${crypto.createHash("sha256").update(await fsp.readFile(full)).digest("hex")}`);
74
+ }
75
+ }
76
+ };
77
+ await walk(dir);
78
+ return crypto.createHash("sha256").update(lines.join("\n")).digest("hex");
79
+ }
80
+
81
+ export interface WorkflowSchemaStamp {
82
+ /** Version of the CLI that generated the schema (`spec-driven@<base>`). */
83
+ base: string;
84
+ patch: number;
85
+ /** Syntactically valid previous default, else `null` (treated as absent). */
86
+ previousDefault: string | null;
87
+ }
88
+
89
+ export function parseStamp(yamlText: string): WorkflowSchemaStamp | null {
90
+ let parsed: unknown;
91
+ try {
92
+ parsed = YAML.parse(yamlText);
93
+ } catch {
94
+ return null;
95
+ }
96
+ const raw = (parsed as Record<string, unknown> | null)?.[STAMP_KEY];
97
+ if (!raw || typeof raw !== "object") return null;
98
+ const s = raw as Record<string, unknown>;
99
+ const m = typeof s.derivedFrom === "string" ? /^spec-driven@(.+)$/.exec(s.derivedFrom) : null;
100
+ if (!m || !semver.valid(m[1])) return null;
101
+ if (typeof s.patch !== "number" || !Number.isInteger(s.patch) || s.patch < 0) return null;
102
+ const prev = isKebabCaseName(s.previousDefault) && s.previousDefault !== WORKFLOW_SCHEMA_NAME ? s.previousDefault : null;
103
+ return { base: m[1], patch: s.patch, previousDefault: prev };
104
+ }
105
+
106
+ export type StampComparison = "current" | "outdated" | "newer" | "conflict";
107
+
108
+ /** Component-wise: base by semver, patch numerically. Never lexicographic. */
109
+ export function compareStamp(
110
+ stamp: { base: string; patch: number },
111
+ local: { base: string; patch: number },
112
+ ): StampComparison {
113
+ const base = semver.compare(stamp.base, local.base);
114
+ const patch = Math.sign(stamp.patch - local.patch);
115
+ const newer = base > 0 || patch > 0;
116
+ const older = base < 0 || patch < 0;
117
+ if (newer && older) return "conflict";
118
+ if (newer) return "newer";
119
+ if (older) return "outdated";
120
+ return "current";
121
+ }
122
+
123
+ export interface SchemaInspection {
124
+ generated: WorkflowSchemaGenerated;
125
+ stamp: WorkflowSchemaStamp | null;
126
+ /** Whole-directory fingerprint; `null` when the dir is absent, a symlink, or (`"when-needed"`) not required. */
127
+ fingerprint: string | null;
128
+ symlink: boolean;
129
+ }
130
+
131
+ export interface InspectOptions {
132
+ /** Version of the resolved CLI. */
133
+ localVersion: string;
134
+ /**
135
+ * `"full"` (default): always compute the whole-directory fingerprint; an
136
+ * unreadable one makes the schema `unmanaged` (writing actions rely on it).
137
+ * `"when-needed"`: classify from the stamp alone and fingerprint only for
138
+ * `newer` / `conflict` (the poll hot path).
139
+ */
140
+ fingerprint?: "full" | "when-needed";
141
+ /** Injectable fingerprint function (default `fingerprintDir`); lets tests count calls. */
142
+ fingerprintFn?: (dir: string) => Promise<string | null>;
143
+ }
144
+
145
+ const unmanaged = (fingerprint: string | null = null, symlink = false): SchemaInspection => ({
146
+ generated: "unmanaged",
147
+ stamp: null,
148
+ fingerprint,
149
+ symlink,
150
+ });
151
+
152
+ /** Stamp of a managed schema directory; `null` for a non-directory or an unreadable / unparseable `schema.yaml`. */
153
+ async function readStamp(dir: string, st: Stats): Promise<WorkflowSchemaStamp | null> {
154
+ if (!st.isDirectory()) return null;
155
+ try {
156
+ return parseStamp(await fsp.readFile(path.join(dir, "schema.yaml"), "utf8"));
157
+ } catch {
158
+ return null;
159
+ }
160
+ }
161
+
162
+ /**
163
+ * Filesystem-only status of `<root>/openspec/schemas/pi-spec-driven`, decided
164
+ * from the stamp first. No CLI spawn; the `newer`/`conflict` local
165
+ * `schema validate` is the caller's job (see `fingerprint` in the result).
166
+ */
167
+ export async function inspectSchema(root: string, opts: InspectOptions): Promise<SchemaInspection> {
168
+ const dir = schemaDirOf(root);
169
+ const full = opts.fingerprint !== "when-needed";
170
+ const fingerprintOf = (opts.fingerprintFn ?? fingerprintDir) as (d: string) => Promise<string | null>;
171
+ const st = await lstatOrNull(dir);
172
+ if (!st) return { generated: "none", stamp: null, fingerprint: null, symlink: false };
173
+ if (st.isSymbolicLink()) return unmanaged(null, true);
174
+ const stamp = await readStamp(dir, st);
175
+ if (!stamp) return unmanaged(full && st.isDirectory() ? await fingerprintOf(dir).catch(() => null) : null);
176
+
177
+ let fingerprint: string | null = null;
178
+ if (full) {
179
+ fingerprint = await fingerprintOf(dir).catch(() => null);
180
+ if (!fingerprint) return unmanaged();
181
+ }
182
+ return judgeStamp(dir, stamp, fingerprint, opts, fingerprintOf);
183
+ }
184
+
185
+ /** Compare a parsed stamp with the local CLI; in `"when-needed"` mode fingerprint only for `newer` / `conflict`. */
186
+ async function judgeStamp(
187
+ dir: string,
188
+ stamp: WorkflowSchemaStamp,
189
+ fingerprintIn: string | null,
190
+ opts: InspectOptions,
191
+ fingerprintOf: (d: string) => Promise<string | null>,
192
+ ): Promise<SchemaInspection> {
193
+ const localBase = semver.valid(opts.localVersion);
194
+ if (!localBase) return { generated: "incompatible", stamp, fingerprint: fingerprintIn, symlink: false };
195
+ const generated: WorkflowSchemaGenerated = compareStamp(stamp, { base: localBase, patch: CURRENT_PATCH });
196
+ let fingerprint = fingerprintIn;
197
+ if (opts.fingerprint === "when-needed" && (generated === "newer" || generated === "conflict")) {
198
+ fingerprint = await fingerprintOf(dir).catch(() => null);
199
+ // No fingerprint → no validate can be keyed.
200
+ if (!fingerprint) return unmanaged();
201
+ }
202
+ return { generated, stamp, fingerprint, symlink: false };
203
+ }
204
+
205
+ // ── Config + change enumeration ─────────────────────────────────────────────
206
+
207
+ export interface ConfigFile {
208
+ path: string;
209
+ doc: YAML.Document;
210
+ /** `schema:` value; `null` when the key is absent. */
211
+ configured: string | null;
212
+ }
213
+
214
+ /** `config.yaml` wins over `config.yml`, as the CLI reads. `null` when neither exists; throws on unparseable YAML / non-string `schema`. */
215
+ export async function readConfigFile(root: string): Promise<ConfigFile | null> {
216
+ for (const name of ["config.yaml", "config.yml"]) {
217
+ const p = path.join(root, "openspec", name);
218
+ let text: string;
219
+ try {
220
+ text = await fsp.readFile(p, "utf8");
221
+ } catch (err) {
222
+ if (errCode(err) === "ENOENT") continue;
223
+ throw err;
224
+ }
225
+ const doc = YAML.parseDocument(text);
226
+ if (doc.errors.length > 0) throw new Error(`${name} is not valid YAML: ${doc.errors[0].message}`);
227
+ const v: unknown = doc.get("schema");
228
+ if (v != null && typeof v !== "string") throw new Error(`${name} has a non-string \`schema:\``);
229
+ return { path: p, doc, configured: typeof v === "string" ? v : null };
230
+ }
231
+ return null;
232
+ }
233
+
234
+ /** Active changes as OpenSpec enumerates them: real directories only, no `archive/`, no dot-dirs, no symlinks. Sorted. */
235
+ export async function enumerateActiveChanges(root: string): Promise<string[]> {
236
+ let entries: Dirent[];
237
+ try {
238
+ entries = await fsp.readdir(changesDirOf(root), { withFileTypes: true });
239
+ } catch {
240
+ return [];
241
+ }
242
+ return entries
243
+ .filter((e) => e.isDirectory() && !e.isSymbolicLink() && e.name !== "archive" && !e.name.startsWith("."))
244
+ .map((e) => e.name)
245
+ .sort();
246
+ }
247
+
248
+ /** `schema:` of `<dir>/.openspec.yaml`: `undefined` = no file, `null` = file without a usable `schema:`. */
249
+ export async function readChangeSchema(dir: string): Promise<string | null | undefined> {
250
+ let text: string;
251
+ try {
252
+ text = await fsp.readFile(path.join(dir, ".openspec.yaml"), "utf8");
253
+ } catch {
254
+ return undefined;
255
+ }
256
+ try {
257
+ const v = (YAML.parse(text) as Record<string, unknown> | null)?.schema;
258
+ return typeof v === "string" ? v : null;
259
+ } catch {
260
+ return null;
261
+ }
262
+ }
263
+
264
+ /**
265
+ * Project-authored schema names under `<cwd>/openspec/schemas/`: real
266
+ * directories only (no symlinks), excluding dot-prefixed staging dirs,
267
+ * `*.fork-*` backups and the managed `pi-spec-driven`; sorted.
268
+ */
269
+ async function listProjectSchemas(cwd: string): Promise<string[]> {
270
+ const dir = schemasDirOf(cwd);
271
+ let names: string[];
272
+ try {
273
+ names = await fsp.readdir(dir);
274
+ } catch {
275
+ return [];
276
+ }
277
+ const kept = await Promise.all(
278
+ names.map(async (name) => {
279
+ if (name.startsWith(".") || name.includes(".fork-") || name === WORKFLOW_SCHEMA_NAME) return null;
280
+ const st = await lstatOrNull(path.join(dir, name));
281
+ return st?.isDirectory() ? name : null;
282
+ }),
283
+ );
284
+ return kept.filter((n): n is string => n !== null).sort();
285
+ }
286
+
287
+ /**
288
+ * Members of `affected` (sorted, as given) without a REGULAR `dependencies.yaml`: lstat only, so a symlink
289
+ * or a directory counts as undeclared and nothing is read. Bounded like the `.openspec.yaml` reads.
290
+ * See change: add-openspec-change-dependencies.
291
+ */
292
+ async function listUndeclared(cwd: string, affected: string[]): Promise<string[]> {
293
+ const flags = await mapLimit(affected, CHANGE_READ_LIMIT, async (name) => {
294
+ const st = await lstatOrNull(path.join(changesDirOf(cwd), name, "dependencies.yaml"));
295
+ return !st?.isFile();
296
+ });
297
+ return affected.filter((_, i) => flags[i]);
298
+ }
299
+
300
+ // ── Status assembly ─────────────────────────────────────────────────────────
301
+
302
+ export interface SchemaStatusOptions extends InspectOptions {
303
+ /** `<openspec package>/schemas`; `null` = unknown (the schema is then never reported missing). A function is resolved lazily, only when the config names a schema. */
304
+ packageSchemasDir: string | null | (() => Promise<string | null>);
305
+ /** User-level schemas dir. Required: this module never resolves it itself. */
306
+ userSchemasDirPath: string;
307
+ }
308
+
309
+ /** `OpenSpecData.workflowSchema` plus the fingerprint a `newer`/`conflict` stamp still has to be validated against. */
310
+ export interface SchemaStatusResult {
311
+ status: OpenSpecWorkflowSchemaStatus;
312
+ /** Set only when `status.generated` is `newer` or `conflict`: the main thread runs `schema validate` for it. */
313
+ validateFingerprint?: string;
314
+ }
315
+
316
+ /**
317
+ * Status from files + the stamp. See "Workflow schema status is reported
318
+ * separately from readiness". Runs on the poll hot path, so the independent
319
+ * filesystem reads are issued concurrently and the per-change
320
+ * `.openspec.yaml` reads are bounded.
321
+ */
322
+ export async function computeSchemaStatus(cwd: string, opts: SchemaStatusOptions): Promise<SchemaStatusResult> {
323
+ const configuredP = readConfigFile(cwd).then(
324
+ (c) => c?.configured ?? null,
325
+ () => null,
326
+ );
327
+ const inspectP = inspectSchema(cwd, opts);
328
+ const missingP = configuredP.then(async (configured) => {
329
+ if (configured === null) return false;
330
+ const pkgDir = typeof opts.packageSchemasDir === "function" ? await opts.packageSchemasDir() : opts.packageSchemasDir;
331
+ if (pkgDir === null) return false;
332
+ const dirs = [schemasDirOf(cwd), opts.userSchemasDirPath, pkgDir];
333
+ const found = await Promise.all(dirs.map(async (d) => !!(await lstatOrNull(path.join(d, configured, "schema.yaml")))));
334
+ return !found.some(Boolean);
335
+ });
336
+ const pinsP = enumerateActiveChanges(cwd).then((names) =>
337
+ mapLimit(names, CHANGE_READ_LIMIT, async (name) => ({
338
+ name,
339
+ pinned: await readChangeSchema(path.join(changesDirOf(cwd), name)),
340
+ })),
341
+ );
342
+ const [configured, inspection, missing, pins, projectSchemas] = await Promise.all([
343
+ configuredP,
344
+ inspectP,
345
+ missingP,
346
+ pinsP,
347
+ listProjectSchemas(cwd),
348
+ ]);
349
+
350
+ const unpinnedChanges: string[] = [];
351
+ const affectedChanges: string[] = [];
352
+ for (const { name, pinned } of pins) {
353
+ if (pinned === undefined) {
354
+ if (configured === WORKFLOW_SCHEMA_NAME) {
355
+ unpinnedChanges.push(name);
356
+ affectedChanges.push(name);
357
+ }
358
+ } else if (pinned === WORKFLOW_SCHEMA_NAME) {
359
+ affectedChanges.push(name);
360
+ }
361
+ }
362
+ const undeclaredChanges = await listUndeclared(cwd, affectedChanges);
363
+ const status: OpenSpecWorkflowSchemaStatus = {
364
+ configured,
365
+ generated: inspection.generated,
366
+ missing,
367
+ unpinnedChanges,
368
+ affectedChanges,
369
+ undeclaredChanges,
370
+ // An update only "adds a required dependencies declaration" when the installed stamp predates it; an
371
+ // outdated stamp already at the dependencies patch is outdated for the CLI base alone.
372
+ raisesToDependencies: inspection.generated === "outdated" && (inspection.stamp?.patch ?? 0) < DEPENDENCIES_PATCH,
373
+ projectSchemas,
374
+ };
375
+ const needsValidate = inspection.generated === "newer" || inspection.generated === "conflict";
376
+ return needsValidate && inspection.fingerprint
377
+ ? { status, validateFingerprint: inspection.fingerprint }
378
+ : { status };
379
+ }