@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
@@ -3,26 +3,39 @@
3
3
  /**
4
4
  * @file graph-build.mjs - build the code graph for one repo.
5
5
  *
6
- * Full rebuild every time, by measurement rather than by principle: on the
7
- * corporate iOS app (4,311 Swift sources, 14.3 MB) the whole pass takes under
8
- * three seconds, so an incremental extraction path would add a cache file, a
9
- * staleness bug surface and a second code path to test in exchange for nothing.
6
+ * Full rebuild every time, by measurement rather than by principle: on a large
7
+ * iOS app (4,400 Swift sources, 14 MB) the whole pass takes about four seconds
8
+ * with call edges, so an incremental extraction path would add a cache
9
+ * file, a staleness bug surface and a second code path to test in exchange for
10
+ * little.
10
11
  * The manifest is still written - Phase 1 uses it to report how far behind a
11
12
  * graph is, not to rebuild a subset.
12
13
  *
13
14
  * Inputs:
14
15
  * --root <path> Repo root. Default: cwd
15
- * --stack <id> ios | android | node | python | go. Required.
16
+ * --stack <id> ios | android | node | python | go | rust | java | csharp | cpp.
17
+ * Required.
16
18
  * --out <path> Graph output. Default: ~/.claude/knowledge/<project>/code-graph.json
17
19
  * --max-nodes N Refuse to write a graph larger than this. Default: 200000.
18
20
  * Callers pass prefs.global.codeGraph.maxNodes. A tree that
19
21
  * blows past it is vendored or generated source, and writing
20
22
  * a several-hundred-megabyte file for it helps nobody, so
21
23
  * the build fails loudly instead of succeeding quietly.
24
+ * --no-calls Skip the calls sidecar (function nodes and call edges)
25
+ * --docs Also write the docs sidecar (documentation sections, rationale)
26
+ * --infra Also write the infra sidecar (Dockerfile, Compose, Kubernetes,
27
+ * Helm, Terraform, CI workflows, .env files, application config)
28
+ * The settings file code-graph.config.json beside the graph
29
+ * ({"docs": true, "infra": true, "calls": false}) sets the same
30
+ * per repo; a flag beats it.
22
31
  * --json Emit the summary as JSON instead of a line
23
32
  *
24
33
  * Output:
25
- * Writes the graph, prints a one-line summary.
34
+ * Writes the main graph (schema 1.2.0: files, symbols, modules and the
35
+ * defines / imports / references / inherits edges) and one sidecar file per
36
+ * layer next to it: code-graph.calls.json, code-graph.docs.json,
37
+ * code-graph.infra.json. A sidecar this run did not build is removed, so no
38
+ * sidecar outlives the graph it was made against. Prints a one-line summary.
26
39
  *
27
40
  * Exit codes:
28
41
  * 0 - built
@@ -32,18 +45,22 @@
32
45
  * @module pipeline/scripts/graph-build
33
46
  */
34
47
 
35
- import { readFileSync, writeFileSync, mkdirSync, existsSync } from "node:fs";
48
+ import { readFileSync, mkdirSync, existsSync } from "node:fs";
36
49
  import { execFileSync } from "node:child_process";
37
50
  import { join, dirname, resolve, basename } from "node:path";
38
51
  import { homedir } from "node:os";
39
52
  import { fileURLToPath } from "node:url";
40
53
  import {
41
54
  loadRules,
55
+ listCandidateFiles,
42
56
  listSourceFiles,
43
57
  extractFile,
44
- buildGraph,
58
+ buildGraphSet,
45
59
  diffManifest,
46
60
  } from "./_code-graph.mjs";
61
+ import { writeGraphFiles } from "./_graph-sidecars.mjs";
62
+ import { makeSafeReader } from "./_safe-read.mjs";
63
+ import { collectDocs, collectInfra } from "./infra/graph.mjs";
47
64
  import { parseArgs } from "../lib/args.mjs";
48
65
  import { exitOnHelp } from "../lib/cli-help.mjs";
49
66
 
@@ -51,6 +68,7 @@ exitOnHelp(import.meta.url);
51
68
 
52
69
  const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));
53
70
  const DEFAULT_MAX_NODES = 200000;
71
+ const MAX_ANALYSIS_MS = 240_000;
54
72
 
55
73
  export function parseFlags(argv) {
56
74
  const { flags, positionals } = parseArgs(argv, { equals: false, terminator: false });
@@ -72,11 +90,42 @@ function headCommit(root) {
72
90
  }
73
91
  }
74
92
 
93
+ export const SETTINGS_FILE = "code-graph.config.json";
94
+
95
+ /**
96
+ * Which layers to build. Calls are on unless switched off; documentation and
97
+ * infrastructure are off unless a flag or the per-repo settings file next to
98
+ * the graph (`code-graph.config.json`: {"docs": true, "infra": true, "calls": false})
99
+ * switches them on. A flag beats the file.
100
+ */
101
+ export function resolveLayers(flags, settings = {}) {
102
+ const pick = (name, fallback) =>
103
+ flags[`no-${name}`] === true
104
+ ? false
105
+ : flags[name] === true
106
+ ? true
107
+ : typeof settings[name] === "boolean"
108
+ ? settings[name]
109
+ : fallback;
110
+ return { calls: pick("calls", true), docs: pick("docs", false), infra: pick("infra", false) };
111
+ }
112
+
113
+ function readSettings(out) {
114
+ try {
115
+ const parsed = JSON.parse(readFileSync(join(dirname(out), SETTINGS_FILE), "utf8"));
116
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
117
+ } catch {
118
+ return {};
119
+ }
120
+ }
121
+
75
122
  function main() {
76
123
  const { flags } = parseFlags(process.argv.slice(2));
77
124
  const stack = flags.stack;
78
125
  if (!stack || stack === true) {
79
- process.stderr.write("graph-build: --stack <ios|android|node|python|go> required\n");
126
+ process.stderr.write(
127
+ "graph-build: --stack <ios|android|node|python|go|rust|java|csharp|cpp> required\n",
128
+ );
80
129
  process.exit(64);
81
130
  }
82
131
 
@@ -94,20 +143,37 @@ function main() {
94
143
  process.stderr.write(`graph-build: ${e.message}\n`);
95
144
  process.exit(1);
96
145
  }
146
+ const layers = resolveLayers(flags, readSettings(out));
97
147
 
98
148
  const startedAt = Date.now();
99
- const files = listSourceFiles(root, rules);
149
+ const candidates = listCandidateFiles(root);
150
+ const files = listSourceFiles(root, rules, candidates);
151
+ const readSafe = makeSafeReader(root);
100
152
  const extracted = new Map();
153
+ let analysisMs = 0;
101
154
  for (const path of files) {
155
+ const text = readSafe(path);
156
+ if (text === null) continue;
102
157
  try {
103
- extracted.set(path, extractFile(readFileSync(join(root, path), "utf8"), rules));
158
+ const began = performance.now();
159
+ extracted.set(
160
+ path,
161
+ extractFile(text, rules, layers.calls ? path : undefined, {
162
+ skipCalls: analysisMs > MAX_ANALYSIS_MS ? "total-time-budget" : null,
163
+ }),
164
+ );
165
+ analysisMs += performance.now() - began;
104
166
  } catch {
105
167
  /* unreadable file: skip, it simply does not reach the graph */
106
168
  }
107
169
  }
108
170
 
109
171
  const { manifest } = diffManifest(root, [...extracted.keys()], {});
110
- const graph = buildGraph({
172
+ const built = buildGraphSet({
173
+ infra: layers.infra ? collectInfra(root, candidates, readSafe) : null,
174
+ docs: layers.docs ? collectDocs(root, candidates, readSafe) : null,
175
+ calls: layers.calls,
176
+ known: new Set(candidates),
111
177
  root,
112
178
  stack,
113
179
  extracted,
@@ -116,6 +182,7 @@ function main() {
116
182
  baseCommit: headCommit(root),
117
183
  generatedAt: new Date().toISOString(),
118
184
  });
185
+ const graph = built.graph;
119
186
 
120
187
  const maxNodes = Number(flags["max-nodes"]) > 0 ? Number(flags["max-nodes"]) : DEFAULT_MAX_NODES;
121
188
  if (graph.stats.nodes > maxNodes) {
@@ -128,16 +195,29 @@ function main() {
128
195
  }
129
196
 
130
197
  mkdirSync(dirname(out), { recursive: true });
131
- writeFileSync(out, JSON.stringify(graph), "utf8");
198
+ writeGraphFiles(out, built);
132
199
 
133
200
  const elapsedMs = Date.now() - startedAt;
134
- const summary = { out, elapsedMs, ...graph.stats };
201
+ const layerStats = Object.fromEntries(
202
+ Object.entries(built.sidecars).map(([name, side]) => [
203
+ name,
204
+ { nodes: side.stats.nodes, edges: side.stats.edges, truncated: side.truncated },
205
+ ]),
206
+ );
207
+ const summary = { out, elapsedMs, ...graph.stats, layers: layerStats };
135
208
  if (flags.json === true) {
136
209
  process.stdout.write(JSON.stringify(summary, null, 2) + "\n");
137
210
  } else {
211
+ const calls = built.sidecars.calls;
212
+ const parts = Object.entries(built.sidecars).map(
213
+ ([name, side]) => `${name} ${side.stats.edges} edges${side.truncated ? " (TRUNCATED)" : ""}`,
214
+ );
138
215
  process.stdout.write(
139
216
  `graph-build: ${graph.stats.files} files, ${graph.stats.nodes} nodes, ` +
140
- `${graph.stats.edges} edges in ${elapsedMs}ms -> ${out}\n`,
217
+ `${graph.stats.edges} edges` +
218
+ (parts.length ? `; sidecars: ${parts.join(", ")}` : "; no sidecars") +
219
+ (calls ? ` (${calls.stats.callFilesSkipped} files not call-analysed)` : "") +
220
+ ` in ${elapsedMs}ms -> ${out}\n`,
141
221
  );
142
222
  }
143
223
  }
@@ -0,0 +1,272 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * @file graph-export.mjs - the code graph in formats other tools read.
5
+ *
6
+ * Formats:
7
+ * dot Graphviz, one node per vertex, edges labelled with their kind
8
+ * graphml GraphML for yEd, Gephi and similar
9
+ * csv nodes and edges as two CSV blocks separated by a blank line
10
+ * mermaid a flowchart; with --level module it is the architecture diagram
11
+ *
12
+ * Levels:
13
+ * symbol every node (default for dot, graphml, csv)
14
+ * file symbol edges are lifted to the files that hold their ends
15
+ * module files are grouped by their first --dirs path segments (default 2)
16
+ * and edges are summed into one weighted arrow per pair
17
+ *
18
+ * A whole graph is rarely readable, so the view is capped: when it holds more
19
+ * than --max-nodes vertices (default 300) the level is raised one step at a
20
+ * time, symbol to file to module, until it fits, and the header says so.
21
+ *
22
+ * Inputs:
23
+ * --graph <path> Graph file. Default: ~/.claude/knowledge/<cwd name>/code-graph.json
24
+ * --format <f> dot | graphml | csv | mermaid. Required.
25
+ * --level <l> symbol | file | module
26
+ * --dirs N Path segments that name a module. Default 2.
27
+ * --kind K,... Keep only these edge kinds
28
+ * --min-confidence C Drop derived edges below low | medium | high. Default: medium; low
29
+ * edges are leads and appear only when asked for
30
+ * --max-nodes N Cap, see above. Default 300.
31
+ * --out <path> Write here instead of stdout
32
+ *
33
+ * Exit codes: 0 written, 1 graph missing or unreadable, 64 usage.
34
+ *
35
+ * @module pipeline/scripts/graph-export
36
+ */
37
+
38
+ import { writeFileSync } from "node:fs";
39
+ import { resolve } from "node:path";
40
+ import { loadGraph, defaultGraphPath } from "./graph-query.mjs";
41
+ import { layerNotes } from "./_graph-sidecars.mjs";
42
+ import { parseArgs } from "../lib/args.mjs";
43
+ import { exitOnHelp } from "../lib/cli-help.mjs";
44
+
45
+ exitOnHelp(import.meta.url);
46
+
47
+ const RANK = { low: 1, medium: 2, high: 3, certain: 4 };
48
+ const RANK_NAME = ["", "low", "medium", "high", "certain"];
49
+ const LEVELS = ["symbol", "file", "module"];
50
+ const FORMATS = new Set(["dot", "graphml", "csv", "mermaid"]);
51
+
52
+ /**
53
+ * The vertices and weighted edges of the graph at a level.
54
+ *
55
+ * @param {object} graph
56
+ * @param {{level: string, dirs: number, kinds: Set<string>|null, min: number, fixedDirs?: boolean}} opts
57
+ * The module view groups by the first `dirs` directories; unless `fixedDirs`, it takes more
58
+ * until the graph has at least two modules, so a tree that keeps everything under `src/`
59
+ * still draws.
60
+ * @returns {{vertices: Map<string, {id: string, label: string, kind: string}>, edges: Map<string, {from: string, to: string, kind: string, weight: number, rank: number}>}}
61
+ * `rank` is the weakest confidence among the edges folded into one arrow (0 when none carries one).
62
+ */
63
+ export function projection(graph, opts) {
64
+ const view = project(graph, opts);
65
+ if (opts.level !== "module" || opts.fixedDirs) return view;
66
+ let dirs = opts.dirs;
67
+ let current = view;
68
+ while (current.edges.size === 0 && dirs < MAX_MODULE_DIRS) {
69
+ dirs++;
70
+ const deeper = project(graph, { ...opts, dirs });
71
+ if (deeper.edges.size === 0 && deeper.vertices.size <= current.vertices.size) break;
72
+ current = deeper;
73
+ }
74
+ return current;
75
+ }
76
+
77
+ const MAX_MODULE_DIRS = 6;
78
+
79
+ function project(graph, { level, dirs, kinds, min }) {
80
+ const byId = new Map(graph.nodes.map((n) => [n.id, n]));
81
+ const fileOf = new Map();
82
+ for (const e of graph.edges)
83
+ if (e.kind === "defines" && e.from.startsWith("file:")) fileOf.set(e.to, e.from);
84
+ const moduleOf = (path) =>
85
+ path ? path.split("/").slice(0, -1).slice(0, dirs).join("/") || "." : "(external)";
86
+
87
+ const key = (id) => {
88
+ const n = byId.get(id);
89
+ if (!n) return null;
90
+ if (level === "symbol")
91
+ return { id, label: n.owner ? `${n.owner}.${n.name}` : n.name, kind: n.symbolKind || n.kind };
92
+ const fid = n.kind === "file" ? id : fileOf.get(id) || id;
93
+ const fn = byId.get(fid) || n;
94
+ if (level === "file") return { id: fid, label: fn.path || fn.name, kind: fn.kind };
95
+ if (!fn.path) return { id: `${fn.kind}:${fn.name}`, label: fn.name, kind: fn.kind };
96
+ const m = moduleOf(fn.path);
97
+ return { id: `module:${m}`, label: m, kind: "module" };
98
+ };
99
+
100
+ const vertices = new Map();
101
+ const edges = new Map();
102
+ for (const e of graph.edges) {
103
+ if (e.kind === "defines" && level !== "symbol") continue;
104
+ if (kinds && !kinds.has(e.kind)) continue;
105
+ if (e.confidence && (RANK[e.confidence] ?? 4) < min) continue;
106
+ const a = key(e.from);
107
+ const b = key(e.to);
108
+ if (!a || !b || a.id === b.id) continue;
109
+ vertices.set(a.id, a);
110
+ vertices.set(b.id, b);
111
+ const k = `${a.id}\0${b.id}\0${e.kind}`;
112
+ const rank = RANK[e.confidence] ?? 0;
113
+ const have = edges.get(k);
114
+ if (have) {
115
+ have.weight++;
116
+ if (rank && (!have.rank || rank < have.rank)) have.rank = rank;
117
+ } else edges.set(k, { from: a.id, to: b.id, kind: e.kind, weight: 1, rank });
118
+ }
119
+ return { vertices, edges };
120
+ }
121
+
122
+ const MAX_LABEL = 300;
123
+ // eslint-disable-next-line no-control-regex
124
+ const CONTROL = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u009F\uFFFE\uFFFF]/g;
125
+
126
+ /** A graph name made safe to print anywhere: no control characters, no line breaks, bounded. */
127
+ const clean = (value) => {
128
+ const text = String(value)
129
+ .replace(/[\r\n\t\u2028\u2029]+/g, " ")
130
+ .replace(CONTROL, "");
131
+ const whole = text.toWellFormed ? text.toWellFormed() : text;
132
+ return whole.length > MAX_LABEL ? `${whole.slice(0, MAX_LABEL)}...` : whole;
133
+ };
134
+
135
+ const MERMAID_CODES = { "&": "#amp;", "<": "#lt;", ">": "#gt;", '"': "#quot;", "|": "#124;" };
136
+
137
+ /**
138
+ * Escape a name for each output syntax. A graph is built from a repository, so a
139
+ * file or symbol name is attacker-chosen text: it must not close a quoted
140
+ * string, open a markup tag, start a comment or begin a spreadsheet formula.
141
+ */
142
+ const esc = {
143
+ dot: (s) => clean(s).replace(/\\/g, "\\\\").replace(/"/g, '\\"'),
144
+ xml: (s) =>
145
+ clean(s).replace(
146
+ /[<>&"']/g,
147
+ (c) => ({ "<": "&lt;", ">": "&gt;", "&": "&amp;", '"': "&quot;", "'": "&apos;" })[c],
148
+ ),
149
+ csv: (s) => {
150
+ const raw = String(s);
151
+ let text = clean(raw);
152
+ const formula = /^[\t\r=+\-@]/.test(raw) || /^[=+\-@]/.test(text);
153
+ if (formula) text = `'${text.replace(/^\s+/, "")}`;
154
+ return formula || /[",]/.test(text) || /^\s|\s$/.test(text)
155
+ ? `"${text.replace(/"/g, '""')}"`
156
+ : text;
157
+ },
158
+ mermaid: (s) => clean(s).replace(/[&<>"|]/g, (c) => MERMAID_CODES[c]),
159
+ comment: (s) => clean(s).replace(/--/g, "- -"),
160
+ };
161
+
162
+ /**
163
+ * @param {string} format
164
+ * @param {{vertices: Map<string, object>, edges: Map<string, object>}} view
165
+ * @param {string} note - one line saying what the view is
166
+ * @returns {string}
167
+ */
168
+ export function render(format, view, note) {
169
+ const vs = [...view.vertices.values()];
170
+ const es = [...view.edges.values()];
171
+ const idx = new Map(vs.map((v, i) => [v.id, i]));
172
+ if (format === "dot") {
173
+ const L = [`// ${esc.comment(note)}`, "digraph code {", " rankdir=LR;"];
174
+ for (const v of vs)
175
+ L.push(` n${idx.get(v.id)} [label="${esc.dot(v.label)}", tooltip="${esc.dot(v.kind)}"];`);
176
+ for (const e of es) {
177
+ const w = e.weight > 1 ? ` (${e.weight})` : "";
178
+ const conf = e.rank ? ` ${RANK_NAME[e.rank]}` : "";
179
+ L.push(` n${idx.get(e.from)} -> n${idx.get(e.to)} [label="${esc.dot(e.kind + w + conf)}"];`);
180
+ }
181
+ L.push("}");
182
+ return L.join("\n") + "\n";
183
+ }
184
+ if (format === "graphml") {
185
+ const L = [
186
+ '<?xml version="1.0" encoding="UTF-8"?>',
187
+ `<!-- ${esc.comment(note)} -->`,
188
+ '<graphml xmlns="http://graphml.graphdrawing.org/xmlns">',
189
+ ' <key id="label" for="node" attr.name="label" attr.type="string"/>',
190
+ ' <key id="kind" for="node" attr.name="kind" attr.type="string"/>',
191
+ ' <key id="ekind" for="edge" attr.name="kind" attr.type="string"/>',
192
+ ' <key id="weight" for="edge" attr.name="weight" attr.type="int"/>',
193
+ ' <key id="confidence" for="edge" attr.name="confidence" attr.type="string"/>',
194
+ ' <graph id="G" edgedefault="directed">',
195
+ ];
196
+ for (const v of vs) {
197
+ L.push(
198
+ ` <node id="n${idx.get(v.id)}"><data key="label">${esc.xml(v.label)}</data><data key="kind">${esc.xml(v.kind)}</data></node>`,
199
+ );
200
+ }
201
+ es.forEach((e, i) => {
202
+ L.push(
203
+ ` <edge id="e${i}" source="n${idx.get(e.from)}" target="n${idx.get(e.to)}"><data key="ekind">${esc.xml(e.kind)}</data><data key="weight">${e.weight}</data>${e.rank ? `<data key="confidence">${RANK_NAME[e.rank]}</data>` : ""}</edge>`,
204
+ );
205
+ });
206
+ L.push(" </graph>", "</graphml>");
207
+ return L.join("\n") + "\n";
208
+ }
209
+ if (format === "csv") {
210
+ const L = ["id,label,kind"];
211
+ for (const v of vs) L.push([v.id, v.label, v.kind].map(esc.csv).join(","));
212
+ L.push("", "from,to,kind,weight,confidence");
213
+ for (const e of es)
214
+ L.push(
215
+ [e.from, e.to, e.kind, Number(e.weight), RANK_NAME[e.rank] || ""].map(esc.csv).join(","),
216
+ );
217
+ return L.join("\n") + "\n";
218
+ }
219
+ const L = [`%% ${esc.comment(note)}`, "flowchart LR"];
220
+ for (const v of vs) L.push(` n${idx.get(v.id)}["${esc.mermaid(v.label)}"]`);
221
+ for (const e of es) {
222
+ const w = e.weight > 1 ? ` x${e.weight}` : "";
223
+ const conf = e.rank ? ` ${RANK_NAME[e.rank]}` : "";
224
+ L.push(` n${idx.get(e.from)} -->|${esc.mermaid(e.kind + w + conf)}| n${idx.get(e.to)}`);
225
+ }
226
+ return L.join("\n") + "\n";
227
+ }
228
+
229
+ function main() {
230
+ const { flags } = parseArgs(process.argv.slice(2), { equals: false, terminator: false });
231
+ const format = flags.format;
232
+ if (typeof format !== "string" || !FORMATS.has(format)) {
233
+ process.stderr.write("graph-export: --format dot|graphml|csv|mermaid required\n");
234
+ process.exit(64);
235
+ }
236
+ const path = flags.graph && flags.graph !== true ? resolve(flags.graph) : defaultGraphPath();
237
+ let graph;
238
+ try {
239
+ graph = loadGraph(path);
240
+ } catch (e) {
241
+ process.stderr.write(`graph-export: ${e.message}\n`);
242
+ process.exit(1);
243
+ }
244
+ const requested =
245
+ typeof flags.level === "string" ? flags.level : format === "mermaid" ? "module" : "symbol";
246
+ if (!LEVELS.includes(requested)) {
247
+ process.stderr.write("graph-export: --level symbol|file|module\n");
248
+ process.exit(64);
249
+ }
250
+ const opts = {
251
+ dirs: Number(flags.dirs) > 0 ? Number(flags.dirs) : 2,
252
+ fixedDirs: Number(flags.dirs) > 0,
253
+ kinds: typeof flags.kind === "string" ? new Set(flags.kind.split(",")) : null,
254
+ min: RANK[flags["min-confidence"]] || RANK.medium,
255
+ };
256
+ const cap = Number(flags["max-nodes"]) > 0 ? Number(flags["max-nodes"]) : 300;
257
+ let level = LEVELS.indexOf(requested);
258
+ let view = projection(graph, { ...opts, level: LEVELS[level] });
259
+ while (view.vertices.size > cap && level < LEVELS.length - 1) {
260
+ level++;
261
+ view = projection(graph, { ...opts, level: LEVELS[level] });
262
+ }
263
+ const raised =
264
+ LEVELS[level] !== requested ? ` (raised from ${requested}: more than ${cap} vertices)` : "";
265
+ const note = `${LEVELS[level]} view of ${graph.stack} graph, ${view.vertices.size} vertices, ${view.edges.size} edges${raised}`;
266
+ const text = render(format, view, note);
267
+ for (const n of layerNotes(graph)) process.stderr.write(`graph-export: note: ${n}\n`);
268
+ if (typeof flags.out === "string") writeFileSync(resolve(flags.out), text, "utf8");
269
+ else process.stdout.write(text);
270
+ }
271
+
272
+ if (process.argv[1] && process.argv[1].endsWith("graph-export.mjs")) main();
@@ -9,7 +9,8 @@
9
9
  * and an extension allowed, with no narrower path) and a current code graph
10
10
  * exists for the repository, it adds one line of additionalContext naming
11
11
  * `/multi-agent:graph ask` and the toolkit's graph query tool, which return
12
- * ranked definitions and their neighbours within a token budget.
12
+ * ranked definitions and their neighbours within a token budget, and names up
13
+ * to three nodes of the graph that carry exactly that name.
13
14
  *
14
15
  * "Current" is graphFreshness() from _diff-impact.mjs, the check
15
16
  * graph-affected.mjs reports: the build commit is HEAD and no indexed file
@@ -42,6 +43,7 @@ import { exitOnHelp } from "../lib/cli-help.mjs";
42
43
  exitOnHelp(import.meta.url);
43
44
 
44
45
  const MAX_INPUT = 256 * 1024;
46
+ const MAX_NAMED = 3;
45
47
  const IDENT = /^[A-Za-z_][A-Za-z0-9_]{2,63}$/;
46
48
  const GLOB_IDENT = /^(?:\*\*\/)?\*?([A-Za-z_][A-Za-z0-9_]{2,63})\*?(?:\.[A-Za-z0-9*]+)?$/;
47
49
 
@@ -158,8 +160,19 @@ export function answer(
158
160
  return null;
159
161
  }
160
162
  if (!saveState(session, { hinted: true })) return null;
163
+ const known = (graph.nodes || [])
164
+ .filter((n) => n.name === ident && n.kind !== "module")
165
+ .slice(0, MAX_NAMED);
166
+ const named = known.length
167
+ ? ` The graph holds ${known
168
+ .map(
169
+ (n) =>
170
+ `${n.owner ? `${n.owner}.` : ""}${n.name} (${n.symbolKind || n.kind}) ${n.path || ""}${n.line ? `:${n.line}` : ""}`,
171
+ )
172
+ .join("; ")}.`
173
+ : "";
161
174
  const text =
162
- `A current code graph exists for ${repo.slug}. For a symbol or concept search such as ` +
175
+ `A current code graph exists for ${repo.slug}.${named} For a symbol or concept search such as ` +
163
176
  `\`${ident}\`, \`/multi-agent:graph ask "${ident}"\` or the toolkit tool ` +
164
177
  `mcp__multi-agent__graph_query returns ranked definitions and their neighbours ` +
165
178
  `within a token budget. Grep stays the right tool for an exact text match.`;