@vibgrate/cli 2026.824.3 → 2026.825.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/dist/{agent-6SJVWFPV.js → agent-DHQYEHVW.js} +13 -12
- package/dist/{agent-6SJVWFPV.js.map → agent-DHQYEHVW.js.map} +1 -1
- package/dist/{approvals-5UBLBNJF.js → approvals-KBM72NU2.js} +5 -5
- package/dist/{approvals-5UBLBNJF.js.map → approvals-KBM72NU2.js.map} +1 -1
- package/dist/{attach-PSGCCJMA.js → attach-O74NL4M5.js} +3 -3
- package/dist/{attach-PSGCCJMA.js.map → attach-O74NL4M5.js.map} +1 -1
- package/dist/{baseline-HPXACNFU.js → baseline-4X6MQBDA.js} +3 -3
- package/dist/{baseline-HPXACNFU.js.map → baseline-4X6MQBDA.js.map} +1 -1
- package/dist/{chunk-B5GOCQFB.js → chunk-27TS2AUJ.js} +8 -8
- package/dist/{chunk-B5GOCQFB.js.map → chunk-27TS2AUJ.js.map} +1 -1
- package/dist/{chunk-2IY24TTR.js → chunk-2NUS5BOR.js} +3 -3
- package/dist/{chunk-2IY24TTR.js.map → chunk-2NUS5BOR.js.map} +1 -1
- package/dist/{chunk-JL66EPZ4.js → chunk-3E7QT4NE.js} +9 -9
- package/dist/{chunk-JL66EPZ4.js.map → chunk-3E7QT4NE.js.map} +1 -1
- package/dist/{chunk-M5QSBXA6.js → chunk-6MIJLO5B.js} +11 -4
- package/dist/chunk-6MIJLO5B.js.map +1 -0
- package/dist/{chunk-SGIFJIII.js → chunk-7M4E7UGX.js} +3 -3
- package/dist/{chunk-SGIFJIII.js.map → chunk-7M4E7UGX.js.map} +1 -1
- package/dist/{chunk-KBLKNR3V.js → chunk-BICZR6UJ.js} +3 -3
- package/dist/{chunk-KBLKNR3V.js.map → chunk-BICZR6UJ.js.map} +1 -1
- package/dist/{chunk-UUNEUEPQ.js → chunk-DIZ5KI5Q.js} +6 -6
- package/dist/{chunk-UUNEUEPQ.js.map → chunk-DIZ5KI5Q.js.map} +1 -1
- package/dist/{chunk-IKB5U3AH.js → chunk-E3XVIFSH.js} +3 -3
- package/dist/{chunk-IKB5U3AH.js.map → chunk-E3XVIFSH.js.map} +1 -1
- package/dist/{chunk-3PNAQUZM.js → chunk-FQHWPOTS.js} +3 -3
- package/dist/{chunk-3PNAQUZM.js.map → chunk-FQHWPOTS.js.map} +1 -1
- package/dist/chunk-G3ACLBMG.js +6 -0
- package/dist/{chunk-AGOKTI77.js.map → chunk-G3ACLBMG.js.map} +1 -1
- package/dist/{chunk-5QO2GFAE.js → chunk-GR7SFCQJ.js} +44 -12
- package/dist/chunk-GR7SFCQJ.js.map +1 -0
- package/dist/{chunk-4PDWV4AE.js → chunk-GWSJYDK7.js} +5 -5
- package/dist/{chunk-4PDWV4AE.js.map → chunk-GWSJYDK7.js.map} +1 -1
- package/dist/{chunk-CJ2R3LVX.js → chunk-HFQIYM6E.js} +4 -4
- package/dist/{chunk-CJ2R3LVX.js.map → chunk-HFQIYM6E.js.map} +1 -1
- package/dist/{chunk-LMHKIQA5.js → chunk-IJVWKZRS.js} +3 -3
- package/dist/{chunk-LMHKIQA5.js.map → chunk-IJVWKZRS.js.map} +1 -1
- package/dist/{chunk-YJ23GGAJ.js → chunk-JAEHLTVX.js} +3 -3
- package/dist/{chunk-YJ23GGAJ.js.map → chunk-JAEHLTVX.js.map} +1 -1
- package/dist/{chunk-USW5WHUG.js → chunk-K3SXWOTT.js} +3 -3
- package/dist/{chunk-USW5WHUG.js.map → chunk-K3SXWOTT.js.map} +1 -1
- package/dist/{chunk-RAEHWCN6.js → chunk-KYM55VZX.js} +6 -6
- package/dist/{chunk-RAEHWCN6.js.map → chunk-KYM55VZX.js.map} +1 -1
- package/dist/chunk-L7GCJNDT.js +90 -0
- package/dist/chunk-L7GCJNDT.js.map +1 -0
- package/dist/{chunk-QP3P4V4I.js → chunk-NS4DL3QR.js} +8 -8
- package/dist/{chunk-QP3P4V4I.js.map → chunk-NS4DL3QR.js.map} +1 -1
- package/dist/{chunk-WATYIYWP.js → chunk-NZES47ST.js} +3 -3
- package/dist/{chunk-WATYIYWP.js.map → chunk-NZES47ST.js.map} +1 -1
- package/dist/{chunk-III7S75O.js → chunk-OIUVWCKM.js} +3 -3
- package/dist/{chunk-III7S75O.js.map → chunk-OIUVWCKM.js.map} +1 -1
- package/dist/{chunk-LA4CETXN.js → chunk-SIXWWQ6S.js} +3 -3
- package/dist/{chunk-LA4CETXN.js.map → chunk-SIXWWQ6S.js.map} +1 -1
- package/dist/{chunk-TWWVTKA7.js → chunk-SYMJSRYF.js} +3 -3
- package/dist/{chunk-TWWVTKA7.js.map → chunk-SYMJSRYF.js.map} +1 -1
- package/dist/{chunk-KRE7SXSA.js → chunk-TT2J2TB6.js} +6 -6
- package/dist/{chunk-KRE7SXSA.js.map → chunk-TT2J2TB6.js.map} +1 -1
- package/dist/{chunk-XHIWQGRE.js → chunk-VMPKOMHG.js} +5 -5
- package/dist/{chunk-XHIWQGRE.js.map → chunk-VMPKOMHG.js.map} +1 -1
- package/dist/cli.js +52 -48
- package/dist/cli.js.map +1 -1
- package/dist/{daemon-AEL5N4SJ.js → daemon-RZS5FPIW.js} +9 -9
- package/dist/{daemon-AEL5N4SJ.js.map → daemon-RZS5FPIW.js.map} +1 -1
- package/dist/embed-worker-main.js +3 -3
- package/dist/{ensure-map-YL5NR6UH.js → ensure-map-DL2S774J.js} +14 -14
- package/dist/{ensure-map-YL5NR6UH.js.map → ensure-map-DL2S774J.js.map} +1 -1
- package/dist/{graph-backend-LEPXFPXQ.js → graph-backend-JXARVT3R.js} +7 -7
- package/dist/{graph-backend-LEPXFPXQ.js.map → graph-backend-JXARVT3R.js.map} +1 -1
- package/dist/index.d.ts +45 -4
- package/dist/index.js +15 -14
- package/dist/index.js.map +1 -1
- package/dist/{interactive-YJ37ZWTA.js → interactive-2XRBRFRB.js} +25 -24
- package/dist/interactive-2XRBRFRB.js.map +1 -0
- package/dist/load-7C5VETRD.js +11 -0
- package/dist/{load-LT6R73IZ.js.map → load-7C5VETRD.js.map} +1 -1
- package/dist/parse-worker.js +2 -2
- package/dist/{run-outcome-YQBPYNEY.js → run-outcome-TMB5TJNA.js} +5 -5
- package/dist/{run-outcome-YQBPYNEY.js.map → run-outcome-TMB5TJNA.js.map} +1 -1
- package/dist/{runtime-session-JSH5UL7Z.js → runtime-session-Y23NVY7R.js} +9 -9
- package/dist/{runtime-session-JSH5UL7Z.js.map → runtime-session-Y23NVY7R.js.map} +1 -1
- package/dist/{session-3FLVZRMM.js → session-KXT2ZTPE.js} +8 -8
- package/dist/{session-3FLVZRMM.js.map → session-KXT2ZTPE.js.map} +1 -1
- package/dist/{stream-json-VJ2O52CR.js → stream-json-NW6AOE47.js} +13 -12
- package/dist/stream-json-NW6AOE47.js.map +1 -0
- package/dist/version-7ABYXWOZ.js +4 -0
- package/dist/{version-VUTM46C5.js.map → version-7ABYXWOZ.js.map} +1 -1
- package/dist/{vg-mcp-bridge-UUMEOJSO.js → vg-mcp-bridge-LXBHKEFR.js} +8 -8
- package/dist/{vg-mcp-bridge-UUMEOJSO.js.map → vg-mcp-bridge-LXBHKEFR.js.map} +1 -1
- package/dist/{vgd-XFT574U6.js → vgd-RW7HCEIP.js} +8 -8
- package/dist/vgd-RW7HCEIP.js.map +1 -0
- package/package.json +2 -5
- package/dist/chunk-5QO2GFAE.js.map +0 -1
- package/dist/chunk-AGOKTI77.js +0 -6
- package/dist/chunk-M5QSBXA6.js.map +0 -1
- package/dist/interactive-YJ37ZWTA.js.map +0 -1
- package/dist/load-LT6R73IZ.js +0 -11
- package/dist/stream-json-VJ2O52CR.js.map +0 -1
- package/dist/version-VUTM46C5.js +0 -4
- package/dist/vgd-XFT574U6.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/engine/limits.ts","../src/engine/scip.ts","../src/engine/rng.ts","../src/engine/analyze.ts","../src/engine/coverage.ts","../src/engine/facts.ts","../src/engine/grounding.ts","../src/engine/pool.ts","../src/engine/ts-resolver.ts","../src/engine/tsc-cache.ts","../src/engine/epistemic.ts","../src/engine/docs-ingest.ts","../src/engine/toolchain/util.ts","../src/engine/toolchain/yaml.ts","../src/engine/toolchain/compose.ts","../src/engine/toolchain/dockerfile.ts","../src/engine/toolchain/helm.ts","../src/engine/toolchain/kubernetes.ts","../src/engine/toolchain/terraform.ts","../src/engine/toolchain/workflows.ts","../src/engine/toolchain/link.ts","../src/engine/toolchain/index.ts","../src/engine/ts-projects.ts","../src/engine/timing.ts","../src/engine/summaries.ts","../src/engine/manifests.ts","../src/engine/hash-files.ts","../src/engine/build.ts","../src/engine/verify.ts","../src/engine/freshness.ts","../src/install/content.ts","../src/install/registry.ts"],"names":["path","fs","enclosing","nodeId","fs2","path2","normalize","add","rel","path3","path4","ts","fs3","path5","fs4","toPosix","source","push","join","fs5","path6","fs6","path7","buildRootIgnore","fs7","ignore","os2","path8","fs9","path9","fs10","os3"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,IAAM,MAAM,IAAA,GAAO,IAAA;AAEZ,IAAM,yBAAyB,CAAA,GAAI,GAAA;AACnC,IAAM,iBAAA,GAAoB,GAAA;AAC1B,IAAM,qBAAA,GAAwB,GAAA;AAIrC,IAAM,mBAAA,GAAsB,GAAA;AAIrB,IAAM,kBAAA,GAAN,cAAiC,KAAA,CAAM;AAAA,EACnC,oBAAA,GAAuB,IAAA;AAAA,EAChC,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,oBAAA;AAAA,EACd;AACF;AAGA,SAAS,MAAA,CAAO,MAAc,QAAA,EAA0B;AACtD,EAAA,MAAM,GAAA,GAAM,OAAA,CAAQ,GAAA,CAAI,IAAI,CAAA;AAC5B,EAAA,IAAI,QAAQ,MAAA,IAAa,GAAA,CAAI,IAAA,EAAK,KAAM,IAAI,OAAO,QAAA;AACnD,EAAA,MAAM,CAA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*\n * Building the map holds every parse table, node, and edge in memory at once,\n * so a pathological corpus (a vendored 200 MB bundle, a million-file tree, a\n * giant TS program) can OOM-kill the process — an uncatchable crash that takes\n * the caller (e.g. a `scan --push`) down with it. These limits convert that\n * crash into either a deterministic skip (per-file size cap, tsc rung cap) or\n * a catchable, actionable error (corpus cap, heap budget).\n *\n * Every limit is overridable via environment variable, and `0` always means\n * \"disabled\". Skips are pure functions of the input (file size, file count) —\n * never of observed memory — so identical input still yields identical output.\n */\n\nexport interface ResourceLimits {\n /** Per-file source cap in bytes. Larger files stay stat-tracked for\n * freshness but are not parsed into the graph. 0 disables. */\n maxFileBytes: number;\n /** Ceiling on discovered corpus files; exceeding aborts with guidance\n * instead of grinding toward an OOM. 0 disables. */\n maxFiles: number;\n /** Ceiling on TS/JS files handed to the in-process TypeScript Compiler API\n * rung (a ts.Program over the whole corpus is the largest single memory\n * consumer). Above it the rung is skipped; the heuristic floor remains.\n * 0 disables. */\n tscMaxFiles: number;\n /** Heap budget in MiB checked at phase boundaries; exceeding aborts with a\n * clear error before V8 hard-crashes. 0 disables. */\n memoryBudgetMb: number;\n}\n\nconst MIB = 1024 * 1024;\n\nexport const DEFAULT_MAX_FILE_BYTES = 2 * MIB;\nexport const DEFAULT_MAX_FILES = 100_000;\nexport const DEFAULT_TSC_MAX_FILES = 10_000;\n\n/** Fraction of V8's heap ceiling we allow the build to consume before\n * aborting — past this an OOM crash is imminent anyway. */\nconst HEAP_GUARD_FRACTION = 0.9;\n\n/** A build stopped by a resource safeguard — catchable, unlike an OOM. The\n * message is user-facing and must carry its own remedy. */\nexport class ResourceLimitError extends Error {\n readonly isResourceLimitError = true;\n constructor(message: string) {\n super(message);\n this.name = 'ResourceLimitError';\n }\n}\n\n/** Non-negative integer from an env var; unset/invalid → fallback. */\nfunction envInt(name: string, fallback: number): number {\n const raw = process.env[name];\n if (raw === undefined || raw.trim() === '') return fallback;\n const n = Number(raw);\n return Number.isInteger(n) && n >= 0 ? n : fallback;\n}\n\n/** Like envInt but with no default — undefined when unset/invalid/0. */\nfunction envIntOptional(name: string): number | undefined {\n const n = envInt(name, 0);\n return n > 0 ? n : undefined;\n}\n\n/** Default heap budget: 90% of V8's configured heap ceiling (respects\n * NODE_OPTIONS=--max-old-space-size), in MiB. */\nexport function defaultMemoryBudgetMb(): number {\n return Math.floor((v8.getHeapStatistics().heap_size_limit / MIB) * HEAP_GUARD_FRACTION);\n}\n\n/**\n * Resolve effective limits: explicit overrides (tests, programmatic callers)\n * win over environment variables, which win over defaults.\n */\nexport function resolveLimits(overrides: Partial<ResourceLimits> = {}): ResourceLimits {\n return {\n maxFileBytes: overrides.maxFileBytes ?? envInt('VG_MAX_FILE_BYTES', DEFAULT_MAX_FILE_BYTES),\n maxFiles: overrides.maxFiles ?? envInt('VG_MAX_FILES', DEFAULT_MAX_FILES),\n tscMaxFiles: overrides.tscMaxFiles ?? envInt('VG_TSC_MAX_FILES', DEFAULT_TSC_MAX_FILES),\n memoryBudgetMb: overrides.memoryBudgetMb ?? envInt('VG_MEMORY_BUDGET_MB', defaultMemoryBudgetMb()),\n };\n}\n\n/** Default parse worker count override (`VG_JOBS`); undefined when unset. */\nexport function envJobs(): number | undefined {\n return envIntOptional('VG_JOBS');\n}\n\n/** Per-worker old-generation heap cap in MiB (`VG_WORKER_HEAP_MB`);\n * undefined when unset (workers inherit the platform default). */\nexport function envWorkerHeapMb(): number | undefined {\n return envIntOptional('VG_WORKER_HEAP_MB');\n}\n\n/**\n * Abort (catchably) when heap use crosses the budget. Called at phase\n * boundaries — cheap enough to call freely, and an abort here beats a V8\n * hard-crash a few allocations later. Only ever *throws*; it never alters\n * build output, so determinism is unaffected.\n */\nexport function checkMemoryBudget(phase: string, budgetMb: number): void {\n if (budgetMb <= 0) return;\n const usedMb = process.memoryUsage().heapUsed / MIB;\n if (usedMb <= budgetMb) return;\n throw new ResourceLimitError(\n `graph build stopped during ${phase}: heap use ${Math.round(usedMb)} MiB exceeds the ` +\n `${budgetMb} MiB budget. Narrow the build (scope to sub-paths, add --exclude globs, or ` +\n `--only <langs>), raise the Node heap (NODE_OPTIONS=--max-old-space-size=8192), or set ` +\n `VG_MEMORY_BUDGET_MB (0 disables this safeguard).`,\n );\n}\n\n/** Human-readable byte count for warnings (\"3.2 MiB\"). */\nexport function formatBytes(n: number): string {\n if (n >= MIB) return `${(n / MIB).toFixed(1)} MiB`;\n if (n >= 1024) return `${(n / 1024).toFixed(1)} KiB`;\n return `${n} B`;\n}\n","/**\n * SCIP ingestion — the precise resolution rung (VG-ENGINE-TEARDOWN §3.2).\n *\n * Reads a real SCIP index (`index.scip`) produced by a language indexer\n * (scip-typescript, scip-python, scip-java, rust-analyzer→SCIP, …) and turns its\n * precise occurrences into call/reference edges at `resolution: \"scip\"`,\n * confidence 1.0 — a real SCIP indexer win. vg does\n * NOT bundle indexers; it consumes an index the user/CI generates (deterministic,\n * offline). The heuristic resolver remains the floor for files SCIP didn't cover.\n *\n * A small, dependency-free protobuf reader decodes only the fields we need, so\n * the core stays lean.\n */\n\nimport type { EdgeKind, GraphEdge, GraphNode, ResolverKind } from '../schema.js';\nimport { edgeId } from './ids.js';\n\n// SCIP SymbolRole bitmask (scip.proto).\nconst ROLE_DEFINITION = 0x1;\n\nexport interface ScipOccurrence {\n /** [startLine, startChar, endLine, endChar] or [startLine, startChar, endChar], 0-based. */\n range: number[];\n symbol: string;\n roles: number;\n}\nexport interface ScipDocument {\n relativePath: string;\n occurrences: ScipOccurrence[];\n}\nexport interface ScipIndex {\n documents: ScipDocument[];\n toolName?: string;\n toolVersion?: string;\n}\n\n// --- minimal protobuf wire reader ---\n\nclass Reader {\n pos = 0;\n constructor(private buf: Uint8Array) {}\n get done(): boolean {\n return this.pos >= this.buf.length;\n }\n varint(): number {\n let result = 0;\n let shift = 0;\n for (;;) {\n const b = this.buf[this.pos++];\n result += (b & 0x7f) * 2 ** shift; // avoid <<shift overflow past 31 bits\n if ((b & 0x80) === 0) break;\n shift += 7;\n }\n return result;\n }\n tag(): { field: number; wire: number } {\n const t = this.varint();\n return { field: t >>> 3, wire: t & 0x7 };\n }\n bytes(): Uint8Array {\n const len = this.varint();\n const out = this.buf.subarray(this.pos, this.pos + len);\n this.pos += len;\n return out;\n }\n skip(wire: number): void {\n if (wire === 0) this.varint();\n else if (wire === 2) this.bytes();\n else if (wire === 5) this.pos += 4;\n else if (wire === 1) this.pos += 8;\n }\n}\n\nconst td = new TextDecoder();\n\nexport function decodeScipIndex(buf: Uint8Array): ScipIndex {\n const index: ScipIndex = { documents: [] };\n const r = new Reader(buf);\n while (!r.done) {\n const { field, wire } = r.tag();\n if (field === 1 && wire === 2) decodeMetadata(r.bytes(), index); // Index.metadata\n else if (field === 2 && wire === 2) index.documents.push(decodeDocument(r.bytes()));\n else r.skip(wire);\n }\n return index;\n}\n\nfunction decodeMetadata(buf: Uint8Array, index: ScipIndex): void {\n const r = new Reader(buf);\n while (!r.done) {\n const { field, wire } = r.tag();\n if (field === 2 && wire === 2) decodeToolInfo(r.bytes(), index); // Metadata.tool_info\n else r.skip(wire);\n }\n}\n\nfunction decodeToolInfo(buf: Uint8Array, index: ScipIndex): void {\n const r = new Reader(buf);\n while (!r.done) {\n const { field, wire } = r.tag();\n if (field === 1 && wire === 2) index.toolName = td.decode(r.bytes());\n else if (field === 2 && wire === 2) index.toolVersion = td.decode(r.bytes());\n else r.skip(wire);\n }\n}\n\nfunction decodeDocument(buf: Uint8Array): ScipDocument {\n const doc: ScipDocument = { relativePath: '', occurrences: [] };\n const r = new Reader(buf);\n while (!r.done) {\n const { field, wire } = r.tag();\n if (field === 1 && wire === 2) doc.relativePath = td.decode(r.bytes()); // relative_path\n else if (field === 2 && wire === 2) doc.occurrences.push(decodeOccurrence(r.bytes()));\n else r.skip(wire);\n }\n return doc;\n}\n\nfunction decodeOccurrence(buf: Uint8Array): ScipOccurrence {\n const occ: ScipOccurrence = { range: [], symbol: '', roles: 0 };\n const r = new Reader(buf);\n while (!r.done) {\n const { field, wire } = r.tag();\n if (field === 1) {\n if (wire === 2) {\n // packed repeated int32\n const sub = new Reader(r.bytes());\n while (!sub.done) occ.range.push(sub.varint());\n } else if (wire === 0) {\n occ.range.push(r.varint());\n } else r.skip(wire);\n } else if (field === 2 && wire === 2) occ.symbol = td.decode(r.bytes());\n else if (field === 3 && wire === 0) occ.roles = r.varint();\n else r.skip(wire);\n }\n return occ;\n}\n\n// --- mapping occurrences → edges ---\n\nexport interface ScipResult {\n edges: GraphEdge[];\n /** Repo-relative files SCIP covered (it is authoritative for these). */\n coveredFiles: Set<string>;\n /** counts for status/provenance. */\n stats: { documents: number; references: number; resolved: number };\n}\n\n/**\n * Build precise edges from a SCIP index, mapped onto our nodes by (file, line).\n * A reference occurrence's enclosing node → the node where its symbol is defined.\n */\nexport function scipEdges(index: ScipIndex, nodes: GraphNode[], relForScip: (p: string) => string): ScipResult {\n // nodes per repo-relative file, with quick line lookup.\n const nodesByFile = new Map<string, GraphNode[]>();\n for (const n of nodes) {\n if (n.kind === 'file' || n.kind === 'external') continue;\n const list = nodesByFile.get(n.file);\n if (list) list.push(n);\n else nodesByFile.set(n.file, [n]);\n }\n\n // First pass: symbol → defining node (from Definition occurrences).\n const symbolToNode = new Map<string, GraphNode>();\n const coveredFiles = new Set<string>();\n for (const doc of index.documents) {\n const file = relForScip(doc.relativePath);\n const fileNodes = nodesByFile.get(file);\n if (!fileNodes) continue;\n coveredFiles.add(file);\n for (const occ of doc.occurrences) {\n if ((occ.roles & ROLE_DEFINITION) === 0 || !occ.symbol || occ.symbol.startsWith('local ')) continue;\n const line = (occ.range[0] ?? 0) + 1; // SCIP is 0-based; our spans 1-based\n const node = nodeStartingAt(fileNodes, line) ?? enclosing(fileNodes, line);\n if (node) symbolToNode.set(occ.symbol, node);\n }\n }\n\n // Second pass: reference occurrences → edges.\n const edgeMap = new Map<string, GraphEdge>();\n let references = 0;\n let resolved = 0;\n for (const doc of index.documents) {\n const file = relForScip(doc.relativePath);\n const fileNodes = nodesByFile.get(file);\n if (!fileNodes) continue;\n for (const occ of doc.occurrences) {\n if ((occ.roles & ROLE_DEFINITION) !== 0 || !occ.symbol || occ.symbol.startsWith('local ')) continue;\n references++;\n const target = symbolToNode.get(occ.symbol);\n if (!target) continue; // symbol defined outside the repo (external) — skip\n const line = (occ.range[0] ?? 0) + 1;\n const src = enclosing(fileNodes, line);\n if (!src || src.id === target.id) continue;\n const kind: EdgeKind = target.kind === 'function' || target.kind === 'method' ? 'call' : 'references';\n add(edgeMap, kind, src.id, target.id);\n resolved++;\n }\n }\n\n return {\n edges: [...edgeMap.values()],\n coveredFiles,\n stats: { documents: index.documents.length, references, resolved },\n };\n}\n\nfunction add(map: Map<string, GraphEdge>, kind: EdgeKind, src: string, dst: string): void {\n const id = edgeId(kind, src, dst);\n const existing = map.get(id);\n if (existing) {\n existing.count = (existing.count ?? 1) + 1;\n return;\n }\n const resolution: ResolverKind = 'scip';\n map.set(id, { id, kind, src, dst, resolution, confidence: 1.0, count: 1 });\n}\n\n/** Smallest node whose span contains `line`. */\nfunction enclosing(nodes: GraphNode[], line: number): GraphNode | undefined {\n let best: GraphNode | undefined;\n for (const n of nodes) {\n if (n.span.start <= line && n.span.end >= line) {\n if (!best || n.span.end - n.span.start < best.span.end - best.span.start) best = n;\n }\n }\n return best;\n}\n\n/** A node whose span starts exactly at `line` (the defined symbol). */\nfunction nodeStartingAt(nodes: GraphNode[], line: number): GraphNode | undefined {\n let best: GraphNode | undefined;\n for (const n of nodes) {\n if (n.span.start === line) {\n if (!best || n.span.end - n.span.start < best.span.end - best.span.start) best = n;\n }\n }\n return best;\n}\n","/**\n * A tiny seeded PRNG (mulberry32). Used to make Louvain clustering deterministic\n * — same graph + same seed → same communities, every run, every machine. Never\n * use `Math.random()` anywhere in the engine; that would break the determinism\n * contract (VG-ENGINE-TEARDOWN §5).\n */\nexport function mulberry32(seed: number): () => number {\n let a = seed >>> 0;\n return function () {\n a = (a + 0x6d2b79f5) | 0;\n let t = Math.imul(a ^ (a >>> 15), 1 | a);\n t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;\n return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n };\n}\n\n/** The fixed clustering seed (matches the documented determinism inputs). */\nexport const CLUSTER_SEED = 42;\n","import Graph from 'graphology';\nimport pagerank from 'graphology-metrics/centrality/pagerank.js';\nimport betweenness from 'graphology-metrics/centrality/betweenness.js';\nimport eigenvector from 'graphology-metrics/centrality/eigenvector.js';\nimport louvain from 'graphology-communities-louvain';\nimport { mulberry32, CLUSTER_SEED } from './rng.js';\nimport type { Area, EdgeKind, GraphEdge, GraphNode } from '../schema.js';\n\n/**\n * Analysis stage: importance, centrality, hubs, communities, and surprise.\n *\n * - **Centrality** blends PageRank + betweenness + eigenvector + degree over the\n * dependency graph (call/import/extends/implements/references), catching\n * high-fan-in critical nodes that degree-only ranking misses.\n * - **Communities** via Louvain (`graphology-communities-louvain`, MIT), seeded\n * and single-pass for determinism. Leiden (via a permissive WASM impl) is a\n * later enhancement; the cluster mode is reported honestly, never silent.\n * - **Hubs** are centrality outliers (importance ≥ mean + 2σ).\n * - **Surprise** flags improbable cross-area edges (architectural smells),\n * surfaced by `vg oddities`.\n *\n * Pure and deterministic: identical (nodes, edges) → identical result.\n */\n\nexport type ClusterMode = 'leiden' | 'louvain' | 'none';\nexport type AnalysisTier = 'full' | 'large' | 'xl';\n\nexport interface AnalyzeOptions {\n cluster?: ClusterMode; // default 'louvain'\n /** Skip betweenness above this node count (O(V·E) — too slow for huge graphs). */\n betweennessLimit?: number;\n /**\n * Analysis cost tier. When omitted, auto-selected from node count:\n * full ≤5k nodes — PR + betweenness + eigenvector + Louvain\n * large ≤50k — PR + eigenvector + Louvain (no betweenness)\n * xl >50k — PR + degree; Louvain only on file-level contraction\n */\n tier?: AnalysisTier;\n}\n\nexport interface AnalyzeResult {\n nodes: GraphNode[];\n edges: GraphEdge[]; // surprise scores attached\n areas: Area[];\n cluster: ClusterMode;\n tier: AnalysisTier;\n}\n\n/** Node-count thresholds for auto tier selection. */\nexport const TIER_LARGE_NODES = 5_000;\nexport const TIER_XL_NODES = 50_000;\n\nexport function pickAnalysisTier(nodeCount: number, forced?: AnalysisTier): AnalysisTier {\n if (forced) return forced;\n if (nodeCount > TIER_XL_NODES) return 'xl';\n if (nodeCount > TIER_LARGE_NODES) return 'large';\n return 'full';\n}\n\n// Edges that express dependency/importance (excludes contains/test/coverage).\nconst DEP_EDGES = new Set<EdgeKind>(['call', 'import', 'extends', 'implements', 'references']);\n// Edges that express cohesion for community detection (adds containment).\nconst CLUSTER_EDGE_KINDS = new Set<EdgeKind>([...DEP_EDGES, 'contains']);\n\nconst IMPORTANCE_WEIGHTS = { pagerank: 0.4, betweenness: 0.25, eigenvector: 0.2, degree: 0.15 };\nconst DEFAULT_BETWEENNESS_LIMIT = 5000;\n\nexport function analyze(\n nodes: GraphNode[],\n edges: GraphEdge[],\n options: AnalyzeOptions = {},\n): AnalyzeResult {\n const tier = pickAnalysisTier(nodes.length, options.tier);\n const mode = options.cluster ?? (tier === 'xl' ? 'louvain' : 'louvain');\n // Sorted for deterministic graph construction (Louvain RNG consumption order).\n const ids = [...nodes.map((n) => n.id)].sort((a, b) => a.localeCompare(b));\n\n // --- centrality (directed dependency graph) ---\n // Tier policy (honest, never silent):\n // full — PR + betweenness (≤limit) + eigenvector + degree\n // large — PR + eigenvector + degree (betweenness off)\n // xl — PR + degree (eigenvector off; betweenness off)\n const dg = simpleGraph(ids, edges, DEP_EDGES, 'directed');\n const pr = safeMetric(() => pagerank(dg), ids);\n const bwLimit = options.betweennessLimit ?? DEFAULT_BETWEENNESS_LIMIT;\n const bw =\n tier === 'full' && dg.order <= bwLimit\n ? safeMetric(() => betweenness(dg), ids)\n : zeros(ids);\n const ev =\n tier === 'full' || tier === 'large'\n ? safeMetric(() => eigenvector(dg), ids)\n : zeros(ids);\n const deg = degreeMap(dg, ids);\n\n const prN = normalize(pr);\n const bwN = normalize(bw);\n const evN = normalize(ev);\n const degN = normalize(deg);\n\n // Re-weight when expensive metrics are zeroed so scores stay informative.\n const weights =\n tier === 'xl'\n ? { pagerank: 0.7, betweenness: 0, eigenvector: 0, degree: 0.3 }\n : tier === 'large'\n ? { pagerank: 0.5, betweenness: 0, eigenvector: 0.25, degree: 0.25 }\n : IMPORTANCE_WEIGHTS;\n\n const importance = new Map<string, number>();\n for (const id of ids) {\n const score =\n weights.pagerank * (prN.get(id) ?? 0) +\n weights.betweenness * (bwN.get(id) ?? 0) +\n weights.eigenvector * (evN.get(id) ?? 0) +\n weights.degree * (degN.get(id) ?? 0);\n importance.set(id, score);\n }\n const importanceN = normalize(importance);\n\n // --- hubs (importance outliers) ---\n const vals = [...importanceN.values()];\n const mean = vals.reduce((a, b) => a + b, 0) / (vals.length || 1);\n const variance = vals.reduce((a, b) => a + (b - mean) ** 2, 0) / (vals.length || 1);\n const std = Math.sqrt(variance);\n const hubThreshold = mean + 2 * std;\n\n // --- communities ---\n // xl: cluster on file-level contraction (far fewer nodes) then map members back.\n const { areaByNode, mode: actualMode } =\n tier === 'xl'\n ? clusterFileLevel(nodes, edges, mode)\n : cluster(ids, edges, mode);\n\n const outNodes: GraphNode[] = nodes\n .map((n) => ({\n ...n,\n centrality: {\n degree: round(degN.get(n.id) ?? 0),\n pagerank: round(prN.get(n.id) ?? 0),\n betweenness: round(bwN.get(n.id) ?? 0),\n eigenvector: round(evN.get(n.id) ?? 0),\n },\n importance: round(importanceN.get(n.id) ?? 0),\n area: areaByNode.get(n.id) ?? -1,\n isHub: (importanceN.get(n.id) ?? 0) >= hubThreshold && (importanceN.get(n.id) ?? 0) > 0,\n }))\n .sort((a, b) => a.id.localeCompare(b.id));\n\n // --- areas (with labels, cohesion, external-edge counts) ---\n const areas = buildAreas(outNodes, edges, areaByNode);\n\n // --- surprise on cross-area dependency edges ---\n const outEdges = scoreSurprise(edges, areaByNode);\n\n return { nodes: outNodes, edges: outEdges, areas, cluster: actualMode, tier };\n}\n\n/**\n * XL clustering: run Louvain only over file nodes + file↔file dependency edges\n * (contracts the method-level graph), then assign every symbol the area of its file.\n */\nfunction clusterFileLevel(\n nodes: GraphNode[],\n edges: GraphEdge[],\n mode: ClusterMode,\n): { areaByNode: Map<string, number>; mode: ClusterMode } {\n const fileNodes = nodes.filter((n) => n.kind === 'file');\n const fileIds = fileNodes.map((n) => n.id).sort((a, b) => a.localeCompare(b));\n if (fileIds.length === 0) {\n return { areaByNode: new Map(nodes.map((n) => [n.id, -1])), mode: 'none' };\n }\n\n // Map symbol id → file node id.\n const fileIdByPath = new Map(fileNodes.map((n) => [n.file, n.id]));\n const fileOf = new Map<string, string>();\n for (const n of nodes) {\n if (n.kind === 'file') fileOf.set(n.id, n.id);\n else if (n.file) {\n const fid = fileIdByPath.get(n.file);\n if (fid) fileOf.set(n.id, fid);\n }\n }\n\n // Project dependency edges onto file↔file.\n const fileEdges: GraphEdge[] = [];\n const seen = new Set<string>();\n for (const e of edges) {\n if (!DEP_EDGES.has(e.kind)) continue;\n const sf = fileOf.get(e.src);\n const df = fileOf.get(e.dst);\n if (!sf || !df || sf === df) continue;\n const key = `${e.kind}|${sf}|${df}`;\n if (seen.has(key)) continue;\n seen.add(key);\n fileEdges.push({ ...e, src: sf, dst: df, id: key });\n }\n\n const { areaByNode: fileAreas, mode: used } = cluster(fileIds, fileEdges, mode);\n const areaByNode = new Map<string, number>();\n for (const n of nodes) {\n const fid = fileOf.get(n.id);\n areaByNode.set(n.id, fid ? (fileAreas.get(fid) ?? -1) : -1);\n }\n return { areaByNode, mode: used };\n}\n\n// --- graph construction ---\n\nfunction simpleGraph(\n ids: string[],\n edges: GraphEdge[],\n kinds: Set<EdgeKind>,\n type: 'directed' | 'undirected',\n): Graph {\n const g = new Graph({ type, multi: false, allowSelfLoops: false });\n for (const id of ids) g.addNode(id);\n for (const e of edges) {\n if (!kinds.has(e.kind)) continue;\n if (e.src === e.dst) continue;\n if (!g.hasNode(e.src) || !g.hasNode(e.dst)) continue;\n const w = (e.confidence || 0.5) * (e.count ?? 1);\n if (type === 'directed') {\n g.updateDirectedEdge(e.src, e.dst, (attr) => ({ weight: (attr?.weight ?? 0) + w }));\n } else {\n g.updateUndirectedEdge(e.src, e.dst, (attr) => ({ weight: (attr?.weight ?? 0) + w }));\n }\n }\n return g;\n}\n\nfunction cluster(\n ids: string[],\n edges: GraphEdge[],\n mode: ClusterMode,\n): { areaByNode: Map<string, number>; mode: ClusterMode } {\n if (mode === 'none' || ids.length === 0) {\n return { areaByNode: new Map(ids.map((id) => [id, -1])), mode: 'none' };\n }\n // Leiden is not yet bundled; fall back to Louvain and report it honestly.\n const used: ClusterMode = 'louvain';\n const ug = simpleGraph(ids, edges, CLUSTER_EDGE_KINDS, 'undirected');\n let communities: Record<string, number>;\n try {\n communities = louvain(ug, { rng: mulberry32(CLUSTER_SEED), resolution: 1 });\n } catch {\n return { areaByNode: new Map(ids.map((id) => [id, -1])), mode: 'none' };\n }\n\n // Remap arbitrary Louvain indices → stable area ids ordered by the lowest\n // member node id, so ids are deterministic and diff-stable across runs.\n const byCommunity = new Map<number, string[]>();\n for (const id of ids) {\n const ci = communities[id] ?? -1;\n const list = byCommunity.get(ci);\n if (list) list.push(id);\n else byCommunity.set(ci, [id]);\n }\n const ordered = [...byCommunity.entries()]\n .map(([, members]) => members.sort((a, b) => a.localeCompare(b)))\n .sort((a, b) => a[0].localeCompare(b[0]));\n\n const areaByNode = new Map<string, number>();\n ordered.forEach((members, areaId) => {\n for (const id of members) areaByNode.set(id, areaId);\n });\n return { areaByNode, mode: used };\n}\n\nfunction buildAreas(\n nodes: GraphNode[],\n edges: GraphEdge[],\n areaByNode: Map<string, number>,\n): Area[] {\n const byArea = new Map<number, GraphNode[]>();\n for (const n of nodes) {\n const a = areaByNode.get(n.id) ?? -1;\n if (a < 0) continue;\n const list = byArea.get(a);\n if (list) list.push(n);\n else byArea.set(a, [n]);\n }\n\n // External-edge counts per area (dependency edges crossing area boundaries).\n const externalByArea = new Map<number, number>();\n const internalByArea = new Map<number, number>();\n for (const e of edges) {\n if (!DEP_EDGES.has(e.kind)) continue;\n const sa = areaByNode.get(e.src);\n const da = areaByNode.get(e.dst);\n if (sa === undefined || da === undefined || sa < 0 || da < 0) continue;\n if (sa === da) internalByArea.set(sa, (internalByArea.get(sa) ?? 0) + 1);\n else {\n externalByArea.set(sa, (externalByArea.get(sa) ?? 0) + 1);\n externalByArea.set(da, (externalByArea.get(da) ?? 0) + 1);\n }\n }\n\n const areas: Area[] = [];\n for (const [id, members] of byArea) {\n const sorted = [...members].sort(\n (a, b) => b.importance - a.importance || a.id.localeCompare(b.id),\n );\n const label = sorted[0]?.qualifiedName ?? `area-${id}`;\n const internal = internalByArea.get(id) ?? 0;\n const external = externalByArea.get(id) ?? 0;\n const cohesion = internal + external > 0 ? internal / (internal + external) : 0;\n areas.push({\n id,\n label,\n size: members.length,\n members: members.map((m) => m.id).sort((a, b) => a.localeCompare(b)),\n cohesion: round(cohesion),\n externalEdges: external,\n });\n }\n return areas.sort((a, b) => a.id - b.id);\n}\n\nfunction scoreSurprise(edges: GraphEdge[], areaByNode: Map<string, number>): GraphEdge[] {\n // Count edges between each unordered pair of distinct areas. Rare connections\n // are more \"surprising\" (architectural shortcuts).\n const pairCount = new Map<string, number>();\n for (const e of edges) {\n if (!DEP_EDGES.has(e.kind)) continue;\n const sa = areaByNode.get(e.src);\n const da = areaByNode.get(e.dst);\n if (sa === undefined || da === undefined || sa < 0 || da < 0 || sa === da) continue;\n const key = pairKey(sa, da);\n pairCount.set(key, (pairCount.get(key) ?? 0) + 1);\n }\n\n return edges\n .map((e) => {\n if (!DEP_EDGES.has(e.kind)) return e;\n const sa = areaByNode.get(e.src);\n const da = areaByNode.get(e.dst);\n if (sa === undefined || da === undefined || sa < 0 || da < 0 || sa === da) return e;\n const count = pairCount.get(pairKey(sa, da)) ?? 1;\n // Fewer crossings between two areas → higher surprise.\n return { ...e, surprise: round(1 / count) };\n })\n .sort(\n (a, b) =>\n a.kind.localeCompare(b.kind) || a.src.localeCompare(b.src) || a.dst.localeCompare(b.dst),\n );\n}\n\n// --- numeric helpers ---\n\nfunction safeMetric(fn: () => Record<string, number>, ids: string[]): Map<string, number> {\n try {\n const res = fn();\n return new Map(ids.map((id) => [id, res[id] ?? 0]));\n } catch {\n return zeros(ids);\n }\n}\n\nfunction degreeMap(g: Graph, ids: string[]): Map<string, number> {\n return new Map(ids.map((id) => [id, g.hasNode(id) ? g.degree(id) : 0]));\n}\n\nfunction zeros(ids: string[]): Map<string, number> {\n return new Map(ids.map((id) => [id, 0]));\n}\n\nfunction normalize(m: Map<string, number>): Map<string, number> {\n let max = 0;\n for (const v of m.values()) if (v > max) max = v;\n if (max <= 0) return new Map(m);\n return new Map([...m].map(([k, v]) => [k, v / max]));\n}\n\nfunction round(x: number): number {\n return Math.round(x * 1e6) / 1e6;\n}\n\nfunction pairKey(a: number, b: number): string {\n return a < b ? `${a}|${b}` : `${b}|${a}`;\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type { GraphNode } from '../schema.js';\n\n/**\n * Coverage ingestion (VG-ENGINE-TEARDOWN §3.6) — runtime-grounded test linkage.\n * Parses LCOV (`coverage/lcov.info`) and Istanbul (`coverage-final.json`) into a\n * per-file line→hits map, then sets each node's `coverage` (fraction of its span\n * that ran) and `tested` flag. Stronger than static linkage where present.\n */\n\nexport type LineHits = Map<number, number>; // line → hit count\nexport type CoverageMap = Map<string, LineHits>; // repo-relative posix path → lines\n\nconst DEFAULT_PATHS = [\n 'coverage/lcov.info',\n 'lcov.info',\n 'coverage/coverage-final.json',\n 'coverage-final.json',\n];\n\n/** Find and parse coverage reports under root. Returns null if none found. */\nexport function loadCoverage(root: string, explicit?: string[]): CoverageMap | null {\n const candidates = (explicit && explicit.length ? explicit : DEFAULT_PATHS).map((p) =>\n path.resolve(root, p),\n );\n const found = candidates.filter((p) => fs.existsSync(p));\n if (found.length === 0) return null;\n\n const map: CoverageMap = new Map();\n for (const file of found) {\n try {\n const text = fs.readFileSync(file, 'utf8');\n if (file.endsWith('.json')) mergeIstanbul(map, text, root);\n else mergeLcov(map, text, root);\n } catch {\n /* skip unreadable/garbled report */\n }\n }\n return map.size ? map : null;\n}\n\nfunction rel(root: string, p: string): string {\n const abs = path.isAbsolute(p) ? p : path.resolve(root, p);\n return path.relative(root, abs).split(path.sep).join('/');\n}\n\nfunction bump(map: CoverageMap, file: string, line: number, hits: number): void {\n let lh = map.get(file);\n if (!lh) {\n lh = new Map();\n map.set(file, lh);\n }\n lh.set(line, Math.max(lh.get(line) ?? 0, hits));\n}\n\nfunction mergeLcov(map: CoverageMap, text: string, root: string): void {\n let current: string | null = null;\n for (const raw of text.split('\\n')) {\n const line = raw.trim();\n if (line.startsWith('SF:')) current = rel(root, line.slice(3));\n else if (line.startsWith('DA:') && current) {\n const [ln, hits] = line.slice(3).split(',');\n const n = Number(ln);\n const h = Number(hits);\n if (Number.isFinite(n)) bump(map, current, n, Number.isFinite(h) ? h : 0);\n } else if (line === 'end_of_record') current = null;\n }\n}\n\ninterface IstanbulEntry {\n path?: string;\n statementMap?: Record<string, { start: { line: number }; end: { line: number } }>;\n s?: Record<string, number>;\n}\n\nfunction mergeIstanbul(map: CoverageMap, text: string, root: string): void {\n const data = JSON.parse(text) as Record<string, IstanbulEntry>;\n for (const [key, entry] of Object.entries(data)) {\n const file = rel(root, entry.path ?? key);\n const stmts = entry.statementMap ?? {};\n const counts = entry.s ?? {};\n for (const [id, loc] of Object.entries(stmts)) {\n const hits = counts[id] ?? 0;\n const start = loc.start?.line;\n const end = loc.end?.line ?? start;\n if (!Number.isFinite(start)) continue;\n for (let ln = start; ln <= end; ln++) bump(map, file, ln, hits);\n }\n }\n}\n\n/** Apply coverage to nodes: set `coverage` fraction over the node's span + `tested`. */\nexport function applyCoverage(nodes: GraphNode[], coverage: CoverageMap): GraphNode[] {\n return nodes.map((n) => {\n if (n.kind === 'file' || n.kind === 'external') return n;\n const lh = coverage.get(n.file);\n if (!lh) return n;\n let instrumented = 0;\n let covered = 0;\n for (let ln = n.span.start; ln <= n.span.end; ln++) {\n const hits = lh.get(ln);\n if (hits === undefined) continue;\n instrumented++;\n if (hits > 0) covered++;\n }\n if (instrumented === 0) return n;\n const fraction = Math.round((covered / instrumented) * 1e6) / 1e6;\n const tested = covered > 0 ? true : n.kind === 'function' || n.kind === 'method' ? false : n.tested;\n return { ...n, coverage: fraction, tested };\n });\n}\n","import { canonicalize, shortId } from './hash.js';\nimport type { Fact, GraphEdge, GraphNode } from '../schema.js';\nimport type { FileParse } from './types.js';\n\n/**\n * The open facts subset (VG-PACKAGE-AND-SCHEMA §5) — reimplemented fresh in the\n * open engine: deterministic, no runtime, no corpus, no LLM, no hidden pipeline.\n * Three commodity fact kinds, each epistemic-typed so it never claims more than\n * the open layer can prove:\n *\n * - **contract** — from a public signature/type (declared → Observed)\n * - **invariant** — from a static assert/guard (static → Derived)\n * - **characterization** — from existing test linkage (static → Observed)\n *\n * Emitted on every build (cheap, deterministic). `--deep` is reserved for\n * heavier semantic layers, not for these open facts.\n */\nexport function buildFacts(parses: FileParse[], nodes: GraphNode[], edges: GraphEdge[]): Fact[] {\n const facts: Fact[] = [];\n const byId = new Map(nodes.map((n) => [n.id, n]));\n\n // Index code defs per file for line→enclosing-def lookup (invariants).\n const defsByFile = new Map<string, GraphNode[]>();\n for (const n of nodes) {\n if (n.kind === 'file' || n.kind === 'external') continue;\n const list = defsByFile.get(n.file);\n if (list) list.push(n);\n else defsByFile.set(n.file, [n]);\n }\n\n // --- contracts (from signatures) ---\n for (const n of nodes) {\n if ((n.kind === 'function' || n.kind === 'method') && n.signature) {\n facts.push(makeFact('contract', [n.id], { signature: n.signature }, 'declared', 'Observed', [\n { file: n.file, span: n.span },\n ]));\n }\n }\n\n // --- invariants (from static guards) ---\n for (const p of parses) {\n const defs = defsByFile.get(p.rel);\n if (!defs) continue;\n for (const g of p.guards) {\n const owner = enclosing(defs, g.line);\n if (!owner) continue;\n facts.push(\n makeFact('invariant', [owner.id], { guard: g.expr }, 'static', 'Derived', [\n { file: p.rel, span: { start: g.line, end: g.line } },\n ]),\n );\n }\n }\n\n // --- characterization (from test linkage) ---\n const testsByNode = new Map<string, string[]>();\n for (const e of edges) {\n if (e.kind !== 'test') continue;\n const testFile = byId.get(e.src)?.file;\n if (!testFile) continue;\n const list = testsByNode.get(e.dst);\n if (list) list.push(testFile);\n else testsByNode.set(e.dst, [testFile]);\n }\n for (const [nodeId, testFiles] of testsByNode) {\n const n = byId.get(nodeId);\n if (!n) continue;\n facts.push(\n makeFact(\n 'characterization',\n [nodeId],\n { pinnedBy: [...new Set(testFiles)].sort() },\n 'static',\n 'Observed',\n [{ file: n.file, span: n.span }],\n ),\n );\n }\n\n return facts.sort((a, b) => a.id.localeCompare(b.id));\n}\n\nfunction makeFact(\n kind: Fact['kind'],\n subjectIds: string[],\n predicate: unknown,\n derivedBy: Fact['derivedBy'],\n confidence: Fact['confidence'],\n evidence: Fact['evidence'],\n): Fact {\n const id = shortId(canonicalize({ t: 'fact', kind, subjectIds, predicate }));\n return { id, kind, subjectIds, predicate, derivedBy, confidence, evidence };\n}\n\n/** Smallest def whose line span contains `line`. */\nfunction enclosing(defs: GraphNode[], line: number): GraphNode | undefined {\n let best: GraphNode | undefined;\n for (const d of defs) {\n if (d.span.start <= line && d.span.end >= line) {\n if (!best || d.span.end - d.span.start < best.span.end - best.span.start) best = d;\n }\n }\n return best;\n}\n","import { FREE_PACK, type KnowledgePack, type PackEntry } from '../grounding/pack.js';\nimport type { GraphEdge, GraphNode, GroundingEdge } from '../schema.js';\nimport type { FileParse } from './types.js';\n\n/**\n * Grounding (VG-PACKAGE-AND-SCHEMA §6) — match nodes to knowledge-pack entries by\n * deterministic signals (file imports, called APIs, identifier keywords) and\n * attach cited framing edges. Closed-world tools can't follow without building a\n * corpus. Deterministic-first; the free pack ships in the open CLI.\n */\nexport function groundGraph(\n nodes: GraphNode[],\n edges: GraphEdge[],\n parses: FileParse[],\n packs: KnowledgePack[] = [FREE_PACK],\n): GroundingEdge[] {\n const byId = new Map(nodes.map((n) => [n.id, n]));\n const importsByFile = new Map<string, string[]>();\n for (const p of parses) importsByFile.set(p.rel, p.imports.map((i) => i.source.toLowerCase()));\n\n // callee names per node (from call edges).\n const calleesByNode = new Map<string, string[]>();\n for (const e of edges) {\n if (e.kind !== 'call') continue;\n const callee = byId.get(e.dst)?.name;\n if (!callee) continue;\n const list = calleesByNode.get(e.src);\n if (list) list.push(callee.toLowerCase());\n else calleesByNode.set(e.src, [callee.toLowerCase()]);\n }\n\n const out: GroundingEdge[] = [];\n for (const n of nodes) {\n if (n.kind === 'file' || n.kind === 'external') continue;\n const nameParts = new Set(\n n.name\n .split(/[^a-zA-Z0-9]+|(?<=[a-z])(?=[A-Z])/)\n .filter(Boolean)\n .map((s) => s.toLowerCase()),\n );\n const imports = importsByFile.get(n.file) ?? [];\n const callees = calleesByNode.get(n.id) ?? [];\n\n for (const pack of packs) {\n for (const entry of pack.entries) {\n const conf = matchConfidence(entry, nameParts, imports, callees);\n if (conf > 0) {\n out.push({\n src: n.id,\n packEntryId: entry.id,\n kind: entry.kind,\n confidence: conf,\n rationale: entry.rationale,\n citation: entry.citation,\n });\n }\n }\n }\n }\n\n return out.sort(\n (a, b) =>\n a.src.localeCompare(b.src) || a.packEntryId.localeCompare(b.packEntryId),\n );\n}\n\nfunction matchConfidence(\n entry: PackEntry,\n nameParts: Set<string>,\n imports: string[],\n callees: string[],\n): number {\n let conf = 0;\n if (entry.match.imports) {\n for (const sig of entry.match.imports) {\n if (imports.some((imp) => imp.includes(sig.toLowerCase()))) {\n conf = Math.max(conf, 0.8);\n break;\n }\n }\n }\n if (entry.match.calls) {\n const want = new Set(entry.match.calls.map((s) => s.toLowerCase()));\n if (callees.some((c) => want.has(c))) conf = Math.max(conf, 0.7);\n }\n if (entry.match.keywords) {\n if (entry.match.keywords.some((k) => nameParts.has(k.toLowerCase()))) {\n conf = Math.max(conf, 0.5);\n }\n }\n return conf;\n}\n","import * as fs from 'node:fs';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { parseSource } from './parse.js';\nimport { setGrammarsOverride, resetParser } from './grammars.js';\nimport { checkMemoryBudget, envJobs, envWorkerHeapMb, ResourceLimitError } from './limits.js';\nimport type { DiscoveredFile } from './discover.js';\nimport type { FileParse } from './types.js';\nimport type { ParseTask } from './parse-worker.js';\n\n/**\n * Parse a set of discovered files into FileParse tables.\n *\n * Parsing is CPU-bound and per-file independent, so it parallelises across a\n * worker_threads pool (tinypool) and scales near-linearly with cores — the\n * direct mechanism behind the \"≥5× build\" mandate (VG-ENGINE-TEARDOWN §3.10).\n *\n * The result is identical regardless of how work was sharded: every output is\n * sorted by relative path, so the build never depends on scheduling order. A\n * single-threaded inline path is always available (and used for small repos or\n * when the worker module isn't resolvable, e.g. under ts-only test runners),\n * producing byte-identical output to the pooled path.\n */\n\nexport interface ParseOptions {\n /** Worker count. Default: min(cores - 1, file count). 1 forces inline. */\n jobs?: number;\n /** Force the single-threaded path (tests, debugging). */\n inline?: boolean;\n /** Below this many files, run inline (worker spin-up isn't worth it). */\n inlineThreshold?: number;\n /** Live progress: called as files finish parsing (done of total). */\n onProgress?: (done: number, total: number) => void;\n /** `--grammars <dir>` override for the grammar .wasm files (offline/air-gapped). */\n grammarsDir?: string;\n /** Heap budget (MiB) checked as parse results accumulate; 0/unset skips. */\n memoryBudgetMb?: number;\n}\n\nconst DEFAULT_INLINE_THRESHOLD = 24;\n\nexport async function parseFiles(\n files: DiscoveredFile[],\n options: ParseOptions = {},\n): Promise<FileParse[]> {\n const threshold = options.inlineThreshold ?? DEFAULT_INLINE_THRESHOLD;\n const cores = Math.max(1, os.cpus()?.length ?? 1);\n // Precedence: explicit option (--jobs) → VG_JOBS env → cores - 1. Capping\n // workers caps peak memory too (each worker holds its own grammar set).\n const jobs = Math.max(1, options.jobs ?? envJobs() ?? (Math.min(cores - 1, files.length) || 1));\n\n const workerFile = resolveWorkerFile();\n const useInline =\n options.inline === true ||\n jobs <= 1 ||\n files.length < threshold ||\n workerFile === null;\n\n if (useInline) {\n // Inline runs in this process — apply the override directly.\n if (options.grammarsDir) setGrammarsOverride(options.grammarsDir);\n return sortByRel(await parseInline(files, options));\n }\n return sortByRel(await parsePooled(files, jobs, workerFile, options));\n}\n\n/** Check the accumulating heap every this-many completed files — frequent\n * enough to abort before a crash, cheap enough to be free. */\nconst MEM_CHECK_EVERY = 64;\n\nasync function parseInline(files: DiscoveredFile[], options: ParseOptions): Promise<FileParse[]> {\n const { onProgress, memoryBudgetMb = 0 } = options;\n const out: FileParse[] = [];\n onProgress?.(0, files.length);\n for (const file of files) {\n try {\n const source = fs.readFileSync(file.abs, 'utf8');\n out.push(await parseSource(file.rel, file.lang.id, source));\n } catch (err) {\n // A wasm-level parse crash can leave the language's reused parser\n // mid-state; drop it so the failure stays contained to this file.\n resetParser(file.lang.id);\n out.push(emptyParse(file, `parse failed: ${(err as Error).message}`));\n }\n onProgress?.(out.length, files.length);\n if (out.length % MEM_CHECK_EVERY === 0) checkMemoryBudget('parse', memoryBudgetMb);\n }\n return out;\n}\n\nasync function parsePooled(\n files: DiscoveredFile[],\n jobs: number,\n workerFile: string,\n options: ParseOptions,\n): Promise<FileParse[]> {\n const { onProgress, grammarsDir, memoryBudgetMb = 0 } = options;\n // Dynamic import so tinypool isn't loaded for inline-only runs.\n const { default: Tinypool } = await import('tinypool');\n // VG_WORKER_HEAP_MB caps each worker's old-generation heap so one runaway\n // parse cannot swallow the whole machine; unset = platform default.\n const workerHeapMb = envWorkerHeapMb();\n const pool = new Tinypool({\n filename: workerFile,\n maxThreads: jobs,\n minThreads: 1,\n ...(workerHeapMb ? { resourceLimits: { maxOldGenerationSizeMb: workerHeapMb } } : {}),\n });\n try {\n // More, smaller buckets than threads → finer live progress + better load\n // balancing. Round-robin keeps shards balanced; the final sort makes the\n // output independent of bucket count, so determinism is unaffected.\n const total = files.length;\n const buckets = chunk(\n files.map<ParseTask>((f) => ({ rel: f.rel, abs: f.abs, lang: f.lang.id })),\n Math.min(total, jobs * 8),\n );\n let done = 0;\n onProgress?.(0, total);\n const results = await Promise.all(\n buckets.map((b) =>\n (pool.run({ tasks: b, grammarsDir }) as Promise<FileParse[]>).then((r) => {\n done += b.length;\n onProgress?.(done, total);\n // Results accumulate in *this* process; guard its heap as they land.\n checkMemoryBudget('parse', memoryBudgetMb);\n return r;\n }),\n ),\n );\n return results.flat();\n } catch (err) {\n if (isWorkerOom(err)) {\n throw new ResourceLimitError(\n `graph build stopped: a parse worker exceeded its ${workerHeapMb ?? '?'} MiB heap cap ` +\n `(VG_WORKER_HEAP_MB). Raise the cap, exclude the offending files (--exclude), or ` +\n `run single-threaded with --jobs 1.`,\n );\n }\n throw err;\n } finally {\n await pool.destroy();\n }\n}\n\nfunction isWorkerOom(err: unknown): boolean {\n const e = err as { code?: string; message?: string } | null;\n return e?.code === 'ERR_WORKER_OUT_OF_MEMORY' || /out of memory/i.test(e?.message ?? '');\n}\n\nfunction resolveWorkerFile(): string | null {\n // Only the compiled .js worker is runnable by a bare worker_thread. Under a\n // TS-only runner (vitest/tsx) the .js won't exist → fall back to inline.\n const here = path.dirname(fileURLToPath(import.meta.url));\n const candidate = path.join(here, 'parse-worker.js');\n return fs.existsSync(candidate) ? candidate : null;\n}\n\nfunction chunk<T>(items: T[], buckets: number): T[][] {\n const out: T[][] = Array.from({ length: Math.min(buckets, items.length || 1) }, () => []);\n if (out.length === 0) return [];\n // Round-robin keeps shard sizes balanced regardless of file ordering.\n items.forEach((item, i) => out[i % out.length].push(item));\n return out.filter((c) => c.length > 0);\n}\n\nfunction sortByRel(parses: FileParse[]): FileParse[] {\n return parses.sort((a, b) => (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0));\n}\n\nfunction emptyParse(file: DiscoveredFile, warning: string): FileParse {\n return {\n rel: file.rel,\n lang: file.lang.id,\n hash: '',\n bytes: 0,\n defs: [],\n calls: [],\n imports: [],\n heritage: [],\n typeRefs: [],\n guards: [],\n warnings: [warning],\n };\n}\n","import * as path from 'node:path';\nimport ts from 'typescript';\nimport { edgeId } from './ids.js';\nimport type { EdgeKind, GraphEdge, GraphNode, NodeKind, ResolverKind } from '../schema.js';\n\n/**\n * Precise TS/JS resolution via the TypeScript Compiler API — the type checker\n * itself, in-process, no external tool, `typescript` already a dependency. It\n * resolves `this.x()`, member calls, imported/aliased calls and heritage\n * exactly, which the heuristic rung structurally cannot (real codebases are\n * dominated by member calls → 0% heuristic resolution). Default-on for TS/JS.\n *\n * Deterministic: a ts.Program over the same files + options + compiler version\n * yields the same resolution; edges are stably sorted. Edges carry\n * `resolution: \"tsc\"`, confidence 1.0, and are authoritative for covered files.\n */\n\nconst PRECISE_KIND = 'tsc' satisfies ResolverKind;\n\nexport interface TsResolveResult {\n edges: GraphEdge[];\n /** Repo-relative files the program covered (tsc is authoritative for these). */\n coveredFiles: Set<string>;\n stats: { files: number; calls: number; jsx: number; heritage: number; resolved: number };\n}\n\n/** One walked file's raw checker output, before the cross-file interface\n * bridge. Every edge's `src` node lives in this file, so results partition\n * cleanly by file — the unit the incremental tsc cache stores and reuses. */\nexport interface TsFilePartial {\n /** The program produced a SourceFile for this file (tsc is authoritative). */\n covered: boolean;\n edges: GraphEdge[];\n interfaceCalls: Array<{ srcId: string; interfaceId: string; method: string }>;\n stats: { calls: number; jsx: number; heritage: number; resolved: number };\n}\n\nexport function tsResolveEdges(\n root: string,\n tsFiles: { rel: string; abs: string }[],\n nodes: GraphNode[],\n): TsResolveResult {\n const partials = tsWalkFiles(root, tsFiles, tsFiles, [], nodes);\n return assembleTsResult(tsFiles.map((f) => f.rel), partials, nodes);\n}\n\n/**\n * Walk `walkFiles` with the type checker and return per-file partial results.\n * `mapFiles` is the full file set edge targets may map into (superset of\n * walkFiles — a scoped walk still resolves calls INTO unchanged files).\n * `extraRootFiles` are added as program roots without being walked: ambient\n * declaration files (`.d.ts`, `declare global`/`declare module`) that shape\n * checker answers for every file without being imported by any of them.\n */\nexport function tsWalkFiles(\n root: string,\n walkFiles: { rel: string; abs: string }[],\n mapFiles: { rel: string; abs: string }[],\n extraRootFiles: { rel: string; abs: string }[],\n nodes: GraphNode[],\n): Map<string, TsFilePartial> {\n const partials = new Map<string, TsFilePartial>();\n if (walkFiles.length === 0) return partials;\n\n const absToRel = new Map(mapFiles.map((f) => [normalize(f.abs), f.rel]));\n const options = compilerOptions(root);\n const rootAbs = new Set(walkFiles.map((f) => f.abs));\n for (const f of extraRootFiles) rootAbs.add(f.abs);\n let program: ts.Program;\n try {\n program = ts.createProgram([...rootAbs], options);\n } catch {\n return partials; // never let resolution break the build\n }\n const checker = program.getTypeChecker();\n\n const nodesByFile = new Map<string, GraphNode[]>();\n const fileNodeByRel = new Map<string, GraphNode>();\n for (const n of nodes) {\n if (n.kind === 'file') {\n fileNodeByRel.set(n.file, n);\n continue;\n }\n if (n.kind === 'external') continue;\n const list = nodesByFile.get(n.file);\n if (list) list.push(n);\n else nodesByFile.set(n.file, [n]);\n }\n\n const relForAbs = (abs: string): string | undefined => absToRel.get(normalize(abs));\n\n for (const file of walkFiles) {\n const sf = program.getSourceFile(file.abs);\n if (!sf) {\n partials.set(file.rel, {\n covered: false,\n edges: [],\n interfaceCalls: [],\n stats: { calls: 0, jsx: 0, heritage: 0, resolved: 0 },\n });\n continue;\n }\n const edges = new Map<string, GraphEdge>();\n const stats = { calls: 0, jsx: 0, heritage: 0, resolved: 0 };\n // A method call on an interface-typed receiver resolves to the interface\n // (its method signatures are not graph nodes), so DI-injected services never\n // got a call edge to the concrete implementation. Record such calls here;\n // the cross-file bridge runs in assembleTsResult once ALL covered files'\n // `implements` edges are known.\n const interfaceCalls: Array<{ srcId: string; interfaceId: string; method: string }> = [];\n const fileNodes = nodesByFile.get(file.rel) ?? [];\n const fileNode = fileNodeByRel.get(file.rel);\n\n const lineOf = (pos: number): number => sf.getLineAndCharacterOfPosition(pos).line + 1;\n\n const visit = (node: ts.Node): void => {\n if (ts.isCallExpression(node) || ts.isNewExpression(node)) {\n stats.calls++;\n const target = resolveTarget(checker, node.expression, nodesByFile, relForAbs);\n if (target) {\n // Attribute to the enclosing def, falling back to the file node for\n // top-level calls — mirrors the heuristic so test-linkage and\n // centrality see the same call granularity.\n const src = enclosing(fileNodes, lineOf(node.getStart(sf))) ?? fileNode;\n if (src && src.id !== target.id) {\n add(edges, callKind(target), src.id, target.id);\n stats.resolved++;\n // Interface-typed method call (`svc.method()` where svc: IFoo): the\n // target is the interface node, and the method name is the accessed\n // property. Record it for the single-implementation bridge below.\n if (target.kind === 'interface' && ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression)) {\n interfaceCalls.push({ srcId: src.id, interfaceId: target.id, method: node.expression.name.text });\n }\n }\n }\n } else if (ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node)) {\n // JSX component usage (`<Foo/>`) is a render — a call in the graph.\n // Dominant cross-module link in React/Next code, which the heuristic and\n // a CallExpression-only walk both miss. Lowercase tags are intrinsic\n // HTML elements and resolve to nothing in-repo (skipped).\n if (isComponentTag(node.tagName)) {\n stats.jsx++;\n const target = resolveTarget(checker, node.tagName, nodesByFile, relForAbs);\n if (target) {\n const src = enclosing(fileNodes, lineOf(node.getStart(sf))) ?? fileNode;\n if (src && src.id !== target.id) {\n add(edges, callKind(target), src.id, target.id);\n stats.resolved++;\n }\n }\n }\n } else if (ts.isClassDeclaration(node) && node.heritageClauses) {\n const classLine = lineOf(node.getStart(sf));\n const src = enclosing(fileNodes, classLine);\n for (const clause of node.heritageClauses) {\n const kind: EdgeKind = clause.token === ts.SyntaxKind.ImplementsKeyword ? 'implements' : 'extends';\n for (const t of clause.types) {\n stats.heritage++;\n const target = resolveTarget(checker, t.expression, nodesByFile, relForAbs);\n if (src && target && src.id !== target.id) {\n add(edges, kind, src.id, target.id);\n stats.resolved++;\n }\n }\n }\n }\n ts.forEachChild(node, visit);\n };\n visit(sf);\n\n partials.set(file.rel, { covered: true, edges: [...edges.values()], interfaceCalls, stats });\n }\n\n return partials;\n}\n\n/**\n * Merge per-file partials (fresh walks and cache hits alike) into the final\n * result, then run the single-implementation interface bridge over the merged\n * edge set. `orderedRels` fixes iteration order to the original file order so\n * the output — including edge `count` accumulation — is byte-identical to a\n * single full walk regardless of which files came from cache.\n *\n * Single-implementation bridge: for each interface with EXACTLY ONE\n * implementing class, redirect its recorded interface-typed calls to the\n * implementation's matching method. This is the DI edge that makes impact_of /\n * tests_for / find_path work on the concrete service. Skipped when an\n * interface has zero or several implementations (genuinely ambiguous — the\n * references→interface edge already recorded the dependency).\n */\nexport function assembleTsResult(\n orderedRels: string[],\n partials: Map<string, TsFilePartial>,\n nodes: GraphNode[],\n): TsResolveResult {\n const nodesByFile = new Map<string, GraphNode[]>();\n for (const n of nodes) {\n if (n.kind === 'file' || n.kind === 'external') continue;\n const list = nodesByFile.get(n.file);\n if (list) list.push(n);\n else nodesByFile.set(n.file, [n]);\n }\n const byId = new Map<string, GraphNode>();\n for (const list of nodesByFile.values()) for (const n of list) byId.set(n.id, n);\n\n const edges = new Map<string, GraphEdge>();\n const covered = new Set<string>();\n const stats = { files: 0, calls: 0, jsx: 0, heritage: 0, resolved: 0 };\n const interfaceCalls: Array<{ srcId: string; interfaceId: string; method: string }> = [];\n for (const rel of orderedRels) {\n const p = partials.get(rel);\n if (!p || !p.covered) continue;\n covered.add(rel);\n stats.files++;\n stats.calls += p.stats.calls;\n stats.jsx += p.stats.jsx;\n stats.heritage += p.stats.heritage;\n stats.resolved += p.stats.resolved;\n // Edge ids never collide across files (src always lives in the walked\n // file), so re-seeding a shared map reproduces the full-walk map exactly.\n for (const e of p.edges) edges.set(e.id, { ...e });\n interfaceCalls.push(...p.interfaceCalls);\n }\n\n const implsByInterface = new Map<string, string[]>();\n for (const e of edges.values()) {\n if (e.kind !== 'implements' && e.kind !== 'extends') continue;\n if (byId.get(e.dst)?.kind !== 'interface') continue;\n const list = implsByInterface.get(e.dst);\n if (list) list.push(e.src);\n else implsByInterface.set(e.dst, [e.src]);\n }\n for (const { srcId, interfaceId, method } of interfaceCalls) {\n const impls = implsByInterface.get(interfaceId);\n if (!impls || impls.length !== 1) continue;\n const impl = byId.get(impls[0]);\n if (!impl) continue;\n const target = (nodesByFile.get(impl.file) ?? []).find(\n (n) => (n.kind === 'method' || n.kind === 'function') && n.qualifiedName === `${impl.qualifiedName}.${method}`,\n );\n if (target && target.id !== srcId) {\n add(edges, 'call', srcId, target.id);\n stats.resolved++;\n }\n }\n\n return { edges: [...edges.values()], coveredFiles: covered, stats };\n}\n\n/** A render/invoke target (function/method/class/component) is a `call`; other\n * kinds (interface/property/…) are `references`. */\nfunction callKind(target: GraphNode): EdgeKind {\n return target.kind === 'function' ||\n target.kind === 'method' ||\n target.kind === 'class' ||\n target.kind === 'component'\n ? 'call'\n : 'references';\n}\n\n/** Is a JSX tag a component (resolvable in-repo) vs an intrinsic HTML element? */\nfunction isComponentTag(tag: ts.JsxTagNameExpression): boolean {\n if (ts.isIdentifier(tag)) return /^[A-Z]/.test(tag.text);\n // `<Namespace.Component/>` / `<obj.Member/>` — a property access is a component ref.\n return ts.isPropertyAccessExpression(tag);\n}\n\nfunction resolveTarget(\n checker: ts.TypeChecker,\n expr: ts.Node,\n nodesByFile: Map<string, GraphNode[]>,\n relForAbs: (abs: string) => string | undefined,\n): GraphNode | null {\n let sym = checker.getSymbolAtLocation(expr);\n if (!sym) return null;\n if (sym.flags & ts.SymbolFlags.Alias) {\n try {\n sym = checker.getAliasedSymbol(sym);\n } catch {\n /* keep original */\n }\n }\n const decls = sym.declarations;\n if (!decls) return null;\n for (const decl of decls) {\n const df = decl.getSourceFile();\n const rel = relForAbs(df.fileName);\n if (!rel) continue; // declaration is external (node_modules / lib)\n const fileNodes = nodesByFile.get(rel);\n if (!fileNodes) continue;\n const line = df.getLineAndCharacterOfPosition(decl.getStart(df)).line + 1;\n // Pick the node for this declaration, using its syntax kind to disambiguate\n // when several nodes start on the same line (e.g. a single-line class and\n // its method) — the type checker knows whether we want the method or the\n // class, so a name/line collision never picks the wrong one.\n const node = pickNode(fileNodes, line, expectedKinds(decl));\n if (node) return node;\n }\n return null;\n}\n\n/** Node kinds a declaration could map to (for same-line tie-breaking). */\nfunction expectedKinds(decl: ts.Node): Set<NodeKind> {\n if (ts.isMethodDeclaration(decl) || ts.isMethodSignature(decl)) return new Set(['method']);\n if (ts.isFunctionDeclaration(decl) || ts.isFunctionExpression(decl) || ts.isArrowFunction(decl)) {\n return new Set(['function', 'method', 'component']);\n }\n if (ts.isClassDeclaration(decl) || ts.isClassExpression(decl)) return new Set(['class', 'component']);\n if (ts.isInterfaceDeclaration(decl)) return new Set(['interface']);\n if (\n ts.isPropertyDeclaration(decl) ||\n ts.isPropertySignature(decl) ||\n ts.isGetAccessorDeclaration(decl) ||\n ts.isSetAccessorDeclaration(decl)\n ) {\n return new Set(['property', 'method']);\n }\n if (ts.isConstructorDeclaration(decl)) return new Set(['class', 'method']);\n if (ts.isVariableDeclaration(decl)) return new Set(['function', 'property', 'component']);\n return new Set();\n}\n\n/**\n * The node for a declaration at `line`: among nodes starting exactly there,\n * prefer one whose kind the declaration expects, then the smallest span, then\n * the lexicographically smaller id (a stable, order-independent tiebreak). Falls\n * back to the smallest enclosing node when nothing starts on that line.\n */\nfunction pickNode(nodes: GraphNode[], line: number, want: Set<NodeKind>): GraphNode | undefined {\n let best: GraphNode | undefined;\n for (const n of nodes) {\n if (n.span.start !== line) continue;\n if (!best || better(n, best, want)) best = n;\n }\n return best ?? enclosing(nodes, line);\n}\n\nfunction better(n: GraphNode, best: GraphNode, want: Set<NodeKind>): boolean {\n const nWanted = want.has(n.kind);\n const bWanted = want.has(best.kind);\n if (nWanted !== bWanted) return nWanted;\n const nSize = n.span.end - n.span.start;\n const bSize = best.span.end - best.span.start;\n if (nSize !== bSize) return nSize < bSize;\n return n.id < best.id;\n}\n\nfunction compilerOptions(root: string): ts.CompilerOptions {\n const base: ts.CompilerOptions = {\n allowJs: true,\n checkJs: false,\n skipLibCheck: true,\n noEmit: true,\n noResolve: false,\n target: ts.ScriptTarget.ES2022,\n module: ts.ModuleKind.ESNext,\n moduleResolution: ts.ModuleResolutionKind.Bundler,\n jsx: ts.JsxEmit.Preserve,\n allowImportingTsExtensions: true,\n resolveJsonModule: true,\n };\n // Honor the project's tsconfig (paths/baseUrl) for accurate module resolution.\n // Prefer tsconfig.json, then tsconfig.base.json (Nx/Turborepo), and follow\n // `extends` chains — real monorepos put path aliases in a base config that\n // per-package configs extend. getParsedCommandLineOfConfigFile resolves the\n // whole chain (parseJsonConfigFileContent does not).\n const configPath =\n ts.findConfigFile(root, ts.sys.fileExists, 'tsconfig.json') ??\n ts.findConfigFile(root, ts.sys.fileExists, 'tsconfig.base.json');\n if (configPath) {\n try {\n const host: ts.ParseConfigFileHost = {\n ...ts.sys,\n onUnRecoverableConfigFileDiagnostic: () => {\n /* tolerate broken config — fall back to base */\n },\n };\n const parsed = ts.getParsedCommandLineOfConfigFile(configPath, {}, host);\n if (parsed) {\n // Keep the project's module map (baseUrl/paths) but force our read-only,\n // permissive compile settings on top so resolution is maximal.\n return { ...parsed.options, ...base, baseUrl: parsed.options.baseUrl, paths: parsed.options.paths };\n }\n } catch {\n /* fall back to base */\n }\n }\n return base;\n}\n\nfunction add(map: Map<string, GraphEdge>, kind: EdgeKind, src: string, dst: string): void {\n const id = edgeId(kind, src, dst);\n const existing = map.get(id);\n if (existing) {\n existing.count = (existing.count ?? 1) + 1;\n return;\n }\n map.set(id, { id, kind, src, dst, resolution: PRECISE_KIND, confidence: 1.0, count: 1 });\n}\n\nfunction enclosing(nodes: GraphNode[], line: number): GraphNode | undefined {\n let best: GraphNode | undefined;\n for (const n of nodes) {\n if (n.span.start <= line && n.span.end >= line) {\n if (!best || n.span.end - n.span.start < best.span.end - best.span.start) best = n;\n }\n }\n return best;\n}\n\nfunction normalize(p: string): string {\n return path.resolve(p).split(path.sep).join('/');\n}\n","import * as crypto from 'node:crypto';\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport ts from 'typescript';\nimport { cacheDir } from './cache.js';\nimport { stableStringify } from './serialize.js';\nimport type { TsFilePartial } from './ts-resolver.js';\n\n/**\n * Incremental cache for the tsc precise-resolution rung — the change-scoped\n * downstream stage of VG gap-closure item 2c. The parse cache made parse\n * incremental; this makes the single most expensive downstream stage (the\n * ts.Program + checker walk, ~70% of warm-refresh time) scale with change\n * size instead of repo size.\n *\n * Soundness: a file's checker output can depend only on (a) its own content,\n * (b) the content of files it transitively imports, and (c) ambient\n * declarations (`.d.ts` files and `declare global` / `declare module`\n * blocks), which shape checker answers program-wide without any import edge.\n * The per-file cache key therefore hashes all three, so any change that could\n * alter the output invalidates the entry — an over-approximation, never an\n * under-approximation. The mutation-corpus byte-identity gate\n * (incremental-identity.test.ts) enforces warm ≡ cold over this cache.\n */\n\n// /1: initial version.\nconst TSC_CACHE_VERSION = 'vg-tsc-cache/1';\n\nconst AMBIENT_RE = /\\bdeclare\\s+(global|module)\\b/;\n\ninterface TscEntry {\n /** Content hash the ambient flag (and key, if present) was computed from. */\n hash: string;\n /** File contributes ambient declarations (.d.ts / declare global / declare module). */\n ambient: boolean;\n /** Full invalidation key (own hash + import closure + ambient hash). */\n key?: string;\n partial?: TsFilePartial;\n}\n\ninterface TscCacheFile {\n version: string;\n toolVersion: string;\n ts: string;\n entries: Record<string, TscEntry>;\n}\n\nexport interface TscCache {\n /** The cached per-file result, iff the invalidation key matches. */\n get(rel: string, key: string): TsFilePartial | undefined;\n set(rel: string, hash: string, key: string, partial: TsFilePartial): void;\n /**\n * Whether a file contributes ambient declarations. Reuses the stored flag\n * when the content hash matches; otherwise re-reads the file (changed files\n * only — cheap) and re-scans.\n */\n isAmbient(rel: string, hash: string, abs: string): boolean;\n /** Drop entries for files no longer present. */\n prune(currentRels: Set<string>): void;\n save(): void;\n}\n\nfunction tscCachePath(root: string): string {\n return path.join(cacheDir(root), 'tsc-cache.json');\n}\n\nexport function loadTscCache(root: string, opts: { toolVersion: string; disabled?: boolean }): TscCache {\n const file = tscCachePath(root);\n let data: TscCacheFile = {\n version: TSC_CACHE_VERSION,\n toolVersion: opts.toolVersion,\n ts: ts.version,\n entries: {},\n };\n\n if (!opts.disabled && fs.existsSync(file)) {\n try {\n const loaded = JSON.parse(fs.readFileSync(file, 'utf8')) as TscCacheFile;\n if (\n loaded.version === TSC_CACHE_VERSION &&\n loaded.toolVersion === opts.toolVersion &&\n loaded.ts === ts.version &&\n loaded.entries\n ) {\n data = loaded;\n }\n } catch {\n /* corrupt cache — start fresh */\n }\n }\n\n return {\n get(rel, key) {\n if (opts.disabled) return undefined;\n const entry = data.entries[rel];\n return entry && entry.key === key ? entry.partial : undefined;\n },\n set(rel, hash, key, partial) {\n const ambient = data.entries[rel]?.hash === hash ? data.entries[rel].ambient : detectAmbient(rel, abs$(root, rel));\n data.entries[rel] = { hash, ambient, key, partial };\n },\n isAmbient(rel, hash, abs) {\n const entry = data.entries[rel];\n if (entry && entry.hash === hash) return entry.ambient;\n const ambient = detectAmbient(rel, abs);\n // Record hash+ambient now (key/partial filled in after a walk); a later\n // `set` for the same hash reuses this flag without re-reading the file.\n data.entries[rel] = { hash, ambient };\n return ambient;\n },\n prune(currentRels) {\n for (const rel of Object.keys(data.entries)) {\n if (!currentRels.has(rel)) delete data.entries[rel];\n }\n },\n save() {\n if (opts.disabled) return;\n fs.mkdirSync(cacheDir(root), { recursive: true });\n fs.writeFileSync(file, stableStringify(data, 0));\n },\n };\n}\n\nfunction abs$(root: string, rel: string): string {\n return path.join(root, rel);\n}\n\nfunction detectAmbient(rel: string, abs: string): boolean {\n if (rel.endsWith('.d.ts')) return true;\n try {\n return AMBIENT_RE.test(fs.readFileSync(abs, 'utf8'));\n } catch {\n // Unreadable → treat as ambient so it always invalidates rather than\n // silently going stale.\n return true;\n }\n}\n\n/**\n * A stable fingerprint of the effective compiler configuration: the fully\n * resolved tsconfig option set (extends chains flattened), so a config edit\n * anywhere in the chain invalidates every entry.\n */\nexport function tsConfigFingerprint(root: string): string {\n const configPath =\n ts.findConfigFile(root, ts.sys.fileExists, 'tsconfig.json') ??\n ts.findConfigFile(root, ts.sys.fileExists, 'tsconfig.base.json');\n if (!configPath) return sha('none');\n try {\n const host: ts.ParseConfigFileHost = {\n ...ts.sys,\n onUnRecoverableConfigFileDiagnostic: () => {},\n };\n const parsed = ts.getParsedCommandLineOfConfigFile(configPath, {}, host);\n return sha(stableStringify(parsed?.options ?? 'unparsed', 0));\n } catch {\n return sha('unparsed');\n }\n}\n\n/**\n * Per-file invalidation keys for a set of TS/JS files, from the heuristic\n * resolver's file-level import graph. Each key covers the file's own content\n * hash, the content hashes of its transitive import closure, and the shared\n * ambient hash (all ambient files + resolved tsconfig + compiler version).\n */\nexport function tscKeys(\n rels: string[],\n hashes: Map<string, string>,\n importsByFile: Map<string, Set<string>>,\n ambientHash: string,\n): Map<string, string> {\n const keys = new Map<string, string>();\n for (const rel of rels) {\n // Transitive import closure, restricted to hashed corpus files. Iterative\n // BFS; cycles terminate via the visited set.\n const closure: string[] = [];\n const visited = new Set<string>([rel]);\n const queue = [rel];\n while (queue.length) {\n const cur = queue.pop()!;\n for (const dep of importsByFile.get(cur) ?? []) {\n if (visited.has(dep)) continue;\n visited.add(dep);\n if (hashes.has(dep)) closure.push(dep);\n queue.push(dep);\n }\n }\n closure.sort();\n const lines = closure.map((c) => `${c}\\x00${hashes.get(c)}`);\n keys.set(rel, sha(`${TSC_CACHE_VERSION}\\n${ambientHash}\\n${rel}\\x00${hashes.get(rel)}\\n${lines.join('\\n')}`));\n }\n return keys;\n}\n\n/** The shared ambient component: every ambient file's (rel, hash) plus the\n * resolved compiler configuration and compiler version. */\nexport function ambientFingerprint(\n ambient: Array<{ rel: string; hash: string }>,\n configFingerprint: string,\n): string {\n const lines = ambient\n .map((a) => `${a.rel}\\x00${a.hash}`)\n .sort()\n .join('\\n');\n return sha(`${configFingerprint}\\n${ts.version}\\n${lines}`);\n}\n\nfunction sha(s: string): string {\n return crypto.createHash('sha256').update(s).digest('hex');\n}\n","import type { GraphEdge, NodeKind, ResolverKind } from '../schema.js';\n\n/**\n * Edge-level epistemic confidence.\n *\n * Tree-sitter gives syntax, not semantics: a call graph built purely from it is\n * name-matching — heuristic, i.e. conjecture wearing a deterministic costume.\n * Rather than hide that behind a single 0..1 `confidence`, every edge also\n * carries a coarse, honest *tier* describing HOW it was resolved, so a consumer\n * can filter for the assurance it needs (`WHERE epistemic = 'observed'`).\n *\n * observed — resolved by a semantic resolver (SCIP / stack-graphs / the\n * TypeScript type checker) to a concrete declaration, or a\n * structural fact read directly off the parse tree\n * (containment, an import that resolves to a corpus file).\n * name-matched — matched by symbol name only, with no reachability proof.\n * This is the heuristic call/heritage/reference graph: useful,\n * but conjecture, not observation.\n * declared — asserted by a manifest, config, or an external boundary the\n * graph does not model internally (external package imports,\n * test/coverage linkage). True as a declaration; not verified\n * against code.\n *\n * `epistemic` is the coarse honesty axis; the numeric `confidence` remains the\n * fine gradient within a tier. The tier is a pure, deterministic function of the\n * edge's own fields plus the kind of its destination node.\n */\nexport type EpistemicTier = 'observed' | 'name-matched' | 'declared';\n\nexport const EPISTEMIC_TIERS: readonly EpistemicTier[] = ['observed', 'name-matched', 'declared'];\n\n/** Semantic resolvers observe the real target; the heuristic rung only guesses it. */\nconst SEMANTIC_RESOLVERS = new Set<ResolverKind>(['scip', 'stackgraph', 'tsc']);\n\n/**\n * Classify one edge into its epistemic tier. `dstKind` is the destination node's\n * kind (used to tell an internal import from an external-package import); omit it\n * only when the destination is unknown, in which case imports fall back to\n * `declared` (the safer, less-assured label).\n */\nexport function classifyEpistemic(edge: GraphEdge, dstKind?: NodeKind): EpistemicTier {\n // A semantic resolver saw the concrete declaration — the strongest tier.\n if (SEMANTIC_RESOLVERS.has(edge.resolution)) return 'observed';\n\n switch (edge.kind) {\n case 'contains':\n // Direct syntactic containment from the parse tree — observed, not guessed.\n return 'observed';\n case 'import':\n // Resolved to a real file in the corpus is observed; a bare external\n // package reference is only declared (we never see inside it).\n return dstKind === 'external' || dstKind === undefined ? 'declared' : 'observed';\n case 'test':\n case 'coverage':\n // Asserted by test structure / a coverage report, not verified against\n // the runtime call graph.\n return 'declared';\n default:\n // call / extends / implements / references resolved by the heuristic rung:\n // a symbol-name match with no reachability justification.\n return 'name-matched';\n }\n}\n\n/** Count edges by epistemic tier (deterministic key order). */\nexport function epistemicBreakdown(edges: GraphEdge[]): Record<EpistemicTier, number> {\n const out: Record<EpistemicTier, number> = { observed: 0, 'name-matched': 0, declared: 0 };\n for (const e of edges) {\n if (e.epistemic) out[e.epistemic]++;\n }\n return out;\n}\n","/**\n * Project-context ingest for semantic `vg ask` (Fusion robustness).\n *\n * Turns non-AST project files into graph nodes of kind `document` so agents can\n * answer the questions developers ask most often without grepping the tree:\n *\n * - Human docs: README, AGENTS.md, markdown/txt\n * - Env *examples* only (never live `.env`)\n * - Package manifests (package.json, go.mod, Cargo.toml, …)\n * - Docker / Compose\n * - CI workflows\n * - Build/tool config (tsconfig, turbo, vite, …)\n * - API contracts (OpenAPI, GraphQL, protobuf)\n * - Task runners (Makefile, Justfile)\n *\n * Bodies are secret-scrubbed and size-capped. Lockfiles and live secrets stay\n * out. Pure classification helpers are unit-tested; discovery respects the same\n * SKIP_DIRS / .gitignore rules as source discovery.\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport ignore, { type Ignore } from 'ignore';\nimport { redactSecrets } from '../core-open/utils/redact.js';\nimport { nodeId } from './ids.js';\nimport { isSkippedDirName, SKIP_FILES } from './discover.js';\nimport type { GraphNode } from '../schema.js';\n\n/** Soft cap on characters stored/embedded per document (keeps index snappy). */\nexport const DOC_BODY_MAX_CHARS = 8_000;\n/** Hard cap on bytes we will open for a context file. */\nexport const DOC_FILE_MAX_BYTES = 512 * 1024;\n/** Soft cap on document nodes per build (large monorepos). */\nexport const DOC_MAX_FILES = 600;\n\n// ── Document categories (signature / lang / importance) ────────────────────\n\nexport type DocCategory =\n | 'markdown'\n | 'text'\n | 'env-example'\n | 'manifest'\n | 'docker'\n | 'compose'\n | 'ci'\n | 'build-config'\n | 'api-contract'\n | 'task-runner'\n | 'workspace'\n | 'infra'\n | 'other-config';\n\nexport interface DiscoverDocsOptions {\n root: string;\n exclude?: string[];\n paths?: string[];\n maxFiles?: number;\n}\n\nexport interface DiscoveredDoc {\n rel: string;\n abs: string;\n /** @deprecated use category — kept as alias of category for older tests */\n kind: DocCategory;\n category: DocCategory;\n}\n\n// Human documentation\nconst DOC_EXTENSIONS = new Set(['.md', '.mdx', '.txt', '.rst', '.adoc']);\n\n// Env *examples* only\nconst ENV_EXAMPLE_NAMES = new Set([\n 'example.env',\n 'env.example',\n '.env.example',\n '.env.sample',\n '.env.template',\n '.env.development.example',\n '.env.local.example',\n 'dotenv.example',\n]);\n\n// Exact basenames → category (lowercase)\nconst EXACT_BASENAME: Record<string, DocCategory> = {\n // Manifests / package managers\n 'package.json': 'manifest',\n 'package.yaml': 'manifest',\n 'package.yml': 'manifest',\n 'pyproject.toml': 'manifest',\n 'setup.cfg': 'manifest',\n 'requirements.txt': 'manifest',\n 'requirements-dev.txt': 'manifest',\n 'pipfile': 'manifest',\n 'go.mod': 'manifest',\n 'go.work': 'manifest',\n 'cargo.toml': 'manifest',\n 'composer.json': 'manifest',\n 'gemfile': 'manifest',\n 'podfile': 'manifest',\n 'pubspec.yaml': 'manifest',\n 'mix.exs': 'manifest',\n 'build.gradle': 'manifest',\n 'build.gradle.kts': 'manifest',\n 'settings.gradle': 'manifest',\n 'settings.gradle.kts': 'manifest',\n 'pom.xml': 'manifest',\n 'project.clj': 'manifest',\n 'stack.yaml': 'manifest',\n 'package.swift': 'manifest',\n // Workspace / monorepo\n 'pnpm-workspace.yaml': 'workspace',\n 'pnpm-workspace.yml': 'workspace',\n 'lerna.json': 'workspace',\n 'nx.json': 'workspace',\n 'turbo.json': 'workspace',\n 'rush.json': 'workspace',\n 'workspace.json': 'workspace',\n // Docker\n dockerfile: 'docker',\n 'dockerfile.dev': 'docker',\n 'dockerfile.prod': 'docker',\n 'dockerfile.local': 'docker',\n containerfile: 'docker',\n // Compose\n 'docker-compose.yml': 'compose',\n 'docker-compose.yaml': 'compose',\n 'compose.yml': 'compose',\n 'compose.yaml': 'compose',\n 'docker-compose.dev.yml': 'compose',\n 'docker-compose.prod.yml': 'compose',\n 'docker-compose.override.yml': 'compose',\n // Task runners\n makefile: 'task-runner',\n gnumakefile: 'task-runner',\n justfile: 'task-runner',\n 'taskfile.yml': 'task-runner',\n 'taskfile.yaml': 'task-runner',\n rakefile: 'task-runner',\n // Build / tool config (exact)\n 'tsconfig.json': 'build-config',\n 'jsconfig.json': 'build-config',\n 'vite.config.ts': 'build-config',\n 'vite.config.js': 'build-config',\n 'vite.config.mjs': 'build-config',\n 'vitest.config.ts': 'build-config',\n 'vitest.config.js': 'build-config',\n 'jest.config.js': 'build-config',\n 'jest.config.ts': 'build-config',\n 'jest.config.cjs': 'build-config',\n 'webpack.config.js': 'build-config',\n 'webpack.config.ts': 'build-config',\n 'rollup.config.js': 'build-config',\n 'esbuild.config.js': 'build-config',\n 'next.config.js': 'build-config',\n 'next.config.mjs': 'build-config',\n 'next.config.ts': 'build-config',\n 'nuxt.config.ts': 'build-config',\n 'nuxt.config.js': 'build-config',\n 'astro.config.mjs': 'build-config',\n 'svelte.config.js': 'build-config',\n 'remix.config.js': 'build-config',\n 'angular.json': 'build-config',\n 'babel.config.js': 'build-config',\n 'babel.config.json': 'build-config',\n '.babelrc': 'build-config',\n '.babelrc.js': 'build-config',\n '.babelrc.json': 'build-config',\n 'eslint.config.js': 'build-config',\n 'eslint.config.mjs': 'build-config',\n 'eslint.config.cjs': 'build-config',\n 'eslint.config.ts': 'build-config',\n '.eslintrc': 'build-config',\n '.eslintrc.js': 'build-config',\n '.eslintrc.cjs': 'build-config',\n '.eslintrc.json': 'build-config',\n '.eslintrc.yml': 'build-config',\n '.prettierrc': 'build-config',\n '.prettierrc.js': 'build-config',\n '.prettierrc.json': 'build-config',\n '.prettierrc.yml': 'build-config',\n 'prettier.config.js': 'build-config',\n 'prettier.config.cjs': 'build-config',\n 'ruff.toml': 'build-config',\n '.ruff.toml': 'build-config',\n 'pytest.ini': 'build-config',\n 'tox.ini': 'build-config',\n 'mypy.ini': 'build-config',\n '.mypy.ini': 'build-config',\n 'phpunit.xml': 'build-config',\n 'phpunit.xml.dist': 'build-config',\n // CI exact\n 'jenkinsfile': 'ci',\n '.gitlab-ci.yml': 'ci',\n '.travis.yml': 'ci',\n 'azure-pipelines.yml': 'ci',\n 'buildkite.yml': 'ci',\n 'cloudbuild.yaml': 'ci',\n 'appveyor.yml': 'ci',\n 'circle.yml': 'ci',\n // Deploy / infra (root-level common names)\n 'vercel.json': 'infra',\n 'netlify.toml': 'infra',\n 'wrangler.toml': 'infra',\n 'wrangler.json': 'infra',\n 'wrangler.jsonc': 'infra',\n 'fly.toml': 'infra',\n 'railway.toml': 'infra',\n 'render.yaml': 'infra',\n 'app.yaml': 'infra',\n 'Procfile': 'infra',\n 'procfile': 'infra',\n 'heroku.yml': 'infra',\n 'serverless.yml': 'infra',\n 'serverless.yaml': 'infra',\n 'sam.yaml': 'infra',\n 'samconfig.toml': 'infra',\n 'cdk.json': 'infra',\n 'pulumi.yaml': 'infra',\n 'terraform.tf': 'infra',\n // Agent / project meta (also covered by .md extension)\n 'agents.md': 'markdown',\n 'claude.md': 'markdown',\n 'codeowners': 'other-config',\n '.nvmrc': 'other-config',\n '.node-version': 'other-config',\n '.python-version': 'other-config',\n 'runtime.txt': 'other-config',\n '.tool-versions': 'other-config',\n 'editorconfig': 'other-config',\n '.editorconfig': 'other-config',\n};\n\n// Prefix / pattern basenames\nconst BASENAME_PREFIX: Array<{ re: RegExp; category: DocCategory }> = [\n { re: /^dockerfile(\\.|$)/i, category: 'docker' },\n { re: /^docker-compose(\\.|$)/i, category: 'compose' },\n { re: /^compose\\.(ya?ml)$/i, category: 'compose' },\n { re: /^tsconfig(\\..+)?\\.json$/i, category: 'build-config' },\n { re: /^jsconfig(\\..+)?\\.json$/i, category: 'build-config' },\n { re: /^vite\\.config\\./i, category: 'build-config' },\n { re: /^vitest\\.config\\./i, category: 'build-config' },\n { re: /^jest\\.config\\./i, category: 'build-config' },\n { re: /^webpack\\.config\\./i, category: 'build-config' },\n { re: /^rollup\\.config\\./i, category: 'build-config' },\n { re: /^next\\.config\\./i, category: 'build-config' },\n { re: /^nuxt\\.config\\./i, category: 'build-config' },\n { re: /^astro\\.config\\./i, category: 'build-config' },\n { re: /^eslint\\.config\\./i, category: 'build-config' },\n { re: /^\\.eslintrc/i, category: 'build-config' },\n { re: /^openapi\\./i, category: 'api-contract' },\n { re: /^swagger\\./i, category: 'api-contract' },\n { re: /^requirements(-\\w+)?\\.txt$/i, category: 'manifest' },\n { re: /^dockerfile/i, category: 'docker' },\n];\n\n// Path patterns (posix relative)\nconst PATH_PATTERNS: Array<{ re: RegExp; category: DocCategory }> = [\n // GitHub Actions / workflows\n { re: /^\\.github\\/workflows\\/.+\\.ya?ml$/i, category: 'ci' },\n { re: /^\\.github\\/actions\\/.+/i, category: 'ci' },\n { re: /^\\.circleci\\/.+\\.ya?ml$/i, category: 'ci' },\n { re: /^\\.buildkite\\/.+/i, category: 'ci' },\n // Helm / k8s (values + charts — not every template blob)\n { re: /^charts\\/[^/]+\\/(chart\\.ya?ml|values.*\\.ya?ml)$/i, category: 'infra' },\n { re: /^deploy\\/.+\\.ya?ml$/i, category: 'infra' },\n { re: /^k8s\\/.+\\.ya?ml$/i, category: 'infra' },\n { re: /^kubernetes\\/.+\\.ya?ml$/i, category: 'infra' },\n { re: /^infra\\/.+\\.ya?ml$/i, category: 'infra' },\n { re: /^terraform\\/.+\\.tf$/i, category: 'infra' },\n // API contracts by path\n { re: /(^|\\/)(openapi|swagger)(\\.|\\/)/i, category: 'api-contract' },\n { re: /(^|\\/)api(-)?(spec|schema|contracts?)\\//i, category: 'api-contract' },\n];\n\n// Extensions for API / schema contracts\nconst API_EXTENSIONS = new Set(['.graphql', '.gql', '.proto', '.avsc', '.thrift']);\n\n// Importance by category (feeds hubs/ranking lightly; embed text carries meaning)\nconst IMPORTANCE: Record<DocCategory, number> = {\n markdown: 0.1,\n text: 0.06,\n 'env-example': 0.12,\n manifest: 0.16,\n docker: 0.14,\n compose: 0.15,\n ci: 0.14,\n 'build-config': 0.11,\n 'api-contract': 0.13,\n 'task-runner': 0.13,\n workspace: 0.14,\n infra: 0.12,\n 'other-config': 0.08,\n};\n\nfunction toPosix(p: string): string {\n return p.split(path.sep).join('/');\n}\n\nfunction buildRootIgnore(root: string, exclude: string[]): Ignore {\n const ig = ignore();\n const gitignorePath = path.join(root, '.gitignore');\n if (fs.existsSync(gitignorePath)) {\n try {\n ig.add(fs.readFileSync(gitignorePath, 'utf8'));\n } catch {\n /* ignore */\n }\n }\n if (exclude.length) ig.add(exclude);\n return ig;\n}\n\n/**\n * Classify a path as project-context (document) or not. Pure — no I/O.\n * Live secret env files return false.\n */\nexport function classifyProjectContext(relOrName: string): DocCategory | null {\n const rel = relOrName.replace(/\\\\/g, '/');\n const base = path.basename(rel);\n const baseLower = base.toLowerCase();\n\n // Never live secrets\n if (/^\\.env($|\\.)/i.test(base) && !isEnvExampleName(baseLower)) return null;\n // Never lockfiles / pnp (also in SKIP_FILES)\n if (SKIP_FILES.has(baseLower)) return null;\n\n if (isEnvExampleName(baseLower)) return 'env-example';\n\n const exact = EXACT_BASENAME[baseLower] ?? EXACT_BASENAME[base];\n if (exact) return exact;\n\n for (const { re, category } of BASENAME_PREFIX) {\n if (re.test(base)) return category;\n }\n\n for (const { re, category } of PATH_PATTERNS) {\n if (re.test(rel)) return category;\n }\n\n const ext = path.extname(baseLower);\n if (DOC_EXTENSIONS.has(ext)) return ext === '.txt' ? 'text' : 'markdown';\n if (API_EXTENSIONS.has(ext)) return 'api-contract';\n\n // OpenAPI/Swagger by extension + name\n if ((ext === '.yaml' || ext === '.yml' || ext === '.json') && /openapi|swagger|asyncapi/i.test(base)) {\n return 'api-contract';\n }\n\n // docker-compose variants with extra suffixes\n if (/^docker-compose\\..+\\.ya?ml$/i.test(base) || /^compose\\..+\\.ya?ml$/i.test(base)) {\n return 'compose';\n }\n\n return null;\n}\n\n/** @deprecated prefer classifyProjectContext — true when path is project context. */\nexport function isDocPath(relOrName: string): boolean {\n return classifyProjectContext(relOrName) !== null;\n}\n\nfunction isEnvExampleName(baseLower: string): boolean {\n if (ENV_EXAMPLE_NAMES.has(baseLower)) return true;\n if (/^(\\.)?env\\.(example|sample|template)(\\.|$)/i.test(baseLower)) return true;\n if (/^example\\.env/i.test(baseLower)) return true;\n return false;\n}\n\n\n/**\n * Discover project-context files under root. Deterministic order.\n * Never opens live secret env files or lockfiles.\n */\nexport function discoverDocs(options: DiscoverDocsOptions): DiscoveredDoc[] {\n const root = path.resolve(options.root);\n const maxFiles = options.maxFiles ?? DOC_MAX_FILES;\n const rootIg = buildRootIgnore(root, options.exclude ?? []);\n const scopeAbs = (options.paths?.length ? options.paths.map((p) => path.resolve(root, p)) : [root]).filter((p) =>\n fs.existsSync(p),\n );\n\n const found = new Map<string, DiscoveredDoc>();\n\n const consider = (abs: string): void => {\n if (found.size >= maxFiles) return;\n const rel = toPosix(path.relative(root, abs));\n if (!rel || rel.startsWith('..')) return;\n if (rootIg.ignores(rel)) return;\n const base = path.basename(abs);\n if (SKIP_FILES.has(base.toLowerCase())) return;\n const category = classifyProjectContext(rel);\n if (!category) return;\n try {\n const st = fs.statSync(abs);\n if (!st.isFile() || st.size > DOC_FILE_MAX_BYTES) return;\n if (st.size === 0) return;\n } catch {\n return;\n }\n found.set(rel, { rel, abs, kind: category, category });\n };\n\n const walk = (dir: string, depth: number): void => {\n if (found.size >= maxFiles || depth > 12) return;\n let entries: fs.Dirent[];\n try {\n entries = fs.readdirSync(dir, { withFileTypes: true });\n } catch {\n return;\n }\n for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {\n if (found.size >= maxFiles) return;\n const abs = path.join(dir, entry.name);\n const rel = toPosix(path.relative(root, abs));\n if (entry.isDirectory()) {\n if (isSkippedDirName(entry.name)) continue;\n // Workflows / .github must be walked even if other tools ignore them\n if (rel && rootIg.ignores(`${rel}/`) && !rel.startsWith('.github')) continue;\n walk(abs, depth + 1);\n } else if (entry.isFile()) {\n consider(abs);\n }\n }\n };\n\n for (const scope of scopeAbs) {\n try {\n const st = fs.statSync(scope);\n if (st.isDirectory()) walk(scope, 0);\n else if (st.isFile()) consider(scope);\n } catch {\n /* skip */\n }\n }\n\n return [...found.values()].sort((a, b) => a.rel.localeCompare(b.rel));\n}\n\n/**\n * Prepare a body optimized for retrieval: secret-scrub + optional smart trim\n * for huge manifests / OpenAPI so scripts & paths stay near the front.\n */\nexport function prepareDocBody(rel: string, raw: string, category: DocCategory): string {\n const scrubbed = redactSecrets(raw);\n if (scrubbed.length <= DOC_BODY_MAX_CHARS) return scrubbed;\n\n if (category === 'manifest' && path.basename(rel).toLowerCase() === 'package.json') {\n return summarizePackageJson(scrubbed);\n }\n if (category === 'api-contract' && /\\.(ya?ml|json)$/i.test(rel)) {\n // Prefer head (usually openapi version + info + paths start)\n return scrubbed.slice(0, DOC_BODY_MAX_CHARS);\n }\n if (category === 'ci') {\n return scrubbed.slice(0, DOC_BODY_MAX_CHARS);\n }\n return scrubbed.slice(0, DOC_BODY_MAX_CHARS);\n}\n\n/** Keep name, scripts, dependencies* for package.json when truncated. */\nfunction summarizePackageJson(raw: string): string {\n try {\n const o = JSON.parse(raw) as Record<string, unknown>;\n const keep: Record<string, unknown> = {};\n for (const k of [\n 'name',\n 'version',\n 'description',\n 'private',\n 'type',\n 'packageManager',\n 'engines',\n 'workspaces',\n 'scripts',\n 'dependencies',\n 'devDependencies',\n 'peerDependencies',\n 'optionalDependencies',\n 'main',\n 'bin',\n 'exports',\n ]) {\n if (o[k] !== undefined) keep[k] = o[k];\n }\n const s = JSON.stringify(keep, null, 2);\n return s.length <= DOC_BODY_MAX_CHARS ? s : s.slice(0, DOC_BODY_MAX_CHARS);\n } catch {\n return raw.slice(0, DOC_BODY_MAX_CHARS);\n }\n}\n\n/**\n * Build `document` graph nodes from discovered project-context files.\n */\nexport function documentNodesFromDocs(docs: DiscoveredDoc[]): GraphNode[] {\n const nodes: GraphNode[] = [];\n for (const d of docs) {\n let raw = '';\n try {\n raw = fs.readFileSync(d.abs, 'utf8');\n } catch {\n continue;\n }\n const category = d.category ?? d.kind;\n const scrubbed = prepareDocBody(d.rel, raw, category);\n if (!scrubbed.trim()) continue;\n\n const name = path.basename(d.rel);\n const qualifiedName = d.rel.replace(/\\\\/g, '/');\n const id = nodeId({\n kind: 'document',\n qualifiedName,\n file: qualifiedName,\n signature: category,\n });\n const lineCount = Math.max(1, scrubbed.split('\\n').length);\n const langTag =\n category === 'markdown'\n ? 'md'\n : category === 'env-example'\n ? 'env'\n : category === 'manifest'\n ? 'manifest'\n : category === 'docker' || category === 'compose'\n ? 'docker'\n : category === 'ci'\n ? 'ci'\n : category === 'api-contract'\n ? 'api'\n : category === 'build-config'\n ? 'config'\n : category === 'task-runner'\n ? 'task'\n : category === 'workspace'\n ? 'workspace'\n : category === 'infra'\n ? 'infra'\n : 'txt';\n\n nodes.push({\n id,\n kind: 'document',\n name,\n qualifiedName,\n file: qualifiedName,\n span: { start: 1, end: lineCount },\n lang: langTag,\n signature: `document:${category}`,\n doc: scrubbed,\n importance: IMPORTANCE[category] ?? 0.05,\n centrality: { degree: 0, pagerank: 0, betweenness: 0, eigenvector: 0 },\n area: -1,\n isHub: false,\n tested: null,\n });\n }\n return nodes.sort((a, b) => a.file.localeCompare(b.file) || a.id.localeCompare(b.id));\n}\n\n/** Exported for tests / docs: all exact basenames we treat as project context. */\nexport function projectContextExactBasenames(): string[] {\n return Object.keys(EXACT_BASENAME).sort((a, b) => a.localeCompare(b));\n}\n","import { redactSecrets } from '../../core-open/utils/redact.js';\nimport type { ToolchainSpan } from './types.js';\n\n/**\n * Shared helpers for the toolchain extractors. Everything here is pure and\n * deterministic — no clock, no randomness, no filesystem.\n */\n\n/** Hard cap on bytes an extractor will parse. Beyond this the file is skipped. */\nexport const TOOLCHAIN_FILE_MAX_BYTES = 2 * 1024 * 1024;\n\n/** Cap on nodes emitted from a single file — a generated 40k-line manifest is not worth unbounded graph. */\nexport const TOOLCHAIN_NODES_PER_FILE_MAX = 2_000;\n\n/** Cap on the length of a `doc` summary. */\nconst DOC_MAX_CHARS = 240;\n\n/**\n * Line-offset index for a source file: converts a byte offset to a 1-based\n * line number. Built once per file, then binary-searched — extracting a\n * thousand spans must not be quadratic in file size.\n */\nexport class LineIndex {\n /** Byte offset at which each line starts. */\n private readonly starts: number[];\n\n constructor(source: string) {\n const starts = [0];\n for (let i = 0; i < source.length; i++) {\n if (source.charCodeAt(i) === 10 /* \\n */) starts.push(i + 1);\n }\n this.starts = starts;\n }\n\n /** 1-based line number containing `offset`. */\n lineAt(offset: number): number {\n if (offset <= 0) return 1;\n let lo = 0;\n let hi = this.starts.length - 1;\n while (lo < hi) {\n const mid = (lo + hi + 1) >> 1;\n if (this.starts[mid] <= offset) lo = mid;\n else hi = mid - 1;\n }\n return lo + 1;\n }\n\n /** Span covering the byte range `[start, end)`. */\n span(start: number, end: number): ToolchainSpan {\n const s = this.lineAt(start);\n // `end` is exclusive; step back one byte so a range ending exactly at a\n // newline reports the line it ends on rather than the next, empty one.\n const e = this.lineAt(Math.max(start, end - 1));\n return { start: s, end: Math.max(s, e) };\n }\n\n get lineCount(): number {\n return this.starts.length;\n }\n}\n\n/**\n * Prepare a human-readable summary for storage.\n *\n * GUARDRAILS §1.1 is redact-at-ingest, not at display: IaC and CI files are\n * exactly where live credentials turn up, so every summary that reaches a node\n * passes through here before it is ever written to `graph.json`.\n */\nexport function safeDoc(text: string | undefined): string | undefined {\n if (!text) return undefined;\n const collapsed = text.replace(/\\s+/g, ' ').trim();\n if (!collapsed) return undefined;\n const redacted = redactSecrets(collapsed);\n return redacted.length > DOC_MAX_CHARS ? `${redacted.slice(0, DOC_MAX_CHARS - 1)}…` : redacted;\n}\n\n/**\n * Is this value a reference to a secret rather than a secret itself?\n *\n * Extractors record *references* (`secrets.NPM_TOKEN`, `${var.db_password}`,\n * a `secretKeyRef` name) because those are the useful graph edges. A literal\n * that merely looks secret-shaped is dropped rather than recorded.\n */\nexport function isSecretReference(value: string): boolean {\n return (\n /^\\$\\{\\{?\\s*secrets\\./i.test(value) ||\n /^\\$\\{?\\s*(var|local)\\./i.test(value) ||\n /^\\$\\{?[A-Z0-9_]+\\}?$/.test(value)\n );\n}\n\n/**\n * Normalise a container image reference into `{registry, repository, tag, digest}`.\n *\n * Deliberately does not apply Docker Hub's implicit `docker.io/library` default:\n * the linker matches what a repository actually wrote, and inventing a registry\n * would make `web:latest` in a Compose file stop matching `web:latest` in a\n * workflow's `docker build -t`.\n */\nexport interface ImageRef {\n /** The full reference as written. */\n raw: string;\n /** Everything before the tag/digest. */\n repository: string;\n tag?: string;\n digest?: string;\n}\n\nexport function parseImageRef(raw: string): ImageRef | null {\n const value = raw.trim();\n if (!value || /\\s/.test(value)) return null;\n // An expansion — `${{ env.IMAGE }}`, `{{ .Values.image }}`, or a bare\n // `$BASE` build arg — is not a resolvable image. Recording it would create a\n // node that matches nothing, so it is dropped rather than guessed at.\n if (value.includes('$') || value.includes('{{')) return null;\n\n const atIdx = value.lastIndexOf('@');\n let digest: string | undefined;\n let rest = value;\n if (atIdx > 0) {\n digest = value.slice(atIdx + 1);\n rest = value.slice(0, atIdx);\n }\n\n let tag: string | undefined;\n const colonIdx = rest.lastIndexOf(':');\n // A colon before the last `/` is a registry port (`localhost:5000/img`), not a tag.\n if (colonIdx > 0 && colonIdx > rest.lastIndexOf('/')) {\n tag = rest.slice(colonIdx + 1);\n rest = rest.slice(0, colonIdx);\n }\n if (!rest) return null;\n return { raw: value, repository: rest, tag, digest };\n}\n\n/**\n * The identity two image references are matched on by the linker: repository\n * plus digest when pinned, else repository plus tag. `latest` is treated as a\n * real tag — pretending it is absent makes unrelated images collide.\n */\nexport function imageIdentity(ref: ImageRef): string {\n if (ref.digest) return `${ref.repository}@${ref.digest}`;\n return ref.tag ? `${ref.repository}:${ref.tag}` : ref.repository;\n}\n\n/** Deterministic sort for drafts: by qualifiedName, then kind. */\nexport function byQualifiedName<T extends { qualifiedName: string; kind: string }>(a: T, b: T): number {\n return a.qualifiedName.localeCompare(b.qualifiedName, 'en') || a.kind.localeCompare(b.kind, 'en');\n}\n\n/** POSIX-normalise a repo-relative path (Windows hosts write `\\`). */\nexport function toPosix(rel: string): string {\n return rel.replace(/\\\\/g, '/');\n}\n\n/**\n * Resolve a relative path against a file's directory, POSIX-style, without\n * touching the filesystem. Returns null if the result escapes the repo root —\n * a Compose `build.context` of `../../../etc` must never produce a node\n * claiming to be a repository file.\n */\nexport function resolveRelative(fromFileRel: string, target: string): string | null {\n const base = toPosix(fromFileRel).split('/').slice(0, -1);\n const parts = toPosix(target).split('/');\n const out = [...base];\n for (const part of parts) {\n if (!part || part === '.') continue;\n if (part === '..') {\n if (!out.length) return null; // escaped the root\n out.pop();\n continue;\n }\n out.push(part);\n }\n const joined = out.join('/');\n return joined || null;\n}\n","import YAML from 'yaml';\nimport type { LineIndex } from './util.js';\nimport type { ToolchainSpan } from './types.js';\n\n/**\n * Shared YAML access for the toolchain extractors.\n *\n * Uses the `yaml` package rather than a tree-sitter grammar. That is a\n * deliberate departure from \"tree-sitter everywhere\": `yaml` is already an\n * audited dependency of this package, and it gives us three things a grammar\n * would force us to reimplement by hand —\n *\n * 1. **byte ranges on every node** (`node.range`), which is the whole reason\n * the plan preferred a CST over `serde`-style deserialisation;\n * 2. **multi-document streams** (`---`), which every non-trivial Kubernetes\n * manifest uses;\n * 3. **anchors, aliases and merge keys**, which Helm and Compose files use\n * heavily and which a raw CST would leave unresolved.\n *\n * Everything below is read-only and non-throwing: malformed YAML yields an\n * empty document list plus a warning, never an exception.\n */\n\n/** A parsed YAML document with the AST retained for range lookups. */\nexport interface YamlDoc {\n /** Plain-JS view, with aliases resolved. `null` when the document is empty. */\n value: unknown;\n /** The underlying AST document, for `rangeOf` lookups. */\n ast: YAML.Document.Parsed;\n /** 0-based index within the stream. */\n index: number;\n}\n\nexport interface YamlParseResult {\n docs: YamlDoc[];\n warnings: string[];\n}\n\n/**\n * Parse a YAML stream. Never throws.\n *\n * `maxAliasCount` is clamped: YAML's \"billion laughs\" alias-expansion bomb is a\n * real denial-of-service vector for a scanner that runs over untrusted\n * repositories, and the default limit is generous. A document that trips the\n * limit is reported as a warning and skipped, not expanded.\n */\nexport function parseYamlStream(rel: string, source: string): YamlParseResult {\n const warnings: string[] = [];\n let parsed: YAML.Document.Parsed[];\n try {\n parsed = YAML.parseAllDocuments(source, {\n // Parsing itself does not expand aliases — the bomb only detonates on\n // materialisation, so the alias budget is applied at `toJS` below.\n logLevel: 'silent',\n uniqueKeys: false,\n });\n } catch (err) {\n warnings.push(`${rel}: YAML parse failed (${(err as Error).message})`);\n return { docs: [], warnings };\n }\n\n const docs: YamlDoc[] = [];\n parsed.forEach((ast, index) => {\n if (ast.errors.length) {\n warnings.push(`${rel}: YAML document ${index + 1} has errors — skipped`);\n return;\n }\n let value: unknown;\n try {\n value = ast.toJS({ maxAliasCount: 100 });\n } catch (err) {\n warnings.push(`${rel}: YAML document ${index + 1} could not be materialised (${(err as Error).message})`);\n return;\n }\n if (value === null || value === undefined) return;\n docs.push({ value, ast, index });\n });\n\n return { docs, warnings };\n}\n\n/**\n * Byte range of the value at `path` within a document, as a line span.\n * Falls back to the document's own range when the path has no node — a span is\n * always better than no span, because it still anchors an editor decoration.\n */\nexport function spanAt(doc: YamlDoc, lines: LineIndex, path: (string | number)[]): ToolchainSpan {\n const node = path.length ? safeGetIn(doc.ast, path) : doc.ast.contents;\n const range = nodeRange(node) ?? nodeRange(doc.ast.contents);\n if (!range) return { start: 1, end: 1 };\n return lines.span(range[0], range[2] ?? range[1]);\n}\n\nfunction safeGetIn(ast: YAML.Document.Parsed, path: (string | number)[]): unknown {\n try {\n return ast.getIn(path, true);\n } catch {\n return undefined;\n }\n}\n\nfunction nodeRange(node: unknown): [number, number, number] | null {\n const range = (node as { range?: [number, number, number] } | null)?.range;\n return Array.isArray(range) ? range : null;\n}\n\n/** Read a nested value from a plain-JS document view. */\nexport function getPath(value: unknown, path: (string | number)[]): unknown {\n let current = value;\n for (const key of path) {\n if (current === null || typeof current !== 'object') return undefined;\n current = (current as Record<string | number, unknown>)[key];\n }\n return current;\n}\n\n/** Read a string, or undefined when absent/non-string. Numbers are stringified. */\nexport function getString(value: unknown, path: (string | number)[]): string | undefined {\n const found = getPath(value, path);\n if (typeof found === 'string') return found;\n if (typeof found === 'number' || typeof found === 'boolean') return String(found);\n return undefined;\n}\n\n/** Read an array, or an empty array when absent/non-array. */\nexport function getArray(value: unknown, path: (string | number)[]): unknown[] {\n const found = getPath(value, path);\n return Array.isArray(found) ? found : [];\n}\n\n/** Read a plain object's entries in a deterministic (sorted-key) order. */\nexport function getRecordEntries(value: unknown, path: (string | number)[]): [string, unknown][] {\n const found = getPath(value, path);\n if (!found || typeof found !== 'object' || Array.isArray(found)) return [];\n return Object.entries(found as Record<string, unknown>).sort(([a], [b]) => a.localeCompare(b, 'en'));\n}\n\n/**\n * Does this source look like a Go-templated Helm manifest?\n *\n * Helm templates are not valid YAML before rendering (`{{- if }}` lines break\n * the document), so the Kubernetes extractor must decline them and the Helm\n * extractor handles chart metadata and values instead.\n */\nexport function looksTemplated(source: string): boolean {\n return /\\{\\{-?\\s*(if|range|with|end|define|template|include|toYaml|\\.Values|\\.Release|\\.Chart)/.test(\n source,\n );\n}\n","import {\n LineIndex,\n parseImageRef,\n resolveRelative,\n safeDoc,\n TOOLCHAIN_NODES_PER_FILE_MAX,\n} from './util.js';\nimport { getArray, getPath, getRecordEntries, getString, parseYamlStream, spanAt } from './yaml.js';\nimport type {\n ToolchainEdgeDraft,\n ToolchainExtraction,\n ToolchainExtractor,\n ToolchainNodeDraft,\n} from './types.js';\n\n/**\n * Docker Compose extraction.\n *\n * Each entry under `services:` becomes a `resource` node. A service either\n * `builds_from` an image reference (`image:`) or points at a Dockerfile\n * (`build.context` + `build.dockerfile`) — the latter is the join the linker\n * uses to connect a Compose service to the Dockerfile node, and through it to\n * the source files that Dockerfile copies in.\n *\n * `depends_on` accepts both Compose forms: the short list form and the long\n * map form with `condition:`.\n */\n\n/** Default Dockerfile name when `build.dockerfile` is omitted. */\nconst DEFAULT_DOCKERFILE = 'Dockerfile';\n\nexport const composeExtractor: ToolchainExtractor = {\n format: 'compose',\n\n matches(rel, category) {\n if (category === 'compose') return true;\n return /(^|\\/)(docker-)?compose([.-][\\w.-]+)?\\.ya?ml$/i.test(rel);\n },\n\n extract(rel, source): ToolchainExtraction {\n const { docs, warnings } = parseYamlStream(rel, source);\n const lines = new LineIndex(source);\n const nodes: ToolchainNodeDraft[] = [];\n const edges: ToolchainEdgeDraft[] = [];\n\n const doc = docs[0];\n if (!doc) return { nodes, edges, warnings };\n\n const services = getRecordEntries(doc.value, ['services']);\n const declared = new Set(services.map(([name]) => `service:${name}`));\n\n for (const [name, service] of services) {\n if (nodes.length >= TOOLCHAIN_NODES_PER_FILE_MAX) {\n warnings.push(`${rel}: stopped at ${TOOLCHAIN_NODES_PER_FILE_MAX} nodes`);\n break;\n }\n const address = `service:${name}`;\n const image = getString(service, ['image']);\n const ports = getArray(service, ['ports']).map(String);\n\n nodes.push({\n kind: 'resource',\n name,\n qualifiedName: address,\n span: spanAt(doc, lines, ['services', name]),\n signature: 'compose.service',\n doc: safeDoc(\n [image && `image ${image}`, ports.length && `ports ${ports.join(', ')}`]\n .filter(Boolean)\n .join(', '),\n ),\n importance: 0.5,\n });\n\n // An `image:` reference — the join to a workload or a CI-built tag.\n if (image) {\n const ref = parseImageRef(image);\n if (ref) {\n nodes.push({\n kind: 'image',\n name: ref.repository.split('/').pop() ?? ref.repository,\n qualifiedName: `image:${ref.raw}`,\n span: spanAt(doc, lines, ['services', name, 'image']),\n signature: 'compose.image',\n doc: safeDoc(ref.tag ? `${ref.repository} tag ${ref.tag}` : ref.repository),\n importance: 0.3,\n });\n edges.push({ kind: 'builds_from', from: address, to: `image:${ref.raw}`, confidence: 1 });\n }\n }\n\n // A `build:` stanza — string shorthand or the long object form.\n const dockerfileRel = composeDockerfilePath(rel, service);\n if (dockerfileRel) {\n nodes.push({\n kind: 'image',\n name: dockerfileRel.split('/').pop() ?? dockerfileRel,\n qualifiedName: `dockerfile:${dockerfileRel}`,\n span: spanAt(doc, lines, ['services', name, 'build']),\n signature: 'compose.build',\n doc: safeDoc(`builds from ${dockerfileRel}`),\n importance: 0.4,\n });\n edges.push({\n kind: 'builds_from',\n from: address,\n to: `dockerfile:${dockerfileRel}`,\n confidence: 1,\n });\n }\n\n // `depends_on`: list form and map form.\n for (const target of composeDependsOn(service)) {\n const to = `service:${target}`;\n if (declared.has(to)) edges.push({ kind: 'depends_on', from: address, to, confidence: 1 });\n }\n\n // Published ports.\n for (const port of ports) {\n edges.push({ kind: 'exposes', from: address, to: `port:${port}`, confidence: 1 });\n }\n }\n\n // Port nodes for whatever `exposes` edges were emitted, so no edge dangles.\n const portTargets = new Set(\n edges.filter((e) => e.kind === 'exposes').map((e) => e.to),\n );\n for (const target of [...portTargets].sort()) {\n nodes.push({\n kind: 'property',\n name: target.slice('port:'.length),\n qualifiedName: target,\n span: { start: 1, end: 1 },\n signature: 'compose.port',\n importance: 0.1,\n });\n }\n\n return { nodes, edges, warnings };\n },\n};\n\n/** Repo-relative Dockerfile path for a service's `build:` stanza, if any. */\nfunction composeDockerfilePath(rel: string, service: unknown): string | null {\n const build = getPath(service, ['build']);\n if (build === undefined || build === null) return null;\n\n // Shorthand: `build: ./dir`\n if (typeof build === 'string') {\n return resolveRelative(rel, `${build}/${DEFAULT_DOCKERFILE}`);\n }\n if (typeof build !== 'object') return null;\n\n const context = getString(build, ['context']) ?? '.';\n const dockerfile = getString(build, ['dockerfile']) ?? DEFAULT_DOCKERFILE;\n // `dockerfile` is resolved relative to `context`, not to the compose file.\n return resolveRelative(rel, `${context}/${dockerfile}`);\n}\n\n/** Service names in a `depends_on`, in both supported shapes. */\nfunction composeDependsOn(service: unknown): string[] {\n const raw = getPath(service, ['depends_on']);\n if (Array.isArray(raw)) {\n return raw.filter((v): v is string => typeof v === 'string').sort();\n }\n if (raw && typeof raw === 'object') {\n return Object.keys(raw as Record<string, unknown>).sort();\n }\n return [];\n}\n","import {\n LineIndex,\n parseImageRef,\n resolveRelative,\n safeDoc,\n TOOLCHAIN_NODES_PER_FILE_MAX,\n toPosix,\n} from './util.js';\nimport type {\n ToolchainEdgeDraft,\n ToolchainExtraction,\n ToolchainExtractor,\n ToolchainNodeDraft,\n} from './types.js';\n\n/**\n * Dockerfile extraction — a deterministic scanner, no grammar.\n *\n * This follows the precedent set by `engine/sql-extract.ts` (a pure\n * deterministic extractor with no tree-sitter grammar) and is a deliberate\n * choice rather than a shortcut:\n *\n * - The Dockerfile format is line-oriented with a closed instruction set, an\n * escape-continuation rule and a `# syntax=` / `# escape=` directive\n * header. That is a scanner's natural shape.\n * - No Dockerfile grammar is published as a prebuilt `.wasm` by an upstream\n * we would be willing to add to the supply chain. The one npm package that\n * ships one is a single-maintainer package unrelated to the tree-sitter\n * org; adding it to an enterprise scanner's dependency set to save ~120\n * lines of transparent code is the wrong trade.\n * - The genuinely hard part of a Dockerfile — the shell inside `RUN` — is not\n * solved by a Dockerfile grammar either.\n *\n * ## What is extracted\n *\n * Each `FROM` opens a build stage (`image` node). `FROM x AS y` names it;\n * `COPY --from=` links stages. External base images become `image` nodes so the\n * linker can join a Dockerfile to the registry image a workload runs.\n */\n\n/** The instruction set we act on. Others are parsed and ignored. */\nconst INSTRUCTION = /^([A-Za-z][A-Za-z0-9_]*)\\s+([\\s\\S]*)$/;\n\ninterface LogicalLine {\n instruction: string;\n args: string;\n /** 1-based line the instruction starts on. */\n startLine: number;\n /** 1-based line the instruction ends on (after continuations). */\n endLine: number;\n}\n\n/**\n * Fold a Dockerfile into logical lines, honouring comments, blank lines and the\n * escape-character continuation (which `# escape=` can change to a backtick for\n * Windows containers).\n */\nexport function logicalLines(source: string): LogicalLine[] {\n const rawLines = source.split(/\\r?\\n/);\n let escapeChar = '\\\\';\n\n // Parser directives are only valid before the first non-comment line.\n for (const line of rawLines) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n if (!trimmed.startsWith('#')) break;\n const directive = /^#\\s*escape\\s*=\\s*(\\S)/i.exec(trimmed);\n if (directive) escapeChar = directive[1];\n }\n\n const out: LogicalLine[] = [];\n let buffer: string | null = null;\n let startLine = 0;\n\n for (let i = 0; i < rawLines.length; i++) {\n const raw = rawLines[i];\n const trimmed = raw.trim();\n\n // Comments and blank lines never continue an instruction: Docker strips\n // them between a continuation and the next fragment.\n if (!trimmed || trimmed.startsWith('#')) continue;\n\n const continues = trimmed.endsWith(escapeChar);\n const fragment = continues ? trimmed.slice(0, -1).trimEnd() : trimmed;\n\n if (buffer === null) {\n buffer = fragment;\n startLine = i + 1;\n } else {\n buffer += ` ${fragment}`;\n }\n\n if (!continues) {\n const match = INSTRUCTION.exec(buffer);\n if (match) {\n out.push({\n instruction: match[1].toUpperCase(),\n args: match[2].trim(),\n startLine,\n endLine: i + 1,\n });\n }\n buffer = null;\n }\n }\n\n // An unterminated continuation at EOF still yields its instruction.\n if (buffer !== null) {\n const match = INSTRUCTION.exec(buffer);\n if (match) {\n out.push({\n instruction: match[1].toUpperCase(),\n args: match[2].trim(),\n startLine,\n endLine: rawLines.length,\n });\n }\n }\n\n return out;\n}\n\n/** `FROM <image> [AS <name>]`, with `--platform=` flags stripped. */\nfunction parseFrom(args: string): { image: string; stage?: string } | null {\n const tokens = args.split(/\\s+/).filter(Boolean);\n const positional: string[] = [];\n for (const token of tokens) {\n if (token.startsWith('--')) continue; // --platform=…, --chmod=… etc.\n positional.push(token);\n }\n if (!positional.length) return null;\n const image = positional[0];\n // `AS name` is case-insensitive.\n const asIdx = positional.findIndex((t) => t.toUpperCase() === 'AS');\n const stage = asIdx > 0 && positional[asIdx + 1] ? positional[asIdx + 1] : undefined;\n return { image, stage };\n}\n\n/** `--from=<stage-or-image>` on a COPY instruction. */\nfunction parseCopyFrom(args: string): string | null {\n const match = /--from=(\\S+)/i.exec(args);\n return match ? match[1] : null;\n}\n\n/** Ports named by an EXPOSE instruction. */\nfunction parseExpose(args: string): string[] {\n return args\n .split(/\\s+/)\n .filter(Boolean)\n .filter((token) => !token.startsWith('--'));\n}\n\n/**\n * Concrete source paths a `COPY`/`ADD` reads from the build context.\n *\n * The last positional token is the destination, so it is excluded. Anything\n * that is not a plain path — a glob, a URL, a build-arg expansion, or a bare\n * `.` — is dropped: the cross-domain linker only wants paths it can match\n * exactly against files already in the graph, and a wrong match is worse than\n * no edge.\n */\nexport function copySourcePaths(args: string, hasFromFlag: boolean): string[] {\n if (hasFromFlag) return []; // sources come from another stage, not the repo\n const tokens = args.split(/\\s+/).filter(Boolean).filter((t) => !t.startsWith('--'));\n if (tokens.length < 2) return [];\n const sources = tokens.slice(0, -1);\n return sources\n .filter(\n (source) =>\n source !== '.' &&\n !source.includes('*') &&\n !source.includes('?') &&\n !source.includes('[') &&\n !source.includes('$') &&\n !/^https?:\\/\\//i.test(source),\n )\n .map((source) => source.replace(/^\\.\\//, ''))\n .sort();\n}\n\nexport const dockerfileExtractor: ToolchainExtractor = {\n format: 'dockerfile',\n\n matches(rel, category) {\n if (category === 'docker') return true;\n const base = toPosix(rel).split('/').pop()?.toLowerCase() ?? '';\n return base === 'dockerfile' || base === 'containerfile' || base.startsWith('dockerfile.');\n },\n\n extract(rel, source): ToolchainExtraction {\n const lines = new LineIndex(source);\n const nodes: ToolchainNodeDraft[] = [];\n const edges: ToolchainEdgeDraft[] = [];\n const warnings: string[] = [];\n\n const posixRel = toPosix(rel);\n const fileAddress = `dockerfile:${posixRel}`;\n\n // The Dockerfile itself — the anchor a Compose `build:` edge points at.\n nodes.push({\n kind: 'image',\n name: posixRel.split('/').pop() ?? posixRel,\n qualifiedName: fileAddress,\n span: { start: 1, end: Math.max(1, lines.lineCount) },\n signature: 'dockerfile',\n importance: 0.5,\n });\n\n const stages = new Map<string, string>(); // stage name (lowercased) → address\n /** stage address → candidate repo paths that stage copies from the context. */\n const copySources = new Map<string, Set<string>>();\n let stageIndex = 0;\n let currentStage: string | null = null;\n\n for (const line of logicalLines(source)) {\n if (nodes.length >= TOOLCHAIN_NODES_PER_FILE_MAX) {\n warnings.push(`${rel}: stopped at ${TOOLCHAIN_NODES_PER_FILE_MAX} nodes`);\n break;\n }\n\n switch (line.instruction) {\n case 'FROM': {\n const from = parseFrom(line.args);\n if (!from) break;\n const stageName = from.stage ?? String(stageIndex);\n const stageAddress = `${fileAddress}#${stageName}`;\n stages.set(stageName.toLowerCase(), stageAddress);\n currentStage = stageAddress;\n stageIndex++;\n\n nodes.push({\n kind: 'image',\n name: from.stage ?? `stage ${stageIndex - 1}`,\n qualifiedName: stageAddress,\n span: { start: line.startLine, end: line.endLine },\n signature: 'dockerfile.stage',\n doc: safeDoc(`from ${from.image}`),\n importance: 0.4,\n });\n edges.push({ kind: 'contains', from: fileAddress, to: stageAddress, confidence: 1 });\n\n // A base image that is another stage in this file is a stage edge;\n // otherwise it is an external registry image.\n const baseStage = stages.get(from.image.toLowerCase());\n if (baseStage && baseStage !== stageAddress) {\n edges.push({\n kind: 'builds_from',\n from: stageAddress,\n to: baseStage,\n confidence: 1,\n });\n } else {\n const ref = parseImageRef(from.image);\n // `FROM $BASE` / `FROM ${REGISTRY}/x` is a build-arg indirection we\n // cannot resolve without the build invocation — skip rather than\n // record a node that matches nothing.\n if (ref) {\n const imageAddress = `image:${ref.raw}`;\n nodes.push({\n kind: 'image',\n name: ref.repository.split('/').pop() ?? ref.repository,\n qualifiedName: imageAddress,\n span: { start: line.startLine, end: line.endLine },\n signature: 'dockerfile.base',\n doc: safeDoc(ref.tag ? `${ref.repository} tag ${ref.tag}` : ref.repository),\n importance: 0.3,\n });\n edges.push({\n kind: 'builds_from',\n from: stageAddress,\n to: imageAddress,\n confidence: 1,\n });\n }\n }\n break;\n }\n\n case 'COPY':\n case 'ADD': {\n const fromRef = parseCopyFrom(line.args);\n if (fromRef) {\n if (!currentStage) break;\n const target = stages.get(fromRef.toLowerCase());\n if (target && target !== currentStage) {\n edges.push({ kind: 'depends_on', from: currentStage, to: target, confidence: 1 });\n }\n break;\n }\n // Sources are read from the *build context*, which the Dockerfile\n // itself never states — it is chosen by whoever invokes the build.\n // The two conventions in the wild are \"context is the Dockerfile's\n // directory\" (`build: ./api`) and \"context is the repository root\"\n // (`docker build -f api/Dockerfile .`). Rather than guess, emit both\n // candidates: the linker keeps only paths that resolve to a file\n // already in the graph, so the wrong candidate costs nothing and the\n // right one is never missed.\n if (!currentStage) break;\n const forStage = copySources.get(currentStage) ?? new Set<string>();\n for (const source of copySourcePaths(line.args, false)) {\n const relativeToDockerfile = resolveRelative(posixRel, source);\n if (relativeToDockerfile) forStage.add(relativeToDockerfile);\n forStage.add(toPosix(source).replace(/^\\.\\//, ''));\n }\n if (forStage.size) copySources.set(currentStage, forStage);\n break;\n }\n\n case 'EXPOSE': {\n if (!currentStage) break;\n for (const port of parseExpose(line.args)) {\n const portAddress = `port:${port}`;\n nodes.push({\n kind: 'property',\n name: port,\n qualifiedName: portAddress,\n span: { start: line.startLine, end: line.endLine },\n signature: 'dockerfile.expose',\n importance: 0.1,\n });\n edges.push({ kind: 'exposes', from: currentStage, to: portAddress, confidence: 1 });\n }\n break;\n }\n\n default:\n break;\n }\n }\n\n const copySourcesByStage: Record<string, string[]> = {};\n for (const stage of [...copySources.keys()].sort()) {\n copySourcesByStage[stage] = [...(copySources.get(stage) ?? [])].sort();\n }\n\n return { nodes, edges, warnings, linkHints: { copySourcesByStage } };\n },\n};\n","import { LineIndex, parseImageRef, safeDoc, toPosix } from './util.js';\nimport { getArray, getRecordEntries, getString, parseYamlStream, spanAt } from './yaml.js';\nimport type {\n ToolchainEdgeDraft,\n ToolchainExtraction,\n ToolchainExtractor,\n ToolchainNodeDraft,\n} from './types.js';\n\n/**\n * Helm chart extraction.\n *\n * Helm templates under `templates/` are Go templates, not YAML — they do not\n * parse before rendering, and rendering them would mean running Helm. So this\n * extractor deliberately reads only the two files that *are* well-formed YAML\n * and carry the chart's identity:\n *\n * - `Chart.yaml` → the `chart` node, its version, and `depends_on` edges to\n * declared subchart dependencies;\n * - `values.yaml` → image references, which is what connects a chart to the\n * images a CI pipeline builds.\n *\n * That is a deliberate scope limit, not an oversight: claiming to understand an\n * unrendered template would mean inventing structure. What is extracted here is\n * declared fact.\n */\n\n/**\n * Common `values.yaml` shapes for an image. Helm has no schema, but these three\n * cover the overwhelming majority of charts in the wild, including the\n * `bitnami`/`stable` conventions.\n */\nfunction collectValuesImages(value: unknown, prefix: string[], out: Map<string, string[]>): void {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return;\n\n const repository = getString(value, ['repository']);\n const tag = getString(value, ['tag']);\n const registry = getString(value, ['registry']);\n if (repository) {\n const full = [registry, repository].filter(Boolean).join('/');\n const raw = tag ? `${full}:${tag}` : full;\n if (!out.has(raw)) out.set(raw, prefix);\n }\n\n // A plain `image: repo:tag` string.\n const direct = getString(value, ['image']);\n if (direct && parseImageRef(direct)) {\n if (!out.has(direct)) out.set(direct, [...prefix, 'image']);\n }\n\n for (const [key, child] of getRecordEntries(value, [])) {\n if (key === 'repository' || key === 'tag' || key === 'registry') continue;\n collectValuesImages(child, [...prefix, key], out);\n }\n}\n\nexport const helmExtractor: ToolchainExtractor = {\n format: 'helm',\n\n matches(rel) {\n const base = toPosix(rel).split('/').pop()?.toLowerCase() ?? '';\n if (base === 'chart.yaml' || base === 'chart.yml') return true;\n // Only a `values.yaml` that sits next to a chart is a Helm values file;\n // a bare `values.yaml` elsewhere is just config.\n return /(^|\\/)values([.-][\\w.-]+)?\\.ya?ml$/i.test(rel) && /(^|\\/)charts?\\//i.test(rel);\n },\n\n extract(rel, source): ToolchainExtraction {\n const { docs, warnings } = parseYamlStream(rel, source);\n const lines = new LineIndex(source);\n const nodes: ToolchainNodeDraft[] = [];\n const edges: ToolchainEdgeDraft[] = [];\n\n const doc = docs[0];\n if (!doc) return { nodes, edges, warnings };\n\n const base = toPosix(rel).split('/').pop()?.toLowerCase() ?? '';\n const isChartFile = base === 'chart.yaml' || base === 'chart.yml';\n\n if (isChartFile) {\n const name = getString(doc.value, ['name']);\n if (!name) return { nodes, edges, warnings };\n const version = getString(doc.value, ['version']);\n const appVersion = getString(doc.value, ['appVersion']);\n const address = `chart:${name}`;\n\n nodes.push({\n kind: 'chart',\n name,\n qualifiedName: address,\n span: spanAt(doc, lines, []),\n signature: 'helm.chart',\n doc: safeDoc(\n [version && `version ${version}`, appVersion && `app ${appVersion}`]\n .filter(Boolean)\n .join(', '),\n ),\n importance: 0.7,\n });\n\n // Declared subchart dependencies.\n for (const dependency of getArray(doc.value, ['dependencies'])) {\n const depName = getString(dependency, ['name']);\n if (!depName) continue;\n const depVersion = getString(dependency, ['version']);\n const depAddress = `chart:${depName}`;\n nodes.push({\n kind: 'chart',\n name: depName,\n qualifiedName: depAddress,\n span: spanAt(doc, lines, ['dependencies']),\n signature: 'helm.dependency',\n doc: safeDoc(depVersion ? `version ${depVersion}` : undefined),\n importance: 0.4,\n });\n edges.push({ kind: 'depends_on', from: address, to: depAddress, confidence: 1 });\n }\n\n return { nodes, edges, warnings };\n }\n\n // values.yaml — image references only.\n const images = new Map<string, string[]>();\n collectValuesImages(doc.value, [], images);\n for (const raw of [...images.keys()].sort()) {\n const ref = parseImageRef(raw);\n if (!ref) continue;\n nodes.push({\n kind: 'image',\n name: ref.repository.split('/').pop() ?? ref.repository,\n qualifiedName: `image:${ref.raw}`,\n span: spanAt(doc, lines, images.get(raw) ?? []),\n signature: 'helm.values.image',\n doc: safeDoc(ref.tag ? `${ref.repository} tag ${ref.tag}` : ref.repository),\n importance: 0.3,\n });\n }\n\n return { nodes, edges, warnings };\n },\n};\n","import { LineIndex, parseImageRef, safeDoc, TOOLCHAIN_NODES_PER_FILE_MAX } from './util.js';\nimport {\n getArray,\n getPath,\n getRecordEntries,\n getString,\n looksTemplated,\n parseYamlStream,\n spanAt,\n type YamlDoc,\n} from './yaml.js';\nimport type {\n ToolchainEdgeDraft,\n ToolchainExtraction,\n ToolchainExtractor,\n ToolchainNodeDraft,\n} from './types.js';\n\n/**\n * Kubernetes manifest extraction.\n *\n * Every document in the stream that carries both `apiVersion` and `kind`\n * becomes a node. Workload kinds (those with a pod template) additionally yield\n * `image` nodes for each container, which is what lets the linker join a\n * Deployment to the CI job that built its image.\n *\n * Selector→workload edges are matched *within the file*: a Service whose\n * `spec.selector` is a subset of a workload's pod labels `exposes` it. That is\n * a structural match on declared labels, not a guess, so it carries full\n * confidence — but only same-file, because a cross-file label match without\n * namespace resolution produces false pairs in a monorepo of many charts.\n */\n\n/** Workload kinds that own a pod template, and where that template lives. */\nconst WORKLOAD_TEMPLATE_PATHS: Record<string, (string | number)[]> = {\n Deployment: ['spec', 'template'],\n StatefulSet: ['spec', 'template'],\n DaemonSet: ['spec', 'template'],\n ReplicaSet: ['spec', 'template'],\n ReplicationController: ['spec', 'template'],\n Job: ['spec', 'template'],\n CronJob: ['spec', 'jobTemplate', 'spec', 'template'],\n Pod: [],\n};\n\n/** Container list paths within a pod spec, in extraction order. */\nconst CONTAINER_FIELDS = ['initContainers', 'containers', 'ephemeralContainers'] as const;\n\nfunction isKubernetesDoc(value: unknown): boolean {\n return typeof getString(value, ['apiVersion']) === 'string' && typeof getString(value, ['kind']) === 'string';\n}\n\n/** `namespace/kind/name` — unique within a cluster, and stable across edits. */\nfunction objectAddress(value: unknown): string | null {\n const kind = getString(value, ['kind']);\n const name = getString(value, ['metadata', 'name']);\n if (!kind || !name) return null;\n const namespace = getString(value, ['metadata', 'namespace']) ?? 'default';\n return `${namespace}/${kind}/${name}`;\n}\n\n/** The pod spec of a workload document, or null for non-workload kinds. */\nfunction podSpecPath(kind: string): (string | number)[] | null {\n const templatePath = WORKLOAD_TEMPLATE_PATHS[kind];\n if (!templatePath) return null;\n return [...templatePath, 'spec'];\n}\n\nexport const kubernetesExtractor: ToolchainExtractor = {\n format: 'kubernetes',\n\n matches(rel, category, head) {\n if (!/\\.ya?ml$/i.test(rel)) return false;\n // Helm templates are Go templates, not YAML — the Helm extractor owns them.\n if (looksTemplated(head)) return false;\n if (/(^|\\/)templates\\//i.test(rel)) return false;\n // The signature of a manifest, wherever it lives. Directory conventions\n // (`k8s/`, `deploy/`) are a hint, never the test: plenty of manifests live\n // elsewhere, and plenty of `deploy/*.yml` files are not manifests.\n return /(^|\\n)apiVersion:\\s*\\S/.test(head) && /(^|\\n)kind:\\s*\\S/.test(head);\n },\n\n extract(rel, source): ToolchainExtraction {\n const { docs, warnings } = parseYamlStream(rel, source);\n const lines = new LineIndex(source);\n const nodes: ToolchainNodeDraft[] = [];\n const edges: ToolchainEdgeDraft[] = [];\n\n /** address → pod-template labels, for same-file selector matching. */\n const workloadLabels = new Map<string, Record<string, string>>();\n\n for (const doc of docs) {\n if (nodes.length >= TOOLCHAIN_NODES_PER_FILE_MAX) {\n warnings.push(`${rel}: stopped at ${TOOLCHAIN_NODES_PER_FILE_MAX} nodes`);\n break;\n }\n if (!isKubernetesDoc(doc.value)) continue;\n const address = objectAddress(doc.value);\n if (!address) continue;\n\n const kind = getString(doc.value, ['kind']) as string;\n const name = getString(doc.value, ['metadata', 'name']) as string;\n const podPath = podSpecPath(kind);\n const isWorkload = podPath !== null;\n\n nodes.push({\n kind: isWorkload ? 'workload' : 'resource',\n name,\n qualifiedName: address,\n span: spanAt(doc, lines, []),\n signature: `k8s.${kind}`,\n doc: safeDoc(describeObject(doc.value, kind)),\n importance: isWorkload ? 0.6 : 0.4,\n });\n\n if (isWorkload) {\n const labels = readLabels(doc.value, [...(WORKLOAD_TEMPLATE_PATHS[kind] ?? []), 'metadata', 'labels']);\n if (Object.keys(labels).length) workloadLabels.set(address, labels);\n extractContainers(doc, lines, address, podPath, nodes, edges);\n }\n\n // Volume, ConfigMap and Secret *references* — names only, never values.\n for (const reference of referencedConfig(doc.value, podPath)) {\n edges.push({ kind: 'mounts', from: address, to: reference, confidence: 1 });\n }\n }\n\n // Service → workload, matched on declared labels within this file.\n for (const doc of docs) {\n if (getString(doc.value, ['kind']) !== 'Service') continue;\n const from = objectAddress(doc.value);\n if (!from) continue;\n const selector = readLabels(doc.value, ['spec', 'selector']);\n if (!Object.keys(selector).length) continue;\n for (const [address, labels] of [...workloadLabels].sort(([a], [b]) => a.localeCompare(b, 'en'))) {\n if (isSubset(selector, labels)) {\n edges.push({ kind: 'exposes', from, to: address, confidence: 1 });\n }\n }\n }\n\n return { nodes, edges, warnings };\n },\n};\n\n/** Container nodes plus their `builds_from` image edges. */\nfunction extractContainers(\n doc: YamlDoc,\n lines: LineIndex,\n workloadAddress: string,\n podPath: (string | number)[],\n nodes: ToolchainNodeDraft[],\n edges: ToolchainEdgeDraft[],\n): void {\n const seenImages = new Set<string>();\n for (const field of CONTAINER_FIELDS) {\n const containers = getArray(doc.value, [...podPath, field]);\n containers.forEach((container, index) => {\n const image = getString(container, ['image']);\n if (!image) return;\n const ref = parseImageRef(image);\n // A templated or malformed image reference is skipped rather than\n // recorded: a node named `${{ env.IMAGE }}` matches nothing and only\n // adds noise to the graph.\n if (!ref) return;\n if (seenImages.has(ref.raw)) return;\n seenImages.add(ref.raw);\n\n nodes.push({\n kind: 'image',\n name: ref.repository.split('/').pop() ?? ref.repository,\n qualifiedName: `image:${ref.raw}`,\n span: spanAt(doc, lines, [...podPath, field, index, 'image']),\n signature: 'k8s.image',\n doc: safeDoc(ref.tag ? `${ref.repository} tag ${ref.tag}` : ref.repository),\n importance: 0.3,\n });\n edges.push({\n kind: 'builds_from',\n from: workloadAddress,\n to: `image:${ref.raw}`,\n confidence: 1,\n });\n });\n }\n}\n\n/** ConfigMap/Secret/PVC names a pod spec references. Names only — never values. */\nfunction referencedConfig(value: unknown, podPath: (string | number)[] | null): string[] {\n if (!podPath) return [];\n const out = new Set<string>();\n\n for (const volume of getArray(value, [...podPath, 'volumes'])) {\n const configMap = getString(volume, ['configMap', 'name']);\n if (configMap) out.add(`ConfigMap/${configMap}`);\n const secret = getString(volume, ['secret', 'secretName']);\n if (secret) out.add(`Secret/${secret}`);\n const claim = getString(volume, ['persistentVolumeClaim', 'claimName']);\n if (claim) out.add(`PersistentVolumeClaim/${claim}`);\n }\n\n for (const field of CONTAINER_FIELDS) {\n for (const container of getArray(value, [...podPath, field])) {\n for (const envFrom of getArray(container, ['envFrom'])) {\n const configMap = getString(envFrom, ['configMapRef', 'name']);\n if (configMap) out.add(`ConfigMap/${configMap}`);\n const secret = getString(envFrom, ['secretRef', 'name']);\n if (secret) out.add(`Secret/${secret}`);\n }\n for (const env of getArray(container, ['env'])) {\n const configMap = getString(env, ['valueFrom', 'configMapKeyRef', 'name']);\n if (configMap) out.add(`ConfigMap/${configMap}`);\n const secret = getString(env, ['valueFrom', 'secretKeyRef', 'name']);\n if (secret) out.add(`Secret/${secret}`);\n }\n }\n }\n\n return [...out].sort();\n}\n\nfunction readLabels(value: unknown, path: (string | number)[]): Record<string, string> {\n const out: Record<string, string> = {};\n for (const [key, raw] of getRecordEntries(value, path)) {\n if (typeof raw === 'string') out[key] = raw;\n else if (typeof raw === 'number' || typeof raw === 'boolean') out[key] = String(raw);\n }\n return out;\n}\n\nfunction isSubset(selector: Record<string, string>, labels: Record<string, string>): boolean {\n const keys = Object.keys(selector);\n if (!keys.length) return false;\n return keys.every((key) => labels[key] === selector[key]);\n}\n\n/** A one-line human summary: replicas, container count, exposed ports. */\nfunction describeObject(value: unknown, kind: string): string {\n const parts: string[] = [];\n const replicas = getPath(value, ['spec', 'replicas']);\n if (typeof replicas === 'number') parts.push(`${replicas} replica${replicas === 1 ? '' : 's'}`);\n\n const podPath = podSpecPath(kind);\n if (podPath) {\n const count = CONTAINER_FIELDS.reduce(\n (sum, field) => sum + getArray(value, [...podPath, field]).length,\n 0,\n );\n if (count) parts.push(`${count} container${count === 1 ? '' : 's'}`);\n }\n\n if (kind === 'Service') {\n const type = getString(value, ['spec', 'type']);\n if (type) parts.push(type);\n const ports = getArray(value, ['spec', 'ports'])\n .map((p) => getString(p, ['port']))\n .filter(Boolean);\n if (ports.length) parts.push(`port ${ports.join(', ')}`);\n }\n\n return parts.join(', ');\n}\n","import type { Node } from 'web-tree-sitter';\nimport { toolchainParser } from './grammars.js';\nimport { LineIndex, safeDoc, TOOLCHAIN_NODES_PER_FILE_MAX } from './util.js';\nimport type {\n ToolchainEdgeDraft,\n ToolchainExtraction,\n ToolchainExtractor,\n ToolchainNodeDraft,\n} from './types.js';\n\n/**\n * Terraform / OpenTofu extraction over the HCL concrete syntax tree.\n *\n * This replaces regex scraping. The regexes it supersedes\n * (`core-open/scanners/terraform-scanner.ts`) used patterns of the form\n * `/required_providers\\s*\\{([^}]+)\\}/s`, where `[^}]+` stops at the *first*\n * closing brace — so the extremely common nested form\n *\n * required_providers {\n * aws = { source = \"hashicorp/aws\" } ← inner `}` ends the match\n * azurerm = { source = \"hashicorp/azurerm\" } ← never seen\n * }\n *\n * silently dropped every provider after the first. A CST has no such failure\n * mode: nesting is structure, not a character class.\n *\n * ## What is extracted\n *\n * | Block | Node kind | Address |\n * |---|---|---|\n * | `resource \"T\" \"N\"` | `resource` | `T.N` |\n * | `data \"T\" \"N\"` | `resource` | `data.T.N` |\n * | `module \"N\"` | `module` | `module.N` |\n * | `variable \"N\"` | `property` | `var.N` |\n * | `output \"N\"` | `property` | `output.N` |\n * | `provider \"N\"` | `package` | `provider.N` |\n *\n * Edges come from two sources, both declared rather than guessed: an explicit\n * `depends_on` list, and interpolation references (`subnet_id =\n * aws_subnet.main.id` ⇒ `aws_instance.web depends_on aws_subnet.main`). Both\n * are `depends_on`; a module block additionally `provisions` nothing until the\n * linker sees the module's own files, so we do not invent that edge here.\n */\n\n/**\n * Reference prefixes that name something other than a graph node: loop and\n * context builtins, plus `terraform`/`path` metadata. Referencing them is not\n * a dependency on anything we can point at.\n */\nconst BUILTIN_REF_PREFIXES = new Set([\n 'count',\n 'each',\n 'self',\n 'path',\n 'terraform',\n]);\n\n/** Block types that declare a named, addressable object. */\ntype BlockSpec = {\n kind: ToolchainNodeDraft['kind'];\n /** Number of quoted labels the block carries. */\n labels: 1 | 2;\n /** Build the Terraform address from the labels. */\n address: (labels: string[]) => string;\n signature: string;\n importance: number;\n};\n\nconst BLOCK_SPECS: Record<string, BlockSpec> = {\n resource: {\n kind: 'resource',\n labels: 2,\n address: ([type, name]) => `${type}.${name}`,\n signature: 'terraform.resource',\n importance: 0.5,\n },\n data: {\n kind: 'resource',\n labels: 2,\n address: ([type, name]) => `data.${type}.${name}`,\n signature: 'terraform.data',\n importance: 0.3,\n },\n module: {\n kind: 'module',\n labels: 1,\n address: ([name]) => `module.${name}`,\n signature: 'terraform.module',\n importance: 0.6,\n },\n variable: {\n kind: 'property',\n labels: 1,\n address: ([name]) => `var.${name}`,\n signature: 'terraform.variable',\n importance: 0.2,\n },\n output: {\n kind: 'property',\n labels: 1,\n address: ([name]) => `output.${name}`,\n signature: 'terraform.output',\n importance: 0.3,\n },\n provider: {\n kind: 'package',\n labels: 1,\n address: ([name]) => `provider.${name}`,\n signature: 'terraform.provider',\n importance: 0.4,\n },\n};\n\n/** Unquote an HCL `string_lit` node by reading its `template_literal` child. */\nfunction stringLitValue(node: Node): string {\n for (const child of node.namedChildren) {\n if (child?.type === 'template_literal') return child.text;\n }\n // An empty string literal (\"\") has no template_literal child.\n return '';\n}\n\n/** Top-level `block` nodes of an HCL document, in source order. */\nfunction topLevelBlocks(root: Node): Node[] {\n const out: Node[] = [];\n // config_file → body → block*\n for (const bodyCandidate of root.namedChildren) {\n if (!bodyCandidate) continue;\n const body = bodyCandidate.type === 'body' ? bodyCandidate : null;\n if (!body) continue;\n for (const child of body.namedChildren) {\n if (child?.type === 'block') out.push(child);\n }\n }\n return out;\n}\n\n/** The `body` child of a block, if present. */\nfunction blockBody(block: Node): Node | null {\n for (const child of block.namedChildren) {\n if (child?.type === 'body') return child;\n }\n return null;\n}\n\n/** Direct `attribute` children of a body, as `[name, expressionNode]`. */\nfunction attributes(body: Node): { name: string; expr: Node | null; node: Node }[] {\n const out: { name: string; expr: Node | null; node: Node }[] = [];\n for (const child of body.namedChildren) {\n if (child?.type !== 'attribute') continue;\n let name = '';\n let expr: Node | null = null;\n for (const part of child.namedChildren) {\n if (!part) continue;\n if (!name && part.type === 'identifier') name = part.text;\n else if (part.type === 'expression') expr = part;\n }\n if (name) out.push({ name, expr, node: child });\n }\n return out;\n}\n\n/** Direct nested `block` children of a body. */\nfunction nestedBlocks(body: Node): Node[] {\n const out: Node[] = [];\n for (const child of body.namedChildren) {\n if (child?.type === 'block') out.push(child);\n }\n return out;\n}\n\n/** A block's `identifier` (its type) and its quoted labels. */\nfunction blockHead(block: Node): { type: string; labels: string[] } {\n let type = '';\n const labels: string[] = [];\n for (const child of block.namedChildren) {\n if (!child) continue;\n if (!type && child.type === 'identifier') type = child.text;\n else if (child.type === 'string_lit') labels.push(stringLitValue(child));\n else if (child.type === 'body') break;\n }\n return { type, labels };\n}\n\n/**\n * Collect every Terraform address referenced inside an expression subtree.\n *\n * A reference in HCL is a `variable_expr` (the root name) followed by\n * `get_attr` siblings (the dotted path). `aws_subnet.main.id` yields\n * `aws_subnet` + `main` + `id`; the addressable prefix is `aws_subnet.main`.\n */\nfunction referencedAddresses(expr: Node | null, out: Set<string>): void {\n if (!expr) return;\n const stack: Node[] = [expr];\n while (stack.length) {\n const node = stack.pop();\n if (!node) continue;\n if (node.type === 'variable_expr') {\n const root = node.text;\n // Walk the get_attr chain that follows this variable_expr among its siblings.\n const parts: string[] = [root];\n let sibling = node.nextNamedSibling;\n while (sibling && sibling.type === 'get_attr') {\n const id = sibling.namedChildren.find((c) => c?.type === 'identifier');\n if (!id) break;\n parts.push(id.text);\n sibling = sibling.nextNamedSibling;\n }\n const address = terraformAddress(parts);\n if (address) out.add(address);\n // Do not descend into this variable_expr; its identifier child is the name.\n continue;\n }\n for (const child of node.namedChildren) {\n if (child) stack.push(child);\n }\n }\n}\n\n/**\n * Reduce a dotted reference path to the address of the thing it points at, or\n * null when it points at nothing we model.\n *\n * ['var','ami_id'] → 'var.ami_id'\n * ['aws_subnet','main','id'] → 'aws_subnet.main'\n * ['data','aws_ami','ubuntu','id'] → 'data.aws_ami.ubuntu'\n * ['module','vpc','vpc_id'] → 'module.vpc'\n * ['each','key'] → null (builtin)\n */\nfunction terraformAddress(parts: string[]): string | null {\n const [head, ...rest] = parts;\n if (!head || BUILTIN_REF_PREFIXES.has(head)) return null;\n if (head === 'var' || head === 'local') return rest.length ? `${head}.${rest[0]}` : null;\n if (head === 'module') return rest.length ? `module.${rest[0]}` : null;\n if (head === 'data') return rest.length >= 2 ? `data.${rest[0]}.${rest[1]}` : null;\n // A managed resource reference: `<type>.<name>[.attr…]`. A bare identifier\n // with no attribute is not an address (it is a local name in scope).\n return rest.length ? `${head}.${rest[0]}` : null;\n}\n\n/**\n * `required_providers` inside a `terraform` block. The nested shape is exactly\n * what the old regex could not read:\n *\n * terraform { required_providers { aws = { source = \"…\" version = \"…\" } } }\n */\nfunction extractRequiredProviders(\n terraformBlock: Node,\n lines: LineIndex,\n nodes: ToolchainNodeDraft[],\n seen: Set<string>,\n): void {\n const body = blockBody(terraformBlock);\n if (!body) return;\n for (const nested of nestedBlocks(body)) {\n const { type } = blockHead(nested);\n if (type !== 'required_providers') continue;\n const inner = blockBody(nested);\n if (!inner) continue;\n for (const attr of attributes(inner)) {\n let source: string | undefined;\n let version: string | undefined;\n\n const objectAttrs = attr.expr ? collectObjectAttributes(attr.expr) : [];\n if (objectAttrs.length) {\n // Modern form: `<localName> = { source = \"…\", version = \"…\" }`.\n for (const { key, value } of objectAttrs) {\n if (key === 'source') source = value;\n else if (key === 'version') version = value;\n }\n } else if (attr.expr) {\n // Legacy version-only shorthand: `<localName> = \"~> 2.0\"`. Still valid,\n // and common in pre-0.13 estates. The source is implicit — an\n // unqualified local name resolves to the `hashicorp` namespace.\n const literal = findFirst(attr.expr, 'string_lit');\n if (literal) {\n version = stringLitValue(literal);\n source = `hashicorp/${attr.name}`;\n }\n }\n\n const address = `provider.${attr.name}`;\n if (seen.has(address)) continue;\n seen.add(address);\n nodes.push({\n kind: 'package',\n name: attr.name,\n qualifiedName: address,\n span: lines.span(attr.node.startIndex, attr.node.endIndex),\n signature: 'terraform.required_provider',\n doc: safeDoc(\n [source && `source ${source}`, version && `version ${version}`].filter(Boolean).join(', '),\n ),\n importance: 0.4,\n });\n }\n }\n}\n\n/** `{ key = \"value\", … }` object literal → flat string pairs (string values only). */\nfunction collectObjectAttributes(expr: Node): { key: string; value: string }[] {\n const out: { key: string; value: string }[] = [];\n const stack: Node[] = [expr];\n while (stack.length) {\n const node = stack.pop();\n if (!node) continue;\n if (node.type === 'object_elem') {\n const key = node.namedChildren.find((c) => c?.type === 'expression');\n const rest = node.namedChildren.filter((c) => c?.type === 'expression');\n const valueNode = rest.length > 1 ? rest[1] : null;\n const keyText = key ? plainText(key) : '';\n const valueText = valueNode ? plainText(valueNode) : '';\n if (keyText) out.push({ key: keyText, value: valueText });\n continue;\n }\n for (const child of node.namedChildren) {\n if (child) stack.push(child);\n }\n }\n return out;\n}\n\n/** An expression's literal text, unquoted when it is a plain string. */\nfunction plainText(expr: Node): string {\n const lit = findFirst(expr, 'string_lit');\n if (lit) return stringLitValue(lit);\n return expr.text.trim();\n}\n\nfunction findFirst(node: Node, type: string): Node | null {\n const stack: Node[] = [node];\n while (stack.length) {\n const current = stack.pop();\n if (!current) continue;\n if (current.type === type) return current;\n for (const child of current.namedChildren) {\n if (child) stack.push(child);\n }\n }\n return null;\n}\n\nexport const terraformExtractor: ToolchainExtractor = {\n format: 'terraform',\n\n matches(rel) {\n const lower = rel.toLowerCase();\n return lower.endsWith('.tf') || lower.endsWith('.tofu');\n },\n\n async extract(rel, source): Promise<ToolchainExtraction> {\n const parser = await toolchainParser('hcl');\n if (!parser) {\n return {\n nodes: [],\n edges: [],\n warnings: [`${rel}: HCL grammar unavailable — no Terraform structure extracted`],\n };\n }\n\n const tree = parser.parse(source);\n if (!tree) return { nodes: [], edges: [], warnings: [`${rel}: HCL parse produced no tree`] };\n\n const lines = new LineIndex(source);\n const nodes: ToolchainNodeDraft[] = [];\n const edges: ToolchainEdgeDraft[] = [];\n const warnings: string[] = [];\n const declared = new Set<string>();\n // Referenced-but-not-declared-here addresses are kept so the linker can\n // join them across files; the framework drops edges whose target never\n // resolves, so a cross-file reference is not silently turned into a node.\n const pendingEdges: ToolchainEdgeDraft[] = [];\n\n if (tree.rootNode.hasError) {\n warnings.push(`${rel}: HCL parse recovered from a syntax error — extraction may be partial`);\n }\n\n for (const block of topLevelBlocks(tree.rootNode)) {\n if (nodes.length >= TOOLCHAIN_NODES_PER_FILE_MAX) {\n warnings.push(`${rel}: stopped at ${TOOLCHAIN_NODES_PER_FILE_MAX} nodes`);\n break;\n }\n const { type, labels } = blockHead(block);\n\n if (type === 'terraform') {\n extractRequiredProviders(block, lines, nodes, declared);\n continue;\n }\n\n const spec = BLOCK_SPECS[type];\n if (!spec || labels.length < spec.labels) continue;\n\n const address = spec.address(labels);\n if (declared.has(address)) continue;\n declared.add(address);\n\n const body = blockBody(block);\n const attrs = body ? attributes(body) : [];\n\n // A module's `source` / `version` is the one piece of a Terraform block\n // that behaves like a dependency, so it belongs in the summary.\n const summaryParts: string[] = [];\n for (const attr of attrs) {\n if (attr.name === 'source' || attr.name === 'version' || attr.name === 'description') {\n const value = attr.expr ? plainText(attr.expr) : '';\n if (value) summaryParts.push(`${attr.name} ${value}`);\n }\n }\n\n nodes.push({\n kind: spec.kind,\n name: labels[labels.length - 1] ?? type,\n qualifiedName: address,\n span: lines.span(block.startIndex, block.endIndex),\n signature: spec.signature,\n doc: safeDoc(summaryParts.join(', ')),\n importance: spec.importance,\n });\n\n if (!body) continue;\n\n // Explicit `depends_on = [...]` and implicit interpolation references.\n const references = new Set<string>();\n for (const attr of attrs) {\n referencedAddresses(attr.expr, references);\n }\n // Nested blocks (`lifecycle`, `provisioner`, dynamic bodies) carry\n // references too — a resource referenced only from inside `lifecycle`\n // is still a dependency.\n const nestedStack = nestedBlocks(body);\n while (nestedStack.length) {\n const nested = nestedStack.pop();\n if (!nested) continue;\n const innerBody = blockBody(nested);\n if (!innerBody) continue;\n for (const attr of attributes(innerBody)) referencedAddresses(attr.expr, references);\n nestedStack.push(...nestedBlocks(innerBody));\n }\n\n references.delete(address); // a self-reference is not a dependency\n for (const target of [...references].sort()) {\n pendingEdges.push({ kind: 'depends_on', from: address, to: target, confidence: 1 });\n }\n }\n\n // Keep only edges whose target is declared in this same file. Cross-file\n // Terraform references are real, but resolving them needs the whole\n // module's file set — that is the linker's job, not this extractor's.\n for (const edge of pendingEdges) {\n if (declared.has(edge.to)) edges.push(edge);\n }\n\n return { nodes, edges, warnings };\n },\n};\n","import {\n LineIndex,\n parseImageRef,\n safeDoc,\n TOOLCHAIN_NODES_PER_FILE_MAX,\n toPosix,\n} from './util.js';\nimport { getArray, getPath, getRecordEntries, getString, parseYamlStream, spanAt } from './yaml.js';\nimport type {\n ToolchainEdgeDraft,\n ToolchainExtraction,\n ToolchainExtractor,\n ToolchainNodeDraft,\n} from './types.js';\n\n/**\n * CI workflow extraction — GitHub Actions and GitLab CI.\n *\n * Jobs and steps become nodes; `needs` (Actions) and `needs`/`dependencies`\n * (GitLab) become `depends_on` edges; workflow triggers become `triggers`\n * edges from an event node.\n *\n * ## Secrets\n *\n * CI files are the single most common place a live credential is committed, so\n * this extractor is deliberately conservative (GUARDRAILS §1.1): it records the\n * *name* of a referenced secret (`secrets.NPM_TOKEN` → `secret:NPM_TOKEN`) and\n * never the value of anything. Literal `env:` values are not extracted at all —\n * only keys — because a literal is exactly the case where a token gets pasted.\n */\n\n/** Steps beyond this per job are summarised rather than enumerated. */\nconst MAX_STEPS_PER_JOB = 100;\n\n/** GitLab reserved top-level keys that are not jobs. */\nconst GITLAB_RESERVED = new Set([\n 'stages',\n 'variables',\n 'default',\n 'include',\n 'workflow',\n 'image',\n 'services',\n 'before_script',\n 'after_script',\n 'cache',\n 'pages',\n]);\n\nfunction isGitHubWorkflowPath(rel: string): boolean {\n return /(^|\\/)\\.github\\/workflows\\/[^/]+\\.ya?ml$/i.test(toPosix(rel));\n}\n\nfunction isGitLabCiPath(rel: string): boolean {\n const base = toPosix(rel).split('/').pop()?.toLowerCase() ?? '';\n return base === '.gitlab-ci.yml' || base === '.gitlab-ci.yaml';\n}\n\n/**\n * Image tags a shell script builds or pushes.\n *\n * Recognises `docker build -t X`, `docker buildx build --tag X`, `podman build\n * -t X` and `docker push X`. Only concrete tags are returned — a tag carrying a\n * `${…}` expansion is unresolvable without the runner's environment, and\n * recording it would create a node that matches nothing.\n */\nexport function imagesBuiltBy(script: string): string[] {\n const out = new Set<string>();\n const buildTag = /\\b(?:docker|podman)\\s+(?:buildx\\s+)?build\\b[^\\n]*?(?:-t|--tag)[=\\s]+(\\S+)/g;\n for (const match of script.matchAll(buildTag)) out.add(match[1]);\n const push = /\\b(?:docker|podman)\\s+push\\s+(\\S+)/g;\n for (const match of script.matchAll(push)) out.add(match[1]);\n return [...out].filter((tag) => !tag.includes('${') && !tag.includes('{{')).sort();\n}\n\n/**\n * Terraform working directories a shell script applies.\n *\n * `terraform apply` acts on the step's working directory unless `-chdir` says\n * otherwise, so an apply with neither yields `'.'` — the linker resolves that\n * against the step's declared `working-directory`.\n */\nexport function terraformAppliedDirs(script: string, workingDirectory?: string): string[] {\n const out = new Set<string>();\n const apply = /\\b(?:terraform|tofu)\\s+(?:-chdir=(\\S+)\\s+)?(?:apply|destroy)\\b/g;\n for (const match of script.matchAll(apply)) {\n out.add(match[1] ?? workingDirectory ?? '.');\n }\n return [...out].sort();\n}\n\n/** Does this script hand a Kubernetes manifest to the cluster? */\nexport function appliesKubernetes(script: string): boolean {\n return /\\bkubectl\\s+apply\\b/.test(script) || /\\bhelm\\s+(?:upgrade|install)\\b/.test(script);\n}\n\n/** Secret references inside an arbitrary subtree, as `secret:NAME`. */\nfunction collectSecretReferences(value: unknown, out: Set<string>): void {\n const stack: unknown[] = [value];\n while (stack.length) {\n const current = stack.pop();\n if (typeof current === 'string') {\n // `${{ secrets.NAME }}` — the name is the useful fact; the value never appears here.\n for (const match of current.matchAll(/secrets\\.([A-Za-z_][A-Za-z0-9_]*)/g)) {\n out.add(`secret:${match[1]}`);\n }\n continue;\n }\n if (Array.isArray(current)) {\n stack.push(...current);\n continue;\n }\n if (current && typeof current === 'object') {\n stack.push(...Object.values(current as Record<string, unknown>));\n }\n }\n}\n\nexport const githubActionsExtractor: ToolchainExtractor = {\n format: 'github-actions',\n\n matches(rel) {\n return isGitHubWorkflowPath(rel);\n },\n\n extract(rel, source): ToolchainExtraction {\n const { docs, warnings } = parseYamlStream(rel, source);\n const lines = new LineIndex(source);\n const nodes: ToolchainNodeDraft[] = [];\n const edges: ToolchainEdgeDraft[] = [];\n\n const doc = docs[0];\n if (!doc) return { nodes, edges, warnings };\n\n const workflowName = getString(doc.value, ['name']) ?? toPosix(rel).split('/').pop() ?? rel;\n const workflowAddress = `workflow:${toPosix(rel)}`;\n\n nodes.push({\n kind: 'job',\n name: workflowName,\n qualifiedName: workflowAddress,\n span: spanAt(doc, lines, []),\n signature: 'gha.workflow',\n doc: safeDoc(`GitHub Actions workflow`),\n importance: 0.6,\n });\n\n // Triggers. `on:` is either a string, a list, or a map of event → filter.\n // NB: YAML 1.1 parses a bare `on` key as the boolean `true`; the `yaml`\n // package follows the 1.2 core schema so `on` stays a string, but we accept\n // both so a 1.1-flavoured file still yields triggers.\n const onValue = getPath(doc.value, ['on']) ?? getPath(doc.value, [true as unknown as string]);\n for (const event of triggerEvents(onValue)) {\n const eventAddress = `event:${event}`;\n nodes.push({\n kind: 'property',\n name: event,\n qualifiedName: eventAddress,\n span: spanAt(doc, lines, ['on']),\n signature: 'gha.event',\n importance: 0.2,\n });\n edges.push({ kind: 'triggers', from: eventAddress, to: workflowAddress, confidence: 1 });\n }\n\n const jobs = getRecordEntries(doc.value, ['jobs']);\n const jobAddresses = new Set(jobs.map(([id]) => `job:${id}`));\n\n for (const [jobId, job] of jobs) {\n if (nodes.length >= TOOLCHAIN_NODES_PER_FILE_MAX) {\n warnings.push(`${rel}: stopped at ${TOOLCHAIN_NODES_PER_FILE_MAX} nodes`);\n break;\n }\n const jobAddress = `job:${jobId}`;\n const runsOn = getPath(job, ['runs-on']);\n const steps = getArray(job, ['steps']);\n\n nodes.push({\n kind: 'job',\n name: getString(job, ['name']) ?? jobId,\n qualifiedName: jobAddress,\n span: spanAt(doc, lines, ['jobs', jobId]),\n signature: 'gha.job',\n doc: safeDoc(\n [\n typeof runsOn === 'string' ? `runs-on ${runsOn}` : null,\n steps.length ? `${steps.length} step${steps.length === 1 ? '' : 's'}` : null,\n ]\n .filter(Boolean)\n .join(', '),\n ),\n importance: 0.5,\n });\n edges.push({ kind: 'contains', from: workflowAddress, to: jobAddress, confidence: 1 });\n\n // `needs:` — string or list.\n for (const need of asStringList(getPath(job, ['needs']))) {\n const to = `job:${need}`;\n if (jobAddresses.has(to)) {\n edges.push({ kind: 'depends_on', from: jobAddress, to, confidence: 1 });\n }\n }\n\n // Steps. `uses:` is the reusable-action reference; `run:` is a script the\n // linker later mines for `terraform apply` / `docker build`.\n steps.slice(0, MAX_STEPS_PER_JOB).forEach((step, index) => {\n const uses = getString(step, ['uses']);\n const run = getString(step, ['run']);\n const stepName =\n getString(step, ['name']) ?? uses ?? (run ? run.split('\\n')[0] : `step ${index + 1}`);\n const stepAddress = `${jobAddress}#${index}`;\n nodes.push({\n kind: 'step',\n name: stepName.slice(0, 80),\n qualifiedName: stepAddress,\n span: spanAt(doc, lines, ['jobs', jobId, 'steps', index]),\n signature: uses ? 'gha.step.uses' : 'gha.step.run',\n // `run:` bodies are shell scripts and are exactly where a token gets\n // pasted — safeDoc redacts, and we keep only the first line.\n doc: safeDoc(uses ? `uses ${uses}` : run?.split('\\n')[0]),\n importance: 0.2,\n });\n edges.push({ kind: 'contains', from: jobAddress, to: stepAddress, confidence: 1 });\n\n if (uses) {\n const actionAddress = `action:${uses}`;\n nodes.push({\n kind: 'external',\n name: uses.split('@')[0],\n qualifiedName: actionAddress,\n span: spanAt(doc, lines, ['jobs', jobId, 'steps', index, 'uses']),\n signature: 'gha.action',\n importance: 0.2,\n });\n edges.push({ kind: 'depends_on', from: stepAddress, to: actionAddress, confidence: 1 });\n }\n\n if (run) {\n const stepSpan = spanAt(doc, lines, ['jobs', jobId, 'steps', index]);\n const workingDirectory =\n getString(step, ['working-directory']) ?? getString(job, ['defaults', 'run', 'working-directory']);\n emitScriptEffects(rel, run, workingDirectory, jobAddress, stepSpan, nodes, edges);\n }\n });\n\n if (steps.length > MAX_STEPS_PER_JOB) {\n warnings.push(`${rel}: job ${jobId} has ${steps.length} steps — enumerated the first ${MAX_STEPS_PER_JOB}`);\n }\n\n // Secret *names* referenced anywhere in the job.\n const secrets = new Set<string>();\n collectSecretReferences(job, secrets);\n for (const secret of [...secrets].sort()) {\n nodes.push({\n kind: 'property',\n name: secret.slice('secret:'.length),\n qualifiedName: secret,\n span: spanAt(doc, lines, ['jobs', jobId]),\n signature: 'gha.secret-ref',\n importance: 0.2,\n });\n edges.push({ kind: 'mounts', from: jobAddress, to: secret, confidence: 1 });\n }\n }\n\n return { nodes, edges, warnings };\n },\n};\n\nexport const gitlabCiExtractor: ToolchainExtractor = {\n format: 'gitlab-ci',\n\n matches(rel) {\n return isGitLabCiPath(rel);\n },\n\n extract(rel, source): ToolchainExtraction {\n const { docs, warnings } = parseYamlStream(rel, source);\n const lines = new LineIndex(source);\n const nodes: ToolchainNodeDraft[] = [];\n const edges: ToolchainEdgeDraft[] = [];\n\n const doc = docs[0];\n if (!doc) return { nodes, edges, warnings };\n\n const pipelineAddress = `workflow:${toPosix(rel)}`;\n nodes.push({\n kind: 'job',\n name: 'GitLab CI',\n qualifiedName: pipelineAddress,\n span: spanAt(doc, lines, []),\n signature: 'gitlab.pipeline',\n importance: 0.6,\n });\n\n // Top-level keys that are neither reserved nor a `.hidden` template are jobs.\n const jobs = getRecordEntries(doc.value, []).filter(\n ([key, value]) =>\n !GITLAB_RESERVED.has(key) &&\n !key.startsWith('.') &&\n value !== null &&\n typeof value === 'object' &&\n !Array.isArray(value),\n );\n const jobAddresses = new Set(jobs.map(([id]) => `job:${id}`));\n\n for (const [jobId, job] of jobs) {\n if (nodes.length >= TOOLCHAIN_NODES_PER_FILE_MAX) {\n warnings.push(`${rel}: stopped at ${TOOLCHAIN_NODES_PER_FILE_MAX} nodes`);\n break;\n }\n const jobAddress = `job:${jobId}`;\n const stage = getString(job, ['stage']);\n const image = getString(job, ['image']) ?? getString(job, ['image', 'name']);\n\n nodes.push({\n kind: 'job',\n name: jobId,\n qualifiedName: jobAddress,\n span: spanAt(doc, lines, [jobId]),\n signature: 'gitlab.job',\n doc: safeDoc([stage && `stage ${stage}`, image && `image ${image}`].filter(Boolean).join(', ')),\n importance: 0.5,\n });\n edges.push({ kind: 'contains', from: pipelineAddress, to: jobAddress, confidence: 1 });\n\n // GitLab uses both `needs:` (DAG) and `dependencies:` (artifacts).\n for (const key of ['needs', 'dependencies'] as const) {\n for (const need of asStringList(getPath(job, [key]))) {\n const to = `job:${need}`;\n if (jobAddresses.has(to)) {\n edges.push({ kind: 'depends_on', from: jobAddress, to, confidence: 1 });\n }\n }\n }\n }\n\n return { nodes, edges, warnings };\n },\n};\n\n/**\n * Turn what a `run:` script *does* into nodes and edges, so the cross-domain\n * linker can join on node identity instead of re-parsing shell.\n *\n * These are the anchor points the linker needs: an image this job builds, a\n * Terraform directory it applies, and whether it talks to a cluster at all.\n */\nfunction emitScriptEffects(\n rel: string,\n script: string,\n workingDirectory: string | undefined,\n jobAddress: string,\n span: { start: number; end: number },\n nodes: ToolchainNodeDraft[],\n edges: ToolchainEdgeDraft[],\n): void {\n for (const tag of imagesBuiltBy(script)) {\n const ref = parseImageRef(tag);\n if (!ref) continue;\n const address = `image:${ref.raw}`;\n nodes.push({\n kind: 'image',\n name: ref.repository.split('/').pop() ?? ref.repository,\n qualifiedName: address,\n span,\n signature: 'ci.builds-image',\n doc: safeDoc(ref.tag ? `${ref.repository} tag ${ref.tag}` : ref.repository),\n importance: 0.4,\n });\n // The job creates this artifact.\n edges.push({ kind: 'provisions', from: jobAddress, to: address, confidence: 1 });\n }\n\n for (const dir of terraformAppliedDirs(script, workingDirectory)) {\n // `-chdir=` and `working-directory:` are both relative to the *workspace\n // root* (the checkout), never to the workflow file that names them — a\n // workflow at `.github/workflows/cd.yml` applying `-chdir=infra` means\n // `infra/`, not `.github/workflows/cd.yml/infra`.\n const resolved = normaliseWorkspacePath(dir);\n const address = `tfdir:${resolved}`;\n nodes.push({\n kind: 'resource',\n name: resolved,\n qualifiedName: address,\n span,\n signature: 'ci.terraform-apply',\n doc: safeDoc(`terraform apply in ${resolved}`),\n importance: 0.4,\n });\n edges.push({ kind: 'deploys', from: jobAddress, to: address, confidence: 1 });\n }\n}\n\n/**\n * Normalise a workspace-root-relative path from a CI file: strip a leading\n * `./`, collapse `.` segments and resolve `..` without escaping the root.\n * Returns `'.'` for the root itself.\n */\nfunction normaliseWorkspacePath(dir: string): string {\n const out: string[] = [];\n for (const part of toPosix(dir).split('/')) {\n if (!part || part === '.') continue;\n if (part === '..') {\n out.pop();\n continue;\n }\n out.push(part);\n }\n return out.join('/') || '.';\n}\n\n/** `on:` in its three shapes → a sorted list of event names. */\nfunction triggerEvents(value: unknown): string[] {\n if (typeof value === 'string') return [value];\n if (Array.isArray(value)) return value.filter((v): v is string => typeof v === 'string').sort();\n if (value && typeof value === 'object') return Object.keys(value as Record<string, unknown>).sort();\n return [];\n}\n\n/**\n * A field that is either a string, a list of strings, or a list of objects\n * carrying a `job` key (GitLab's `needs: [{job: build}]`), normalised to names.\n */\nfunction asStringList(value: unknown): string[] {\n if (typeof value === 'string') return [value];\n if (!Array.isArray(value)) return [];\n const out: string[] = [];\n for (const item of value) {\n if (typeof item === 'string') out.push(item);\n else if (item && typeof item === 'object') {\n const job = (item as Record<string, unknown>).job;\n if (typeof job === 'string') out.push(job);\n }\n }\n return out.sort();\n}\n","import { edgeId } from '../ids.js';\nimport type { GraphEdge, GraphNode } from '../../schema.js';\nimport { imageIdentity, parseImageRef, toPosix } from './util.js';\n\n/**\n * Cross-domain linker — Phase 2.1.\n *\n * The per-file extractors deliberately never resolve across files. This pass\n * runs once over the whole extracted set and joins the domains, which is what\n * turns a pile of parsed manifests into an answer to *\"which pipeline deploys\n * the service this code runs in?\"*\n *\n * ## Honesty contract\n *\n * Every edge produced here is an **inference**, not a declaration, and is\n * labelled as such:\n *\n * - `resolution: 'heuristic'` — always. An inferred `deploys` is not a\n * declared `import` and must never claim to be.\n * - `epistemic: 'name-matched'` — these joins match on a name (an image tag,\n * a path), which is exactly what that tier means.\n * - a calibrated `confidence`, lower where the evidence is weaker.\n *\n * Where the evidence is absent the edge is simply **not emitted**. The graph's\n * value is that it does not guess silently, so a repository that wires its\n * pipeline in a way we cannot see gets fewer edges rather than wrong ones.\n *\n * The pass is a pure function of its inputs — no module state, no filesystem,\n * no clock — so a rebuild produces byte-identical edges.\n */\n\n/** Confidence per join, by how directly the evidence supports it. */\nexport const LINK_CONFIDENCE = {\n /** Compose names the Dockerfile path outright. */\n composeBuild: 0.95,\n /** A CI job builds tag X; a workload runs tag X. Same string, both sides. */\n imageIdentity: 0.8,\n /** A CI job applies Terraform in a directory that contains these resources. */\n terraformDir: 0.75,\n /** A Dockerfile copies a path that exists in the repository. */\n dockerfileCopy: 0.6,\n} as const;\n\nexport interface LinkInput {\n /** Toolchain nodes from every extractor. */\n nodes: GraphNode[];\n /** Toolchain edges declared within individual files. */\n edges: GraphEdge[];\n /** Repo-relative source path → its `file` node id, for the Dockerfile join. */\n fileNodes: ReadonlyMap<string, string>;\n /**\n * Dockerfile build stage (by its node `qualifiedName`) → candidate repo paths\n * that stage copies from the build context.\n */\n stageCopySources: ReadonlyMap<string, string[]>;\n}\n\nexport interface LinkResult {\n edges: GraphEdge[];\n /** Per-join counts, for the build summary. */\n counts: Record<string, number>;\n}\n\n/** Join the extracted toolchain nodes across files. */\nexport function linkToolchain(input: LinkInput): LinkResult {\n const { nodes, edges, fileNodes, stageCopySources } = input;\n const out = new Map<string, GraphEdge>();\n const counts: Record<string, number> = {};\n\n const add = (\n kind: GraphEdge['kind'],\n src: string,\n dst: string,\n confidence: number,\n join: string,\n ): void => {\n if (src === dst) return;\n const id = edgeId(kind, src, dst);\n if (out.has(id)) return;\n out.set(id, {\n id,\n kind,\n src,\n dst,\n resolution: 'heuristic',\n confidence,\n epistemic: 'name-matched',\n });\n counts[join] = (counts[join] ?? 0) + 1;\n };\n\n // Already-declared edges, so we never emit a weaker duplicate of something an\n // extractor saw declared outright in one file.\n const declared = new Set(edges.map((e) => `${e.kind} ${e.src} ${e.dst}`));\n\n // ── Index the extracted nodes ────────────────────────────────────────────\n\n const dockerfileByPath = new Map<string, GraphNode>();\n const dockerfileRefs: GraphNode[] = [];\n const imageSites = new Map<string, GraphNode[]>();\n const terraformDirMarkers: GraphNode[] = [];\n const terraformNodesByDir = new Map<string, GraphNode[]>();\n const stagesByDockerfile = new Map<string, GraphNode[]>();\n\n for (const node of nodes) {\n const qn = node.qualifiedName;\n\n if (qn.startsWith('dockerfile:')) {\n const target = qn.slice('dockerfile:'.length);\n if (target.includes('#')) {\n push(stagesByDockerfile, target.split('#')[0], node);\n continue;\n }\n // The Dockerfile's own node lives *in* that file; anything else is a\n // reference to it (a Compose `build:` stanza, say).\n if (toPosix(node.file) === target) dockerfileByPath.set(target, node);\n else dockerfileRefs.push(node);\n continue;\n }\n\n if (qn.startsWith('image:')) {\n const ref = parseImageRef(qn.slice('image:'.length));\n if (ref) push(imageSites, imageIdentity(ref), node);\n continue;\n }\n\n if (qn.startsWith('tfdir:')) {\n terraformDirMarkers.push(node);\n continue;\n }\n\n if (node.lang === 'terraform') push(terraformNodesByDir, dirOf(toPosix(node.file)), node);\n }\n\n // ── Join 1: a Compose build reference → the real Dockerfile ──────────────\n\n for (const ref of dockerfileRefs) {\n const target = dockerfileByPath.get(ref.qualifiedName.slice('dockerfile:'.length));\n if (!target) continue; // the referenced Dockerfile is not in the corpus\n add('builds_from', ref.id, target.id, LINK_CONFIDENCE.composeBuild, 'compose→dockerfile');\n }\n\n // ── Join 2: image identity across files ─────────────────────────────────\n //\n // A CI job that builds `ghcr.io/acme/web:1.2.3` and a Deployment that runs\n // `ghcr.io/acme/web:1.2.3` are talking about the same artifact. The producer\n // side is whatever a `provisions` edge points at; the consumer side is\n // whatever a `builds_from` points at.\n\n const producerOf = new Map<string, string[]>();\n const consumerOf = new Map<string, string[]>();\n for (const edge of edges) {\n if (edge.kind === 'provisions') push(producerOf, edge.dst, edge.src);\n else if (edge.kind === 'builds_from') push(consumerOf, edge.dst, edge.src);\n }\n\n for (const identity of [...imageSites.keys()].sort((a, b) => a.localeCompare(b, 'en'))) {\n const sites = imageSites.get(identity) ?? [];\n if (sites.length < 2) continue; // a single mention is not a join\n\n const producers = new Set<string>();\n const consumers = new Set<string>();\n for (const site of sites) {\n for (const id of producerOf.get(site.id) ?? []) producers.add(id);\n for (const id of consumerOf.get(site.id) ?? []) consumers.add(id);\n }\n for (const producer of [...producers].sort()) {\n for (const consumer of [...consumers].sort()) {\n if (declared.has(`deploys ${producer} ${consumer}`)) continue;\n add('deploys', producer, consumer, LINK_CONFIDENCE.imageIdentity, 'ci→workload');\n }\n }\n\n // Join the image sites themselves, so navigating from a Compose mention of\n // an image reaches the Kubernetes one.\n const ordered = [...sites].sort((a, b) => a.id.localeCompare(b.id, 'en'));\n for (let i = 1; i < ordered.length; i++) {\n add('references', ordered[0].id, ordered[i].id, LINK_CONFIDENCE.imageIdentity, 'image↔image');\n }\n }\n\n // ── Join 3: a CI job that applies Terraform → the resources in that dir ──\n\n const terraformDirs = [...terraformNodesByDir.keys()].sort((a, b) => a.localeCompare(b, 'en'));\n for (const marker of [...terraformDirMarkers].sort((a, b) => a.id.localeCompare(b.id, 'en'))) {\n const dir = marker.qualifiedName.slice('tfdir:'.length);\n for (const resourceDir of terraformDirs) {\n // A root module's apply covers its own directory and below — never the\n // whole repository.\n if (resourceDir !== dir && !resourceDir.startsWith(`${dir}/`)) continue;\n for (const resource of terraformNodesByDir.get(resourceDir) ?? []) {\n // Only declarations that actually create infrastructure: a `variable`\n // or an `output` is not something a pipeline deploys.\n if (resource.signature !== 'terraform.resource' && resource.signature !== 'terraform.module') {\n continue;\n }\n add('deploys', marker.id, resource.id, LINK_CONFIDENCE.terraformDir, 'ci→terraform');\n }\n }\n }\n\n // ── Join 4: a Dockerfile stage → repository files it copies in ───────────\n //\n // The weakest join, and scoped accordingly: only paths that resolve to a file\n // already in the graph produce an edge. A bare `COPY . .` yields nothing — it\n // is true but says nothing.\n\n for (const file of [...stagesByDockerfile.keys()].sort((a, b) => a.localeCompare(b, 'en'))) {\n const stages = [...(stagesByDockerfile.get(file) ?? [])].sort((a, b) =>\n a.qualifiedName.localeCompare(b.qualifiedName, 'en'),\n );\n for (const stage of stages) {\n // Per-stage: a stage whose only COPY is `--from=` another stage reads\n // nothing from the repository and must get no source edges.\n const copied = stageCopySources.get(stage.qualifiedName);\n if (!copied?.length) continue;\n for (const path of copied) {\n const fileNodeId = fileNodes.get(toPosix(path));\n if (!fileNodeId) continue;\n add('depends_on', stage.id, fileNodeId, LINK_CONFIDENCE.dockerfileCopy, 'dockerfile→source');\n }\n }\n }\n\n return {\n edges: [...out.values()].sort(\n (a, b) =>\n a.kind.localeCompare(b.kind, 'en') ||\n a.src.localeCompare(b.src, 'en') ||\n a.dst.localeCompare(b.dst, 'en'),\n ),\n counts,\n };\n}\n\nfunction push<K, V>(map: Map<K, V[]>, key: K, value: V): void {\n const list = map.get(key);\n if (list) list.push(value);\n else map.set(key, [value]);\n}\n\n/** Directory portion of a POSIX path, or `'.'` at the root. */\nfunction dirOf(rel: string): string {\n const idx = rel.lastIndexOf('/');\n return idx === -1 ? '.' : rel.slice(0, idx);\n}\n","import * as fs from 'node:fs';\nimport { edgeId, nodeId } from '../ids.js';\nimport type { GraphEdge, GraphNode } from '../../schema.js';\nimport type { DiscoveredDoc } from '../docs-ingest.js';\nimport { composeExtractor } from './compose.js';\nimport { dockerfileExtractor } from './dockerfile.js';\nimport { helmExtractor } from './helm.js';\nimport { kubernetesExtractor } from './kubernetes.js';\nimport { terraformExtractor } from './terraform.js';\nimport { githubActionsExtractor, gitlabCiExtractor } from './workflows.js';\nimport { linkToolchain } from './link.js';\nimport { safeDoc, TOOLCHAIN_FILE_MAX_BYTES, toPosix } from './util.js';\nimport type { ToolchainExtractor, ToolchainFormat, ToolchainNodeDraft } from './types.js';\n\n/**\n * Toolchain extraction — the structural pass over the infrastructure, CI and\n * container corpus.\n *\n * ## Where this sits\n *\n * `docs-ingest.ts` already discovers and classifies exactly these files, and\n * turns each into one truncated `document` node for semantic ask. This module\n * runs over that same discovered set and adds *structure*: resources,\n * workloads, jobs, steps, images, charts, and the edges between them. The\n * document node stays — it is the semantic-ask surface — so nothing regresses.\n *\n * Critically, this does **not** register these files as source code. Adding\n * `.tf`/`.yaml` to `engine/languages.ts` would sweep them into the source\n * corpus, which drives `project-classification.ts` — and that picks the billing\n * tier. Extraction here leaves the source corpus, DriftScore and billing\n * untouched.\n *\n * ## Determinism\n *\n * Extractors are pure over `(rel, source)`. Files are processed in sorted path\n * order, nodes and edges are sorted before return, and ids are content-addressed\n * via the same `nodeId`/`edgeId` helpers the code graph uses. Identical corpus\n * in → byte-identical output.\n */\n\n/**\n * Registered extractors, in match order. Order matters: Helm must win over\n * Kubernetes for a chart's `values.yaml`, and Compose must win over Kubernetes\n * for a `compose.yaml` that happens to contain an `apiVersion` key.\n */\nconst EXTRACTORS: ToolchainExtractor[] = [\n terraformExtractor,\n dockerfileExtractor,\n githubActionsExtractor,\n gitlabCiExtractor,\n helmExtractor,\n composeExtractor,\n kubernetesExtractor,\n];\n\n/** Bytes of a file inspected for content heuristics. */\nconst HEAD_BYTES = 4096;\n\nexport interface ToolchainResult {\n nodes: GraphNode[];\n edges: GraphEdge[];\n warnings: string[];\n /** Per-format file counts, for the build summary and `ProjectProfile`. */\n counts: Record<string, number>;\n /** Per-join counts from the cross-domain linker. */\n linkCounts: Record<string, number>;\n}\n\nexport interface ExtractToolchainOptions {\n /**\n * Repo-relative source path → its `file` node id. Supplied by the build so\n * the cross-domain linker can join a Dockerfile to the files it copies in.\n * Omit to skip that join.\n */\n fileNodes?: ReadonlyMap<string, string>;\n}\n\nconst EMPTY_RESULT: ToolchainResult = {\n nodes: [],\n edges: [],\n warnings: [],\n counts: {},\n linkCounts: {},\n};\n\n/** Every registered format id, sorted. Exported for the profile/report layer. */\nexport function toolchainFormats(): ToolchainFormat[] {\n return [...new Set(EXTRACTORS.map((e) => e.format))].sort() as ToolchainFormat[];\n}\n\n/**\n * Pick the extractor for a discovered file, or null when none applies.\n * Exported so the LSP can answer \"is this file structurally understood?\"\n * without running a full extraction.\n */\nexport function extractorFor(doc: DiscoveredDoc, head: string): ToolchainExtractor | null {\n for (const extractor of EXTRACTORS) {\n try {\n if (extractor.matches(toPosix(doc.rel), doc.category ?? doc.kind, head)) return extractor;\n } catch {\n /* a matcher must never break discovery */\n }\n }\n return null;\n}\n\n/**\n * Run structural extraction over the discovered document set.\n *\n * Never throws: a malformed manifest, an unreadable file or a missing grammar\n * degrades to a warning and zero structure for that file. Infrastructure files\n * are frequently templated, partial or generated, and a scanner that dies on\n * one of them is a scanner nobody keeps installed.\n */\nexport async function extractToolchain(\n docs: DiscoveredDoc[],\n options: ExtractToolchainOptions = {},\n): Promise<ToolchainResult> {\n if (!docs.length) return EMPTY_RESULT;\n\n const nodes = new Map<string, GraphNode>();\n const edges = new Map<string, GraphEdge>();\n const warnings: string[] = [];\n const counts: Record<string, number> = {};\n const stageCopySources = new Map<string, string[]>();\n\n // Sorted path order keeps the output stable regardless of discovery order.\n const ordered = [...docs].sort((a, b) => toPosix(a.rel).localeCompare(toPosix(b.rel), 'en'));\n\n for (const doc of ordered) {\n let source: string;\n let head: string;\n try {\n const stat = fs.statSync(doc.abs);\n if (stat.size > TOOLCHAIN_FILE_MAX_BYTES) continue;\n source = fs.readFileSync(doc.abs, 'utf8');\n head = source.slice(0, HEAD_BYTES);\n } catch {\n continue; // unreadable — docs-ingest already tolerates this\n }\n\n const extractor = extractorFor(doc, head);\n if (!extractor) continue;\n\n const rel = toPosix(doc.rel);\n let extraction;\n try {\n extraction = await extractor.extract(rel, source);\n } catch (err) {\n warnings.push(`${rel}: ${extractor.format} extraction failed (${(err as Error).message})`);\n continue;\n }\n\n if (extraction.warnings?.length) warnings.push(...extraction.warnings);\n for (const [stage, paths] of Object.entries(extraction.linkHints?.copySourcesByStage ?? {})) {\n if (paths.length) stageCopySources.set(stage, paths);\n }\n if (!extraction.nodes.length) continue;\n\n counts[extractor.format] = (counts[extractor.format] ?? 0) + 1;\n\n // Drafts → graph nodes. `qualifiedName` is scoped by file, so two files\n // declaring `service:web` stay distinct nodes.\n const idByQualifiedName = new Map<string, string>();\n for (const draft of extraction.nodes) {\n const id = nodeId({\n kind: draft.kind,\n qualifiedName: draft.qualifiedName,\n file: rel,\n signature: draft.signature,\n });\n // First declaration of a name in a file wins; a repeat is the same thing.\n if (!idByQualifiedName.has(draft.qualifiedName)) {\n idByQualifiedName.set(draft.qualifiedName, id);\n }\n if (nodes.has(id)) continue;\n nodes.set(id, toGraphNode(id, draft, rel, extractor.format));\n }\n\n for (const draft of extraction.edges) {\n const src = idByQualifiedName.get(draft.from);\n const dst = idByQualifiedName.get(draft.to);\n // A dangling edge is dropped, never turned into a placeholder node: the\n // graph's value is that it does not invent things it cannot see.\n if (!src || !dst || src === dst) continue;\n const id = edgeId(draft.kind, src, dst);\n if (edges.has(id)) continue;\n edges.set(id, {\n id,\n kind: draft.kind,\n src,\n dst,\n // Structural extraction from a declaration in the file itself.\n resolution: 'heuristic',\n confidence: draft.confidence ?? 1,\n epistemic: 'declared',\n });\n }\n }\n\n const sortedNodes = [...nodes.values()].sort((a, b) => a.id.localeCompare(b.id, 'en'));\n const sortedEdges = [...edges.values()].sort(byEdgeOrder);\n\n // Phase 2.1 — join the domains across files. Runs once over the whole set.\n const linked = linkToolchain({\n nodes: sortedNodes,\n edges: sortedEdges,\n fileNodes: options.fileNodes ?? new Map(),\n stageCopySources,\n });\n\n // A linker edge never overwrites a declared one of the same identity: the\n // declaration is the stronger claim.\n const declaredIds = new Set(sortedEdges.map((e) => e.id));\n const allEdges = [...sortedEdges, ...linked.edges.filter((e) => !declaredIds.has(e.id))].sort(\n byEdgeOrder,\n );\n\n return {\n nodes: sortedNodes,\n edges: allEdges,\n warnings: [...new Set(warnings)].sort(),\n counts,\n linkCounts: linked.counts,\n };\n}\n\nfunction byEdgeOrder(a: GraphEdge, b: GraphEdge): number {\n return (\n a.kind.localeCompare(b.kind, 'en') ||\n a.src.localeCompare(b.src, 'en') ||\n a.dst.localeCompare(b.dst, 'en')\n );\n}\n\nfunction toGraphNode(\n id: string,\n draft: ToolchainNodeDraft,\n rel: string,\n format: ToolchainFormat,\n): GraphNode {\n return {\n id,\n kind: draft.kind,\n name: draft.name,\n qualifiedName: draft.qualifiedName,\n file: rel,\n span: draft.span,\n // `lang` is the format tag, so `--only` and the report can filter on it\n // without colliding with a source language id.\n lang: format,\n signature: draft.signature,\n doc: safeDoc(draft.doc),\n importance: draft.importance ?? 0.3,\n centrality: { degree: 0, pagerank: 0, betweenness: 0, eigenvector: 0 },\n area: -1,\n isHub: false,\n // Infrastructure has no notion of unit-test coverage; `null` is the\n // schema's \"not analyzable\", which is the honest answer.\n tested: null,\n };\n}\n\nexport type { ToolchainExtractor, ToolchainFormat } from './types.js';\n","/**\n * Partition TS/JS files into project shards for incremental / monorepo-safe\n * TypeScript Compiler API resolution. Each shard gets its own `createProgram`\n * so a large monorepo never pays for one giant Program over every package.\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\n\nexport interface TsFile {\n rel: string;\n abs: string;\n}\n\nexport interface TsProjectShard {\n /** Directory that owns the nearest tsconfig / package.json (repo-relative POSIX). */\n key: string;\n files: TsFile[];\n}\n\n/**\n * Group files by nearest ancestor that contains `tsconfig.json` /\n * `tsconfig.base.json` / `package.json`, falling back to the repo root.\n * Deterministic: shards sorted by key; files within a shard sorted by rel.\n */\nexport function shardTsProjects(root: string, files: TsFile[]): TsProjectShard[] {\n if (files.length === 0) return [];\n\n const cache = new Map<string, string>(); // abs dir → project key (rel posix)\n const byKey = new Map<string, TsFile[]>();\n\n for (const f of files) {\n const dir = path.dirname(f.abs);\n const key = nearestProjectKey(root, dir, cache);\n const list = byKey.get(key);\n if (list) list.push(f);\n else byKey.set(key, [f]);\n }\n\n return [...byKey.entries()]\n .sort((a, b) => a[0].localeCompare(b[0]))\n .map(([key, shardFiles]) => ({\n key,\n files: [...shardFiles].sort((a, b) => a.rel.localeCompare(b.rel)),\n }));\n}\n\nfunction nearestProjectKey(root: string, startDir: string, cache: Map<string, string>): string {\n const hit = cache.get(startDir);\n if (hit !== undefined) return hit;\n\n let dir = startDir;\n const rootAbs = path.resolve(root);\n while (true) {\n if (\n fs.existsSync(path.join(dir, 'tsconfig.json')) ||\n fs.existsSync(path.join(dir, 'tsconfig.base.json')) ||\n fs.existsSync(path.join(dir, 'package.json'))\n ) {\n const key = toPosix(path.relative(rootAbs, dir)) || '.';\n cache.set(startDir, key);\n return key;\n }\n if (dir === rootAbs || path.dirname(dir) === dir) {\n cache.set(startDir, '.');\n return '.';\n }\n dir = path.dirname(dir);\n }\n}\n\nfunction toPosix(p: string): string {\n return p.split(path.sep).join('/');\n}\n","/**\n * Stage wall-clock timers for build diagnostics.\n * Pure measurement — never enters the serialized graph artifact.\n */\n\nexport type StageName =\n | 'discover'\n | 'hash'\n | 'parse'\n | 'resolve'\n | 'tsc'\n | 'scip'\n | 'tests'\n /** Structural extraction over the infrastructure/CI corpus (engine/toolchain/). */\n | 'toolchain'\n | 'analyze'\n | 'facts'\n | 'ground'\n | 'index'\n | 'total';\n\nexport type StageTimings = Partial<Record<StageName, number>>;\n\nexport class StageTimer {\n private readonly marks = new Map<string, number>();\n private readonly durations: StageTimings = {};\n\n start(name: StageName): void {\n this.marks.set(name, nowMs());\n }\n\n end(name: StageName): number {\n const t0 = this.marks.get(name);\n if (t0 === undefined) return 0;\n const ms = Math.round((nowMs() - t0) * 1000) / 1000;\n this.durations[name] = ms;\n this.marks.delete(name);\n return ms;\n }\n\n /** Run `fn` under a named stage. */\n async measure<T>(name: StageName, fn: () => T | Promise<T>): Promise<T> {\n this.start(name);\n try {\n return await fn();\n } finally {\n this.end(name);\n }\n }\n\n snapshot(): StageTimings {\n return { ...this.durations };\n }\n}\n\nfunction nowMs(): number {\n return Number(process.hrtime.bigint() / 1000n) / 1000;\n}\n","/**\n * Build-time graph summaries for fast agent answers (hubs + blast radius).\n * Pure and deterministic: same graph → same summaries.\n */\n\nimport { indexFor } from './relations.js';\nimport type { EdgeKind, VgGraph } from '../schema.js';\n\nconst DEPEND_EDGES = new Set<EdgeKind>(['call', 'import', 'extends', 'implements', 'references']);\n\nexport interface HubBlastSummary {\n id: string;\n name: string;\n kind: string;\n file: string;\n importance: number;\n /** Direct dependents (depth 1). */\n direct: number;\n /** Dependents within depth 2 (includes direct). */\n depth2: number;\n /** Distinct files among depth-2 dependents. */\n files: number;\n tested: boolean | null;\n}\n\nexport interface GraphSummaries {\n hubs: HubBlastSummary[];\n}\n\nconst HUB_LIMIT = 40;\n\n/**\n * Precompute blast-radius counts for the top hubs (by importance).\n * Used by MCP/CLI for near-instant \"what breaks if this hub changes\" answers.\n */\nexport function buildSummaries(graph: VgGraph): GraphSummaries {\n const index = indexFor(graph);\n const candidates = graph.nodes\n .filter((n) => n.kind !== 'file' && n.kind !== 'external' && n.kind !== 'document')\n .sort((a, b) => b.importance - a.importance || a.qualifiedName.localeCompare(b.qualifiedName))\n .slice(0, HUB_LIMIT);\n\n const hubs: HubBlastSummary[] = candidates.map((n) => {\n const d1 = reverseDependents(index, n.id, 1);\n const d2 = reverseDependents(index, n.id, 2);\n const files = new Set<string>();\n for (const id of d2) {\n const node = index.node(id);\n if (node?.file) files.add(node.file);\n }\n return {\n id: n.id,\n name: n.qualifiedName,\n kind: n.kind,\n file: n.file,\n importance: n.importance,\n direct: d1.size,\n depth2: d2.size,\n files: files.size,\n tested: n.tested,\n };\n });\n\n // Stable order already by importance; re-sort for safety.\n hubs.sort((a, b) => b.importance - a.importance || a.name.localeCompare(b.name));\n return { hubs };\n}\n\nfunction reverseDependents(\n index: ReturnType<typeof indexFor>,\n rootId: string,\n maxDepth: number,\n): Set<string> {\n const affected = new Set<string>();\n let frontier = [rootId];\n for (let depth = 1; depth <= maxDepth; depth++) {\n const next: string[] = [];\n for (const id of frontier) {\n for (const e of index.in(id)) {\n if (!DEPEND_EDGES.has(e.kind)) continue;\n if (e.src === rootId || affected.has(e.src)) continue;\n affected.add(e.src);\n next.push(e.src);\n }\n }\n frontier = next;\n if (frontier.length === 0) break;\n }\n return affected;\n}\n","/**\n * Deterministic package-manifest extraction.\n *\n * Pulls declared dependencies from package.json and go.mod into the code map as\n * `package` nodes + `import` edges to external packages. Complements source-level\n * imports so hubs/impact/ask can see the dependency surface without lockfile noise\n * (lockfiles stay skipped by discover).\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport ignore, { type Ignore } from 'ignore';\nimport { nodeId, edgeId } from './ids.js';\nimport { isSkippedDirName } from './discover.js';\nimport type { GraphEdge, GraphNode } from '../schema.js';\n\nexport interface ManifestExtract {\n nodes: GraphNode[];\n edges: GraphEdge[];\n /** Number of package.json + go.mod files processed. */\n files: number;\n deps: number;\n}\n\nconst emptyNode = (\n partial: Pick<GraphNode, 'id' | 'kind' | 'name' | 'qualifiedName' | 'file' | 'lang'> & {\n span?: GraphNode['span'];\n },\n): GraphNode => ({\n ...partial,\n span: partial.span ?? { start: 1, end: 1 },\n importance: 0,\n centrality: { degree: 0, pagerank: 0, betweenness: 0, eigenvector: 0 },\n area: -1,\n isHub: false,\n tested: null,\n});\n\n/**\n * Walk the project for package.json / go.mod (respecting the same skip rules as\n * discover) and return package nodes + dependency edges. Pure over filesystem\n * content; stable sort on output.\n */\nexport function extractManifests(\n root: string,\n opts: { exclude?: string[]; paths?: string[] } = {},\n): ManifestExtract {\n const absRoot = path.resolve(root);\n const ig = buildRootIgnore(absRoot, opts.exclude ?? []);\n const scopes = (opts.paths?.length ? opts.paths : ['.'])\n .map((p) => path.resolve(absRoot, p))\n .filter((p) => fs.existsSync(p));\n\n const found = new Map<string, string>(); // rel → abs\n for (const scope of scopes) {\n walkManifests(absRoot, scope, ig, found);\n }\n\n const nodes = new Map<string, GraphNode>();\n const edges = new Map<string, GraphEdge>();\n let deps = 0;\n\n for (const rel of [...found.keys()].sort()) {\n const abs = found.get(rel)!;\n const base = path.posix.basename(rel);\n try {\n if (base === 'package.json') {\n deps += ingestPackageJson(rel, abs, nodes, edges);\n } else if (base === 'go.mod') {\n deps += ingestGoMod(rel, abs, nodes, edges);\n }\n } catch {\n /* unreadable / invalid — skip */\n }\n }\n\n return {\n nodes: [...nodes.values()].sort((a, b) => a.id.localeCompare(b.id)),\n edges: [...edges.values()].sort(\n (a, b) =>\n a.kind.localeCompare(b.kind) || a.src.localeCompare(b.src) || a.dst.localeCompare(b.dst),\n ),\n files: found.size,\n deps,\n };\n}\n\nfunction ingestPackageJson(\n rel: string,\n abs: string,\n nodes: Map<string, GraphNode>,\n edges: Map<string, GraphEdge>,\n): number {\n const raw = JSON.parse(fs.readFileSync(abs, 'utf8')) as {\n name?: string;\n dependencies?: Record<string, string>;\n peerDependencies?: Record<string, string>;\n optionalDependencies?: Record<string, string>;\n };\n const pkgName = (raw.name && String(raw.name).trim()) || path.posix.dirname(rel) || '.';\n const localId = nodeId({ kind: 'package', qualifiedName: pkgName, file: rel });\n nodes.set(\n localId,\n emptyNode({\n id: localId,\n kind: 'package',\n name: pkgName.includes('/') ? pkgName.split('/').pop()! : pkgName,\n qualifiedName: pkgName,\n file: rel,\n lang: 'json',\n }),\n );\n\n // Also a file node so the graph links the manifest file itself.\n const fileId = nodeId({ kind: 'file', qualifiedName: rel, file: rel });\n nodes.set(\n fileId,\n emptyNode({\n id: fileId,\n kind: 'file',\n name: path.posix.basename(rel),\n qualifiedName: rel,\n file: rel,\n lang: 'json',\n }),\n );\n addEdge(edges, 'contains', fileId, localId, 1.0);\n\n let n = 0;\n const depMaps = [raw.dependencies, raw.peerDependencies, raw.optionalDependencies];\n const names = new Set<string>();\n for (const m of depMaps) {\n if (!m || typeof m !== 'object') continue;\n for (const name of Object.keys(m)) {\n if (name) names.add(name);\n }\n }\n for (const name of [...names].sort()) {\n const extId = ensureExternal(nodes, name);\n addEdge(edges, 'import', localId, extId, 1.0);\n n++;\n }\n return n;\n}\n\nfunction ingestGoMod(\n rel: string,\n abs: string,\n nodes: Map<string, GraphNode>,\n edges: Map<string, GraphEdge>,\n): number {\n const text = fs.readFileSync(abs, 'utf8');\n let moduleName = path.posix.dirname(rel) || '.';\n const moduleMatch = /^\\s*module\\s+(\\S+)/m.exec(text);\n if (moduleMatch) moduleName = moduleMatch[1];\n\n const localId = nodeId({ kind: 'package', qualifiedName: moduleName, file: rel });\n nodes.set(\n localId,\n emptyNode({\n id: localId,\n kind: 'package',\n name: moduleName.split('/').pop() ?? moduleName,\n qualifiedName: moduleName,\n file: rel,\n lang: 'go',\n }),\n );\n const fileId = nodeId({ kind: 'file', qualifiedName: rel, file: rel });\n nodes.set(\n fileId,\n emptyNode({\n id: fileId,\n kind: 'file',\n name: path.posix.basename(rel),\n qualifiedName: rel,\n file: rel,\n lang: 'go',\n }),\n );\n addEdge(edges, 'contains', fileId, localId, 1.0);\n\n // require blocks and single-line requires (ignore replace/exclude).\n const reqNames = new Set<string>();\n const block = /require\\s*\\(([\\s\\S]*?)\\)/g;\n let bm: RegExpExecArray | null;\n while ((bm = block.exec(text)) !== null) {\n for (const line of bm[1].split('\\n')) {\n const m = /^\\s*(\\S+)\\s+v\\S+/.exec(line);\n if (m && !line.trim().startsWith('//')) reqNames.add(m[1]);\n }\n }\n const single = /^\\s*require\\s+(\\S+)\\s+v\\S+/gm;\n let sm: RegExpExecArray | null;\n while ((sm = single.exec(text)) !== null) reqNames.add(sm[1]);\n\n let n = 0;\n for (const name of [...reqNames].sort()) {\n const extId = ensureExternal(nodes, name);\n addEdge(edges, 'import', localId, extId, 1.0);\n n++;\n }\n return n;\n}\n\nfunction ensureExternal(nodes: Map<string, GraphNode>, name: string): string {\n const id = nodeId({ kind: 'external', qualifiedName: name, file: '' });\n if (!nodes.has(id)) {\n nodes.set(\n id,\n emptyNode({\n id,\n kind: 'external',\n name,\n qualifiedName: name,\n file: '',\n lang: 'external',\n }),\n );\n }\n return id;\n}\n\nfunction addEdge(\n edges: Map<string, GraphEdge>,\n kind: GraphEdge['kind'],\n src: string,\n dst: string,\n confidence: number,\n): void {\n if (src === dst) return;\n const id = edgeId(kind, src, dst);\n if (edges.has(id)) return;\n edges.set(id, {\n id,\n kind,\n src,\n dst,\n resolution: 'heuristic',\n confidence,\n epistemic: 'declared',\n count: 1,\n });\n}\n\nfunction buildRootIgnore(root: string, exclude: string[]): Ignore {\n const ig = ignore();\n const gitignorePath = path.join(root, '.gitignore');\n if (fs.existsSync(gitignorePath)) {\n try {\n ig.add(fs.readFileSync(gitignorePath, 'utf8'));\n } catch {\n /* ignore */\n }\n }\n if (exclude.length) ig.add(exclude);\n return ig;\n}\n\nfunction walkManifests(\n root: string,\n dir: string,\n ig: Ignore,\n found: Map<string, string>,\n): void {\n let entries: fs.Dirent[];\n try {\n entries = fs.readdirSync(dir, { withFileTypes: true });\n } catch {\n return;\n }\n for (const entry of entries) {\n const abs = path.join(dir, entry.name);\n const rel = path.relative(root, abs).split(path.sep).join('/');\n if (entry.isDirectory()) {\n if (isSkippedDirName(entry.name)) continue;\n if (rel && ig.ignores(`${rel}/`)) continue;\n walkManifests(root, abs, ig, found);\n } else if (entry.isFile()) {\n const base = entry.name;\n if (base !== 'package.json' && base !== 'go.mod') continue;\n if (rel && ig.ignores(rel)) continue;\n found.set(rel, abs);\n }\n }\n}\n","/**\n * Parallel content hashing for the build hash stage.\n * Deterministic: callers sort/merge results by path; workers only compute hashes.\n */\n\nimport * as fs from 'node:fs/promises';\nimport * as os from 'node:os';\nimport { hashBytes } from './hash.js';\n\nexport interface HashJob {\n rel: string;\n abs: string;\n}\n\nexport interface HashResult {\n rel: string;\n hash: string;\n /** False if the file could not be read. */\n ok: boolean;\n}\n\n/**\n * Hash many files with bounded concurrency. Order of results is not guaranteed;\n * sort by `rel` if you need stable order.\n */\nexport async function hashFilesParallel(\n jobs: HashJob[],\n concurrency?: number,\n): Promise<HashResult[]> {\n if (jobs.length === 0) return [];\n const limit = Math.max(\n 1,\n Math.min(concurrency ?? Math.max(1, (os.cpus()?.length ?? 4) * 2), jobs.length),\n );\n\n const out: HashResult[] = new Array(jobs.length);\n let next = 0;\n\n async function worker(): Promise<void> {\n for (;;) {\n const i = next++;\n if (i >= jobs.length) return;\n const job = jobs[i];\n try {\n const buf = await fs.readFile(job.abs);\n out[i] = { rel: job.rel, hash: hashBytes(buf), ok: true };\n } catch {\n out[i] = { rel: job.rel, hash: '', ok: false };\n }\n }\n }\n\n await Promise.all(Array.from({ length: limit }, () => worker()));\n return out;\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { discover, mergeExcludes, type DiscoveredFile } from './discover.js';\nimport { parseFiles } from './pool.js';\nimport { resolve } from './resolve.js';\nimport { buildModuleResolver } from './module-resolver.js';\nimport { assembleTsResult, tsWalkFiles, type TsFilePartial } from './ts-resolver.js';\nimport { decodeScipIndex, scipEdges } from './scip.js';\nimport { analyze, type AnalysisTier, type ClusterMode } from './analyze.js';\nimport { applyStaticTestLinkage } from './tests.js';\nimport { loadCoverage, applyCoverage } from './coverage.js';\nimport { buildFacts } from './facts.js';\nimport { groundGraph } from './grounding.js';\nimport { loadCache } from './cache.js';\nimport { ambientFingerprint, loadTscCache, tsConfigFingerprint, tscKeys } from './tsc-cache.js';\nimport {\n resolveLimits,\n checkMemoryBudget,\n formatBytes,\n ResourceLimitError,\n type ResourceLimits,\n} from './limits.js';\nimport { hashString, hashBytes, canonicalize, shortId } from './hash.js';\nimport { grammarSetVersion } from './grammars.js';\nimport { classifyEpistemic } from './epistemic.js';\nimport { discoverDocs, documentNodesFromDocs } from './docs-ingest.js';\nimport { extractToolchain } from './toolchain/index.js';\nimport { toolchainGrammarSetVersion } from './toolchain/grammars.js';\nimport { shardTsProjects } from './ts-projects.js';\nimport { writeGraphIndex } from './index-db.js';\nimport { StageTimer, type StageTimings } from './timing.js';\nimport { buildSummaries } from './summaries.js';\nimport { extractManifests } from './manifests.js';\nimport { hashFilesParallel } from './hash-files.js';\nimport { VERSION } from '../version.js';\nimport {\n SCHEMA_VERSION,\n type EdgeKind,\n type GraphEdge,\n type ResolverKind,\n type Toolchain,\n type VgGraph,\n} from '../schema.js';\nimport type { ScipIndex } from './scip.js';\nimport type { FileParse } from './types.js';\nimport type { ResolveResult } from './resolve.js';\nimport { fileRolesFromParses } from './ast-roles.js';\nimport type { AstRoleHit } from '../core-open/scanners/architecture/ast-roles.js';\n\nexport interface BuildOptions {\n /** Directory to build (default cwd). */\n root: string;\n /** Restrict to language ids. */\n only?: string[];\n /** Extra ignore globs (gitignore syntax). */\n exclude?: string[];\n /** Sub-paths to scope to. */\n paths?: string[];\n /** Worker count; 1 forces inline. */\n jobs?: number;\n /** Force single-threaded parsing. */\n inline?: boolean;\n /** Disable the incremental cache (full rebuild). */\n noCache?: boolean;\n /** Heavier open passes (recorded in provenance; Phase 1+ wires the analyses). */\n deep?: boolean;\n /** Community detection mode (default 'louvain'). */\n cluster?: ClusterMode;\n /** Coverage report paths (default: auto-detect lcov/istanbul). */\n coverage?: string[];\n /** Skip coverage ingestion. */\n noCoverage?: boolean;\n /** Skip grounding (free knowledge pack). Default: grounding on. */\n noGround?: boolean;\n /** Path to a SCIP index to ingest (default: auto-detect index.scip). */\n scip?: string;\n /** Skip SCIP ingestion even if an index is present. */\n noScip?: boolean;\n /** Skip the in-process TypeScript Compiler API resolver (heuristic floor only). */\n noTsc?: boolean;\n /**\n * Fast mode: skip tsc precise resolve (heuristic only). Useful for XL cold\n * builds when precision can wait for a focused rebuild.\n */\n fast?: boolean;\n /** Force analysis tier (default: auto by node count). */\n analysisTier?: AnalysisTier;\n /** Skip writing the SQLite serve index. */\n noIndex?: boolean;\n /** Pin the artifact timestamp for byte-deterministic output. */\n generatedAt?: string;\n /** Live progress during the parse phase (files done of total). */\n onParseProgress?: (done: number, total: number) => void;\n /** Override directory for grammar .wasm files (offline / air-gapped). */\n grammarsDir?: string;\n /** Resource-safeguard overrides (else VG_MAX_FILE_BYTES / VG_MAX_FILES /\n * VG_TSC_MAX_FILES / VG_MEMORY_BUDGET_MB env vars, else defaults). */\n limits?: Partial<ResourceLimits>;\n}\n\n/** Stat + content hash of one corpus file at build time. */\nexport interface FileStat {\n rel: string;\n size: number;\n mtimeMs: number;\n hash: string;\n}\n\nexport interface BuildResult {\n graph: VgGraph;\n timing: { totalMs: number; stages: StageTimings };\n reparsed: number;\n reused: number;\n /** Files skipped via mtime+size fingerprint (subset of reused). */\n statHits: number;\n totalFiles: number;\n /** Stat+hash of every file in the corpus — input for the freshness snapshot. */\n fileStats: FileStat[];\n resolveStats: ResolveResult['stats'];\n /** Present when the TypeScript Compiler API resolver ran (TS/JS files). */\n tsc?: {\n files: number;\n calls: number;\n jsx: number;\n heritage: number;\n resolved: number;\n shards?: number;\n /** Files whose checker output was reused from the tsc cache (change-scoped\n * downstream, gap-closure 2c). Subset of `files`. */\n reusedFiles?: number;\n };\n /** Present when a SCIP index was ingested. */\n scip?: { documents: number; references: number; resolved: number; tool?: string };\n /** SQLite index write result. */\n index?: { ok: boolean; path?: string; reason?: string };\n warnings: string[];\n /** Architecture role hits extracted during the parse already paid for. */\n fileRoles: AstRoleHit[];\n}\n\nexport async function buildGraph(options: BuildOptions): Promise<BuildResult> {\n const timer = new StageTimer();\n timer.start('total');\n const root = path.resolve(options.root);\n const exclude = mergeExcludes(root, options.exclude);\n timer.start('discover');\n const files = discover({\n root,\n only: options.only,\n exclude,\n paths: options.paths,\n });\n timer.end('discover');\n\n // Resource safeguards (see limits.ts): stop a pathological corpus before it\n // OOM-kills the process. Skips are deterministic functions of the input.\n const limits = resolveLimits(options.limits);\n if (limits.maxFiles > 0 && files.length > limits.maxFiles) {\n throw new ResourceLimitError(\n `graph build stopped: ${files.length.toLocaleString()} files exceed the ` +\n `${limits.maxFiles.toLocaleString()}-file limit. Scope the build (pass sub-paths, add ` +\n `--exclude globs, or --only <langs>), or set VG_MAX_FILES to raise the limit ` +\n `(0 disables it).`,\n );\n }\n checkMemoryBudget('discovery', limits.memoryBudgetMb);\n\n // The toolchain grammar set is a determinism input too: an HCL grammar change\n // can change the Terraform structure extracted, so it belongs in the\n // reproducibility fingerprint alongside the source grammars.\n const grammars = `${grammarSetVersion()}+${toolchainGrammarSetVersion()}`;\n const cache = loadCache(root, {\n toolVersion: VERSION,\n grammars,\n disabled: options.noCache,\n });\n\n // Hash every discovered file (mtime+size fast path → content hash) and split\n // into reuse vs reparse. The stat is taken *before* the read so a mid-read\n // edit shows up as a stat mismatch on the next freshness probe.\n timer.start('hash');\n const hashes = new Map<string, string>();\n const fileStats: FileStat[] = [];\n const toParse: DiscoveredFile[] = [];\n const reused: FileParse[] = [];\n const buildWarnings: string[] = [];\n let statHits = 0;\n const pendingHash: { file: DiscoveredFile; size: number; mtimeMs: number }[] = [];\n for (const file of files) {\n let stat: fs.Stats;\n try {\n stat = fs.statSync(file.abs);\n } catch {\n // Unreadable now (race/permissions) — skip; it just won't be in the graph.\n continue;\n }\n if (limits.maxFileBytes > 0 && stat.size > limits.maxFileBytes) {\n // Too large to parse (almost always generated/minified). It stays in\n // fileStats — under a size-derived sentinel hash, so the file is never\n // read into memory — because the freshness probe re-discovers it; were\n // it absent from the snapshot every probe would report phantom \"added\"\n // drift and auto-refresh would rebuild in a loop.\n fileStats.push({\n rel: file.rel,\n size: stat.size,\n mtimeMs: stat.mtimeMs,\n hash: hashString(`vg:oversize:${stat.size}`),\n });\n buildWarnings.push(\n `${file.rel}: skipped — ${formatBytes(stat.size)} exceeds the ` +\n `${formatBytes(limits.maxFileBytes)} per-file limit (set VG_MAX_FILE_BYTES to raise it, 0 to disable)`,\n );\n continue;\n }\n\n // Fast path: unchanged mtime+size → reuse parse without reading bytes.\n const byStat = options.noCache\n ? undefined\n : cache.getByStat(file.rel, stat.mtimeMs, stat.size);\n if (byStat) {\n hashes.set(file.rel, byStat.hash);\n if (byStat.parse.hash !== byStat.hash) byStat.parse.hash = byStat.hash;\n fileStats.push({\n rel: file.rel,\n size: stat.size,\n mtimeMs: stat.mtimeMs,\n hash: byStat.hash,\n });\n reused.push(byStat.parse);\n statHits++;\n continue;\n }\n\n // Defer content hashing to a parallel batch (below) for files that miss\n // the mtime fast path — big monorepos spend real time in sequential reads.\n pendingHash.push({ file, size: stat.size, mtimeMs: stat.mtimeMs });\n }\n\n // Parallel content hash for the pending set.\n if (pendingHash.length) {\n const jobs = pendingHash.map((p) => ({ rel: p.file.rel, abs: p.file.abs }));\n const results = await hashFilesParallel(jobs, options.jobs);\n const byRel = new Map(results.map((r) => [r.rel, r]));\n // Stable order: process pendingHash in discovery order (already sorted).\n for (const p of pendingHash) {\n const r = byRel.get(p.file.rel);\n if (!r || !r.ok) continue;\n hashes.set(p.file.rel, r.hash);\n fileStats.push({\n rel: p.file.rel,\n size: p.size,\n mtimeMs: p.mtimeMs,\n hash: r.hash,\n });\n const cached = cache.get(p.file.rel, r.hash);\n if (cached) {\n reused.push(cached);\n cache.set(p.file.rel, cached, { mtimeMs: p.mtimeMs, size: p.size });\n } else {\n toParse.push(p.file);\n }\n }\n }\n timer.end('hash');\n\n timer.start('parse');\n const parsedNew = await parseFiles(toParse, {\n jobs: options.jobs,\n inline: options.inline,\n onProgress: options.onParseProgress,\n grammarsDir: options.grammarsDir,\n memoryBudgetMb: limits.memoryBudgetMb,\n });\n timer.end('parse');\n checkMemoryBudget('parse', limits.memoryBudgetMb);\n for (const p of parsedNew) {\n // Never persist a failed parse: a transient parse-runtime crash (e.g. a\n // corrupted wasm heap) would otherwise poison the cache for that content\n // hash and every later build would reuse the empty parse instead of\n // re-parsing the file.\n if (p.defs.length === 0 && p.warnings?.some((w) => w.startsWith('parse failed:'))) continue;\n const st = fileStats.find((f) => f.rel === p.rel);\n cache.set(p.rel, p, st ? { mtimeMs: st.mtimeMs, size: st.size } : undefined);\n }\n\n // Persist the cache for the next incremental build.\n const currentRels = new Set(files.map((f) => f.rel));\n cache.prune(currentRels);\n cache.save();\n\n const parses = [...reused, ...parsedNew].sort((a, b) =>\n a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0,\n );\n\n const warnings = [...buildWarnings, ...parses.flatMap((p) => p.warnings ?? [])];\n\n // Resolve → nodes/edges. The module resolver follows relative imports plus\n // tsconfig path aliases and workspace-package names (so monorepo cross-package\n // imports resolve, not just relative ones).\n timer.start('resolve');\n const moduleResolver = buildModuleResolver(root, new Set(parses.map((p) => p.rel)));\n const resolved = resolve(parses, moduleResolver);\n timer.end('resolve');\n checkMemoryBudget('resolve', limits.memoryBudgetMb);\n\n // Package manifests (package.json / go.mod) → package nodes + dep import edges.\n // Runs after source resolve so package hubs participate in centrality/areas.\n const manifests = extractManifests(root, {\n exclude,\n paths: options.paths,\n });\n if (manifests.files > 0) {\n const byId = new Map(resolved.nodes.map((n) => [n.id, n]));\n for (const n of manifests.nodes) {\n if (!byId.has(n.id)) {\n byId.set(n.id, n);\n resolved.nodes.push(n);\n }\n }\n const edgeById = new Map(resolved.edges.map((e) => [e.id, e]));\n for (const e of manifests.edges) {\n if (!edgeById.has(e.id)) {\n edgeById.set(e.id, e);\n resolved.edges.push(e);\n }\n }\n resolved.nodes.sort((a, b) => a.id.localeCompare(b.id));\n resolved.edges.sort(\n (a, b) =>\n a.kind.localeCompare(b.kind) || a.src.localeCompare(b.src) || a.dst.localeCompare(b.dst),\n );\n }\n\n // Precise resolution rungs sit above the heuristic floor and are authoritative\n // for the files they cover (their relational edges replace the heuristic ones,\n // not merely augment them). Order: heuristic → tsc → scip. Runs before\n // test-linkage so it sharpens those edges too.\n const nodeFileById = new Map(resolved.nodes.map((n) => [n.id, n.file]));\n let edges = resolved.edges;\n const resolvers: ResolverKind[] = [...resolved.stats.resolvers];\n // Files a precise rung (tsc/scip) covered — their heuristic unknowns are\n // superseded by the authoritative resolver and must not be reported as unknown.\n const preciseCoveredFiles = new Set<string>();\n\n // Rung 1 — TypeScript Compiler API for TS/JS (default-on, in-process, no\n // external tool). The type checker resolves member/`this`/imported/aliased\n // calls and heritage that the heuristic structurally cannot.\n let tscStats: BuildResult['tsc'];\n // `hashes` holds exactly the parsed corpus — oversized (size-capped) files\n // are excluded here too, so the TS program never loads them.\n const skipTsc = options.noTsc || options.fast;\n let tsFiles = skipTsc\n ? []\n : files\n .filter((f) => (f.lang.id === 'ts' || f.lang.id === 'tsx' || f.lang.id === 'js') && hashes.has(f.rel))\n .map((f) => ({ rel: f.rel, abs: f.abs }));\n if (limits.tscMaxFiles > 0 && tsFiles.length > limits.tscMaxFiles) {\n // A ts.Program over the whole corpus is the largest single memory consumer\n // in the build. Past the cap, fall back to the heuristic floor (still a\n // complete graph, just less precise call resolution).\n warnings.push(\n `typescript resolver skipped — ${tsFiles.length.toLocaleString()} TS/JS files exceed the ` +\n `${limits.tscMaxFiles.toLocaleString()}-file limit; calls use the heuristic resolver ` +\n `(set VG_TSC_MAX_FILES to raise it, 0 to disable)`,\n );\n tsFiles = [];\n }\n timer.start('tsc');\n if (tsFiles.length) {\n // Shard by nearest tsconfig/package.json so monorepos never pay for one\n // giant Program over every package.\n const shards = shardTsProjects(root, tsFiles);\n let filesCovered = 0;\n let calls = 0;\n let jsx = 0;\n let heritage = 0;\n let resolvedCount = 0;\n let tscReusedFiles = 0;\n const coveredAll = new Set<string>();\n const preciseAll: GraphEdge[] = [];\n\n // Change-scoped downstream (gap-closure 2c): per-file checker results are\n // cached under a key covering the file's content, its transitive import\n // closure, and the shard's ambient surface — so a warm refresh re-walks\n // only the changed files and their reverse-dependency closure instead of\n // the whole corpus. assembleTsResult re-merges cached + fresh partials in\n // original file order, so the output is byte-identical to a full walk\n // (enforced by incremental-identity.test.ts).\n const tscCache = loadTscCache(root, { toolVersion: VERSION, disabled: options.noCache });\n const cfgFingerprint = tsConfigFingerprint(root);\n\n for (const shard of shards) {\n const ambientFiles = shard.files.filter((f) => tscCache.isAmbient(f.rel, hashes.get(f.rel)!, f.abs));\n const ambientHash = ambientFingerprint(\n ambientFiles.map((f) => ({ rel: f.rel, hash: hashes.get(f.rel)! })),\n cfgFingerprint,\n );\n const keys = tscKeys(shard.files.map((f) => f.rel), hashes, resolved.importsByFile, ambientHash);\n\n const partials = new Map<string, TsFilePartial>();\n const walkFiles: typeof shard.files = [];\n for (const f of shard.files) {\n const cached = tscCache.get(f.rel, keys.get(f.rel)!);\n if (cached) {\n partials.set(f.rel, cached);\n tscReusedFiles++;\n } else {\n walkFiles.push(f);\n }\n }\n // Ambient files must be in the program even when their own results are\n // cached — their global declarations shape checker answers everywhere.\n const walkRels = new Set(walkFiles.map((f) => f.rel));\n const extraRoots = ambientFiles.filter((f) => !walkRels.has(f.rel));\n const fresh = tsWalkFiles(root, walkFiles, shard.files, extraRoots, resolved.nodes);\n for (const [rel, partial] of fresh) {\n partials.set(rel, partial);\n tscCache.set(rel, hashes.get(rel)!, keys.get(rel)!, partial);\n }\n\n const res = assembleTsResult(shard.files.map((f) => f.rel), partials, resolved.nodes);\n if (res.stats.files === 0) continue;\n filesCovered += res.stats.files;\n calls += res.stats.calls;\n jsx += res.stats.jsx;\n heritage += res.stats.heritage;\n resolvedCount += res.stats.resolved;\n for (const f of res.coveredFiles) coveredAll.add(f);\n preciseAll.push(...res.edges);\n }\n\n tscCache.prune(new Set(tsFiles.map((f) => f.rel)));\n tscCache.save();\n\n if (filesCovered > 0) {\n edges = mergePreciseEdges(edges, preciseAll, coveredAll, nodeFileById);\n for (const f of coveredAll) preciseCoveredFiles.add(f);\n if (!resolvers.includes('tsc')) resolvers.unshift('tsc');\n tscStats = {\n files: filesCovered,\n calls,\n jsx,\n heritage,\n resolved: resolvedCount,\n shards: shards.length,\n reusedFiles: tscReusedFiles,\n };\n }\n checkMemoryBudget('typescript resolution', limits.memoryBudgetMb);\n }\n timer.end('tsc');\n\n // Rung 2 — a real SCIP index (if present), the most precise rung for any\n // language an indexer covers.\n const scip = options.noScip ? null : loadScipIndex(root, options.scip);\n let scipStats: BuildResult['scip'];\n if (scip) {\n const res = scipEdges(scip.index, resolved.nodes, toRepoRel);\n edges = mergePreciseEdges(edges, res.edges, res.coveredFiles, nodeFileById);\n for (const f of res.coveredFiles) preciseCoveredFiles.add(f);\n if (!resolvers.includes('scip')) resolvers.unshift('scip');\n scipStats = { ...res.stats, tool: scip.tool };\n }\n\n // Test-awareness: static test→code linkage, then runtime coverage if present.\n const linked = applyStaticTestLinkage(resolved.nodes, edges);\n let nodes = linked.nodes;\n const coverage = options.noCoverage ? null : loadCoverage(root, options.coverage);\n if (coverage) nodes = applyCoverage(nodes, coverage);\n\n // Documentation / example-env text nodes for semantic ask (not AST-parsed).\n const docs = discoverDocs({\n root,\n exclude,\n paths: options.paths,\n });\n for (const d of docs) {\n try {\n const st = fs.statSync(d.abs);\n const hash = hashBytes(fs.readFileSync(d.abs));\n hashes.set(d.rel, hash);\n fileStats.push({ rel: d.rel, size: st.size, mtimeMs: st.mtimeMs, hash });\n } catch {\n /* skip unreadable docs */\n }\n }\n const docNodes = documentNodesFromDocs(docs);\n if (docNodes.length) nodes = [...nodes, ...docNodes];\n\n // Structural extraction over the same discovered set (engine/toolchain/).\n // The `document` nodes above stay — they remain the semantic-ask surface —\n // and this adds the *structure*: resources, workloads, jobs, images, charts.\n //\n // NB: this reads `docs`, not the source corpus. Registering `.tf`/`.yaml` as\n // source languages would change file counts that feed billing tiers, so the\n // toolchain corpus is deliberately kept separate.\n timer.start('toolchain');\n const fileNodesByPath = new Map<string, string>();\n for (const node of nodes) {\n if (node.kind === 'file') fileNodesByPath.set(node.file.replace(/\\\\/g, '/'), node.id);\n }\n const toolchainResult = await extractToolchain(docs, { fileNodes: fileNodesByPath });\n if (toolchainResult.nodes.length) nodes = [...nodes, ...toolchainResult.nodes];\n timer.end('toolchain');\n\n // Analyse → centrality/areas/surprise (test/coverage edges excluded from these).\n timer.start('analyze');\n const graphEdges = toolchainResult.edges.length\n ? [...linked.edges, ...toolchainResult.edges]\n : linked.edges;\n const analysis = analyze(nodes, graphEdges, {\n cluster: options.cluster,\n tier: options.analysisTier,\n });\n timer.end('analyze');\n checkMemoryBudget('analysis', limits.memoryBudgetMb);\n\n const languages = [\n ...new Set([\n ...parses.map((p) => p.lang),\n ...docNodes.map((n) => n.lang),\n ...toolchainResult.nodes.map((n) => n.lang),\n ]),\n ].sort();\n const edgeKinds = [...new Set(analysis.edges.map((e) => e.kind))].sort() as EdgeKind[];\n const corpusHash = computeCorpusHash(parses, hashes);\n\n // Edge-level epistemic tier: stamp every edge with how it was resolved\n // (observed / name-matched / declared) so consumers can filter by assurance.\n // Pure function of the edge's fields + its destination node kind → deterministic.\n const nodeKindById = new Map(analysis.nodes.map((n) => [n.id, n.kind]));\n for (const e of analysis.edges) {\n e.epistemic = classifyEpistemic(e, nodeKindById.get(e.dst));\n }\n\n const toolchain = computeToolchain(grammars, resolvers);\n\n const generatedAt = options.generatedAt ?? new Date().toISOString();\n const testsCount = linked.testFiles.length;\n const untestedCount = analysis.nodes.filter(\n (n) => (n.kind === 'function' || n.kind === 'method') && n.tested === false,\n ).length;\n\n const graph: VgGraph = {\n schemaVersion: SCHEMA_VERSION,\n generatedAt,\n provenance: {\n tool: 'vg',\n version: VERSION,\n grammars: Object.fromEntries(languages.map((l) => [l, grammars])),\n resolver: resolvers,\n deep: options.deep ?? false,\n corpusHash,\n toolchain,\n },\n meta: {\n root: path.basename(root) === '' ? '.' : '.',\n languages,\n analysisTier: analysis.tier,\n counts: {\n nodes: analysis.nodes.length,\n edges: analysis.edges.length,\n areas: analysis.areas.length,\n tests: testsCount,\n untested: untestedCount,\n },\n cluster: analysis.cluster,\n edgeKinds,\n },\n nodes: analysis.nodes,\n edges: analysis.edges,\n areas: analysis.areas,\n };\n\n // Unknowns: heuristic references we could not resolve, minus any site a precise\n // rung authoritatively covered. Ranked/consumed by `vg unknowns`. Deterministic\n // (already sorted by resolve()); only ids that survived analysis are kept.\n const survivingIds = new Set(analysis.nodes.map((n) => n.id));\n const unknowns = resolved.unresolved\n .filter((u) => !preciseCoveredFiles.has(u.fromRel) && survivingIds.has(u.from))\n .map((u) => ({ from: u.from, name: u.name, kind: u.kind, count: u.count }));\n if (unknowns.length) graph.unknowns = unknowns;\n\n // Hub blast-radius summaries (cheap agent answers for \"what breaks if X changes\").\n graph.summaries = buildSummaries(graph);\n\n // Deterministic open facts (contracts / invariants / characterization) are\n // cheap AST-level work and ship on every build so `vg facts` works without a\n // second pass. `--deep` remains the switch for heavier semantic layers.\n {\n const facts = buildFacts(parses, analysis.nodes, analysis.edges);\n if (facts.length) graph.facts = facts;\n }\n // Grounding (default on).\n if (!options.noGround) {\n const grounding = groundGraph(analysis.nodes, analysis.edges, parses);\n if (grounding.length) graph.grounding = grounding;\n }\n\n let indexResult: BuildResult['index'];\n if (!options.noIndex) {\n timer.start('index');\n const wr = writeGraphIndex(root, graph);\n indexResult = { ok: wr.ok, path: wr.ok ? wr.path : undefined, reason: wr.reason };\n timer.end('index');\n }\n\n timer.end('total');\n const stages = timer.snapshot();\n\n return {\n graph,\n timing: { totalMs: stages.total ?? 0, stages },\n reparsed: parsedNew.length,\n reused: reused.length,\n statHits,\n totalFiles: files.length,\n fileStats,\n resolveStats: resolved.stats,\n tsc: tscStats,\n scip: scipStats,\n index: indexResult,\n warnings,\n fileRoles: fileRolesFromParses(parses),\n };\n}\n\n/** Repo-relative POSIX path for a SCIP document path. */\nfunction toRepoRel(p: string): string {\n return p.split('\\\\').join('/').replace(/^\\.?\\//, '');\n}\n\n/** Auto-detect (or take an explicit) SCIP index and decode it. */\nfunction loadScipIndex(root: string, explicit?: string): { index: ScipIndex; tool?: string } | null {\n const candidates = [\n explicit,\n path.join(root, 'index.scip'),\n path.join(root, '.vibgrate', 'index.scip'),\n ].filter((p): p is string => Boolean(p));\n for (const file of candidates) {\n const abs = path.isAbsolute(file) ? file : path.resolve(root, file);\n if (!fs.existsSync(abs)) continue;\n try {\n const index = decodeScipIndex(new Uint8Array(fs.readFileSync(abs)));\n if (index.documents.length) {\n return { index, tool: index.toolVersion ? `${index.toolName} ${index.toolVersion}` : index.toolName };\n }\n } catch {\n /* unreadable/garbled index — fall back to heuristic */\n }\n }\n return null;\n}\n\n/** Relational edge kinds a precise resolver is authoritative for. Structural\n * kinds (import/contains/test/coverage) are produced elsewhere and preserved. */\nconst PRECISE_KINDS = new Set<EdgeKind>(['call', 'references', 'extends', 'implements']);\n\n/**\n * Merge precise edges over the base set, treating the precise rung as\n * authoritative for the files it covered. For a covered file we DROP the\n * heuristic relational edges originating there (they are guesses the precise\n * resolver has now superseded) and replace them with the precise ones. Edges\n * whose source lives in an uncovered file, and non-relational edges, are kept.\n * Already-precise edges (tsc/scip) are never dropped. Precise wins on id\n * collision. Output is stably sorted for determinism.\n */\nfunction mergePreciseEdges(\n base: GraphEdge[],\n precise: GraphEdge[],\n coveredFiles: Set<string>,\n nodeFileById: Map<string, string>,\n): GraphEdge[] {\n const byId = new Map<string, GraphEdge>();\n for (const e of base) {\n if (PRECISE_KINDS.has(e.kind) && e.resolution === 'heuristic') {\n const srcFile = nodeFileById.get(e.src);\n if (srcFile && coveredFiles.has(srcFile)) continue; // superseded by precise rung\n }\n byId.set(e.id, e);\n }\n for (const e of precise) byId.set(e.id, e); // precise wins on id collision\n return [...byId.values()].sort(\n (a, b) =>\n a.kind.localeCompare(b.kind) || a.src.localeCompare(b.src) || a.dst.localeCompare(b.dst),\n );\n}\n\n/**\n * The reproducibility fingerprint: a short content-address over the parts of the\n * toolchain that deterministically shape graph *content* — schema, tool version,\n * tree-sitter grammar set, and the resolver kinds available. Node/OS versions are\n * deliberately excluded so the graph stays byte-stable across host runtimes; the\n * fingerprint pins the parse/resolve toolchain, which is what actually changes\n * edges between a CI run and a laptop run. This is the value `vg attest` signs and\n * `vg verify` compares against a committed graph.\n */\nfunction computeToolchain(grammars: string, resolvers: ResolverKind[]): Toolchain {\n const sortedResolvers = [...new Set(resolvers)].sort();\n return {\n schema: SCHEMA_VERSION,\n tool: VERSION,\n grammars,\n resolvers: sortedResolvers,\n fingerprint: shortId(\n canonicalize({\n schema: SCHEMA_VERSION,\n tool: VERSION,\n grammars,\n resolvers: sortedResolvers,\n }),\n ),\n };\n}\n\n/**\n * blake3 over the sorted (path, content-hash) list — the corpus identity.\n * Includes documentation / env-example files (in `hashes`) as well as parsed\n * source, so README edits invalidate the map identity and embedding cache.\n */\nfunction computeCorpusHash(parses: FileParse[], hashes: Map<string, string>): string {\n const fromParses = parses.map((p) => [p.rel, hashes.get(p.rel) ?? p.hash] as const);\n const fromHashes = [...hashes.entries()].map(([rel, hash]) => [rel, hash] as const);\n const byRel = new Map<string, string>();\n for (const [rel, hash] of [...fromParses, ...fromHashes]) byRel.set(rel, hash);\n const list = [...byRel.entries()].sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));\n return hashString(canonicalize(list));\n}\n\n","import { buildGraph } from './build.js';\nimport { serializeGraph } from './serialize.js';\nimport { loadGraph } from './load.js';\nimport { hashString } from './hash.js';\n\n/**\n * Determinism self-check (`vg verify`, exit 4 on failure).\n *\n * Proves the load-bearing guarantees:\n * 1. Run-to-run determinism — two full rebuilds are byte-identical.\n * 2. Cache safety — an incremental (cache-warm) build equals a full rebuild.\n * 3. Toolchain reproducibility — the toolchain that would build the graph here\n * matches the one recorded in the committed `graph.json` (when present), so a\n * CI run and a laptop run on different grammar/resolver versions are caught\n * instead of silently producing a different graph.\n *\n * `generatedAt` is pinned to a constant for the comparison so the only legitimate\n * source of variation is removed and any real nondeterminism surfaces.\n */\n\nconst PINNED = '1970-01-01T00:00:00.000Z';\n\nexport interface VerifyResult {\n ok: boolean;\n checks: { name: string; ok: boolean; detail?: string }[];\n digest: string;\n}\n\nexport async function verifyDeterminism(opts: {\n root: string;\n only?: string[];\n exclude?: string[];\n jobs?: number;\n}): Promise<VerifyResult> {\n const base = { root: opts.root, only: opts.only, exclude: opts.exclude, generatedAt: PINNED };\n\n const buildA = await buildGraph({ ...base, noCache: true, jobs: opts.jobs });\n const a = serializeGraph(buildA.graph);\n const b = serializeGraph((await buildGraph({ ...base, noCache: true, jobs: 1 })).graph);\n const cached = serializeGraph((await buildGraph({ ...base, noCache: false })).graph);\n\n const checks = [\n { name: 'run-to-run determinism', ok: a === b, detail: diffHint(a, b) },\n { name: 'cache safety (incremental == full)', ok: a === cached, detail: diffHint(a, cached) },\n ];\n\n // Toolchain reproducibility: if a graph.json is committed, the toolchain that\n // would build it here must match the one it was built with. A mismatch is the\n // CI-vs-laptop divergence surfacing loudly instead of as a silent content diff.\n // Skip under --only/--exclude: a scoped rebuild's resolver set (e.g. no tsc for\n // a non-TS subtree) legitimately differs from the full-repo committed graph, so\n // comparing the two would be a false failure.\n const scoped = Boolean(opts.only?.length || opts.exclude?.length);\n const committed = scoped ? null : loadGraph(opts.root);\n const committedFp = committed?.provenance.toolchain?.fingerprint;\n const currentFp = buildA.graph.provenance.toolchain?.fingerprint;\n if (committedFp && currentFp) {\n const ok = committedFp === currentFp;\n checks.push({\n name: 'toolchain fingerprint matches committed graph',\n ok,\n detail: ok\n ? undefined\n : `committed toolchain ${committedFp} != current ${currentFp} ` +\n `(grammar/resolver versions differ — rebuild or align the toolchain)`,\n });\n }\n\n return {\n ok: checks.every((c) => c.ok),\n checks,\n digest: hashString(a),\n };\n}\n\nfunction diffHint(x: string, y: string): string | undefined {\n if (x === y) return undefined;\n // Find the first differing line for an actionable message (no internals leak).\n const xl = x.split('\\n');\n const yl = y.split('\\n');\n const n = Math.max(xl.length, yl.length);\n for (let i = 0; i < n; i++) {\n if (xl[i] !== yl[i]) {\n return `first divergence at line ${i + 1}`;\n }\n }\n return 'outputs differ in length';\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { discover, mergeExcludes } from './discover.js';\nimport { discoverDocs } from './docs-ingest.js';\nimport { hashBytes } from './hash.js';\nimport { cacheDir } from './cache.js';\nimport { stableStringify } from './serialize.js';\nimport type { FileStat } from './build.js';\n\n/**\n * Freshness tracking for the code map (VG auto-refresh).\n *\n * Every build writes a *snapshot* — the stat (size, mtime) and content hash of\n * each corpus file, plus the build scope — under `.vibgrate/cache/` (gitignored,\n * machine-local, never part of the committed artifact). A *probe* then answers\n * \"did the working tree drift from the map?\" with a stat-only walk: no file is\n * read unless its size/mtime moved, and a moved stat is confirmed by re-hashing\n * just that file. Touch-only changes (git checkout, `touch`, editor re-saves\n * with identical content) are *absorbed*: the snapshot's stats are updated in\n * place so they never trigger a rebuild — not now, not on the next probe.\n *\n * This is what lets `vg serve` and `vg ask` stay fresh without a filesystem\n * watcher: freshness only matters at the moment of a query, so we check on\n * read, cheaply, and rebuild incrementally only when content really changed.\n */\n\nconst SNAPSHOT_VERSION = 'vg-freshness/1';\n\n/** The graph-affecting discovery/build scope, replayed verbatim on refresh. */\nexport interface BuildScope {\n only?: string[];\n exclude?: string[];\n paths?: string[];\n deep?: boolean;\n noGround?: boolean;\n scip?: string;\n noScip?: boolean;\n noTsc?: boolean;\n cluster?: string;\n grammarsDir?: string;\n}\n\ninterface SnapshotFile {\n version: string;\n /** corpusHash of the build this snapshot belongs to. */\n corpusHash: string;\n scope: BuildScope;\n files: Record<string, { size: number; mtimeMs: number; hash: string }>;\n}\n\nexport interface Drift {\n /** Files whose *content* changed (stat moved AND hash differs). */\n changed: string[];\n /** Files present now but absent from the snapshot. */\n added: string[];\n /** Snapshot files no longer present. */\n removed: string[];\n}\n\nexport interface ProbeResult {\n drift: Drift;\n /** The recorded build scope — what a refresh must replay. */\n scope: BuildScope;\n /** corpusHash the current map was built from. */\n corpusHash: string;\n}\n\nexport function snapshotPath(root: string): string {\n return path.join(cacheDir(root), 'freshness.json');\n}\n\n/** Persist the snapshot after a successful build. Best-effort (cache-only). */\nexport function writeSnapshot(\n root: string,\n corpusHash: string,\n fileStats: FileStat[],\n scope: BuildScope = {},\n): void {\n const files: SnapshotFile['files'] = {};\n for (const f of fileStats) files[f.rel] = { size: f.size, mtimeMs: f.mtimeMs, hash: f.hash };\n const snapshot: SnapshotFile = { version: SNAPSHOT_VERSION, corpusHash, scope: pruneScope(scope), files };\n try {\n fs.mkdirSync(cacheDir(root), { recursive: true });\n fs.writeFileSync(snapshotPath(root), stableStringify(snapshot, 0));\n } catch {\n /* read-only checkout etc. — freshness just stays unavailable */\n }\n}\n\nexport function loadSnapshot(root: string): SnapshotFile | null {\n try {\n const loaded = JSON.parse(fs.readFileSync(snapshotPath(root), 'utf8')) as SnapshotFile;\n if (loaded.version === SNAPSHOT_VERSION && loaded.files && typeof loaded.corpusHash === 'string') {\n return { ...loaded, scope: loaded.scope ?? {} };\n }\n } catch {\n /* missing/corrupt → no snapshot */\n }\n return null;\n}\n\nexport function hasDrift(drift: Drift): boolean {\n return drift.changed.length + drift.added.length + drift.removed.length > 0;\n}\n\n/** Total drifted files — the number shown to humans. */\nexport function driftCount(drift: Drift): number {\n return drift.changed.length + drift.added.length + drift.removed.length;\n}\n\n/**\n * Compare the working tree to the snapshot. Returns null when no snapshot\n * exists (nothing was ever built on this machine — auto-refresh stays off\n * rather than guessing the build scope). Stat-only except for files whose\n * stat moved; touch-only moves are absorbed back into the snapshot.\n */\nexport function probeFreshness(root: string): ProbeResult | null {\n const snapshot = loadSnapshot(root);\n if (!snapshot) return null;\n\n const { scope } = snapshot;\n const exclude = mergeExcludes(root, scope.exclude);\n // Must match the build's fileStats universe: language sources + context docs\n // (README, CI yaml, package manifests, …). Probing only `discover()` left\n // every document in the snapshot as \"removed\" after a successful build, so\n // `vg status` kept reporting hundreds of drifted files after ask/serve refresh.\n let discovered: { rel: string; abs: string }[];\n try {\n const code = discover({ root, only: scope.only, exclude, paths: scope.paths });\n const docs = discoverDocs({ root, exclude, paths: scope.paths });\n const byRel = new Map<string, string>();\n for (const f of code) byRel.set(f.rel, f.abs);\n for (const d of docs) {\n if (!byRel.has(d.rel)) byRel.set(d.rel, d.abs);\n }\n discovered = [...byRel.entries()]\n .map(([rel, abs]) => ({ rel, abs }))\n .sort((a, b) => (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0));\n } catch {\n return null; // root vanished / unreadable — treat as unknown, not stale\n }\n\n const drift: Drift = { changed: [], added: [], removed: [] };\n const seen = new Set<string>();\n let absorbed = false;\n\n for (const file of discovered) {\n seen.add(file.rel);\n const entry = snapshot.files[file.rel];\n if (!entry) {\n drift.added.push(file.rel);\n continue;\n }\n let stat: fs.Stats;\n try {\n stat = fs.statSync(file.abs);\n } catch {\n drift.removed.push(file.rel); // raced away between walk and stat\n continue;\n }\n if (stat.size === entry.size && stat.mtimeMs === entry.mtimeMs) continue;\n // Stat moved — confirm with content before declaring drift.\n // Build records oversized files with a size-only sentinel hash so the probe\n // must not re-read them into memory (or mis-report them as always-changed).\n if (entry.hash.startsWith('vg:oversize:')) {\n const expected = `vg:oversize:${stat.size}`;\n if (entry.hash === expected) {\n snapshot.files[file.rel] = { size: stat.size, mtimeMs: stat.mtimeMs, hash: entry.hash };\n absorbed = true;\n } else {\n drift.changed.push(file.rel);\n }\n continue;\n }\n let hash = '';\n try {\n hash = hashBytes(fs.readFileSync(file.abs));\n } catch {\n drift.removed.push(file.rel);\n continue;\n }\n if (hash === entry.hash) {\n // Touch-only (checkout/`touch`/identical re-save): absorb the new stat\n // so this file never re-triggers a probe, without any rebuild.\n snapshot.files[file.rel] = { size: stat.size, mtimeMs: stat.mtimeMs, hash };\n absorbed = true;\n } else {\n drift.changed.push(file.rel);\n }\n }\n\n for (const rel of Object.keys(snapshot.files)) {\n if (!seen.has(rel)) drift.removed.push(rel);\n }\n\n // Persist absorptions only when the tree is otherwise clean — a real drift\n // triggers a rebuild that rewrites the snapshot wholesale anyway.\n if (absorbed && !hasDrift(drift)) {\n try {\n fs.writeFileSync(snapshotPath(root), stableStringify(snapshot, 0));\n } catch {\n /* best-effort */\n }\n }\n\n drift.changed.sort();\n drift.added.sort();\n drift.removed.sort();\n return { drift, scope, corpusHash: snapshot.corpusHash };\n}\n\n/** Drop empty/undefined scope fields so the snapshot stays minimal and stable. */\nfunction pruneScope(scope: BuildScope): BuildScope {\n const out: BuildScope = {};\n if (scope.only?.length) out.only = [...scope.only].sort();\n if (scope.exclude?.length) out.exclude = [...scope.exclude];\n if (scope.paths?.length) out.paths = [...scope.paths];\n if (scope.deep) out.deep = true;\n if (scope.noGround) out.noGround = true;\n if (scope.scip) out.scip = scope.scip;\n if (scope.noScip) out.noScip = true;\n if (scope.noTsc) out.noTsc = true;\n if (scope.cluster) out.cluster = scope.cluster;\n if (scope.grammarsDir) out.grammarsDir = scope.grammarsDir;\n return out;\n}\n","/**\n * Shared, deterministic content for `vg install`: the skill body and the advisory\n * nudge. Posture is deliberately lighter-touch — the nudge\n * *suggests* the graph as the faster path, never asserts \"MANDATORY\"\n * (VG-ASSISTANT-INSTALL §1). On small repos we say searching is fine.\n */\n\nexport const SKILL_MARKER = 'vg-graph-skill';\nexport const NUDGE_BEGIN = '<!-- vg:begin -->';\nexport const NUDGE_END = '<!-- vg:end -->';\n\n/**\n * Version of the generated instruction content (skill + nudge). Bump on ANY\n * wording/structure change to those templates: files written by `vg install`\n * carry this number in an HTML-comment marker, and `vg` builds auto-refresh\n * installed copies whose marker is older (see registry.ts\n * refreshInstalledInstructions) — so evolved instructions reach existing\n * repos the first time a new CLI version builds there.\n *\n * History: v1 = the unversioned originals (detected by their headings);\n * v2 = versioned markers + the strong MCP-first recommendation.\n */\nexport const INSTALL_CONTENT_VERSION = 2;\n\nconst VERSION_MARKER_RE = /<!--\\s*vg:v(\\d+)\\b[^>]*-->/;\n\n/** The marker line embedded in every generated instruction file. */\nexport function versionMarker(): string {\n return `<!-- vg:v${INSTALL_CONTENT_VERSION} · managed by \\`vg install\\` — auto-refreshed when these instructions evolve; remove this line to opt out -->`;\n}\n\n/**\n * The content version a previously-written instruction file carries, or null\n * when it has no marker (pre-versioning installs, or user-authored files).\n */\nexport function installedContentVersion(text: string): number | null {\n const m = VERSION_MARKER_RE.exec(text);\n return m ? Number(m[1]) : null;\n}\n\n/**\n * The `--client` value the skill/nudge tells the assistant to pass to `vg` so its\n * CLI calls are attributed. `vg install <assistant>` passes the assistant id\n * (e.g. `claude`, `cursor`); the canonical reference copy uses a placeholder.\n */\nfunction clientFlag(client?: string): string {\n return client ? `--client=${client}` : '--client=<your-ai>';\n}\n\nexport function skillMarkdown(client?: string): string {\n const cf = clientFlag(client);\n return `---\nname: vg\ndescription: Query the local code graph (vg) for structure, impact, and navigation instead of grepping/reading many files.\n---\n\n${versionMarker()}\n\n# vg — the code map\n\nThis repo has a deterministic code graph built by \\`vg\\`. Prefer it over reading or\ngrepping many files — it is smaller, more relevant context, and free.\n\n## Use the MCP tools — not the CLI\n\nWhen the \\`vg\\` MCP server is registered (it is after \\`vg install\\`), **always call\nits read-only tools instead of shelling out to the CLI.** The server keeps the\nmap parsed, the relation index warm, and the embedding model loaded across\ncalls, so an MCP call answers in milliseconds — while every CLI invocation pays\nNode startup plus a fresh map parse, hundreds of times more. Tools:\n\\`query_graph\\`, \\`get_node\\`, \\`impact_of\\`, \\`find_path\\`, \\`list_hubs\\`, \\`list_areas\\`,\n\\`get_graph_summary\\`, \\`search_symbols\\`. They are side-effect-free and\nauto-approvable, and the server records which client is calling automatically.\nReach for the CLI only when the MCP server is genuinely unavailable — never as\nthe first resort.\n\n## CLI fallback — only when the MCP server is unavailable\n\nIf (and only if) no \\`vg\\` MCP server is available, use the CLI — and **always\npass \\`${cf}\\`** so your calls are counted (that's how the CLI-vs-MCP split is\nmeasured and the tools improved):\n\n- **Understand code:** \\`vg \"<question>\" ${cf}\\` — a budget-bounded, fact-annotated context block.\n- **Find a symbol:** \\`vg show <name> ${cf}\\` — what it is, what it calls, what calls it.\n- **Before changing something:** \\`vg impact <name> ${cf}\\` — what breaks if you change it.\n- **Navigate:** \\`vg path <A> <B> ${cf}\\`, \\`vg tree <name> ${cf}\\`.\n\n## Dependencies & library docs\n\n- **Upgrade drift:** \\`vg drift\\` lists what is outdated across dependencies\n (offline; \\`--online\\` for currency). \\`vg scan\\` scores upgrade drift and\n \\`vg report\\` renders it (text | json | sarif | md).\n- **Version-correct docs:** \\`vg lib <name>\\` returns drift-annotated, version-\n specific usage docs for a library — inject these instead of guessing an API.\n\n### Library-docs discipline\n\nWhen a task needs a library's API, use the docs tools before web search or\ntraining-data recall — they are official content matched to the version **this\nproject has installed**, and they win when the two conflict.\n\n- **Workflow:** \\`resolve_library\\` once per library, then \\`library_docs\\` with the\n returned \\`targetId\\` and a focused query (good: \"zod refine custom error\n message\"; bad: \"zod\"). Never guess a targetId.\n- **Budget:** at most **3 docs calls per task**. If 2 \\`library_docs\\` calls have\n not surfaced the section you need, read the package source under\n \\`node_modules\\` instead of searching again.\n- **Skip the docs tools** for language built-ins, stable well-known syntax, or\n an API already shown in the current context — they add nothing there.\n\n## Keep it fresh\n\nThe map keeps itself fresh: \\`vg ask\\` and the MCP tools detect changed files\nand rebuild it incrementally before answering — you can edit code and query\nimmediately. Running \\`vg\\` after a large pull still warms everything in one go.\nThe map lives at \\`.vibgrate/graph.json\\` and is deterministic (byte-identical\nacross machines).\n`;\n}\n\nexport function nudgeMarkdown(smallRepo: boolean, client?: string): string {\n const cf = clientFlag(client);\n if (smallRepo) {\n return `${NUDGE_BEGIN}\n${versionMarker()}\n## Code navigation (vg)\n\nThis repo is small enough that searching files directly is fine. Still, before a\nchange, the \\`vg\\` graph shows what breaks: use the \\`vg\\` MCP tools when the server\nis registered (\\`impact_of\\`, \\`query_graph\\` — the warm server answers far faster\nthan spawning the CLI). Only without the server, fall back to the CLI and pass\n\\`${cf}\\` so the call is counted: \\`vg impact <name> ${cf}\\`,\n\\`vg \"<question>\" ${cf}\\`.\n${NUDGE_END}`;\n }\n return `${NUDGE_BEGIN}\n${versionMarker()}\n## Code navigation (vg) — use the MCP tools first\n\nA deterministic code graph is available. It is usually the faster, cheaper path\nthan reading or grepping many files. **When the \\`vg\\` MCP server is registered,\nalways use its tools** (\\`query_graph\\`, \\`get_node\\`, \\`impact_of\\`,\n\\`search_symbols\\`, …) — the map, indexes, and embedding model stay warm across\ncalls, so they answer in milliseconds, while every CLI invocation pays Node\nstartup plus a fresh map parse. Fall back to the CLI only when the server is\nunavailable, and then pass \\`${cf}\\` so the call is counted:\n\n- \\`vg \"<question>\" ${cf}\\` — a compact, fact-annotated context block for a question.\n- \\`vg show <name> ${cf}\\` — what a symbol is, its callers and callees.\n- \\`vg impact <name> ${cf}\\` — what breaks if you change it.\n\nThis is advisory, not mandatory — remove it with \\`vg uninstall\\` (or delete this\nblock).\n${NUDGE_END}`;\n}\n\n/** The MCP server entry registered for local stdio use. */\nexport function mcpServerEntry(launch: ServeLaunch = { command: 'vg', args: ['serve'] }): {\n command: string;\n args: string[];\n} {\n return { command: launch.command, args: launch.args };\n}\n\nexport interface ServeLaunch {\n command: string;\n args: string[];\n /** Human-readable explanation when the launch is not the plain `vg serve`. */\n note?: string;\n}\n","import * as fs from 'node:fs';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport {\n skillMarkdown,\n nudgeMarkdown,\n mcpServerEntry,\n installedContentVersion,\n INSTALL_CONTENT_VERSION,\n NUDGE_BEGIN,\n NUDGE_END,\n type ServeLaunch,\n} from './content.js';\nimport { CliError, ExitCode } from '../util/exit.js';\nimport { ensureVibgrateGitignore } from '../engine/artifacts.js';\nimport { whichOnPath, isInstalledOwnBinary } from '../util/cli-invocation.js';\nimport { navigationToolsetConfig, HOT_TOOLS, deferredToolNames } from '../mcp/tools.js';\n\n/**\n * Per-assistant install registry (a focused subset of VG-ASSISTANT-INSTALL §2;\n * the remaining 20+ assistants are added in Phase 3). All paths are repo-local\n * (the team-shareable, safe default); writes are idempotent.\n */\n\nexport interface McpTarget {\n file: string; // project-relative\n key: 'mcpServers' | 'servers' | 'mcp_servers';\n /** Config syntax. Defaults to JSON; Grok's project config is TOML. */\n format?: 'json' | 'toml';\n vscode?: boolean; // VS Code uses { servers: { vg: { type:'stdio', ... } } }\n}\nexport interface NudgeTarget {\n file: string;\n kind: 'block' | 'file';\n}\nexport interface Assistant {\n id: string;\n label: string;\n skill?: string; // project-relative SKILL.md path\n mcp?: McpTarget;\n nudge?: NudgeTarget;\n /**\n * Signs this assistant is in use, checked by `detectAssistants`:\n * `markers` are project-relative paths, `homeMarkers` are relative to the\n * user's home folder, `bin` are executables looked up on PATH. Detection is\n * best-effort presence-checking only — nothing is read or executed.\n */\n markers?: string[];\n homeMarkers?: string[];\n bin?: string[];\n}\n\nexport const ASSISTANTS: Assistant[] = [\n {\n id: 'claude',\n label: 'Claude Code',\n skill: '.claude/skills/vg/SKILL.md',\n mcp: { file: '.mcp.json', key: 'mcpServers' },\n nudge: { file: 'CLAUDE.md', kind: 'block' },\n markers: ['CLAUDE.md', '.claude'],\n homeMarkers: ['.claude', '.claude.json'],\n bin: ['claude'],\n },\n {\n id: 'cursor',\n label: 'Cursor',\n mcp: { file: '.cursor/mcp.json', key: 'mcpServers' },\n nudge: { file: '.cursor/rules/vg.mdc', kind: 'file' },\n markers: ['.cursor', '.cursorrules'],\n homeMarkers: ['.cursor'],\n bin: ['cursor-agent'],\n },\n {\n id: 'windsurf',\n label: 'Windsurf',\n mcp: { file: '.windsurf/mcp.json', key: 'mcpServers' },\n nudge: { file: '.windsurf/rules/vg.md', kind: 'file' },\n markers: ['.windsurf', '.windsurfrules'],\n homeMarkers: ['.codeium/windsurf'],\n },\n {\n id: 'vscode',\n label: 'VS Code (Copilot Chat)',\n mcp: { file: '.vscode/mcp.json', key: 'servers', vscode: true },\n nudge: { file: '.github/copilot-instructions.md', kind: 'block' },\n markers: ['.github/copilot-instructions.md'],\n },\n {\n id: 'codex',\n label: 'Codex',\n skill: '.codex/skills/vg/SKILL.md',\n nudge: { file: 'AGENTS.md', kind: 'block' },\n markers: ['.codex'],\n homeMarkers: ['.codex'],\n bin: ['codex'],\n },\n {\n id: 'gemini',\n label: 'Gemini CLI',\n skill: '.gemini/skills/vg/SKILL.md',\n nudge: { file: 'GEMINI.md', kind: 'block' },\n markers: ['GEMINI.md', '.gemini'],\n homeMarkers: ['.gemini'],\n bin: ['gemini'],\n },\n {\n // Grok reads project-scoped MCP servers from `.grok/config.toml` — a TOML\n // `[mcp_servers.<name>]` table, the same thing `grok mcp add --scope\n // project` writes. Without it Grok sees the skill but no `vg` server, says\n // it \"isn't listed among connected servers\", and falls back to shelling the\n // CLI (slow, and killed by its command timeout on a stale map).\n id: 'grok',\n label: 'Grok CLI',\n skill: '.grok/skills/vg/SKILL.md',\n mcp: { file: '.grok/config.toml', key: 'mcp_servers', format: 'toml' },\n nudge: { file: 'AGENTS.md', kind: 'block' },\n markers: ['.grok', 'GROK.md'],\n homeMarkers: ['.grok'],\n bin: ['grok'],\n },\n // Skill + advisory AGENTS.md nudge (the broad-reach common denominator). MCP\n // registration for these hosts is host-specific and added as their formats\n // stabilise; the skill + nudge work today.\n { id: 'opencode', label: 'OpenCode', skill: '.opencode/skills/vg/SKILL.md', nudge: { file: 'AGENTS.md', kind: 'block' }, markers: ['.opencode', 'opencode.json'], homeMarkers: ['.config/opencode'], bin: ['opencode'] },\n { id: 'kilo', label: 'Kilo Code', skill: '.kilo/skills/vg/SKILL.md', nudge: { file: 'AGENTS.md', kind: 'block' }, markers: ['.kilo', '.kilocode'], homeMarkers: ['.kilocode'] },\n { id: 'aider', label: 'Aider', skill: '.aider/vg/SKILL.md', nudge: { file: 'AGENTS.md', kind: 'block' }, markers: ['.aider', '.aider.conf.yml'], homeMarkers: ['.aider.conf.yml'], bin: ['aider'] },\n { id: 'factory', label: 'Factory Droid', skill: '.factory/skills/vg/SKILL.md', nudge: { file: 'AGENTS.md', kind: 'block' }, markers: ['.factory'], homeMarkers: ['.factory'], bin: ['droid'] },\n { id: 'trae', label: 'Trae', skill: '.trae/skills/vg/SKILL.md', nudge: { file: 'AGENTS.md', kind: 'block' }, markers: ['.trae'], homeMarkers: ['.trae'] },\n { id: 'kiro', label: 'Kiro', skill: '.kiro/skills/vg/SKILL.md', nudge: { file: '.kiro/steering/vg.md', kind: 'file' }, markers: ['.kiro'], homeMarkers: ['.kiro'] },\n { id: 'amp', label: 'Amp', skill: '.agents/skills/vg/SKILL.md', nudge: { file: 'AGENTS.md', kind: 'block' }, homeMarkers: ['.config/amp'], bin: ['amp'] },\n { id: 'kimi', label: 'Kimi Code', skill: '.kimi/skills/vg/SKILL.md', nudge: { file: 'AGENTS.md', kind: 'block' }, markers: ['.kimi'], homeMarkers: ['.kimi'] },\n { id: 'codebuddy', label: 'CodeBuddy', skill: '.codebuddy/skills/vg/SKILL.md', nudge: { file: 'CODEBUDDY.md', kind: 'block' }, markers: ['CODEBUDDY.md', '.codebuddy'], homeMarkers: ['.codebuddy'] },\n { id: 'copilot-cli', label: 'GitHub Copilot CLI', skill: '.copilot/skills/vg/SKILL.md', nudge: { file: 'AGENTS.md', kind: 'block' }, markers: ['.copilot'], homeMarkers: ['.copilot'], bin: ['copilot'] },\n { id: 'pi', label: 'Pi', skill: '.pi/agent/skills/vg/SKILL.md', nudge: { file: 'AGENTS.md', kind: 'block' }, markers: ['.pi'], homeMarkers: ['.pi'] },\n { id: 'devin', label: 'Devin CLI', skill: '.devin/skills/vg/SKILL.md', nudge: { file: 'AGENTS.md', kind: 'block' }, markers: ['.devin'], homeMarkers: ['.devin'] },\n { id: 'hermes', label: 'Hermes', skill: '.hermes/skills/vg/SKILL.md', nudge: { file: 'AGENTS.md', kind: 'block' }, markers: ['.hermes'], homeMarkers: ['.hermes'] },\n { id: 'openclaw', label: 'OpenClaw', skill: '.openclaw/skills/vg/SKILL.md', nudge: { file: 'AGENTS.md', kind: 'block' }, markers: ['.openclaw'], homeMarkers: ['.openclaw'], bin: ['openclaw'] },\n { id: 'agents', label: 'Agent-Skills (generic)', skill: '.agents/skills/vg/SKILL.md', nudge: { file: 'AGENTS.md', kind: 'block' }, markers: ['AGENTS.md', '.agents'] },\n];\n\nexport function assistantById(id: string): Assistant | undefined {\n return ASSISTANTS.find((a) => a.id === id);\n}\n\n// --- detection ---\n\nexport interface DetectedAssistant {\n assistant: Assistant;\n /** Where the sign was found — in the repo, in the user's home folder, or on PATH. */\n via: 'repo' | 'home' | 'path';\n /** The specific marker path or executable name that matched. */\n marker: string;\n}\n\nexport interface DetectOptions {\n /** Home folder override (tests). Defaults to `os.homedir()`. */\n home?: string;\n /** PATH lookup override (tests). Defaults to `whichOnPath`. */\n which?: (cmd: string) => string | null;\n}\n\n/**\n * Best-effort detection of which AI assistants are in use — by their footprint\n * in the repo (rules files, config dirs), their per-user config in the home\n * folder, or their CLI on PATH. Pure presence checks: nothing is read,\n * parsed, or executed, and a miss is always safe (it only means \"not\n * auto-selected\"). First match per assistant wins, repo before home before\n * PATH, so the reported marker is the most local evidence.\n */\nexport function detectAssistants(root: string, opts: DetectOptions = {}): DetectedAssistant[] {\n const home = opts.home ?? os.homedir();\n const which = opts.which ?? whichOnPath;\n const found: DetectedAssistant[] = [];\n for (const assistant of ASSISTANTS) {\n const repoHit = (assistant.markers ?? []).find((m) => fs.existsSync(path.join(root, m)));\n if (repoHit) {\n found.push({ assistant, via: 'repo', marker: repoHit });\n continue;\n }\n const homeHit = (assistant.homeMarkers ?? []).find((m) => fs.existsSync(path.join(home, m)));\n if (homeHit) {\n found.push({ assistant, via: 'home', marker: homeHit });\n continue;\n }\n const binHit = (assistant.bin ?? []).find((b) => which(b) !== null);\n if (binHit) found.push({ assistant, via: 'path', marker: binHit });\n }\n return found;\n}\n\nexport interface InstallOptions {\n root: string;\n hook?: boolean; // write the advisory nudge (default true)\n smallRepo: boolean;\n /** Resolved MCP launch command; defaults to detectServeLaunch(). */\n launch?: ServeLaunch;\n}\n\nexport interface InstallAction {\n wrote: string[];\n skipped: string[];\n /** Explanation when the MCP entry is not the plain `vg serve` (e.g. PATH fallback). */\n note?: string;\n}\n\n/**\n * Resolve how the assistant host should launch the MCP server. `command: \"vg\"`\n * only works when `vg` on PATH is a *persistent install* of this CLI — a user\n * who ran via npx (whose `vg` is a throwaway npx-cache binary that disappears\n * after the run), or whose `vg` belongs to another tool (see\n * scripts/postinstall.mjs), would get a server that silently fails to start or,\n * worse, launches the wrong binary. Detection is best-effort and never throws;\n * the fallbacks keep the entry working: installed `vg` → installed `vibgrate` →\n * `npx -y -p @vibgrate/cli vg`.\n */\nexport function detectServeLaunch(which: (cmd: string) => string | null = whichOnPath): ServeLaunch {\n const vg = which('vg');\n if (vg && isInstalledOwnBinary(vg)) return { command: 'vg', args: ['serve'] };\n const vibgrate = which('vibgrate');\n if (vibgrate && isInstalledOwnBinary(vibgrate)) {\n return {\n command: 'vibgrate',\n args: ['serve'],\n note: vg\n ? '`vg` on PATH belongs to another tool — registered the identical `vibgrate serve` instead'\n : '`vg` is not on PATH — registered the identical `vibgrate serve` instead',\n };\n }\n return {\n command: 'npx',\n args: ['-y', '-p', '@vibgrate/cli', 'vg', 'serve'],\n note: 'vg is not installed on PATH — registered an npx launcher. Install globally (`npm i -g @vibgrate/cli`) and rerun `vg install` for a faster startup.',\n };\n}\n\nexport function installAssistant(a: Assistant, opts: InstallOptions): InstallAction {\n const wrote: string[] = [];\n const skipped: string[] = [];\n let note: string | undefined;\n\n if (a.skill) {\n // Pass the assistant id as the --client value so the installed skill tells\n // this AI to identify itself on CLI calls (the MCP path detects it itself).\n writeFileEnsured(path.join(opts.root, a.skill), skillMarkdown(a.id));\n wrote.push(a.skill);\n }\n if (a.mcp) {\n const launch = opts.launch ?? detectServeLaunch();\n upsertMcp(path.join(opts.root, a.mcp.file), a.mcp, launch);\n wrote.push(a.mcp.file);\n note = launch.note;\n } else {\n skipped.push('mcp (host-specific setup)');\n }\n if (a.nudge && opts.hook !== false) {\n writeNudge(path.join(opts.root, a.nudge.file), a.nudge, opts.smallRepo, a.id);\n wrote.push(a.nudge.file);\n } else if (a.nudge) {\n skipped.push('nudge (--no-hook)');\n }\n\n return { wrote, skipped, note };\n}\n\nexport function uninstallAssistant(a: Assistant, root: string, purge: boolean): string[] {\n const removed: string[] = [];\n if (a.mcp) {\n const file = path.join(root, a.mcp.file);\n if (removeMcp(file, a.mcp)) removed.push(a.mcp.file);\n }\n if (a.nudge) {\n const file = path.join(root, a.nudge.file);\n if (a.nudge.kind === 'block') {\n if (removeBlock(file)) removed.push(a.nudge.file);\n } else if (fs.existsSync(file)) {\n fs.rmSync(file);\n removed.push(a.nudge.file);\n }\n }\n if (purge && a.skill) {\n const file = path.join(root, a.skill);\n if (fs.existsSync(file)) {\n fs.rmSync(file);\n removed.push(a.skill);\n }\n }\n return removed;\n}\n\n/**\n * True when this assistant already has Vibgrate Graph / AI Context wiring in\n * `root` (skill file, MCP `vg` entry, or our nudge block/file).\n */\nexport function isAssistantInstalled(a: Assistant, root: string): boolean {\n if (a.skill && fs.existsSync(path.join(root, a.skill))) return true;\n if (a.mcp) {\n const file = path.join(root, a.mcp.file);\n if (a.mcp.format === 'toml') {\n if (hasTomlMcp(file, a.mcp)) return true;\n } else if (fs.existsSync(file)) {\n try {\n const config = readJson(file);\n const bag = config[a.mcp.key];\n if (bag && typeof bag === 'object' && bag !== null && 'vg' in (bag as object)) return true;\n } catch {\n /* unreadable — treat as not installed */\n }\n }\n }\n if (a.nudge) {\n const file = path.join(root, a.nudge.file);\n if (!fs.existsSync(file)) return false;\n const text = readTextSafe(file);\n if (!text) return false;\n if (a.nudge.kind === 'block') return text.includes(NUDGE_BEGIN);\n // File-kind nudge: ours when version-marked or carrying generated headings.\n return installedContentVersion(text) !== null || text.includes('# vg') || text.includes('Vibgrate');\n }\n return false;\n}\n\n// --- writers ---\n\nfunction writeFileEnsured(file: string, content: string): void {\n fs.mkdirSync(path.dirname(file), { recursive: true });\n fs.writeFileSync(file, content);\n}\n\n/**\n * Write the deferred-loading navigation config once per project (plan P3,\n * VG-NAVIGATION-PROFILE.md). `vg serve` always exposes the one optimized tool\n * set; this file is the CLIENT loading configuration for agents built on the\n * Claude API that support `defer_loading` + tool-search — it keeps the hot\n * navigation core in context and defers the rest, cutting the per-step schema\n * bill to ~350–450 tokens (vs ~1,881 for the full set). Hosts that don't\n * support deferral ignore it and serve the whole optimized set. Returns the\n * repo-relative path written.\n */\nexport function writeNavigationConfig(root: string): string {\n // `vg install` may be the first thing to create `.vibgrate/` — make sure the\n // default ignore file lands with it so the install never dirties the branch.\n ensureVibgrateGitignore(root);\n const rel = path.join('.vibgrate', 'mcp-navigation.json');\n const doc = {\n _readme:\n 'Deferred-loading config for agents embedding `vg serve` via the Claude API ' +\n '(defer_loading + tool-search). The hot navigation core stays in context; the rest ' +\n 'load on demand — ~350-450 schema tokens/step vs ~1,881 for the full set. Hosts without ' +\n 'defer_loading ignore this and serve the whole (already optimized) tool set. See ' +\n 'docs/graph/VG-NAVIGATION-PROFILE.md.',\n hot_core: [...HOT_TOOLS],\n deferred: deferredToolNames(),\n toolset: navigationToolsetConfig(),\n };\n writeFileEnsured(path.join(root, rel), `${JSON.stringify(doc, null, 2)}\\n`);\n return rel;\n}\n\nfunction upsertMcp(file: string, target: McpTarget, launch: ServeLaunch): void {\n if (target.format === 'toml') {\n upsertTomlMcp(file, target, launch);\n return;\n }\n const config = readJson(file);\n const entry = mcpServerEntry(launch);\n const value = target.vscode ? { type: 'stdio', ...entry } : entry;\n const bag = (config[target.key] && typeof config[target.key] === 'object'\n ? config[target.key]\n : {}) as Record<string, unknown>;\n bag.vg = value;\n config[target.key] = bag;\n writeFileEnsured(file, `${JSON.stringify(config, null, 2)}\\n`);\n}\n\n/**\n * The `[<key>.vg]` table in a TOML config (Grok's `.grok/config.toml`), and\n * everything up to the next top-level table header. Anchored to a line start so\n * a key *value* that happens to contain the text can't match.\n */\nfunction tomlTableRe(key: string): RegExp {\n return new RegExp(`(^|\\\\n)[ \\\\t]*\\\\[${escapeRe(key)}\\\\.vg\\\\][^\\\\n]*\\\\n(?:(?![ \\\\t]*\\\\[)[^\\\\n]*\\\\n?)*`);\n}\n\nfunction tomlString(s: string): string {\n return JSON.stringify(s); // TOML basic strings share JSON's escaping\n}\n\n/**\n * Merge our `vg` server into a TOML config, rewriting only our own table.\n * Everything else in the file — the user's other servers, their comments and\n * formatting — is preserved verbatim, which a parse-and-reserialize round trip\n * could not promise.\n */\nfunction upsertTomlMcp(file: string, target: McpTarget, launch: ServeLaunch): void {\n const entry = mcpServerEntry(launch);\n const table =\n `[${target.key}.vg]\\n` +\n `command = ${tomlString(entry.command)}\\n` +\n `args = [${entry.args.map(tomlString).join(', ')}]\\n`;\n const existing = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';\n const re = tomlTableRe(target.key);\n const next = re.test(existing)\n ? existing.replace(re, (m) => (m.startsWith('\\n') ? `\\n${table}` : table))\n : existing.length\n ? `${existing.replace(/\\s*$/, '')}\\n\\n${table}`\n : table;\n writeFileEnsured(file, next);\n}\n\nfunction removeTomlMcp(file: string, target: McpTarget): boolean {\n if (!fs.existsSync(file)) return false;\n const existing = readTextSafe(file);\n if (existing === null) return false;\n const re = tomlTableRe(target.key);\n if (!re.test(existing)) return false;\n const next = existing.replace(re, (m) => (m.startsWith('\\n') ? '\\n' : '')).replace(/\\n{3,}/g, '\\n\\n');\n writeFileEnsured(file, next.trim().length ? next : '');\n return true;\n}\n\nfunction hasTomlMcp(file: string, target: McpTarget): boolean {\n if (!fs.existsSync(file)) return false;\n const text = readTextSafe(file);\n return text !== null && tomlTableRe(target.key).test(text);\n}\n\nfunction removeMcp(file: string, target: McpTarget): boolean {\n if (target.format === 'toml') return removeTomlMcp(file, target);\n if (!fs.existsSync(file)) return false;\n const config = readJson(file);\n const bag = config[target.key] as Record<string, unknown> | undefined;\n if (!bag || !(bag.vg !== undefined)) return false;\n delete bag.vg;\n writeFileEnsured(file, `${JSON.stringify(config, null, 2)}\\n`);\n return true;\n}\n\n/**\n * Below this many mapped files the nudge honestly says searching is fine.\n * Shared by `vg install` and the post-build instruction refresh so both write\n * the same variant.\n */\nexport const SMALL_REPO_FILES = 150;\n\n/** One instruction file brought up to the current content version. */\nexport interface RefreshedInstruction {\n /** Repo-relative path of the refreshed file. */\n file: string;\n /** The version it carried (0 = pre-versioning legacy content). */\n from: number;\n to: number;\n}\n\n/**\n * Bring previously-installed assistant instructions up to the current content\n * version (INSTALL_CONTENT_VERSION). Called after every successful `vg` build,\n * so evolved instructions reach existing repos the first time a new CLI\n * version builds there — no re-run of `vg install` needed.\n *\n * Ownership rules — this must never clobber user-authored content:\n * - a file with a `vg:v<N>` marker is ours; refreshed when N is older.\n * Removing the marker line opts the file out permanently.\n * - a marker-less file at a known install path is refreshed ONLY when it\n * still carries the generated headings (legacy pre-versioning copies),\n * and treated as version 0.\n * - nudge blocks refresh only the vg:begin…vg:end region; the rest of the\n * host file (CLAUDE.md, AGENTS.md, …) is untouched.\n */\nexport function refreshInstalledInstructions(root: string, smallRepo: boolean): RefreshedInstruction[] {\n const out: RefreshedInstruction[] = [];\n const staleVersion = (text: string, legacySignature: string): number | null => {\n const v = installedContentVersion(text);\n if (v !== null) return v < INSTALL_CONTENT_VERSION ? v : null;\n return text.includes(legacySignature) ? 0 : null; // marker-less: legacy ours, or not ours at all\n };\n\n for (const a of ASSISTANTS) {\n if (a.skill) {\n const file = path.join(root, a.skill);\n if (fs.existsSync(file)) {\n const text = readTextSafe(file);\n const from = text === null ? null : staleVersion(text, '# vg — the code map');\n if (from !== null) {\n writeFileEnsured(file, skillMarkdown(a.id));\n out.push({ file: a.skill, from, to: INSTALL_CONTENT_VERSION });\n }\n }\n }\n if (a.nudge) {\n const file = path.join(root, a.nudge.file);\n if (!fs.existsSync(file)) continue;\n const text = readTextSafe(file);\n if (text === null) continue;\n if (a.nudge.kind === 'block') {\n const block = new RegExp(`${escapeRe(NUDGE_BEGIN)}[\\\\s\\\\S]*?${escapeRe(NUDGE_END)}`).exec(text);\n if (!block) continue; // no vg block in this host file — nothing of ours to refresh\n const from = staleVersion(block[0], '## Code navigation (vg)');\n if (from !== null) {\n writeNudge(file, a.nudge, smallRepo, a.id);\n out.push({ file: a.nudge.file, from, to: INSTALL_CONTENT_VERSION });\n }\n } else {\n const from = staleVersion(text, '## Code navigation (vg)');\n if (from !== null) {\n writeNudge(file, a.nudge, smallRepo, a.id);\n out.push({ file: a.nudge.file, from, to: INSTALL_CONTENT_VERSION });\n }\n }\n }\n }\n return out;\n}\n\nfunction readTextSafe(file: string): string | null {\n try {\n return fs.readFileSync(file, 'utf8');\n } catch {\n return null; // unreadable — leave it alone\n }\n}\n\nfunction writeNudge(file: string, target: NudgeTarget, smallRepo: boolean, client?: string): void {\n if (target.kind === 'file') {\n // Dedicated rule file owned by vg (Cursor .mdc needs frontmatter).\n const body = file.endsWith('.mdc')\n ? `---\\ndescription: vg code graph\\nalwaysApply: true\\n---\\n${stripMarkers(nudgeMarkdown(smallRepo, client))}`\n : stripMarkers(nudgeMarkdown(smallRepo, client));\n writeFileEnsured(file, `${body}\\n`);\n return;\n }\n upsertBlock(file, nudgeMarkdown(smallRepo, client));\n}\n\nfunction upsertBlock(file: string, block: string): void {\n fs.mkdirSync(path.dirname(file), { recursive: true });\n let existing = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';\n const re = new RegExp(`${escapeRe(NUDGE_BEGIN)}[\\\\s\\\\S]*?${escapeRe(NUDGE_END)}`);\n if (re.test(existing)) existing = existing.replace(re, block);\n else existing = existing.length ? `${existing.replace(/\\s*$/, '')}\\n\\n${block}\\n` : `${block}\\n`;\n fs.writeFileSync(file, existing);\n}\n\nfunction removeBlock(file: string): boolean {\n if (!fs.existsSync(file)) return false;\n const existing = fs.readFileSync(file, 'utf8');\n const re = new RegExp(`\\\\n*${escapeRe(NUDGE_BEGIN)}[\\\\s\\\\S]*?${escapeRe(NUDGE_END)}\\\\n*`);\n if (!re.test(existing)) return false;\n fs.writeFileSync(file, existing.replace(re, '\\n'));\n return true;\n}\n\n/**\n * Read a JSON config we are about to merge into. A *missing* file is an empty\n * config; a *malformed* file must abort — silently treating it as empty would\n * rewrite the file and destroy the user's other MCP server entries.\n */\nfunction readJson(file: string): Record<string, unknown> {\n if (!fs.existsSync(file)) return {};\n try {\n const parsed = JSON.parse(fs.readFileSync(file, 'utf8')) as unknown;\n if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {\n return parsed as Record<string, unknown>;\n }\n throw new Error('not a JSON object');\n } catch {\n throw new CliError(\n `${file} exists but is not valid JSON — fix or remove it, then rerun. Refusing to overwrite it (that would lose your existing entries).`,\n ExitCode.ERROR,\n );\n }\n}\n\nfunction stripMarkers(s: string): string {\n return s.replace(NUDGE_BEGIN, '').replace(NUDGE_END, '').trim();\n}\n\nfunction escapeRe(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/engine/limits.ts","../src/engine/scip.ts","../src/engine/rng.ts","../src/engine/analyze.ts","../src/engine/coverage.ts","../src/engine/facts.ts","../src/engine/grounding.ts","../src/engine/pool.ts","../src/engine/ts-resolver.ts","../src/engine/tsc-cache.ts","../src/engine/epistemic.ts","../src/engine/docs-ingest.ts","../src/engine/toolchain/util.ts","../src/engine/toolchain/yaml.ts","../src/engine/toolchain/compose.ts","../src/engine/toolchain/dockerfile.ts","../src/engine/toolchain/helm.ts","../src/engine/toolchain/kubernetes.ts","../src/engine/toolchain/terraform.ts","../src/engine/toolchain/workflows.ts","../src/engine/toolchain/link.ts","../src/engine/toolchain/index.ts","../src/engine/ts-projects.ts","../src/engine/timing.ts","../src/engine/summaries.ts","../src/engine/manifests.ts","../src/engine/hash-files.ts","../src/engine/build.ts","../src/engine/verify.ts","../src/engine/freshness.ts","../src/install/content.ts","../src/install/registry.ts"],"names":["path","fs","enclosing","nodeId","fs2","path2","normalize","add","rel","path3","path4","ts","fs3","path5","fs4","toPosix","source","push","join","fs5","path6","fs6","path7","buildRootIgnore","fs7","ignore","os2","path8","fs9","path9","fs10","os3"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,IAAM,MAAM,IAAA,GAAO,IAAA;AAEZ,IAAM,yBAAyB,CAAA,GAAI,GAAA;AACnC,IAAM,iBAAA,GAAoB,GAA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AA;AAAA,EACrC,CAAA,CAAA,MAAQ;AACN,IAAA,MAAM,IAAI,QAAA;AAAA,MACR,GAAG,IAAI,CAAA,oIAAA,CAAA;AAAA,MACP,QAAA,CAAS;AAAA,KACX;AAAA,EACF;AACF;AAEA,SAAS,aAAa,CAAA,EAAmB;AACvC,EAAA,OAAO,CAAA,CAAE,QAAQ,WAAA,EAAa,EAAE,EAAE,OAAA,CAAQ,SAAA,EAAW,EAAE,CAAA,CAAE,IAAA,EAAK;AAChE;AAEA,SAAS,SAAS,CAAA,EAAmB;AACnC,EAAA,OAAO,CAAA,CAAE,OAAA,CAAQ,qBAAA,EAAuB,MAAM,CAAA;AAChD","file":"chunk-NS4DL3QR.js","sourcesContent":["import * as v8 from 'node:v8';\n\n/**\n * Resource safeguards for the graph build.\n *\n * Building the map holds every parse table, node, and edge in memory at once,\n * so a pathological corpus (a vendored 200 MB bundle, a million-file tree, a\n * giant TS program) can OOM-kill the process — an uncatchable crash that takes\n * the caller (e.g. a `scan --push`) down with it. These limits convert that\n * crash into either a deterministic skip (per-file size cap, tsc rung cap) or\n * a catchable, actionable error (corpus cap, heap budget).\n *\n * Every limit is overridable via environment variable, and `0` always means\n * \"disabled\". Skips are pure functions of the input (file size, file count) —\n * never of observed memory — so identical input still yields identical output.\n */\n\nexport interface ResourceLimits {\n /** Per-file source cap in bytes. Larger files stay stat-tracked for\n * freshness but are not parsed into the graph. 0 disables. */\n maxFileBytes: number;\n /** Ceiling on discovered corpus files; exceeding aborts with guidance\n * instead of grinding toward an OOM. 0 disables. */\n maxFiles: number;\n /** Ceiling on TS/JS files handed to the in-process TypeScript Compiler API\n * rung (a ts.Program over the whole corpus is the largest single memory\n * consumer). Above it the rung is skipped; the heuristic floor remains.\n * 0 disables. */\n tscMaxFiles: number;\n /** Heap budget in MiB checked at phase boundaries; exceeding aborts with a\n * clear error before V8 hard-crashes. 0 disables. */\n memoryBudgetMb: number;\n}\n\nconst MIB = 1024 * 1024;\n\nexport const DEFAULT_MAX_FILE_BYTES = 2 * MIB;\nexport const DEFAULT_MAX_FILES = 100_000;\nexport const DEFAULT_TSC_MAX_FILES = 10_000;\n\n/** Fraction of V8's heap ceiling we allow the build to consume before\n * aborting — past this an OOM crash is imminent anyway. */\nconst HEAP_GUARD_FRACTION = 0.9;\n\n/** A build stopped by a resource safeguard — catchable, unlike an OOM. The\n * message is user-facing and must carry its own remedy. */\nexport class ResourceLimitError extends Error {\n readonly isResourceLimitError = true;\n constructor(message: string) {\n super(message);\n this.name = 'ResourceLimitError';\n }\n}\n\n/** Non-negative integer from an env var; unset/invalid → fallback. */\nfunction envInt(name: string, fallback: number): number {\n const raw = process.env[name];\n if (raw === undefined || raw.trim() === '') return fallback;\n const n = Number(raw);\n return Number.isInteger(n) && n >= 0 ? n : fallback;\n}\n\n/** Like envInt but with no default — undefined when unset/invalid/0. */\nfunction envIntOptional(name: string): number | undefined {\n const n = envInt(name, 0);\n return n > 0 ? n : undefined;\n}\n\n/** Default heap budget: 90% of V8's configured heap ceiling (respects\n * NODE_OPTIONS=--max-old-space-size), in MiB. */\nexport function defaultMemoryBudgetMb(): number {\n return Math.floor((v8.getHeapStatistics().heap_size_limit / MIB) * HEAP_GUARD_FRACTION);\n}\n\n/**\n * Resolve effective limits: explicit overrides (tests, programmatic callers)\n * win over environment variables, which win over defaults.\n */\nexport function resolveLimits(overrides: Partial<ResourceLimits> = {}): ResourceLimits {\n return {\n maxFileBytes: overrides.maxFileBytes ?? envInt('VG_MAX_FILE_BYTES', DEFAULT_MAX_FILE_BYTES),\n maxFiles: overrides.maxFiles ?? envInt('VG_MAX_FILES', DEFAULT_MAX_FILES),\n tscMaxFiles: overrides.tscMaxFiles ?? envInt('VG_TSC_MAX_FILES', DEFAULT_TSC_MAX_FILES),\n memoryBudgetMb: overrides.memoryBudgetMb ?? envInt('VG_MEMORY_BUDGET_MB', defaultMemoryBudgetMb()),\n };\n}\n\n/** Default parse worker count override (`VG_JOBS`); undefined when unset. */\nexport function envJobs(): number | undefined {\n return envIntOptional('VG_JOBS');\n}\n\n/** Per-worker old-generation heap cap in MiB (`VG_WORKER_HEAP_MB`);\n * undefined when unset (workers inherit the platform default). */\nexport function envWorkerHeapMb(): number | undefined {\n return envIntOptional('VG_WORKER_HEAP_MB');\n}\n\n/**\n * Abort (catchably) when heap use crosses the budget. Called at phase\n * boundaries — cheap enough to call freely, and an abort here beats a V8\n * hard-crash a few allocations later. Only ever *throws*; it never alters\n * build output, so determinism is unaffected.\n */\nexport function checkMemoryBudget(phase: string, budgetMb: number): void {\n if (budgetMb <= 0) return;\n const usedMb = process.memoryUsage().heapUsed / MIB;\n if (usedMb <= budgetMb) return;\n throw new ResourceLimitError(\n `graph build stopped during ${phase}: heap use ${Math.round(usedMb)} MiB exceeds the ` +\n `${budgetMb} MiB budget. Narrow the build (scope to sub-paths, add --exclude globs, or ` +\n `--only <langs>), raise the Node heap (NODE_OPTIONS=--max-old-space-size=8192), or set ` +\n `VG_MEMORY_BUDGET_MB (0 disables this safeguard).`,\n );\n}\n\n/** Human-readable byte count for warnings (\"3.2 MiB\"). */\nexport function formatBytes(n: number): string {\n if (n >= MIB) return `${(n / MIB).toFixed(1)} MiB`;\n if (n >= 1024) return `${(n / 1024).toFixed(1)} KiB`;\n return `${n} B`;\n}\n","/**\n * SCIP ingestion — the precise resolution rung (VG-ENGINE-TEARDOWN §3.2).\n *\n * Reads a real SCIP index (`index.scip`) produced by a language indexer\n * (scip-typescript, scip-python, scip-java, rust-analyzer→SCIP, …) and turns its\n * precise occurrences into call/reference edges at `resolution: \"scip\"`,\n * confidence 1.0 — a real SCIP indexer win. vg does\n * NOT bundle indexers; it consumes an index the user/CI generates (deterministic,\n * offline). The heuristic resolver remains the floor for files SCIP didn't cover.\n *\n * A small, dependency-free protobuf reader decodes only the fields we need, so\n * the core stays lean.\n */\n\nimport type { EdgeKind, GraphEdge, GraphNode, ResolverKind } from '../schema.js';\nimport { edgeId } from './ids.js';\n\n// SCIP SymbolRole bitmask (scip.proto).\nconst ROLE_DEFINITION = 0x1;\n\nexport interface ScipOccurrence {\n /** [startLine, startChar, endLine, endChar] or [startLine, startChar, endChar], 0-based. */\n range: number[];\n symbol: string;\n roles: number;\n}\nexport interface ScipDocument {\n relativePath: string;\n occurrences: ScipOccurrence[];\n}\nexport interface ScipIndex {\n documents: ScipDocument[];\n toolName?: string;\n toolVersion?: string;\n}\n\n// --- minimal protobuf wire reader ---\n\nclass Reader {\n pos = 0;\n constructor(private buf: Uint8Array) {}\n get done(): boolean {\n return this.pos >= this.buf.length;\n }\n varint(): number {\n let result = 0;\n let shift = 0;\n for (;;) {\n const b = this.buf[this.pos++];\n result += (b & 0x7f) * 2 ** shift; // avoid <<shift overflow past 31 bits\n if ((b & 0x80) === 0) break;\n shift += 7;\n }\n return result;\n }\n tag(): { field: number; wire: number } {\n const t = this.varint();\n return { field: t >>> 3, wire: t & 0x7 };\n }\n bytes(): Uint8Array {\n const len = this.varint();\n const out = this.buf.subarray(this.pos, this.pos + len);\n this.pos += len;\n return out;\n }\n skip(wire: number): void {\n if (wire === 0) this.varint();\n else if (wire === 2) this.bytes();\n else if (wire === 5) this.pos += 4;\n else if (wire === 1) this.pos += 8;\n }\n}\n\nconst td = new TextDecoder();\n\nexport function decodeScipIndex(buf: Uint8Array): ScipIndex {\n const index: ScipIndex = { documents: [] };\n const r = new Reader(buf);\n while (!r.done) {\n const { field, wire } = r.tag();\n if (field === 1 && wire === 2) decodeMetadata(r.bytes(), index); // Index.metadata\n else if (field === 2 && wire === 2) index.documents.push(decodeDocument(r.bytes()));\n else r.skip(wire);\n }\n return index;\n}\n\nfunction decodeMetadata(buf: Uint8Array, index: ScipIndex): void {\n const r = new Reader(buf);\n while (!r.done) {\n const { field, wire } = r.tag();\n if (field === 2 && wire === 2) decodeToolInfo(r.bytes(), index); // Metadata.tool_info\n else r.skip(wire);\n }\n}\n\nfunction decodeToolInfo(buf: Uint8Array, index: ScipIndex): void {\n const r = new Reader(buf);\n while (!r.done) {\n const { field, wire } = r.tag();\n if (field === 1 && wire === 2) index.toolName = td.decode(r.bytes());\n else if (field === 2 && wire === 2) index.toolVersion = td.decode(r.bytes());\n else r.skip(wire);\n }\n}\n\nfunction decodeDocument(buf: Uint8Array): ScipDocument {\n const doc: ScipDocument = { relativePath: '', occurrences: [] };\n const r = new Reader(buf);\n while (!r.done) {\n const { field, wire } = r.tag();\n if (field === 1 && wire === 2) doc.relativePath = td.decode(r.bytes()); // relative_path\n else if (field === 2 && wire === 2) doc.occurrences.push(decodeOccurrence(r.bytes()));\n else r.skip(wire);\n }\n return doc;\n}\n\nfunction decodeOccurrence(buf: Uint8Array): ScipOccurrence {\n const occ: ScipOccurrence = { range: [], symbol: '', roles: 0 };\n const r = new Reader(buf);\n while (!r.done) {\n const { field, wire } = r.tag();\n if (field === 1) {\n if (wire === 2) {\n // packed repeated int32\n const sub = new Reader(r.bytes());\n while (!sub.done) occ.range.push(sub.varint());\n } else if (wire === 0) {\n occ.range.push(r.varint());\n } else r.skip(wire);\n } else if (field === 2 && wire === 2) occ.symbol = td.decode(r.bytes());\n else if (field === 3 && wire === 0) occ.roles = r.varint();\n else r.skip(wire);\n }\n return occ;\n}\n\n// --- mapping occurrences → edges ---\n\nexport interface ScipResult {\n edges: GraphEdge[];\n /** Repo-relative files SCIP covered (it is authoritative for these). */\n coveredFiles: Set<string>;\n /** counts for status/provenance. */\n stats: { documents: number; references: number; resolved: number };\n}\n\n/**\n * Build precise edges from a SCIP index, mapped onto our nodes by (file, line).\n * A reference occurrence's enclosing node → the node where its symbol is defined.\n */\nexport function scipEdges(index: ScipIndex, nodes: GraphNode[], relForScip: (p: string) => string): ScipResult {\n // nodes per repo-relative file, with quick line lookup.\n const nodesByFile = new Map<string, GraphNode[]>();\n for (const n of nodes) {\n if (n.kind === 'file' || n.kind === 'external') continue;\n const list = nodesByFile.get(n.file);\n if (list) list.push(n);\n else nodesByFile.set(n.file, [n]);\n }\n\n // First pass: symbol → defining node (from Definition occurrences).\n const symbolToNode = new Map<string, GraphNode>();\n const coveredFiles = new Set<string>();\n for (const doc of index.documents) {\n const file = relForScip(doc.relativePath);\n const fileNodes = nodesByFile.get(file);\n if (!fileNodes) continue;\n coveredFiles.add(file);\n for (const occ of doc.occurrences) {\n if ((occ.roles & ROLE_DEFINITION) === 0 || !occ.symbol || occ.symbol.startsWith('local ')) continue;\n const line = (occ.range[0] ?? 0) + 1; // SCIP is 0-based; our spans 1-based\n const node = nodeStartingAt(fileNodes, line) ?? enclosing(fileNodes, line);\n if (node) symbolToNode.set(occ.symbol, node);\n }\n }\n\n // Second pass: reference occurrences → edges.\n const edgeMap = new Map<string, GraphEdge>();\n let references = 0;\n let resolved = 0;\n for (const doc of index.documents) {\n const file = relForScip(doc.relativePath);\n const fileNodes = nodesByFile.get(file);\n if (!fileNodes) continue;\n for (const occ of doc.occurrences) {\n if ((occ.roles & ROLE_DEFINITION) !== 0 || !occ.symbol || occ.symbol.startsWith('local ')) continue;\n references++;\n const target = symbolToNode.get(occ.symbol);\n if (!target) continue; // symbol defined outside the repo (external) — skip\n const line = (occ.range[0] ?? 0) + 1;\n const src = enclosing(fileNodes, line);\n if (!src || src.id === target.id) continue;\n const kind: EdgeKind = target.kind === 'function' || target.kind === 'method' ? 'call' : 'references';\n add(edgeMap, kind, src.id, target.id);\n resolved++;\n }\n }\n\n return {\n edges: [...edgeMap.values()],\n coveredFiles,\n stats: { documents: index.documents.length, references, resolved },\n };\n}\n\nfunction add(map: Map<string, GraphEdge>, kind: EdgeKind, src: string, dst: string): void {\n const id = edgeId(kind, src, dst);\n const existing = map.get(id);\n if (existing) {\n existing.count = (existing.count ?? 1) + 1;\n return;\n }\n const resolution: ResolverKind = 'scip';\n map.set(id, { id, kind, src, dst, resolution, confidence: 1.0, count: 1 });\n}\n\n/** Smallest node whose span contains `line`. */\nfunction enclosing(nodes: GraphNode[], line: number): GraphNode | undefined {\n let best: GraphNode | undefined;\n for (const n of nodes) {\n if (n.span.start <= line && n.span.end >= line) {\n if (!best || n.span.end - n.span.start < best.span.end - best.span.start) best = n;\n }\n }\n return best;\n}\n\n/** A node whose span starts exactly at `line` (the defined symbol). */\nfunction nodeStartingAt(nodes: GraphNode[], line: number): GraphNode | undefined {\n let best: GraphNode | undefined;\n for (const n of nodes) {\n if (n.span.start === line) {\n if (!best || n.span.end - n.span.start < best.span.end - best.span.start) best = n;\n }\n }\n return best;\n}\n","/**\n * A tiny seeded PRNG (mulberry32). Used to make Louvain clustering deterministic\n * — same graph + same seed → same communities, every run, every machine. Never\n * use `Math.random()` anywhere in the engine; that would break the determinism\n * contract (VG-ENGINE-TEARDOWN §5).\n */\nexport function mulberry32(seed: number): () => number {\n let a = seed >>> 0;\n return function () {\n a = (a + 0x6d2b79f5) | 0;\n let t = Math.imul(a ^ (a >>> 15), 1 | a);\n t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;\n return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n };\n}\n\n/** The fixed clustering seed (matches the documented determinism inputs). */\nexport const CLUSTER_SEED = 42;\n","import Graph from 'graphology';\nimport pagerank from 'graphology-metrics/centrality/pagerank.js';\nimport betweenness from 'graphology-metrics/centrality/betweenness.js';\nimport eigenvector from 'graphology-metrics/centrality/eigenvector.js';\nimport louvain from 'graphology-communities-louvain';\nimport { mulberry32, CLUSTER_SEED } from './rng.js';\nimport type { Area, EdgeKind, GraphEdge, GraphNode } from '../schema.js';\n\n/**\n * Analysis stage: importance, centrality, hubs, communities, and surprise.\n *\n * - **Centrality** blends PageRank + betweenness + eigenvector + degree over the\n * dependency graph (call/import/extends/implements/references), catching\n * high-fan-in critical nodes that degree-only ranking misses.\n * - **Communities** via Louvain (`graphology-communities-louvain`, MIT), seeded\n * and single-pass for determinism. Leiden (via a permissive WASM impl) is a\n * later enhancement; the cluster mode is reported honestly, never silent.\n * - **Hubs** are centrality outliers (importance ≥ mean + 2σ).\n * - **Surprise** flags improbable cross-area edges (architectural smells),\n * surfaced by `vg oddities`.\n *\n * Pure and deterministic: identical (nodes, edges) → identical result.\n */\n\nexport type ClusterMode = 'leiden' | 'louvain' | 'none';\nexport type AnalysisTier = 'full' | 'large' | 'xl';\n\nexport interface AnalyzeOptions {\n cluster?: ClusterMode; // default 'louvain'\n /** Skip betweenness above this node count (O(V·E) — too slow for huge graphs). */\n betweennessLimit?: number;\n /**\n * Analysis cost tier. When omitted, auto-selected from node count:\n * full ≤5k nodes — PR + betweenness + eigenvector + Louvain\n * large ≤50k — PR + eigenvector + Louvain (no betweenness)\n * xl >50k — PR + degree; Louvain only on file-level contraction\n */\n tier?: AnalysisTier;\n}\n\nexport interface AnalyzeResult {\n nodes: GraphNode[];\n edges: GraphEdge[]; // surprise scores attached\n areas: Area[];\n cluster: ClusterMode;\n tier: AnalysisTier;\n}\n\n/** Node-count thresholds for auto tier selection. */\nexport const TIER_LARGE_NODES = 5_000;\nexport const TIER_XL_NODES = 50_000;\n\nexport function pickAnalysisTier(nodeCount: number, forced?: AnalysisTier): AnalysisTier {\n if (forced) return forced;\n if (nodeCount > TIER_XL_NODES) return 'xl';\n if (nodeCount > TIER_LARGE_NODES) return 'large';\n return 'full';\n}\n\n// Edges that express dependency/importance (excludes contains/test/coverage).\nconst DEP_EDGES = new Set<EdgeKind>(['call', 'import', 'extends', 'implements', 'references']);\n// Edges that express cohesion for community detection (adds containment).\nconst CLUSTER_EDGE_KINDS = new Set<EdgeKind>([...DEP_EDGES, 'contains']);\n\nconst IMPORTANCE_WEIGHTS = { pagerank: 0.4, betweenness: 0.25, eigenvector: 0.2, degree: 0.15 };\nconst DEFAULT_BETWEENNESS_LIMIT = 5000;\n\nexport function analyze(\n nodes: GraphNode[],\n edges: GraphEdge[],\n options: AnalyzeOptions = {},\n): AnalyzeResult {\n const tier = pickAnalysisTier(nodes.length, options.tier);\n const mode = options.cluster ?? (tier === 'xl' ? 'louvain' : 'louvain');\n // Sorted for deterministic graph construction (Louvain RNG consumption order).\n const ids = [...nodes.map((n) => n.id)].sort((a, b) => a.localeCompare(b));\n\n // --- centrality (directed dependency graph) ---\n // Tier policy (honest, never silent):\n // full — PR + betweenness (≤limit) + eigenvector + degree\n // large — PR + eigenvector + degree (betweenness off)\n // xl — PR + degree (eigenvector off; betweenness off)\n const dg = simpleGraph(ids, edges, DEP_EDGES, 'directed');\n const pr = safeMetric(() => pagerank(dg), ids);\n const bwLimit = options.betweennessLimit ?? DEFAULT_BETWEENNESS_LIMIT;\n const bw =\n tier === 'full' && dg.order <= bwLimit\n ? safeMetric(() => betweenness(dg), ids)\n : zeros(ids);\n const ev =\n tier === 'full' || tier === 'large'\n ? safeMetric(() => eigenvector(dg), ids)\n : zeros(ids);\n const deg = degreeMap(dg, ids);\n\n const prN = normalize(pr);\n const bwN = normalize(bw);\n const evN = normalize(ev);\n const degN = normalize(deg);\n\n // Re-weight when expensive metrics are zeroed so scores stay informative.\n const weights =\n tier === 'xl'\n ? { pagerank: 0.7, betweenness: 0, eigenvector: 0, degree: 0.3 }\n : tier === 'large'\n ? { pagerank: 0.5, betweenness: 0, eigenvector: 0.25, degree: 0.25 }\n : IMPORTANCE_WEIGHTS;\n\n const importance = new Map<string, number>();\n for (const id of ids) {\n const score =\n weights.pagerank * (prN.get(id) ?? 0) +\n weights.betweenness * (bwN.get(id) ?? 0) +\n weights.eigenvector * (evN.get(id) ?? 0) +\n weights.degree * (degN.get(id) ?? 0);\n importance.set(id, score);\n }\n const importanceN = normalize(importance);\n\n // --- hubs (importance outliers) ---\n const vals = [...importanceN.values()];\n const mean = vals.reduce((a, b) => a + b, 0) / (vals.length || 1);\n const variance = vals.reduce((a, b) => a + (b - mean) ** 2, 0) / (vals.length || 1);\n const std = Math.sqrt(variance);\n const hubThreshold = mean + 2 * std;\n\n // --- communities ---\n // xl: cluster on file-level contraction (far fewer nodes) then map members back.\n const { areaByNode, mode: actualMode } =\n tier === 'xl'\n ? clusterFileLevel(nodes, edges, mode)\n : cluster(ids, edges, mode);\n\n const outNodes: GraphNode[] = nodes\n .map((n) => ({\n ...n,\n centrality: {\n degree: round(degN.get(n.id) ?? 0),\n pagerank: round(prN.get(n.id) ?? 0),\n betweenness: round(bwN.get(n.id) ?? 0),\n eigenvector: round(evN.get(n.id) ?? 0),\n },\n importance: round(importanceN.get(n.id) ?? 0),\n area: areaByNode.get(n.id) ?? -1,\n isHub: (importanceN.get(n.id) ?? 0) >= hubThreshold && (importanceN.get(n.id) ?? 0) > 0,\n }))\n .sort((a, b) => a.id.localeCompare(b.id));\n\n // --- areas (with labels, cohesion, external-edge counts) ---\n const areas = buildAreas(outNodes, edges, areaByNode);\n\n // --- surprise on cross-area dependency edges ---\n const outEdges = scoreSurprise(edges, areaByNode);\n\n return { nodes: outNodes, edges: outEdges, areas, cluster: actualMode, tier };\n}\n\n/**\n * XL clustering: run Louvain only over file nodes + file↔file dependency edges\n * (contracts the method-level graph), then assign every symbol the area of its file.\n */\nfunction clusterFileLevel(\n nodes: GraphNode[],\n edges: GraphEdge[],\n mode: ClusterMode,\n): { areaByNode: Map<string, number>; mode: ClusterMode } {\n const fileNodes = nodes.filter((n) => n.kind === 'file');\n const fileIds = fileNodes.map((n) => n.id).sort((a, b) => a.localeCompare(b));\n if (fileIds.length === 0) {\n return { areaByNode: new Map(nodes.map((n) => [n.id, -1])), mode: 'none' };\n }\n\n // Map symbol id → file node id.\n const fileIdByPath = new Map(fileNodes.map((n) => [n.file, n.id]));\n const fileOf = new Map<string, string>();\n for (const n of nodes) {\n if (n.kind === 'file') fileOf.set(n.id, n.id);\n else if (n.file) {\n const fid = fileIdByPath.get(n.file);\n if (fid) fileOf.set(n.id, fid);\n }\n }\n\n // Project dependency edges onto file↔file.\n const fileEdges: GraphEdge[] = [];\n const seen = new Set<string>();\n for (const e of edges) {\n if (!DEP_EDGES.has(e.kind)) continue;\n const sf = fileOf.get(e.src);\n const df = fileOf.get(e.dst);\n if (!sf || !df || sf === df) continue;\n const key = `${e.kind}|${sf}|${df}`;\n if (seen.has(key)) continue;\n seen.add(key);\n fileEdges.push({ ...e, src: sf, dst: df, id: key });\n }\n\n const { areaByNode: fileAreas, mode: used } = cluster(fileIds, fileEdges, mode);\n const areaByNode = new Map<string, number>();\n for (const n of nodes) {\n const fid = fileOf.get(n.id);\n areaByNode.set(n.id, fid ? (fileAreas.get(fid) ?? -1) : -1);\n }\n return { areaByNode, mode: used };\n}\n\n// --- graph construction ---\n\nfunction simpleGraph(\n ids: string[],\n edges: GraphEdge[],\n kinds: Set<EdgeKind>,\n type: 'directed' | 'undirected',\n): Graph {\n const g = new Graph({ type, multi: false, allowSelfLoops: false });\n for (const id of ids) g.addNode(id);\n for (const e of edges) {\n if (!kinds.has(e.kind)) continue;\n if (e.src === e.dst) continue;\n if (!g.hasNode(e.src) || !g.hasNode(e.dst)) continue;\n const w = (e.confidence || 0.5) * (e.count ?? 1);\n if (type === 'directed') {\n g.updateDirectedEdge(e.src, e.dst, (attr) => ({ weight: (attr?.weight ?? 0) + w }));\n } else {\n g.updateUndirectedEdge(e.src, e.dst, (attr) => ({ weight: (attr?.weight ?? 0) + w }));\n }\n }\n return g;\n}\n\nfunction cluster(\n ids: string[],\n edges: GraphEdge[],\n mode: ClusterMode,\n): { areaByNode: Map<string, number>; mode: ClusterMode } {\n if (mode === 'none' || ids.length === 0) {\n return { areaByNode: new Map(ids.map((id) => [id, -1])), mode: 'none' };\n }\n // Leiden is not yet bundled; fall back to Louvain and report it honestly.\n const used: ClusterMode = 'louvain';\n const ug = simpleGraph(ids, edges, CLUSTER_EDGE_KINDS, 'undirected');\n let communities: Record<string, number>;\n try {\n communities = louvain(ug, { rng: mulberry32(CLUSTER_SEED), resolution: 1 });\n } catch {\n return { areaByNode: new Map(ids.map((id) => [id, -1])), mode: 'none' };\n }\n\n // Remap arbitrary Louvain indices → stable area ids ordered by the lowest\n // member node id, so ids are deterministic and diff-stable across runs.\n const byCommunity = new Map<number, string[]>();\n for (const id of ids) {\n const ci = communities[id] ?? -1;\n const list = byCommunity.get(ci);\n if (list) list.push(id);\n else byCommunity.set(ci, [id]);\n }\n const ordered = [...byCommunity.entries()]\n .map(([, members]) => members.sort((a, b) => a.localeCompare(b)))\n .sort((a, b) => a[0].localeCompare(b[0]));\n\n const areaByNode = new Map<string, number>();\n ordered.forEach((members, areaId) => {\n for (const id of members) areaByNode.set(id, areaId);\n });\n return { areaByNode, mode: used };\n}\n\nfunction buildAreas(\n nodes: GraphNode[],\n edges: GraphEdge[],\n areaByNode: Map<string, number>,\n): Area[] {\n const byArea = new Map<number, GraphNode[]>();\n for (const n of nodes) {\n const a = areaByNode.get(n.id) ?? -1;\n if (a < 0) continue;\n const list = byArea.get(a);\n if (list) list.push(n);\n else byArea.set(a, [n]);\n }\n\n // External-edge counts per area (dependency edges crossing area boundaries).\n const externalByArea = new Map<number, number>();\n const internalByArea = new Map<number, number>();\n for (const e of edges) {\n if (!DEP_EDGES.has(e.kind)) continue;\n const sa = areaByNode.get(e.src);\n const da = areaByNode.get(e.dst);\n if (sa === undefined || da === undefined || sa < 0 || da < 0) continue;\n if (sa === da) internalByArea.set(sa, (internalByArea.get(sa) ?? 0) + 1);\n else {\n externalByArea.set(sa, (externalByArea.get(sa) ?? 0) + 1);\n externalByArea.set(da, (externalByArea.get(da) ?? 0) + 1);\n }\n }\n\n const areas: Area[] = [];\n for (const [id, members] of byArea) {\n const sorted = [...members].sort(\n (a, b) => b.importance - a.importance || a.id.localeCompare(b.id),\n );\n const label = sorted[0]?.qualifiedName ?? `area-${id}`;\n const internal = internalByArea.get(id) ?? 0;\n const external = externalByArea.get(id) ?? 0;\n const cohesion = internal + external > 0 ? internal / (internal + external) : 0;\n areas.push({\n id,\n label,\n size: members.length,\n members: members.map((m) => m.id).sort((a, b) => a.localeCompare(b)),\n cohesion: round(cohesion),\n externalEdges: external,\n });\n }\n return areas.sort((a, b) => a.id - b.id);\n}\n\nfunction scoreSurprise(edges: GraphEdge[], areaByNode: Map<string, number>): GraphEdge[] {\n // Count edges between each unordered pair of distinct areas. Rare connections\n // are more \"surprising\" (architectural shortcuts).\n const pairCount = new Map<string, number>();\n for (const e of edges) {\n if (!DEP_EDGES.has(e.kind)) continue;\n const sa = areaByNode.get(e.src);\n const da = areaByNode.get(e.dst);\n if (sa === undefined || da === undefined || sa < 0 || da < 0 || sa === da) continue;\n const key = pairKey(sa, da);\n pairCount.set(key, (pairCount.get(key) ?? 0) + 1);\n }\n\n return edges\n .map((e) => {\n if (!DEP_EDGES.has(e.kind)) return e;\n const sa = areaByNode.get(e.src);\n const da = areaByNode.get(e.dst);\n if (sa === undefined || da === undefined || sa < 0 || da < 0 || sa === da) return e;\n const count = pairCount.get(pairKey(sa, da)) ?? 1;\n // Fewer crossings between two areas → higher surprise.\n return { ...e, surprise: round(1 / count) };\n })\n .sort(\n (a, b) =>\n a.kind.localeCompare(b.kind) || a.src.localeCompare(b.src) || a.dst.localeCompare(b.dst),\n );\n}\n\n// --- numeric helpers ---\n\nfunction safeMetric(fn: () => Record<string, number>, ids: string[]): Map<string, number> {\n try {\n const res = fn();\n return new Map(ids.map((id) => [id, res[id] ?? 0]));\n } catch {\n return zeros(ids);\n }\n}\n\nfunction degreeMap(g: Graph, ids: string[]): Map<string, number> {\n return new Map(ids.map((id) => [id, g.hasNode(id) ? g.degree(id) : 0]));\n}\n\nfunction zeros(ids: string[]): Map<string, number> {\n return new Map(ids.map((id) => [id, 0]));\n}\n\nfunction normalize(m: Map<string, number>): Map<string, number> {\n let max = 0;\n for (const v of m.values()) if (v > max) max = v;\n if (max <= 0) return new Map(m);\n return new Map([...m].map(([k, v]) => [k, v / max]));\n}\n\nfunction round(x: number): number {\n return Math.round(x * 1e6) / 1e6;\n}\n\nfunction pairKey(a: number, b: number): string {\n return a < b ? `${a}|${b}` : `${b}|${a}`;\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type { GraphNode } from '../schema.js';\n\n/**\n * Coverage ingestion (VG-ENGINE-TEARDOWN §3.6) — runtime-grounded test linkage.\n * Parses LCOV (`coverage/lcov.info`) and Istanbul (`coverage-final.json`) into a\n * per-file line→hits map, then sets each node's `coverage` (fraction of its span\n * that ran) and `tested` flag. Stronger than static linkage where present.\n */\n\nexport type LineHits = Map<number, number>; // line → hit count\nexport type CoverageMap = Map<string, LineHits>; // repo-relative posix path → lines\n\nconst DEFAULT_PATHS = [\n 'coverage/lcov.info',\n 'lcov.info',\n 'coverage/coverage-final.json',\n 'coverage-final.json',\n];\n\n/** Find and parse coverage reports under root. Returns null if none found. */\nexport function loadCoverage(root: string, explicit?: string[]): CoverageMap | null {\n const candidates = (explicit && explicit.length ? explicit : DEFAULT_PATHS).map((p) =>\n path.resolve(root, p),\n );\n const found = candidates.filter((p) => fs.existsSync(p));\n if (found.length === 0) return null;\n\n const map: CoverageMap = new Map();\n for (const file of found) {\n try {\n const text = fs.readFileSync(file, 'utf8');\n if (file.endsWith('.json')) mergeIstanbul(map, text, root);\n else mergeLcov(map, text, root);\n } catch {\n /* skip unreadable/garbled report */\n }\n }\n return map.size ? map : null;\n}\n\nfunction rel(root: string, p: string): string {\n const abs = path.isAbsolute(p) ? p : path.resolve(root, p);\n return path.relative(root, abs).split(path.sep).join('/');\n}\n\nfunction bump(map: CoverageMap, file: string, line: number, hits: number): void {\n let lh = map.get(file);\n if (!lh) {\n lh = new Map();\n map.set(file, lh);\n }\n lh.set(line, Math.max(lh.get(line) ?? 0, hits));\n}\n\nfunction mergeLcov(map: CoverageMap, text: string, root: string): void {\n let current: string | null = null;\n for (const raw of text.split('\\n')) {\n const line = raw.trim();\n if (line.startsWith('SF:')) current = rel(root, line.slice(3));\n else if (line.startsWith('DA:') && current) {\n const [ln, hits] = line.slice(3).split(',');\n const n = Number(ln);\n const h = Number(hits);\n if (Number.isFinite(n)) bump(map, current, n, Number.isFinite(h) ? h : 0);\n } else if (line === 'end_of_record') current = null;\n }\n}\n\ninterface IstanbulEntry {\n path?: string;\n statementMap?: Record<string, { start: { line: number }; end: { line: number } }>;\n s?: Record<string, number>;\n}\n\nfunction mergeIstanbul(map: CoverageMap, text: string, root: string): void {\n const data = JSON.parse(text) as Record<string, IstanbulEntry>;\n for (const [key, entry] of Object.entries(data)) {\n const file = rel(root, entry.path ?? key);\n const stmts = entry.statementMap ?? {};\n const counts = entry.s ?? {};\n for (const [id, loc] of Object.entries(stmts)) {\n const hits = counts[id] ?? 0;\n const start = loc.start?.line;\n const end = loc.end?.line ?? start;\n if (!Number.isFinite(start)) continue;\n for (let ln = start; ln <= end; ln++) bump(map, file, ln, hits);\n }\n }\n}\n\n/** Apply coverage to nodes: set `coverage` fraction over the node's span + `tested`. */\nexport function applyCoverage(nodes: GraphNode[], coverage: CoverageMap): GraphNode[] {\n return nodes.map((n) => {\n if (n.kind === 'file' || n.kind === 'external') return n;\n const lh = coverage.get(n.file);\n if (!lh) return n;\n let instrumented = 0;\n let covered = 0;\n for (let ln = n.span.start; ln <= n.span.end; ln++) {\n const hits = lh.get(ln);\n if (hits === undefined) continue;\n instrumented++;\n if (hits > 0) covered++;\n }\n if (instrumented === 0) return n;\n const fraction = Math.round((covered / instrumented) * 1e6) / 1e6;\n const tested = covered > 0 ? true : n.kind === 'function' || n.kind === 'method' ? false : n.tested;\n return { ...n, coverage: fraction, tested };\n });\n}\n","import { canonicalize, shortId } from './hash.js';\nimport type { Fact, GraphEdge, GraphNode } from '../schema.js';\nimport type { FileParse } from './types.js';\n\n/**\n * The open facts subset (VG-PACKAGE-AND-SCHEMA §5) — reimplemented fresh in the\n * open engine: deterministic, no runtime, no corpus, no LLM, no hidden pipeline.\n * Three commodity fact kinds, each epistemic-typed so it never claims more than\n * the open layer can prove:\n *\n * - **contract** — from a public signature/type (declared → Observed)\n * - **invariant** — from a static assert/guard (static → Derived)\n * - **characterization** — from existing test linkage (static → Observed)\n *\n * Emitted on every build (cheap, deterministic). `--deep` is reserved for\n * heavier semantic layers, not for these open facts.\n */\nexport function buildFacts(parses: FileParse[], nodes: GraphNode[], edges: GraphEdge[]): Fact[] {\n const facts: Fact[] = [];\n const byId = new Map(nodes.map((n) => [n.id, n]));\n\n // Index code defs per file for line→enclosing-def lookup (invariants).\n const defsByFile = new Map<string, GraphNode[]>();\n for (const n of nodes) {\n if (n.kind === 'file' || n.kind === 'external') continue;\n const list = defsByFile.get(n.file);\n if (list) list.push(n);\n else defsByFile.set(n.file, [n]);\n }\n\n // --- contracts (from signatures) ---\n for (const n of nodes) {\n if ((n.kind === 'function' || n.kind === 'method') && n.signature) {\n facts.push(makeFact('contract', [n.id], { signature: n.signature }, 'declared', 'Observed', [\n { file: n.file, span: n.span },\n ]));\n }\n }\n\n // --- invariants (from static guards) ---\n for (const p of parses) {\n const defs = defsByFile.get(p.rel);\n if (!defs) continue;\n for (const g of p.guards) {\n const owner = enclosing(defs, g.line);\n if (!owner) continue;\n facts.push(\n makeFact('invariant', [owner.id], { guard: g.expr }, 'static', 'Derived', [\n { file: p.rel, span: { start: g.line, end: g.line } },\n ]),\n );\n }\n }\n\n // --- characterization (from test linkage) ---\n const testsByNode = new Map<string, string[]>();\n for (const e of edges) {\n if (e.kind !== 'test') continue;\n const testFile = byId.get(e.src)?.file;\n if (!testFile) continue;\n const list = testsByNode.get(e.dst);\n if (list) list.push(testFile);\n else testsByNode.set(e.dst, [testFile]);\n }\n for (const [nodeId, testFiles] of testsByNode) {\n const n = byId.get(nodeId);\n if (!n) continue;\n facts.push(\n makeFact(\n 'characterization',\n [nodeId],\n { pinnedBy: [...new Set(testFiles)].sort() },\n 'static',\n 'Observed',\n [{ file: n.file, span: n.span }],\n ),\n );\n }\n\n return facts.sort((a, b) => a.id.localeCompare(b.id));\n}\n\nfunction makeFact(\n kind: Fact['kind'],\n subjectIds: string[],\n predicate: unknown,\n derivedBy: Fact['derivedBy'],\n confidence: Fact['confidence'],\n evidence: Fact['evidence'],\n): Fact {\n const id = shortId(canonicalize({ t: 'fact', kind, subjectIds, predicate }));\n return { id, kind, subjectIds, predicate, derivedBy, confidence, evidence };\n}\n\n/** Smallest def whose line span contains `line`. */\nfunction enclosing(defs: GraphNode[], line: number): GraphNode | undefined {\n let best: GraphNode | undefined;\n for (const d of defs) {\n if (d.span.start <= line && d.span.end >= line) {\n if (!best || d.span.end - d.span.start < best.span.end - best.span.start) best = d;\n }\n }\n return best;\n}\n","import { FREE_PACK, type KnowledgePack, type PackEntry } from '../grounding/pack.js';\nimport type { GraphEdge, GraphNode, GroundingEdge } from '../schema.js';\nimport type { FileParse } from './types.js';\n\n/**\n * Grounding (VG-PACKAGE-AND-SCHEMA §6) — match nodes to knowledge-pack entries by\n * deterministic signals (file imports, called APIs, identifier keywords) and\n * attach cited framing edges. Closed-world tools can't follow without building a\n * corpus. Deterministic-first; the free pack ships in the open CLI.\n */\nexport function groundGraph(\n nodes: GraphNode[],\n edges: GraphEdge[],\n parses: FileParse[],\n packs: KnowledgePack[] = [FREE_PACK],\n): GroundingEdge[] {\n const byId = new Map(nodes.map((n) => [n.id, n]));\n const importsByFile = new Map<string, string[]>();\n for (const p of parses) importsByFile.set(p.rel, p.imports.map((i) => i.source.toLowerCase()));\n\n // callee names per node (from call edges).\n const calleesByNode = new Map<string, string[]>();\n for (const e of edges) {\n if (e.kind !== 'call') continue;\n const callee = byId.get(e.dst)?.name;\n if (!callee) continue;\n const list = calleesByNode.get(e.src);\n if (list) list.push(callee.toLowerCase());\n else calleesByNode.set(e.src, [callee.toLowerCase()]);\n }\n\n const out: GroundingEdge[] = [];\n for (const n of nodes) {\n if (n.kind === 'file' || n.kind === 'external') continue;\n const nameParts = new Set(\n n.name\n .split(/[^a-zA-Z0-9]+|(?<=[a-z])(?=[A-Z])/)\n .filter(Boolean)\n .map((s) => s.toLowerCase()),\n );\n const imports = importsByFile.get(n.file) ?? [];\n const callees = calleesByNode.get(n.id) ?? [];\n\n for (const pack of packs) {\n for (const entry of pack.entries) {\n const conf = matchConfidence(entry, nameParts, imports, callees);\n if (conf > 0) {\n out.push({\n src: n.id,\n packEntryId: entry.id,\n kind: entry.kind,\n confidence: conf,\n rationale: entry.rationale,\n citation: entry.citation,\n });\n }\n }\n }\n }\n\n return out.sort(\n (a, b) =>\n a.src.localeCompare(b.src) || a.packEntryId.localeCompare(b.packEntryId),\n );\n}\n\nfunction matchConfidence(\n entry: PackEntry,\n nameParts: Set<string>,\n imports: string[],\n callees: string[],\n): number {\n let conf = 0;\n if (entry.match.imports) {\n for (const sig of entry.match.imports) {\n if (imports.some((imp) => imp.includes(sig.toLowerCase()))) {\n conf = Math.max(conf, 0.8);\n break;\n }\n }\n }\n if (entry.match.calls) {\n const want = new Set(entry.match.calls.map((s) => s.toLowerCase()));\n if (callees.some((c) => want.has(c))) conf = Math.max(conf, 0.7);\n }\n if (entry.match.keywords) {\n if (entry.match.keywords.some((k) => nameParts.has(k.toLowerCase()))) {\n conf = Math.max(conf, 0.5);\n }\n }\n return conf;\n}\n","import * as fs from 'node:fs';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { parseSource } from './parse.js';\nimport { setGrammarsOverride, resetParser } from './grammars.js';\nimport { checkMemoryBudget, envJobs, envWorkerHeapMb, ResourceLimitError } from './limits.js';\nimport type { DiscoveredFile } from './discover.js';\nimport type { FileParse } from './types.js';\nimport type { ParseTask } from './parse-worker.js';\n\n/**\n * Parse a set of discovered files into FileParse tables.\n *\n * Parsing is CPU-bound and per-file independent, so it parallelises across a\n * worker_threads pool (tinypool) and scales near-linearly with cores — the\n * direct mechanism behind the \"≥5× build\" mandate (VG-ENGINE-TEARDOWN §3.10).\n *\n * The result is identical regardless of how work was sharded: every output is\n * sorted by relative path, so the build never depends on scheduling order. A\n * single-threaded inline path is always available (and used for small repos or\n * when the worker module isn't resolvable, e.g. under ts-only test runners),\n * producing byte-identical output to the pooled path.\n */\n\nexport interface ParseOptions {\n /** Worker count. Default: min(cores - 1, file count). 1 forces inline. */\n jobs?: number;\n /** Force the single-threaded path (tests, debugging). */\n inline?: boolean;\n /** Below this many files, run inline (worker spin-up isn't worth it). */\n inlineThreshold?: number;\n /** Live progress: called as files finish parsing (done of total). */\n onProgress?: (done: number, total: number) => void;\n /** `--grammars <dir>` override for the grammar .wasm files (offline/air-gapped). */\n grammarsDir?: string;\n /** Heap budget (MiB) checked as parse results accumulate; 0/unset skips. */\n memoryBudgetMb?: number;\n}\n\nconst DEFAULT_INLINE_THRESHOLD = 24;\n\nexport async function parseFiles(\n files: DiscoveredFile[],\n options: ParseOptions = {},\n): Promise<FileParse[]> {\n const threshold = options.inlineThreshold ?? DEFAULT_INLINE_THRESHOLD;\n const cores = Math.max(1, os.cpus()?.length ?? 1);\n // Precedence: explicit option (--jobs) → VG_JOBS env → cores - 1. Capping\n // workers caps peak memory too (each worker holds its own grammar set).\n const jobs = Math.max(1, options.jobs ?? envJobs() ?? (Math.min(cores - 1, files.length) || 1));\n\n const workerFile = resolveWorkerFile();\n const useInline =\n options.inline === true ||\n jobs <= 1 ||\n files.length < threshold ||\n workerFile === null;\n\n if (useInline) {\n // Inline runs in this process — apply the override directly.\n if (options.grammarsDir) setGrammarsOverride(options.grammarsDir);\n return sortByRel(await parseInline(files, options));\n }\n return sortByRel(await parsePooled(files, jobs, workerFile, options));\n}\n\n/** Check the accumulating heap every this-many completed files — frequent\n * enough to abort before a crash, cheap enough to be free. */\nconst MEM_CHECK_EVERY = 64;\n\nasync function parseInline(files: DiscoveredFile[], options: ParseOptions): Promise<FileParse[]> {\n const { onProgress, memoryBudgetMb = 0 } = options;\n const out: FileParse[] = [];\n onProgress?.(0, files.length);\n for (const file of files) {\n try {\n const source = fs.readFileSync(file.abs, 'utf8');\n out.push(await parseSource(file.rel, file.lang.id, source));\n } catch (err) {\n // A wasm-level parse crash can leave the language's reused parser\n // mid-state; drop it so the failure stays contained to this file.\n resetParser(file.lang.id);\n out.push(emptyParse(file, `parse failed: ${(err as Error).message}`));\n }\n onProgress?.(out.length, files.length);\n if (out.length % MEM_CHECK_EVERY === 0) checkMemoryBudget('parse', memoryBudgetMb);\n }\n return out;\n}\n\nasync function parsePooled(\n files: DiscoveredFile[],\n jobs: number,\n workerFile: string,\n options: ParseOptions,\n): Promise<FileParse[]> {\n const { onProgress, grammarsDir, memoryBudgetMb = 0 } = options;\n // Dynamic import so tinypool isn't loaded for inline-only runs.\n const { default: Tinypool } = await import('tinypool');\n // VG_WORKER_HEAP_MB caps each worker's old-generation heap so one runaway\n // parse cannot swallow the whole machine; unset = platform default.\n const workerHeapMb = envWorkerHeapMb();\n const pool = new Tinypool({\n filename: workerFile,\n maxThreads: jobs,\n minThreads: 1,\n ...(workerHeapMb ? { resourceLimits: { maxOldGenerationSizeMb: workerHeapMb } } : {}),\n });\n try {\n // More, smaller buckets than threads → finer live progress + better load\n // balancing. Round-robin keeps shards balanced; the final sort makes the\n // output independent of bucket count, so determinism is unaffected.\n const total = files.length;\n const buckets = chunk(\n files.map<ParseTask>((f) => ({ rel: f.rel, abs: f.abs, lang: f.lang.id })),\n Math.min(total, jobs * 8),\n );\n let done = 0;\n onProgress?.(0, total);\n const results = await Promise.all(\n buckets.map((b) =>\n (pool.run({ tasks: b, grammarsDir }) as Promise<FileParse[]>).then((r) => {\n done += b.length;\n onProgress?.(done, total);\n // Results accumulate in *this* process; guard its heap as they land.\n checkMemoryBudget('parse', memoryBudgetMb);\n return r;\n }),\n ),\n );\n return results.flat();\n } catch (err) {\n if (isWorkerOom(err)) {\n throw new ResourceLimitError(\n `graph build stopped: a parse worker exceeded its ${workerHeapMb ?? '?'} MiB heap cap ` +\n `(VG_WORKER_HEAP_MB). Raise the cap, exclude the offending files (--exclude), or ` +\n `run single-threaded with --jobs 1.`,\n );\n }\n throw err;\n } finally {\n await pool.destroy();\n }\n}\n\nfunction isWorkerOom(err: unknown): boolean {\n const e = err as { code?: string; message?: string } | null;\n return e?.code === 'ERR_WORKER_OUT_OF_MEMORY' || /out of memory/i.test(e?.message ?? '');\n}\n\nfunction resolveWorkerFile(): string | null {\n // Only the compiled .js worker is runnable by a bare worker_thread. Under a\n // TS-only runner (vitest/tsx) the .js won't exist → fall back to inline.\n const here = path.dirname(fileURLToPath(import.meta.url));\n const candidate = path.join(here, 'parse-worker.js');\n return fs.existsSync(candidate) ? candidate : null;\n}\n\nfunction chunk<T>(items: T[], buckets: number): T[][] {\n const out: T[][] = Array.from({ length: Math.min(buckets, items.length || 1) }, () => []);\n if (out.length === 0) return [];\n // Round-robin keeps shard sizes balanced regardless of file ordering.\n items.forEach((item, i) => out[i % out.length].push(item));\n return out.filter((c) => c.length > 0);\n}\n\nfunction sortByRel(parses: FileParse[]): FileParse[] {\n return parses.sort((a, b) => (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0));\n}\n\nfunction emptyParse(file: DiscoveredFile, warning: string): FileParse {\n return {\n rel: file.rel,\n lang: file.lang.id,\n hash: '',\n bytes: 0,\n defs: [],\n calls: [],\n imports: [],\n heritage: [],\n typeRefs: [],\n guards: [],\n warnings: [warning],\n };\n}\n","import * as path from 'node:path';\nimport ts from 'typescript';\nimport { edgeId } from './ids.js';\nimport type { EdgeKind, GraphEdge, GraphNode, NodeKind, ResolverKind } from '../schema.js';\n\n/**\n * Precise TS/JS resolution via the TypeScript Compiler API — the type checker\n * itself, in-process, no external tool, `typescript` already a dependency. It\n * resolves `this.x()`, member calls, imported/aliased calls and heritage\n * exactly, which the heuristic rung structurally cannot (real codebases are\n * dominated by member calls → 0% heuristic resolution). Default-on for TS/JS.\n *\n * Deterministic: a ts.Program over the same files + options + compiler version\n * yields the same resolution; edges are stably sorted. Edges carry\n * `resolution: \"tsc\"`, confidence 1.0, and are authoritative for covered files.\n */\n\nconst PRECISE_KIND = 'tsc' satisfies ResolverKind;\n\nexport interface TsResolveResult {\n edges: GraphEdge[];\n /** Repo-relative files the program covered (tsc is authoritative for these). */\n coveredFiles: Set<string>;\n stats: { files: number; calls: number; jsx: number; heritage: number; resolved: number };\n}\n\n/** One walked file's raw checker output, before the cross-file interface\n * bridge. Every edge's `src` node lives in this file, so results partition\n * cleanly by file — the unit the incremental tsc cache stores and reuses. */\nexport interface TsFilePartial {\n /** The program produced a SourceFile for this file (tsc is authoritative). */\n covered: boolean;\n edges: GraphEdge[];\n interfaceCalls: Array<{ srcId: string; interfaceId: string; method: string }>;\n stats: { calls: number; jsx: number; heritage: number; resolved: number };\n}\n\nexport function tsResolveEdges(\n root: string,\n tsFiles: { rel: string; abs: string }[],\n nodes: GraphNode[],\n): TsResolveResult {\n const partials = tsWalkFiles(root, tsFiles, tsFiles, [], nodes);\n return assembleTsResult(tsFiles.map((f) => f.rel), partials, nodes);\n}\n\n/**\n * Walk `walkFiles` with the type checker and return per-file partial results.\n * `mapFiles` is the full file set edge targets may map into (superset of\n * walkFiles — a scoped walk still resolves calls INTO unchanged files).\n * `extraRootFiles` are added as program roots without being walked: ambient\n * declaration files (`.d.ts`, `declare global`/`declare module`) that shape\n * checker answers for every file without being imported by any of them.\n */\nexport function tsWalkFiles(\n root: string,\n walkFiles: { rel: string; abs: string }[],\n mapFiles: { rel: string; abs: string }[],\n extraRootFiles: { rel: string; abs: string }[],\n nodes: GraphNode[],\n): Map<string, TsFilePartial> {\n const partials = new Map<string, TsFilePartial>();\n if (walkFiles.length === 0) return partials;\n\n const absToRel = new Map(mapFiles.map((f) => [normalize(f.abs), f.rel]));\n const options = compilerOptions(root);\n const rootAbs = new Set(walkFiles.map((f) => f.abs));\n for (const f of extraRootFiles) rootAbs.add(f.abs);\n let program: ts.Program;\n try {\n program = ts.createProgram([...rootAbs], options);\n } catch {\n return partials; // never let resolution break the build\n }\n const checker = program.getTypeChecker();\n\n const nodesByFile = new Map<string, GraphNode[]>();\n const fileNodeByRel = new Map<string, GraphNode>();\n for (const n of nodes) {\n if (n.kind === 'file') {\n fileNodeByRel.set(n.file, n);\n continue;\n }\n if (n.kind === 'external') continue;\n const list = nodesByFile.get(n.file);\n if (list) list.push(n);\n else nodesByFile.set(n.file, [n]);\n }\n\n const relForAbs = (abs: string): string | undefined => absToRel.get(normalize(abs));\n\n for (const file of walkFiles) {\n const sf = program.getSourceFile(file.abs);\n if (!sf) {\n partials.set(file.rel, {\n covered: false,\n edges: [],\n interfaceCalls: [],\n stats: { calls: 0, jsx: 0, heritage: 0, resolved: 0 },\n });\n continue;\n }\n const edges = new Map<string, GraphEdge>();\n const stats = { calls: 0, jsx: 0, heritage: 0, resolved: 0 };\n // A method call on an interface-typed receiver resolves to the interface\n // (its method signatures are not graph nodes), so DI-injected services never\n // got a call edge to the concrete implementation. Record such calls here;\n // the cross-file bridge runs in assembleTsResult once ALL covered files'\n // `implements` edges are known.\n const interfaceCalls: Array<{ srcId: string; interfaceId: string; method: string }> = [];\n const fileNodes = nodesByFile.get(file.rel) ?? [];\n const fileNode = fileNodeByRel.get(file.rel);\n\n const lineOf = (pos: number): number => sf.getLineAndCharacterOfPosition(pos).line + 1;\n\n const visit = (node: ts.Node): void => {\n if (ts.isCallExpression(node) || ts.isNewExpression(node)) {\n stats.calls++;\n const target = resolveTarget(checker, node.expression, nodesByFile, relForAbs);\n if (target) {\n // Attribute to the enclosing def, falling back to the file node for\n // top-level calls — mirrors the heuristic so test-linkage and\n // centrality see the same call granularity.\n const src = enclosing(fileNodes, lineOf(node.getStart(sf))) ?? fileNode;\n if (src && src.id !== target.id) {\n add(edges, callKind(target), src.id, target.id);\n stats.resolved++;\n // Interface-typed method call (`svc.method()` where svc: IFoo): the\n // target is the interface node, and the method name is the accessed\n // property. Record it for the single-implementation bridge below.\n if (target.kind === 'interface' && ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression)) {\n interfaceCalls.push({ srcId: src.id, interfaceId: target.id, method: node.expression.name.text });\n }\n }\n }\n } else if (ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node)) {\n // JSX component usage (`<Foo/>`) is a render — a call in the graph.\n // Dominant cross-module link in React/Next code, which the heuristic and\n // a CallExpression-only walk both miss. Lowercase tags are intrinsic\n // HTML elements and resolve to nothing in-repo (skipped).\n if (isComponentTag(node.tagName)) {\n stats.jsx++;\n const target = resolveTarget(checker, node.tagName, nodesByFile, relForAbs);\n if (target) {\n const src = enclosing(fileNodes, lineOf(node.getStart(sf))) ?? fileNode;\n if (src && src.id !== target.id) {\n add(edges, callKind(target), src.id, target.id);\n stats.resolved++;\n }\n }\n }\n } else if (ts.isClassDeclaration(node) && node.heritageClauses) {\n const classLine = lineOf(node.getStart(sf));\n const src = enclosing(fileNodes, classLine);\n for (const clause of node.heritageClauses) {\n const kind: EdgeKind = clause.token === ts.SyntaxKind.ImplementsKeyword ? 'implements' : 'extends';\n for (const t of clause.types) {\n stats.heritage++;\n const target = resolveTarget(checker, t.expression, nodesByFile, relForAbs);\n if (src && target && src.id !== target.id) {\n add(edges, kind, src.id, target.id);\n stats.resolved++;\n }\n }\n }\n }\n ts.forEachChild(node, visit);\n };\n visit(sf);\n\n partials.set(file.rel, { covered: true, edges: [...edges.values()], interfaceCalls, stats });\n }\n\n return partials;\n}\n\n/**\n * Merge per-file partials (fresh walks and cache hits alike) into the final\n * result, then run the single-implementation interface bridge over the merged\n * edge set. `orderedRels` fixes iteration order to the original file order so\n * the output — including edge `count` accumulation — is byte-identical to a\n * single full walk regardless of which files came from cache.\n *\n * Single-implementation bridge: for each interface with EXACTLY ONE\n * implementing class, redirect its recorded interface-typed calls to the\n * implementation's matching method. This is the DI edge that makes impact_of /\n * tests_for / find_path work on the concrete service. Skipped when an\n * interface has zero or several implementations (genuinely ambiguous — the\n * references→interface edge already recorded the dependency).\n */\nexport function assembleTsResult(\n orderedRels: string[],\n partials: Map<string, TsFilePartial>,\n nodes: GraphNode[],\n): TsResolveResult {\n const nodesByFile = new Map<string, GraphNode[]>();\n for (const n of nodes) {\n if (n.kind === 'file' || n.kind === 'external') continue;\n const list = nodesByFile.get(n.file);\n if (list) list.push(n);\n else nodesByFile.set(n.file, [n]);\n }\n const byId = new Map<string, GraphNode>();\n for (const list of nodesByFile.values()) for (const n of list) byId.set(n.id, n);\n\n const edges = new Map<string, GraphEdge>();\n const covered = new Set<string>();\n const stats = { files: 0, calls: 0, jsx: 0, heritage: 0, resolved: 0 };\n const interfaceCalls: Array<{ srcId: string; interfaceId: string; method: string }> = [];\n for (const rel of orderedRels) {\n const p = partials.get(rel);\n if (!p || !p.covered) continue;\n covered.add(rel);\n stats.files++;\n stats.calls += p.stats.calls;\n stats.jsx += p.stats.jsx;\n stats.heritage += p.stats.heritage;\n stats.resolved += p.stats.resolved;\n // Edge ids never collide across files (src always lives in the walked\n // file), so re-seeding a shared map reproduces the full-walk map exactly.\n for (const e of p.edges) edges.set(e.id, { ...e });\n interfaceCalls.push(...p.interfaceCalls);\n }\n\n const implsByInterface = new Map<string, string[]>();\n for (const e of edges.values()) {\n if (e.kind !== 'implements' && e.kind !== 'extends') continue;\n if (byId.get(e.dst)?.kind !== 'interface') continue;\n const list = implsByInterface.get(e.dst);\n if (list) list.push(e.src);\n else implsByInterface.set(e.dst, [e.src]);\n }\n for (const { srcId, interfaceId, method } of interfaceCalls) {\n const impls = implsByInterface.get(interfaceId);\n if (!impls || impls.length !== 1) continue;\n const impl = byId.get(impls[0]);\n if (!impl) continue;\n const target = (nodesByFile.get(impl.file) ?? []).find(\n (n) => (n.kind === 'method' || n.kind === 'function') && n.qualifiedName === `${impl.qualifiedName}.${method}`,\n );\n if (target && target.id !== srcId) {\n add(edges, 'call', srcId, target.id);\n stats.resolved++;\n }\n }\n\n return { edges: [...edges.values()], coveredFiles: covered, stats };\n}\n\n/** A render/invoke target (function/method/class/component) is a `call`; other\n * kinds (interface/property/…) are `references`. */\nfunction callKind(target: GraphNode): EdgeKind {\n return target.kind === 'function' ||\n target.kind === 'method' ||\n target.kind === 'class' ||\n target.kind === 'component'\n ? 'call'\n : 'references';\n}\n\n/** Is a JSX tag a component (resolvable in-repo) vs an intrinsic HTML element? */\nfunction isComponentTag(tag: ts.JsxTagNameExpression): boolean {\n if (ts.isIdentifier(tag)) return /^[A-Z]/.test(tag.text);\n // `<Namespace.Component/>` / `<obj.Member/>` — a property access is a component ref.\n return ts.isPropertyAccessExpression(tag);\n}\n\nfunction resolveTarget(\n checker: ts.TypeChecker,\n expr: ts.Node,\n nodesByFile: Map<string, GraphNode[]>,\n relForAbs: (abs: string) => string | undefined,\n): GraphNode | null {\n let sym = checker.getSymbolAtLocation(expr);\n if (!sym) return null;\n if (sym.flags & ts.SymbolFlags.Alias) {\n try {\n sym = checker.getAliasedSymbol(sym);\n } catch {\n /* keep original */\n }\n }\n const decls = sym.declarations;\n if (!decls) return null;\n for (const decl of decls) {\n const df = decl.getSourceFile();\n const rel = relForAbs(df.fileName);\n if (!rel) continue; // declaration is external (node_modules / lib)\n const fileNodes = nodesByFile.get(rel);\n if (!fileNodes) continue;\n const line = df.getLineAndCharacterOfPosition(decl.getStart(df)).line + 1;\n // Pick the node for this declaration, using its syntax kind to disambiguate\n // when several nodes start on the same line (e.g. a single-line class and\n // its method) — the type checker knows whether we want the method or the\n // class, so a name/line collision never picks the wrong one.\n const node = pickNode(fileNodes, line, expectedKinds(decl));\n if (node) return node;\n }\n return null;\n}\n\n/** Node kinds a declaration could map to (for same-line tie-breaking). */\nfunction expectedKinds(decl: ts.Node): Set<NodeKind> {\n if (ts.isMethodDeclaration(decl) || ts.isMethodSignature(decl)) return new Set(['method']);\n if (ts.isFunctionDeclaration(decl) || ts.isFunctionExpression(decl) || ts.isArrowFunction(decl)) {\n return new Set(['function', 'method', 'component']);\n }\n if (ts.isClassDeclaration(decl) || ts.isClassExpression(decl)) return new Set(['class', 'component']);\n if (ts.isInterfaceDeclaration(decl)) return new Set(['interface']);\n if (\n ts.isPropertyDeclaration(decl) ||\n ts.isPropertySignature(decl) ||\n ts.isGetAccessorDeclaration(decl) ||\n ts.isSetAccessorDeclaration(decl)\n ) {\n return new Set(['property', 'method']);\n }\n if (ts.isConstructorDeclaration(decl)) return new Set(['class', 'method']);\n if (ts.isVariableDeclaration(decl)) return new Set(['function', 'property', 'component']);\n return new Set();\n}\n\n/**\n * The node for a declaration at `line`: among nodes starting exactly there,\n * prefer one whose kind the declaration expects, then the smallest span, then\n * the lexicographically smaller id (a stable, order-independent tiebreak). Falls\n * back to the smallest enclosing node when nothing starts on that line.\n */\nfunction pickNode(nodes: GraphNode[], line: number, want: Set<NodeKind>): GraphNode | undefined {\n let best: GraphNode | undefined;\n for (const n of nodes) {\n if (n.span.start !== line) continue;\n if (!best || better(n, best, want)) best = n;\n }\n return best ?? enclosing(nodes, line);\n}\n\nfunction better(n: GraphNode, best: GraphNode, want: Set<NodeKind>): boolean {\n const nWanted = want.has(n.kind);\n const bWanted = want.has(best.kind);\n if (nWanted !== bWanted) return nWanted;\n const nSize = n.span.end - n.span.start;\n const bSize = best.span.end - best.span.start;\n if (nSize !== bSize) return nSize < bSize;\n return n.id < best.id;\n}\n\nfunction compilerOptions(root: string): ts.CompilerOptions {\n const base: ts.CompilerOptions = {\n allowJs: true,\n checkJs: false,\n skipLibCheck: true,\n noEmit: true,\n noResolve: false,\n target: ts.ScriptTarget.ES2022,\n module: ts.ModuleKind.ESNext,\n moduleResolution: ts.ModuleResolutionKind.Bundler,\n jsx: ts.JsxEmit.Preserve,\n allowImportingTsExtensions: true,\n resolveJsonModule: true,\n };\n // Honor the project's tsconfig (paths/baseUrl) for accurate module resolution.\n // Prefer tsconfig.json, then tsconfig.base.json (Nx/Turborepo), and follow\n // `extends` chains — real monorepos put path aliases in a base config that\n // per-package configs extend. getParsedCommandLineOfConfigFile resolves the\n // whole chain (parseJsonConfigFileContent does not).\n const configPath =\n ts.findConfigFile(root, ts.sys.fileExists, 'tsconfig.json') ??\n ts.findConfigFile(root, ts.sys.fileExists, 'tsconfig.base.json');\n if (configPath) {\n try {\n const host: ts.ParseConfigFileHost = {\n ...ts.sys,\n onUnRecoverableConfigFileDiagnostic: () => {\n /* tolerate broken config — fall back to base */\n },\n };\n const parsed = ts.getParsedCommandLineOfConfigFile(configPath, {}, host);\n if (parsed) {\n // Keep the project's module map (baseUrl/paths) but force our read-only,\n // permissive compile settings on top so resolution is maximal.\n return { ...parsed.options, ...base, baseUrl: parsed.options.baseUrl, paths: parsed.options.paths };\n }\n } catch {\n /* fall back to base */\n }\n }\n return base;\n}\n\nfunction add(map: Map<string, GraphEdge>, kind: EdgeKind, src: string, dst: string): void {\n const id = edgeId(kind, src, dst);\n const existing = map.get(id);\n if (existing) {\n existing.count = (existing.count ?? 1) + 1;\n return;\n }\n map.set(id, { id, kind, src, dst, resolution: PRECISE_KIND, confidence: 1.0, count: 1 });\n}\n\nfunction enclosing(nodes: GraphNode[], line: number): GraphNode | undefined {\n let best: GraphNode | undefined;\n for (const n of nodes) {\n if (n.span.start <= line && n.span.end >= line) {\n if (!best || n.span.end - n.span.start < best.span.end - best.span.start) best = n;\n }\n }\n return best;\n}\n\nfunction normalize(p: string): string {\n return path.resolve(p).split(path.sep).join('/');\n}\n","import * as crypto from 'node:crypto';\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport ts from 'typescript';\nimport { cacheDir } from './cache.js';\nimport { stableStringify } from './serialize.js';\nimport type { TsFilePartial } from './ts-resolver.js';\n\n/**\n * Incremental cache for the tsc precise-resolution rung — the change-scoped\n * downstream stage of VG gap-closure item 2c. The parse cache made parse\n * incremental; this makes the single most expensive downstream stage (the\n * ts.Program + checker walk, ~70% of warm-refresh time) scale with change\n * size instead of repo size.\n *\n * Soundness: a file's checker output can depend only on (a) its own content,\n * (b) the content of files it transitively imports, and (c) ambient\n * declarations (`.d.ts` files and `declare global` / `declare module`\n * blocks), which shape checker answers program-wide without any import edge.\n * The per-file cache key therefore hashes all three, so any change that could\n * alter the output invalidates the entry — an over-approximation, never an\n * under-approximation. The mutation-corpus byte-identity gate\n * (incremental-identity.test.ts) enforces warm ≡ cold over this cache.\n */\n\n// /1: initial version.\nconst TSC_CACHE_VERSION = 'vg-tsc-cache/1';\n\nconst AMBIENT_RE = /\\bdeclare\\s+(global|module)\\b/;\n\ninterface TscEntry {\n /** Content hash the ambient flag (and key, if present) was computed from. */\n hash: string;\n /** File contributes ambient declarations (.d.ts / declare global / declare module). */\n ambient: boolean;\n /** Full invalidation key (own hash + import closure + ambient hash). */\n key?: string;\n partial?: TsFilePartial;\n}\n\ninterface TscCacheFile {\n version: string;\n toolVersion: string;\n ts: string;\n entries: Record<string, TscEntry>;\n}\n\nexport interface TscCache {\n /** The cached per-file result, iff the invalidation key matches. */\n get(rel: string, key: string): TsFilePartial | undefined;\n set(rel: string, hash: string, key: string, partial: TsFilePartial): void;\n /**\n * Whether a file contributes ambient declarations. Reuses the stored flag\n * when the content hash matches; otherwise re-reads the file (changed files\n * only — cheap) and re-scans.\n */\n isAmbient(rel: string, hash: string, abs: string): boolean;\n /** Drop entries for files no longer present. */\n prune(currentRels: Set<string>): void;\n save(): void;\n}\n\nfunction tscCachePath(root: string): string {\n return path.join(cacheDir(root), 'tsc-cache.json');\n}\n\nexport function loadTscCache(root: string, opts: { toolVersion: string; disabled?: boolean }): TscCache {\n const file = tscCachePath(root);\n let data: TscCacheFile = {\n version: TSC_CACHE_VERSION,\n toolVersion: opts.toolVersion,\n ts: ts.version,\n entries: {},\n };\n\n if (!opts.disabled && fs.existsSync(file)) {\n try {\n const loaded = JSON.parse(fs.readFileSync(file, 'utf8')) as TscCacheFile;\n if (\n loaded.version === TSC_CACHE_VERSION &&\n loaded.toolVersion === opts.toolVersion &&\n loaded.ts === ts.version &&\n loaded.entries\n ) {\n data = loaded;\n }\n } catch {\n /* corrupt cache — start fresh */\n }\n }\n\n return {\n get(rel, key) {\n if (opts.disabled) return undefined;\n const entry = data.entries[rel];\n return entry && entry.key === key ? entry.partial : undefined;\n },\n set(rel, hash, key, partial) {\n const ambient = data.entries[rel]?.hash === hash ? data.entries[rel].ambient : detectAmbient(rel, abs$(root, rel));\n data.entries[rel] = { hash, ambient, key, partial };\n },\n isAmbient(rel, hash, abs) {\n const entry = data.entries[rel];\n if (entry && entry.hash === hash) return entry.ambient;\n const ambient = detectAmbient(rel, abs);\n // Record hash+ambient now (key/partial filled in after a walk); a later\n // `set` for the same hash reuses this flag without re-reading the file.\n data.entries[rel] = { hash, ambient };\n return ambient;\n },\n prune(currentRels) {\n for (const rel of Object.keys(data.entries)) {\n if (!currentRels.has(rel)) delete data.entries[rel];\n }\n },\n save() {\n if (opts.disabled) return;\n fs.mkdirSync(cacheDir(root), { recursive: true });\n fs.writeFileSync(file, stableStringify(data, 0));\n },\n };\n}\n\nfunction abs$(root: string, rel: string): string {\n return path.join(root, rel);\n}\n\nfunction detectAmbient(rel: string, abs: string): boolean {\n if (rel.endsWith('.d.ts')) return true;\n try {\n return AMBIENT_RE.test(fs.readFileSync(abs, 'utf8'));\n } catch {\n // Unreadable → treat as ambient so it always invalidates rather than\n // silently going stale.\n return true;\n }\n}\n\n/**\n * A stable fingerprint of the effective compiler configuration: the fully\n * resolved tsconfig option set (extends chains flattened), so a config edit\n * anywhere in the chain invalidates every entry.\n */\nexport function tsConfigFingerprint(root: string): string {\n const configPath =\n ts.findConfigFile(root, ts.sys.fileExists, 'tsconfig.json') ??\n ts.findConfigFile(root, ts.sys.fileExists, 'tsconfig.base.json');\n if (!configPath) return sha('none');\n try {\n const host: ts.ParseConfigFileHost = {\n ...ts.sys,\n onUnRecoverableConfigFileDiagnostic: () => {},\n };\n const parsed = ts.getParsedCommandLineOfConfigFile(configPath, {}, host);\n return sha(stableStringify(parsed?.options ?? 'unparsed', 0));\n } catch {\n return sha('unparsed');\n }\n}\n\n/**\n * Per-file invalidation keys for a set of TS/JS files, from the heuristic\n * resolver's file-level import graph. Each key covers the file's own content\n * hash, the content hashes of its transitive import closure, and the shared\n * ambient hash (all ambient files + resolved tsconfig + compiler version).\n */\nexport function tscKeys(\n rels: string[],\n hashes: Map<string, string>,\n importsByFile: Map<string, Set<string>>,\n ambientHash: string,\n): Map<string, string> {\n const keys = new Map<string, string>();\n for (const rel of rels) {\n // Transitive import closure, restricted to hashed corpus files. Iterative\n // BFS; cycles terminate via the visited set.\n const closure: string[] = [];\n const visited = new Set<string>([rel]);\n const queue = [rel];\n while (queue.length) {\n const cur = queue.pop()!;\n for (const dep of importsByFile.get(cur) ?? []) {\n if (visited.has(dep)) continue;\n visited.add(dep);\n if (hashes.has(dep)) closure.push(dep);\n queue.push(dep);\n }\n }\n closure.sort();\n const lines = closure.map((c) => `${c}\\x00${hashes.get(c)}`);\n keys.set(rel, sha(`${TSC_CACHE_VERSION}\\n${ambientHash}\\n${rel}\\x00${hashes.get(rel)}\\n${lines.join('\\n')}`));\n }\n return keys;\n}\n\n/** The shared ambient component: every ambient file's (rel, hash) plus the\n * resolved compiler configuration and compiler version. */\nexport function ambientFingerprint(\n ambient: Array<{ rel: string; hash: string }>,\n configFingerprint: string,\n): string {\n const lines = ambient\n .map((a) => `${a.rel}\\x00${a.hash}`)\n .sort()\n .join('\\n');\n return sha(`${configFingerprint}\\n${ts.version}\\n${lines}`);\n}\n\nfunction sha(s: string): string {\n return crypto.createHash('sha256').update(s).digest('hex');\n}\n","import type { GraphEdge, NodeKind, ResolverKind } from '../schema.js';\n\n/**\n * Edge-level epistemic confidence.\n *\n * Tree-sitter gives syntax, not semantics: a call graph built purely from it is\n * name-matching — heuristic, i.e. conjecture wearing a deterministic costume.\n * Rather than hide that behind a single 0..1 `confidence`, every edge also\n * carries a coarse, honest *tier* describing HOW it was resolved, so a consumer\n * can filter for the assurance it needs (`WHERE epistemic = 'observed'`).\n *\n * observed — resolved by a semantic resolver (SCIP / stack-graphs / the\n * TypeScript type checker) to a concrete declaration, or a\n * structural fact read directly off the parse tree\n * (containment, an import that resolves to a corpus file).\n * name-matched — matched by symbol name only, with no reachability proof.\n * This is the heuristic call/heritage/reference graph: useful,\n * but conjecture, not observation.\n * declared — asserted by a manifest, config, or an external boundary the\n * graph does not model internally (external package imports,\n * test/coverage linkage). True as a declaration; not verified\n * against code.\n *\n * `epistemic` is the coarse honesty axis; the numeric `confidence` remains the\n * fine gradient within a tier. The tier is a pure, deterministic function of the\n * edge's own fields plus the kind of its destination node.\n */\nexport type EpistemicTier = 'observed' | 'name-matched' | 'declared';\n\nexport const EPISTEMIC_TIERS: readonly EpistemicTier[] = ['observed', 'name-matched', 'declared'];\n\n/** Semantic resolvers observe the real target; the heuristic rung only guesses it. */\nconst SEMANTIC_RESOLVERS = new Set<ResolverKind>(['scip', 'stackgraph', 'tsc']);\n\n/**\n * Classify one edge into its epistemic tier. `dstKind` is the destination node's\n * kind (used to tell an internal import from an external-package import); omit it\n * only when the destination is unknown, in which case imports fall back to\n * `declared` (the safer, less-assured label).\n */\nexport function classifyEpistemic(edge: GraphEdge, dstKind?: NodeKind): EpistemicTier {\n // A semantic resolver saw the concrete declaration — the strongest tier.\n if (SEMANTIC_RESOLVERS.has(edge.resolution)) return 'observed';\n\n switch (edge.kind) {\n case 'contains':\n // Direct syntactic containment from the parse tree — observed, not guessed.\n return 'observed';\n case 'import':\n // Resolved to a real file in the corpus is observed; a bare external\n // package reference is only declared (we never see inside it).\n return dstKind === 'external' || dstKind === undefined ? 'declared' : 'observed';\n case 'test':\n case 'coverage':\n // Asserted by test structure / a coverage report, not verified against\n // the runtime call graph.\n return 'declared';\n default:\n // call / extends / implements / references resolved by the heuristic rung:\n // a symbol-name match with no reachability justification.\n return 'name-matched';\n }\n}\n\n/** Count edges by epistemic tier (deterministic key order). */\nexport function epistemicBreakdown(edges: GraphEdge[]): Record<EpistemicTier, number> {\n const out: Record<EpistemicTier, number> = { observed: 0, 'name-matched': 0, declared: 0 };\n for (const e of edges) {\n if (e.epistemic) out[e.epistemic]++;\n }\n return out;\n}\n","/**\n * Project-context ingest for semantic `vg ask` (Fusion robustness).\n *\n * Turns non-AST project files into graph nodes of kind `document` so agents can\n * answer the questions developers ask most often without grepping the tree:\n *\n * - Human docs: README, AGENTS.md, markdown/txt\n * - Env *examples* only (never live `.env`)\n * - Package manifests (package.json, go.mod, Cargo.toml, …)\n * - Docker / Compose\n * - CI workflows\n * - Build/tool config (tsconfig, turbo, vite, …)\n * - API contracts (OpenAPI, GraphQL, protobuf)\n * - Task runners (Makefile, Justfile)\n *\n * Bodies are secret-scrubbed and size-capped. Lockfiles and live secrets stay\n * out. Pure classification helpers are unit-tested; discovery respects the same\n * SKIP_DIRS / .gitignore rules as source discovery.\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport ignore, { type Ignore } from 'ignore';\nimport { redactSecrets } from '../core-open/utils/redact.js';\nimport { nodeId } from './ids.js';\nimport { isSkippedDirName, SKIP_FILES } from './discover.js';\nimport type { GraphNode } from '../schema.js';\n\n/** Soft cap on characters stored/embedded per document (keeps index snappy). */\nexport const DOC_BODY_MAX_CHARS = 8_000;\n/** Hard cap on bytes we will open for a context file. */\nexport const DOC_FILE_MAX_BYTES = 512 * 1024;\n/** Soft cap on document nodes per build (large monorepos). */\nexport const DOC_MAX_FILES = 600;\n\n// ── Document categories (signature / lang / importance) ────────────────────\n\nexport type DocCategory =\n | 'markdown'\n | 'text'\n | 'env-example'\n | 'manifest'\n | 'docker'\n | 'compose'\n | 'ci'\n | 'build-config'\n | 'api-contract'\n | 'task-runner'\n | 'workspace'\n | 'infra'\n | 'other-config';\n\nexport interface DiscoverDocsOptions {\n root: string;\n exclude?: string[];\n paths?: string[];\n maxFiles?: number;\n}\n\nexport interface DiscoveredDoc {\n rel: string;\n abs: string;\n /** @deprecated use category — kept as alias of category for older tests */\n kind: DocCategory;\n category: DocCategory;\n}\n\n// Human documentation\nconst DOC_EXTENSIONS = new Set(['.md', '.mdx', '.txt', '.rst', '.adoc']);\n\n// Env *examples* only\nconst ENV_EXAMPLE_NAMES = new Set([\n 'example.env',\n 'env.example',\n '.env.example',\n '.env.sample',\n '.env.template',\n '.env.development.example',\n '.env.local.example',\n 'dotenv.example',\n]);\n\n// Exact basenames → category (lowercase)\nconst EXACT_BASENAME: Record<string, DocCategory> = {\n // Manifests / package managers\n 'package.json': 'manifest',\n 'package.yaml': 'manifest',\n 'package.yml': 'manifest',\n 'pyproject.toml': 'manifest',\n 'setup.cfg': 'manifest',\n 'requirements.txt': 'manifest',\n 'requirements-dev.txt': 'manifest',\n 'pipfile': 'manifest',\n 'go.mod': 'manifest',\n 'go.work': 'manifest',\n 'cargo.toml': 'manifest',\n 'composer.json': 'manifest',\n 'gemfile': 'manifest',\n 'podfile': 'manifest',\n 'pubspec.yaml': 'manifest',\n 'mix.exs': 'manifest',\n 'build.gradle': 'manifest',\n 'build.gradle.kts': 'manifest',\n 'settings.gradle': 'manifest',\n 'settings.gradle.kts': 'manifest',\n 'pom.xml': 'manifest',\n 'project.clj': 'manifest',\n 'stack.yaml': 'manifest',\n 'package.swift': 'manifest',\n // Workspace / monorepo\n 'pnpm-workspace.yaml': 'workspace',\n 'pnpm-workspace.yml': 'workspace',\n 'lerna.json': 'workspace',\n 'nx.json': 'workspace',\n 'turbo.json': 'workspace',\n 'rush.json': 'workspace',\n 'workspace.json': 'workspace',\n // Docker\n dockerfile: 'docker',\n 'dockerfile.dev': 'docker',\n 'dockerfile.prod': 'docker',\n 'dockerfile.local': 'docker',\n containerfile: 'docker',\n // Compose\n 'docker-compose.yml': 'compose',\n 'docker-compose.yaml': 'compose',\n 'compose.yml': 'compose',\n 'compose.yaml': 'compose',\n 'docker-compose.dev.yml': 'compose',\n 'docker-compose.prod.yml': 'compose',\n 'docker-compose.override.yml': 'compose',\n // Task runners\n makefile: 'task-runner',\n gnumakefile: 'task-runner',\n justfile: 'task-runner',\n 'taskfile.yml': 'task-runner',\n 'taskfile.yaml': 'task-runner',\n rakefile: 'task-runner',\n // Build / tool config (exact)\n 'tsconfig.json': 'build-config',\n 'jsconfig.json': 'build-config',\n 'vite.config.ts': 'build-config',\n 'vite.config.js': 'build-config',\n 'vite.config.mjs': 'build-config',\n 'vitest.config.ts': 'build-config',\n 'vitest.config.js': 'build-config',\n 'jest.config.js': 'build-config',\n 'jest.config.ts': 'build-config',\n 'jest.config.cjs': 'build-config',\n 'webpack.config.js': 'build-config',\n 'webpack.config.ts': 'build-config',\n 'rollup.config.js': 'build-config',\n 'esbuild.config.js': 'build-config',\n 'next.config.js': 'build-config',\n 'next.config.mjs': 'build-config',\n 'next.config.ts': 'build-config',\n 'nuxt.config.ts': 'build-config',\n 'nuxt.config.js': 'build-config',\n 'astro.config.mjs': 'build-config',\n 'svelte.config.js': 'build-config',\n 'remix.config.js': 'build-config',\n 'angular.json': 'build-config',\n 'babel.config.js': 'build-config',\n 'babel.config.json': 'build-config',\n '.babelrc': 'build-config',\n '.babelrc.js': 'build-config',\n '.babelrc.json': 'build-config',\n 'eslint.config.js': 'build-config',\n 'eslint.config.mjs': 'build-config',\n 'eslint.config.cjs': 'build-config',\n 'eslint.config.ts': 'build-config',\n '.eslintrc': 'build-config',\n '.eslintrc.js': 'build-config',\n '.eslintrc.cjs': 'build-config',\n '.eslintrc.json': 'build-config',\n '.eslintrc.yml': 'build-config',\n '.prettierrc': 'build-config',\n '.prettierrc.js': 'build-config',\n '.prettierrc.json': 'build-config',\n '.prettierrc.yml': 'build-config',\n 'prettier.config.js': 'build-config',\n 'prettier.config.cjs': 'build-config',\n 'ruff.toml': 'build-config',\n '.ruff.toml': 'build-config',\n 'pytest.ini': 'build-config',\n 'tox.ini': 'build-config',\n 'mypy.ini': 'build-config',\n '.mypy.ini': 'build-config',\n 'phpunit.xml': 'build-config',\n 'phpunit.xml.dist': 'build-config',\n // CI exact\n 'jenkinsfile': 'ci',\n '.gitlab-ci.yml': 'ci',\n '.travis.yml': 'ci',\n 'azure-pipelines.yml': 'ci',\n 'buildkite.yml': 'ci',\n 'cloudbuild.yaml': 'ci',\n 'appveyor.yml': 'ci',\n 'circle.yml': 'ci',\n // Deploy / infra (root-level common names)\n 'vercel.json': 'infra',\n 'netlify.toml': 'infra',\n 'wrangler.toml': 'infra',\n 'wrangler.json': 'infra',\n 'wrangler.jsonc': 'infra',\n 'fly.toml': 'infra',\n 'railway.toml': 'infra',\n 'render.yaml': 'infra',\n 'app.yaml': 'infra',\n 'Procfile': 'infra',\n 'procfile': 'infra',\n 'heroku.yml': 'infra',\n 'serverless.yml': 'infra',\n 'serverless.yaml': 'infra',\n 'sam.yaml': 'infra',\n 'samconfig.toml': 'infra',\n 'cdk.json': 'infra',\n 'pulumi.yaml': 'infra',\n 'terraform.tf': 'infra',\n // Agent / project meta (also covered by .md extension)\n 'agents.md': 'markdown',\n 'claude.md': 'markdown',\n 'codeowners': 'other-config',\n '.nvmrc': 'other-config',\n '.node-version': 'other-config',\n '.python-version': 'other-config',\n 'runtime.txt': 'other-config',\n '.tool-versions': 'other-config',\n 'editorconfig': 'other-config',\n '.editorconfig': 'other-config',\n};\n\n// Prefix / pattern basenames\nconst BASENAME_PREFIX: Array<{ re: RegExp; category: DocCategory }> = [\n { re: /^dockerfile(\\.|$)/i, category: 'docker' },\n { re: /^docker-compose(\\.|$)/i, category: 'compose' },\n { re: /^compose\\.(ya?ml)$/i, category: 'compose' },\n { re: /^tsconfig(\\..+)?\\.json$/i, category: 'build-config' },\n { re: /^jsconfig(\\..+)?\\.json$/i, category: 'build-config' },\n { re: /^vite\\.config\\./i, category: 'build-config' },\n { re: /^vitest\\.config\\./i, category: 'build-config' },\n { re: /^jest\\.config\\./i, category: 'build-config' },\n { re: /^webpack\\.config\\./i, category: 'build-config' },\n { re: /^rollup\\.config\\./i, category: 'build-config' },\n { re: /^next\\.config\\./i, category: 'build-config' },\n { re: /^nuxt\\.config\\./i, category: 'build-config' },\n { re: /^astro\\.config\\./i, category: 'build-config' },\n { re: /^eslint\\.config\\./i, category: 'build-config' },\n { re: /^\\.eslintrc/i, category: 'build-config' },\n { re: /^openapi\\./i, category: 'api-contract' },\n { re: /^swagger\\./i, category: 'api-contract' },\n { re: /^requirements(-\\w+)?\\.txt$/i, category: 'manifest' },\n { re: /^dockerfile/i, category: 'docker' },\n];\n\n// Path patterns (posix relative)\nconst PATH_PATTERNS: Array<{ re: RegExp; category: DocCategory }> = [\n // GitHub Actions / workflows\n { re: /^\\.github\\/workflows\\/.+\\.ya?ml$/i, category: 'ci' },\n { re: /^\\.github\\/actions\\/.+/i, category: 'ci' },\n { re: /^\\.circleci\\/.+\\.ya?ml$/i, category: 'ci' },\n { re: /^\\.buildkite\\/.+/i, category: 'ci' },\n // Helm / k8s (values + charts — not every template blob)\n { re: /^charts\\/[^/]+\\/(chart\\.ya?ml|values.*\\.ya?ml)$/i, category: 'infra' },\n { re: /^deploy\\/.+\\.ya?ml$/i, category: 'infra' },\n { re: /^k8s\\/.+\\.ya?ml$/i, category: 'infra' },\n { re: /^kubernetes\\/.+\\.ya?ml$/i, category: 'infra' },\n { re: /^infra\\/.+\\.ya?ml$/i, category: 'infra' },\n { re: /^terraform\\/.+\\.tf$/i, category: 'infra' },\n // API contracts by path\n { re: /(^|\\/)(openapi|swagger)(\\.|\\/)/i, category: 'api-contract' },\n { re: /(^|\\/)api(-)?(spec|schema|contracts?)\\//i, category: 'api-contract' },\n];\n\n// Extensions for API / schema contracts\nconst API_EXTENSIONS = new Set(['.graphql', '.gql', '.proto', '.avsc', '.thrift']);\n\n// Importance by category (feeds hubs/ranking lightly; embed text carries meaning)\nconst IMPORTANCE: Record<DocCategory, number> = {\n markdown: 0.1,\n text: 0.06,\n 'env-example': 0.12,\n manifest: 0.16,\n docker: 0.14,\n compose: 0.15,\n ci: 0.14,\n 'build-config': 0.11,\n 'api-contract': 0.13,\n 'task-runner': 0.13,\n workspace: 0.14,\n infra: 0.12,\n 'other-config': 0.08,\n};\n\nfunction toPosix(p: string): string {\n return p.split(path.sep).join('/');\n}\n\nfunction buildRootIgnore(root: string, exclude: string[]): Ignore {\n const ig = ignore();\n const gitignorePath = path.join(root, '.gitignore');\n if (fs.existsSync(gitignorePath)) {\n try {\n ig.add(fs.readFileSync(gitignorePath, 'utf8'));\n } catch {\n /* ignore */\n }\n }\n if (exclude.length) ig.add(exclude);\n return ig;\n}\n\n/**\n * Classify a path as project-context (document) or not. Pure — no I/O.\n * Live secret env files return false.\n */\nexport function classifyProjectContext(relOrName: string): DocCategory | null {\n const rel = relOrName.replace(/\\\\/g, '/');\n const base = path.basename(rel);\n const baseLower = base.toLowerCase();\n\n // Never live secrets\n if (/^\\.env($|\\.)/i.test(base) && !isEnvExampleName(baseLower)) return null;\n // Never lockfiles / pnp (also in SKIP_FILES)\n if (SKIP_FILES.has(baseLower)) return null;\n\n if (isEnvExampleName(baseLower)) return 'env-example';\n\n const exact = EXACT_BASENAME[baseLower] ?? EXACT_BASENAME[base];\n if (exact) return exact;\n\n for (const { re, category } of BASENAME_PREFIX) {\n if (re.test(base)) return category;\n }\n\n for (const { re, category } of PATH_PATTERNS) {\n if (re.test(rel)) return category;\n }\n\n const ext = path.extname(baseLower);\n if (DOC_EXTENSIONS.has(ext)) return ext === '.txt' ? 'text' : 'markdown';\n if (API_EXTENSIONS.has(ext)) return 'api-contract';\n\n // OpenAPI/Swagger by extension + name\n if ((ext === '.yaml' || ext === '.yml' || ext === '.json') && /openapi|swagger|asyncapi/i.test(base)) {\n return 'api-contract';\n }\n\n // docker-compose variants with extra suffixes\n if (/^docker-compose\\..+\\.ya?ml$/i.test(base) || /^compose\\..+\\.ya?ml$/i.test(base)) {\n return 'compose';\n }\n\n return null;\n}\n\n/** @deprecated prefer classifyProjectContext — true when path is project context. */\nexport function isDocPath(relOrName: string): boolean {\n return classifyProjectContext(relOrName) !== null;\n}\n\nfunction isEnvExampleName(baseLower: string): boolean {\n if (ENV_EXAMPLE_NAMES.has(baseLower)) return true;\n if (/^(\\.)?env\\.(example|sample|template)(\\.|$)/i.test(baseLower)) return true;\n if (/^example\\.env/i.test(baseLower)) return true;\n return false;\n}\n\n\n/**\n * Discover project-context files under root. Deterministic order.\n * Never opens live secret env files or lockfiles.\n */\nexport function discoverDocs(options: DiscoverDocsOptions): DiscoveredDoc[] {\n const root = path.resolve(options.root);\n const maxFiles = options.maxFiles ?? DOC_MAX_FILES;\n const rootIg = buildRootIgnore(root, options.exclude ?? []);\n const scopeAbs = (options.paths?.length ? options.paths.map((p) => path.resolve(root, p)) : [root]).filter((p) =>\n fs.existsSync(p),\n );\n\n const found = new Map<string, DiscoveredDoc>();\n\n const consider = (abs: string): void => {\n if (found.size >= maxFiles) return;\n const rel = toPosix(path.relative(root, abs));\n if (!rel || rel.startsWith('..')) return;\n if (rootIg.ignores(rel)) return;\n const base = path.basename(abs);\n if (SKIP_FILES.has(base.toLowerCase())) return;\n const category = classifyProjectContext(rel);\n if (!category) return;\n try {\n const st = fs.statSync(abs);\n if (!st.isFile() || st.size > DOC_FILE_MAX_BYTES) return;\n if (st.size === 0) return;\n } catch {\n return;\n }\n found.set(rel, { rel, abs, kind: category, category });\n };\n\n const walk = (dir: string, depth: number): void => {\n if (found.size >= maxFiles || depth > 12) return;\n let entries: fs.Dirent[];\n try {\n entries = fs.readdirSync(dir, { withFileTypes: true });\n } catch {\n return;\n }\n for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {\n if (found.size >= maxFiles) return;\n const abs = path.join(dir, entry.name);\n const rel = toPosix(path.relative(root, abs));\n if (entry.isDirectory()) {\n if (isSkippedDirName(entry.name)) continue;\n // Workflows / .github must be walked even if other tools ignore them\n if (rel && rootIg.ignores(`${rel}/`) && !rel.startsWith('.github')) continue;\n walk(abs, depth + 1);\n } else if (entry.isFile()) {\n consider(abs);\n }\n }\n };\n\n for (const scope of scopeAbs) {\n try {\n const st = fs.statSync(scope);\n if (st.isDirectory()) walk(scope, 0);\n else if (st.isFile()) consider(scope);\n } catch {\n /* skip */\n }\n }\n\n return [...found.values()].sort((a, b) => a.rel.localeCompare(b.rel));\n}\n\n/**\n * Prepare a body optimized for retrieval: secret-scrub + optional smart trim\n * for huge manifests / OpenAPI so scripts & paths stay near the front.\n */\nexport function prepareDocBody(rel: string, raw: string, category: DocCategory): string {\n const scrubbed = redactSecrets(raw);\n if (scrubbed.length <= DOC_BODY_MAX_CHARS) return scrubbed;\n\n if (category === 'manifest' && path.basename(rel).toLowerCase() === 'package.json') {\n return summarizePackageJson(scrubbed);\n }\n if (category === 'api-contract' && /\\.(ya?ml|json)$/i.test(rel)) {\n // Prefer head (usually openapi version + info + paths start)\n return scrubbed.slice(0, DOC_BODY_MAX_CHARS);\n }\n if (category === 'ci') {\n return scrubbed.slice(0, DOC_BODY_MAX_CHARS);\n }\n return scrubbed.slice(0, DOC_BODY_MAX_CHARS);\n}\n\n/** Keep name, scripts, dependencies* for package.json when truncated. */\nfunction summarizePackageJson(raw: string): string {\n try {\n const o = JSON.parse(raw) as Record<string, unknown>;\n const keep: Record<string, unknown> = {};\n for (const k of [\n 'name',\n 'version',\n 'description',\n 'private',\n 'type',\n 'packageManager',\n 'engines',\n 'workspaces',\n 'scripts',\n 'dependencies',\n 'devDependencies',\n 'peerDependencies',\n 'optionalDependencies',\n 'main',\n 'bin',\n 'exports',\n ]) {\n if (o[k] !== undefined) keep[k] = o[k];\n }\n const s = JSON.stringify(keep, null, 2);\n return s.length <= DOC_BODY_MAX_CHARS ? s : s.slice(0, DOC_BODY_MAX_CHARS);\n } catch {\n return raw.slice(0, DOC_BODY_MAX_CHARS);\n }\n}\n\n/**\n * Build `document` graph nodes from discovered project-context files.\n */\nexport function documentNodesFromDocs(docs: DiscoveredDoc[]): GraphNode[] {\n const nodes: GraphNode[] = [];\n for (const d of docs) {\n let raw = '';\n try {\n raw = fs.readFileSync(d.abs, 'utf8');\n } catch {\n continue;\n }\n const category = d.category ?? d.kind;\n const scrubbed = prepareDocBody(d.rel, raw, category);\n if (!scrubbed.trim()) continue;\n\n const name = path.basename(d.rel);\n const qualifiedName = d.rel.replace(/\\\\/g, '/');\n const id = nodeId({\n kind: 'document',\n qualifiedName,\n file: qualifiedName,\n signature: category,\n });\n const lineCount = Math.max(1, scrubbed.split('\\n').length);\n const langTag =\n category === 'markdown'\n ? 'md'\n : category === 'env-example'\n ? 'env'\n : category === 'manifest'\n ? 'manifest'\n : category === 'docker' || category === 'compose'\n ? 'docker'\n : category === 'ci'\n ? 'ci'\n : category === 'api-contract'\n ? 'api'\n : category === 'build-config'\n ? 'config'\n : category === 'task-runner'\n ? 'task'\n : category === 'workspace'\n ? 'workspace'\n : category === 'infra'\n ? 'infra'\n : 'txt';\n\n nodes.push({\n id,\n kind: 'document',\n name,\n qualifiedName,\n file: qualifiedName,\n span: { start: 1, end: lineCount },\n lang: langTag,\n signature: `document:${category}`,\n doc: scrubbed,\n importance: IMPORTANCE[category] ?? 0.05,\n centrality: { degree: 0, pagerank: 0, betweenness: 0, eigenvector: 0 },\n area: -1,\n isHub: false,\n tested: null,\n });\n }\n return nodes.sort((a, b) => a.file.localeCompare(b.file) || a.id.localeCompare(b.id));\n}\n\n/** Exported for tests / docs: all exact basenames we treat as project context. */\nexport function projectContextExactBasenames(): string[] {\n return Object.keys(EXACT_BASENAME).sort((a, b) => a.localeCompare(b));\n}\n","import { redactSecrets } from '../../core-open/utils/redact.js';\nimport type { ToolchainSpan } from './types.js';\n\n/**\n * Shared helpers for the toolchain extractors. Everything here is pure and\n * deterministic — no clock, no randomness, no filesystem.\n */\n\n/** Hard cap on bytes an extractor will parse. Beyond this the file is skipped. */\nexport const TOOLCHAIN_FILE_MAX_BYTES = 2 * 1024 * 1024;\n\n/** Cap on nodes emitted from a single file — a generated 40k-line manifest is not worth unbounded graph. */\nexport const TOOLCHAIN_NODES_PER_FILE_MAX = 2_000;\n\n/** Cap on the length of a `doc` summary. */\nconst DOC_MAX_CHARS = 240;\n\n/**\n * Line-offset index for a source file: converts a byte offset to a 1-based\n * line number. Built once per file, then binary-searched — extracting a\n * thousand spans must not be quadratic in file size.\n */\nexport class LineIndex {\n /** Byte offset at which each line starts. */\n private readonly starts: number[];\n\n constructor(source: string) {\n const starts = [0];\n for (let i = 0; i < source.length; i++) {\n if (source.charCodeAt(i) === 10 /* \\n */) starts.push(i + 1);\n }\n this.starts = starts;\n }\n\n /** 1-based line number containing `offset`. */\n lineAt(offset: number): number {\n if (offset <= 0) return 1;\n let lo = 0;\n let hi = this.starts.length - 1;\n while (lo < hi) {\n const mid = (lo + hi + 1) >> 1;\n if (this.starts[mid] <= offset) lo = mid;\n else hi = mid - 1;\n }\n return lo + 1;\n }\n\n /** Span covering the byte range `[start, end)`. */\n span(start: number, end: number): ToolchainSpan {\n const s = this.lineAt(start);\n // `end` is exclusive; step back one byte so a range ending exactly at a\n // newline reports the line it ends on rather than the next, empty one.\n const e = this.lineAt(Math.max(start, end - 1));\n return { start: s, end: Math.max(s, e) };\n }\n\n get lineCount(): number {\n return this.starts.length;\n }\n}\n\n/**\n * Prepare a human-readable summary for storage.\n *\n * GUARDRAILS §1.1 is redact-at-ingest, not at display: IaC and CI files are\n * exactly where live credentials turn up, so every summary that reaches a node\n * passes through here before it is ever written to `graph.json`.\n */\nexport function safeDoc(text: string | undefined): string | undefined {\n if (!text) return undefined;\n const collapsed = text.replace(/\\s+/g, ' ').trim();\n if (!collapsed) return undefined;\n const redacted = redactSecrets(collapsed);\n return redacted.length > DOC_MAX_CHARS ? `${redacted.slice(0, DOC_MAX_CHARS - 1)}…` : redacted;\n}\n\n/**\n * Is this value a reference to a secret rather than a secret itself?\n *\n * Extractors record *references* (`secrets.NPM_TOKEN`, `${var.db_password}`,\n * a `secretKeyRef` name) because those are the useful graph edges. A literal\n * that merely looks secret-shaped is dropped rather than recorded.\n */\nexport function isSecretReference(value: string): boolean {\n return (\n /^\\$\\{\\{?\\s*secrets\\./i.test(value) ||\n /^\\$\\{?\\s*(var|local)\\./i.test(value) ||\n /^\\$\\{?[A-Z0-9_]+\\}?$/.test(value)\n );\n}\n\n/**\n * Normalise a container image reference into `{registry, repository, tag, digest}`.\n *\n * Deliberately does not apply Docker Hub's implicit `docker.io/library` default:\n * the linker matches what a repository actually wrote, and inventing a registry\n * would make `web:latest` in a Compose file stop matching `web:latest` in a\n * workflow's `docker build -t`.\n */\nexport interface ImageRef {\n /** The full reference as written. */\n raw: string;\n /** Everything before the tag/digest. */\n repository: string;\n tag?: string;\n digest?: string;\n}\n\nexport function parseImageRef(raw: string): ImageRef | null {\n const value = raw.trim();\n if (!value || /\\s/.test(value)) return null;\n // An expansion — `${{ env.IMAGE }}`, `{{ .Values.image }}`, or a bare\n // `$BASE` build arg — is not a resolvable image. Recording it would create a\n // node that matches nothing, so it is dropped rather than guessed at.\n if (value.includes('$') || value.includes('{{')) return null;\n\n const atIdx = value.lastIndexOf('@');\n let digest: string | undefined;\n let rest = value;\n if (atIdx > 0) {\n digest = value.slice(atIdx + 1);\n rest = value.slice(0, atIdx);\n }\n\n let tag: string | undefined;\n const colonIdx = rest.lastIndexOf(':');\n // A colon before the last `/` is a registry port (`localhost:5000/img`), not a tag.\n if (colonIdx > 0 && colonIdx > rest.lastIndexOf('/')) {\n tag = rest.slice(colonIdx + 1);\n rest = rest.slice(0, colonIdx);\n }\n if (!rest) return null;\n return { raw: value, repository: rest, tag, digest };\n}\n\n/**\n * The identity two image references are matched on by the linker: repository\n * plus digest when pinned, else repository plus tag. `latest` is treated as a\n * real tag — pretending it is absent makes unrelated images collide.\n */\nexport function imageIdentity(ref: ImageRef): string {\n if (ref.digest) return `${ref.repository}@${ref.digest}`;\n return ref.tag ? `${ref.repository}:${ref.tag}` : ref.repository;\n}\n\n/** Deterministic sort for drafts: by qualifiedName, then kind. */\nexport function byQualifiedName<T extends { qualifiedName: string; kind: string }>(a: T, b: T): number {\n return a.qualifiedName.localeCompare(b.qualifiedName, 'en') || a.kind.localeCompare(b.kind, 'en');\n}\n\n/** POSIX-normalise a repo-relative path (Windows hosts write `\\`). */\nexport function toPosix(rel: string): string {\n return rel.replace(/\\\\/g, '/');\n}\n\n/**\n * Resolve a relative path against a file's directory, POSIX-style, without\n * touching the filesystem. Returns null if the result escapes the repo root —\n * a Compose `build.context` of `../../../etc` must never produce a node\n * claiming to be a repository file.\n */\nexport function resolveRelative(fromFileRel: string, target: string): string | null {\n const base = toPosix(fromFileRel).split('/').slice(0, -1);\n const parts = toPosix(target).split('/');\n const out = [...base];\n for (const part of parts) {\n if (!part || part === '.') continue;\n if (part === '..') {\n if (!out.length) return null; // escaped the root\n out.pop();\n continue;\n }\n out.push(part);\n }\n const joined = out.join('/');\n return joined || null;\n}\n","import YAML from 'yaml';\nimport type { LineIndex } from './util.js';\nimport type { ToolchainSpan } from './types.js';\n\n/**\n * Shared YAML access for the toolchain extractors.\n *\n * Uses the `yaml` package rather than a tree-sitter grammar. That is a\n * deliberate departure from \"tree-sitter everywhere\": `yaml` is already an\n * audited dependency of this package, and it gives us three things a grammar\n * would force us to reimplement by hand —\n *\n * 1. **byte ranges on every node** (`node.range`), which is the whole reason\n * the plan preferred a CST over `serde`-style deserialisation;\n * 2. **multi-document streams** (`---`), which every non-trivial Kubernetes\n * manifest uses;\n * 3. **anchors, aliases and merge keys**, which Helm and Compose files use\n * heavily and which a raw CST would leave unresolved.\n *\n * Everything below is read-only and non-throwing: malformed YAML yields an\n * empty document list plus a warning, never an exception.\n */\n\n/** A parsed YAML document with the AST retained for range lookups. */\nexport interface YamlDoc {\n /** Plain-JS view, with aliases resolved. `null` when the document is empty. */\n value: unknown;\n /** The underlying AST document, for `rangeOf` lookups. */\n ast: YAML.Document.Parsed;\n /** 0-based index within the stream. */\n index: number;\n}\n\nexport interface YamlParseResult {\n docs: YamlDoc[];\n warnings: string[];\n}\n\n/**\n * Parse a YAML stream. Never throws.\n *\n * `maxAliasCount` is clamped: YAML's \"billion laughs\" alias-expansion bomb is a\n * real denial-of-service vector for a scanner that runs over untrusted\n * repositories, and the default limit is generous. A document that trips the\n * limit is reported as a warning and skipped, not expanded.\n */\nexport function parseYamlStream(rel: string, source: string): YamlParseResult {\n const warnings: string[] = [];\n let parsed: YAML.Document.Parsed[];\n try {\n parsed = YAML.parseAllDocuments(source, {\n // Parsing itself does not expand aliases — the bomb only detonates on\n // materialisation, so the alias budget is applied at `toJS` below.\n logLevel: 'silent',\n uniqueKeys: false,\n });\n } catch (err) {\n warnings.push(`${rel}: YAML parse failed (${(err as Error).message})`);\n return { docs: [], warnings };\n }\n\n const docs: YamlDoc[] = [];\n parsed.forEach((ast, index) => {\n if (ast.errors.length) {\n warnings.push(`${rel}: YAML document ${index + 1} has errors — skipped`);\n return;\n }\n let value: unknown;\n try {\n value = ast.toJS({ maxAliasCount: 100 });\n } catch (err) {\n warnings.push(`${rel}: YAML document ${index + 1} could not be materialised (${(err as Error).message})`);\n return;\n }\n if (value === null || value === undefined) return;\n docs.push({ value, ast, index });\n });\n\n return { docs, warnings };\n}\n\n/**\n * Byte range of the value at `path` within a document, as a line span.\n * Falls back to the document's own range when the path has no node — a span is\n * always better than no span, because it still anchors an editor decoration.\n */\nexport function spanAt(doc: YamlDoc, lines: LineIndex, path: (string | number)[]): ToolchainSpan {\n const node = path.length ? safeGetIn(doc.ast, path) : doc.ast.contents;\n const range = nodeRange(node) ?? nodeRange(doc.ast.contents);\n if (!range) return { start: 1, end: 1 };\n return lines.span(range[0], range[2] ?? range[1]);\n}\n\nfunction safeGetIn(ast: YAML.Document.Parsed, path: (string | number)[]): unknown {\n try {\n return ast.getIn(path, true);\n } catch {\n return undefined;\n }\n}\n\nfunction nodeRange(node: unknown): [number, number, number] | null {\n const range = (node as { range?: [number, number, number] } | null)?.range;\n return Array.isArray(range) ? range : null;\n}\n\n/** Read a nested value from a plain-JS document view. */\nexport function getPath(value: unknown, path: (string | number)[]): unknown {\n let current = value;\n for (const key of path) {\n if (current === null || typeof current !== 'object') return undefined;\n current = (current as Record<string | number, unknown>)[key];\n }\n return current;\n}\n\n/** Read a string, or undefined when absent/non-string. Numbers are stringified. */\nexport function getString(value: unknown, path: (string | number)[]): string | undefined {\n const found = getPath(value, path);\n if (typeof found === 'string') return found;\n if (typeof found === 'number' || typeof found === 'boolean') return String(found);\n return undefined;\n}\n\n/** Read an array, or an empty array when absent/non-array. */\nexport function getArray(value: unknown, path: (string | number)[]): unknown[] {\n const found = getPath(value, path);\n return Array.isArray(found) ? found : [];\n}\n\n/** Read a plain object's entries in a deterministic (sorted-key) order. */\nexport function getRecordEntries(value: unknown, path: (string | number)[]): [string, unknown][] {\n const found = getPath(value, path);\n if (!found || typeof found !== 'object' || Array.isArray(found)) return [];\n return Object.entries(found as Record<string, unknown>).sort(([a], [b]) => a.localeCompare(b, 'en'));\n}\n\n/**\n * Does this source look like a Go-templated Helm manifest?\n *\n * Helm templates are not valid YAML before rendering (`{{- if }}` lines break\n * the document), so the Kubernetes extractor must decline them and the Helm\n * extractor handles chart metadata and values instead.\n */\nexport function looksTemplated(source: string): boolean {\n return /\\{\\{-?\\s*(if|range|with|end|define|template|include|toYaml|\\.Values|\\.Release|\\.Chart)/.test(\n source,\n );\n}\n","import {\n LineIndex,\n parseImageRef,\n resolveRelative,\n safeDoc,\n TOOLCHAIN_NODES_PER_FILE_MAX,\n} from './util.js';\nimport { getArray, getPath, getRecordEntries, getString, parseYamlStream, spanAt } from './yaml.js';\nimport type {\n ToolchainEdgeDraft,\n ToolchainExtraction,\n ToolchainExtractor,\n ToolchainNodeDraft,\n} from './types.js';\n\n/**\n * Docker Compose extraction.\n *\n * Each entry under `services:` becomes a `resource` node. A service either\n * `builds_from` an image reference (`image:`) or points at a Dockerfile\n * (`build.context` + `build.dockerfile`) — the latter is the join the linker\n * uses to connect a Compose service to the Dockerfile node, and through it to\n * the source files that Dockerfile copies in.\n *\n * `depends_on` accepts both Compose forms: the short list form and the long\n * map form with `condition:`.\n */\n\n/** Default Dockerfile name when `build.dockerfile` is omitted. */\nconst DEFAULT_DOCKERFILE = 'Dockerfile';\n\nexport const composeExtractor: ToolchainExtractor = {\n format: 'compose',\n\n matches(rel, category) {\n if (category === 'compose') return true;\n return /(^|\\/)(docker-)?compose([.-][\\w.-]+)?\\.ya?ml$/i.test(rel);\n },\n\n extract(rel, source): ToolchainExtraction {\n const { docs, warnings } = parseYamlStream(rel, source);\n const lines = new LineIndex(source);\n const nodes: ToolchainNodeDraft[] = [];\n const edges: ToolchainEdgeDraft[] = [];\n\n const doc = docs[0];\n if (!doc) return { nodes, edges, warnings };\n\n const services = getRecordEntries(doc.value, ['services']);\n const declared = new Set(services.map(([name]) => `service:${name}`));\n\n for (const [name, service] of services) {\n if (nodes.length >= TOOLCHAIN_NODES_PER_FILE_MAX) {\n warnings.push(`${rel}: stopped at ${TOOLCHAIN_NODES_PER_FILE_MAX} nodes`);\n break;\n }\n const address = `service:${name}`;\n const image = getString(service, ['image']);\n const ports = getArray(service, ['ports']).map(String);\n\n nodes.push({\n kind: 'resource',\n name,\n qualifiedName: address,\n span: spanAt(doc, lines, ['services', name]),\n signature: 'compose.service',\n doc: safeDoc(\n [image && `image ${image}`, ports.length && `ports ${ports.join(', ')}`]\n .filter(Boolean)\n .join(', '),\n ),\n importance: 0.5,\n });\n\n // An `image:` reference — the join to a workload or a CI-built tag.\n if (image) {\n const ref = parseImageRef(image);\n if (ref) {\n nodes.push({\n kind: 'image',\n name: ref.repository.split('/').pop() ?? ref.repository,\n qualifiedName: `image:${ref.raw}`,\n span: spanAt(doc, lines, ['services', name, 'image']),\n signature: 'compose.image',\n doc: safeDoc(ref.tag ? `${ref.repository} tag ${ref.tag}` : ref.repository),\n importance: 0.3,\n });\n edges.push({ kind: 'builds_from', from: address, to: `image:${ref.raw}`, confidence: 1 });\n }\n }\n\n // A `build:` stanza — string shorthand or the long object form.\n const dockerfileRel = composeDockerfilePath(rel, service);\n if (dockerfileRel) {\n nodes.push({\n kind: 'image',\n name: dockerfileRel.split('/').pop() ?? dockerfileRel,\n qualifiedName: `dockerfile:${dockerfileRel}`,\n span: spanAt(doc, lines, ['services', name, 'build']),\n signature: 'compose.build',\n doc: safeDoc(`builds from ${dockerfileRel}`),\n importance: 0.4,\n });\n edges.push({\n kind: 'builds_from',\n from: address,\n to: `dockerfile:${dockerfileRel}`,\n confidence: 1,\n });\n }\n\n // `depends_on`: list form and map form.\n for (const target of composeDependsOn(service)) {\n const to = `service:${target}`;\n if (declared.has(to)) edges.push({ kind: 'depends_on', from: address, to, confidence: 1 });\n }\n\n // Published ports.\n for (const port of ports) {\n edges.push({ kind: 'exposes', from: address, to: `port:${port}`, confidence: 1 });\n }\n }\n\n // Port nodes for whatever `exposes` edges were emitted, so no edge dangles.\n const portTargets = new Set(\n edges.filter((e) => e.kind === 'exposes').map((e) => e.to),\n );\n for (const target of [...portTargets].sort()) {\n nodes.push({\n kind: 'property',\n name: target.slice('port:'.length),\n qualifiedName: target,\n span: { start: 1, end: 1 },\n signature: 'compose.port',\n importance: 0.1,\n });\n }\n\n return { nodes, edges, warnings };\n },\n};\n\n/** Repo-relative Dockerfile path for a service's `build:` stanza, if any. */\nfunction composeDockerfilePath(rel: string, service: unknown): string | null {\n const build = getPath(service, ['build']);\n if (build === undefined || build === null) return null;\n\n // Shorthand: `build: ./dir`\n if (typeof build === 'string') {\n return resolveRelative(rel, `${build}/${DEFAULT_DOCKERFILE}`);\n }\n if (typeof build !== 'object') return null;\n\n const context = getString(build, ['context']) ?? '.';\n const dockerfile = getString(build, ['dockerfile']) ?? DEFAULT_DOCKERFILE;\n // `dockerfile` is resolved relative to `context`, not to the compose file.\n return resolveRelative(rel, `${context}/${dockerfile}`);\n}\n\n/** Service names in a `depends_on`, in both supported shapes. */\nfunction composeDependsOn(service: unknown): string[] {\n const raw = getPath(service, ['depends_on']);\n if (Array.isArray(raw)) {\n return raw.filter((v): v is string => typeof v === 'string').sort();\n }\n if (raw && typeof raw === 'object') {\n return Object.keys(raw as Record<string, unknown>).sort();\n }\n return [];\n}\n","import {\n LineIndex,\n parseImageRef,\n resolveRelative,\n safeDoc,\n TOOLCHAIN_NODES_PER_FILE_MAX,\n toPosix,\n} from './util.js';\nimport type {\n ToolchainEdgeDraft,\n ToolchainExtraction,\n ToolchainExtractor,\n ToolchainNodeDraft,\n} from './types.js';\n\n/**\n * Dockerfile extraction — a deterministic scanner, no grammar.\n *\n * This follows the precedent set by `engine/sql-extract.ts` (a pure\n * deterministic extractor with no tree-sitter grammar) and is a deliberate\n * choice rather than a shortcut:\n *\n * - The Dockerfile format is line-oriented with a closed instruction set, an\n * escape-continuation rule and a `# syntax=` / `# escape=` directive\n * header. That is a scanner's natural shape.\n * - No Dockerfile grammar is published as a prebuilt `.wasm` by an upstream\n * we would be willing to add to the supply chain. The one npm package that\n * ships one is a single-maintainer package unrelated to the tree-sitter\n * org; adding it to an enterprise scanner's dependency set to save ~120\n * lines of transparent code is the wrong trade.\n * - The genuinely hard part of a Dockerfile — the shell inside `RUN` — is not\n * solved by a Dockerfile grammar either.\n *\n * ## What is extracted\n *\n * Each `FROM` opens a build stage (`image` node). `FROM x AS y` names it;\n * `COPY --from=` links stages. External base images become `image` nodes so the\n * linker can join a Dockerfile to the registry image a workload runs.\n */\n\n/** The instruction set we act on. Others are parsed and ignored. */\nconst INSTRUCTION = /^([A-Za-z][A-Za-z0-9_]*)\\s+([\\s\\S]*)$/;\n\ninterface LogicalLine {\n instruction: string;\n args: string;\n /** 1-based line the instruction starts on. */\n startLine: number;\n /** 1-based line the instruction ends on (after continuations). */\n endLine: number;\n}\n\n/**\n * Fold a Dockerfile into logical lines, honouring comments, blank lines and the\n * escape-character continuation (which `# escape=` can change to a backtick for\n * Windows containers).\n */\nexport function logicalLines(source: string): LogicalLine[] {\n const rawLines = source.split(/\\r?\\n/);\n let escapeChar = '\\\\';\n\n // Parser directives are only valid before the first non-comment line.\n for (const line of rawLines) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n if (!trimmed.startsWith('#')) break;\n const directive = /^#\\s*escape\\s*=\\s*(\\S)/i.exec(trimmed);\n if (directive) escapeChar = directive[1];\n }\n\n const out: LogicalLine[] = [];\n let buffer: string | null = null;\n let startLine = 0;\n\n for (let i = 0; i < rawLines.length; i++) {\n const raw = rawLines[i];\n const trimmed = raw.trim();\n\n // Comments and blank lines never continue an instruction: Docker strips\n // them between a continuation and the next fragment.\n if (!trimmed || trimmed.startsWith('#')) continue;\n\n const continues = trimmed.endsWith(escapeChar);\n const fragment = continues ? trimmed.slice(0, -1).trimEnd() : trimmed;\n\n if (buffer === null) {\n buffer = fragment;\n startLine = i + 1;\n } else {\n buffer += ` ${fragment}`;\n }\n\n if (!continues) {\n const match = INSTRUCTION.exec(buffer);\n if (match) {\n out.push({\n instruction: match[1].toUpperCase(),\n args: match[2].trim(),\n startLine,\n endLine: i + 1,\n });\n }\n buffer = null;\n }\n }\n\n // An unterminated continuation at EOF still yields its instruction.\n if (buffer !== null) {\n const match = INSTRUCTION.exec(buffer);\n if (match) {\n out.push({\n instruction: match[1].toUpperCase(),\n args: match[2].trim(),\n startLine,\n endLine: rawLines.length,\n });\n }\n }\n\n return out;\n}\n\n/** `FROM <image> [AS <name>]`, with `--platform=` flags stripped. */\nfunction parseFrom(args: string): { image: string; stage?: string } | null {\n const tokens = args.split(/\\s+/).filter(Boolean);\n const positional: string[] = [];\n for (const token of tokens) {\n if (token.startsWith('--')) continue; // --platform=…, --chmod=… etc.\n positional.push(token);\n }\n if (!positional.length) return null;\n const image = positional[0];\n // `AS name` is case-insensitive.\n const asIdx = positional.findIndex((t) => t.toUpperCase() === 'AS');\n const stage = asIdx > 0 && positional[asIdx + 1] ? positional[asIdx + 1] : undefined;\n return { image, stage };\n}\n\n/** `--from=<stage-or-image>` on a COPY instruction. */\nfunction parseCopyFrom(args: string): string | null {\n const match = /--from=(\\S+)/i.exec(args);\n return match ? match[1] : null;\n}\n\n/** Ports named by an EXPOSE instruction. */\nfunction parseExpose(args: string): string[] {\n return args\n .split(/\\s+/)\n .filter(Boolean)\n .filter((token) => !token.startsWith('--'));\n}\n\n/**\n * Concrete source paths a `COPY`/`ADD` reads from the build context.\n *\n * The last positional token is the destination, so it is excluded. Anything\n * that is not a plain path — a glob, a URL, a build-arg expansion, or a bare\n * `.` — is dropped: the cross-domain linker only wants paths it can match\n * exactly against files already in the graph, and a wrong match is worse than\n * no edge.\n */\nexport function copySourcePaths(args: string, hasFromFlag: boolean): string[] {\n if (hasFromFlag) return []; // sources come from another stage, not the repo\n const tokens = args.split(/\\s+/).filter(Boolean).filter((t) => !t.startsWith('--'));\n if (tokens.length < 2) return [];\n const sources = tokens.slice(0, -1);\n return sources\n .filter(\n (source) =>\n source !== '.' &&\n !source.includes('*') &&\n !source.includes('?') &&\n !source.includes('[') &&\n !source.includes('$') &&\n !/^https?:\\/\\//i.test(source),\n )\n .map((source) => source.replace(/^\\.\\//, ''))\n .sort();\n}\n\nexport const dockerfileExtractor: ToolchainExtractor = {\n format: 'dockerfile',\n\n matches(rel, category) {\n if (category === 'docker') return true;\n const base = toPosix(rel).split('/').pop()?.toLowerCase() ?? '';\n return base === 'dockerfile' || base === 'containerfile' || base.startsWith('dockerfile.');\n },\n\n extract(rel, source): ToolchainExtraction {\n const lines = new LineIndex(source);\n const nodes: ToolchainNodeDraft[] = [];\n const edges: ToolchainEdgeDraft[] = [];\n const warnings: string[] = [];\n\n const posixRel = toPosix(rel);\n const fileAddress = `dockerfile:${posixRel}`;\n\n // The Dockerfile itself — the anchor a Compose `build:` edge points at.\n nodes.push({\n kind: 'image',\n name: posixRel.split('/').pop() ?? posixRel,\n qualifiedName: fileAddress,\n span: { start: 1, end: Math.max(1, lines.lineCount) },\n signature: 'dockerfile',\n importance: 0.5,\n });\n\n const stages = new Map<string, string>(); // stage name (lowercased) → address\n /** stage address → candidate repo paths that stage copies from the context. */\n const copySources = new Map<string, Set<string>>();\n let stageIndex = 0;\n let currentStage: string | null = null;\n\n for (const line of logicalLines(source)) {\n if (nodes.length >= TOOLCHAIN_NODES_PER_FILE_MAX) {\n warnings.push(`${rel}: stopped at ${TOOLCHAIN_NODES_PER_FILE_MAX} nodes`);\n break;\n }\n\n switch (line.instruction) {\n case 'FROM': {\n const from = parseFrom(line.args);\n if (!from) break;\n const stageName = from.stage ?? String(stageIndex);\n const stageAddress = `${fileAddress}#${stageName}`;\n stages.set(stageName.toLowerCase(), stageAddress);\n currentStage = stageAddress;\n stageIndex++;\n\n nodes.push({\n kind: 'image',\n name: from.stage ?? `stage ${stageIndex - 1}`,\n qualifiedName: stageAddress,\n span: { start: line.startLine, end: line.endLine },\n signature: 'dockerfile.stage',\n doc: safeDoc(`from ${from.image}`),\n importance: 0.4,\n });\n edges.push({ kind: 'contains', from: fileAddress, to: stageAddress, confidence: 1 });\n\n // A base image that is another stage in this file is a stage edge;\n // otherwise it is an external registry image.\n const baseStage = stages.get(from.image.toLowerCase());\n if (baseStage && baseStage !== stageAddress) {\n edges.push({\n kind: 'builds_from',\n from: stageAddress,\n to: baseStage,\n confidence: 1,\n });\n } else {\n const ref = parseImageRef(from.image);\n // `FROM $BASE` / `FROM ${REGISTRY}/x` is a build-arg indirection we\n // cannot resolve without the build invocation — skip rather than\n // record a node that matches nothing.\n if (ref) {\n const imageAddress = `image:${ref.raw}`;\n nodes.push({\n kind: 'image',\n name: ref.repository.split('/').pop() ?? ref.repository,\n qualifiedName: imageAddress,\n span: { start: line.startLine, end: line.endLine },\n signature: 'dockerfile.base',\n doc: safeDoc(ref.tag ? `${ref.repository} tag ${ref.tag}` : ref.repository),\n importance: 0.3,\n });\n edges.push({\n kind: 'builds_from',\n from: stageAddress,\n to: imageAddress,\n confidence: 1,\n });\n }\n }\n break;\n }\n\n case 'COPY':\n case 'ADD': {\n const fromRef = parseCopyFrom(line.args);\n if (fromRef) {\n if (!currentStage) break;\n const target = stages.get(fromRef.toLowerCase());\n if (target && target !== currentStage) {\n edges.push({ kind: 'depends_on', from: currentStage, to: target, confidence: 1 });\n }\n break;\n }\n // Sources are read from the *build context*, which the Dockerfile\n // itself never states — it is chosen by whoever invokes the build.\n // The two conventions in the wild are \"context is the Dockerfile's\n // directory\" (`build: ./api`) and \"context is the repository root\"\n // (`docker build -f api/Dockerfile .`). Rather than guess, emit both\n // candidates: the linker keeps only paths that resolve to a file\n // already in the graph, so the wrong candidate costs nothing and the\n // right one is never missed.\n if (!currentStage) break;\n const forStage = copySources.get(currentStage) ?? new Set<string>();\n for (const source of copySourcePaths(line.args, false)) {\n const relativeToDockerfile = resolveRelative(posixRel, source);\n if (relativeToDockerfile) forStage.add(relativeToDockerfile);\n forStage.add(toPosix(source).replace(/^\\.\\//, ''));\n }\n if (forStage.size) copySources.set(currentStage, forStage);\n break;\n }\n\n case 'EXPOSE': {\n if (!currentStage) break;\n for (const port of parseExpose(line.args)) {\n const portAddress = `port:${port}`;\n nodes.push({\n kind: 'property',\n name: port,\n qualifiedName: portAddress,\n span: { start: line.startLine, end: line.endLine },\n signature: 'dockerfile.expose',\n importance: 0.1,\n });\n edges.push({ kind: 'exposes', from: currentStage, to: portAddress, confidence: 1 });\n }\n break;\n }\n\n default:\n break;\n }\n }\n\n const copySourcesByStage: Record<string, string[]> = {};\n for (const stage of [...copySources.keys()].sort()) {\n copySourcesByStage[stage] = [...(copySources.get(stage) ?? [])].sort();\n }\n\n return { nodes, edges, warnings, linkHints: { copySourcesByStage } };\n },\n};\n","import { LineIndex, parseImageRef, safeDoc, toPosix } from './util.js';\nimport { getArray, getRecordEntries, getString, parseYamlStream, spanAt } from './yaml.js';\nimport type {\n ToolchainEdgeDraft,\n ToolchainExtraction,\n ToolchainExtractor,\n ToolchainNodeDraft,\n} from './types.js';\n\n/**\n * Helm chart extraction.\n *\n * Helm templates under `templates/` are Go templates, not YAML — they do not\n * parse before rendering, and rendering them would mean running Helm. So this\n * extractor deliberately reads only the two files that *are* well-formed YAML\n * and carry the chart's identity:\n *\n * - `Chart.yaml` → the `chart` node, its version, and `depends_on` edges to\n * declared subchart dependencies;\n * - `values.yaml` → image references, which is what connects a chart to the\n * images a CI pipeline builds.\n *\n * That is a deliberate scope limit, not an oversight: claiming to understand an\n * unrendered template would mean inventing structure. What is extracted here is\n * declared fact.\n */\n\n/**\n * Common `values.yaml` shapes for an image. Helm has no schema, but these three\n * cover the overwhelming majority of charts in the wild, including the\n * `bitnami`/`stable` conventions.\n */\nfunction collectValuesImages(value: unknown, prefix: string[], out: Map<string, string[]>): void {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return;\n\n const repository = getString(value, ['repository']);\n const tag = getString(value, ['tag']);\n const registry = getString(value, ['registry']);\n if (repository) {\n const full = [registry, repository].filter(Boolean).join('/');\n const raw = tag ? `${full}:${tag}` : full;\n if (!out.has(raw)) out.set(raw, prefix);\n }\n\n // A plain `image: repo:tag` string.\n const direct = getString(value, ['image']);\n if (direct && parseImageRef(direct)) {\n if (!out.has(direct)) out.set(direct, [...prefix, 'image']);\n }\n\n for (const [key, child] of getRecordEntries(value, [])) {\n if (key === 'repository' || key === 'tag' || key === 'registry') continue;\n collectValuesImages(child, [...prefix, key], out);\n }\n}\n\nexport const helmExtractor: ToolchainExtractor = {\n format: 'helm',\n\n matches(rel) {\n const base = toPosix(rel).split('/').pop()?.toLowerCase() ?? '';\n if (base === 'chart.yaml' || base === 'chart.yml') return true;\n // Only a `values.yaml` that sits next to a chart is a Helm values file;\n // a bare `values.yaml` elsewhere is just config.\n return /(^|\\/)values([.-][\\w.-]+)?\\.ya?ml$/i.test(rel) && /(^|\\/)charts?\\//i.test(rel);\n },\n\n extract(rel, source): ToolchainExtraction {\n const { docs, warnings } = parseYamlStream(rel, source);\n const lines = new LineIndex(source);\n const nodes: ToolchainNodeDraft[] = [];\n const edges: ToolchainEdgeDraft[] = [];\n\n const doc = docs[0];\n if (!doc) return { nodes, edges, warnings };\n\n const base = toPosix(rel).split('/').pop()?.toLowerCase() ?? '';\n const isChartFile = base === 'chart.yaml' || base === 'chart.yml';\n\n if (isChartFile) {\n const name = getString(doc.value, ['name']);\n if (!name) return { nodes, edges, warnings };\n const version = getString(doc.value, ['version']);\n const appVersion = getString(doc.value, ['appVersion']);\n const address = `chart:${name}`;\n\n nodes.push({\n kind: 'chart',\n name,\n qualifiedName: address,\n span: spanAt(doc, lines, []),\n signature: 'helm.chart',\n doc: safeDoc(\n [version && `version ${version}`, appVersion && `app ${appVersion}`]\n .filter(Boolean)\n .join(', '),\n ),\n importance: 0.7,\n });\n\n // Declared subchart dependencies.\n for (const dependency of getArray(doc.value, ['dependencies'])) {\n const depName = getString(dependency, ['name']);\n if (!depName) continue;\n const depVersion = getString(dependency, ['version']);\n const depAddress = `chart:${depName}`;\n nodes.push({\n kind: 'chart',\n name: depName,\n qualifiedName: depAddress,\n span: spanAt(doc, lines, ['dependencies']),\n signature: 'helm.dependency',\n doc: safeDoc(depVersion ? `version ${depVersion}` : undefined),\n importance: 0.4,\n });\n edges.push({ kind: 'depends_on', from: address, to: depAddress, confidence: 1 });\n }\n\n return { nodes, edges, warnings };\n }\n\n // values.yaml — image references only.\n const images = new Map<string, string[]>();\n collectValuesImages(doc.value, [], images);\n for (const raw of [...images.keys()].sort()) {\n const ref = parseImageRef(raw);\n if (!ref) continue;\n nodes.push({\n kind: 'image',\n name: ref.repository.split('/').pop() ?? ref.repository,\n qualifiedName: `image:${ref.raw}`,\n span: spanAt(doc, lines, images.get(raw) ?? []),\n signature: 'helm.values.image',\n doc: safeDoc(ref.tag ? `${ref.repository} tag ${ref.tag}` : ref.repository),\n importance: 0.3,\n });\n }\n\n return { nodes, edges, warnings };\n },\n};\n","import { LineIndex, parseImageRef, safeDoc, TOOLCHAIN_NODES_PER_FILE_MAX } from './util.js';\nimport {\n getArray,\n getPath,\n getRecordEntries,\n getString,\n looksTemplated,\n parseYamlStream,\n spanAt,\n type YamlDoc,\n} from './yaml.js';\nimport type {\n ToolchainEdgeDraft,\n ToolchainExtraction,\n ToolchainExtractor,\n ToolchainNodeDraft,\n} from './types.js';\n\n/**\n * Kubernetes manifest extraction.\n *\n * Every document in the stream that carries both `apiVersion` and `kind`\n * becomes a node. Workload kinds (those with a pod template) additionally yield\n * `image` nodes for each container, which is what lets the linker join a\n * Deployment to the CI job that built its image.\n *\n * Selector→workload edges are matched *within the file*: a Service whose\n * `spec.selector` is a subset of a workload's pod labels `exposes` it. That is\n * a structural match on declared labels, not a guess, so it carries full\n * confidence — but only same-file, because a cross-file label match without\n * namespace resolution produces false pairs in a monorepo of many charts.\n */\n\n/** Workload kinds that own a pod template, and where that template lives. */\nconst WORKLOAD_TEMPLATE_PATHS: Record<string, (string | number)[]> = {\n Deployment: ['spec', 'template'],\n StatefulSet: ['spec', 'template'],\n DaemonSet: ['spec', 'template'],\n ReplicaSet: ['spec', 'template'],\n ReplicationController: ['spec', 'template'],\n Job: ['spec', 'template'],\n CronJob: ['spec', 'jobTemplate', 'spec', 'template'],\n Pod: [],\n};\n\n/** Container list paths within a pod spec, in extraction order. */\nconst CONTAINER_FIELDS = ['initContainers', 'containers', 'ephemeralContainers'] as const;\n\nfunction isKubernetesDoc(value: unknown): boolean {\n return typeof getString(value, ['apiVersion']) === 'string' && typeof getString(value, ['kind']) === 'string';\n}\n\n/** `namespace/kind/name` — unique within a cluster, and stable across edits. */\nfunction objectAddress(value: unknown): string | null {\n const kind = getString(value, ['kind']);\n const name = getString(value, ['metadata', 'name']);\n if (!kind || !name) return null;\n const namespace = getString(value, ['metadata', 'namespace']) ?? 'default';\n return `${namespace}/${kind}/${name}`;\n}\n\n/** The pod spec of a workload document, or null for non-workload kinds. */\nfunction podSpecPath(kind: string): (string | number)[] | null {\n const templatePath = WORKLOAD_TEMPLATE_PATHS[kind];\n if (!templatePath) return null;\n return [...templatePath, 'spec'];\n}\n\nexport const kubernetesExtractor: ToolchainExtractor = {\n format: 'kubernetes',\n\n matches(rel, category, head) {\n if (!/\\.ya?ml$/i.test(rel)) return false;\n // Helm templates are Go templates, not YAML — the Helm extractor owns them.\n if (looksTemplated(head)) return false;\n if (/(^|\\/)templates\\//i.test(rel)) return false;\n // The signature of a manifest, wherever it lives. Directory conventions\n // (`k8s/`, `deploy/`) are a hint, never the test: plenty of manifests live\n // elsewhere, and plenty of `deploy/*.yml` files are not manifests.\n return /(^|\\n)apiVersion:\\s*\\S/.test(head) && /(^|\\n)kind:\\s*\\S/.test(head);\n },\n\n extract(rel, source): ToolchainExtraction {\n const { docs, warnings } = parseYamlStream(rel, source);\n const lines = new LineIndex(source);\n const nodes: ToolchainNodeDraft[] = [];\n const edges: ToolchainEdgeDraft[] = [];\n\n /** address → pod-template labels, for same-file selector matching. */\n const workloadLabels = new Map<string, Record<string, string>>();\n\n for (const doc of docs) {\n if (nodes.length >= TOOLCHAIN_NODES_PER_FILE_MAX) {\n warnings.push(`${rel}: stopped at ${TOOLCHAIN_NODES_PER_FILE_MAX} nodes`);\n break;\n }\n if (!isKubernetesDoc(doc.value)) continue;\n const address = objectAddress(doc.value);\n if (!address) continue;\n\n const kind = getString(doc.value, ['kind']) as string;\n const name = getString(doc.value, ['metadata', 'name']) as string;\n const podPath = podSpecPath(kind);\n const isWorkload = podPath !== null;\n\n nodes.push({\n kind: isWorkload ? 'workload' : 'resource',\n name,\n qualifiedName: address,\n span: spanAt(doc, lines, []),\n signature: `k8s.${kind}`,\n doc: safeDoc(describeObject(doc.value, kind)),\n importance: isWorkload ? 0.6 : 0.4,\n });\n\n if (isWorkload) {\n const labels = readLabels(doc.value, [...(WORKLOAD_TEMPLATE_PATHS[kind] ?? []), 'metadata', 'labels']);\n if (Object.keys(labels).length) workloadLabels.set(address, labels);\n extractContainers(doc, lines, address, podPath, nodes, edges);\n }\n\n // Volume, ConfigMap and Secret *references* — names only, never values.\n for (const reference of referencedConfig(doc.value, podPath)) {\n edges.push({ kind: 'mounts', from: address, to: reference, confidence: 1 });\n }\n }\n\n // Service → workload, matched on declared labels within this file.\n for (const doc of docs) {\n if (getString(doc.value, ['kind']) !== 'Service') continue;\n const from = objectAddress(doc.value);\n if (!from) continue;\n const selector = readLabels(doc.value, ['spec', 'selector']);\n if (!Object.keys(selector).length) continue;\n for (const [address, labels] of [...workloadLabels].sort(([a], [b]) => a.localeCompare(b, 'en'))) {\n if (isSubset(selector, labels)) {\n edges.push({ kind: 'exposes', from, to: address, confidence: 1 });\n }\n }\n }\n\n return { nodes, edges, warnings };\n },\n};\n\n/** Container nodes plus their `builds_from` image edges. */\nfunction extractContainers(\n doc: YamlDoc,\n lines: LineIndex,\n workloadAddress: string,\n podPath: (string | number)[],\n nodes: ToolchainNodeDraft[],\n edges: ToolchainEdgeDraft[],\n): void {\n const seenImages = new Set<string>();\n for (const field of CONTAINER_FIELDS) {\n const containers = getArray(doc.value, [...podPath, field]);\n containers.forEach((container, index) => {\n const image = getString(container, ['image']);\n if (!image) return;\n const ref = parseImageRef(image);\n // A templated or malformed image reference is skipped rather than\n // recorded: a node named `${{ env.IMAGE }}` matches nothing and only\n // adds noise to the graph.\n if (!ref) return;\n if (seenImages.has(ref.raw)) return;\n seenImages.add(ref.raw);\n\n nodes.push({\n kind: 'image',\n name: ref.repository.split('/').pop() ?? ref.repository,\n qualifiedName: `image:${ref.raw}`,\n span: spanAt(doc, lines, [...podPath, field, index, 'image']),\n signature: 'k8s.image',\n doc: safeDoc(ref.tag ? `${ref.repository} tag ${ref.tag}` : ref.repository),\n importance: 0.3,\n });\n edges.push({\n kind: 'builds_from',\n from: workloadAddress,\n to: `image:${ref.raw}`,\n confidence: 1,\n });\n });\n }\n}\n\n/** ConfigMap/Secret/PVC names a pod spec references. Names only — never values. */\nfunction referencedConfig(value: unknown, podPath: (string | number)[] | null): string[] {\n if (!podPath) return [];\n const out = new Set<string>();\n\n for (const volume of getArray(value, [...podPath, 'volumes'])) {\n const configMap = getString(volume, ['configMap', 'name']);\n if (configMap) out.add(`ConfigMap/${configMap}`);\n const secret = getString(volume, ['secret', 'secretName']);\n if (secret) out.add(`Secret/${secret}`);\n const claim = getString(volume, ['persistentVolumeClaim', 'claimName']);\n if (claim) out.add(`PersistentVolumeClaim/${claim}`);\n }\n\n for (const field of CONTAINER_FIELDS) {\n for (const container of getArray(value, [...podPath, field])) {\n for (const envFrom of getArray(container, ['envFrom'])) {\n const configMap = getString(envFrom, ['configMapRef', 'name']);\n if (configMap) out.add(`ConfigMap/${configMap}`);\n const secret = getString(envFrom, ['secretRef', 'name']);\n if (secret) out.add(`Secret/${secret}`);\n }\n for (const env of getArray(container, ['env'])) {\n const configMap = getString(env, ['valueFrom', 'configMapKeyRef', 'name']);\n if (configMap) out.add(`ConfigMap/${configMap}`);\n const secret = getString(env, ['valueFrom', 'secretKeyRef', 'name']);\n if (secret) out.add(`Secret/${secret}`);\n }\n }\n }\n\n return [...out].sort();\n}\n\nfunction readLabels(value: unknown, path: (string | number)[]): Record<string, string> {\n const out: Record<string, string> = {};\n for (const [key, raw] of getRecordEntries(value, path)) {\n if (typeof raw === 'string') out[key] = raw;\n else if (typeof raw === 'number' || typeof raw === 'boolean') out[key] = String(raw);\n }\n return out;\n}\n\nfunction isSubset(selector: Record<string, string>, labels: Record<string, string>): boolean {\n const keys = Object.keys(selector);\n if (!keys.length) return false;\n return keys.every((key) => labels[key] === selector[key]);\n}\n\n/** A one-line human summary: replicas, container count, exposed ports. */\nfunction describeObject(value: unknown, kind: string): string {\n const parts: string[] = [];\n const replicas = getPath(value, ['spec', 'replicas']);\n if (typeof replicas === 'number') parts.push(`${replicas} replica${replicas === 1 ? '' : 's'}`);\n\n const podPath = podSpecPath(kind);\n if (podPath) {\n const count = CONTAINER_FIELDS.reduce(\n (sum, field) => sum + getArray(value, [...podPath, field]).length,\n 0,\n );\n if (count) parts.push(`${count} container${count === 1 ? '' : 's'}`);\n }\n\n if (kind === 'Service') {\n const type = getString(value, ['spec', 'type']);\n if (type) parts.push(type);\n const ports = getArray(value, ['spec', 'ports'])\n .map((p) => getString(p, ['port']))\n .filter(Boolean);\n if (ports.length) parts.push(`port ${ports.join(', ')}`);\n }\n\n return parts.join(', ');\n}\n","import type { Node } from 'web-tree-sitter';\nimport { toolchainParser } from './grammars.js';\nimport { LineIndex, safeDoc, TOOLCHAIN_NODES_PER_FILE_MAX } from './util.js';\nimport type {\n ToolchainEdgeDraft,\n ToolchainExtraction,\n ToolchainExtractor,\n ToolchainNodeDraft,\n} from './types.js';\n\n/**\n * Terraform / OpenTofu extraction over the HCL concrete syntax tree.\n *\n * This replaces regex scraping. The regexes it supersedes\n * (`core-open/scanners/terraform-scanner.ts`) used patterns of the form\n * `/required_providers\\s*\\{([^}]+)\\}/s`, where `[^}]+` stops at the *first*\n * closing brace — so the extremely common nested form\n *\n * required_providers {\n * aws = { source = \"hashicorp/aws\" } ← inner `}` ends the match\n * azurerm = { source = \"hashicorp/azurerm\" } ← never seen\n * }\n *\n * silently dropped every provider after the first. A CST has no such failure\n * mode: nesting is structure, not a character class.\n *\n * ## What is extracted\n *\n * | Block | Node kind | Address |\n * |---|---|---|\n * | `resource \"T\" \"N\"` | `resource` | `T.N` |\n * | `data \"T\" \"N\"` | `resource` | `data.T.N` |\n * | `module \"N\"` | `module` | `module.N` |\n * | `variable \"N\"` | `property` | `var.N` |\n * | `output \"N\"` | `property` | `output.N` |\n * | `provider \"N\"` | `package` | `provider.N` |\n *\n * Edges come from two sources, both declared rather than guessed: an explicit\n * `depends_on` list, and interpolation references (`subnet_id =\n * aws_subnet.main.id` ⇒ `aws_instance.web depends_on aws_subnet.main`). Both\n * are `depends_on`; a module block additionally `provisions` nothing until the\n * linker sees the module's own files, so we do not invent that edge here.\n */\n\n/**\n * Reference prefixes that name something other than a graph node: loop and\n * context builtins, plus `terraform`/`path` metadata. Referencing them is not\n * a dependency on anything we can point at.\n */\nconst BUILTIN_REF_PREFIXES = new Set([\n 'count',\n 'each',\n 'self',\n 'path',\n 'terraform',\n]);\n\n/** Block types that declare a named, addressable object. */\ntype BlockSpec = {\n kind: ToolchainNodeDraft['kind'];\n /** Number of quoted labels the block carries. */\n labels: 1 | 2;\n /** Build the Terraform address from the labels. */\n address: (labels: string[]) => string;\n signature: string;\n importance: number;\n};\n\nconst BLOCK_SPECS: Record<string, BlockSpec> = {\n resource: {\n kind: 'resource',\n labels: 2,\n address: ([type, name]) => `${type}.${name}`,\n signature: 'terraform.resource',\n importance: 0.5,\n },\n data: {\n kind: 'resource',\n labels: 2,\n address: ([type, name]) => `data.${type}.${name}`,\n signature: 'terraform.data',\n importance: 0.3,\n },\n module: {\n kind: 'module',\n labels: 1,\n address: ([name]) => `module.${name}`,\n signature: 'terraform.module',\n importance: 0.6,\n },\n variable: {\n kind: 'property',\n labels: 1,\n address: ([name]) => `var.${name}`,\n signature: 'terraform.variable',\n importance: 0.2,\n },\n output: {\n kind: 'property',\n labels: 1,\n address: ([name]) => `output.${name}`,\n signature: 'terraform.output',\n importance: 0.3,\n },\n provider: {\n kind: 'package',\n labels: 1,\n address: ([name]) => `provider.${name}`,\n signature: 'terraform.provider',\n importance: 0.4,\n },\n};\n\n/** Unquote an HCL `string_lit` node by reading its `template_literal` child. */\nfunction stringLitValue(node: Node): string {\n for (const child of node.namedChildren) {\n if (child?.type === 'template_literal') return child.text;\n }\n // An empty string literal (\"\") has no template_literal child.\n return '';\n}\n\n/** Top-level `block` nodes of an HCL document, in source order. */\nfunction topLevelBlocks(root: Node): Node[] {\n const out: Node[] = [];\n // config_file → body → block*\n for (const bodyCandidate of root.namedChildren) {\n if (!bodyCandidate) continue;\n const body = bodyCandidate.type === 'body' ? bodyCandidate : null;\n if (!body) continue;\n for (const child of body.namedChildren) {\n if (child?.type === 'block') out.push(child);\n }\n }\n return out;\n}\n\n/** The `body` child of a block, if present. */\nfunction blockBody(block: Node): Node | null {\n for (const child of block.namedChildren) {\n if (child?.type === 'body') return child;\n }\n return null;\n}\n\n/** Direct `attribute` children of a body, as `[name, expressionNode]`. */\nfunction attributes(body: Node): { name: string; expr: Node | null; node: Node }[] {\n const out: { name: string; expr: Node | null; node: Node }[] = [];\n for (const child of body.namedChildren) {\n if (child?.type !== 'attribute') continue;\n let name = '';\n let expr: Node | null = null;\n for (const part of child.namedChildren) {\n if (!part) continue;\n if (!name && part.type === 'identifier') name = part.text;\n else if (part.type === 'expression') expr = part;\n }\n if (name) out.push({ name, expr, node: child });\n }\n return out;\n}\n\n/** Direct nested `block` children of a body. */\nfunction nestedBlocks(body: Node): Node[] {\n const out: Node[] = [];\n for (const child of body.namedChildren) {\n if (child?.type === 'block') out.push(child);\n }\n return out;\n}\n\n/** A block's `identifier` (its type) and its quoted labels. */\nfunction blockHead(block: Node): { type: string; labels: string[] } {\n let type = '';\n const labels: string[] = [];\n for (const child of block.namedChildren) {\n if (!child) continue;\n if (!type && child.type === 'identifier') type = child.text;\n else if (child.type === 'string_lit') labels.push(stringLitValue(child));\n else if (child.type === 'body') break;\n }\n return { type, labels };\n}\n\n/**\n * Collect every Terraform address referenced inside an expression subtree.\n *\n * A reference in HCL is a `variable_expr` (the root name) followed by\n * `get_attr` siblings (the dotted path). `aws_subnet.main.id` yields\n * `aws_subnet` + `main` + `id`; the addressable prefix is `aws_subnet.main`.\n */\nfunction referencedAddresses(expr: Node | null, out: Set<string>): void {\n if (!expr) return;\n const stack: Node[] = [expr];\n while (stack.length) {\n const node = stack.pop();\n if (!node) continue;\n if (node.type === 'variable_expr') {\n const root = node.text;\n // Walk the get_attr chain that follows this variable_expr among its siblings.\n const parts: string[] = [root];\n let sibling = node.nextNamedSibling;\n while (sibling && sibling.type === 'get_attr') {\n const id = sibling.namedChildren.find((c) => c?.type === 'identifier');\n if (!id) break;\n parts.push(id.text);\n sibling = sibling.nextNamedSibling;\n }\n const address = terraformAddress(parts);\n if (address) out.add(address);\n // Do not descend into this variable_expr; its identifier child is the name.\n continue;\n }\n for (const child of node.namedChildren) {\n if (child) stack.push(child);\n }\n }\n}\n\n/**\n * Reduce a dotted reference path to the address of the thing it points at, or\n * null when it points at nothing we model.\n *\n * ['var','ami_id'] → 'var.ami_id'\n * ['aws_subnet','main','id'] → 'aws_subnet.main'\n * ['data','aws_ami','ubuntu','id'] → 'data.aws_ami.ubuntu'\n * ['module','vpc','vpc_id'] → 'module.vpc'\n * ['each','key'] → null (builtin)\n */\nfunction terraformAddress(parts: string[]): string | null {\n const [head, ...rest] = parts;\n if (!head || BUILTIN_REF_PREFIXES.has(head)) return null;\n if (head === 'var' || head === 'local') return rest.length ? `${head}.${rest[0]}` : null;\n if (head === 'module') return rest.length ? `module.${rest[0]}` : null;\n if (head === 'data') return rest.length >= 2 ? `data.${rest[0]}.${rest[1]}` : null;\n // A managed resource reference: `<type>.<name>[.attr…]`. A bare identifier\n // with no attribute is not an address (it is a local name in scope).\n return rest.length ? `${head}.${rest[0]}` : null;\n}\n\n/**\n * `required_providers` inside a `terraform` block. The nested shape is exactly\n * what the old regex could not read:\n *\n * terraform { required_providers { aws = { source = \"…\" version = \"…\" } } }\n */\nfunction extractRequiredProviders(\n terraformBlock: Node,\n lines: LineIndex,\n nodes: ToolchainNodeDraft[],\n seen: Set<string>,\n): void {\n const body = blockBody(terraformBlock);\n if (!body) return;\n for (const nested of nestedBlocks(body)) {\n const { type } = blockHead(nested);\n if (type !== 'required_providers') continue;\n const inner = blockBody(nested);\n if (!inner) continue;\n for (const attr of attributes(inner)) {\n let source: string | undefined;\n let version: string | undefined;\n\n const objectAttrs = attr.expr ? collectObjectAttributes(attr.expr) : [];\n if (objectAttrs.length) {\n // Modern form: `<localName> = { source = \"…\", version = \"…\" }`.\n for (const { key, value } of objectAttrs) {\n if (key === 'source') source = value;\n else if (key === 'version') version = value;\n }\n } else if (attr.expr) {\n // Legacy version-only shorthand: `<localName> = \"~> 2.0\"`. Still valid,\n // and common in pre-0.13 estates. The source is implicit — an\n // unqualified local name resolves to the `hashicorp` namespace.\n const literal = findFirst(attr.expr, 'string_lit');\n if (literal) {\n version = stringLitValue(literal);\n source = `hashicorp/${attr.name}`;\n }\n }\n\n const address = `provider.${attr.name}`;\n if (seen.has(address)) continue;\n seen.add(address);\n nodes.push({\n kind: 'package',\n name: attr.name,\n qualifiedName: address,\n span: lines.span(attr.node.startIndex, attr.node.endIndex),\n signature: 'terraform.required_provider',\n doc: safeDoc(\n [source && `source ${source}`, version && `version ${version}`].filter(Boolean).join(', '),\n ),\n importance: 0.4,\n });\n }\n }\n}\n\n/** `{ key = \"value\", … }` object literal → flat string pairs (string values only). */\nfunction collectObjectAttributes(expr: Node): { key: string; value: string }[] {\n const out: { key: string; value: string }[] = [];\n const stack: Node[] = [expr];\n while (stack.length) {\n const node = stack.pop();\n if (!node) continue;\n if (node.type === 'object_elem') {\n const key = node.namedChildren.find((c) => c?.type === 'expression');\n const rest = node.namedChildren.filter((c) => c?.type === 'expression');\n const valueNode = rest.length > 1 ? rest[1] : null;\n const keyText = key ? plainText(key) : '';\n const valueText = valueNode ? plainText(valueNode) : '';\n if (keyText) out.push({ key: keyText, value: valueText });\n continue;\n }\n for (const child of node.namedChildren) {\n if (child) stack.push(child);\n }\n }\n return out;\n}\n\n/** An expression's literal text, unquoted when it is a plain string. */\nfunction plainText(expr: Node): string {\n const lit = findFirst(expr, 'string_lit');\n if (lit) return stringLitValue(lit);\n return expr.text.trim();\n}\n\nfunction findFirst(node: Node, type: string): Node | null {\n const stack: Node[] = [node];\n while (stack.length) {\n const current = stack.pop();\n if (!current) continue;\n if (current.type === type) return current;\n for (const child of current.namedChildren) {\n if (child) stack.push(child);\n }\n }\n return null;\n}\n\nexport const terraformExtractor: ToolchainExtractor = {\n format: 'terraform',\n\n matches(rel) {\n const lower = rel.toLowerCase();\n return lower.endsWith('.tf') || lower.endsWith('.tofu');\n },\n\n async extract(rel, source): Promise<ToolchainExtraction> {\n const parser = await toolchainParser('hcl');\n if (!parser) {\n return {\n nodes: [],\n edges: [],\n warnings: [`${rel}: HCL grammar unavailable — no Terraform structure extracted`],\n };\n }\n\n const tree = parser.parse(source);\n if (!tree) return { nodes: [], edges: [], warnings: [`${rel}: HCL parse produced no tree`] };\n\n const lines = new LineIndex(source);\n const nodes: ToolchainNodeDraft[] = [];\n const edges: ToolchainEdgeDraft[] = [];\n const warnings: string[] = [];\n const declared = new Set<string>();\n // Referenced-but-not-declared-here addresses are kept so the linker can\n // join them across files; the framework drops edges whose target never\n // resolves, so a cross-file reference is not silently turned into a node.\n const pendingEdges: ToolchainEdgeDraft[] = [];\n\n if (tree.rootNode.hasError) {\n warnings.push(`${rel}: HCL parse recovered from a syntax error — extraction may be partial`);\n }\n\n for (const block of topLevelBlocks(tree.rootNode)) {\n if (nodes.length >= TOOLCHAIN_NODES_PER_FILE_MAX) {\n warnings.push(`${rel}: stopped at ${TOOLCHAIN_NODES_PER_FILE_MAX} nodes`);\n break;\n }\n const { type, labels } = blockHead(block);\n\n if (type === 'terraform') {\n extractRequiredProviders(block, lines, nodes, declared);\n continue;\n }\n\n const spec = BLOCK_SPECS[type];\n if (!spec || labels.length < spec.labels) continue;\n\n const address = spec.address(labels);\n if (declared.has(address)) continue;\n declared.add(address);\n\n const body = blockBody(block);\n const attrs = body ? attributes(body) : [];\n\n // A module's `source` / `version` is the one piece of a Terraform block\n // that behaves like a dependency, so it belongs in the summary.\n const summaryParts: string[] = [];\n for (const attr of attrs) {\n if (attr.name === 'source' || attr.name === 'version' || attr.name === 'description') {\n const value = attr.expr ? plainText(attr.expr) : '';\n if (value) summaryParts.push(`${attr.name} ${value}`);\n }\n }\n\n nodes.push({\n kind: spec.kind,\n name: labels[labels.length - 1] ?? type,\n qualifiedName: address,\n span: lines.span(block.startIndex, block.endIndex),\n signature: spec.signature,\n doc: safeDoc(summaryParts.join(', ')),\n importance: spec.importance,\n });\n\n if (!body) continue;\n\n // Explicit `depends_on = [...]` and implicit interpolation references.\n const references = new Set<string>();\n for (const attr of attrs) {\n referencedAddresses(attr.expr, references);\n }\n // Nested blocks (`lifecycle`, `provisioner`, dynamic bodies) carry\n // references too — a resource referenced only from inside `lifecycle`\n // is still a dependency.\n const nestedStack = nestedBlocks(body);\n while (nestedStack.length) {\n const nested = nestedStack.pop();\n if (!nested) continue;\n const innerBody = blockBody(nested);\n if (!innerBody) continue;\n for (const attr of attributes(innerBody)) referencedAddresses(attr.expr, references);\n nestedStack.push(...nestedBlocks(innerBody));\n }\n\n references.delete(address); // a self-reference is not a dependency\n for (const target of [...references].sort()) {\n pendingEdges.push({ kind: 'depends_on', from: address, to: target, confidence: 1 });\n }\n }\n\n // Keep only edges whose target is declared in this same file. Cross-file\n // Terraform references are real, but resolving them needs the whole\n // module's file set — that is the linker's job, not this extractor's.\n for (const edge of pendingEdges) {\n if (declared.has(edge.to)) edges.push(edge);\n }\n\n return { nodes, edges, warnings };\n },\n};\n","import {\n LineIndex,\n parseImageRef,\n safeDoc,\n TOOLCHAIN_NODES_PER_FILE_MAX,\n toPosix,\n} from './util.js';\nimport { getArray, getPath, getRecordEntries, getString, parseYamlStream, spanAt } from './yaml.js';\nimport type {\n ToolchainEdgeDraft,\n ToolchainExtraction,\n ToolchainExtractor,\n ToolchainNodeDraft,\n} from './types.js';\n\n/**\n * CI workflow extraction — GitHub Actions and GitLab CI.\n *\n * Jobs and steps become nodes; `needs` (Actions) and `needs`/`dependencies`\n * (GitLab) become `depends_on` edges; workflow triggers become `triggers`\n * edges from an event node.\n *\n * ## Secrets\n *\n * CI files are the single most common place a live credential is committed, so\n * this extractor is deliberately conservative (GUARDRAILS §1.1): it records the\n * *name* of a referenced secret (`secrets.NPM_TOKEN` → `secret:NPM_TOKEN`) and\n * never the value of anything. Literal `env:` values are not extracted at all —\n * only keys — because a literal is exactly the case where a token gets pasted.\n */\n\n/** Steps beyond this per job are summarised rather than enumerated. */\nconst MAX_STEPS_PER_JOB = 100;\n\n/** GitLab reserved top-level keys that are not jobs. */\nconst GITLAB_RESERVED = new Set([\n 'stages',\n 'variables',\n 'default',\n 'include',\n 'workflow',\n 'image',\n 'services',\n 'before_script',\n 'after_script',\n 'cache',\n 'pages',\n]);\n\nfunction isGitHubWorkflowPath(rel: string): boolean {\n return /(^|\\/)\\.github\\/workflows\\/[^/]+\\.ya?ml$/i.test(toPosix(rel));\n}\n\nfunction isGitLabCiPath(rel: string): boolean {\n const base = toPosix(rel).split('/').pop()?.toLowerCase() ?? '';\n return base === '.gitlab-ci.yml' || base === '.gitlab-ci.yaml';\n}\n\n/**\n * Image tags a shell script builds or pushes.\n *\n * Recognises `docker build -t X`, `docker buildx build --tag X`, `podman build\n * -t X` and `docker push X`. Only concrete tags are returned — a tag carrying a\n * `${…}` expansion is unresolvable without the runner's environment, and\n * recording it would create a node that matches nothing.\n */\nexport function imagesBuiltBy(script: string): string[] {\n const out = new Set<string>();\n const buildTag = /\\b(?:docker|podman)\\s+(?:buildx\\s+)?build\\b[^\\n]*?(?:-t|--tag)[=\\s]+(\\S+)/g;\n for (const match of script.matchAll(buildTag)) out.add(match[1]);\n const push = /\\b(?:docker|podman)\\s+push\\s+(\\S+)/g;\n for (const match of script.matchAll(push)) out.add(match[1]);\n return [...out].filter((tag) => !tag.includes('${') && !tag.includes('{{')).sort();\n}\n\n/**\n * Terraform working directories a shell script applies.\n *\n * `terraform apply` acts on the step's working directory unless `-chdir` says\n * otherwise, so an apply with neither yields `'.'` — the linker resolves that\n * against the step's declared `working-directory`.\n */\nexport function terraformAppliedDirs(script: string, workingDirectory?: string): string[] {\n const out = new Set<string>();\n const apply = /\\b(?:terraform|tofu)\\s+(?:-chdir=(\\S+)\\s+)?(?:apply|destroy)\\b/g;\n for (const match of script.matchAll(apply)) {\n out.add(match[1] ?? workingDirectory ?? '.');\n }\n return [...out].sort();\n}\n\n/** Does this script hand a Kubernetes manifest to the cluster? */\nexport function appliesKubernetes(script: string): boolean {\n return /\\bkubectl\\s+apply\\b/.test(script) || /\\bhelm\\s+(?:upgrade|install)\\b/.test(script);\n}\n\n/** Secret references inside an arbitrary subtree, as `secret:NAME`. */\nfunction collectSecretReferences(value: unknown, out: Set<string>): void {\n const stack: unknown[] = [value];\n while (stack.length) {\n const current = stack.pop();\n if (typeof current === 'string') {\n // `${{ secrets.NAME }}` — the name is the useful fact; the value never appears here.\n for (const match of current.matchAll(/secrets\\.([A-Za-z_][A-Za-z0-9_]*)/g)) {\n out.add(`secret:${match[1]}`);\n }\n continue;\n }\n if (Array.isArray(current)) {\n stack.push(...current);\n continue;\n }\n if (current && typeof current === 'object') {\n stack.push(...Object.values(current as Record<string, unknown>));\n }\n }\n}\n\nexport const githubActionsExtractor: ToolchainExtractor = {\n format: 'github-actions',\n\n matches(rel) {\n return isGitHubWorkflowPath(rel);\n },\n\n extract(rel, source): ToolchainExtraction {\n const { docs, warnings } = parseYamlStream(rel, source);\n const lines = new LineIndex(source);\n const nodes: ToolchainNodeDraft[] = [];\n const edges: ToolchainEdgeDraft[] = [];\n\n const doc = docs[0];\n if (!doc) return { nodes, edges, warnings };\n\n const workflowName = getString(doc.value, ['name']) ?? toPosix(rel).split('/').pop() ?? rel;\n const workflowAddress = `workflow:${toPosix(rel)}`;\n\n nodes.push({\n kind: 'job',\n name: workflowName,\n qualifiedName: workflowAddress,\n span: spanAt(doc, lines, []),\n signature: 'gha.workflow',\n doc: safeDoc(`GitHub Actions workflow`),\n importance: 0.6,\n });\n\n // Triggers. `on:` is either a string, a list, or a map of event → filter.\n // NB: YAML 1.1 parses a bare `on` key as the boolean `true`; the `yaml`\n // package follows the 1.2 core schema so `on` stays a string, but we accept\n // both so a 1.1-flavoured file still yields triggers.\n const onValue = getPath(doc.value, ['on']) ?? getPath(doc.value, [true as unknown as string]);\n for (const event of triggerEvents(onValue)) {\n const eventAddress = `event:${event}`;\n nodes.push({\n kind: 'property',\n name: event,\n qualifiedName: eventAddress,\n span: spanAt(doc, lines, ['on']),\n signature: 'gha.event',\n importance: 0.2,\n });\n edges.push({ kind: 'triggers', from: eventAddress, to: workflowAddress, confidence: 1 });\n }\n\n const jobs = getRecordEntries(doc.value, ['jobs']);\n const jobAddresses = new Set(jobs.map(([id]) => `job:${id}`));\n\n for (const [jobId, job] of jobs) {\n if (nodes.length >= TOOLCHAIN_NODES_PER_FILE_MAX) {\n warnings.push(`${rel}: stopped at ${TOOLCHAIN_NODES_PER_FILE_MAX} nodes`);\n break;\n }\n const jobAddress = `job:${jobId}`;\n const runsOn = getPath(job, ['runs-on']);\n const steps = getArray(job, ['steps']);\n\n nodes.push({\n kind: 'job',\n name: getString(job, ['name']) ?? jobId,\n qualifiedName: jobAddress,\n span: spanAt(doc, lines, ['jobs', jobId]),\n signature: 'gha.job',\n doc: safeDoc(\n [\n typeof runsOn === 'string' ? `runs-on ${runsOn}` : null,\n steps.length ? `${steps.length} step${steps.length === 1 ? '' : 's'}` : null,\n ]\n .filter(Boolean)\n .join(', '),\n ),\n importance: 0.5,\n });\n edges.push({ kind: 'contains', from: workflowAddress, to: jobAddress, confidence: 1 });\n\n // `needs:` — string or list.\n for (const need of asStringList(getPath(job, ['needs']))) {\n const to = `job:${need}`;\n if (jobAddresses.has(to)) {\n edges.push({ kind: 'depends_on', from: jobAddress, to, confidence: 1 });\n }\n }\n\n // Steps. `uses:` is the reusable-action reference; `run:` is a script the\n // linker later mines for `terraform apply` / `docker build`.\n steps.slice(0, MAX_STEPS_PER_JOB).forEach((step, index) => {\n const uses = getString(step, ['uses']);\n const run = getString(step, ['run']);\n const stepName =\n getString(step, ['name']) ?? uses ?? (run ? run.split('\\n')[0] : `step ${index + 1}`);\n const stepAddress = `${jobAddress}#${index}`;\n nodes.push({\n kind: 'step',\n name: stepName.slice(0, 80),\n qualifiedName: stepAddress,\n span: spanAt(doc, lines, ['jobs', jobId, 'steps', index]),\n signature: uses ? 'gha.step.uses' : 'gha.step.run',\n // `run:` bodies are shell scripts and are exactly where a token gets\n // pasted — safeDoc redacts, and we keep only the first line.\n doc: safeDoc(uses ? `uses ${uses}` : run?.split('\\n')[0]),\n importance: 0.2,\n });\n edges.push({ kind: 'contains', from: jobAddress, to: stepAddress, confidence: 1 });\n\n if (uses) {\n const actionAddress = `action:${uses}`;\n nodes.push({\n kind: 'external',\n name: uses.split('@')[0],\n qualifiedName: actionAddress,\n span: spanAt(doc, lines, ['jobs', jobId, 'steps', index, 'uses']),\n signature: 'gha.action',\n importance: 0.2,\n });\n edges.push({ kind: 'depends_on', from: stepAddress, to: actionAddress, confidence: 1 });\n }\n\n if (run) {\n const stepSpan = spanAt(doc, lines, ['jobs', jobId, 'steps', index]);\n const workingDirectory =\n getString(step, ['working-directory']) ?? getString(job, ['defaults', 'run', 'working-directory']);\n emitScriptEffects(rel, run, workingDirectory, jobAddress, stepSpan, nodes, edges);\n }\n });\n\n if (steps.length > MAX_STEPS_PER_JOB) {\n warnings.push(`${rel}: job ${jobId} has ${steps.length} steps — enumerated the first ${MAX_STEPS_PER_JOB}`);\n }\n\n // Secret *names* referenced anywhere in the job.\n const secrets = new Set<string>();\n collectSecretReferences(job, secrets);\n for (const secret of [...secrets].sort()) {\n nodes.push({\n kind: 'property',\n name: secret.slice('secret:'.length),\n qualifiedName: secret,\n span: spanAt(doc, lines, ['jobs', jobId]),\n signature: 'gha.secret-ref',\n importance: 0.2,\n });\n edges.push({ kind: 'mounts', from: jobAddress, to: secret, confidence: 1 });\n }\n }\n\n return { nodes, edges, warnings };\n },\n};\n\nexport const gitlabCiExtractor: ToolchainExtractor = {\n format: 'gitlab-ci',\n\n matches(rel) {\n return isGitLabCiPath(rel);\n },\n\n extract(rel, source): ToolchainExtraction {\n const { docs, warnings } = parseYamlStream(rel, source);\n const lines = new LineIndex(source);\n const nodes: ToolchainNodeDraft[] = [];\n const edges: ToolchainEdgeDraft[] = [];\n\n const doc = docs[0];\n if (!doc) return { nodes, edges, warnings };\n\n const pipelineAddress = `workflow:${toPosix(rel)}`;\n nodes.push({\n kind: 'job',\n name: 'GitLab CI',\n qualifiedName: pipelineAddress,\n span: spanAt(doc, lines, []),\n signature: 'gitlab.pipeline',\n importance: 0.6,\n });\n\n // Top-level keys that are neither reserved nor a `.hidden` template are jobs.\n const jobs = getRecordEntries(doc.value, []).filter(\n ([key, value]) =>\n !GITLAB_RESERVED.has(key) &&\n !key.startsWith('.') &&\n value !== null &&\n typeof value === 'object' &&\n !Array.isArray(value),\n );\n const jobAddresses = new Set(jobs.map(([id]) => `job:${id}`));\n\n for (const [jobId, job] of jobs) {\n if (nodes.length >= TOOLCHAIN_NODES_PER_FILE_MAX) {\n warnings.push(`${rel}: stopped at ${TOOLCHAIN_NODES_PER_FILE_MAX} nodes`);\n break;\n }\n const jobAddress = `job:${jobId}`;\n const stage = getString(job, ['stage']);\n const image = getString(job, ['image']) ?? getString(job, ['image', 'name']);\n\n nodes.push({\n kind: 'job',\n name: jobId,\n qualifiedName: jobAddress,\n span: spanAt(doc, lines, [jobId]),\n signature: 'gitlab.job',\n doc: safeDoc([stage && `stage ${stage}`, image && `image ${image}`].filter(Boolean).join(', ')),\n importance: 0.5,\n });\n edges.push({ kind: 'contains', from: pipelineAddress, to: jobAddress, confidence: 1 });\n\n // GitLab uses both `needs:` (DAG) and `dependencies:` (artifacts).\n for (const key of ['needs', 'dependencies'] as const) {\n for (const need of asStringList(getPath(job, [key]))) {\n const to = `job:${need}`;\n if (jobAddresses.has(to)) {\n edges.push({ kind: 'depends_on', from: jobAddress, to, confidence: 1 });\n }\n }\n }\n }\n\n return { nodes, edges, warnings };\n },\n};\n\n/**\n * Turn what a `run:` script *does* into nodes and edges, so the cross-domain\n * linker can join on node identity instead of re-parsing shell.\n *\n * These are the anchor points the linker needs: an image this job builds, a\n * Terraform directory it applies, and whether it talks to a cluster at all.\n */\nfunction emitScriptEffects(\n rel: string,\n script: string,\n workingDirectory: string | undefined,\n jobAddress: string,\n span: { start: number; end: number },\n nodes: ToolchainNodeDraft[],\n edges: ToolchainEdgeDraft[],\n): void {\n for (const tag of imagesBuiltBy(script)) {\n const ref = parseImageRef(tag);\n if (!ref) continue;\n const address = `image:${ref.raw}`;\n nodes.push({\n kind: 'image',\n name: ref.repository.split('/').pop() ?? ref.repository,\n qualifiedName: address,\n span,\n signature: 'ci.builds-image',\n doc: safeDoc(ref.tag ? `${ref.repository} tag ${ref.tag}` : ref.repository),\n importance: 0.4,\n });\n // The job creates this artifact.\n edges.push({ kind: 'provisions', from: jobAddress, to: address, confidence: 1 });\n }\n\n for (const dir of terraformAppliedDirs(script, workingDirectory)) {\n // `-chdir=` and `working-directory:` are both relative to the *workspace\n // root* (the checkout), never to the workflow file that names them — a\n // workflow at `.github/workflows/cd.yml` applying `-chdir=infra` means\n // `infra/`, not `.github/workflows/cd.yml/infra`.\n const resolved = normaliseWorkspacePath(dir);\n const address = `tfdir:${resolved}`;\n nodes.push({\n kind: 'resource',\n name: resolved,\n qualifiedName: address,\n span,\n signature: 'ci.terraform-apply',\n doc: safeDoc(`terraform apply in ${resolved}`),\n importance: 0.4,\n });\n edges.push({ kind: 'deploys', from: jobAddress, to: address, confidence: 1 });\n }\n}\n\n/**\n * Normalise a workspace-root-relative path from a CI file: strip a leading\n * `./`, collapse `.` segments and resolve `..` without escaping the root.\n * Returns `'.'` for the root itself.\n */\nfunction normaliseWorkspacePath(dir: string): string {\n const out: string[] = [];\n for (const part of toPosix(dir).split('/')) {\n if (!part || part === '.') continue;\n if (part === '..') {\n out.pop();\n continue;\n }\n out.push(part);\n }\n return out.join('/') || '.';\n}\n\n/** `on:` in its three shapes → a sorted list of event names. */\nfunction triggerEvents(value: unknown): string[] {\n if (typeof value === 'string') return [value];\n if (Array.isArray(value)) return value.filter((v): v is string => typeof v === 'string').sort();\n if (value && typeof value === 'object') return Object.keys(value as Record<string, unknown>).sort();\n return [];\n}\n\n/**\n * A field that is either a string, a list of strings, or a list of objects\n * carrying a `job` key (GitLab's `needs: [{job: build}]`), normalised to names.\n */\nfunction asStringList(value: unknown): string[] {\n if (typeof value === 'string') return [value];\n if (!Array.isArray(value)) return [];\n const out: string[] = [];\n for (const item of value) {\n if (typeof item === 'string') out.push(item);\n else if (item && typeof item === 'object') {\n const job = (item as Record<string, unknown>).job;\n if (typeof job === 'string') out.push(job);\n }\n }\n return out.sort();\n}\n","import { edgeId } from '../ids.js';\nimport type { GraphEdge, GraphNode } from '../../schema.js';\nimport { imageIdentity, parseImageRef, toPosix } from './util.js';\n\n/**\n * Cross-domain linker — Phase 2.1.\n *\n * The per-file extractors deliberately never resolve across files. This pass\n * runs once over the whole extracted set and joins the domains, which is what\n * turns a pile of parsed manifests into an answer to *\"which pipeline deploys\n * the service this code runs in?\"*\n *\n * ## Honesty contract\n *\n * Every edge produced here is an **inference**, not a declaration, and is\n * labelled as such:\n *\n * - `resolution: 'heuristic'` — always. An inferred `deploys` is not a\n * declared `import` and must never claim to be.\n * - `epistemic: 'name-matched'` — these joins match on a name (an image tag,\n * a path), which is exactly what that tier means.\n * - a calibrated `confidence`, lower where the evidence is weaker.\n *\n * Where the evidence is absent the edge is simply **not emitted**. The graph's\n * value is that it does not guess silently, so a repository that wires its\n * pipeline in a way we cannot see gets fewer edges rather than wrong ones.\n *\n * The pass is a pure function of its inputs — no module state, no filesystem,\n * no clock — so a rebuild produces byte-identical edges.\n */\n\n/** Confidence per join, by how directly the evidence supports it. */\nexport const LINK_CONFIDENCE = {\n /** Compose names the Dockerfile path outright. */\n composeBuild: 0.95,\n /** A CI job builds tag X; a workload runs tag X. Same string, both sides. */\n imageIdentity: 0.8,\n /** A CI job applies Terraform in a directory that contains these resources. */\n terraformDir: 0.75,\n /** A Dockerfile copies a path that exists in the repository. */\n dockerfileCopy: 0.6,\n} as const;\n\nexport interface LinkInput {\n /** Toolchain nodes from every extractor. */\n nodes: GraphNode[];\n /** Toolchain edges declared within individual files. */\n edges: GraphEdge[];\n /** Repo-relative source path → its `file` node id, for the Dockerfile join. */\n fileNodes: ReadonlyMap<string, string>;\n /**\n * Dockerfile build stage (by its node `qualifiedName`) → candidate repo paths\n * that stage copies from the build context.\n */\n stageCopySources: ReadonlyMap<string, string[]>;\n}\n\nexport interface LinkResult {\n edges: GraphEdge[];\n /** Per-join counts, for the build summary. */\n counts: Record<string, number>;\n}\n\n/** Join the extracted toolchain nodes across files. */\nexport function linkToolchain(input: LinkInput): LinkResult {\n const { nodes, edges, fileNodes, stageCopySources } = input;\n const out = new Map<string, GraphEdge>();\n const counts: Record<string, number> = {};\n\n const add = (\n kind: GraphEdge['kind'],\n src: string,\n dst: string,\n confidence: number,\n join: string,\n ): void => {\n if (src === dst) return;\n const id = edgeId(kind, src, dst);\n if (out.has(id)) return;\n out.set(id, {\n id,\n kind,\n src,\n dst,\n resolution: 'heuristic',\n confidence,\n epistemic: 'name-matched',\n });\n counts[join] = (counts[join] ?? 0) + 1;\n };\n\n // Already-declared edges, so we never emit a weaker duplicate of something an\n // extractor saw declared outright in one file.\n const declared = new Set(edges.map((e) => `${e.kind} ${e.src} ${e.dst}`));\n\n // ── Index the extracted nodes ────────────────────────────────────────────\n\n const dockerfileByPath = new Map<string, GraphNode>();\n const dockerfileRefs: GraphNode[] = [];\n const imageSites = new Map<string, GraphNode[]>();\n const terraformDirMarkers: GraphNode[] = [];\n const terraformNodesByDir = new Map<string, GraphNode[]>();\n const stagesByDockerfile = new Map<string, GraphNode[]>();\n\n for (const node of nodes) {\n const qn = node.qualifiedName;\n\n if (qn.startsWith('dockerfile:')) {\n const target = qn.slice('dockerfile:'.length);\n if (target.includes('#')) {\n push(stagesByDockerfile, target.split('#')[0], node);\n continue;\n }\n // The Dockerfile's own node lives *in* that file; anything else is a\n // reference to it (a Compose `build:` stanza, say).\n if (toPosix(node.file) === target) dockerfileByPath.set(target, node);\n else dockerfileRefs.push(node);\n continue;\n }\n\n if (qn.startsWith('image:')) {\n const ref = parseImageRef(qn.slice('image:'.length));\n if (ref) push(imageSites, imageIdentity(ref), node);\n continue;\n }\n\n if (qn.startsWith('tfdir:')) {\n terraformDirMarkers.push(node);\n continue;\n }\n\n if (node.lang === 'terraform') push(terraformNodesByDir, dirOf(toPosix(node.file)), node);\n }\n\n // ── Join 1: a Compose build reference → the real Dockerfile ──────────────\n\n for (const ref of dockerfileRefs) {\n const target = dockerfileByPath.get(ref.qualifiedName.slice('dockerfile:'.length));\n if (!target) continue; // the referenced Dockerfile is not in the corpus\n add('builds_from', ref.id, target.id, LINK_CONFIDENCE.composeBuild, 'compose→dockerfile');\n }\n\n // ── Join 2: image identity across files ─────────────────────────────────\n //\n // A CI job that builds `ghcr.io/acme/web:1.2.3` and a Deployment that runs\n // `ghcr.io/acme/web:1.2.3` are talking about the same artifact. The producer\n // side is whatever a `provisions` edge points at; the consumer side is\n // whatever a `builds_from` points at.\n\n const producerOf = new Map<string, string[]>();\n const consumerOf = new Map<string, string[]>();\n for (const edge of edges) {\n if (edge.kind === 'provisions') push(producerOf, edge.dst, edge.src);\n else if (edge.kind === 'builds_from') push(consumerOf, edge.dst, edge.src);\n }\n\n for (const identity of [...imageSites.keys()].sort((a, b) => a.localeCompare(b, 'en'))) {\n const sites = imageSites.get(identity) ?? [];\n if (sites.length < 2) continue; // a single mention is not a join\n\n const producers = new Set<string>();\n const consumers = new Set<string>();\n for (const site of sites) {\n for (const id of producerOf.get(site.id) ?? []) producers.add(id);\n for (const id of consumerOf.get(site.id) ?? []) consumers.add(id);\n }\n for (const producer of [...producers].sort()) {\n for (const consumer of [...consumers].sort()) {\n if (declared.has(`deploys ${producer} ${consumer}`)) continue;\n add('deploys', producer, consumer, LINK_CONFIDENCE.imageIdentity, 'ci→workload');\n }\n }\n\n // Join the image sites themselves, so navigating from a Compose mention of\n // an image reaches the Kubernetes one.\n const ordered = [...sites].sort((a, b) => a.id.localeCompare(b.id, 'en'));\n for (let i = 1; i < ordered.length; i++) {\n add('references', ordered[0].id, ordered[i].id, LINK_CONFIDENCE.imageIdentity, 'image↔image');\n }\n }\n\n // ── Join 3: a CI job that applies Terraform → the resources in that dir ──\n\n const terraformDirs = [...terraformNodesByDir.keys()].sort((a, b) => a.localeCompare(b, 'en'));\n for (const marker of [...terraformDirMarkers].sort((a, b) => a.id.localeCompare(b.id, 'en'))) {\n const dir = marker.qualifiedName.slice('tfdir:'.length);\n for (const resourceDir of terraformDirs) {\n // A root module's apply covers its own directory and below — never the\n // whole repository.\n if (resourceDir !== dir && !resourceDir.startsWith(`${dir}/`)) continue;\n for (const resource of terraformNodesByDir.get(resourceDir) ?? []) {\n // Only declarations that actually create infrastructure: a `variable`\n // or an `output` is not something a pipeline deploys.\n if (resource.signature !== 'terraform.resource' && resource.signature !== 'terraform.module') {\n continue;\n }\n add('deploys', marker.id, resource.id, LINK_CONFIDENCE.terraformDir, 'ci→terraform');\n }\n }\n }\n\n // ── Join 4: a Dockerfile stage → repository files it copies in ───────────\n //\n // The weakest join, and scoped accordingly: only paths that resolve to a file\n // already in the graph produce an edge. A bare `COPY . .` yields nothing — it\n // is true but says nothing.\n\n for (const file of [...stagesByDockerfile.keys()].sort((a, b) => a.localeCompare(b, 'en'))) {\n const stages = [...(stagesByDockerfile.get(file) ?? [])].sort((a, b) =>\n a.qualifiedName.localeCompare(b.qualifiedName, 'en'),\n );\n for (const stage of stages) {\n // Per-stage: a stage whose only COPY is `--from=` another stage reads\n // nothing from the repository and must get no source edges.\n const copied = stageCopySources.get(stage.qualifiedName);\n if (!copied?.length) continue;\n for (const path of copied) {\n const fileNodeId = fileNodes.get(toPosix(path));\n if (!fileNodeId) continue;\n add('depends_on', stage.id, fileNodeId, LINK_CONFIDENCE.dockerfileCopy, 'dockerfile→source');\n }\n }\n }\n\n return {\n edges: [...out.values()].sort(\n (a, b) =>\n a.kind.localeCompare(b.kind, 'en') ||\n a.src.localeCompare(b.src, 'en') ||\n a.dst.localeCompare(b.dst, 'en'),\n ),\n counts,\n };\n}\n\nfunction push<K, V>(map: Map<K, V[]>, key: K, value: V): void {\n const list = map.get(key);\n if (list) list.push(value);\n else map.set(key, [value]);\n}\n\n/** Directory portion of a POSIX path, or `'.'` at the root. */\nfunction dirOf(rel: string): string {\n const idx = rel.lastIndexOf('/');\n return idx === -1 ? '.' : rel.slice(0, idx);\n}\n","import * as fs from 'node:fs';\nimport { edgeId, nodeId } from '../ids.js';\nimport type { GraphEdge, GraphNode } from '../../schema.js';\nimport type { DiscoveredDoc } from '../docs-ingest.js';\nimport { composeExtractor } from './compose.js';\nimport { dockerfileExtractor } from './dockerfile.js';\nimport { helmExtractor } from './helm.js';\nimport { kubernetesExtractor } from './kubernetes.js';\nimport { terraformExtractor } from './terraform.js';\nimport { githubActionsExtractor, gitlabCiExtractor } from './workflows.js';\nimport { linkToolchain } from './link.js';\nimport { safeDoc, TOOLCHAIN_FILE_MAX_BYTES, toPosix } from './util.js';\nimport type { ToolchainExtractor, ToolchainFormat, ToolchainNodeDraft } from './types.js';\n\n/**\n * Toolchain extraction — the structural pass over the infrastructure, CI and\n * container corpus.\n *\n * ## Where this sits\n *\n * `docs-ingest.ts` already discovers and classifies exactly these files, and\n * turns each into one truncated `document` node for semantic ask. This module\n * runs over that same discovered set and adds *structure*: resources,\n * workloads, jobs, steps, images, charts, and the edges between them. The\n * document node stays — it is the semantic-ask surface — so nothing regresses.\n *\n * Critically, this does **not** register these files as source code. Adding\n * `.tf`/`.yaml` to `engine/languages.ts` would sweep them into the source\n * corpus, which drives `project-classification.ts` — and that picks the billing\n * tier. Extraction here leaves the source corpus, DriftScore and billing\n * untouched.\n *\n * ## Determinism\n *\n * Extractors are pure over `(rel, source)`. Files are processed in sorted path\n * order, nodes and edges are sorted before return, and ids are content-addressed\n * via the same `nodeId`/`edgeId` helpers the code graph uses. Identical corpus\n * in → byte-identical output.\n */\n\n/**\n * Registered extractors, in match order. Order matters: Helm must win over\n * Kubernetes for a chart's `values.yaml`, and Compose must win over Kubernetes\n * for a `compose.yaml` that happens to contain an `apiVersion` key.\n */\nconst EXTRACTORS: ToolchainExtractor[] = [\n terraformExtractor,\n dockerfileExtractor,\n githubActionsExtractor,\n gitlabCiExtractor,\n helmExtractor,\n composeExtractor,\n kubernetesExtractor,\n];\n\n/** Bytes of a file inspected for content heuristics. */\nconst HEAD_BYTES = 4096;\n\nexport interface ToolchainResult {\n nodes: GraphNode[];\n edges: GraphEdge[];\n warnings: string[];\n /** Per-format file counts, for the build summary and `ProjectProfile`. */\n counts: Record<string, number>;\n /** Per-join counts from the cross-domain linker. */\n linkCounts: Record<string, number>;\n}\n\nexport interface ExtractToolchainOptions {\n /**\n * Repo-relative source path → its `file` node id. Supplied by the build so\n * the cross-domain linker can join a Dockerfile to the files it copies in.\n * Omit to skip that join.\n */\n fileNodes?: ReadonlyMap<string, string>;\n}\n\nconst EMPTY_RESULT: ToolchainResult = {\n nodes: [],\n edges: [],\n warnings: [],\n counts: {},\n linkCounts: {},\n};\n\n/** Every registered format id, sorted. Exported for the profile/report layer. */\nexport function toolchainFormats(): ToolchainFormat[] {\n return [...new Set(EXTRACTORS.map((e) => e.format))].sort() as ToolchainFormat[];\n}\n\n/**\n * Pick the extractor for a discovered file, or null when none applies.\n * Exported so the LSP can answer \"is this file structurally understood?\"\n * without running a full extraction.\n */\nexport function extractorFor(doc: DiscoveredDoc, head: string): ToolchainExtractor | null {\n for (const extractor of EXTRACTORS) {\n try {\n if (extractor.matches(toPosix(doc.rel), doc.category ?? doc.kind, head)) return extractor;\n } catch {\n /* a matcher must never break discovery */\n }\n }\n return null;\n}\n\n/**\n * Run structural extraction over the discovered document set.\n *\n * Never throws: a malformed manifest, an unreadable file or a missing grammar\n * degrades to a warning and zero structure for that file. Infrastructure files\n * are frequently templated, partial or generated, and a scanner that dies on\n * one of them is a scanner nobody keeps installed.\n */\nexport async function extractToolchain(\n docs: DiscoveredDoc[],\n options: ExtractToolchainOptions = {},\n): Promise<ToolchainResult> {\n if (!docs.length) return EMPTY_RESULT;\n\n const nodes = new Map<string, GraphNode>();\n const edges = new Map<string, GraphEdge>();\n const warnings: string[] = [];\n const counts: Record<string, number> = {};\n const stageCopySources = new Map<string, string[]>();\n\n // Sorted path order keeps the output stable regardless of discovery order.\n const ordered = [...docs].sort((a, b) => toPosix(a.rel).localeCompare(toPosix(b.rel), 'en'));\n\n for (const doc of ordered) {\n let source: string;\n let head: string;\n try {\n const stat = fs.statSync(doc.abs);\n if (stat.size > TOOLCHAIN_FILE_MAX_BYTES) continue;\n source = fs.readFileSync(doc.abs, 'utf8');\n head = source.slice(0, HEAD_BYTES);\n } catch {\n continue; // unreadable — docs-ingest already tolerates this\n }\n\n const extractor = extractorFor(doc, head);\n if (!extractor) continue;\n\n const rel = toPosix(doc.rel);\n let extraction;\n try {\n extraction = await extractor.extract(rel, source);\n } catch (err) {\n warnings.push(`${rel}: ${extractor.format} extraction failed (${(err as Error).message})`);\n continue;\n }\n\n if (extraction.warnings?.length) warnings.push(...extraction.warnings);\n for (const [stage, paths] of Object.entries(extraction.linkHints?.copySourcesByStage ?? {})) {\n if (paths.length) stageCopySources.set(stage, paths);\n }\n if (!extraction.nodes.length) continue;\n\n counts[extractor.format] = (counts[extractor.format] ?? 0) + 1;\n\n // Drafts → graph nodes. `qualifiedName` is scoped by file, so two files\n // declaring `service:web` stay distinct nodes.\n const idByQualifiedName = new Map<string, string>();\n for (const draft of extraction.nodes) {\n const id = nodeId({\n kind: draft.kind,\n qualifiedName: draft.qualifiedName,\n file: rel,\n signature: draft.signature,\n });\n // First declaration of a name in a file wins; a repeat is the same thing.\n if (!idByQualifiedName.has(draft.qualifiedName)) {\n idByQualifiedName.set(draft.qualifiedName, id);\n }\n if (nodes.has(id)) continue;\n nodes.set(id, toGraphNode(id, draft, rel, extractor.format));\n }\n\n for (const draft of extraction.edges) {\n const src = idByQualifiedName.get(draft.from);\n const dst = idByQualifiedName.get(draft.to);\n // A dangling edge is dropped, never turned into a placeholder node: the\n // graph's value is that it does not invent things it cannot see.\n if (!src || !dst || src === dst) continue;\n const id = edgeId(draft.kind, src, dst);\n if (edges.has(id)) continue;\n edges.set(id, {\n id,\n kind: draft.kind,\n src,\n dst,\n // Structural extraction from a declaration in the file itself.\n resolution: 'heuristic',\n confidence: draft.confidence ?? 1,\n epistemic: 'declared',\n });\n }\n }\n\n const sortedNodes = [...nodes.values()].sort((a, b) => a.id.localeCompare(b.id, 'en'));\n const sortedEdges = [...edges.values()].sort(byEdgeOrder);\n\n // Phase 2.1 — join the domains across files. Runs once over the whole set.\n const linked = linkToolchain({\n nodes: sortedNodes,\n edges: sortedEdges,\n fileNodes: options.fileNodes ?? new Map(),\n stageCopySources,\n });\n\n // A linker edge never overwrites a declared one of the same identity: the\n // declaration is the stronger claim.\n const declaredIds = new Set(sortedEdges.map((e) => e.id));\n const allEdges = [...sortedEdges, ...linked.edges.filter((e) => !declaredIds.has(e.id))].sort(\n byEdgeOrder,\n );\n\n return {\n nodes: sortedNodes,\n edges: allEdges,\n warnings: [...new Set(warnings)].sort(),\n counts,\n linkCounts: linked.counts,\n };\n}\n\nfunction byEdgeOrder(a: GraphEdge, b: GraphEdge): number {\n return (\n a.kind.localeCompare(b.kind, 'en') ||\n a.src.localeCompare(b.src, 'en') ||\n a.dst.localeCompare(b.dst, 'en')\n );\n}\n\nfunction toGraphNode(\n id: string,\n draft: ToolchainNodeDraft,\n rel: string,\n format: ToolchainFormat,\n): GraphNode {\n return {\n id,\n kind: draft.kind,\n name: draft.name,\n qualifiedName: draft.qualifiedName,\n file: rel,\n span: draft.span,\n // `lang` is the format tag, so `--only` and the report can filter on it\n // without colliding with a source language id.\n lang: format,\n signature: draft.signature,\n doc: safeDoc(draft.doc),\n importance: draft.importance ?? 0.3,\n centrality: { degree: 0, pagerank: 0, betweenness: 0, eigenvector: 0 },\n area: -1,\n isHub: false,\n // Infrastructure has no notion of unit-test coverage; `null` is the\n // schema's \"not analyzable\", which is the honest answer.\n tested: null,\n };\n}\n\nexport type { ToolchainExtractor, ToolchainFormat } from './types.js';\n","/**\n * Partition TS/JS files into project shards for incremental / monorepo-safe\n * TypeScript Compiler API resolution. Each shard gets its own `createProgram`\n * so a large monorepo never pays for one giant Program over every package.\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\n\nexport interface TsFile {\n rel: string;\n abs: string;\n}\n\nexport interface TsProjectShard {\n /** Directory that owns the nearest tsconfig / package.json (repo-relative POSIX). */\n key: string;\n files: TsFile[];\n}\n\n/**\n * Group files by nearest ancestor that contains `tsconfig.json` /\n * `tsconfig.base.json` / `package.json`, falling back to the repo root.\n * Deterministic: shards sorted by key; files within a shard sorted by rel.\n */\nexport function shardTsProjects(root: string, files: TsFile[]): TsProjectShard[] {\n if (files.length === 0) return [];\n\n const cache = new Map<string, string>(); // abs dir → project key (rel posix)\n const byKey = new Map<string, TsFile[]>();\n\n for (const f of files) {\n const dir = path.dirname(f.abs);\n const key = nearestProjectKey(root, dir, cache);\n const list = byKey.get(key);\n if (list) list.push(f);\n else byKey.set(key, [f]);\n }\n\n return [...byKey.entries()]\n .sort((a, b) => a[0].localeCompare(b[0]))\n .map(([key, shardFiles]) => ({\n key,\n files: [...shardFiles].sort((a, b) => a.rel.localeCompare(b.rel)),\n }));\n}\n\nfunction nearestProjectKey(root: string, startDir: string, cache: Map<string, string>): string {\n const hit = cache.get(startDir);\n if (hit !== undefined) return hit;\n\n let dir = startDir;\n const rootAbs = path.resolve(root);\n while (true) {\n if (\n fs.existsSync(path.join(dir, 'tsconfig.json')) ||\n fs.existsSync(path.join(dir, 'tsconfig.base.json')) ||\n fs.existsSync(path.join(dir, 'package.json'))\n ) {\n const key = toPosix(path.relative(rootAbs, dir)) || '.';\n cache.set(startDir, key);\n return key;\n }\n if (dir === rootAbs || path.dirname(dir) === dir) {\n cache.set(startDir, '.');\n return '.';\n }\n dir = path.dirname(dir);\n }\n}\n\nfunction toPosix(p: string): string {\n return p.split(path.sep).join('/');\n}\n","/**\n * Stage wall-clock timers for build diagnostics.\n * Pure measurement — never enters the serialized graph artifact.\n */\n\nexport type StageName =\n | 'discover'\n | 'hash'\n | 'parse'\n | 'resolve'\n | 'tsc'\n | 'scip'\n | 'tests'\n /** Structural extraction over the infrastructure/CI corpus (engine/toolchain/). */\n | 'toolchain'\n | 'analyze'\n | 'facts'\n | 'ground'\n | 'index'\n | 'total';\n\nexport type StageTimings = Partial<Record<StageName, number>>;\n\nexport class StageTimer {\n private readonly marks = new Map<string, number>();\n private readonly durations: StageTimings = {};\n\n start(name: StageName): void {\n this.marks.set(name, nowMs());\n }\n\n end(name: StageName): number {\n const t0 = this.marks.get(name);\n if (t0 === undefined) return 0;\n const ms = Math.round((nowMs() - t0) * 1000) / 1000;\n this.durations[name] = ms;\n this.marks.delete(name);\n return ms;\n }\n\n /** Run `fn` under a named stage. */\n async measure<T>(name: StageName, fn: () => T | Promise<T>): Promise<T> {\n this.start(name);\n try {\n return await fn();\n } finally {\n this.end(name);\n }\n }\n\n snapshot(): StageTimings {\n return { ...this.durations };\n }\n}\n\nfunction nowMs(): number {\n return Number(process.hrtime.bigint() / 1000n) / 1000;\n}\n","/**\n * Build-time graph summaries for fast agent answers (hubs + blast radius).\n * Pure and deterministic: same graph → same summaries.\n */\n\nimport { indexFor } from './relations.js';\nimport type { EdgeKind, VgGraph } from '../schema.js';\n\nconst DEPEND_EDGES = new Set<EdgeKind>(['call', 'import', 'extends', 'implements', 'references']);\n\nexport interface HubBlastSummary {\n id: string;\n name: string;\n kind: string;\n file: string;\n importance: number;\n /** Direct dependents (depth 1). */\n direct: number;\n /** Dependents within depth 2 (includes direct). */\n depth2: number;\n /** Distinct files among depth-2 dependents. */\n files: number;\n tested: boolean | null;\n}\n\nexport interface GraphSummaries {\n hubs: HubBlastSummary[];\n}\n\nconst HUB_LIMIT = 40;\n\n/**\n * Precompute blast-radius counts for the top hubs (by importance).\n * Used by MCP/CLI for near-instant \"what breaks if this hub changes\" answers.\n */\nexport function buildSummaries(graph: VgGraph): GraphSummaries {\n const index = indexFor(graph);\n const candidates = graph.nodes\n .filter((n) => n.kind !== 'file' && n.kind !== 'external' && n.kind !== 'document')\n .sort((a, b) => b.importance - a.importance || a.qualifiedName.localeCompare(b.qualifiedName))\n .slice(0, HUB_LIMIT);\n\n const hubs: HubBlastSummary[] = candidates.map((n) => {\n const d1 = reverseDependents(index, n.id, 1);\n const d2 = reverseDependents(index, n.id, 2);\n const files = new Set<string>();\n for (const id of d2) {\n const node = index.node(id);\n if (node?.file) files.add(node.file);\n }\n return {\n id: n.id,\n name: n.qualifiedName,\n kind: n.kind,\n file: n.file,\n importance: n.importance,\n direct: d1.size,\n depth2: d2.size,\n files: files.size,\n tested: n.tested,\n };\n });\n\n // Stable order already by importance; re-sort for safety.\n hubs.sort((a, b) => b.importance - a.importance || a.name.localeCompare(b.name));\n return { hubs };\n}\n\nfunction reverseDependents(\n index: ReturnType<typeof indexFor>,\n rootId: string,\n maxDepth: number,\n): Set<string> {\n const affected = new Set<string>();\n let frontier = [rootId];\n for (let depth = 1; depth <= maxDepth; depth++) {\n const next: string[] = [];\n for (const id of frontier) {\n for (const e of index.in(id)) {\n if (!DEPEND_EDGES.has(e.kind)) continue;\n if (e.src === rootId || affected.has(e.src)) continue;\n affected.add(e.src);\n next.push(e.src);\n }\n }\n frontier = next;\n if (frontier.length === 0) break;\n }\n return affected;\n}\n","/**\n * Deterministic package-manifest extraction.\n *\n * Pulls declared dependencies from package.json and go.mod into the code map as\n * `package` nodes + `import` edges to external packages. Complements source-level\n * imports so hubs/impact/ask can see the dependency surface without lockfile noise\n * (lockfiles stay skipped by discover).\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport ignore, { type Ignore } from 'ignore';\nimport { nodeId, edgeId } from './ids.js';\nimport { isSkippedDirName } from './discover.js';\nimport type { GraphEdge, GraphNode } from '../schema.js';\n\nexport interface ManifestExtract {\n nodes: GraphNode[];\n edges: GraphEdge[];\n /** Number of package.json + go.mod files processed. */\n files: number;\n deps: number;\n}\n\nconst emptyNode = (\n partial: Pick<GraphNode, 'id' | 'kind' | 'name' | 'qualifiedName' | 'file' | 'lang'> & {\n span?: GraphNode['span'];\n },\n): GraphNode => ({\n ...partial,\n span: partial.span ?? { start: 1, end: 1 },\n importance: 0,\n centrality: { degree: 0, pagerank: 0, betweenness: 0, eigenvector: 0 },\n area: -1,\n isHub: false,\n tested: null,\n});\n\n/**\n * Walk the project for package.json / go.mod (respecting the same skip rules as\n * discover) and return package nodes + dependency edges. Pure over filesystem\n * content; stable sort on output.\n */\nexport function extractManifests(\n root: string,\n opts: { exclude?: string[]; paths?: string[] } = {},\n): ManifestExtract {\n const absRoot = path.resolve(root);\n const ig = buildRootIgnore(absRoot, opts.exclude ?? []);\n const scopes = (opts.paths?.length ? opts.paths : ['.'])\n .map((p) => path.resolve(absRoot, p))\n .filter((p) => fs.existsSync(p));\n\n const found = new Map<string, string>(); // rel → abs\n for (const scope of scopes) {\n walkManifests(absRoot, scope, ig, found);\n }\n\n const nodes = new Map<string, GraphNode>();\n const edges = new Map<string, GraphEdge>();\n let deps = 0;\n\n for (const rel of [...found.keys()].sort()) {\n const abs = found.get(rel)!;\n const base = path.posix.basename(rel);\n try {\n if (base === 'package.json') {\n deps += ingestPackageJson(rel, abs, nodes, edges);\n } else if (base === 'go.mod') {\n deps += ingestGoMod(rel, abs, nodes, edges);\n }\n } catch {\n /* unreadable / invalid — skip */\n }\n }\n\n return {\n nodes: [...nodes.values()].sort((a, b) => a.id.localeCompare(b.id)),\n edges: [...edges.values()].sort(\n (a, b) =>\n a.kind.localeCompare(b.kind) || a.src.localeCompare(b.src) || a.dst.localeCompare(b.dst),\n ),\n files: found.size,\n deps,\n };\n}\n\nfunction ingestPackageJson(\n rel: string,\n abs: string,\n nodes: Map<string, GraphNode>,\n edges: Map<string, GraphEdge>,\n): number {\n const raw = JSON.parse(fs.readFileSync(abs, 'utf8')) as {\n name?: string;\n dependencies?: Record<string, string>;\n peerDependencies?: Record<string, string>;\n optionalDependencies?: Record<string, string>;\n };\n const pkgName = (raw.name && String(raw.name).trim()) || path.posix.dirname(rel) || '.';\n const localId = nodeId({ kind: 'package', qualifiedName: pkgName, file: rel });\n nodes.set(\n localId,\n emptyNode({\n id: localId,\n kind: 'package',\n name: pkgName.includes('/') ? pkgName.split('/').pop()! : pkgName,\n qualifiedName: pkgName,\n file: rel,\n lang: 'json',\n }),\n );\n\n // Also a file node so the graph links the manifest file itself.\n const fileId = nodeId({ kind: 'file', qualifiedName: rel, file: rel });\n nodes.set(\n fileId,\n emptyNode({\n id: fileId,\n kind: 'file',\n name: path.posix.basename(rel),\n qualifiedName: rel,\n file: rel,\n lang: 'json',\n }),\n );\n addEdge(edges, 'contains', fileId, localId, 1.0);\n\n let n = 0;\n const depMaps = [raw.dependencies, raw.peerDependencies, raw.optionalDependencies];\n const names = new Set<string>();\n for (const m of depMaps) {\n if (!m || typeof m !== 'object') continue;\n for (const name of Object.keys(m)) {\n if (name) names.add(name);\n }\n }\n for (const name of [...names].sort()) {\n const extId = ensureExternal(nodes, name);\n addEdge(edges, 'import', localId, extId, 1.0);\n n++;\n }\n return n;\n}\n\nfunction ingestGoMod(\n rel: string,\n abs: string,\n nodes: Map<string, GraphNode>,\n edges: Map<string, GraphEdge>,\n): number {\n const text = fs.readFileSync(abs, 'utf8');\n let moduleName = path.posix.dirname(rel) || '.';\n const moduleMatch = /^\\s*module\\s+(\\S+)/m.exec(text);\n if (moduleMatch) moduleName = moduleMatch[1];\n\n const localId = nodeId({ kind: 'package', qualifiedName: moduleName, file: rel });\n nodes.set(\n localId,\n emptyNode({\n id: localId,\n kind: 'package',\n name: moduleName.split('/').pop() ?? moduleName,\n qualifiedName: moduleName,\n file: rel,\n lang: 'go',\n }),\n );\n const fileId = nodeId({ kind: 'file', qualifiedName: rel, file: rel });\n nodes.set(\n fileId,\n emptyNode({\n id: fileId,\n kind: 'file',\n name: path.posix.basename(rel),\n qualifiedName: rel,\n file: rel,\n lang: 'go',\n }),\n );\n addEdge(edges, 'contains', fileId, localId, 1.0);\n\n // require blocks and single-line requires (ignore replace/exclude).\n const reqNames = new Set<string>();\n const block = /require\\s*\\(([\\s\\S]*?)\\)/g;\n let bm: RegExpExecArray | null;\n while ((bm = block.exec(text)) !== null) {\n for (const line of bm[1].split('\\n')) {\n const m = /^\\s*(\\S+)\\s+v\\S+/.exec(line);\n if (m && !line.trim().startsWith('//')) reqNames.add(m[1]);\n }\n }\n const single = /^\\s*require\\s+(\\S+)\\s+v\\S+/gm;\n let sm: RegExpExecArray | null;\n while ((sm = single.exec(text)) !== null) reqNames.add(sm[1]);\n\n let n = 0;\n for (const name of [...reqNames].sort()) {\n const extId = ensureExternal(nodes, name);\n addEdge(edges, 'import', localId, extId, 1.0);\n n++;\n }\n return n;\n}\n\nfunction ensureExternal(nodes: Map<string, GraphNode>, name: string): string {\n const id = nodeId({ kind: 'external', qualifiedName: name, file: '' });\n if (!nodes.has(id)) {\n nodes.set(\n id,\n emptyNode({\n id,\n kind: 'external',\n name,\n qualifiedName: name,\n file: '',\n lang: 'external',\n }),\n );\n }\n return id;\n}\n\nfunction addEdge(\n edges: Map<string, GraphEdge>,\n kind: GraphEdge['kind'],\n src: string,\n dst: string,\n confidence: number,\n): void {\n if (src === dst) return;\n const id = edgeId(kind, src, dst);\n if (edges.has(id)) return;\n edges.set(id, {\n id,\n kind,\n src,\n dst,\n resolution: 'heuristic',\n confidence,\n epistemic: 'declared',\n count: 1,\n });\n}\n\nfunction buildRootIgnore(root: string, exclude: string[]): Ignore {\n const ig = ignore();\n const gitignorePath = path.join(root, '.gitignore');\n if (fs.existsSync(gitignorePath)) {\n try {\n ig.add(fs.readFileSync(gitignorePath, 'utf8'));\n } catch {\n /* ignore */\n }\n }\n if (exclude.length) ig.add(exclude);\n return ig;\n}\n\nfunction walkManifests(\n root: string,\n dir: string,\n ig: Ignore,\n found: Map<string, string>,\n): void {\n let entries: fs.Dirent[];\n try {\n entries = fs.readdirSync(dir, { withFileTypes: true });\n } catch {\n return;\n }\n for (const entry of entries) {\n const abs = path.join(dir, entry.name);\n const rel = path.relative(root, abs).split(path.sep).join('/');\n if (entry.isDirectory()) {\n if (isSkippedDirName(entry.name)) continue;\n if (rel && ig.ignores(`${rel}/`)) continue;\n walkManifests(root, abs, ig, found);\n } else if (entry.isFile()) {\n const base = entry.name;\n if (base !== 'package.json' && base !== 'go.mod') continue;\n if (rel && ig.ignores(rel)) continue;\n found.set(rel, abs);\n }\n }\n}\n","/**\n * Parallel content hashing for the build hash stage.\n * Deterministic: callers sort/merge results by path; workers only compute hashes.\n */\n\nimport * as fs from 'node:fs/promises';\nimport * as os from 'node:os';\nimport { hashBytes } from './hash.js';\n\nexport interface HashJob {\n rel: string;\n abs: string;\n}\n\nexport interface HashResult {\n rel: string;\n hash: string;\n /** False if the file could not be read. */\n ok: boolean;\n}\n\n/**\n * Hash many files with bounded concurrency. Order of results is not guaranteed;\n * sort by `rel` if you need stable order.\n */\nexport async function hashFilesParallel(\n jobs: HashJob[],\n concurrency?: number,\n): Promise<HashResult[]> {\n if (jobs.length === 0) return [];\n const limit = Math.max(\n 1,\n Math.min(concurrency ?? Math.max(1, (os.cpus()?.length ?? 4) * 2), jobs.length),\n );\n\n const out: HashResult[] = new Array(jobs.length);\n let next = 0;\n\n async function worker(): Promise<void> {\n for (;;) {\n const i = next++;\n if (i >= jobs.length) return;\n const job = jobs[i];\n try {\n const buf = await fs.readFile(job.abs);\n out[i] = { rel: job.rel, hash: hashBytes(buf), ok: true };\n } catch {\n out[i] = { rel: job.rel, hash: '', ok: false };\n }\n }\n }\n\n await Promise.all(Array.from({ length: limit }, () => worker()));\n return out;\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { discover, mergeExcludes, type DiscoveredFile } from './discover.js';\nimport { parseFiles } from './pool.js';\nimport { resolve } from './resolve.js';\nimport { buildModuleResolver } from './module-resolver.js';\nimport { assembleTsResult, tsWalkFiles, type TsFilePartial } from './ts-resolver.js';\nimport { decodeScipIndex, scipEdges } from './scip.js';\nimport { analyze, type AnalysisTier, type ClusterMode } from './analyze.js';\nimport { applyStaticTestLinkage } from './tests.js';\nimport { loadCoverage, applyCoverage } from './coverage.js';\nimport { buildFacts } from './facts.js';\nimport { groundGraph } from './grounding.js';\nimport { loadCache } from './cache.js';\nimport { ambientFingerprint, loadTscCache, tsConfigFingerprint, tscKeys } from './tsc-cache.js';\nimport {\n resolveLimits,\n checkMemoryBudget,\n formatBytes,\n ResourceLimitError,\n type ResourceLimits,\n} from './limits.js';\nimport { hashString, hashBytes, canonicalize, shortId } from './hash.js';\nimport { grammarSetVersion } from './grammars.js';\nimport { classifyEpistemic } from './epistemic.js';\nimport { discoverDocs, documentNodesFromDocs } from './docs-ingest.js';\nimport { extractToolchain } from './toolchain/index.js';\nimport { toolchainGrammarSetVersion } from './toolchain/grammars.js';\nimport { shardTsProjects } from './ts-projects.js';\nimport { writeGraphIndex } from './index-db.js';\nimport { StageTimer, type StageTimings } from './timing.js';\nimport { buildSummaries } from './summaries.js';\nimport { extractManifests } from './manifests.js';\nimport { hashFilesParallel } from './hash-files.js';\nimport { VERSION } from '../version.js';\nimport {\n SCHEMA_VERSION,\n type EdgeKind,\n type GraphEdge,\n type ResolverKind,\n type Toolchain,\n type VgGraph,\n} from '../schema.js';\nimport type { ScipIndex } from './scip.js';\nimport type { FileParse } from './types.js';\nimport type { ResolveResult } from './resolve.js';\nimport { fileRolesFromParses } from './ast-roles.js';\nimport type { AstRoleHit } from '../core-open/scanners/architecture/ast-roles.js';\n\nexport interface BuildOptions {\n /** Directory to build (default cwd). */\n root: string;\n /** Restrict to language ids. */\n only?: string[];\n /** Extra ignore globs (gitignore syntax). */\n exclude?: string[];\n /** Sub-paths to scope to. */\n paths?: string[];\n /** Worker count; 1 forces inline. */\n jobs?: number;\n /** Force single-threaded parsing. */\n inline?: boolean;\n /** Disable the incremental cache (full rebuild). */\n noCache?: boolean;\n /** Heavier open passes (recorded in provenance; Phase 1+ wires the analyses). */\n deep?: boolean;\n /** Community detection mode (default 'louvain'). */\n cluster?: ClusterMode;\n /** Coverage report paths (default: auto-detect lcov/istanbul). */\n coverage?: string[];\n /** Skip coverage ingestion. */\n noCoverage?: boolean;\n /** Skip grounding (free knowledge pack). Default: grounding on. */\n noGround?: boolean;\n /** Path to a SCIP index to ingest (default: auto-detect index.scip). */\n scip?: string;\n /** Skip SCIP ingestion even if an index is present. */\n noScip?: boolean;\n /** Skip the in-process TypeScript Compiler API resolver (heuristic floor only). */\n noTsc?: boolean;\n /**\n * Fast mode: skip tsc precise resolve (heuristic only). Useful for XL cold\n * builds when precision can wait for a focused rebuild.\n */\n fast?: boolean;\n /** Force analysis tier (default: auto by node count). */\n analysisTier?: AnalysisTier;\n /** Skip writing the SQLite serve index. */\n noIndex?: boolean;\n /** Pin the artifact timestamp for byte-deterministic output. */\n generatedAt?: string;\n /** Live progress during the parse phase (files done of total). */\n onParseProgress?: (done: number, total: number) => void;\n /** Override directory for grammar .wasm files (offline / air-gapped). */\n grammarsDir?: string;\n /** Resource-safeguard overrides (else VG_MAX_FILE_BYTES / VG_MAX_FILES /\n * VG_TSC_MAX_FILES / VG_MEMORY_BUDGET_MB env vars, else defaults). */\n limits?: Partial<ResourceLimits>;\n}\n\n/** Stat + content hash of one corpus file at build time. */\nexport interface FileStat {\n rel: string;\n size: number;\n mtimeMs: number;\n hash: string;\n}\n\nexport interface BuildResult {\n graph: VgGraph;\n timing: { totalMs: number; stages: StageTimings };\n reparsed: number;\n reused: number;\n /** Files skipped via mtime+size fingerprint (subset of reused). */\n statHits: number;\n totalFiles: number;\n /** Stat+hash of every file in the corpus — input for the freshness snapshot. */\n fileStats: FileStat[];\n resolveStats: ResolveResult['stats'];\n /** Present when the TypeScript Compiler API resolver ran (TS/JS files). */\n tsc?: {\n files: number;\n calls: number;\n jsx: number;\n heritage: number;\n resolved: number;\n shards?: number;\n /** Files whose checker output was reused from the tsc cache (change-scoped\n * downstream, gap-closure 2c). Subset of `files`. */\n reusedFiles?: number;\n };\n /** Present when a SCIP index was ingested. */\n scip?: { documents: number; references: number; resolved: number; tool?: string };\n /** SQLite index write result. */\n index?: { ok: boolean; path?: string; reason?: string };\n warnings: string[];\n /** Architecture role hits extracted during the parse already paid for. */\n fileRoles: AstRoleHit[];\n}\n\nexport async function buildGraph(options: BuildOptions): Promise<BuildResult> {\n const timer = new StageTimer();\n timer.start('total');\n const root = path.resolve(options.root);\n const exclude = mergeExcludes(root, options.exclude);\n timer.start('discover');\n const files = discover({\n root,\n only: options.only,\n exclude,\n paths: options.paths,\n });\n timer.end('discover');\n\n // Resource safeguards (see limits.ts): stop a pathological corpus before it\n // OOM-kills the process. Skips are deterministic functions of the input.\n const limits = resolveLimits(options.limits);\n if (limits.maxFiles > 0 && files.length > limits.maxFiles) {\n throw new ResourceLimitError(\n `graph build stopped: ${files.length.toLocaleString()} files exceed the ` +\n `${limits.maxFiles.toLocaleString()}-file limit. Scope the build (pass sub-paths, add ` +\n `--exclude globs, or --only <langs>), or set VG_MAX_FILES to raise the limit ` +\n `(0 disables it).`,\n );\n }\n checkMemoryBudget('discovery', limits.memoryBudgetMb);\n\n // The toolchain grammar set is a determinism input too: an HCL grammar change\n // can change the Terraform structure extracted, so it belongs in the\n // reproducibility fingerprint alongside the source grammars.\n const grammars = `${grammarSetVersion()}+${toolchainGrammarSetVersion()}`;\n const cache = loadCache(root, {\n toolVersion: VERSION,\n grammars,\n disabled: options.noCache,\n });\n\n // Hash every discovered file (mtime+size fast path → content hash) and split\n // into reuse vs reparse. The stat is taken *before* the read so a mid-read\n // edit shows up as a stat mismatch on the next freshness probe.\n timer.start('hash');\n const hashes = new Map<string, string>();\n const fileStats: FileStat[] = [];\n const toParse: DiscoveredFile[] = [];\n const reused: FileParse[] = [];\n const buildWarnings: string[] = [];\n let statHits = 0;\n const pendingHash: { file: DiscoveredFile; size: number; mtimeMs: number }[] = [];\n for (const file of files) {\n let stat: fs.Stats;\n try {\n stat = fs.statSync(file.abs);\n } catch {\n // Unreadable now (race/permissions) — skip; it just won't be in the graph.\n continue;\n }\n if (limits.maxFileBytes > 0 && stat.size > limits.maxFileBytes) {\n // Too large to parse (almost always generated/minified). It stays in\n // fileStats — under a size-derived sentinel hash, so the file is never\n // read into memory — because the freshness probe re-discovers it; were\n // it absent from the snapshot every probe would report phantom \"added\"\n // drift and auto-refresh would rebuild in a loop.\n fileStats.push({\n rel: file.rel,\n size: stat.size,\n mtimeMs: stat.mtimeMs,\n hash: hashString(`vg:oversize:${stat.size}`),\n });\n buildWarnings.push(\n `${file.rel}: skipped — ${formatBytes(stat.size)} exceeds the ` +\n `${formatBytes(limits.maxFileBytes)} per-file limit (set VG_MAX_FILE_BYTES to raise it, 0 to disable)`,\n );\n continue;\n }\n\n // Fast path: unchanged mtime+size → reuse parse without reading bytes.\n const byStat = options.noCache\n ? undefined\n : cache.getByStat(file.rel, stat.mtimeMs, stat.size);\n if (byStat) {\n hashes.set(file.rel, byStat.hash);\n if (byStat.parse.hash !== byStat.hash) byStat.parse.hash = byStat.hash;\n fileStats.push({\n rel: file.rel,\n size: stat.size,\n mtimeMs: stat.mtimeMs,\n hash: byStat.hash,\n });\n reused.push(byStat.parse);\n statHits++;\n continue;\n }\n\n // Defer content hashing to a parallel batch (below) for files that miss\n // the mtime fast path — big monorepos spend real time in sequential reads.\n pendingHash.push({ file, size: stat.size, mtimeMs: stat.mtimeMs });\n }\n\n // Parallel content hash for the pending set.\n if (pendingHash.length) {\n const jobs = pendingHash.map((p) => ({ rel: p.file.rel, abs: p.file.abs }));\n const results = await hashFilesParallel(jobs, options.jobs);\n const byRel = new Map(results.map((r) => [r.rel, r]));\n // Stable order: process pendingHash in discovery order (already sorted).\n for (const p of pendingHash) {\n const r = byRel.get(p.file.rel);\n if (!r || !r.ok) continue;\n hashes.set(p.file.rel, r.hash);\n fileStats.push({\n rel: p.file.rel,\n size: p.size,\n mtimeMs: p.mtimeMs,\n hash: r.hash,\n });\n const cached = cache.get(p.file.rel, r.hash);\n if (cached) {\n reused.push(cached);\n cache.set(p.file.rel, cached, { mtimeMs: p.mtimeMs, size: p.size });\n } else {\n toParse.push(p.file);\n }\n }\n }\n timer.end('hash');\n\n timer.start('parse');\n const parsedNew = await parseFiles(toParse, {\n jobs: options.jobs,\n inline: options.inline,\n onProgress: options.onParseProgress,\n grammarsDir: options.grammarsDir,\n memoryBudgetMb: limits.memoryBudgetMb,\n });\n timer.end('parse');\n checkMemoryBudget('parse', limits.memoryBudgetMb);\n for (const p of parsedNew) {\n // Never persist a failed parse: a transient parse-runtime crash (e.g. a\n // corrupted wasm heap) would otherwise poison the cache for that content\n // hash and every later build would reuse the empty parse instead of\n // re-parsing the file.\n if (p.defs.length === 0 && p.warnings?.some((w) => w.startsWith('parse failed:'))) continue;\n const st = fileStats.find((f) => f.rel === p.rel);\n cache.set(p.rel, p, st ? { mtimeMs: st.mtimeMs, size: st.size } : undefined);\n }\n\n // Persist the cache for the next incremental build.\n const currentRels = new Set(files.map((f) => f.rel));\n cache.prune(currentRels);\n cache.save();\n\n const parses = [...reused, ...parsedNew].sort((a, b) =>\n a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0,\n );\n\n const warnings = [...buildWarnings, ...parses.flatMap((p) => p.warnings ?? [])];\n\n // Resolve → nodes/edges. The module resolver follows relative imports plus\n // tsconfig path aliases and workspace-package names (so monorepo cross-package\n // imports resolve, not just relative ones).\n timer.start('resolve');\n const moduleResolver = buildModuleResolver(root, new Set(parses.map((p) => p.rel)));\n const resolved = resolve(parses, moduleResolver);\n timer.end('resolve');\n checkMemoryBudget('resolve', limits.memoryBudgetMb);\n\n // Package manifests (package.json / go.mod) → package nodes + dep import edges.\n // Runs after source resolve so package hubs participate in centrality/areas.\n const manifests = extractManifests(root, {\n exclude,\n paths: options.paths,\n });\n if (manifests.files > 0) {\n const byId = new Map(resolved.nodes.map((n) => [n.id, n]));\n for (const n of manifests.nodes) {\n if (!byId.has(n.id)) {\n byId.set(n.id, n);\n resolved.nodes.push(n);\n }\n }\n const edgeById = new Map(resolved.edges.map((e) => [e.id, e]));\n for (const e of manifests.edges) {\n if (!edgeById.has(e.id)) {\n edgeById.set(e.id, e);\n resolved.edges.push(e);\n }\n }\n resolved.nodes.sort((a, b) => a.id.localeCompare(b.id));\n resolved.edges.sort(\n (a, b) =>\n a.kind.localeCompare(b.kind) || a.src.localeCompare(b.src) || a.dst.localeCompare(b.dst),\n );\n }\n\n // Precise resolution rungs sit above the heuristic floor and are authoritative\n // for the files they cover (their relational edges replace the heuristic ones,\n // not merely augment them). Order: heuristic → tsc → scip. Runs before\n // test-linkage so it sharpens those edges too.\n const nodeFileById = new Map(resolved.nodes.map((n) => [n.id, n.file]));\n let edges = resolved.edges;\n const resolvers: ResolverKind[] = [...resolved.stats.resolvers];\n // Files a precise rung (tsc/scip) covered — their heuristic unknowns are\n // superseded by the authoritative resolver and must not be reported as unknown.\n const preciseCoveredFiles = new Set<string>();\n\n // Rung 1 — TypeScript Compiler API for TS/JS (default-on, in-process, no\n // external tool). The type checker resolves member/`this`/imported/aliased\n // calls and heritage that the heuristic structurally cannot.\n let tscStats: BuildResult['tsc'];\n // `hashes` holds exactly the parsed corpus — oversized (size-capped) files\n // are excluded here too, so the TS program never loads them.\n const skipTsc = options.noTsc || options.fast;\n let tsFiles = skipTsc\n ? []\n : files\n .filter((f) => (f.lang.id === 'ts' || f.lang.id === 'tsx' || f.lang.id === 'js') && hashes.has(f.rel))\n .map((f) => ({ rel: f.rel, abs: f.abs }));\n if (limits.tscMaxFiles > 0 && tsFiles.length > limits.tscMaxFiles) {\n // A ts.Program over the whole corpus is the largest single memory consumer\n // in the build. Past the cap, fall back to the heuristic floor (still a\n // complete graph, just less precise call resolution).\n warnings.push(\n `typescript resolver skipped — ${tsFiles.length.toLocaleString()} TS/JS files exceed the ` +\n `${limits.tscMaxFiles.toLocaleString()}-file limit; calls use the heuristic resolver ` +\n `(set VG_TSC_MAX_FILES to raise it, 0 to disable)`,\n );\n tsFiles = [];\n }\n timer.start('tsc');\n if (tsFiles.length) {\n // Shard by nearest tsconfig/package.json so monorepos never pay for one\n // giant Program over every package.\n const shards = shardTsProjects(root, tsFiles);\n let filesCovered = 0;\n let calls = 0;\n let jsx = 0;\n let heritage = 0;\n let resolvedCount = 0;\n let tscReusedFiles = 0;\n const coveredAll = new Set<string>();\n const preciseAll: GraphEdge[] = [];\n\n // Change-scoped downstream (gap-closure 2c): per-file checker results are\n // cached under a key covering the file's content, its transitive import\n // closure, and the shard's ambient surface — so a warm refresh re-walks\n // only the changed files and their reverse-dependency closure instead of\n // the whole corpus. assembleTsResult re-merges cached + fresh partials in\n // original file order, so the output is byte-identical to a full walk\n // (enforced by incremental-identity.test.ts).\n const tscCache = loadTscCache(root, { toolVersion: VERSION, disabled: options.noCache });\n const cfgFingerprint = tsConfigFingerprint(root);\n\n for (const shard of shards) {\n const ambientFiles = shard.files.filter((f) => tscCache.isAmbient(f.rel, hashes.get(f.rel)!, f.abs));\n const ambientHash = ambientFingerprint(\n ambientFiles.map((f) => ({ rel: f.rel, hash: hashes.get(f.rel)! })),\n cfgFingerprint,\n );\n const keys = tscKeys(shard.files.map((f) => f.rel), hashes, resolved.importsByFile, ambientHash);\n\n const partials = new Map<string, TsFilePartial>();\n const walkFiles: typeof shard.files = [];\n for (const f of shard.files) {\n const cached = tscCache.get(f.rel, keys.get(f.rel)!);\n if (cached) {\n partials.set(f.rel, cached);\n tscReusedFiles++;\n } else {\n walkFiles.push(f);\n }\n }\n // Ambient files must be in the program even when their own results are\n // cached — their global declarations shape checker answers everywhere.\n const walkRels = new Set(walkFiles.map((f) => f.rel));\n const extraRoots = ambientFiles.filter((f) => !walkRels.has(f.rel));\n const fresh = tsWalkFiles(root, walkFiles, shard.files, extraRoots, resolved.nodes);\n for (const [rel, partial] of fresh) {\n partials.set(rel, partial);\n tscCache.set(rel, hashes.get(rel)!, keys.get(rel)!, partial);\n }\n\n const res = assembleTsResult(shard.files.map((f) => f.rel), partials, resolved.nodes);\n if (res.stats.files === 0) continue;\n filesCovered += res.stats.files;\n calls += res.stats.calls;\n jsx += res.stats.jsx;\n heritage += res.stats.heritage;\n resolvedCount += res.stats.resolved;\n for (const f of res.coveredFiles) coveredAll.add(f);\n preciseAll.push(...res.edges);\n }\n\n tscCache.prune(new Set(tsFiles.map((f) => f.rel)));\n tscCache.save();\n\n if (filesCovered > 0) {\n edges = mergePreciseEdges(edges, preciseAll, coveredAll, nodeFileById);\n for (const f of coveredAll) preciseCoveredFiles.add(f);\n if (!resolvers.includes('tsc')) resolvers.unshift('tsc');\n tscStats = {\n files: filesCovered,\n calls,\n jsx,\n heritage,\n resolved: resolvedCount,\n shards: shards.length,\n reusedFiles: tscReusedFiles,\n };\n }\n checkMemoryBudget('typescript resolution', limits.memoryBudgetMb);\n }\n timer.end('tsc');\n\n // Rung 2 — a real SCIP index (if present), the most precise rung for any\n // language an indexer covers.\n const scip = options.noScip ? null : loadScipIndex(root, options.scip);\n let scipStats: BuildResult['scip'];\n if (scip) {\n const res = scipEdges(scip.index, resolved.nodes, toRepoRel);\n edges = mergePreciseEdges(edges, res.edges, res.coveredFiles, nodeFileById);\n for (const f of res.coveredFiles) preciseCoveredFiles.add(f);\n if (!resolvers.includes('scip')) resolvers.unshift('scip');\n scipStats = { ...res.stats, tool: scip.tool };\n }\n\n // Test-awareness: static test→code linkage, then runtime coverage if present.\n const linked = applyStaticTestLinkage(resolved.nodes, edges);\n let nodes = linked.nodes;\n const coverage = options.noCoverage ? null : loadCoverage(root, options.coverage);\n if (coverage) nodes = applyCoverage(nodes, coverage);\n\n // Documentation / example-env text nodes for semantic ask (not AST-parsed).\n const docs = discoverDocs({\n root,\n exclude,\n paths: options.paths,\n });\n for (const d of docs) {\n try {\n const st = fs.statSync(d.abs);\n const hash = hashBytes(fs.readFileSync(d.abs));\n hashes.set(d.rel, hash);\n fileStats.push({ rel: d.rel, size: st.size, mtimeMs: st.mtimeMs, hash });\n } catch {\n /* skip unreadable docs */\n }\n }\n const docNodes = documentNodesFromDocs(docs);\n if (docNodes.length) nodes = [...nodes, ...docNodes];\n\n // Structural extraction over the same discovered set (engine/toolchain/).\n // The `document` nodes above stay — they remain the semantic-ask surface —\n // and this adds the *structure*: resources, workloads, jobs, images, charts.\n //\n // NB: this reads `docs`, not the source corpus. Registering `.tf`/`.yaml` as\n // source languages would change file counts that feed billing tiers, so the\n // toolchain corpus is deliberately kept separate.\n timer.start('toolchain');\n const fileNodesByPath = new Map<string, string>();\n for (const node of nodes) {\n if (node.kind === 'file') fileNodesByPath.set(node.file.replace(/\\\\/g, '/'), node.id);\n }\n const toolchainResult = await extractToolchain(docs, { fileNodes: fileNodesByPath });\n if (toolchainResult.nodes.length) nodes = [...nodes, ...toolchainResult.nodes];\n timer.end('toolchain');\n\n // Analyse → centrality/areas/surprise (test/coverage edges excluded from these).\n timer.start('analyze');\n const graphEdges = toolchainResult.edges.length\n ? [...linked.edges, ...toolchainResult.edges]\n : linked.edges;\n const analysis = analyze(nodes, graphEdges, {\n cluster: options.cluster,\n tier: options.analysisTier,\n });\n timer.end('analyze');\n checkMemoryBudget('analysis', limits.memoryBudgetMb);\n\n const languages = [\n ...new Set([\n ...parses.map((p) => p.lang),\n ...docNodes.map((n) => n.lang),\n ...toolchainResult.nodes.map((n) => n.lang),\n ]),\n ].sort();\n const edgeKinds = [...new Set(analysis.edges.map((e) => e.kind))].sort() as EdgeKind[];\n const corpusHash = computeCorpusHash(parses, hashes);\n\n // Edge-level epistemic tier: stamp every edge with how it was resolved\n // (observed / name-matched / declared) so consumers can filter by assurance.\n // Pure function of the edge's fields + its destination node kind → deterministic.\n const nodeKindById = new Map(analysis.nodes.map((n) => [n.id, n.kind]));\n for (const e of analysis.edges) {\n e.epistemic = classifyEpistemic(e, nodeKindById.get(e.dst));\n }\n\n const toolchain = computeToolchain(grammars, resolvers);\n\n const generatedAt = options.generatedAt ?? new Date().toISOString();\n const testsCount = linked.testFiles.length;\n const untestedCount = analysis.nodes.filter(\n (n) => (n.kind === 'function' || n.kind === 'method') && n.tested === false,\n ).length;\n\n const graph: VgGraph = {\n schemaVersion: SCHEMA_VERSION,\n generatedAt,\n provenance: {\n tool: 'vg',\n version: VERSION,\n grammars: Object.fromEntries(languages.map((l) => [l, grammars])),\n resolver: resolvers,\n deep: options.deep ?? false,\n corpusHash,\n toolchain,\n },\n meta: {\n root: path.basename(root) === '' ? '.' : '.',\n languages,\n analysisTier: analysis.tier,\n counts: {\n nodes: analysis.nodes.length,\n edges: analysis.edges.length,\n areas: analysis.areas.length,\n tests: testsCount,\n untested: untestedCount,\n },\n cluster: analysis.cluster,\n edgeKinds,\n },\n nodes: analysis.nodes,\n edges: analysis.edges,\n areas: analysis.areas,\n };\n\n // Unknowns: heuristic references we could not resolve, minus any site a precise\n // rung authoritatively covered. Ranked/consumed by `vg unknowns`. Deterministic\n // (already sorted by resolve()); only ids that survived analysis are kept.\n const survivingIds = new Set(analysis.nodes.map((n) => n.id));\n const unknowns = resolved.unresolved\n .filter((u) => !preciseCoveredFiles.has(u.fromRel) && survivingIds.has(u.from))\n .map((u) => ({ from: u.from, name: u.name, kind: u.kind, count: u.count }));\n if (unknowns.length) graph.unknowns = unknowns;\n\n // Hub blast-radius summaries (cheap agent answers for \"what breaks if X changes\").\n graph.summaries = buildSummaries(graph);\n\n // Deterministic open facts (contracts / invariants / characterization) are\n // cheap AST-level work and ship on every build so `vg facts` works without a\n // second pass. `--deep` remains the switch for heavier semantic layers.\n {\n const facts = buildFacts(parses, analysis.nodes, analysis.edges);\n if (facts.length) graph.facts = facts;\n }\n // Grounding (default on).\n if (!options.noGround) {\n const grounding = groundGraph(analysis.nodes, analysis.edges, parses);\n if (grounding.length) graph.grounding = grounding;\n }\n\n let indexResult: BuildResult['index'];\n if (!options.noIndex) {\n timer.start('index');\n const wr = writeGraphIndex(root, graph);\n indexResult = { ok: wr.ok, path: wr.ok ? wr.path : undefined, reason: wr.reason };\n timer.end('index');\n }\n\n timer.end('total');\n const stages = timer.snapshot();\n\n return {\n graph,\n timing: { totalMs: stages.total ?? 0, stages },\n reparsed: parsedNew.length,\n reused: reused.length,\n statHits,\n totalFiles: files.length,\n fileStats,\n resolveStats: resolved.stats,\n tsc: tscStats,\n scip: scipStats,\n index: indexResult,\n warnings,\n fileRoles: fileRolesFromParses(parses),\n };\n}\n\n/** Repo-relative POSIX path for a SCIP document path. */\nfunction toRepoRel(p: string): string {\n return p.split('\\\\').join('/').replace(/^\\.?\\//, '');\n}\n\n/** Auto-detect (or take an explicit) SCIP index and decode it. */\nfunction loadScipIndex(root: string, explicit?: string): { index: ScipIndex; tool?: string } | null {\n const candidates = [\n explicit,\n path.join(root, 'index.scip'),\n path.join(root, '.vibgrate', 'index.scip'),\n ].filter((p): p is string => Boolean(p));\n for (const file of candidates) {\n const abs = path.isAbsolute(file) ? file : path.resolve(root, file);\n if (!fs.existsSync(abs)) continue;\n try {\n const index = decodeScipIndex(new Uint8Array(fs.readFileSync(abs)));\n if (index.documents.length) {\n return { index, tool: index.toolVersion ? `${index.toolName} ${index.toolVersion}` : index.toolName };\n }\n } catch {\n /* unreadable/garbled index — fall back to heuristic */\n }\n }\n return null;\n}\n\n/** Relational edge kinds a precise resolver is authoritative for. Structural\n * kinds (import/contains/test/coverage) are produced elsewhere and preserved. */\nconst PRECISE_KINDS = new Set<EdgeKind>(['call', 'references', 'extends', 'implements']);\n\n/**\n * Merge precise edges over the base set, treating the precise rung as\n * authoritative for the files it covered. For a covered file we DROP the\n * heuristic relational edges originating there (they are guesses the precise\n * resolver has now superseded) and replace them with the precise ones. Edges\n * whose source lives in an uncovered file, and non-relational edges, are kept.\n * Already-precise edges (tsc/scip) are never dropped. Precise wins on id\n * collision. Output is stably sorted for determinism.\n */\nfunction mergePreciseEdges(\n base: GraphEdge[],\n precise: GraphEdge[],\n coveredFiles: Set<string>,\n nodeFileById: Map<string, string>,\n): GraphEdge[] {\n const byId = new Map<string, GraphEdge>();\n for (const e of base) {\n if (PRECISE_KINDS.has(e.kind) && e.resolution === 'heuristic') {\n const srcFile = nodeFileById.get(e.src);\n if (srcFile && coveredFiles.has(srcFile)) continue; // superseded by precise rung\n }\n byId.set(e.id, e);\n }\n for (const e of precise) byId.set(e.id, e); // precise wins on id collision\n return [...byId.values()].sort(\n (a, b) =>\n a.kind.localeCompare(b.kind) || a.src.localeCompare(b.src) || a.dst.localeCompare(b.dst),\n );\n}\n\n/**\n * The reproducibility fingerprint: a short content-address over the parts of the\n * toolchain that deterministically shape graph *content* — schema, tool version,\n * tree-sitter grammar set, and the resolver kinds available. Node/OS versions are\n * deliberately excluded so the graph stays byte-stable across host runtimes; the\n * fingerprint pins the parse/resolve toolchain, which is what actually changes\n * edges between a CI run and a laptop run. This is the value `vg attest` signs and\n * `vg verify` compares against a committed graph.\n */\nfunction computeToolchain(grammars: string, resolvers: ResolverKind[]): Toolchain {\n const sortedResolvers = [...new Set(resolvers)].sort();\n return {\n schema: SCHEMA_VERSION,\n tool: VERSION,\n grammars,\n resolvers: sortedResolvers,\n fingerprint: shortId(\n canonicalize({\n schema: SCHEMA_VERSION,\n tool: VERSION,\n grammars,\n resolvers: sortedResolvers,\n }),\n ),\n };\n}\n\n/**\n * blake3 over the sorted (path, content-hash) list — the corpus identity.\n * Includes documentation / env-example files (in `hashes`) as well as parsed\n * source, so README edits invalidate the map identity and embedding cache.\n */\nfunction computeCorpusHash(parses: FileParse[], hashes: Map<string, string>): string {\n const fromParses = parses.map((p) => [p.rel, hashes.get(p.rel) ?? p.hash] as const);\n const fromHashes = [...hashes.entries()].map(([rel, hash]) => [rel, hash] as const);\n const byRel = new Map<string, string>();\n for (const [rel, hash] of [...fromParses, ...fromHashes]) byRel.set(rel, hash);\n const list = [...byRel.entries()].sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));\n return hashString(canonicalize(list));\n}\n\n","import { buildGraph } from './build.js';\nimport { serializeGraph } from './serialize.js';\nimport { loadGraph } from './load.js';\nimport { hashString } from './hash.js';\n\n/**\n * Determinism self-check (`vg verify`, exit 4 on failure).\n *\n * Proves the load-bearing guarantees:\n * 1. Run-to-run determinism — two full rebuilds are byte-identical.\n * 2. Cache safety — an incremental (cache-warm) build equals a full rebuild.\n * 3. Toolchain reproducibility — the toolchain that would build the graph here\n * matches the one recorded in the committed `graph.json` (when present), so a\n * CI run and a laptop run on different grammar/resolver versions are caught\n * instead of silently producing a different graph.\n *\n * `generatedAt` is pinned to a constant for the comparison so the only legitimate\n * source of variation is removed and any real nondeterminism surfaces.\n */\n\nconst PINNED = '1970-01-01T00:00:00.000Z';\n\nexport interface VerifyResult {\n ok: boolean;\n checks: { name: string; ok: boolean; detail?: string }[];\n digest: string;\n}\n\nexport async function verifyDeterminism(opts: {\n root: string;\n only?: string[];\n exclude?: string[];\n jobs?: number;\n}): Promise<VerifyResult> {\n const base = { root: opts.root, only: opts.only, exclude: opts.exclude, generatedAt: PINNED };\n\n const buildA = await buildGraph({ ...base, noCache: true, jobs: opts.jobs });\n const a = serializeGraph(buildA.graph);\n const b = serializeGraph((await buildGraph({ ...base, noCache: true, jobs: 1 })).graph);\n const cached = serializeGraph((await buildGraph({ ...base, noCache: false })).graph);\n\n const checks = [\n { name: 'run-to-run determinism', ok: a === b, detail: diffHint(a, b) },\n { name: 'cache safety (incremental == full)', ok: a === cached, detail: diffHint(a, cached) },\n ];\n\n // Toolchain reproducibility: if a graph.json is committed, the toolchain that\n // would build it here must match the one it was built with. A mismatch is the\n // CI-vs-laptop divergence surfacing loudly instead of as a silent content diff.\n // Skip under --only/--exclude: a scoped rebuild's resolver set (e.g. no tsc for\n // a non-TS subtree) legitimately differs from the full-repo committed graph, so\n // comparing the two would be a false failure.\n const scoped = Boolean(opts.only?.length || opts.exclude?.length);\n const committed = scoped ? null : loadGraph(opts.root);\n const committedFp = committed?.provenance.toolchain?.fingerprint;\n const currentFp = buildA.graph.provenance.toolchain?.fingerprint;\n if (committedFp && currentFp) {\n const ok = committedFp === currentFp;\n checks.push({\n name: 'toolchain fingerprint matches committed graph',\n ok,\n detail: ok\n ? undefined\n : `committed toolchain ${committedFp} != current ${currentFp} ` +\n `(grammar/resolver versions differ — rebuild or align the toolchain)`,\n });\n }\n\n return {\n ok: checks.every((c) => c.ok),\n checks,\n digest: hashString(a),\n };\n}\n\nfunction diffHint(x: string, y: string): string | undefined {\n if (x === y) return undefined;\n // Find the first differing line for an actionable message (no internals leak).\n const xl = x.split('\\n');\n const yl = y.split('\\n');\n const n = Math.max(xl.length, yl.length);\n for (let i = 0; i < n; i++) {\n if (xl[i] !== yl[i]) {\n return `first divergence at line ${i + 1}`;\n }\n }\n return 'outputs differ in length';\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { discover, mergeExcludes } from './discover.js';\nimport { discoverDocs } from './docs-ingest.js';\nimport { hashBytes } from './hash.js';\nimport { cacheDir } from './cache.js';\nimport { stableStringify } from './serialize.js';\nimport type { FileStat } from './build.js';\n\n/**\n * Freshness tracking for the code map (VG auto-refresh).\n *\n * Every build writes a *snapshot* — the stat (size, mtime) and content hash of\n * each corpus file, plus the build scope — under `.vibgrate/cache/` (gitignored,\n * machine-local, never part of the committed artifact). A *probe* then answers\n * \"did the working tree drift from the map?\" with a stat-only walk: no file is\n * read unless its size/mtime moved, and a moved stat is confirmed by re-hashing\n * just that file. Touch-only changes (git checkout, `touch`, editor re-saves\n * with identical content) are *absorbed*: the snapshot's stats are updated in\n * place so they never trigger a rebuild — not now, not on the next probe.\n *\n * This is what lets `vg serve` and `vg ask` stay fresh without a filesystem\n * watcher: freshness only matters at the moment of a query, so we check on\n * read, cheaply, and rebuild incrementally only when content really changed.\n */\n\nconst SNAPSHOT_VERSION = 'vg-freshness/1';\n\n/** The graph-affecting discovery/build scope, replayed verbatim on refresh. */\nexport interface BuildScope {\n only?: string[];\n exclude?: string[];\n paths?: string[];\n deep?: boolean;\n noGround?: boolean;\n scip?: string;\n noScip?: boolean;\n noTsc?: boolean;\n cluster?: string;\n grammarsDir?: string;\n}\n\ninterface SnapshotFile {\n version: string;\n /** corpusHash of the build this snapshot belongs to. */\n corpusHash: string;\n scope: BuildScope;\n files: Record<string, { size: number; mtimeMs: number; hash: string }>;\n}\n\nexport interface Drift {\n /** Files whose *content* changed (stat moved AND hash differs). */\n changed: string[];\n /** Files present now but absent from the snapshot. */\n added: string[];\n /** Snapshot files no longer present. */\n removed: string[];\n}\n\nexport interface ProbeResult {\n drift: Drift;\n /** The recorded build scope — what a refresh must replay. */\n scope: BuildScope;\n /** corpusHash the current map was built from. */\n corpusHash: string;\n}\n\nexport function snapshotPath(root: string): string {\n return path.join(cacheDir(root), 'freshness.json');\n}\n\n/** Persist the snapshot after a successful build. Best-effort (cache-only). */\nexport function writeSnapshot(\n root: string,\n corpusHash: string,\n fileStats: FileStat[],\n scope: BuildScope = {},\n): void {\n const files: SnapshotFile['files'] = {};\n for (const f of fileStats) files[f.rel] = { size: f.size, mtimeMs: f.mtimeMs, hash: f.hash };\n const snapshot: SnapshotFile = { version: SNAPSHOT_VERSION, corpusHash, scope: pruneScope(scope), files };\n try {\n fs.mkdirSync(cacheDir(root), { recursive: true });\n fs.writeFileSync(snapshotPath(root), stableStringify(snapshot, 0));\n } catch {\n /* read-only checkout etc. — freshness just stays unavailable */\n }\n}\n\nexport function loadSnapshot(root: string): SnapshotFile | null {\n try {\n const loaded = JSON.parse(fs.readFileSync(snapshotPath(root), 'utf8')) as SnapshotFile;\n if (loaded.version === SNAPSHOT_VERSION && loaded.files && typeof loaded.corpusHash === 'string') {\n return { ...loaded, scope: loaded.scope ?? {} };\n }\n } catch {\n /* missing/corrupt → no snapshot */\n }\n return null;\n}\n\nexport function hasDrift(drift: Drift): boolean {\n return drift.changed.length + drift.added.length + drift.removed.length > 0;\n}\n\n/** Total drifted files — the number shown to humans. */\nexport function driftCount(drift: Drift): number {\n return drift.changed.length + drift.added.length + drift.removed.length;\n}\n\n/**\n * Compare the working tree to the snapshot. Returns null when no snapshot\n * exists (nothing was ever built on this machine — auto-refresh stays off\n * rather than guessing the build scope). Stat-only except for files whose\n * stat moved; touch-only moves are absorbed back into the snapshot.\n */\nexport function probeFreshness(root: string): ProbeResult | null {\n const snapshot = loadSnapshot(root);\n if (!snapshot) return null;\n\n const { scope } = snapshot;\n const exclude = mergeExcludes(root, scope.exclude);\n // Must match the build's fileStats universe: language sources + context docs\n // (README, CI yaml, package manifests, …). Probing only `discover()` left\n // every document in the snapshot as \"removed\" after a successful build, so\n // `vg status` kept reporting hundreds of drifted files after ask/serve refresh.\n let discovered: { rel: string; abs: string }[];\n try {\n const code = discover({ root, only: scope.only, exclude, paths: scope.paths });\n const docs = discoverDocs({ root, exclude, paths: scope.paths });\n const byRel = new Map<string, string>();\n for (const f of code) byRel.set(f.rel, f.abs);\n for (const d of docs) {\n if (!byRel.has(d.rel)) byRel.set(d.rel, d.abs);\n }\n discovered = [...byRel.entries()]\n .map(([rel, abs]) => ({ rel, abs }))\n .sort((a, b) => (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0));\n } catch {\n return null; // root vanished / unreadable — treat as unknown, not stale\n }\n\n const drift: Drift = { changed: [], added: [], removed: [] };\n const seen = new Set<string>();\n let absorbed = false;\n\n for (const file of discovered) {\n seen.add(file.rel);\n const entry = snapshot.files[file.rel];\n if (!entry) {\n drift.added.push(file.rel);\n continue;\n }\n let stat: fs.Stats;\n try {\n stat = fs.statSync(file.abs);\n } catch {\n drift.removed.push(file.rel); // raced away between walk and stat\n continue;\n }\n if (stat.size === entry.size && stat.mtimeMs === entry.mtimeMs) continue;\n // Stat moved — confirm with content before declaring drift.\n // Build records oversized files with a size-only sentinel hash so the probe\n // must not re-read them into memory (or mis-report them as always-changed).\n if (entry.hash.startsWith('vg:oversize:')) {\n const expected = `vg:oversize:${stat.size}`;\n if (entry.hash === expected) {\n snapshot.files[file.rel] = { size: stat.size, mtimeMs: stat.mtimeMs, hash: entry.hash };\n absorbed = true;\n } else {\n drift.changed.push(file.rel);\n }\n continue;\n }\n let hash = '';\n try {\n hash = hashBytes(fs.readFileSync(file.abs));\n } catch {\n drift.removed.push(file.rel);\n continue;\n }\n if (hash === entry.hash) {\n // Touch-only (checkout/`touch`/identical re-save): absorb the new stat\n // so this file never re-triggers a probe, without any rebuild.\n snapshot.files[file.rel] = { size: stat.size, mtimeMs: stat.mtimeMs, hash };\n absorbed = true;\n } else {\n drift.changed.push(file.rel);\n }\n }\n\n for (const rel of Object.keys(snapshot.files)) {\n if (!seen.has(rel)) drift.removed.push(rel);\n }\n\n // Persist absorptions only when the tree is otherwise clean — a real drift\n // triggers a rebuild that rewrites the snapshot wholesale anyway.\n if (absorbed && !hasDrift(drift)) {\n try {\n fs.writeFileSync(snapshotPath(root), stableStringify(snapshot, 0));\n } catch {\n /* best-effort */\n }\n }\n\n drift.changed.sort();\n drift.added.sort();\n drift.removed.sort();\n return { drift, scope, corpusHash: snapshot.corpusHash };\n}\n\n/** Drop empty/undefined scope fields so the snapshot stays minimal and stable. */\nfunction pruneScope(scope: BuildScope): BuildScope {\n const out: BuildScope = {};\n if (scope.only?.length) out.only = [...scope.only].sort();\n if (scope.exclude?.length) out.exclude = [...scope.exclude];\n if (scope.paths?.length) out.paths = [...scope.paths];\n if (scope.deep) out.deep = true;\n if (scope.noGround) out.noGround = true;\n if (scope.scip) out.scip = scope.scip;\n if (scope.noScip) out.noScip = true;\n if (scope.noTsc) out.noTsc = true;\n if (scope.cluster) out.cluster = scope.cluster;\n if (scope.grammarsDir) out.grammarsDir = scope.grammarsDir;\n return out;\n}\n","/**\n * Shared, deterministic content for `vg install`: the skill body and the advisory\n * nudge. Posture is deliberately lighter-touch — the nudge\n * *suggests* the graph as the faster path, never asserts \"MANDATORY\"\n * (VG-ASSISTANT-INSTALL §1). On small repos we say searching is fine.\n */\n\nexport const SKILL_MARKER = 'vg-graph-skill';\nexport const NUDGE_BEGIN = '<!-- vg:begin -->';\nexport const NUDGE_END = '<!-- vg:end -->';\n\n/**\n * Version of the generated instruction content (skill + nudge). Bump on ANY\n * wording/structure change to those templates: files written by `vg install`\n * carry this number in an HTML-comment marker, and `vg` builds auto-refresh\n * installed copies whose marker is older (see registry.ts\n * refreshInstalledInstructions) — so evolved instructions reach existing\n * repos the first time a new CLI version builds there.\n *\n * History: v1 = the unversioned originals (detected by their headings);\n * v2 = versioned markers + the strong MCP-first recommendation.\n */\nexport const INSTALL_CONTENT_VERSION = 2;\n\nconst VERSION_MARKER_RE = /<!--\\s*vg:v(\\d+)\\b[^>]*-->/;\n\n/** The marker line embedded in every generated instruction file. */\nexport function versionMarker(): string {\n return `<!-- vg:v${INSTALL_CONTENT_VERSION} · managed by \\`vg install\\` — auto-refreshed when these instructions evolve; remove this line to opt out -->`;\n}\n\n/**\n * The content version a previously-written instruction file carries, or null\n * when it has no marker (pre-versioning installs, or user-authored files).\n */\nexport function installedContentVersion(text: string): number | null {\n const m = VERSION_MARKER_RE.exec(text);\n return m ? Number(m[1]) : null;\n}\n\n/**\n * The `--client` value the skill/nudge tells the assistant to pass to `vg` so its\n * CLI calls are attributed. `vg install <assistant>` passes the assistant id\n * (e.g. `claude`, `cursor`); the canonical reference copy uses a placeholder.\n */\nfunction clientFlag(client?: string): string {\n return client ? `--client=${client}` : '--client=<your-ai>';\n}\n\nexport function skillMarkdown(client?: string): string {\n const cf = clientFlag(client);\n return `---\nname: vg\ndescription: Query the local code graph (vg) for structure, impact, and navigation instead of grepping/reading many files.\n---\n\n${versionMarker()}\n\n# vg — the code map\n\nThis repo has a deterministic code graph built by \\`vg\\`. Prefer it over reading or\ngrepping many files — it is smaller, more relevant context, and free.\n\n## Use the MCP tools — not the CLI\n\nWhen the \\`vg\\` MCP server is registered (it is after \\`vg install\\`), **always call\nits read-only tools instead of shelling out to the CLI.** The server keeps the\nmap parsed, the relation index warm, and the embedding model loaded across\ncalls, so an MCP call answers in milliseconds — while every CLI invocation pays\nNode startup plus a fresh map parse, hundreds of times more. Tools:\n\\`query_graph\\`, \\`get_node\\`, \\`impact_of\\`, \\`find_path\\`, \\`list_hubs\\`, \\`list_areas\\`,\n\\`get_graph_summary\\`, \\`search_symbols\\`. They are side-effect-free and\nauto-approvable, and the server records which client is calling automatically.\nReach for the CLI only when the MCP server is genuinely unavailable — never as\nthe first resort.\n\n## CLI fallback — only when the MCP server is unavailable\n\nIf (and only if) no \\`vg\\` MCP server is available, use the CLI — and **always\npass \\`${cf}\\`** so your calls are counted (that's how the CLI-vs-MCP split is\nmeasured and the tools improved):\n\n- **Understand code:** \\`vg \"<question>\" ${cf}\\` — a budget-bounded, fact-annotated context block.\n- **Find a symbol:** \\`vg show <name> ${cf}\\` — what it is, what it calls, what calls it.\n- **Before changing something:** \\`vg impact <name> ${cf}\\` — what breaks if you change it.\n- **Navigate:** \\`vg path <A> <B> ${cf}\\`, \\`vg tree <name> ${cf}\\`.\n\n## Dependencies & library docs\n\n- **Upgrade drift:** \\`vg drift\\` lists what is outdated across dependencies\n (offline; \\`--online\\` for currency). \\`vg scan\\` scores upgrade drift and\n \\`vg report\\` renders it (text | json | sarif | md).\n- **Version-correct docs:** \\`vg lib <name>\\` returns drift-annotated, version-\n specific usage docs for a library — inject these instead of guessing an API.\n\n### Library-docs discipline\n\nWhen a task needs a library's API, use the docs tools before web search or\ntraining-data recall — they are official content matched to the version **this\nproject has installed**, and they win when the two conflict.\n\n- **Workflow:** \\`resolve_library\\` once per library, then \\`library_docs\\` with the\n returned \\`targetId\\` and a focused query (good: \"zod refine custom error\n message\"; bad: \"zod\"). Never guess a targetId.\n- **Budget:** at most **3 docs calls per task**. If 2 \\`library_docs\\` calls have\n not surfaced the section you need, read the package source under\n \\`node_modules\\` instead of searching again.\n- **Skip the docs tools** for language built-ins, stable well-known syntax, or\n an API already shown in the current context — they add nothing there.\n\n## Keep it fresh\n\nThe map keeps itself fresh: \\`vg ask\\` and the MCP tools detect changed files\nand rebuild it incrementally before answering — you can edit code and query\nimmediately. Running \\`vg\\` after a large pull still warms everything in one go.\nThe map lives at \\`.vibgrate/graph.json\\` and is deterministic (byte-identical\nacross machines).\n`;\n}\n\nexport function nudgeMarkdown(smallRepo: boolean, client?: string): string {\n const cf = clientFlag(client);\n if (smallRepo) {\n return `${NUDGE_BEGIN}\n${versionMarker()}\n## Code navigation (vg)\n\nThis repo is small enough that searching files directly is fine. Still, before a\nchange, the \\`vg\\` graph shows what breaks: use the \\`vg\\` MCP tools when the server\nis registered (\\`impact_of\\`, \\`query_graph\\` — the warm server answers far faster\nthan spawning the CLI). Only without the server, fall back to the CLI and pass\n\\`${cf}\\` so the call is counted: \\`vg impact <name> ${cf}\\`,\n\\`vg \"<question>\" ${cf}\\`.\n${NUDGE_END}`;\n }\n return `${NUDGE_BEGIN}\n${versionMarker()}\n## Code navigation (vg) — use the MCP tools first\n\nA deterministic code graph is available. It is usually the faster, cheaper path\nthan reading or grepping many files. **When the \\`vg\\` MCP server is registered,\nalways use its tools** (\\`query_graph\\`, \\`get_node\\`, \\`impact_of\\`,\n\\`search_symbols\\`, …) — the map, indexes, and embedding model stay warm across\ncalls, so they answer in milliseconds, while every CLI invocation pays Node\nstartup plus a fresh map parse. Fall back to the CLI only when the server is\nunavailable, and then pass \\`${cf}\\` so the call is counted:\n\n- \\`vg \"<question>\" ${cf}\\` — a compact, fact-annotated context block for a question.\n- \\`vg show <name> ${cf}\\` — what a symbol is, its callers and callees.\n- \\`vg impact <name> ${cf}\\` — what breaks if you change it.\n\nThis is advisory, not mandatory — remove it with \\`vg uninstall\\` (or delete this\nblock).\n${NUDGE_END}`;\n}\n\n/** The MCP server entry registered for local stdio use. */\nexport function mcpServerEntry(launch: ServeLaunch = { command: 'vg', args: ['serve'] }): {\n command: string;\n args: string[];\n} {\n return { command: launch.command, args: launch.args };\n}\n\nexport interface ServeLaunch {\n command: string;\n args: string[];\n /** Human-readable explanation when the launch is not the plain `vg serve`. */\n note?: string;\n}\n","import * as fs from 'node:fs';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport {\n skillMarkdown,\n nudgeMarkdown,\n mcpServerEntry,\n installedContentVersion,\n INSTALL_CONTENT_VERSION,\n NUDGE_BEGIN,\n NUDGE_END,\n type ServeLaunch,\n} from './content.js';\nimport { CliError, ExitCode } from '../util/exit.js';\nimport { ensureVibgrateGitignore } from '../engine/artifacts.js';\nimport { whichOnPath, isInstalledOwnBinary } from '../util/cli-invocation.js';\nimport { navigationToolsetConfig, HOT_TOOLS, deferredToolNames } from '../mcp/tools.js';\n\n/**\n * Per-assistant install registry (a focused subset of VG-ASSISTANT-INSTALL §2;\n * the remaining 20+ assistants are added in Phase 3). All paths are repo-local\n * (the team-shareable, safe default); writes are idempotent.\n */\n\nexport interface McpTarget {\n file: string; // project-relative\n key: 'mcpServers' | 'servers' | 'mcp_servers';\n /** Config syntax. Defaults to JSON; Grok's project config is TOML. */\n format?: 'json' | 'toml';\n vscode?: boolean; // VS Code uses { servers: { vg: { type:'stdio', ... } } }\n}\nexport interface NudgeTarget {\n file: string;\n kind: 'block' | 'file';\n}\nexport interface Assistant {\n id: string;\n label: string;\n skill?: string; // project-relative SKILL.md path\n mcp?: McpTarget;\n nudge?: NudgeTarget;\n /**\n * Signs this assistant is in use, checked by `detectAssistants`:\n * `markers` are project-relative paths, `homeMarkers` are relative to the\n * user's home folder, `bin` are executables looked up on PATH. Detection is\n * best-effort presence-checking only — nothing is read or executed.\n */\n markers?: string[];\n homeMarkers?: string[];\n bin?: string[];\n}\n\nexport const ASSISTANTS: Assistant[] = [\n {\n id: 'claude',\n label: 'Claude Code',\n skill: '.claude/skills/vg/SKILL.md',\n mcp: { file: '.mcp.json', key: 'mcpServers' },\n nudge: { file: 'CLAUDE.md', kind: 'block' },\n markers: ['CLAUDE.md', '.claude'],\n homeMarkers: ['.claude', '.claude.json'],\n bin: ['claude'],\n },\n {\n id: 'cursor',\n label: 'Cursor',\n mcp: { file: '.cursor/mcp.json', key: 'mcpServers' },\n nudge: { file: '.cursor/rules/vg.mdc', kind: 'file' },\n markers: ['.cursor', '.cursorrules'],\n homeMarkers: ['.cursor'],\n bin: ['cursor-agent'],\n },\n {\n id: 'windsurf',\n label: 'Windsurf',\n mcp: { file: '.windsurf/mcp.json', key: 'mcpServers' },\n nudge: { file: '.windsurf/rules/vg.md', kind: 'file' },\n markers: ['.windsurf', '.windsurfrules'],\n homeMarkers: ['.codeium/windsurf'],\n },\n {\n id: 'vscode',\n label: 'VS Code (Copilot Chat)',\n mcp: { file: '.vscode/mcp.json', key: 'servers', vscode: true },\n nudge: { file: '.github/copilot-instructions.md', kind: 'block' },\n markers: ['.github/copilot-instructions.md'],\n },\n {\n id: 'codex',\n label: 'Codex',\n skill: '.codex/skills/vg/SKILL.md',\n nudge: { file: 'AGENTS.md', kind: 'block' },\n markers: ['.codex'],\n homeMarkers: ['.codex'],\n bin: ['codex'],\n },\n {\n id: 'gemini',\n label: 'Gemini CLI',\n skill: '.gemini/skills/vg/SKILL.md',\n nudge: { file: 'GEMINI.md', kind: 'block' },\n markers: ['GEMINI.md', '.gemini'],\n homeMarkers: ['.gemini'],\n bin: ['gemini'],\n },\n {\n // Grok reads project-scoped MCP servers from `.grok/config.toml` — a TOML\n // `[mcp_servers.<name>]` table, the same thing `grok mcp add --scope\n // project` writes. Without it Grok sees the skill but no `vg` server, says\n // it \"isn't listed among connected servers\", and falls back to shelling the\n // CLI (slow, and killed by its command timeout on a stale map).\n id: 'grok',\n label: 'Grok CLI',\n skill: '.grok/skills/vg/SKILL.md',\n mcp: { file: '.grok/config.toml', key: 'mcp_servers', format: 'toml' },\n nudge: { file: 'AGENTS.md', kind: 'block' },\n markers: ['.grok', 'GROK.md'],\n homeMarkers: ['.grok'],\n bin: ['grok'],\n },\n // Skill + advisory AGENTS.md nudge (the broad-reach common denominator). MCP\n // registration for these hosts is host-specific and added as their formats\n // stabilise; the skill + nudge work today.\n { id: 'opencode', label: 'OpenCode', skill: '.opencode/skills/vg/SKILL.md', nudge: { file: 'AGENTS.md', kind: 'block' }, markers: ['.opencode', 'opencode.json'], homeMarkers: ['.config/opencode'], bin: ['opencode'] },\n { id: 'kilo', label: 'Kilo Code', skill: '.kilo/skills/vg/SKILL.md', nudge: { file: 'AGENTS.md', kind: 'block' }, markers: ['.kilo', '.kilocode'], homeMarkers: ['.kilocode'] },\n { id: 'aider', label: 'Aider', skill: '.aider/vg/SKILL.md', nudge: { file: 'AGENTS.md', kind: 'block' }, markers: ['.aider', '.aider.conf.yml'], homeMarkers: ['.aider.conf.yml'], bin: ['aider'] },\n { id: 'factory', label: 'Factory Droid', skill: '.factory/skills/vg/SKILL.md', nudge: { file: 'AGENTS.md', kind: 'block' }, markers: ['.factory'], homeMarkers: ['.factory'], bin: ['droid'] },\n { id: 'trae', label: 'Trae', skill: '.trae/skills/vg/SKILL.md', nudge: { file: 'AGENTS.md', kind: 'block' }, markers: ['.trae'], homeMarkers: ['.trae'] },\n { id: 'kiro', label: 'Kiro', skill: '.kiro/skills/vg/SKILL.md', nudge: { file: '.kiro/steering/vg.md', kind: 'file' }, markers: ['.kiro'], homeMarkers: ['.kiro'] },\n { id: 'amp', label: 'Amp', skill: '.agents/skills/vg/SKILL.md', nudge: { file: 'AGENTS.md', kind: 'block' }, homeMarkers: ['.config/amp'], bin: ['amp'] },\n { id: 'kimi', label: 'Kimi Code', skill: '.kimi/skills/vg/SKILL.md', nudge: { file: 'AGENTS.md', kind: 'block' }, markers: ['.kimi'], homeMarkers: ['.kimi'] },\n { id: 'codebuddy', label: 'CodeBuddy', skill: '.codebuddy/skills/vg/SKILL.md', nudge: { file: 'CODEBUDDY.md', kind: 'block' }, markers: ['CODEBUDDY.md', '.codebuddy'], homeMarkers: ['.codebuddy'] },\n { id: 'copilot-cli', label: 'GitHub Copilot CLI', skill: '.copilot/skills/vg/SKILL.md', nudge: { file: 'AGENTS.md', kind: 'block' }, markers: ['.copilot'], homeMarkers: ['.copilot'], bin: ['copilot'] },\n { id: 'pi', label: 'Pi', skill: '.pi/agent/skills/vg/SKILL.md', nudge: { file: 'AGENTS.md', kind: 'block' }, markers: ['.pi'], homeMarkers: ['.pi'] },\n { id: 'devin', label: 'Devin CLI', skill: '.devin/skills/vg/SKILL.md', nudge: { file: 'AGENTS.md', kind: 'block' }, markers: ['.devin'], homeMarkers: ['.devin'] },\n { id: 'hermes', label: 'Hermes', skill: '.hermes/skills/vg/SKILL.md', nudge: { file: 'AGENTS.md', kind: 'block' }, markers: ['.hermes'], homeMarkers: ['.hermes'] },\n { id: 'openclaw', label: 'OpenClaw', skill: '.openclaw/skills/vg/SKILL.md', nudge: { file: 'AGENTS.md', kind: 'block' }, markers: ['.openclaw'], homeMarkers: ['.openclaw'], bin: ['openclaw'] },\n { id: 'agents', label: 'Agent-Skills (generic)', skill: '.agents/skills/vg/SKILL.md', nudge: { file: 'AGENTS.md', kind: 'block' }, markers: ['AGENTS.md', '.agents'] },\n];\n\nexport function assistantById(id: string): Assistant | undefined {\n return ASSISTANTS.find((a) => a.id === id);\n}\n\n// --- detection ---\n\nexport interface DetectedAssistant {\n assistant: Assistant;\n /** Where the sign was found — in the repo, in the user's home folder, or on PATH. */\n via: 'repo' | 'home' | 'path';\n /** The specific marker path or executable name that matched. */\n marker: string;\n}\n\nexport interface DetectOptions {\n /** Home folder override (tests). Defaults to `os.homedir()`. */\n home?: string;\n /** PATH lookup override (tests). Defaults to `whichOnPath`. */\n which?: (cmd: string) => string | null;\n}\n\n/**\n * Best-effort detection of which AI assistants are in use — by their footprint\n * in the repo (rules files, config dirs), their per-user config in the home\n * folder, or their CLI on PATH. Pure presence checks: nothing is read,\n * parsed, or executed, and a miss is always safe (it only means \"not\n * auto-selected\"). First match per assistant wins, repo before home before\n * PATH, so the reported marker is the most local evidence.\n */\nexport function detectAssistants(root: string, opts: DetectOptions = {}): DetectedAssistant[] {\n const home = opts.home ?? os.homedir();\n const which = opts.which ?? whichOnPath;\n const found: DetectedAssistant[] = [];\n for (const assistant of ASSISTANTS) {\n const repoHit = (assistant.markers ?? []).find((m) => fs.existsSync(path.join(root, m)));\n if (repoHit) {\n found.push({ assistant, via: 'repo', marker: repoHit });\n continue;\n }\n const homeHit = (assistant.homeMarkers ?? []).find((m) => fs.existsSync(path.join(home, m)));\n if (homeHit) {\n found.push({ assistant, via: 'home', marker: homeHit });\n continue;\n }\n const binHit = (assistant.bin ?? []).find((b) => which(b) !== null);\n if (binHit) found.push({ assistant, via: 'path', marker: binHit });\n }\n return found;\n}\n\nexport interface InstallOptions {\n root: string;\n hook?: boolean; // write the advisory nudge (default true)\n smallRepo: boolean;\n /** Resolved MCP launch command; defaults to detectServeLaunch(). */\n launch?: ServeLaunch;\n}\n\nexport interface InstallAction {\n wrote: string[];\n skipped: string[];\n /** Explanation when the MCP entry is not the plain `vg serve` (e.g. PATH fallback). */\n note?: string;\n}\n\n/**\n * Resolve how the assistant host should launch the MCP server. `command: \"vg\"`\n * only works when `vg` on PATH is a *persistent install* of this CLI — a user\n * who ran via npx (whose `vg` is a throwaway npx-cache binary that disappears\n * after the run), or whose `vg` belongs to another tool (see\n * scripts/postinstall.mjs), would get a server that silently fails to start or,\n * worse, launches the wrong binary. Detection is best-effort and never throws;\n * the fallbacks keep the entry working: installed `vg` → installed `vibgrate` →\n * `npx -y -p @vibgrate/cli vg`.\n */\nexport function detectServeLaunch(which: (cmd: string) => string | null = whichOnPath): ServeLaunch {\n const vg = which('vg');\n if (vg && isInstalledOwnBinary(vg)) return { command: 'vg', args: ['serve'] };\n const vibgrate = which('vibgrate');\n if (vibgrate && isInstalledOwnBinary(vibgrate)) {\n return {\n command: 'vibgrate',\n args: ['serve'],\n note: vg\n ? '`vg` on PATH belongs to another tool — registered the identical `vibgrate serve` instead'\n : '`vg` is not on PATH — registered the identical `vibgrate serve` instead',\n };\n }\n return {\n command: 'npx',\n args: ['-y', '-p', '@vibgrate/cli', 'vg', 'serve'],\n note: 'vg is not installed on PATH — registered an npx launcher. Install globally (`npm i -g @vibgrate/cli`) and rerun `vg install` for a faster startup.',\n };\n}\n\nexport function installAssistant(a: Assistant, opts: InstallOptions): InstallAction {\n const wrote: string[] = [];\n const skipped: string[] = [];\n let note: string | undefined;\n\n if (a.skill) {\n // Pass the assistant id as the --client value so the installed skill tells\n // this AI to identify itself on CLI calls (the MCP path detects it itself).\n writeFileEnsured(path.join(opts.root, a.skill), skillMarkdown(a.id));\n wrote.push(a.skill);\n }\n if (a.mcp) {\n const launch = opts.launch ?? detectServeLaunch();\n upsertMcp(path.join(opts.root, a.mcp.file), a.mcp, launch);\n wrote.push(a.mcp.file);\n note = launch.note;\n } else {\n skipped.push('mcp (host-specific setup)');\n }\n if (a.nudge && opts.hook !== false) {\n writeNudge(path.join(opts.root, a.nudge.file), a.nudge, opts.smallRepo, a.id);\n wrote.push(a.nudge.file);\n } else if (a.nudge) {\n skipped.push('nudge (--no-hook)');\n }\n\n return { wrote, skipped, note };\n}\n\nexport function uninstallAssistant(a: Assistant, root: string, purge: boolean): string[] {\n const removed: string[] = [];\n if (a.mcp) {\n const file = path.join(root, a.mcp.file);\n if (removeMcp(file, a.mcp)) removed.push(a.mcp.file);\n }\n if (a.nudge) {\n const file = path.join(root, a.nudge.file);\n if (a.nudge.kind === 'block') {\n if (removeBlock(file)) removed.push(a.nudge.file);\n } else if (fs.existsSync(file)) {\n fs.rmSync(file);\n removed.push(a.nudge.file);\n }\n }\n if (purge && a.skill) {\n const file = path.join(root, a.skill);\n if (fs.existsSync(file)) {\n fs.rmSync(file);\n removed.push(a.skill);\n }\n }\n return removed;\n}\n\n/**\n * True when this assistant already has Vibgrate Graph / AI Context wiring in\n * `root` (skill file, MCP `vg` entry, or our nudge block/file).\n */\nexport function isAssistantInstalled(a: Assistant, root: string): boolean {\n if (a.skill && fs.existsSync(path.join(root, a.skill))) return true;\n if (a.mcp) {\n const file = path.join(root, a.mcp.file);\n if (a.mcp.format === 'toml') {\n if (hasTomlMcp(file, a.mcp)) return true;\n } else if (fs.existsSync(file)) {\n try {\n const config = readJson(file);\n const bag = config[a.mcp.key];\n if (bag && typeof bag === 'object' && bag !== null && 'vg' in (bag as object)) return true;\n } catch {\n /* unreadable — treat as not installed */\n }\n }\n }\n if (a.nudge) {\n const file = path.join(root, a.nudge.file);\n if (!fs.existsSync(file)) return false;\n const text = readTextSafe(file);\n if (!text) return false;\n if (a.nudge.kind === 'block') return text.includes(NUDGE_BEGIN);\n // File-kind nudge: ours when version-marked or carrying generated headings.\n return installedContentVersion(text) !== null || text.includes('# vg') || text.includes('Vibgrate');\n }\n return false;\n}\n\n// --- writers ---\n\nfunction writeFileEnsured(file: string, content: string): void {\n fs.mkdirSync(path.dirname(file), { recursive: true });\n fs.writeFileSync(file, content);\n}\n\n/**\n * Write the deferred-loading navigation config once per project (plan P3,\n * VG-NAVIGATION-PROFILE.md). `vg serve` always exposes the one optimized tool\n * set; this file is the CLIENT loading configuration for agents built on the\n * Claude API that support `defer_loading` + tool-search — it keeps the hot\n * navigation core in context and defers the rest, cutting the per-step schema\n * bill to ~350–450 tokens (vs ~1,881 for the full set). Hosts that don't\n * support deferral ignore it and serve the whole optimized set. Returns the\n * repo-relative path written.\n */\nexport function writeNavigationConfig(root: string): string {\n // `vg install` may be the first thing to create `.vibgrate/` — make sure the\n // default ignore file lands with it so the install never dirties the branch.\n ensureVibgrateGitignore(root);\n const rel = path.join('.vibgrate', 'mcp-navigation.json');\n const doc = {\n _readme:\n 'Deferred-loading config for agents embedding `vg serve` via the Claude API ' +\n '(defer_loading + tool-search). The hot navigation core stays in context; the rest ' +\n 'load on demand — ~350-450 schema tokens/step vs ~1,881 for the full set. Hosts without ' +\n 'defer_loading ignore this and serve the whole (already optimized) tool set. See ' +\n 'docs/graph/VG-NAVIGATION-PROFILE.md.',\n hot_core: [...HOT_TOOLS],\n deferred: deferredToolNames(),\n toolset: navigationToolsetConfig(),\n };\n writeFileEnsured(path.join(root, rel), `${JSON.stringify(doc, null, 2)}\\n`);\n return rel;\n}\n\nfunction upsertMcp(file: string, target: McpTarget, launch: ServeLaunch): void {\n if (target.format === 'toml') {\n upsertTomlMcp(file, target, launch);\n return;\n }\n const config = readJson(file);\n const entry = mcpServerEntry(launch);\n const value = target.vscode ? { type: 'stdio', ...entry } : entry;\n const bag = (config[target.key] && typeof config[target.key] === 'object'\n ? config[target.key]\n : {}) as Record<string, unknown>;\n bag.vg = value;\n config[target.key] = bag;\n writeFileEnsured(file, `${JSON.stringify(config, null, 2)}\\n`);\n}\n\n/**\n * The `[<key>.vg]` table in a TOML config (Grok's `.grok/config.toml`), and\n * everything up to the next top-level table header. Anchored to a line start so\n * a key *value* that happens to contain the text can't match.\n */\nfunction tomlTableRe(key: string): RegExp {\n return new RegExp(`(^|\\\\n)[ \\\\t]*\\\\[${escapeRe(key)}\\\\.vg\\\\][^\\\\n]*\\\\n(?:(?![ \\\\t]*\\\\[)[^\\\\n]*\\\\n?)*`);\n}\n\nfunction tomlString(s: string): string {\n return JSON.stringify(s); // TOML basic strings share JSON's escaping\n}\n\n/**\n * Merge our `vg` server into a TOML config, rewriting only our own table.\n * Everything else in the file — the user's other servers, their comments and\n * formatting — is preserved verbatim, which a parse-and-reserialize round trip\n * could not promise.\n */\nfunction upsertTomlMcp(file: string, target: McpTarget, launch: ServeLaunch): void {\n const entry = mcpServerEntry(launch);\n const table =\n `[${target.key}.vg]\\n` +\n `command = ${tomlString(entry.command)}\\n` +\n `args = [${entry.args.map(tomlString).join(', ')}]\\n`;\n const existing = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';\n const re = tomlTableRe(target.key);\n const next = re.test(existing)\n ? existing.replace(re, (m) => (m.startsWith('\\n') ? `\\n${table}` : table))\n : existing.length\n ? `${existing.replace(/\\s*$/, '')}\\n\\n${table}`\n : table;\n writeFileEnsured(file, next);\n}\n\nfunction removeTomlMcp(file: string, target: McpTarget): boolean {\n if (!fs.existsSync(file)) return false;\n const existing = readTextSafe(file);\n if (existing === null) return false;\n const re = tomlTableRe(target.key);\n if (!re.test(existing)) return false;\n const next = existing.replace(re, (m) => (m.startsWith('\\n') ? '\\n' : '')).replace(/\\n{3,}/g, '\\n\\n');\n writeFileEnsured(file, next.trim().length ? next : '');\n return true;\n}\n\nfunction hasTomlMcp(file: string, target: McpTarget): boolean {\n if (!fs.existsSync(file)) return false;\n const text = readTextSafe(file);\n return text !== null && tomlTableRe(target.key).test(text);\n}\n\nfunction removeMcp(file: string, target: McpTarget): boolean {\n if (target.format === 'toml') return removeTomlMcp(file, target);\n if (!fs.existsSync(file)) return false;\n const config = readJson(file);\n const bag = config[target.key] as Record<string, unknown> | undefined;\n if (!bag || !(bag.vg !== undefined)) return false;\n delete bag.vg;\n writeFileEnsured(file, `${JSON.stringify(config, null, 2)}\\n`);\n return true;\n}\n\n/**\n * Below this many mapped files the nudge honestly says searching is fine.\n * Shared by `vg install` and the post-build instruction refresh so both write\n * the same variant.\n */\nexport const SMALL_REPO_FILES = 150;\n\n/** One instruction file brought up to the current content version. */\nexport interface RefreshedInstruction {\n /** Repo-relative path of the refreshed file. */\n file: string;\n /** The version it carried (0 = pre-versioning legacy content). */\n from: number;\n to: number;\n}\n\n/**\n * Bring previously-installed assistant instructions up to the current content\n * version (INSTALL_CONTENT_VERSION). Called after every successful `vg` build,\n * so evolved instructions reach existing repos the first time a new CLI\n * version builds there — no re-run of `vg install` needed.\n *\n * Ownership rules — this must never clobber user-authored content:\n * - a file with a `vg:v<N>` marker is ours; refreshed when N is older.\n * Removing the marker line opts the file out permanently.\n * - a marker-less file at a known install path is refreshed ONLY when it\n * still carries the generated headings (legacy pre-versioning copies),\n * and treated as version 0.\n * - nudge blocks refresh only the vg:begin…vg:end region; the rest of the\n * host file (CLAUDE.md, AGENTS.md, …) is untouched.\n */\nexport function refreshInstalledInstructions(root: string, smallRepo: boolean): RefreshedInstruction[] {\n const out: RefreshedInstruction[] = [];\n const staleVersion = (text: string, legacySignature: string): number | null => {\n const v = installedContentVersion(text);\n if (v !== null) return v < INSTALL_CONTENT_VERSION ? v : null;\n return text.includes(legacySignature) ? 0 : null; // marker-less: legacy ours, or not ours at all\n };\n\n for (const a of ASSISTANTS) {\n if (a.skill) {\n const file = path.join(root, a.skill);\n if (fs.existsSync(file)) {\n const text = readTextSafe(file);\n const from = text === null ? null : staleVersion(text, '# vg — the code map');\n if (from !== null) {\n writeFileEnsured(file, skillMarkdown(a.id));\n out.push({ file: a.skill, from, to: INSTALL_CONTENT_VERSION });\n }\n }\n }\n if (a.nudge) {\n const file = path.join(root, a.nudge.file);\n if (!fs.existsSync(file)) continue;\n const text = readTextSafe(file);\n if (text === null) continue;\n if (a.nudge.kind === 'block') {\n const block = new RegExp(`${escapeRe(NUDGE_BEGIN)}[\\\\s\\\\S]*?${escapeRe(NUDGE_END)}`).exec(text);\n if (!block) continue; // no vg block in this host file — nothing of ours to refresh\n const from = staleVersion(block[0], '## Code navigation (vg)');\n if (from !== null) {\n writeNudge(file, a.nudge, smallRepo, a.id);\n out.push({ file: a.nudge.file, from, to: INSTALL_CONTENT_VERSION });\n }\n } else {\n const from = staleVersion(text, '## Code navigation (vg)');\n if (from !== null) {\n writeNudge(file, a.nudge, smallRepo, a.id);\n out.push({ file: a.nudge.file, from, to: INSTALL_CONTENT_VERSION });\n }\n }\n }\n }\n return out;\n}\n\nfunction readTextSafe(file: string): string | null {\n try {\n return fs.readFileSync(file, 'utf8');\n } catch {\n return null; // unreadable — leave it alone\n }\n}\n\nfunction writeNudge(file: string, target: NudgeTarget, smallRepo: boolean, client?: string): void {\n if (target.kind === 'file') {\n // Dedicated rule file owned by vg (Cursor .mdc needs frontmatter).\n const body = file.endsWith('.mdc')\n ? `---\\ndescription: vg code graph\\nalwaysApply: true\\n---\\n${stripMarkers(nudgeMarkdown(smallRepo, client))}`\n : stripMarkers(nudgeMarkdown(smallRepo, client));\n writeFileEnsured(file, `${body}\\n`);\n return;\n }\n upsertBlock(file, nudgeMarkdown(smallRepo, client));\n}\n\nfunction upsertBlock(file: string, block: string): void {\n fs.mkdirSync(path.dirname(file), { recursive: true });\n let existing = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';\n const re = new RegExp(`${escapeRe(NUDGE_BEGIN)}[\\\\s\\\\S]*?${escapeRe(NUDGE_END)}`);\n if (re.test(existing)) existing = existing.replace(re, block);\n else existing = existing.length ? `${existing.replace(/\\s*$/, '')}\\n\\n${block}\\n` : `${block}\\n`;\n fs.writeFileSync(file, existing);\n}\n\nfunction removeBlock(file: string): boolean {\n if (!fs.existsSync(file)) return false;\n const existing = fs.readFileSync(file, 'utf8');\n const re = new RegExp(`\\\\n*${escapeRe(NUDGE_BEGIN)}[\\\\s\\\\S]*?${escapeRe(NUDGE_END)}\\\\n*`);\n if (!re.test(existing)) return false;\n fs.writeFileSync(file, existing.replace(re, '\\n'));\n return true;\n}\n\n/**\n * Read a JSON config we are about to merge into. A *missing* file is an empty\n * config; a *malformed* file must abort — silently treating it as empty would\n * rewrite the file and destroy the user's other MCP server entries.\n */\nfunction readJson(file: string): Record<string, unknown> {\n if (!fs.existsSync(file)) return {};\n try {\n const parsed = JSON.parse(fs.readFileSync(file, 'utf8')) as unknown;\n if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {\n return parsed as Record<string, unknown>;\n }\n throw new Error('not a JSON object');\n } catch {\n throw new CliError(\n `${file} exists but is not valid JSON — fix or remove it, then rerun. Refusing to overwrite it (that would lose your existing entries).`,\n ExitCode.ERROR,\n );\n }\n}\n\nfunction stripMarkers(s: string): string {\n return s.replace(NUDGE_BEGIN, '').replace(NUDGE_END, '').trim();\n}\n\nfunction escapeRe(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n"]}
|