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