@mmerterden/multi-agent-pipeline 23.3.0 → 23.5.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 (239) hide show
  1. package/CHANGELOG.md +73 -0
  2. package/README.md +27 -8
  3. package/README.tr.md +28 -9
  4. package/SECURITY.md +16 -0
  5. package/docs/adr/0008-installer-modularization-and-secret-leak-defense.md +1 -1
  6. package/docs/adr/0010-own-code-graph.md +299 -8
  7. package/docs/architecture.md +3 -3
  8. package/docs/ecosystem.md +10 -10
  9. package/docs/engineering.md +4 -4
  10. package/docs/facts.json +8 -8
  11. package/docs/features.md +5 -5
  12. package/docs/performance.md +17 -17
  13. package/install/_dev-only-files.mjs +9 -0
  14. package/install/_platform-filter.mjs +2 -55
  15. package/install/claude.mjs +28 -2
  16. package/install/codex.mjs +1 -3
  17. package/install/copilot.mjs +4 -8
  18. package/install/templates/claude-hooks.json +32 -1
  19. package/manifest.json +236 -167
  20. package/package.json +11 -3
  21. package/pipeline/commands/multi-agent/SKILL.md +1 -1
  22. package/pipeline/commands/multi-agent/design-check/SKILL.md +3 -2
  23. package/pipeline/commands/multi-agent/diff-explain/SKILL.md +3 -3
  24. package/pipeline/commands/multi-agent/graph/SKILL.md +57 -24
  25. package/pipeline/commands/multi-agent/pair/SKILL.md +92 -0
  26. package/pipeline/commands/multi-agent/prune-prompts/SKILL.md +1 -1
  27. package/pipeline/commands/multi-agent/search/SKILL.md +7 -1
  28. package/pipeline/commands/multi-agent/status/SKILL.md +4 -0
  29. package/pipeline/commands/multi-agent/sync/SKILL.md +3 -3
  30. package/pipeline/contract/CHANGELOG.md +63 -0
  31. package/pipeline/contract/README.md +1 -0
  32. package/pipeline/contract/build.mjs +13 -1
  33. package/pipeline/contract/fixtures/error-invalid-request.json +1 -1
  34. package/pipeline/contract/fixtures/error-unauthorized.json +1 -1
  35. package/pipeline/contract/fixtures/runs-awaiting-question.json +4 -1
  36. package/pipeline/contract/fixtures/runs-empty.json +1 -1
  37. package/pipeline/contract/fixtures/runs-failed.json +4 -1
  38. package/pipeline/contract/fixtures/runs-old-schema.json +3 -0
  39. package/pipeline/contract/fixtures/runs-pr-opened-redacted.json +4 -1
  40. package/pipeline/contract/fixtures/runs-pr-opened.json +4 -1
  41. package/pipeline/contract/fixtures/runs-running.json +4 -1
  42. package/pipeline/contract/manifest.json +41 -15
  43. package/pipeline/contract/types/index.d.ts +81 -3
  44. package/pipeline/lib/detach-self.mjs +95 -0
  45. package/pipeline/lib/public-mcp-servers.mjs +33 -0
  46. package/pipeline/lib/rotated-log.mjs +93 -0
  47. package/pipeline/lib/stack-detect.sh +1 -1
  48. package/pipeline/lib/tls-trust.mjs +29 -0
  49. package/pipeline/lib/usage-lifecycle.mjs +9 -11
  50. package/pipeline/lib/usage-names.generated.mjs +613 -0
  51. package/pipeline/lib/usage-run-key.mjs +235 -0
  52. package/pipeline/lib/usage-vocab.mjs +210 -0
  53. package/pipeline/multi-agent-refs/analysis/intake.md +2 -2
  54. package/pipeline/multi-agent-refs/analysis/render.md +1 -1
  55. package/pipeline/multi-agent-refs/channels/generator.md +4 -5
  56. package/pipeline/multi-agent-refs/cross-cli-contract.md +3 -3
  57. package/pipeline/multi-agent-refs/design-check/init-inventory.md +11 -1
  58. package/pipeline/multi-agent-refs/design-check/scope-and-ledger.md +1 -1
  59. package/pipeline/multi-agent-refs/features/code-graph.md +146 -11
  60. package/pipeline/multi-agent-refs/features/code-intelligence.md +16 -14
  61. package/pipeline/multi-agent-refs/features/dev-critic.md +7 -7
  62. package/pipeline/multi-agent-refs/features/model-fallback.md +6 -4
  63. package/pipeline/multi-agent-refs/features/remote-control.md +253 -0
  64. package/pipeline/multi-agent-refs/features/review-delta.md +1 -1
  65. package/pipeline/multi-agent-refs/features/review-file-set.md +3 -3
  66. package/pipeline/multi-agent-refs/features/review-multi-repo.md +1 -1
  67. package/pipeline/multi-agent-refs/features/session-brief.md +42 -0
  68. package/pipeline/multi-agent-refs/features/skill-conformance.md +3 -3
  69. package/pipeline/multi-agent-refs/features/usage-reporting.md +255 -27
  70. package/pipeline/multi-agent-refs/help/en.md +3 -2
  71. package/pipeline/multi-agent-refs/help/tr.md +3 -2
  72. package/pipeline/multi-agent-refs/knowledge.md +1 -1
  73. package/pipeline/multi-agent-refs/orchestrator/dispatcher.md +2 -2
  74. package/pipeline/multi-agent-refs/phases/operations.md +2 -2
  75. package/pipeline/multi-agent-refs/phases/phase-0-init.md +13 -12
  76. package/pipeline/multi-agent-refs/phases/phase-1-plan.md +4 -4
  77. package/pipeline/multi-agent-refs/phases/phase-3-review.md +2 -0
  78. package/pipeline/multi-agent-refs/phases/phase-5-report.md +1 -1
  79. package/pipeline/multi-agent-refs/platform-parity.md +2 -2
  80. package/pipeline/multi-agent-refs/wiki-capture.md +3 -17
  81. package/pipeline/office/index.html +1309 -236
  82. package/pipeline/office/toolkit.json +1 -1
  83. package/pipeline/rules/outside-the-pipeline.md +1 -1
  84. package/pipeline/schemas/activity.schema.json +23 -0
  85. package/pipeline/schemas/agent-state.schema.json +6 -1
  86. package/pipeline/schemas/code-graph-calls.schema.json +254 -0
  87. package/pipeline/schemas/code-graph-docs.schema.json +223 -0
  88. package/pipeline/schemas/code-graph-infra.schema.json +227 -0
  89. package/pipeline/schemas/code-graph.schema.json +2 -2
  90. package/pipeline/schemas/examples/design-check-config.json +27 -0
  91. package/pipeline/schemas/learning-curve.schema.json +67 -0
  92. package/pipeline/schemas/mcp-health.schema.json +96 -0
  93. package/pipeline/schemas/office-jobs.json +69 -2
  94. package/pipeline/schemas/office-jobs.schema.json +8 -1
  95. package/pipeline/schemas/phases.json +5 -0
  96. package/pipeline/schemas/phases.schema.json +8 -0
  97. package/pipeline/schemas/prefs.schema.json +46 -12
  98. package/pipeline/schemas/runs-index.schema.json +17 -0
  99. package/pipeline/schemas/toolkit-path-params.json +78 -8
  100. package/pipeline/scripts/README.md +1 -0
  101. package/pipeline/scripts/_code-graph.mjs +184 -103
  102. package/pipeline/scripts/_contract-core.mjs +1 -1
  103. package/pipeline/scripts/_contract-routes-office.mjs +33 -0
  104. package/pipeline/scripts/_diff-impact.mjs +21 -2
  105. package/pipeline/scripts/_graph-sidecars.mjs +372 -0
  106. package/pipeline/scripts/_http-post.mjs +103 -115
  107. package/pipeline/scripts/_safe-read.mjs +57 -0
  108. package/pipeline/scripts/_skill-practices.mjs +26 -0
  109. package/pipeline/scripts/_strip-code.mjs +380 -0
  110. package/pipeline/scripts/activity-snapshot.mjs +13 -1
  111. package/pipeline/scripts/aggregate-metrics.mjs +3 -5
  112. package/pipeline/scripts/build-stack-plugins.mjs +1 -47
  113. package/pipeline/scripts/call-graph/index.mjs +78 -0
  114. package/pipeline/scripts/call-graph/lang/cpp.mjs +308 -0
  115. package/pipeline/scripts/call-graph/lang/csharp.mjs +130 -0
  116. package/pipeline/scripts/call-graph/lang/go.mjs +303 -0
  117. package/pipeline/scripts/call-graph/lang/java.mjs +370 -0
  118. package/pipeline/scripts/call-graph/lang/kotlin.mjs +397 -0
  119. package/pipeline/scripts/call-graph/lang/python.mjs +399 -0
  120. package/pipeline/scripts/call-graph/lang/rust.mjs +345 -0
  121. package/pipeline/scripts/call-graph/lang/shared.mjs +230 -0
  122. package/pipeline/scripts/call-graph/lang/swift.mjs +432 -0
  123. package/pipeline/scripts/call-graph/lang/typescript.mjs +692 -0
  124. package/pipeline/scripts/call-graph/lex.mjs +396 -0
  125. package/pipeline/scripts/call-graph/platform.mjs +86 -0
  126. package/pipeline/scripts/call-graph/profiles.mjs +89 -0
  127. package/pipeline/scripts/call-graph/resolve.mjs +1125 -0
  128. package/pipeline/scripts/call-graph/scan.mjs +267 -0
  129. package/pipeline/scripts/code-graph-rules/android.json +7 -2
  130. package/pipeline/scripts/code-graph-rules/cpp.json +99 -0
  131. package/pipeline/scripts/code-graph-rules/csharp.json +102 -0
  132. package/pipeline/scripts/code-graph-rules/go.json +2 -1
  133. package/pipeline/scripts/code-graph-rules/ios.json +3 -1
  134. package/pipeline/scripts/code-graph-rules/java.json +76 -0
  135. package/pipeline/scripts/code-graph-rules/node.json +7 -2
  136. package/pipeline/scripts/code-graph-rules/python.json +6 -2
  137. package/pipeline/scripts/code-graph-rules/rust.json +105 -0
  138. package/pipeline/scripts/contract-server.mjs +3 -0
  139. package/pipeline/scripts/design-check-config.mjs +205 -0
  140. package/pipeline/scripts/feedback-send.mjs +26 -26
  141. package/pipeline/scripts/gate-ledger.mjs +2 -1
  142. package/pipeline/scripts/gen-facts.mjs +1 -2
  143. package/pipeline/scripts/gen-usage-names.mjs +124 -0
  144. package/pipeline/scripts/graph-affected.mjs +109 -20
  145. package/pipeline/scripts/graph-build.mjs +95 -15
  146. package/pipeline/scripts/graph-export.mjs +272 -0
  147. package/pipeline/scripts/graph-hint.mjs +15 -2
  148. package/pipeline/scripts/graph-query.mjs +305 -26
  149. package/pipeline/scripts/graph-report.mjs +187 -1
  150. package/pipeline/scripts/health-report.mjs +3 -4
  151. package/pipeline/scripts/infra/docs.mjs +317 -0
  152. package/pipeline/scripts/infra/extract.mjs +998 -0
  153. package/pipeline/scripts/infra/graph.mjs +245 -0
  154. package/pipeline/scripts/infra/yaml-lite.mjs +311 -0
  155. package/pipeline/scripts/job-launch.mjs +67 -2
  156. package/pipeline/scripts/learning-curve.mjs +288 -178
  157. package/pipeline/scripts/log-metric.sh +10 -1
  158. package/pipeline/scripts/mcp-health.mjs +309 -0
  159. package/pipeline/scripts/note-agent-event.mjs +3 -4
  160. package/pipeline/scripts/note-command-use.mjs +333 -0
  161. package/pipeline/scripts/note-command-use.sh +126 -0
  162. package/pipeline/scripts/note-mcp-call.sh +89 -0
  163. package/pipeline/scripts/note-mcp-failure.mjs +272 -1
  164. package/pipeline/scripts/note-session.sh +62 -3
  165. package/pipeline/scripts/note-skill-use.mjs +58 -2
  166. package/pipeline/scripts/office-build.mjs +115 -1
  167. package/pipeline/scripts/office-memory.mjs +14 -5
  168. package/pipeline/scripts/pair.mjs +333 -0
  169. package/pipeline/scripts/pre-push-check.sh +1 -1
  170. package/pipeline/scripts/remote/cbor.mjs +128 -0
  171. package/pipeline/scripts/remote/contract.mjs +98 -0
  172. package/pipeline/scripts/remote/handler.mjs +330 -0
  173. package/pipeline/scripts/remote/handles.mjs +57 -0
  174. package/pipeline/scripts/remote/lifecycle.mjs +186 -0
  175. package/pipeline/scripts/remote/listener.mjs +204 -0
  176. package/pipeline/scripts/remote/lockout.mjs +103 -0
  177. package/pipeline/scripts/remote/nonces.mjs +61 -0
  178. package/pipeline/scripts/remote/pairing.mjs +519 -0
  179. package/pipeline/scripts/remote/qr-encode.mjs +459 -0
  180. package/pipeline/scripts/remote/store.mjs +191 -0
  181. package/pipeline/scripts/remote/transport.mjs +211 -0
  182. package/pipeline/scripts/remote/verbs.json +70 -0
  183. package/pipeline/scripts/remote/verbs.mjs +217 -0
  184. package/pipeline/scripts/remote/webauthn.mjs +169 -0
  185. package/pipeline/scripts/remote/wire.mjs +364 -0
  186. package/pipeline/scripts/remote-listener.mjs +83 -0
  187. package/pipeline/scripts/route-learn.mjs +4 -4
  188. package/pipeline/scripts/run-kill.mjs +1 -1
  189. package/pipeline/scripts/run-write.mjs +13 -2
  190. package/pipeline/scripts/runs-index.mjs +30 -3
  191. package/pipeline/scripts/search-logs.sh +9 -0
  192. package/pipeline/scripts/session-brief.mjs +458 -0
  193. package/pipeline/scripts/session-brief.sh +130 -0
  194. package/pipeline/scripts/skill-usage.mjs +16 -5
  195. package/pipeline/scripts/test-gap-rules/cpp.json +25 -0
  196. package/pipeline/scripts/test-gap-rules/csharp.json +20 -0
  197. package/pipeline/scripts/test-gap-rules/java.json +20 -0
  198. package/pipeline/scripts/test-gap-rules/rust.json +14 -0
  199. package/pipeline/scripts/token-budget-report.mjs +3 -2
  200. package/pipeline/scripts/uninstall.mjs +29 -0
  201. package/pipeline/scripts/usage-access.mjs +16 -31
  202. package/pipeline/scripts/usage-health.mjs +31 -62
  203. package/pipeline/scripts/usage-register-beacon.mjs +11 -22
  204. package/pipeline/scripts/usage-register.mjs +39 -29
  205. package/pipeline/scripts/usage-report.mjs +579 -178
  206. package/pipeline/scripts/validate-code-graph.mjs +361 -111
  207. package/pipeline/scripts/write-state.mjs +39 -0
  208. package/pipeline/skills/.skill-manifest.json +21 -17
  209. package/pipeline/skills/.skills-index.json +13 -2
  210. package/pipeline/skills/shared/README.md +5 -4
  211. package/pipeline/skills/shared/core/multi-agent-design-check/SKILL.md +1 -1
  212. package/pipeline/skills/shared/core/multi-agent-diff-explain/SKILL.md +3 -3
  213. package/pipeline/skills/shared/core/multi-agent-graph/SKILL.md +55 -21
  214. package/pipeline/skills/shared/core/multi-agent-pair/SKILL.md +41 -0
  215. package/pipeline/skills/shared/core/multi-agent-prune-prompts/SKILL.md +1 -1
  216. package/pipeline/skills/shared/core/multi-agent-sync/SKILL.md +3 -3
  217. package/pipeline/skills/shared/external/app-store-optimization/SKILL.md +2 -3
  218. package/pipeline/skills/shared/external/app-store-optimization/references/keyword-research-methodology.md +2 -2
  219. package/pipeline/skills/shared/external/app-store-optimization/references/product-page-variants.md +2 -2
  220. package/pipeline/skills/shared/external/app-store-review/SKILL.md +11 -4
  221. package/pipeline/skills/shared/external/build-settings-audit/SKILL.md +1 -1
  222. package/pipeline/skills/shared/external/build-time-benchmark/SKILL.md +5 -5
  223. package/pipeline/skills/shared/external/build-time-fixes/SKILL.md +5 -5
  224. package/pipeline/skills/shared/external/build-time-optimizer/SKILL.md +6 -6
  225. package/pipeline/skills/shared/external/free-llm-apis/references/providers.md +1 -0
  226. package/pipeline/skills/shared/external/ios-coding-standard/references/STANDARD.md +2 -2
  227. package/pipeline/skills/shared/external/ios-haptics/references/core-haptics.md +1 -1
  228. package/pipeline/skills/shared/external/localization-reuse-map/references/publish-and-snapshot.md +1 -1
  229. package/pipeline/skills/shared/external/package-build-audit/SKILL.md +3 -3
  230. package/pipeline/skills/shared/external/reverse-engineer-own-app/SKILL.md +2 -3
  231. package/pipeline/skills/shared/external/swift-compile-hotspots/SKILL.md +2 -2
  232. package/pipeline/skills/shared/external/weatherkit/SKILL.md +5 -6
  233. package/pipeline/skills/skills-index.md +3 -2
  234. package/docs/FIGMA_PIPELINE.md +0 -137
  235. package/pipeline/lib/identifier-scan.mjs +0 -156
  236. package/pipeline/scripts/_renamed-skills.mjs +0 -164
  237. package/pipeline/scripts/publish-staged.mjs +0 -324
  238. package/pipeline/skills/renamed.json +0 -30
  239. package/pipeline/skills/shared/external/ios-coding-standard/scripts/check_structure.py +0 -765
@@ -21,7 +21,7 @@ import { launchRepoAllowed, launchRepos } from "./launch-request.mjs";
21
21
  import { selectRuns } from "./runs-index.mjs";
22
22
 
23
23
  /** The contract as a whole; pipeline/contract/manifest.json carries the same. */
24
- export const CONTRACT_VERSION = "2.0.0";
24
+ export const CONTRACT_VERSION = "2.3.0";
25
25
  /** Confirm tokens held at once; the oldest is dropped past this. */
26
26
  export const MAX_CONFIRMS = 256;
27
27
  /** How long a kill or gc confirm token stays valid. */
@@ -8,9 +8,11 @@
8
8
 
9
9
  import { activitySnapshot, agentChat, createActivityCache } from "./activity-snapshot.mjs";
10
10
  import { officeCredentials } from "./office-credentials.mjs";
11
+ import { CONTRACT_VERSION as LEARNING_VERSION, cachedLearningCurve } from "./learning-curve.mjs";
11
12
  import { officeLedger } from "./office-ledger.mjs";
12
13
  import { officeMemory } from "./office-memory.mjs";
13
14
  import { officeServerRoom } from "./office-server-room.mjs";
15
+ import { createMcpHealthCache } from "./mcp-health.mjs";
14
16
  import { officeArchive } from "./office-archive.mjs";
15
17
  import { systemStatus } from "./system-status.mjs";
16
18
  import { reapEndedJobs } from "./job-launch.mjs";
@@ -20,6 +22,7 @@ const SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
20
22
  const AGENT_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
21
23
 
22
24
  const activityCache = createActivityCache();
25
+ const mcpHealthCached = createMcpHealthCache();
23
26
  // Each session list the floor reads once is also where the office learns a
24
27
  // job ended: its run home and launch file are removed then.
25
28
  let reapedFor = null;
@@ -80,6 +83,26 @@ export const officeRoutes = {
80
83
  query: [],
81
84
  handle: () => officeLedger(),
82
85
  },
86
+ learning: {
87
+ method: "GET",
88
+ path: "/v1/learning-curve",
89
+ remote: "read",
90
+ query: [],
91
+ handle: shared(
92
+ () => "learning-curve",
93
+ () => {
94
+ const curve = cachedLearningCurve();
95
+ if (!curve.ok)
96
+ return {
97
+ contractVersion: LEARNING_VERSION,
98
+ ok: false,
99
+ code: curve.code,
100
+ buckets: [],
101
+ };
102
+ return { contractVersion: LEARNING_VERSION, ...curve };
103
+ },
104
+ ),
105
+ },
83
106
  system: {
84
107
  method: "GET",
85
108
  path: "/v1/system",
@@ -120,6 +143,16 @@ export const officeRoutes = {
120
143
  async () => officeServerRoom({ activity: await activityNow(), lang: officeLang() }),
121
144
  ),
122
145
  },
146
+ mcpHealth: {
147
+ method: "GET",
148
+ path: "/v1/mcp-health",
149
+ query: [],
150
+ remote: "local-only",
151
+ handle: shared(
152
+ () => "mcp-health",
153
+ () => mcpHealthCached(),
154
+ ),
155
+ },
123
156
  archive: {
124
157
  method: "GET",
125
158
  path: "/v1/archive",
@@ -24,6 +24,7 @@ import { execFileSync } from "node:child_process";
24
24
  import { existsSync, statSync } from "node:fs";
25
25
  import { join } from "node:path";
26
26
  import { diffHeaderPath } from "./git-path.mjs";
27
+ import { listSourceFiles, loadRules } from "./_code-graph.mjs";
27
28
 
28
29
  const HUNK_RE = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
29
30
 
@@ -266,7 +267,8 @@ function gitOut(root, args) {
266
267
  *
267
268
  * @param {object} graph
268
269
  * @param {{root?: string}} [opts] - defaults to the root recorded in the graph
269
- * @returns {{stale: boolean, commitMoved: boolean|null, baseCommit: string|null, head: string|null, changedFiles: string[], removedFiles: string[]}}
270
+ * @returns {{stale: boolean, commitMoved: boolean|null, baseCommit: string|null, head: string|null, changedFiles: string[], removedFiles: string[], addedFiles: string[]}}
271
+ * addedFiles are source files of the graph's stack that exist now and were not in the build
270
272
  */
271
273
  export function graphFreshness(graph, { root = graph.root } = {}) {
272
274
  const manifest = graph.manifest || {};
@@ -284,16 +286,33 @@ export function graphFreshness(graph, { root = graph.root } = {}) {
284
286
  const head = root ? gitOut(root, ["rev-parse", "HEAD"]) : null;
285
287
  const baseCommit = graph.baseCommit || null;
286
288
  const commitMoved = head && baseCommit ? head !== baseCommit : null;
289
+ const addedFiles = [];
290
+ if (root && Object.keys(manifest).length > 0) {
291
+ try {
292
+ for (const p of listSourceFiles(root, loadRules(graph.stack))) {
293
+ if (!(p in manifest) && addedFiles.length < MAX_ADDED_LISTED) addedFiles.push(p);
294
+ }
295
+ } catch {
296
+ // A stack with no rules on this install, or a root that is gone: nothing to add.
297
+ }
298
+ }
287
299
  return {
288
- stale: Boolean(commitMoved) || changedFiles.length > 0 || removedFiles.length > 0,
300
+ stale:
301
+ Boolean(commitMoved) ||
302
+ changedFiles.length > 0 ||
303
+ removedFiles.length > 0 ||
304
+ addedFiles.length > 0,
289
305
  commitMoved,
290
306
  baseCommit,
291
307
  head,
292
308
  changedFiles: changedFiles.sort(),
293
309
  removedFiles: removedFiles.sort(),
310
+ addedFiles: addedFiles.sort(),
294
311
  };
295
312
  }
296
313
 
314
+ const MAX_ADDED_LISTED = 200;
315
+
297
316
  /**
298
317
  * Which side of a diff the graph's line numbers describe. For a commit range
299
318
  * (`range`, `<base>..<head>`) the graph's build commit decides: built at the
@@ -0,0 +1,372 @@
1
+ /**
2
+ * @file _graph-sidecars.mjs - the graph's optional layers, stored beside the main file.
3
+ *
4
+ * The main graph file (`code-graph.json`) holds files, symbols, modules and the
5
+ * defines / imports / references / inherits edges between them, at schema 1.2.0.
6
+ * Everything newer lives in a sidecar next to it, so a reader that only knows
7
+ * the main file keeps working and the main file does not grow for a user who
8
+ * never asks for the extra layer:
9
+ *
10
+ * calls function and method nodes, `defines` edges to them and `calls`
11
+ * edges between them (built by default)
12
+ * docs documentation sections, rationale comments, `mentions` / `explains`
13
+ * infra Dockerfile, Compose, Kubernetes, Helm, Terraform, CI, env and
14
+ * config nodes with the edges that connect code to them
15
+ *
16
+ * Each sidecar has its own schema version, names the build of the main graph it
17
+ * was made against (`parent`), carries the node and edge counts it was capped
18
+ * to (`truncated`), and, for docs and infra, a manifest of the files it read so
19
+ * an edited README, Dockerfile or .env marks it stale. Hub metrics stay
20
+ * structural: a sidecar never changes a node's `degree`.
21
+ *
22
+ * @module pipeline/scripts/_graph-sidecars
23
+ */
24
+
25
+ import { existsSync, readFileSync, statSync, unlinkSync, writeFileSync } from "node:fs";
26
+ import { join } from "node:path";
27
+
28
+ export const SIDECAR_NAMES = ["calls", "docs", "infra"];
29
+
30
+ export const SIDECAR_SPECS = {
31
+ calls: {
32
+ version: "1.0.0",
33
+ nodeKinds: ["symbol"],
34
+ edgeKinds: ["defines", "calls"],
35
+ maxNodes: 250_000,
36
+ maxEdges: 1_000_000,
37
+ },
38
+ docs: {
39
+ version: "1.0.0",
40
+ nodeKinds: ["file", "doc", "rationale"],
41
+ edgeKinds: ["defines", "mentions", "explains"],
42
+ maxNodes: 20_000,
43
+ maxEdges: 80_000,
44
+ },
45
+ infra: {
46
+ version: "1.0.0",
47
+ nodeKinds: ["file", "infra", "env", "config", "module"],
48
+ edgeKinds: ["defines", "sets", "uses", "builds", "runs", "reads"],
49
+ maxNodes: 30_000,
50
+ maxEdges: 120_000,
51
+ },
52
+ };
53
+
54
+ /** How a call edge can have been derived; the resolver emits nothing else. */
55
+ export const CALL_VIAS = new Set([
56
+ "typed-receiver",
57
+ "self-receiver",
58
+ "super-receiver",
59
+ "static-receiver",
60
+ "implicit-self",
61
+ "same-file",
62
+ "same-package",
63
+ "import",
64
+ "module-member",
65
+ "interface-member",
66
+ "ambiguous-overload",
67
+ "constructor",
68
+ "dispatch",
69
+ "inherited",
70
+ "same-directory",
71
+ "chained-return-type",
72
+ "unique-name",
73
+ "name-arity",
74
+ ]);
75
+
76
+ const CONF_RANK = { certain: 4, high: 3, medium: 2, low: 1 };
77
+
78
+ /** Path of a sidecar given the main graph path. */
79
+ export function sidecarPath(graphPath, name) {
80
+ return /\.json$/.test(graphPath)
81
+ ? graphPath.replace(/\.json$/, `.${name}.json`)
82
+ : `${graphPath}.${name}.json`;
83
+ }
84
+
85
+ /**
86
+ * Keep a sidecar within its caps. Edges go first: structural `defines` edges,
87
+ * then the rest by confidence, so a cap drops the weakest edges. Nodes no kept
88
+ * edge touches are dropped with them. What was cut is recorded, never silent.
89
+ *
90
+ * @param {{nodes: Array, edges: Array}} body
91
+ * @param {{maxNodes: number, maxEdges: number}} caps
92
+ * @returns {{nodes: Array, edges: Array, truncated: object|null}}
93
+ */
94
+ export function capSidecar(body, caps) {
95
+ let { nodes, edges } = body;
96
+ const droppedEdgesBefore = edges.length;
97
+ const droppedNodesBefore = nodes.length;
98
+ if (edges.length > caps.maxEdges) {
99
+ const ranked = edges
100
+ .map((e, i) => ({ e, i }))
101
+ .sort((a, b) => {
102
+ const ra = a.e.kind === "defines" ? 9 : (CONF_RANK[a.e.confidence] ?? 4);
103
+ const rb = b.e.kind === "defines" ? 9 : (CONF_RANK[b.e.confidence] ?? 4);
104
+ return rb - ra || a.i - b.i;
105
+ })
106
+ .slice(0, caps.maxEdges)
107
+ .sort((a, b) => a.i - b.i);
108
+ edges = ranked.map((x) => x.e);
109
+ }
110
+ if (nodes.length > caps.maxNodes) {
111
+ nodes = nodes.slice(0, caps.maxNodes);
112
+ const keep = new Set(nodes.map((n) => n.id));
113
+ edges = edges.filter(
114
+ (e) => (!isSidecarId(e.from) || keep.has(e.from)) && (!isSidecarId(e.to) || keep.has(e.to)),
115
+ );
116
+ }
117
+ const touched = new Set();
118
+ for (const e of edges) {
119
+ touched.add(e.from);
120
+ touched.add(e.to);
121
+ }
122
+ if (edges.length < droppedEdgesBefore) nodes = nodes.filter((n) => touched.has(n.id));
123
+ const cutEdges = droppedEdgesBefore - edges.length;
124
+ const cutNodes = droppedNodesBefore - nodes.length;
125
+ return {
126
+ nodes,
127
+ edges,
128
+ truncated:
129
+ cutEdges > 0 || cutNodes > 0
130
+ ? {
131
+ edges: cutEdges,
132
+ nodes: cutNodes,
133
+ reason: `capped at ${caps.maxNodes} nodes and ${caps.maxEdges} edges`,
134
+ }
135
+ : null,
136
+ };
137
+ }
138
+
139
+ const isSidecarId = (id) => !/^(file:|module:)/.test(id);
140
+
141
+ /**
142
+ * Wrap a layer's nodes and edges as a sidecar document.
143
+ *
144
+ * @param {string} name - calls | docs | infra
145
+ * @param {object} main - the main graph
146
+ * @param {{nodes: Array, edges: Array, annotations?: object, manifest?: object, stats?: object, coverage?: object}} body
147
+ * @param {{maxNodes?: number, maxEdges?: number}} [caps]
148
+ */
149
+ export function makeSidecar(name, main, body, caps = {}) {
150
+ const spec = SIDECAR_SPECS[name];
151
+ const capped = capSidecar(body, {
152
+ maxNodes: caps.maxNodes ?? spec.maxNodes,
153
+ maxEdges: caps.maxEdges ?? spec.maxEdges,
154
+ });
155
+ return {
156
+ sidecar: name,
157
+ schemaVersion: spec.version,
158
+ parent: {
159
+ generatedAt: main.generatedAt,
160
+ baseCommit: main.baseCommit ?? null,
161
+ stack: main.stack,
162
+ nodes: main.stats.nodes,
163
+ edges: main.stats.edges,
164
+ },
165
+ generatedAt: main.generatedAt,
166
+ stats: { ...(body.stats || {}), nodes: capped.nodes.length, edges: capped.edges.length },
167
+ truncated: capped.truncated,
168
+ ...(body.annotations && Object.keys(body.annotations).length
169
+ ? { annotations: body.annotations }
170
+ : {}),
171
+ ...(body.manifest ? { manifest: body.manifest } : {}),
172
+ ...(body.coverage ? { coverage: body.coverage } : {}),
173
+ nodes: capped.nodes,
174
+ edges: capped.edges,
175
+ };
176
+ }
177
+
178
+ /** Write the main graph and its sidecars; remove sidecars this build did not make. */
179
+ export function writeGraphFiles(out, built) {
180
+ writeFileSync(out, JSON.stringify(built.graph), "utf8");
181
+ for (const name of SIDECAR_NAMES) {
182
+ const p = sidecarPath(out, name);
183
+ const side = built.sidecars[name];
184
+ if (side) writeFileSync(p, JSON.stringify(side), "utf8");
185
+ else if (existsSync(p)) unlinkSync(p);
186
+ }
187
+ }
188
+
189
+ function manifestDrift(root, manifest) {
190
+ const changed = [];
191
+ const removed = [];
192
+ for (const [path, prev] of Object.entries(manifest || {})) {
193
+ let st;
194
+ try {
195
+ st = statSync(join(root, path));
196
+ } catch {
197
+ removed.push(path);
198
+ continue;
199
+ }
200
+ if (st.size !== prev.size || Math.floor(st.mtimeMs) !== prev.mtimeMs) changed.push(path);
201
+ }
202
+ return { changed, removed };
203
+ }
204
+
205
+ /**
206
+ * Read the sidecars next to a main graph and join them to it.
207
+ *
208
+ * The result of each sidecar is reported in `graph.sidecars[name]`:
209
+ * state present | absent | stale | mismatched | invalid
210
+ * reason one sentence, ready to print
211
+ * A mismatched sidecar (made against a different build of the main graph) is
212
+ * not joined: its ids could point at nodes the main file no longer has. A stale
213
+ * one (its inputs changed since) is joined and flagged.
214
+ *
215
+ * @param {object} graph - parsed main graph, mutated
216
+ * @param {string} graphPath
217
+ * @param {{read?: (p: string) => string|null, parsed?: object, addedPaths?: (name: string, side: object) => string[]}} [io]
218
+ * @returns {object} the same graph
219
+ */
220
+ export function attachSidecars(graph, graphPath, io = {}) {
221
+ const read =
222
+ io.read ||
223
+ ((p) => {
224
+ try {
225
+ return readFileSync(p, "utf8");
226
+ } catch {
227
+ return null;
228
+ }
229
+ });
230
+ const ids = new Set(graph.nodes.map((n) => n.id));
231
+ const byId = new Map(graph.nodes.map((n) => [n.id, n]));
232
+ const status = {};
233
+ const extraStats = {};
234
+ for (const name of SIDECAR_NAMES) {
235
+ let side = io.parsed?.[name];
236
+ if (!side) {
237
+ const text = read(sidecarPath(graphPath, name));
238
+ if (text === null) {
239
+ status[name] = { state: "absent", reason: absentReason(name) };
240
+ continue;
241
+ }
242
+ try {
243
+ side = JSON.parse(text);
244
+ } catch {
245
+ status[name] = { state: "invalid", reason: `${name} sidecar is not valid JSON` };
246
+ continue;
247
+ }
248
+ }
249
+ const spec = SIDECAR_SPECS[name];
250
+ if (
251
+ !side ||
252
+ side.sidecar !== name ||
253
+ !Array.isArray(side.nodes) ||
254
+ !Array.isArray(side.edges) ||
255
+ typeof side.schemaVersion !== "string"
256
+ ) {
257
+ status[name] = { state: "invalid", reason: `${name} sidecar is malformed` };
258
+ continue;
259
+ }
260
+ if (side.schemaVersion.split(".")[0] !== spec.version.split(".")[0]) {
261
+ status[name] = {
262
+ state: "invalid",
263
+ reason: `${name} sidecar is schema ${side.schemaVersion}, this reader knows ${spec.version}`,
264
+ };
265
+ continue;
266
+ }
267
+ if (!side.parent || side.parent.generatedAt !== graph.generatedAt) {
268
+ status[name] = {
269
+ state: "mismatched",
270
+ reason: `${name} sidecar was built against a different graph build and was not joined; rebuild the graph`,
271
+ };
272
+ continue;
273
+ }
274
+ for (const [id, extra] of Object.entries(side.annotations || {})) {
275
+ const node = byId.get(id);
276
+ if (node) Object.assign(node, extra);
277
+ }
278
+ for (const n of side.nodes) {
279
+ if (ids.has(n.id)) continue;
280
+ ids.add(n.id);
281
+ const added = { ...n, degree: 0, layer: name };
282
+ graph.nodes.push(added);
283
+ byId.set(n.id, added);
284
+ }
285
+ for (const e of side.edges) if (ids.has(e.from) && ids.has(e.to)) graph.edges.push(e);
286
+ Object.assign(extraStats, side.stats || {});
287
+ if (side.coverage) graph.coverage = { ...(graph.coverage || {}), ...side.coverage };
288
+ const state = { state: "present", reason: "", truncated: side.truncated || null };
289
+ if (side.truncated) {
290
+ state.reason = `${name} sidecar is truncated: ${side.truncated.edges} edge(s) and ${side.truncated.nodes} node(s) cut (${side.truncated.reason})`;
291
+ }
292
+ if (side.manifest) {
293
+ const root = graph.root;
294
+ const drift = root ? manifestDrift(root, side.manifest) : { changed: [], removed: [] };
295
+ const added = io.addedPaths ? io.addedPaths(name, side) : [];
296
+ if (drift.changed.length || drift.removed.length || added.length) {
297
+ state.state = "stale";
298
+ const parts = [];
299
+ if (drift.changed.length) parts.push(`${drift.changed.length} changed`);
300
+ if (drift.removed.length) parts.push(`${drift.removed.length} removed`);
301
+ if (added.length) parts.push(`${added.length} added`);
302
+ state.reason = `${name} sidecar is stale: ${parts.join(", ")} input file(s) since it was built`;
303
+ state.files = [...drift.changed, ...drift.removed, ...added].slice(0, 10);
304
+ }
305
+ }
306
+ status[name] = state;
307
+ }
308
+ graph.sidecars = status;
309
+ graph.stats = { ...graph.stats, ...stripBase(extraStats) };
310
+ return graph;
311
+ }
312
+
313
+ const stripBase = ({ nodes, edges, ...rest }) => {
314
+ void nodes;
315
+ void edges;
316
+ return rest;
317
+ };
318
+
319
+ function absentReason(name) {
320
+ if (name === "calls") return "no calls sidecar: rebuild the graph to add call edges";
321
+ const flag = name === "docs" ? "--docs" : "--infra";
322
+ return `no ${name} sidecar: it is opt-in, build with ${flag}`;
323
+ }
324
+
325
+ /** One line per sidecar that is not plainly present, for a reader to print. */
326
+ export function sidecarNotes(graph) {
327
+ return Object.values(graph.sidecars || {})
328
+ .filter((s) => s.state !== "present" || s.truncated)
329
+ .map((s) => s.reason)
330
+ .filter(Boolean);
331
+ }
332
+
333
+ /** Layers a set of node kinds comes from. */
334
+ export function layersOfKinds(kinds) {
335
+ const out = new Set();
336
+ for (const k of kinds) {
337
+ if (k === "doc" || k === "rationale") out.add("docs");
338
+ else if (k === "infra" || k === "env" || k === "config") out.add("infra");
339
+ else if (k === "calls") out.add("calls");
340
+ }
341
+ return [...out];
342
+ }
343
+
344
+ /**
345
+ * What a reader must tell the user about the layers its answer drew on: absent,
346
+ * stale, mismatched, invalid or truncated. Empty when each is plainly present.
347
+ *
348
+ * @param {object} graph - from loadGraph
349
+ * @param {string[]} names - layers the answer used
350
+ * @returns {string[]}
351
+ */
352
+ export function notesFor(graph, names) {
353
+ return names
354
+ .map((n) => graph.sidecars?.[n])
355
+ .filter((s) => s && (s.state !== "present" || s.truncated))
356
+ .map((s) => s.reason)
357
+ .filter(Boolean);
358
+ }
359
+
360
+ /**
361
+ * Notes a reader that uses every layer must print: calls whatever its state,
362
+ * docs and infra only once they exist (their absence is the default, not news).
363
+ */
364
+ export function layerNotes(graph) {
365
+ return Object.entries(graph.sidecars || {})
366
+ .filter(
367
+ ([name, st]) =>
368
+ (name === "calls" || st.state !== "absent") && (st.state !== "present" || st.truncated),
369
+ )
370
+ .map(([, st]) => st.reason)
371
+ .filter(Boolean);
372
+ }