@geml/geml 1.1.1 → 1.4.2

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.
package/codemap/build.mjs CHANGED
@@ -1,354 +1,609 @@
1
- #!/usr/bin/env node
2
- // geml-code-graph build — one shot: adapter → exchange format (build/) → GEML tree (graph/).
3
- //
4
- // geml codemap build --root <repo-root> # AUTO: detect languages,
5
- // # run the right indexer(s), merge into one map
6
- // geml codemap build --db <graph.db> --root <repo-root> # crg
7
- // geml codemap build --adapter joern --raw <dir> \
8
- // --adapter scip --raw <index.scip> --root <repo> # merged multi-language
9
- // geml codemap build --adapter joern --raw <dir> --root <repo-root> # joern
10
- // [--out .geml-code-graph] [--build .geml-code-graph/_build]
11
- // [--container module|dir|file] container granularity (default dir)
12
- // [--lang <JAVASRC|NEWC|…>] force the Joern frontend (auto mode,
13
- // mixed-majority repos)
14
- // [--joern <path>] Joern install (auto mode): the launcher OR the
15
- // unzipped joern-cli dir; else GEML_JOERN, else PATH
16
- // [--history [-m "msg"]] snapshot changed docs into .gemlhistory
17
- // sidecars (per-node history + revert)
18
- //
19
- // Auto mode (no --adapter and no --db, just --root): detect.mjs picks the
20
- // indexer per language from manifests + source extensions, we run scip
21
- // (npx @sourcegraph/scip-typescript) and/or Joern (joern-export.sc) into
22
- // <out>/_build/, then feed the results into the SAME merge as the explicit
23
- // --adapter path, and record the replay recipe into _index/refresh.json.
24
- //
25
- // Output shape: docs/codemap-profile.md — one document per container (single
26
- // meta with module/src/entry, empty-body code blocks with src=/anchor=, and
27
- // the #calls / #called-by / #unresolved CSV edge tables). Verify with
28
- // geml codemap verify (geml check + profile reference checks).
29
- //
30
- // Adapters (docs/DESIGN-geml-code-graph.md §3):
31
- // crg code-review-graph SQLite graph.db (tree-sitter level; everything
32
- // honestly labelled resolution:"heuristic") [P0, default]
33
- // joern Joern CPG export: run geml-parser/codemap/joern-export.sc inside
34
- // joern first; --raw points at its outDir [P1]
35
- //
36
- // After building, run: geml codemap verify <out-dir>
37
- import { writeFileSync, mkdirSync, existsSync, readFileSync, statSync } from "node:fs";
38
- import { join, resolve, basename, dirname, relative } from "node:path";
39
- import { fileURLToPath } from "node:url";
40
- import { execFileSync, spawnSync } from "node:child_process";
41
- import { emit } from "./emit.mjs";
42
- import { makeExcluder } from "./exclude.mjs";
43
- import { detectLanguages, indexerCommand, collectSourceFiles } from "./detect.mjs";
44
-
45
- const args = process.argv.slice(2);
46
- const flag = (name, dflt) => {
47
- const i = args.indexOf(name);
48
- return i >= 0 ? args[i + 1] : dflt;
49
- };
50
-
51
- const root = flag("--root");
52
- const outDir = resolve(flag("--out", ".geml-code-graph"));
53
- // Intermediates live INSIDE the codemap dir (alongside _index) so a build
54
- // leaves nothing scattered at the repo root `.geml-code-graph/_build/`.
55
- const buildDir = resolve(flag("--build", join(outDir, "_build")));
56
-
57
- // Adapter inputs are REPEATABLE — one codemap can merge several extractions
58
- // (e.g. Joern for the Java modules + SCIP for the TypeScript ones). Each
59
- // `--adapter X` opens a group; the following `--db`/`--raw` belongs to it.
60
- // A bare `--db` without `--adapter` keeps the historical crg default.
61
- const inputs = [];
62
- {
63
- let cur = null;
64
- for (let i = 0; i < args.length; i++) {
65
- if (args[i] === "--adapter") { cur = { adapter: args[++i] }; inputs.push(cur); }
66
- else if (args[i] === "--db") { if (!cur) { cur = { adapter: "crg" }; inputs.push(cur); } cur.db = args[++i]; cur = null; }
67
- else if (args[i] === "--raw") { if (!cur) { console.error("--raw needs a preceding --adapter"); process.exit(2); } cur.raw = args[++i]; cur = null; }
68
- }
69
- }
70
- // ---- auto-detect mode -------------------------------------------------------
71
- // A --root with NO --adapter and NO --db (inputs still empty): detect the
72
- // languages ourselves, run the right indexer(s) into <out>/_build/, then push
73
- // the results into `inputs` so the merge below runs UNCHANGED. This is the
74
- // one-command onboarding path; the explicit --adapter/--db paths are untouched.
75
- let recordRecipe = null; // { rootAbs, steps } — written to refresh.json after emit
76
- if (root && !inputs.length) {
77
- const rootAbs = resolve(root);
78
- const excludeGlobs0 = args.flatMap((v, i) => (args[i - 1] === "--exclude" ? [v] : []));
79
- const { files, manifests } = collectSourceFiles(rootAbs);
80
- const excluder = makeExcluder({
81
- root: rootAbs, globs: excludeGlobs0, gitignore: !args.includes("--no-gitignore"),
82
- files: [...files, ...manifests], exec: execFileSync,
83
- });
84
- const jobs = detectLanguages(rootAbs, { files, manifests, excluder });
85
-
86
- // --lang forces the Joern frontend (GEML_LANG) the escape hatch for a
87
- // mixed repo whose majority language isn't the one you want. Joern jobs only.
88
- const langOverride = flag("--lang");
89
- if (langOverride) {
90
- const L = langOverride.toUpperCase();
91
- const touched = jobs.filter((j) => j.indexer === "joern");
92
- for (const j of touched) { j.gemlLang = L; j.signal += ` --lang ${L}`; }
93
- if (!touched.length) console.error(`--lang ${langOverride}: no Joern language detected to override (ignored)`);
94
- }
95
-
96
- if (!jobs.length) {
97
- console.error(`could not auto-detect a supported language under ${rootAbs}.`);
98
- console.error("supported: TypeScript/JS (scip); Java, C, Python, Go, Kotlin (joern).");
99
- console.error("pass an explicit --adapter scip|joern --raw <in> or --db <graph.db> instead (geml codemap build --help).");
100
- process.exit(1);
101
- }
102
-
103
- // Shell-quote a single token so a spaced path (e.g. C:\Program Files\…) or
104
- // the codemap dir survives cmd.exe / sh word-splitting.
105
- const q = (s) => (/[\s"]/.test(String(s)) ? `"${String(s).replace(/"/g, '\\"')}"` : String(s));
106
- // Run a command PORTABLY: on Windows go through cmd.exe (shell) so npx.cmd /
107
- // joern.bat resolve, quoting each token so spaced paths survive; on unix exec
108
- // the binary directly (execvp searches PATH, no quoting pitfalls). Mirrors the
109
- // `shell: process.platform === "win32"` pattern verify.mjs uses.
110
- const runCmd = (argv, opts = {}) =>
111
- (process.platform === "win32"
112
- ? spawnSync(argv.map(q).join(" "), { shell: true, ...opts })
113
- : spawnSync(argv[0], argv.slice(1), opts));
114
-
115
- // Resolve the Joern launcher, honoring an explicit install location so users
116
- // (Windows especially) need not put joern on PATH. A --joern / GEML_JOERN
117
- // value may be the launcher itself OR the unzipped joern-cli DIRECTORY holding
118
- // it (joern.bat on Windows, joern on unix). Tried in order — --joern flag,
119
- // then GEML_JOERN, then `joern` on PATH — and the first that answers
120
- // `--version` wins. GEML_SRC/GEML_OUT/GEML_LANG always pass as ENV VARS, never
121
- // --param (the Windows joern.bat -> repl-bridge hop mangles --param).
122
- const launcherName = process.platform === "win32" ? "joern.bat" : "joern";
123
- const asLauncher = (v) => {
124
- try { if (statSync(v).isDirectory()) return join(v, launcherName); } catch { /* not a dir: a launcher path or bare command */ }
125
- return v;
126
- };
127
- let joernBin = null;
128
- const joernJobs = jobs.filter((j) => j.indexer === "joern");
129
- if (joernJobs.length) {
130
- for (const cand of [flag("--joern"), process.env.GEML_JOERN, "joern"].filter((v) => v)) {
131
- const bin = asLauncher(cand);
132
- const r = runCmd([bin, "--version"], { stdio: "ignore" });
133
- if (!r.error && r.status === 0) { joernBin = bin; break; }
134
- }
135
- if (!joernBin) {
136
- const langs = [...new Set(joernJobs.map((j) => j.language))].join(", ");
137
- console.error(
138
- `Joern is required for ${langs} but was not found (looked at --joern, GEML_JOERN, then PATH).\n`
139
- + "Install one and retry:\n"
140
- + " macOS/Linux:\n"
141
- + " mkdir joern && cd joern\n"
142
- + ' curl -L "https://github.com/joernio/joern/releases/latest/download/joern-install.sh" -o joern-install.sh\n'
143
- + " chmod +x joern-install.sh && ./joern-install.sh\n"
144
- + " Windows:\n"
145
- + " download joern-cli.zip from https://github.com/joernio/joern/releases , unzip it, then\n"
146
- + " add that folder to PATH or pass --joern <unzipped-folder>\n"
147
- + "Docs: https://docs.joern.io/installation",
148
- );
149
- process.exit(1);
150
- }
151
- }
152
-
153
- // Transparent plan before doing any slow work.
154
- console.error(`detected: ${jobs.map((j) => `${j.language} (${j.signal}) -> ${j.indexer}${j.gemlLang ? `[${j.gemlLang}]` : ""}`).join("; ")}`);
155
-
156
- const scriptPath = resolve(dirname(fileURLToPath(import.meta.url)), "joern-export.sc");
157
- const scriptPosix = scriptPath.replace(/\\/g, "/");
158
- const relToRoot = (p) => (relative(rootAbs, p).replace(/\\/g, "/") || ".");
159
- mkdirSync(buildDir, { recursive: true });
160
- const indexSteps = [];
161
-
162
- console.error("indexing...");
163
- for (const job of jobs) {
164
- const cmd = indexerCommand(job, { root: rootAbs, buildDir, scriptPath });
165
- // scip runs the npx launcher; joern runs the resolved launcher. Env
166
- // (GEML_SRC/OUT/LANG for joern) rides through the spawn options.
167
- const argv = [job.indexer === "joern" ? joernBin : cmd.argv[0], ...cmd.argv.slice(1)];
168
- const r = runCmd(argv, {
169
- cwd: cmd.cwd, stdio: "inherit",
170
- env: cmd.env ? { ...process.env, ...cmd.env } : process.env,
171
- });
172
- if (r.error || r.status !== 0) {
173
- console.error(`indexer failed for ${job.language} (${job.indexer}): ${r.error ? r.error.message : `exit ${r.status}`}`);
174
- process.exit(1);
175
- }
176
- inputs.push({ adapter: cmd.adapter, raw: cmd.raw });
177
- // Recipe step (paths relative to <root>, the cwd refresh replays in). The
178
- // Joern env is written in the RECORDING host's native shell syntax —
179
- // refresh.json is machine-local (it re-invokes locally-installed indexers),
180
- // and cmd.exe ignores the POSIX `VAR=val cmd` prefix.
181
- if (job.indexer === "scip") {
182
- indexSteps.push(`npx --yes @sourcegraph/scip-typescript index --output ${relToRoot(cmd.raw)}`);
183
- } else {
184
- const relOut = relToRoot(cmd.raw);
185
- indexSteps.push(process.platform === "win32"
186
- ? `set "GEML_SRC=." && set "GEML_OUT=${relOut}" && set "GEML_LANG=${job.gemlLang}" && joern --script ${q(scriptPosix)}`
187
- : `GEML_SRC=. GEML_OUT=${relOut} GEML_LANG=${job.gemlLang} joern --script ${q(scriptPosix)}`);
188
- }
189
- }
190
- console.error("merging...");
191
- recordRecipe = { rootAbs, indexSteps };
192
- }
193
-
194
- const bad = inputs.find((s) => !["crg", "joern", "scip"].includes(s.adapter) || (s.adapter === "crg" ? !s.db : !s.raw));
195
- if (!root || !inputs.length || bad) {
196
- console.error("usage: geml codemap build --root <repo-root> # auto-detect languages, index, and merge");
197
- console.error(" or: geml codemap build (--db <graph.db> | --adapter joern|scip --raw <dir|index.scip>)+ --root <repo-root> [--out .geml-code-graph] [--build .geml-code-graph/_build] [--container module|dir|file] [--lang <LANG>] [--joern <path>] [--exclude <glob>]... [--no-gitignore] [--history [-m msg]]");
198
- process.exit(2);
199
- }
200
-
201
- // Extract every input and concatenate — anchors are namespaced by language and
202
- // path, so inputs don't collide; identical anchors across inputs are dropped
203
- // with a warning (first input wins).
204
- const symbols = [];
205
- const edges = [];
206
- const seenAnchors = new Set();
207
- for (const spec of inputs) {
208
- const { extract } = await import(`./adapters/${spec.adapter}.mjs`);
209
- const r = extract(spec.adapter === "crg" ? { db: spec.db, root } : { raw: spec.raw, root });
210
- let dropped = 0;
211
- for (const s of r.symbols) {
212
- if (seenAnchors.has(s.anchor)) { dropped++; continue; }
213
- seenAnchors.add(s.anchor);
214
- symbols.push(s);
215
- }
216
- for (const e of r.edges) edges.push(e);
217
- console.error(`input ${spec.adapter}: ${r.symbols.length} symbols, ${r.edges.length} edges${dropped ? ` (${dropped} duplicate anchors dropped)` : ""}`);
218
- }
219
-
220
- // Exclusion: drop symbols whose source file is git-ignored (default) or
221
- // matches an explicit --exclude glob. Vendored copies and third-party dumps
222
- // belong out of the graph; the edge tables key on surviving anchors, so
223
- // dangling references simply vanish (emit skips edges whose endpoints are
224
- // gone). --no-gitignore turns off the git-driven half.
225
- const excludeGlobs = args.flatMap((v, i) => (args[i - 1] === "--exclude" ? [v] : []));
226
- const excluder = makeExcluder({
227
- root: resolve(root),
228
- globs: excludeGlobs,
229
- gitignore: !args.includes("--no-gitignore"),
230
- files: [...new Set(symbols.map((s) => s.file))],
231
- exec: execFileSync,
232
- });
233
- const kept = symbols.filter((s) => !excluder(s.file));
234
- const excludedCount = symbols.length - kept.length;
235
- if (excludedCount) {
236
- symbols.length = 0;
237
- for (const s of kept) symbols.push(s);
238
- console.error(
239
- `excluded ${excludedCount} symbol(s) via ${!args.includes("--no-gitignore") ? ".gitignore" : "(gitignore off)"}`
240
- + `${excludeGlobs.length ? ` + ${excludeGlobs.length} --exclude glob(s)` : ""}`,
241
- );
242
- }
243
-
244
- // Exchange format on disk the layer contract (§3). Deterministic order so
245
- // the jsonl files diff cleanly across builds.
246
- symbols.sort((a, b) => a.anchor.localeCompare(b.anchor));
247
- edges.sort((a, b) =>
248
- a.from.localeCompare(b.from) || a.kind.localeCompare(b.kind)
249
- || String(a.to ?? a.to_text).localeCompare(String(b.to ?? b.to_text)));
250
- mkdirSync(buildDir, { recursive: true });
251
- const jsonl = (rows) => rows.map((r) => JSON.stringify(r)).join("\n") + "\n";
252
- const writeIfChanged = (p, content) => {
253
- if (existsSync(p) && readFileSync(p, "utf8") === content) return;
254
- writeFileSync(p, content);
255
- };
256
- writeIfChanged(join(buildDir, "symbols.jsonl"), jsonl(symbols));
257
- writeIfChanged(join(buildDir, "edges.jsonl"), jsonl(edges));
258
-
259
- // Container granularity (codemap profile): module = first path segment,
260
- // dir = containing directory (default), file = one document per source file.
261
- const containerGranularity = flag("--container", "dir");
262
- if (!["module", "dir", "file"].includes(containerGranularity)) {
263
- console.error(`--container must be module|dir|file (got '${containerGranularity}')`);
264
- process.exit(2);
265
- }
266
- // Best-effort commit stamp for index.geml meta.
267
- let commit;
268
- try {
269
- commit = execFileSync("git", ["-C", resolve(root), "rev-parse", "--short", "HEAD"], { encoding: "utf8" }).trim();
270
- } catch { /* not a git repo */ }
271
-
272
- const stats = emit({
273
- symbols, edges, outDir, buildDir,
274
- repoName: basename(resolve(root)),
275
- container: containerGranularity,
276
- commit,
277
- root: resolve(root),
278
- });
279
-
280
- console.error(
281
- `geml-code-graph: ${stats.methods} methods (${stats.symbols} symbols), ${stats.edges} edges `
282
- + `(${stats.resolved} resolved), ${stats.leaves} leaves, ${stats.entries} app entries -> `
283
- + `${stats.containers} containers (${stats.written} of ${stats.docs} files written), `
284
- + `${(stats.bytes / 1048576).toFixed(2)} MB -> ${outDir}`,
285
- );
286
-
287
- // --history: snapshot every changed document into its .gemlhistory sidecar —
288
- // the graph's own architectural history (geml history log / revert per node).
289
- // Targets = documents rewritten this build, plus any document that has no
290
- // sidecar yet (first run, or --history adopted later).
291
- if (args.includes("--history")) {
292
- const histMod = resolve(dirname(fileURLToPath(import.meta.url)), "../dist/history.js");
293
- if (!existsSync(histMod)) {
294
- console.error("--history needs the built parser (cd geml-parser && npm install && npm run build)");
295
- process.exit(1);
296
- }
297
- const { commit, isCurrent } = await import(`file://${histMod.replace(/\\/g, "/")}`);
298
- const message = flag("-m", flag("--message", "graph build"));
299
- const targets = new Set(stats.writtenDocs);
300
- for (const d of stats.allDocs) {
301
- if (targets.has(d)) continue;
302
- const gemlPath = join(outDir, d);
303
- const sidecar = gemlPath.replace(/\.geml$/, ".gemlhistory");
304
- // No sidecar yet, or the sidecar tip drifted from the file (a previous
305
- // commit attempt was refused): both need a snapshot even though this build
306
- // did not rewrite the document.
307
- if (!existsSync(sidecar) || !isCurrent(sidecar, gemlPath)) targets.add(d);
308
- }
309
- let committed = 0;
310
- const histFailed = [];
311
- for (const d of [...targets].sort()) {
312
- const gemlPath = join(outDir, d);
313
- try {
314
- commit({ gemlPath, historyPath: gemlPath.replace(/\.geml$/, ".gemlhistory"), summary: message });
315
- committed++;
316
- } catch (e) {
317
- // One document's history refusing a commit (e.g. the round-trip gate)
318
- // must not abort the build or the other documents' snapshots. The
319
- // failing document's previous revision stays intact.
320
- histFailed.push(d);
321
- console.error(`history: ${d}: ${e.message}`);
322
- }
323
- }
324
- console.error(
325
- `history: committed ${committed} document(s) (${stats.allDocs.length - committed - histFailed.length} unchanged, skipped)`
326
- + (histFailed.length ? `; FAILED: ${histFailed.join(", ")}` : ""),
327
- );
328
- }
329
-
330
- // Auto mode records the exact replay recipe (index explicit build verify)
331
- // into _index/refresh.json on the FIRST build, so `geml codemap refresh` (and
332
- // the commit hook) can reproduce it. An existing recipe is left untouched.
333
- // Paths are relative to <root>, which is the cwd refresh runs each step in.
334
- if (recordRecipe) {
335
- const cfgPath = join(outDir, "_index", "refresh.json");
336
- if (!existsSync(cfgPath)) {
337
- const rel = (p) => (relative(recordRecipe.rootAbs, p).replace(/\\/g, "/") || ".");
338
- const relOut = rel(outDir);
339
- const buildStep = ["geml codemap build",
340
- ...inputs.map((s) => `--adapter ${s.adapter} --raw ${rel(s.raw)}`),
341
- "--root .", `--out ${relOut}`,
342
- containerGranularity !== "dir" ? `--container ${containerGranularity}` : "",
343
- args.includes("--history") ? "--history" : "",
344
- ].filter(Boolean).join(" ");
345
- const cfg = {
346
- root: relative(outDir, recordRecipe.rootAbs).replace(/\\/g, "/") || "..",
347
- steps: [...recordRecipe.indexSteps, buildStep, `geml codemap verify ${relOut}`],
348
- };
349
- mkdirSync(join(outDir, "_index"), { recursive: true });
350
- writeFileSync(cfgPath, JSON.stringify(cfg, null, 2) + "\n");
351
- console.error(`recorded build recipe -> ${cfgPath}`);
352
- }
353
- }
354
- console.error(`next: geml codemap verify ${outDir}`);
1
+ #!/usr/bin/env node
2
+ // geml-code-graph build — one shot: adapter → exchange format (build/) → GEML tree (graph/).
3
+ //
4
+ // geml codemap build --root <repo-root> # AUTO: detect languages,
5
+ // # run the right indexer(s), merge into one map
6
+ // geml codemap build --db <graph.db> --root <repo-root> # crg
7
+ // geml codemap build --adapter joern --raw <dir> \
8
+ // --adapter scip --raw <index.scip> --root <repo> # merged multi-language
9
+ // geml codemap build --adapter joern --raw <dir> --root <repo-root> # joern
10
+ // [--out .geml-code-graph] [--build .geml-code-graph/_build]
11
+ // [--container module|dir|file] container granularity (default dir)
12
+ // [--lang <JAVASRC|NEWC|…>] force the Joern frontend (auto mode,
13
+ // mixed-majority repos)
14
+ // [--joern <path>] Joern install (auto mode): the launcher OR the
15
+ // unzipped joern-cli dir; else GEML_JOERN, else PATH
16
+ // [--history [-m "msg"]] snapshot changed docs into .gemlhistory
17
+ // sidecars (per-node history + revert)
18
+ //
19
+ // Auto mode (no --adapter and no --db, just --root): detect.mjs picks the
20
+ // indexer per language from manifests + source extensions, we run scip
21
+ // (npx @sourcegraph/scip-typescript for TS/JS, rust-analyzer scip for Rust)
22
+ // and/or Joern (joern-export.sc) into <out>/_build/, then feed the results
23
+ // into the SAME merge as the explicit --adapter path, and record the replay
24
+ // recipe into _index/refresh.json.
25
+ //
26
+ // Output shape: docs/codemap-profile.md one document per container (single
27
+ // meta with module/src/entry, empty-body code blocks with src=/anchor=, and
28
+ // the #calls / #called-by / #unresolved CSV edge tables). Verify with
29
+ // geml codemap verify (geml check + profile reference checks).
30
+ //
31
+ // Adapters (docs/DESIGN-geml-code-graph.md §3):
32
+ // crg code-review-graph SQLite graph.db (tree-sitter level; everything
33
+ // honestly labelled resolution:"heuristic") [P0, default]
34
+ // joern Joern CPG export: run geml-parser/codemap/joern-export.sc inside
35
+ // joern first; --raw points at its outDir [P1]
36
+ //
37
+ // After building, run: geml codemap verify <out-dir>
38
+ import { writeFileSync, mkdirSync, existsSync, readFileSync, statSync } from "node:fs";
39
+ import { join, resolve, basename, dirname, relative } from "node:path";
40
+ import { fileURLToPath } from "node:url";
41
+ import { execFileSync, spawnSync } from "node:child_process";
42
+ import { emit } from "./emit.mjs";
43
+ import { makeExcluder } from "./exclude.mjs";
44
+ import { detectLanguages, indexerCommand, collectSourceFiles } from "./detect.mjs";
45
+ import { loadOrSeedFoldings } from "./foldings.mjs";
46
+ import { detectEntries } from "./entries.mjs";
47
+ import { discoverModuleRoots } from "./normalize.mjs";
48
+ import { recipeFingerprint, trustRecipe, RECIPE_VERSION } from "./recipe-trust.mjs";
49
+ import { buildCrossStackOverlay } from "./cross-stack.mjs";
50
+
51
+ const args = process.argv.slice(2);
52
+ const flag = (name, dflt) => {
53
+ const i = args.indexOf(name);
54
+ return i >= 0 ? args[i + 1] : dflt;
55
+ };
56
+
57
+ const USAGE = [
58
+ "usage: geml codemap build [--root <repo-root>] # auto-detect languages, index, and merge (--root defaults to the current directory)",
59
+ " or: geml codemap build (--db <graph.db> | --adapter joern|scip --raw <dir|index.scip> [--remap <virtual-dir>])+ [--root <repo-root>] [--out .geml-code-graph] [--build .geml-code-graph/_build] [--container module|dir|file] [--lang <LANG>] [--joern <path>] [--exclude <glob>]... [--no-gitignore] [--history [-m msg]]",
60
+ ].join("\n");
61
+ if (args.includes("--help") || args.includes("-h")) { console.log(USAGE); process.exit(0); }
62
+
63
+ // --root defaults to the current directory, so `geml codemap build` with no
64
+ // arguments indexes the repo you're standing in.
65
+ const root = flag("--root", ".");
66
+ const outDir = resolve(flag("--out", ".geml-code-graph"));
67
+ // Intermediates live INSIDE the codemap dir (alongside _index) so a build
68
+ // leaves nothing scattered at the repo root — `.geml-code-graph/_build/`.
69
+ const buildDir = resolve(flag("--build", join(outDir, "_build")));
70
+
71
+ // Adapter inputs are REPEATABLE one codemap can merge several extractions
72
+ // (e.g. Joern for the Java modules + SCIP for the TypeScript ones). Each
73
+ // `--adapter X` opens a group; the following `--db`/`--raw` belongs to it.
74
+ // A bare `--db` without `--adapter` keeps the historical crg default.
75
+ const inputs = [];
76
+ {
77
+ let cur = null;
78
+ for (let i = 0; i < args.length; i++) {
79
+ if (args[i] === "--adapter") { cur = { adapter: args[++i] }; inputs.push(cur); }
80
+ else if (args[i] === "--db") { if (!cur) { cur = { adapter: "crg" }; inputs.push(cur); } cur.db = args[++i]; cur = null; }
81
+ else if (args[i] === "--raw") { if (!cur) { console.error("--raw needs a preceding --adapter"); process.exit(2); } cur.raw = args[++i]; cur = null; }
82
+ // --remap <virtual dir>: the preceding scip input was produced over an
83
+ // SFC virtual dir (sfc-virtualize.mjs) — the adapter maps shadow paths
84
+ // back to the original .vue/.svelte sources. Recorded into refresh.json
85
+ // so replays keep the remapping.
86
+ else if (args[i] === "--remap") { if (!inputs.length) { console.error("--remap needs a preceding --adapter/--raw group"); process.exit(2); } inputs[inputs.length - 1].remap = args[++i]; }
87
+ }
88
+ }
89
+ // ---- auto-detect mode -------------------------------------------------------
90
+ // A --root with NO --adapter and NO --db (inputs still empty): detect the
91
+ // languages ourselves, run the right indexer(s) into <out>/_build/, then push
92
+ // the results into `inputs` so the merge below runs UNCHANGED. This is the
93
+ // one-command onboarding path; the explicit --adapter/--db paths are untouched.
94
+ let recordRecipe = null; // { rootAbs, steps } — written to refresh.json after emit
95
+ let detectedLanguages = []; // languages seen in auto-detect; seeds foldings' language conventions
96
+ let entryHints = []; // app-entry hints (entries.mjs), matched to symbols in emit
97
+ if (root && !inputs.length) {
98
+ const rootAbs = resolve(root);
99
+ const excludeGlobs0 = args.flatMap((v, i) => (args[i - 1] === "--exclude" ? [v] : []));
100
+ const { files, manifests, pkgs } = collectSourceFiles(rootAbs);
101
+ const excluder = makeExcluder({
102
+ root: rootAbs, globs: excludeGlobs0, gitignore: !args.includes("--no-gitignore"),
103
+ files: [...files, ...manifests, ...pkgs], exec: execFileSync,
104
+ });
105
+ const jobs = detectLanguages(rootAbs, { files, manifests, pkgs, excluder });
106
+ detectedLanguages = [...new Set(jobs.map((j) => j.language))];
107
+ // App-entry hints from manifests/layout/source markers pure detection now,
108
+ // matched to extracted symbols (or noted file-level) inside emit.
109
+ entryHints = detectEntries(rootAbs, {
110
+ files: files.filter((f) => !excluder(f)),
111
+ manifests: manifests.filter((m) => !excluder(m)),
112
+ pkgs: (pkgs ?? []).filter((p) => !excluder(p)),
113
+ });
114
+
115
+ // --lang forces the Joern frontend (GEML_LANG) the escape hatch for a
116
+ // mixed repo whose majority language isn't the one you want. Joern jobs only.
117
+ const langOverride = flag("--lang");
118
+ if (langOverride) {
119
+ const L = langOverride.toUpperCase();
120
+ const touched = jobs.filter((j) => j.indexer === "joern");
121
+ for (const j of touched) { j.gemlLang = L; j.signal += ` --lang ${L}`; }
122
+ if (!touched.length) console.error(`--lang ${langOverride}: no Joern language detected to override (ignored)`);
123
+ }
124
+
125
+ if (!jobs.length) {
126
+ console.error(`could not auto-detect a supported language under ${rootAbs}.`);
127
+ console.error("supported: TypeScript/JS, Rust (scip); Java, C, Python, Go, Kotlin (joern).");
128
+ console.error("pass an explicit --adapter scip|joern --raw <in> or --db <graph.db> instead (geml codemap build --help).");
129
+ process.exit(1);
130
+ }
131
+
132
+ // Space-aware quote: wrap a token in double quotes only when it contains
133
+ // whitespace or a quote. Used for (a) the PROGRAM token of a spawned command
134
+ // and (b) recording human-readable recipe steps into refresh.json. The
135
+ // program token must NOT be blanket-quoted: a bare launcher name resolved via
136
+ // PATH (npx / joern) whose .cmd/.bat shim uses %~dp0 breaks if the name is
137
+ // quoted — cmd then resolves %~dp0 against the cwd, not the shim's dir. A
138
+ // spaced launcher PATH is a full path, so quoting it keeps %~dp0 correct.
139
+ const q = (s) => (/[\s"]/.test(String(s)) ? `"${String(s).replace(/"/g, '\\"')}"` : String(s));
140
+ // Hardened quote for command ARGUMENTS on win32. Node does NOT escape args
141
+ // under shell:true it only concatenates them (Node DEP0190) — so an
142
+ // unquoted argument such as a source directory named `a&calc` reaching the
143
+ // --output path would break out of the command and run `calc`. ALWAYS wrap in
144
+ // double quotes: inside quotes cmd.exe treats & | < > ( ) ^ and whitespace as
145
+ // literal, neutralizing injection while keeping spaced paths intact. Embedded
146
+ // quotes / trailing backslash runs follow the CRT rules so the child's
147
+ // CommandLineToArgvW recovers the exact token.
148
+ const shq = (s) => `"${String(s).replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/, '$1$1')}"`;
149
+ // Run a command PORTABLY. On Windows we MUST go through cmd.exe (shell:true):
150
+ // npx.cmd / joern.bat / rust-analyzer.bat are .cmd/.bat launchers and modern
151
+ // Node refuses to spawn those with shell:false (EINVAL). Build ONE pre-escaped
152
+ // command string ourselves (never an args array — that is the unescaped
153
+ // DEP0190 path): the program via q (bare names stay bare so a shim's %~dp0
154
+ // resolves), every argument via shq (always quoted, so no argument can
155
+ // inject). On unix we exec the binary directly (no shell, no injection).
156
+ const runCmd = (argv, opts = {}) =>
157
+ (process.platform === "win32"
158
+ ? spawnSync([q(argv[0]), ...argv.slice(1).map(shq)].join(" "), { shell: true, ...opts })
159
+ : spawnSync(argv[0], argv.slice(1), opts));
160
+
161
+ // Resolve the Joern launcher, honoring an explicit install location so users
162
+ // (Windows especially) need not put joern on PATH. A --joern / GEML_JOERN
163
+ // value may be the launcher itself OR the unzipped joern-cli DIRECTORY holding
164
+ // it (joern.bat on Windows, joern on unix). Tried in order — --joern flag,
165
+ // then GEML_JOERN, then `joern` on PATH and the first that answers
166
+ // `--version` wins. GEML_SRC/GEML_OUT/GEML_LANG always pass as ENV VARS, never
167
+ // --param (the Windows joern.bat -> repl-bridge hop mangles --param).
168
+ const launcherName = process.platform === "win32" ? "joern.bat" : "joern";
169
+ const asLauncher = (v) => {
170
+ try { if (statSync(v).isDirectory()) return join(v, launcherName); } catch { /* not a dir: a launcher path or bare command */ }
171
+ return v;
172
+ };
173
+ let joernBin = null;
174
+ const joernJobs = jobs.filter((j) => j.indexer === "joern");
175
+ if (joernJobs.length) {
176
+ // Joern creates a `workspace/` CPG cache in its CWD on startup — even for
177
+ // `--version`. Probe (and, below, run) it FROM the build dir so that cache
178
+ // lands in _build/, never scattered at the repo root. buildDir must exist
179
+ // first (it is also (re)created before emit); mkdir is idempotent.
180
+ mkdirSync(buildDir, { recursive: true });
181
+ for (const cand of [flag("--joern"), process.env.GEML_JOERN, "joern"].filter((v) => v)) {
182
+ const bin = asLauncher(cand);
183
+ const r = runCmd([bin, "--version"], { stdio: "ignore", cwd: buildDir });
184
+ if (!r.error && r.status === 0) { joernBin = bin; break; }
185
+ }
186
+ if (!joernBin) {
187
+ const langs = [...new Set(joernJobs.map((j) => j.language))].join(", ");
188
+ console.error(
189
+ `Joern is required for ${langs} but was not found (looked at --joern, GEML_JOERN, then PATH).\n`
190
+ + "Install one and retry:\n"
191
+ + " macOS/Linux:\n"
192
+ + " mkdir joern && cd joern\n"
193
+ + ' curl -L "https://github.com/joernio/joern/releases/latest/download/joern-install.sh" -o joern-install.sh\n'
194
+ + " chmod +x joern-install.sh && ./joern-install.sh\n"
195
+ + " Windows:\n"
196
+ + " download joern-cli.zip from https://github.com/joernio/joern/releases , unzip it, then\n"
197
+ + " add that folder to PATH or pass --joern <unzipped-folder>\n"
198
+ + "Docs: https://docs.joern.io/installation",
199
+ );
200
+ process.exit(1);
201
+ }
202
+ }
203
+
204
+ // Same courtesy for Rust: rust-analyzer produces the SCIP index, so probe it
205
+ // BEFORE any slow work and fail with install instructions instead of a
206
+ // mid-build spawn error. (A rustup shim without the component installed also
207
+ // answers `--version` non-zero, so it lands here too.)
208
+ if (jobs.some((j) => j.language === "Rust")) {
209
+ const r = runCmd(["rust-analyzer", "--version"], { stdio: "ignore" });
210
+ if (r.error || r.status !== 0) {
211
+ console.error(
212
+ "rust-analyzer is required for Rust but was not found on PATH (or is not runnable).\n"
213
+ + "Install it and retry:\n"
214
+ + " rustup component add rust-analyzer # rustup-managed toolchains\n"
215
+ + " or download a release binary: https://github.com/rust-lang/rust-analyzer/releases\n"
216
+ + "and make sure `rust-analyzer --version` works in this shell.",
217
+ );
218
+ process.exit(1);
219
+ }
220
+ }
221
+
222
+ // Transparent plan before doing any slow work.
223
+ // A monorepo with vendored trees (next.js's src/compiled: 140 package.json
224
+ // bundles) turns the full job list into a wall — summarize past 10.
225
+ if (jobs.length > 10) {
226
+ const byLang = new Map();
227
+ for (const j of jobs) byLang.set(j.language, (byLang.get(j.language) ?? 0) + 1);
228
+ const langs = [...byLang].map(([l, n]) => (n > 1 ? `${l}×${n}` : l)).join(", ");
229
+ const sample = jobs.slice(0, 5).map((j) => j.subroot ?? j.language).join("; ");
230
+ console.error(`detected: ${jobs.length} jobs (${langs}) — e.g. ${sample}; … (vendored trees inflating this? --exclude "path/**" trims them)`);
231
+ } else {
232
+ console.error(`detected: ${jobs.map((j) => `${j.language}${j.subroot ? `[${j.subroot}]` : ""} (${j.signal}) -> ${j.indexer}${j.gemlLang ? `[${j.gemlLang}]` : ""}`).join("; ")}`);
233
+ }
234
+
235
+ const scriptPath = resolve(dirname(fileURLToPath(import.meta.url)), "joern-export.sc");
236
+ const scriptPosix = scriptPath.replace(/\\/g, "/");
237
+ const sfcScript = resolve(dirname(fileURLToPath(import.meta.url)), "sfc-virtualize.mjs");
238
+ const sfcScriptPosix = sfcScript.replace(/\\/g, "/");
239
+ const relToRoot = (p) => (relative(rootAbs, p).replace(/\\/g, "/") || ".");
240
+ mkdirSync(buildDir, { recursive: true });
241
+ // Structured recipe steps { cwd?, env?, argv:[...] } (security fix R2-1).
242
+ // Attacker-controllable sub-project dir names appear here ONLY as DISCRETE
243
+ // structured values (a step's cwd, or an argv element) — NEVER concatenated
244
+ // into a shell string at rest. refresh executes each step without building an
245
+ // attacker-influenced command line (see codemap/refresh.mjs).
246
+ const indexSteps = [];
247
+ // Build a recorded step's env map, dropping undefined values so the step's
248
+ // fingerprint stays stable (GEML_LANG is unset for scip jobs).
249
+ const envOf = (obj) => {
250
+ const env = {};
251
+ for (const [k, v] of Object.entries(obj)) if (v != null) env[k] = String(v);
252
+ return env;
253
+ };
254
+
255
+ console.error("indexing...");
256
+ const failedLangs = [];
257
+ for (const job of jobs) {
258
+ let cmd = indexerCommand(job, { root: rootAbs, buildDir, scriptPath, sfcScript });
259
+ let preStep = null;
260
+ if (cmd.pre) {
261
+ // SFC job: run the virtualizer first. If it fails (offline npx, exotic
262
+ // SFC syntax), the project must not lose its plain TS coverage — fall
263
+ // back to the sfc-less job and say the gap out loud.
264
+ const pr = runCmd(cmd.pre.argv, {
265
+ cwd: cmd.pre.cwd, stdio: "inherit",
266
+ env: { ...process.env, ...cmd.pre.env },
267
+ });
268
+ if (pr.error || pr.status !== 0) {
269
+ console.error(
270
+ `sfc virtualizer failed for ${job.language}${job.subroot ? `[${job.subroot}]` : ""} `
271
+ + `(${pr.error ? pr.error.message : `exit ${pr.status}`}) — falling back to plain TS indexing; `
272
+ + ".vue/.svelte files stay invisible until this is fixed and build re-runs.",
273
+ );
274
+ cmd = indexerCommand({ ...job, sfc: undefined }, { root: rootAbs, buildDir, scriptPath, sfcScript });
275
+ } else {
276
+ // Runs at root (cmd.pre.cwd === root), so no cwd; the virtualizer reads
277
+ // GEML_SRC/GEML_OUT (relative to root) from env. argv[-1] is the script
278
+ // path — record the forward-slash form.
279
+ preStep = {
280
+ env: envOf({ GEML_SRC: relToRoot(cmd.pre.env.GEML_SRC), GEML_OUT: relToRoot(cmd.pre.env.GEML_OUT) }),
281
+ argv: [...cmd.pre.argv.slice(0, -1), sfcScriptPosix],
282
+ };
283
+ }
284
+ }
285
+ // scip runs the npx launcher; joern runs the resolved launcher. Env
286
+ // (GEML_SRC/OUT/LANG for joern) rides through the spawn options.
287
+ const argv = [job.indexer === "joern" ? joernBin : cmd.argv[0], ...cmd.argv.slice(1)];
288
+ const r = runCmd(argv, {
289
+ cwd: cmd.cwd, stdio: "inherit",
290
+ env: cmd.env ? { ...process.env, ...cmd.env } : process.env,
291
+ });
292
+ if (r.error || r.status !== 0) {
293
+ // One language failing must not sink the others' finished work — keep
294
+ // going, build what succeeded, and say the gap out loud below. Name the
295
+ // subroot so a monorepo says WHICH project's indexer died, not just the
296
+ // language (several TS projects can each have their own scip job).
297
+ const where = job.subroot ? `${job.language} at ${job.subroot}` : job.language;
298
+ console.error(`indexer failed for ${where} (${job.indexer}): ${r.error ? r.error.message : `exit ${r.status}`}`);
299
+ failedLangs.push(job.language);
300
+ continue;
301
+ }
302
+ inputs.push({ adapter: cmd.adapter, raw: cmd.raw, remap: cmd.remapDir });
303
+ // Recipe step (paths relative to <root>, the cwd refresh replays in)
304
+ // successful steps only, so `refresh` replays a recipe that works.
305
+ if (preStep) indexSteps.push(preStep);
306
+ if (job.indexer === "scip") {
307
+ // Subrooted jobs replay from their own dir (SFC jobs from the virtual
308
+ // dir, standalone crates from the crate dir); the output path is written
309
+ // relative to THAT cwd, recorded as step.cwd (omitted when it is root).
310
+ const relRaw = relative(cmd.cwd, cmd.raw).replace(/\\/g, "/");
311
+ const cwdRel = relToRoot(cmd.cwd);
312
+ const step = {};
313
+ if (cwdRel !== ".") step.cwd = cwdRel;
314
+ step.argv = cmd.argv[0] === "npx"
315
+ ? [...cmd.argv.slice(0, -1), relRaw]
316
+ : ["rust-analyzer", "scip", ".", "--output", relRaw];
317
+ indexSteps.push(step);
318
+ } else {
319
+ // Joern replays IN the build dir (cmd.cwd), so its workspace cache lands
320
+ // under _build/ on refresh too — not at the repo root. Re-base the env
321
+ // paths on that cwd: GEML_SRC climbs back to the root, GEML_OUT is the raw
322
+ // dir's name (a sibling under _build). Mirrors the subrooted-scip step.
323
+ const relRaw = relative(cmd.cwd, cmd.raw).replace(/\\/g, "/");
324
+ const srcRel = relative(cmd.cwd, rootAbs).replace(/\\/g, "/") || ".";
325
+ const cwdRel = relToRoot(cmd.cwd);
326
+ const step = {
327
+ env: envOf({ GEML_SRC: srcRel, GEML_OUT: relRaw, GEML_LANG: job.gemlLang }),
328
+ argv: ["joern", "--script", scriptPosix],
329
+ };
330
+ if (cwdRel !== ".") step.cwd = cwdRel;
331
+ indexSteps.push(step);
332
+ }
333
+ }
334
+ if (!inputs.length) {
335
+ console.error("every indexer failed nothing to build.");
336
+ process.exit(1);
337
+ }
338
+ if (failedLangs.length) {
339
+ console.error(`WARNING: continuing WITHOUT ${failedLangs.join(", ")} — the codemap covers the remaining language(s) only. Fix that indexer and re-run build to fill the gap.`);
340
+ }
341
+ console.error("merging...");
342
+ recordRecipe = { rootAbs, indexSteps };
343
+ }
344
+
345
+ const bad = inputs.find((s) => !["crg", "joern", "scip"].includes(s.adapter) || (s.adapter === "crg" ? !s.db : !s.raw));
346
+ if (!inputs.length || bad) {
347
+ console.error(USAGE);
348
+ process.exit(2);
349
+ }
350
+
351
+ // Extract every input and concatenate — anchors are namespaced by language and
352
+ // path, so inputs don't collide; identical anchors across inputs are dropped
353
+ // with a warning (first input wins).
354
+ const symbols = [];
355
+ const edges = [];
356
+ const seenAnchors = new Set();
357
+ for (const spec of inputs) {
358
+ const { extract } = await import(`./adapters/${spec.adapter}.mjs`);
359
+ const r = extract(spec.adapter === "crg" ? { db: spec.db, root } : { raw: spec.raw, root, remapDir: spec.remap });
360
+ let dropped = 0;
361
+ for (const s of r.symbols) {
362
+ if (seenAnchors.has(s.anchor)) { dropped++; continue; }
363
+ seenAnchors.add(s.anchor);
364
+ symbols.push(s);
365
+ }
366
+ for (const e of r.edges) edges.push(e);
367
+ console.error(`input ${spec.adapter}: ${r.symbols.length} symbols, ${r.edges.length} edges${dropped ? ` (${dropped} duplicate anchors dropped)` : ""}`);
368
+ }
369
+
370
+ // Exclusion: drop symbols whose source file is git-ignored (default) or
371
+ // matches an explicit --exclude glob. Vendored copies and third-party dumps
372
+ // belong out of the graph; the edge tables key on surviving anchors, so
373
+ // dangling references simply vanish (emit skips edges whose endpoints are
374
+ // gone). --no-gitignore turns off the git-driven half.
375
+ const excludeGlobs = args.flatMap((v, i) => (args[i - 1] === "--exclude" ? [v] : []));
376
+ const excluder = makeExcluder({
377
+ root: resolve(root),
378
+ globs: excludeGlobs,
379
+ gitignore: !args.includes("--no-gitignore"),
380
+ files: [...new Set(symbols.map((s) => s.file))],
381
+ exec: execFileSync,
382
+ });
383
+ const kept = symbols.filter((s) => !excluder(s.file));
384
+ const excludedCount = symbols.length - kept.length;
385
+
386
+ // App-entry hints for the EXPLICIT-adapter path too (auto mode computed them
387
+ // alongside language detection): the entry signals live in the repo's
388
+ // manifests and sources, not in how the indexes were produced.
389
+ if (root && !recordRecipe && !entryHints.length) {
390
+ const rootAbs = resolve(root);
391
+ const c = collectSourceFiles(rootAbs);
392
+ const excl = makeExcluder({
393
+ root: rootAbs, globs: excludeGlobs, gitignore: !args.includes("--no-gitignore"),
394
+ files: [...c.files, ...c.manifests, ...c.pkgs], exec: execFileSync,
395
+ });
396
+ entryHints = detectEntries(rootAbs, {
397
+ files: c.files.filter((f) => !excl(f)),
398
+ manifests: c.manifests.filter((m) => !excl(m)),
399
+ pkgs: c.pkgs.filter((p) => !excl(p)),
400
+ });
401
+ }
402
+ if (excludedCount) {
403
+ symbols.length = 0;
404
+ for (const s of kept) symbols.push(s);
405
+ console.error(
406
+ `excluded ${excludedCount} symbol(s) via ${!args.includes("--no-gitignore") ? ".gitignore" : "(gitignore off)"}`
407
+ + `${excludeGlobs.length ? ` + ${excludeGlobs.length} --exclude glob(s)` : ""}`,
408
+ );
409
+ }
410
+
411
+ // Cross-stack API links: detect frontend HTTP call sites + backend route
412
+ // declarations across the merged graph and append `http` edges wiring each
413
+ // caller's enclosing symbol to the handler's — the seam that joins a full
414
+ // stack's two otherwise-disjoint trees. Kept OUT of the verified `calls`
415
+ // relation (own edge kind + confidence). Best-effort: a detector failure must
416
+ // never sink an otherwise-good build.
417
+ try {
418
+ const rootAbs = resolve(root);
419
+ const scanFiles = [...new Set(symbols.map((s) => s.file))];
420
+ const { edges: httpEdges, audit } = buildCrossStackOverlay({
421
+ symbols,
422
+ files: scanFiles,
423
+ readText: (rel) => { try { return readFileSync(join(rootAbs, ...rel.split("/")), "utf8"); } catch { return null; } },
424
+ });
425
+ for (const e of httpEdges) edges.push(e);
426
+ if (httpEdges.length) {
427
+ console.error(
428
+ `cross-stack: ${httpEdges.length} api link(s) across ${audit.endpoints} endpoint(s)`
429
+ + (audit.divergent.length ? `, ${audit.divergent.length} method-divergent` : "")
430
+ + (audit.deadRoutes.length ? `, ${audit.deadRoutes.length} uncalled route(s)` : ""));
431
+ mkdirSync(join(outDir, "_index"), { recursive: true });
432
+ const auditPath = join(outDir, "_index", "cross-stack.json");
433
+ const auditContent = JSON.stringify(audit, null, 2) + "\n";
434
+ if (!existsSync(auditPath) || readFileSync(auditPath, "utf8") !== auditContent) writeFileSync(auditPath, auditContent);
435
+ }
436
+ } catch (e) {
437
+ console.error(`cross-stack overlay skipped: ${e.message}`);
438
+ }
439
+
440
+ // Exchange format on disk — the layer contract (§3). Deterministic order so
441
+ // the jsonl files diff cleanly across builds.
442
+ symbols.sort((a, b) => a.anchor.localeCompare(b.anchor));
443
+ edges.sort((a, b) =>
444
+ String(a.from ?? a.from_text ?? "").localeCompare(String(b.from ?? b.from_text ?? "")) || a.kind.localeCompare(b.kind)
445
+ || String(a.to ?? a.to_text).localeCompare(String(b.to ?? b.to_text)));
446
+ mkdirSync(buildDir, { recursive: true });
447
+ const jsonl = (rows) => rows.map((r) => JSON.stringify(r)).join("\n") + "\n";
448
+ const writeIfChanged = (p, content) => {
449
+ if (existsSync(p) && readFileSync(p, "utf8") === content) return;
450
+ writeFileSync(p, content);
451
+ };
452
+ writeIfChanged(join(buildDir, "symbols.jsonl"), jsonl(symbols));
453
+ writeIfChanged(join(buildDir, "edges.jsonl"), jsonl(edges));
454
+
455
+ // Container granularity (codemap profile): module = first path segment,
456
+ // dir = containing directory (default), file = one document per source file.
457
+ const containerGranularity = flag("--container", "dir");
458
+ if (!["module", "dir", "file"].includes(containerGranularity)) {
459
+ console.error(`--container must be module|dir|file (got '${containerGranularity}')`);
460
+ process.exit(2);
461
+ }
462
+ // Best-effort commit stamp for index.geml meta.
463
+ let commit;
464
+ try {
465
+ commit = execFileSync("git", ["-C", resolve(root), "rev-parse", "--short", "HEAD"], { encoding: "utf8" }).trim();
466
+ } catch { /* not a git repo */ }
467
+
468
+ // Ceremony-folding config: read _index/foldings.geml, or seed it on this first
469
+ // build from the discovered module roots + detected languages. Human-owned
470
+ // once seeded (never rewritten); threaded into emit for display normalisation.
471
+ const { config: foldings, seeded: foldingsSeeded } = loadOrSeedFoldings({
472
+ outDir,
473
+ moduleRoots: discoverModuleRoots(resolve(root)),
474
+ languages: detectedLanguages,
475
+ });
476
+ if (foldingsSeeded) console.error("seeded _index/foldings.geml — edit to tune module folding");
477
+
478
+ const stats = emit({
479
+ symbols, edges, outDir, buildDir,
480
+ repoName: basename(resolve(root)),
481
+ container: containerGranularity,
482
+ commit,
483
+ root: resolve(root),
484
+ foldings,
485
+ entryHints,
486
+ });
487
+
488
+ // Keep the transient build dir out of version control while the `.geml` graph
489
+ // and `_index/` stay committable (the graph is meant to be committed & shared).
490
+ // `_build/` holds only regenerable intermediates — the *.jsonl exchange files
491
+ // and Joern's `workspace/` CPG cache — so one ignore rule covers them all.
492
+ // Written once; a user's later edits to this file are preserved, never clobbered.
493
+ const ignoreFile = join(outDir, ".gitignore");
494
+ if (!existsSync(ignoreFile)) writeFileSync(ignoreFile, "_build/\n");
495
+
496
+ console.error(
497
+ `geml-code-graph: ${stats.methods} methods (${stats.symbols} symbols), ${stats.edges} edges `
498
+ + `(${stats.resolved} resolved), ${stats.leaves} leaves, ${stats.entries} app entries -> `
499
+ + `${stats.containers} containers (${stats.written} of ${stats.docs} files written), `
500
+ + `${(stats.bytes / 1048576).toFixed(2)} MB -> ${outDir}`,
501
+ );
502
+
503
+ // --history: snapshot every changed document into its .gemlhistory sidecar —
504
+ // the graph's own architectural history (geml history log / revert per node).
505
+ // Targets = documents rewritten this build, plus any document that has no
506
+ // sidecar yet (first run, or --history adopted later).
507
+ if (args.includes("--history")) {
508
+ const histMod = resolve(dirname(fileURLToPath(import.meta.url)), "../dist/history.js");
509
+ if (!existsSync(histMod)) {
510
+ console.error("--history needs the built parser (cd geml-parser && npm install && npm run build)");
511
+ process.exit(1);
512
+ }
513
+ const { commit, isCurrent } = await import(`file://${histMod.replace(/\\/g, "/")}`);
514
+ const message = flag("-m", flag("--message", "graph build"));
515
+ const targets = new Set(stats.writtenDocs);
516
+ for (const d of stats.allDocs) {
517
+ if (targets.has(d)) continue;
518
+ const gemlPath = join(outDir, d);
519
+ const sidecar = gemlPath.replace(/\.geml$/, ".gemlhistory");
520
+ // No sidecar yet, or the sidecar tip drifted from the file (a previous
521
+ // commit attempt was refused): both need a snapshot even though this build
522
+ // did not rewrite the document.
523
+ if (!existsSync(sidecar) || !isCurrent(sidecar, gemlPath)) targets.add(d);
524
+ }
525
+ let committed = 0;
526
+ const histFailed = [];
527
+ for (const d of [...targets].sort()) {
528
+ const gemlPath = join(outDir, d);
529
+ try {
530
+ commit({ gemlPath, historyPath: gemlPath.replace(/\.geml$/, ".gemlhistory"), summary: message });
531
+ committed++;
532
+ } catch (e) {
533
+ // One document's history refusing a commit (e.g. the round-trip gate)
534
+ // must not abort the build or the other documents' snapshots. The
535
+ // failing document's previous revision stays intact.
536
+ histFailed.push(d);
537
+ console.error(`history: ${d}: ${e.message}`);
538
+ }
539
+ }
540
+ console.error(
541
+ `history: committed ${committed} document(s) (${stats.allDocs.length - committed - histFailed.length} unchanged, skipped)`
542
+ + (histFailed.length ? `; FAILED: ${histFailed.join(", ")}` : ""),
543
+ );
544
+ }
545
+
546
+ // Auto mode records the exact replay recipe (index → explicit build → verify)
547
+ // into _index/refresh.json on the FIRST build, so `geml codemap refresh` (and
548
+ // the commit hook) can reproduce it. An existing recipe is left untouched —
549
+ // EXCEPT one whose on-disk schema `version` does not match RECIPE_VERSION:
550
+ // refresh refuses an out-of-date recipe, so a rebuild re-records it in the
551
+ // current format. Judging by a standalone schema version (not the parser
552
+ // version, which bumps every patch) means a FUTURE format change is cleanly
553
+ // detected without a parser bump forcing a needless re-index. This is the
554
+ // "re-run build" upgrade path refresh points users to; a recipe already at the
555
+ // current version stays write-once (not clobbered). Paths are relative to
556
+ // <root>, which is the cwd refresh runs each step in.
557
+ if (recordRecipe) {
558
+ const cfgPath = join(outDir, "_index", "refresh.json");
559
+ let needsRerecord = false;
560
+ if (existsSync(cfgPath)) {
561
+ try { needsRerecord = JSON.parse(readFileSync(cfgPath, "utf8")).version !== RECIPE_VERSION; }
562
+ catch { needsRerecord = true; } // unparseable → re-record clean
563
+ }
564
+ if (!existsSync(cfgPath) || needsRerecord) {
565
+ const rel = (p) => (relative(recordRecipe.rootAbs, p).replace(/\\/g, "/") || ".");
566
+ const relOut = rel(outDir);
567
+ // Structured build + verify steps (security fix R2-1): argv arrays, never a
568
+ // shell string. Each `--adapter/--raw[/--remap]` group is discrete tokens.
569
+ const buildArgv = ["geml", "codemap", "build",
570
+ ...inputs.flatMap((s) => ["--adapter", s.adapter, "--raw", rel(s.raw), ...(s.remap ? ["--remap", rel(s.remap)] : [])]),
571
+ "--root", ".", "--out", relOut,
572
+ ...(containerGranularity !== "dir" ? ["--container", containerGranularity] : []),
573
+ ...(args.includes("--history") ? ["--history"] : []),
574
+ ];
575
+ // Parser version — recorded as `generator` PROVENANCE only, never as part of
576
+ // the compatibility check or the fingerprint (it bumps every patch release;
577
+ // judging by it would force a full re-index of every project each release).
578
+ const pkgVersion = (() => {
579
+ try { return JSON.parse(readFileSync(join(dirname(fileURLToPath(import.meta.url)), "..", "package.json"), "utf8")).version; }
580
+ catch { return "?"; }
581
+ })();
582
+ const cfg = {
583
+ version: RECIPE_VERSION,
584
+ generator: `geml ${pkgVersion}`,
585
+ // Project root relative to the codemap dir (refresh runs each step under
586
+ // <root>). Normally outDir is a subdir of root so relative() yields ".."
587
+ // etc.; when --out == --root it yields "" and the project root IS the
588
+ // codemap dir, so record "." — recording ".." would send refresh into
589
+ // the PARENT of the real root.
590
+ root: relative(outDir, recordRecipe.rootAbs).replace(/\\/g, "/") || ".",
591
+ steps: [...recordRecipe.indexSteps, { argv: buildArgv }, { argv: ["geml", "codemap", "verify", relOut] }],
592
+ };
593
+ mkdirSync(join(outDir, "_index"), { recursive: true });
594
+ writeFileSync(cfgPath, JSON.stringify(cfg, null, 2) + "\n");
595
+ console.error(`recorded build recipe -> ${cfgPath}`);
596
+ // Auto-trust the recipe we just authored (security fix C2). The user ran
597
+ // build locally, so their own recipe is trusted by construction and the
598
+ // normal build -> refresh flow needs no prompt. Uses the SAME fingerprint
599
+ // fn as refresh, so the two agree exactly. Best-effort: a trust-store write
600
+ // failure must not fail an otherwise-successful build — the user can still
601
+ // approve later with `geml codemap refresh --trust`.
602
+ try {
603
+ trustRecipe(recipeFingerprint(cfg), outDir);
604
+ } catch (e) {
605
+ console.error(`warning: could not record the codemap recipe as trusted (${e.message}); run \`geml codemap refresh --trust\` after reviewing _index/refresh.json`);
606
+ }
607
+ }
608
+ }
609
+ console.error(`next: geml codemap verify ${outDir}`);