@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
@@ -0,0 +1,760 @@
1
+ /**
2
+ * OpenSpec change-to-change dependencies: per-change `dependencies.yaml`
3
+ * parser + safe reader, proposal / spec-delta scanners, and the pure graph
4
+ * computation (merge, resolution, validation, waves).
5
+ *
6
+ * The graph is deterministic: identical repository content yields byte-identical
7
+ * output regardless of line endings, directory order or host OS. Nothing here
8
+ * writes to disk; the only I/O is `readDependenciesFile` (bounded, symlink-safe).
9
+ *
10
+ * See change: add-openspec-change-dependencies.
11
+ */
12
+
13
+ import { constants as fsConstants } from "node:fs";
14
+ import * as fsp from "node:fs/promises";
15
+ import { parse as parseYaml, stringify as stringifyYaml } from "yaml";
16
+ import type {
17
+ ChangeDependencies,
18
+ DependencyEdge,
19
+ DependencyEdgeSource,
20
+ DependencyIssue,
21
+ } from "./types.js";
22
+
23
+ /** OpenSpec's change-id grammar (not the dashboard's stricter slug rule). */
24
+ export const KEBAB_ID_REGEX = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
25
+ export const DEPENDENCIES_FILE = "dependencies.yaml";
26
+ /** Hard read cap; the reader reads at most `MAX_DEPENDENCIES_BYTES + 1`. */
27
+ export const MAX_DEPENDENCIES_BYTES = 64 * 1024;
28
+ export const MAX_REASON_CHARS = 500;
29
+ const MAX_INFERRED_REASON_CHARS = 200;
30
+
31
+ // ── Declared file ───────────────────────────────────────────────────
32
+
33
+ export interface DeclaredBlocker {
34
+ change: string;
35
+ reason?: string;
36
+ }
37
+
38
+ /** The file's own lists (what the editor edits; reasons preserved). */
39
+ export interface DeclaredDependencies {
40
+ blockedBy: DeclaredBlocker[];
41
+ notBlockedBy: string[];
42
+ related: string[];
43
+ }
44
+
45
+ export type ParseResult = { ok: true; value: DeclaredDependencies } | { ok: false; error: string };
46
+
47
+ const EMPTY_DECLARED = (): DeclaredDependencies => ({ blockedBy: [], notBlockedBy: [], related: [] });
48
+ const ALLOWED_KEYS = new Set(["blocked_by", "not_blocked_by", "related"]);
49
+
50
+ function fail(error: string): ParseResult {
51
+ return { ok: false, error };
52
+ }
53
+
54
+ function isEmptyValue(v: unknown): boolean {
55
+ return v === null || v === undefined || v === "";
56
+ }
57
+
58
+ function nameList(key: string, v: unknown): { names: string[] } | { error: string } {
59
+ if (isEmptyValue(v)) return { names: [] };
60
+ if (!Array.isArray(v)) return { error: `\`${key}\` must be a list` };
61
+ const names: string[] = [];
62
+ for (const item of v) {
63
+ if (typeof item !== "string" || !KEBAB_ID_REGEX.test(item)) {
64
+ return { error: `\`${key}\` has an invalid change name: ${JSON.stringify(item)}` };
65
+ }
66
+ if (!names.includes(item)) names.push(item);
67
+ }
68
+ return { names };
69
+ }
70
+
71
+ /**
72
+ * Parse the text of a `dependencies.yaml`. `failsafe` schema (every scalar is
73
+ * a string, so `123` stays a name), aliases rejected. Never throws.
74
+ */
75
+ export function parseDependenciesFile(text: string): ParseResult {
76
+ let doc: unknown;
77
+ try {
78
+ doc = parseYaml(text, { schema: "failsafe", maxAliasCount: 0 });
79
+ } catch (err) {
80
+ const msg = err instanceof Error ? err.message.split("\n")[0] : String(err);
81
+ return fail(`unparseable YAML: ${msg}`);
82
+ }
83
+ if (isEmptyValue(doc)) return { ok: true, value: EMPTY_DECLARED() };
84
+ if (typeof doc !== "object" || Array.isArray(doc)) return fail("top level must be a mapping");
85
+ const obj = doc as Record<string, unknown>;
86
+ for (const key of Object.keys(obj)) {
87
+ if (!ALLOWED_KEYS.has(key)) return fail(`unknown top-level key \`${key}\``);
88
+ }
89
+ const value = EMPTY_DECLARED();
90
+
91
+ const rawBlocked = obj.blocked_by;
92
+ if (!isEmptyValue(rawBlocked)) {
93
+ if (!Array.isArray(rawBlocked)) return fail("`blocked_by` must be a list");
94
+ for (const item of rawBlocked) {
95
+ let change: unknown;
96
+ let reason: unknown;
97
+ if (typeof item === "string") {
98
+ change = item;
99
+ } else if (item && typeof item === "object" && !Array.isArray(item)) {
100
+ const rec = item as Record<string, unknown>;
101
+ for (const k of Object.keys(rec)) {
102
+ if (k !== "change" && k !== "reason") return fail(`\`blocked_by\` entry has unknown key \`${k}\``);
103
+ }
104
+ change = rec.change;
105
+ reason = rec.reason;
106
+ } else {
107
+ return fail("`blocked_by` entries must be a name or { change, reason? }");
108
+ }
109
+ if (typeof change !== "string" || !KEBAB_ID_REGEX.test(change)) {
110
+ return fail(`\`blocked_by\` has an invalid change name: ${JSON.stringify(change)}`);
111
+ }
112
+ if (reason !== undefined && reason !== null) {
113
+ if (typeof reason !== "string") return fail("`reason` must be a string");
114
+ if (reason.length > MAX_REASON_CHARS) return fail(`\`reason\` exceeds ${MAX_REASON_CHARS} characters`);
115
+ }
116
+ if (value.blockedBy.some((b) => b.change === change)) continue;
117
+ value.blockedBy.push(typeof reason === "string" && reason !== "" ? { change, reason } : { change });
118
+ }
119
+ }
120
+ for (const [key, target] of [
121
+ ["not_blocked_by", "notBlockedBy"],
122
+ ["related", "related"],
123
+ ] as const) {
124
+ const r = nameList(key, obj[key]);
125
+ if ("error" in r) return fail(r.error);
126
+ value[target] = r.names;
127
+ }
128
+ return { ok: true, value };
129
+ }
130
+
131
+ /** Serialize declared lists through the YAML serializer (never string concatenation). */
132
+ export function serializeDependencies(d: DeclaredDependencies): string {
133
+ return stringifyYaml({
134
+ blocked_by: d.blockedBy.map((b) => (b.reason ? { change: b.change, reason: b.reason } : { change: b.change })),
135
+ not_blocked_by: d.notBlockedBy,
136
+ related: d.related,
137
+ });
138
+ }
139
+
140
+ export interface FileStat {
141
+ mtimeMs: number;
142
+ size: number;
143
+ }
144
+
145
+ export type ReadResult =
146
+ | { kind: "absent" }
147
+ | { kind: "invalid"; error: string; stat?: FileStat }
148
+ | { kind: "ok"; value: DeclaredDependencies; stat: FileStat };
149
+
150
+ type ReaderFs = Pick<typeof fsp, "lstat" | "open">;
151
+
152
+ /**
153
+ * Read + parse a `dependencies.yaml` under the read rules: only a regular,
154
+ * non-symlink file is opened; at most 64 KiB + 1 byte is read. A symlink, a
155
+ * non-regular file (FIFO, device) or an oversize file is `invalid` and is
156
+ * never read through. `fsImpl` is a test seam.
157
+ */
158
+ export async function readDependenciesFile(file: string, fsImpl: ReaderFs = fsp): Promise<ReadResult> {
159
+ let st: Awaited<ReturnType<ReaderFs["lstat"]>>;
160
+ try {
161
+ st = await fsImpl.lstat(file);
162
+ } catch (err) {
163
+ const code = (err as NodeJS.ErrnoException).code;
164
+ if (code === "ENOENT" || code === "ENOTDIR") return { kind: "absent" };
165
+ return { kind: "invalid", error: `unreadable: ${code ?? "error"}` };
166
+ }
167
+ const stat: FileStat = { mtimeMs: st.mtimeMs, size: st.size };
168
+ if (st.isSymbolicLink()) return { kind: "invalid", error: "is a symlink", stat };
169
+ if (!st.isFile()) return { kind: "invalid", error: "is not a regular file", stat };
170
+ if (st.size > MAX_DEPENDENCIES_BYTES) {
171
+ return { kind: "invalid", error: `exceeds ${MAX_DEPENDENCIES_BYTES} bytes`, stat };
172
+ }
173
+ let text: string;
174
+ let openedStat: FileStat = stat;
175
+ try {
176
+ const noFollow = typeof fsConstants.O_NOFOLLOW === "number" ? fsConstants.O_NOFOLLOW : 0;
177
+ // O_NONBLOCK: a FIFO swapped in after the lstat must not park a threadpool thread until a writer
178
+ // appears; the fstat re-check below then rejects it. No effect on regular files.
179
+ const nonBlock = typeof fsConstants.O_NONBLOCK === "number" ? fsConstants.O_NONBLOCK : 0;
180
+ const handle = await fsImpl.open(file, fsConstants.O_RDONLY | noFollow | nonBlock);
181
+ try {
182
+ const hs = await handle.stat();
183
+ if (!hs.isFile()) return { kind: "invalid", error: "is not a regular file", stat };
184
+ openedStat = { mtimeMs: hs.mtimeMs, size: hs.size };
185
+ const buf = Buffer.alloc(MAX_DEPENDENCIES_BYTES + 1);
186
+ const { bytesRead } = await handle.read(buf, 0, buf.length, 0);
187
+ if (bytesRead > MAX_DEPENDENCIES_BYTES) {
188
+ return { kind: "invalid", error: `exceeds ${MAX_DEPENDENCIES_BYTES} bytes`, stat: openedStat };
189
+ }
190
+ text = buf.subarray(0, bytesRead).toString("utf8");
191
+ } finally {
192
+ await handle.close();
193
+ }
194
+ } catch (err) {
195
+ const code = (err as NodeJS.ErrnoException).code;
196
+ return { kind: "invalid", error: `unreadable: ${code ?? "error"}`, stat };
197
+ }
198
+ const parsed = parseDependenciesFile(text);
199
+ if (!parsed.ok) return { kind: "invalid", error: parsed.error, stat: openedStat };
200
+ return { kind: "ok", value: parsed.value, stat: openedStat };
201
+ }
202
+
203
+ // ── Proposal and delta scanners (per-file, cacheable) ───────────────
204
+
205
+ export interface LabelledToken {
206
+ token: string;
207
+ /** The label line: `\r` removed, whitespace collapsed, ≤ 200 chars. */
208
+ line: string;
209
+ }
210
+
211
+ /** Per-file scan of a `proposal.md`: independent of any other file. */
212
+ export interface ProposalScan {
213
+ /** Tokens under `Blocked by` / `Depends on` / `Builds on`. */
214
+ blockedBy: LabelledToken[];
215
+ /** Tokens under `Blocks`. */
216
+ blocks: LabelledToken[];
217
+ /** Backticked change-id-shaped tokens outside labelled regions and fences. */
218
+ mentions: string[];
219
+ }
220
+
221
+ export interface DeltaScan {
222
+ /** Has `## ADDED Requirements`. */
223
+ added: boolean;
224
+ /** Has `## MODIFIED|REMOVED|RENAMED Requirements`. */
225
+ modifies: boolean;
226
+ /** Has at least one of the four headers. */
227
+ anyHeader: boolean;
228
+ }
229
+
230
+ /** Collapse whitespace runs, drop `\r`, truncate. */
231
+ export function normalizeText(s: string, max: number): string {
232
+ const t = s.replace(/\r/g, "").replace(/\s+/g, " ").trim();
233
+ return t.length > max ? t.slice(0, max).trimEnd() : t;
234
+ }
235
+
236
+ const FENCE_RE = /^\s{0,3}(`{3,}|~{3,})/;
237
+ const LIST_MARKER_RE = /^\s*(?:[-*+]\s+|\d+[.)]\s+)/;
238
+ const HEADING_RE = /^\s{0,3}#{1,6}\s/;
239
+ const BOLD = String.raw`(?:\*\*|__)`;
240
+ /**
241
+ * Label grammar: optional list marker, optional bold, label, optional
242
+ * parenthetical, then `:` (inside or outside the bold) or a backticked token.
243
+ * `Blocks on:` is not a label — nothing after `Blocks` may be a word.
244
+ */
245
+ const LABEL_RE = new RegExp(
246
+ String.raw`^\s*(?:[-*+]\s+|\d+[.)]\s+)?${BOLD}?(blocked by|depends on|builds on|blocks)(?:[ \t]*\([^)\n]*\))?` +
247
+ String.raw`(?:[ \t]*:${BOLD}?|[ \t]*${BOLD}[ \t]*:?|(?=[ \t]+\`))`,
248
+ "i",
249
+ );
250
+
251
+ function indentOf(line: string): number {
252
+ return line.length - line.trimStart().length;
253
+ }
254
+
255
+ function backtickTokens(s: string): string[] {
256
+ const out: string[] = [];
257
+ for (const m of s.matchAll(/`([^`\n]+)`/g)) {
258
+ const t = m[1].trim();
259
+ if (KEBAB_ID_REGEX.test(t)) out.push(t);
260
+ }
261
+ return out;
262
+ }
263
+
264
+ function lineClosesFence(line: string, fence: string): boolean {
265
+ const m = FENCE_RE.exec(line);
266
+ return !!m && m[1][0] === fence[0] && m[1].length >= fence.length;
267
+ }
268
+
269
+ /** Scan a proposal for labelled dependency lines and prose mentions. */
270
+ export function scanProposal(text: string): ProposalScan {
271
+ const lines = text.split("\n").map((l) => l.replace(/\r$/, ""));
272
+ const labelled = new Map<number, true>();
273
+ const blockedBy: LabelledToken[] = [];
274
+ const blocks: LabelledToken[] = [];
275
+ const seen = { b: new Set<string>(), k: new Set<string>() };
276
+
277
+ let fence: string | null = null;
278
+ const inFence: boolean[] = lines.map((l) => {
279
+ if (fence) {
280
+ const closes = lineClosesFence(l, fence);
281
+ if (closes) fence = null;
282
+ return true;
283
+ }
284
+ const m = FENCE_RE.exec(l);
285
+ if (m) {
286
+ fence = m[1];
287
+ return true;
288
+ }
289
+ return false;
290
+ });
291
+
292
+ for (let i = 0; i < lines.length; i++) {
293
+ if (inFence[i] || labelled.has(i)) continue;
294
+ const m = LABEL_RE.exec(lines[i]);
295
+ if (!m) continue;
296
+ const kind = m[1].toLowerCase() === "blocks" ? "blocks" : "blockedBy";
297
+ const indent = indentOf(lines[i]);
298
+ const tokens = backtickTokens(lines[i].slice(m[0].length));
299
+ labelled.set(i, true);
300
+ for (let j = i + 1; j < lines.length; j++) {
301
+ const l = lines[j];
302
+ if (inFence[j] || l.trim() === "" || HEADING_RE.test(l)) break;
303
+ if (indentOf(l) <= indent && (LIST_MARKER_RE.test(l) || LABEL_RE.test(l))) break;
304
+ labelled.set(j, true);
305
+ tokens.push(...backtickTokens(l));
306
+ }
307
+ const line = normalizeText(lines[i], MAX_INFERRED_REASON_CHARS);
308
+ const target = kind === "blocks" ? blocks : blockedBy;
309
+ const seenSet = kind === "blocks" ? seen.k : seen.b;
310
+ for (const token of tokens) {
311
+ if (seenSet.has(token)) continue;
312
+ seenSet.add(token);
313
+ target.push({ token, line });
314
+ }
315
+ }
316
+
317
+ const mentions = new Set<string>();
318
+ for (let i = 0; i < lines.length; i++) {
319
+ if (inFence[i] || labelled.has(i)) continue;
320
+ for (const t of backtickTokens(lines[i])) mentions.add(t);
321
+ }
322
+ return { blockedBy, blocks, mentions: [...mentions].sort() };
323
+ }
324
+
325
+ const DELTA_HEADER_RE = /^##\s+(ADDED|MODIFIED|REMOVED|RENAMED)\s+Requirements\s*$/i;
326
+
327
+ /** Scan a delta `spec.md` for requirement section headers (outside fences). */
328
+ export function scanDelta(text: string): DeltaScan {
329
+ let added = false;
330
+ let modifies = false;
331
+ let fence: string | null = null;
332
+ for (const raw of text.split("\n")) {
333
+ const line = raw.replace(/\r$/, "");
334
+ if (fence) {
335
+ if (lineClosesFence(line, fence)) fence = null;
336
+ continue;
337
+ }
338
+ const f = FENCE_RE.exec(line);
339
+ if (f) {
340
+ fence = f[1];
341
+ continue;
342
+ }
343
+ const m = DELTA_HEADER_RE.exec(line);
344
+ if (!m) continue;
345
+ if (m[1].toUpperCase() === "ADDED") added = true;
346
+ else modifies = true;
347
+ }
348
+ return { added, modifies, anyHeader: added || modifies };
349
+ }
350
+
351
+ const ARCHIVE_DIR_RE = /^\d{4}-\d{2}-\d{2}-(.+)$/;
352
+
353
+ /** `archive/<YYYY-MM-DD>-<name>` directory name → `<name>`; `null` when it does not match. */
354
+ export function archivedChangeName(dirName: string): string | null {
355
+ const m = ARCHIVE_DIR_RE.exec(dirName);
356
+ return m ? m[1] : null;
357
+ }
358
+
359
+ // ── Graph ───────────────────────────────────────────────────────────
360
+
361
+ export type DeclaredState =
362
+ | { state: "absent" }
363
+ | { state: "invalid"; error: string }
364
+ | { state: "ok"; value: DeclaredDependencies };
365
+
366
+ /** Everything the graph needs to know about one active change. */
367
+ export interface ChangeInputs {
368
+ name: string;
369
+ declared: DeclaredState;
370
+ proposal: ProposalScan | null;
371
+ /** Capability id (spec path relative to `specs/`) → delta scan. */
372
+ deltas: Record<string, DeltaScan>;
373
+ }
374
+
375
+ export interface GraphInputs {
376
+ changes: ChangeInputs[];
377
+ /** Names of archived changes (exact `<date>-<name>` directories, name part only). */
378
+ archived: string[];
379
+ /** Capability ids that have a main spec `openspec/specs/<cap>/spec.md`. */
380
+ mainSpecs: string[];
381
+ }
382
+
383
+ const PRIORITY: Record<DependencyEdgeSource, number> = {
384
+ declared: 3,
385
+ "inferred-text": 2,
386
+ "inferred-capability": 1,
387
+ };
388
+
389
+ interface Candidate {
390
+ blocked: string;
391
+ blocker: string;
392
+ source: DependencyEdgeSource;
393
+ reason?: string;
394
+ satisfied: boolean;
395
+ }
396
+
397
+ const cmp = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);
398
+
399
+ function sortIssues(issues: DependencyIssue[]): DependencyIssue[] {
400
+ return issues.sort((x, y) => cmp(x.code, y.code) || cmp(x.message, y.message));
401
+ }
402
+
403
+ type Adj = Map<string, string[]>;
404
+
405
+ /** Tarjan SCC over `adj` (node → successors); returns only non-trivial components. */
406
+ function nonTrivialSccs(nodes: string[], adj: Adj): string[][] {
407
+ let index = 0;
408
+ const idx = new Map<string, number>();
409
+ const low = new Map<string, number>();
410
+ const onStack = new Set<string>();
411
+ const stack: string[] = [];
412
+ const out: string[][] = [];
413
+ const popComponent = (root: string): string[] => {
414
+ const comp: string[] = [];
415
+ let w: string;
416
+ do {
417
+ w = stack.pop() as string;
418
+ onStack.delete(w);
419
+ comp.push(w);
420
+ } while (w !== root);
421
+ return comp;
422
+ };
423
+ const visit = (v: string): void => {
424
+ idx.set(v, index);
425
+ low.set(v, index);
426
+ index++;
427
+ stack.push(v);
428
+ onStack.add(v);
429
+ for (const w of adj.get(v) ?? []) {
430
+ if (!idx.has(w)) {
431
+ visit(w);
432
+ low.set(v, Math.min(low.get(v) as number, low.get(w) as number));
433
+ } else if (onStack.has(w)) {
434
+ low.set(v, Math.min(low.get(v) as number, idx.get(w) as number));
435
+ }
436
+ }
437
+ if (low.get(v) !== idx.get(v)) return;
438
+ const comp = popComponent(v);
439
+ if (comp.length > 1) out.push(comp.sort(cmp));
440
+ };
441
+ for (const n of nodes) if (!idx.has(n)) visit(n);
442
+ return out;
443
+ }
444
+
445
+ const push = <K, V>(m: Map<K, V[]>, k: K, v: V): void => {
446
+ const list = m.get(k);
447
+ if (list) list.push(v);
448
+ else m.set(k, [v]);
449
+ };
450
+
451
+ /** Reverse adjacency (successor → predecessors) restricted to `members`. */
452
+ function reverseWithin(members: Set<string>, adj: Adj): Adj {
453
+ const rev: Adj = new Map();
454
+ for (const v of members) for (const w of adj.get(v) ?? []) if (members.has(w)) push(rev, w, v);
455
+ return rev;
456
+ }
457
+
458
+ /** BFS distance of every node to `target` along `adj` edges (`target` = 0). */
459
+ function distancesTo(target: string, rev: Adj): Map<string, number> {
460
+ const dist = new Map<string, number>([[target, 0]]);
461
+ const queue = [target];
462
+ for (let q = 0; q < queue.length; q++) {
463
+ const here = dist.get(queue[q]) as number;
464
+ for (const p of rev.get(queue[q]) ?? []) {
465
+ if (dist.has(p)) continue;
466
+ dist.set(p, here + 1);
467
+ queue.push(p);
468
+ }
469
+ }
470
+ return dist;
471
+ }
472
+
473
+ /** Shortest cycle through the SCC's smallest member; lexicographically smallest on ties. */
474
+ function canonicalCycle(members: string[], adj: Adj): string[] {
475
+ const set = new Set(members);
476
+ const start = members[0];
477
+ const dist = distancesTo(start, reverseWithin(set, adj));
478
+ const successors = (v: string) => (adj.get(v) ?? []).filter((w) => set.has(w) && dist.has(w));
479
+ // cycle length: shortest way back to `start` through one of its successors
480
+ let remaining = Math.min(...successors(start).map((w) => (dist.get(w) as number) + 1));
481
+ if (!Number.isFinite(remaining)) return [start]; // not a cycle (callers pass whole SCCs; never loop regardless)
482
+ const path = [start];
483
+ let cur = start;
484
+ while (remaining > 0) {
485
+ cur = successors(cur)
486
+ .filter((w) => dist.get(w) === remaining - 1)
487
+ .sort(cmp)[0];
488
+ path.push(cur);
489
+ remaining--;
490
+ }
491
+ return path;
492
+ }
493
+
494
+ // ── graph stages ────────────────────────────────────────────────────
495
+
496
+ /** Mutable state shared by the stages of one `computeDependencyGraph` call. */
497
+ interface GraphCtx {
498
+ inputs: ChangeInputs[];
499
+ names: string[];
500
+ active: Set<string>;
501
+ archived: Set<string>;
502
+ mainSpecs: Set<string>;
503
+ issues: Map<string, DependencyIssue[]>;
504
+ related: Map<string, Set<string>>;
505
+ notBlocked: Map<string, Set<string>>;
506
+ candidates: Candidate[];
507
+ }
508
+
509
+ const addIssue = (ctx: GraphCtx, name: string, issue: DependencyIssue): void => {
510
+ (ctx.issues.get(name) as DependencyIssue[]).push(issue);
511
+ };
512
+
513
+ const resolveName = (ctx: GraphCtx, n: string): "active" | "archived" | "unknown" =>
514
+ ctx.active.has(n) ? "active" : ctx.archived.has(n) ? "archived" : "unknown";
515
+
516
+ /** Declared file: invalid → error; else `related`, `not_blocked_by` and one candidate per `blocked_by` entry. */
517
+ function collectDeclared(ctx: GraphCtx, c: ChangeInputs): void {
518
+ const x = c.name;
519
+ if (c.declared.state === "invalid") {
520
+ addIssue(ctx, x, { severity: "error", code: "invalid-file", message: c.declared.error });
521
+ return;
522
+ }
523
+ if (c.declared.state !== "ok") return;
524
+ const d = c.declared.value;
525
+ const nbb = new Set(d.notBlockedBy);
526
+ ctx.notBlocked.set(x, nbb);
527
+ for (const r of d.related) if (r !== x && ctx.active.has(r)) (ctx.related.get(x) as Set<string>).add(r);
528
+ for (const b of d.blockedBy) {
529
+ if (b.change === x) {
530
+ addIssue(ctx, x, { severity: "error", code: "self-reference", message: "change lists itself in blocked_by" });
531
+ continue;
532
+ }
533
+ if (nbb.has(b.change)) {
534
+ addIssue(ctx, x, {
535
+ severity: "warning",
536
+ code: "conflicting-entry",
537
+ message: `\`${b.change}\` is in both blocked_by and not_blocked_by; not_blocked_by wins`,
538
+ with: [b.change],
539
+ });
540
+ continue;
541
+ }
542
+ const res = resolveName(ctx, b.change);
543
+ if (res === "unknown") {
544
+ addIssue(ctx, x, {
545
+ severity: "warning",
546
+ code: "unknown-change",
547
+ message: `blocked_by names unknown change \`${b.change}\``,
548
+ with: [b.change],
549
+ });
550
+ continue;
551
+ }
552
+ ctx.candidates.push({
553
+ blocked: x,
554
+ blocker: b.change,
555
+ source: "declared",
556
+ ...(b.reason ? { reason: normalizeText(b.reason, MAX_REASON_CHARS) } : {}),
557
+ satisfied: res === "archived",
558
+ });
559
+ }
560
+ }
561
+
562
+ /** L1: labelled proposal lines → candidates; prose mentions → `related`. */
563
+ function collectProposalEdges(ctx: GraphCtx, c: ChangeInputs): void {
564
+ if (!c.proposal) return;
565
+ const x = c.name;
566
+ for (const t of c.proposal.blockedBy) {
567
+ const res = t.token === x ? "unknown" : resolveName(ctx, t.token);
568
+ if (res === "unknown") continue;
569
+ ctx.candidates.push({ blocked: x, blocker: t.token, source: "inferred-text", reason: t.line, satisfied: res === "archived" });
570
+ }
571
+ for (const t of c.proposal.blocks) {
572
+ if (t.token === x || !ctx.active.has(t.token)) continue;
573
+ ctx.candidates.push({ blocked: t.token, blocker: x, source: "inferred-text", reason: t.line, satisfied: false });
574
+ }
575
+ for (const m of c.proposal.mentions) if (m !== x && ctx.active.has(m)) (ctx.related.get(x) as Set<string>).add(m);
576
+ }
577
+
578
+ /** L2 for one capability: a sole birther blocks every other change with a delta header; several birthers warn. */
579
+ function collectCapabilityBirth(ctx: GraphCtx, cap: string, touching: ChangeInputs[]): void {
580
+ const birthers = touching.filter((c) => c.deltas[cap].added && !c.deltas[cap].modifies);
581
+ if (birthers.length >= 2) {
582
+ for (const b of birthers) {
583
+ const others = birthers.filter((o) => o !== b).map((o) => o.name);
584
+ addIssue(ctx, b.name, {
585
+ severity: "warning",
586
+ code: "duplicate-capability",
587
+ message: `capability \`${cap}\` is also added by ${others.map((o) => `\`${o}\``).join(", ")}; declare the order`,
588
+ with: others,
589
+ });
590
+ }
591
+ return;
592
+ }
593
+ if (birthers.length !== 1) return;
594
+ const birth = birthers[0];
595
+ for (const c of touching) {
596
+ if (c === birth || !c.deltas[cap].anyHeader) continue;
597
+ ctx.candidates.push({ blocked: c.name, blocker: birth.name, source: "inferred-capability", reason: cap, satisfied: false });
598
+ }
599
+ }
600
+
601
+ /** L2 + L3 over every capability touched by a delta; returns the undirected `overlaps`. */
602
+ function collectCapabilityEdges(ctx: GraphCtx): Map<string, Set<string>> {
603
+ const byCap = new Map<string, ChangeInputs[]>();
604
+ for (const c of ctx.inputs) for (const cap of Object.keys(c.deltas)) push(byCap, cap, c);
605
+ const overlaps = new Map<string, Set<string>>(ctx.names.map((n) => [n, new Set()]));
606
+ for (const cap of [...byCap.keys()].sort(cmp)) {
607
+ const touching = byCap.get(cap) as ChangeInputs[];
608
+ for (const a of touching) for (const b of touching) if (a !== b) (overlaps.get(a.name) as Set<string>).add(b.name);
609
+ if (!ctx.mainSpecs.has(cap)) collectCapabilityBirth(ctx, cap, touching);
610
+ }
611
+ return overlaps;
612
+ }
613
+
614
+ /** One edge per ordered (blocked, blocker) pair: highest priority wins; `not_blocked_by` suppresses. */
615
+ function mergeEdges(ctx: GraphCtx): Map<string, Map<string, Candidate>> {
616
+ const edges = new Map<string, Map<string, Candidate>>(ctx.names.map((n) => [n, new Map()]));
617
+ for (const cand of ctx.candidates) {
618
+ if (ctx.notBlocked.get(cand.blocked)?.has(cand.blocker)) continue;
619
+ const row = edges.get(cand.blocked);
620
+ if (!row) continue;
621
+ const cur = row.get(cand.blocker);
622
+ if (!cur || PRIORITY[cand.source] > PRIORITY[cur.source]) row.set(cand.blocker, cand);
623
+ }
624
+ return edges;
625
+ }
626
+
627
+ /** Open edges among active changes (node → blockers), all sources and declared-only. */
628
+ function openAdjacency(ctx: GraphCtx, edges: Map<string, Map<string, Candidate>>): { open: Adj; declared: Adj } {
629
+ const open: Adj = new Map();
630
+ const declared: Adj = new Map();
631
+ for (const n of ctx.names) {
632
+ const o: string[] = [];
633
+ const d: string[] = [];
634
+ for (const [blocker, e] of [...(edges.get(n) as Map<string, Candidate>)].sort((a, b) => cmp(a[0], b[0]))) {
635
+ if (e.satisfied || !ctx.active.has(blocker)) continue;
636
+ o.push(blocker);
637
+ if (e.source === "declared") d.push(blocker);
638
+ }
639
+ open.set(n, o);
640
+ declared.set(n, d);
641
+ }
642
+ return { open, declared };
643
+ }
644
+
645
+ /** Cycles: declared-only SCCs are errors, remaining members of full-graph SCCs are warnings. */
646
+ function reportCycles(ctx: GraphCtx, adj: { open: Adj; declared: Adj }): Set<string> {
647
+ const members = new Set<string>();
648
+ // The path is always taken over the WHOLE strongly connected `comp`; `targets` are the members that
649
+ // receive the issue (a subset for warnings, since declared-cycle members already carry an error).
650
+ const report = (comp: string[], graph: Adj, severity: "error" | "warning", targets: string[] = comp) => {
651
+ const path = canonicalCycle(comp, graph);
652
+ for (const m of targets) {
653
+ members.add(m);
654
+ addIssue(ctx, m, { severity, code: "cycle", message: `dependency cycle: ${path.join(" → ")}`, path });
655
+ }
656
+ };
657
+ const errorMembers = new Set<string>();
658
+ for (const comp of nonTrivialSccs(ctx.names, adj.declared)) {
659
+ report(comp, adj.declared, "error");
660
+ for (const m of comp) errorMembers.add(m);
661
+ }
662
+ for (const comp of nonTrivialSccs(ctx.names, adj.open)) {
663
+ const rest = comp.filter((m) => !errorMembers.has(m));
664
+ if (rest.length > 0) report(comp, adj.open, "warning", rest);
665
+ }
666
+ return members;
667
+ }
668
+
669
+ /** Changes with an open path to a cycle member (the members themselves excluded). */
670
+ function downstreamOfCycles(cycleMembers: Set<string>, rev: Adj): Set<string> {
671
+ const seen = new Set<string>(cycleMembers);
672
+ const downstream = new Set<string>();
673
+ const stack = [...cycleMembers];
674
+ while (stack.length > 0) {
675
+ for (const dep of rev.get(stack.pop() as string) ?? []) {
676
+ if (seen.has(dep)) continue;
677
+ seen.add(dep);
678
+ downstream.add(dep);
679
+ stack.push(dep);
680
+ }
681
+ }
682
+ return downstream;
683
+ }
684
+
685
+ /** Kahn layering over `eligible` nodes; wave 1 has no open blockers. */
686
+ function assignWaves(eligible: string[], openAdj: Adj, rev: Adj): Map<string, number> {
687
+ const wave = new Map<string, number>();
688
+ const indeg = new Map<string, number>(eligible.map((n) => [n, (openAdj.get(n) ?? []).length]));
689
+ let layer = eligible.filter((n) => indeg.get(n) === 0);
690
+ for (let w = 1; layer.length > 0; w++) {
691
+ const next: string[] = [];
692
+ for (const n of layer) {
693
+ wave.set(n, w);
694
+ for (const dep of rev.get(n) ?? []) {
695
+ if (!indeg.has(dep)) continue;
696
+ const left = (indeg.get(dep) as number) - 1;
697
+ indeg.set(dep, left);
698
+ if (left === 0) next.push(dep);
699
+ }
700
+ }
701
+ layer = next.sort(cmp);
702
+ }
703
+ return wave;
704
+ }
705
+
706
+ export function computeDependencyGraph(input: GraphInputs): Record<string, ChangeDependencies> {
707
+ const inputs = [...input.changes].sort((a, b) => cmp(a.name, b.name));
708
+ const names = inputs.map((c) => c.name);
709
+ const ctx: GraphCtx = {
710
+ inputs,
711
+ names,
712
+ active: new Set(names),
713
+ archived: new Set(input.archived),
714
+ mainSpecs: new Set(input.mainSpecs),
715
+ issues: new Map(names.map((n) => [n, []])),
716
+ related: new Map(names.map((n) => [n, new Set<string>()])),
717
+ notBlocked: new Map(names.map((n) => [n, new Set<string>()])),
718
+ candidates: [],
719
+ };
720
+
721
+ for (const c of inputs) {
722
+ collectDeclared(ctx, c);
723
+ collectProposalEdges(ctx, c);
724
+ }
725
+ const overlaps = collectCapabilityEdges(ctx);
726
+ const edges = mergeEdges(ctx);
727
+ const adj = openAdjacency(ctx, edges);
728
+
729
+ const cycleMembers = reportCycles(ctx, adj);
730
+ const rev: Adj = new Map();
731
+ for (const [n, blockers] of adj.open) for (const b of blockers) push(rev, b, n);
732
+ const downstream = downstreamOfCycles(cycleMembers, rev);
733
+ for (const n of [...downstream].sort(cmp)) {
734
+ addIssue(ctx, n, { severity: "warning", code: "blocked-by-cycle", message: "blocked by a change that is part of a dependency cycle" });
735
+ }
736
+ const wave = assignWaves(names.filter((n) => !cycleMembers.has(n) && !downstream.has(n)), adj.open, rev);
737
+
738
+ const out: Record<string, ChangeDependencies> = {};
739
+ for (const c of inputs) {
740
+ const n = c.name;
741
+ const blockedBy: DependencyEdge[] = [...(edges.get(n) as Map<string, Candidate>)]
742
+ .sort((a, b) => cmp(a[0], b[0]))
743
+ .map(([blocker, e]) => ({
744
+ change: blocker,
745
+ source: e.source,
746
+ ...(e.reason !== undefined ? { reason: e.reason } : {}),
747
+ state: e.satisfied ? ("satisfied" as const) : ("open" as const),
748
+ }));
749
+ out[n] = {
750
+ hasFile: c.declared.state !== "absent",
751
+ blockedBy,
752
+ blocks: (rev.get(n) ?? []).slice().sort(cmp),
753
+ related: [...(ctx.related.get(n) as Set<string>)].sort(cmp),
754
+ overlaps: [...(overlaps.get(n) as Set<string>)].sort(cmp),
755
+ wave: wave.get(n) ?? null,
756
+ issues: sortIssues(ctx.issues.get(n) as DependencyIssue[]),
757
+ };
758
+ }
759
+ return out;
760
+ }