graphifyy 0.3.17 → 0.3.28
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/README.ja-JP.md +60 -17
- package/README.md +41 -13
- package/README.zh-CN.md +54 -17
- package/dist/cli.js +862 -369
- package/dist/cli.js.map +1 -1
- package/dist/index.cjs +1070 -598
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +36 -6
- package/dist/index.d.ts +36 -6
- package/dist/index.js +1092 -614
- package/dist/index.js.map +1 -1
- package/dist/skill-runtime.js +1182 -669
- package/dist/skill-runtime.js.map +1 -1
- package/package.json +14 -4
- package/src/skills/skill-claw.md +1 -0
- package/src/skills/skill-codex.md +69 -11
- package/src/skills/skill-droid.md +73 -6
- package/src/skills/skill-gemini.toml +207 -0
- package/src/skills/skill-opencode.md +73 -6
- package/src/skills/skill-trae.md +1 -0
- package/src/skills/skill-windows.md +76 -5
- package/src/skills/skill.md +82 -8
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/skill-runtime.ts","../src/analyze.ts","../src/collections.ts","../src/cluster.ts","../src/benchmark.ts","../src/cache.ts","../src/build.ts","../src/validate.ts","../src/detect.ts","../src/export.ts","../src/security.ts","../src/extract.ts","../src/ingest.ts","../src/report.ts"],"sourcesContent":["import { Command } from \"commander\";\nimport Graph from \"graphology\";\nimport {\n existsSync,\n mkdirSync,\n readFileSync,\n writeFileSync,\n} from \"node:fs\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nimport { graphDiff, godNodes, surprisingConnections, suggestQuestions } from \"./analyze.js\";\nimport { runBenchmark, printBenchmark } from \"./benchmark.js\";\nimport { saveSemanticCache, checkSemanticCache } from \"./cache.js\";\nimport { buildFromJson } from \"./build.js\";\nimport { cluster, scoreAll } from \"./cluster.js\";\nimport { detect, detectIncremental, saveManifest } from \"./detect.js\";\nimport { toCypher, toGraphml, toHtml, toJson, toSvg, pushToNeo4j } from \"./export.js\";\nimport { extractWithDiagnostics } from \"./extract.js\";\nimport { ingest, saveQueryResult } from \"./ingest.js\";\nimport { generate } from \"./report.js\";\nimport type {\n DetectionResult,\n Extraction,\n GodNodeEntry,\n GraphDiffResult,\n SuggestedQuestion,\n SurpriseEntry,\n} from \"./types.js\";\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\ninterface AnalysisFile {\n communities: Record<string, string[]>;\n cohesion: Record<string, number>;\n gods: GodNodeEntry[];\n surprises: SurpriseEntry[];\n questions?: SuggestedQuestion[];\n labels?: Record<string, string>;\n diff?: GraphDiffResult;\n}\n\nfunction readJson<T>(path: string): T {\n return JSON.parse(readFileSync(resolve(path), \"utf-8\")) as T;\n}\n\nfunction writeJson(path: string, value: unknown): void {\n const resolved = resolve(path);\n mkdirSync(dirname(resolved), { recursive: true });\n writeFileSync(resolved, JSON.stringify(value, null, 2), \"utf-8\");\n}\n\nfunction getVersion(): string {\n try {\n const pkg = JSON.parse(readFileSync(join(__dirname, \"..\", \"package.json\"), \"utf-8\"));\n return pkg.version ?? \"unknown\";\n } catch {\n return \"unknown\";\n }\n}\n\nfunction defaultLabels(communities: Map<number, string[]>): Map<number, string> {\n const labels = new Map<number, string>();\n for (const cid of communities.keys()) {\n labels.set(cid, `Community ${cid}`);\n }\n return labels;\n}\n\nfunction mapToObject<V>(map: Map<number, V>): Record<string, V> {\n return Object.fromEntries([...map.entries()].map(([k, v]) => [String(k), v]));\n}\n\nfunction objectToStringMap(obj?: Record<string, string> | null): Map<number, string> {\n const result = new Map<number, string>();\n if (!obj) return result;\n for (const [key, value] of Object.entries(obj)) {\n const cid = Number.parseInt(key, 10);\n if (Number.isFinite(cid)) result.set(cid, value);\n }\n return result;\n}\n\nfunction ensureExtractionShape(value?: Partial<Extraction> | null): Extraction {\n return {\n nodes: value?.nodes ?? [],\n edges: value?.edges ?? [],\n hyperedges: value?.hyperedges ?? [],\n input_tokens: value?.input_tokens ?? 0,\n output_tokens: value?.output_tokens ?? 0,\n };\n}\n\nfunction loadGraph(graphPath: string): Graph {\n const raw = readJson<{\n nodes?: Array<Record<string, unknown> & { id: string }>;\n links?: Array<Record<string, unknown> & { source: string; target: string }>;\n hyperedges?: Array<Record<string, unknown>>;\n }>(graphPath);\n const G = new Graph({ type: \"undirected\" });\n\n for (const node of raw.nodes ?? []) {\n const { id, ...attrs } = node;\n G.mergeNode(id, attrs);\n }\n for (const link of raw.links ?? []) {\n const { source, target, ...attrs } = link;\n if (!G.hasNode(source) || !G.hasNode(target)) continue;\n try {\n G.mergeEdge(source, target, attrs);\n } catch {\n /* ignore duplicate merge failures */\n }\n }\n if (raw.hyperedges && raw.hyperedges.length > 0) {\n G.setAttribute(\"hyperedges\", raw.hyperedges);\n }\n return G;\n}\n\nfunction mergeHyperedges(\n existing: Array<Record<string, unknown>> = [],\n incoming: Array<Record<string, unknown>> = [],\n): Array<Record<string, unknown>> {\n const seen = new Set<string>();\n const merged: Array<Record<string, unknown>> = [];\n for (const hyperedge of [...existing, ...incoming]) {\n const id = String(hyperedge.id ?? \"\");\n const key = id || JSON.stringify(hyperedge);\n if (seen.has(key)) continue;\n seen.add(key);\n merged.push(hyperedge);\n }\n return merged;\n}\n\nfunction mergeGraphs(target: Graph, source: Graph): void {\n source.forEachNode((nodeId, attrs) => {\n target.mergeNode(nodeId, attrs);\n });\n source.forEachEdge((_edge, attrs, sourceId, targetId) => {\n if (!target.hasNode(sourceId) || !target.hasNode(targetId)) return;\n try {\n target.mergeEdge(sourceId, targetId, attrs);\n } catch {\n /* ignore */\n }\n });\n const mergedHyperedges = mergeHyperedges(\n (target.getAttribute(\"hyperedges\") as Array<Record<string, unknown>> | undefined) ?? [],\n (source.getAttribute(\"hyperedges\") as Array<Record<string, unknown>> | undefined) ?? [],\n );\n if (mergedHyperedges.length > 0) {\n target.setAttribute(\"hyperedges\", mergedHyperedges);\n }\n}\n\nfunction analyzeGraph(\n G: Graph,\n detection: DetectionResult,\n root: string,\n tokenCost: { input: number; output: number },\n labelsOverride?: Map<number, string>,\n): {\n communities: Map<number, string[]>;\n cohesion: Map<number, number>;\n labels: Map<number, string>;\n gods: GodNodeEntry[];\n surprises: SurpriseEntry[];\n questions: SuggestedQuestion[];\n report: string;\n analysis: AnalysisFile;\n} {\n const communities = cluster(G);\n const cohesion = scoreAll(G, communities);\n const labels = labelsOverride && labelsOverride.size > 0 ? labelsOverride : defaultLabels(communities);\n const gods = godNodes(G);\n const surprises = surprisingConnections(G, communities);\n const questions = suggestQuestions(G, communities, labels);\n const report = generate(\n G,\n communities,\n cohesion,\n labels,\n gods,\n surprises,\n detection,\n tokenCost,\n root,\n questions,\n );\n return {\n communities,\n cohesion,\n labels,\n gods,\n surprises,\n questions,\n report,\n analysis: {\n communities: mapToObject(communities),\n cohesion: mapToObject(cohesion),\n gods,\n surprises,\n questions,\n labels: mapToObject(labels),\n },\n };\n}\n\nfunction placeholderDetection(root: string = \".\"): DetectionResult {\n return {\n files: { code: [], document: [], paper: [], image: [] },\n total_files: 0,\n total_words: 0,\n needs_graph: true,\n warning: `Reused existing graph at ${resolve(root)} without re-running corpus detection.`,\n skipped_sensitive: [],\n graphifyignore_patterns: 0,\n };\n}\n\nfunction mergeSemanticArtifacts(\n cached: Partial<Extraction> | null | undefined,\n fresh: Partial<Extraction> | null | undefined,\n): Extraction {\n const cachedExtraction = ensureExtractionShape(cached);\n const freshExtraction = ensureExtractionShape(fresh);\n\n const dedupedNodes: Extraction[\"nodes\"] = [];\n const seen = new Set<string>();\n for (const node of [...cachedExtraction.nodes, ...freshExtraction.nodes]) {\n if (seen.has(node.id)) continue;\n seen.add(node.id);\n dedupedNodes.push(node);\n }\n\n return {\n nodes: dedupedNodes,\n edges: [...cachedExtraction.edges, ...freshExtraction.edges],\n hyperedges: [...(cachedExtraction.hyperedges ?? []), ...(freshExtraction.hyperedges ?? [])],\n input_tokens: freshExtraction.input_tokens ?? 0,\n output_tokens: freshExtraction.output_tokens ?? 0,\n };\n}\n\nfunction mergeAstAndSemantic(\n astInput: Partial<Extraction> | null | undefined,\n semanticInput: Partial<Extraction> | null | undefined,\n): Extraction {\n const ast = ensureExtractionShape(astInput);\n const semantic = ensureExtractionShape(semanticInput);\n\n const mergedNodes: Extraction[\"nodes\"] = [...ast.nodes];\n const seen = new Set(ast.nodes.map((node) => node.id));\n for (const node of semantic.nodes) {\n if (seen.has(node.id)) continue;\n seen.add(node.id);\n mergedNodes.push(node);\n }\n\n return {\n nodes: mergedNodes,\n edges: [...ast.edges, ...semantic.edges],\n hyperedges: semantic.hyperedges ?? [],\n input_tokens: semantic.input_tokens ?? 0,\n output_tokens: semantic.output_tokens ?? 0,\n };\n}\n\nfunction updateCostFile(\n extractionInput: Partial<Extraction> | null | undefined,\n detection: DetectionResult,\n outPath: string,\n): {\n runs: Array<{ date: string; input_tokens: number; output_tokens: number; files: number }>;\n total_input_tokens: number;\n total_output_tokens: number;\n} {\n const extraction = ensureExtractionShape(extractionInput);\n let cost = {\n runs: [] as Array<{ date: string; input_tokens: number; output_tokens: number; files: number }>,\n total_input_tokens: 0,\n total_output_tokens: 0,\n };\n const resolved = resolve(outPath);\n if (existsSync(resolved)) {\n cost = readJson<typeof cost>(resolved);\n }\n\n const input = extraction.input_tokens ?? 0;\n const output = extraction.output_tokens ?? 0;\n cost.runs.push({\n date: new Date().toISOString(),\n input_tokens: input,\n output_tokens: output,\n files: detection.total_files,\n });\n cost.total_input_tokens += input;\n cost.total_output_tokens += output;\n writeJson(resolved, cost);\n return cost;\n}\n\nfunction findBestMatchingNode(G: Graph, term: string): string | null {\n const words = term.toLowerCase().split(/\\s+/).filter(Boolean);\n let best: { score: number; nodeId: string } | null = null;\n G.forEachNode((nodeId, data) => {\n const label = ((data.label as string) ?? \"\").toLowerCase();\n const score = words.filter((word) => label.includes(word)).length;\n if (score <= 0) return;\n if (!best || score > best.score) {\n best = { score, nodeId };\n }\n });\n return best?.nodeId ?? null;\n}\n\nfunction runtimeInfo(): Record<string, string> {\n return {\n runtime: \"typescript\",\n version: getVersion(),\n node: process.execPath,\n script: __filename,\n module: join(__dirname, \"index.js\"),\n cli: join(__dirname, \"cli.js\"),\n };\n}\n\nasync function main(): Promise<void> {\n const program = new Command();\n program.name(\"graphify-skill-runtime\");\n\n program\n .command(\"runtime-info\")\n .description(\"Print the runtime metadata for the Codex TypeScript skill\")\n .action(() => {\n console.log(JSON.stringify(runtimeInfo(), null, 2));\n });\n\n program\n .command(\"detect\")\n .argument(\"<inputPath>\")\n .option(\"--out <path>\")\n .action((inputPath, opts) => {\n const result = detect(resolve(inputPath));\n if (opts.out) {\n writeJson(opts.out, result);\n console.log(`Detected ${result.total_files} files in ${resolve(inputPath)}`);\n } else {\n console.log(JSON.stringify(result, null, 2));\n }\n });\n\n program\n .command(\"detect-incremental\")\n .argument(\"<inputPath>\")\n .option(\"--manifest <path>\", \"Path to manifest.json\", \"graphify-out/manifest.json\")\n .option(\"--out <path>\")\n .action((inputPath, opts) => {\n const result = detectIncremental(resolve(inputPath), resolve(opts.manifest));\n if (opts.out) {\n writeJson(opts.out, result);\n console.log(`${result.new_total ?? 0} new/changed file(s) under ${resolve(inputPath)}`);\n } else {\n console.log(JSON.stringify(result, null, 2));\n }\n });\n\n program\n .command(\"extract-ast\")\n .requiredOption(\"--detect <path>\", \"Path to detection JSON\")\n .requiredOption(\"--out <path>\", \"Path to AST extraction JSON\")\n .option(\"--incremental\", \"Use detection.new_files.code instead of detection.files.code\")\n .action(async (opts) => {\n const detection = readJson<DetectionResult>(opts.detect);\n const codeFiles = opts.incremental\n ? detection.new_files?.code ?? []\n : detection.files.code ?? [];\n\n if (codeFiles.length === 0) {\n writeJson(opts.out, ensureExtractionShape());\n console.log(\"No code files - skipping AST extraction\");\n return;\n }\n\n const { extraction, diagnostics } = await extractWithDiagnostics(codeFiles);\n writeJson(opts.out, extraction);\n if (diagnostics.length > 0) {\n const sample = diagnostics\n .slice(0, 3)\n .map((d) => `${d.filePath}: ${d.error}`)\n .join(\" | \");\n console.log(`AST: ${extraction.nodes.length} nodes, ${extraction.edges.length} edges (${diagnostics.length} file(s) failed: ${sample})`);\n return;\n }\n console.log(`AST: ${extraction.nodes.length} nodes, ${extraction.edges.length} edges`);\n });\n\n program\n .command(\"check-semantic-cache\")\n .requiredOption(\"--detect <path>\", \"Path to detection JSON\")\n .option(\"--incremental\", \"Use detection.new_files when present\")\n .option(\"--root <path>\", \"Graph root for cache resolution\", \".\")\n .requiredOption(\"--cached-out <path>\", \"Path to cached extraction JSON\")\n .requiredOption(\"--uncached-out <path>\", \"Path to newline-delimited uncached file list\")\n .action((opts) => {\n const detection = readJson<DetectionResult>(opts.detect);\n const source = opts.incremental && detection.new_files ? detection.new_files : detection.files;\n const allFiles = [\n ...(source.document ?? []),\n ...(source.paper ?? []),\n ...(source.image ?? []),\n ];\n const [cachedNodes, cachedEdges, cachedHyperedges, uncached] = checkSemanticCache(\n allFiles,\n resolve(opts.root),\n );\n writeJson(opts.cachedOut, {\n nodes: cachedNodes,\n edges: cachedEdges,\n hyperedges: cachedHyperedges,\n });\n mkdirSync(dirname(resolve(opts.uncachedOut)), { recursive: true });\n writeFileSync(resolve(opts.uncachedOut), uncached.join(\"\\n\"), \"utf-8\");\n console.log(`Cache: ${allFiles.length - uncached.length} files hit, ${uncached.length} files need extraction`);\n });\n\n program\n .command(\"save-semantic-cache\")\n .requiredOption(\"--input <path>\", \"Path to semantic extraction JSON\")\n .option(\"--root <path>\", \"Graph root for cache resolution\", \".\")\n .action((opts) => {\n const extraction = ensureExtractionShape(readJson<Partial<Extraction>>(opts.input));\n const saved = saveSemanticCache(\n extraction.nodes as Array<Record<string, unknown>>,\n extraction.edges as Array<Record<string, unknown>>,\n (extraction.hyperedges ?? []) as Array<Record<string, unknown>>,\n resolve(opts.root),\n );\n console.log(`Cached ${saved} files`);\n });\n\n program\n .command(\"merge-semantic\")\n .requiredOption(\"--cached <path>\")\n .requiredOption(\"--new <path>\")\n .requiredOption(\"--out <path>\")\n .action((opts) => {\n const cached = ensureExtractionShape(readJson<Partial<Extraction>>(opts.cached));\n const fresh = ensureExtractionShape(readJson<Partial<Extraction>>(opts.new));\n\n const dedupedNodes: Extraction[\"nodes\"] = [];\n const seen = new Set<string>();\n for (const node of [...cached.nodes, ...fresh.nodes]) {\n if (seen.has(node.id)) continue;\n seen.add(node.id);\n dedupedNodes.push(node);\n }\n\n const merged: Extraction = {\n nodes: dedupedNodes,\n edges: [...cached.edges, ...fresh.edges],\n hyperedges: [...(cached.hyperedges ?? []), ...(fresh.hyperedges ?? [])],\n input_tokens: fresh.input_tokens ?? 0,\n output_tokens: fresh.output_tokens ?? 0,\n };\n writeJson(opts.out, merged);\n console.log(\n `Extraction complete - ${merged.nodes.length} nodes, ${merged.edges.length} edges (${cached.nodes.length} from cache, ${fresh.nodes.length} new)`,\n );\n });\n\n program\n .command(\"merge-extraction\")\n .requiredOption(\"--ast <path>\")\n .requiredOption(\"--semantic <path>\")\n .requiredOption(\"--out <path>\")\n .action((opts) => {\n const ast = ensureExtractionShape(readJson<Partial<Extraction>>(opts.ast));\n const semantic = ensureExtractionShape(readJson<Partial<Extraction>>(opts.semantic));\n\n const mergedNodes: Extraction[\"nodes\"] = [...ast.nodes];\n const seen = new Set(ast.nodes.map((node) => node.id));\n for (const node of semantic.nodes) {\n if (seen.has(node.id)) continue;\n seen.add(node.id);\n mergedNodes.push(node);\n }\n\n const merged: Extraction = {\n nodes: mergedNodes,\n edges: [...ast.edges, ...semantic.edges],\n hyperedges: semantic.hyperedges ?? [],\n input_tokens: semantic.input_tokens ?? 0,\n output_tokens: semantic.output_tokens ?? 0,\n };\n writeJson(opts.out, merged);\n console.log(\n `Merged: ${merged.nodes.length} nodes, ${merged.edges.length} edges (${ast.nodes.length} AST + ${semantic.nodes.length} semantic)`,\n );\n });\n\n program\n .command(\"finalize-build\")\n .requiredOption(\"--detect <path>\")\n .requiredOption(\"--ast <path>\")\n .requiredOption(\"--root <path>\")\n .requiredOption(\"--graph-out <path>\")\n .requiredOption(\"--report-out <path>\")\n .requiredOption(\"--analysis-out <path>\")\n .requiredOption(\"--cost-out <path>\")\n .option(\"--cached <path>\", \"Optional cached semantic JSON\")\n .option(\"--semantic-new <path>\", \"Optional fresh semantic JSON\")\n .option(\"--html-out <path>\", \"Optional graph.html output path\")\n .action((opts) => {\n const detection = readJson<DetectionResult>(opts.detect);\n const ast = ensureExtractionShape(readJson<Partial<Extraction>>(opts.ast));\n const cached = opts.cached && existsSync(resolve(opts.cached))\n ? readJson<Partial<Extraction>>(opts.cached)\n : null;\n const semanticNew = opts.semanticNew && existsSync(resolve(opts.semanticNew))\n ? readJson<Partial<Extraction>>(opts.semanticNew)\n : null;\n\n if (semanticNew) {\n saveSemanticCache(\n semanticNew.nodes as Array<Record<string, unknown>>,\n semanticNew.edges as Array<Record<string, unknown>>,\n (semanticNew.hyperedges ?? []) as Array<Record<string, unknown>>,\n \".\",\n );\n }\n\n const semantic = mergeSemanticArtifacts(cached, semanticNew);\n const extraction = mergeAstAndSemantic(ast, semantic);\n const G = buildFromJson(extraction);\n if (G.order === 0) {\n throw new Error(\"Graph is empty - extraction produced no nodes.\");\n }\n\n const analyzed = analyzeGraph(\n G,\n detection,\n resolve(opts.root),\n { input: extraction.input_tokens ?? 0, output: extraction.output_tokens ?? 0 },\n );\n\n toJson(G, analyzed.communities, resolve(opts.graphOut));\n writeFileSync(resolve(opts.reportOut), analyzed.report, \"utf-8\");\n writeJson(opts.analysisOut, analyzed.analysis);\n if (opts.htmlOut) {\n toHtml(G, analyzed.communities, resolve(opts.htmlOut), {\n communityLabels: analyzed.labels,\n });\n }\n saveManifest(detection.files, join(dirname(resolve(opts.graphOut)), \"manifest.json\"));\n const cost = updateCostFile(extraction, detection, opts.costOut);\n\n console.log(`Graph: ${G.order} nodes, ${G.size} edges, ${analyzed.communities.size} communities`);\n console.log(`This run: ${(extraction.input_tokens ?? 0).toLocaleString()} input tokens, ${(extraction.output_tokens ?? 0).toLocaleString()} output tokens`);\n console.log(`All time: ${cost.total_input_tokens.toLocaleString()} input, ${cost.total_output_tokens.toLocaleString()} output (${cost.runs.length} runs)`);\n });\n\n program\n .command(\"finalize-update\")\n .requiredOption(\"--detect <path>\")\n .requiredOption(\"--ast <path>\")\n .requiredOption(\"--existing-graph <path>\")\n .requiredOption(\"--root <path>\")\n .requiredOption(\"--graph-out <path>\")\n .requiredOption(\"--report-out <path>\")\n .requiredOption(\"--analysis-out <path>\")\n .requiredOption(\"--cost-out <path>\")\n .option(\"--cached <path>\", \"Optional cached semantic JSON\")\n .option(\"--semantic-new <path>\", \"Optional fresh semantic JSON\")\n .option(\"--html-out <path>\", \"Optional graph.html output path\")\n .action((opts) => {\n const detection = readJson<DetectionResult>(opts.detect);\n const ast = ensureExtractionShape(readJson<Partial<Extraction>>(opts.ast));\n const cached = opts.cached && existsSync(resolve(opts.cached))\n ? readJson<Partial<Extraction>>(opts.cached)\n : null;\n const semanticNew = opts.semanticNew && existsSync(resolve(opts.semanticNew))\n ? readJson<Partial<Extraction>>(opts.semanticNew)\n : null;\n\n if (semanticNew) {\n saveSemanticCache(\n semanticNew.nodes as Array<Record<string, unknown>>,\n semanticNew.edges as Array<Record<string, unknown>>,\n (semanticNew.hyperedges ?? []) as Array<Record<string, unknown>>,\n \".\",\n );\n }\n\n const semantic = mergeSemanticArtifacts(cached, semanticNew);\n const extraction = mergeAstAndSemantic(ast, semantic);\n\n const oldGraph = loadGraph(opts.existingGraph);\n const mergedGraph = loadGraph(opts.existingGraph);\n const newGraph = buildFromJson(extraction);\n mergeGraphs(mergedGraph, newGraph);\n\n const analyzed = analyzeGraph(\n mergedGraph,\n detection,\n resolve(opts.root),\n { input: extraction.input_tokens ?? 0, output: extraction.output_tokens ?? 0 },\n );\n analyzed.analysis.diff = graphDiff(oldGraph, mergedGraph);\n\n toJson(mergedGraph, analyzed.communities, resolve(opts.graphOut));\n writeFileSync(resolve(opts.reportOut), analyzed.report, \"utf-8\");\n writeJson(opts.analysisOut, analyzed.analysis);\n if (opts.htmlOut) {\n toHtml(mergedGraph, analyzed.communities, resolve(opts.htmlOut), {\n communityLabels: analyzed.labels,\n });\n }\n saveManifest(detection.files, join(dirname(resolve(opts.graphOut)), \"manifest.json\"));\n const cost = updateCostFile(extraction, detection, opts.costOut);\n\n console.log(`Merged: ${mergedGraph.order} nodes, ${mergedGraph.size} edges`);\n console.log(analyzed.analysis.diff.summary);\n console.log(`This run: ${(extraction.input_tokens ?? 0).toLocaleString()} input tokens, ${(extraction.output_tokens ?? 0).toLocaleString()} output tokens`);\n console.log(`All time: ${cost.total_input_tokens.toLocaleString()} input, ${cost.total_output_tokens.toLocaleString()} output (${cost.runs.length} runs)`);\n });\n\n program\n .command(\"analyze-build\")\n .requiredOption(\"--extract <path>\")\n .requiredOption(\"--detect <path>\")\n .requiredOption(\"--root <path>\")\n .requiredOption(\"--graph-out <path>\")\n .requiredOption(\"--report-out <path>\")\n .requiredOption(\"--analysis-out <path>\")\n .action((opts) => {\n const extraction = ensureExtractionShape(readJson<Partial<Extraction>>(opts.extract));\n const detection = readJson<DetectionResult>(opts.detect);\n const root = resolve(opts.root);\n const G = buildFromJson(extraction);\n\n if (G.order === 0) {\n throw new Error(\"Graph is empty - extraction produced no nodes.\");\n }\n\n const analyzed = analyzeGraph(\n G,\n detection,\n root,\n { input: extraction.input_tokens ?? 0, output: extraction.output_tokens ?? 0 },\n );\n\n mkdirSync(dirname(resolve(opts.graphOut)), { recursive: true });\n toJson(G, analyzed.communities, resolve(opts.graphOut));\n writeFileSync(resolve(opts.reportOut), analyzed.report, \"utf-8\");\n writeJson(opts.analysisOut, analyzed.analysis);\n saveManifest(detection.files, join(dirname(resolve(opts.graphOut)), \"manifest.json\"));\n console.log(`Graph: ${G.order} nodes, ${G.size} edges, ${analyzed.communities.size} communities`);\n });\n\n program\n .command(\"write-labeled-report\")\n .requiredOption(\"--extract <path>\")\n .requiredOption(\"--detect <path>\")\n .requiredOption(\"--analysis <path>\")\n .requiredOption(\"--labels <path>\")\n .requiredOption(\"--root <path>\")\n .requiredOption(\"--report-out <path>\")\n .action((opts) => {\n const extraction = ensureExtractionShape(readJson<Partial<Extraction>>(opts.extract));\n const detection = readJson<DetectionResult>(opts.detect);\n const analysis = readJson<AnalysisFile>(opts.analysis);\n const labelObject = readJson<Record<string, string>>(opts.labels);\n const labels = objectToStringMap(labelObject);\n const G = buildFromJson(extraction);\n const communities = new Map<number, string[]>(\n Object.entries(analysis.communities).map(([key, value]) => [Number.parseInt(key, 10), value]),\n );\n const cohesion = new Map<number, number>(\n Object.entries(analysis.cohesion).map(([key, value]) => [Number.parseInt(key, 10), value]),\n );\n const questions = suggestQuestions(G, communities, labels);\n const report = generate(\n G,\n communities,\n cohesion,\n labels,\n analysis.gods,\n analysis.surprises,\n detection,\n { input: extraction.input_tokens ?? 0, output: extraction.output_tokens ?? 0 },\n resolve(opts.root),\n questions,\n );\n\n analysis.questions = questions;\n analysis.labels = mapToObject(labels);\n writeFileSync(resolve(opts.reportOut), report, \"utf-8\");\n writeJson(opts.analysis, analysis);\n console.log(\"Report updated with community labels\");\n });\n\n program\n .command(\"export-html\")\n .requiredOption(\"--extract <path>\")\n .requiredOption(\"--analysis <path>\")\n .option(\"--labels <path>\")\n .requiredOption(\"--out <path>\")\n .action((opts) => {\n const extraction = ensureExtractionShape(readJson<Partial<Extraction>>(opts.extract));\n const analysis = readJson<AnalysisFile>(opts.analysis);\n const labels = opts.labels ? objectToStringMap(readJson<Record<string, string>>(opts.labels)) : objectToStringMap(analysis.labels);\n const communities = new Map<number, string[]>(\n Object.entries(analysis.communities).map(([key, value]) => [Number.parseInt(key, 10), value]),\n );\n const G = buildFromJson(extraction);\n toHtml(G, communities, resolve(opts.out), { communityLabels: labels });\n console.log(\"graph.html written - open in any browser, no server needed\");\n });\n\n program\n .command(\"export-svg\")\n .requiredOption(\"--extract <path>\")\n .requiredOption(\"--analysis <path>\")\n .option(\"--labels <path>\")\n .requiredOption(\"--out <path>\")\n .action((opts) => {\n const extraction = ensureExtractionShape(readJson<Partial<Extraction>>(opts.extract));\n const analysis = readJson<AnalysisFile>(opts.analysis);\n const labels = opts.labels ? objectToStringMap(readJson<Record<string, string>>(opts.labels)) : objectToStringMap(analysis.labels);\n const communities = new Map<number, string[]>(\n Object.entries(analysis.communities).map(([key, value]) => [Number.parseInt(key, 10), value]),\n );\n const G = buildFromJson(extraction);\n toSvg(G, communities, resolve(opts.out), labels);\n console.log(\"graph.svg written - embeds in Obsidian, Notion, GitHub READMEs\");\n });\n\n program\n .command(\"export-graphml\")\n .requiredOption(\"--extract <path>\")\n .requiredOption(\"--analysis <path>\")\n .requiredOption(\"--out <path>\")\n .action((opts) => {\n const extraction = ensureExtractionShape(readJson<Partial<Extraction>>(opts.extract));\n const analysis = readJson<AnalysisFile>(opts.analysis);\n const communities = new Map<number, string[]>(\n Object.entries(analysis.communities).map(([key, value]) => [Number.parseInt(key, 10), value]),\n );\n const G = buildFromJson(extraction);\n toGraphml(G, communities, resolve(opts.out));\n console.log(\"graph.graphml written - open in Gephi, yEd, or any GraphML tool\");\n });\n\n program\n .command(\"export-cypher\")\n .requiredOption(\"--extract <path>\")\n .requiredOption(\"--out <path>\")\n .action((opts) => {\n const extraction = ensureExtractionShape(readJson<Partial<Extraction>>(opts.extract));\n const G = buildFromJson(extraction);\n toCypher(G, resolve(opts.out));\n console.log(\"cypher.txt written - import with: cypher-shell < graphify-out/cypher.txt\");\n });\n\n program\n .command(\"push-neo4j\")\n .requiredOption(\"--extract <path>\")\n .requiredOption(\"--analysis <path>\")\n .requiredOption(\"--uri <uri>\")\n .requiredOption(\"--user <user>\")\n .requiredOption(\"--password <password>\")\n .action(async (opts) => {\n const extraction = ensureExtractionShape(readJson<Partial<Extraction>>(opts.extract));\n const analysis = readJson<AnalysisFile>(opts.analysis);\n const G = buildFromJson(extraction);\n const communities = new Map<number, string[]>(\n Object.entries(analysis.communities).map(([key, value]) => [Number.parseInt(key, 10), value]),\n );\n const result = await pushToNeo4j(G, {\n uri: opts.uri,\n user: opts.user,\n password: opts.password,\n communities,\n });\n console.log(`Pushed to Neo4j: ${result.nodes} nodes, ${result.edges} edges`);\n });\n\n program\n .command(\"benchmark\")\n .requiredOption(\"--graph <path>\")\n .option(\"--corpus-words <n>\")\n .action((opts) => {\n const corpusWords = opts.corpusWords ? Number.parseInt(opts.corpusWords, 10) : undefined;\n const result = runBenchmark(resolve(opts.graph), corpusWords);\n printBenchmark(result);\n });\n\n program\n .command(\"update-cost\")\n .requiredOption(\"--extract <path>\")\n .requiredOption(\"--detect <path>\")\n .requiredOption(\"--out <path>\")\n .action((opts) => {\n const extraction = ensureExtractionShape(readJson<Partial<Extraction>>(opts.extract));\n const detection = readJson<DetectionResult>(opts.detect);\n const outPath = resolve(opts.out);\n\n let cost = {\n runs: [] as Array<{ date: string; input_tokens: number; output_tokens: number; files: number }>,\n total_input_tokens: 0,\n total_output_tokens: 0,\n };\n if (existsSync(outPath)) {\n cost = readJson<typeof cost>(outPath);\n }\n\n const input = extraction.input_tokens ?? 0;\n const output = extraction.output_tokens ?? 0;\n cost.runs.push({\n date: new Date().toISOString(),\n input_tokens: input,\n output_tokens: output,\n files: detection.total_files,\n });\n cost.total_input_tokens += input;\n cost.total_output_tokens += output;\n writeJson(outPath, cost);\n\n console.log(`This run: ${input.toLocaleString()} input tokens, ${output.toLocaleString()} output tokens`);\n console.log(\n `All time: ${cost.total_input_tokens.toLocaleString()} input, ${cost.total_output_tokens.toLocaleString()} output (${cost.runs.length} runs)`,\n );\n });\n\n program\n .command(\"merge-update\")\n .requiredOption(\"--existing-graph <path>\")\n .requiredOption(\"--extract <path>\")\n .requiredOption(\"--detect <path>\")\n .requiredOption(\"--root <path>\")\n .requiredOption(\"--graph-out <path>\")\n .requiredOption(\"--report-out <path>\")\n .requiredOption(\"--analysis-out <path>\")\n .action((opts) => {\n const oldGraph = loadGraph(opts.existingGraph);\n const mergedGraph = loadGraph(opts.existingGraph);\n const extraction = ensureExtractionShape(readJson<Partial<Extraction>>(opts.extract));\n const detection = readJson<DetectionResult>(opts.detect);\n const newGraph = buildFromJson(extraction);\n\n mergeGraphs(mergedGraph, newGraph);\n\n const analyzed = analyzeGraph(\n mergedGraph,\n detection,\n resolve(opts.root),\n { input: extraction.input_tokens ?? 0, output: extraction.output_tokens ?? 0 },\n );\n analyzed.analysis.diff = graphDiff(oldGraph, mergedGraph);\n\n toJson(mergedGraph, analyzed.communities, resolve(opts.graphOut));\n writeFileSync(resolve(opts.reportOut), analyzed.report, \"utf-8\");\n writeJson(opts.analysisOut, analyzed.analysis);\n saveManifest(detection.files, join(dirname(resolve(opts.graphOut)), \"manifest.json\"));\n\n console.log(`Merged: ${mergedGraph.order} nodes, ${mergedGraph.size} edges`);\n console.log(analyzed.analysis.diff.summary);\n });\n\n program\n .command(\"cluster-only\")\n .requiredOption(\"--graph <path>\")\n .requiredOption(\"--root <path>\")\n .requiredOption(\"--graph-out <path>\")\n .requiredOption(\"--report-out <path>\")\n .requiredOption(\"--analysis-out <path>\")\n .action((opts) => {\n const G = loadGraph(opts.graph);\n const analyzed = analyzeGraph(\n G,\n placeholderDetection(opts.root),\n resolve(opts.root),\n { input: 0, output: 0 },\n );\n toJson(G, analyzed.communities, resolve(opts.graphOut));\n writeFileSync(resolve(opts.reportOut), analyzed.report, \"utf-8\");\n writeJson(opts.analysisOut, analyzed.analysis);\n console.log(`Re-clustered: ${analyzed.communities.size} communities`);\n });\n\n program\n .command(\"path\")\n .requiredOption(\"--graph <path>\")\n .argument(\"<nodeA>\")\n .argument(\"<nodeB>\")\n .action(async (nodeA, nodeB, opts) => {\n const G = loadGraph(opts.graph);\n const source = findBestMatchingNode(G, nodeA);\n const target = findBestMatchingNode(G, nodeB);\n if (!source || !target) {\n console.log(`Could not find nodes matching: ${JSON.stringify(nodeA)} or ${JSON.stringify(nodeB)}`);\n return;\n }\n let path: string[];\n try {\n const shortestPath = await import(\"graphology-shortest-path/unweighted.js\");\n path = shortestPath.bidirectional(G, source, target) ?? [];\n } catch {\n throw new Error(\"graphology-shortest-path is unavailable\");\n }\n if (path.length === 0) {\n console.log(`No path found between ${JSON.stringify(nodeA)} and ${JSON.stringify(nodeB)}`);\n return;\n }\n console.log(`Shortest path (${path.length - 1} hops):`);\n for (let i = 0; i < path.length; i++) {\n const nodeId = path[i]!;\n const label = (G.getNodeAttribute(nodeId, \"label\") as string) ?? nodeId;\n if (i === path.length - 1) {\n console.log(` ${label}`);\n break;\n }\n const nextNode = path[i + 1]!;\n const edgeId = G.edge(nodeId, nextNode);\n const attrs = edgeId ? G.getEdgeAttributes(edgeId) : {};\n console.log(` ${label} --${attrs.relation ?? \"\"}--> [${attrs.confidence ?? \"\"}]`);\n }\n });\n\n program\n .command(\"explain\")\n .requiredOption(\"--graph <path>\")\n .argument(\"<nodeName>\")\n .action((nodeName, opts) => {\n const G = loadGraph(opts.graph);\n const nodeId = findBestMatchingNode(G, nodeName);\n if (!nodeId) {\n console.log(`No node matching ${JSON.stringify(nodeName)}`);\n return;\n }\n const attrs = G.getNodeAttributes(nodeId);\n console.log(`NODE: ${(attrs.label as string) ?? nodeId}`);\n console.log(` source: ${(attrs.source_file as string) ?? \"unknown\"}`);\n console.log(` type: ${(attrs.file_type as string) ?? \"unknown\"}`);\n console.log(` degree: ${G.degree(nodeId)}`);\n console.log(\"\");\n console.log(\"CONNECTIONS:\");\n G.forEachNeighbor(nodeId, (neighbor) => {\n const edgeId = G.edge(nodeId, neighbor);\n const edge = edgeId ? G.getEdgeAttributes(edgeId) : {};\n const label = (G.getNodeAttribute(neighbor, \"label\") as string) ?? neighbor;\n const sourceFile = (G.getNodeAttribute(neighbor, \"source_file\") as string) ?? \"\";\n console.log(` --${edge.relation ?? \"\"}--> ${label} [${edge.confidence ?? \"\"}] (${sourceFile})`);\n });\n });\n\n program\n .command(\"ingest\")\n .argument(\"<url>\")\n .option(\"--target-dir <path>\", \"Directory to save fetched content\", \"./raw\")\n .option(\"--author <name>\")\n .option(\"--contributor <name>\")\n .action(async (url, opts) => {\n const outPath = await ingest(url, resolve(opts.targetDir), {\n author: opts.author ?? null,\n contributor: opts.contributor ?? null,\n });\n console.log(`Saved to ${outPath}`);\n });\n\n program\n .command(\"save-query-result\")\n .requiredOption(\"--question <text>\")\n .requiredOption(\"--answer <text>\")\n .requiredOption(\"--memory-dir <path>\")\n .option(\"--query-type <type>\", \"Type label for the saved Q&A\", \"query\")\n .option(\"--source-nodes-json <json>\", \"JSON array of source node labels\", \"[]\")\n .action((opts) => {\n const outPath = saveQueryResult({\n question: opts.question,\n answer: opts.answer,\n memoryDir: resolve(opts.memoryDir),\n queryType: opts.queryType,\n sourceNodes: JSON.parse(opts.sourceNodesJson) as string[],\n });\n console.log(`Saved to ${outPath}`);\n });\n\n await program.parseAsync(process.argv);\n}\n\nmain().catch((error) => {\n const message = error instanceof Error ? error.message : String(error);\n console.error(message);\n process.exit(1);\n});\n","/**\n * Graph analysis: god nodes (most connected), surprising connections (cross-community),\n * suggested questions, graph diff.\n */\nimport Graph from \"graphology\";\nimport betweennessCentrality from \"graphology-metrics/centrality/betweenness.js\";\nimport type { GodNodeEntry, SurpriseEntry, SuggestedQuestion, GraphDiffResult } from \"./types.js\";\nimport { type NumericMapLike, toNumericMap } from \"./collections.js\";\nimport { cohesionScore } from \"./cluster.js\";\n\ntype GraphInstance = InstanceType<typeof Graph>;\n\nfunction nodeCommunityMap(communities: NumericMapLike<string[]>): Map<string, number> {\n const communityMap = toNumericMap(communities);\n const result = new Map<string, number>();\n for (const [cid, nodes] of communityMap) {\n for (const n of nodes) result.set(n, cid);\n }\n return result;\n}\n\nexport function isFileNode(G: Graph, nodeId: string): boolean {\n const attrs = G.getNodeAttributes(nodeId);\n const label = (attrs.label as string) ?? \"\";\n if (!label) return false;\n\n const sourceFile = (attrs.source_file as string) ?? \"\";\n if (sourceFile) {\n const fileName = sourceFile.split(\"/\").pop() ?? \"\";\n if (label === fileName) return true;\n }\n\n if (label.startsWith(\".\") && label.endsWith(\"()\")) return true;\n if (label.endsWith(\"()\") && G.degree(nodeId) <= 1) return true;\n return false;\n}\n\nexport function isConceptNode(G: Graph, nodeId: string): boolean {\n const data = G.getNodeAttributes(nodeId);\n const source = (data.source_file as string) ?? \"\";\n if (!source) return true;\n const lastPart = source.split(\"/\").pop() ?? \"\";\n if (!lastPart.includes(\".\")) return true;\n return false;\n}\n\nconst CODE_EXTENSIONS = new Set([\n \"py\", \"ts\", \"tsx\", \"js\", \"go\", \"rs\", \"java\", \"rb\", \"cpp\", \"c\", \"h\", \"cs\", \"kt\", \"scala\", \"php\",\n]);\nconst DOC_EXTENSIONS = new Set([\"md\", \"txt\", \"rst\"]);\nconst PAPER_EXTENSIONS = new Set([\"pdf\"]);\nconst IMAGE_EXTENSIONS = new Set([\"png\", \"jpg\", \"jpeg\", \"webp\", \"gif\", \"svg\"]);\n\nfunction fileCategory(path: string): string {\n const ext = path.includes(\".\") ? path.split(\".\").pop()?.toLowerCase() ?? \"\" : \"\";\n if (CODE_EXTENSIONS.has(ext)) return \"code\";\n if (PAPER_EXTENSIONS.has(ext)) return \"paper\";\n if (IMAGE_EXTENSIONS.has(ext)) return \"image\";\n return \"doc\";\n}\n\nfunction topLevelDir(path: string): string {\n return path.includes(\"/\") ? path.split(\"/\")[0]! : path;\n}\n\nfunction surpriseScore(\n G: Graph,\n u: string,\n v: string,\n data: Record<string, unknown>,\n nodeCommunity: Map<string, number>,\n uSource: string,\n vSource: string,\n): [number, string[]] {\n let score = 0;\n const reasons: string[] = [];\n\n const conf = (data.confidence as string) ?? \"EXTRACTED\";\n const confBonus: Record<string, number> = { AMBIGUOUS: 3, INFERRED: 2, EXTRACTED: 1 };\n score += confBonus[conf] ?? 1;\n if (conf === \"AMBIGUOUS\" || conf === \"INFERRED\") {\n reasons.push(`${conf.toLowerCase()} connection - not explicitly stated in source`);\n }\n\n const catU = fileCategory(uSource);\n const catV = fileCategory(vSource);\n if (catU !== catV) {\n score += 2;\n reasons.push(`crosses file types (${catU} ↔ ${catV})`);\n }\n\n if (topLevelDir(uSource) !== topLevelDir(vSource)) {\n score += 2;\n reasons.push(\"connects across different repos/directories\");\n }\n\n const cidU = nodeCommunity.get(u);\n const cidV = nodeCommunity.get(v);\n if (cidU !== undefined && cidV !== undefined && cidU !== cidV) {\n score += 1;\n reasons.push(\"bridges separate communities\");\n }\n\n if (data.relation === \"semantically_similar_to\") {\n score = Math.floor(score * 1.5);\n reasons.push(\"semantically similar concepts with no structural link\");\n }\n\n const degU = G.degree(u);\n const degV = G.degree(v);\n if (Math.min(degU, degV) <= 2 && Math.max(degU, degV) >= 5) {\n score += 1;\n const peripheral = degU <= 2 ? (G.getNodeAttribute(u, \"label\") as string) : (G.getNodeAttribute(v, \"label\") as string);\n const hub = degU <= 2 ? (G.getNodeAttribute(v, \"label\") as string) : (G.getNodeAttribute(u, \"label\") as string);\n reasons.push(`peripheral node \\`${peripheral}\\` unexpectedly reaches hub \\`${hub}\\``);\n }\n\n return [score, reasons];\n}\n\nexport function godNodes(G: Graph, topN: number = 10): GodNodeEntry[] {\n const degree: [string, number][] = [];\n G.forEachNode((n) => degree.push([n, G.degree(n)]));\n degree.sort((a, b) => b[1] - a[1]);\n\n const result: GodNodeEntry[] = [];\n for (const [nodeId, deg] of degree) {\n if (isFileNode(G, nodeId) || isConceptNode(G, nodeId)) continue;\n result.push({\n id: nodeId,\n label: (G.getNodeAttribute(nodeId, \"label\") as string) ?? nodeId,\n edges: deg,\n });\n if (result.length >= topN) break;\n }\n return result;\n}\n\nexport function surprisingConnections(\n G: Graph,\n communities?: NumericMapLike<string[]>,\n topN: number = 5,\n): SurpriseEntry[] {\n const comms = toNumericMap(communities);\n const sourceFiles = new Set<string>();\n G.forEachNode((_, data) => {\n const sf = (data.source_file as string) ?? \"\";\n if (sf) sourceFiles.add(sf);\n });\n const isMultiSource = sourceFiles.size > 1;\n\n if (isMultiSource) {\n return crossFileSurprises(G, comms, topN);\n }\n return crossCommunitySurprises(G, comms, topN);\n}\n\nfunction crossFileSurprises(G: Graph, communities: Map<number, string[]>, topN: number): SurpriseEntry[] {\n const nodeCommunity = nodeCommunityMap(communities);\n const candidates: (SurpriseEntry & { _score: number })[] = [];\n\n G.forEachEdge((edge, data, source, target) => {\n const relation = (data.relation as string) ?? \"\";\n if ([\"imports\", \"imports_from\", \"contains\", \"method\"].includes(relation)) return;\n if (isConceptNode(G, source) || isConceptNode(G, target)) return;\n if (isFileNode(G, source) || isFileNode(G, target)) return;\n\n const uSource = (G.getNodeAttribute(source, \"source_file\") as string) ?? \"\";\n const vSource = (G.getNodeAttribute(target, \"source_file\") as string) ?? \"\";\n if (!uSource || !vSource || uSource === vSource) return;\n\n const [score, reasons] = surpriseScore(G, source, target, data, nodeCommunity, uSource, vSource);\n const srcId = (data._src as string) ?? source;\n const tgtId = (data._tgt as string) ?? target;\n\n candidates.push({\n _score: score,\n source: (G.getNodeAttribute(srcId, \"label\") as string) ?? srcId,\n target: (G.getNodeAttribute(tgtId, \"label\") as string) ?? tgtId,\n source_files: [\n (G.getNodeAttribute(srcId, \"source_file\") as string) ?? \"\",\n (G.getNodeAttribute(tgtId, \"source_file\") as string) ?? \"\",\n ],\n confidence: (data.confidence as SurpriseEntry[\"confidence\"]) ?? \"EXTRACTED\",\n relation,\n why: reasons.length > 0 ? reasons.join(\"; \") : \"cross-file semantic connection\",\n });\n });\n\n candidates.sort((a, b) => b._score - a._score);\n const result = candidates.slice(0, topN).map(({ _score, ...rest }) => rest);\n\n if (result.length > 0) return result;\n return crossCommunitySurprises(G, communities, topN);\n}\n\nfunction crossCommunitySurprises(\n G: Graph,\n communities: Map<number, string[]>,\n topN: number,\n): SurpriseEntry[] {\n if (communities.size === 0) {\n if (G.size === 0) return [];\n // Use edge betweenness centrality approximation\n return edgeBetweennessSurprises(G, topN);\n }\n\n const nodeCommunity = nodeCommunityMap(communities);\n const surprises: (SurpriseEntry & { _pair: string })[] = [];\n\n G.forEachEdge((edge, data, u, v) => {\n const cidU = nodeCommunity.get(u);\n const cidV = nodeCommunity.get(v);\n if (cidU === undefined || cidV === undefined || cidU === cidV) return;\n if (isFileNode(G, u) || isFileNode(G, v)) return;\n const relation = (data.relation as string) ?? \"\";\n if ([\"imports\", \"imports_from\", \"contains\", \"method\"].includes(relation)) return;\n\n const srcId = (data._src as string) ?? u;\n const tgtId = (data._tgt as string) ?? v;\n\n surprises.push({\n source: (G.getNodeAttribute(srcId, \"label\") as string) ?? srcId,\n target: (G.getNodeAttribute(tgtId, \"label\") as string) ?? tgtId,\n source_files: [\n (G.getNodeAttribute(srcId, \"source_file\") as string) ?? \"\",\n (G.getNodeAttribute(tgtId, \"source_file\") as string) ?? \"\",\n ],\n confidence: (data.confidence as SurpriseEntry[\"confidence\"]) ?? \"EXTRACTED\",\n relation,\n note: `Bridges community ${cidU} → community ${cidV}`,\n _pair: [Math.min(cidU, cidV), Math.max(cidU, cidV)].join(\",\"),\n });\n });\n\n const order: Record<string, number> = { AMBIGUOUS: 0, INFERRED: 1, EXTRACTED: 2 };\n surprises.sort((a, b) => (order[a.confidence] ?? 3) - (order[b.confidence] ?? 3));\n\n const seenPairs = new Set<string>();\n const deduped: SurpriseEntry[] = [];\n for (const s of surprises) {\n const pair = s._pair;\n if (!seenPairs.has(pair)) {\n seenPairs.add(pair);\n const { _pair, ...rest } = s;\n deduped.push(rest);\n }\n }\n return deduped.slice(0, topN);\n}\n\nfunction edgeBetweennessSurprises(G: Graph, topN: number): SurpriseEntry[] {\n // Approximate edge betweenness via node betweenness\n const bc = betweennessCentrality(G);\n const edgeScores: [string, string, number, Record<string, unknown>][] = [];\n\n G.forEachEdge((edge, data, u, v) => {\n const score = (bc[u] ?? 0) + (bc[v] ?? 0);\n edgeScores.push([u, v, score, data]);\n });\n\n edgeScores.sort((a, b) => b[2] - a[2]);\n\n return edgeScores.slice(0, topN).map(([u, v, score, data]) => ({\n source: (G.getNodeAttribute(u, \"label\") as string) ?? u,\n target: (G.getNodeAttribute(v, \"label\") as string) ?? v,\n source_files: [\n (G.getNodeAttribute(u, \"source_file\") as string) ?? \"\",\n (G.getNodeAttribute(v, \"source_file\") as string) ?? \"\",\n ],\n confidence: (data.confidence as SurpriseEntry[\"confidence\"]) ?? \"EXTRACTED\",\n relation: (data.relation as string) ?? \"\",\n note: `Bridges graph structure (betweenness=${score.toFixed(3)})`,\n }));\n}\n\nexport function suggestQuestions(\n G: Graph,\n communities: NumericMapLike<string[]>,\n communityLabels: NumericMapLike<string>,\n topN: number = 7,\n): SuggestedQuestion[] {\n const communityMap = toNumericMap(communities);\n const labelMap = toNumericMap(communityLabels);\n const questions: SuggestedQuestion[] = [];\n const nodeCommunity = nodeCommunityMap(communityMap);\n\n // 1. AMBIGUOUS edges\n G.forEachEdge((edge, data, u, v) => {\n if (data.confidence === \"AMBIGUOUS\") {\n const ul = (G.getNodeAttribute(u, \"label\") as string) ?? u;\n const vl = (G.getNodeAttribute(v, \"label\") as string) ?? v;\n const relation = (data.relation as string) ?? \"related to\";\n questions.push({\n type: \"ambiguous_edge\",\n question: `What is the exact relationship between \\`${ul}\\` and \\`${vl}\\`?`,\n why: `Edge tagged AMBIGUOUS (relation: ${relation}) - confidence is low.`,\n });\n }\n });\n\n // 2. Bridge nodes (high betweenness)\n if (G.size > 0) {\n const bc = betweennessCentrality(G);\n const bridges: [string, number][] = Object.entries(bc)\n .filter(([n, s]) => !isFileNode(G, n) && !isConceptNode(G, n) && (s as number) > 0)\n .sort((a, b) => (b[1] as number) - (a[1] as number))\n .slice(0, 3) as [string, number][];\n\n for (const [nodeId, score] of bridges) {\n const label = (G.getNodeAttribute(nodeId, \"label\") as string) ?? nodeId;\n const cid = nodeCommunity.get(nodeId);\n const commLabel = cid !== undefined ? (labelMap.get(cid) ?? `Community ${cid}`) : \"unknown\";\n const neighborComms = new Set<number>();\n G.forEachNeighbor(nodeId, (n) => {\n const nc = nodeCommunity.get(n);\n if (nc !== undefined && nc !== cid) neighborComms.add(nc);\n });\n if (neighborComms.size > 0) {\n const otherLabels = [...neighborComms].map((c) => labelMap.get(c) ?? `Community ${c}`);\n questions.push({\n type: \"bridge_node\",\n question: `Why does \\`${label}\\` connect \\`${commLabel}\\` to ${otherLabels.map((l) => `\\`${l}\\``).join(\", \")}?`,\n why: `High betweenness centrality (${score.toFixed(3)}) - this node is a cross-community bridge.`,\n });\n }\n }\n }\n\n // 3. God nodes with many INFERRED edges\n const degree: [string, number][] = [];\n G.forEachNode((n) => degree.push([n, G.degree(n)]));\n degree.sort((a, b) => b[1] - a[1]);\n const topNodes = degree.filter(([n]) => !isFileNode(G, n)).slice(0, 5);\n\n for (const [nodeId] of topNodes) {\n const inferred: string[] = [];\n G.forEachEdge(nodeId, (edge, data, source, target) => {\n if (data.confidence === \"INFERRED\") {\n const srcId = (data._src as string) ?? source;\n const tgtId = (data._tgt as string) ?? target;\n const otherId = srcId === nodeId ? tgtId : srcId;\n inferred.push((G.getNodeAttribute(otherId, \"label\") as string) ?? otherId);\n }\n });\n if (inferred.length >= 2) {\n const label = (G.getNodeAttribute(nodeId, \"label\") as string) ?? nodeId;\n questions.push({\n type: \"verify_inferred\",\n question: `Are the ${inferred.length} inferred relationships involving \\`${label}\\` (e.g. with \\`${inferred[0]}\\` and \\`${inferred[1]}\\`) actually correct?`,\n why: `\\`${label}\\` has ${inferred.length} INFERRED edges - model-reasoned connections that need verification.`,\n });\n }\n }\n\n // 4. Isolated nodes\n const isolated: string[] = [];\n G.forEachNode((n) => {\n if (G.degree(n) <= 1 && !isFileNode(G, n) && !isConceptNode(G, n)) {\n isolated.push(n);\n }\n });\n if (isolated.length > 0) {\n const labels = isolated.slice(0, 3).map((n) => (G.getNodeAttribute(n, \"label\") as string) ?? n);\n questions.push({\n type: \"isolated_nodes\",\n question: `What connects ${labels.map((l) => `\\`${l}\\``).join(\", \")} to the rest of the system?`,\n why: `${isolated.length} weakly-connected nodes found - possible documentation gaps or missing edges.`,\n });\n }\n\n // 5. Low-cohesion communities\n for (const [cid, nodes] of communityMap) {\n const score = cohesionScore(G, nodes);\n if (score < 0.15 && nodes.length >= 5) {\n const label = labelMap.get(cid) ?? `Community ${cid}`;\n questions.push({\n type: \"low_cohesion\",\n question: `Should \\`${label}\\` be split into smaller, more focused modules?`,\n why: `Cohesion score ${score} - nodes in this community are weakly interconnected.`,\n });\n }\n }\n\n if (questions.length === 0) {\n return [{\n type: \"no_signal\",\n question: null,\n why:\n \"Not enough signal to generate questions. \" +\n \"This usually means the corpus has no AMBIGUOUS edges, no bridge nodes, \" +\n \"no INFERRED relationships, and all communities are tightly cohesive. \" +\n \"Add more files or run with --mode deep to extract richer edges.\",\n }];\n }\n\n return questions.slice(0, topN);\n}\n\nexport function graphDiff(GOld: Graph, GNew: Graph): GraphDiffResult {\n const oldNodes = new Set(GOld.nodes());\n const newNodes = new Set(GNew.nodes());\n\n const addedNodeIds = [...newNodes].filter((n) => !oldNodes.has(n));\n const removedNodeIds = [...oldNodes].filter((n) => !newNodes.has(n));\n\n const newNodesList = addedNodeIds.map((n) => ({\n id: n,\n label: (GNew.getNodeAttribute(n, \"label\") as string) ?? n,\n }));\n const removedNodesList = removedNodeIds.map((n) => ({\n id: n,\n label: (GOld.getNodeAttribute(n, \"label\") as string) ?? n,\n }));\n\n function edgeKey(u: string, v: string, relation: string): string {\n return `${[u, v].sort().join(\",\")}:${relation}`;\n }\n\n const oldEdgeKeys = new Set<string>();\n GOld.forEachEdge((edge, data, u, v) => {\n oldEdgeKeys.add(edgeKey(u, v, (data.relation as string) ?? \"\"));\n });\n const newEdgeKeys = new Set<string>();\n GNew.forEachEdge((edge, data, u, v) => {\n newEdgeKeys.add(edgeKey(u, v, (data.relation as string) ?? \"\"));\n });\n\n const addedEdgeKeys = new Set([...newEdgeKeys].filter((k) => !oldEdgeKeys.has(k)));\n const removedEdgeKeys = new Set([...oldEdgeKeys].filter((k) => !newEdgeKeys.has(k)));\n\n const newEdgesList: GraphDiffResult[\"new_edges\"] = [];\n GNew.forEachEdge((edge, data, u, v) => {\n if (addedEdgeKeys.has(edgeKey(u, v, (data.relation as string) ?? \"\"))) {\n newEdgesList.push({\n source: u, target: v,\n relation: (data.relation as string) ?? \"\",\n confidence: (data.confidence as string) ?? \"\",\n });\n }\n });\n\n const removedEdgesList: GraphDiffResult[\"removed_edges\"] = [];\n GOld.forEachEdge((edge, data, u, v) => {\n if (removedEdgeKeys.has(edgeKey(u, v, (data.relation as string) ?? \"\"))) {\n removedEdgesList.push({\n source: u, target: v,\n relation: (data.relation as string) ?? \"\",\n confidence: (data.confidence as string) ?? \"\",\n });\n }\n });\n\n const parts: string[] = [];\n if (newNodesList.length > 0) parts.push(`${newNodesList.length} new node${newNodesList.length !== 1 ? \"s\" : \"\"}`);\n if (newEdgesList.length > 0) parts.push(`${newEdgesList.length} new edge${newEdgesList.length !== 1 ? \"s\" : \"\"}`);\n if (removedNodesList.length > 0) parts.push(`${removedNodesList.length} node${removedNodesList.length !== 1 ? \"s\" : \"\"} removed`);\n if (removedEdgesList.length > 0) parts.push(`${removedEdgesList.length} edge${removedEdgesList.length !== 1 ? \"s\" : \"\"} removed`);\n\n return {\n new_nodes: newNodesList,\n removed_nodes: removedNodesList,\n new_edges: newEdgesList,\n removed_edges: removedEdgesList,\n summary: parts.length > 0 ? parts.join(\", \") : \"no changes\",\n };\n}\n","export type NumericMapLike<T> = Map<number, T> | Record<number | string, T>;\nexport type StringMapLike<T> = Map<string, T> | Record<string, T>;\n\nexport function toNumericMap<T>(\n value: NumericMapLike<T> | null | undefined,\n): Map<number, T> {\n if (value instanceof Map) return value;\n\n const map = new Map<number, T>();\n if (!value) return map;\n\n for (const [key, entry] of Object.entries(value)) {\n const numericKey = Number(key);\n if (Number.isFinite(numericKey)) {\n map.set(numericKey, entry as T);\n }\n }\n\n return map;\n}\n\nexport function toStringMap<T>(\n value: StringMapLike<T> | null | undefined,\n): Map<string, T> {\n if (value instanceof Map) return value;\n\n const map = new Map<string, T>();\n if (!value) return map;\n\n for (const [key, entry] of Object.entries(value)) {\n map.set(key, entry as T);\n }\n\n return map;\n}\n","/**\n * Community detection on graphology graphs.\n * Uses Louvain (graphology-communities-louvain).\n * Splits oversized communities. Returns cohesion scores.\n */\nimport Graph from \"graphology\";\nimport louvain from \"graphology-communities-louvain\";\nimport { type NumericMapLike, toNumericMap } from \"./collections.js\";\n\nconst MAX_COMMUNITY_FRACTION = 0.25;\nconst MIN_SPLIT_SIZE = 10;\n\nfunction partition(G: Graph): Map<string, number> {\n // louvain assigns community attribute to each node, returns mapping\n const result = louvain(G);\n const map = new Map<string, number>();\n for (const [node, cid] of Object.entries(result)) {\n map.set(node, cid as number);\n }\n return map;\n}\n\nfunction splitCommunity(G: Graph, nodes: string[]): string[][] {\n const subgraph = G.copy();\n // Remove nodes not in this community\n const nodeSet = new Set(nodes);\n subgraph.forEachNode((n) => {\n if (!nodeSet.has(n)) subgraph.dropNode(n);\n });\n\n if (subgraph.size === 0) {\n return nodes.map((n) => [n]);\n }\n\n try {\n const subPartition = partition(subgraph);\n const subCommunities = new Map<number, string[]>();\n for (const [node, cid] of subPartition) {\n if (!subCommunities.has(cid)) subCommunities.set(cid, []);\n subCommunities.get(cid)!.push(node);\n }\n if (subCommunities.size <= 1) {\n return [[...nodes].sort()];\n }\n return [...subCommunities.values()].map((v) => [...v].sort());\n } catch {\n return [[...nodes].sort()];\n }\n}\n\nexport function cluster(G: Graph): Map<number, string[]> {\n if (G.order === 0) return new Map();\n\n if (G.size === 0) {\n const result = new Map<number, string[]>();\n const sorted = [...G.nodes()].sort();\n sorted.forEach((n, i) => result.set(i, [n]));\n return result;\n }\n\n // Handle isolates separately\n const isolates: string[] = [];\n const connectedNodes: string[] = [];\n G.forEachNode((n) => {\n if (G.degree(n) === 0) {\n isolates.push(n);\n } else {\n connectedNodes.push(n);\n }\n });\n\n const raw = new Map<number, string[]>();\n\n if (connectedNodes.length > 0) {\n // Build subgraph of connected nodes\n const connected = G.copy();\n for (const iso of isolates) {\n connected.dropNode(iso);\n }\n const partitionMap = partition(connected);\n for (const [node, cid] of partitionMap) {\n if (!raw.has(cid)) raw.set(cid, []);\n raw.get(cid)!.push(node);\n }\n }\n\n // Each isolate becomes its own single-node community\n let nextCid = Math.max(-1, ...raw.keys()) + 1;\n for (const node of isolates) {\n raw.set(nextCid, [node]);\n nextCid++;\n }\n\n // Split oversized communities\n const maxSize = Math.max(MIN_SPLIT_SIZE, Math.floor(G.order * MAX_COMMUNITY_FRACTION));\n const finalCommunities: string[][] = [];\n for (const nodes of raw.values()) {\n if (nodes.length > maxSize) {\n finalCommunities.push(...splitCommunity(G, nodes));\n } else {\n finalCommunities.push(nodes);\n }\n }\n\n // Re-index by size descending for deterministic ordering\n finalCommunities.sort((a, b) => b.length - a.length);\n const result = new Map<number, string[]>();\n finalCommunities.forEach((nodes, i) => {\n result.set(i, [...nodes].sort());\n });\n return result;\n}\n\n/** Ratio of actual intra-community edges to maximum possible. */\nexport function cohesionScore(G: Graph, communityNodes: string[]): number {\n const n = communityNodes.length;\n if (n <= 1) return 1.0;\n const nodeSet = new Set(communityNodes);\n let actual = 0;\n G.forEachEdge((edge, attrs, source, target) => {\n if (nodeSet.has(source) && nodeSet.has(target)) {\n actual++;\n }\n });\n const possible = (n * (n - 1)) / 2;\n return possible > 0 ? Math.round((actual / possible) * 100) / 100 : 0.0;\n}\n\nexport function scoreAll(\n G: Graph,\n communities: NumericMapLike<string[]>,\n): Map<number, number> {\n const communityMap = toNumericMap(communities);\n const result = new Map<number, number>();\n for (const [cid, nodes] of communityMap) {\n result.set(cid, cohesionScore(G, nodes));\n }\n return result;\n}\n","/**\n * Token-reduction benchmark - measures how much context graphify saves vs naive full-corpus approach.\n */\nimport { readFileSync, existsSync } from \"node:fs\";\nimport Graph from \"graphology\";\nimport type { BenchmarkResult } from \"./types.js\";\n\nconst CHARS_PER_TOKEN = 4;\n\nfunction estimateTokens(text: string): number {\n return Math.max(1, Math.floor(text.length / CHARS_PER_TOKEN));\n}\n\nfunction querySubgraphTokens(G: Graph, question: string, depth: number = 3): number {\n const terms = question.toLowerCase().split(/\\s+/).filter((t) => t.length > 2);\n const scored: [number, string][] = [];\n G.forEachNode((nid, data) => {\n const label = ((data.label as string) ?? \"\").toLowerCase();\n const score = terms.filter((t) => label.includes(t)).length;\n if (score > 0) scored.push([score, nid]);\n });\n scored.sort((a, b) => b[0] - a[0]);\n const startNodes = scored.slice(0, 3).map(([, nid]) => nid);\n if (startNodes.length === 0) return 0;\n\n const visited = new Set(startNodes);\n let frontier = new Set(startNodes);\n const edgesSeen: [string, string][] = [];\n\n for (let d = 0; d < depth; d++) {\n const nextFrontier = new Set<string>();\n for (const n of frontier) {\n G.forEachNeighbor(n, (neighbor) => {\n if (!visited.has(neighbor)) {\n nextFrontier.add(neighbor);\n edgesSeen.push([n, neighbor]);\n }\n });\n }\n for (const n of nextFrontier) visited.add(n);\n frontier = nextFrontier;\n }\n\n const lines: string[] = [];\n for (const nid of visited) {\n const d = G.getNodeAttributes(nid);\n lines.push(`NODE ${d.label ?? nid} src=${d.source_file ?? \"\"} loc=${d.source_location ?? \"\"}`);\n }\n for (const [u, v] of edgesSeen) {\n if (visited.has(u) && visited.has(v)) {\n const edge = G.edge(u, v);\n if (edge) {\n const d = G.getEdgeAttributes(edge);\n lines.push(`EDGE ${G.getNodeAttribute(u, \"label\") ?? u} --${d.relation ?? \"\"}--> ${G.getNodeAttribute(v, \"label\") ?? v}`);\n }\n }\n }\n\n return estimateTokens(lines.join(\"\\n\"));\n}\n\nconst SAMPLE_QUESTIONS = [\n \"how does authentication work\",\n \"what is the main entry point\",\n \"how are errors handled\",\n \"what connects the data layer to the api\",\n \"what are the core abstractions\",\n];\n\ninterface BenchmarkOptions {\n corpusWords?: number;\n questions?: string[];\n}\n\nfunction loadGraph(graphPath: string): Graph {\n const raw = JSON.parse(readFileSync(graphPath, \"utf-8\"));\n const G = new Graph({ type: \"undirected\" });\n for (const node of raw.nodes ?? []) {\n const { id, ...attrs } = node;\n G.mergeNode(id, attrs);\n }\n for (const link of raw.links ?? []) {\n const { source, target, ...attrs } = link;\n if (G.hasNode(source) && G.hasNode(target)) {\n try { G.mergeEdge(source, target, attrs); } catch { /* ignore */ }\n }\n }\n return G;\n}\n\nexport function runBenchmark(\n graphPath: string = \"graphify-out/graph.json\",\n corpusWordsOrOptions?: number | BenchmarkOptions,\n questions?: string[],\n): BenchmarkResult {\n const options = typeof corpusWordsOrOptions === \"number\"\n ? { corpusWords: corpusWordsOrOptions, questions }\n : (corpusWordsOrOptions ?? {});\n\n if (!existsSync(graphPath)) {\n return { error: `Graph file not found: ${graphPath}. Build the graph first.` };\n }\n\n const G = loadGraph(graphPath);\n\n const corpusWords = options.corpusWords ?? (G.order * 50);\n\n if (corpusWords === undefined) {\n return { error: \"Could not determine corpus size.\" };\n }\n\n const corpusTokens = Math.floor((corpusWords * 100) / 75);\n const qs = options.questions ?? SAMPLE_QUESTIONS;\n const perQuestion: Array<{ question: string; query_tokens: number; reduction: number }> = [];\n\n for (const q of qs) {\n const qt = querySubgraphTokens(G, q);\n if (qt > 0) {\n perQuestion.push({\n question: q,\n query_tokens: qt,\n reduction: Math.round((corpusTokens / qt) * 10) / 10,\n });\n }\n }\n\n if (perQuestion.length === 0) {\n return { error: \"No matching nodes found for sample questions. Build the graph first.\" };\n }\n\n const avgQueryTokens = Math.floor(\n perQuestion.reduce((s, p) => s + p.query_tokens, 0) / perQuestion.length,\n );\n const reductionRatio = avgQueryTokens > 0 ? Math.round((corpusTokens / avgQueryTokens) * 10) / 10 : 0;\n\n return {\n corpus_tokens: corpusTokens,\n corpus_words: corpusWords,\n nodes: G.order,\n edges: G.size,\n avg_query_tokens: avgQueryTokens,\n reduction_ratio: reductionRatio,\n per_question: perQuestion,\n };\n}\n\nexport function printBenchmark(result: BenchmarkResult): void {\n if (result.error) {\n console.log(`Benchmark error: ${result.error}`);\n return;\n }\n\n console.log(`\\ngraphify token reduction benchmark`);\n console.log(\"─\".repeat(50));\n console.log(` Corpus: ${result.corpus_words!.toLocaleString()} words → ~${result.corpus_tokens!.toLocaleString()} tokens (naive)`);\n console.log(` Graph: ${result.nodes!.toLocaleString()} nodes, ${result.edges!.toLocaleString()} edges`);\n console.log(` Avg query cost: ~${result.avg_query_tokens!.toLocaleString()} tokens`);\n console.log(` Reduction: ${result.reduction_ratio}x fewer tokens per query`);\n console.log(`\\n Per question:`);\n for (const p of result.per_question!) {\n console.log(` [${p.reduction}x] ${p.question.slice(0, 55)}`);\n }\n console.log();\n}\n","/**\n * Per-file extraction cache - skip unchanged files on re-run.\n */\nimport { createHash } from \"node:crypto\";\nimport { readFileSync, writeFileSync, mkdirSync, readdirSync, unlinkSync, renameSync, existsSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\n\n/** SHA256 of file contents + resolved path. Prevents cache collisions on identical content. */\nexport function fileHash(filePath: string): string {\n const content = readFileSync(filePath);\n const resolved = resolve(filePath);\n const h = createHash(\"sha256\");\n h.update(content);\n h.update(\"\\0\");\n h.update(resolved);\n return h.digest(\"hex\");\n}\n\n/** Returns graphify-out/cache/ path - creates it if needed. */\nexport function cacheDir(root: string = \".\"): string {\n const d = join(root, \"graphify-out\", \"cache\");\n mkdirSync(d, { recursive: true });\n return d;\n}\n\n/**\n * Return cached extraction for this file if hash matches, else null.\n */\nexport function loadCached(filePath: string, root: string = \".\"): Record<string, unknown> | null {\n let h: string;\n try {\n h = fileHash(filePath);\n } catch {\n return null;\n }\n const entry = join(cacheDir(root), `${h}.json`);\n if (!existsSync(entry)) return null;\n try {\n return JSON.parse(readFileSync(entry, \"utf-8\")) as Record<string, unknown>;\n } catch {\n return null;\n }\n}\n\n/** Save extraction result for this file. */\nexport function saveCached(filePath: string, result: Record<string, unknown>, root: string = \".\"): void {\n const h = fileHash(filePath);\n const entry = join(cacheDir(root), `${h}.json`);\n const tmp = entry + \".tmp\";\n try {\n writeFileSync(tmp, JSON.stringify(result));\n renameSync(tmp, entry);\n } catch {\n try { unlinkSync(tmp); } catch { /* ignore */ }\n throw new Error(`Failed to save cache for ${filePath}`);\n }\n}\n\n/** Return set of file hashes that have a valid cache entry. */\nexport function cachedFiles(root: string = \".\"): Set<string> {\n const d = cacheDir(root);\n const result = new Set<string>();\n try {\n for (const f of readdirSync(d)) {\n if (f.endsWith(\".json\")) {\n result.add(f.replace(\".json\", \"\"));\n }\n }\n } catch { /* ignore */ }\n return result;\n}\n\n/** Delete all graphify-out/cache/*.json files. */\nexport function clearCache(root: string = \".\"): void {\n const d = cacheDir(root);\n try {\n for (const f of readdirSync(d)) {\n if (f.endsWith(\".json\")) {\n unlinkSync(join(d, f));\n }\n }\n } catch { /* ignore */ }\n}\n\ninterface ExtractionPart {\n nodes: Array<Record<string, unknown>>;\n edges: Array<Record<string, unknown>>;\n hyperedges: Array<Record<string, unknown>>;\n}\n\n/**\n * Check semantic extraction cache for a list of file paths.\n * Returns [cachedNodes, cachedEdges, cachedHyperedges, uncachedFiles].\n */\nexport function checkSemanticCache(\n files: string[],\n root: string = \".\",\n): [Array<Record<string, unknown>>, Array<Record<string, unknown>>, Array<Record<string, unknown>>, string[]] {\n const cachedNodes: Array<Record<string, unknown>> = [];\n const cachedEdges: Array<Record<string, unknown>> = [];\n const cachedHyperedges: Array<Record<string, unknown>> = [];\n const uncached: string[] = [];\n\n for (const fpath of files) {\n const result = loadCached(fpath, root);\n if (result !== null) {\n const r = result as unknown as ExtractionPart;\n cachedNodes.push(...(r.nodes ?? []));\n cachedEdges.push(...(r.edges ?? []));\n cachedHyperedges.push(...(r.hyperedges ?? []));\n } else {\n uncached.push(fpath);\n }\n }\n\n return [cachedNodes, cachedEdges, cachedHyperedges, uncached];\n}\n\n/**\n * Save semantic extraction results to cache, keyed by source_file.\n * Returns the number of files cached.\n */\nexport function saveSemanticCache(\n nodes: Array<Record<string, unknown>>,\n edges: Array<Record<string, unknown>>,\n hyperedges: Array<Record<string, unknown>> | null = null,\n root: string = \".\",\n): number {\n const byFile = new Map<string, ExtractionPart>();\n\n for (const n of nodes) {\n const src = (n.source_file as string) ?? \"\";\n if (!src) continue;\n if (!byFile.has(src)) byFile.set(src, { nodes: [], edges: [], hyperedges: [] });\n byFile.get(src)!.nodes.push(n);\n }\n for (const e of edges) {\n const src = (e.source_file as string) ?? \"\";\n if (!src) continue;\n if (!byFile.has(src)) byFile.set(src, { nodes: [], edges: [], hyperedges: [] });\n byFile.get(src)!.edges.push(e);\n }\n for (const h of hyperedges ?? []) {\n const src = (h.source_file as string) ?? \"\";\n if (!src) continue;\n if (!byFile.has(src)) byFile.set(src, { nodes: [], edges: [], hyperedges: [] });\n byFile.get(src)!.hyperedges.push(h);\n }\n\n let saved = 0;\n for (const [fpath, result] of byFile) {\n const p = resolve(root, fpath);\n if (existsSync(p)) {\n saveCached(p, result as unknown as Record<string, unknown>, root);\n saved++;\n }\n }\n return saved;\n}\n","/**\n * Assemble node+edge dicts into a graphology Graph, preserving edge direction.\n *\n * Node deduplication — three layers:\n *\n * 1. Within a file (AST): each extractor tracks a `seenIds` set.\n * 2. Between files (build): graphology mergeNode is idempotent — last write wins.\n * 3. Semantic merge (skill): before calling build(), the skill merges results\n * using an explicit `seen` set keyed on node.id.\n */\nimport Graph from \"graphology\";\nimport type { Extraction } from \"./types.js\";\nimport { validateExtraction } from \"./validate.js\";\n\nexport function buildFromJson(extraction: Extraction): Graph {\n const errors = validateExtraction(extraction);\n // Dangling edges (stdlib/external imports) are expected - only warn about real schema errors.\n const realErrors = errors.filter((e) => !e.includes(\"does not match any node id\"));\n if (realErrors.length > 0) {\n console.error(\n `[graphify] Extraction warning (${realErrors.length} issues): ${realErrors[0]}`,\n );\n }\n\n const G = new Graph({ type: \"undirected\", multi: false });\n\n for (const node of extraction.nodes ?? []) {\n const { id, ...attrs } = node;\n G.mergeNode(id, attrs);\n }\n\n const nodeSet = new Set(G.nodes());\n\n for (const edge of extraction.edges ?? []) {\n const { source, target, ...attrs } = edge;\n if (!nodeSet.has(source) || !nodeSet.has(target)) continue;\n // Preserve original edge direction\n attrs._src = source;\n attrs._tgt = target;\n // graphology mergeEdge prevents duplicates on same src/tgt pair\n try {\n G.mergeEdge(source, target, attrs);\n } catch {\n // ignore if edge already exists with different key\n }\n }\n\n const hyperedges = extraction.hyperedges ?? [];\n if (hyperedges.length > 0) {\n G.setAttribute(\"hyperedges\", hyperedges);\n }\n\n return G;\n}\n\n/**\n * Merge multiple extraction results into one graph.\n * Extractions are merged in order — last attributes win for duplicate node IDs.\n */\nexport function build(extractions: Extraction[]): Graph {\n const combined: Extraction = {\n nodes: [],\n edges: [],\n hyperedges: [],\n input_tokens: 0,\n output_tokens: 0,\n };\n for (const ext of extractions) {\n combined.nodes.push(...(ext.nodes ?? []));\n combined.edges.push(...(ext.edges ?? []));\n (combined.hyperedges ??= []).push(...(ext.hyperedges ?? []));\n combined.input_tokens += ext.input_tokens ?? 0;\n combined.output_tokens += ext.output_tokens ?? 0;\n }\n return buildFromJson(combined);\n}\n","/**\n * Validate extraction JSON against the graphify schema before graph assembly.\n */\n\nexport const VALID_FILE_TYPES = new Set([\"code\", \"document\", \"paper\", \"image\", \"rationale\"]);\nexport const VALID_CONFIDENCES = new Set([\"EXTRACTED\", \"INFERRED\", \"AMBIGUOUS\"]);\nexport const REQUIRED_NODE_FIELDS = [\"id\", \"label\", \"file_type\", \"source_file\"] as const;\nexport const REQUIRED_EDGE_FIELDS = [\"source\", \"target\", \"relation\", \"confidence\", \"source_file\"] as const;\n\n/**\n * Validate an extraction JSON dict against the graphify schema.\n * Returns a list of error strings - empty list means valid.\n */\nexport function validateExtraction(data: unknown): string[] {\n if (typeof data !== \"object\" || data === null || Array.isArray(data)) {\n return [\"Extraction must be a JSON object\"];\n }\n\n const d = data as Record<string, unknown>;\n const errors: string[] = [];\n\n // Nodes\n if (!(\"nodes\" in d)) {\n errors.push(\"Missing required key 'nodes'\");\n } else if (!Array.isArray(d.nodes)) {\n errors.push(\"'nodes' must be a list\");\n } else {\n for (let i = 0; i < d.nodes.length; i++) {\n const node = d.nodes[i] as Record<string, unknown>;\n if (typeof node !== \"object\" || node === null || Array.isArray(node)) {\n errors.push(`Node ${i} must be an object`);\n continue;\n }\n for (const field of REQUIRED_NODE_FIELDS) {\n if (!(field in node)) {\n errors.push(\n `Node ${i} (id=${JSON.stringify(node.id ?? \"?\")}) missing required field '${field}'`,\n );\n }\n }\n if (\"file_type\" in node && !VALID_FILE_TYPES.has(node.file_type as string)) {\n errors.push(\n `Node ${i} (id=${JSON.stringify(node.id ?? \"?\")}) has invalid file_type ` +\n `'${node.file_type}' - must be one of ${JSON.stringify([...VALID_FILE_TYPES].sort())}`,\n );\n }\n }\n }\n\n // Edges\n if (!(\"edges\" in d)) {\n errors.push(\"Missing required key 'edges'\");\n } else if (!Array.isArray(d.edges)) {\n errors.push(\"'edges' must be a list\");\n } else {\n const nodeIds = new Set<string>();\n if (Array.isArray(d.nodes)) {\n for (const n of d.nodes) {\n if (typeof n === \"object\" && n !== null && \"id\" in n) {\n nodeIds.add((n as Record<string, unknown>).id as string);\n }\n }\n }\n\n for (let i = 0; i < d.edges.length; i++) {\n const edge = d.edges[i] as Record<string, unknown>;\n if (typeof edge !== \"object\" || edge === null || Array.isArray(edge)) {\n errors.push(`Edge ${i} must be an object`);\n continue;\n }\n for (const field of REQUIRED_EDGE_FIELDS) {\n if (!(field in edge)) {\n errors.push(`Edge ${i} missing required field '${field}'`);\n }\n }\n if (\"confidence\" in edge && !VALID_CONFIDENCES.has(edge.confidence as string)) {\n errors.push(\n `Edge ${i} has invalid confidence '${edge.confidence}' ` +\n `- must be one of ${JSON.stringify([...VALID_CONFIDENCES].sort())}`,\n );\n }\n if (\"source\" in edge && nodeIds.size > 0 && !nodeIds.has(edge.source as string)) {\n errors.push(`Edge ${i} source '${edge.source}' does not match any node id`);\n }\n if (\"target\" in edge && nodeIds.size > 0 && !nodeIds.has(edge.target as string)) {\n errors.push(`Edge ${i} target '${edge.target}' does not match any node id`);\n }\n }\n }\n\n return errors;\n}\n\n/** Raise an error with all validation errors if extraction is invalid. */\nexport function assertValid(data: unknown): void {\n const errors = validateExtraction(data);\n if (errors.length > 0) {\n const msg =\n `Extraction JSON has ${errors.length} error(s):\\n` +\n errors.map((e) => ` • ${e}`).join(\"\\n\");\n throw new Error(msg);\n }\n}\n","/**\n * File discovery, type classification, and corpus health checks.\n */\nimport {\n readdirSync, readFileSync, writeFileSync, statSync, existsSync, mkdirSync, lstatSync,\n} from \"node:fs\";\nimport { join, resolve, extname, basename, relative, sep } from \"node:path\";\nimport { createHash } from \"node:crypto\";\nimport { FileType } from \"./types.js\";\nimport type { DetectionResult } from \"./types.js\";\n\nconst MANIFEST_PATH = \"graphify-out/manifest.json\";\n\nexport const CODE_EXTENSIONS = new Set([\n \".py\", \".ts\", \".js\", \".jsx\", \".tsx\", \".go\", \".rs\", \".java\", \".cpp\", \".cc\", \".cxx\",\n \".c\", \".h\", \".hpp\", \".rb\", \".swift\", \".kt\", \".kts\", \".cs\", \".scala\", \".php\",\n \".lua\", \".toc\", \".zig\", \".ps1\", \".ex\", \".exs\", \".m\", \".mm\", \".jl\",\n]);\n\nexport const DOC_EXTENSIONS = new Set([\".md\", \".txt\", \".rst\"]);\nexport const PAPER_EXTENSIONS = new Set([\".pdf\"]);\nexport const IMAGE_EXTENSIONS = new Set([\".png\", \".jpg\", \".jpeg\", \".gif\", \".webp\", \".svg\"]);\nexport const OFFICE_EXTENSIONS = new Set([\".docx\", \".xlsx\"]);\n\nconst CORPUS_WARN_THRESHOLD = 50_000;\nconst CORPUS_UPPER_THRESHOLD = 500_000;\nconst FILE_COUNT_UPPER = 200;\n\n// Sensitive file patterns\nconst SENSITIVE_PATTERNS = [\n /(^|[\\\\/])\\.(env|envrc)(\\.|$)/i,\n /\\.(pem|key|p12|pfx|cert|crt|der|p8)$/i,\n /(credential|secret|passwd|password|token|private_key)/i,\n /(id_rsa|id_dsa|id_ecdsa|id_ed25519)(\\.pub)?$/,\n /(\\.netrc|\\.pgpass|\\.htpasswd)$/i,\n /(aws_credentials|gcloud_credentials|service.account)/i,\n];\n\n// Academic paper signals\nconst PAPER_SIGNALS = [\n /\\barxiv\\b/i, /\\bdoi\\s*:/i, /\\babstract\\b/i, /\\bproceedings\\b/i,\n /\\bjournal\\b/i, /\\bpreprint\\b/i, /\\\\cite\\{/, /\\[\\d+\\]/, /\\[\\n\\d+\\n\\]/,\n /eq\\.\\s*\\d+|equation\\s+\\d+/i, /\\d{4}\\.\\d{4,5}/, /\\bwe propose\\b/i, /\\bliterature\\b/i,\n];\nconst PAPER_SIGNAL_THRESHOLD = 3;\n\nfunction isSensitive(filePath: string): boolean {\n const name = basename(filePath);\n return SENSITIVE_PATTERNS.some((p) => p.test(name) || p.test(filePath));\n}\n\nfunction looksLikePaper(filePath: string): boolean {\n try {\n const text = readFileSync(filePath, \"utf-8\").slice(0, 3000);\n const hits = PAPER_SIGNALS.filter((p) => p.test(text)).length;\n return hits >= PAPER_SIGNAL_THRESHOLD;\n } catch {\n return false;\n }\n}\n\nconst ASSET_DIR_MARKERS = new Set([\".imageset\", \".xcassets\", \".appiconset\", \".colorset\", \".launchimage\"]);\n\nexport function classifyFile(filePath: string): FileType | null {\n const ext = extname(filePath).toLowerCase();\n if (CODE_EXTENSIONS.has(ext)) return FileType.CODE;\n if (PAPER_EXTENSIONS.has(ext)) {\n // PDFs inside Xcode asset catalogs are vector icons, not papers\n const parts = filePath.split(sep);\n if (parts.some((p) => [...ASSET_DIR_MARKERS].some((m) => p.endsWith(m)))) return null;\n return FileType.PAPER;\n }\n if (IMAGE_EXTENSIONS.has(ext)) return FileType.IMAGE;\n if (DOC_EXTENSIONS.has(ext)) {\n if (looksLikePaper(filePath)) return FileType.PAPER;\n return FileType.DOCUMENT;\n }\n if (OFFICE_EXTENSIONS.has(ext)) return FileType.DOCUMENT;\n return null;\n}\n\n/** Extract plain text from a PDF file using pdf-parse. */\nexport async function extractPdfText(filePath: string): Promise<string> {\n try {\n const pdfParse = (await import(\"pdf-parse\")).default;\n const buf = readFileSync(filePath);\n const data = await pdfParse(buf);\n return data.text;\n } catch {\n return \"\";\n }\n}\n\n/** Convert a .docx file to markdown text using mammoth. */\nexport async function docxToMarkdown(filePath: string): Promise<string> {\n try {\n const mammoth = await import(\"mammoth\");\n const result = await mammoth.convertToHtml({ path: filePath });\n // mammoth produces HTML; strip tags for a simple text fallback\n return result.value.replace(/<[^>]+>/g, \" \").replace(/\\s+/g, \" \").trim();\n } catch {\n return \"\";\n }\n}\n\n/** Convert an .xlsx file to markdown text using exceljs. */\nexport async function xlsxToMarkdown(filePath: string): Promise<string> {\n try {\n const ExcelJS = await import(\"exceljs\");\n const wb = new ExcelJS.Workbook();\n await wb.xlsx.readFile(filePath);\n const sections: string[] = [];\n wb.eachSheet((ws) => {\n const rows: string[][] = [];\n ws.eachRow((row) => {\n const cells = (row.values as unknown[]).slice(1).map((v) => (v != null ? String(v) : \"\"));\n rows.push(cells);\n });\n if (rows.length === 0) return;\n sections.push(`## Sheet: ${ws.name}`);\n const header = \"| \" + rows[0]!.join(\" | \") + \" |\";\n const sep = \"| \" + rows[0]!.map(() => \"---\").join(\" | \") + \" |\";\n sections.push(header, sep);\n for (const row of rows.slice(1)) {\n sections.push(\"| \" + row.join(\" | \") + \" |\");\n }\n });\n return sections.join(\"\\n\");\n } catch {\n return \"\";\n }\n}\n\n/** Convert .docx/.xlsx to a markdown sidecar file. */\nexport async function convertOfficeFile(filePath: string, outDir: string): Promise<string | null> {\n const ext = extname(filePath).toLowerCase();\n let text: string;\n if (ext === \".docx\") {\n text = await docxToMarkdown(filePath);\n } else if (ext === \".xlsx\") {\n text = await xlsxToMarkdown(filePath);\n } else {\n return null;\n }\n\n if (!text.trim()) return null;\n\n mkdirSync(outDir, { recursive: true });\n const nameHash = createHash(\"sha256\").update(resolve(filePath)).digest(\"hex\").slice(0, 8);\n const stem = basename(filePath, extname(filePath));\n const outPath = join(outDir, `${stem}_${nameHash}.md`);\n writeFileSync(outPath, `<!-- converted from ${basename(filePath)} -->\\n\\n${text}`, \"utf-8\");\n return outPath;\n}\n\nfunction countWords(filePath: string): number {\n try {\n const text = readFileSync(filePath, \"utf-8\");\n return text.split(/\\s+/).filter(Boolean).length;\n } catch {\n return 0;\n }\n}\n\n// Directory names to always skip\nconst SKIP_DIRS = new Set([\n \"venv\", \".venv\", \"env\", \".env\", \"node_modules\", \"__pycache__\", \".git\",\n \"dist\", \"build\", \"target\", \"out\", \"site-packages\", \"lib64\",\n \".pytest_cache\", \".mypy_cache\", \".ruff_cache\", \".tox\", \".eggs\",\n]);\n\nfunction isNoiseDir(part: string): boolean {\n if (SKIP_DIRS.has(part)) return true;\n if (part.endsWith(\"_venv\") || part.endsWith(\"_env\")) return true;\n if (part.endsWith(\".egg-info\")) return true;\n return false;\n}\n\nfunction loadGraphifyignore(root: string): string[] {\n const ignoreFile = join(root, \".graphifyignore\");\n if (!existsSync(ignoreFile)) return [];\n const patterns: string[] = [];\n for (let line of readFileSync(ignoreFile, \"utf-8\").split(\"\\n\")) {\n line = line.trim();\n if (line && !line.startsWith(\"#\")) {\n patterns.push(line);\n }\n }\n return patterns;\n}\n\nfunction matchGlob(text: string, pattern: string): boolean {\n // Simple glob matching (*, ?)\n const regex = pattern\n .replace(/[.+^${}()|[\\]\\\\]/g, \"\\\\$&\")\n .replace(/\\*/g, \".*\")\n .replace(/\\?/g, \".\");\n return new RegExp(`^${regex}$`).test(text);\n}\n\nfunction isIgnored(filePath: string, root: string, patterns: string[]): boolean {\n if (patterns.length === 0) return false;\n let rel: string;\n try {\n rel = relative(root, filePath).replace(/\\\\/g, \"/\");\n } catch {\n return false;\n }\n const parts = rel.split(\"/\");\n for (const pattern of patterns) {\n const p = pattern.replace(/^\\/+|\\/+$/g, \"\");\n if (!p) continue;\n if (matchGlob(rel, p)) return true;\n if (matchGlob(basename(filePath), p)) return true;\n for (let i = 0; i < parts.length; i++) {\n if (matchGlob(parts[i]!, p)) return true;\n if (matchGlob(parts.slice(0, i + 1).join(\"/\"), p)) return true;\n }\n }\n return false;\n}\n\nfunction walkDir(\n dir: string,\n root: string,\n ignorePatterns: string[],\n followSymlinks: boolean,\n skipPrune: boolean,\n): string[] {\n const result: string[] = [];\n let entries: string[];\n try {\n entries = readdirSync(dir);\n } catch {\n return result;\n }\n\n for (const entry of entries) {\n const full = join(dir, entry);\n let stat;\n try {\n stat = followSymlinks ? statSync(full) : lstatSync(full);\n } catch {\n continue;\n }\n\n if (stat.isDirectory()) {\n if (!skipPrune) {\n if (entry.startsWith(\".\")) continue;\n if (isNoiseDir(entry)) continue;\n if (isIgnored(full, root, ignorePatterns)) continue;\n }\n result.push(...walkDir(full, root, ignorePatterns, followSymlinks, skipPrune));\n } else if (stat.isFile()) {\n result.push(full);\n }\n }\n\n return result;\n}\n\nexport function detect(root: string, options?: { followSymlinks?: boolean }): DetectionResult {\n const followSymlinks = options?.followSymlinks ?? false;\n const rootResolved = resolve(root);\n const ignorePatterns = loadGraphifyignore(rootResolved);\n const convertedDir = join(rootResolved, \"graphify-out\", \"converted\");\n const memoryDir = join(rootResolved, \"graphify-out\", \"memory\");\n\n const files: Record<string, string[]> = {\n code: [], document: [], paper: [], image: [],\n };\n let totalWords = 0;\n const skippedSensitive: string[] = [];\n\n // Walk main tree\n const allFiles = walkDir(rootResolved, rootResolved, ignorePatterns, followSymlinks, false);\n\n // Also walk memory dir if it exists\n if (existsSync(memoryDir)) {\n allFiles.push(...walkDir(memoryDir, rootResolved, ignorePatterns, followSymlinks, true));\n }\n\n const seen = new Set<string>();\n\n for (const p of allFiles) {\n if (seen.has(p)) continue;\n seen.add(p);\n\n const inMemory = existsSync(memoryDir) && p.startsWith(memoryDir);\n if (!inMemory) {\n if (basename(p).startsWith(\".\")) continue;\n if (p.startsWith(convertedDir)) continue;\n }\n if (isIgnored(p, rootResolved, ignorePatterns)) continue;\n if (isSensitive(p)) {\n skippedSensitive.push(p);\n continue;\n }\n\n const ftype = classifyFile(p);\n if (!ftype) continue;\n\n // Office files: convert to markdown sidecar\n if (OFFICE_EXTENSIONS.has(extname(p).toLowerCase())) {\n // Note: office conversion is async but detect is sync.\n // We skip office files in sync detect; they're handled in the async pipeline.\n skippedSensitive.push(p + \" [office conversion requires async - use pipeline]\");\n continue;\n }\n\n files[ftype]!.push(p);\n totalWords += countWords(p);\n }\n\n const totalFiles = Object.values(files).reduce((s, v) => s + v.length, 0);\n const needsGraph = totalWords >= CORPUS_WARN_THRESHOLD;\n\n let warning: string | null = null;\n if (!needsGraph) {\n warning = `Corpus is ~${totalWords.toLocaleString()} words - fits in a single context window. You may not need a graph.`;\n } else if (totalWords >= CORPUS_UPPER_THRESHOLD || totalFiles >= FILE_COUNT_UPPER) {\n warning =\n `Large corpus: ${totalFiles} files · ~${totalWords.toLocaleString()} words. ` +\n `Semantic extraction will be expensive (many Claude tokens). ` +\n `Consider running on a subfolder, or use --no-semantic to run AST-only.`;\n }\n\n return {\n files,\n total_files: totalFiles,\n total_words: totalWords,\n needs_graph: needsGraph,\n warning,\n skipped_sensitive: skippedSensitive,\n graphifyignore_patterns: ignorePatterns.length,\n };\n}\n\nexport function loadManifest(manifestPath: string = MANIFEST_PATH): Record<string, number> {\n try {\n return JSON.parse(readFileSync(manifestPath, \"utf-8\")) as Record<string, number>;\n } catch {\n return {};\n }\n}\n\nexport function saveManifest(files: Record<string, string[]>, manifestPath: string = MANIFEST_PATH): void {\n const manifest: Record<string, number> = {};\n for (const fileList of Object.values(files)) {\n for (const f of fileList) {\n try {\n manifest[f] = statSync(f).mtimeMs;\n } catch { /* deleted between detect and save */ }\n }\n }\n const dir = join(manifestPath, \"..\");\n mkdirSync(dir, { recursive: true });\n writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));\n}\n\nexport function detectIncremental(root: string, manifestPath: string = MANIFEST_PATH): DetectionResult {\n const full = detect(root);\n const manifest = loadManifest(manifestPath);\n\n if (Object.keys(manifest).length === 0) {\n return {\n ...full,\n incremental: true,\n new_files: full.files,\n unchanged_files: Object.fromEntries(Object.keys(full.files).map((k) => [k, []])),\n new_total: full.total_files,\n };\n }\n\n const newFiles: Record<string, string[]> = {};\n const unchangedFiles: Record<string, string[]> = {};\n for (const k of Object.keys(full.files)) {\n newFiles[k] = [];\n unchangedFiles[k] = [];\n }\n\n for (const [ftype, fileList] of Object.entries(full.files)) {\n for (const f of fileList) {\n const storedMtime = manifest[f];\n let currentMtime = 0;\n try { currentMtime = statSync(f).mtimeMs; } catch { /* ignore */ }\n if (storedMtime === undefined || currentMtime > storedMtime) {\n newFiles[ftype]!.push(f);\n } else {\n unchangedFiles[ftype]!.push(f);\n }\n }\n }\n\n const currentFiles = new Set(Object.values(full.files).flat());\n const deletedFiles = Object.keys(manifest).filter((f) => !currentFiles.has(f));\n const newTotal = Object.values(newFiles).reduce((s, v) => s + v.length, 0);\n\n return {\n ...full,\n incremental: true,\n new_files: newFiles,\n unchanged_files: unchangedFiles,\n new_total: newTotal,\n deleted_files: deletedFiles,\n };\n}\n","/**\n * Export graph to HTML, JSON, SVG, GraphML, Obsidian Canvas, and Neo4j Cypher.\n */\nimport { writeFileSync } from \"node:fs\";\nimport Graph from \"graphology\";\nimport { sanitizeLabel, escapeHtml } from \"./security.js\";\nimport type { Hyperedge } from \"./types.js\";\nimport {\n type NumericMapLike,\n type StringMapLike,\n toNumericMap,\n toStringMap,\n} from \"./collections.js\";\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nconst COMMUNITY_COLORS = [\n \"#4E79A7\", \"#F28E2B\", \"#E15759\", \"#76B7B2\", \"#59A14F\",\n \"#EDC948\", \"#B07AA1\", \"#FF9DA7\", \"#9C755F\", \"#BAB0AC\",\n];\n\nconst MAX_NODES_FOR_VIZ = 5_000;\n\nconst CONFIDENCE_SCORE_DEFAULTS: Record<string, number> = {\n EXTRACTED: 1.0,\n INFERRED: 0.5,\n AMBIGUOUS: 0.2,\n};\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\ntype CommunityLabelsInput = NumericMapLike<string>;\ntype CommunityLabelOptions = { communityLabels?: CommunityLabelsInput };\ntype SvgOptions = CommunityLabelOptions & { figsize?: [number, number] };\ntype CanvasOptions = CommunityLabelOptions & { nodeFilenames?: StringMapLike<string> };\ntype Neo4jPushOptions = {\n uri: string;\n user: string;\n password: string;\n communities?: NumericMapLike<string[]>;\n};\n\nfunction nodeCommunityMap(communities: NumericMapLike<string[]>): Map<string, number> {\n const communityMap = toNumericMap(communities);\n const result = new Map<string, number>();\n for (const [cid, nodes] of communityMap) {\n for (const n of nodes) result.set(n, cid);\n }\n return result;\n}\n\nfunction cypherEscape(s: string): string {\n return s.replace(/\\\\/g, \"\\\\\\\\\").replace(/'/g, \"\\\\'\");\n}\n\nfunction isCommunityLabelOptions(\n value: CommunityLabelsInput | CommunityLabelOptions,\n): value is CommunityLabelOptions {\n return !(value instanceof Map) && Object.prototype.hasOwnProperty.call(value, \"communityLabels\");\n}\n\nfunction isCanvasOptions(\n value: CommunityLabelsInput | CanvasOptions,\n): value is CanvasOptions {\n return !(value instanceof Map) && (\n Object.prototype.hasOwnProperty.call(value, \"communityLabels\") ||\n Object.prototype.hasOwnProperty.call(value, \"nodeFilenames\")\n );\n}\n\nfunction isSvgOptions(\n value: CommunityLabelsInput | SvgOptions,\n): value is SvgOptions {\n return !(value instanceof Map) && (\n Object.prototype.hasOwnProperty.call(value, \"communityLabels\") ||\n Object.prototype.hasOwnProperty.call(value, \"figsize\")\n );\n}\n\nfunction normalizeCommunityLabels(\n labelsOrOptions?: CommunityLabelsInput | CommunityLabelOptions,\n): Map<number, string> | undefined {\n if (!labelsOrOptions) return undefined;\n if (!isCommunityLabelOptions(labelsOrOptions)) {\n return toNumericMap(labelsOrOptions as CommunityLabelsInput);\n }\n return toNumericMap(labelsOrOptions.communityLabels);\n}\n\n// ---------------------------------------------------------------------------\n// toJson\n// ---------------------------------------------------------------------------\n\nexport function toJson(\n G: Graph,\n communities: NumericMapLike<string[]>,\n outputPath: string,\n): void {\n const nodeComm = nodeCommunityMap(communities);\n\n const nodes: Record<string, unknown>[] = [];\n G.forEachNode((nodeId, attrs) => {\n nodes.push({\n id: nodeId,\n ...attrs,\n community: nodeComm.get(nodeId) ?? null,\n });\n });\n\n const links: Record<string, unknown>[] = [];\n G.forEachEdge((_edge, data, source, target) => {\n const link: Record<string, unknown> = {\n source,\n target,\n ...data,\n };\n if (link.confidence_score === undefined) {\n const conf = (data.confidence as string) ?? \"EXTRACTED\";\n link.confidence_score = CONFIDENCE_SCORE_DEFAULTS[conf] ?? 1.0;\n }\n links.push(link);\n });\n\n const hyperedges = (G.getAttribute(\"hyperedges\") as Hyperedge[] | undefined) ?? [];\n\n const output = {\n directed: false,\n multigraph: false,\n graph: {},\n nodes,\n links,\n hyperedges,\n };\n\n writeFileSync(outputPath, JSON.stringify(output, null, 2), \"utf-8\");\n}\n\n// ---------------------------------------------------------------------------\n// toCypher\n// ---------------------------------------------------------------------------\n\nexport function toCypher(G: Graph, outputPath: string): void {\n const lines: string[] = [\"// Neo4j Cypher import - generated by the graphify skill\", \"\"];\n\n G.forEachNode((nodeId, data) => {\n const label = cypherEscape((data.label as string) ?? nodeId);\n const nodeIdEsc = cypherEscape(nodeId);\n const rawFt = ((data.file_type as string) ?? \"unknown\")\n .charAt(0).toUpperCase() + ((data.file_type as string) ?? \"unknown\").slice(1);\n const cleaned = rawFt.replace(/[^A-Za-z0-9_]/g, \"\");\n const ftype = cleaned && /^[A-Za-z]/.test(cleaned) ? cleaned : \"Entity\";\n lines.push(`MERGE (n:${ftype} {id: '${nodeIdEsc}', label: '${label}'});`);\n });\n\n lines.push(\"\");\n\n G.forEachEdge((_edge, data, u, v) => {\n const rel = ((data.relation as string) ?? \"RELATES_TO\")\n .toUpperCase()\n .replace(/[^A-Za-z0-9_]/g, \"_\");\n const conf = cypherEscape((data.confidence as string) ?? \"EXTRACTED\");\n const uEsc = cypherEscape(u);\n const vEsc = cypherEscape(v);\n lines.push(\n `MATCH (a {id: '${uEsc}'}), (b {id: '${vEsc}'}) ` +\n `MERGE (a)-[:${rel} {confidence: '${conf}'}]->(b);`,\n );\n });\n\n writeFileSync(outputPath, lines.join(\"\\n\"), \"utf-8\");\n}\n\nfunction neo4jLabel(label: string): string {\n const sanitized = label.replace(/[^A-Za-z0-9_]/g, \"\");\n return sanitized || \"Entity\";\n}\n\nfunction neo4jRelation(relation: string): string {\n const sanitized = relation\n .toUpperCase()\n .replace(/[\\s-]+/g, \"_\")\n .replace(/[^A-Z0-9_]/g, \"_\");\n return sanitized || \"RELATED_TO\";\n}\n\nfunction scalarProps(data: Record<string, unknown>): Record<string, string | number | boolean> {\n const props: Record<string, string | number | boolean> = {};\n for (const [key, value] of Object.entries(data)) {\n if (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n ) {\n props[key] = value;\n }\n }\n return props;\n}\n\nexport async function pushToNeo4j(\n G: Graph,\n optionsOrUri: Neo4jPushOptions | string,\n user?: string,\n password?: string,\n communities?: NumericMapLike<string[]>,\n): Promise<{ nodes: number; edges: number }> {\n const options = typeof optionsOrUri === \"string\"\n ? {\n uri: optionsOrUri,\n user: user ?? \"neo4j\",\n password: password ?? \"\",\n communities,\n }\n : optionsOrUri;\n\n let neo4jMod: Record<string, any>;\n try {\n neo4jMod = await import(\"neo4j-driver\");\n } catch {\n throw new Error(\"neo4j-driver not installed. Run: npm install neo4j-driver\");\n }\n\n const neo4j = neo4jMod.default ?? neo4jMod;\n const driver = neo4j.driver(\n options.uri,\n neo4j.auth.basic(options.user, options.password),\n );\n const communityMap = nodeCommunityMap(options.communities ?? new Map<number, string[]>());\n\n let nodes = 0;\n let edges = 0;\n const session = driver.session();\n\n try {\n for (const nodeId of G.nodes()) {\n const attrs = G.getNodeAttributes(nodeId) as Record<string, unknown>;\n const props = scalarProps(attrs);\n props.id = nodeId;\n\n const communityId = communityMap.get(nodeId);\n if (communityId !== undefined) {\n props.community = communityId;\n }\n\n const fileType = neo4jLabel(\n (((attrs.file_type as string) ?? \"Entity\").charAt(0).toUpperCase()) +\n (((attrs.file_type as string) ?? \"Entity\").slice(1)),\n );\n\n await session.run(\n `MERGE (n:${fileType} {id: $id}) SET n += $props`,\n { id: nodeId, props },\n );\n nodes++;\n }\n\n for (const edgeKey of G.edges()) {\n const source = G.source(edgeKey);\n const target = G.target(edgeKey);\n const attrs = G.getEdgeAttributes(edgeKey) as Record<string, unknown>;\n const relation = neo4jRelation((attrs.relation as string) ?? \"RELATED_TO\");\n const props = scalarProps(attrs);\n\n await session.run(\n `MATCH (a {id: $source}), (b {id: $target}) ` +\n `MERGE (a)-[r:${relation}]->(b) SET r += $props`,\n { source, target, props },\n );\n edges++;\n }\n } finally {\n await session.close();\n await driver.close();\n }\n\n return { nodes, edges };\n}\n\n// ---------------------------------------------------------------------------\n// toHtml - full interactive vis.js visualization\n// ---------------------------------------------------------------------------\n\nfunction htmlStyles(): string {\n return `<style>\n * { box-sizing: border-box; margin: 0; padding: 0; }\n body { background: #0f0f1a; color: #e0e0e0; font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif; display: flex; height: 100vh; overflow: hidden; }\n #graph { flex: 1; }\n #sidebar { width: 280px; background: #1a1a2e; border-left: 1px solid #2a2a4e; display: flex; flex-direction: column; overflow: hidden; }\n #search-wrap { padding: 12px; border-bottom: 1px solid #2a2a4e; }\n #search { width: 100%; background: #0f0f1a; border: 1px solid #3a3a5e; color: #e0e0e0; padding: 7px 10px; border-radius: 6px; font-size: 13px; outline: none; }\n #search:focus { border-color: #4E79A7; }\n #search-results { max-height: 140px; overflow-y: auto; padding: 4px 12px; border-bottom: 1px solid #2a2a4e; display: none; }\n .search-item { padding: 4px 6px; cursor: pointer; border-radius: 4px; font-size: 12px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }\n .search-item:hover { background: #2a2a4e; }\n #info-panel { padding: 14px; border-bottom: 1px solid #2a2a4e; min-height: 140px; }\n #info-panel h3 { font-size: 13px; color: #aaa; margin-bottom: 8px; text-transform: uppercase; letter-spacing: 0.05em; }\n #info-content { font-size: 13px; color: #ccc; line-height: 1.6; }\n #info-content .field { margin-bottom: 5px; }\n #info-content .field b { color: #e0e0e0; }\n #info-content .empty { color: #555; font-style: italic; }\n .neighbor-link { display: block; padding: 2px 6px; margin: 2px 0; border-radius: 3px; cursor: pointer; font-size: 12px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; border-left: 3px solid #333; }\n .neighbor-link:hover { background: #2a2a4e; }\n #neighbors-list { max-height: 160px; overflow-y: auto; margin-top: 4px; }\n #legend-wrap { flex: 1; overflow-y: auto; padding: 12px; }\n #legend-wrap h3 { font-size: 13px; color: #aaa; margin-bottom: 10px; text-transform: uppercase; letter-spacing: 0.05em; }\n .legend-item { display: flex; align-items: center; gap: 8px; padding: 4px 0; cursor: pointer; border-radius: 4px; font-size: 12px; }\n .legend-item:hover { background: #2a2a4e; padding-left: 4px; }\n .legend-item.dimmed { opacity: 0.35; }\n .legend-dot { width: 12px; height: 12px; border-radius: 50%; flex-shrink: 0; }\n .legend-label { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n .legend-count { color: #666; font-size: 11px; }\n #stats { padding: 10px 14px; border-top: 1px solid #2a2a4e; font-size: 11px; color: #555; }\n</style>`;\n}\n\nfunction hyperedgeScript(hyperedgesJson: string): string {\n return `<script>\n// Render hyperedges as shaded regions\nconst hyperedges = ${hyperedgesJson};\nfunction drawHyperedges() {\n const canvas = network.canvas.frame.canvas;\n const ctx = canvas.getContext('2d');\n hyperedges.forEach(h => {\n const positions = h.nodes\n .map(nid => network.getPositions([nid])[nid])\n .filter(p => p !== undefined);\n if (positions.length < 2) return;\n // Draw convex hull as filled polygon\n ctx.save();\n ctx.globalAlpha = 0.12;\n ctx.fillStyle = '#6366f1';\n ctx.strokeStyle = '#6366f1';\n ctx.lineWidth = 2;\n ctx.beginPath();\n const scale = network.getScale();\n const offset = network.getViewPosition();\n const toCanvas = (p) => ({\n x: (p.x - offset.x) * scale + canvas.width / 2,\n y: (p.y - offset.y) * scale + canvas.height / 2\n });\n const pts = positions.map(toCanvas);\n // Expand hull slightly\n const cx = pts.reduce((s, p) => s + p.x, 0) / pts.length;\n const cy = pts.reduce((s, p) => s + p.y, 0) / pts.length;\n const expanded = pts.map(p => ({\n x: cx + (p.x - cx) * 1.15,\n y: cy + (p.y - cy) * 1.15\n }));\n ctx.moveTo(expanded[0].x, expanded[0].y);\n expanded.slice(1).forEach(p => ctx.lineTo(p.x, p.y));\n ctx.closePath();\n ctx.fill();\n ctx.globalAlpha = 0.4;\n ctx.stroke();\n // Label\n ctx.globalAlpha = 0.8;\n ctx.fillStyle = '#4f46e5';\n ctx.font = 'bold 11px sans-serif';\n ctx.textAlign = 'center';\n ctx.fillText(h.label, cx, cy - 5);\n ctx.restore();\n });\n}\nnetwork.on('afterDrawing', drawHyperedges);\n</script>`;\n}\n\nfunction htmlScript(nodesJson: string, edgesJson: string, legendJson: string): string {\n return `<script>\nconst RAW_NODES = ${nodesJson};\nconst RAW_EDGES = ${edgesJson};\nconst LEGEND = ${legendJson};\n\n// Build vis datasets\nconst nodesDS = new vis.DataSet(RAW_NODES.map(n => ({\n id: n.id, label: n.label, color: n.color, size: n.size,\n font: n.font, title: n.title,\n _community: n.community, _community_name: n.community_name,\n _source_file: n.source_file, _file_type: n.file_type, _degree: n.degree,\n})));\n\nconst edgesDS = new vis.DataSet(RAW_EDGES.map((e, i) => ({\n id: i, from: e.from, to: e.to,\n label: '',\n title: e.title,\n dashes: e.dashes,\n width: e.width,\n color: e.color,\n arrows: { to: { enabled: true, scaleFactor: 0.5 } },\n})));\n\nconst container = document.getElementById('graph');\nconst network = new vis.Network(container, { nodes: nodesDS, edges: edgesDS }, {\n physics: {\n enabled: true,\n solver: 'forceAtlas2Based',\n forceAtlas2Based: {\n gravitationalConstant: -60,\n centralGravity: 0.005,\n springLength: 120,\n springConstant: 0.08,\n damping: 0.4,\n avoidOverlap: 0.8,\n },\n stabilization: { iterations: 200, fit: true },\n },\n interaction: {\n hover: true,\n tooltipDelay: 100,\n hideEdgesOnDrag: true,\n navigationButtons: false,\n keyboard: false,\n },\n nodes: { shape: 'dot', borderWidth: 1.5 },\n edges: { smooth: { type: 'continuous', roundness: 0.2 }, selectionWidth: 3 },\n});\n\nnetwork.once('stabilizationIterationsDone', () => {\n network.setOptions({ physics: { enabled: false } });\n});\n\nfunction showInfo(nodeId) {\n const n = nodesDS.get(nodeId);\n if (!n) return;\n const neighborIds = network.getConnectedNodes(nodeId);\n const neighborItems = neighborIds.map(nid => {\n const nb = nodesDS.get(nid);\n const color = nb ? nb.color.background : '#555';\n return \\`<span class=\"neighbor-link\" style=\"border-left-color:\\${color}\" onclick=\"focusNode('\\${nid}')\">\\${nb ? nb.label : nid}</span>\\`;\n }).join('');\n document.getElementById('info-content').innerHTML = \\`\n <div class=\"field\"><b>\\${n.label}</b></div>\n <div class=\"field\">Type: \\${n._file_type || 'unknown'}</div>\n <div class=\"field\">Community: \\${n._community_name}</div>\n <div class=\"field\">Source: \\${n._source_file || '-'}</div>\n <div class=\"field\">Degree: \\${n._degree}</div>\n \\${neighborIds.length ? \\`<div class=\"field\" style=\"margin-top:8px;color:#aaa;font-size:11px\">Neighbors (\\${neighborIds.length})</div><div id=\"neighbors-list\">\\${neighborItems}</div>\\` : ''}\n \\`;\n}\n\nfunction focusNode(nodeId) {\n network.focus(nodeId, { scale: 1.4, animation: true });\n network.selectNodes([nodeId]);\n showInfo(nodeId);\n}\n\nnetwork.on('click', params => {\n if (params.nodes.length > 0) showInfo(params.nodes[0]);\n else document.getElementById('info-content').innerHTML = '<span class=\"empty\">Click a node to inspect it</span>';\n});\n\nconst searchInput = document.getElementById('search');\nconst searchResults = document.getElementById('search-results');\nsearchInput.addEventListener('input', () => {\n const q = searchInput.value.toLowerCase().trim();\n searchResults.innerHTML = '';\n if (!q) { searchResults.style.display = 'none'; return; }\n const matches = RAW_NODES.filter(n => n.label.toLowerCase().includes(q)).slice(0, 20);\n if (!matches.length) { searchResults.style.display = 'none'; return; }\n searchResults.style.display = 'block';\n matches.forEach(n => {\n const el = document.createElement('div');\n el.className = 'search-item';\n el.textContent = n.label;\n el.style.borderLeft = \\`3px solid \\${n.color.background}\\`;\n el.style.paddingLeft = '8px';\n el.onclick = () => {\n network.focus(n.id, { scale: 1.5, animation: true });\n network.selectNodes([n.id]);\n showInfo(n.id);\n searchResults.style.display = 'none';\n searchInput.value = '';\n };\n searchResults.appendChild(el);\n });\n});\ndocument.addEventListener('click', e => {\n if (!searchResults.contains(e.target) && e.target !== searchInput)\n searchResults.style.display = 'none';\n});\n\nconst hiddenCommunities = new Set();\nconst legendEl = document.getElementById('legend');\nLEGEND.forEach(c => {\n const item = document.createElement('div');\n item.className = 'legend-item';\n item.innerHTML = \\`<div class=\"legend-dot\" style=\"background:\\${c.color}\"></div>\n <span class=\"legend-label\">\\${c.label}</span>\n <span class=\"legend-count\">\\${c.count}</span>\\`;\n item.onclick = () => {\n if (hiddenCommunities.has(c.cid)) {\n hiddenCommunities.delete(c.cid);\n item.classList.remove('dimmed');\n } else {\n hiddenCommunities.add(c.cid);\n item.classList.add('dimmed');\n }\n const updates = RAW_NODES\n .filter(n => n.community === c.cid)\n .map(n => ({ id: n.id, hidden: hiddenCommunities.has(c.cid) }));\n nodesDS.update(updates);\n };\n legendEl.appendChild(item);\n});\n</script>`;\n}\n\nexport function toHtml(\n G: Graph,\n communities: NumericMapLike<string[]>,\n outputPath: string,\n communityLabelsOrOptions?: CommunityLabelsInput | CommunityLabelOptions,\n): void {\n const communityMap = toNumericMap(communities);\n const communityLabels = normalizeCommunityLabels(communityLabelsOrOptions);\n if (G.order > MAX_NODES_FOR_VIZ) {\n throw new Error(\n `Graph has ${G.order} nodes - too large for HTML viz. ` +\n `Use --no-viz or reduce input size.`,\n );\n }\n\n const nodeComm = nodeCommunityMap(communityMap);\n const degree = new Map<string, number>();\n G.forEachNode((n) => degree.set(n, G.degree(n)));\n const maxDeg = Math.max(1, ...degree.values());\n\n // Build nodes list for vis.js\n interface VisNode {\n id: string;\n label: string;\n color: { background: string; border: string; highlight: { background: string; border: string } };\n size: number;\n font: { size: number; color: string };\n title: string;\n community: number;\n community_name: string;\n source_file: string;\n file_type: string;\n degree: number;\n }\n const visNodes: VisNode[] = [];\n G.forEachNode((nodeId, data) => {\n const cid = nodeComm.get(nodeId) ?? 0;\n const color = COMMUNITY_COLORS[cid % COMMUNITY_COLORS.length]!;\n const label = sanitizeLabel((data.label as string) ?? nodeId);\n const deg = degree.get(nodeId) ?? 1;\n const size = 10 + 30 * (deg / maxDeg);\n const fontSize = deg >= maxDeg * 0.15 ? 12 : 0;\n visNodes.push({\n id: nodeId,\n label,\n color: {\n background: color,\n border: color,\n highlight: { background: \"#ffffff\", border: color },\n },\n size: Math.round(size * 10) / 10,\n font: { size: fontSize, color: \"#ffffff\" },\n title: label,\n community: cid,\n community_name: sanitizeLabel(communityLabels?.get(cid) ?? `Community ${cid}`),\n source_file: sanitizeLabel((data.source_file as string) ?? \"\"),\n file_type: (data.file_type as string) ?? \"\",\n degree: deg,\n });\n });\n\n // Build edges list\n interface VisEdge {\n from: string;\n to: string;\n label: string;\n title: string;\n dashes: boolean;\n width: number;\n color: { opacity: number };\n confidence: string;\n }\n const visEdges: VisEdge[] = [];\n G.forEachEdge((_edge, data, u, v) => {\n const confidence = (data.confidence as string) ?? \"EXTRACTED\";\n const relation = (data.relation as string) ?? \"\";\n visEdges.push({\n from: u,\n to: v,\n label: relation,\n title: `${relation} [${confidence}]`,\n dashes: confidence !== \"EXTRACTED\",\n width: confidence === \"EXTRACTED\" ? 2 : 1,\n color: { opacity: confidence === \"EXTRACTED\" ? 0.7 : 0.35 },\n confidence,\n });\n });\n\n // Build community legend data\n interface LegendEntry {\n cid: number;\n color: string;\n label: string;\n count: number;\n }\n const legendData: LegendEntry[] = [];\n const labelKeys = communityLabels ? [...communityLabels.keys()].sort((a, b) => a - b) : [];\n for (const cid of labelKeys) {\n const color = COMMUNITY_COLORS[cid % COMMUNITY_COLORS.length]!;\n const lbl = escapeHtml(sanitizeLabel(communityLabels?.get(cid) ?? `Community ${cid}`));\n const n = communityMap.get(cid)?.length ?? 0;\n legendData.push({ cid, color, label: lbl, count: n });\n }\n\n const nodesJson = JSON.stringify(visNodes);\n const edgesJson = JSON.stringify(visEdges);\n const legendJson = JSON.stringify(legendData);\n const rawHyperedges = (G.getAttribute(\"hyperedges\") as Hyperedge[] | undefined) ?? [];\n const hyperedgesJson = JSON.stringify(rawHyperedges);\n const title = escapeHtml(sanitizeLabel(outputPath));\n const stats =\n `${G.order} nodes · ${G.size} edges · ${communityMap.size} communities`;\n\n const html = `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<title>graphify - ${title}</title>\n<script src=\"https://unpkg.com/vis-network/standalone/umd/vis-network.min.js\"></script>\n${htmlStyles()}\n</head>\n<body>\n<div id=\"graph\"></div>\n<div id=\"sidebar\">\n <div id=\"search-wrap\">\n <input id=\"search\" type=\"text\" placeholder=\"Search nodes...\" autocomplete=\"off\">\n <div id=\"search-results\"></div>\n </div>\n <div id=\"info-panel\">\n <h3>Node Info</h3>\n <div id=\"info-content\"><span class=\"empty\">Click a node to inspect it</span></div>\n </div>\n <div id=\"legend-wrap\">\n <h3>Communities</h3>\n <div id=\"legend\"></div>\n </div>\n <div id=\"stats\">${stats}</div>\n</div>\n${htmlScript(nodesJson, edgesJson, legendJson)}\n${hyperedgeScript(hyperedgesJson)}\n</body>\n</html>`;\n\n writeFileSync(outputPath, html, \"utf-8\");\n}\n\n// ---------------------------------------------------------------------------\n// toGraphml\n// ---------------------------------------------------------------------------\n\nexport function toGraphml(\n G: Graph,\n communities: NumericMapLike<string[]>,\n outputPath: string,\n): void {\n const nodeComm = nodeCommunityMap(communities);\n\n const xmlEsc = (s: string): string =>\n s\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\")\n .replace(/'/g, \"'\");\n\n const lines: string[] = [];\n lines.push('<?xml version=\"1.0\" encoding=\"UTF-8\"?>');\n lines.push(\n '<graphml xmlns=\"http://graphml.graphstruct.org/graphml\"' +\n ' xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"' +\n ' xsi:schemaLocation=\"http://graphml.graphstruct.org/graphml' +\n ' http://graphml.graphstruct.org/graphml/1.0/graphml.xsd\">',\n );\n\n // Declare attribute keys\n lines.push(' <key id=\"label\" for=\"node\" attr.name=\"label\" attr.type=\"string\"/>');\n lines.push(' <key id=\"file_type\" for=\"node\" attr.name=\"file_type\" attr.type=\"string\"/>');\n lines.push(' <key id=\"source_file\" for=\"node\" attr.name=\"source_file\" attr.type=\"string\"/>');\n lines.push(' <key id=\"community\" for=\"node\" attr.name=\"community\" attr.type=\"int\"/>');\n lines.push(' <key id=\"relation\" for=\"edge\" attr.name=\"relation\" attr.type=\"string\"/>');\n lines.push(' <key id=\"confidence\" for=\"edge\" attr.name=\"confidence\" attr.type=\"string\"/>');\n\n lines.push(' <graph id=\"G\" edgedefault=\"undirected\">');\n\n G.forEachNode((nodeId, data) => {\n lines.push(` <node id=\"${xmlEsc(nodeId)}\">`);\n lines.push(` <data key=\"label\">${xmlEsc((data.label as string) ?? nodeId)}</data>`);\n lines.push(` <data key=\"file_type\">${xmlEsc((data.file_type as string) ?? \"\")}</data>`);\n lines.push(` <data key=\"source_file\">${xmlEsc((data.source_file as string) ?? \"\")}</data>`);\n lines.push(` <data key=\"community\">${nodeComm.get(nodeId) ?? -1}</data>`);\n lines.push(\" </node>\");\n });\n\n G.forEachEdge((_edge, data, source, target) => {\n lines.push(` <edge source=\"${xmlEsc(source)}\" target=\"${xmlEsc(target)}\">`);\n lines.push(` <data key=\"relation\">${xmlEsc((data.relation as string) ?? \"\")}</data>`);\n lines.push(` <data key=\"confidence\">${xmlEsc((data.confidence as string) ?? \"EXTRACTED\")}</data>`);\n lines.push(\" </edge>\");\n });\n\n lines.push(\" </graph>\");\n lines.push(\"</graphml>\");\n\n writeFileSync(outputPath, lines.join(\"\\n\"), \"utf-8\");\n}\n\n// ---------------------------------------------------------------------------\n// toSvg - simple circle-layout SVG\n// ---------------------------------------------------------------------------\n\nexport function toSvg(\n G: Graph,\n communities: NumericMapLike<string[]>,\n outputPath: string,\n communityLabelsOrOptions?: CommunityLabelsInput | SvgOptions,\n figsize: [number, number] = [20, 14],\n): void {\n const communityMap = toNumericMap(communities);\n const options = communityLabelsOrOptions && isSvgOptions(communityLabelsOrOptions)\n ? communityLabelsOrOptions\n : undefined;\n const communityLabels = normalizeCommunityLabels(communityLabelsOrOptions);\n const nodeComm = nodeCommunityMap(communityMap);\n const figureSize = options?.figsize ?? figsize;\n const [widthIn, heightIn] = figureSize;\n const width = widthIn * 60;\n const height = heightIn * 60;\n const cx = width / 2;\n const cy = height / 2;\n const radius = Math.min(cx, cy) * 0.8;\n\n const nodeList = G.nodes();\n const n = nodeList.length;\n\n // Compute positions using a simple circle layout\n const pos = new Map<string, [number, number]>();\n for (let i = 0; i < n; i++) {\n const angle = (2 * Math.PI * i) / Math.max(n, 1);\n pos.set(nodeList[i]!, [\n cx + radius * Math.cos(angle),\n cy + radius * Math.sin(angle),\n ]);\n }\n\n const degree = new Map<string, number>();\n G.forEachNode((node) => degree.set(node, G.degree(node)));\n const maxDeg = Math.max(1, ...degree.values());\n\n const xmlEsc = (s: string): string =>\n s\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\");\n\n const svgParts: string[] = [];\n svgParts.push(\n `<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 ${width} ${height}\" ` +\n `width=\"${width}\" height=\"${height}\" style=\"background:#1a1a2e\">`,\n );\n\n // Draw edges\n G.forEachEdge((_edge, data, u, v) => {\n const [x1, y1] = pos.get(u) ?? [0, 0];\n const [x2, y2] = pos.get(v) ?? [0, 0];\n const conf = (data.confidence as string) ?? \"EXTRACTED\";\n const dasharray = conf === \"EXTRACTED\" ? \"\" : ' stroke-dasharray=\"4,4\"';\n const opacity = conf === \"EXTRACTED\" ? 0.6 : 0.3;\n svgParts.push(\n ` <line x1=\"${x1}\" y1=\"${y1}\" x2=\"${x2}\" y2=\"${y2}\" ` +\n `stroke=\"#aaaaaa\" stroke-width=\"0.8\" opacity=\"${opacity}\"${dasharray}/>`,\n );\n });\n\n // Draw nodes\n for (const nodeId of nodeList) {\n const [x, y] = pos.get(nodeId) ?? [0, 0];\n const cid = nodeComm.get(nodeId) ?? 0;\n const color = COMMUNITY_COLORS[cid % COMMUNITY_COLORS.length]!;\n const deg = degree.get(nodeId) ?? 1;\n const r = 4 + 12 * (deg / maxDeg);\n svgParts.push(\n ` <circle cx=\"${x}\" cy=\"${y}\" r=\"${r}\" fill=\"${color}\" opacity=\"0.9\"/>`,\n );\n const label = (G.getNodeAttribute(nodeId, \"label\") as string) ?? nodeId;\n svgParts.push(\n ` <text x=\"${x}\" y=\"${y + r + 10}\" text-anchor=\"middle\" ` +\n `fill=\"white\" font-size=\"7\" font-family=\"sans-serif\">${xmlEsc(label)}</text>`,\n );\n }\n\n // Legend\n if (communityLabels) {\n const sortedKeys = [...communityLabels.keys()].sort((a, b) => a - b);\n let ly = 20;\n for (const cid of sortedKeys) {\n const color = COMMUNITY_COLORS[cid % COMMUNITY_COLORS.length]!;\n const label = communityLabels.get(cid) ?? `Community ${cid}`;\n const count = communityMap.get(cid)?.length ?? 0;\n svgParts.push(\n ` <circle cx=\"20\" cy=\"${ly}\" r=\"5\" fill=\"${color}\"/>`,\n );\n svgParts.push(\n ` <text x=\"30\" y=\"${ly + 4}\" fill=\"white\" font-size=\"8\" ` +\n `font-family=\"sans-serif\">${xmlEsc(label)} (${count})</text>`,\n );\n ly += 18;\n }\n }\n\n svgParts.push(\"</svg>\");\n writeFileSync(outputPath, svgParts.join(\"\\n\"), \"utf-8\");\n}\n\n// ---------------------------------------------------------------------------\n// toCanvas - Obsidian .canvas JSON\n// ---------------------------------------------------------------------------\n\nexport function toCanvas(\n G: Graph,\n communities: NumericMapLike<string[]>,\n outputPath: string,\n communityLabelsOrOptions?: CommunityLabelsInput | CanvasOptions,\n nodeFilenames?: StringMapLike<string>,\n): void {\n const communityMap = toNumericMap(communities);\n const options = communityLabelsOrOptions && isCanvasOptions(communityLabelsOrOptions)\n ? communityLabelsOrOptions\n : undefined;\n const communityLabels = normalizeCommunityLabels(communityLabelsOrOptions);\n const providedNodeFilenames = options?.nodeFilenames ?? nodeFilenames;\n const CANVAS_COLORS = [\"1\", \"2\", \"3\", \"4\", \"5\", \"6\"];\n\n function safeName(label: string): string {\n return label.replace(/[\\\\/*?:\"<>|#^[\\]]/g, \"\").trim() || \"unnamed\";\n }\n\n // Build nodeFilenames if not provided\n let filenameMap: Map<string, string>;\n if (!providedNodeFilenames) {\n filenameMap = new Map<string, string>();\n const seenNames = new Map<string, number>();\n G.forEachNode((nodeId, data) => {\n const base = safeName((data.label as string) ?? nodeId);\n const count = seenNames.get(base);\n if (count !== undefined) {\n const next = count + 1;\n seenNames.set(base, next);\n filenameMap.set(nodeId, `${base}_${next}`);\n } else {\n seenNames.set(base, 0);\n filenameMap.set(nodeId, base);\n }\n });\n } else {\n filenameMap = toStringMap(providedNodeFilenames);\n }\n\n const numCommunities = communityMap.size;\n const cols = numCommunities > 0 ? Math.ceil(Math.sqrt(numCommunities)) : 1;\n const rows = numCommunities > 0 ? Math.ceil(numCommunities / cols) : 1;\n\n const canvasNodes: Record<string, unknown>[] = [];\n const canvasEdges: Record<string, unknown>[] = [];\n\n const sortedCids = [...communityMap.keys()].sort((a, b) => a - b);\n\n // Precompute group sizes\n const groupSizes = new Map<number, [number, number]>();\n for (const cid of sortedCids) {\n const members = communityMap.get(cid) ?? [];\n const memberCount = members.length;\n const w = Math.max(600, memberCount > 0 ? 220 * Math.ceil(Math.sqrt(memberCount)) : 600);\n const h = Math.max(400, memberCount > 0 ? 100 * Math.ceil(memberCount / 3) + 120 : 400);\n groupSizes.set(cid, [w, h]);\n }\n\n // Compute column widths and row heights\n const gap = 80;\n const colWidths: number[] = [];\n for (let colIdx = 0; colIdx < cols; colIdx++) {\n let maxW = 0;\n for (let rowIdx = 0; rowIdx < rows; rowIdx++) {\n const linear = rowIdx * cols + colIdx;\n if (linear < sortedCids.length) {\n const cid = sortedCids[linear]!;\n const [w] = groupSizes.get(cid) ?? [600, 400];\n maxW = Math.max(maxW, w);\n }\n }\n colWidths.push(maxW);\n }\n\n const rowHeights: number[] = [];\n for (let rowIdx = 0; rowIdx < rows; rowIdx++) {\n let maxH = 0;\n for (let colIdx = 0; colIdx < cols; colIdx++) {\n const linear = rowIdx * cols + colIdx;\n if (linear < sortedCids.length) {\n const cid = sortedCids[linear]!;\n const [, h] = groupSizes.get(cid) ?? [600, 400];\n maxH = Math.max(maxH, h);\n }\n }\n rowHeights.push(maxH);\n }\n\n // Map from cid -> layout\n const groupLayout = new Map<number, [number, number, number, number]>();\n for (let idx = 0; idx < sortedCids.length; idx++) {\n const cid = sortedCids[idx]!;\n const colIdx = idx % cols;\n const rowIdx = Math.floor(idx / cols);\n const gx = colWidths.slice(0, colIdx).reduce((a, b) => a + b, 0) + colIdx * gap;\n const gy = rowHeights.slice(0, rowIdx).reduce((a, b) => a + b, 0) + rowIdx * gap;\n const [gw, gh] = groupSizes.get(cid) ?? [600, 400];\n groupLayout.set(cid, [gx, gy, gw, gh]);\n }\n\n // Collect all node IDs in canvas\n const allCanvasNodeIds = new Set<string>();\n for (const members of communityMap.values()) {\n for (const m of members) allCanvasNodeIds.add(m);\n }\n\n // Generate group and node canvas entries\n for (let idx = 0; idx < sortedCids.length; idx++) {\n const cid = sortedCids[idx]!;\n const members = communityMap.get(cid) ?? [];\n const communityName = communityLabels?.get(cid) ?? `Community ${cid}`;\n const [gx, gy, gw, gh] = groupLayout.get(cid) ?? [0, 0, 600, 400];\n const canvasColor = CANVAS_COLORS[idx % CANVAS_COLORS.length]!;\n\n // Group node\n canvasNodes.push({\n id: `g${cid}`,\n type: \"group\",\n label: communityName,\n x: gx,\n y: gy,\n width: gw,\n height: gh,\n color: canvasColor,\n });\n\n // Node cards inside the group\n const sortedMembers = [...members].sort((a, b) => {\n const la = (G.getNodeAttribute(a, \"label\") as string) ?? a;\n const lb = (G.getNodeAttribute(b, \"label\") as string) ?? b;\n return la.localeCompare(lb);\n });\n for (let mIdx = 0; mIdx < sortedMembers.length; mIdx++) {\n const nodeId = sortedMembers[mIdx]!;\n const col = mIdx % 3;\n const row = Math.floor(mIdx / 3);\n const nx = gx + 20 + col * (180 + 20);\n const ny = gy + 80 + row * (60 + 20);\n const fname =\n filenameMap.get(nodeId) ??\n safeName((G.getNodeAttribute(nodeId, \"label\") as string) ?? nodeId);\n canvasNodes.push({\n id: `n_${nodeId}`,\n type: \"file\",\n file: `graphify/obsidian/${fname}.md`,\n x: nx,\n y: ny,\n width: 180,\n height: 60,\n });\n }\n }\n\n // Generate edges - only between nodes both in canvas, cap at 200 highest-weight\n const allEdgesWeighted: [number, string, string, string][] = [];\n G.forEachEdge((_edge, edata, u, v) => {\n if (allCanvasNodeIds.has(u) && allCanvasNodeIds.has(v)) {\n const weight = (edata.weight as number) ?? 1.0;\n const relation = (edata.relation as string) ?? \"\";\n const conf = (edata.confidence as string) ?? \"EXTRACTED\";\n const label = relation ? `${relation} [${conf}]` : `[${conf}]`;\n allEdgesWeighted.push([weight, u, v, label]);\n }\n });\n\n allEdgesWeighted.sort((a, b) => b[0] - a[0]);\n for (const [, u, v, label] of allEdgesWeighted.slice(0, 200)) {\n canvasEdges.push({\n id: `e_${u}_${v}`,\n fromNode: `n_${u}`,\n toNode: `n_${v}`,\n label,\n });\n }\n\n const canvasData = { nodes: canvasNodes, edges: canvasEdges };\n writeFileSync(outputPath, JSON.stringify(canvasData, null, 2), \"utf-8\");\n}\n","/**\n * Security helpers - URL validation, safe fetch, path guards, label sanitization.\n */\nimport { resolve as pathResolve } from \"node:path\";\nimport { existsSync } from \"node:fs\";\nimport { URL } from \"node:url\";\nimport * as dns from \"node:dns/promises\";\nimport * as net from \"node:net\";\n\nconst ALLOWED_SCHEMES = new Set([\"http:\", \"https:\"]);\nconst MAX_FETCH_BYTES = 52_428_800; // 50 MB\nconst MAX_TEXT_BYTES = 10_485_760; // 10 MB\nconst BLOCKED_HOSTS = new Set([\"metadata.google.internal\", \"metadata.google.com\"]);\n\n// ---------------------------------------------------------------------------\n// URL validation\n// ---------------------------------------------------------------------------\n\n/**\n * Raise if url is not http/https, or targets a private/internal IP.\n * Blocks file://, ftp://, data:, and any other SSRF-prone scheme.\n */\nexport async function validateUrl(url: string): Promise<string> {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n throw new Error(`Invalid URL: ${url}`);\n }\n\n if (!ALLOWED_SCHEMES.has(parsed.protocol)) {\n throw new Error(\n `Blocked URL scheme '${parsed.protocol}' - only http and https are allowed. Got: ${url}`,\n );\n }\n\n const hostname = parsed.hostname;\n if (hostname) {\n if (BLOCKED_HOSTS.has(hostname.toLowerCase())) {\n throw new Error(`Blocked cloud metadata endpoint '${hostname}'. Got: ${url}`);\n }\n\n // Resolve hostname and block private/reserved IP ranges\n try {\n const addrs = await dns.resolve4(hostname).catch(() => [] as string[]);\n const addrs6 = await dns.resolve6(hostname).catch(() => [] as string[]);\n for (const addr of [...addrs, ...addrs6]) {\n if (isPrivateIp(addr)) {\n throw new Error(\n `Blocked private/internal IP ${addr} (resolved from '${hostname}'). Got: ${url}`,\n );\n }\n }\n } catch (e) {\n if (e instanceof Error && e.message.startsWith(\"Blocked\")) throw e;\n // DNS failure will surface later during fetch\n }\n }\n\n return url;\n}\n\n/** Synchronous URL validation (scheme + hostname only, no DNS). */\nexport function validateUrlSync(url: string): string {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n throw new Error(`Invalid URL: ${url}`);\n }\n\n if (!ALLOWED_SCHEMES.has(parsed.protocol)) {\n throw new Error(\n `Blocked URL scheme '${parsed.protocol}' - only http and https are allowed. Got: ${url}`,\n );\n }\n\n if (parsed.hostname && BLOCKED_HOSTS.has(parsed.hostname.toLowerCase())) {\n throw new Error(`Blocked cloud metadata endpoint '${parsed.hostname}'. Got: ${url}`);\n }\n\n return url;\n}\n\nfunction isPrivateIp(addr: string): boolean {\n if (net.isIPv4(addr)) {\n const parts = addr.split(\".\").map(Number);\n const [a, b] = parts as [number, number, ...number[]];\n // 127.x.x.x, 10.x.x.x, 172.16-31.x.x, 192.168.x.x, 169.254.x.x, 0.x.x.x\n if (a === 127) return true;\n if (a === 10) return true;\n if (a === 172 && b !== undefined && b >= 16 && b <= 31) return true;\n if (a === 192 && b === 168) return true;\n if (a === 169 && b === 254) return true;\n if (a === 0) return true;\n return false;\n }\n if (net.isIPv6(addr)) {\n const lower = addr.toLowerCase();\n if (lower === \"::1\" || lower.startsWith(\"fe80:\") || lower.startsWith(\"fc\") || lower.startsWith(\"fd\")) {\n return true;\n }\n }\n return false;\n}\n\n// ---------------------------------------------------------------------------\n// Safe fetch\n// ---------------------------------------------------------------------------\n\n/**\n * Fetch url and return raw bytes (Buffer).\n * Validates URL, caps response body, follows redirects with re-validation.\n */\nexport async function safeFetch(\n url: string,\n maxBytes: number = MAX_FETCH_BYTES,\n timeout: number = 30_000,\n): Promise<Buffer> {\n await validateUrl(url);\n\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeout);\n\n try {\n const resp = await fetch(url, {\n signal: controller.signal,\n headers: { \"User-Agent\": \"Mozilla/5.0 graphify/1.0\" },\n redirect: \"follow\",\n });\n\n if (!resp.ok) {\n throw new Error(`HTTP ${resp.status} fetching ${url}`);\n }\n\n // Validate final URL after redirects\n if (resp.url !== url) {\n await validateUrl(resp.url);\n }\n\n const reader = resp.body?.getReader();\n if (!reader) throw new Error(\"No response body\");\n\n const chunks: Uint8Array[] = [];\n let total = 0;\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.length;\n if (total > maxBytes) {\n reader.cancel();\n throw new Error(\n `Response from ${url} exceeds size limit (${Math.floor(maxBytes / 1_048_576)} MB). Aborting download.`,\n );\n }\n chunks.push(value);\n }\n\n return Buffer.concat(chunks);\n } finally {\n clearTimeout(timer);\n }\n}\n\n/** Fetch url and return decoded text (UTF-8). */\nexport async function safeFetchText(\n url: string,\n maxBytes: number = MAX_TEXT_BYTES,\n timeout: number = 15_000,\n): Promise<string> {\n const raw = await safeFetch(url, maxBytes, timeout);\n return raw.toString(\"utf-8\");\n}\n\n// ---------------------------------------------------------------------------\n// Path validation\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve path and verify it stays inside base (defaults to graphify-out/).\n * Requires the base directory to exist.\n */\nexport function validateGraphPath(filePath: string, base?: string): string {\n const resolvedBase = pathResolve(base ?? \"graphify-out\");\n\n if (!existsSync(resolvedBase)) {\n throw new Error(\n `Graph base directory does not exist: ${resolvedBase}. Run the graphify skill first to build the graph (for Codex: $graphify .).`,\n );\n }\n\n const resolved = pathResolve(filePath);\n\n if (!resolved.startsWith(resolvedBase + \"/\") && resolved !== resolvedBase) {\n throw new Error(\n `Path '${filePath}' escapes the allowed directory ${resolvedBase}. Only paths inside graphify-out/ are permitted.`,\n );\n }\n\n if (!existsSync(resolved)) {\n throw new Error(`Graph file not found: ${resolved}`);\n }\n\n return resolved;\n}\n\n// ---------------------------------------------------------------------------\n// Label sanitization\n// ---------------------------------------------------------------------------\n\nconst CONTROL_CHAR_RE = /[\\x00-\\x1f\\x7f]/g;\nconst MAX_LABEL_LEN = 256;\n\n/** Strip control characters and cap length. Safe for JSON embedding. */\nexport function sanitizeLabel(text: string): string {\n let cleaned = text.replace(CONTROL_CHAR_RE, \"\");\n if (cleaned.length > MAX_LABEL_LEN) {\n cleaned = cleaned.slice(0, MAX_LABEL_LEN);\n }\n return cleaned;\n}\n\n/** Escape text for safe HTML embedding. */\nexport function escapeHtml(text: string): string {\n return text\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\")\n .replace(/'/g, \"'\");\n}\n","/**\n * Deterministic structural extraction from source code using tree-sitter.\n * Outputs nodes + edges dicts.\n *\n * TypeScript port of graphify/extract.py — uses web-tree-sitter (WASM) instead\n * of Python's native tree-sitter bindings.\n */\n\nimport { readFileSync, readdirSync, lstatSync, realpathSync, existsSync } from \"node:fs\";\nimport { resolve, basename, extname, dirname, join, sep } from \"node:path\";\nimport { createRequire } from \"node:module\";\nimport type { GraphNode, GraphEdge, Extraction } from \"./types.js\";\nimport { loadCached, saveCached } from \"./cache.js\";\n\n// ---------------------------------------------------------------------------\n// web-tree-sitter types (re-exported from the package)\n// ---------------------------------------------------------------------------\nimport * as TreeSitter from \"web-tree-sitter\";\ntype SyntaxNode = TreeSitter.Node;\ntype Tree = TreeSitter.Tree;\n\nconst Parser = (\n (TreeSitter as unknown as { Parser?: typeof TreeSitter.Parser }).Parser ??\n (TreeSitter as unknown as { default?: typeof TreeSitter.Parser }).default\n)!;\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nlet _parserInitialized = false;\n\nfunction getModuleRequire(): NodeJS.Require {\n try {\n return createRequire(import.meta.url);\n } catch {\n return require;\n }\n}\n\nconst moduleRequire = getModuleRequire();\n\nasync function ensureParserInit(): Promise<void> {\n if (!_parserInitialized) {\n await Parser.init();\n _parserInitialized = true;\n }\n}\n\nfunction parseText(parser: InstanceType<typeof Parser>, source: string): Tree {\n const tree = parser.parse(source);\n if (!tree) {\n throw new Error(\"Parser returned null\");\n }\n return tree;\n}\n\n/** Try to locate a WASM grammar file. Returns the resolved path or null. */\nfunction resolveGrammarWasm(langName: string): string | null {\n const packageName = new Map<string, string>([\n [\"c_sharp\", \"c-sharp\"],\n ]).get(langName) ?? langName;\n // Try common npm package conventions\n const candidates = [\n `tree-sitter-${packageName}/tree-sitter-${langName}.wasm`,\n `tree-sitter-${packageName}/tree-sitter-${packageName}.wasm`,\n `tree-sitter-${packageName}/tree_sitter_${langName}.wasm`,\n `tree-sitter-${packageName}/tree_sitter_${packageName.replace(/-/g, \"_\")}.wasm`,\n `tree-sitter-${packageName}/${langName}.wasm`,\n `tree-sitter-${packageName}/${packageName}.wasm`,\n ];\n for (const candidate of candidates) {\n try {\n const resolved = moduleRequire.resolve(candidate);\n if (existsSync(resolved)) return resolved;\n } catch {\n /* not found via require.resolve — skip */\n }\n }\n // Also try a path relative to node_modules\n const nmDir = join(process.cwd(), \"node_modules\");\n for (const candidate of candidates) {\n const p = join(nmDir, candidate);\n if (existsSync(p)) return p;\n }\n return null;\n}\n\n/**\n * Cache of loaded Parser.Language instances keyed by language name.\n * Avoids re-reading WASM files on every file extraction.\n */\nconst _languageCache = new Map<string, TreeSitter.Language>();\n\nasync function loadLanguage(langName: string): Promise<TreeSitter.Language | null> {\n if (_languageCache.has(langName)) return _languageCache.get(langName)!;\n const wasmPath = resolveGrammarWasm(langName);\n if (!wasmPath) return null;\n try {\n const lang = await TreeSitter.Language.load(wasmPath);\n _languageCache.set(langName, lang);\n return lang;\n } catch {\n return null;\n }\n}\n\n/** Build a stable node ID from one or more name parts. */\nfunction _makeId(...parts: string[]): string {\n const combined = parts\n .filter(Boolean)\n .map((p) => p.replace(/^[_.]+|[_.]+$/g, \"\"))\n .join(\"_\");\n const cleaned = combined.replace(/[^a-zA-Z0-9]+/g, \"_\");\n return cleaned.replace(/^_+|_+$/g, \"\").toLowerCase();\n}\n\nfunction _readText(node: SyntaxNode, source: string): string {\n return source.slice(node.startIndex, node.endIndex);\n}\n\n// ---------------------------------------------------------------------------\n// LanguageConfig interface + generic helpers\n// ---------------------------------------------------------------------------\n\ntype ImportHandler = (\n node: SyntaxNode,\n source: string,\n fileNid: string,\n stem: string,\n edges: GraphEdge[],\n strPath: string,\n) => void;\n\ntype ResolveFunctionNameFn = (node: SyntaxNode, source: string) => string | null;\n\ntype ExtraWalkFn = (\n node: SyntaxNode,\n source: string,\n fileNid: string,\n stem: string,\n strPath: string,\n nodes: GraphNode[],\n edges: GraphEdge[],\n seenIds: Set<string>,\n functionBodies: Array<[string, SyntaxNode]>,\n parentClassNid: string | null,\n addNodeFn: (nid: string, label: string, line: number) => void,\n addEdgeFn: (src: string, tgt: string, relation: string, line: number) => void,\n walkFn?: (node: SyntaxNode, parentClassNid: string | null) => void,\n) => boolean;\n\ninterface LanguageConfig {\n tsGrammarName: string; // e.g. \"python\"\n tsModule: string; // original Python module name — used for language-specific branches\n\n classTypes: Set<string>;\n functionTypes: Set<string>;\n importTypes: Set<string>;\n callTypes: Set<string>;\n\n nameField: string;\n nameFallbackChildTypes: string[];\n\n bodyField: string;\n bodyFallbackChildTypes: string[];\n\n callFunctionField: string;\n callAccessorNodeTypes: Set<string>;\n callAccessorField: string;\n\n functionBoundaryTypes: Set<string>;\n\n importHandler: ImportHandler | null;\n resolveFunctionNameFn: ResolveFunctionNameFn | null;\n\n functionLabelParens: boolean;\n\n extraWalkFn: ExtraWalkFn | null;\n}\n\nfunction defaultConfig(overrides: Partial<LanguageConfig> & Pick<LanguageConfig, \"tsGrammarName\" | \"tsModule\">): LanguageConfig {\n return {\n classTypes: new Set(),\n functionTypes: new Set(),\n importTypes: new Set(),\n callTypes: new Set(),\n nameField: \"name\",\n nameFallbackChildTypes: [],\n bodyField: \"body\",\n bodyFallbackChildTypes: [],\n callFunctionField: \"function\",\n callAccessorNodeTypes: new Set(),\n callAccessorField: \"attribute\",\n functionBoundaryTypes: new Set(),\n importHandler: null,\n resolveFunctionNameFn: null,\n functionLabelParens: true,\n extraWalkFn: null,\n ...overrides,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Generic helpers for name / body resolution\n// ---------------------------------------------------------------------------\n\nfunction _resolveName(node: SyntaxNode, source: string, config: LanguageConfig): string | null {\n if (config.resolveFunctionNameFn !== null) {\n return null; // caller handles this separately\n }\n const n = node.childForFieldName(config.nameField);\n if (n) return _readText(n, source);\n for (const child of node.children) {\n if (config.nameFallbackChildTypes.includes(child.type)) {\n return _readText(child, source);\n }\n }\n return null;\n}\n\nfunction _findBody(node: SyntaxNode, config: LanguageConfig): SyntaxNode | null {\n const b = node.childForFieldName(config.bodyField);\n if (b) return b;\n for (const child of node.children) {\n if (config.bodyFallbackChildTypes.includes(child.type)) {\n return child;\n }\n }\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Import handlers\n// ---------------------------------------------------------------------------\n\nfunction _importPython(\n node: SyntaxNode, source: string, fileNid: string, _stem: string,\n edges: GraphEdge[], strPath: string,\n): void {\n const t = node.type;\n if (t === \"import_statement\") {\n for (const child of node.children) {\n if (child.type === \"dotted_name\" || child.type === \"aliased_import\") {\n const raw = _readText(child, source);\n const moduleName = raw.split(\" as \")[0]!.trim().replace(/^\\.+/, \"\");\n const tgtNid = _makeId(moduleName);\n edges.push({\n source: fileNid, target: tgtNid, relation: \"imports\",\n confidence: \"EXTRACTED\", source_file: strPath,\n source_location: `L${node.startPosition.row + 1}`, weight: 1.0,\n });\n }\n }\n } else if (t === \"import_from_statement\") {\n const moduleNode = node.childForFieldName(\"module_name\");\n if (moduleNode) {\n const raw = _readText(moduleNode, source).replace(/^\\.+/, \"\");\n const tgtNid = _makeId(raw);\n edges.push({\n source: fileNid, target: tgtNid, relation: \"imports_from\",\n confidence: \"EXTRACTED\", source_file: strPath,\n source_location: `L${node.startPosition.row + 1}`, weight: 1.0,\n });\n }\n }\n}\n\nfunction _importJs(\n node: SyntaxNode, source: string, fileNid: string, _stem: string,\n edges: GraphEdge[], strPath: string,\n): void {\n for (const child of node.children) {\n if (child.type === \"string\") {\n const raw = _readText(child, source).replace(/^['\"`\\s]+|['\"`\\s]+$/g, \"\");\n const moduleName = raw.replace(/^\\.\\/|^\\.\\.\\//, \"\").split(\"/\").pop() ?? \"\";\n if (moduleName) {\n const tgtNid = _makeId(moduleName);\n edges.push({\n source: fileNid, target: tgtNid, relation: \"imports_from\",\n confidence: \"EXTRACTED\", source_file: strPath,\n source_location: `L${node.startPosition.row + 1}`, weight: 1.0,\n });\n }\n break;\n }\n }\n}\n\nfunction _importJava(\n node: SyntaxNode, source: string, fileNid: string, _stem: string,\n edges: GraphEdge[], strPath: string,\n): void {\n function walkScoped(n: SyntaxNode): string {\n const parts: string[] = [];\n let cur: SyntaxNode | null = n;\n while (cur) {\n if (cur.type === \"scoped_identifier\") {\n const nameNode = cur.childForFieldName(\"name\");\n if (nameNode) parts.push(_readText(nameNode, source));\n cur = cur.childForFieldName(\"scope\");\n } else if (cur.type === \"identifier\") {\n parts.push(_readText(cur, source));\n break;\n } else {\n break;\n }\n }\n parts.reverse();\n return parts.join(\".\");\n }\n\n for (const child of node.children) {\n if (child.type === \"scoped_identifier\" || child.type === \"identifier\") {\n const pathStr = walkScoped(child);\n const pathParts = pathStr.split(\".\");\n let moduleName = pathParts[pathParts.length - 1]!.replace(/\\*/g, \"\").replace(/\\.+$/, \"\").trim();\n if (!moduleName && pathParts.length > 1) {\n moduleName = pathParts[pathParts.length - 2]!;\n }\n if (!moduleName) moduleName = pathStr;\n if (moduleName) {\n const tgtNid = _makeId(moduleName);\n edges.push({\n source: fileNid, target: tgtNid, relation: \"imports\",\n confidence: \"EXTRACTED\", source_file: strPath,\n source_location: `L${node.startPosition.row + 1}`, weight: 1.0,\n });\n }\n break;\n }\n }\n}\n\nfunction _importC(\n node: SyntaxNode, source: string, fileNid: string, _stem: string,\n edges: GraphEdge[], strPath: string,\n): void {\n for (const child of node.children) {\n if ([\"string_literal\", \"system_lib_string\", \"string\"].includes(child.type)) {\n const raw = _readText(child, source).replace(/^[\"<>\\s]+|[\"<>\\s]+$/g, \"\");\n const moduleName = raw.split(\"/\").pop()!.split(\".\")[0]!;\n if (moduleName) {\n const tgtNid = _makeId(moduleName);\n edges.push({\n source: fileNid, target: tgtNid, relation: \"imports\",\n confidence: \"EXTRACTED\", source_file: strPath,\n source_location: `L${node.startPosition.row + 1}`, weight: 1.0,\n });\n }\n break;\n }\n }\n}\n\nfunction _importCsharp(\n node: SyntaxNode, source: string, fileNid: string, _stem: string,\n edges: GraphEdge[], strPath: string,\n): void {\n for (const child of node.children) {\n if ([\"qualified_name\", \"identifier\", \"name_equals\"].includes(child.type)) {\n const raw = _readText(child, source);\n const moduleName = raw.split(\".\").pop()!.trim();\n if (moduleName) {\n const tgtNid = _makeId(moduleName);\n edges.push({\n source: fileNid, target: tgtNid, relation: \"imports\",\n confidence: \"EXTRACTED\", source_file: strPath,\n source_location: `L${node.startPosition.row + 1}`, weight: 1.0,\n });\n }\n break;\n }\n }\n}\n\nfunction _importKotlin(\n node: SyntaxNode, source: string, fileNid: string, _stem: string,\n edges: GraphEdge[], strPath: string,\n): void {\n const pathNode = node.childForFieldName(\"path\");\n if (pathNode) {\n const raw = _readText(pathNode, source);\n const moduleName = raw.split(\".\").pop()!.trim();\n if (moduleName) {\n const tgtNid = _makeId(moduleName);\n edges.push({\n source: fileNid, target: tgtNid, relation: \"imports\",\n confidence: \"EXTRACTED\", source_file: strPath,\n source_location: `L${node.startPosition.row + 1}`, weight: 1.0,\n });\n }\n return;\n }\n // Fallback: find identifier child\n for (const child of node.children) {\n if (child.type === \"identifier\") {\n const raw = _readText(child, source);\n const tgtNid = _makeId(raw);\n edges.push({\n source: fileNid, target: tgtNid, relation: \"imports\",\n confidence: \"EXTRACTED\", source_file: strPath,\n source_location: `L${node.startPosition.row + 1}`, weight: 1.0,\n });\n break;\n }\n }\n}\n\nfunction _importScala(\n node: SyntaxNode, source: string, fileNid: string, _stem: string,\n edges: GraphEdge[], strPath: string,\n): void {\n for (const child of node.children) {\n if (child.type === \"stable_id\" || child.type === \"identifier\") {\n const raw = _readText(child, source);\n const moduleName = raw.split(\".\").pop()!.replace(/[{}\\s]/g, \"\").trim();\n if (moduleName && moduleName !== \"_\") {\n const tgtNid = _makeId(moduleName);\n edges.push({\n source: fileNid, target: tgtNid, relation: \"imports\",\n confidence: \"EXTRACTED\", source_file: strPath,\n source_location: `L${node.startPosition.row + 1}`, weight: 1.0,\n });\n }\n break;\n }\n }\n}\n\nfunction _importPhp(\n node: SyntaxNode, source: string, fileNid: string, _stem: string,\n edges: GraphEdge[], strPath: string,\n): void {\n for (const child of node.children) {\n if ([\"qualified_name\", \"name\", \"identifier\"].includes(child.type)) {\n const raw = _readText(child, source);\n const moduleName = raw.split(\"\\\\\").pop()!.trim();\n if (moduleName) {\n const tgtNid = _makeId(moduleName);\n edges.push({\n source: fileNid, target: tgtNid, relation: \"imports\",\n confidence: \"EXTRACTED\", source_file: strPath,\n source_location: `L${node.startPosition.row + 1}`, weight: 1.0,\n });\n }\n break;\n }\n }\n}\n\nfunction _importLua(\n node: SyntaxNode, source: string, fileNid: string, _stem: string,\n edges: GraphEdge[], strPath: string,\n): void {\n const text = _readText(node, source);\n const m = text.match(/require\\s*[('\"]?\\s*['\"]?([^'\")\\s]+)/);\n if (m) {\n const moduleName = m[1]!.split(\".\").pop()!;\n if (moduleName) {\n edges.push({\n source: fileNid, target: moduleName, relation: \"imports\",\n confidence: \"EXTRACTED\", source_file: strPath,\n source_location: String(node.startPosition.row + 1), weight: 1.0,\n });\n }\n }\n}\n\nfunction _importSwift(\n node: SyntaxNode, source: string, fileNid: string, _stem: string,\n edges: GraphEdge[], strPath: string,\n): void {\n for (const child of node.children) {\n if (child.type === \"identifier\") {\n const raw = _readText(child, source);\n const tgtNid = _makeId(raw);\n edges.push({\n source: fileNid, target: tgtNid, relation: \"imports\",\n confidence: \"EXTRACTED\", source_file: strPath,\n source_location: `L${node.startPosition.row + 1}`, weight: 1.0,\n });\n break;\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// C/C++ function name helpers\n// ---------------------------------------------------------------------------\n\nfunction _getCFuncName(node: SyntaxNode, source: string): string | null {\n if (node.type === \"identifier\") return _readText(node, source);\n const decl = node.childForFieldName(\"declarator\");\n if (decl) return _getCFuncName(decl, source);\n for (const child of node.children) {\n if (child.type === \"identifier\") return _readText(child, source);\n }\n return null;\n}\n\nfunction _getCppFuncName(node: SyntaxNode, source: string): string | null {\n if (node.type === \"identifier\") return _readText(node, source);\n if (node.type === \"qualified_identifier\") {\n const nameNode = node.childForFieldName(\"name\");\n if (nameNode) return _readText(nameNode, source);\n }\n const decl = node.childForFieldName(\"declarator\");\n if (decl) return _getCppFuncName(decl, source);\n for (const child of node.children) {\n if (child.type === \"identifier\") return _readText(child, source);\n }\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// JS/TS extra walk for arrow functions\n// ---------------------------------------------------------------------------\n\nfunction _jsExtraWalk(\n node: SyntaxNode, source: string, fileNid: string, stem: string, _strPath: string,\n _nodes: GraphNode[], _edges: GraphEdge[], _seenIds: Set<string>,\n functionBodies: Array<[string, SyntaxNode]>,\n _parentClassNid: string | null,\n addNodeFn: (nid: string, label: string, line: number) => void,\n addEdgeFn: (src: string, tgt: string, relation: string, line: number) => void,\n): boolean {\n if (node.type === \"lexical_declaration\") {\n for (const child of node.children) {\n if (child.type === \"variable_declarator\") {\n const value = child.childForFieldName(\"value\");\n if (value && value.type === \"arrow_function\") {\n const nameNode = child.childForFieldName(\"name\");\n if (nameNode) {\n const funcName = _readText(nameNode, source);\n const line = child.startPosition.row + 1;\n const funcNid = _makeId(stem, funcName);\n addNodeFn(funcNid, `${funcName}()`, line);\n addEdgeFn(fileNid, funcNid, \"contains\", line);\n const body = value.childForFieldName(\"body\");\n if (body) {\n functionBodies.push([funcNid, body]);\n }\n }\n }\n }\n }\n return true;\n }\n return false;\n}\n\n// ---------------------------------------------------------------------------\n// C# extra walk for namespace declarations\n// ---------------------------------------------------------------------------\n\nfunction _csharpExtraWalk(\n node: SyntaxNode, source: string, fileNid: string, stem: string, _strPath: string,\n _nodes: GraphNode[], _edges: GraphEdge[], _seenIds: Set<string>,\n _functionBodies: Array<[string, SyntaxNode]>,\n parentClassNid: string | null,\n addNodeFn: (nid: string, label: string, line: number) => void,\n addEdgeFn: (src: string, tgt: string, relation: string, line: number) => void,\n walkFn?: (node: SyntaxNode, parentClassNid: string | null) => void,\n): boolean {\n if (node.type === \"namespace_declaration\") {\n const nameNode = node.childForFieldName(\"name\");\n if (nameNode) {\n const nsName = _readText(nameNode, source);\n const nsNid = _makeId(stem, nsName);\n const line = node.startPosition.row + 1;\n addNodeFn(nsNid, nsName, line);\n addEdgeFn(fileNid, nsNid, \"contains\", line);\n }\n const body = node.childForFieldName(\"body\");\n if (body && walkFn) {\n for (const child of body.children) {\n walkFn(child, parentClassNid);\n }\n }\n return true;\n }\n return false;\n}\n\n// ---------------------------------------------------------------------------\n// Swift extra walk for enum cases\n// ---------------------------------------------------------------------------\n\nfunction _swiftExtraWalk(\n node: SyntaxNode, source: string, _fileNid: string, _stem: string, _strPath: string,\n _nodes: GraphNode[], _edges: GraphEdge[], _seenIds: Set<string>,\n _functionBodies: Array<[string, SyntaxNode]>,\n parentClassNid: string | null,\n addNodeFn: (nid: string, label: string, line: number) => void,\n addEdgeFn: (src: string, tgt: string, relation: string, line: number) => void,\n): boolean {\n if (node.type === \"enum_entry\" && parentClassNid) {\n for (const child of node.children) {\n if (child.type === \"simple_identifier\") {\n const caseName = _readText(child, source);\n const caseNid = _makeId(parentClassNid, caseName);\n const line = node.startPosition.row + 1;\n addNodeFn(caseNid, caseName, line);\n addEdgeFn(parentClassNid, caseNid, \"case_of\", line);\n }\n }\n return true;\n }\n return false;\n}\n\n// ---------------------------------------------------------------------------\n// Language configs\n// ---------------------------------------------------------------------------\n\nconst _PYTHON_CONFIG: LanguageConfig = defaultConfig({\n tsGrammarName: \"python\",\n tsModule: \"tree_sitter_python\",\n classTypes: new Set([\"class_definition\"]),\n functionTypes: new Set([\"function_definition\"]),\n importTypes: new Set([\"import_statement\", \"import_from_statement\"]),\n callTypes: new Set([\"call\"]),\n callFunctionField: \"function\",\n callAccessorNodeTypes: new Set([\"attribute\"]),\n callAccessorField: \"attribute\",\n functionBoundaryTypes: new Set([\"function_definition\"]),\n importHandler: _importPython,\n});\n\nconst _JS_CONFIG: LanguageConfig = defaultConfig({\n tsGrammarName: \"javascript\",\n tsModule: \"tree_sitter_javascript\",\n classTypes: new Set([\"class_declaration\"]),\n functionTypes: new Set([\"function_declaration\", \"method_definition\"]),\n importTypes: new Set([\"import_statement\"]),\n callTypes: new Set([\"call_expression\"]),\n callFunctionField: \"function\",\n callAccessorNodeTypes: new Set([\"member_expression\"]),\n callAccessorField: \"property\",\n functionBoundaryTypes: new Set([\"function_declaration\", \"arrow_function\", \"method_definition\"]),\n importHandler: _importJs,\n});\n\nconst _TS_CONFIG: LanguageConfig = defaultConfig({\n tsGrammarName: \"typescript\",\n tsModule: \"tree_sitter_typescript\",\n classTypes: new Set([\"class_declaration\"]),\n functionTypes: new Set([\"function_declaration\", \"method_definition\"]),\n importTypes: new Set([\"import_statement\"]),\n callTypes: new Set([\"call_expression\"]),\n callFunctionField: \"function\",\n callAccessorNodeTypes: new Set([\"member_expression\"]),\n callAccessorField: \"property\",\n functionBoundaryTypes: new Set([\"function_declaration\", \"arrow_function\", \"method_definition\"]),\n importHandler: _importJs,\n});\n\nconst _JAVA_CONFIG: LanguageConfig = defaultConfig({\n tsGrammarName: \"java\",\n tsModule: \"tree_sitter_java\",\n classTypes: new Set([\"class_declaration\", \"interface_declaration\"]),\n functionTypes: new Set([\"method_declaration\", \"constructor_declaration\"]),\n importTypes: new Set([\"import_declaration\"]),\n callTypes: new Set([\"method_invocation\"]),\n callFunctionField: \"name\",\n callAccessorNodeTypes: new Set(),\n functionBoundaryTypes: new Set([\"method_declaration\", \"constructor_declaration\"]),\n importHandler: _importJava,\n});\n\nconst _C_CONFIG: LanguageConfig = defaultConfig({\n tsGrammarName: \"c\",\n tsModule: \"tree_sitter_c\",\n classTypes: new Set(),\n functionTypes: new Set([\"function_definition\"]),\n importTypes: new Set([\"preproc_include\"]),\n callTypes: new Set([\"call_expression\"]),\n callFunctionField: \"function\",\n callAccessorNodeTypes: new Set([\"field_expression\"]),\n callAccessorField: \"field\",\n functionBoundaryTypes: new Set([\"function_definition\"]),\n importHandler: _importC,\n resolveFunctionNameFn: _getCFuncName,\n});\n\nconst _CPP_CONFIG: LanguageConfig = defaultConfig({\n tsGrammarName: \"cpp\",\n tsModule: \"tree_sitter_cpp\",\n classTypes: new Set([\"class_specifier\"]),\n functionTypes: new Set([\"function_definition\"]),\n importTypes: new Set([\"preproc_include\"]),\n callTypes: new Set([\"call_expression\"]),\n callFunctionField: \"function\",\n callAccessorNodeTypes: new Set([\"field_expression\", \"qualified_identifier\"]),\n callAccessorField: \"field\",\n functionBoundaryTypes: new Set([\"function_definition\"]),\n importHandler: _importC,\n resolveFunctionNameFn: _getCppFuncName,\n});\n\nconst _RUBY_CONFIG: LanguageConfig = defaultConfig({\n tsGrammarName: \"ruby\",\n tsModule: \"tree_sitter_ruby\",\n classTypes: new Set([\"class\"]),\n functionTypes: new Set([\"method\", \"singleton_method\"]),\n importTypes: new Set(),\n callTypes: new Set([\"call\"]),\n callFunctionField: \"method\",\n callAccessorNodeTypes: new Set(),\n nameFallbackChildTypes: [\"constant\", \"scope_resolution\", \"identifier\"],\n bodyFallbackChildTypes: [\"body_statement\"],\n functionBoundaryTypes: new Set([\"method\", \"singleton_method\"]),\n});\n\nconst _CSHARP_CONFIG: LanguageConfig = defaultConfig({\n tsGrammarName: \"c_sharp\",\n tsModule: \"tree_sitter_c_sharp\",\n classTypes: new Set([\"class_declaration\", \"interface_declaration\"]),\n functionTypes: new Set([\"method_declaration\"]),\n importTypes: new Set([\"using_directive\"]),\n callTypes: new Set([\"invocation_expression\"]),\n callFunctionField: \"function\",\n callAccessorNodeTypes: new Set([\"member_access_expression\"]),\n callAccessorField: \"name\",\n bodyFallbackChildTypes: [\"declaration_list\"],\n functionBoundaryTypes: new Set([\"method_declaration\"]),\n importHandler: _importCsharp,\n});\n\nconst _KOTLIN_CONFIG: LanguageConfig = defaultConfig({\n tsGrammarName: \"kotlin\",\n tsModule: \"tree_sitter_kotlin\",\n classTypes: new Set([\"class_declaration\", \"object_declaration\"]),\n functionTypes: new Set([\"function_declaration\"]),\n importTypes: new Set([\"import_header\"]),\n callTypes: new Set([\"call_expression\"]),\n callFunctionField: \"\",\n callAccessorNodeTypes: new Set([\"navigation_expression\"]),\n callAccessorField: \"\",\n nameFallbackChildTypes: [\"simple_identifier\"],\n bodyFallbackChildTypes: [\"function_body\", \"class_body\"],\n functionBoundaryTypes: new Set([\"function_declaration\"]),\n importHandler: _importKotlin,\n});\n\nconst _SCALA_CONFIG: LanguageConfig = defaultConfig({\n tsGrammarName: \"scala\",\n tsModule: \"tree_sitter_scala\",\n classTypes: new Set([\"class_definition\", \"object_definition\"]),\n functionTypes: new Set([\"function_definition\"]),\n importTypes: new Set([\"import_declaration\"]),\n callTypes: new Set([\"call_expression\"]),\n callFunctionField: \"\",\n callAccessorNodeTypes: new Set([\"field_expression\"]),\n callAccessorField: \"field\",\n nameFallbackChildTypes: [\"identifier\"],\n bodyFallbackChildTypes: [\"template_body\"],\n functionBoundaryTypes: new Set([\"function_definition\"]),\n importHandler: _importScala,\n});\n\nconst _PHP_CONFIG: LanguageConfig = defaultConfig({\n tsGrammarName: \"php\",\n tsModule: \"tree_sitter_php\",\n classTypes: new Set([\"class_declaration\"]),\n functionTypes: new Set([\"function_definition\", \"method_declaration\"]),\n importTypes: new Set([\"namespace_use_clause\"]),\n callTypes: new Set([\"function_call_expression\", \"member_call_expression\"]),\n callFunctionField: \"function\",\n callAccessorNodeTypes: new Set([\"member_call_expression\"]),\n callAccessorField: \"name\",\n nameFallbackChildTypes: [\"name\"],\n bodyFallbackChildTypes: [\"declaration_list\", \"compound_statement\"],\n functionBoundaryTypes: new Set([\"function_definition\", \"method_declaration\"]),\n importHandler: _importPhp,\n});\n\nconst _LUA_CONFIG: LanguageConfig = defaultConfig({\n tsGrammarName: \"lua\",\n tsModule: \"tree_sitter_lua\",\n classTypes: new Set(),\n functionTypes: new Set([\"function_declaration\"]),\n importTypes: new Set([\"variable_declaration\"]),\n callTypes: new Set([\"function_call\"]),\n callFunctionField: \"name\",\n callAccessorNodeTypes: new Set([\"method_index_expression\"]),\n callAccessorField: \"name\",\n nameFallbackChildTypes: [\"identifier\", \"method_index_expression\"],\n bodyFallbackChildTypes: [\"block\"],\n functionBoundaryTypes: new Set([\"function_declaration\"]),\n importHandler: _importLua,\n});\n\nconst _SWIFT_CONFIG: LanguageConfig = defaultConfig({\n tsGrammarName: \"swift\",\n tsModule: \"tree_sitter_swift\",\n classTypes: new Set([\"class_declaration\", \"protocol_declaration\"]),\n functionTypes: new Set([\"function_declaration\", \"init_declaration\", \"deinit_declaration\", \"subscript_declaration\"]),\n importTypes: new Set([\"import_declaration\"]),\n callTypes: new Set([\"call_expression\"]),\n callFunctionField: \"\",\n callAccessorNodeTypes: new Set([\"navigation_expression\"]),\n callAccessorField: \"\",\n nameFallbackChildTypes: [\"simple_identifier\", \"type_identifier\", \"user_type\"],\n bodyFallbackChildTypes: [\"class_body\", \"protocol_body\", \"function_body\", \"enum_class_body\"],\n functionBoundaryTypes: new Set([\"function_declaration\", \"init_declaration\", \"deinit_declaration\", \"subscript_declaration\"]),\n importHandler: _importSwift,\n});\n\n// ---------------------------------------------------------------------------\n// Generic extractor\n// ---------------------------------------------------------------------------\n\nexport interface ExtractionResult {\n nodes: GraphNode[];\n edges: GraphEdge[];\n error?: string;\n}\n\nasync function _extractGeneric(filePath: string, config: LanguageConfig): Promise<ExtractionResult> {\n await ensureParserInit();\n const lang = await loadLanguage(config.tsGrammarName);\n if (!lang) {\n return { nodes: [], edges: [], error: `Grammar not found for ${config.tsGrammarName}` };\n }\n\n let source: string;\n let tree: Tree;\n try {\n const parser = new Parser();\n parser.setLanguage(lang);\n source = readFileSync(filePath, \"utf-8\");\n tree = parseText(parser, source);\n } catch (e: unknown) {\n return { nodes: [], edges: [], error: String(e) };\n }\n\n const root = tree.rootNode;\n const stem = basename(filePath, extname(filePath));\n const strPath = filePath;\n const nodes: GraphNode[] = [];\n const edges: GraphEdge[] = [];\n const seenIds = new Set<string>();\n const functionBodies: Array<[string, SyntaxNode]> = [];\n\n function addNode(nid: string, label: string, line: number): void {\n if (!seenIds.has(nid)) {\n seenIds.add(nid);\n nodes.push({\n id: nid, label, file_type: \"code\",\n source_file: strPath, source_location: `L${line}`,\n });\n }\n }\n\n function addEdge(\n src: string, tgt: string, relation: string, line: number,\n confidence: \"EXTRACTED\" | \"INFERRED\" = \"EXTRACTED\", weight: number = 1.0,\n ): void {\n edges.push({\n source: src, target: tgt, relation,\n confidence, source_file: strPath,\n source_location: `L${line}`, weight,\n });\n }\n\n const fileNid = _makeId(stem);\n addNode(fileNid, basename(filePath), 1);\n\n function walk(node: SyntaxNode, parentClassNid: string | null = null): void {\n const t = node.type;\n\n // Import types\n if (config.importTypes.has(t)) {\n if (config.importHandler) {\n config.importHandler(node, source, fileNid, stem, edges, strPath);\n }\n return;\n }\n\n // Class types\n if (config.classTypes.has(t)) {\n let nameNode = node.childForFieldName(config.nameField);\n if (!nameNode) {\n for (const child of node.children) {\n if (config.nameFallbackChildTypes.includes(child.type)) {\n nameNode = child;\n break;\n }\n }\n }\n if (!nameNode) return;\n const className = _readText(nameNode, source);\n const classNid = _makeId(stem, className);\n const line = node.startPosition.row + 1;\n addNode(classNid, className, line);\n addEdge(fileNid, classNid, \"contains\", line);\n\n // Python-specific: inheritance\n if (config.tsModule === \"tree_sitter_python\") {\n const args = node.childForFieldName(\"superclasses\");\n if (args) {\n for (const arg of args.children) {\n if (arg.type === \"identifier\") {\n const base = _readText(arg, source);\n let baseNid = _makeId(stem, base);\n if (!seenIds.has(baseNid)) {\n baseNid = _makeId(base);\n if (!seenIds.has(baseNid)) {\n nodes.push({\n id: baseNid, label: base, file_type: \"code\",\n source_file: \"\", source_location: \"\",\n });\n seenIds.add(baseNid);\n }\n }\n addEdge(classNid, baseNid, \"inherits\", line);\n }\n }\n }\n }\n\n // Swift-specific: conformance / inheritance\n if (config.tsModule === \"tree_sitter_swift\") {\n for (const child of node.children) {\n if (child.type === \"inheritance_specifier\") {\n for (const sub of child.children) {\n if (sub.type === \"user_type\" || sub.type === \"type_identifier\") {\n const base = _readText(sub, source);\n let baseNid = _makeId(stem, base);\n if (!seenIds.has(baseNid)) {\n baseNid = _makeId(base);\n if (!seenIds.has(baseNid)) {\n nodes.push({\n id: baseNid, label: base, file_type: \"code\",\n source_file: \"\", source_location: \"\",\n });\n seenIds.add(baseNid);\n }\n }\n addEdge(classNid, baseNid, \"inherits\", line);\n }\n }\n }\n }\n }\n\n // C#-specific: inheritance / interface implementation via base_list\n if (config.tsModule === \"tree_sitter_c_sharp\") {\n for (const child of node.children) {\n if (child.type === \"base_list\") {\n for (const sub of child.children) {\n if (sub.type === \"identifier\" || sub.type === \"generic_name\") {\n let base: string;\n if (sub.type === \"generic_name\") {\n const nameChild = sub.childForFieldName(\"name\");\n base = nameChild ? _readText(nameChild, source) : _readText(sub.children[0]!, source);\n } else {\n base = _readText(sub, source);\n }\n let baseNid = _makeId(stem, base);\n if (!seenIds.has(baseNid)) {\n baseNid = _makeId(base);\n if (!seenIds.has(baseNid)) {\n nodes.push({\n id: baseNid, label: base, file_type: \"code\",\n source_file: \"\", source_location: \"\",\n });\n seenIds.add(baseNid);\n }\n }\n addEdge(classNid, baseNid, \"inherits\", line);\n }\n }\n }\n }\n }\n\n // Find body and recurse\n const body = _findBody(node, config);\n if (body) {\n for (const child of body.children) {\n walk(child, classNid);\n }\n }\n return;\n }\n\n // Function types\n if (config.functionTypes.has(t)) {\n let funcName: string | null = null;\n\n // Swift deinit/subscript have no name field\n if (t === \"deinit_declaration\") {\n funcName = \"deinit\";\n } else if (t === \"subscript_declaration\") {\n funcName = \"subscript\";\n } else if (config.resolveFunctionNameFn !== null) {\n // C/C++ style: use declarator\n const declarator = node.childForFieldName(\"declarator\");\n if (declarator) {\n funcName = config.resolveFunctionNameFn(declarator, source);\n }\n } else {\n let nameNode = node.childForFieldName(config.nameField);\n if (!nameNode) {\n for (const child of node.children) {\n if (config.nameFallbackChildTypes.includes(child.type)) {\n nameNode = child;\n break;\n }\n }\n }\n funcName = nameNode ? _readText(nameNode, source) : null;\n }\n\n if (!funcName) return;\n\n const line = node.startPosition.row + 1;\n let funcNid: string;\n if (parentClassNid) {\n funcNid = _makeId(parentClassNid, funcName);\n addNode(funcNid, `.${funcName}()`, line);\n addEdge(parentClassNid, funcNid, \"method\", line);\n } else {\n funcNid = _makeId(stem, funcName);\n addNode(funcNid, `${funcName}()`, line);\n addEdge(fileNid, funcNid, \"contains\", line);\n }\n\n const body = _findBody(node, config);\n if (body) {\n functionBodies.push([funcNid, body]);\n }\n return;\n }\n\n // JS/TS arrow functions\n if (config.tsModule === \"tree_sitter_javascript\" || config.tsModule === \"tree_sitter_typescript\") {\n if (_jsExtraWalk(node, source, fileNid, stem, strPath,\n nodes, edges, seenIds, functionBodies,\n parentClassNid, addNode, addEdge)) {\n return;\n }\n }\n\n // C# namespaces\n if (config.tsModule === \"tree_sitter_c_sharp\") {\n if (_csharpExtraWalk(node, source, fileNid, stem, strPath,\n nodes, edges, seenIds, functionBodies,\n parentClassNid, addNode, addEdge, walk)) {\n return;\n }\n }\n\n // Swift enum cases\n if (config.tsModule === \"tree_sitter_swift\") {\n if (_swiftExtraWalk(node, source, fileNid, stem, strPath,\n nodes, edges, seenIds, functionBodies,\n parentClassNid, addNode, addEdge)) {\n return;\n }\n }\n\n // Default: recurse\n for (const child of node.children) {\n walk(child, null);\n }\n }\n\n walk(root);\n\n // -- Call-graph pass --\n const labelToNid = new Map<string, string>();\n for (const n of nodes) {\n const raw = n.label;\n const normalised = raw.replace(/\\(?\\)$/g, \"\").replace(/^\\./, \"\");\n labelToNid.set(normalised.toLowerCase(), n.id);\n }\n\n const seenCallPairs = new Set<string>();\n\n function walkCalls(node: SyntaxNode, callerNid: string): void {\n if (config.functionBoundaryTypes.has(node.type)) return;\n\n if (config.callTypes.has(node.type)) {\n let calleeName: string | null = null;\n\n // Special handling per language\n if (config.tsModule === \"tree_sitter_swift\") {\n const first = node.children[0] ?? null;\n if (first) {\n if (first.type === \"simple_identifier\") {\n calleeName = _readText(first, source);\n } else if (first.type === \"navigation_expression\") {\n for (const child of first.children) {\n if (child.type === \"navigation_suffix\") {\n for (const sc of child.children) {\n if (sc.type === \"simple_identifier\") {\n calleeName = _readText(sc, source);\n }\n }\n }\n }\n }\n }\n } else if (config.tsModule === \"tree_sitter_kotlin\") {\n const first = node.children[0] ?? null;\n if (first) {\n if (first.type === \"simple_identifier\") {\n calleeName = _readText(first, source);\n } else if (first.type === \"navigation_expression\") {\n for (let i = first.children.length - 1; i >= 0; i--) {\n if (first.children[i]!.type === \"simple_identifier\") {\n calleeName = _readText(first.children[i]!, source);\n break;\n }\n }\n }\n }\n } else if (config.tsModule === \"tree_sitter_scala\") {\n const first = node.children[0] ?? null;\n if (first) {\n if (first.type === \"identifier\") {\n calleeName = _readText(first, source);\n } else if (first.type === \"field_expression\") {\n const field = first.childForFieldName(\"field\");\n if (field) {\n calleeName = _readText(field, source);\n } else {\n for (let i = first.children.length - 1; i >= 0; i--) {\n if (first.children[i]!.type === \"identifier\") {\n calleeName = _readText(first.children[i]!, source);\n break;\n }\n }\n }\n }\n }\n } else if (config.tsModule === \"tree_sitter_c_sharp\" && node.type === \"invocation_expression\") {\n const nameNode = node.childForFieldName(\"name\");\n if (nameNode) {\n calleeName = _readText(nameNode, source);\n } else {\n for (const child of node.children) {\n if (child.isNamed) {\n const raw = _readText(child, source);\n if (raw.includes(\".\")) {\n calleeName = raw.split(\".\").pop()!;\n } else {\n calleeName = raw;\n }\n break;\n }\n }\n }\n } else if (config.tsModule === \"tree_sitter_php\") {\n if (node.type === \"function_call_expression\") {\n const funcNode = node.childForFieldName(\"function\");\n if (funcNode) calleeName = _readText(funcNode, source);\n } else {\n const nameNode = node.childForFieldName(\"name\");\n if (nameNode) calleeName = _readText(nameNode, source);\n }\n } else if (config.tsModule === \"tree_sitter_cpp\") {\n const funcNode = config.callFunctionField ? node.childForFieldName(config.callFunctionField) : null;\n if (funcNode) {\n if (funcNode.type === \"identifier\") {\n calleeName = _readText(funcNode, source);\n } else if (funcNode.type === \"field_expression\" || funcNode.type === \"qualified_identifier\") {\n const name = funcNode.childForFieldName(\"field\") ?? funcNode.childForFieldName(\"name\");\n if (name) calleeName = _readText(name, source);\n }\n }\n } else {\n // Generic: get callee from callFunctionField\n const funcNode = config.callFunctionField ? node.childForFieldName(config.callFunctionField) : null;\n if (funcNode) {\n if (funcNode.type === \"identifier\") {\n calleeName = _readText(funcNode, source);\n } else if (config.callAccessorNodeTypes.has(funcNode.type)) {\n if (config.callAccessorField) {\n const attr = funcNode.childForFieldName(config.callAccessorField);\n if (attr) calleeName = _readText(attr, source);\n }\n } else {\n // Try reading the node directly (e.g. Java name field is the callee)\n calleeName = _readText(funcNode, source);\n }\n }\n }\n\n if (calleeName) {\n const tgtNid = labelToNid.get(calleeName.toLowerCase());\n if (tgtNid && tgtNid !== callerNid) {\n const pair = `${callerNid}|${tgtNid}`;\n if (!seenCallPairs.has(pair)) {\n seenCallPairs.add(pair);\n const line = node.startPosition.row + 1;\n edges.push({\n source: callerNid, target: tgtNid, relation: \"calls\",\n confidence: \"INFERRED\", source_file: strPath,\n source_location: `L${line}`, weight: 0.8,\n });\n }\n }\n }\n }\n\n for (const child of node.children) {\n walkCalls(child, callerNid);\n }\n }\n\n for (const [callerNid, bodyNode] of functionBodies) {\n walkCalls(bodyNode, callerNid);\n }\n\n // -- Clean edges --\n const validIds = seenIds;\n const cleanEdges = edges.filter((edge) => {\n const src = edge.source;\n const tgt = edge.target;\n return validIds.has(src) && (validIds.has(tgt) || edge.relation === \"imports\" || edge.relation === \"imports_from\");\n });\n\n return { nodes, edges: cleanEdges };\n}\n\n// ---------------------------------------------------------------------------\n// Python rationale extraction\n// ---------------------------------------------------------------------------\n\nconst _RATIONALE_PREFIXES = [\n \"# NOTE:\", \"# IMPORTANT:\", \"# HACK:\", \"# WHY:\",\n \"# RATIONALE:\", \"# TODO:\", \"# FIXME:\",\n];\n\nasync function _extractPythonRationale(filePath: string, result: ExtractionResult): Promise<void> {\n await ensureParserInit();\n const lang = await loadLanguage(\"python\");\n if (!lang) return;\n\n let source: string;\n let root: SyntaxNode;\n try {\n const parser = new Parser();\n parser.setLanguage(lang);\n source = readFileSync(filePath, \"utf-8\");\n const tree = parseText(parser, source);\n root = tree.rootNode;\n } catch {\n return;\n }\n\n const stem = basename(filePath, extname(filePath));\n const strPath = filePath;\n const { nodes, edges } = result;\n const seenIds = new Set(nodes.map((n) => n.id));\n const fileNid = _makeId(stem);\n\n function getDocstring(bodyNode: SyntaxNode | null): [string, number] | null {\n if (!bodyNode) return null;\n for (const child of bodyNode.children) {\n if (child.type === \"expression_statement\") {\n for (const sub of child.children) {\n if (sub.type === \"string\" || sub.type === \"concatenated_string\") {\n let text = source.slice(sub.startIndex, sub.endIndex);\n text = text.replace(/^[\"']+|[\"']+$/g, \"\").replace(/^\"\"\"+|\"\"\"+$/g, \"\").replace(/^'''+|'''+$/g, \"\").trim();\n if (text.length > 20) {\n return [text, child.startPosition.row + 1];\n }\n }\n }\n }\n break;\n }\n return null;\n }\n\n function addRationale(text: string, line: number, parentNid: string): void {\n const label = text.slice(0, 80).replace(/\\n/g, \" \").trim();\n const rid = _makeId(stem, \"rationale\", String(line));\n if (!seenIds.has(rid)) {\n seenIds.add(rid);\n nodes.push({\n id: rid, label, file_type: \"rationale\" as GraphNode[\"file_type\"],\n source_file: strPath, source_location: `L${line}`,\n });\n }\n edges.push({\n source: rid, target: parentNid, relation: \"rationale_for\",\n confidence: \"EXTRACTED\", source_file: strPath,\n source_location: `L${line}`, weight: 1.0,\n });\n }\n\n // Module-level docstring\n const ds = getDocstring(root);\n if (ds) addRationale(ds[0], ds[1], fileNid);\n\n // Class and function docstrings\n function walkDocstrings(node: SyntaxNode, parentNid: string): void {\n const t = node.type;\n if (t === \"class_definition\") {\n const nameNode = node.childForFieldName(\"name\");\n const body = node.childForFieldName(\"body\");\n if (nameNode && body) {\n const className = source.slice(nameNode.startIndex, nameNode.endIndex);\n const nid = _makeId(stem, className);\n const classDs = getDocstring(body);\n if (classDs) addRationale(classDs[0], classDs[1], nid);\n for (const child of body.children) {\n walkDocstrings(child, nid);\n }\n }\n return;\n }\n if (t === \"function_definition\") {\n const nameNode = node.childForFieldName(\"name\");\n const body = node.childForFieldName(\"body\");\n if (nameNode && body) {\n const funcName = source.slice(nameNode.startIndex, nameNode.endIndex);\n const nid = parentNid !== fileNid ? _makeId(parentNid, funcName) : _makeId(stem, funcName);\n const funcDs = getDocstring(body);\n if (funcDs) addRationale(funcDs[0], funcDs[1], nid);\n }\n return;\n }\n for (const child of node.children) {\n walkDocstrings(child, parentNid);\n }\n }\n\n walkDocstrings(root, fileNid);\n\n // Rationale comments\n const lines = source.split(\"\\n\");\n for (let lineno = 0; lineno < lines.length; lineno++) {\n const stripped = lines[lineno]!.trim();\n if (_RATIONALE_PREFIXES.some((p) => stripped.startsWith(p))) {\n addRationale(stripped, lineno + 1, fileNid);\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Public API: per-language extractors\n// ---------------------------------------------------------------------------\n\nexport async function extractPython(filePath: string): Promise<ExtractionResult> {\n const result = await _extractGeneric(filePath, _PYTHON_CONFIG);\n if (!result.error) {\n await _extractPythonRationale(filePath, result);\n }\n return result;\n}\n\nexport async function extractJs(filePath: string): Promise<ExtractionResult> {\n const ext = extname(filePath);\n const config = (ext === \".ts\" || ext === \".tsx\") ? _TS_CONFIG : _JS_CONFIG;\n return _extractGeneric(filePath, config);\n}\n\nexport async function extractJava(filePath: string): Promise<ExtractionResult> {\n return _extractGeneric(filePath, _JAVA_CONFIG);\n}\n\nexport async function extractC(filePath: string): Promise<ExtractionResult> {\n return _extractGeneric(filePath, _C_CONFIG);\n}\n\nexport async function extractCpp(filePath: string): Promise<ExtractionResult> {\n return _extractGeneric(filePath, _CPP_CONFIG);\n}\n\nexport async function extractRuby(filePath: string): Promise<ExtractionResult> {\n return _extractGeneric(filePath, _RUBY_CONFIG);\n}\n\nexport async function extractCsharp(filePath: string): Promise<ExtractionResult> {\n return _extractGeneric(filePath, _CSHARP_CONFIG);\n}\n\nexport async function extractKotlin(filePath: string): Promise<ExtractionResult> {\n return _extractGeneric(filePath, _KOTLIN_CONFIG);\n}\n\nexport async function extractScala(filePath: string): Promise<ExtractionResult> {\n return _extractGeneric(filePath, _SCALA_CONFIG);\n}\n\nexport async function extractPhp(filePath: string): Promise<ExtractionResult> {\n return _extractGeneric(filePath, _PHP_CONFIG);\n}\n\nexport async function extractLua(filePath: string): Promise<ExtractionResult> {\n return _extractGeneric(filePath, _LUA_CONFIG);\n}\n\nexport async function extractSwift(filePath: string): Promise<ExtractionResult> {\n return _extractGeneric(filePath, _SWIFT_CONFIG);\n}\n\n// ---------------------------------------------------------------------------\n// Julia extractor (custom walk)\n// ---------------------------------------------------------------------------\n\nexport async function extractJulia(filePath: string): Promise<ExtractionResult> {\n await ensureParserInit();\n const lang = await loadLanguage(\"julia\");\n if (!lang) {\n return { nodes: [], edges: [], error: \"tree-sitter-julia not available\" };\n }\n\n let source: string;\n let tree: Tree;\n try {\n const parser = new Parser();\n parser.setLanguage(lang);\n source = readFileSync(filePath, \"utf-8\");\n tree = parseText(parser, source);\n } catch (e: unknown) {\n return { nodes: [], edges: [], error: String(e) };\n }\n\n const root = tree.rootNode;\n const stem = basename(filePath, extname(filePath));\n const strPath = filePath;\n const nodes: GraphNode[] = [];\n const edges: GraphEdge[] = [];\n const seenIds = new Set<string>();\n const functionBodies: Array<[string, SyntaxNode]> = [];\n\n function addNode(nid: string, label: string, line: number): void {\n if (!seenIds.has(nid)) {\n seenIds.add(nid);\n nodes.push({ id: nid, label, file_type: \"code\", source_file: strPath, source_location: `L${line}` });\n }\n }\n\n function addEdge(\n src: string, tgt: string, relation: string, line: number,\n confidence: \"EXTRACTED\" | \"INFERRED\" = \"EXTRACTED\", weight: number = 1.0,\n ): void {\n edges.push({ source: src, target: tgt, relation, confidence, source_file: strPath, source_location: `L${line}`, weight });\n }\n\n const fileNid = _makeId(stem);\n addNode(fileNid, basename(filePath), 1);\n\n function funcNameFromSignature(sigNode: SyntaxNode): string | null {\n for (const child of sigNode.children) {\n if (child.type === \"call_expression\") {\n const callee = child.children[0] ?? null;\n if (callee && callee.type === \"identifier\") {\n return _readText(callee, source);\n }\n }\n }\n return null;\n }\n\n function walkCalls(bodyNode: SyntaxNode, funcNid: string): void {\n if (!bodyNode) return;\n const t = bodyNode.type;\n if (t === \"function_definition\" || t === \"short_function_definition\") return;\n if (t === \"call_expression\" && bodyNode.children.length > 0) {\n const callee = bodyNode.children[0]!;\n if (callee.type === \"identifier\") {\n const calleeName = _readText(callee, source);\n const targetNid = _makeId(stem, calleeName);\n addEdge(funcNid, targetNid, \"calls\", bodyNode.startPosition.row + 1, \"EXTRACTED\");\n } else if (callee.type === \"field_expression\" && callee.children.length >= 3) {\n const methodNode = callee.children[callee.children.length - 1]!;\n const methodName = _readText(methodNode, source);\n const targetNid = _makeId(stem, methodName);\n addEdge(funcNid, targetNid, \"calls\", bodyNode.startPosition.row + 1, \"EXTRACTED\");\n }\n }\n for (const child of bodyNode.children) {\n walkCalls(child, funcNid);\n }\n }\n\n function walk(node: SyntaxNode, scopeNid: string): void {\n const t = node.type;\n\n // Module\n if (t === \"module_definition\") {\n const nameNode = node.children.find((c) => c.type === \"identifier\") ?? null;\n if (nameNode) {\n const modName = _readText(nameNode, source);\n const modNid = _makeId(stem, modName);\n const line = node.startPosition.row + 1;\n addNode(modNid, modName, line);\n addEdge(fileNid, modNid, \"defines\", line);\n for (const child of node.children) {\n walk(child, modNid);\n }\n }\n return;\n }\n\n // Struct\n if (t === \"struct_definition\") {\n const typeHead = node.children.find((c) => c.type === \"type_head\") ?? null;\n if (typeHead) {\n const binExpr = typeHead.children.find((c) => c.type === \"binary_expression\") ?? null;\n if (binExpr) {\n const identifiers = binExpr.children.filter((c) => c.type === \"identifier\");\n if (identifiers.length > 0) {\n const structName = _readText(identifiers[0]!, source);\n const structNid = _makeId(stem, structName);\n const line = node.startPosition.row + 1;\n addNode(structNid, structName, line);\n addEdge(scopeNid, structNid, \"defines\", line);\n if (identifiers.length >= 2) {\n const superName = _readText(identifiers[identifiers.length - 1]!, source);\n addEdge(structNid, _makeId(stem, superName), \"inherits\", line, \"EXTRACTED\");\n }\n }\n } else {\n const nameNode = typeHead.children.find((c) => c.type === \"identifier\") ?? null;\n if (nameNode) {\n const structName = _readText(nameNode, source);\n const structNid = _makeId(stem, structName);\n const line = node.startPosition.row + 1;\n addNode(structNid, structName, line);\n addEdge(scopeNid, structNid, \"defines\", line);\n }\n }\n }\n return;\n }\n\n // Abstract type\n if (t === \"abstract_definition\") {\n const typeHead = node.children.find((c) => c.type === \"type_head\") ?? null;\n if (typeHead) {\n const nameNode = typeHead.children.find((c) => c.type === \"identifier\") ?? null;\n if (nameNode) {\n const absName = _readText(nameNode, source);\n const absNid = _makeId(stem, absName);\n const line = node.startPosition.row + 1;\n addNode(absNid, absName, line);\n addEdge(scopeNid, absNid, \"defines\", line);\n }\n }\n return;\n }\n\n // Function: function foo(...) ... end\n if (t === \"function_definition\") {\n const sigNode = node.children.find((c) => c.type === \"signature\") ?? null;\n if (sigNode) {\n const funcName = funcNameFromSignature(sigNode);\n if (funcName) {\n const funcNid = _makeId(stem, funcName);\n const line = node.startPosition.row + 1;\n addNode(funcNid, `${funcName}()`, line);\n addEdge(scopeNid, funcNid, \"defines\", line);\n functionBodies.push([funcNid, node]);\n }\n }\n return;\n }\n\n // Short function: foo(x) = expr\n if (t === \"assignment\") {\n const lhs = node.children[0] ?? null;\n if (lhs && lhs.type === \"call_expression\" && lhs.children.length > 0) {\n const callee = lhs.children[0]!;\n if (callee.type === \"identifier\") {\n const funcName = _readText(callee, source);\n const funcNid = _makeId(stem, funcName);\n const line = node.startPosition.row + 1;\n addNode(funcNid, `${funcName}()`, line);\n addEdge(scopeNid, funcNid, \"defines\", line);\n const rhs = node.children.length >= 3 ? node.children[node.children.length - 1]! : null;\n if (rhs) {\n functionBodies.push([funcNid, rhs]);\n }\n }\n }\n return;\n }\n\n // Using / Import\n if (t === \"using_statement\" || t === \"import_statement\") {\n const line = node.startPosition.row + 1;\n for (const child of node.children) {\n if (child.type === \"identifier\") {\n const modName = _readText(child, source);\n const impNid = _makeId(modName);\n addNode(impNid, modName, line);\n addEdge(scopeNid, impNid, \"imports\", line);\n } else if (child.type === \"selected_import\") {\n const identifiers = child.children.filter((c) => c.type === \"identifier\");\n if (identifiers.length > 0) {\n const pkgName = _readText(identifiers[0]!, source);\n const pkgNid = _makeId(pkgName);\n addNode(pkgNid, pkgName, line);\n addEdge(scopeNid, pkgNid, \"imports\", line);\n }\n }\n }\n return;\n }\n\n for (const child of node.children) {\n walk(child, scopeNid);\n }\n }\n\n walk(root, fileNid);\n\n for (const [funcNid, bodyNode] of functionBodies) {\n if (bodyNode.type === \"function_definition\") {\n for (const child of bodyNode.children) {\n if (child.type !== \"signature\") {\n walkCalls(child, funcNid);\n }\n }\n } else {\n walkCalls(bodyNode, funcNid);\n }\n }\n\n return { nodes, edges };\n}\n\n// ---------------------------------------------------------------------------\n// Go extractor (custom walk)\n// ---------------------------------------------------------------------------\n\nexport async function extractGo(filePath: string): Promise<ExtractionResult> {\n await ensureParserInit();\n const lang = await loadLanguage(\"go\");\n if (!lang) {\n return { nodes: [], edges: [], error: \"tree-sitter-go not available\" };\n }\n\n let source: string;\n let tree: Tree;\n try {\n const parser = new Parser();\n parser.setLanguage(lang);\n source = readFileSync(filePath, \"utf-8\");\n tree = parseText(parser, source);\n } catch (e: unknown) {\n return { nodes: [], edges: [], error: String(e) };\n }\n\n const root = tree.rootNode;\n const stem = basename(filePath, extname(filePath));\n const pkgScope = dirname(filePath).split(sep).pop() || stem;\n const strPath = filePath;\n const nodes: GraphNode[] = [];\n const edges: GraphEdge[] = [];\n const seenIds = new Set<string>();\n const functionBodies: Array<[string, SyntaxNode]> = [];\n\n function addNode(nid: string, label: string, line: number): void {\n if (!seenIds.has(nid)) {\n seenIds.add(nid);\n nodes.push({ id: nid, label, file_type: \"code\", source_file: strPath, source_location: `L${line}` });\n }\n }\n\n function addEdge(\n src: string, tgt: string, relation: string, line: number,\n confidence: \"EXTRACTED\" | \"INFERRED\" = \"EXTRACTED\", weight: number = 1.0,\n ): void {\n edges.push({ source: src, target: tgt, relation, confidence, source_file: strPath, source_location: `L${line}`, weight });\n }\n\n const fileNid = _makeId(stem);\n addNode(fileNid, basename(filePath), 1);\n\n function walk(node: SyntaxNode): void {\n const t = node.type;\n\n if (t === \"function_declaration\") {\n const nameNode = node.childForFieldName(\"name\");\n if (nameNode) {\n const funcName = _readText(nameNode, source);\n const line = node.startPosition.row + 1;\n const funcNid = _makeId(stem, funcName);\n addNode(funcNid, `${funcName}()`, line);\n addEdge(fileNid, funcNid, \"contains\", line);\n const body = node.childForFieldName(\"body\");\n if (body) functionBodies.push([funcNid, body]);\n }\n return;\n }\n\n if (t === \"method_declaration\") {\n const receiver = node.childForFieldName(\"receiver\");\n let receiverType: string | null = null;\n if (receiver) {\n for (const param of receiver.children) {\n if (param.type === \"parameter_declaration\") {\n const typeNode = param.childForFieldName(\"type\");\n if (typeNode) {\n receiverType = _readText(typeNode, source).replace(/^\\*/, \"\").trim();\n }\n break;\n }\n }\n }\n const nameNode = node.childForFieldName(\"name\");\n if (nameNode) {\n const methodName = _readText(nameNode, source);\n const line = node.startPosition.row + 1;\n let methodNid: string;\n if (receiverType) {\n const parentNid = _makeId(pkgScope, receiverType);\n addNode(parentNid, receiverType, line);\n methodNid = _makeId(parentNid, methodName);\n addNode(methodNid, `.${methodName}()`, line);\n addEdge(parentNid, methodNid, \"method\", line);\n } else {\n methodNid = _makeId(stem, methodName);\n addNode(methodNid, `${methodName}()`, line);\n addEdge(fileNid, methodNid, \"contains\", line);\n }\n const body = node.childForFieldName(\"body\");\n if (body) functionBodies.push([methodNid, body]);\n }\n return;\n }\n\n if (t === \"type_declaration\") {\n for (const child of node.children) {\n if (child.type === \"type_spec\") {\n const nameNode = child.childForFieldName(\"name\");\n if (nameNode) {\n const typeName = _readText(nameNode, source);\n const line = child.startPosition.row + 1;\n const typeNid = _makeId(pkgScope, typeName);\n addNode(typeNid, typeName, line);\n addEdge(fileNid, typeNid, \"contains\", line);\n }\n }\n }\n return;\n }\n\n if (t === \"import_declaration\") {\n for (const child of node.children) {\n if (child.type === \"import_spec_list\") {\n for (const spec of child.children) {\n if (spec.type === \"import_spec\") {\n const pathNode = spec.childForFieldName(\"path\");\n if (pathNode) {\n const raw = _readText(pathNode, source).replace(/^\"|\"$/g, \"\");\n const moduleName = raw.split(\"/\").pop()!;\n const tgtNid = _makeId(moduleName);\n addEdge(fileNid, tgtNid, \"imports_from\", spec.startPosition.row + 1);\n }\n }\n }\n } else if (child.type === \"import_spec\") {\n const pathNode = child.childForFieldName(\"path\");\n if (pathNode) {\n const raw = _readText(pathNode, source).replace(/^\"|\"$/g, \"\");\n const moduleName = raw.split(\"/\").pop()!;\n const tgtNid = _makeId(moduleName);\n addEdge(fileNid, tgtNid, \"imports_from\", child.startPosition.row + 1);\n }\n }\n }\n return;\n }\n\n for (const child of node.children) {\n walk(child);\n }\n }\n\n walk(root);\n\n // Call-graph pass\n const labelToNid = new Map<string, string>();\n for (const n of nodes) {\n const normalised = n.label.replace(/\\(?\\)$/g, \"\").replace(/^\\./, \"\");\n labelToNid.set(normalised.toLowerCase(), n.id);\n }\n\n const seenCallPairs = new Set<string>();\n\n function walkCalls(node: SyntaxNode, callerNid: string): void {\n if (node.type === \"function_declaration\" || node.type === \"method_declaration\") return;\n if (node.type === \"call_expression\") {\n const funcNode = node.childForFieldName(\"function\");\n let calleeName: string | null = null;\n if (funcNode) {\n if (funcNode.type === \"identifier\") {\n calleeName = _readText(funcNode, source);\n } else if (funcNode.type === \"selector_expression\") {\n const field = funcNode.childForFieldName(\"field\");\n if (field) calleeName = _readText(field, source);\n }\n }\n if (calleeName) {\n const tgtNid = labelToNid.get(calleeName.toLowerCase());\n if (tgtNid && tgtNid !== callerNid) {\n const pair = `${callerNid}|${tgtNid}`;\n if (!seenCallPairs.has(pair)) {\n seenCallPairs.add(pair);\n const line = node.startPosition.row + 1;\n edges.push({\n source: callerNid, target: tgtNid, relation: \"calls\",\n confidence: \"INFERRED\", source_file: strPath,\n source_location: `L${line}`, weight: 0.8,\n });\n }\n }\n }\n }\n for (const child of node.children) {\n walkCalls(child, callerNid);\n }\n }\n\n for (const [callerNid, bodyNode] of functionBodies) {\n walkCalls(bodyNode, callerNid);\n }\n\n const cleanEdges = edges.filter((e) =>\n seenIds.has(e.source) && (seenIds.has(e.target) || e.relation === \"imports\" || e.relation === \"imports_from\"),\n );\n\n return { nodes, edges: cleanEdges };\n}\n\n// ---------------------------------------------------------------------------\n// Rust extractor (custom walk)\n// ---------------------------------------------------------------------------\n\nexport async function extractRust(filePath: string): Promise<ExtractionResult> {\n await ensureParserInit();\n const lang = await loadLanguage(\"rust\");\n if (!lang) {\n return { nodes: [], edges: [], error: \"tree-sitter-rust not available\" };\n }\n\n let source: string;\n let tree: Tree;\n try {\n const parser = new Parser();\n parser.setLanguage(lang);\n source = readFileSync(filePath, \"utf-8\");\n tree = parseText(parser, source);\n } catch (e: unknown) {\n return { nodes: [], edges: [], error: String(e) };\n }\n\n const root = tree.rootNode;\n const stem = basename(filePath, extname(filePath));\n const strPath = filePath;\n const nodes: GraphNode[] = [];\n const edges: GraphEdge[] = [];\n const seenIds = new Set<string>();\n const functionBodies: Array<[string, SyntaxNode]> = [];\n\n function addNode(nid: string, label: string, line: number): void {\n if (!seenIds.has(nid)) {\n seenIds.add(nid);\n nodes.push({ id: nid, label, file_type: \"code\", source_file: strPath, source_location: `L${line}` });\n }\n }\n\n function addEdge(\n src: string, tgt: string, relation: string, line: number,\n confidence: \"EXTRACTED\" | \"INFERRED\" = \"EXTRACTED\", weight: number = 1.0,\n ): void {\n edges.push({ source: src, target: tgt, relation, confidence, source_file: strPath, source_location: `L${line}`, weight });\n }\n\n const fileNid = _makeId(stem);\n addNode(fileNid, basename(filePath), 1);\n\n function walk(node: SyntaxNode, parentImplNid: string | null = null): void {\n const t = node.type;\n\n if (t === \"function_item\") {\n const nameNode = node.childForFieldName(\"name\");\n if (nameNode) {\n const funcName = _readText(nameNode, source);\n const line = node.startPosition.row + 1;\n let funcNid: string;\n if (parentImplNid) {\n funcNid = _makeId(parentImplNid, funcName);\n addNode(funcNid, `.${funcName}()`, line);\n addEdge(parentImplNid, funcNid, \"method\", line);\n } else {\n funcNid = _makeId(stem, funcName);\n addNode(funcNid, `${funcName}()`, line);\n addEdge(fileNid, funcNid, \"contains\", line);\n }\n const body = node.childForFieldName(\"body\");\n if (body) functionBodies.push([funcNid, body]);\n }\n return;\n }\n\n if (t === \"struct_item\" || t === \"enum_item\" || t === \"trait_item\") {\n const nameNode = node.childForFieldName(\"name\");\n if (nameNode) {\n const itemName = _readText(nameNode, source);\n const line = node.startPosition.row + 1;\n const itemNid = _makeId(stem, itemName);\n addNode(itemNid, itemName, line);\n addEdge(fileNid, itemNid, \"contains\", line);\n }\n return;\n }\n\n if (t === \"impl_item\") {\n const typeNode = node.childForFieldName(\"type\");\n let implNid: string | null = null;\n if (typeNode) {\n const typeName = _readText(typeNode, source).trim();\n implNid = _makeId(stem, typeName);\n addNode(implNid, typeName, node.startPosition.row + 1);\n }\n const body = node.childForFieldName(\"body\");\n if (body) {\n for (const child of body.children) {\n walk(child, implNid);\n }\n }\n return;\n }\n\n if (t === \"use_declaration\") {\n const arg = node.childForFieldName(\"argument\");\n if (arg) {\n const raw = _readText(arg, source);\n const clean = raw.split(\"{\")[0]!.replace(/:+$/, \"\").replace(/\\*$/, \"\").replace(/:+$/, \"\");\n const moduleName = clean.split(\"::\").pop()!.trim();\n if (moduleName) {\n const tgtNid = _makeId(moduleName);\n addEdge(fileNid, tgtNid, \"imports_from\", node.startPosition.row + 1);\n }\n }\n return;\n }\n\n for (const child of node.children) {\n walk(child, null);\n }\n }\n\n walk(root);\n\n // Call-graph pass\n const labelToNid = new Map<string, string>();\n for (const n of nodes) {\n const normalised = n.label.replace(/\\(?\\)$/g, \"\").replace(/^\\./, \"\");\n labelToNid.set(normalised.toLowerCase(), n.id);\n }\n\n const seenCallPairs = new Set<string>();\n\n function walkCalls(node: SyntaxNode, callerNid: string): void {\n if (node.type === \"function_item\") return;\n if (node.type === \"call_expression\") {\n const funcNode = node.childForFieldName(\"function\");\n let calleeName: string | null = null;\n if (funcNode) {\n if (funcNode.type === \"identifier\") {\n calleeName = _readText(funcNode, source);\n } else if (funcNode.type === \"field_expression\") {\n const field = funcNode.childForFieldName(\"field\");\n if (field) calleeName = _readText(field, source);\n } else if (funcNode.type === \"scoped_identifier\") {\n const name = funcNode.childForFieldName(\"name\");\n if (name) calleeName = _readText(name, source);\n }\n }\n if (calleeName) {\n const tgtNid = labelToNid.get(calleeName.toLowerCase());\n if (tgtNid && tgtNid !== callerNid) {\n const pair = `${callerNid}|${tgtNid}`;\n if (!seenCallPairs.has(pair)) {\n seenCallPairs.add(pair);\n const line = node.startPosition.row + 1;\n edges.push({\n source: callerNid, target: tgtNid, relation: \"calls\",\n confidence: \"INFERRED\", source_file: strPath,\n source_location: `L${line}`, weight: 0.8,\n });\n }\n }\n }\n }\n for (const child of node.children) {\n walkCalls(child, callerNid);\n }\n }\n\n for (const [callerNid, bodyNode] of functionBodies) {\n walkCalls(bodyNode, callerNid);\n }\n\n const cleanEdges = edges.filter((e) =>\n seenIds.has(e.source) && (seenIds.has(e.target) || e.relation === \"imports\" || e.relation === \"imports_from\"),\n );\n\n return { nodes, edges: cleanEdges };\n}\n\n// ---------------------------------------------------------------------------\n// Zig extractor (custom walk)\n// ---------------------------------------------------------------------------\n\nexport async function extractZig(filePath: string): Promise<ExtractionResult> {\n await ensureParserInit();\n const lang = await loadLanguage(\"zig\");\n if (!lang) {\n return { nodes: [], edges: [], error: \"tree-sitter-zig not available\" };\n }\n\n let source: string;\n let tree: Tree;\n try {\n const parser = new Parser();\n parser.setLanguage(lang);\n source = readFileSync(filePath, \"utf-8\");\n tree = parseText(parser, source);\n } catch (e: unknown) {\n return { nodes: [], edges: [], error: String(e) };\n }\n\n const root = tree.rootNode;\n const stem = basename(filePath, extname(filePath));\n const strPath = filePath;\n const nodes: GraphNode[] = [];\n const edges: GraphEdge[] = [];\n const seenIds = new Set<string>();\n const functionBodies: Array<[string, SyntaxNode]> = [];\n\n function addNode(nid: string, label: string, line: number): void {\n if (!seenIds.has(nid)) {\n seenIds.add(nid);\n nodes.push({ id: nid, label, file_type: \"code\", source_file: strPath, source_location: `L${line}` });\n }\n }\n\n function addEdge(\n src: string, tgt: string, relation: string, line: number,\n confidence: \"EXTRACTED\" | \"INFERRED\" = \"EXTRACTED\", weight: number = 1.0,\n ): void {\n edges.push({ source: src, target: tgt, relation, confidence, source_file: strPath, source_location: `L${line}`, weight });\n }\n\n const fileNid = _makeId(stem);\n addNode(fileNid, basename(filePath), 1);\n\n function extractImport(node: SyntaxNode): void {\n for (const child of node.children) {\n if (child.type === \"builtin_function\") {\n let bi: string | null = null;\n let args: SyntaxNode | null = null;\n for (const c of child.children) {\n if (c.type === \"builtin_identifier\") bi = _readText(c, source);\n else if (c.type === \"arguments\") args = c;\n }\n if ((bi === \"@import\" || bi === \"@cImport\") && args) {\n for (const arg of args.children) {\n if (arg.type === \"string_literal\" || arg.type === \"string\") {\n const raw = _readText(arg, source).replace(/^\"|\"$/g, \"\");\n const moduleName = raw.split(\"/\").pop()!.split(\".\")[0]!;\n if (moduleName) {\n const tgtNid = _makeId(moduleName);\n addEdge(fileNid, tgtNid, \"imports_from\", node.startPosition.row + 1);\n }\n return;\n }\n }\n }\n } else if (child.type === \"field_expression\") {\n extractImport(child);\n return;\n }\n }\n }\n\n function walk(node: SyntaxNode, parentStructNid: string | null = null): void {\n const t = node.type;\n\n if (t === \"function_declaration\") {\n const nameNode = node.childForFieldName(\"name\");\n if (nameNode) {\n const funcName = _readText(nameNode, source);\n const line = node.startPosition.row + 1;\n let funcNid: string;\n if (parentStructNid) {\n funcNid = _makeId(parentStructNid, funcName);\n addNode(funcNid, `.${funcName}()`, line);\n addEdge(parentStructNid, funcNid, \"method\", line);\n } else {\n funcNid = _makeId(stem, funcName);\n addNode(funcNid, `${funcName}()`, line);\n addEdge(fileNid, funcNid, \"contains\", line);\n }\n const body = node.childForFieldName(\"body\");\n if (body) functionBodies.push([funcNid, body]);\n }\n return;\n }\n\n if (t === \"variable_declaration\") {\n let nameNode: SyntaxNode | null = null;\n let valueNode: SyntaxNode | null = null;\n for (const child of node.children) {\n if (child.type === \"identifier\") {\n nameNode = child;\n } else if ([\"struct_declaration\", \"enum_declaration\", \"union_declaration\", \"builtin_function\", \"field_expression\"].includes(child.type)) {\n valueNode = child;\n }\n }\n\n if (valueNode && valueNode.type === \"struct_declaration\") {\n if (nameNode) {\n const structName = _readText(nameNode, source);\n const line = node.startPosition.row + 1;\n const structNid = _makeId(stem, structName);\n addNode(structNid, structName, line);\n addEdge(fileNid, structNid, \"contains\", line);\n for (const child of valueNode.children) {\n walk(child, structNid);\n }\n }\n return;\n }\n\n if (valueNode && (valueNode.type === \"enum_declaration\" || valueNode.type === \"union_declaration\")) {\n if (nameNode) {\n const typeName = _readText(nameNode, source);\n const line = node.startPosition.row + 1;\n const typeNid = _makeId(stem, typeName);\n addNode(typeNid, typeName, line);\n addEdge(fileNid, typeNid, \"contains\", line);\n }\n return;\n }\n\n if (valueNode && (valueNode.type === \"builtin_function\" || valueNode.type === \"field_expression\")) {\n extractImport(node);\n }\n return;\n }\n\n for (const child of node.children) {\n walk(child, parentStructNid);\n }\n }\n\n walk(root);\n\n // Call-graph pass\n const seenCallPairs = new Set<string>();\n\n function walkCalls(node: SyntaxNode, callerNid: string): void {\n if (node.type === \"function_declaration\") return;\n if (node.type === \"call_expression\") {\n const fn = node.childForFieldName(\"function\");\n if (fn) {\n const callee = _readText(fn, source).split(\".\").pop()!;\n const tgtNid = nodes.find(\n (n) => n.label === `${callee}()` || n.label === `.${callee}()`,\n )?.id ?? null;\n if (tgtNid && tgtNid !== callerNid) {\n const pair = `${callerNid}|${tgtNid}`;\n if (!seenCallPairs.has(pair)) {\n seenCallPairs.add(pair);\n addEdge(callerNid, tgtNid, \"calls\", node.startPosition.row + 1, \"INFERRED\", 0.8);\n }\n }\n }\n }\n for (const child of node.children) {\n walkCalls(child, callerNid);\n }\n }\n\n for (const [callerNid, bodyNode] of functionBodies) {\n walkCalls(bodyNode, callerNid);\n }\n\n const cleanEdges = edges.filter((e) =>\n seenIds.has(e.source) && (seenIds.has(e.target) || e.relation === \"imports_from\"),\n );\n\n return { nodes, edges: cleanEdges };\n}\n\n// ---------------------------------------------------------------------------\n// PowerShell extractor (custom walk)\n// ---------------------------------------------------------------------------\n\nexport async function extractPowershell(filePath: string): Promise<ExtractionResult> {\n await ensureParserInit();\n const lang = await loadLanguage(\"powershell\");\n if (!lang) {\n return { nodes: [], edges: [], error: \"tree-sitter-powershell not available\" };\n }\n\n let source: string;\n let tree: Tree;\n try {\n const parser = new Parser();\n parser.setLanguage(lang);\n source = readFileSync(filePath, \"utf-8\");\n tree = parseText(parser, source);\n } catch (e: unknown) {\n return { nodes: [], edges: [], error: String(e) };\n }\n\n const root = tree.rootNode;\n const stem = basename(filePath, extname(filePath));\n const strPath = filePath;\n const nodes: GraphNode[] = [];\n const edges: GraphEdge[] = [];\n const seenIds = new Set<string>();\n const functionBodies: Array<[string, SyntaxNode]> = [];\n\n function addNode(nid: string, label: string, line: number): void {\n if (!seenIds.has(nid)) {\n seenIds.add(nid);\n nodes.push({ id: nid, label, file_type: \"code\", source_file: strPath, source_location: `L${line}` });\n }\n }\n\n function addEdge(\n src: string, tgt: string, relation: string, line: number,\n confidence: \"EXTRACTED\" | \"INFERRED\" = \"EXTRACTED\", weight: number = 1.0,\n ): void {\n edges.push({ source: src, target: tgt, relation, confidence, source_file: strPath, source_location: `L${line}`, weight });\n }\n\n const fileNid = _makeId(stem);\n addNode(fileNid, basename(filePath), 1);\n\n const _PS_SKIP = new Set([\n \"using\", \"return\", \"if\", \"else\", \"elseif\", \"foreach\", \"for\",\n \"while\", \"do\", \"switch\", \"try\", \"catch\", \"finally\", \"throw\",\n \"break\", \"continue\", \"exit\", \"param\", \"begin\", \"process\", \"end\",\n ]);\n\n function findScriptBlockBody(node: SyntaxNode): SyntaxNode | null {\n for (const child of node.children) {\n if (child.type === \"script_block\") {\n for (const sc of child.children) {\n if (sc.type === \"script_block_body\") return sc;\n }\n return child;\n }\n }\n return null;\n }\n\n function walk(node: SyntaxNode, parentClassNid: string | null = null): void {\n const t = node.type;\n\n if (t === \"function_statement\") {\n const nameNode = node.children.find((c) => c.type === \"function_name\") ?? null;\n if (nameNode) {\n const funcName = _readText(nameNode, source);\n const line = node.startPosition.row + 1;\n const funcNid = _makeId(stem, funcName);\n addNode(funcNid, `${funcName}()`, line);\n addEdge(fileNid, funcNid, \"contains\", line);\n const body = findScriptBlockBody(node);\n if (body) functionBodies.push([funcNid, body]);\n }\n return;\n }\n\n if (t === \"class_statement\") {\n const nameNode = node.children.find((c) => c.type === \"simple_name\") ?? null;\n if (nameNode) {\n const className = _readText(nameNode, source);\n const line = node.startPosition.row + 1;\n const classNid = _makeId(stem, className);\n addNode(classNid, className, line);\n addEdge(fileNid, classNid, \"contains\", line);\n for (const child of node.children) {\n walk(child, classNid);\n }\n }\n return;\n }\n\n if (t === \"class_method_definition\") {\n const nameNode = node.children.find((c) => c.type === \"simple_name\") ?? null;\n if (nameNode) {\n const methodName = _readText(nameNode, source);\n const line = node.startPosition.row + 1;\n let methodNid: string;\n if (parentClassNid) {\n methodNid = _makeId(parentClassNid, methodName);\n addNode(methodNid, `.${methodName}()`, line);\n addEdge(parentClassNid, methodNid, \"method\", line);\n } else {\n methodNid = _makeId(stem, methodName);\n addNode(methodNid, `${methodName}()`, line);\n addEdge(fileNid, methodNid, \"contains\", line);\n }\n const body = findScriptBlockBody(node);\n if (body) functionBodies.push([methodNid, body]);\n }\n return;\n }\n\n if (t === \"command\") {\n const cmdNameNode = node.children.find((c) => c.type === \"command_name\") ?? null;\n if (cmdNameNode) {\n const cmdText = _readText(cmdNameNode, source).toLowerCase();\n if (cmdText === \"using\") {\n const tokens: string[] = [];\n for (const child of node.children) {\n if (child.type === \"command_elements\") {\n for (const el of child.children) {\n if (el.type === \"generic_token\") {\n tokens.push(_readText(el, source));\n }\n }\n }\n }\n const moduleTokens = tokens.filter(\n (tk) => ![\"namespace\", \"module\", \"assembly\"].includes(tk.toLowerCase()),\n );\n if (moduleTokens.length > 0) {\n const moduleName = moduleTokens[moduleTokens.length - 1]!.split(\".\").pop()!;\n addEdge(fileNid, _makeId(moduleName), \"imports_from\", node.startPosition.row + 1);\n }\n }\n }\n return;\n }\n\n for (const child of node.children) {\n walk(child, parentClassNid);\n }\n }\n\n walk(root);\n\n // Call-graph pass\n const labelToNid = new Map<string, string>();\n for (const n of nodes) {\n const normalised = n.label.replace(/\\(?\\)$/g, \"\").replace(/^\\./, \"\");\n labelToNid.set(normalised.toLowerCase(), n.id);\n }\n\n const seenCallPairs = new Set<string>();\n\n function walkCalls(node: SyntaxNode, callerNid: string): void {\n if (node.type === \"function_statement\" || node.type === \"class_statement\") return;\n if (node.type === \"command\") {\n const cmdNameNode = node.children.find((c) => c.type === \"command_name\") ?? null;\n if (cmdNameNode) {\n const cmdText = _readText(cmdNameNode, source);\n if (!_PS_SKIP.has(cmdText.toLowerCase())) {\n const tgtNid = labelToNid.get(cmdText.toLowerCase());\n if (tgtNid && tgtNid !== callerNid) {\n const pair = `${callerNid}|${tgtNid}`;\n if (!seenCallPairs.has(pair)) {\n seenCallPairs.add(pair);\n addEdge(callerNid, tgtNid, \"calls\", node.startPosition.row + 1, \"INFERRED\", 0.8);\n }\n }\n }\n }\n }\n for (const child of node.children) {\n walkCalls(child, callerNid);\n }\n }\n\n for (const [callerNid, bodyNode] of functionBodies) {\n walkCalls(bodyNode, callerNid);\n }\n\n const cleanEdges = edges.filter((e) =>\n seenIds.has(e.source) && (seenIds.has(e.target) || e.relation === \"imports_from\"),\n );\n\n return { nodes, edges: cleanEdges };\n}\n\n// ---------------------------------------------------------------------------\n// Objective-C extractor (custom walk)\n// ---------------------------------------------------------------------------\n\nexport async function extractObjc(filePath: string): Promise<ExtractionResult> {\n await ensureParserInit();\n const lang = await loadLanguage(\"objc\");\n if (!lang) {\n return { nodes: [], edges: [], error: \"tree-sitter-objc not available\" };\n }\n\n let source: string;\n let tree: Tree;\n try {\n const parser = new Parser();\n parser.setLanguage(lang);\n source = readFileSync(filePath, \"utf-8\");\n tree = parseText(parser, source);\n } catch (e: unknown) {\n return { nodes: [], edges: [], error: String(e) };\n }\n\n const root = tree.rootNode;\n const stem = basename(filePath, extname(filePath));\n const strPath = filePath;\n const nodes: GraphNode[] = [];\n const edges: GraphEdge[] = [];\n const seenIds = new Set<string>();\n const methodBodies: Array<[string, SyntaxNode]> = [];\n\n function addNode(nid: string, label: string, line: number): void {\n if (!seenIds.has(nid)) {\n seenIds.add(nid);\n nodes.push({ id: nid, label, file_type: \"code\", source_file: strPath, source_location: `L${line}` });\n }\n }\n\n function addEdge(\n src: string, tgt: string, relation: string, line: number,\n confidence: \"EXTRACTED\" | \"INFERRED\" = \"EXTRACTED\", weight: number = 1.0,\n ): void {\n edges.push({ source: src, target: tgt, relation, confidence, source_file: strPath, source_location: `L${line}`, weight });\n }\n\n const fileNid = _makeId(stem);\n addNode(fileNid, basename(filePath), 1);\n\n function _read(node: SyntaxNode): string {\n return source.slice(node.startIndex, node.endIndex);\n }\n\n function walk(node: SyntaxNode, parentNid: string | null = null): void {\n const t = node.type;\n const line = node.startPosition.row + 1;\n\n if (t === \"preproc_include\") {\n for (const child of node.children) {\n if (child.type === \"system_lib_string\") {\n const raw = _read(child).replace(/^[<>]+|[<>]+$/g, \"\");\n const module = raw.split(\"/\").pop()!.replace(\".h\", \"\");\n if (module) {\n const tgtNid = _makeId(module);\n addEdge(fileNid, tgtNid, \"imports\", line);\n }\n } else if (child.type === \"string_literal\") {\n for (const sub of child.children) {\n if (sub.type === \"string_content\") {\n const raw = _read(sub);\n const module = raw.split(\"/\").pop()!.replace(\".h\", \"\");\n if (module) {\n const tgtNid = _makeId(module);\n addEdge(fileNid, tgtNid, \"imports\", line);\n }\n }\n }\n }\n }\n return;\n }\n\n if (t === \"class_interface\") {\n const identifiers = node.children.filter((c) => c.type === \"identifier\");\n if (identifiers.length === 0) {\n for (const child of node.children) walk(child, parentNid);\n return;\n }\n const name = _read(identifiers[0]!);\n const clsNid = _makeId(stem, name);\n addNode(clsNid, name, line);\n addEdge(fileNid, clsNid, \"contains\", line);\n // superclass is second identifier after ':'\n let colonSeen = false;\n for (const child of node.children) {\n if (child.type === \":\") {\n colonSeen = true;\n } else if (colonSeen && child.type === \"identifier\") {\n const superNid = _makeId(_read(child));\n addEdge(clsNid, superNid, \"inherits\", line);\n colonSeen = false;\n } else if (child.type === \"parameterized_arguments\") {\n for (const sub of child.children) {\n if (sub.type === \"type_name\") {\n for (const s of sub.children) {\n if (s.type === \"type_identifier\") {\n const protoNid = _makeId(_read(s));\n addEdge(clsNid, protoNid, \"imports\", line);\n }\n }\n }\n }\n } else if (child.type === \"method_declaration\") {\n walk(child, clsNid);\n }\n }\n return;\n }\n\n if (t === \"class_implementation\") {\n let name: string | null = null;\n for (const child of node.children) {\n if (child.type === \"identifier\") { name = _read(child); break; }\n }\n if (!name) {\n for (const child of node.children) walk(child, parentNid);\n return;\n }\n const implNid = _makeId(stem, name);\n if (!seenIds.has(implNid)) {\n addNode(implNid, name, line);\n addEdge(fileNid, implNid, \"contains\", line);\n }\n for (const child of node.children) {\n if (child.type === \"implementation_definition\") {\n for (const sub of child.children) walk(sub, implNid);\n }\n }\n return;\n }\n\n if (t === \"protocol_declaration\") {\n let name: string | null = null;\n for (const child of node.children) {\n if (child.type === \"identifier\") { name = _read(child); break; }\n }\n if (name) {\n const protoNid = _makeId(stem, name);\n addNode(protoNid, `<${name}>`, line);\n addEdge(fileNid, protoNid, \"contains\", line);\n for (const child of node.children) walk(child, protoNid);\n }\n return;\n }\n\n if (t === \"method_declaration\" || t === \"method_definition\") {\n const container = parentNid || fileNid;\n const parts: string[] = [];\n for (const child of node.children) {\n if (child.type === \"identifier\") {\n parts.push(_read(child));\n }\n }\n const methodName = parts.join(\"\") || null;\n if (methodName) {\n const methodNid = _makeId(container, methodName);\n addNode(methodNid, `-${methodName}`, line);\n addEdge(container, methodNid, \"method\", line);\n if (t === \"method_definition\") {\n methodBodies.push([methodNid, node]);\n }\n }\n return;\n }\n\n for (const child of node.children) {\n walk(child, parentNid);\n }\n }\n\n walk(root);\n\n // Second pass: resolve calls inside method bodies\n const allMethodNids = new Set(nodes.filter((n) => n.id !== fileNid).map((n) => n.id));\n const seenCalls = new Set<string>();\n\n for (const [callerNid, bodyNode] of methodBodies) {\n function objcWalkCalls(n: SyntaxNode): void {\n if (n.type === \"message_expression\") {\n for (const child of n.children) {\n if (child.type === \"selector\" || child.type === \"keyword_argument_list\") {\n const sel: string[] = [];\n if (child.type === \"selector\") {\n sel.push(_read(child));\n } else {\n for (const sub of child.children) {\n if (sub.type === \"keyword_argument\") {\n for (const s of sub.children) {\n if (s.type === \"selector\") sel.push(_read(s));\n }\n }\n }\n }\n const methodName = sel.join(\"\");\n for (const candidate of allMethodNids) {\n if (candidate.endsWith(_makeId(\"\", methodName).replace(/^_/, \"\"))) {\n const pair = `${callerNid}|${candidate}`;\n if (!seenCalls.has(pair) && callerNid !== candidate) {\n seenCalls.add(pair);\n addEdge(callerNid, candidate, \"calls\", bodyNode.startPosition.row + 1, \"INFERRED\", 0.8);\n }\n }\n }\n }\n }\n }\n for (const child of n.children) {\n objcWalkCalls(child);\n }\n }\n objcWalkCalls(bodyNode);\n }\n\n return { nodes, edges, error: undefined };\n}\n\n// ---------------------------------------------------------------------------\n// Elixir extractor (custom walk)\n// ---------------------------------------------------------------------------\n\nexport async function extractElixir(filePath: string): Promise<ExtractionResult> {\n await ensureParserInit();\n const lang = await loadLanguage(\"elixir\");\n if (!lang) {\n return { nodes: [], edges: [], error: \"tree-sitter-elixir not available\" };\n }\n\n let source: string;\n let tree: Tree;\n try {\n const parser = new Parser();\n parser.setLanguage(lang);\n source = readFileSync(filePath, \"utf-8\");\n tree = parseText(parser, source);\n } catch (e: unknown) {\n return { nodes: [], edges: [], error: String(e) };\n }\n\n const root = tree.rootNode;\n const stem = basename(filePath, extname(filePath));\n const strPath = filePath;\n const nodes: GraphNode[] = [];\n const edges: GraphEdge[] = [];\n const seenIds = new Set<string>();\n const functionBodies: Array<[string, SyntaxNode]> = [];\n\n function addNode(nid: string, label: string, line: number): void {\n if (!seenIds.has(nid)) {\n seenIds.add(nid);\n nodes.push({ id: nid, label, file_type: \"code\", source_file: strPath, source_location: `L${line}` });\n }\n }\n\n function addEdge(\n src: string, tgt: string, relation: string, line: number,\n confidence: \"EXTRACTED\" | \"INFERRED\" = \"EXTRACTED\", weight: number = 1.0,\n ): void {\n edges.push({ source: src, target: tgt, relation, confidence, source_file: strPath, source_location: `L${line}`, weight });\n }\n\n const fileNid = _makeId(stem);\n addNode(fileNid, basename(filePath), 1);\n\n const _IMPORT_KEYWORDS = new Set([\"alias\", \"import\", \"require\", \"use\"]);\n\n function getAliasText(node: SyntaxNode): string | null {\n for (const child of node.children) {\n if (child.type === \"alias\") {\n return source.slice(child.startIndex, child.endIndex);\n }\n }\n return null;\n }\n\n function walk(node: SyntaxNode, parentModuleNid: string | null = null): void {\n if (node.type !== \"call\") {\n for (const child of node.children) walk(child, parentModuleNid);\n return;\n }\n\n let identifierNode: SyntaxNode | null = null;\n let argumentsNode: SyntaxNode | null = null;\n let doBlockNode: SyntaxNode | null = null;\n for (const child of node.children) {\n if (child.type === \"identifier\") identifierNode = child;\n else if (child.type === \"arguments\") argumentsNode = child;\n else if (child.type === \"do_block\") doBlockNode = child;\n }\n\n if (!identifierNode) {\n for (const child of node.children) walk(child, parentModuleNid);\n return;\n }\n\n const keyword = source.slice(identifierNode.startIndex, identifierNode.endIndex);\n const line = node.startPosition.row + 1;\n\n if (keyword === \"defmodule\") {\n const moduleName = argumentsNode ? getAliasText(argumentsNode) : null;\n if (!moduleName) return;\n const moduleNid = _makeId(stem, moduleName);\n addNode(moduleNid, moduleName, line);\n addEdge(fileNid, moduleNid, \"contains\", line);\n if (doBlockNode) {\n for (const child of doBlockNode.children) walk(child, moduleNid);\n }\n return;\n }\n\n if (keyword === \"def\" || keyword === \"defp\") {\n let funcName: string | null = null;\n if (argumentsNode) {\n for (const child of argumentsNode.children) {\n if (child.type === \"call\") {\n for (const sub of child.children) {\n if (sub.type === \"identifier\") {\n funcName = source.slice(sub.startIndex, sub.endIndex);\n break;\n }\n }\n } else if (child.type === \"identifier\") {\n funcName = source.slice(child.startIndex, child.endIndex);\n break;\n }\n }\n }\n if (!funcName) return;\n const container = parentModuleNid || fileNid;\n const funcNid = _makeId(container, funcName);\n addNode(funcNid, `${funcName}()`, line);\n if (parentModuleNid) {\n addEdge(parentModuleNid, funcNid, \"method\", line);\n } else {\n addEdge(fileNid, funcNid, \"contains\", line);\n }\n if (doBlockNode) {\n functionBodies.push([funcNid, doBlockNode]);\n }\n return;\n }\n\n if (_IMPORT_KEYWORDS.has(keyword) && argumentsNode) {\n const moduleName = getAliasText(argumentsNode);\n if (moduleName) {\n const tgtNid = _makeId(moduleName);\n addEdge(fileNid, tgtNid, \"imports\", line);\n }\n return;\n }\n\n for (const child of node.children) walk(child, parentModuleNid);\n }\n\n walk(root);\n\n // Call-graph pass\n const labelToNid = new Map<string, string>();\n for (const n of nodes) {\n const normalised = n.label.replace(/\\(?\\)$/g, \"\").replace(/^\\./, \"\");\n labelToNid.set(normalised.toLowerCase(), n.id);\n }\n\n const seenCallPairs = new Set<string>();\n const _SKIP_KEYWORDS = new Set([\n \"def\", \"defp\", \"defmodule\", \"defmacro\", \"defmacrop\",\n \"defstruct\", \"defprotocol\", \"defimpl\", \"defguard\",\n \"alias\", \"import\", \"require\", \"use\",\n \"if\", \"unless\", \"case\", \"cond\", \"with\", \"for\",\n ]);\n\n function walkCalls(node: SyntaxNode, callerNid: string): void {\n if (node.type !== \"call\") {\n for (const child of node.children) walkCalls(child, callerNid);\n return;\n }\n for (const child of node.children) {\n if (child.type === \"identifier\") {\n const kw = source.slice(child.startIndex, child.endIndex);\n if (_SKIP_KEYWORDS.has(kw)) {\n for (const c of node.children) walkCalls(c, callerNid);\n return;\n }\n break;\n }\n }\n let calleeName: string | null = null;\n for (const child of node.children) {\n if (child.type === \"dot\") {\n const dotText = source.slice(child.startIndex, child.endIndex);\n const parts = dotText.replace(/\\.$/, \"\").split(\".\");\n if (parts.length > 0) calleeName = parts[parts.length - 1]!;\n break;\n }\n if (child.type === \"identifier\") {\n calleeName = source.slice(child.startIndex, child.endIndex);\n break;\n }\n }\n if (calleeName) {\n const tgtNid = labelToNid.get(calleeName.toLowerCase());\n if (tgtNid && tgtNid !== callerNid) {\n const pair = `${callerNid}|${tgtNid}`;\n if (!seenCallPairs.has(pair)) {\n seenCallPairs.add(pair);\n addEdge(callerNid, tgtNid, \"calls\", node.startPosition.row + 1, \"INFERRED\", 0.8);\n }\n }\n }\n for (const child of node.children) {\n walkCalls(child, callerNid);\n }\n }\n\n for (const [callerNid, body] of functionBodies) {\n walkCalls(body, callerNid);\n }\n\n const cleanEdges = edges.filter((e) =>\n seenIds.has(e.source) && (seenIds.has(e.target) || e.relation === \"imports\"),\n );\n\n return { nodes, edges: cleanEdges, error: undefined };\n}\n\n// ---------------------------------------------------------------------------\n// Cross-file import resolution (Python only)\n// ---------------------------------------------------------------------------\n\nasync function _resolveCrossFileImports(\n perFile: ExtractionResult[],\n paths: string[],\n): Promise<GraphEdge[]> {\n await ensureParserInit();\n const lang = await loadLanguage(\"python\");\n if (!lang) return [];\n\n const parser = new Parser();\n parser.setLanguage(lang);\n\n // Pass 1: name -> node_id across all files\n const stemToEntities = new Map<string, Map<string, string>>();\n for (const fileResult of perFile) {\n for (const node of fileResult.nodes ?? []) {\n const src = node.source_file ?? \"\";\n if (!src) continue;\n const fileStem = basename(src, extname(src));\n const label = node.label ?? \"\";\n const nid = node.id ?? \"\";\n if (label && !label.endsWith(\")\") && !label.endsWith(\".py\") && !label.startsWith(\"_\")) {\n if (!stemToEntities.has(fileStem)) stemToEntities.set(fileStem, new Map());\n stemToEntities.get(fileStem)!.set(label, nid);\n }\n }\n }\n\n // Pass 2\n const newEdges: GraphEdge[] = [];\n const stemToPath = new Map<string, string>();\n for (const p of paths) {\n stemToPath.set(basename(p, extname(p)), p);\n }\n\n for (let idx = 0; idx < perFile.length; idx++) {\n const fileResult = perFile[idx]!;\n const filePath = paths[idx]!;\n const fileStem = basename(filePath, extname(filePath));\n const strPath = filePath;\n\n const localClasses = fileResult.nodes\n .filter((n) =>\n n.source_file === strPath &&\n !n.label.endsWith(\")\") &&\n !n.label.endsWith(\".py\") &&\n n.id !== _makeId(fileStem),\n )\n .map((n) => n.id);\n\n if (localClasses.length === 0) continue;\n\n let source: string;\n let tree: Tree;\n try {\n source = readFileSync(filePath, \"utf-8\");\n tree = parseText(parser, source);\n } catch {\n continue;\n }\n\n function walkImports(node: SyntaxNode): void {\n if (node.type === \"import_from_statement\") {\n let targetStem: string | null = null;\n for (const child of node.children) {\n if (child.type === \"relative_import\") {\n for (const sub of child.children) {\n if (sub.type === \"dotted_name\") {\n const raw = source.slice(sub.startIndex, sub.endIndex);\n targetStem = raw.split(\".\").pop()!;\n break;\n }\n }\n break;\n }\n if (child.type === \"dotted_name\" && targetStem === null) {\n const raw = source.slice(child.startIndex, child.endIndex);\n targetStem = raw.split(\".\").pop()!;\n }\n }\n\n if (!targetStem || !stemToEntities.has(targetStem)) return;\n\n const importedNames: string[] = [];\n let pastImportKw = false;\n for (const child of node.children) {\n if (child.type === \"import\") {\n pastImportKw = true;\n continue;\n }\n if (!pastImportKw) continue;\n if (child.type === \"dotted_name\") {\n importedNames.push(source.slice(child.startIndex, child.endIndex));\n } else if (child.type === \"aliased_import\") {\n const nameNode = child.childForFieldName(\"name\");\n if (nameNode) {\n importedNames.push(source.slice(nameNode.startIndex, nameNode.endIndex));\n }\n }\n }\n\n const line = node.startPosition.row + 1;\n for (const name of importedNames) {\n const tgtNid = stemToEntities.get(targetStem)?.get(name);\n if (tgtNid) {\n for (const srcClassNid of localClasses) {\n newEdges.push({\n source: srcClassNid, target: tgtNid, relation: \"uses\",\n confidence: \"INFERRED\", source_file: strPath,\n source_location: `L${line}`, weight: 0.8,\n });\n }\n }\n }\n }\n for (const child of node.children) {\n walkImports(child);\n }\n }\n\n walkImports(tree.rootNode);\n }\n\n return newEdges;\n}\n\n// ---------------------------------------------------------------------------\n// Main extract() and collectFiles()\n// ---------------------------------------------------------------------------\n\ntype ExtractorFn = (filePath: string) => Promise<ExtractionResult>;\n\nconst _DISPATCH: Record<string, ExtractorFn> = {\n \".py\": extractPython,\n \".js\": extractJs,\n \".jsx\": extractJs,\n \".ts\": extractJs,\n \".tsx\": extractJs,\n \".go\": extractGo,\n \".rs\": extractRust,\n \".java\": extractJava,\n \".c\": extractC,\n \".h\": extractC,\n \".cpp\": extractCpp,\n \".cc\": extractCpp,\n \".cxx\": extractCpp,\n \".hpp\": extractCpp,\n \".rb\": extractRuby,\n \".cs\": extractCsharp,\n \".kt\": extractKotlin,\n \".kts\": extractKotlin,\n \".scala\": extractScala,\n \".php\": extractPhp,\n \".swift\": extractSwift,\n \".lua\": extractLua,\n \".toc\": extractLua,\n \".zig\": extractZig,\n \".ps1\": extractPowershell,\n \".ex\": extractElixir,\n \".exs\": extractElixir,\n \".m\": extractObjc,\n \".mm\": extractObjc,\n \".jl\": extractJulia,\n};\n\n/**\n * Extract AST nodes and edges from a list of code files.\n *\n * Two-pass process:\n * 1. Per-file structural extraction (classes, functions, imports)\n * 2. Cross-file import resolution: turns file-level imports into\n * class-level INFERRED edges (DigestAuth --uses--> Response)\n */\nexport interface ExtractionDiagnostic {\n filePath: string;\n error: string;\n}\n\nexport interface ExtractWithDiagnosticsResult {\n extraction: Extraction;\n diagnostics: ExtractionDiagnostic[];\n}\n\nexport async function extractWithDiagnostics(paths: string[]): Promise<ExtractWithDiagnosticsResult> {\n const perFile: ExtractionResult[] = [];\n const diagnostics: ExtractionDiagnostic[] = [];\n\n // Infer a common root for cache keys\n let root = \".\";\n try {\n if (paths.length === 0) {\n root = \".\";\n } else if (paths.length === 1) {\n root = dirname(paths[0]!);\n } else {\n // Find common prefix directory\n const parts = paths.map((p) => p.split(sep));\n const minLen = Math.min(...parts.map((p) => p.length));\n let commonLen = 0;\n for (let i = 0; i < minLen; i++) {\n const uniqueAtLevel = new Set(parts.map((p) => p[i]));\n if (uniqueAtLevel.size === 1) commonLen++;\n else break;\n }\n root = commonLen > 0 ? parts[0]!.slice(0, commonLen).join(sep) : \".\";\n }\n } catch {\n root = \".\";\n }\n\n const total = paths.length;\n const _PROGRESS_INTERVAL = 100;\n\n for (let i = 0; i < paths.length; i++) {\n if (total >= _PROGRESS_INTERVAL && i % _PROGRESS_INTERVAL === 0 && i > 0) {\n process.stderr.write(` AST extraction: ${i}/${total} files (${Math.floor(i * 100 / total)}%)\\n`);\n }\n const filePath = paths[i]!;\n const ext = extname(filePath);\n const extractor = _DISPATCH[ext];\n if (!extractor) continue;\n\n const cached = loadCached(filePath, root);\n if (cached !== null) {\n perFile.push(cached as unknown as ExtractionResult);\n continue;\n }\n\n const result = await extractor(filePath);\n if (!result.error) {\n saveCached(filePath, result as unknown as Record<string, unknown>, root);\n } else {\n diagnostics.push({ filePath, error: result.error });\n }\n perFile.push(result);\n }\n\n if (total >= _PROGRESS_INTERVAL) {\n process.stderr.write(` AST extraction: ${total}/${total} files (100%)\\n`);\n }\n\n const allNodes: GraphNode[] = [];\n const allEdges: GraphEdge[] = [];\n for (const result of perFile) {\n allNodes.push(...(result.nodes ?? []));\n allEdges.push(...(result.edges ?? []));\n }\n\n // Add cross-file class-level edges (Python only)\n const pyPaths = paths.filter((p) => extname(p) === \".py\");\n if (pyPaths.length > 0) {\n const pyResults = perFile.filter((_r, i) => extname(paths[i]!) === \".py\");\n try {\n const crossFileEdges = await _resolveCrossFileImports(pyResults, pyPaths);\n allEdges.push(...crossFileEdges);\n } catch {\n // Cross-file import resolution failed, skipping\n }\n }\n\n return {\n extraction: {\n nodes: allNodes,\n edges: allEdges,\n input_tokens: 0,\n output_tokens: 0,\n },\n diagnostics,\n };\n}\n\nexport async function extract(paths: string[]): Promise<Extraction> {\n const { extraction } = await extractWithDiagnostics(paths);\n return extraction;\n}\n\n// ---------------------------------------------------------------------------\n// collectFiles\n// ---------------------------------------------------------------------------\n\nconst _EXTENSIONS = new Set([\n \".py\", \".js\", \".ts\", \".tsx\", \".go\", \".rs\",\n \".java\", \".c\", \".h\", \".cpp\", \".cc\", \".cxx\", \".hpp\",\n \".rb\", \".cs\", \".kt\", \".kts\", \".scala\", \".php\", \".swift\",\n \".lua\", \".toc\", \".zig\", \".ps1\",\n \".m\", \".mm\",\n \".jl\", \".jsx\", \".ex\", \".exs\",\n]);\n\n/**\n * Walk a directory (or return a single file) and collect code files by\n * supported extension.\n */\nexport function collectFiles(target: string, options?: { followSymlinks?: boolean }): string[] {\n const followSymlinks = options?.followSymlinks ?? false;\n const resolved = resolve(target);\n\n try {\n const stat = lstatSync(resolved);\n if (stat.isFile()) return [resolved];\n } catch {\n return [];\n }\n\n const results: string[] = [];\n\n function walkDir(dir: string, visited: Set<string>): void {\n let entries: string[];\n try {\n entries = readdirSync(dir);\n } catch {\n return;\n }\n\n for (const entry of entries) {\n if (entry.startsWith(\".\")) continue;\n const fullPath = join(dir, entry);\n\n let stat;\n try {\n stat = lstatSync(fullPath);\n } catch {\n continue;\n }\n\n if (stat.isSymbolicLink() && !followSymlinks) continue;\n\n if (stat.isDirectory() || (stat.isSymbolicLink() && followSymlinks)) {\n // Cycle detection for symlinks\n if (stat.isSymbolicLink()) {\n try {\n const real = realpathSync(fullPath);\n if (visited.has(real)) continue;\n visited.add(real);\n const parentReal = realpathSync(dirname(fullPath));\n if (parentReal === real || parentReal.startsWith(real + sep)) continue;\n } catch {\n continue;\n }\n }\n\n // Skip hidden directories\n const pathParts = fullPath.split(sep);\n if (pathParts.some((part) => part.startsWith(\".\"))) continue;\n\n walkDir(fullPath, visited);\n } else if (stat.isFile()) {\n const ext = extname(entry);\n if (_EXTENSIONS.has(ext)) {\n results.push(fullPath);\n }\n }\n }\n }\n\n walkDir(resolved, new Set<string>());\n return results.sort();\n}\n","/**\n * URL ingestion - fetch URLs (tweet/arxiv/pdf/web/image) and save as annotated markdown.\n *\n * Uses Node.js global fetch, turndown for HTML-to-markdown conversion, and\n * security helpers for safe fetching and URL validation.\n */\nimport { existsSync, mkdirSync, writeFileSync } from \"node:fs\";\nimport { resolve as pathResolve, basename, extname } from \"node:path\";\nimport { safeFetch, safeFetchText, validateUrl } from \"./security.js\";\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction yamlStr(s: string): string {\n return s\n .replace(/\\\\/g, \"\\\\\\\\\")\n .replace(/\"/g, '\\\\\"')\n .replace(/\\n/g, \" \")\n .replace(/\\r/g, \" \");\n}\n\nfunction safeFilename(url: string, suffix: string): string {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n return `unknown${suffix}`;\n }\n let name = parsed.hostname + parsed.pathname;\n name = name.replace(/[^\\w\\-]/g, \"_\").replace(/^_+|_+$/g, \"\");\n name = name.replace(/_+/g, \"_\").slice(0, 80);\n return name + suffix;\n}\n\nfunction detectUrlType(url: string): string {\n const lower = url.toLowerCase();\n if (lower.includes(\"twitter.com\") || lower.includes(\"x.com\")) return \"tweet\";\n if (lower.includes(\"arxiv.org\")) return \"arxiv\";\n if (lower.includes(\"github.com\")) return \"github\";\n if (lower.includes(\"youtube.com\") || lower.includes(\"youtu.be\"))\n return \"youtube\";\n try {\n const parsed = new URL(url);\n const path = parsed.pathname.toLowerCase();\n if (path.endsWith(\".pdf\")) return \"pdf\";\n if (\n [\".png\", \".jpg\", \".jpeg\", \".webp\", \".gif\"].some((ext) =>\n path.endsWith(ext),\n )\n )\n return \"image\";\n } catch {\n // fall through\n }\n return \"webpage\";\n}\n\nasync function htmlToMarkdown(html: string, _url: string): Promise<string> {\n try {\n const TurndownService = (await import(\"turndown\")).default;\n const td = new TurndownService({\n headingStyle: \"atx\",\n codeBlockStyle: \"fenced\",\n });\n return td.turndown(html);\n } catch {\n // Fallback: strip tags\n let text = html.replace(/<script[^>]*>.*?<\\/script>/gis, \"\");\n text = text.replace(/<style[^>]*>.*?<\\/style>/gis, \"\");\n text = text.replace(/<[^>]+>/g, \" \");\n text = text.replace(/\\s+/g, \" \").trim();\n return text.slice(0, 8000);\n }\n}\n\n// ---------------------------------------------------------------------------\n// URL type handlers\n// ---------------------------------------------------------------------------\n\nasync function fetchTweet(\n url: string,\n author: string | null,\n contributor: string | null,\n): Promise<[string, string]> {\n const oembedUrl = url.replace(\"x.com\", \"twitter.com\");\n const oembedApi = `https://publish.twitter.com/oembed?url=${encodeURIComponent(oembedUrl)}&omit_script=true`;\n\n let tweetText: string;\n let tweetAuthor: string;\n try {\n const data = JSON.parse(await safeFetchText(oembedApi)) as Record<\n string,\n unknown\n >;\n tweetText = ((data.html as string) ?? \"\")\n .replace(/<[^>]+>/g, \"\")\n .trim();\n tweetAuthor = (data.author_name as string) ?? \"unknown\";\n } catch {\n tweetText = `Tweet at ${url} (could not fetch content)`;\n tweetAuthor = \"unknown\";\n }\n\n const now = new Date().toISOString();\n const content = `---\nsource_url: ${url}\ntype: tweet\nauthor: ${tweetAuthor}\ncaptured_at: ${now}\ncontributor: ${contributor ?? author ?? \"unknown\"}\n---\n\n# Tweet by @${tweetAuthor}\n\n${tweetText}\n\nSource: ${url}\n`;\n const filename = safeFilename(url, \".md\");\n return [content, filename];\n}\n\nasync function fetchWebpage(\n url: string,\n author: string | null,\n contributor: string | null,\n): Promise<[string, string]> {\n const html = await safeFetchText(url);\n\n const titleMatch = html.match(/<title[^>]*>(.*?)<\\/title>/is);\n const title = titleMatch\n ? titleMatch[1]!.replace(/\\s+/g, \" \").trim()\n : url;\n\n const markdown = await htmlToMarkdown(html, url);\n const now = new Date().toISOString();\n const content = `---\nsource_url: ${url}\ntype: webpage\ntitle: \"${yamlStr(title)}\"\ncaptured_at: ${now}\ncontributor: ${contributor ?? author ?? \"unknown\"}\n---\n\n# ${title}\n\nSource: ${url}\n\n---\n\n${markdown.slice(0, 12000)}\n`;\n const filename = safeFilename(url, \".md\");\n return [content, filename];\n}\n\nasync function fetchArxiv(\n url: string,\n author: string | null,\n contributor: string | null,\n): Promise<[string, string]> {\n const arxivMatch = url.match(/(\\d{4}\\.\\d{4,5})/);\n if (!arxivMatch) {\n return fetchWebpage(url, author, contributor);\n }\n\n const arxivId = arxivMatch[1]!;\n let title = arxivId;\n let abstract = \"\";\n let paperAuthors = \"\";\n\n const apiUrl = `https://export.arxiv.org/abs/${arxivId}`;\n try {\n const html = await safeFetchText(apiUrl);\n const abstractMatch = html.match(\n /class=\"abstract[^\"]*\"[^>]*>(.*?)<\\/blockquote>/is,\n );\n if (abstractMatch) {\n abstract = abstractMatch[1]!.replace(/<[^>]+>/g, \"\").trim();\n }\n const titleMatch = html.match(\n /class=\"title[^\"]*\"[^>]*>(.*?)<\\/h1>/is,\n );\n if (titleMatch) {\n title = titleMatch[1]!.replace(/<[^>]+>/g, \" \").trim();\n }\n const authorsMatch = html.match(\n /class=\"authors\"[^>]*>(.*?)<\\/div>/is,\n );\n if (authorsMatch) {\n paperAuthors = authorsMatch[1]!.replace(/<[^>]+>/g, \"\").trim();\n }\n } catch {\n // Use defaults set above\n }\n\n const now = new Date().toISOString();\n const content = `---\nsource_url: ${url}\narxiv_id: ${arxivId}\ntype: paper\ntitle: \"${title}\"\npaper_authors: \"${paperAuthors}\"\ncaptured_at: ${now}\ncontributor: ${contributor ?? author ?? \"unknown\"}\n---\n\n# ${title}\n\n**Authors:** ${paperAuthors}\n**arXiv:** ${arxivId}\n\n## Abstract\n\n${abstract}\n\nSource: ${url}\n`;\n const filename = `arxiv_${arxivId.replace(\".\", \"_\")}.md`;\n return [content, filename];\n}\n\nasync function downloadBinary(\n url: string,\n suffix: string,\n targetDir: string,\n): Promise<string> {\n const filename = safeFilename(url, suffix);\n const outPath = pathResolve(targetDir, filename);\n const data = await safeFetch(url);\n writeFileSync(outPath, data);\n return outPath;\n}\n\ninterface IngestOptions {\n author?: string | null;\n contributor?: string | null;\n}\n\nfunction normalizeIngestOptions(\n authorOrOptions: string | IngestOptions | null | undefined,\n contributor: string | null | undefined,\n): { author: string | null; contributor: string | null } {\n if (typeof authorOrOptions === \"string\" || authorOrOptions == null) {\n return {\n author: authorOrOptions ?? null,\n contributor: contributor ?? null,\n };\n }\n\n return {\n author: authorOrOptions.author ?? null,\n contributor: authorOrOptions.contributor ?? null,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Main ingest function\n// ---------------------------------------------------------------------------\n\nexport async function ingest(\n url: string,\n targetDir: string,\n authorOrOptions: string | IngestOptions | null = null,\n contributor: string | null = null,\n): Promise<string> {\n mkdirSync(targetDir, { recursive: true });\n const urlType = detectUrlType(url);\n const { author, contributor: normalizedContributor } = normalizeIngestOptions(\n authorOrOptions,\n contributor,\n );\n\n await validateUrl(url);\n\n let content: string;\n let filename: string;\n\n if (urlType === \"pdf\") {\n const out = await downloadBinary(url, \".pdf\", targetDir);\n console.log(`Downloaded PDF: ${basename(out)}`);\n return out;\n }\n\n if (urlType === \"image\") {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n throw new Error(`Invalid URL: ${url}`);\n }\n const suffix = extname(parsed.pathname) || \".jpg\";\n const out = await downloadBinary(url, suffix, targetDir);\n console.log(`Downloaded image: ${basename(out)}`);\n return out;\n }\n\n if (urlType === \"tweet\") {\n [content, filename] = await fetchTweet(url, author, normalizedContributor);\n } else if (urlType === \"arxiv\") {\n [content, filename] = await fetchArxiv(url, author, normalizedContributor);\n } else {\n [content, filename] = await fetchWebpage(url, author, normalizedContributor);\n }\n\n let outPath = pathResolve(targetDir, filename);\n let counter = 1;\n while (existsSync(outPath)) {\n const stem = filename.replace(/\\.md$/, \"\");\n outPath = pathResolve(targetDir, `${stem}_${counter}.md`);\n counter++;\n }\n\n writeFileSync(outPath, content, \"utf-8\");\n console.log(`Saved ${urlType}: ${basename(outPath)}`);\n return outPath;\n}\n\n// ---------------------------------------------------------------------------\n// Save query result (memory loop)\n// ---------------------------------------------------------------------------\n\nexport function saveQueryResult(\n questionOrOptions:\n | string\n | {\n question: string;\n answer: string;\n memoryDir: string;\n queryType?: string;\n sourceNodes?: string[] | null;\n },\n answer?: string,\n memoryDir?: string,\n queryType: string = \"query\",\n sourceNodes: string[] | null = null,\n): string {\n const payload = typeof questionOrOptions === \"string\"\n ? {\n question: questionOrOptions,\n answer: answer ?? \"\",\n memoryDir: memoryDir ?? \"\",\n queryType,\n sourceNodes,\n }\n : {\n question: questionOrOptions.question,\n answer: questionOrOptions.answer,\n memoryDir: questionOrOptions.memoryDir,\n queryType: questionOrOptions.queryType ?? \"query\",\n sourceNodes: questionOrOptions.sourceNodes ?? null,\n };\n\n if (!payload.question) throw new Error(\"saveQueryResult requires a question\");\n if (!payload.memoryDir) throw new Error(\"saveQueryResult requires a memoryDir\");\n\n const effectiveAnswer = payload.answer ?? \"\";\n mkdirSync(payload.memoryDir, { recursive: true });\n\n const now = new Date();\n const slug = payload.question\n .toLowerCase()\n .replace(/[^\\w]/g, \"_\")\n .slice(0, 50)\n .replace(/_+$/, \"\");\n const ts = now\n .toISOString()\n .replace(/[-:]/g, \"\")\n .replace(\"T\", \"_\")\n .slice(0, 15);\n const filename = `query_${ts}_${slug}.md`;\n\n const frontmatterLines = [\n \"---\",\n `type: \"${payload.queryType}\"`,\n `date: \"${now.toISOString()}\"`,\n `question: \"${yamlStr(payload.question)}\"`,\n 'contributor: \"graphify\"',\n ];\n if (payload.sourceNodes && payload.sourceNodes.length > 0) {\n const nodesStr = payload.sourceNodes\n .slice(0, 10)\n .map((n) => `\"${n}\"`)\n .join(\", \");\n frontmatterLines.push(`source_nodes: [${nodesStr}]`);\n }\n frontmatterLines.push(\"---\");\n\n const bodyLines = [\n \"\",\n `# Q: ${payload.question}`,\n \"\",\n \"## Answer\",\n \"\",\n effectiveAnswer,\n ];\n if (payload.sourceNodes && payload.sourceNodes.length > 0) {\n bodyLines.push(\"\", \"## Source Nodes\", \"\");\n for (const n of payload.sourceNodes) {\n bodyLines.push(`- ${n}`);\n }\n }\n\n const content = [...frontmatterLines, ...bodyLines].join(\"\\n\");\n const outPath = pathResolve(payload.memoryDir, filename);\n writeFileSync(outPath, content, \"utf-8\");\n return outPath;\n}\n\n// ---------------------------------------------------------------------------\n// CLI entry point\n// ---------------------------------------------------------------------------\n\nconst isDirectExecution = typeof process !== \"undefined\" &&\n typeof process.argv[1] === \"string\" &&\n /^ingest\\.(?:js|mjs|cjs|ts)$/.test(basename(process.argv[1]));\n\nif (isDirectExecution) {\n const url = process.argv[2];\n const targetDir = process.argv[3] ?? \"./raw\";\n const author = process.argv[4] ?? null;\n if (!url) {\n console.error(\"Usage: ingest <url> [target_dir] [author]\");\n process.exit(1);\n }\n ingest(url, targetDir, author)\n .then((out) => console.log(`Ready for graphify: ${out}`))\n .catch((err) => {\n console.error(err);\n process.exit(1);\n });\n}\n","/**\n * Generate GRAPH_REPORT.md - the human-readable audit trail.\n */\nimport Graph from \"graphology\";\nimport type { GodNodeEntry, SurpriseEntry, SuggestedQuestion, DetectionResult } from \"./types.js\";\nimport { type NumericMapLike, toNumericMap } from \"./collections.js\";\nimport { isFileNode, isConceptNode } from \"./analyze.js\";\n\nexport function generate(\n G: Graph,\n communities: NumericMapLike<string[]>,\n cohesionScores: NumericMapLike<number>,\n communityLabels: NumericMapLike<string>,\n godNodeList: GodNodeEntry[],\n surpriseList: SurpriseEntry[],\n detectionResult: DetectionResult,\n tokenCost: { input: number; output: number },\n root: string,\n suggestedQuestions?:\n | SuggestedQuestion[]\n | { suggestedQuestions?: SuggestedQuestion[] | null }\n | null,\n): string {\n const communityMap = toNumericMap(communities);\n const cohesionMap = toNumericMap(cohesionScores);\n const labelMap = toNumericMap(communityLabels);\n const suggestedQuestionList = Array.isArray(suggestedQuestions)\n ? suggestedQuestions\n : (suggestedQuestions?.suggestedQuestions ?? null);\n const today = new Date().toISOString().slice(0, 10);\n\n const confidences: string[] = [];\n G.forEachEdge((_, data) => {\n confidences.push((data.confidence as string) ?? \"EXTRACTED\");\n });\n const total = confidences.length || 1;\n const extPct = Math.round((confidences.filter((c) => c === \"EXTRACTED\").length / total) * 100);\n const infPct = Math.round((confidences.filter((c) => c === \"INFERRED\").length / total) * 100);\n const ambPct = Math.round((confidences.filter((c) => c === \"AMBIGUOUS\").length / total) * 100);\n\n const infEdges: { score: number }[] = [];\n G.forEachEdge((_, data) => {\n if (data.confidence === \"INFERRED\") {\n infEdges.push({ score: (data.confidence_score as number) ?? 0.5 });\n }\n });\n const infAvg = infEdges.length > 0\n ? Math.round((infEdges.reduce((s, e) => s + e.score, 0) / infEdges.length) * 100) / 100\n : null;\n\n const lines: string[] = [\n `# Graph Report - ${root} (${today})`,\n \"\",\n \"## Corpus Check\",\n ];\n\n if (detectionResult.warning) {\n lines.push(`- ${detectionResult.warning}`);\n } else {\n lines.push(\n `- ${detectionResult.total_files} files · ~${detectionResult.total_words.toLocaleString()} words`,\n \"- Verdict: corpus is large enough that graph structure adds value.\",\n );\n }\n\n lines.push(\n \"\",\n \"## Summary\",\n `- ${G.order} nodes · ${G.size} edges · ${communityMap.size} communities detected`,\n `- Extraction: ${extPct}% EXTRACTED · ${infPct}% INFERRED · ${ambPct}% AMBIGUOUS` +\n (infAvg !== null ? ` · INFERRED: ${infEdges.length} edges (avg confidence: ${infAvg})` : \"\"),\n `- Token cost: ${tokenCost.input.toLocaleString()} input · ${tokenCost.output.toLocaleString()} output`,\n \"\",\n \"## God Nodes (most connected - your core abstractions)\",\n );\n\n godNodeList.forEach((node, i) => {\n lines.push(`${i + 1}. \\`${node.label}\\` - ${node.edges} edges`);\n });\n\n lines.push(\"\", \"## Surprising Connections (you probably didn't know these)\");\n if (surpriseList.length > 0) {\n for (const s of surpriseList) {\n const relation = s.relation ?? \"related_to\";\n const note = s.note ?? \"\";\n const files = s.source_files ?? [\"\", \"\"];\n const conf = s.confidence ?? \"EXTRACTED\";\n const cscore = s.confidence_score;\n const confTag = conf === \"INFERRED\" && cscore != null ? `INFERRED ${cscore.toFixed(2)}` : conf;\n const semTag = relation === \"semantically_similar_to\" ? \" [semantically similar]\" : \"\";\n lines.push(\n `- \\`${s.source}\\` --${relation}--> \\`${s.target}\\` [${confTag}]${semTag}`,\n ` ${files[0]} → ${files[1]}${note ? ` _${note}_` : \"\"}`,\n );\n }\n } else {\n lines.push(\"- None detected - all connections are within the same source files.\");\n }\n\n const hyperedges = (G.getAttribute(\"hyperedges\") as Array<Record<string, unknown>>) ?? [];\n if (hyperedges.length > 0) {\n lines.push(\"\", \"## Hyperedges (group relationships)\");\n for (const h of hyperedges) {\n const nodeLabels = ((h.nodes as string[]) ?? []).join(\", \");\n const conf = (h.confidence as string) ?? \"INFERRED\";\n const cscore = h.confidence_score as number | undefined;\n const confTag = cscore != null ? `${conf} ${cscore.toFixed(2)}` : conf;\n lines.push(`- **${h.label ?? h.id ?? \"\"}** — ${nodeLabels} [${confTag}]`);\n }\n }\n\n lines.push(\"\", \"## Communities\");\n for (const [cid, nodes] of communityMap) {\n const label = labelMap.get(cid) ?? `Community ${cid}`;\n const score = cohesionMap.get(cid) ?? 0.0;\n const realNodes = nodes.filter((n) => !isFileNode(G, n));\n const display = realNodes.slice(0, 8).map((n) => (G.getNodeAttribute(n, \"label\") as string) ?? n);\n const suffix = realNodes.length > 8 ? ` (+${realNodes.length - 8} more)` : \"\";\n lines.push(\n \"\",\n `### Community ${cid} - \"${label}\"`,\n `Cohesion: ${score}`,\n `Nodes (${realNodes.length}): ${display.join(\", \")}${suffix}`,\n );\n }\n\n const ambiguous: [string, string, Record<string, unknown>][] = [];\n G.forEachEdge((_, data, u, v) => {\n if (data.confidence === \"AMBIGUOUS\") ambiguous.push([u, v, data]);\n });\n if (ambiguous.length > 0) {\n lines.push(\"\", \"## Ambiguous Edges - Review These\");\n for (const [u, v, d] of ambiguous) {\n const ul = (G.getNodeAttribute(u, \"label\") as string) ?? u;\n const vl = (G.getNodeAttribute(v, \"label\") as string) ?? v;\n lines.push(\n `- \\`${ul}\\` → \\`${vl}\\` [AMBIGUOUS]`,\n ` ${d.source_file ?? \"\"} · relation: ${d.relation ?? \"unknown\"}`,\n );\n }\n }\n\n // Gaps section\n const isolated = G.nodes().filter(\n (n) => G.degree(n) <= 1 && !isFileNode(G, n) && !isConceptNode(G, n),\n );\n const thinCommunities = new Map<number, string[]>();\n for (const [cid, nodes] of communityMap) {\n if (nodes.length < 3) thinCommunities.set(cid, nodes);\n }\n const gapCount = isolated.length + thinCommunities.size;\n\n if (gapCount > 0 || ambPct > 20) {\n lines.push(\"\", \"## Knowledge Gaps\");\n if (isolated.length > 0) {\n const isolatedLabels = isolated.slice(0, 5).map((n) => (G.getNodeAttribute(n, \"label\") as string) ?? n);\n const suffix = isolated.length > 5 ? ` (+${isolated.length - 5} more)` : \"\";\n lines.push(\n `- **${isolated.length} isolated node(s):** ${isolatedLabels.map((l) => `\\`${l}\\``).join(\", \")}${suffix}`,\n \" These have ≤1 connection - possible missing edges or undocumented components.\",\n );\n }\n if (thinCommunities.size > 0) {\n for (const [cid, nodes] of thinCommunities) {\n const label = labelMap.get(cid) ?? `Community ${cid}`;\n const nodeLabels = nodes.map((n) => (G.getNodeAttribute(n, \"label\") as string) ?? n);\n lines.push(\n `- **Thin community \\`${label}\\`** (${nodes.length} nodes): ${nodeLabels.map((l) => `\\`${l}\\``).join(\", \")}`,\n \" Too small to be a meaningful cluster - may be noise or needs more connections extracted.\",\n );\n }\n }\n if (ambPct > 20) {\n lines.push(`- **High ambiguity: ${ambPct}% of edges are AMBIGUOUS.** Review the Ambiguous Edges section above.`);\n }\n }\n\n if (suggestedQuestionList && suggestedQuestionList.length > 0) {\n lines.push(\"\", \"## Suggested Questions\");\n const noSignal = suggestedQuestionList.length === 1 && suggestedQuestionList[0]!.type === \"no_signal\";\n if (noSignal) {\n lines.push(`_${suggestedQuestionList[0]!.why}_`);\n } else {\n lines.push(\"_Questions this graph is uniquely positioned to answer:_\", \"\");\n for (const q of suggestedQuestionList) {\n if (q.question) {\n lines.push(`- **${q.question}**`, ` _${q.why}_`);\n }\n }\n }\n }\n\n return lines.join(\"\\n\");\n}\n"],"mappings":";;;;;;;;AAAA,SAAS,eAAe;AACxB,OAAOA,YAAW;AAClB;AAAA,EACE,cAAAC;AAAA,EACA,aAAAC;AAAA,EACA,gBAAAC;AAAA,EACA,iBAAAC;AAAA,OACK;AACP,SAAS,WAAAC,UAAS,QAAAC,OAAM,WAAAC,gBAAe;AACvC,SAAS,qBAA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B,UAAU,aAAa,KAAgB;AAC9E,cAAQ,IAAI,OAAO,KAAK,YAAY,EAAE,OAAO,KAAK,KAAK,KAAK,cAAc,EAAE,MAAM,UAAU,GAAG;AAAA,IACjG,CAAC;AAAA,EACH,CAAC;AAEH,UACG,QAAQ,QAAQ,EAChB,SAAS,OAAO,EAChB,OAAO,uBAAuB,qCAAqC,OAAO,EAC1E,OAAO,iBAAiB,EACxB,OAAO,sBAAsB,EAC7B,OAAO,OAAO,KAAK,SAAS;AAC3B,UAAM,UAAU,MAAM,OAAO,KAAKJ,SAAQ,KAAK,SAAS,GAAG;AAAA,MACzD,QAAQ,KAAK,UAAU;AAAA,MACvB,aAAa,KAAK,eAAe;AAAA,IACnC,CAAC;AACD,YAAQ,IAAI,YAAY,OAAO,EAAE;AAAA,EACnC,CAAC;AAEH,UACG,QAAQ,mBAAmB,EAC3B,eAAe,mBAAmB,EAClC,eAAe,iBAAiB,EAChC,eAAe,qBAAqB,EACpC,OAAO,uBAAuB,gCAAgC,OAAO,EACrE,OAAO,8BAA8B,oCAAoC,IAAI,EAC7E,OAAO,CAAC,SAAS;AAChB,UAAM,UAAU,gBAAgB;AAAA,MAC9B,UAAU,KAAK;AAAA,MACf,QAAQ,KAAK;AAAA,MACb,WAAWA,SAAQ,KAAK,SAAS;AAAA,MACjC,WAAW,KAAK;AAAA,MAChB,aAAa,KAAK,MAAM,KAAK,eAAe;AAAA,IAC9C,CAAC;AACD,YAAQ,IAAI,YAAY,OAAO,EAAE;AAAA,EACnC,CAAC;AAEH,QAAM,QAAQ,WAAW,QAAQ,IAAI;AACvC;AAEA,KAAK,EAAE,MAAM,CAAC,UAAU;AACtB,QAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACrE,UAAQ,MAAM,OAAO;AACrB,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["Graph","existsSync","mkdirSync","readFileSync","writeFileSync","dirname","join","resolve","result","readFileSync","existsSync","existsSync","Graph","Graph","readdirSync","readFileSync","writeFileSync","existsSync","mkdirSync","join","resolve","createHash","CODE_EXTENSIONS","PAPER_EXTENSIONS","IMAGE_EXTENSIONS","readFileSync","readFileSync","join","existsSync","readdirSync","resolve","mkdirSync","writeFileSync","writeFileSync","existsSync","URL","nodeCommunityMap","nodeCommunityMap","writeFileSync","readFileSync","readdirSync","lstatSync","existsSync","resolve","basename","extname","join","sep","Parser","existsSync","join","Parser","readFileSync","basename","extname","sep","existsSync","mkdirSync","writeFileSync","pathResolve","basename","extname","pathResolve","writeFileSync","mkdirSync","basename","extname","existsSync","dirname","readFileSync","resolve","mkdirSync","writeFileSync","join","loadGraph","Graph","existsSync"]}
|
|
1
|
+
{"version":3,"sources":["../src/skill-runtime.ts","../src/analyze.ts","../src/collections.ts","../src/cluster.ts","../src/graph.ts","../src/detect.ts","../src/benchmark.ts","../src/cache.ts","../src/validate.ts","../src/build.ts","../src/export.ts","../src/security.ts","../src/extract.ts","../src/ingest.ts","../src/transcribe.ts","../src/report.ts"],"sourcesContent":["import { Command } from \"commander\";\nimport Graph from \"graphology\";\nimport {\n existsSync,\n mkdirSync,\n readFileSync,\n writeFileSync,\n} from \"node:fs\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nimport { graphDiff, godNodes, surprisingConnections, suggestQuestions } from \"./analyze.js\";\nimport { runBenchmark, printBenchmark } from \"./benchmark.js\";\nimport { saveSemanticCache, checkSemanticCache } from \"./cache.js\";\nimport { buildFromJson } from \"./build.js\";\nimport { cluster, scoreAll } from \"./cluster.js\";\nimport { detect, detectIncremental, saveManifest } from \"./detect.js\";\nimport { toCypher, toGraphml, toHtml, toJson, toSvg, pushToNeo4j } from \"./export.js\";\nimport { extractWithDiagnostics } from \"./extract.js\";\nimport {\n forEachTraversalNeighbor,\n isDirectedGraph,\n loadGraphFromData,\n type SerializedGraphData,\n} from \"./graph.js\";\nimport { ingest, saveQueryResult } from \"./ingest.js\";\nimport { generate } from \"./report.js\";\nimport { augmentDetectionWithTranscripts } from \"./transcribe.js\";\nimport type {\n DetectionResult,\n Extraction,\n GodNodeEntry,\n GraphDiffResult,\n SuggestedQuestion,\n SurpriseEntry,\n} from \"./types.js\";\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\ninterface AnalysisFile {\n communities: Record<string, string[]>;\n cohesion: Record<string, number>;\n gods: GodNodeEntry[];\n surprises: SurpriseEntry[];\n questions?: SuggestedQuestion[];\n labels?: Record<string, string>;\n diff?: GraphDiffResult;\n}\n\nfunction readJson<T>(path: string): T {\n return JSON.parse(readFileSync(resolve(path), \"utf-8\")) as T;\n}\n\nfunction writeJson(path: string, value: unknown): void {\n const resolved = resolve(path);\n mkdirSync(dirname(resolved), { recursive: true });\n writeFileSync(resolved, JSON.stringify(value, null, 2), \"utf-8\");\n}\n\nfunction getVersion(): string {\n try {\n const pkg = JSON.parse(readFileSync(join(__dirname, \"..\", \"package.json\"), \"utf-8\"));\n return pkg.version ?? \"unknown\";\n } catch {\n return \"unknown\";\n }\n}\n\nfunction defaultLabels(communities: Map<number, string[]>): Map<number, string> {\n const labels = new Map<number, string>();\n for (const cid of communities.keys()) {\n labels.set(cid, `Community ${cid}`);\n }\n return labels;\n}\n\nfunction mapToObject<V>(map: Map<number, V>): Record<string, V> {\n return Object.fromEntries([...map.entries()].map(([k, v]) => [String(k), v]));\n}\n\nfunction objectToStringMap(obj?: Record<string, string> | null): Map<number, string> {\n const result = new Map<number, string>();\n if (!obj) return result;\n for (const [key, value] of Object.entries(obj)) {\n const cid = Number.parseInt(key, 10);\n if (Number.isFinite(cid)) result.set(cid, value);\n }\n return result;\n}\n\nfunction ensureExtractionShape(value?: Partial<Extraction> | null): Extraction {\n return {\n nodes: value?.nodes ?? [],\n edges: value?.edges ?? [],\n hyperedges: value?.hyperedges ?? [],\n input_tokens: value?.input_tokens ?? 0,\n output_tokens: value?.output_tokens ?? 0,\n };\n}\n\nfunction loadGraph(graphPath: string): Graph {\n const raw = readJson<SerializedGraphData>(graphPath);\n return loadGraphFromData(raw);\n}\n\nfunction shouldBuildDirected(\n opts: { directed?: boolean },\n existingGraph?: Graph,\n): boolean {\n return opts.directed === true || (existingGraph ? isDirectedGraph(existingGraph) : false);\n}\n\nfunction mergeHyperedges(\n existing: Array<Record<string, unknown>> = [],\n incoming: Array<Record<string, unknown>> = [],\n): Array<Record<string, unknown>> {\n const seen = new Set<string>();\n const merged: Array<Record<string, unknown>> = [];\n for (const hyperedge of [...existing, ...incoming]) {\n const id = String(hyperedge.id ?? \"\");\n const key = id || JSON.stringify(hyperedge);\n if (seen.has(key)) continue;\n seen.add(key);\n merged.push(hyperedge);\n }\n return merged;\n}\n\nfunction mergeGraphs(target: Graph, source: Graph): void {\n source.forEachNode((nodeId, attrs) => {\n target.mergeNode(nodeId, attrs);\n });\n source.forEachEdge((_edge, attrs, sourceId, targetId) => {\n if (!target.hasNode(sourceId) || !target.hasNode(targetId)) return;\n try {\n target.mergeEdge(sourceId, targetId, attrs);\n } catch {\n /* ignore */\n }\n });\n const mergedHyperedges = mergeHyperedges(\n (target.getAttribute(\"hyperedges\") as Array<Record<string, unknown>> | undefined) ?? [],\n (source.getAttribute(\"hyperedges\") as Array<Record<string, unknown>> | undefined) ?? [],\n );\n if (mergedHyperedges.length > 0) {\n target.setAttribute(\"hyperedges\", mergedHyperedges);\n }\n}\n\nfunction analyzeGraph(\n G: Graph,\n detection: DetectionResult,\n root: string,\n tokenCost: { input: number; output: number },\n labelsOverride?: Map<number, string>,\n): {\n communities: Map<number, string[]>;\n cohesion: Map<number, number>;\n labels: Map<number, string>;\n gods: GodNodeEntry[];\n surprises: SurpriseEntry[];\n questions: SuggestedQuestion[];\n report: string;\n analysis: AnalysisFile;\n} {\n const communities = cluster(G);\n const cohesion = scoreAll(G, communities);\n const labels = labelsOverride && labelsOverride.size > 0 ? labelsOverride : defaultLabels(communities);\n const gods = godNodes(G);\n const surprises = surprisingConnections(G, communities);\n const questions = suggestQuestions(G, communities, labels);\n const report = generate(\n G,\n communities,\n cohesion,\n labels,\n gods,\n surprises,\n detection,\n tokenCost,\n root,\n questions,\n );\n return {\n communities,\n cohesion,\n labels,\n gods,\n surprises,\n questions,\n report,\n analysis: {\n communities: mapToObject(communities),\n cohesion: mapToObject(cohesion),\n gods,\n surprises,\n questions,\n labels: mapToObject(labels),\n },\n };\n}\n\nfunction placeholderDetection(root: string = \".\"): DetectionResult {\n return {\n files: { code: [], document: [], paper: [], image: [], video: [] },\n total_files: 0,\n total_words: 0,\n needs_graph: true,\n warning: `Reused existing graph at ${resolve(root)} without re-running corpus detection.`,\n skipped_sensitive: [],\n graphifyignore_patterns: 0,\n };\n}\n\nfunction mergeSemanticArtifacts(\n cached: Partial<Extraction> | null | undefined,\n fresh: Partial<Extraction> | null | undefined,\n): Extraction {\n const cachedExtraction = ensureExtractionShape(cached);\n const freshExtraction = ensureExtractionShape(fresh);\n\n const dedupedNodes: Extraction[\"nodes\"] = [];\n const seen = new Set<string>();\n for (const node of [...cachedExtraction.nodes, ...freshExtraction.nodes]) {\n if (seen.has(node.id)) continue;\n seen.add(node.id);\n dedupedNodes.push(node);\n }\n\n return {\n nodes: dedupedNodes,\n edges: [...cachedExtraction.edges, ...freshExtraction.edges],\n hyperedges: [...(cachedExtraction.hyperedges ?? []), ...(freshExtraction.hyperedges ?? [])],\n input_tokens: freshExtraction.input_tokens ?? 0,\n output_tokens: freshExtraction.output_tokens ?? 0,\n };\n}\n\nfunction mergeAstAndSemantic(\n astInput: Partial<Extraction> | null | undefined,\n semanticInput: Partial<Extraction> | null | undefined,\n): Extraction {\n const ast = ensureExtractionShape(astInput);\n const semantic = ensureExtractionShape(semanticInput);\n\n const mergedNodes: Extraction[\"nodes\"] = [...ast.nodes];\n const seen = new Set(ast.nodes.map((node) => node.id));\n for (const node of semantic.nodes) {\n if (seen.has(node.id)) continue;\n seen.add(node.id);\n mergedNodes.push(node);\n }\n\n return {\n nodes: mergedNodes,\n edges: [...ast.edges, ...semantic.edges],\n hyperedges: semantic.hyperedges ?? [],\n input_tokens: semantic.input_tokens ?? 0,\n output_tokens: semantic.output_tokens ?? 0,\n };\n}\n\nfunction updateCostFile(\n extractionInput: Partial<Extraction> | null | undefined,\n detection: DetectionResult,\n outPath: string,\n): {\n runs: Array<{ date: string; input_tokens: number; output_tokens: number; files: number }>;\n total_input_tokens: number;\n total_output_tokens: number;\n} {\n const extraction = ensureExtractionShape(extractionInput);\n let cost = {\n runs: [] as Array<{ date: string; input_tokens: number; output_tokens: number; files: number }>,\n total_input_tokens: 0,\n total_output_tokens: 0,\n };\n const resolved = resolve(outPath);\n if (existsSync(resolved)) {\n cost = readJson<typeof cost>(resolved);\n }\n\n const input = extraction.input_tokens ?? 0;\n const output = extraction.output_tokens ?? 0;\n cost.runs.push({\n date: new Date().toISOString(),\n input_tokens: input,\n output_tokens: output,\n files: detection.total_files,\n });\n cost.total_input_tokens += input;\n cost.total_output_tokens += output;\n writeJson(resolved, cost);\n return cost;\n}\n\nfunction findBestMatchingNode(G: Graph, term: string): string | null {\n const words = term.toLowerCase().split(/\\s+/).filter(Boolean);\n let best: { score: number; nodeId: string } | null = null;\n G.forEachNode((nodeId, data) => {\n const label = ((data.label as string) ?? \"\").toLowerCase();\n const score = words.filter((word) => label.includes(word)).length;\n if (score <= 0) return;\n if (!best || score > best.score) {\n best = { score, nodeId };\n }\n });\n return best?.nodeId ?? null;\n}\n\nfunction runtimeInfo(): Record<string, string> {\n return {\n runtime: \"typescript\",\n version: getVersion(),\n node: process.execPath,\n script: __filename,\n module: join(__dirname, \"index.js\"),\n cli: join(__dirname, \"cli.js\"),\n };\n}\n\nasync function main(): Promise<void> {\n const program = new Command();\n program.name(\"graphify-skill-runtime\");\n\n program\n .command(\"runtime-info\")\n .description(\"Print the runtime metadata for the Codex TypeScript skill\")\n .action(() => {\n console.log(JSON.stringify(runtimeInfo(), null, 2));\n });\n\n program\n .command(\"detect\")\n .argument(\"<inputPath>\")\n .option(\"--out <path>\")\n .action((inputPath, opts) => {\n const result = detect(resolve(inputPath));\n if (opts.out) {\n writeJson(opts.out, result);\n console.log(`Detected ${result.total_files} files in ${resolve(inputPath)}`);\n } else {\n console.log(JSON.stringify(result, null, 2));\n }\n });\n\n program\n .command(\"detect-incremental\")\n .argument(\"<inputPath>\")\n .option(\"--manifest <path>\", \"Path to manifest.json\", \"graphify-out/manifest.json\")\n .option(\"--out <path>\")\n .action((inputPath, opts) => {\n const result = detectIncremental(resolve(inputPath), resolve(opts.manifest));\n if (opts.out) {\n writeJson(opts.out, result);\n console.log(`${result.new_total ?? 0} new/changed file(s) under ${resolve(inputPath)}`);\n } else {\n console.log(JSON.stringify(result, null, 2));\n }\n });\n\n program\n .command(\"prepare-semantic-detect\")\n .requiredOption(\"--detect <path>\", \"Path to the base detection JSON\")\n .requiredOption(\"--out <path>\", \"Path to the augmented semantic detection JSON\")\n .requiredOption(\"--transcripts-out <path>\", \"Path to the transcript path list JSON\")\n .option(\"--analysis <path>\", \"Optional analysis JSON from a previous run\")\n .option(\"--incremental\", \"Use detection.new_files.video and force retranscription\")\n .option(\"--whisper-model <name>\", \"Whisper model override for local transcription\")\n .action(async (opts) => {\n const detection = readJson<DetectionResult>(opts.detect);\n const analysis = opts.analysis && existsSync(resolve(opts.analysis))\n ? readJson<AnalysisFile>(opts.analysis)\n : null;\n const transcriptsDir = join(dirname(resolve(opts.out)), \"transcripts\");\n const { detection: semanticDetection, transcriptPaths } = await augmentDetectionWithTranscripts(detection, {\n outputDir: transcriptsDir,\n godNodes: analysis?.gods,\n incremental: opts.incremental,\n whisperModel: opts.whisperModel,\n });\n\n writeJson(opts.out, semanticDetection);\n writeJson(opts.transcriptsOut, transcriptPaths);\n console.log(`Transcribed ${transcriptPaths.length} video file(s) -> treating as docs`);\n });\n\n program\n .command(\"extract-ast\")\n .requiredOption(\"--detect <path>\", \"Path to detection JSON\")\n .requiredOption(\"--out <path>\", \"Path to AST extraction JSON\")\n .option(\"--incremental\", \"Use detection.new_files.code instead of detection.files.code\")\n .action(async (opts) => {\n const detection = readJson<DetectionResult>(opts.detect);\n const codeFiles = opts.incremental\n ? detection.new_files?.code ?? []\n : detection.files.code ?? [];\n\n if (codeFiles.length === 0) {\n writeJson(opts.out, ensureExtractionShape());\n console.log(\"No code files - skipping AST extraction\");\n return;\n }\n\n const { extraction, diagnostics } = await extractWithDiagnostics(codeFiles);\n writeJson(opts.out, extraction);\n if (diagnostics.length > 0) {\n const sample = diagnostics\n .slice(0, 3)\n .map((d) => `${d.filePath}: ${d.error}`)\n .join(\" | \");\n console.log(`AST: ${extraction.nodes.length} nodes, ${extraction.edges.length} edges (${diagnostics.length} file(s) failed: ${sample})`);\n return;\n }\n console.log(`AST: ${extraction.nodes.length} nodes, ${extraction.edges.length} edges`);\n });\n\n program\n .command(\"check-semantic-cache\")\n .requiredOption(\"--detect <path>\", \"Path to detection JSON\")\n .option(\"--incremental\", \"Use detection.new_files when present\")\n .option(\"--root <path>\", \"Graph root for cache resolution\", \".\")\n .requiredOption(\"--cached-out <path>\", \"Path to cached extraction JSON\")\n .requiredOption(\"--uncached-out <path>\", \"Path to newline-delimited uncached file list\")\n .action((opts) => {\n const detection = readJson<DetectionResult>(opts.detect);\n const source = opts.incremental && detection.new_files ? detection.new_files : detection.files;\n const allFiles = [\n ...(source.document ?? []),\n ...(source.paper ?? []),\n ...(source.image ?? []),\n ];\n const [cachedNodes, cachedEdges, cachedHyperedges, uncached] = checkSemanticCache(\n allFiles,\n resolve(opts.root),\n );\n writeJson(opts.cachedOut, {\n nodes: cachedNodes,\n edges: cachedEdges,\n hyperedges: cachedHyperedges,\n });\n mkdirSync(dirname(resolve(opts.uncachedOut)), { recursive: true });\n writeFileSync(resolve(opts.uncachedOut), uncached.join(\"\\n\"), \"utf-8\");\n console.log(`Cache: ${allFiles.length - uncached.length} files hit, ${uncached.length} files need extraction`);\n });\n\n program\n .command(\"save-semantic-cache\")\n .requiredOption(\"--input <path>\", \"Path to semantic extraction JSON\")\n .option(\"--root <path>\", \"Graph root for cache resolution\", \".\")\n .action((opts) => {\n const extraction = ensureExtractionShape(readJson<Partial<Extraction>>(opts.input));\n const saved = saveSemanticCache(\n extraction.nodes as Array<Record<string, unknown>>,\n extraction.edges as Array<Record<string, unknown>>,\n (extraction.hyperedges ?? []) as Array<Record<string, unknown>>,\n resolve(opts.root),\n );\n console.log(`Cached ${saved} files`);\n });\n\n program\n .command(\"merge-semantic\")\n .requiredOption(\"--cached <path>\")\n .requiredOption(\"--new <path>\")\n .requiredOption(\"--out <path>\")\n .action((opts) => {\n const cached = ensureExtractionShape(readJson<Partial<Extraction>>(opts.cached));\n const fresh = ensureExtractionShape(readJson<Partial<Extraction>>(opts.new));\n\n const dedupedNodes: Extraction[\"nodes\"] = [];\n const seen = new Set<string>();\n for (const node of [...cached.nodes, ...fresh.nodes]) {\n if (seen.has(node.id)) continue;\n seen.add(node.id);\n dedupedNodes.push(node);\n }\n\n const merged: Extraction = {\n nodes: dedupedNodes,\n edges: [...cached.edges, ...fresh.edges],\n hyperedges: [...(cached.hyperedges ?? []), ...(fresh.hyperedges ?? [])],\n input_tokens: fresh.input_tokens ?? 0,\n output_tokens: fresh.output_tokens ?? 0,\n };\n writeJson(opts.out, merged);\n console.log(\n `Extraction complete - ${merged.nodes.length} nodes, ${merged.edges.length} edges (${cached.nodes.length} from cache, ${fresh.nodes.length} new)`,\n );\n });\n\n program\n .command(\"merge-extraction\")\n .requiredOption(\"--ast <path>\")\n .requiredOption(\"--semantic <path>\")\n .requiredOption(\"--out <path>\")\n .action((opts) => {\n const ast = ensureExtractionShape(readJson<Partial<Extraction>>(opts.ast));\n const semantic = ensureExtractionShape(readJson<Partial<Extraction>>(opts.semantic));\n\n const mergedNodes: Extraction[\"nodes\"] = [...ast.nodes];\n const seen = new Set(ast.nodes.map((node) => node.id));\n for (const node of semantic.nodes) {\n if (seen.has(node.id)) continue;\n seen.add(node.id);\n mergedNodes.push(node);\n }\n\n const merged: Extraction = {\n nodes: mergedNodes,\n edges: [...ast.edges, ...semantic.edges],\n hyperedges: semantic.hyperedges ?? [],\n input_tokens: semantic.input_tokens ?? 0,\n output_tokens: semantic.output_tokens ?? 0,\n };\n writeJson(opts.out, merged);\n console.log(\n `Merged: ${merged.nodes.length} nodes, ${merged.edges.length} edges (${ast.nodes.length} AST + ${semantic.nodes.length} semantic)`,\n );\n });\n\n program\n .command(\"finalize-build\")\n .requiredOption(\"--detect <path>\")\n .requiredOption(\"--ast <path>\")\n .requiredOption(\"--root <path>\")\n .requiredOption(\"--graph-out <path>\")\n .requiredOption(\"--report-out <path>\")\n .requiredOption(\"--analysis-out <path>\")\n .requiredOption(\"--cost-out <path>\")\n .option(\"--directed\", \"Build a directed graph (preserves source->target)\")\n .option(\"--cached <path>\", \"Optional cached semantic JSON\")\n .option(\"--semantic-new <path>\", \"Optional fresh semantic JSON\")\n .option(\"--html-out <path>\", \"Optional graph.html output path\")\n .action((opts) => {\n const detection = readJson<DetectionResult>(opts.detect);\n const ast = ensureExtractionShape(readJson<Partial<Extraction>>(opts.ast));\n const cached = opts.cached && existsSync(resolve(opts.cached))\n ? readJson<Partial<Extraction>>(opts.cached)\n : null;\n const semanticNew = opts.semanticNew && existsSync(resolve(opts.semanticNew))\n ? readJson<Partial<Extraction>>(opts.semanticNew)\n : null;\n\n if (semanticNew) {\n saveSemanticCache(\n semanticNew.nodes as Array<Record<string, unknown>>,\n semanticNew.edges as Array<Record<string, unknown>>,\n (semanticNew.hyperedges ?? []) as Array<Record<string, unknown>>,\n \".\",\n );\n }\n\n const semantic = mergeSemanticArtifacts(cached, semanticNew);\n const extraction = mergeAstAndSemantic(ast, semantic);\n const G = buildFromJson(extraction, { directed: shouldBuildDirected(opts) });\n if (G.order === 0) {\n throw new Error(\"Graph is empty - extraction produced no nodes.\");\n }\n\n const analyzed = analyzeGraph(\n G,\n detection,\n resolve(opts.root),\n { input: extraction.input_tokens ?? 0, output: extraction.output_tokens ?? 0 },\n );\n\n toJson(G, analyzed.communities, resolve(opts.graphOut), {\n communityLabels: analyzed.labels,\n });\n writeFileSync(resolve(opts.reportOut), analyzed.report, \"utf-8\");\n writeJson(opts.analysisOut, analyzed.analysis);\n if (opts.htmlOut) {\n toHtml(G, analyzed.communities, resolve(opts.htmlOut), {\n communityLabels: analyzed.labels,\n });\n }\n saveManifest(detection.files, join(dirname(resolve(opts.graphOut)), \"manifest.json\"));\n const cost = updateCostFile(extraction, detection, opts.costOut);\n\n console.log(`Graph: ${G.order} nodes, ${G.size} edges, ${analyzed.communities.size} communities`);\n console.log(`This run: ${(extraction.input_tokens ?? 0).toLocaleString()} input tokens, ${(extraction.output_tokens ?? 0).toLocaleString()} output tokens`);\n console.log(`All time: ${cost.total_input_tokens.toLocaleString()} input, ${cost.total_output_tokens.toLocaleString()} output (${cost.runs.length} runs)`);\n });\n\n program\n .command(\"finalize-update\")\n .requiredOption(\"--detect <path>\")\n .requiredOption(\"--ast <path>\")\n .requiredOption(\"--existing-graph <path>\")\n .requiredOption(\"--root <path>\")\n .requiredOption(\"--graph-out <path>\")\n .requiredOption(\"--report-out <path>\")\n .requiredOption(\"--analysis-out <path>\")\n .requiredOption(\"--cost-out <path>\")\n .option(\"--directed\", \"Build a directed graph (preserves source->target)\")\n .option(\"--cached <path>\", \"Optional cached semantic JSON\")\n .option(\"--semantic-new <path>\", \"Optional fresh semantic JSON\")\n .option(\"--html-out <path>\", \"Optional graph.html output path\")\n .action((opts) => {\n const detection = readJson<DetectionResult>(opts.detect);\n const ast = ensureExtractionShape(readJson<Partial<Extraction>>(opts.ast));\n const cached = opts.cached && existsSync(resolve(opts.cached))\n ? readJson<Partial<Extraction>>(opts.cached)\n : null;\n const semanticNew = opts.semanticNew && existsSync(resolve(opts.semanticNew))\n ? readJson<Partial<Extraction>>(opts.semanticNew)\n : null;\n\n if (semanticNew) {\n saveSemanticCache(\n semanticNew.nodes as Array<Record<string, unknown>>,\n semanticNew.edges as Array<Record<string, unknown>>,\n (semanticNew.hyperedges ?? []) as Array<Record<string, unknown>>,\n \".\",\n );\n }\n\n const semantic = mergeSemanticArtifacts(cached, semanticNew);\n const extraction = mergeAstAndSemantic(ast, semantic);\n\n const oldGraph = loadGraph(opts.existingGraph);\n const mergedGraph = loadGraph(opts.existingGraph);\n const newGraph = buildFromJson(extraction, {\n directed: shouldBuildDirected(opts, oldGraph),\n });\n mergeGraphs(mergedGraph, newGraph);\n\n const analyzed = analyzeGraph(\n mergedGraph,\n detection,\n resolve(opts.root),\n { input: extraction.input_tokens ?? 0, output: extraction.output_tokens ?? 0 },\n );\n analyzed.analysis.diff = graphDiff(oldGraph, mergedGraph);\n\n toJson(mergedGraph, analyzed.communities, resolve(opts.graphOut), {\n communityLabels: analyzed.labels,\n });\n writeFileSync(resolve(opts.reportOut), analyzed.report, \"utf-8\");\n writeJson(opts.analysisOut, analyzed.analysis);\n if (opts.htmlOut) {\n toHtml(mergedGraph, analyzed.communities, resolve(opts.htmlOut), {\n communityLabels: analyzed.labels,\n });\n }\n saveManifest(detection.files, join(dirname(resolve(opts.graphOut)), \"manifest.json\"));\n const cost = updateCostFile(extraction, detection, opts.costOut);\n\n console.log(`Merged: ${mergedGraph.order} nodes, ${mergedGraph.size} edges`);\n console.log(analyzed.analysis.diff.summary);\n console.log(`This run: ${(extraction.input_tokens ?? 0).toLocaleString()} input tokens, ${(extraction.output_tokens ?? 0).toLocaleString()} output tokens`);\n console.log(`All time: ${cost.total_input_tokens.toLocaleString()} input, ${cost.total_output_tokens.toLocaleString()} output (${cost.runs.length} runs)`);\n });\n\n program\n .command(\"analyze-build\")\n .requiredOption(\"--extract <path>\")\n .requiredOption(\"--detect <path>\")\n .requiredOption(\"--root <path>\")\n .requiredOption(\"--graph-out <path>\")\n .requiredOption(\"--report-out <path>\")\n .requiredOption(\"--analysis-out <path>\")\n .option(\"--directed\", \"Build a directed graph (preserves source->target)\")\n .action((opts) => {\n const extraction = ensureExtractionShape(readJson<Partial<Extraction>>(opts.extract));\n const detection = readJson<DetectionResult>(opts.detect);\n const root = resolve(opts.root);\n const G = buildFromJson(extraction, { directed: shouldBuildDirected(opts) });\n\n if (G.order === 0) {\n throw new Error(\"Graph is empty - extraction produced no nodes.\");\n }\n\n const analyzed = analyzeGraph(\n G,\n detection,\n root,\n { input: extraction.input_tokens ?? 0, output: extraction.output_tokens ?? 0 },\n );\n\n mkdirSync(dirname(resolve(opts.graphOut)), { recursive: true });\n toJson(G, analyzed.communities, resolve(opts.graphOut), {\n communityLabels: analyzed.labels,\n });\n writeFileSync(resolve(opts.reportOut), analyzed.report, \"utf-8\");\n writeJson(opts.analysisOut, analyzed.analysis);\n saveManifest(detection.files, join(dirname(resolve(opts.graphOut)), \"manifest.json\"));\n console.log(`Graph: ${G.order} nodes, ${G.size} edges, ${analyzed.communities.size} communities`);\n });\n\n program\n .command(\"write-labeled-report\")\n .requiredOption(\"--extract <path>\")\n .requiredOption(\"--detect <path>\")\n .requiredOption(\"--analysis <path>\")\n .requiredOption(\"--labels <path>\")\n .requiredOption(\"--root <path>\")\n .requiredOption(\"--report-out <path>\")\n .option(\"--directed\", \"Build a directed graph (preserves source->target)\")\n .option(\"--graph-out <path>\")\n .option(\"--html-out <path>\")\n .action((opts) => {\n const extraction = ensureExtractionShape(readJson<Partial<Extraction>>(opts.extract));\n const detection = readJson<DetectionResult>(opts.detect);\n const analysis = readJson<AnalysisFile>(opts.analysis);\n const labelObject = readJson<Record<string, string>>(opts.labels);\n const labels = objectToStringMap(labelObject);\n const G = buildFromJson(extraction, { directed: shouldBuildDirected(opts) });\n const communities = new Map<number, string[]>(\n Object.entries(analysis.communities).map(([key, value]) => [Number.parseInt(key, 10), value]),\n );\n const cohesion = new Map<number, number>(\n Object.entries(analysis.cohesion).map(([key, value]) => [Number.parseInt(key, 10), value]),\n );\n const questions = suggestQuestions(G, communities, labels);\n const report = generate(\n G,\n communities,\n cohesion,\n labels,\n analysis.gods,\n analysis.surprises,\n detection,\n { input: extraction.input_tokens ?? 0, output: extraction.output_tokens ?? 0 },\n resolve(opts.root),\n questions,\n );\n\n analysis.questions = questions;\n analysis.labels = mapToObject(labels);\n writeFileSync(resolve(opts.reportOut), report, \"utf-8\");\n if (opts.graphOut) {\n toJson(G, communities, resolve(opts.graphOut), { communityLabels: labels });\n }\n if (opts.htmlOut) {\n toHtml(G, communities, resolve(opts.htmlOut), { communityLabels: labels });\n }\n writeJson(opts.analysis, analysis);\n console.log(\"Labeled artifacts updated\");\n });\n\n program\n .command(\"export-html\")\n .requiredOption(\"--extract <path>\")\n .requiredOption(\"--analysis <path>\")\n .option(\"--labels <path>\")\n .requiredOption(\"--out <path>\")\n .option(\"--directed\", \"Build a directed graph (preserves source->target)\")\n .action((opts) => {\n const extraction = ensureExtractionShape(readJson<Partial<Extraction>>(opts.extract));\n const analysis = readJson<AnalysisFile>(opts.analysis);\n const labels = opts.labels ? objectToStringMap(readJson<Record<string, string>>(opts.labels)) : objectToStringMap(analysis.labels);\n const communities = new Map<number, string[]>(\n Object.entries(analysis.communities).map(([key, value]) => [Number.parseInt(key, 10), value]),\n );\n const G = buildFromJson(extraction, { directed: shouldBuildDirected(opts) });\n toHtml(G, communities, resolve(opts.out), { communityLabels: labels });\n console.log(\"graph.html written - open in any browser, no server needed\");\n });\n\n program\n .command(\"export-svg\")\n .requiredOption(\"--extract <path>\")\n .requiredOption(\"--analysis <path>\")\n .option(\"--labels <path>\")\n .requiredOption(\"--out <path>\")\n .option(\"--directed\", \"Build a directed graph (preserves source->target)\")\n .action((opts) => {\n const extraction = ensureExtractionShape(readJson<Partial<Extraction>>(opts.extract));\n const analysis = readJson<AnalysisFile>(opts.analysis);\n const labels = opts.labels ? objectToStringMap(readJson<Record<string, string>>(opts.labels)) : objectToStringMap(analysis.labels);\n const communities = new Map<number, string[]>(\n Object.entries(analysis.communities).map(([key, value]) => [Number.parseInt(key, 10), value]),\n );\n const G = buildFromJson(extraction, { directed: shouldBuildDirected(opts) });\n toSvg(G, communities, resolve(opts.out), labels);\n console.log(\"graph.svg written - embeds in Obsidian, Notion, GitHub READMEs\");\n });\n\n program\n .command(\"export-graphml\")\n .requiredOption(\"--extract <path>\")\n .requiredOption(\"--analysis <path>\")\n .requiredOption(\"--out <path>\")\n .option(\"--directed\", \"Build a directed graph (preserves source->target)\")\n .action((opts) => {\n const extraction = ensureExtractionShape(readJson<Partial<Extraction>>(opts.extract));\n const analysis = readJson<AnalysisFile>(opts.analysis);\n const communities = new Map<number, string[]>(\n Object.entries(analysis.communities).map(([key, value]) => [Number.parseInt(key, 10), value]),\n );\n const G = buildFromJson(extraction, { directed: shouldBuildDirected(opts) });\n toGraphml(G, communities, resolve(opts.out));\n console.log(\"graph.graphml written - open in Gephi, yEd, or any GraphML tool\");\n });\n\n program\n .command(\"export-cypher\")\n .requiredOption(\"--extract <path>\")\n .requiredOption(\"--out <path>\")\n .option(\"--directed\", \"Build a directed graph (preserves source->target)\")\n .action((opts) => {\n const extraction = ensureExtractionShape(readJson<Partial<Extraction>>(opts.extract));\n const G = buildFromJson(extraction, { directed: shouldBuildDirected(opts) });\n toCypher(G, resolve(opts.out));\n console.log(\"cypher.txt written - import with: cypher-shell < graphify-out/cypher.txt\");\n });\n\n program\n .command(\"push-neo4j\")\n .requiredOption(\"--extract <path>\")\n .requiredOption(\"--analysis <path>\")\n .requiredOption(\"--uri <uri>\")\n .requiredOption(\"--user <user>\")\n .requiredOption(\"--password <password>\")\n .option(\"--directed\", \"Build a directed graph (preserves source->target)\")\n .action(async (opts) => {\n const extraction = ensureExtractionShape(readJson<Partial<Extraction>>(opts.extract));\n const analysis = readJson<AnalysisFile>(opts.analysis);\n const G = buildFromJson(extraction, { directed: shouldBuildDirected(opts) });\n const communities = new Map<number, string[]>(\n Object.entries(analysis.communities).map(([key, value]) => [Number.parseInt(key, 10), value]),\n );\n const result = await pushToNeo4j(G, {\n uri: opts.uri,\n user: opts.user,\n password: opts.password,\n communities,\n });\n console.log(`Pushed to Neo4j: ${result.nodes} nodes, ${result.edges} edges`);\n });\n\n program\n .command(\"benchmark\")\n .requiredOption(\"--graph <path>\")\n .option(\"--corpus-words <n>\")\n .action((opts) => {\n const corpusWords = opts.corpusWords ? Number.parseInt(opts.corpusWords, 10) : undefined;\n const result = runBenchmark(resolve(opts.graph), corpusWords);\n printBenchmark(result);\n });\n\n program\n .command(\"update-cost\")\n .requiredOption(\"--extract <path>\")\n .requiredOption(\"--detect <path>\")\n .requiredOption(\"--out <path>\")\n .action((opts) => {\n const extraction = ensureExtractionShape(readJson<Partial<Extraction>>(opts.extract));\n const detection = readJson<DetectionResult>(opts.detect);\n const outPath = resolve(opts.out);\n\n let cost = {\n runs: [] as Array<{ date: string; input_tokens: number; output_tokens: number; files: number }>,\n total_input_tokens: 0,\n total_output_tokens: 0,\n };\n if (existsSync(outPath)) {\n cost = readJson<typeof cost>(outPath);\n }\n\n const input = extraction.input_tokens ?? 0;\n const output = extraction.output_tokens ?? 0;\n cost.runs.push({\n date: new Date().toISOString(),\n input_tokens: input,\n output_tokens: output,\n files: detection.total_files,\n });\n cost.total_input_tokens += input;\n cost.total_output_tokens += output;\n writeJson(outPath, cost);\n\n console.log(`This run: ${input.toLocaleString()} input tokens, ${output.toLocaleString()} output tokens`);\n console.log(\n `All time: ${cost.total_input_tokens.toLocaleString()} input, ${cost.total_output_tokens.toLocaleString()} output (${cost.runs.length} runs)`,\n );\n });\n\n program\n .command(\"merge-update\")\n .requiredOption(\"--existing-graph <path>\")\n .requiredOption(\"--extract <path>\")\n .requiredOption(\"--detect <path>\")\n .requiredOption(\"--root <path>\")\n .requiredOption(\"--graph-out <path>\")\n .requiredOption(\"--report-out <path>\")\n .requiredOption(\"--analysis-out <path>\")\n .option(\"--directed\", \"Build a directed graph (preserves source->target)\")\n .action((opts) => {\n const oldGraph = loadGraph(opts.existingGraph);\n const mergedGraph = loadGraph(opts.existingGraph);\n const extraction = ensureExtractionShape(readJson<Partial<Extraction>>(opts.extract));\n const detection = readJson<DetectionResult>(opts.detect);\n const newGraph = buildFromJson(extraction, {\n directed: shouldBuildDirected(opts, oldGraph),\n });\n\n mergeGraphs(mergedGraph, newGraph);\n\n const analyzed = analyzeGraph(\n mergedGraph,\n detection,\n resolve(opts.root),\n { input: extraction.input_tokens ?? 0, output: extraction.output_tokens ?? 0 },\n );\n analyzed.analysis.diff = graphDiff(oldGraph, mergedGraph);\n\n toJson(mergedGraph, analyzed.communities, resolve(opts.graphOut), {\n communityLabels: analyzed.labels,\n });\n writeFileSync(resolve(opts.reportOut), analyzed.report, \"utf-8\");\n writeJson(opts.analysisOut, analyzed.analysis);\n saveManifest(detection.files, join(dirname(resolve(opts.graphOut)), \"manifest.json\"));\n\n console.log(`Merged: ${mergedGraph.order} nodes, ${mergedGraph.size} edges`);\n console.log(analyzed.analysis.diff.summary);\n });\n\n program\n .command(\"cluster-only\")\n .requiredOption(\"--graph <path>\")\n .requiredOption(\"--root <path>\")\n .requiredOption(\"--graph-out <path>\")\n .requiredOption(\"--report-out <path>\")\n .requiredOption(\"--analysis-out <path>\")\n .action((opts) => {\n const G = loadGraph(opts.graph);\n const analyzed = analyzeGraph(\n G,\n placeholderDetection(opts.root),\n resolve(opts.root),\n { input: 0, output: 0 },\n );\n toJson(G, analyzed.communities, resolve(opts.graphOut), {\n communityLabels: analyzed.labels,\n });\n writeFileSync(resolve(opts.reportOut), analyzed.report, \"utf-8\");\n writeJson(opts.analysisOut, analyzed.analysis);\n console.log(`Re-clustered: ${analyzed.communities.size} communities`);\n });\n\n program\n .command(\"path\")\n .requiredOption(\"--graph <path>\")\n .argument(\"<nodeA>\")\n .argument(\"<nodeB>\")\n .action(async (nodeA, nodeB, opts) => {\n const G = loadGraph(opts.graph);\n const source = findBestMatchingNode(G, nodeA);\n const target = findBestMatchingNode(G, nodeB);\n if (!source || !target) {\n console.log(`Could not find nodes matching: ${JSON.stringify(nodeA)} or ${JSON.stringify(nodeB)}`);\n return;\n }\n let path: string[];\n try {\n const shortestPath = await import(\"graphology-shortest-path/unweighted.js\");\n path = shortestPath.bidirectional(G, source, target) ?? [];\n } catch {\n throw new Error(\"graphology-shortest-path is unavailable\");\n }\n if (path.length === 0) {\n console.log(`No path found between ${JSON.stringify(nodeA)} and ${JSON.stringify(nodeB)}`);\n return;\n }\n console.log(`Shortest path (${path.length - 1} hops):`);\n for (let i = 0; i < path.length; i++) {\n const nodeId = path[i]!;\n const label = (G.getNodeAttribute(nodeId, \"label\") as string) ?? nodeId;\n if (i === path.length - 1) {\n console.log(` ${label}`);\n break;\n }\n const nextNode = path[i + 1]!;\n const edgeId = G.edge(nodeId, nextNode);\n const attrs = edgeId ? G.getEdgeAttributes(edgeId) : {};\n console.log(` ${label} --${attrs.relation ?? \"\"}--> [${attrs.confidence ?? \"\"}]`);\n }\n });\n\n program\n .command(\"explain\")\n .requiredOption(\"--graph <path>\")\n .argument(\"<nodeName>\")\n .action((nodeName, opts) => {\n const G = loadGraph(opts.graph);\n const nodeId = findBestMatchingNode(G, nodeName);\n if (!nodeId) {\n console.log(`No node matching ${JSON.stringify(nodeName)}`);\n return;\n }\n const attrs = G.getNodeAttributes(nodeId);\n console.log(`NODE: ${(attrs.label as string) ?? nodeId}`);\n console.log(` source: ${(attrs.source_file as string) ?? \"unknown\"}`);\n console.log(` type: ${(attrs.file_type as string) ?? \"unknown\"}`);\n console.log(` degree: ${G.degree(nodeId)}`);\n console.log(\"\");\n console.log(\"CONNECTIONS:\");\n forEachTraversalNeighbor(G, nodeId, (neighbor) => {\n const edgeId = G.edge(nodeId, neighbor);\n const edge = edgeId ? G.getEdgeAttributes(edgeId) : {};\n const label = (G.getNodeAttribute(neighbor, \"label\") as string) ?? neighbor;\n const sourceFile = (G.getNodeAttribute(neighbor, \"source_file\") as string) ?? \"\";\n console.log(` --${edge.relation ?? \"\"}--> ${label} [${edge.confidence ?? \"\"}] (${sourceFile})`);\n });\n });\n\n program\n .command(\"ingest\")\n .argument(\"<url>\")\n .option(\"--target-dir <path>\", \"Directory to save fetched content\", \"./raw\")\n .option(\"--author <name>\")\n .option(\"--contributor <name>\")\n .action(async (url, opts) => {\n const outPath = await ingest(url, resolve(opts.targetDir), {\n author: opts.author ?? null,\n contributor: opts.contributor ?? null,\n });\n console.log(`Saved to ${outPath}`);\n });\n\n program\n .command(\"save-query-result\")\n .requiredOption(\"--question <text>\")\n .requiredOption(\"--answer <text>\")\n .requiredOption(\"--memory-dir <path>\")\n .option(\"--query-type <type>\", \"Type label for the saved Q&A\", \"query\")\n .option(\"--source-nodes-json <json>\", \"JSON array of source node labels\", \"[]\")\n .action((opts) => {\n const outPath = saveQueryResult({\n question: opts.question,\n answer: opts.answer,\n memoryDir: resolve(opts.memoryDir),\n queryType: opts.queryType,\n sourceNodes: JSON.parse(opts.sourceNodesJson) as string[],\n });\n console.log(`Saved to ${outPath}`);\n });\n\n await program.parseAsync(process.argv);\n}\n\nmain().catch((error) => {\n const message = error instanceof Error ? error.message : String(error);\n console.error(message);\n process.exit(1);\n});\n","/**\n * Graph analysis: god nodes (most connected), surprising connections (cross-community),\n * suggested questions, graph diff.\n */\nimport Graph from \"graphology\";\nimport betweennessCentrality from \"graphology-metrics/centrality/betweenness.js\";\nimport type { GodNodeEntry, SurpriseEntry, SuggestedQuestion, GraphDiffResult } from \"./types.js\";\nimport { type NumericMapLike, toNumericMap } from \"./collections.js\";\nimport { cohesionScore } from \"./cluster.js\";\nimport { traversalNeighbors } from \"./graph.js\";\nimport {\n CODE_EXTENSIONS,\n DOC_EXTENSIONS,\n PAPER_EXTENSIONS,\n IMAGE_EXTENSIONS,\n} from \"./detect.js\";\n\ntype GraphInstance = InstanceType<typeof Graph>;\n\nfunction nodeCommunityMap(communities: NumericMapLike<string[]>): Map<string, number> {\n const communityMap = toNumericMap(communities);\n const result = new Map<string, number>();\n for (const [cid, nodes] of communityMap) {\n for (const n of nodes) result.set(n, cid);\n }\n return result;\n}\n\nexport function isFileNode(G: Graph, nodeId: string): boolean {\n const attrs = G.getNodeAttributes(nodeId);\n const label = (attrs.label as string) ?? \"\";\n if (!label) return false;\n\n const sourceFile = (attrs.source_file as string) ?? \"\";\n if (sourceFile) {\n const fileName = sourceFile.split(\"/\").pop() ?? \"\";\n if (label === fileName) return true;\n }\n\n if (label.startsWith(\".\") && label.endsWith(\"()\")) return true;\n if (label.endsWith(\"()\") && G.degree(nodeId) <= 1) return true;\n return false;\n}\n\nexport function isConceptNode(G: Graph, nodeId: string): boolean {\n const data = G.getNodeAttributes(nodeId);\n const source = (data.source_file as string) ?? \"\";\n if (!source) return true;\n const lastPart = source.split(\"/\").pop() ?? \"\";\n if (!lastPart.includes(\".\")) return true;\n return false;\n}\n\nfunction fileCategory(path: string): string {\n const ext = path.includes(\".\")\n ? `.${path.split(\".\").pop()?.toLowerCase() ?? \"\"}`\n : \"\";\n if (CODE_EXTENSIONS.has(ext)) return \"code\";\n if (PAPER_EXTENSIONS.has(ext)) return \"paper\";\n if (IMAGE_EXTENSIONS.has(ext)) return \"image\";\n if (DOC_EXTENSIONS.has(ext)) return \"doc\";\n return \"doc\";\n}\n\nfunction topLevelDir(path: string): string {\n return path.includes(\"/\") ? path.split(\"/\")[0]! : path;\n}\n\nfunction surpriseScore(\n G: Graph,\n u: string,\n v: string,\n data: Record<string, unknown>,\n nodeCommunity: Map<string, number>,\n uSource: string,\n vSource: string,\n): [number, string[]] {\n let score = 0;\n const reasons: string[] = [];\n\n const conf = (data.confidence as string) ?? \"EXTRACTED\";\n const confBonus: Record<string, number> = { AMBIGUOUS: 3, INFERRED: 2, EXTRACTED: 1 };\n score += confBonus[conf] ?? 1;\n if (conf === \"AMBIGUOUS\" || conf === \"INFERRED\") {\n reasons.push(`${conf.toLowerCase()} connection - not explicitly stated in source`);\n }\n\n const catU = fileCategory(uSource);\n const catV = fileCategory(vSource);\n if (catU !== catV) {\n score += 2;\n reasons.push(`crosses file types (${catU} ↔ ${catV})`);\n }\n\n if (topLevelDir(uSource) !== topLevelDir(vSource)) {\n score += 2;\n reasons.push(\"connects across different repos/directories\");\n }\n\n const cidU = nodeCommunity.get(u);\n const cidV = nodeCommunity.get(v);\n if (cidU !== undefined && cidV !== undefined && cidU !== cidV) {\n score += 1;\n reasons.push(\"bridges separate communities\");\n }\n\n if (data.relation === \"semantically_similar_to\") {\n score = Math.floor(score * 1.5);\n reasons.push(\"semantically similar concepts with no structural link\");\n }\n\n const degU = G.degree(u);\n const degV = G.degree(v);\n if (Math.min(degU, degV) <= 2 && Math.max(degU, degV) >= 5) {\n score += 1;\n const peripheral = degU <= 2 ? (G.getNodeAttribute(u, \"label\") as string) : (G.getNodeAttribute(v, \"label\") as string);\n const hub = degU <= 2 ? (G.getNodeAttribute(v, \"label\") as string) : (G.getNodeAttribute(u, \"label\") as string);\n reasons.push(`peripheral node \\`${peripheral}\\` unexpectedly reaches hub \\`${hub}\\``);\n }\n\n return [score, reasons];\n}\n\nexport function godNodes(G: Graph, topN: number = 10): GodNodeEntry[] {\n const degree: [string, number][] = [];\n G.forEachNode((n) => degree.push([n, G.degree(n)]));\n degree.sort((a, b) => b[1] - a[1]);\n\n const result: GodNodeEntry[] = [];\n for (const [nodeId, deg] of degree) {\n if (isFileNode(G, nodeId) || isConceptNode(G, nodeId)) continue;\n result.push({\n id: nodeId,\n label: (G.getNodeAttribute(nodeId, \"label\") as string) ?? nodeId,\n edges: deg,\n });\n if (result.length >= topN) break;\n }\n return result;\n}\n\nexport function surprisingConnections(\n G: Graph,\n communities?: NumericMapLike<string[]>,\n topN: number = 5,\n): SurpriseEntry[] {\n const comms = toNumericMap(communities);\n const sourceFiles = new Set<string>();\n G.forEachNode((_, data) => {\n const sf = (data.source_file as string) ?? \"\";\n if (sf) sourceFiles.add(sf);\n });\n const isMultiSource = sourceFiles.size > 1;\n\n if (isMultiSource) {\n return crossFileSurprises(G, comms, topN);\n }\n return crossCommunitySurprises(G, comms, topN);\n}\n\nfunction crossFileSurprises(G: Graph, communities: Map<number, string[]>, topN: number): SurpriseEntry[] {\n const nodeCommunity = nodeCommunityMap(communities);\n const candidates: (SurpriseEntry & { _score: number })[] = [];\n\n G.forEachEdge((edge, data, source, target) => {\n const relation = (data.relation as string) ?? \"\";\n if ([\"imports\", \"imports_from\", \"contains\", \"method\"].includes(relation)) return;\n if (isConceptNode(G, source) || isConceptNode(G, target)) return;\n if (isFileNode(G, source) || isFileNode(G, target)) return;\n\n const uSource = (G.getNodeAttribute(source, \"source_file\") as string) ?? \"\";\n const vSource = (G.getNodeAttribute(target, \"source_file\") as string) ?? \"\";\n if (!uSource || !vSource || uSource === vSource) return;\n\n const [score, reasons] = surpriseScore(G, source, target, data, nodeCommunity, uSource, vSource);\n const srcId = (data._src as string) ?? source;\n const tgtId = (data._tgt as string) ?? target;\n\n candidates.push({\n _score: score,\n source: (G.getNodeAttribute(srcId, \"label\") as string) ?? srcId,\n target: (G.getNodeAttribute(tgtId, \"label\") as string) ?? tgtId,\n source_files: [\n (G.getNodeAttribute(srcId, \"source_file\") as string) ?? \"\",\n (G.getNodeAttribute(tgtId, \"source_file\") as string) ?? \"\",\n ],\n confidence: (data.confidence as SurpriseEntry[\"confidence\"]) ?? \"EXTRACTED\",\n relation,\n why: reasons.length > 0 ? reasons.join(\"; \") : \"cross-file semantic connection\",\n });\n });\n\n candidates.sort((a, b) => b._score - a._score);\n const result = candidates.slice(0, topN).map(({ _score, ...rest }) => rest);\n\n if (result.length > 0) return result;\n return crossCommunitySurprises(G, communities, topN);\n}\n\nfunction crossCommunitySurprises(\n G: Graph,\n communities: Map<number, string[]>,\n topN: number,\n): SurpriseEntry[] {\n if (communities.size === 0) {\n if (G.size === 0) return [];\n // Use edge betweenness centrality approximation\n return edgeBetweennessSurprises(G, topN);\n }\n\n const nodeCommunity = nodeCommunityMap(communities);\n const surprises: (SurpriseEntry & { _pair: string })[] = [];\n\n G.forEachEdge((edge, data, u, v) => {\n const cidU = nodeCommunity.get(u);\n const cidV = nodeCommunity.get(v);\n if (cidU === undefined || cidV === undefined || cidU === cidV) return;\n if (isFileNode(G, u) || isFileNode(G, v)) return;\n const relation = (data.relation as string) ?? \"\";\n if ([\"imports\", \"imports_from\", \"contains\", \"method\"].includes(relation)) return;\n\n const srcId = (data._src as string) ?? u;\n const tgtId = (data._tgt as string) ?? v;\n\n surprises.push({\n source: (G.getNodeAttribute(srcId, \"label\") as string) ?? srcId,\n target: (G.getNodeAttribute(tgtId, \"label\") as string) ?? tgtId,\n source_files: [\n (G.getNodeAttribute(srcId, \"source_file\") as string) ?? \"\",\n (G.getNodeAttribute(tgtId, \"source_file\") as string) ?? \"\",\n ],\n confidence: (data.confidence as SurpriseEntry[\"confidence\"]) ?? \"EXTRACTED\",\n relation,\n note: `Bridges community ${cidU} → community ${cidV}`,\n _pair: [Math.min(cidU, cidV), Math.max(cidU, cidV)].join(\",\"),\n });\n });\n\n const order: Record<string, number> = { AMBIGUOUS: 0, INFERRED: 1, EXTRACTED: 2 };\n surprises.sort((a, b) => (order[a.confidence] ?? 3) - (order[b.confidence] ?? 3));\n\n const seenPairs = new Set<string>();\n const deduped: SurpriseEntry[] = [];\n for (const s of surprises) {\n const pair = s._pair;\n if (!seenPairs.has(pair)) {\n seenPairs.add(pair);\n const { _pair, ...rest } = s;\n deduped.push(rest);\n }\n }\n return deduped.slice(0, topN);\n}\n\nfunction edgeBetweennessSurprises(G: Graph, topN: number): SurpriseEntry[] {\n // Approximate edge betweenness via node betweenness\n const bc = betweennessCentrality(G);\n const edgeScores: [string, string, number, Record<string, unknown>][] = [];\n\n G.forEachEdge((edge, data, u, v) => {\n const score = (bc[u] ?? 0) + (bc[v] ?? 0);\n edgeScores.push([u, v, score, data]);\n });\n\n edgeScores.sort((a, b) => b[2] - a[2]);\n\n return edgeScores.slice(0, topN).map(([u, v, score, data]) => ({\n source: (G.getNodeAttribute(u, \"label\") as string) ?? u,\n target: (G.getNodeAttribute(v, \"label\") as string) ?? v,\n source_files: [\n (G.getNodeAttribute(u, \"source_file\") as string) ?? \"\",\n (G.getNodeAttribute(v, \"source_file\") as string) ?? \"\",\n ],\n confidence: (data.confidence as SurpriseEntry[\"confidence\"]) ?? \"EXTRACTED\",\n relation: (data.relation as string) ?? \"\",\n note: `Bridges graph structure (betweenness=${score.toFixed(3)})`,\n }));\n}\n\nexport function suggestQuestions(\n G: Graph,\n communities: NumericMapLike<string[]>,\n communityLabels: NumericMapLike<string>,\n topN: number = 7,\n): SuggestedQuestion[] {\n const communityMap = toNumericMap(communities);\n const labelMap = toNumericMap(communityLabels);\n const questions: SuggestedQuestion[] = [];\n const nodeCommunity = nodeCommunityMap(communityMap);\n\n // 1. AMBIGUOUS edges\n G.forEachEdge((edge, data, u, v) => {\n if (data.confidence === \"AMBIGUOUS\") {\n const ul = (G.getNodeAttribute(u, \"label\") as string) ?? u;\n const vl = (G.getNodeAttribute(v, \"label\") as string) ?? v;\n const relation = (data.relation as string) ?? \"related to\";\n questions.push({\n type: \"ambiguous_edge\",\n question: `What is the exact relationship between \\`${ul}\\` and \\`${vl}\\`?`,\n why: `Edge tagged AMBIGUOUS (relation: ${relation}) - confidence is low.`,\n });\n }\n });\n\n // 2. Bridge nodes (high betweenness)\n if (G.size > 0) {\n const bc = betweennessCentrality(G);\n const bridges: [string, number][] = Object.entries(bc)\n .filter(([n, s]) => !isFileNode(G, n) && !isConceptNode(G, n) && (s as number) > 0)\n .sort((a, b) => (b[1] as number) - (a[1] as number))\n .slice(0, 3) as [string, number][];\n\n for (const [nodeId, score] of bridges) {\n const label = (G.getNodeAttribute(nodeId, \"label\") as string) ?? nodeId;\n const cid = nodeCommunity.get(nodeId);\n const commLabel = cid !== undefined ? (labelMap.get(cid) ?? `Community ${cid}`) : \"unknown\";\n const neighborComms = new Set<number>();\n for (const n of traversalNeighbors(G, nodeId)) {\n const nc = nodeCommunity.get(n);\n if (nc !== undefined && nc !== cid) neighborComms.add(nc);\n }\n if (neighborComms.size > 0) {\n const otherLabels = [...neighborComms].map((c) => labelMap.get(c) ?? `Community ${c}`);\n questions.push({\n type: \"bridge_node\",\n question: `Why does \\`${label}\\` connect \\`${commLabel}\\` to ${otherLabels.map((l) => `\\`${l}\\``).join(\", \")}?`,\n why: `High betweenness centrality (${score.toFixed(3)}) - this node is a cross-community bridge.`,\n });\n }\n }\n }\n\n // 3. God nodes with many INFERRED edges\n const degree: [string, number][] = [];\n G.forEachNode((n) => degree.push([n, G.degree(n)]));\n degree.sort((a, b) => b[1] - a[1]);\n const topNodes = degree.filter(([n]) => !isFileNode(G, n)).slice(0, 5);\n\n for (const [nodeId] of topNodes) {\n const inferred: string[] = [];\n G.forEachEdge(nodeId, (edge, data, source, target) => {\n if (data.confidence === \"INFERRED\") {\n const srcId = (data._src as string) ?? source;\n const tgtId = (data._tgt as string) ?? target;\n const otherId = srcId === nodeId ? tgtId : srcId;\n inferred.push((G.getNodeAttribute(otherId, \"label\") as string) ?? otherId);\n }\n });\n if (inferred.length >= 2) {\n const label = (G.getNodeAttribute(nodeId, \"label\") as string) ?? nodeId;\n questions.push({\n type: \"verify_inferred\",\n question: `Are the ${inferred.length} inferred relationships involving \\`${label}\\` (e.g. with \\`${inferred[0]}\\` and \\`${inferred[1]}\\`) actually correct?`,\n why: `\\`${label}\\` has ${inferred.length} INFERRED edges - model-reasoned connections that need verification.`,\n });\n }\n }\n\n // 4. Isolated nodes\n const isolated: string[] = [];\n G.forEachNode((n) => {\n if (G.degree(n) <= 1 && !isFileNode(G, n) && !isConceptNode(G, n)) {\n isolated.push(n);\n }\n });\n if (isolated.length > 0) {\n const labels = isolated.slice(0, 3).map((n) => (G.getNodeAttribute(n, \"label\") as string) ?? n);\n questions.push({\n type: \"isolated_nodes\",\n question: `What connects ${labels.map((l) => `\\`${l}\\``).join(\", \")} to the rest of the system?`,\n why: `${isolated.length} weakly-connected nodes found - possible documentation gaps or missing edges.`,\n });\n }\n\n // 5. Low-cohesion communities\n for (const [cid, nodes] of communityMap) {\n const score = cohesionScore(G, nodes);\n if (score < 0.15 && nodes.length >= 5) {\n const label = labelMap.get(cid) ?? `Community ${cid}`;\n questions.push({\n type: \"low_cohesion\",\n question: `Should \\`${label}\\` be split into smaller, more focused modules?`,\n why: `Cohesion score ${score} - nodes in this community are weakly interconnected.`,\n });\n }\n }\n\n if (questions.length === 0) {\n return [{\n type: \"no_signal\",\n question: null,\n why:\n \"Not enough signal to generate questions. \" +\n \"This usually means the corpus has no AMBIGUOUS edges, no bridge nodes, \" +\n \"no INFERRED relationships, and all communities are tightly cohesive. \" +\n \"Add more files or run with --mode deep to extract richer edges.\",\n }];\n }\n\n return questions.slice(0, topN);\n}\n\nexport function graphDiff(GOld: Graph, GNew: Graph): GraphDiffResult {\n const oldNodes = new Set(GOld.nodes());\n const newNodes = new Set(GNew.nodes());\n\n const addedNodeIds = [...newNodes].filter((n) => !oldNodes.has(n));\n const removedNodeIds = [...oldNodes].filter((n) => !newNodes.has(n));\n\n const newNodesList = addedNodeIds.map((n) => ({\n id: n,\n label: (GNew.getNodeAttribute(n, \"label\") as string) ?? n,\n }));\n const removedNodesList = removedNodeIds.map((n) => ({\n id: n,\n label: (GOld.getNodeAttribute(n, \"label\") as string) ?? n,\n }));\n\n function edgeKey(u: string, v: string, relation: string): string {\n return `${[u, v].sort().join(\",\")}:${relation}`;\n }\n\n const oldEdgeKeys = new Set<string>();\n GOld.forEachEdge((edge, data, u, v) => {\n oldEdgeKeys.add(edgeKey(u, v, (data.relation as string) ?? \"\"));\n });\n const newEdgeKeys = new Set<string>();\n GNew.forEachEdge((edge, data, u, v) => {\n newEdgeKeys.add(edgeKey(u, v, (data.relation as string) ?? \"\"));\n });\n\n const addedEdgeKeys = new Set([...newEdgeKeys].filter((k) => !oldEdgeKeys.has(k)));\n const removedEdgeKeys = new Set([...oldEdgeKeys].filter((k) => !newEdgeKeys.has(k)));\n\n const newEdgesList: GraphDiffResult[\"new_edges\"] = [];\n GNew.forEachEdge((edge, data, u, v) => {\n if (addedEdgeKeys.has(edgeKey(u, v, (data.relation as string) ?? \"\"))) {\n newEdgesList.push({\n source: u, target: v,\n relation: (data.relation as string) ?? \"\",\n confidence: (data.confidence as string) ?? \"\",\n });\n }\n });\n\n const removedEdgesList: GraphDiffResult[\"removed_edges\"] = [];\n GOld.forEachEdge((edge, data, u, v) => {\n if (removedEdgeKeys.has(edgeKey(u, v, (data.relation as string) ?? \"\"))) {\n removedEdgesList.push({\n source: u, target: v,\n relation: (data.relation as string) ?? \"\",\n confidence: (data.confidence as string) ?? \"\",\n });\n }\n });\n\n const parts: string[] = [];\n if (newNodesList.length > 0) parts.push(`${newNodesList.length} new node${newNodesList.length !== 1 ? \"s\" : \"\"}`);\n if (newEdgesList.length > 0) parts.push(`${newEdgesList.length} new edge${newEdgesList.length !== 1 ? \"s\" : \"\"}`);\n if (removedNodesList.length > 0) parts.push(`${removedNodesList.length} node${removedNodesList.length !== 1 ? \"s\" : \"\"} removed`);\n if (removedEdgesList.length > 0) parts.push(`${removedEdgesList.length} edge${removedEdgesList.length !== 1 ? \"s\" : \"\"} removed`);\n\n return {\n new_nodes: newNodesList,\n removed_nodes: removedNodesList,\n new_edges: newEdgesList,\n removed_edges: removedEdgesList,\n summary: parts.length > 0 ? parts.join(\", \") : \"no changes\",\n };\n}\n","export type NumericMapLike<T> = Map<number, T> | Record<number | string, T>;\nexport type StringMapLike<T> = Map<string, T> | Record<string, T>;\n\nexport function toNumericMap<T>(\n value: NumericMapLike<T> | null | undefined,\n): Map<number, T> {\n if (value instanceof Map) return value;\n\n const map = new Map<number, T>();\n if (!value) return map;\n\n for (const [key, entry] of Object.entries(value)) {\n const numericKey = Number(key);\n if (Number.isFinite(numericKey)) {\n map.set(numericKey, entry as T);\n }\n }\n\n return map;\n}\n\nexport function toStringMap<T>(\n value: StringMapLike<T> | null | undefined,\n): Map<string, T> {\n if (value instanceof Map) return value;\n\n const map = new Map<string, T>();\n if (!value) return map;\n\n for (const [key, entry] of Object.entries(value)) {\n map.set(key, entry as T);\n }\n\n return map;\n}\n","/**\n * Community detection on graphology graphs.\n * Uses Louvain (graphology-communities-louvain).\n * Splits oversized communities. Returns cohesion scores.\n */\nimport Graph from \"graphology\";\nimport louvain from \"graphology-communities-louvain\";\nimport { type NumericMapLike, toNumericMap } from \"./collections.js\";\nimport { toUndirectedGraph } from \"./graph.js\";\n\nconst MAX_COMMUNITY_FRACTION = 0.25;\nconst MIN_SPLIT_SIZE = 10;\n\nfunction partition(G: Graph): Map<string, number> {\n // louvain assigns community attribute to each node, returns mapping\n const result = louvain(G.type === \"directed\" ? toUndirectedGraph(G) : G);\n const map = new Map<string, number>();\n for (const [node, cid] of Object.entries(result)) {\n map.set(node, cid as number);\n }\n return map;\n}\n\nfunction splitCommunity(G: Graph, nodes: string[]): string[][] {\n const subgraph = G.copy();\n // Remove nodes not in this community\n const nodeSet = new Set(nodes);\n subgraph.forEachNode((n) => {\n if (!nodeSet.has(n)) subgraph.dropNode(n);\n });\n\n if (subgraph.size === 0) {\n return nodes.map((n) => [n]);\n }\n\n try {\n const subPartition = partition(subgraph);\n const subCommunities = new Map<number, string[]>();\n for (const [node, cid] of subPartition) {\n if (!subCommunities.has(cid)) subCommunities.set(cid, []);\n subCommunities.get(cid)!.push(node);\n }\n if (subCommunities.size <= 1) {\n return [[...nodes].sort()];\n }\n return [...subCommunities.values()].map((v) => [...v].sort());\n } catch {\n return [[...nodes].sort()];\n }\n}\n\nexport function cluster(G: Graph): Map<number, string[]> {\n if (G.order === 0) return new Map();\n\n if (G.size === 0) {\n const result = new Map<number, string[]>();\n const sorted = [...G.nodes()].sort();\n sorted.forEach((n, i) => result.set(i, [n]));\n return result;\n }\n\n // Handle isolates separately\n const isolates: string[] = [];\n const connectedNodes: string[] = [];\n G.forEachNode((n) => {\n if (G.degree(n) === 0) {\n isolates.push(n);\n } else {\n connectedNodes.push(n);\n }\n });\n\n const raw = new Map<number, string[]>();\n\n if (connectedNodes.length > 0) {\n // Build subgraph of connected nodes\n const connected = G.copy();\n for (const iso of isolates) {\n connected.dropNode(iso);\n }\n const partitionMap = partition(connected);\n for (const [node, cid] of partitionMap) {\n if (!raw.has(cid)) raw.set(cid, []);\n raw.get(cid)!.push(node);\n }\n }\n\n // Each isolate becomes its own single-node community\n let nextCid = Math.max(-1, ...raw.keys()) + 1;\n for (const node of isolates) {\n raw.set(nextCid, [node]);\n nextCid++;\n }\n\n // Split oversized communities\n const maxSize = Math.max(MIN_SPLIT_SIZE, Math.floor(G.order * MAX_COMMUNITY_FRACTION));\n const finalCommunities: string[][] = [];\n for (const nodes of raw.values()) {\n if (nodes.length > maxSize) {\n finalCommunities.push(...splitCommunity(G, nodes));\n } else {\n finalCommunities.push(nodes);\n }\n }\n\n // Re-index by size descending for deterministic ordering\n finalCommunities.sort((a, b) => b.length - a.length);\n const result = new Map<number, string[]>();\n finalCommunities.forEach((nodes, i) => {\n result.set(i, [...nodes].sort());\n });\n return result;\n}\n\n/** Ratio of actual intra-community edges to maximum possible. */\nexport function cohesionScore(G: Graph, communityNodes: string[]): number {\n const n = communityNodes.length;\n if (n <= 1) return 1.0;\n const nodeSet = new Set(communityNodes);\n let actual = 0;\n G.forEachEdge((edge, attrs, source, target) => {\n if (nodeSet.has(source) && nodeSet.has(target)) {\n actual++;\n }\n });\n const possible = (n * (n - 1)) / 2;\n return possible > 0 ? Math.round((actual / possible) * 100) / 100 : 0.0;\n}\n\nexport function scoreAll(\n G: Graph,\n communities: NumericMapLike<string[]>,\n): Map<number, number> {\n const communityMap = toNumericMap(communities);\n const result = new Map<number, number>();\n for (const [cid, nodes] of communityMap) {\n result.set(cid, cohesionScore(G, nodes));\n }\n return result;\n}\n","import Graph from \"graphology\";\n\nexport interface SerializedGraphData {\n directed?: boolean;\n multigraph?: boolean;\n graph?: Record<string, unknown>;\n nodes?: Array<Record<string, unknown> & { id: string }>;\n links?: Array<Record<string, unknown> & { source: string; target: string }>;\n edges?: Array<Record<string, unknown> & { source: string; target: string }>;\n hyperedges?: Array<Record<string, unknown>>;\n}\n\nexport function createGraph(directed: boolean = false): Graph {\n return new Graph({ type: directed ? \"directed\" : \"undirected\", multi: false });\n}\n\nexport function isDirectedGraph(G: Graph): boolean {\n return G.type === \"directed\";\n}\n\nexport function loadGraphFromData(raw: SerializedGraphData): Graph {\n const G = createGraph(raw.directed === true);\n\n for (const [key, value] of Object.entries(raw.graph ?? {})) {\n G.setAttribute(key, value);\n }\n\n for (const node of raw.nodes ?? []) {\n const { id, ...attrs } = node;\n G.mergeNode(id, attrs);\n }\n\n for (const link of raw.links ?? raw.edges ?? []) {\n const { source, target, ...attrs } = link;\n if (!G.hasNode(source) || !G.hasNode(target)) continue;\n try {\n G.mergeEdge(source, target, attrs);\n } catch {\n /* ignore duplicate merge failures */\n }\n }\n\n if (raw.hyperedges && raw.hyperedges.length > 0) {\n G.setAttribute(\"hyperedges\", raw.hyperedges);\n }\n\n return G;\n}\n\nexport function toUndirectedGraph(G: Graph): Graph {\n if (!isDirectedGraph(G)) return G.copy();\n\n const copy = createGraph(false);\n\n for (const [key, value] of Object.entries(G.getAttributes())) {\n copy.setAttribute(key, value);\n }\n\n G.forEachNode((nodeId, attrs) => {\n copy.mergeNode(nodeId, attrs);\n });\n\n G.forEachEdge((_edge, attrs, source, target) => {\n if (!copy.hasNode(source) || !copy.hasNode(target)) return;\n try {\n copy.mergeEdge(source, target, attrs);\n } catch {\n /* ignore duplicate merge failures */\n }\n });\n\n return copy;\n}\n\nexport function forEachTraversalNeighbor(\n G: Graph,\n node: string,\n callback: (neighbor: string) => void,\n): void {\n if (isDirectedGraph(G)) {\n G.forEachOutboundNeighbor(node, callback);\n return;\n }\n G.forEachNeighbor(node, callback);\n}\n\nexport function traversalNeighbors(G: Graph, node: string): string[] {\n const neighbors: string[] = [];\n forEachTraversalNeighbor(G, node, (neighbor) => {\n neighbors.push(neighbor);\n });\n return neighbors;\n}\n","/**\n * File discovery, type classification, and corpus health checks.\n */\nimport {\n readdirSync, readFileSync, writeFileSync, statSync, existsSync, mkdirSync, lstatSync,\n} from \"node:fs\";\nimport { join, resolve, extname, basename, relative, sep, dirname } from \"node:path\";\nimport { createHash } from \"node:crypto\";\nimport { FileType } from \"./types.js\";\nimport type { DetectionResult } from \"./types.js\";\n\nconst MANIFEST_PATH = \"graphify-out/manifest.json\";\n\nexport const CODE_EXTENSIONS = new Set([\n \".py\", \".ts\", \".js\", \".jsx\", \".tsx\", \".go\", \".rs\", \".java\", \".cpp\", \".cc\", \".cxx\",\n \".c\", \".h\", \".hpp\", \".rb\", \".swift\", \".kt\", \".kts\", \".cs\", \".scala\", \".php\",\n \".lua\", \".toc\", \".zig\", \".ps1\", \".ex\", \".exs\", \".m\", \".mm\", \".jl\",\n]);\n\nexport const DOC_EXTENSIONS = new Set([\".md\", \".txt\", \".rst\"]);\nexport const PAPER_EXTENSIONS = new Set([\".pdf\"]);\nexport const IMAGE_EXTENSIONS = new Set([\".png\", \".jpg\", \".jpeg\", \".gif\", \".webp\", \".svg\"]);\nexport const OFFICE_EXTENSIONS = new Set([\".docx\", \".xlsx\"]);\nexport const VIDEO_EXTENSIONS = new Set([\n \".mp4\", \".mov\", \".webm\", \".mkv\", \".avi\", \".m4v\", \".mp3\", \".wav\", \".m4a\", \".ogg\",\n]);\n\nconst CORPUS_WARN_THRESHOLD = 50_000;\nconst CORPUS_UPPER_THRESHOLD = 500_000;\nconst FILE_COUNT_UPPER = 200;\n\n// Sensitive file patterns\nconst SENSITIVE_PATTERNS = [\n /(^|[\\\\/])\\.(env|envrc)(\\.|$)/i,\n /\\.(pem|key|p12|pfx|cert|crt|der|p8)$/i,\n /(credential|secret|passwd|password|token|private_key)/i,\n /(id_rsa|id_dsa|id_ecdsa|id_ed25519)(\\.pub)?$/,\n /(\\.netrc|\\.pgpass|\\.htpasswd)$/i,\n /(aws_credentials|gcloud_credentials|service.account)/i,\n];\n\n// Academic paper signals\nconst PAPER_SIGNALS = [\n /\\barxiv\\b/i, /\\bdoi\\s*:/i, /\\babstract\\b/i, /\\bproceedings\\b/i,\n /\\bjournal\\b/i, /\\bpreprint\\b/i, /\\\\cite\\{/, /\\[\\d+\\]/, /\\[\\n\\d+\\n\\]/,\n /eq\\.\\s*\\d+|equation\\s+\\d+/i, /\\d{4}\\.\\d{4,5}/, /\\bwe propose\\b/i, /\\bliterature\\b/i,\n];\nconst PAPER_SIGNAL_THRESHOLD = 3;\n\nfunction isSensitive(filePath: string): boolean {\n const name = basename(filePath);\n return SENSITIVE_PATTERNS.some((p) => p.test(name) || p.test(filePath));\n}\n\nfunction looksLikePaper(filePath: string): boolean {\n try {\n const text = readFileSync(filePath, \"utf-8\").slice(0, 3000);\n const hits = PAPER_SIGNALS.filter((p) => p.test(text)).length;\n return hits >= PAPER_SIGNAL_THRESHOLD;\n } catch {\n return false;\n }\n}\n\nconst ASSET_DIR_MARKERS = new Set([\".imageset\", \".xcassets\", \".appiconset\", \".colorset\", \".launchimage\"]);\n\nexport function classifyFile(filePath: string): FileType | null {\n const ext = extname(filePath).toLowerCase();\n if (CODE_EXTENSIONS.has(ext)) return FileType.CODE;\n if (PAPER_EXTENSIONS.has(ext)) {\n // PDFs inside Xcode asset catalogs are vector icons, not papers\n const parts = filePath.split(sep);\n if (parts.some((p) => [...ASSET_DIR_MARKERS].some((m) => p.endsWith(m)))) return null;\n return FileType.PAPER;\n }\n if (IMAGE_EXTENSIONS.has(ext)) return FileType.IMAGE;\n if (VIDEO_EXTENSIONS.has(ext)) return FileType.VIDEO;\n if (DOC_EXTENSIONS.has(ext)) {\n if (looksLikePaper(filePath)) return FileType.PAPER;\n return FileType.DOCUMENT;\n }\n if (OFFICE_EXTENSIONS.has(ext)) return FileType.DOCUMENT;\n return null;\n}\n\n/** Extract plain text from a PDF file using pdf-parse. */\nexport async function extractPdfText(filePath: string): Promise<string> {\n try {\n const pdfParse = (await import(\"pdf-parse\")).default;\n const buf = readFileSync(filePath);\n const data = await pdfParse(buf);\n return data.text;\n } catch {\n return \"\";\n }\n}\n\n/** Convert a .docx file to markdown text using mammoth. */\nexport async function docxToMarkdown(filePath: string): Promise<string> {\n try {\n const mammoth = await import(\"mammoth\");\n const result = await mammoth.convertToHtml({ path: filePath });\n // mammoth produces HTML; strip tags for a simple text fallback\n return result.value.replace(/<[^>]+>/g, \" \").replace(/\\s+/g, \" \").trim();\n } catch {\n return \"\";\n }\n}\n\n/** Convert an .xlsx file to markdown text using exceljs. */\nexport async function xlsxToMarkdown(filePath: string): Promise<string> {\n try {\n const ExcelJS = await import(\"exceljs\");\n const wb = new ExcelJS.Workbook();\n await wb.xlsx.readFile(filePath);\n const sections: string[] = [];\n wb.eachSheet((ws) => {\n const rows: string[][] = [];\n ws.eachRow((row) => {\n const cells = (row.values as unknown[]).slice(1).map((v) => (v != null ? String(v) : \"\"));\n rows.push(cells);\n });\n if (rows.length === 0) return;\n sections.push(`## Sheet: ${ws.name}`);\n const header = \"| \" + rows[0]!.join(\" | \") + \" |\";\n const sep = \"| \" + rows[0]!.map(() => \"---\").join(\" | \") + \" |\";\n sections.push(header, sep);\n for (const row of rows.slice(1)) {\n sections.push(\"| \" + row.join(\" | \") + \" |\");\n }\n });\n return sections.join(\"\\n\");\n } catch {\n return \"\";\n }\n}\n\n/** Convert .docx/.xlsx to a markdown sidecar file. */\nexport async function convertOfficeFile(filePath: string, outDir: string): Promise<string | null> {\n const ext = extname(filePath).toLowerCase();\n let text: string;\n if (ext === \".docx\") {\n text = await docxToMarkdown(filePath);\n } else if (ext === \".xlsx\") {\n text = await xlsxToMarkdown(filePath);\n } else {\n return null;\n }\n\n if (!text.trim()) return null;\n\n mkdirSync(outDir, { recursive: true });\n const nameHash = createHash(\"sha256\").update(resolve(filePath)).digest(\"hex\").slice(0, 8);\n const stem = basename(filePath, extname(filePath));\n const outPath = join(outDir, `${stem}_${nameHash}.md`);\n writeFileSync(outPath, `<!-- converted from ${basename(filePath)} -->\\n\\n${text}`, \"utf-8\");\n return outPath;\n}\n\nfunction countWords(filePath: string): number {\n try {\n const text = readFileSync(filePath, \"utf-8\");\n return text.split(/\\s+/).filter(Boolean).length;\n } catch {\n return 0;\n }\n}\n\n// Directory names to always skip\nconst SKIP_DIRS = new Set([\n \"venv\", \".venv\", \"env\", \".env\", \"node_modules\", \"__pycache__\", \".git\",\n \"dist\", \"build\", \"target\", \"out\", \"site-packages\", \"lib64\",\n \".pytest_cache\", \".mypy_cache\", \".ruff_cache\", \".tox\", \".eggs\",\n]);\n\nfunction isNoiseDir(part: string): boolean {\n if (SKIP_DIRS.has(part)) return true;\n if (part.endsWith(\"_venv\") || part.endsWith(\"_env\")) return true;\n if (part.endsWith(\".egg-info\")) return true;\n return false;\n}\n\nfunction loadGraphifyignore(root: string): string[] {\n const patterns: string[] = [];\n let current = resolve(root);\n\n while (true) {\n const ignoreFile = join(current, \".graphifyignore\");\n if (existsSync(ignoreFile)) {\n for (let line of readFileSync(ignoreFile, \"utf-8\").split(\"\\n\")) {\n line = line.trim();\n if (line && !line.startsWith(\"#\")) {\n patterns.push(line);\n }\n }\n }\n\n if (existsSync(join(current, \".git\"))) {\n break;\n }\n\n const parent = dirname(current);\n if (parent === current) {\n break;\n }\n current = parent;\n }\n return patterns;\n}\n\nfunction matchGlob(text: string, pattern: string): boolean {\n // Simple glob matching (*, ?)\n const regex = pattern\n .replace(/[.+^${}()|[\\]\\\\]/g, \"\\\\$&\")\n .replace(/\\*/g, \".*\")\n .replace(/\\?/g, \".\");\n return new RegExp(`^${regex}$`).test(text);\n}\n\nfunction isIgnored(filePath: string, root: string, patterns: string[]): boolean {\n if (patterns.length === 0) return false;\n let rel: string;\n try {\n rel = relative(root, filePath).replace(/\\\\/g, \"/\");\n } catch {\n return false;\n }\n const parts = rel.split(\"/\");\n for (const pattern of patterns) {\n const p = pattern.replace(/^\\/+|\\/+$/g, \"\");\n if (!p) continue;\n if (matchGlob(rel, p)) return true;\n if (matchGlob(basename(filePath), p)) return true;\n for (let i = 0; i < parts.length; i++) {\n if (matchGlob(parts[i]!, p)) return true;\n if (matchGlob(parts.slice(0, i + 1).join(\"/\"), p)) return true;\n }\n }\n return false;\n}\n\nfunction walkDir(\n dir: string,\n root: string,\n ignorePatterns: string[],\n followSymlinks: boolean,\n skipPrune: boolean,\n): string[] {\n const result: string[] = [];\n let entries: string[];\n try {\n entries = readdirSync(dir);\n } catch {\n return result;\n }\n\n for (const entry of entries) {\n const full = join(dir, entry);\n let stat;\n try {\n stat = followSymlinks ? statSync(full) : lstatSync(full);\n } catch {\n continue;\n }\n\n if (stat.isDirectory()) {\n if (!skipPrune) {\n if (entry.startsWith(\".\")) continue;\n if (isNoiseDir(entry)) continue;\n if (isIgnored(full, root, ignorePatterns)) continue;\n }\n result.push(...walkDir(full, root, ignorePatterns, followSymlinks, skipPrune));\n } else if (stat.isFile()) {\n result.push(full);\n }\n }\n\n return result;\n}\n\nexport function detect(root: string, options?: { followSymlinks?: boolean }): DetectionResult {\n const followSymlinks = options?.followSymlinks ?? false;\n const rootResolved = resolve(root);\n const ignorePatterns = loadGraphifyignore(rootResolved);\n const convertedDir = join(rootResolved, \"graphify-out\", \"converted\");\n const memoryDir = join(rootResolved, \"graphify-out\", \"memory\");\n\n const files: Record<string, string[]> = {\n code: [], document: [], paper: [], image: [], video: [],\n };\n let totalWords = 0;\n const skippedSensitive: string[] = [];\n\n // Walk main tree\n const allFiles = walkDir(rootResolved, rootResolved, ignorePatterns, followSymlinks, false);\n\n // Also walk memory dir if it exists\n if (existsSync(memoryDir)) {\n allFiles.push(...walkDir(memoryDir, rootResolved, ignorePatterns, followSymlinks, true));\n }\n\n const seen = new Set<string>();\n\n for (const p of allFiles) {\n if (seen.has(p)) continue;\n seen.add(p);\n\n const inMemory = existsSync(memoryDir) && p.startsWith(memoryDir);\n if (!inMemory) {\n if (basename(p).startsWith(\".\")) continue;\n if (p.startsWith(convertedDir)) continue;\n }\n if (isIgnored(p, rootResolved, ignorePatterns)) continue;\n if (isSensitive(p)) {\n skippedSensitive.push(p);\n continue;\n }\n\n const ftype = classifyFile(p);\n if (!ftype) continue;\n\n // Office files: convert to markdown sidecar\n if (OFFICE_EXTENSIONS.has(extname(p).toLowerCase())) {\n // Note: office conversion is async but detect is sync.\n // We skip office files in sync detect; they're handled in the async pipeline.\n skippedSensitive.push(p + \" [office conversion requires async - use pipeline]\");\n continue;\n }\n\n files[ftype]!.push(p);\n if (ftype !== FileType.VIDEO) {\n totalWords += countWords(p);\n }\n }\n\n const totalFiles = Object.values(files).reduce((s, v) => s + v.length, 0);\n const needsGraph = totalWords >= CORPUS_WARN_THRESHOLD;\n\n let warning: string | null = null;\n if (!needsGraph) {\n warning = `Corpus is ~${totalWords.toLocaleString()} words - fits in a single context window. You may not need a graph.`;\n } else if (totalWords >= CORPUS_UPPER_THRESHOLD || totalFiles >= FILE_COUNT_UPPER) {\n warning =\n `Large corpus: ${totalFiles} files · ~${totalWords.toLocaleString()} words. ` +\n `Semantic extraction will be expensive (many Claude tokens). ` +\n `Consider running on a subfolder, or use --no-semantic to run AST-only.`;\n }\n\n return {\n files,\n total_files: totalFiles,\n total_words: totalWords,\n needs_graph: needsGraph,\n warning,\n skipped_sensitive: skippedSensitive,\n graphifyignore_patterns: ignorePatterns.length,\n };\n}\n\nexport function loadManifest(manifestPath: string = MANIFEST_PATH): Record<string, number> {\n try {\n return JSON.parse(readFileSync(manifestPath, \"utf-8\")) as Record<string, number>;\n } catch {\n return {};\n }\n}\n\nexport function saveManifest(files: Record<string, string[]>, manifestPath: string = MANIFEST_PATH): void {\n const manifest: Record<string, number> = {};\n for (const fileList of Object.values(files)) {\n for (const f of fileList) {\n try {\n manifest[f] = statSync(f).mtimeMs;\n } catch { /* deleted between detect and save */ }\n }\n }\n const dir = join(manifestPath, \"..\");\n mkdirSync(dir, { recursive: true });\n writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));\n}\n\nexport function detectIncremental(root: string, manifestPath: string = MANIFEST_PATH): DetectionResult {\n const full = detect(root);\n const manifest = loadManifest(manifestPath);\n\n if (Object.keys(manifest).length === 0) {\n return {\n ...full,\n incremental: true,\n new_files: full.files,\n unchanged_files: Object.fromEntries(Object.keys(full.files).map((k) => [k, []])),\n new_total: full.total_files,\n };\n }\n\n const newFiles: Record<string, string[]> = {};\n const unchangedFiles: Record<string, string[]> = {};\n for (const k of Object.keys(full.files)) {\n newFiles[k] = [];\n unchangedFiles[k] = [];\n }\n\n for (const [ftype, fileList] of Object.entries(full.files)) {\n for (const f of fileList) {\n const storedMtime = manifest[f];\n let currentMtime = 0;\n try { currentMtime = statSync(f).mtimeMs; } catch { /* ignore */ }\n if (storedMtime === undefined || currentMtime > storedMtime) {\n newFiles[ftype]!.push(f);\n } else {\n unchangedFiles[ftype]!.push(f);\n }\n }\n }\n\n const currentFiles = new Set(Object.values(full.files).flat());\n const deletedFiles = Object.keys(manifest).filter((f) => !currentFiles.has(f));\n const newTotal = Object.values(newFiles).reduce((s, v) => s + v.length, 0);\n\n return {\n ...full,\n incremental: true,\n new_files: newFiles,\n unchanged_files: unchangedFiles,\n new_total: newTotal,\n deleted_files: deletedFiles,\n };\n}\n","/**\n * Token-reduction benchmark - measures how much context graphify saves vs naive full-corpus approach.\n */\nimport { readFileSync, existsSync } from \"node:fs\";\nimport Graph from \"graphology\";\nimport { forEachTraversalNeighbor, loadGraphFromData, type SerializedGraphData } from \"./graph.js\";\nimport type { BenchmarkResult } from \"./types.js\";\n\nconst CHARS_PER_TOKEN = 4;\n\nfunction estimateTokens(text: string): number {\n return Math.max(1, Math.floor(text.length / CHARS_PER_TOKEN));\n}\n\nfunction querySubgraphTokens(G: Graph, question: string, depth: number = 3): number {\n const terms = question.toLowerCase().split(/\\s+/).filter((t) => t.length > 2);\n const scored: [number, string][] = [];\n G.forEachNode((nid, data) => {\n const label = ((data.label as string) ?? \"\").toLowerCase();\n const score = terms.filter((t) => label.includes(t)).length;\n if (score > 0) scored.push([score, nid]);\n });\n scored.sort((a, b) => b[0] - a[0]);\n const startNodes = scored.slice(0, 3).map(([, nid]) => nid);\n if (startNodes.length === 0) return 0;\n\n const visited = new Set(startNodes);\n let frontier = new Set(startNodes);\n const edgesSeen: [string, string][] = [];\n\n for (let d = 0; d < depth; d++) {\n const nextFrontier = new Set<string>();\n for (const n of frontier) {\n forEachTraversalNeighbor(G, n, (neighbor) => {\n if (!visited.has(neighbor)) {\n nextFrontier.add(neighbor);\n edgesSeen.push([n, neighbor]);\n }\n });\n }\n for (const n of nextFrontier) visited.add(n);\n frontier = nextFrontier;\n }\n\n const lines: string[] = [];\n for (const nid of visited) {\n const d = G.getNodeAttributes(nid);\n lines.push(`NODE ${d.label ?? nid} src=${d.source_file ?? \"\"} loc=${d.source_location ?? \"\"}`);\n }\n for (const [u, v] of edgesSeen) {\n if (visited.has(u) && visited.has(v)) {\n const edge = G.edge(u, v);\n if (edge) {\n const d = G.getEdgeAttributes(edge);\n lines.push(`EDGE ${G.getNodeAttribute(u, \"label\") ?? u} --${d.relation ?? \"\"}--> ${G.getNodeAttribute(v, \"label\") ?? v}`);\n }\n }\n }\n\n return estimateTokens(lines.join(\"\\n\"));\n}\n\nconst SAMPLE_QUESTIONS = [\n \"how does authentication work\",\n \"what is the main entry point\",\n \"how are errors handled\",\n \"what connects the data layer to the api\",\n \"what are the core abstractions\",\n];\n\ninterface BenchmarkOptions {\n corpusWords?: number;\n questions?: string[];\n}\n\nfunction loadGraph(graphPath: string): Graph {\n const raw = JSON.parse(readFileSync(graphPath, \"utf-8\")) as SerializedGraphData;\n return loadGraphFromData(raw);\n}\n\nexport function runBenchmark(\n graphPath: string = \"graphify-out/graph.json\",\n corpusWordsOrOptions?: number | BenchmarkOptions,\n questions?: string[],\n): BenchmarkResult {\n const options = typeof corpusWordsOrOptions === \"number\"\n ? { corpusWords: corpusWordsOrOptions, questions }\n : (corpusWordsOrOptions ?? {});\n\n if (!existsSync(graphPath)) {\n return { error: `Graph file not found: ${graphPath}. Build the graph first.` };\n }\n\n const G = loadGraph(graphPath);\n\n const corpusWords = options.corpusWords ?? (G.order * 50);\n\n if (corpusWords === undefined) {\n return { error: \"Could not determine corpus size.\" };\n }\n\n const corpusTokens = Math.floor((corpusWords * 100) / 75);\n const qs = options.questions ?? SAMPLE_QUESTIONS;\n const perQuestion: Array<{ question: string; query_tokens: number; reduction: number }> = [];\n\n for (const q of qs) {\n const qt = querySubgraphTokens(G, q);\n if (qt > 0) {\n perQuestion.push({\n question: q,\n query_tokens: qt,\n reduction: Math.round((corpusTokens / qt) * 10) / 10,\n });\n }\n }\n\n if (perQuestion.length === 0) {\n return { error: \"No matching nodes found for sample questions. Build the graph first.\" };\n }\n\n const avgQueryTokens = Math.floor(\n perQuestion.reduce((s, p) => s + p.query_tokens, 0) / perQuestion.length,\n );\n const reductionRatio = avgQueryTokens > 0 ? Math.round((corpusTokens / avgQueryTokens) * 10) / 10 : 0;\n\n return {\n corpus_tokens: corpusTokens,\n corpus_words: corpusWords,\n nodes: G.order,\n edges: G.size,\n avg_query_tokens: avgQueryTokens,\n reduction_ratio: reductionRatio,\n per_question: perQuestion,\n };\n}\n\nexport function printBenchmark(result: BenchmarkResult): void {\n if (result.error) {\n console.log(`Benchmark error: ${result.error}`);\n return;\n }\n\n console.log(`\\ngraphify token reduction benchmark`);\n console.log(\"─\".repeat(50));\n console.log(` Corpus: ${result.corpus_words!.toLocaleString()} words → ~${result.corpus_tokens!.toLocaleString()} tokens (naive)`);\n console.log(` Graph: ${result.nodes!.toLocaleString()} nodes, ${result.edges!.toLocaleString()} edges`);\n console.log(` Avg query cost: ~${result.avg_query_tokens!.toLocaleString()} tokens`);\n console.log(` Reduction: ${result.reduction_ratio}x fewer tokens per query`);\n console.log(`\\n Per question:`);\n for (const p of result.per_question!) {\n console.log(` [${p.reduction}x] ${p.question.slice(0, 55)}`);\n }\n console.log();\n}\n","/**\n * Per-file extraction cache - skip unchanged files on re-run.\n */\nimport { createHash } from \"node:crypto\";\nimport { readFileSync, writeFileSync, mkdirSync, readdirSync, unlinkSync, renameSync, existsSync } from \"node:fs\";\nimport { extname, join, resolve } from \"node:path\";\n\nfunction bodyContent(content: Buffer): Buffer {\n const text = content.toString(\"utf-8\");\n if (!text.startsWith(\"---\")) {\n return content;\n }\n const end = text.indexOf(\"\\n---\", 3);\n if (end === -1) {\n return content;\n }\n return Buffer.from(text.slice(end + 4), \"utf-8\");\n}\n\n/**\n * SHA256 of file contents + resolved path. Prevents cache collisions on identical content.\n *\n * For Markdown files, YAML frontmatter is stripped before hashing so metadata-only\n * changes do not invalidate semantic extraction cache entries.\n */\nexport function fileHash(filePath: string): string {\n const raw = readFileSync(filePath);\n const content = extname(filePath).toLowerCase() === \".md\" ? bodyContent(raw) : raw;\n const resolved = resolve(filePath);\n const h = createHash(\"sha256\");\n h.update(content);\n h.update(\"\\0\");\n h.update(resolved);\n return h.digest(\"hex\");\n}\n\n/** Returns graphify-out/cache/ path - creates it if needed. */\nexport function cacheDir(root: string = \".\"): string {\n const d = join(root, \"graphify-out\", \"cache\");\n mkdirSync(d, { recursive: true });\n return d;\n}\n\n/**\n * Return cached extraction for this file if hash matches, else null.\n */\nexport function loadCached(filePath: string, root: string = \".\"): Record<string, unknown> | null {\n let h: string;\n try {\n h = fileHash(filePath);\n } catch {\n return null;\n }\n const entry = join(cacheDir(root), `${h}.json`);\n if (!existsSync(entry)) return null;\n try {\n return JSON.parse(readFileSync(entry, \"utf-8\")) as Record<string, unknown>;\n } catch {\n return null;\n }\n}\n\n/** Save extraction result for this file. */\nexport function saveCached(filePath: string, result: Record<string, unknown>, root: string = \".\"): void {\n const h = fileHash(filePath);\n const entry = join(cacheDir(root), `${h}.json`);\n const tmp = entry + \".tmp\";\n try {\n writeFileSync(tmp, JSON.stringify(result));\n renameSync(tmp, entry);\n } catch {\n try { unlinkSync(tmp); } catch { /* ignore */ }\n throw new Error(`Failed to save cache for ${filePath}`);\n }\n}\n\n/** Return set of file hashes that have a valid cache entry. */\nexport function cachedFiles(root: string = \".\"): Set<string> {\n const d = cacheDir(root);\n const result = new Set<string>();\n try {\n for (const f of readdirSync(d)) {\n if (f.endsWith(\".json\")) {\n result.add(f.replace(\".json\", \"\"));\n }\n }\n } catch { /* ignore */ }\n return result;\n}\n\n/** Delete all graphify-out/cache/*.json files. */\nexport function clearCache(root: string = \".\"): void {\n const d = cacheDir(root);\n try {\n for (const f of readdirSync(d)) {\n if (f.endsWith(\".json\")) {\n unlinkSync(join(d, f));\n }\n }\n } catch { /* ignore */ }\n}\n\ninterface ExtractionPart {\n nodes: Array<Record<string, unknown>>;\n edges: Array<Record<string, unknown>>;\n hyperedges: Array<Record<string, unknown>>;\n}\n\n/**\n * Check semantic extraction cache for a list of file paths.\n * Returns [cachedNodes, cachedEdges, cachedHyperedges, uncachedFiles].\n */\nexport function checkSemanticCache(\n files: string[],\n root: string = \".\",\n): [Array<Record<string, unknown>>, Array<Record<string, unknown>>, Array<Record<string, unknown>>, string[]] {\n const cachedNodes: Array<Record<string, unknown>> = [];\n const cachedEdges: Array<Record<string, unknown>> = [];\n const cachedHyperedges: Array<Record<string, unknown>> = [];\n const uncached: string[] = [];\n\n for (const fpath of files) {\n const result = loadCached(fpath, root);\n if (result !== null) {\n const r = result as unknown as ExtractionPart;\n cachedNodes.push(...(r.nodes ?? []));\n cachedEdges.push(...(r.edges ?? []));\n cachedHyperedges.push(...(r.hyperedges ?? []));\n } else {\n uncached.push(fpath);\n }\n }\n\n return [cachedNodes, cachedEdges, cachedHyperedges, uncached];\n}\n\n/**\n * Save semantic extraction results to cache, keyed by source_file.\n * Returns the number of files cached.\n */\nexport function saveSemanticCache(\n nodes: Array<Record<string, unknown>>,\n edges: Array<Record<string, unknown>>,\n hyperedges: Array<Record<string, unknown>> | null = null,\n root: string = \".\",\n): number {\n const byFile = new Map<string, ExtractionPart>();\n\n for (const n of nodes) {\n const src = (n.source_file as string) ?? \"\";\n if (!src) continue;\n if (!byFile.has(src)) byFile.set(src, { nodes: [], edges: [], hyperedges: [] });\n byFile.get(src)!.nodes.push(n);\n }\n for (const e of edges) {\n const src = (e.source_file as string) ?? \"\";\n if (!src) continue;\n if (!byFile.has(src)) byFile.set(src, { nodes: [], edges: [], hyperedges: [] });\n byFile.get(src)!.edges.push(e);\n }\n for (const h of hyperedges ?? []) {\n const src = (h.source_file as string) ?? \"\";\n if (!src) continue;\n if (!byFile.has(src)) byFile.set(src, { nodes: [], edges: [], hyperedges: [] });\n byFile.get(src)!.hyperedges.push(h);\n }\n\n let saved = 0;\n for (const [fpath, result] of byFile) {\n const p = resolve(root, fpath);\n if (existsSync(p)) {\n saveCached(p, result as unknown as Record<string, unknown>, root);\n saved++;\n }\n }\n return saved;\n}\n","/**\n * Validate extraction JSON against the graphify schema before graph assembly.\n */\n\nexport const VALID_FILE_TYPES = new Set([\"code\", \"document\", \"paper\", \"image\", \"rationale\"]);\nexport const VALID_CONFIDENCES = new Set([\"EXTRACTED\", \"INFERRED\", \"AMBIGUOUS\"]);\nexport const REQUIRED_NODE_FIELDS = [\"id\", \"label\", \"file_type\", \"source_file\"] as const;\nexport const REQUIRED_EDGE_FIELDS = [\"source\", \"target\", \"relation\", \"confidence\", \"source_file\"] as const;\n\n/**\n * Validate an extraction JSON dict against the graphify schema.\n * Returns a list of error strings - empty list means valid.\n */\nexport function validateExtraction(data: unknown): string[] {\n if (typeof data !== \"object\" || data === null || Array.isArray(data)) {\n return [\"Extraction must be a JSON object\"];\n }\n\n const d = data as Record<string, unknown>;\n const errors: string[] = [];\n\n // Nodes\n if (!(\"nodes\" in d)) {\n errors.push(\"Missing required key 'nodes'\");\n } else if (!Array.isArray(d.nodes)) {\n errors.push(\"'nodes' must be a list\");\n } else {\n for (let i = 0; i < d.nodes.length; i++) {\n const node = d.nodes[i] as Record<string, unknown>;\n if (typeof node !== \"object\" || node === null || Array.isArray(node)) {\n errors.push(`Node ${i} must be an object`);\n continue;\n }\n for (const field of REQUIRED_NODE_FIELDS) {\n if (!(field in node)) {\n errors.push(\n `Node ${i} (id=${JSON.stringify(node.id ?? \"?\")}) missing required field '${field}'`,\n );\n }\n }\n if (\"file_type\" in node && !VALID_FILE_TYPES.has(node.file_type as string)) {\n errors.push(\n `Node ${i} (id=${JSON.stringify(node.id ?? \"?\")}) has invalid file_type ` +\n `'${node.file_type}' - must be one of ${JSON.stringify([...VALID_FILE_TYPES].sort())}`,\n );\n }\n }\n }\n\n // Edges\n if (!(\"edges\" in d)) {\n errors.push(\"Missing required key 'edges'\");\n } else if (!Array.isArray(d.edges)) {\n errors.push(\"'edges' must be a list\");\n } else {\n const nodeIds = new Set<string>();\n if (Array.isArray(d.nodes)) {\n for (const n of d.nodes) {\n if (typeof n === \"object\" && n !== null && \"id\" in n) {\n nodeIds.add((n as Record<string, unknown>).id as string);\n }\n }\n }\n\n for (let i = 0; i < d.edges.length; i++) {\n const edge = d.edges[i] as Record<string, unknown>;\n if (typeof edge !== \"object\" || edge === null || Array.isArray(edge)) {\n errors.push(`Edge ${i} must be an object`);\n continue;\n }\n for (const field of REQUIRED_EDGE_FIELDS) {\n if (!(field in edge)) {\n errors.push(`Edge ${i} missing required field '${field}'`);\n }\n }\n if (\"confidence\" in edge && !VALID_CONFIDENCES.has(edge.confidence as string)) {\n errors.push(\n `Edge ${i} has invalid confidence '${edge.confidence}' ` +\n `- must be one of ${JSON.stringify([...VALID_CONFIDENCES].sort())}`,\n );\n }\n if (\"source\" in edge && nodeIds.size > 0 && !nodeIds.has(edge.source as string)) {\n errors.push(`Edge ${i} source '${edge.source}' does not match any node id`);\n }\n if (\"target\" in edge && nodeIds.size > 0 && !nodeIds.has(edge.target as string)) {\n errors.push(`Edge ${i} target '${edge.target}' does not match any node id`);\n }\n }\n }\n\n return errors;\n}\n\n/** Raise an error with all validation errors if extraction is invalid. */\nexport function assertValid(data: unknown): void {\n const errors = validateExtraction(data);\n if (errors.length > 0) {\n const msg =\n `Extraction JSON has ${errors.length} error(s):\\n` +\n errors.map((e) => ` • ${e}`).join(\"\\n\");\n throw new Error(msg);\n }\n}\n","/**\n * Assemble node+edge dicts into a graphology Graph, preserving edge direction.\n *\n * Node deduplication — three layers:\n *\n * 1. Within a file (AST): each extractor tracks a `seenIds` set.\n * 2. Between files (build): graphology mergeNode is idempotent — last write wins.\n * 3. Semantic merge (skill): before calling build(), the skill merges results\n * using an explicit `seen` set keyed on node.id.\n */\nimport Graph from \"graphology\";\nimport type { Extraction } from \"./types.js\";\nimport { createGraph } from \"./graph.js\";\nimport { validateExtraction } from \"./validate.js\";\n\nexport interface BuildOptions {\n directed?: boolean;\n}\n\nexport function buildFromJson(extraction: Extraction, options?: BuildOptions): Graph {\n const errors = validateExtraction(extraction);\n // Dangling edges (stdlib/external imports) are expected - only warn about real schema errors.\n const realErrors = errors.filter((e) => !e.includes(\"does not match any node id\"));\n if (realErrors.length > 0) {\n console.error(\n `[graphify] Extraction warning (${realErrors.length} issues): ${realErrors[0]}`,\n );\n }\n\n const G = createGraph(options?.directed === true);\n\n for (const node of extraction.nodes ?? []) {\n const { id, ...attrs } = node;\n G.mergeNode(id, attrs);\n }\n\n const nodeSet = new Set(G.nodes());\n\n for (const edge of extraction.edges ?? []) {\n const { source, target, ...attrs } = edge;\n if (!nodeSet.has(source) || !nodeSet.has(target)) continue;\n // Preserve original edge direction\n attrs._src = source;\n attrs._tgt = target;\n // graphology mergeEdge prevents duplicates on same src/tgt pair\n try {\n G.mergeEdge(source, target, attrs);\n } catch {\n // ignore if edge already exists with different key\n }\n }\n\n const hyperedges = extraction.hyperedges ?? [];\n if (hyperedges.length > 0) {\n G.setAttribute(\"hyperedges\", hyperedges);\n }\n\n return G;\n}\n\n/**\n * Merge multiple extraction results into one graph.\n * Extractions are merged in order — last attributes win for duplicate node IDs.\n */\nexport function build(extractions: Extraction[], options?: BuildOptions): Graph {\n const combined: Extraction = {\n nodes: [],\n edges: [],\n hyperedges: [],\n input_tokens: 0,\n output_tokens: 0,\n };\n for (const ext of extractions) {\n combined.nodes.push(...(ext.nodes ?? []));\n combined.edges.push(...(ext.edges ?? []));\n (combined.hyperedges ??= []).push(...(ext.hyperedges ?? []));\n combined.input_tokens += ext.input_tokens ?? 0;\n combined.output_tokens += ext.output_tokens ?? 0;\n }\n return buildFromJson(combined, options);\n}\n","/**\n * Export graph to HTML, JSON, SVG, GraphML, Obsidian Canvas, and Neo4j Cypher.\n */\nimport { writeFileSync } from \"node:fs\";\nimport Graph from \"graphology\";\nimport { sanitizeLabel, escapeHtml } from \"./security.js\";\nimport { isDirectedGraph } from \"./graph.js\";\nimport type { Hyperedge } from \"./types.js\";\nimport {\n type NumericMapLike,\n type StringMapLike,\n toNumericMap,\n toStringMap,\n} from \"./collections.js\";\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nconst COMMUNITY_COLORS = [\n \"#4E79A7\", \"#F28E2B\", \"#E15759\", \"#76B7B2\", \"#59A14F\",\n \"#EDC948\", \"#B07AA1\", \"#FF9DA7\", \"#9C755F\", \"#BAB0AC\",\n];\n\nconst MAX_NODES_FOR_VIZ = 5_000;\n\nconst CONFIDENCE_SCORE_DEFAULTS: Record<string, number> = {\n EXTRACTED: 1.0,\n INFERRED: 0.5,\n AMBIGUOUS: 0.2,\n};\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\ntype CommunityLabelsInput = NumericMapLike<string>;\ntype CommunityLabelOptions = { communityLabels?: CommunityLabelsInput };\ntype JsonOptions = CommunityLabelOptions;\ntype SvgOptions = CommunityLabelOptions & { figsize?: [number, number] };\ntype CanvasOptions = CommunityLabelOptions & { nodeFilenames?: StringMapLike<string> };\ntype Neo4jPushOptions = {\n uri: string;\n user: string;\n password: string;\n communities?: NumericMapLike<string[]>;\n};\n\nfunction nodeCommunityMap(communities: NumericMapLike<string[]>): Map<string, number> {\n const communityMap = toNumericMap(communities);\n const result = new Map<string, number>();\n for (const [cid, nodes] of communityMap) {\n for (const n of nodes) result.set(n, cid);\n }\n return result;\n}\n\nfunction cypherEscape(s: string): string {\n return s.replace(/\\\\/g, \"\\\\\\\\\").replace(/'/g, \"\\\\'\");\n}\n\nfunction isCommunityLabelOptions(\n value: CommunityLabelsInput | CommunityLabelOptions,\n): value is CommunityLabelOptions {\n return !(value instanceof Map) && Object.prototype.hasOwnProperty.call(value, \"communityLabels\");\n}\n\nfunction isCanvasOptions(\n value: CommunityLabelsInput | CanvasOptions,\n): value is CanvasOptions {\n return !(value instanceof Map) && (\n Object.prototype.hasOwnProperty.call(value, \"communityLabels\") ||\n Object.prototype.hasOwnProperty.call(value, \"nodeFilenames\")\n );\n}\n\nfunction isSvgOptions(\n value: CommunityLabelsInput | SvgOptions,\n): value is SvgOptions {\n return !(value instanceof Map) && (\n Object.prototype.hasOwnProperty.call(value, \"communityLabels\") ||\n Object.prototype.hasOwnProperty.call(value, \"figsize\")\n );\n}\n\nfunction normalizeCommunityLabels(\n labelsOrOptions?: CommunityLabelsInput | CommunityLabelOptions,\n): Map<number, string> | undefined {\n if (!labelsOrOptions) return undefined;\n if (!isCommunityLabelOptions(labelsOrOptions)) {\n return toNumericMap(labelsOrOptions as CommunityLabelsInput);\n }\n return toNumericMap(labelsOrOptions.communityLabels);\n}\n\n// ---------------------------------------------------------------------------\n// toJson\n// ---------------------------------------------------------------------------\n\nexport function toJson(\n G: Graph,\n communities: NumericMapLike<string[]>,\n outputPath: string,\n communityLabelsOrOptions?: CommunityLabelsInput | JsonOptions,\n): void {\n const nodeComm = nodeCommunityMap(communities);\n const communityLabels = normalizeCommunityLabels(communityLabelsOrOptions);\n\n const nodes: Record<string, unknown>[] = [];\n G.forEachNode((nodeId, attrs) => {\n const communityId = nodeComm.get(nodeId) ?? null;\n nodes.push({\n id: nodeId,\n ...attrs,\n community: communityId,\n community_name:\n communityId !== null\n ? sanitizeLabel(communityLabels?.get(communityId) ?? `Community ${communityId}`)\n : null,\n });\n });\n\n const links: Record<string, unknown>[] = [];\n G.forEachEdge((_edge, data, source, target) => {\n const link: Record<string, unknown> = {\n source,\n target,\n ...data,\n };\n if (link.confidence_score === undefined) {\n const conf = (data.confidence as string) ?? \"EXTRACTED\";\n link.confidence_score = CONFIDENCE_SCORE_DEFAULTS[conf] ?? 1.0;\n }\n links.push(link);\n });\n\n const hyperedges = (G.getAttribute(\"hyperedges\") as Hyperedge[] | undefined) ?? [];\n const communityLabelsObject = communityLabels\n ? Object.fromEntries(\n [...communityLabels.entries()]\n .sort((a, b) => a[0] - b[0])\n .map(([cid, label]) => [String(cid), sanitizeLabel(label)]),\n )\n : {};\n\n const output = {\n directed: isDirectedGraph(G),\n multigraph: false,\n graph: {\n community_labels: communityLabelsObject,\n },\n nodes,\n links,\n hyperedges,\n };\n\n writeFileSync(outputPath, JSON.stringify(output, null, 2), \"utf-8\");\n}\n\n// ---------------------------------------------------------------------------\n// toCypher\n// ---------------------------------------------------------------------------\n\nexport function toCypher(G: Graph, outputPath: string): void {\n const lines: string[] = [\"// Neo4j Cypher import - generated by the graphify skill\", \"\"];\n\n G.forEachNode((nodeId, data) => {\n const label = cypherEscape((data.label as string) ?? nodeId);\n const nodeIdEsc = cypherEscape(nodeId);\n const rawFt = ((data.file_type as string) ?? \"unknown\")\n .charAt(0).toUpperCase() + ((data.file_type as string) ?? \"unknown\").slice(1);\n const cleaned = rawFt.replace(/[^A-Za-z0-9_]/g, \"\");\n const ftype = cleaned && /^[A-Za-z]/.test(cleaned) ? cleaned : \"Entity\";\n lines.push(`MERGE (n:${ftype} {id: '${nodeIdEsc}', label: '${label}'});`);\n });\n\n lines.push(\"\");\n\n G.forEachEdge((_edge, data, u, v) => {\n const rel = ((data.relation as string) ?? \"RELATES_TO\")\n .toUpperCase()\n .replace(/[^A-Za-z0-9_]/g, \"_\");\n const conf = cypherEscape((data.confidence as string) ?? \"EXTRACTED\");\n const uEsc = cypherEscape(u);\n const vEsc = cypherEscape(v);\n lines.push(\n `MATCH (a {id: '${uEsc}'}), (b {id: '${vEsc}'}) ` +\n `MERGE (a)-[:${rel} {confidence: '${conf}'}]->(b);`,\n );\n });\n\n writeFileSync(outputPath, lines.join(\"\\n\"), \"utf-8\");\n}\n\nfunction neo4jLabel(label: string): string {\n const sanitized = label.replace(/[^A-Za-z0-9_]/g, \"\");\n return sanitized || \"Entity\";\n}\n\nfunction neo4jRelation(relation: string): string {\n const sanitized = relation\n .toUpperCase()\n .replace(/[\\s-]+/g, \"_\")\n .replace(/[^A-Z0-9_]/g, \"_\");\n return sanitized || \"RELATED_TO\";\n}\n\nfunction scalarProps(data: Record<string, unknown>): Record<string, string | number | boolean> {\n const props: Record<string, string | number | boolean> = {};\n for (const [key, value] of Object.entries(data)) {\n if (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n ) {\n props[key] = value;\n }\n }\n return props;\n}\n\nexport async function pushToNeo4j(\n G: Graph,\n optionsOrUri: Neo4jPushOptions | string,\n user?: string,\n password?: string,\n communities?: NumericMapLike<string[]>,\n): Promise<{ nodes: number; edges: number }> {\n const options = typeof optionsOrUri === \"string\"\n ? {\n uri: optionsOrUri,\n user: user ?? \"neo4j\",\n password: password ?? \"\",\n communities,\n }\n : optionsOrUri;\n\n let neo4jMod: Record<string, any>;\n try {\n neo4jMod = await import(\"neo4j-driver\");\n } catch {\n throw new Error(\"neo4j-driver not installed. Run: npm install neo4j-driver\");\n }\n\n const neo4j = neo4jMod.default ?? neo4jMod;\n const driver = neo4j.driver(\n options.uri,\n neo4j.auth.basic(options.user, options.password),\n );\n const communityMap = nodeCommunityMap(options.communities ?? new Map<number, string[]>());\n\n let nodes = 0;\n let edges = 0;\n const session = driver.session();\n\n try {\n for (const nodeId of G.nodes()) {\n const attrs = G.getNodeAttributes(nodeId) as Record<string, unknown>;\n const props = scalarProps(attrs);\n props.id = nodeId;\n\n const communityId = communityMap.get(nodeId);\n if (communityId !== undefined) {\n props.community = communityId;\n }\n\n const fileType = neo4jLabel(\n (((attrs.file_type as string) ?? \"Entity\").charAt(0).toUpperCase()) +\n (((attrs.file_type as string) ?? \"Entity\").slice(1)),\n );\n\n await session.run(\n `MERGE (n:${fileType} {id: $id}) SET n += $props`,\n { id: nodeId, props },\n );\n nodes++;\n }\n\n for (const edgeKey of G.edges()) {\n const source = G.source(edgeKey);\n const target = G.target(edgeKey);\n const attrs = G.getEdgeAttributes(edgeKey) as Record<string, unknown>;\n const relation = neo4jRelation((attrs.relation as string) ?? \"RELATED_TO\");\n const props = scalarProps(attrs);\n\n await session.run(\n `MATCH (a {id: $source}), (b {id: $target}) ` +\n `MERGE (a)-[r:${relation}]->(b) SET r += $props`,\n { source, target, props },\n );\n edges++;\n }\n } finally {\n await session.close();\n await driver.close();\n }\n\n return { nodes, edges };\n}\n\n// ---------------------------------------------------------------------------\n// toHtml - full interactive vis.js visualization\n// ---------------------------------------------------------------------------\n\nfunction htmlStyles(): string {\n return `<style>\n * { box-sizing: border-box; margin: 0; padding: 0; }\n body { background: #0f0f1a; color: #e0e0e0; font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif; display: flex; height: 100vh; overflow: hidden; }\n #graph { flex: 1; }\n #sidebar { width: 280px; background: #1a1a2e; border-left: 1px solid #2a2a4e; display: flex; flex-direction: column; overflow: hidden; }\n #search-wrap { padding: 12px; border-bottom: 1px solid #2a2a4e; }\n #search { width: 100%; background: #0f0f1a; border: 1px solid #3a3a5e; color: #e0e0e0; padding: 7px 10px; border-radius: 6px; font-size: 13px; outline: none; }\n #search:focus { border-color: #4E79A7; }\n #search-results { max-height: 140px; overflow-y: auto; padding: 4px 12px; border-bottom: 1px solid #2a2a4e; display: none; }\n .search-item { padding: 4px 6px; cursor: pointer; border-radius: 4px; font-size: 12px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }\n .search-item:hover { background: #2a2a4e; }\n #info-panel { padding: 14px; border-bottom: 1px solid #2a2a4e; min-height: 140px; }\n #info-panel h3 { font-size: 13px; color: #aaa; margin-bottom: 8px; text-transform: uppercase; letter-spacing: 0.05em; }\n #info-content { font-size: 13px; color: #ccc; line-height: 1.6; }\n #info-content .field { margin-bottom: 5px; }\n #info-content .field b { color: #e0e0e0; }\n #info-content .empty { color: #555; font-style: italic; }\n .neighbor-link { display: block; padding: 2px 6px; margin: 2px 0; border-radius: 3px; cursor: pointer; font-size: 12px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; border-left: 3px solid #333; }\n .neighbor-link:hover { background: #2a2a4e; }\n #neighbors-list { max-height: 160px; overflow-y: auto; margin-top: 4px; }\n #legend-wrap { flex: 1; overflow-y: auto; padding: 12px; }\n #legend-wrap h3 { font-size: 13px; color: #aaa; margin-bottom: 10px; text-transform: uppercase; letter-spacing: 0.05em; }\n .legend-item { display: flex; align-items: center; gap: 8px; padding: 4px 0; cursor: pointer; border-radius: 4px; font-size: 12px; }\n .legend-item:hover { background: #2a2a4e; padding-left: 4px; }\n .legend-item.dimmed { opacity: 0.35; }\n .legend-dot { width: 12px; height: 12px; border-radius: 50%; flex-shrink: 0; }\n .legend-label { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n .legend-count { color: #666; font-size: 11px; }\n #stats { padding: 10px 14px; border-top: 1px solid #2a2a4e; font-size: 11px; color: #555; }\n</style>`;\n}\n\nfunction hyperedgeScript(hyperedgesJson: string): string {\n return `<script>\n// Render hyperedges as shaded regions\nconst hyperedges = ${hyperedgesJson};\nfunction drawHyperedges() {\n const canvas = network.canvas.frame.canvas;\n const ctx = canvas.getContext('2d');\n hyperedges.forEach(h => {\n const positions = h.nodes\n .map(nid => network.getPositions([nid])[nid])\n .filter(p => p !== undefined);\n if (positions.length < 2) return;\n // Draw convex hull as filled polygon\n ctx.save();\n ctx.globalAlpha = 0.12;\n ctx.fillStyle = '#6366f1';\n ctx.strokeStyle = '#6366f1';\n ctx.lineWidth = 2;\n ctx.beginPath();\n const scale = network.getScale();\n const offset = network.getViewPosition();\n const toCanvas = (p) => ({\n x: (p.x - offset.x) * scale + canvas.width / 2,\n y: (p.y - offset.y) * scale + canvas.height / 2\n });\n const pts = positions.map(toCanvas);\n // Expand hull slightly\n const cx = pts.reduce((s, p) => s + p.x, 0) / pts.length;\n const cy = pts.reduce((s, p) => s + p.y, 0) / pts.length;\n const expanded = pts.map(p => ({\n x: cx + (p.x - cx) * 1.15,\n y: cy + (p.y - cy) * 1.15\n }));\n ctx.moveTo(expanded[0].x, expanded[0].y);\n expanded.slice(1).forEach(p => ctx.lineTo(p.x, p.y));\n ctx.closePath();\n ctx.fill();\n ctx.globalAlpha = 0.4;\n ctx.stroke();\n // Label\n ctx.globalAlpha = 0.8;\n ctx.fillStyle = '#4f46e5';\n ctx.font = 'bold 11px sans-serif';\n ctx.textAlign = 'center';\n ctx.fillText(h.label, cx, cy - 5);\n ctx.restore();\n });\n}\nnetwork.on('afterDrawing', drawHyperedges);\n</script>`;\n}\n\nfunction htmlScript(nodesJson: string, edgesJson: string, legendJson: string): string {\n return `<script>\nconst RAW_NODES = ${nodesJson};\nconst RAW_EDGES = ${edgesJson};\nconst LEGEND = ${legendJson};\n\n// Build vis datasets\nconst nodesDS = new vis.DataSet(RAW_NODES.map(n => ({\n id: n.id, label: n.label, color: n.color, size: n.size,\n font: n.font, title: n.title,\n _community: n.community, _community_name: n.community_name,\n _source_file: n.source_file, _file_type: n.file_type, _degree: n.degree,\n})));\n\nconst edgesDS = new vis.DataSet(RAW_EDGES.map((e, i) => ({\n id: i, from: e.from, to: e.to,\n label: '',\n title: e.title,\n dashes: e.dashes,\n width: e.width,\n color: e.color,\n arrows: { to: { enabled: true, scaleFactor: 0.5 } },\n})));\n\nconst container = document.getElementById('graph');\nconst network = new vis.Network(container, { nodes: nodesDS, edges: edgesDS }, {\n physics: {\n enabled: true,\n solver: 'forceAtlas2Based',\n forceAtlas2Based: {\n gravitationalConstant: -60,\n centralGravity: 0.005,\n springLength: 120,\n springConstant: 0.08,\n damping: 0.4,\n avoidOverlap: 0.8,\n },\n stabilization: { iterations: 200, fit: true },\n },\n interaction: {\n hover: true,\n tooltipDelay: 100,\n hideEdgesOnDrag: true,\n navigationButtons: false,\n keyboard: false,\n },\n nodes: { shape: 'dot', borderWidth: 1.5 },\n edges: { smooth: { type: 'continuous', roundness: 0.2 }, selectionWidth: 3 },\n});\n\nnetwork.once('stabilizationIterationsDone', () => {\n network.setOptions({ physics: { enabled: false } });\n});\n\nfunction showInfo(nodeId) {\n const n = nodesDS.get(nodeId);\n if (!n) return;\n const neighborIds = network.getConnectedNodes(nodeId);\n const neighborItems = neighborIds.map(nid => {\n const nb = nodesDS.get(nid);\n const color = nb ? nb.color.background : '#555';\n return \\`<span class=\"neighbor-link\" style=\"border-left-color:\\${color}\" onclick=\"focusNode('\\${nid}')\">\\${nb ? nb.label : nid}</span>\\`;\n }).join('');\n document.getElementById('info-content').innerHTML = \\`\n <div class=\"field\"><b>\\${n.label}</b></div>\n <div class=\"field\">Type: \\${n._file_type || 'unknown'}</div>\n <div class=\"field\">Community: \\${n._community_name}</div>\n <div class=\"field\">Source: \\${n._source_file || '-'}</div>\n <div class=\"field\">Degree: \\${n._degree}</div>\n \\${neighborIds.length ? \\`<div class=\"field\" style=\"margin-top:8px;color:#aaa;font-size:11px\">Neighbors (\\${neighborIds.length})</div><div id=\"neighbors-list\">\\${neighborItems}</div>\\` : ''}\n \\`;\n}\n\nfunction focusNode(nodeId) {\n network.focus(nodeId, { scale: 1.4, animation: true });\n network.selectNodes([nodeId]);\n showInfo(nodeId);\n}\n\nlet hoveredNodeId = null;\nnetwork.on('hoverNode', params => {\n hoveredNodeId = params.node;\n container.style.cursor = 'pointer';\n});\nnetwork.on('blurNode', () => {\n hoveredNodeId = null;\n container.style.cursor = 'default';\n});\ncontainer.addEventListener('click', () => {\n if (hoveredNodeId !== null) {\n showInfo(hoveredNodeId);\n network.selectNodes([hoveredNodeId]);\n }\n});\nnetwork.on('click', params => {\n if (params.nodes.length > 0) showInfo(params.nodes[0]);\n else if (hoveredNodeId === null) document.getElementById('info-content').innerHTML = '<span class=\"empty\">Click a node to inspect it</span>';\n});\n\nconst searchInput = document.getElementById('search');\nconst searchResults = document.getElementById('search-results');\nsearchInput.addEventListener('input', () => {\n const q = searchInput.value.toLowerCase().trim();\n searchResults.innerHTML = '';\n if (!q) { searchResults.style.display = 'none'; return; }\n const matches = RAW_NODES.filter(n => n.label.toLowerCase().includes(q)).slice(0, 20);\n if (!matches.length) { searchResults.style.display = 'none'; return; }\n searchResults.style.display = 'block';\n matches.forEach(n => {\n const el = document.createElement('div');\n el.className = 'search-item';\n el.textContent = n.label;\n el.style.borderLeft = \\`3px solid \\${n.color.background}\\`;\n el.style.paddingLeft = '8px';\n el.onclick = () => {\n network.focus(n.id, { scale: 1.5, animation: true });\n network.selectNodes([n.id]);\n showInfo(n.id);\n searchResults.style.display = 'none';\n searchInput.value = '';\n };\n searchResults.appendChild(el);\n });\n});\ndocument.addEventListener('click', e => {\n if (!searchResults.contains(e.target) && e.target !== searchInput)\n searchResults.style.display = 'none';\n});\n\nconst hiddenCommunities = new Set();\nconst legendEl = document.getElementById('legend');\nLEGEND.forEach(c => {\n const item = document.createElement('div');\n item.className = 'legend-item';\n item.innerHTML = \\`<div class=\"legend-dot\" style=\"background:\\${c.color}\"></div>\n <span class=\"legend-label\">\\${c.label}</span>\n <span class=\"legend-count\">\\${c.count}</span>\\`;\n item.onclick = () => {\n if (hiddenCommunities.has(c.cid)) {\n hiddenCommunities.delete(c.cid);\n item.classList.remove('dimmed');\n } else {\n hiddenCommunities.add(c.cid);\n item.classList.add('dimmed');\n }\n const updates = RAW_NODES\n .filter(n => n.community === c.cid)\n .map(n => ({ id: n.id, hidden: hiddenCommunities.has(c.cid) }));\n nodesDS.update(updates);\n };\n legendEl.appendChild(item);\n});\n</script>`;\n}\n\nexport function toHtml(\n G: Graph,\n communities: NumericMapLike<string[]>,\n outputPath: string,\n communityLabelsOrOptions?: CommunityLabelsInput | CommunityLabelOptions,\n): void {\n const communityMap = toNumericMap(communities);\n const communityLabels = normalizeCommunityLabels(communityLabelsOrOptions);\n if (G.order > MAX_NODES_FOR_VIZ) {\n throw new Error(\n `Graph has ${G.order} nodes - too large for HTML viz. ` +\n `Use --no-viz or reduce input size.`,\n );\n }\n\n const nodeComm = nodeCommunityMap(communityMap);\n const degree = new Map<string, number>();\n G.forEachNode((n) => degree.set(n, G.degree(n)));\n const maxDeg = Math.max(1, ...degree.values());\n\n // Build nodes list for vis.js\n interface VisNode {\n id: string;\n label: string;\n color: { background: string; border: string; highlight: { background: string; border: string } };\n size: number;\n font: { size: number; color: string };\n title: string;\n community: number;\n community_name: string;\n source_file: string;\n file_type: string;\n degree: number;\n }\n const visNodes: VisNode[] = [];\n G.forEachNode((nodeId, data) => {\n const cid = nodeComm.get(nodeId) ?? 0;\n const color = COMMUNITY_COLORS[cid % COMMUNITY_COLORS.length]!;\n const label = sanitizeLabel((data.label as string) ?? nodeId);\n const deg = degree.get(nodeId) ?? 1;\n const size = 10 + 30 * (deg / maxDeg);\n const fontSize = deg >= maxDeg * 0.15 ? 12 : 0;\n visNodes.push({\n id: nodeId,\n label,\n color: {\n background: color,\n border: color,\n highlight: { background: \"#ffffff\", border: color },\n },\n size: Math.round(size * 10) / 10,\n font: { size: fontSize, color: \"#ffffff\" },\n title: label,\n community: cid,\n community_name: sanitizeLabel(communityLabels?.get(cid) ?? `Community ${cid}`),\n source_file: sanitizeLabel((data.source_file as string) ?? \"\"),\n file_type: (data.file_type as string) ?? \"\",\n degree: deg,\n });\n });\n\n // Build edges list\n interface VisEdge {\n from: string;\n to: string;\n label: string;\n title: string;\n dashes: boolean;\n width: number;\n color: { opacity: number };\n confidence: string;\n }\n const visEdges: VisEdge[] = [];\n G.forEachEdge((_edge, data, u, v) => {\n const confidence = (data.confidence as string) ?? \"EXTRACTED\";\n const relation = (data.relation as string) ?? \"\";\n visEdges.push({\n from: u,\n to: v,\n label: relation,\n title: `${relation} [${confidence}]`,\n dashes: confidence !== \"EXTRACTED\",\n width: confidence === \"EXTRACTED\" ? 2 : 1,\n color: { opacity: confidence === \"EXTRACTED\" ? 0.7 : 0.35 },\n confidence,\n });\n });\n\n // Build community legend data\n interface LegendEntry {\n cid: number;\n color: string;\n label: string;\n count: number;\n }\n const legendData: LegendEntry[] = [];\n const labelKeys = communityLabels ? [...communityLabels.keys()].sort((a, b) => a - b) : [];\n for (const cid of labelKeys) {\n const color = COMMUNITY_COLORS[cid % COMMUNITY_COLORS.length]!;\n const lbl = escapeHtml(sanitizeLabel(communityLabels?.get(cid) ?? `Community ${cid}`));\n const n = communityMap.get(cid)?.length ?? 0;\n legendData.push({ cid, color, label: lbl, count: n });\n }\n\n const nodesJson = JSON.stringify(visNodes);\n const edgesJson = JSON.stringify(visEdges);\n const legendJson = JSON.stringify(legendData);\n const rawHyperedges = (G.getAttribute(\"hyperedges\") as Hyperedge[] | undefined) ?? [];\n const hyperedgesJson = JSON.stringify(rawHyperedges);\n const title = escapeHtml(sanitizeLabel(outputPath));\n const stats =\n `${G.order} nodes · ${G.size} edges · ${communityMap.size} communities`;\n\n const html = `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<title>graphify - ${title}</title>\n<script src=\"https://unpkg.com/vis-network/standalone/umd/vis-network.min.js\"></script>\n${htmlStyles()}\n</head>\n<body>\n<div id=\"graph\"></div>\n<div id=\"sidebar\">\n <div id=\"search-wrap\">\n <input id=\"search\" type=\"text\" placeholder=\"Search nodes...\" autocomplete=\"off\">\n <div id=\"search-results\"></div>\n </div>\n <div id=\"info-panel\">\n <h3>Node Info</h3>\n <div id=\"info-content\"><span class=\"empty\">Click a node to inspect it</span></div>\n </div>\n <div id=\"legend-wrap\">\n <h3>Communities</h3>\n <div id=\"legend\"></div>\n </div>\n <div id=\"stats\">${stats}</div>\n</div>\n${htmlScript(nodesJson, edgesJson, legendJson)}\n${hyperedgeScript(hyperedgesJson)}\n</body>\n</html>`;\n\n writeFileSync(outputPath, html, \"utf-8\");\n}\n\n// ---------------------------------------------------------------------------\n// toGraphml\n// ---------------------------------------------------------------------------\n\nexport function toGraphml(\n G: Graph,\n communities: NumericMapLike<string[]>,\n outputPath: string,\n): void {\n const nodeComm = nodeCommunityMap(communities);\n\n const xmlEsc = (s: string): string =>\n s\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\")\n .replace(/'/g, \"'\");\n\n const lines: string[] = [];\n lines.push('<?xml version=\"1.0\" encoding=\"UTF-8\"?>');\n lines.push(\n '<graphml xmlns=\"http://graphml.graphstruct.org/graphml\"' +\n ' xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"' +\n ' xsi:schemaLocation=\"http://graphml.graphstruct.org/graphml' +\n ' http://graphml.graphstruct.org/graphml/1.0/graphml.xsd\">',\n );\n\n // Declare attribute keys\n lines.push(' <key id=\"label\" for=\"node\" attr.name=\"label\" attr.type=\"string\"/>');\n lines.push(' <key id=\"file_type\" for=\"node\" attr.name=\"file_type\" attr.type=\"string\"/>');\n lines.push(' <key id=\"source_file\" for=\"node\" attr.name=\"source_file\" attr.type=\"string\"/>');\n lines.push(' <key id=\"community\" for=\"node\" attr.name=\"community\" attr.type=\"int\"/>');\n lines.push(' <key id=\"relation\" for=\"edge\" attr.name=\"relation\" attr.type=\"string\"/>');\n lines.push(' <key id=\"confidence\" for=\"edge\" attr.name=\"confidence\" attr.type=\"string\"/>');\n\n lines.push(` <graph id=\"G\" edgedefault=\"${isDirectedGraph(G) ? \"directed\" : \"undirected\"}\">`);\n\n G.forEachNode((nodeId, data) => {\n lines.push(` <node id=\"${xmlEsc(nodeId)}\">`);\n lines.push(` <data key=\"label\">${xmlEsc((data.label as string) ?? nodeId)}</data>`);\n lines.push(` <data key=\"file_type\">${xmlEsc((data.file_type as string) ?? \"\")}</data>`);\n lines.push(` <data key=\"source_file\">${xmlEsc((data.source_file as string) ?? \"\")}</data>`);\n lines.push(` <data key=\"community\">${nodeComm.get(nodeId) ?? -1}</data>`);\n lines.push(\" </node>\");\n });\n\n G.forEachEdge((_edge, data, source, target) => {\n lines.push(` <edge source=\"${xmlEsc(source)}\" target=\"${xmlEsc(target)}\">`);\n lines.push(` <data key=\"relation\">${xmlEsc((data.relation as string) ?? \"\")}</data>`);\n lines.push(` <data key=\"confidence\">${xmlEsc((data.confidence as string) ?? \"EXTRACTED\")}</data>`);\n lines.push(\" </edge>\");\n });\n\n lines.push(\" </graph>\");\n lines.push(\"</graphml>\");\n\n writeFileSync(outputPath, lines.join(\"\\n\"), \"utf-8\");\n}\n\n// ---------------------------------------------------------------------------\n// toSvg - simple circle-layout SVG\n// ---------------------------------------------------------------------------\n\nexport function toSvg(\n G: Graph,\n communities: NumericMapLike<string[]>,\n outputPath: string,\n communityLabelsOrOptions?: CommunityLabelsInput | SvgOptions,\n figsize: [number, number] = [20, 14],\n): void {\n const communityMap = toNumericMap(communities);\n const options = communityLabelsOrOptions && isSvgOptions(communityLabelsOrOptions)\n ? communityLabelsOrOptions\n : undefined;\n const communityLabels = normalizeCommunityLabels(communityLabelsOrOptions);\n const nodeComm = nodeCommunityMap(communityMap);\n const figureSize = options?.figsize ?? figsize;\n const [widthIn, heightIn] = figureSize;\n const width = widthIn * 60;\n const height = heightIn * 60;\n const cx = width / 2;\n const cy = height / 2;\n const radius = Math.min(cx, cy) * 0.8;\n\n const nodeList = G.nodes();\n const n = nodeList.length;\n\n // Compute positions using a simple circle layout\n const pos = new Map<string, [number, number]>();\n for (let i = 0; i < n; i++) {\n const angle = (2 * Math.PI * i) / Math.max(n, 1);\n pos.set(nodeList[i]!, [\n cx + radius * Math.cos(angle),\n cy + radius * Math.sin(angle),\n ]);\n }\n\n const degree = new Map<string, number>();\n G.forEachNode((node) => degree.set(node, G.degree(node)));\n const maxDeg = Math.max(1, ...degree.values());\n\n const xmlEsc = (s: string): string =>\n s\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\");\n\n const svgParts: string[] = [];\n svgParts.push(\n `<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 ${width} ${height}\" ` +\n `width=\"${width}\" height=\"${height}\" style=\"background:#1a1a2e\">`,\n );\n\n // Draw edges\n G.forEachEdge((_edge, data, u, v) => {\n const [x1, y1] = pos.get(u) ?? [0, 0];\n const [x2, y2] = pos.get(v) ?? [0, 0];\n const conf = (data.confidence as string) ?? \"EXTRACTED\";\n const dasharray = conf === \"EXTRACTED\" ? \"\" : ' stroke-dasharray=\"4,4\"';\n const opacity = conf === \"EXTRACTED\" ? 0.6 : 0.3;\n svgParts.push(\n ` <line x1=\"${x1}\" y1=\"${y1}\" x2=\"${x2}\" y2=\"${y2}\" ` +\n `stroke=\"#aaaaaa\" stroke-width=\"0.8\" opacity=\"${opacity}\"${dasharray}/>`,\n );\n });\n\n // Draw nodes\n for (const nodeId of nodeList) {\n const [x, y] = pos.get(nodeId) ?? [0, 0];\n const cid = nodeComm.get(nodeId) ?? 0;\n const color = COMMUNITY_COLORS[cid % COMMUNITY_COLORS.length]!;\n const deg = degree.get(nodeId) ?? 1;\n const r = 4 + 12 * (deg / maxDeg);\n svgParts.push(\n ` <circle cx=\"${x}\" cy=\"${y}\" r=\"${r}\" fill=\"${color}\" opacity=\"0.9\"/>`,\n );\n const label = (G.getNodeAttribute(nodeId, \"label\") as string) ?? nodeId;\n svgParts.push(\n ` <text x=\"${x}\" y=\"${y + r + 10}\" text-anchor=\"middle\" ` +\n `fill=\"white\" font-size=\"7\" font-family=\"sans-serif\">${xmlEsc(label)}</text>`,\n );\n }\n\n // Legend\n if (communityLabels) {\n const sortedKeys = [...communityLabels.keys()].sort((a, b) => a - b);\n let ly = 20;\n for (const cid of sortedKeys) {\n const color = COMMUNITY_COLORS[cid % COMMUNITY_COLORS.length]!;\n const label = communityLabels.get(cid) ?? `Community ${cid}`;\n const count = communityMap.get(cid)?.length ?? 0;\n svgParts.push(\n ` <circle cx=\"20\" cy=\"${ly}\" r=\"5\" fill=\"${color}\"/>`,\n );\n svgParts.push(\n ` <text x=\"30\" y=\"${ly + 4}\" fill=\"white\" font-size=\"8\" ` +\n `font-family=\"sans-serif\">${xmlEsc(label)} (${count})</text>`,\n );\n ly += 18;\n }\n }\n\n svgParts.push(\"</svg>\");\n writeFileSync(outputPath, svgParts.join(\"\\n\"), \"utf-8\");\n}\n\n// ---------------------------------------------------------------------------\n// toCanvas - Obsidian .canvas JSON\n// ---------------------------------------------------------------------------\n\nexport function toCanvas(\n G: Graph,\n communities: NumericMapLike<string[]>,\n outputPath: string,\n communityLabelsOrOptions?: CommunityLabelsInput | CanvasOptions,\n nodeFilenames?: StringMapLike<string>,\n): void {\n const communityMap = toNumericMap(communities);\n const options = communityLabelsOrOptions && isCanvasOptions(communityLabelsOrOptions)\n ? communityLabelsOrOptions\n : undefined;\n const communityLabels = normalizeCommunityLabels(communityLabelsOrOptions);\n const providedNodeFilenames = options?.nodeFilenames ?? nodeFilenames;\n const CANVAS_COLORS = [\"1\", \"2\", \"3\", \"4\", \"5\", \"6\"];\n\n function safeName(label: string): string {\n return label\n .replace(/\\r\\n/g, \" \")\n .replace(/\\r/g, \" \")\n .replace(/\\n/g, \" \")\n .replace(/[\\\\/*?:\"<>|#^[\\]]/g, \"\")\n .trim() || \"unnamed\";\n }\n\n // Build nodeFilenames if not provided\n let filenameMap: Map<string, string>;\n if (!providedNodeFilenames) {\n filenameMap = new Map<string, string>();\n const seenNames = new Map<string, number>();\n G.forEachNode((nodeId, data) => {\n const base = safeName((data.label as string) ?? nodeId);\n const count = seenNames.get(base);\n if (count !== undefined) {\n const next = count + 1;\n seenNames.set(base, next);\n filenameMap.set(nodeId, `${base}_${next}`);\n } else {\n seenNames.set(base, 0);\n filenameMap.set(nodeId, base);\n }\n });\n } else {\n filenameMap = toStringMap(providedNodeFilenames);\n }\n\n const numCommunities = communityMap.size;\n const cols = numCommunities > 0 ? Math.ceil(Math.sqrt(numCommunities)) : 1;\n const rows = numCommunities > 0 ? Math.ceil(numCommunities / cols) : 1;\n\n const canvasNodes: Record<string, unknown>[] = [];\n const canvasEdges: Record<string, unknown>[] = [];\n\n const sortedCids = [...communityMap.keys()].sort((a, b) => a - b);\n\n // Precompute group sizes\n const groupSizes = new Map<number, [number, number]>();\n for (const cid of sortedCids) {\n const members = communityMap.get(cid) ?? [];\n const memberCount = members.length;\n const w = Math.max(600, memberCount > 0 ? 220 * Math.ceil(Math.sqrt(memberCount)) : 600);\n const h = Math.max(400, memberCount > 0 ? 100 * Math.ceil(memberCount / 3) + 120 : 400);\n groupSizes.set(cid, [w, h]);\n }\n\n // Compute column widths and row heights\n const gap = 80;\n const colWidths: number[] = [];\n for (let colIdx = 0; colIdx < cols; colIdx++) {\n let maxW = 0;\n for (let rowIdx = 0; rowIdx < rows; rowIdx++) {\n const linear = rowIdx * cols + colIdx;\n if (linear < sortedCids.length) {\n const cid = sortedCids[linear]!;\n const [w] = groupSizes.get(cid) ?? [600, 400];\n maxW = Math.max(maxW, w);\n }\n }\n colWidths.push(maxW);\n }\n\n const rowHeights: number[] = [];\n for (let rowIdx = 0; rowIdx < rows; rowIdx++) {\n let maxH = 0;\n for (let colIdx = 0; colIdx < cols; colIdx++) {\n const linear = rowIdx * cols + colIdx;\n if (linear < sortedCids.length) {\n const cid = sortedCids[linear]!;\n const [, h] = groupSizes.get(cid) ?? [600, 400];\n maxH = Math.max(maxH, h);\n }\n }\n rowHeights.push(maxH);\n }\n\n // Map from cid -> layout\n const groupLayout = new Map<number, [number, number, number, number]>();\n for (let idx = 0; idx < sortedCids.length; idx++) {\n const cid = sortedCids[idx]!;\n const colIdx = idx % cols;\n const rowIdx = Math.floor(idx / cols);\n const gx = colWidths.slice(0, colIdx).reduce((a, b) => a + b, 0) + colIdx * gap;\n const gy = rowHeights.slice(0, rowIdx).reduce((a, b) => a + b, 0) + rowIdx * gap;\n const [gw, gh] = groupSizes.get(cid) ?? [600, 400];\n groupLayout.set(cid, [gx, gy, gw, gh]);\n }\n\n // Collect all node IDs in canvas\n const allCanvasNodeIds = new Set<string>();\n for (const members of communityMap.values()) {\n for (const m of members) allCanvasNodeIds.add(m);\n }\n\n // Generate group and node canvas entries\n for (let idx = 0; idx < sortedCids.length; idx++) {\n const cid = sortedCids[idx]!;\n const members = communityMap.get(cid) ?? [];\n const communityName = communityLabels?.get(cid) ?? `Community ${cid}`;\n const [gx, gy, gw, gh] = groupLayout.get(cid) ?? [0, 0, 600, 400];\n const canvasColor = CANVAS_COLORS[idx % CANVAS_COLORS.length]!;\n\n // Group node\n canvasNodes.push({\n id: `g${cid}`,\n type: \"group\",\n label: communityName,\n x: gx,\n y: gy,\n width: gw,\n height: gh,\n color: canvasColor,\n });\n\n // Node cards inside the group\n const sortedMembers = [...members].sort((a, b) => {\n const la = (G.getNodeAttribute(a, \"label\") as string) ?? a;\n const lb = (G.getNodeAttribute(b, \"label\") as string) ?? b;\n return la.localeCompare(lb);\n });\n for (let mIdx = 0; mIdx < sortedMembers.length; mIdx++) {\n const nodeId = sortedMembers[mIdx]!;\n const col = mIdx % 3;\n const row = Math.floor(mIdx / 3);\n const nx = gx + 20 + col * (180 + 20);\n const ny = gy + 80 + row * (60 + 20);\n const fname =\n filenameMap.get(nodeId) ??\n safeName((G.getNodeAttribute(nodeId, \"label\") as string) ?? nodeId);\n canvasNodes.push({\n id: `n_${nodeId}`,\n type: \"file\",\n file: `graphify/obsidian/${fname}.md`,\n x: nx,\n y: ny,\n width: 180,\n height: 60,\n });\n }\n }\n\n // Generate edges - only between nodes both in canvas, cap at 200 highest-weight\n const allEdgesWeighted: [number, string, string, string][] = [];\n G.forEachEdge((_edge, edata, u, v) => {\n if (allCanvasNodeIds.has(u) && allCanvasNodeIds.has(v)) {\n const weight = (edata.weight as number) ?? 1.0;\n const relation = (edata.relation as string) ?? \"\";\n const conf = (edata.confidence as string) ?? \"EXTRACTED\";\n const label = relation ? `${relation} [${conf}]` : `[${conf}]`;\n allEdgesWeighted.push([weight, u, v, label]);\n }\n });\n\n allEdgesWeighted.sort((a, b) => b[0] - a[0]);\n for (const [, u, v, label] of allEdgesWeighted.slice(0, 200)) {\n canvasEdges.push({\n id: `e_${u}_${v}`,\n fromNode: `n_${u}`,\n toNode: `n_${v}`,\n label,\n });\n }\n\n const canvasData = { nodes: canvasNodes, edges: canvasEdges };\n writeFileSync(outputPath, JSON.stringify(canvasData, null, 2), \"utf-8\");\n}\n","/**\n * Security helpers - URL validation, safe fetch, path guards, label sanitization.\n */\nimport { resolve as pathResolve } from \"node:path\";\nimport { existsSync } from \"node:fs\";\nimport { URL } from \"node:url\";\nimport * as dns from \"node:dns/promises\";\nimport * as net from \"node:net\";\n\nconst ALLOWED_SCHEMES = new Set([\"http:\", \"https:\"]);\nconst MAX_FETCH_BYTES = 52_428_800; // 50 MB\nconst MAX_TEXT_BYTES = 10_485_760; // 10 MB\nconst BLOCKED_HOSTS = new Set([\"metadata.google.internal\", \"metadata.google.com\"]);\n\n// ---------------------------------------------------------------------------\n// URL validation\n// ---------------------------------------------------------------------------\n\n/**\n * Raise if url is not http/https, or targets a private/internal IP.\n * Blocks file://, ftp://, data:, and any other SSRF-prone scheme.\n */\nexport async function validateUrl(url: string): Promise<string> {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n throw new Error(`Invalid URL: ${url}`);\n }\n\n if (!ALLOWED_SCHEMES.has(parsed.protocol)) {\n throw new Error(\n `Blocked URL scheme '${parsed.protocol}' - only http and https are allowed. Got: ${url}`,\n );\n }\n\n const hostname = parsed.hostname;\n if (hostname) {\n if (BLOCKED_HOSTS.has(hostname.toLowerCase())) {\n throw new Error(`Blocked cloud metadata endpoint '${hostname}'. Got: ${url}`);\n }\n\n // Resolve hostname and block private/reserved IP ranges\n try {\n const addrs = await dns.resolve4(hostname).catch(() => [] as string[]);\n const addrs6 = await dns.resolve6(hostname).catch(() => [] as string[]);\n for (const addr of [...addrs, ...addrs6]) {\n if (isPrivateIp(addr)) {\n throw new Error(\n `Blocked private/internal IP ${addr} (resolved from '${hostname}'). Got: ${url}`,\n );\n }\n }\n } catch (e) {\n if (e instanceof Error && e.message.startsWith(\"Blocked\")) throw e;\n // DNS failure will surface later during fetch\n }\n }\n\n return url;\n}\n\n/** Synchronous URL validation (scheme + hostname only, no DNS). */\nexport function validateUrlSync(url: string): string {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n throw new Error(`Invalid URL: ${url}`);\n }\n\n if (!ALLOWED_SCHEMES.has(parsed.protocol)) {\n throw new Error(\n `Blocked URL scheme '${parsed.protocol}' - only http and https are allowed. Got: ${url}`,\n );\n }\n\n if (parsed.hostname && BLOCKED_HOSTS.has(parsed.hostname.toLowerCase())) {\n throw new Error(`Blocked cloud metadata endpoint '${parsed.hostname}'. Got: ${url}`);\n }\n\n return url;\n}\n\nfunction isPrivateIp(addr: string): boolean {\n if (net.isIPv4(addr)) {\n const parts = addr.split(\".\").map(Number);\n const [a, b] = parts as [number, number, ...number[]];\n // 127.x.x.x, 10.x.x.x, 172.16-31.x.x, 192.168.x.x, 169.254.x.x, 0.x.x.x\n if (a === 127) return true;\n if (a === 10) return true;\n if (a === 172 && b !== undefined && b >= 16 && b <= 31) return true;\n if (a === 192 && b === 168) return true;\n if (a === 169 && b === 254) return true;\n if (a === 0) return true;\n return false;\n }\n if (net.isIPv6(addr)) {\n const lower = addr.toLowerCase();\n if (lower === \"::1\" || lower.startsWith(\"fe80:\") || lower.startsWith(\"fc\") || lower.startsWith(\"fd\")) {\n return true;\n }\n }\n return false;\n}\n\n// ---------------------------------------------------------------------------\n// Safe fetch\n// ---------------------------------------------------------------------------\n\n/**\n * Fetch url and return raw bytes (Buffer).\n * Validates URL, caps response body, follows redirects with re-validation.\n */\nexport async function safeFetch(\n url: string,\n maxBytes: number = MAX_FETCH_BYTES,\n timeout: number = 30_000,\n): Promise<Buffer> {\n await validateUrl(url);\n\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeout);\n\n try {\n const resp = await fetch(url, {\n signal: controller.signal,\n headers: { \"User-Agent\": \"Mozilla/5.0 graphify/1.0\" },\n redirect: \"follow\",\n });\n\n if (!resp.ok) {\n throw new Error(`HTTP ${resp.status} fetching ${url}`);\n }\n\n // Validate final URL after redirects\n if (resp.url !== url) {\n await validateUrl(resp.url);\n }\n\n const reader = resp.body?.getReader();\n if (!reader) throw new Error(\"No response body\");\n\n const chunks: Uint8Array[] = [];\n let total = 0;\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.length;\n if (total > maxBytes) {\n reader.cancel();\n throw new Error(\n `Response from ${url} exceeds size limit (${Math.floor(maxBytes / 1_048_576)} MB). Aborting download.`,\n );\n }\n chunks.push(value);\n }\n\n return Buffer.concat(chunks);\n } finally {\n clearTimeout(timer);\n }\n}\n\n/** Fetch url and return decoded text (UTF-8). */\nexport async function safeFetchText(\n url: string,\n maxBytes: number = MAX_TEXT_BYTES,\n timeout: number = 15_000,\n): Promise<string> {\n const raw = await safeFetch(url, maxBytes, timeout);\n return raw.toString(\"utf-8\");\n}\n\n// ---------------------------------------------------------------------------\n// Path validation\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve path and verify it stays inside base (defaults to graphify-out/).\n * Requires the base directory to exist.\n */\nexport function validateGraphPath(filePath: string, base?: string): string {\n const resolvedBase = pathResolve(base ?? \"graphify-out\");\n\n if (!existsSync(resolvedBase)) {\n throw new Error(\n `Graph base directory does not exist: ${resolvedBase}. Run the graphify skill first to build the graph (for Codex: $graphify .).`,\n );\n }\n\n const resolved = pathResolve(filePath);\n\n if (!resolved.startsWith(resolvedBase + \"/\") && resolved !== resolvedBase) {\n throw new Error(\n `Path '${filePath}' escapes the allowed directory ${resolvedBase}. Only paths inside graphify-out/ are permitted.`,\n );\n }\n\n if (!existsSync(resolved)) {\n throw new Error(`Graph file not found: ${resolved}`);\n }\n\n return resolved;\n}\n\n// ---------------------------------------------------------------------------\n// Label sanitization\n// ---------------------------------------------------------------------------\n\nconst CONTROL_CHAR_RE = /[\\x00-\\x1f\\x7f]/g;\nconst MAX_LABEL_LEN = 256;\n\n/** Strip control characters and cap length. Safe for JSON embedding. */\nexport function sanitizeLabel(text: string): string {\n let cleaned = text.replace(CONTROL_CHAR_RE, \"\");\n if (cleaned.length > MAX_LABEL_LEN) {\n cleaned = cleaned.slice(0, MAX_LABEL_LEN);\n }\n return cleaned;\n}\n\n/** Escape text for safe HTML embedding. */\nexport function escapeHtml(text: string): string {\n return text\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\")\n .replace(/'/g, \"'\");\n}\n","/**\n * Deterministic structural extraction from source code using tree-sitter.\n * Outputs nodes + edges dicts.\n *\n * TypeScript port of graphify/extract.py — uses web-tree-sitter (WASM) instead\n * of Python's native tree-sitter bindings.\n */\n\nimport { readFileSync, readdirSync, lstatSync, realpathSync, existsSync } from \"node:fs\";\nimport { resolve, basename, extname, dirname, join, sep } from \"node:path\";\nimport { createRequire } from \"node:module\";\nimport type { GraphNode, GraphEdge, Extraction } from \"./types.js\";\nimport { loadCached, saveCached } from \"./cache.js\";\n\n// ---------------------------------------------------------------------------\n// web-tree-sitter types (re-exported from the package)\n// ---------------------------------------------------------------------------\nimport * as TreeSitter from \"web-tree-sitter\";\ntype SyntaxNode = TreeSitter.Node;\ntype Tree = TreeSitter.Tree;\n\nconst Parser = (\n (TreeSitter as unknown as { Parser?: typeof TreeSitter.Parser }).Parser ??\n (TreeSitter as unknown as { default?: typeof TreeSitter.Parser }).default\n)!;\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nlet _parserInitialized = false;\n\nfunction getModuleRequire(): NodeJS.Require {\n try {\n return createRequire(import.meta.url);\n } catch {\n return require;\n }\n}\n\nconst moduleRequire = getModuleRequire();\n\nasync function ensureParserInit(): Promise<void> {\n if (!_parserInitialized) {\n await Parser.init();\n _parserInitialized = true;\n }\n}\n\nfunction parseText(parser: InstanceType<typeof Parser>, source: string): Tree {\n const tree = parser.parse(source);\n if (!tree) {\n throw new Error(\"Parser returned null\");\n }\n return tree;\n}\n\n/** Try to locate a WASM grammar file. Returns the resolved path or null. */\nfunction resolveGrammarWasm(langName: string): string | null {\n const packageName = new Map<string, string>([\n [\"c_sharp\", \"c-sharp\"],\n ]).get(langName) ?? langName;\n // Try common npm package conventions\n const candidates = [\n `tree-sitter-${packageName}/tree-sitter-${langName}.wasm`,\n `tree-sitter-${packageName}/tree-sitter-${packageName}.wasm`,\n `tree-sitter-${packageName}/tree_sitter_${langName}.wasm`,\n `tree-sitter-${packageName}/tree_sitter_${packageName.replace(/-/g, \"_\")}.wasm`,\n `tree-sitter-${packageName}/${langName}.wasm`,\n `tree-sitter-${packageName}/${packageName}.wasm`,\n ];\n for (const candidate of candidates) {\n try {\n const resolved = moduleRequire.resolve(candidate);\n if (existsSync(resolved)) return resolved;\n } catch {\n /* not found via require.resolve — skip */\n }\n }\n // Also try a path relative to node_modules\n const nmDir = join(process.cwd(), \"node_modules\");\n for (const candidate of candidates) {\n const p = join(nmDir, candidate);\n if (existsSync(p)) return p;\n }\n return null;\n}\n\n/**\n * Cache of loaded Parser.Language instances keyed by language name.\n * Avoids re-reading WASM files on every file extraction.\n */\nconst _languageCache = new Map<string, TreeSitter.Language>();\n\nasync function loadLanguage(langName: string): Promise<TreeSitter.Language | null> {\n if (_languageCache.has(langName)) return _languageCache.get(langName)!;\n const wasmPath = resolveGrammarWasm(langName);\n if (!wasmPath) return null;\n try {\n const lang = await TreeSitter.Language.load(wasmPath);\n _languageCache.set(langName, lang);\n return lang;\n } catch {\n return null;\n }\n}\n\n/** Build a stable node ID from one or more name parts. */\nfunction _makeId(...parts: string[]): string {\n const combined = parts\n .filter(Boolean)\n .map((p) => p.replace(/^[_.]+|[_.]+$/g, \"\"))\n .join(\"_\");\n const cleaned = combined.replace(/[^a-zA-Z0-9]+/g, \"_\");\n return cleaned.replace(/^_+|_+$/g, \"\").toLowerCase();\n}\n\nfunction _readText(node: SyntaxNode, source: string): string {\n return source.slice(node.startIndex, node.endIndex);\n}\n\n// ---------------------------------------------------------------------------\n// LanguageConfig interface + generic helpers\n// ---------------------------------------------------------------------------\n\ntype ImportHandler = (\n node: SyntaxNode,\n source: string,\n fileNid: string,\n stem: string,\n edges: GraphEdge[],\n strPath: string,\n) => void;\n\ntype ResolveFunctionNameFn = (node: SyntaxNode, source: string) => string | null;\n\ntype ExtraWalkFn = (\n node: SyntaxNode,\n source: string,\n fileNid: string,\n stem: string,\n strPath: string,\n nodes: GraphNode[],\n edges: GraphEdge[],\n seenIds: Set<string>,\n functionBodies: Array<[string, SyntaxNode]>,\n parentClassNid: string | null,\n addNodeFn: (nid: string, label: string, line: number) => void,\n addEdgeFn: (src: string, tgt: string, relation: string, line: number) => void,\n walkFn?: (node: SyntaxNode, parentClassNid: string | null) => void,\n) => boolean;\n\ninterface LanguageConfig {\n tsGrammarName: string; // e.g. \"python\"\n tsModule: string; // original Python module name — used for language-specific branches\n\n classTypes: Set<string>;\n functionTypes: Set<string>;\n importTypes: Set<string>;\n callTypes: Set<string>;\n\n nameField: string;\n nameFallbackChildTypes: string[];\n\n bodyField: string;\n bodyFallbackChildTypes: string[];\n\n callFunctionField: string;\n callAccessorNodeTypes: Set<string>;\n callAccessorField: string;\n\n functionBoundaryTypes: Set<string>;\n\n importHandler: ImportHandler | null;\n resolveFunctionNameFn: ResolveFunctionNameFn | null;\n\n functionLabelParens: boolean;\n\n extraWalkFn: ExtraWalkFn | null;\n}\n\nfunction defaultConfig(overrides: Partial<LanguageConfig> & Pick<LanguageConfig, \"tsGrammarName\" | \"tsModule\">): LanguageConfig {\n return {\n classTypes: new Set(),\n functionTypes: new Set(),\n importTypes: new Set(),\n callTypes: new Set(),\n nameField: \"name\",\n nameFallbackChildTypes: [],\n bodyField: \"body\",\n bodyFallbackChildTypes: [],\n callFunctionField: \"function\",\n callAccessorNodeTypes: new Set(),\n callAccessorField: \"attribute\",\n functionBoundaryTypes: new Set(),\n importHandler: null,\n resolveFunctionNameFn: null,\n functionLabelParens: true,\n extraWalkFn: null,\n ...overrides,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Generic helpers for name / body resolution\n// ---------------------------------------------------------------------------\n\nfunction _resolveName(node: SyntaxNode, source: string, config: LanguageConfig): string | null {\n if (config.resolveFunctionNameFn !== null) {\n return null; // caller handles this separately\n }\n const n = node.childForFieldName(config.nameField);\n if (n) return _readText(n, source);\n for (const child of node.children) {\n if (config.nameFallbackChildTypes.includes(child.type)) {\n return _readText(child, source);\n }\n }\n return null;\n}\n\nfunction _findBody(node: SyntaxNode, config: LanguageConfig): SyntaxNode | null {\n const b = node.childForFieldName(config.bodyField);\n if (b) return b;\n for (const child of node.children) {\n if (config.bodyFallbackChildTypes.includes(child.type)) {\n return child;\n }\n }\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Import handlers\n// ---------------------------------------------------------------------------\n\nfunction _importPython(\n node: SyntaxNode, source: string, fileNid: string, _stem: string,\n edges: GraphEdge[], strPath: string,\n): void {\n const t = node.type;\n if (t === \"import_statement\") {\n for (const child of node.children) {\n if (child.type === \"dotted_name\" || child.type === \"aliased_import\") {\n const raw = _readText(child, source);\n const moduleName = raw.split(\" as \")[0]!.trim().replace(/^\\.+/, \"\");\n const tgtNid = _makeId(moduleName);\n edges.push({\n source: fileNid, target: tgtNid, relation: \"imports\",\n confidence: \"EXTRACTED\", source_file: strPath,\n source_location: `L${node.startPosition.row + 1}`, weight: 1.0,\n });\n }\n }\n } else if (t === \"import_from_statement\") {\n const moduleNode = node.childForFieldName(\"module_name\");\n if (moduleNode) {\n const raw = _readText(moduleNode, source).replace(/^\\.+/, \"\");\n const tgtNid = _makeId(raw);\n edges.push({\n source: fileNid, target: tgtNid, relation: \"imports_from\",\n confidence: \"EXTRACTED\", source_file: strPath,\n source_location: `L${node.startPosition.row + 1}`, weight: 1.0,\n });\n }\n }\n}\n\nfunction _importJs(\n node: SyntaxNode, source: string, fileNid: string, _stem: string,\n edges: GraphEdge[], strPath: string,\n): void {\n for (const child of node.children) {\n if (child.type === \"string\") {\n const raw = _readText(child, source).replace(/^['\"`\\s]+|['\"`\\s]+$/g, \"\");\n const moduleName = raw.replace(/^\\.\\/|^\\.\\.\\//, \"\").split(\"/\").pop() ?? \"\";\n if (moduleName) {\n const tgtNid = _makeId(moduleName);\n edges.push({\n source: fileNid, target: tgtNid, relation: \"imports_from\",\n confidence: \"EXTRACTED\", source_file: strPath,\n source_location: `L${node.startPosition.row + 1}`, weight: 1.0,\n });\n }\n break;\n }\n }\n}\n\nfunction _importJava(\n node: SyntaxNode, source: string, fileNid: string, _stem: string,\n edges: GraphEdge[], strPath: string,\n): void {\n function walkScoped(n: SyntaxNode): string {\n const parts: string[] = [];\n let cur: SyntaxNode | null = n;\n while (cur) {\n if (cur.type === \"scoped_identifier\") {\n const nameNode = cur.childForFieldName(\"name\");\n if (nameNode) parts.push(_readText(nameNode, source));\n cur = cur.childForFieldName(\"scope\");\n } else if (cur.type === \"identifier\") {\n parts.push(_readText(cur, source));\n break;\n } else {\n break;\n }\n }\n parts.reverse();\n return parts.join(\".\");\n }\n\n for (const child of node.children) {\n if (child.type === \"scoped_identifier\" || child.type === \"identifier\") {\n const pathStr = walkScoped(child);\n const pathParts = pathStr.split(\".\");\n let moduleName = pathParts[pathParts.length - 1]!.replace(/\\*/g, \"\").replace(/\\.+$/, \"\").trim();\n if (!moduleName && pathParts.length > 1) {\n moduleName = pathParts[pathParts.length - 2]!;\n }\n if (!moduleName) moduleName = pathStr;\n if (moduleName) {\n const tgtNid = _makeId(moduleName);\n edges.push({\n source: fileNid, target: tgtNid, relation: \"imports\",\n confidence: \"EXTRACTED\", source_file: strPath,\n source_location: `L${node.startPosition.row + 1}`, weight: 1.0,\n });\n }\n break;\n }\n }\n}\n\nfunction _importC(\n node: SyntaxNode, source: string, fileNid: string, _stem: string,\n edges: GraphEdge[], strPath: string,\n): void {\n for (const child of node.children) {\n if ([\"string_literal\", \"system_lib_string\", \"string\"].includes(child.type)) {\n const raw = _readText(child, source).replace(/^[\"<>\\s]+|[\"<>\\s]+$/g, \"\");\n const moduleName = raw.split(\"/\").pop()!.split(\".\")[0]!;\n if (moduleName) {\n const tgtNid = _makeId(moduleName);\n edges.push({\n source: fileNid, target: tgtNid, relation: \"imports\",\n confidence: \"EXTRACTED\", source_file: strPath,\n source_location: `L${node.startPosition.row + 1}`, weight: 1.0,\n });\n }\n break;\n }\n }\n}\n\nfunction _importCsharp(\n node: SyntaxNode, source: string, fileNid: string, _stem: string,\n edges: GraphEdge[], strPath: string,\n): void {\n for (const child of node.children) {\n if ([\"qualified_name\", \"identifier\", \"name_equals\"].includes(child.type)) {\n const raw = _readText(child, source);\n const moduleName = raw.split(\".\").pop()!.trim();\n if (moduleName) {\n const tgtNid = _makeId(moduleName);\n edges.push({\n source: fileNid, target: tgtNid, relation: \"imports\",\n confidence: \"EXTRACTED\", source_file: strPath,\n source_location: `L${node.startPosition.row + 1}`, weight: 1.0,\n });\n }\n break;\n }\n }\n}\n\nfunction _importKotlin(\n node: SyntaxNode, source: string, fileNid: string, _stem: string,\n edges: GraphEdge[], strPath: string,\n): void {\n const pathNode = node.childForFieldName(\"path\");\n if (pathNode) {\n const raw = _readText(pathNode, source);\n const moduleName = raw.split(\".\").pop()!.trim();\n if (moduleName) {\n const tgtNid = _makeId(moduleName);\n edges.push({\n source: fileNid, target: tgtNid, relation: \"imports\",\n confidence: \"EXTRACTED\", source_file: strPath,\n source_location: `L${node.startPosition.row + 1}`, weight: 1.0,\n });\n }\n return;\n }\n // Fallback: find identifier child\n for (const child of node.children) {\n if (child.type === \"identifier\") {\n const raw = _readText(child, source);\n const tgtNid = _makeId(raw);\n edges.push({\n source: fileNid, target: tgtNid, relation: \"imports\",\n confidence: \"EXTRACTED\", source_file: strPath,\n source_location: `L${node.startPosition.row + 1}`, weight: 1.0,\n });\n break;\n }\n }\n}\n\nfunction _importScala(\n node: SyntaxNode, source: string, fileNid: string, _stem: string,\n edges: GraphEdge[], strPath: string,\n): void {\n for (const child of node.children) {\n if (child.type === \"stable_id\" || child.type === \"identifier\") {\n const raw = _readText(child, source);\n const moduleName = raw.split(\".\").pop()!.replace(/[{}\\s]/g, \"\").trim();\n if (moduleName && moduleName !== \"_\") {\n const tgtNid = _makeId(moduleName);\n edges.push({\n source: fileNid, target: tgtNid, relation: \"imports\",\n confidence: \"EXTRACTED\", source_file: strPath,\n source_location: `L${node.startPosition.row + 1}`, weight: 1.0,\n });\n }\n break;\n }\n }\n}\n\nfunction _importPhp(\n node: SyntaxNode, source: string, fileNid: string, _stem: string,\n edges: GraphEdge[], strPath: string,\n): void {\n for (const child of node.children) {\n if ([\"qualified_name\", \"name\", \"identifier\"].includes(child.type)) {\n const raw = _readText(child, source);\n const moduleName = raw.split(\"\\\\\").pop()!.trim();\n if (moduleName) {\n const tgtNid = _makeId(moduleName);\n edges.push({\n source: fileNid, target: tgtNid, relation: \"imports\",\n confidence: \"EXTRACTED\", source_file: strPath,\n source_location: `L${node.startPosition.row + 1}`, weight: 1.0,\n });\n }\n break;\n }\n }\n}\n\nfunction _importLua(\n node: SyntaxNode, source: string, fileNid: string, _stem: string,\n edges: GraphEdge[], strPath: string,\n): void {\n const text = _readText(node, source);\n const m = text.match(/require\\s*[('\"]?\\s*['\"]?([^'\")\\s]+)/);\n if (m) {\n const moduleName = m[1]!.split(\".\").pop()!;\n if (moduleName) {\n edges.push({\n source: fileNid, target: moduleName, relation: \"imports\",\n confidence: \"EXTRACTED\", source_file: strPath,\n source_location: String(node.startPosition.row + 1), weight: 1.0,\n });\n }\n }\n}\n\nfunction _importSwift(\n node: SyntaxNode, source: string, fileNid: string, _stem: string,\n edges: GraphEdge[], strPath: string,\n): void {\n for (const child of node.children) {\n if (child.type === \"identifier\") {\n const raw = _readText(child, source);\n const tgtNid = _makeId(raw);\n edges.push({\n source: fileNid, target: tgtNid, relation: \"imports\",\n confidence: \"EXTRACTED\", source_file: strPath,\n source_location: `L${node.startPosition.row + 1}`, weight: 1.0,\n });\n break;\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// C/C++ function name helpers\n// ---------------------------------------------------------------------------\n\nfunction _getCFuncName(node: SyntaxNode, source: string): string | null {\n if (node.type === \"identifier\") return _readText(node, source);\n const decl = node.childForFieldName(\"declarator\");\n if (decl) return _getCFuncName(decl, source);\n for (const child of node.children) {\n if (child.type === \"identifier\") return _readText(child, source);\n }\n return null;\n}\n\nfunction _getCppFuncName(node: SyntaxNode, source: string): string | null {\n if (node.type === \"identifier\") return _readText(node, source);\n if (node.type === \"qualified_identifier\") {\n const nameNode = node.childForFieldName(\"name\");\n if (nameNode) return _readText(nameNode, source);\n }\n const decl = node.childForFieldName(\"declarator\");\n if (decl) return _getCppFuncName(decl, source);\n for (const child of node.children) {\n if (child.type === \"identifier\") return _readText(child, source);\n }\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// JS/TS extra walk for arrow functions\n// ---------------------------------------------------------------------------\n\nfunction _jsExtraWalk(\n node: SyntaxNode, source: string, fileNid: string, stem: string, _strPath: string,\n _nodes: GraphNode[], _edges: GraphEdge[], _seenIds: Set<string>,\n functionBodies: Array<[string, SyntaxNode]>,\n _parentClassNid: string | null,\n addNodeFn: (nid: string, label: string, line: number) => void,\n addEdgeFn: (src: string, tgt: string, relation: string, line: number) => void,\n): boolean {\n if (node.type === \"lexical_declaration\") {\n for (const child of node.children) {\n if (child.type === \"variable_declarator\") {\n const value = child.childForFieldName(\"value\");\n if (value && value.type === \"arrow_function\") {\n const nameNode = child.childForFieldName(\"name\");\n if (nameNode) {\n const funcName = _readText(nameNode, source);\n const line = child.startPosition.row + 1;\n const funcNid = _makeId(stem, funcName);\n addNodeFn(funcNid, `${funcName}()`, line);\n addEdgeFn(fileNid, funcNid, \"contains\", line);\n const body = value.childForFieldName(\"body\");\n if (body) {\n functionBodies.push([funcNid, body]);\n }\n }\n }\n }\n }\n return true;\n }\n return false;\n}\n\n// ---------------------------------------------------------------------------\n// C# extra walk for namespace declarations\n// ---------------------------------------------------------------------------\n\nfunction _csharpExtraWalk(\n node: SyntaxNode, source: string, fileNid: string, stem: string, _strPath: string,\n _nodes: GraphNode[], _edges: GraphEdge[], _seenIds: Set<string>,\n _functionBodies: Array<[string, SyntaxNode]>,\n parentClassNid: string | null,\n addNodeFn: (nid: string, label: string, line: number) => void,\n addEdgeFn: (src: string, tgt: string, relation: string, line: number) => void,\n walkFn?: (node: SyntaxNode, parentClassNid: string | null) => void,\n): boolean {\n if (node.type === \"namespace_declaration\") {\n const nameNode = node.childForFieldName(\"name\");\n if (nameNode) {\n const nsName = _readText(nameNode, source);\n const nsNid = _makeId(stem, nsName);\n const line = node.startPosition.row + 1;\n addNodeFn(nsNid, nsName, line);\n addEdgeFn(fileNid, nsNid, \"contains\", line);\n }\n const body = node.childForFieldName(\"body\");\n if (body && walkFn) {\n for (const child of body.children) {\n walkFn(child, parentClassNid);\n }\n }\n return true;\n }\n return false;\n}\n\n// ---------------------------------------------------------------------------\n// Swift extra walk for enum cases\n// ---------------------------------------------------------------------------\n\nfunction _swiftExtraWalk(\n node: SyntaxNode, source: string, _fileNid: string, _stem: string, _strPath: string,\n _nodes: GraphNode[], _edges: GraphEdge[], _seenIds: Set<string>,\n _functionBodies: Array<[string, SyntaxNode]>,\n parentClassNid: string | null,\n addNodeFn: (nid: string, label: string, line: number) => void,\n addEdgeFn: (src: string, tgt: string, relation: string, line: number) => void,\n): boolean {\n if (node.type === \"enum_entry\" && parentClassNid) {\n for (const child of node.children) {\n if (child.type === \"simple_identifier\") {\n const caseName = _readText(child, source);\n const caseNid = _makeId(parentClassNid, caseName);\n const line = node.startPosition.row + 1;\n addNodeFn(caseNid, caseName, line);\n addEdgeFn(parentClassNid, caseNid, \"case_of\", line);\n }\n }\n return true;\n }\n return false;\n}\n\n// ---------------------------------------------------------------------------\n// Language configs\n// ---------------------------------------------------------------------------\n\nconst _PYTHON_CONFIG: LanguageConfig = defaultConfig({\n tsGrammarName: \"python\",\n tsModule: \"tree_sitter_python\",\n classTypes: new Set([\"class_definition\"]),\n functionTypes: new Set([\"function_definition\"]),\n importTypes: new Set([\"import_statement\", \"import_from_statement\"]),\n callTypes: new Set([\"call\"]),\n callFunctionField: \"function\",\n callAccessorNodeTypes: new Set([\"attribute\"]),\n callAccessorField: \"attribute\",\n functionBoundaryTypes: new Set([\"function_definition\"]),\n importHandler: _importPython,\n});\n\nconst _JS_CONFIG: LanguageConfig = defaultConfig({\n tsGrammarName: \"javascript\",\n tsModule: \"tree_sitter_javascript\",\n classTypes: new Set([\"class_declaration\"]),\n functionTypes: new Set([\"function_declaration\", \"method_definition\"]),\n importTypes: new Set([\"import_statement\"]),\n callTypes: new Set([\"call_expression\"]),\n callFunctionField: \"function\",\n callAccessorNodeTypes: new Set([\"member_expression\"]),\n callAccessorField: \"property\",\n functionBoundaryTypes: new Set([\"function_declaration\", \"arrow_function\", \"method_definition\"]),\n importHandler: _importJs,\n});\n\nconst _TS_CONFIG: LanguageConfig = defaultConfig({\n tsGrammarName: \"typescript\",\n tsModule: \"tree_sitter_typescript\",\n classTypes: new Set([\"class_declaration\"]),\n functionTypes: new Set([\"function_declaration\", \"method_definition\"]),\n importTypes: new Set([\"import_statement\"]),\n callTypes: new Set([\"call_expression\"]),\n callFunctionField: \"function\",\n callAccessorNodeTypes: new Set([\"member_expression\"]),\n callAccessorField: \"property\",\n functionBoundaryTypes: new Set([\"function_declaration\", \"arrow_function\", \"method_definition\"]),\n importHandler: _importJs,\n});\n\nconst _JAVA_CONFIG: LanguageConfig = defaultConfig({\n tsGrammarName: \"java\",\n tsModule: \"tree_sitter_java\",\n classTypes: new Set([\"class_declaration\", \"interface_declaration\"]),\n functionTypes: new Set([\"method_declaration\", \"constructor_declaration\"]),\n importTypes: new Set([\"import_declaration\"]),\n callTypes: new Set([\"method_invocation\"]),\n callFunctionField: \"name\",\n callAccessorNodeTypes: new Set(),\n functionBoundaryTypes: new Set([\"method_declaration\", \"constructor_declaration\"]),\n importHandler: _importJava,\n});\n\nconst _C_CONFIG: LanguageConfig = defaultConfig({\n tsGrammarName: \"c\",\n tsModule: \"tree_sitter_c\",\n classTypes: new Set(),\n functionTypes: new Set([\"function_definition\"]),\n importTypes: new Set([\"preproc_include\"]),\n callTypes: new Set([\"call_expression\"]),\n callFunctionField: \"function\",\n callAccessorNodeTypes: new Set([\"field_expression\"]),\n callAccessorField: \"field\",\n functionBoundaryTypes: new Set([\"function_definition\"]),\n importHandler: _importC,\n resolveFunctionNameFn: _getCFuncName,\n});\n\nconst _CPP_CONFIG: LanguageConfig = defaultConfig({\n tsGrammarName: \"cpp\",\n tsModule: \"tree_sitter_cpp\",\n classTypes: new Set([\"class_specifier\"]),\n functionTypes: new Set([\"function_definition\"]),\n importTypes: new Set([\"preproc_include\"]),\n callTypes: new Set([\"call_expression\"]),\n callFunctionField: \"function\",\n callAccessorNodeTypes: new Set([\"field_expression\", \"qualified_identifier\"]),\n callAccessorField: \"field\",\n functionBoundaryTypes: new Set([\"function_definition\"]),\n importHandler: _importC,\n resolveFunctionNameFn: _getCppFuncName,\n});\n\nconst _RUBY_CONFIG: LanguageConfig = defaultConfig({\n tsGrammarName: \"ruby\",\n tsModule: \"tree_sitter_ruby\",\n classTypes: new Set([\"class\"]),\n functionTypes: new Set([\"method\", \"singleton_method\"]),\n importTypes: new Set(),\n callTypes: new Set([\"call\"]),\n callFunctionField: \"method\",\n callAccessorNodeTypes: new Set(),\n nameFallbackChildTypes: [\"constant\", \"scope_resolution\", \"identifier\"],\n bodyFallbackChildTypes: [\"body_statement\"],\n functionBoundaryTypes: new Set([\"method\", \"singleton_method\"]),\n});\n\nconst _CSHARP_CONFIG: LanguageConfig = defaultConfig({\n tsGrammarName: \"c_sharp\",\n tsModule: \"tree_sitter_c_sharp\",\n classTypes: new Set([\"class_declaration\", \"interface_declaration\"]),\n functionTypes: new Set([\"method_declaration\"]),\n importTypes: new Set([\"using_directive\"]),\n callTypes: new Set([\"invocation_expression\"]),\n callFunctionField: \"function\",\n callAccessorNodeTypes: new Set([\"member_access_expression\"]),\n callAccessorField: \"name\",\n bodyFallbackChildTypes: [\"declaration_list\"],\n functionBoundaryTypes: new Set([\"method_declaration\"]),\n importHandler: _importCsharp,\n});\n\nconst _KOTLIN_CONFIG: LanguageConfig = defaultConfig({\n tsGrammarName: \"kotlin\",\n tsModule: \"tree_sitter_kotlin\",\n classTypes: new Set([\"class_declaration\", \"object_declaration\"]),\n functionTypes: new Set([\"function_declaration\"]),\n importTypes: new Set([\"import_header\"]),\n callTypes: new Set([\"call_expression\"]),\n callFunctionField: \"\",\n callAccessorNodeTypes: new Set([\"navigation_expression\"]),\n callAccessorField: \"\",\n nameFallbackChildTypes: [\"simple_identifier\"],\n bodyFallbackChildTypes: [\"function_body\", \"class_body\"],\n functionBoundaryTypes: new Set([\"function_declaration\"]),\n importHandler: _importKotlin,\n});\n\nconst _SCALA_CONFIG: LanguageConfig = defaultConfig({\n tsGrammarName: \"scala\",\n tsModule: \"tree_sitter_scala\",\n classTypes: new Set([\"class_definition\", \"object_definition\"]),\n functionTypes: new Set([\"function_definition\"]),\n importTypes: new Set([\"import_declaration\"]),\n callTypes: new Set([\"call_expression\"]),\n callFunctionField: \"\",\n callAccessorNodeTypes: new Set([\"field_expression\"]),\n callAccessorField: \"field\",\n nameFallbackChildTypes: [\"identifier\"],\n bodyFallbackChildTypes: [\"template_body\"],\n functionBoundaryTypes: new Set([\"function_definition\"]),\n importHandler: _importScala,\n});\n\nconst _PHP_CONFIG: LanguageConfig = defaultConfig({\n tsGrammarName: \"php\",\n tsModule: \"tree_sitter_php\",\n classTypes: new Set([\"class_declaration\"]),\n functionTypes: new Set([\"function_definition\", \"method_declaration\"]),\n importTypes: new Set([\"namespace_use_clause\"]),\n callTypes: new Set([\"function_call_expression\", \"member_call_expression\"]),\n callFunctionField: \"function\",\n callAccessorNodeTypes: new Set([\"member_call_expression\"]),\n callAccessorField: \"name\",\n nameFallbackChildTypes: [\"name\"],\n bodyFallbackChildTypes: [\"declaration_list\", \"compound_statement\"],\n functionBoundaryTypes: new Set([\"function_definition\", \"method_declaration\"]),\n importHandler: _importPhp,\n});\n\nconst _LUA_CONFIG: LanguageConfig = defaultConfig({\n tsGrammarName: \"lua\",\n tsModule: \"tree_sitter_lua\",\n classTypes: new Set(),\n functionTypes: new Set([\"function_declaration\"]),\n importTypes: new Set([\"variable_declaration\"]),\n callTypes: new Set([\"function_call\"]),\n callFunctionField: \"name\",\n callAccessorNodeTypes: new Set([\"method_index_expression\"]),\n callAccessorField: \"name\",\n nameFallbackChildTypes: [\"identifier\", \"method_index_expression\"],\n bodyFallbackChildTypes: [\"block\"],\n functionBoundaryTypes: new Set([\"function_declaration\"]),\n importHandler: _importLua,\n});\n\nconst _SWIFT_CONFIG: LanguageConfig = defaultConfig({\n tsGrammarName: \"swift\",\n tsModule: \"tree_sitter_swift\",\n classTypes: new Set([\"class_declaration\", \"protocol_declaration\"]),\n functionTypes: new Set([\"function_declaration\", \"init_declaration\", \"deinit_declaration\", \"subscript_declaration\"]),\n importTypes: new Set([\"import_declaration\"]),\n callTypes: new Set([\"call_expression\"]),\n callFunctionField: \"\",\n callAccessorNodeTypes: new Set([\"navigation_expression\"]),\n callAccessorField: \"\",\n nameFallbackChildTypes: [\"simple_identifier\", \"type_identifier\", \"user_type\"],\n bodyFallbackChildTypes: [\"class_body\", \"protocol_body\", \"function_body\", \"enum_class_body\"],\n functionBoundaryTypes: new Set([\"function_declaration\", \"init_declaration\", \"deinit_declaration\", \"subscript_declaration\"]),\n importHandler: _importSwift,\n});\n\n// ---------------------------------------------------------------------------\n// Generic extractor\n// ---------------------------------------------------------------------------\n\nexport interface ExtractionResult {\n nodes: GraphNode[];\n edges: GraphEdge[];\n error?: string;\n}\n\nasync function _extractGeneric(filePath: string, config: LanguageConfig): Promise<ExtractionResult> {\n await ensureParserInit();\n const lang = await loadLanguage(config.tsGrammarName);\n if (!lang) {\n return { nodes: [], edges: [], error: `Grammar not found for ${config.tsGrammarName}` };\n }\n\n let source: string;\n let tree: Tree;\n try {\n const parser = new Parser();\n parser.setLanguage(lang);\n source = readFileSync(filePath, \"utf-8\");\n tree = parseText(parser, source);\n } catch (e: unknown) {\n return { nodes: [], edges: [], error: String(e) };\n }\n\n const root = tree.rootNode;\n const stem = basename(filePath, extname(filePath));\n const strPath = filePath;\n const nodes: GraphNode[] = [];\n const edges: GraphEdge[] = [];\n const seenIds = new Set<string>();\n const functionBodies: Array<[string, SyntaxNode]> = [];\n\n function addNode(nid: string, label: string, line: number): void {\n if (!seenIds.has(nid)) {\n seenIds.add(nid);\n nodes.push({\n id: nid, label, file_type: \"code\",\n source_file: strPath, source_location: `L${line}`,\n });\n }\n }\n\n function addEdge(\n src: string, tgt: string, relation: string, line: number,\n confidence: \"EXTRACTED\" | \"INFERRED\" = \"EXTRACTED\", weight: number = 1.0,\n ): void {\n edges.push({\n source: src, target: tgt, relation,\n confidence, source_file: strPath,\n source_location: `L${line}`, weight,\n });\n }\n\n const fileNid = _makeId(stem);\n addNode(fileNid, basename(filePath), 1);\n\n function walk(node: SyntaxNode, parentClassNid: string | null = null): void {\n const t = node.type;\n\n // Import types\n if (config.importTypes.has(t)) {\n if (config.importHandler) {\n config.importHandler(node, source, fileNid, stem, edges, strPath);\n }\n return;\n }\n\n // Class types\n if (config.classTypes.has(t)) {\n let nameNode = node.childForFieldName(config.nameField);\n if (!nameNode) {\n for (const child of node.children) {\n if (config.nameFallbackChildTypes.includes(child.type)) {\n nameNode = child;\n break;\n }\n }\n }\n if (!nameNode) return;\n const className = _readText(nameNode, source);\n const classNid = _makeId(stem, className);\n const line = node.startPosition.row + 1;\n addNode(classNid, className, line);\n addEdge(fileNid, classNid, \"contains\", line);\n\n // Python-specific: inheritance\n if (config.tsModule === \"tree_sitter_python\") {\n const args = node.childForFieldName(\"superclasses\");\n if (args) {\n for (const arg of args.children) {\n if (arg.type === \"identifier\") {\n const base = _readText(arg, source);\n let baseNid = _makeId(stem, base);\n if (!seenIds.has(baseNid)) {\n baseNid = _makeId(base);\n if (!seenIds.has(baseNid)) {\n nodes.push({\n id: baseNid, label: base, file_type: \"code\",\n source_file: \"\", source_location: \"\",\n });\n seenIds.add(baseNid);\n }\n }\n addEdge(classNid, baseNid, \"inherits\", line);\n }\n }\n }\n }\n\n // Swift-specific: conformance / inheritance\n if (config.tsModule === \"tree_sitter_swift\") {\n for (const child of node.children) {\n if (child.type === \"inheritance_specifier\") {\n for (const sub of child.children) {\n if (sub.type === \"user_type\" || sub.type === \"type_identifier\") {\n const base = _readText(sub, source);\n let baseNid = _makeId(stem, base);\n if (!seenIds.has(baseNid)) {\n baseNid = _makeId(base);\n if (!seenIds.has(baseNid)) {\n nodes.push({\n id: baseNid, label: base, file_type: \"code\",\n source_file: \"\", source_location: \"\",\n });\n seenIds.add(baseNid);\n }\n }\n addEdge(classNid, baseNid, \"inherits\", line);\n }\n }\n }\n }\n }\n\n // C#-specific: inheritance / interface implementation via base_list\n if (config.tsModule === \"tree_sitter_c_sharp\") {\n for (const child of node.children) {\n if (child.type === \"base_list\") {\n for (const sub of child.children) {\n if (sub.type === \"identifier\" || sub.type === \"generic_name\") {\n let base: string;\n if (sub.type === \"generic_name\") {\n const nameChild = sub.childForFieldName(\"name\");\n base = nameChild ? _readText(nameChild, source) : _readText(sub.children[0]!, source);\n } else {\n base = _readText(sub, source);\n }\n let baseNid = _makeId(stem, base);\n if (!seenIds.has(baseNid)) {\n baseNid = _makeId(base);\n if (!seenIds.has(baseNid)) {\n nodes.push({\n id: baseNid, label: base, file_type: \"code\",\n source_file: \"\", source_location: \"\",\n });\n seenIds.add(baseNid);\n }\n }\n addEdge(classNid, baseNid, \"inherits\", line);\n }\n }\n }\n }\n }\n\n // Find body and recurse\n const body = _findBody(node, config);\n if (body) {\n for (const child of body.children) {\n walk(child, classNid);\n }\n }\n return;\n }\n\n // Function types\n if (config.functionTypes.has(t)) {\n let funcName: string | null = null;\n\n // Swift deinit/subscript have no name field\n if (t === \"deinit_declaration\") {\n funcName = \"deinit\";\n } else if (t === \"subscript_declaration\") {\n funcName = \"subscript\";\n } else if (config.resolveFunctionNameFn !== null) {\n // C/C++ style: use declarator\n const declarator = node.childForFieldName(\"declarator\");\n if (declarator) {\n funcName = config.resolveFunctionNameFn(declarator, source);\n }\n } else {\n let nameNode = node.childForFieldName(config.nameField);\n if (!nameNode) {\n for (const child of node.children) {\n if (config.nameFallbackChildTypes.includes(child.type)) {\n nameNode = child;\n break;\n }\n }\n }\n funcName = nameNode ? _readText(nameNode, source) : null;\n }\n\n if (!funcName) return;\n\n const line = node.startPosition.row + 1;\n let funcNid: string;\n if (parentClassNid) {\n funcNid = _makeId(parentClassNid, funcName);\n addNode(funcNid, `.${funcName}()`, line);\n addEdge(parentClassNid, funcNid, \"method\", line);\n } else {\n funcNid = _makeId(stem, funcName);\n addNode(funcNid, `${funcName}()`, line);\n addEdge(fileNid, funcNid, \"contains\", line);\n }\n\n const body = _findBody(node, config);\n if (body) {\n functionBodies.push([funcNid, body]);\n }\n return;\n }\n\n // JS/TS arrow functions\n if (config.tsModule === \"tree_sitter_javascript\" || config.tsModule === \"tree_sitter_typescript\") {\n if (_jsExtraWalk(node, source, fileNid, stem, strPath,\n nodes, edges, seenIds, functionBodies,\n parentClassNid, addNode, addEdge)) {\n return;\n }\n }\n\n // C# namespaces\n if (config.tsModule === \"tree_sitter_c_sharp\") {\n if (_csharpExtraWalk(node, source, fileNid, stem, strPath,\n nodes, edges, seenIds, functionBodies,\n parentClassNid, addNode, addEdge, walk)) {\n return;\n }\n }\n\n // Swift enum cases\n if (config.tsModule === \"tree_sitter_swift\") {\n if (_swiftExtraWalk(node, source, fileNid, stem, strPath,\n nodes, edges, seenIds, functionBodies,\n parentClassNid, addNode, addEdge)) {\n return;\n }\n }\n\n // Default: recurse\n for (const child of node.children) {\n walk(child, null);\n }\n }\n\n walk(root);\n\n // -- Call-graph pass --\n const labelToNid = new Map<string, string>();\n for (const n of nodes) {\n const raw = n.label;\n const normalised = raw.replace(/\\(?\\)$/g, \"\").replace(/^\\./, \"\");\n labelToNid.set(normalised.toLowerCase(), n.id);\n }\n\n const seenCallPairs = new Set<string>();\n\n function walkCalls(node: SyntaxNode, callerNid: string): void {\n if (config.functionBoundaryTypes.has(node.type)) return;\n\n if (config.callTypes.has(node.type)) {\n let calleeName: string | null = null;\n\n // Special handling per language\n if (config.tsModule === \"tree_sitter_swift\") {\n const first = node.children[0] ?? null;\n if (first) {\n if (first.type === \"simple_identifier\") {\n calleeName = _readText(first, source);\n } else if (first.type === \"navigation_expression\") {\n for (const child of first.children) {\n if (child.type === \"navigation_suffix\") {\n for (const sc of child.children) {\n if (sc.type === \"simple_identifier\") {\n calleeName = _readText(sc, source);\n }\n }\n }\n }\n }\n }\n } else if (config.tsModule === \"tree_sitter_kotlin\") {\n const first = node.children[0] ?? null;\n if (first) {\n if (first.type === \"simple_identifier\") {\n calleeName = _readText(first, source);\n } else if (first.type === \"navigation_expression\") {\n for (let i = first.children.length - 1; i >= 0; i--) {\n if (first.children[i]!.type === \"simple_identifier\") {\n calleeName = _readText(first.children[i]!, source);\n break;\n }\n }\n }\n }\n } else if (config.tsModule === \"tree_sitter_scala\") {\n const first = node.children[0] ?? null;\n if (first) {\n if (first.type === \"identifier\") {\n calleeName = _readText(first, source);\n } else if (first.type === \"field_expression\") {\n const field = first.childForFieldName(\"field\");\n if (field) {\n calleeName = _readText(field, source);\n } else {\n for (let i = first.children.length - 1; i >= 0; i--) {\n if (first.children[i]!.type === \"identifier\") {\n calleeName = _readText(first.children[i]!, source);\n break;\n }\n }\n }\n }\n }\n } else if (config.tsModule === \"tree_sitter_c_sharp\" && node.type === \"invocation_expression\") {\n const nameNode = node.childForFieldName(\"name\");\n if (nameNode) {\n calleeName = _readText(nameNode, source);\n } else {\n for (const child of node.children) {\n if (child.isNamed) {\n const raw = _readText(child, source);\n if (raw.includes(\".\")) {\n calleeName = raw.split(\".\").pop()!;\n } else {\n calleeName = raw;\n }\n break;\n }\n }\n }\n } else if (config.tsModule === \"tree_sitter_php\") {\n if (node.type === \"function_call_expression\") {\n const funcNode = node.childForFieldName(\"function\");\n if (funcNode) calleeName = _readText(funcNode, source);\n } else {\n const nameNode = node.childForFieldName(\"name\");\n if (nameNode) calleeName = _readText(nameNode, source);\n }\n } else if (config.tsModule === \"tree_sitter_cpp\") {\n const funcNode = config.callFunctionField ? node.childForFieldName(config.callFunctionField) : null;\n if (funcNode) {\n if (funcNode.type === \"identifier\") {\n calleeName = _readText(funcNode, source);\n } else if (funcNode.type === \"field_expression\" || funcNode.type === \"qualified_identifier\") {\n const name = funcNode.childForFieldName(\"field\") ?? funcNode.childForFieldName(\"name\");\n if (name) calleeName = _readText(name, source);\n }\n }\n } else {\n // Generic: get callee from callFunctionField\n const funcNode = config.callFunctionField ? node.childForFieldName(config.callFunctionField) : null;\n if (funcNode) {\n if (funcNode.type === \"identifier\") {\n calleeName = _readText(funcNode, source);\n } else if (config.callAccessorNodeTypes.has(funcNode.type)) {\n if (config.callAccessorField) {\n const attr = funcNode.childForFieldName(config.callAccessorField);\n if (attr) calleeName = _readText(attr, source);\n }\n } else {\n // Try reading the node directly (e.g. Java name field is the callee)\n calleeName = _readText(funcNode, source);\n }\n }\n }\n\n if (calleeName) {\n const tgtNid = labelToNid.get(calleeName.toLowerCase());\n if (tgtNid && tgtNid !== callerNid) {\n const pair = `${callerNid}|${tgtNid}`;\n if (!seenCallPairs.has(pair)) {\n seenCallPairs.add(pair);\n const line = node.startPosition.row + 1;\n edges.push({\n source: callerNid, target: tgtNid, relation: \"calls\",\n confidence: \"EXTRACTED\", source_file: strPath,\n source_location: `L${line}`, weight: 1.0,\n });\n }\n }\n }\n }\n\n for (const child of node.children) {\n walkCalls(child, callerNid);\n }\n }\n\n for (const [callerNid, bodyNode] of functionBodies) {\n walkCalls(bodyNode, callerNid);\n }\n\n // -- Clean edges --\n const validIds = seenIds;\n const cleanEdges = edges.filter((edge) => {\n const src = edge.source;\n const tgt = edge.target;\n return validIds.has(src) && (validIds.has(tgt) || edge.relation === \"imports\" || edge.relation === \"imports_from\");\n });\n\n return { nodes, edges: cleanEdges };\n}\n\n// ---------------------------------------------------------------------------\n// Python rationale extraction\n// ---------------------------------------------------------------------------\n\nconst _RATIONALE_PREFIXES = [\n \"# NOTE:\", \"# IMPORTANT:\", \"# HACK:\", \"# WHY:\",\n \"# RATIONALE:\", \"# TODO:\", \"# FIXME:\",\n];\n\nasync function _extractPythonRationale(filePath: string, result: ExtractionResult): Promise<void> {\n await ensureParserInit();\n const lang = await loadLanguage(\"python\");\n if (!lang) return;\n\n let source: string;\n let root: SyntaxNode;\n try {\n const parser = new Parser();\n parser.setLanguage(lang);\n source = readFileSync(filePath, \"utf-8\");\n const tree = parseText(parser, source);\n root = tree.rootNode;\n } catch {\n return;\n }\n\n const stem = basename(filePath, extname(filePath));\n const strPath = filePath;\n const { nodes, edges } = result;\n const seenIds = new Set(nodes.map((n) => n.id));\n const fileNid = _makeId(stem);\n\n function getDocstring(bodyNode: SyntaxNode | null): [string, number] | null {\n if (!bodyNode) return null;\n for (const child of bodyNode.children) {\n if (child.type === \"expression_statement\") {\n for (const sub of child.children) {\n if (sub.type === \"string\" || sub.type === \"concatenated_string\") {\n let text = source.slice(sub.startIndex, sub.endIndex);\n text = text.replace(/^[\"']+|[\"']+$/g, \"\").replace(/^\"\"\"+|\"\"\"+$/g, \"\").replace(/^'''+|'''+$/g, \"\").trim();\n if (text.length > 20) {\n return [text, child.startPosition.row + 1];\n }\n }\n }\n }\n break;\n }\n return null;\n }\n\n function addRationale(text: string, line: number, parentNid: string): void {\n const label = text.slice(0, 80).replace(/\\n/g, \" \").trim();\n const rid = _makeId(stem, \"rationale\", String(line));\n if (!seenIds.has(rid)) {\n seenIds.add(rid);\n nodes.push({\n id: rid, label, file_type: \"rationale\" as GraphNode[\"file_type\"],\n source_file: strPath, source_location: `L${line}`,\n });\n }\n edges.push({\n source: rid, target: parentNid, relation: \"rationale_for\",\n confidence: \"EXTRACTED\", source_file: strPath,\n source_location: `L${line}`, weight: 1.0,\n });\n }\n\n // Module-level docstring\n const ds = getDocstring(root);\n if (ds) addRationale(ds[0], ds[1], fileNid);\n\n // Class and function docstrings\n function walkDocstrings(node: SyntaxNode, parentNid: string): void {\n const t = node.type;\n if (t === \"class_definition\") {\n const nameNode = node.childForFieldName(\"name\");\n const body = node.childForFieldName(\"body\");\n if (nameNode && body) {\n const className = source.slice(nameNode.startIndex, nameNode.endIndex);\n const nid = _makeId(stem, className);\n const classDs = getDocstring(body);\n if (classDs) addRationale(classDs[0], classDs[1], nid);\n for (const child of body.children) {\n walkDocstrings(child, nid);\n }\n }\n return;\n }\n if (t === \"function_definition\") {\n const nameNode = node.childForFieldName(\"name\");\n const body = node.childForFieldName(\"body\");\n if (nameNode && body) {\n const funcName = source.slice(nameNode.startIndex, nameNode.endIndex);\n const nid = parentNid !== fileNid ? _makeId(parentNid, funcName) : _makeId(stem, funcName);\n const funcDs = getDocstring(body);\n if (funcDs) addRationale(funcDs[0], funcDs[1], nid);\n }\n return;\n }\n for (const child of node.children) {\n walkDocstrings(child, parentNid);\n }\n }\n\n walkDocstrings(root, fileNid);\n\n // Rationale comments\n const lines = source.split(\"\\n\");\n for (let lineno = 0; lineno < lines.length; lineno++) {\n const stripped = lines[lineno]!.trim();\n if (_RATIONALE_PREFIXES.some((p) => stripped.startsWith(p))) {\n addRationale(stripped, lineno + 1, fileNid);\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Public API: per-language extractors\n// ---------------------------------------------------------------------------\n\nexport async function extractPython(filePath: string): Promise<ExtractionResult> {\n const result = await _extractGeneric(filePath, _PYTHON_CONFIG);\n if (!result.error) {\n await _extractPythonRationale(filePath, result);\n }\n return result;\n}\n\nexport async function extractJs(filePath: string): Promise<ExtractionResult> {\n const ext = extname(filePath);\n const config = (ext === \".ts\" || ext === \".tsx\") ? _TS_CONFIG : _JS_CONFIG;\n return _extractGeneric(filePath, config);\n}\n\nexport async function extractJava(filePath: string): Promise<ExtractionResult> {\n return _extractGeneric(filePath, _JAVA_CONFIG);\n}\n\nexport async function extractC(filePath: string): Promise<ExtractionResult> {\n return _extractGeneric(filePath, _C_CONFIG);\n}\n\nexport async function extractCpp(filePath: string): Promise<ExtractionResult> {\n return _extractGeneric(filePath, _CPP_CONFIG);\n}\n\nexport async function extractRuby(filePath: string): Promise<ExtractionResult> {\n return _extractGeneric(filePath, _RUBY_CONFIG);\n}\n\nexport async function extractCsharp(filePath: string): Promise<ExtractionResult> {\n return _extractGeneric(filePath, _CSHARP_CONFIG);\n}\n\nexport async function extractKotlin(filePath: string): Promise<ExtractionResult> {\n return _extractGeneric(filePath, _KOTLIN_CONFIG);\n}\n\nexport async function extractScala(filePath: string): Promise<ExtractionResult> {\n return _extractGeneric(filePath, _SCALA_CONFIG);\n}\n\nexport async function extractPhp(filePath: string): Promise<ExtractionResult> {\n return _extractGeneric(filePath, _PHP_CONFIG);\n}\n\nexport async function extractLua(filePath: string): Promise<ExtractionResult> {\n return _extractGeneric(filePath, _LUA_CONFIG);\n}\n\nexport async function extractSwift(filePath: string): Promise<ExtractionResult> {\n return _extractGeneric(filePath, _SWIFT_CONFIG);\n}\n\n// ---------------------------------------------------------------------------\n// Julia extractor (custom walk)\n// ---------------------------------------------------------------------------\n\nexport async function extractJulia(filePath: string): Promise<ExtractionResult> {\n await ensureParserInit();\n const lang = await loadLanguage(\"julia\");\n if (!lang) {\n return { nodes: [], edges: [], error: \"tree-sitter-julia not available\" };\n }\n\n let source: string;\n let tree: Tree;\n try {\n const parser = new Parser();\n parser.setLanguage(lang);\n source = readFileSync(filePath, \"utf-8\");\n tree = parseText(parser, source);\n } catch (e: unknown) {\n return { nodes: [], edges: [], error: String(e) };\n }\n\n const root = tree.rootNode;\n const stem = basename(filePath, extname(filePath));\n const strPath = filePath;\n const nodes: GraphNode[] = [];\n const edges: GraphEdge[] = [];\n const seenIds = new Set<string>();\n const functionBodies: Array<[string, SyntaxNode]> = [];\n\n function addNode(nid: string, label: string, line: number): void {\n if (!seenIds.has(nid)) {\n seenIds.add(nid);\n nodes.push({ id: nid, label, file_type: \"code\", source_file: strPath, source_location: `L${line}` });\n }\n }\n\n function addEdge(\n src: string, tgt: string, relation: string, line: number,\n confidence: \"EXTRACTED\" | \"INFERRED\" = \"EXTRACTED\", weight: number = 1.0,\n ): void {\n edges.push({ source: src, target: tgt, relation, confidence, source_file: strPath, source_location: `L${line}`, weight });\n }\n\n const fileNid = _makeId(stem);\n addNode(fileNid, basename(filePath), 1);\n\n function funcNameFromSignature(sigNode: SyntaxNode): string | null {\n for (const child of sigNode.children) {\n if (child.type === \"call_expression\") {\n const callee = child.children[0] ?? null;\n if (callee && callee.type === \"identifier\") {\n return _readText(callee, source);\n }\n }\n }\n return null;\n }\n\n function walkCalls(bodyNode: SyntaxNode, funcNid: string): void {\n if (!bodyNode) return;\n const t = bodyNode.type;\n if (t === \"function_definition\" || t === \"short_function_definition\") return;\n if (t === \"call_expression\" && bodyNode.children.length > 0) {\n const callee = bodyNode.children[0]!;\n if (callee.type === \"identifier\") {\n const calleeName = _readText(callee, source);\n const targetNid = _makeId(stem, calleeName);\n addEdge(funcNid, targetNid, \"calls\", bodyNode.startPosition.row + 1, \"EXTRACTED\");\n } else if (callee.type === \"field_expression\" && callee.children.length >= 3) {\n const methodNode = callee.children[callee.children.length - 1]!;\n const methodName = _readText(methodNode, source);\n const targetNid = _makeId(stem, methodName);\n addEdge(funcNid, targetNid, \"calls\", bodyNode.startPosition.row + 1, \"EXTRACTED\");\n }\n }\n for (const child of bodyNode.children) {\n walkCalls(child, funcNid);\n }\n }\n\n function walk(node: SyntaxNode, scopeNid: string): void {\n const t = node.type;\n\n // Module\n if (t === \"module_definition\") {\n const nameNode = node.children.find((c) => c.type === \"identifier\") ?? null;\n if (nameNode) {\n const modName = _readText(nameNode, source);\n const modNid = _makeId(stem, modName);\n const line = node.startPosition.row + 1;\n addNode(modNid, modName, line);\n addEdge(fileNid, modNid, \"defines\", line);\n for (const child of node.children) {\n walk(child, modNid);\n }\n }\n return;\n }\n\n // Struct\n if (t === \"struct_definition\") {\n const typeHead = node.children.find((c) => c.type === \"type_head\") ?? null;\n if (typeHead) {\n const binExpr = typeHead.children.find((c) => c.type === \"binary_expression\") ?? null;\n if (binExpr) {\n const identifiers = binExpr.children.filter((c) => c.type === \"identifier\");\n if (identifiers.length > 0) {\n const structName = _readText(identifiers[0]!, source);\n const structNid = _makeId(stem, structName);\n const line = node.startPosition.row + 1;\n addNode(structNid, structName, line);\n addEdge(scopeNid, structNid, \"defines\", line);\n if (identifiers.length >= 2) {\n const superName = _readText(identifiers[identifiers.length - 1]!, source);\n addEdge(structNid, _makeId(stem, superName), \"inherits\", line, \"EXTRACTED\");\n }\n }\n } else {\n const nameNode = typeHead.children.find((c) => c.type === \"identifier\") ?? null;\n if (nameNode) {\n const structName = _readText(nameNode, source);\n const structNid = _makeId(stem, structName);\n const line = node.startPosition.row + 1;\n addNode(structNid, structName, line);\n addEdge(scopeNid, structNid, \"defines\", line);\n }\n }\n }\n return;\n }\n\n // Abstract type\n if (t === \"abstract_definition\") {\n const typeHead = node.children.find((c) => c.type === \"type_head\") ?? null;\n if (typeHead) {\n const nameNode = typeHead.children.find((c) => c.type === \"identifier\") ?? null;\n if (nameNode) {\n const absName = _readText(nameNode, source);\n const absNid = _makeId(stem, absName);\n const line = node.startPosition.row + 1;\n addNode(absNid, absName, line);\n addEdge(scopeNid, absNid, \"defines\", line);\n }\n }\n return;\n }\n\n // Function: function foo(...) ... end\n if (t === \"function_definition\") {\n const sigNode = node.children.find((c) => c.type === \"signature\") ?? null;\n if (sigNode) {\n const funcName = funcNameFromSignature(sigNode);\n if (funcName) {\n const funcNid = _makeId(stem, funcName);\n const line = node.startPosition.row + 1;\n addNode(funcNid, `${funcName}()`, line);\n addEdge(scopeNid, funcNid, \"defines\", line);\n functionBodies.push([funcNid, node]);\n }\n }\n return;\n }\n\n // Short function: foo(x) = expr\n if (t === \"assignment\") {\n const lhs = node.children[0] ?? null;\n if (lhs && lhs.type === \"call_expression\" && lhs.children.length > 0) {\n const callee = lhs.children[0]!;\n if (callee.type === \"identifier\") {\n const funcName = _readText(callee, source);\n const funcNid = _makeId(stem, funcName);\n const line = node.startPosition.row + 1;\n addNode(funcNid, `${funcName}()`, line);\n addEdge(scopeNid, funcNid, \"defines\", line);\n const rhs = node.children.length >= 3 ? node.children[node.children.length - 1]! : null;\n if (rhs) {\n functionBodies.push([funcNid, rhs]);\n }\n }\n }\n return;\n }\n\n // Using / Import\n if (t === \"using_statement\" || t === \"import_statement\") {\n const line = node.startPosition.row + 1;\n for (const child of node.children) {\n if (child.type === \"identifier\") {\n const modName = _readText(child, source);\n const impNid = _makeId(modName);\n addNode(impNid, modName, line);\n addEdge(scopeNid, impNid, \"imports\", line);\n } else if (child.type === \"selected_import\") {\n const identifiers = child.children.filter((c) => c.type === \"identifier\");\n if (identifiers.length > 0) {\n const pkgName = _readText(identifiers[0]!, source);\n const pkgNid = _makeId(pkgName);\n addNode(pkgNid, pkgName, line);\n addEdge(scopeNid, pkgNid, \"imports\", line);\n }\n }\n }\n return;\n }\n\n for (const child of node.children) {\n walk(child, scopeNid);\n }\n }\n\n walk(root, fileNid);\n\n for (const [funcNid, bodyNode] of functionBodies) {\n if (bodyNode.type === \"function_definition\") {\n for (const child of bodyNode.children) {\n if (child.type !== \"signature\") {\n walkCalls(child, funcNid);\n }\n }\n } else {\n walkCalls(bodyNode, funcNid);\n }\n }\n\n return { nodes, edges };\n}\n\n// ---------------------------------------------------------------------------\n// Go extractor (custom walk)\n// ---------------------------------------------------------------------------\n\nexport async function extractGo(filePath: string): Promise<ExtractionResult> {\n await ensureParserInit();\n const lang = await loadLanguage(\"go\");\n if (!lang) {\n return { nodes: [], edges: [], error: \"tree-sitter-go not available\" };\n }\n\n let source: string;\n let tree: Tree;\n try {\n const parser = new Parser();\n parser.setLanguage(lang);\n source = readFileSync(filePath, \"utf-8\");\n tree = parseText(parser, source);\n } catch (e: unknown) {\n return { nodes: [], edges: [], error: String(e) };\n }\n\n const root = tree.rootNode;\n const stem = basename(filePath, extname(filePath));\n const pkgScope = dirname(filePath).split(sep).pop() || stem;\n const strPath = filePath;\n const nodes: GraphNode[] = [];\n const edges: GraphEdge[] = [];\n const seenIds = new Set<string>();\n const functionBodies: Array<[string, SyntaxNode]> = [];\n\n function addNode(nid: string, label: string, line: number): void {\n if (!seenIds.has(nid)) {\n seenIds.add(nid);\n nodes.push({ id: nid, label, file_type: \"code\", source_file: strPath, source_location: `L${line}` });\n }\n }\n\n function addEdge(\n src: string, tgt: string, relation: string, line: number,\n confidence: \"EXTRACTED\" | \"INFERRED\" = \"EXTRACTED\", weight: number = 1.0,\n ): void {\n edges.push({ source: src, target: tgt, relation, confidence, source_file: strPath, source_location: `L${line}`, weight });\n }\n\n const fileNid = _makeId(stem);\n addNode(fileNid, basename(filePath), 1);\n\n function walk(node: SyntaxNode): void {\n const t = node.type;\n\n if (t === \"function_declaration\") {\n const nameNode = node.childForFieldName(\"name\");\n if (nameNode) {\n const funcName = _readText(nameNode, source);\n const line = node.startPosition.row + 1;\n const funcNid = _makeId(stem, funcName);\n addNode(funcNid, `${funcName}()`, line);\n addEdge(fileNid, funcNid, \"contains\", line);\n const body = node.childForFieldName(\"body\");\n if (body) functionBodies.push([funcNid, body]);\n }\n return;\n }\n\n if (t === \"method_declaration\") {\n const receiver = node.childForFieldName(\"receiver\");\n let receiverType: string | null = null;\n if (receiver) {\n for (const param of receiver.children) {\n if (param.type === \"parameter_declaration\") {\n const typeNode = param.childForFieldName(\"type\");\n if (typeNode) {\n receiverType = _readText(typeNode, source).replace(/^\\*/, \"\").trim();\n }\n break;\n }\n }\n }\n const nameNode = node.childForFieldName(\"name\");\n if (nameNode) {\n const methodName = _readText(nameNode, source);\n const line = node.startPosition.row + 1;\n let methodNid: string;\n if (receiverType) {\n const parentNid = _makeId(pkgScope, receiverType);\n addNode(parentNid, receiverType, line);\n methodNid = _makeId(parentNid, methodName);\n addNode(methodNid, `.${methodName}()`, line);\n addEdge(parentNid, methodNid, \"method\", line);\n } else {\n methodNid = _makeId(stem, methodName);\n addNode(methodNid, `${methodName}()`, line);\n addEdge(fileNid, methodNid, \"contains\", line);\n }\n const body = node.childForFieldName(\"body\");\n if (body) functionBodies.push([methodNid, body]);\n }\n return;\n }\n\n if (t === \"type_declaration\") {\n for (const child of node.children) {\n if (child.type === \"type_spec\") {\n const nameNode = child.childForFieldName(\"name\");\n if (nameNode) {\n const typeName = _readText(nameNode, source);\n const line = child.startPosition.row + 1;\n const typeNid = _makeId(pkgScope, typeName);\n addNode(typeNid, typeName, line);\n addEdge(fileNid, typeNid, \"contains\", line);\n }\n }\n }\n return;\n }\n\n if (t === \"import_declaration\") {\n for (const child of node.children) {\n if (child.type === \"import_spec_list\") {\n for (const spec of child.children) {\n if (spec.type === \"import_spec\") {\n const pathNode = spec.childForFieldName(\"path\");\n if (pathNode) {\n const raw = _readText(pathNode, source).replace(/^\"|\"$/g, \"\");\n const moduleName = raw.split(\"/\").pop()!;\n const tgtNid = _makeId(moduleName);\n addEdge(fileNid, tgtNid, \"imports_from\", spec.startPosition.row + 1);\n }\n }\n }\n } else if (child.type === \"import_spec\") {\n const pathNode = child.childForFieldName(\"path\");\n if (pathNode) {\n const raw = _readText(pathNode, source).replace(/^\"|\"$/g, \"\");\n const moduleName = raw.split(\"/\").pop()!;\n const tgtNid = _makeId(moduleName);\n addEdge(fileNid, tgtNid, \"imports_from\", child.startPosition.row + 1);\n }\n }\n }\n return;\n }\n\n for (const child of node.children) {\n walk(child);\n }\n }\n\n walk(root);\n\n // Call-graph pass\n const labelToNid = new Map<string, string>();\n for (const n of nodes) {\n const normalised = n.label.replace(/\\(?\\)$/g, \"\").replace(/^\\./, \"\");\n labelToNid.set(normalised.toLowerCase(), n.id);\n }\n\n const seenCallPairs = new Set<string>();\n\n function walkCalls(node: SyntaxNode, callerNid: string): void {\n if (node.type === \"function_declaration\" || node.type === \"method_declaration\") return;\n if (node.type === \"call_expression\") {\n const funcNode = node.childForFieldName(\"function\");\n let calleeName: string | null = null;\n if (funcNode) {\n if (funcNode.type === \"identifier\") {\n calleeName = _readText(funcNode, source);\n } else if (funcNode.type === \"selector_expression\") {\n const field = funcNode.childForFieldName(\"field\");\n if (field) calleeName = _readText(field, source);\n }\n }\n if (calleeName) {\n const tgtNid = labelToNid.get(calleeName.toLowerCase());\n if (tgtNid && tgtNid !== callerNid) {\n const pair = `${callerNid}|${tgtNid}`;\n if (!seenCallPairs.has(pair)) {\n seenCallPairs.add(pair);\n const line = node.startPosition.row + 1;\n edges.push({\n source: callerNid, target: tgtNid, relation: \"calls\",\n confidence: \"EXTRACTED\", source_file: strPath,\n source_location: `L${line}`, weight: 1.0,\n });\n }\n }\n }\n }\n for (const child of node.children) {\n walkCalls(child, callerNid);\n }\n }\n\n for (const [callerNid, bodyNode] of functionBodies) {\n walkCalls(bodyNode, callerNid);\n }\n\n const cleanEdges = edges.filter((e) =>\n seenIds.has(e.source) && (seenIds.has(e.target) || e.relation === \"imports\" || e.relation === \"imports_from\"),\n );\n\n return { nodes, edges: cleanEdges };\n}\n\n// ---------------------------------------------------------------------------\n// Rust extractor (custom walk)\n// ---------------------------------------------------------------------------\n\nexport async function extractRust(filePath: string): Promise<ExtractionResult> {\n await ensureParserInit();\n const lang = await loadLanguage(\"rust\");\n if (!lang) {\n return { nodes: [], edges: [], error: \"tree-sitter-rust not available\" };\n }\n\n let source: string;\n let tree: Tree;\n try {\n const parser = new Parser();\n parser.setLanguage(lang);\n source = readFileSync(filePath, \"utf-8\");\n tree = parseText(parser, source);\n } catch (e: unknown) {\n return { nodes: [], edges: [], error: String(e) };\n }\n\n const root = tree.rootNode;\n const stem = basename(filePath, extname(filePath));\n const strPath = filePath;\n const nodes: GraphNode[] = [];\n const edges: GraphEdge[] = [];\n const seenIds = new Set<string>();\n const functionBodies: Array<[string, SyntaxNode]> = [];\n\n function addNode(nid: string, label: string, line: number): void {\n if (!seenIds.has(nid)) {\n seenIds.add(nid);\n nodes.push({ id: nid, label, file_type: \"code\", source_file: strPath, source_location: `L${line}` });\n }\n }\n\n function addEdge(\n src: string, tgt: string, relation: string, line: number,\n confidence: \"EXTRACTED\" | \"INFERRED\" = \"EXTRACTED\", weight: number = 1.0,\n ): void {\n edges.push({ source: src, target: tgt, relation, confidence, source_file: strPath, source_location: `L${line}`, weight });\n }\n\n const fileNid = _makeId(stem);\n addNode(fileNid, basename(filePath), 1);\n\n function walk(node: SyntaxNode, parentImplNid: string | null = null): void {\n const t = node.type;\n\n if (t === \"function_item\") {\n const nameNode = node.childForFieldName(\"name\");\n if (nameNode) {\n const funcName = _readText(nameNode, source);\n const line = node.startPosition.row + 1;\n let funcNid: string;\n if (parentImplNid) {\n funcNid = _makeId(parentImplNid, funcName);\n addNode(funcNid, `.${funcName}()`, line);\n addEdge(parentImplNid, funcNid, \"method\", line);\n } else {\n funcNid = _makeId(stem, funcName);\n addNode(funcNid, `${funcName}()`, line);\n addEdge(fileNid, funcNid, \"contains\", line);\n }\n const body = node.childForFieldName(\"body\");\n if (body) functionBodies.push([funcNid, body]);\n }\n return;\n }\n\n if (t === \"struct_item\" || t === \"enum_item\" || t === \"trait_item\") {\n const nameNode = node.childForFieldName(\"name\");\n if (nameNode) {\n const itemName = _readText(nameNode, source);\n const line = node.startPosition.row + 1;\n const itemNid = _makeId(stem, itemName);\n addNode(itemNid, itemName, line);\n addEdge(fileNid, itemNid, \"contains\", line);\n }\n return;\n }\n\n if (t === \"impl_item\") {\n const typeNode = node.childForFieldName(\"type\");\n let implNid: string | null = null;\n if (typeNode) {\n const typeName = _readText(typeNode, source).trim();\n implNid = _makeId(stem, typeName);\n addNode(implNid, typeName, node.startPosition.row + 1);\n }\n const body = node.childForFieldName(\"body\");\n if (body) {\n for (const child of body.children) {\n walk(child, implNid);\n }\n }\n return;\n }\n\n if (t === \"use_declaration\") {\n const arg = node.childForFieldName(\"argument\");\n if (arg) {\n const raw = _readText(arg, source);\n const clean = raw.split(\"{\")[0]!.replace(/:+$/, \"\").replace(/\\*$/, \"\").replace(/:+$/, \"\");\n const moduleName = clean.split(\"::\").pop()!.trim();\n if (moduleName) {\n const tgtNid = _makeId(moduleName);\n addEdge(fileNid, tgtNid, \"imports_from\", node.startPosition.row + 1);\n }\n }\n return;\n }\n\n for (const child of node.children) {\n walk(child, null);\n }\n }\n\n walk(root);\n\n // Call-graph pass\n const labelToNid = new Map<string, string>();\n for (const n of nodes) {\n const normalised = n.label.replace(/\\(?\\)$/g, \"\").replace(/^\\./, \"\");\n labelToNid.set(normalised.toLowerCase(), n.id);\n }\n\n const seenCallPairs = new Set<string>();\n\n function walkCalls(node: SyntaxNode, callerNid: string): void {\n if (node.type === \"function_item\") return;\n if (node.type === \"call_expression\") {\n const funcNode = node.childForFieldName(\"function\");\n let calleeName: string | null = null;\n if (funcNode) {\n if (funcNode.type === \"identifier\") {\n calleeName = _readText(funcNode, source);\n } else if (funcNode.type === \"field_expression\") {\n const field = funcNode.childForFieldName(\"field\");\n if (field) calleeName = _readText(field, source);\n } else if (funcNode.type === \"scoped_identifier\") {\n const name = funcNode.childForFieldName(\"name\");\n if (name) calleeName = _readText(name, source);\n }\n }\n if (calleeName) {\n const tgtNid = labelToNid.get(calleeName.toLowerCase());\n if (tgtNid && tgtNid !== callerNid) {\n const pair = `${callerNid}|${tgtNid}`;\n if (!seenCallPairs.has(pair)) {\n seenCallPairs.add(pair);\n const line = node.startPosition.row + 1;\n edges.push({\n source: callerNid, target: tgtNid, relation: \"calls\",\n confidence: \"EXTRACTED\", source_file: strPath,\n source_location: `L${line}`, weight: 1.0,\n });\n }\n }\n }\n }\n for (const child of node.children) {\n walkCalls(child, callerNid);\n }\n }\n\n for (const [callerNid, bodyNode] of functionBodies) {\n walkCalls(bodyNode, callerNid);\n }\n\n const cleanEdges = edges.filter((e) =>\n seenIds.has(e.source) && (seenIds.has(e.target) || e.relation === \"imports\" || e.relation === \"imports_from\"),\n );\n\n return { nodes, edges: cleanEdges };\n}\n\n// ---------------------------------------------------------------------------\n// Zig extractor (custom walk)\n// ---------------------------------------------------------------------------\n\nexport async function extractZig(filePath: string): Promise<ExtractionResult> {\n await ensureParserInit();\n const lang = await loadLanguage(\"zig\");\n if (!lang) {\n return { nodes: [], edges: [], error: \"tree-sitter-zig not available\" };\n }\n\n let source: string;\n let tree: Tree;\n try {\n const parser = new Parser();\n parser.setLanguage(lang);\n source = readFileSync(filePath, \"utf-8\");\n tree = parseText(parser, source);\n } catch (e: unknown) {\n return { nodes: [], edges: [], error: String(e) };\n }\n\n const root = tree.rootNode;\n const stem = basename(filePath, extname(filePath));\n const strPath = filePath;\n const nodes: GraphNode[] = [];\n const edges: GraphEdge[] = [];\n const seenIds = new Set<string>();\n const functionBodies: Array<[string, SyntaxNode]> = [];\n\n function addNode(nid: string, label: string, line: number): void {\n if (!seenIds.has(nid)) {\n seenIds.add(nid);\n nodes.push({ id: nid, label, file_type: \"code\", source_file: strPath, source_location: `L${line}` });\n }\n }\n\n function addEdge(\n src: string, tgt: string, relation: string, line: number,\n confidence: \"EXTRACTED\" | \"INFERRED\" = \"EXTRACTED\", weight: number = 1.0,\n ): void {\n edges.push({ source: src, target: tgt, relation, confidence, source_file: strPath, source_location: `L${line}`, weight });\n }\n\n const fileNid = _makeId(stem);\n addNode(fileNid, basename(filePath), 1);\n\n function extractImport(node: SyntaxNode): void {\n for (const child of node.children) {\n if (child.type === \"builtin_function\") {\n let bi: string | null = null;\n let args: SyntaxNode | null = null;\n for (const c of child.children) {\n if (c.type === \"builtin_identifier\") bi = _readText(c, source);\n else if (c.type === \"arguments\") args = c;\n }\n if ((bi === \"@import\" || bi === \"@cImport\") && args) {\n for (const arg of args.children) {\n if (arg.type === \"string_literal\" || arg.type === \"string\") {\n const raw = _readText(arg, source).replace(/^\"|\"$/g, \"\");\n const moduleName = raw.split(\"/\").pop()!.split(\".\")[0]!;\n if (moduleName) {\n const tgtNid = _makeId(moduleName);\n addEdge(fileNid, tgtNid, \"imports_from\", node.startPosition.row + 1);\n }\n return;\n }\n }\n }\n } else if (child.type === \"field_expression\") {\n extractImport(child);\n return;\n }\n }\n }\n\n function walk(node: SyntaxNode, parentStructNid: string | null = null): void {\n const t = node.type;\n\n if (t === \"function_declaration\") {\n const nameNode = node.childForFieldName(\"name\");\n if (nameNode) {\n const funcName = _readText(nameNode, source);\n const line = node.startPosition.row + 1;\n let funcNid: string;\n if (parentStructNid) {\n funcNid = _makeId(parentStructNid, funcName);\n addNode(funcNid, `.${funcName}()`, line);\n addEdge(parentStructNid, funcNid, \"method\", line);\n } else {\n funcNid = _makeId(stem, funcName);\n addNode(funcNid, `${funcName}()`, line);\n addEdge(fileNid, funcNid, \"contains\", line);\n }\n const body = node.childForFieldName(\"body\");\n if (body) functionBodies.push([funcNid, body]);\n }\n return;\n }\n\n if (t === \"variable_declaration\") {\n let nameNode: SyntaxNode | null = null;\n let valueNode: SyntaxNode | null = null;\n for (const child of node.children) {\n if (child.type === \"identifier\") {\n nameNode = child;\n } else if ([\"struct_declaration\", \"enum_declaration\", \"union_declaration\", \"builtin_function\", \"field_expression\"].includes(child.type)) {\n valueNode = child;\n }\n }\n\n if (valueNode && valueNode.type === \"struct_declaration\") {\n if (nameNode) {\n const structName = _readText(nameNode, source);\n const line = node.startPosition.row + 1;\n const structNid = _makeId(stem, structName);\n addNode(structNid, structName, line);\n addEdge(fileNid, structNid, \"contains\", line);\n for (const child of valueNode.children) {\n walk(child, structNid);\n }\n }\n return;\n }\n\n if (valueNode && (valueNode.type === \"enum_declaration\" || valueNode.type === \"union_declaration\")) {\n if (nameNode) {\n const typeName = _readText(nameNode, source);\n const line = node.startPosition.row + 1;\n const typeNid = _makeId(stem, typeName);\n addNode(typeNid, typeName, line);\n addEdge(fileNid, typeNid, \"contains\", line);\n }\n return;\n }\n\n if (valueNode && (valueNode.type === \"builtin_function\" || valueNode.type === \"field_expression\")) {\n extractImport(node);\n }\n return;\n }\n\n for (const child of node.children) {\n walk(child, parentStructNid);\n }\n }\n\n walk(root);\n\n // Call-graph pass\n const seenCallPairs = new Set<string>();\n\n function walkCalls(node: SyntaxNode, callerNid: string): void {\n if (node.type === \"function_declaration\") return;\n if (node.type === \"call_expression\") {\n const fn = node.childForFieldName(\"function\");\n if (fn) {\n const callee = _readText(fn, source).split(\".\").pop()!;\n const tgtNid = nodes.find(\n (n) => n.label === `${callee}()` || n.label === `.${callee}()`,\n )?.id ?? null;\n if (tgtNid && tgtNid !== callerNid) {\n const pair = `${callerNid}|${tgtNid}`;\n if (!seenCallPairs.has(pair)) {\n seenCallPairs.add(pair);\n addEdge(callerNid, tgtNid, \"calls\", node.startPosition.row + 1, \"EXTRACTED\", 1.0);\n }\n }\n }\n }\n for (const child of node.children) {\n walkCalls(child, callerNid);\n }\n }\n\n for (const [callerNid, bodyNode] of functionBodies) {\n walkCalls(bodyNode, callerNid);\n }\n\n const cleanEdges = edges.filter((e) =>\n seenIds.has(e.source) && (seenIds.has(e.target) || e.relation === \"imports_from\"),\n );\n\n return { nodes, edges: cleanEdges };\n}\n\n// ---------------------------------------------------------------------------\n// PowerShell extractor (custom walk)\n// ---------------------------------------------------------------------------\n\nexport async function extractPowershell(filePath: string): Promise<ExtractionResult> {\n await ensureParserInit();\n const lang = await loadLanguage(\"powershell\");\n if (!lang) {\n return { nodes: [], edges: [], error: \"tree-sitter-powershell not available\" };\n }\n\n let source: string;\n let tree: Tree;\n try {\n const parser = new Parser();\n parser.setLanguage(lang);\n source = readFileSync(filePath, \"utf-8\");\n tree = parseText(parser, source);\n } catch (e: unknown) {\n return { nodes: [], edges: [], error: String(e) };\n }\n\n const root = tree.rootNode;\n const stem = basename(filePath, extname(filePath));\n const strPath = filePath;\n const nodes: GraphNode[] = [];\n const edges: GraphEdge[] = [];\n const seenIds = new Set<string>();\n const functionBodies: Array<[string, SyntaxNode]> = [];\n\n function addNode(nid: string, label: string, line: number): void {\n if (!seenIds.has(nid)) {\n seenIds.add(nid);\n nodes.push({ id: nid, label, file_type: \"code\", source_file: strPath, source_location: `L${line}` });\n }\n }\n\n function addEdge(\n src: string, tgt: string, relation: string, line: number,\n confidence: \"EXTRACTED\" | \"INFERRED\" = \"EXTRACTED\", weight: number = 1.0,\n ): void {\n edges.push({ source: src, target: tgt, relation, confidence, source_file: strPath, source_location: `L${line}`, weight });\n }\n\n const fileNid = _makeId(stem);\n addNode(fileNid, basename(filePath), 1);\n\n const _PS_SKIP = new Set([\n \"using\", \"return\", \"if\", \"else\", \"elseif\", \"foreach\", \"for\",\n \"while\", \"do\", \"switch\", \"try\", \"catch\", \"finally\", \"throw\",\n \"break\", \"continue\", \"exit\", \"param\", \"begin\", \"process\", \"end\",\n ]);\n\n function findScriptBlockBody(node: SyntaxNode): SyntaxNode | null {\n for (const child of node.children) {\n if (child.type === \"script_block\") {\n for (const sc of child.children) {\n if (sc.type === \"script_block_body\") return sc;\n }\n return child;\n }\n }\n return null;\n }\n\n function walk(node: SyntaxNode, parentClassNid: string | null = null): void {\n const t = node.type;\n\n if (t === \"function_statement\") {\n const nameNode = node.children.find((c) => c.type === \"function_name\") ?? null;\n if (nameNode) {\n const funcName = _readText(nameNode, source);\n const line = node.startPosition.row + 1;\n const funcNid = _makeId(stem, funcName);\n addNode(funcNid, `${funcName}()`, line);\n addEdge(fileNid, funcNid, \"contains\", line);\n const body = findScriptBlockBody(node);\n if (body) functionBodies.push([funcNid, body]);\n }\n return;\n }\n\n if (t === \"class_statement\") {\n const nameNode = node.children.find((c) => c.type === \"simple_name\") ?? null;\n if (nameNode) {\n const className = _readText(nameNode, source);\n const line = node.startPosition.row + 1;\n const classNid = _makeId(stem, className);\n addNode(classNid, className, line);\n addEdge(fileNid, classNid, \"contains\", line);\n for (const child of node.children) {\n walk(child, classNid);\n }\n }\n return;\n }\n\n if (t === \"class_method_definition\") {\n const nameNode = node.children.find((c) => c.type === \"simple_name\") ?? null;\n if (nameNode) {\n const methodName = _readText(nameNode, source);\n const line = node.startPosition.row + 1;\n let methodNid: string;\n if (parentClassNid) {\n methodNid = _makeId(parentClassNid, methodName);\n addNode(methodNid, `.${methodName}()`, line);\n addEdge(parentClassNid, methodNid, \"method\", line);\n } else {\n methodNid = _makeId(stem, methodName);\n addNode(methodNid, `${methodName}()`, line);\n addEdge(fileNid, methodNid, \"contains\", line);\n }\n const body = findScriptBlockBody(node);\n if (body) functionBodies.push([methodNid, body]);\n }\n return;\n }\n\n if (t === \"command\") {\n const cmdNameNode = node.children.find((c) => c.type === \"command_name\") ?? null;\n if (cmdNameNode) {\n const cmdText = _readText(cmdNameNode, source).toLowerCase();\n if (cmdText === \"using\") {\n const tokens: string[] = [];\n for (const child of node.children) {\n if (child.type === \"command_elements\") {\n for (const el of child.children) {\n if (el.type === \"generic_token\") {\n tokens.push(_readText(el, source));\n }\n }\n }\n }\n const moduleTokens = tokens.filter(\n (tk) => ![\"namespace\", \"module\", \"assembly\"].includes(tk.toLowerCase()),\n );\n if (moduleTokens.length > 0) {\n const moduleName = moduleTokens[moduleTokens.length - 1]!.split(\".\").pop()!;\n addEdge(fileNid, _makeId(moduleName), \"imports_from\", node.startPosition.row + 1);\n }\n }\n }\n return;\n }\n\n for (const child of node.children) {\n walk(child, parentClassNid);\n }\n }\n\n walk(root);\n\n // Call-graph pass\n const labelToNid = new Map<string, string>();\n for (const n of nodes) {\n const normalised = n.label.replace(/\\(?\\)$/g, \"\").replace(/^\\./, \"\");\n labelToNid.set(normalised.toLowerCase(), n.id);\n }\n\n const seenCallPairs = new Set<string>();\n\n function walkCalls(node: SyntaxNode, callerNid: string): void {\n if (node.type === \"function_statement\" || node.type === \"class_statement\") return;\n if (node.type === \"command\") {\n const cmdNameNode = node.children.find((c) => c.type === \"command_name\") ?? null;\n if (cmdNameNode) {\n const cmdText = _readText(cmdNameNode, source);\n if (!_PS_SKIP.has(cmdText.toLowerCase())) {\n const tgtNid = labelToNid.get(cmdText.toLowerCase());\n if (tgtNid && tgtNid !== callerNid) {\n const pair = `${callerNid}|${tgtNid}`;\n if (!seenCallPairs.has(pair)) {\n seenCallPairs.add(pair);\n addEdge(callerNid, tgtNid, \"calls\", node.startPosition.row + 1, \"EXTRACTED\", 1.0);\n }\n }\n }\n }\n }\n for (const child of node.children) {\n walkCalls(child, callerNid);\n }\n }\n\n for (const [callerNid, bodyNode] of functionBodies) {\n walkCalls(bodyNode, callerNid);\n }\n\n const cleanEdges = edges.filter((e) =>\n seenIds.has(e.source) && (seenIds.has(e.target) || e.relation === \"imports_from\"),\n );\n\n return { nodes, edges: cleanEdges };\n}\n\n// ---------------------------------------------------------------------------\n// Objective-C extractor (custom walk)\n// ---------------------------------------------------------------------------\n\nexport async function extractObjc(filePath: string): Promise<ExtractionResult> {\n await ensureParserInit();\n const lang = await loadLanguage(\"objc\");\n if (!lang) {\n return { nodes: [], edges: [], error: \"tree-sitter-objc not available\" };\n }\n\n let source: string;\n let tree: Tree;\n try {\n const parser = new Parser();\n parser.setLanguage(lang);\n source = readFileSync(filePath, \"utf-8\");\n tree = parseText(parser, source);\n } catch (e: unknown) {\n return { nodes: [], edges: [], error: String(e) };\n }\n\n const root = tree.rootNode;\n const stem = basename(filePath, extname(filePath));\n const strPath = filePath;\n const nodes: GraphNode[] = [];\n const edges: GraphEdge[] = [];\n const seenIds = new Set<string>();\n const methodBodies: Array<[string, SyntaxNode]> = [];\n\n function addNode(nid: string, label: string, line: number): void {\n if (!seenIds.has(nid)) {\n seenIds.add(nid);\n nodes.push({ id: nid, label, file_type: \"code\", source_file: strPath, source_location: `L${line}` });\n }\n }\n\n function addEdge(\n src: string, tgt: string, relation: string, line: number,\n confidence: \"EXTRACTED\" | \"INFERRED\" = \"EXTRACTED\", weight: number = 1.0,\n ): void {\n edges.push({ source: src, target: tgt, relation, confidence, source_file: strPath, source_location: `L${line}`, weight });\n }\n\n const fileNid = _makeId(stem);\n addNode(fileNid, basename(filePath), 1);\n\n function _read(node: SyntaxNode): string {\n return source.slice(node.startIndex, node.endIndex);\n }\n\n function walk(node: SyntaxNode, parentNid: string | null = null): void {\n const t = node.type;\n const line = node.startPosition.row + 1;\n\n if (t === \"preproc_include\") {\n for (const child of node.children) {\n if (child.type === \"system_lib_string\") {\n const raw = _read(child).replace(/^[<>]+|[<>]+$/g, \"\");\n const module = raw.split(\"/\").pop()!.replace(\".h\", \"\");\n if (module) {\n const tgtNid = _makeId(module);\n addEdge(fileNid, tgtNid, \"imports\", line);\n }\n } else if (child.type === \"string_literal\") {\n for (const sub of child.children) {\n if (sub.type === \"string_content\") {\n const raw = _read(sub);\n const module = raw.split(\"/\").pop()!.replace(\".h\", \"\");\n if (module) {\n const tgtNid = _makeId(module);\n addEdge(fileNid, tgtNid, \"imports\", line);\n }\n }\n }\n }\n }\n return;\n }\n\n if (t === \"class_interface\") {\n const identifiers = node.children.filter((c) => c.type === \"identifier\");\n if (identifiers.length === 0) {\n for (const child of node.children) walk(child, parentNid);\n return;\n }\n const name = _read(identifiers[0]!);\n const clsNid = _makeId(stem, name);\n addNode(clsNid, name, line);\n addEdge(fileNid, clsNid, \"contains\", line);\n // superclass is second identifier after ':'\n let colonSeen = false;\n for (const child of node.children) {\n if (child.type === \":\") {\n colonSeen = true;\n } else if (colonSeen && child.type === \"identifier\") {\n const superNid = _makeId(_read(child));\n addEdge(clsNid, superNid, \"inherits\", line);\n colonSeen = false;\n } else if (child.type === \"parameterized_arguments\") {\n for (const sub of child.children) {\n if (sub.type === \"type_name\") {\n for (const s of sub.children) {\n if (s.type === \"type_identifier\") {\n const protoNid = _makeId(_read(s));\n addEdge(clsNid, protoNid, \"imports\", line);\n }\n }\n }\n }\n } else if (child.type === \"method_declaration\") {\n walk(child, clsNid);\n }\n }\n return;\n }\n\n if (t === \"class_implementation\") {\n let name: string | null = null;\n for (const child of node.children) {\n if (child.type === \"identifier\") { name = _read(child); break; }\n }\n if (!name) {\n for (const child of node.children) walk(child, parentNid);\n return;\n }\n const implNid = _makeId(stem, name);\n if (!seenIds.has(implNid)) {\n addNode(implNid, name, line);\n addEdge(fileNid, implNid, \"contains\", line);\n }\n for (const child of node.children) {\n if (child.type === \"implementation_definition\") {\n for (const sub of child.children) walk(sub, implNid);\n }\n }\n return;\n }\n\n if (t === \"protocol_declaration\") {\n let name: string | null = null;\n for (const child of node.children) {\n if (child.type === \"identifier\") { name = _read(child); break; }\n }\n if (name) {\n const protoNid = _makeId(stem, name);\n addNode(protoNid, `<${name}>`, line);\n addEdge(fileNid, protoNid, \"contains\", line);\n for (const child of node.children) walk(child, protoNid);\n }\n return;\n }\n\n if (t === \"method_declaration\" || t === \"method_definition\") {\n const container = parentNid || fileNid;\n const parts: string[] = [];\n for (const child of node.children) {\n if (child.type === \"identifier\") {\n parts.push(_read(child));\n }\n }\n const methodName = parts.join(\"\") || null;\n if (methodName) {\n const methodNid = _makeId(container, methodName);\n addNode(methodNid, `-${methodName}`, line);\n addEdge(container, methodNid, \"method\", line);\n if (t === \"method_definition\") {\n methodBodies.push([methodNid, node]);\n }\n }\n return;\n }\n\n for (const child of node.children) {\n walk(child, parentNid);\n }\n }\n\n walk(root);\n\n // Second pass: resolve calls inside method bodies\n const allMethodNids = new Set(nodes.filter((n) => n.id !== fileNid).map((n) => n.id));\n const seenCalls = new Set<string>();\n\n for (const [callerNid, bodyNode] of methodBodies) {\n function objcWalkCalls(n: SyntaxNode): void {\n if (n.type === \"message_expression\") {\n for (const child of n.children) {\n if (child.type === \"selector\" || child.type === \"keyword_argument_list\") {\n const sel: string[] = [];\n if (child.type === \"selector\") {\n sel.push(_read(child));\n } else {\n for (const sub of child.children) {\n if (sub.type === \"keyword_argument\") {\n for (const s of sub.children) {\n if (s.type === \"selector\") sel.push(_read(s));\n }\n }\n }\n }\n const methodName = sel.join(\"\");\n for (const candidate of allMethodNids) {\n if (candidate.endsWith(_makeId(\"\", methodName).replace(/^_/, \"\"))) {\n const pair = `${callerNid}|${candidate}`;\n if (!seenCalls.has(pair) && callerNid !== candidate) {\n seenCalls.add(pair);\n addEdge(callerNid, candidate, \"calls\", bodyNode.startPosition.row + 1, \"EXTRACTED\", 1.0);\n }\n }\n }\n }\n }\n }\n for (const child of n.children) {\n objcWalkCalls(child);\n }\n }\n objcWalkCalls(bodyNode);\n }\n\n return { nodes, edges, error: undefined };\n}\n\n// ---------------------------------------------------------------------------\n// Elixir extractor (custom walk)\n// ---------------------------------------------------------------------------\n\nexport async function extractElixir(filePath: string): Promise<ExtractionResult> {\n await ensureParserInit();\n const lang = await loadLanguage(\"elixir\");\n if (!lang) {\n return { nodes: [], edges: [], error: \"tree-sitter-elixir not available\" };\n }\n\n let source: string;\n let tree: Tree;\n try {\n const parser = new Parser();\n parser.setLanguage(lang);\n source = readFileSync(filePath, \"utf-8\");\n tree = parseText(parser, source);\n } catch (e: unknown) {\n return { nodes: [], edges: [], error: String(e) };\n }\n\n const root = tree.rootNode;\n const stem = basename(filePath, extname(filePath));\n const strPath = filePath;\n const nodes: GraphNode[] = [];\n const edges: GraphEdge[] = [];\n const seenIds = new Set<string>();\n const functionBodies: Array<[string, SyntaxNode]> = [];\n\n function addNode(nid: string, label: string, line: number): void {\n if (!seenIds.has(nid)) {\n seenIds.add(nid);\n nodes.push({ id: nid, label, file_type: \"code\", source_file: strPath, source_location: `L${line}` });\n }\n }\n\n function addEdge(\n src: string, tgt: string, relation: string, line: number,\n confidence: \"EXTRACTED\" | \"INFERRED\" = \"EXTRACTED\", weight: number = 1.0,\n ): void {\n edges.push({ source: src, target: tgt, relation, confidence, source_file: strPath, source_location: `L${line}`, weight });\n }\n\n const fileNid = _makeId(stem);\n addNode(fileNid, basename(filePath), 1);\n\n const _IMPORT_KEYWORDS = new Set([\"alias\", \"import\", \"require\", \"use\"]);\n\n function getAliasText(node: SyntaxNode): string | null {\n for (const child of node.children) {\n if (child.type === \"alias\") {\n return source.slice(child.startIndex, child.endIndex);\n }\n }\n return null;\n }\n\n function walk(node: SyntaxNode, parentModuleNid: string | null = null): void {\n if (node.type !== \"call\") {\n for (const child of node.children) walk(child, parentModuleNid);\n return;\n }\n\n let identifierNode: SyntaxNode | null = null;\n let argumentsNode: SyntaxNode | null = null;\n let doBlockNode: SyntaxNode | null = null;\n for (const child of node.children) {\n if (child.type === \"identifier\") identifierNode = child;\n else if (child.type === \"arguments\") argumentsNode = child;\n else if (child.type === \"do_block\") doBlockNode = child;\n }\n\n if (!identifierNode) {\n for (const child of node.children) walk(child, parentModuleNid);\n return;\n }\n\n const keyword = source.slice(identifierNode.startIndex, identifierNode.endIndex);\n const line = node.startPosition.row + 1;\n\n if (keyword === \"defmodule\") {\n const moduleName = argumentsNode ? getAliasText(argumentsNode) : null;\n if (!moduleName) return;\n const moduleNid = _makeId(stem, moduleName);\n addNode(moduleNid, moduleName, line);\n addEdge(fileNid, moduleNid, \"contains\", line);\n if (doBlockNode) {\n for (const child of doBlockNode.children) walk(child, moduleNid);\n }\n return;\n }\n\n if (keyword === \"def\" || keyword === \"defp\") {\n let funcName: string | null = null;\n if (argumentsNode) {\n for (const child of argumentsNode.children) {\n if (child.type === \"call\") {\n for (const sub of child.children) {\n if (sub.type === \"identifier\") {\n funcName = source.slice(sub.startIndex, sub.endIndex);\n break;\n }\n }\n } else if (child.type === \"identifier\") {\n funcName = source.slice(child.startIndex, child.endIndex);\n break;\n }\n }\n }\n if (!funcName) return;\n const container = parentModuleNid || fileNid;\n const funcNid = _makeId(container, funcName);\n addNode(funcNid, `${funcName}()`, line);\n if (parentModuleNid) {\n addEdge(parentModuleNid, funcNid, \"method\", line);\n } else {\n addEdge(fileNid, funcNid, \"contains\", line);\n }\n if (doBlockNode) {\n functionBodies.push([funcNid, doBlockNode]);\n }\n return;\n }\n\n if (_IMPORT_KEYWORDS.has(keyword) && argumentsNode) {\n const moduleName = getAliasText(argumentsNode);\n if (moduleName) {\n const tgtNid = _makeId(moduleName);\n addEdge(fileNid, tgtNid, \"imports\", line);\n }\n return;\n }\n\n for (const child of node.children) walk(child, parentModuleNid);\n }\n\n walk(root);\n\n // Call-graph pass\n const labelToNid = new Map<string, string>();\n for (const n of nodes) {\n const normalised = n.label.replace(/\\(?\\)$/g, \"\").replace(/^\\./, \"\");\n labelToNid.set(normalised.toLowerCase(), n.id);\n }\n\n const seenCallPairs = new Set<string>();\n const _SKIP_KEYWORDS = new Set([\n \"def\", \"defp\", \"defmodule\", \"defmacro\", \"defmacrop\",\n \"defstruct\", \"defprotocol\", \"defimpl\", \"defguard\",\n \"alias\", \"import\", \"require\", \"use\",\n \"if\", \"unless\", \"case\", \"cond\", \"with\", \"for\",\n ]);\n\n function walkCalls(node: SyntaxNode, callerNid: string): void {\n if (node.type !== \"call\") {\n for (const child of node.children) walkCalls(child, callerNid);\n return;\n }\n for (const child of node.children) {\n if (child.type === \"identifier\") {\n const kw = source.slice(child.startIndex, child.endIndex);\n if (_SKIP_KEYWORDS.has(kw)) {\n for (const c of node.children) walkCalls(c, callerNid);\n return;\n }\n break;\n }\n }\n let calleeName: string | null = null;\n for (const child of node.children) {\n if (child.type === \"dot\") {\n const dotText = source.slice(child.startIndex, child.endIndex);\n const parts = dotText.replace(/\\.$/, \"\").split(\".\");\n if (parts.length > 0) calleeName = parts[parts.length - 1]!;\n break;\n }\n if (child.type === \"identifier\") {\n calleeName = source.slice(child.startIndex, child.endIndex);\n break;\n }\n }\n if (calleeName) {\n const tgtNid = labelToNid.get(calleeName.toLowerCase());\n if (tgtNid && tgtNid !== callerNid) {\n const pair = `${callerNid}|${tgtNid}`;\n if (!seenCallPairs.has(pair)) {\n seenCallPairs.add(pair);\n addEdge(callerNid, tgtNid, \"calls\", node.startPosition.row + 1, \"EXTRACTED\", 1.0);\n }\n }\n }\n for (const child of node.children) {\n walkCalls(child, callerNid);\n }\n }\n\n for (const [callerNid, body] of functionBodies) {\n walkCalls(body, callerNid);\n }\n\n const cleanEdges = edges.filter((e) =>\n seenIds.has(e.source) && (seenIds.has(e.target) || e.relation === \"imports\"),\n );\n\n return { nodes, edges: cleanEdges, error: undefined };\n}\n\n// ---------------------------------------------------------------------------\n// Cross-file import resolution (Python only)\n// ---------------------------------------------------------------------------\n\nasync function _resolveCrossFileImports(\n perFile: ExtractionResult[],\n paths: string[],\n): Promise<GraphEdge[]> {\n await ensureParserInit();\n const lang = await loadLanguage(\"python\");\n if (!lang) return [];\n\n const parser = new Parser();\n parser.setLanguage(lang);\n\n // Pass 1: name -> node_id across all files\n const stemToEntities = new Map<string, Map<string, string>>();\n for (const fileResult of perFile) {\n for (const node of fileResult.nodes ?? []) {\n const src = node.source_file ?? \"\";\n if (!src) continue;\n const fileStem = basename(src, extname(src));\n const label = node.label ?? \"\";\n const nid = node.id ?? \"\";\n if (label && !label.endsWith(\")\") && !label.endsWith(\".py\") && !label.startsWith(\"_\")) {\n if (!stemToEntities.has(fileStem)) stemToEntities.set(fileStem, new Map());\n stemToEntities.get(fileStem)!.set(label, nid);\n }\n }\n }\n\n // Pass 2\n const newEdges: GraphEdge[] = [];\n const stemToPath = new Map<string, string>();\n for (const p of paths) {\n stemToPath.set(basename(p, extname(p)), p);\n }\n\n for (let idx = 0; idx < perFile.length; idx++) {\n const fileResult = perFile[idx]!;\n const filePath = paths[idx]!;\n const fileStem = basename(filePath, extname(filePath));\n const strPath = filePath;\n\n const localClasses = fileResult.nodes\n .filter((n) =>\n n.source_file === strPath &&\n !n.label.endsWith(\")\") &&\n !n.label.endsWith(\".py\") &&\n n.id !== _makeId(fileStem),\n )\n .map((n) => n.id);\n\n if (localClasses.length === 0) continue;\n\n let source: string;\n let tree: Tree;\n try {\n source = readFileSync(filePath, \"utf-8\");\n tree = parseText(parser, source);\n } catch {\n continue;\n }\n\n function walkImports(node: SyntaxNode): void {\n if (node.type === \"import_from_statement\") {\n let targetStem: string | null = null;\n for (const child of node.children) {\n if (child.type === \"relative_import\") {\n for (const sub of child.children) {\n if (sub.type === \"dotted_name\") {\n const raw = source.slice(sub.startIndex, sub.endIndex);\n targetStem = raw.split(\".\").pop()!;\n break;\n }\n }\n break;\n }\n if (child.type === \"dotted_name\" && targetStem === null) {\n const raw = source.slice(child.startIndex, child.endIndex);\n targetStem = raw.split(\".\").pop()!;\n }\n }\n\n if (!targetStem || !stemToEntities.has(targetStem)) return;\n\n const importedNames: string[] = [];\n let pastImportKw = false;\n for (const child of node.children) {\n if (child.type === \"import\") {\n pastImportKw = true;\n continue;\n }\n if (!pastImportKw) continue;\n if (child.type === \"dotted_name\") {\n importedNames.push(source.slice(child.startIndex, child.endIndex));\n } else if (child.type === \"aliased_import\") {\n const nameNode = child.childForFieldName(\"name\");\n if (nameNode) {\n importedNames.push(source.slice(nameNode.startIndex, nameNode.endIndex));\n }\n }\n }\n\n const line = node.startPosition.row + 1;\n for (const name of importedNames) {\n const tgtNid = stemToEntities.get(targetStem)?.get(name);\n if (tgtNid) {\n for (const srcClassNid of localClasses) {\n newEdges.push({\n source: srcClassNid, target: tgtNid, relation: \"uses\",\n confidence: \"INFERRED\", source_file: strPath,\n source_location: `L${line}`, weight: 0.8,\n });\n }\n }\n }\n }\n for (const child of node.children) {\n walkImports(child);\n }\n }\n\n walkImports(tree.rootNode);\n }\n\n return newEdges;\n}\n\n// ---------------------------------------------------------------------------\n// Main extract() and collectFiles()\n// ---------------------------------------------------------------------------\n\ntype ExtractorFn = (filePath: string) => Promise<ExtractionResult>;\n\nconst _DISPATCH: Record<string, ExtractorFn> = {\n \".py\": extractPython,\n \".js\": extractJs,\n \".jsx\": extractJs,\n \".ts\": extractJs,\n \".tsx\": extractJs,\n \".go\": extractGo,\n \".rs\": extractRust,\n \".java\": extractJava,\n \".c\": extractC,\n \".h\": extractC,\n \".cpp\": extractCpp,\n \".cc\": extractCpp,\n \".cxx\": extractCpp,\n \".hpp\": extractCpp,\n \".rb\": extractRuby,\n \".cs\": extractCsharp,\n \".kt\": extractKotlin,\n \".kts\": extractKotlin,\n \".scala\": extractScala,\n \".php\": extractPhp,\n \".swift\": extractSwift,\n \".lua\": extractLua,\n \".toc\": extractLua,\n \".zig\": extractZig,\n \".ps1\": extractPowershell,\n \".ex\": extractElixir,\n \".exs\": extractElixir,\n \".m\": extractObjc,\n \".mm\": extractObjc,\n \".jl\": extractJulia,\n};\n\n/**\n * Extract AST nodes and edges from a list of code files.\n *\n * Two-pass process:\n * 1. Per-file structural extraction (classes, functions, imports)\n * 2. Cross-file import resolution: turns file-level imports into\n * class-level INFERRED edges (DigestAuth --uses--> Response)\n */\nexport interface ExtractionDiagnostic {\n filePath: string;\n error: string;\n}\n\nexport interface ExtractWithDiagnosticsResult {\n extraction: Extraction;\n diagnostics: ExtractionDiagnostic[];\n}\n\nexport async function extractWithDiagnostics(paths: string[]): Promise<ExtractWithDiagnosticsResult> {\n const perFile: ExtractionResult[] = [];\n const diagnostics: ExtractionDiagnostic[] = [];\n\n // Infer a common root for cache keys\n let root = \".\";\n try {\n if (paths.length === 0) {\n root = \".\";\n } else if (paths.length === 1) {\n root = dirname(paths[0]!);\n } else {\n // Find common prefix directory\n const parts = paths.map((p) => p.split(sep));\n const minLen = Math.min(...parts.map((p) => p.length));\n let commonLen = 0;\n for (let i = 0; i < minLen; i++) {\n const uniqueAtLevel = new Set(parts.map((p) => p[i]));\n if (uniqueAtLevel.size === 1) commonLen++;\n else break;\n }\n root = commonLen > 0 ? parts[0]!.slice(0, commonLen).join(sep) : \".\";\n }\n } catch {\n root = \".\";\n }\n\n const total = paths.length;\n const _PROGRESS_INTERVAL = 100;\n\n for (let i = 0; i < paths.length; i++) {\n if (total >= _PROGRESS_INTERVAL && i % _PROGRESS_INTERVAL === 0 && i > 0) {\n process.stderr.write(` AST extraction: ${i}/${total} files (${Math.floor(i * 100 / total)}%)\\n`);\n }\n const filePath = paths[i]!;\n const ext = extname(filePath);\n const extractor = _DISPATCH[ext];\n if (!extractor) continue;\n\n const cached = loadCached(filePath, root);\n if (cached !== null) {\n perFile.push(cached as unknown as ExtractionResult);\n continue;\n }\n\n const result = await extractor(filePath);\n if (!result.error) {\n saveCached(filePath, result as unknown as Record<string, unknown>, root);\n } else {\n diagnostics.push({ filePath, error: result.error });\n }\n perFile.push(result);\n }\n\n if (total >= _PROGRESS_INTERVAL) {\n process.stderr.write(` AST extraction: ${total}/${total} files (100%)\\n`);\n }\n\n const allNodes: GraphNode[] = [];\n const allEdges: GraphEdge[] = [];\n for (const result of perFile) {\n allNodes.push(...(result.nodes ?? []));\n allEdges.push(...(result.edges ?? []));\n }\n\n // Add cross-file class-level edges (Python only)\n const pyPaths = paths.filter((p) => extname(p) === \".py\");\n if (pyPaths.length > 0) {\n const pyResults = perFile.filter((_r, i) => extname(paths[i]!) === \".py\");\n try {\n const crossFileEdges = await _resolveCrossFileImports(pyResults, pyPaths);\n allEdges.push(...crossFileEdges);\n } catch {\n // Cross-file import resolution failed, skipping\n }\n }\n\n return {\n extraction: {\n nodes: allNodes,\n edges: allEdges,\n input_tokens: 0,\n output_tokens: 0,\n },\n diagnostics,\n };\n}\n\nexport async function extract(paths: string[]): Promise<Extraction> {\n const { extraction } = await extractWithDiagnostics(paths);\n return extraction;\n}\n\n// ---------------------------------------------------------------------------\n// collectFiles\n// ---------------------------------------------------------------------------\n\nconst _EXTENSIONS = new Set([\n \".py\", \".js\", \".ts\", \".tsx\", \".go\", \".rs\",\n \".java\", \".c\", \".h\", \".cpp\", \".cc\", \".cxx\", \".hpp\",\n \".rb\", \".cs\", \".kt\", \".kts\", \".scala\", \".php\", \".swift\",\n \".lua\", \".toc\", \".zig\", \".ps1\",\n \".m\", \".mm\",\n \".jl\", \".jsx\", \".ex\", \".exs\",\n]);\n\n/**\n * Walk a directory (or return a single file) and collect code files by\n * supported extension.\n */\nexport function collectFiles(target: string, options?: { followSymlinks?: boolean }): string[] {\n const followSymlinks = options?.followSymlinks ?? false;\n const resolved = resolve(target);\n\n try {\n const stat = lstatSync(resolved);\n if (stat.isFile()) return [resolved];\n } catch {\n return [];\n }\n\n const results: string[] = [];\n\n function walkDir(dir: string, visited: Set<string>): void {\n let entries: string[];\n try {\n entries = readdirSync(dir);\n } catch {\n return;\n }\n\n for (const entry of entries) {\n if (entry.startsWith(\".\")) continue;\n const fullPath = join(dir, entry);\n\n let stat;\n try {\n stat = lstatSync(fullPath);\n } catch {\n continue;\n }\n\n if (stat.isSymbolicLink() && !followSymlinks) continue;\n\n if (stat.isDirectory() || (stat.isSymbolicLink() && followSymlinks)) {\n // Cycle detection for symlinks\n if (stat.isSymbolicLink()) {\n try {\n const real = realpathSync(fullPath);\n if (visited.has(real)) continue;\n visited.add(real);\n const parentReal = realpathSync(dirname(fullPath));\n if (parentReal === real || parentReal.startsWith(real + sep)) continue;\n } catch {\n continue;\n }\n }\n\n // Skip hidden directories\n const pathParts = fullPath.split(sep);\n if (pathParts.some((part) => part.startsWith(\".\"))) continue;\n\n walkDir(fullPath, visited);\n } else if (stat.isFile()) {\n const ext = extname(entry);\n if (_EXTENSIONS.has(ext)) {\n results.push(fullPath);\n }\n }\n }\n }\n\n walkDir(resolved, new Set<string>());\n return results.sort();\n}\n","/**\n * URL ingestion - fetch URLs (tweet/arxiv/pdf/web/image/youtube) and save as annotated markdown or audio.\n *\n * Uses Node.js global fetch, turndown for HTML-to-markdown conversion, and\n * security helpers for safe fetching and URL validation.\n */\nimport { existsSync, mkdirSync, writeFileSync } from \"node:fs\";\nimport { resolve as pathResolve, basename, extname } from \"node:path\";\nimport { safeFetch, safeFetchText, validateUrl } from \"./security.js\";\nimport { downloadAudio } from \"./transcribe.js\";\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction yamlStr(s: string): string {\n return s\n .replace(/\\\\/g, \"\\\\\\\\\")\n .replace(/\"/g, '\\\\\"')\n .replace(/\\n/g, \" \")\n .replace(/\\r/g, \" \");\n}\n\nfunction safeFilename(url: string, suffix: string): string {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n return `unknown${suffix}`;\n }\n let name = parsed.hostname + parsed.pathname;\n name = name.replace(/[^\\w\\-]/g, \"_\").replace(/^_+|_+$/g, \"\");\n name = name.replace(/_+/g, \"_\").slice(0, 80);\n return name + suffix;\n}\n\nfunction detectUrlType(url: string): string {\n const lower = url.toLowerCase();\n if (lower.includes(\"twitter.com\") || lower.includes(\"x.com\")) return \"tweet\";\n if (lower.includes(\"arxiv.org\")) return \"arxiv\";\n if (lower.includes(\"github.com\")) return \"github\";\n if (lower.includes(\"youtube.com\") || lower.includes(\"youtu.be\"))\n return \"youtube\";\n try {\n const parsed = new URL(url);\n const path = parsed.pathname.toLowerCase();\n if (path.endsWith(\".pdf\")) return \"pdf\";\n if (\n [\".png\", \".jpg\", \".jpeg\", \".webp\", \".gif\"].some((ext) =>\n path.endsWith(ext),\n )\n )\n return \"image\";\n } catch {\n // fall through\n }\n return \"webpage\";\n}\n\nasync function htmlToMarkdown(html: string, _url: string): Promise<string> {\n try {\n const TurndownService = (await import(\"turndown\")).default;\n const td = new TurndownService({\n headingStyle: \"atx\",\n codeBlockStyle: \"fenced\",\n });\n return td.turndown(html);\n } catch {\n // Fallback: strip tags\n let text = html.replace(/<script[^>]*>.*?<\\/script>/gis, \"\");\n text = text.replace(/<style[^>]*>.*?<\\/style>/gis, \"\");\n text = text.replace(/<[^>]+>/g, \" \");\n text = text.replace(/\\s+/g, \" \").trim();\n return text.slice(0, 8000);\n }\n}\n\n// ---------------------------------------------------------------------------\n// URL type handlers\n// ---------------------------------------------------------------------------\n\nasync function fetchTweet(\n url: string,\n author: string | null,\n contributor: string | null,\n): Promise<[string, string]> {\n const oembedUrl = url.replace(\"x.com\", \"twitter.com\");\n const oembedApi = `https://publish.twitter.com/oembed?url=${encodeURIComponent(oembedUrl)}&omit_script=true`;\n\n let tweetText: string;\n let tweetAuthor: string;\n try {\n const data = JSON.parse(await safeFetchText(oembedApi)) as Record<\n string,\n unknown\n >;\n tweetText = ((data.html as string) ?? \"\")\n .replace(/<[^>]+>/g, \"\")\n .trim();\n tweetAuthor = (data.author_name as string) ?? \"unknown\";\n } catch {\n tweetText = `Tweet at ${url} (could not fetch content)`;\n tweetAuthor = \"unknown\";\n }\n\n const now = new Date().toISOString();\n const content = `---\nsource_url: ${url}\ntype: tweet\nauthor: ${tweetAuthor}\ncaptured_at: ${now}\ncontributor: ${contributor ?? author ?? \"unknown\"}\n---\n\n# Tweet by @${tweetAuthor}\n\n${tweetText}\n\nSource: ${url}\n`;\n const filename = safeFilename(url, \".md\");\n return [content, filename];\n}\n\nasync function fetchWebpage(\n url: string,\n author: string | null,\n contributor: string | null,\n): Promise<[string, string]> {\n const html = await safeFetchText(url);\n\n const titleMatch = html.match(/<title[^>]*>(.*?)<\\/title>/is);\n const title = titleMatch\n ? titleMatch[1]!.replace(/\\s+/g, \" \").trim()\n : url;\n\n const markdown = await htmlToMarkdown(html, url);\n const now = new Date().toISOString();\n const content = `---\nsource_url: ${url}\ntype: webpage\ntitle: \"${yamlStr(title)}\"\ncaptured_at: ${now}\ncontributor: ${contributor ?? author ?? \"unknown\"}\n---\n\n# ${title}\n\nSource: ${url}\n\n---\n\n${markdown.slice(0, 12000)}\n`;\n const filename = safeFilename(url, \".md\");\n return [content, filename];\n}\n\nasync function fetchArxiv(\n url: string,\n author: string | null,\n contributor: string | null,\n): Promise<[string, string]> {\n const arxivMatch = url.match(/(\\d{4}\\.\\d{4,5})/);\n if (!arxivMatch) {\n return fetchWebpage(url, author, contributor);\n }\n\n const arxivId = arxivMatch[1]!;\n let title = arxivId;\n let abstract = \"\";\n let paperAuthors = \"\";\n\n const apiUrl = `https://export.arxiv.org/abs/${arxivId}`;\n try {\n const html = await safeFetchText(apiUrl);\n const abstractMatch = html.match(\n /class=\"abstract[^\"]*\"[^>]*>(.*?)<\\/blockquote>/is,\n );\n if (abstractMatch) {\n abstract = abstractMatch[1]!.replace(/<[^>]+>/g, \"\").trim();\n }\n const titleMatch = html.match(\n /class=\"title[^\"]*\"[^>]*>(.*?)<\\/h1>/is,\n );\n if (titleMatch) {\n title = titleMatch[1]!.replace(/<[^>]+>/g, \" \").trim();\n }\n const authorsMatch = html.match(\n /class=\"authors\"[^>]*>(.*?)<\\/div>/is,\n );\n if (authorsMatch) {\n paperAuthors = authorsMatch[1]!.replace(/<[^>]+>/g, \"\").trim();\n }\n } catch {\n // Use defaults set above\n }\n\n const now = new Date().toISOString();\n const content = `---\nsource_url: ${url}\narxiv_id: ${arxivId}\ntype: paper\ntitle: \"${title}\"\npaper_authors: \"${paperAuthors}\"\ncaptured_at: ${now}\ncontributor: ${contributor ?? author ?? \"unknown\"}\n---\n\n# ${title}\n\n**Authors:** ${paperAuthors}\n**arXiv:** ${arxivId}\n\n## Abstract\n\n${abstract}\n\nSource: ${url}\n`;\n const filename = `arxiv_${arxivId.replace(\".\", \"_\")}.md`;\n return [content, filename];\n}\n\nasync function downloadBinary(\n url: string,\n suffix: string,\n targetDir: string,\n): Promise<string> {\n const filename = safeFilename(url, suffix);\n const outPath = pathResolve(targetDir, filename);\n const data = await safeFetch(url);\n writeFileSync(outPath, data);\n return outPath;\n}\n\ninterface IngestOptions {\n author?: string | null;\n contributor?: string | null;\n}\n\nfunction normalizeIngestOptions(\n authorOrOptions: string | IngestOptions | null | undefined,\n contributor: string | null | undefined,\n): { author: string | null; contributor: string | null } {\n if (typeof authorOrOptions === \"string\" || authorOrOptions == null) {\n return {\n author: authorOrOptions ?? null,\n contributor: contributor ?? null,\n };\n }\n\n return {\n author: authorOrOptions.author ?? null,\n contributor: authorOrOptions.contributor ?? null,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Main ingest function\n// ---------------------------------------------------------------------------\n\nexport async function ingest(\n url: string,\n targetDir: string,\n authorOrOptions: string | IngestOptions | null = null,\n contributor: string | null = null,\n): Promise<string> {\n mkdirSync(targetDir, { recursive: true });\n const urlType = detectUrlType(url);\n const { author, contributor: normalizedContributor } = normalizeIngestOptions(\n authorOrOptions,\n contributor,\n );\n\n await validateUrl(url);\n\n let content: string;\n let filename: string;\n\n if (urlType === \"pdf\") {\n const out = await downloadBinary(url, \".pdf\", targetDir);\n console.log(`Downloaded PDF: ${basename(out)}`);\n return out;\n }\n\n if (urlType === \"image\") {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n throw new Error(`Invalid URL: ${url}`);\n }\n const suffix = extname(parsed.pathname) || \".jpg\";\n const out = await downloadBinary(url, suffix, targetDir);\n console.log(`Downloaded image: ${basename(out)}`);\n return out;\n }\n\n if (urlType === \"youtube\") {\n const out = downloadAudio(url, targetDir);\n console.log(`Downloaded audio: ${basename(out)}`);\n return out;\n }\n\n if (urlType === \"tweet\") {\n [content, filename] = await fetchTweet(url, author, normalizedContributor);\n } else if (urlType === \"arxiv\") {\n [content, filename] = await fetchArxiv(url, author, normalizedContributor);\n } else {\n [content, filename] = await fetchWebpage(url, author, normalizedContributor);\n }\n\n let outPath = pathResolve(targetDir, filename);\n let counter = 1;\n while (existsSync(outPath)) {\n const stem = filename.replace(/\\.md$/, \"\");\n outPath = pathResolve(targetDir, `${stem}_${counter}.md`);\n counter++;\n }\n\n writeFileSync(outPath, content, \"utf-8\");\n console.log(`Saved ${urlType}: ${basename(outPath)}`);\n return outPath;\n}\n\n// ---------------------------------------------------------------------------\n// Save query result (memory loop)\n// ---------------------------------------------------------------------------\n\nexport function saveQueryResult(\n questionOrOptions:\n | string\n | {\n question: string;\n answer: string;\n memoryDir: string;\n queryType?: string;\n sourceNodes?: string[] | null;\n },\n answer?: string,\n memoryDir?: string,\n queryType: string = \"query\",\n sourceNodes: string[] | null = null,\n): string {\n const payload = typeof questionOrOptions === \"string\"\n ? {\n question: questionOrOptions,\n answer: answer ?? \"\",\n memoryDir: memoryDir ?? \"\",\n queryType,\n sourceNodes,\n }\n : {\n question: questionOrOptions.question,\n answer: questionOrOptions.answer,\n memoryDir: questionOrOptions.memoryDir,\n queryType: questionOrOptions.queryType ?? \"query\",\n sourceNodes: questionOrOptions.sourceNodes ?? null,\n };\n\n if (!payload.question) throw new Error(\"saveQueryResult requires a question\");\n if (!payload.memoryDir) throw new Error(\"saveQueryResult requires a memoryDir\");\n\n const effectiveAnswer = payload.answer ?? \"\";\n mkdirSync(payload.memoryDir, { recursive: true });\n\n const now = new Date();\n const slug = payload.question\n .toLowerCase()\n .replace(/[^\\w]/g, \"_\")\n .slice(0, 50)\n .replace(/_+$/, \"\");\n const ts = now\n .toISOString()\n .replace(/[-:]/g, \"\")\n .replace(\"T\", \"_\")\n .slice(0, 15);\n const filename = `query_${ts}_${slug}.md`;\n\n const frontmatterLines = [\n \"---\",\n `type: \"${payload.queryType}\"`,\n `date: \"${now.toISOString()}\"`,\n `question: \"${yamlStr(payload.question)}\"`,\n 'contributor: \"graphify\"',\n ];\n if (payload.sourceNodes && payload.sourceNodes.length > 0) {\n const nodesStr = payload.sourceNodes\n .slice(0, 10)\n .map((n) => `\"${n}\"`)\n .join(\", \");\n frontmatterLines.push(`source_nodes: [${nodesStr}]`);\n }\n frontmatterLines.push(\"---\");\n\n const bodyLines = [\n \"\",\n `# Q: ${payload.question}`,\n \"\",\n \"## Answer\",\n \"\",\n effectiveAnswer,\n ];\n if (payload.sourceNodes && payload.sourceNodes.length > 0) {\n bodyLines.push(\"\", \"## Source Nodes\", \"\");\n for (const n of payload.sourceNodes) {\n bodyLines.push(`- ${n}`);\n }\n }\n\n const content = [...frontmatterLines, ...bodyLines].join(\"\\n\");\n const outPath = pathResolve(payload.memoryDir, filename);\n writeFileSync(outPath, content, \"utf-8\");\n return outPath;\n}\n\n// ---------------------------------------------------------------------------\n// CLI entry point\n// ---------------------------------------------------------------------------\n\nconst isDirectExecution = typeof process !== \"undefined\" &&\n typeof process.argv[1] === \"string\" &&\n /^ingest\\.(?:js|mjs|cjs|ts)$/.test(basename(process.argv[1]));\n\nif (isDirectExecution) {\n const url = process.argv[2];\n const targetDir = process.argv[3] ?? \"./raw\";\n const author = process.argv[4] ?? null;\n if (!url) {\n console.error(\"Usage: ingest <url> [target_dir] [author]\");\n process.exit(1);\n }\n ingest(url, targetDir, author)\n .then((out) => console.log(`Ready for graphify: ${out}`))\n .catch((err) => {\n console.error(err);\n process.exit(1);\n });\n}\n","import * as childProcess from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport {\n cpSync,\n createWriteStream,\n existsSync,\n mkdirSync,\n mkdtempSync,\n readdirSync,\n renameSync,\n rmSync,\n writeFileSync,\n} from \"node:fs\";\nimport { homedir, platform, tmpdir } from \"node:os\";\nimport { basename, dirname, extname, join, resolve } from \"node:path\";\nimport { Readable } from \"node:stream\";\nimport { pipeline } from \"node:stream/promises\";\nimport type { DetectionResult } from \"./types.js\";\n\nconst URL_PREFIXES = [\"http://\", \"https://\", \"www.\"];\nconst CACHED_AUDIO_EXTENSIONS = [\".m4a\", \".opus\", \".mp3\", \".ogg\", \".wav\", \".webm\"];\nconst DEFAULT_MODEL = \"base\";\nconst TRANSCRIPTS_DIR = \"graphify-out/transcripts\";\nconst FALLBACK_PROMPT = \"Use proper punctuation and paragraph breaks.\";\nconst SHERPA_RELEASE_BASE =\n \"https://github.com/k2-fsa/sherpa-onnx/releases/download/asr-models\";\nconst AUDIO_SAMPLE_RATE = 16000;\nconst SUPPORTED_MODELS = new Set([\n \"tiny\",\n \"tiny.en\",\n \"base\",\n \"base.en\",\n \"small\",\n \"small.en\",\n \"medium\",\n \"medium.en\",\n \"large-v1\",\n \"large-v2\",\n \"large-v3\",\n \"turbo\",\n \"distil-small.en\",\n \"distil-medium.en\",\n \"distil-large-v2\",\n \"distil-large-v3\",\n \"distil-large-v3.5\",\n]);\n\nconst MODEL_ALIASES: Record<string, string> = {\n large: \"large-v3\",\n};\n\ninterface SherpaWave {\n samples: Float32Array;\n sampleRate: number;\n}\n\ninterface SherpaResult {\n text?: string;\n}\n\ninterface SherpaStream {\n acceptWaveform(input: SherpaWave): void;\n setOption?(key: string, value: string): void;\n}\n\ninterface SherpaRecognizer {\n createStream(): SherpaStream;\n decodeAsync(stream: SherpaStream): Promise<SherpaResult>;\n}\n\ninterface SherpaModule {\n OfflineRecognizer: {\n createAsync(config: unknown): Promise<SherpaRecognizer>;\n };\n readWave(path: string): SherpaWave;\n}\n\ninterface WhisperArtifacts {\n requestedModel: string;\n resolvedModel: string;\n modelDir: string;\n encoderPath: string;\n decoderPath: string;\n tokensPath: string;\n}\n\nconst recognizerCache = new Map<string, Promise<SherpaRecognizer>>();\nlet sherpaModulePromise: Promise<SherpaModule> | null = null;\n\nfunction runCommand(\n command: string,\n args: string[],\n options?: Omit<childProcess.SpawnSyncOptionsWithStringEncoding, \"encoding\">,\n): childProcess.SpawnSyncReturns<string> {\n const result = childProcess.spawnSync(command, args, {\n encoding: \"utf-8\",\n ...options,\n });\n if (result.error) {\n throw result.error;\n }\n if (result.status !== 0) {\n throw new Error(result.stderr?.trim() || result.stdout?.trim() || `${command} failed`);\n }\n return result;\n}\n\nfunction defaultWhisperCacheDir(): string {\n if (process.env.GRAPHIFY_WHISPER_CACHE_DIR) {\n return resolve(process.env.GRAPHIFY_WHISPER_CACHE_DIR);\n }\n if (platform() === \"win32\") {\n return join(\n process.env.LOCALAPPDATA ?? join(homedir(), \"AppData\", \"Local\"),\n \"graphify\",\n \"whisper\",\n );\n }\n return join(process.env.XDG_CACHE_HOME ?? join(homedir(), \".cache\"), \"graphify\", \"whisper\");\n}\n\nfunction ffmpegBinary(): string {\n return process.env.GRAPHIFY_FFMPEG_BIN ?? \"ffmpeg\";\n}\n\nfunction tarBinary(): string {\n return process.env.GRAPHIFY_TAR_BIN ?? \"tar\";\n}\n\nfunction resolveRequestedModel(modelName?: string): { requested: string; resolved: string } {\n const requested = modelName ?? process.env.GRAPHIFY_WHISPER_MODEL ?? DEFAULT_MODEL;\n const resolved = MODEL_ALIASES[requested] ?? requested;\n if (!SUPPORTED_MODELS.has(resolved)) {\n throw new Error(\n `Unsupported GRAPHIFY_WHISPER_MODEL \"${requested}\". ` +\n `Supported local TS models: ${[...SUPPORTED_MODELS].sort().join(\", \")}`,\n );\n }\n return { requested, resolved };\n}\n\nfunction walkFiles(dir: string): string[] {\n if (!existsSync(dir)) return [];\n const files: string[] = [];\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n const fullPath = join(dir, entry.name);\n if (entry.isDirectory()) {\n files.push(...walkFiles(fullPath));\n } else {\n files.push(fullPath);\n }\n }\n return files;\n}\n\nfunction findArtifactsIn(dir: string): Omit<WhisperArtifacts, \"requestedModel\" | \"resolvedModel\"> | null {\n const files = walkFiles(dir);\n const encoderPath =\n files.find((path) => path.endsWith(\"-encoder.int8.onnx\"))\n ?? files.find((path) => path.endsWith(\"-encoder.onnx\"));\n const decoderPath =\n files.find((path) => path.endsWith(\"-decoder.int8.onnx\"))\n ?? files.find((path) => path.endsWith(\"-decoder.onnx\"));\n const tokensPath = files.find((path) => path.endsWith(\"-tokens.txt\"));\n if (!encoderPath || !decoderPath || !tokensPath) {\n return null;\n }\n return {\n modelDir: dir,\n encoderPath,\n decoderPath,\n tokensPath,\n };\n}\n\nfunction normalizeModelError(detail: string): string {\n if (detail.includes(\"404\")) {\n return `${detail}. The local sherpa-onnx release asset was not found for this Whisper model name.`;\n }\n return detail;\n}\n\nasync function writeResponseToFile(response: Response, destination: string): Promise<void> {\n if (!response.ok || !response.body) {\n throw new Error(`HTTP ${response.status} while downloading ${response.url}`);\n }\n await pipeline(Readable.fromWeb(response.body as globalThis.ReadableStream<Uint8Array>), createWriteStream(destination));\n}\n\nasync function ensureWhisperArtifacts(modelName?: string): Promise<WhisperArtifacts> {\n const { requested, resolved } = resolveRequestedModel(modelName);\n const cacheRoot = defaultWhisperCacheDir();\n mkdirSync(cacheRoot, { recursive: true });\n\n const modelDir = join(cacheRoot, `sherpa-onnx-whisper-${resolved}`);\n const cached = findArtifactsIn(modelDir);\n if (cached) {\n return { requestedModel: requested, resolvedModel: resolved, ...cached };\n }\n\n const tempDir = mkdtempSync(join(tmpdir(), \"graphify-whisper-model-\"));\n const extractDir = join(tempDir, \"extract\");\n const archiveName = `sherpa-onnx-whisper-${resolved}.tar.bz2`;\n const archivePath = join(tempDir, archiveName);\n mkdirSync(extractDir, { recursive: true });\n\n try {\n const url = `${SHERPA_RELEASE_BASE}/${archiveName}`;\n console.log(` downloading whisper model: ${resolved}`);\n const response = await fetch(url);\n await writeResponseToFile(response, archivePath);\n\n runCommand(tarBinary(), [\"-xjf\", archivePath, \"-C\", extractDir]);\n\n const extractedRoot = walkFiles(extractDir)\n .map((path) => dirname(path))\n .find((path) => findArtifactsIn(path) !== null);\n const sourceDir =\n extractedRoot\n ?? readdirSync(extractDir, { withFileTypes: true })\n .filter((entry) => entry.isDirectory())\n .map((entry) => join(extractDir, entry.name))\n .find((path) => findArtifactsIn(path) !== null);\n\n if (!sourceDir) {\n throw new Error(`Downloaded archive for ${resolved} but could not locate Whisper model files`);\n }\n\n if (existsSync(modelDir)) {\n rmSync(modelDir, { recursive: true, force: true });\n }\n try {\n renameSync(sourceDir, modelDir);\n } catch {\n cpSync(sourceDir, modelDir, { recursive: true });\n }\n\n const artifacts = findArtifactsIn(modelDir);\n if (!artifacts) {\n throw new Error(`Model cache for ${resolved} is incomplete after extraction`);\n }\n\n return { requestedModel: requested, resolvedModel: resolved, ...artifacts };\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\n throw new Error(normalizeModelError(detail));\n } finally {\n rmSync(tempDir, { recursive: true, force: true });\n }\n}\n\nasync function loadSherpaModule(): Promise<SherpaModule> {\n if (!sherpaModulePromise) {\n sherpaModulePromise = import(\"sherpa-onnx-node\")\n .then((imported) => (\n Reflect.has(imported, \"default\")\n ? Reflect.get(imported, \"default\")\n : imported\n ) as SherpaModule)\n .catch((error) => {\n sherpaModulePromise = null;\n const detail = error instanceof Error ? error.message : String(error);\n throw new Error(\n \"Video transcription requires the optional dependency sherpa-onnx-node. \" +\n `Install it locally, then retry. ${detail}`,\n );\n });\n }\n return sherpaModulePromise;\n}\n\nasync function getRecognizer(\n modelName?: string,\n sherpa?: SherpaModule,\n): Promise<{ recognizer: SherpaRecognizer; artifacts: WhisperArtifacts }> {\n const artifacts = await ensureWhisperArtifacts(modelName);\n const cacheKey = artifacts.modelDir;\n const existing = recognizerCache.get(cacheKey);\n if (existing) {\n return { recognizer: await existing, artifacts };\n }\n\n const createRecognizer = (async () => {\n const runtime = sherpa ?? (await loadSherpaModule());\n return runtime.OfflineRecognizer.createAsync({\n featConfig: {\n sampleRate: AUDIO_SAMPLE_RATE,\n featureDim: 80,\n },\n modelConfig: {\n whisper: {\n encoder: artifacts.encoderPath,\n decoder: artifacts.decoderPath,\n task: \"transcribe\",\n },\n tokens: artifacts.tokensPath,\n numThreads: 1,\n provider: \"cpu\",\n debug: 0,\n },\n });\n })();\n\n recognizerCache.set(\n cacheKey,\n createRecognizer.catch((error) => {\n recognizerCache.delete(cacheKey);\n throw error;\n }),\n );\n\n return { recognizer: await recognizerCache.get(cacheKey)!, artifacts };\n}\n\nfunction normalizeToWave(audioPath: string, workingDir: string): string {\n const wavPath = join(workingDir, `${basename(audioPath, extname(audioPath))}.wav`);\n try {\n runCommand(ffmpegBinary(), [\n \"-y\",\n \"-i\",\n audioPath,\n \"-vn\",\n \"-ac\",\n \"1\",\n \"-ar\",\n String(AUDIO_SAMPLE_RATE),\n \"-c:a\",\n \"pcm_s16le\",\n wavPath,\n ]);\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\n throw new Error(\n \"Video transcription requires ffmpeg in PATH. \" +\n `Install ffmpeg locally, then retry. ${detail}`,\n );\n }\n return wavPath;\n}\n\nfunction extractTranscriptText(result: SherpaResult): string {\n return String(result.text ?? \"\").trim();\n}\n\nexport function isUrl(pathLike: string): boolean {\n return URL_PREFIXES.some((prefix) => pathLike.startsWith(prefix));\n}\n\nexport function downloadAudio(url: string, outputDir: string): string {\n mkdirSync(outputDir, { recursive: true });\n\n const urlHash = createHash(\"sha1\").update(url).digest(\"hex\").slice(0, 12);\n for (const ext of CACHED_AUDIO_EXTENSIONS) {\n const candidate = join(outputDir, `yt_${urlHash}${ext}`);\n if (existsSync(candidate)) {\n console.log(` cached audio: ${basename(candidate)}`);\n return candidate;\n }\n }\n\n const outTemplate = join(outputDir, `yt_${urlHash}.%(ext)s`);\n try {\n console.log(` downloading audio: ${url.slice(0, 80)} ...`);\n runCommand(\"yt-dlp\", [\n \"-f\",\n \"bestaudio[ext=m4a]/bestaudio/best\",\n \"-o\",\n outTemplate,\n \"--quiet\",\n \"--no-warnings\",\n \"--no-playlist\",\n url,\n ]);\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\n throw new Error(\n `YouTube/URL download requires yt-dlp. Install yt-dlp to enable video ingestion. ${detail}`,\n );\n }\n\n for (const entry of readdirSync(outputDir)) {\n if (entry.startsWith(`yt_${urlHash}.`)) {\n return join(outputDir, entry);\n }\n }\n\n throw new Error(`yt-dlp finished without producing an audio file for ${url}`);\n}\n\nexport function buildWhisperPrompt(\n godNodes: Array<{ label?: string | null }>,\n): string {\n const override = process.env.GRAPHIFY_WHISPER_PROMPT;\n if (override) return override;\n\n const labels = godNodes\n .map((node) => node.label ?? \"\")\n .filter((label): label is string => Boolean(label))\n .slice(0, 5);\n if (labels.length === 0) {\n return FALLBACK_PROMPT;\n }\n return `Technical discussion about ${labels.join(\", \")}. ${FALLBACK_PROMPT}`;\n}\n\nexport async function transcribe(\n videoPath: string,\n outputDir: string = TRANSCRIPTS_DIR,\n initialPrompt?: string,\n force: boolean = false,\n): Promise<string> {\n const outDir = resolve(outputDir);\n mkdirSync(outDir, { recursive: true });\n\n const audioPath = isUrl(videoPath)\n ? downloadAudio(videoPath, join(outDir, \"downloads\"))\n : resolve(videoPath);\n const transcriptPath = join(outDir, `${basename(audioPath, extname(audioPath))}.txt`);\n\n if (existsSync(transcriptPath) && !force) {\n return transcriptPath;\n }\n\n const prompt = initialPrompt ?? process.env.GRAPHIFY_WHISPER_PROMPT ?? FALLBACK_PROMPT;\n const requestedModel = process.env.GRAPHIFY_WHISPER_MODEL ?? DEFAULT_MODEL;\n const tempDir = mkdtempSync(join(tmpdir(), \"graphify-transcribe-\"));\n\n try {\n console.log(` transcribing ${basename(audioPath)} (model=${requestedModel}) ...`);\n const wavPath = normalizeToWave(audioPath, tempDir);\n const sherpa = await loadSherpaModule();\n const { recognizer, artifacts } = await getRecognizer(requestedModel, sherpa);\n const wave = sherpa.readWave(wavPath);\n const stream = recognizer.createStream();\n if (prompt && typeof stream.setOption === \"function\") {\n try {\n stream.setOption(\"prompt\", prompt);\n } catch {\n /* ignored: sherpa-onnx does not guarantee prompt support across builds */\n }\n }\n stream.acceptWaveform({ samples: wave.samples, sampleRate: wave.sampleRate });\n const result = await recognizer.decodeAsync(stream);\n const transcript = extractTranscriptText(result);\n writeFileSync(transcriptPath, transcript, \"utf-8\");\n if (artifacts.requestedModel !== artifacts.resolvedModel) {\n console.log(` model alias: ${artifacts.requestedModel} -> ${artifacts.resolvedModel}`);\n }\n } catch (error) {\n if (error instanceof Error && error.message.startsWith(\"Unsupported GRAPHIFY_WHISPER_MODEL\")) {\n throw error;\n }\n const detail = error instanceof Error ? error.message : String(error);\n throw new Error(\n \"Video transcription requires the local TypeScript toolchain: sherpa-onnx-node + ffmpeg. \" +\n `Retry after installing them. ${detail}`,\n );\n } finally {\n rmSync(tempDir, { recursive: true, force: true });\n }\n\n return transcriptPath;\n}\n\nexport async function transcribeAll(\n videoFiles: string[],\n outputDir?: string,\n initialPrompt?: string,\n force: boolean = false,\n): Promise<string[]> {\n if (videoFiles.length === 0) {\n return [];\n }\n\n const transcriptPaths: string[] = [];\n for (const videoFile of videoFiles) {\n try {\n transcriptPaths.push(await transcribe(videoFile, outputDir, initialPrompt, force));\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\n console.log(` warning: could not transcribe ${videoFile}: ${detail}`);\n }\n }\n return transcriptPaths;\n}\n\nfunction cloneDetection(detection: DetectionResult): DetectionResult {\n return JSON.parse(JSON.stringify(detection)) as DetectionResult;\n}\n\nexport async function augmentDetectionWithTranscripts(\n detection: DetectionResult,\n options?: {\n outputDir?: string;\n initialPrompt?: string;\n godNodes?: Array<{ label?: string | null }>;\n incremental?: boolean;\n whisperModel?: string;\n },\n): Promise<{ detection: DetectionResult; transcriptPaths: string[]; prompt: string }> {\n const nextDetection = cloneDetection(detection);\n const source = options?.incremental && nextDetection.new_files ? nextDetection.new_files : nextDetection.files;\n const videoFiles = [...(source.video ?? [])];\n const prompt = options?.initialPrompt ?? buildWhisperPrompt(options?.godNodes ?? []);\n\n if (videoFiles.length === 0) {\n return { detection: nextDetection, transcriptPaths: [], prompt };\n }\n\n const previousModel = process.env.GRAPHIFY_WHISPER_MODEL;\n if (options?.whisperModel) {\n process.env.GRAPHIFY_WHISPER_MODEL = options.whisperModel;\n }\n\n try {\n const transcriptPaths = await transcribeAll(\n videoFiles,\n options?.outputDir,\n prompt,\n options?.incremental === true,\n );\n const existingDocuments = source.document ?? [];\n source.document = [...existingDocuments, ...transcriptPaths];\n return { detection: nextDetection, transcriptPaths, prompt };\n } finally {\n if (options?.whisperModel) {\n if (previousModel === undefined) {\n delete process.env.GRAPHIFY_WHISPER_MODEL;\n } else {\n process.env.GRAPHIFY_WHISPER_MODEL = previousModel;\n }\n }\n }\n}\n","/**\n * Generate GRAPH_REPORT.md - the human-readable audit trail.\n */\nimport Graph from \"graphology\";\nimport type { GodNodeEntry, SurpriseEntry, SuggestedQuestion, DetectionResult } from \"./types.js\";\nimport { type NumericMapLike, toNumericMap } from \"./collections.js\";\nimport { isFileNode, isConceptNode } from \"./analyze.js\";\n\nexport function generate(\n G: Graph,\n communities: NumericMapLike<string[]>,\n cohesionScores: NumericMapLike<number>,\n communityLabels: NumericMapLike<string>,\n godNodeList: GodNodeEntry[],\n surpriseList: SurpriseEntry[],\n detectionResult: DetectionResult,\n tokenCost: { input: number; output: number },\n root: string,\n suggestedQuestions?:\n | SuggestedQuestion[]\n | { suggestedQuestions?: SuggestedQuestion[] | null }\n | null,\n): string {\n const communityMap = toNumericMap(communities);\n const cohesionMap = toNumericMap(cohesionScores);\n const labelMap = toNumericMap(communityLabels);\n const suggestedQuestionList = Array.isArray(suggestedQuestions)\n ? suggestedQuestions\n : (suggestedQuestions?.suggestedQuestions ?? null);\n const today = new Date().toISOString().slice(0, 10);\n\n const confidences: string[] = [];\n G.forEachEdge((_, data) => {\n confidences.push((data.confidence as string) ?? \"EXTRACTED\");\n });\n const total = confidences.length || 1;\n const extPct = Math.round((confidences.filter((c) => c === \"EXTRACTED\").length / total) * 100);\n const infPct = Math.round((confidences.filter((c) => c === \"INFERRED\").length / total) * 100);\n const ambPct = Math.round((confidences.filter((c) => c === \"AMBIGUOUS\").length / total) * 100);\n\n const infEdges: { score: number }[] = [];\n G.forEachEdge((_, data) => {\n if (data.confidence === \"INFERRED\") {\n infEdges.push({ score: (data.confidence_score as number) ?? 0.5 });\n }\n });\n const infAvg = infEdges.length > 0\n ? Math.round((infEdges.reduce((s, e) => s + e.score, 0) / infEdges.length) * 100) / 100\n : null;\n\n const lines: string[] = [\n `# Graph Report - ${root} (${today})`,\n \"\",\n \"## Corpus Check\",\n ];\n\n if (detectionResult.warning) {\n lines.push(`- ${detectionResult.warning}`);\n } else {\n lines.push(\n `- ${detectionResult.total_files} files · ~${detectionResult.total_words.toLocaleString()} words`,\n \"- Verdict: corpus is large enough that graph structure adds value.\",\n );\n }\n\n lines.push(\n \"\",\n \"## Summary\",\n `- ${G.order} nodes · ${G.size} edges · ${communityMap.size} communities detected`,\n `- Extraction: ${extPct}% EXTRACTED · ${infPct}% INFERRED · ${ambPct}% AMBIGUOUS` +\n (infAvg !== null ? ` · INFERRED: ${infEdges.length} edges (avg confidence: ${infAvg})` : \"\"),\n `- Token cost: ${tokenCost.input.toLocaleString()} input · ${tokenCost.output.toLocaleString()} output`,\n \"\",\n \"## God Nodes (most connected - your core abstractions)\",\n );\n\n godNodeList.forEach((node, i) => {\n lines.push(`${i + 1}. \\`${node.label}\\` - ${node.edges} edges`);\n });\n\n lines.push(\"\", \"## Surprising Connections (you probably didn't know these)\");\n if (surpriseList.length > 0) {\n for (const s of surpriseList) {\n const relation = s.relation ?? \"related_to\";\n const note = s.note ?? \"\";\n const files = s.source_files ?? [\"\", \"\"];\n const conf = s.confidence ?? \"EXTRACTED\";\n const cscore = s.confidence_score;\n const confTag = conf === \"INFERRED\" && cscore != null ? `INFERRED ${cscore.toFixed(2)}` : conf;\n const semTag = relation === \"semantically_similar_to\" ? \" [semantically similar]\" : \"\";\n lines.push(\n `- \\`${s.source}\\` --${relation}--> \\`${s.target}\\` [${confTag}]${semTag}`,\n ` ${files[0]} → ${files[1]}${note ? ` _${note}_` : \"\"}`,\n );\n }\n } else {\n lines.push(\"- None detected - all connections are within the same source files.\");\n }\n\n const hyperedges = (G.getAttribute(\"hyperedges\") as Array<Record<string, unknown>>) ?? [];\n if (hyperedges.length > 0) {\n lines.push(\"\", \"## Hyperedges (group relationships)\");\n for (const h of hyperedges) {\n const nodeLabels = ((h.nodes as string[]) ?? []).join(\", \");\n const conf = (h.confidence as string) ?? \"INFERRED\";\n const cscore = h.confidence_score as number | undefined;\n const confTag = cscore != null ? `${conf} ${cscore.toFixed(2)}` : conf;\n lines.push(`- **${h.label ?? h.id ?? \"\"}** — ${nodeLabels} [${confTag}]`);\n }\n }\n\n lines.push(\"\", \"## Communities\");\n for (const [cid, nodes] of communityMap) {\n const label = labelMap.get(cid) ?? `Community ${cid}`;\n const score = cohesionMap.get(cid) ?? 0.0;\n const realNodes = nodes.filter((n) => !isFileNode(G, n));\n const display = realNodes.slice(0, 8).map((n) => (G.getNodeAttribute(n, \"label\") as string) ?? n);\n const suffix = realNodes.length > 8 ? ` (+${realNodes.length - 8} more)` : \"\";\n lines.push(\n \"\",\n `### Community ${cid} - \"${label}\"`,\n `Cohesion: ${score}`,\n `Nodes (${realNodes.length}): ${display.join(\", \")}${suffix}`,\n );\n }\n\n const ambiguous: [string, string, Record<string, unknown>][] = [];\n G.forEachEdge((_, data, u, v) => {\n if (data.confidence === \"AMBIGUOUS\") ambiguous.push([u, v, data]);\n });\n if (ambiguous.length > 0) {\n lines.push(\"\", \"## Ambiguous Edges - Review These\");\n for (const [u, v, d] of ambiguous) {\n const ul = (G.getNodeAttribute(u, \"label\") as string) ?? u;\n const vl = (G.getNodeAttribute(v, \"label\") as string) ?? v;\n lines.push(\n `- \\`${ul}\\` → \\`${vl}\\` [AMBIGUOUS]`,\n ` ${d.source_file ?? \"\"} · relation: ${d.relation ?? \"unknown\"}`,\n );\n }\n }\n\n // Gaps section\n const isolated = G.nodes().filter(\n (n) => G.degree(n) <= 1 && !isFileNode(G, n) && !isConceptNode(G, n),\n );\n const thinCommunities = new Map<number, string[]>();\n for (const [cid, nodes] of communityMap) {\n if (nodes.length < 3) thinCommunities.set(cid, nodes);\n }\n const gapCount = isolated.length + thinCommunities.size;\n\n if (gapCount > 0 || ambPct > 20) {\n lines.push(\"\", \"## Knowledge Gaps\");\n if (isolated.length > 0) {\n const isolatedLabels = isolated.slice(0, 5).map((n) => (G.getNodeAttribute(n, \"label\") as string) ?? n);\n const suffix = isolated.length > 5 ? ` (+${isolated.length - 5} more)` : \"\";\n lines.push(\n `- **${isolated.length} isolated node(s):** ${isolatedLabels.map((l) => `\\`${l}\\``).join(\", \")}${suffix}`,\n \" These have ≤1 connection - possible missing edges or undocumented components.\",\n );\n }\n if (thinCommunities.size > 0) {\n for (const [cid, nodes] of thinCommunities) {\n const label = labelMap.get(cid) ?? `Community ${cid}`;\n const nodeLabels = nodes.map((n) => (G.getNodeAttribute(n, \"label\") as string) ?? n);\n lines.push(\n `- **Thin community \\`${label}\\`** (${nodes.length} nodes): ${nodeLabels.map((l) => `\\`${l}\\``).join(\", \")}`,\n \" Too small to be a meaningful cluster - may be noise or needs more connections extracted.\",\n );\n }\n }\n if (ambPct > 20) {\n lines.push(`- **High ambiguity: ${ambPct}% of edges are AMBIGUOUS.** Review the Ambiguous Edges section above.`);\n }\n }\n\n if (suggestedQuestionList && suggestedQuestionList.length > 0) {\n lines.push(\"\", \"## Suggested Questions\");\n const noSignal = suggestedQuestionList.length === 1 && suggestedQuestionList[0]!.type === \"no_signal\";\n if (noSignal) {\n lines.push(`_${suggestedQuestionList[0]!.why}_`);\n } else {\n lines.push(\"_Questions this graph is uniquely positioned to answer:_\", \"\");\n for (const q of suggestedQuestionList) {\n if (q.question) {\n lines.push(`- **${q.question}**`, ` _${q.why}_`);\n }\n }\n }\n }\n\n return lines.join(\"\\n\");\n}\n"],"mappings":";;;;;;;;AAAA,SAAS,eAAe;AAExB;AAAA,EACE,cAAAA;AAAA,EACA,aAAAC;AAAA,EACA,gBAAAC;AAAA,EACA,iBAAAC;AAAA,OACK;AACP,SAAS,WAAAC,UAAS,QAAAC,OAAM,WAAAC,gBAAe;AACvC,SAAS,qBAAqB;;;ACJ9B,OAAO,2BAA2B;;;ACF3B,SAAS,aACd,OACgB;AAChB,MAAI,iBAAiB,IAAK,QAAO;AAEjC,QAAM,MAAM,oBAAI,IAAe;AAC/B,MAAI,CAAC,MAAO,QAAO;AAEnB,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,KAAK,GAAG;AAChD,UAAM,aAAa,OAAO,GAAG;AAC7B,QAAI,OAAO,SAAS,UAAU,GAAG;AAC/B,UAAI,IAAI,YAAY,KAAU;AAAA,IAChC;AAAA,EACF;AAEA,SAAO;AACT;;;ACbA,OAAO,aAA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","join","resolve","result","readFileSync","existsSync","readFileSync","existsSync","createHash","readFileSync","writeFileSync","mkdirSync","readdirSync","existsSync","extname","join","resolve","resolve","existsSync","writeFileSync","existsSync","URL","nodeCommunityMap","nodeCommunityMap","writeFileSync","readFileSync","readdirSync","lstatSync","existsSync","resolve","basename","extname","dirname","join","sep","Parser","existsSync","join","Parser","readFileSync","basename","extname","dirname","sep","existsSync","mkdirSync","writeFileSync","pathResolve","basename","extname","createHash","existsSync","mkdirSync","readdirSync","renameSync","writeFileSync","basename","dirname","extname","join","resolve","godNodes","pathResolve","writeFileSync","mkdirSync","basename","extname","existsSync","dirname","readFileSync","resolve","mkdirSync","writeFileSync","join","loadGraph","existsSync"]}
|