@mmerterden/multi-agent-pipeline 23.3.0 → 23.4.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 (224) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/README.md +25 -6
  3. package/README.tr.md +26 -7
  4. package/docs/adr/0008-installer-modularization-and-secret-leak-defense.md +1 -1
  5. package/docs/adr/0010-own-code-graph.md +299 -8
  6. package/docs/architecture.md +3 -3
  7. package/docs/ecosystem.md +10 -10
  8. package/docs/engineering.md +4 -4
  9. package/docs/facts.json +8 -8
  10. package/docs/features.md +5 -5
  11. package/docs/performance.md +17 -17
  12. package/install/_dev-only-files.mjs +9 -0
  13. package/install/claude.mjs +28 -2
  14. package/install/templates/claude-hooks.json +32 -1
  15. package/manifest.json +223 -155
  16. package/package.json +11 -3
  17. package/pipeline/commands/multi-agent/SKILL.md +1 -1
  18. package/pipeline/commands/multi-agent/design-check/SKILL.md +2 -2
  19. package/pipeline/commands/multi-agent/diff-explain/SKILL.md +3 -3
  20. package/pipeline/commands/multi-agent/graph/SKILL.md +57 -24
  21. package/pipeline/commands/multi-agent/pair/SKILL.md +92 -0
  22. package/pipeline/commands/multi-agent/prune-prompts/SKILL.md +1 -1
  23. package/pipeline/commands/multi-agent/search/SKILL.md +7 -1
  24. package/pipeline/commands/multi-agent/status/SKILL.md +4 -0
  25. package/pipeline/commands/multi-agent/sync/SKILL.md +3 -3
  26. package/pipeline/contract/CHANGELOG.md +49 -0
  27. package/pipeline/contract/build.mjs +13 -1
  28. package/pipeline/contract/fixtures/error-invalid-request.json +1 -1
  29. package/pipeline/contract/fixtures/error-unauthorized.json +1 -1
  30. package/pipeline/contract/fixtures/runs-awaiting-question.json +4 -1
  31. package/pipeline/contract/fixtures/runs-empty.json +1 -1
  32. package/pipeline/contract/fixtures/runs-failed.json +4 -1
  33. package/pipeline/contract/fixtures/runs-old-schema.json +3 -0
  34. package/pipeline/contract/fixtures/runs-pr-opened-redacted.json +4 -1
  35. package/pipeline/contract/fixtures/runs-pr-opened.json +4 -1
  36. package/pipeline/contract/fixtures/runs-running.json +4 -1
  37. package/pipeline/contract/manifest.json +28 -15
  38. package/pipeline/contract/types/index.d.ts +55 -3
  39. package/pipeline/lib/detach-self.mjs +95 -0
  40. package/pipeline/lib/public-mcp-servers.mjs +33 -0
  41. package/pipeline/lib/rotated-log.mjs +93 -0
  42. package/pipeline/lib/tls-trust.mjs +29 -0
  43. package/pipeline/lib/usage-lifecycle.mjs +9 -11
  44. package/pipeline/lib/usage-names.generated.mjs +614 -0
  45. package/pipeline/lib/usage-run-key.mjs +235 -0
  46. package/pipeline/lib/usage-vocab.mjs +210 -0
  47. package/pipeline/multi-agent-refs/analysis/intake.md +2 -2
  48. package/pipeline/multi-agent-refs/analysis/render.md +1 -1
  49. package/pipeline/multi-agent-refs/channels/generator.md +4 -5
  50. package/pipeline/multi-agent-refs/cross-cli-contract.md +3 -3
  51. package/pipeline/multi-agent-refs/design-check/scope-and-ledger.md +1 -1
  52. package/pipeline/multi-agent-refs/features/code-graph.md +146 -11
  53. package/pipeline/multi-agent-refs/features/code-intelligence.md +16 -14
  54. package/pipeline/multi-agent-refs/features/dev-critic.md +7 -7
  55. package/pipeline/multi-agent-refs/features/model-fallback.md +6 -4
  56. package/pipeline/multi-agent-refs/features/remote-control.md +252 -0
  57. package/pipeline/multi-agent-refs/features/review-delta.md +1 -1
  58. package/pipeline/multi-agent-refs/features/review-file-set.md +3 -3
  59. package/pipeline/multi-agent-refs/features/review-multi-repo.md +1 -1
  60. package/pipeline/multi-agent-refs/features/session-brief.md +42 -0
  61. package/pipeline/multi-agent-refs/features/skill-conformance.md +3 -3
  62. package/pipeline/multi-agent-refs/features/usage-reporting.md +252 -24
  63. package/pipeline/multi-agent-refs/help/en.md +3 -2
  64. package/pipeline/multi-agent-refs/help/tr.md +3 -2
  65. package/pipeline/multi-agent-refs/knowledge.md +1 -1
  66. package/pipeline/multi-agent-refs/orchestrator/dispatcher.md +1 -1
  67. package/pipeline/multi-agent-refs/phases/operations.md +2 -2
  68. package/pipeline/multi-agent-refs/phases/phase-0-init.md +13 -12
  69. package/pipeline/multi-agent-refs/phases/phase-1-plan.md +4 -4
  70. package/pipeline/multi-agent-refs/phases/phase-3-review.md +2 -0
  71. package/pipeline/multi-agent-refs/phases/phase-5-report.md +1 -1
  72. package/pipeline/multi-agent-refs/platform-parity.md +2 -2
  73. package/pipeline/multi-agent-refs/wiki-capture.md +3 -17
  74. package/pipeline/office/index.html +1207 -233
  75. package/pipeline/office/toolkit.json +1 -1
  76. package/pipeline/rules/outside-the-pipeline.md +1 -1
  77. package/pipeline/schemas/activity.schema.json +23 -0
  78. package/pipeline/schemas/agent-state.schema.json +6 -1
  79. package/pipeline/schemas/code-graph-calls.schema.json +254 -0
  80. package/pipeline/schemas/code-graph-docs.schema.json +223 -0
  81. package/pipeline/schemas/code-graph-infra.schema.json +227 -0
  82. package/pipeline/schemas/code-graph.schema.json +2 -2
  83. package/pipeline/schemas/examples/design-check-config.json +27 -0
  84. package/pipeline/schemas/learning-curve.schema.json +67 -0
  85. package/pipeline/schemas/office-jobs.json +69 -2
  86. package/pipeline/schemas/office-jobs.schema.json +8 -1
  87. package/pipeline/schemas/phases.json +5 -0
  88. package/pipeline/schemas/phases.schema.json +8 -0
  89. package/pipeline/schemas/prefs.schema.json +46 -12
  90. package/pipeline/schemas/runs-index.schema.json +17 -0
  91. package/pipeline/schemas/toolkit-path-params.json +84 -8
  92. package/pipeline/scripts/README.md +1 -0
  93. package/pipeline/scripts/_code-graph.mjs +184 -103
  94. package/pipeline/scripts/_contract-core.mjs +1 -1
  95. package/pipeline/scripts/_contract-routes-office.mjs +21 -0
  96. package/pipeline/scripts/_diff-impact.mjs +21 -2
  97. package/pipeline/scripts/_graph-sidecars.mjs +372 -0
  98. package/pipeline/scripts/_http-post.mjs +103 -115
  99. package/pipeline/scripts/_safe-read.mjs +57 -0
  100. package/pipeline/scripts/_skill-practices.mjs +26 -0
  101. package/pipeline/scripts/_strip-code.mjs +380 -0
  102. package/pipeline/scripts/activity-snapshot.mjs +13 -1
  103. package/pipeline/scripts/aggregate-metrics.mjs +3 -5
  104. package/pipeline/scripts/call-graph/index.mjs +78 -0
  105. package/pipeline/scripts/call-graph/lang/cpp.mjs +308 -0
  106. package/pipeline/scripts/call-graph/lang/csharp.mjs +130 -0
  107. package/pipeline/scripts/call-graph/lang/go.mjs +303 -0
  108. package/pipeline/scripts/call-graph/lang/java.mjs +370 -0
  109. package/pipeline/scripts/call-graph/lang/kotlin.mjs +397 -0
  110. package/pipeline/scripts/call-graph/lang/python.mjs +399 -0
  111. package/pipeline/scripts/call-graph/lang/rust.mjs +345 -0
  112. package/pipeline/scripts/call-graph/lang/shared.mjs +230 -0
  113. package/pipeline/scripts/call-graph/lang/swift.mjs +432 -0
  114. package/pipeline/scripts/call-graph/lang/typescript.mjs +692 -0
  115. package/pipeline/scripts/call-graph/lex.mjs +396 -0
  116. package/pipeline/scripts/call-graph/platform.mjs +86 -0
  117. package/pipeline/scripts/call-graph/profiles.mjs +89 -0
  118. package/pipeline/scripts/call-graph/resolve.mjs +1125 -0
  119. package/pipeline/scripts/call-graph/scan.mjs +267 -0
  120. package/pipeline/scripts/code-graph-rules/android.json +7 -2
  121. package/pipeline/scripts/code-graph-rules/cpp.json +99 -0
  122. package/pipeline/scripts/code-graph-rules/csharp.json +102 -0
  123. package/pipeline/scripts/code-graph-rules/go.json +2 -1
  124. package/pipeline/scripts/code-graph-rules/ios.json +3 -1
  125. package/pipeline/scripts/code-graph-rules/java.json +76 -0
  126. package/pipeline/scripts/code-graph-rules/node.json +7 -2
  127. package/pipeline/scripts/code-graph-rules/python.json +6 -2
  128. package/pipeline/scripts/code-graph-rules/rust.json +105 -0
  129. package/pipeline/scripts/contract-server.mjs +1 -0
  130. package/pipeline/scripts/feedback-send.mjs +26 -26
  131. package/pipeline/scripts/gate-ledger.mjs +2 -1
  132. package/pipeline/scripts/gen-usage-names.mjs +124 -0
  133. package/pipeline/scripts/graph-affected.mjs +109 -20
  134. package/pipeline/scripts/graph-build.mjs +95 -15
  135. package/pipeline/scripts/graph-export.mjs +272 -0
  136. package/pipeline/scripts/graph-hint.mjs +15 -2
  137. package/pipeline/scripts/graph-query.mjs +305 -26
  138. package/pipeline/scripts/graph-report.mjs +187 -1
  139. package/pipeline/scripts/health-report.mjs +3 -4
  140. package/pipeline/scripts/infra/docs.mjs +317 -0
  141. package/pipeline/scripts/infra/extract.mjs +998 -0
  142. package/pipeline/scripts/infra/graph.mjs +245 -0
  143. package/pipeline/scripts/infra/yaml-lite.mjs +311 -0
  144. package/pipeline/scripts/job-launch.mjs +67 -2
  145. package/pipeline/scripts/learning-curve.mjs +288 -178
  146. package/pipeline/scripts/log-metric.sh +10 -1
  147. package/pipeline/scripts/note-agent-event.mjs +3 -4
  148. package/pipeline/scripts/note-command-use.mjs +333 -0
  149. package/pipeline/scripts/note-command-use.sh +126 -0
  150. package/pipeline/scripts/note-mcp-call.sh +89 -0
  151. package/pipeline/scripts/note-mcp-failure.mjs +272 -1
  152. package/pipeline/scripts/note-session.sh +62 -3
  153. package/pipeline/scripts/note-skill-use.mjs +58 -2
  154. package/pipeline/scripts/office-build.mjs +115 -1
  155. package/pipeline/scripts/office-memory.mjs +14 -5
  156. package/pipeline/scripts/pair.mjs +333 -0
  157. package/pipeline/scripts/pre-push-check.sh +1 -1
  158. package/pipeline/scripts/remote/cbor.mjs +128 -0
  159. package/pipeline/scripts/remote/contract.mjs +98 -0
  160. package/pipeline/scripts/remote/handler.mjs +317 -0
  161. package/pipeline/scripts/remote/handles.mjs +57 -0
  162. package/pipeline/scripts/remote/lifecycle.mjs +186 -0
  163. package/pipeline/scripts/remote/listener.mjs +204 -0
  164. package/pipeline/scripts/remote/lockout.mjs +103 -0
  165. package/pipeline/scripts/remote/nonces.mjs +61 -0
  166. package/pipeline/scripts/remote/pairing.mjs +519 -0
  167. package/pipeline/scripts/remote/qr-encode.mjs +459 -0
  168. package/pipeline/scripts/remote/store.mjs +188 -0
  169. package/pipeline/scripts/remote/transport.mjs +211 -0
  170. package/pipeline/scripts/remote/verbs.json +70 -0
  171. package/pipeline/scripts/remote/verbs.mjs +217 -0
  172. package/pipeline/scripts/remote/webauthn.mjs +169 -0
  173. package/pipeline/scripts/remote/wire.mjs +364 -0
  174. package/pipeline/scripts/remote-listener.mjs +83 -0
  175. package/pipeline/scripts/route-learn.mjs +4 -4
  176. package/pipeline/scripts/run-kill.mjs +1 -1
  177. package/pipeline/scripts/run-write.mjs +13 -2
  178. package/pipeline/scripts/runs-index.mjs +30 -3
  179. package/pipeline/scripts/search-logs.sh +9 -0
  180. package/pipeline/scripts/session-brief.mjs +458 -0
  181. package/pipeline/scripts/session-brief.sh +130 -0
  182. package/pipeline/scripts/test-gap-rules/cpp.json +25 -0
  183. package/pipeline/scripts/test-gap-rules/csharp.json +20 -0
  184. package/pipeline/scripts/test-gap-rules/java.json +20 -0
  185. package/pipeline/scripts/test-gap-rules/rust.json +14 -0
  186. package/pipeline/scripts/token-budget-report.mjs +3 -2
  187. package/pipeline/scripts/uninstall.mjs +29 -0
  188. package/pipeline/scripts/usage-access.mjs +16 -31
  189. package/pipeline/scripts/usage-health.mjs +31 -62
  190. package/pipeline/scripts/usage-register-beacon.mjs +11 -22
  191. package/pipeline/scripts/usage-register.mjs +39 -29
  192. package/pipeline/scripts/usage-report.mjs +579 -178
  193. package/pipeline/scripts/validate-code-graph.mjs +361 -111
  194. package/pipeline/scripts/write-state.mjs +39 -0
  195. package/pipeline/skills/.skill-manifest.json +21 -17
  196. package/pipeline/skills/.skills-index.json +13 -2
  197. package/pipeline/skills/shared/README.md +5 -4
  198. package/pipeline/skills/shared/core/multi-agent-design-check/SKILL.md +1 -1
  199. package/pipeline/skills/shared/core/multi-agent-diff-explain/SKILL.md +3 -3
  200. package/pipeline/skills/shared/core/multi-agent-graph/SKILL.md +55 -21
  201. package/pipeline/skills/shared/core/multi-agent-pair/SKILL.md +41 -0
  202. package/pipeline/skills/shared/core/multi-agent-prune-prompts/SKILL.md +1 -1
  203. package/pipeline/skills/shared/core/multi-agent-sync/SKILL.md +3 -3
  204. package/pipeline/skills/shared/external/app-store-optimization/SKILL.md +2 -3
  205. package/pipeline/skills/shared/external/app-store-optimization/references/keyword-research-methodology.md +2 -2
  206. package/pipeline/skills/shared/external/app-store-optimization/references/product-page-variants.md +2 -2
  207. package/pipeline/skills/shared/external/app-store-review/SKILL.md +11 -4
  208. package/pipeline/skills/shared/external/build-settings-audit/SKILL.md +1 -1
  209. package/pipeline/skills/shared/external/build-time-benchmark/SKILL.md +5 -5
  210. package/pipeline/skills/shared/external/build-time-fixes/SKILL.md +5 -5
  211. package/pipeline/skills/shared/external/build-time-optimizer/SKILL.md +6 -6
  212. package/pipeline/skills/shared/external/free-llm-apis/references/providers.md +1 -0
  213. package/pipeline/skills/shared/external/ios-coding-standard/references/STANDARD.md +2 -2
  214. package/pipeline/skills/shared/external/ios-haptics/references/core-haptics.md +1 -1
  215. package/pipeline/skills/shared/external/localization-reuse-map/references/publish-and-snapshot.md +1 -1
  216. package/pipeline/skills/shared/external/package-build-audit/SKILL.md +3 -3
  217. package/pipeline/skills/shared/external/reverse-engineer-own-app/SKILL.md +2 -3
  218. package/pipeline/skills/shared/external/swift-compile-hotspots/SKILL.md +2 -2
  219. package/pipeline/skills/shared/external/weatherkit/SKILL.md +5 -6
  220. package/pipeline/skills/skills-index.md +3 -2
  221. package/docs/FIGMA_PIPELINE.md +0 -137
  222. package/pipeline/lib/identifier-scan.mjs +0 -156
  223. package/pipeline/scripts/publish-staged.mjs +0 -324
  224. package/pipeline/skills/shared/external/ios-coding-standard/scripts/check_structure.py +0 -765
@@ -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
+ }
@@ -1,141 +1,129 @@
1
- // _http-post.mjs - POST a JSON body, falling back to curl when Node's fetch
2
- // cannot reach the host at all.
1
+ // _http-post.mjs - POST a JSON body through node:https, with certificate
2
+ // verification that the environment cannot weaken.
3
3
  //
4
- // Node's built-in fetch ignores HTTPS_PROXY and trusts only its bundled CA
5
- // list, so behind a corporate proxy or a TLS-inspecting gateway it fails with
6
- // ECONNREFUSED, ENOTFOUND or SELF_SIGNED_CERT_IN_CHAIN while gh, git and curl on
7
- // the same machine work. curl honours the proxy variables and the system trust
8
- // store, so a transport failure (never an HTTP status) is retried through it.
4
+ // Every usage send (the run record, the lifecycle record, registration, the
5
+ // access check, the failure beacon and feedback) carries a bearer token or a
6
+ // login, so the transport is fixed rather than negotiated:
9
7
  //
10
- // Secret headers never reach argv: curl reads them from a 0600 file that is
11
- // removed before this returns. Redirects are never followed by either path.
8
+ // - node:https with an explicit `rejectUnauthorized: true` on the request and
9
+ // on a dedicated agent. NODE_TLS_REJECT_UNAUTHORIZED=0 does not apply to an
10
+ // option that is set explicitly.
11
+ // - The dedicated agent is not the global one, so an environment proxy
12
+ // (HTTPS_PROXY, NODE_USE_ENV_PROXY) is not used.
13
+ // - No second client. A transport or certificate failure is reported as it
14
+ // is; it is never retried through curl or anything else, which is how a
15
+ // CURL_CA_BUNDLE or SSL_CERT_FILE pointing at an attacker's certificate
16
+ // would otherwise get the token delivered.
17
+ // - The trust store (lib/tls-trust.mjs, shared with the remote transport) is
18
+ // Node's bundled roots plus the file NODE_EXTRA_CA_CERTS names, passed to
19
+ // the agent as `ca`. NODE_EXTRA_CA_CERTS is the documented
20
+ // way to trust a corporate TLS-inspecting CA; SSL_CERT_FILE, SSL_CERT_DIR
21
+ // and the other ways of adding trust are not applied to these requests.
22
+ //
23
+ // node:https is part of every supported Node (engines >= 20.11), so there is
24
+ // nothing to fall back to. Redirects are never followed. Plain http is allowed
25
+ // for a loopback address only.
26
+
27
+ import http from "node:http";
28
+ import https from "node:https";
29
+ import { trustedRoots } from "../lib/tls-trust.mjs";
30
+
31
+ const MAX_BODY = 1024 * 1024;
32
+ const LOOPBACK = new Set(["127.0.0.1", "localhost", "[::1]", "::1"]);
12
33
 
13
- import { spawn as spawnChild } from "node:child_process";
14
- import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
15
- import { tmpdir } from "node:os";
16
- import { join } from "node:path";
34
+ const agent = new https.Agent({ rejectUnauthorized: true, keepAlive: false, ca: trustedRoots() });
17
35
 
18
- /** The low-level reason a fetch failed, e.g. ECONNREFUSED or SELF_SIGNED_CERT_IN_CHAIN. */
36
+ /** The low-level reason a request failed, e.g. ECONNREFUSED or SELF_SIGNED_CERT_IN_CHAIN. */
19
37
  export function failureCode(err, aborted = false) {
20
38
  if (aborted) return "timeout";
21
39
  return String(err?.cause?.code ?? err?.code ?? err?.name ?? "error").slice(0, 40);
22
40
  }
23
41
 
24
- function run(spawn, cmd, args, input, timeoutMs) {
25
- return new Promise((resolve) => {
26
- let stdout = "";
27
- let child;
28
- try {
29
- child = spawn(cmd, args, { stdio: ["pipe", "pipe", "ignore"] });
30
- } catch (error) {
31
- resolve({ error });
32
- return;
33
- }
34
- const timer = setTimeout(() => child.kill("SIGKILL"), timeoutMs);
35
- child.stdout.on("data", (c) => (stdout += c));
36
- child.on("error", (error) => {
37
- clearTimeout(timer);
38
- resolve({ error });
39
- });
40
- child.on("close", (status) => {
41
- clearTimeout(timer);
42
- resolve({ status, stdout });
43
- });
44
- child.stdin.end(input);
45
- });
42
+ function target(url) {
43
+ let u;
44
+ try {
45
+ u = new URL(url);
46
+ } catch {
47
+ return null;
48
+ }
49
+ if (u.protocol === "https:") return { u, secure: true };
50
+ if (u.protocol === "http:" && LOOPBACK.has(u.hostname)) return { u, secure: false };
51
+ return null;
46
52
  }
47
53
 
48
54
  /**
49
- * One POST through curl. Returns { status, body, location, transport: "curl" }
50
- * or { failure, transport: "curl" } when curl is missing or cannot connect.
55
+ * One POST. Resolves { status, body, location }; rejects with an error whose
56
+ * `code` says why no HTTP answer came (`timeout`, `scheme-not-allowed`,
57
+ * `too-large` for an answer over 1 MB, which also closes the socket, or the
58
+ * socket or certificate error's own code).
51
59
  */
52
- export async function curlPost({ url, headers = {}, body, timeoutMs, spawn = spawnChild }) {
53
- const dir = mkdtempSync(join(tmpdir(), "ma-http-"));
54
- const headerFile = join(dir, "headers");
55
- try {
56
- const lines = Object.entries(headers).map(([k, v]) => `${k}: ${v}`);
57
- writeFileSync(headerFile, lines.join("\n") + "\n", { mode: 0o600 });
58
- const seconds = String(Math.max(1, Math.ceil(timeoutMs / 1000)));
59
- const r = await run(
60
- spawn,
61
- "curl",
62
- [
63
- "-sS",
64
- "--max-time",
65
- seconds,
66
- "-X",
67
- "POST",
68
- "-H",
69
- `@${headerFile}`,
70
- "--data-binary",
71
- "@-",
72
- "-w",
73
- "\n%{http_code} %{redirect_url}",
74
- url,
75
- ],
76
- body,
77
- timeoutMs + 2000,
78
- );
79
- if (r.error) return { failure: failureCode(r.error), transport: "curl" };
80
- if (r.status !== 0) {
81
- return { failure: `curl-exit-${r.status}`, transport: "curl" };
60
+ export function httpsSend({ url, headers = {}, body, timeoutMs }) {
61
+ return new Promise((resolve, reject) => {
62
+ const t = target(url);
63
+ if (!t) {
64
+ reject(Object.assign(new Error("scheme not allowed"), { code: "scheme-not-allowed" }));
65
+ return;
82
66
  }
83
- const out = String(r.stdout ?? "");
84
- const cut = out.lastIndexOf("\n");
85
- const [code, location = ""] = out.slice(cut + 1).split(" ");
86
- return {
87
- status: Number(code) || 0,
88
- body: out.slice(0, cut),
89
- location: location || null,
90
- transport: "curl",
67
+ const payload = Buffer.from(String(body ?? ""), "utf8");
68
+ const options = {
69
+ method: "POST",
70
+ hostname: t.u.hostname.replace(/^\[|\]$/g, ""),
71
+ port: t.u.port || (t.secure ? 443 : 80),
72
+ path: `${t.u.pathname}${t.u.search}`,
73
+ headers: { ...headers, "Content-Length": payload.length },
74
+ ...(t.secure ? { agent, rejectUnauthorized: true } : {}),
91
75
  };
92
- } finally {
93
- rmSync(dir, { recursive: true, force: true });
94
- }
76
+ let settled = false;
77
+ const done = (fn, value) => {
78
+ if (settled) return;
79
+ settled = true;
80
+ clearTimeout(timer);
81
+ fn(value);
82
+ };
83
+ const req = (t.secure ? https : http).request(options, (res) => {
84
+ const chunks = [];
85
+ let size = 0;
86
+ res.on("data", (c) => {
87
+ size += c.length;
88
+ if (size > MAX_BODY) {
89
+ req.destroy();
90
+ done(reject, Object.assign(new Error("response too large"), { code: "too-large" }));
91
+ return;
92
+ }
93
+ chunks.push(c);
94
+ });
95
+ res.on("end", () =>
96
+ done(resolve, {
97
+ status: res.statusCode ?? 0,
98
+ body: Buffer.concat(chunks).toString("utf8"),
99
+ location: res.headers.location ?? null,
100
+ }),
101
+ );
102
+ res.on("error", (e) => done(reject, e));
103
+ });
104
+ const timer = setTimeout(() => {
105
+ req.destroy();
106
+ done(reject, Object.assign(new Error("timeout"), { code: "timeout" }));
107
+ }, timeoutMs);
108
+ req.on("error", (e) => done(reject, e));
109
+ req.end(payload);
110
+ });
95
111
  }
96
112
 
97
113
  /**
98
- * fetch first; on a transport failure, curl. Returns { status, body, location,
99
- * transport } on any HTTP answer, or { failure, fetchFailure, transport } when
100
- * neither path reached the host. `fetchFailure` keeps the original cause.
114
+ * POST a JSON body. Returns { status, body, location, transport: "https" } on
115
+ * any HTTP answer, or { failure, transport: "https" } when none came.
101
116
  */
102
- export async function postJson({
103
- url,
104
- headers = {},
105
- body,
106
- timeoutMs,
107
- fetchImpl = fetch,
108
- curl = curlPost,
109
- }) {
110
- const ctrl = new AbortController();
111
- const timer = setTimeout(() => ctrl.abort(), timeoutMs);
112
- let fetchFailure;
117
+ export async function postJson({ url, headers = {}, body, timeoutMs, send = httpsSend }) {
113
118
  try {
114
- const res = await fetchImpl(url, {
115
- method: "POST",
119
+ const r = await send({
120
+ url,
116
121
  headers: { "Content-Type": "application/json", ...headers },
117
122
  body,
118
- redirect: "manual",
119
- signal: ctrl.signal,
123
+ timeoutMs,
120
124
  });
121
- const text = await res.text().catch(() => "");
122
- return {
123
- status: res.status,
124
- body: text,
125
- location: res.headers.get("location"),
126
- transport: "fetch",
127
- };
125
+ return { status: r.status, body: r.body, location: r.location ?? null, transport: "https" };
128
126
  } catch (err) {
129
- fetchFailure = failureCode(err, ctrl.signal.aborted);
130
- } finally {
131
- clearTimeout(timer);
127
+ return { failure: failureCode(err), transport: "https" };
132
128
  }
133
- const viaCurl = await curl({
134
- url,
135
- headers: { "Content-Type": "application/json", ...headers },
136
- body,
137
- timeoutMs,
138
- });
139
- if (viaCurl.failure) return { failure: viaCurl.failure, fetchFailure, transport: "curl" };
140
- return { ...viaCurl, fetchFailure };
141
129
  }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * @file _safe-read.mjs - read a file of an untrusted tree without leaving it.
3
+ *
4
+ * A repository can hold a symbolic link to a file outside itself, a named pipe
5
+ * or a device. Opening those would read something that is not the repository
6
+ * or block forever, so a path is read only when it is a regular file whose real
7
+ * location is inside the root. A link that stays inside the root is followed.
8
+ *
9
+ * @module pipeline/scripts/_safe-read
10
+ */
11
+
12
+ import { lstatSync, readFileSync, realpathSync, statSync } from "node:fs";
13
+ import { dirname, join, sep } from "node:path";
14
+
15
+ /**
16
+ * @param {string} root - absolute repo root
17
+ * @returns {(rel: string, maxBytes?: number) => string|null} reader; null when the
18
+ * path is not a regular file inside root, is too large, or cannot be read
19
+ */
20
+ export function makeSafeReader(root) {
21
+ let realRoot;
22
+ try {
23
+ realRoot = realpathSync(root);
24
+ } catch {
25
+ return () => null;
26
+ }
27
+ const dirOk = new Map();
28
+ const inside = (abs) => abs === realRoot || abs.startsWith(realRoot + sep);
29
+ const parentInside = (abs) => {
30
+ const dir = dirname(abs);
31
+ if (dirOk.has(dir)) return dirOk.get(dir);
32
+ let ok;
33
+ try {
34
+ ok = inside(realpathSync(dir));
35
+ } catch {
36
+ ok = false;
37
+ }
38
+ dirOk.set(dir, ok);
39
+ return ok;
40
+ };
41
+ return (rel, maxBytes = Infinity) => {
42
+ const abs = join(root, rel);
43
+ try {
44
+ if (!parentInside(abs)) return null;
45
+ const link = lstatSync(abs);
46
+ let st = link;
47
+ if (link.isSymbolicLink()) {
48
+ if (!inside(realpathSync(abs))) return null;
49
+ st = statSync(abs);
50
+ }
51
+ if (!st.isFile() || st.size > maxBytes) return null;
52
+ return readFileSync(abs, "utf8");
53
+ } catch {
54
+ return null;
55
+ }
56
+ };
57
+ }