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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/validate.ts","../src/build.ts","../src/collections.ts","../src/cluster.ts","../src/analyze.ts","../src/report.ts","../src/security.ts","../src/export.ts","../src/cache.ts","../src/extract.ts","../src/index.ts","../src/types.ts","../src/wiki.ts","../src/detect.ts","../src/benchmark.ts","../src/ingest.ts","../src/serve.ts","../src/watch.ts"],"sourcesContent":["/**\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 { 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","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 * 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","/**\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","/**\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, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/'/g, \"&#39;\");\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 &middot; ${G.size} edges &middot; ${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, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/'/g, \"&apos;\");\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, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\");\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 * 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 * 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 * graphify - extract · build · cluster · analyze · report.\n */\n\nexport { type GraphNode, type GraphEdge, type Extraction, type Hyperedge, type DetectionResult, FileType } from \"./types.js\";\nexport { validateExtraction, assertValid } from \"./validate.js\";\nexport { buildFromJson, build } from \"./build.js\";\nexport { cluster, cohesionScore, scoreAll } from \"./cluster.js\";\nexport { godNodes, surprisingConnections, suggestQuestions, graphDiff } from \"./analyze.js\";\nexport { generate as generateReport } from \"./report.js\";\nexport { toJson, toHtml, toSvg, toGraphml, toCypher, toCanvas, pushToNeo4j } from \"./export.js\";\nexport { toWiki } from \"./wiki.js\";\nexport { detect, classifyFile, detectIncremental, saveManifest } from \"./detect.js\";\nexport { extract, collectFiles } from \"./extract.js\";\nexport { fileHash, loadCached, saveCached, checkSemanticCache, saveSemanticCache } from \"./cache.js\";\nexport { validateUrl, safeFetch, safeFetchText, validateGraphPath, sanitizeLabel } from \"./security.js\";\nexport { runBenchmark, printBenchmark } from \"./benchmark.js\";\nexport { ingest, saveQueryResult } from \"./ingest.js\";\nexport { serve } from \"./serve.js\";\nexport { watch, rebuildCode } from \"./watch.js\";\n","/** File type classification for corpus files. */\nexport enum FileType {\n CODE = \"code\",\n DOCUMENT = \"document\",\n PAPER = \"paper\",\n IMAGE = \"image\",\n}\n\n/** Confidence level for extracted relationships. */\nexport type Confidence = \"EXTRACTED\" | \"INFERRED\" | \"AMBIGUOUS\";\n\n/** A node in the knowledge graph. */\nexport interface GraphNode {\n id: string;\n label: string;\n file_type: \"code\" | \"document\" | \"paper\" | \"image\" | \"rationale\";\n source_file: string;\n source_location?: string;\n confidence?: Confidence;\n community?: number;\n [key: string]: unknown;\n}\n\n/** An edge in the knowledge graph. */\nexport interface GraphEdge {\n source: string;\n target: string;\n relation: string;\n confidence: Confidence;\n source_file: string;\n source_location?: string;\n confidence_score?: number;\n weight?: number;\n /** Original source direction (preserved for display). */\n _src?: string;\n /** Original target direction (preserved for display). */\n _tgt?: string;\n [key: string]: unknown;\n}\n\n/** A hyperedge grouping multiple nodes. */\nexport interface Hyperedge {\n id: string;\n label: string;\n nodes: string[];\n relation: string;\n confidence: Confidence;\n source_file: string;\n confidence_score?: number;\n [key: string]: unknown;\n}\n\n/** Output of an extraction pass. */\nexport interface Extraction {\n nodes: GraphNode[];\n edges: GraphEdge[];\n hyperedges?: Hyperedge[];\n input_tokens: number;\n output_tokens: number;\n}\n\n/** Output of the detect() function. */\nexport interface DetectionResult {\n files: Record<string, string[]>;\n total_files: number;\n total_words: number;\n needs_graph: boolean;\n warning: string | null;\n skipped_sensitive: string[];\n graphifyignore_patterns: number;\n /** Present in incremental mode. */\n incremental?: boolean;\n new_files?: Record<string, string[]>;\n unchanged_files?: Record<string, string[]>;\n new_total?: number;\n deleted_files?: string[];\n}\n\n/** A god node (most connected entity). */\nexport interface GodNodeEntry {\n id: string;\n label: string;\n edges: number;\n}\n\n/** A surprising connection. */\nexport interface SurpriseEntry {\n source: string;\n target: string;\n source_files: [string, string];\n confidence: Confidence;\n relation: string;\n note?: string;\n why?: string;\n confidence_score?: number;\n}\n\n/** A suggested question. */\nexport interface SuggestedQuestion {\n type: string;\n question: string | null;\n why: string;\n}\n\n/** Benchmark result. */\nexport interface BenchmarkResult {\n corpus_tokens?: number;\n corpus_words?: number;\n nodes?: number;\n edges?: number;\n avg_query_tokens?: number;\n reduction_ratio?: number;\n per_question?: Array<{ question: string; query_tokens: number; reduction: number }>;\n error?: string;\n}\n\n/** Graph diff between two snapshots. */\nexport interface GraphDiffResult {\n new_nodes: Array<{ id: string; label: string }>;\n removed_nodes: Array<{ id: string; label: string }>;\n new_edges: Array<{ source: string; target: string; relation: string; confidence: string }>;\n removed_edges: Array<{ source: string; target: string; relation: string; confidence: string }>;\n summary: string;\n}\n\n/** Platform configuration for skill installation. */\nexport interface PlatformConfig {\n skill_file: string;\n skill_dst: string;\n claude_md: boolean;\n}\n","/**\n * Wiki export - Wikipedia-style markdown articles from the knowledge graph.\n * Generates an agent-crawlable wiki: index.md + one article per community + god node articles.\n */\nimport { mkdirSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport Graph from \"graphology\";\nimport type { GodNodeEntry } from \"./types.js\";\nimport { type NumericMapLike, toNumericMap } from \"./collections.js\";\n\nfunction safeFilename(name: string): string {\n return name.replace(/\\//g, \"-\").replace(/ /g, \"_\").replace(/:/g, \"-\");\n}\n\nfunction crossCommunityLinks(\n G: Graph,\n nodes: string[],\n ownCid: number,\n labels: NumericMapLike<string>,\n): [string, number][] {\n const labelMap = toNumericMap(labels);\n const counts = new Map<string, number>();\n for (const nid of nodes) {\n G.forEachNeighbor(nid, (neighbor) => {\n const ncid = G.getNodeAttribute(neighbor, \"community\") as number | undefined;\n if (ncid !== undefined && ncid !== ownCid) {\n const label = labelMap.get(ncid) ?? `Community ${ncid}`;\n counts.set(label, (counts.get(label) ?? 0) + 1);\n }\n });\n }\n return [...counts.entries()].sort((a, b) => b[1] - a[1]);\n}\n\nfunction communityArticle(\n G: Graph,\n cid: number,\n nodes: string[],\n label: string,\n labels: Map<number, string>,\n cohesion: number | undefined,\n): string {\n const topNodes = [...nodes].sort((a, b) => G.degree(b) - G.degree(a)).slice(0, 25);\n const cross = crossCommunityLinks(G, nodes, cid, labels);\n\n const confCounts: Record<string, number> = { EXTRACTED: 0, INFERRED: 0, AMBIGUOUS: 0 };\n for (const nid of nodes) {\n G.forEachEdge(nid, (_, data) => {\n const conf = (data.confidence as string) ?? \"EXTRACTED\";\n confCounts[conf] = (confCounts[conf] ?? 0) + 1;\n });\n }\n const totalEdges = Object.values(confCounts).reduce((s, n) => s + n, 0) || 1;\n\n const sources = [...new Set(nodes.map((n) => (G.getNodeAttribute(n, \"source_file\") as string) ?? \"\").filter(Boolean))].sort();\n\n const lines: string[] = [];\n lines.push(`# ${label}`, \"\");\n\n const metaParts = [`${nodes.length} nodes`];\n if (cohesion !== undefined) metaParts.push(`cohesion ${cohesion.toFixed(2)}`);\n lines.push(`> ${metaParts.join(\" · \")}`, \"\");\n\n lines.push(\"## Key Concepts\", \"\");\n for (const nid of topNodes) {\n const d = G.getNodeAttributes(nid);\n const nodeLabel = (d.label as string) ?? nid;\n const src = (d.source_file as string) ?? \"\";\n const degree = G.degree(nid);\n const srcStr = src ? ` — \\`${src}\\`` : \"\";\n lines.push(`- **${nodeLabel}** (${degree} connections)${srcStr}`);\n }\n const remaining = nodes.length - topNodes.length;\n if (remaining > 0) lines.push(`- *... and ${remaining} more nodes in this community*`);\n lines.push(\"\");\n\n lines.push(\"## Relationships\", \"\");\n if (cross.length > 0) {\n for (const [otherLabel, count] of cross.slice(0, 12)) {\n lines.push(`- [[${otherLabel}]] (${count} shared connections)`);\n }\n } else {\n lines.push(\"- No strong cross-community connections detected\");\n }\n lines.push(\"\");\n\n if (sources.length > 0) {\n lines.push(\"## Source Files\", \"\");\n for (const src of sources.slice(0, 20)) {\n lines.push(`- \\`${src}\\``);\n }\n lines.push(\"\");\n }\n\n lines.push(\"## Audit Trail\", \"\");\n for (const conf of [\"EXTRACTED\", \"INFERRED\", \"AMBIGUOUS\"]) {\n const n = confCounts[conf] ?? 0;\n const pct = Math.round((n / totalEdges) * 100);\n lines.push(`- ${conf}: ${n} (${pct}%)`);\n }\n lines.push(\"\");\n\n lines.push(\"---\", \"\", \"*Part of the graphify knowledge wiki. See [[index]] to navigate.*\");\n return lines.join(\"\\n\");\n}\n\nfunction godNodeArticle(G: Graph, nid: string, labels: Map<number, string>): string {\n const d = G.getNodeAttributes(nid);\n const nodeLabel = (d.label as string) ?? nid;\n const src = (d.source_file as string) ?? \"\";\n const cid = d.community as number | undefined;\n const communityName = cid !== undefined ? (labels.get(cid) ?? `Community ${cid}`) : undefined;\n\n const lines: string[] = [];\n lines.push(`# ${nodeLabel}`, \"\");\n lines.push(`> God node · ${G.degree(nid)} connections · \\`${src}\\``, \"\");\n\n if (communityName) {\n lines.push(`**Community:** [[${communityName}]]`, \"\");\n }\n\n const byRelation = new Map<string, string[]>();\n const neighbors = [...G.neighbors(nid)].sort((a, b) => G.degree(b) - G.degree(a));\n for (const neighbor of neighbors) {\n const ed = G.getEdgeAttributes(G.edge(nid, neighbor)!);\n const rel = (ed.relation as string) ?? \"related\";\n const neighborLabel = (G.getNodeAttribute(neighbor, \"label\") as string) ?? neighbor;\n const conf = (ed.confidence as string) ?? \"\";\n const confStr = conf ? ` \\`${conf}\\`` : \"\";\n if (!byRelation.has(rel)) byRelation.set(rel, []);\n byRelation.get(rel)!.push(`[[${neighborLabel}]]${confStr}`);\n }\n\n lines.push(\"## Connections by Relation\", \"\");\n for (const [rel, targets] of [...byRelation.entries()].sort()) {\n lines.push(`### ${rel}`);\n for (const t of targets.slice(0, 20)) {\n lines.push(`- ${t}`);\n }\n lines.push(\"\");\n }\n\n lines.push(\"---\", \"\", \"*Part of the graphify knowledge wiki. See [[index]] to navigate.*\");\n return lines.join(\"\\n\");\n}\n\nfunction indexMd(\n communities: Map<number, string[]>,\n labels: Map<number, string>,\n godNodesData: GodNodeEntry[],\n totalNodes: number,\n totalEdges: number,\n): string {\n const lines: string[] = [\n \"# Knowledge Graph Index\",\n \"\",\n \"> Auto-generated by graphify. Start here — read community articles for context, then drill into god nodes for detail.\",\n \"\",\n `**${totalNodes} nodes · ${totalEdges} edges · ${communities.size} communities**`,\n \"\",\n \"---\",\n \"\",\n \"## Communities\",\n \"(sorted by size, largest first)\",\n \"\",\n ];\n\n const sorted = [...communities.entries()].sort((a, b) => b[1].length - a[1].length);\n for (const [cid, nodes] of sorted) {\n const label = labels.get(cid) ?? `Community ${cid}`;\n lines.push(`- [[${label}]] — ${nodes.length} nodes`);\n }\n lines.push(\"\");\n\n if (godNodesData.length > 0) {\n lines.push(\"## God Nodes\", \"(most connected concepts — the load-bearing abstractions)\", \"\");\n for (const node of godNodesData) {\n lines.push(`- [[${node.label}]] — ${node.edges} connections`);\n }\n lines.push(\"\");\n }\n\n lines.push(\n \"---\",\n \"\",\n \"*Generated by [graphify](https://github.com/safishamsi/graphify)*\",\n );\n return lines.join(\"\\n\");\n}\n\nexport function toWiki(\n G: Graph,\n communities: NumericMapLike<string[]>,\n outputDir: string,\n options?: {\n communityLabels?: NumericMapLike<string>;\n cohesion?: NumericMapLike<number>;\n godNodesData?: GodNodeEntry[];\n },\n): number {\n const communityMap = toNumericMap(communities);\n mkdirSync(outputDir, { recursive: true });\n\n const labels = options?.communityLabels\n ? toNumericMap(options.communityLabels)\n : new Map([...communityMap.keys()].map((cid) => [cid, `Community ${cid}`]));\n const cohesion = toNumericMap(options?.cohesion);\n const godNodesData = options?.godNodesData ?? [];\n\n let count = 0;\n\n // Community articles\n for (const [cid, nodes] of communityMap) {\n const label = labels.get(cid) ?? `Community ${cid}`;\n const article = communityArticle(G, cid, nodes, label, labels, cohesion.get(cid));\n writeFileSync(join(outputDir, `${safeFilename(label)}.md`), article);\n count++;\n }\n\n // God node articles\n for (const nodeData of godNodesData) {\n const nid = nodeData.id;\n if (nid && G.hasNode(nid)) {\n const article = godNodeArticle(G, nid, labels);\n writeFileSync(join(outputDir, `${safeFilename(nodeData.label)}.md`), article);\n count++;\n }\n }\n\n // Index\n writeFileSync(\n join(outputDir, \"index.md\"),\n indexMd(communityMap, labels, godNodesData, G.order, G.size),\n );\n\n return count;\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 * 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 * 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 * MCP stdio server - exposes graph query tools to Claude and other agents.\n *\n * Uses @modelcontextprotocol/sdk for the server and graphology for the graph.\n */\nimport { readFileSync } from \"node:fs\";\nimport Graph from \"graphology\";\nimport { bidirectional } from \"graphology-shortest-path/unweighted.js\";\nimport { basename } from \"node:path\";\nimport { validateGraphPath, sanitizeLabel } from \"./security.js\";\nimport { godNodes as computeGodNodes } from \"./analyze.js\";\nimport type { Transport } from \"@modelcontextprotocol/sdk/shared/transport.js\";\n\n// ---------------------------------------------------------------------------\n// Graph loading\n// ---------------------------------------------------------------------------\n\nfunction loadGraph(graphPath: string): Graph {\n let safePath: string;\n try {\n safePath = validateGraphPath(graphPath);\n } catch (err) {\n console.error(`error: ${err instanceof Error ? err.message : err}`);\n process.exit(1);\n }\n\n let data: Record<string, unknown>;\n try {\n data = JSON.parse(readFileSync(safePath, \"utf-8\")) as Record<string, unknown>;\n } catch (err) {\n console.error(\n `error: graph.json is corrupted (${err instanceof Error ? err.message : err}). Re-run the graphify skill to rebuild it (for Codex: $graphify .).`,\n );\n process.exit(1);\n }\n\n const G = new Graph({ type: \"undirected\", multi: false });\n\n // Reconstruct from node-link format\n const nodes = (data.nodes ?? []) as Array<Record<string, unknown>>;\n for (const node of nodes) {\n const { id, ...attrs } = node;\n G.mergeNode(id as string, attrs);\n }\n\n const links = (data.links ?? data.edges ?? []) as Array<Record<string, unknown>>;\n for (const link of links) {\n const { source, target, ...attrs } = link;\n try {\n G.mergeEdge(source as string, target as string, attrs);\n } catch {\n // ignore duplicate edges or missing nodes\n }\n }\n\n return G;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction communitiesFromGraph(G: Graph): Map<number, string[]> {\n const communities = new Map<number, string[]>();\n G.forEachNode((nodeId, data) => {\n const cid = data.community as number | undefined;\n if (cid !== undefined && cid !== null) {\n if (!communities.has(cid)) communities.set(cid, []);\n communities.get(cid)!.push(nodeId);\n }\n });\n return communities;\n}\n\nfunction scoreNodes(G: Graph, terms: string[]): Array<[number, string]> {\n const scored: Array<[number, string]> = [];\n G.forEachNode((nid, data) => {\n const label = ((data.label as string) ?? \"\").toLowerCase();\n const source = ((data.source_file as string) ?? \"\").toLowerCase();\n const score =\n terms.reduce((s, t) => s + (label.includes(t) ? 1 : 0), 0) +\n terms.reduce((s, t) => s + (source.includes(t) ? 0.5 : 0), 0);\n if (score > 0) scored.push([score, nid]);\n });\n scored.sort((a, b) => b[0] - a[0]);\n return scored;\n}\n\nfunction bfs(\n G: Graph,\n startNodes: string[],\n depth: number,\n): { visited: Set<string>; edges: Array<[string, string]> } {\n const visited = new Set<string>(startNodes);\n let frontier = new Set<string>(startNodes);\n const edges: Array<[string, string]> = [];\n for (let i = 0; i < depth; i++) {\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 edges.push([n, neighbor]);\n }\n });\n }\n for (const n of nextFrontier) visited.add(n);\n frontier = nextFrontier;\n }\n return { visited, edges };\n}\n\nfunction dfs(\n G: Graph,\n startNodes: string[],\n depth: number,\n): { visited: Set<string>; edges: Array<[string, string]> } {\n const visited = new Set<string>();\n const edges: Array<[string, string]> = [];\n const stack: Array<[string, number]> = [...startNodes].reverse().map((n) => [n, 0]);\n while (stack.length > 0) {\n const [node, d] = stack.pop()!;\n if (visited.has(node) || d > depth) continue;\n visited.add(node);\n G.forEachNeighbor(node, (neighbor) => {\n if (!visited.has(neighbor)) {\n stack.push([neighbor, d + 1]);\n edges.push([node, neighbor]);\n }\n });\n }\n return { visited, edges };\n}\n\nfunction subgraphToText(\n G: Graph,\n nodes: Set<string>,\n edges: Array<[string, string]>,\n tokenBudget: number = 2000,\n): string {\n const charBudget = tokenBudget * 3;\n const lines: string[] = [];\n\n const sorted = [...nodes].sort((a, b) => G.degree(b) - G.degree(a));\n for (const nid of sorted) {\n const d = G.getNodeAttributes(nid);\n lines.push(\n `NODE ${sanitizeLabel((d.label as string) ?? nid)} [src=${d.source_file ?? \"\"} loc=${d.source_location ?? \"\"} community=${d.community ?? \"\"}]`,\n );\n }\n for (const [u, v] of edges) {\n if (nodes.has(u) && nodes.has(v)) {\n const edgeKey = G.edge(u, v);\n if (!edgeKey) continue;\n const d = G.getEdgeAttributes(edgeKey);\n lines.push(\n `EDGE ${sanitizeLabel((G.getNodeAttribute(u, \"label\") as string) ?? u)} --${d.relation ?? \"\"} [${d.confidence ?? \"\"}]--> ${sanitizeLabel((G.getNodeAttribute(v, \"label\") as string) ?? v)}`,\n );\n }\n }\n let output = lines.join(\"\\n\");\n if (output.length > charBudget) {\n output = output.slice(0, charBudget) + `\\n... (truncated to ~${tokenBudget} token budget)`;\n }\n return output;\n}\n\nfunction findNode(G: Graph, label: string): string[] {\n const term = label.toLowerCase();\n const result: string[] = [];\n G.forEachNode((nid, d) => {\n if (\n ((d.label as string) ?? \"\").toLowerCase().includes(term) ||\n nid.toLowerCase() === term\n ) {\n result.push(nid);\n }\n });\n return result;\n}\n\n// ---------------------------------------------------------------------------\n// Tool handlers\n// ---------------------------------------------------------------------------\n\nfunction toolQueryGraph(G: Graph, args: Record<string, unknown>): string {\n const question = args.question as string;\n const mode = (args.mode as string) ?? \"bfs\";\n const depth = Math.min(Number(args.depth ?? 3), 6);\n const budget = Number(args.token_budget ?? 2000);\n const terms = question\n .split(/\\s+/)\n .filter((t) => t.length > 2)\n .map((t) => t.toLowerCase());\n\n const scored = scoreNodes(G, terms);\n const startNodes = scored.slice(0, 3).map(([, nid]) => nid);\n if (startNodes.length === 0) return \"No matching nodes found.\";\n\n const { visited, edges } =\n mode === \"dfs\" ? dfs(G, startNodes, depth) : bfs(G, startNodes, depth);\n\n const startLabels = startNodes.map(\n (n) => (G.getNodeAttribute(n, \"label\") as string) ?? n,\n );\n const header = `Traversal: ${mode.toUpperCase()} depth=${depth} | Start: [${startLabels.join(\", \")}] | ${visited.size} nodes found\\n\\n`;\n return header + subgraphToText(G, visited, edges, budget);\n}\n\nfunction toolGetNode(G: Graph, args: Record<string, unknown>): string {\n const label = (args.label as string).toLowerCase();\n const matches: Array<[string, Record<string, unknown>]> = [];\n G.forEachNode((nid, d) => {\n if (\n ((d.label as string) ?? \"\").toLowerCase().includes(label) ||\n nid.toLowerCase() === label\n ) {\n matches.push([nid, d]);\n }\n });\n if (matches.length === 0) return `No node matching '${label}' found.`;\n const [nid, d] = matches[0]!;\n return [\n `Node: ${d.label ?? nid}`,\n ` ID: ${nid}`,\n ` Source: ${d.source_file ?? \"\"} ${d.source_location ?? \"\"}`,\n ` Type: ${d.file_type ?? \"\"}`,\n ` Community: ${d.community ?? \"\"}`,\n ` Degree: ${G.degree(nid)}`,\n ].join(\"\\n\");\n}\n\nfunction toolGetNeighbors(G: Graph, args: Record<string, unknown>): string {\n const label = (args.label as string).toLowerCase();\n const relFilter = ((args.relation_filter as string) ?? \"\").toLowerCase();\n const matches = findNode(G, label);\n if (matches.length === 0) return `No node matching '${label}' found.`;\n const nid = matches[0]!;\n const lines = [`Neighbors of ${(G.getNodeAttribute(nid, \"label\") as string) ?? nid}:`];\n G.forEachNeighbor(nid, (neighbor) => {\n const edgeKey = G.edge(nid, neighbor);\n if (!edgeKey) return;\n const d = G.getEdgeAttributes(edgeKey);\n const rel = (d.relation as string) ?? \"\";\n if (relFilter && !rel.toLowerCase().includes(relFilter)) return;\n lines.push(\n ` --> ${(G.getNodeAttribute(neighbor, \"label\") as string) ?? neighbor} [${rel}] [${d.confidence ?? \"\"}]`,\n );\n });\n return lines.join(\"\\n\");\n}\n\nfunction toolGetCommunity(\n communities: Map<number, string[]>,\n G: Graph,\n args: Record<string, unknown>,\n): string {\n const cid = Number(args.community_id);\n const nodes = communities.get(cid);\n if (!nodes || nodes.length === 0) return `Community ${cid} not found.`;\n const lines = [`Community ${cid} (${nodes.length} nodes):`];\n for (const n of nodes) {\n const d = G.getNodeAttributes(n);\n lines.push(` ${d.label ?? n} [${d.source_file ?? \"\"}]`);\n }\n return lines.join(\"\\n\");\n}\n\nfunction toolGodNodes(G: Graph, args: Record<string, unknown>): string {\n const topN = Number(args.top_n ?? 10);\n const nodes = computeGodNodes(G, topN);\n const lines = [\"God nodes (most connected):\"];\n nodes.forEach((n, i) => {\n lines.push(` ${i + 1}. ${n.label} - ${n.edges} edges`);\n });\n return lines.join(\"\\n\");\n}\n\nfunction toolGraphStats(\n G: Graph,\n communities: Map<number, string[]>,\n): string {\n const confs: string[] = [];\n G.forEachEdge((_, data) => {\n confs.push((data.confidence as string) ?? \"EXTRACTED\");\n });\n const total = confs.length || 1;\n return [\n `Nodes: ${G.order}`,\n `Edges: ${G.size}`,\n `Communities: ${communities.size}`,\n `EXTRACTED: ${Math.round((confs.filter((c) => c === \"EXTRACTED\").length / total) * 100)}%`,\n `INFERRED: ${Math.round((confs.filter((c) => c === \"INFERRED\").length / total) * 100)}%`,\n `AMBIGUOUS: ${Math.round((confs.filter((c) => c === \"AMBIGUOUS\").length / total) * 100)}%`,\n ].join(\"\\n\");\n}\n\nfunction toolShortestPath(G: Graph, args: Record<string, unknown>): string {\n const srcTerms = (args.source as string)\n .split(/\\s+/)\n .map((t) => t.toLowerCase());\n const tgtTerms = (args.target as string)\n .split(/\\s+/)\n .map((t) => t.toLowerCase());\n const srcScored = scoreNodes(G, srcTerms);\n const tgtScored = scoreNodes(G, tgtTerms);\n\n if (srcScored.length === 0)\n return `No node matching source '${args.source}' found.`;\n if (tgtScored.length === 0)\n return `No node matching target '${args.target}' found.`;\n\n const srcNid = srcScored[0]![1];\n const tgtNid = tgtScored[0]![1];\n const maxHops = Number(args.max_hops ?? 8);\n\n const pathNodes = bidirectional(G, srcNid, tgtNid);\n if (!pathNodes) {\n return `No path found between '${(G.getNodeAttribute(srcNid, \"label\") as string) ?? srcNid}' and '${(G.getNodeAttribute(tgtNid, \"label\") as string) ?? tgtNid}'.`;\n }\n\n const hops = pathNodes.length - 1;\n if (hops > maxHops) return `Path exceeds max_hops=${maxHops} (${hops} hops found).`;\n\n const segments: string[] = [];\n for (let i = 0; i < pathNodes.length - 1; i++) {\n const u = pathNodes[i]!;\n const v = pathNodes[i + 1]!;\n const edgeKey = G.edge(u, v);\n const edata = edgeKey ? G.getEdgeAttributes(edgeKey) : {};\n const rel = (edata.relation as string) ?? \"\";\n const conf = (edata.confidence as string) ?? \"\";\n const confStr = conf ? ` [${conf}]` : \"\";\n if (i === 0) {\n segments.push((G.getNodeAttribute(u, \"label\") as string) ?? u);\n }\n segments.push(\n `--${rel}${confStr}--> ${(G.getNodeAttribute(v, \"label\") as string) ?? v}`,\n );\n }\n return `Shortest path (${hops} hops):\\n ${segments.join(\" \")}`;\n}\n\n// ---------------------------------------------------------------------------\n// Server\n// ---------------------------------------------------------------------------\n\nexport async function serve(\n graphPath: string = \"graphify-out/graph.json\",\n transport?: Transport,\n): Promise<void> {\n let Server: typeof import(\"@modelcontextprotocol/sdk/server/index.js\").Server;\n let StdioServerTransport: typeof import(\"@modelcontextprotocol/sdk/server/stdio.js\").StdioServerTransport;\n let ListToolsRequestSchema: typeof import(\"@modelcontextprotocol/sdk/types.js\").ListToolsRequestSchema;\n let CallToolRequestSchema: typeof import(\"@modelcontextprotocol/sdk/types.js\").CallToolRequestSchema;\n\n try {\n const serverMod = await import(\"@modelcontextprotocol/sdk/server/index.js\");\n const stdioMod = await import(\"@modelcontextprotocol/sdk/server/stdio.js\");\n const typesMod = await import(\"@modelcontextprotocol/sdk/types.js\");\n Server = serverMod.Server;\n StdioServerTransport = stdioMod.StdioServerTransport;\n ListToolsRequestSchema = typesMod.ListToolsRequestSchema;\n CallToolRequestSchema = typesMod.CallToolRequestSchema;\n } catch {\n throw new Error(\n \"@modelcontextprotocol/sdk not installed. Run: npm install @modelcontextprotocol/sdk\",\n );\n }\n\n const G = loadGraph(graphPath);\n const communities = communitiesFromGraph(G);\n\n const server = new Server(\n { name: \"graphify\", version: \"0.3.17\" },\n { capabilities: { tools: {} } },\n );\n\n server.setRequestHandler(ListToolsRequestSchema, async () => ({\n tools: [\n {\n name: \"query_graph\",\n description:\n \"Search the knowledge graph using BFS or DFS. Returns relevant nodes and edges as text context.\",\n inputSchema: {\n type: \"object\" as const,\n properties: {\n question: {\n type: \"string\",\n description: \"Natural language question or keyword search\",\n },\n mode: {\n type: \"string\",\n enum: [\"bfs\", \"dfs\"],\n default: \"bfs\",\n description: \"bfs=broad context, dfs=trace a specific path\",\n },\n depth: {\n type: \"integer\",\n default: 3,\n description: \"Traversal depth (1-6)\",\n },\n token_budget: {\n type: \"integer\",\n default: 2000,\n description: \"Max output tokens\",\n },\n },\n required: [\"question\"],\n },\n },\n {\n name: \"get_node\",\n description: \"Get full details for a specific node by label or ID.\",\n inputSchema: {\n type: \"object\" as const,\n properties: {\n label: {\n type: \"string\",\n description: \"Node label or ID to look up\",\n },\n },\n required: [\"label\"],\n },\n },\n {\n name: \"get_neighbors\",\n description:\n \"Get all direct neighbors of a node with edge details.\",\n inputSchema: {\n type: \"object\" as const,\n properties: {\n label: { type: \"string\" },\n relation_filter: {\n type: \"string\",\n description: \"Optional: filter by relation type\",\n },\n },\n required: [\"label\"],\n },\n },\n {\n name: \"get_community\",\n description: \"Get all nodes in a community by community ID.\",\n inputSchema: {\n type: \"object\" as const,\n properties: {\n community_id: {\n type: \"integer\",\n description: \"Community ID (0-indexed by size)\",\n },\n },\n required: [\"community_id\"],\n },\n },\n {\n name: \"god_nodes\",\n description:\n \"Return the most connected nodes - the core abstractions of the knowledge graph.\",\n inputSchema: {\n type: \"object\" as const,\n properties: {\n top_n: { type: \"integer\", default: 10 },\n },\n },\n },\n {\n name: \"graph_stats\",\n description:\n \"Return summary statistics: node count, edge count, communities, confidence breakdown.\",\n inputSchema: { type: \"object\" as const, properties: {} },\n },\n {\n name: \"shortest_path\",\n description:\n \"Find the shortest path between two concepts in the knowledge graph.\",\n inputSchema: {\n type: \"object\" as const,\n properties: {\n source: {\n type: \"string\",\n description: \"Source concept label or keyword\",\n },\n target: {\n type: \"string\",\n description: \"Target concept label or keyword\",\n },\n max_hops: {\n type: \"integer\",\n default: 8,\n description: \"Maximum hops to consider\",\n },\n },\n required: [\"source\", \"target\"],\n },\n },\n ],\n }));\n\n const handlers: Record<\n string,\n (args: Record<string, unknown>) => string\n > = {\n query_graph: (a) => toolQueryGraph(G, a),\n get_node: (a) => toolGetNode(G, a),\n get_neighbors: (a) => toolGetNeighbors(G, a),\n get_community: (a) => toolGetCommunity(communities, G, a),\n god_nodes: (a) => toolGodNodes(G, a),\n graph_stats: () => toolGraphStats(G, communities),\n shortest_path: (a) => toolShortestPath(G, a),\n };\n\n server.setRequestHandler(CallToolRequestSchema, async (request) => {\n const { name, arguments: args } = request.params;\n const handler = handlers[name];\n if (!handler) {\n return { content: [{ type: \"text\" as const, text: `Unknown tool: ${name}` }] };\n }\n const text = handler((args ?? {}) as Record<string, unknown>);\n return { content: [{ type: \"text\" as const, text }] };\n });\n\n const serverTransport = transport ?? new StdioServerTransport();\n let keepAlive: NodeJS.Timeout | undefined;\n if (!transport) {\n keepAlive = setInterval(() => undefined, 60_000);\n process.stdin?.resume();\n }\n\n const closed = new Promise<void>((resolve) => {\n const previousOnClose = server.onclose;\n server.onclose = () => {\n if (keepAlive) {\n clearInterval(keepAlive);\n }\n previousOnClose?.();\n resolve();\n };\n });\n\n await server.connect(serverTransport);\n if (transport) {\n await closed;\n }\n}\n\n// ---------------------------------------------------------------------------\n// CLI entry point\n// ---------------------------------------------------------------------------\n\nconst isDirectExecution = typeof process !== \"undefined\" &&\n typeof process.argv[1] === \"string\" &&\n /^serve\\.(?:js|mjs|cjs|ts)$/.test(basename(process.argv[1]));\n\nif (isDirectExecution) {\n const graphPath = process.argv[2] ?? \"graphify-out/graph.json\";\n serve(graphPath).catch((err) => {\n console.error(err);\n process.exit(1);\n });\n}\n","/**\n * File watcher - monitor a folder and auto-trigger graph rebuild when files change.\n *\n * Uses chokidar instead of Python watchdog.\n * Code-only changes rebuild graph automatically (no LLM needed).\n * Doc/paper/image changes write a flag and notify the user.\n */\nimport { existsSync, mkdirSync, writeFileSync, unlinkSync } from \"node:fs\";\nimport { resolve as pathResolve, extname, basename } from \"node:path\";\n\nconst WATCHED_EXTENSIONS = new Set([\n \".py\", \".ts\", \".js\", \".go\", \".rs\", \".java\", \".cpp\", \".c\", \".rb\", \".swift\", \".kt\",\n \".cs\", \".scala\", \".php\", \".cc\", \".cxx\", \".hpp\", \".h\", \".kts\",\n \".md\", \".txt\", \".rst\", \".pdf\",\n \".png\", \".jpg\", \".jpeg\", \".webp\", \".gif\", \".svg\",\n]);\n\nconst CODE_EXTENSIONS = new Set([\n \".py\", \".ts\", \".js\", \".go\", \".rs\", \".java\", \".cpp\", \".c\", \".rb\", \".swift\", \".kt\",\n \".cs\", \".scala\", \".php\", \".cc\", \".cxx\", \".hpp\", \".h\", \".kts\",\n]);\n\n// ---------------------------------------------------------------------------\n// Rebuild pipeline (code-only, no LLM)\n// ---------------------------------------------------------------------------\n\nexport async function rebuildCode(\n watchPath: string,\n followSymlinks: boolean = false,\n): Promise<boolean> {\n try {\n // Dynamic imports - these modules are in the same package\n const { collectFiles, extractWithDiagnostics } = await import(\"./extract.js\");\n const { buildFromJson } = await import(\"./build.js\");\n const { cluster, scoreAll } = await import(\"./cluster.js\");\n const { godNodes, surprisingConnections, suggestQuestions } = await import(\"./analyze.js\");\n const { generate } = await import(\"./report.js\");\n const { toJson } = await import(\"./export.js\");\n\n let codeFiles = await collectFiles(watchPath, { followSymlinks });\n codeFiles = codeFiles.filter(\n (f: string) =>\n !f.includes(\"graphify-out\") &&\n !f.includes(\"__pycache__\") &&\n !f.includes(\"node_modules\"),\n );\n\n if (codeFiles.length === 0) {\n console.log(\"[graphify watch] No code files found - nothing to rebuild.\");\n return false;\n }\n\n const { extraction: result, diagnostics } = await extractWithDiagnostics(codeFiles);\n if (diagnostics.length > 0) {\n console.log(\n `[graphify watch] AST extraction failed for ${diagnostics.length} file(s): ` +\n `${diagnostics.slice(0, 3).map((d) => `${d.filePath}: ${d.error}`).join(\" | \")}`,\n );\n }\n if (result.nodes.length === 0) {\n console.log(\"[graphify watch] Rebuild failed: AST extraction produced no graph nodes.\");\n return false;\n }\n\n const detection = {\n files: {\n code: codeFiles,\n document: [] as string[],\n paper: [] as string[],\n image: [] as string[],\n },\n total_files: codeFiles.length,\n total_words: 0,\n needs_graph: true,\n warning: null,\n skipped_sensitive: [] as string[],\n graphifyignore_patterns: 0,\n };\n\n const G = buildFromJson(result);\n const communities = cluster(G);\n const cohesion = scoreAll(G, communities);\n const gods = godNodes(G);\n const surprises = surprisingConnections(G, communities);\n const labels = new Map<number, string>();\n for (const cid of communities.keys()) {\n labels.set(cid, `Community ${cid}`);\n }\n const questions = suggestQuestions(G, communities, labels);\n\n const outDir = pathResolve(watchPath, \"graphify-out\");\n mkdirSync(outDir, { recursive: true });\n\n const report = generate(\n G,\n communities,\n cohesion,\n labels,\n gods,\n surprises,\n detection,\n { input: 0, output: 0 },\n watchPath,\n questions,\n );\n writeFileSync(pathResolve(outDir, \"GRAPH_REPORT.md\"), report, \"utf-8\");\n toJson(G, communities, pathResolve(outDir, \"graph.json\"));\n\n // Clear stale needs_update flag if present\n const flagPath = pathResolve(outDir, \"needs_update\");\n if (existsSync(flagPath)) {\n unlinkSync(flagPath);\n }\n\n console.log(\n `[graphify watch] Rebuilt: ${G.order} nodes, ${G.size} edges, ${communities.size} communities`,\n );\n console.log(\n `[graphify watch] graph.json and GRAPH_REPORT.md updated in ${outDir}`,\n );\n return true;\n } catch (err) {\n console.log(\n `[graphify watch] Rebuild failed: ${err instanceof Error ? err.message : err}`,\n );\n return false;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Notification fallback (non-code changes)\n// ---------------------------------------------------------------------------\n\nfunction notifyOnly(watchPath: string): void {\n const outDir = pathResolve(watchPath, \"graphify-out\");\n mkdirSync(outDir, { recursive: true });\n const flagPath = pathResolve(outDir, \"needs_update\");\n writeFileSync(flagPath, \"1\", \"utf-8\");\n console.log(`\\n[graphify watch] New or changed files detected in ${watchPath}`);\n console.log(\n \"[graphify watch] Non-code files changed - semantic re-extraction requires LLM.\",\n );\n console.log(\n \"[graphify watch] Run the graphify skill with `--update` to refresh semantic data (for Codex: `$graphify . --update`).\",\n );\n console.log(`[graphify watch] Flag written to ${flagPath}`);\n}\n\nfunction hasNonCode(changedPaths: string[]): boolean {\n return changedPaths.some((p) => !CODE_EXTENSIONS.has(extname(p).toLowerCase()));\n}\n\n// ---------------------------------------------------------------------------\n// Main watcher\n// ---------------------------------------------------------------------------\n\nexport async function watch(\n watchPath: string,\n debounce: number = 3.0,\n): Promise<void> {\n let chokidar: typeof import(\"chokidar\");\n try {\n chokidar = await import(\"chokidar\");\n } catch {\n throw new Error(\"chokidar not installed. Run: npm install chokidar\");\n }\n\n const resolvedPath = pathResolve(watchPath);\n let lastTrigger = 0;\n let pending = false;\n const changed = new Set<string>();\n\n const watcher = chokidar.watch(resolvedPath, {\n persistent: true,\n ignoreInitial: true,\n followSymlinks: false,\n ignored: [\n /node_modules/,\n /\\.git/,\n /graphify-out/,\n ],\n });\n\n watcher.on(\"all\", (_event: string, filePath: string) => {\n const ext = extname(filePath).toLowerCase();\n if (!WATCHED_EXTENSIONS.has(ext)) return;\n\n // Skip hidden directories\n const parts = filePath.split(\"/\");\n if (parts.some((part) => part.startsWith(\".\") && part !== \".\")) return;\n\n lastTrigger = Date.now();\n pending = true;\n changed.add(filePath);\n });\n\n console.log(\n `[graphify watch] Watching ${resolvedPath} - press Ctrl+C to stop`,\n );\n console.log(\n \"[graphify watch] Code changes rebuild graph automatically. Doc/image changes require a graphify skill `--update` run.\",\n );\n console.log(`[graphify watch] Debounce: ${debounce}s`);\n\n const debounceMs = debounce * 1000;\n\n const poll = setInterval(async () => {\n if (pending && Date.now() - lastTrigger >= debounceMs) {\n pending = false;\n const batch = [...changed];\n changed.clear();\n console.log(`\\n[graphify watch] ${batch.length} file(s) changed`);\n if (hasNonCode(batch)) {\n notifyOnly(watchPath);\n } else {\n await rebuildCode(watchPath);\n }\n }\n }, 500);\n\n // Graceful shutdown\n const cleanup = () => {\n console.log(\"\\n[graphify watch] Stopped.\");\n clearInterval(poll);\n watcher.close();\n process.exit(0);\n };\n\n process.on(\"SIGINT\", cleanup);\n process.on(\"SIGTERM\", cleanup);\n}\n\n// ---------------------------------------------------------------------------\n// CLI entry point\n// ---------------------------------------------------------------------------\n\nconst isDirectExecution = typeof process !== \"undefined\" &&\n typeof process.argv[1] === \"string\" &&\n /^watch\\.(?:js|mjs|cjs|ts)$/.test(basename(process.argv[1]));\n\nif (isDirectExecution) {\n const watchPath = process.argv[2] ?? \".\";\n const debounce = process.argv[3] ? parseFloat(process.argv[3]) : 3.0;\n watch(watchPath, debounce).catch((err) => {\n console.error(err);\n process.exit(1);\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAaO,SAAS,mBAAmB,MAAyB;AAC1D,MAAI,OAAO,SAAS,YAAY,SAAS,QAAQ,MAAM,QAAQ,IAAI,GAAG;AACpE,WAAO,CAAC,kCAAkC;AAAA,EAC5C;AAEA,QAAM,IAAI;AACV,QAAM,SAAmB,CAAC;AAG1B,MAAI,EAAE,WAAW,IAAI;AACnB,WAAO,KAAK,8BAA8B;AAAA,EAC5C,WAAW,CAAC,MAAM,QAAQ,EAAE,KAAK,GAAG;AAClC,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7D,IAAIA,oBAAmB;AACrB,QAAM,YAAY,QAAQ,KAAK,CAAC,KAAK;AACrC,QAAM,WAAW,QAAQ,KAAK,CAAC,IAAI,WAAW,QAAQ,KAAK,CAAC,CAAC,IAAI;AACjE,QAAM,WAAW,QAAQ,EAAE,MAAM,CAAC,QAAQ;AACxC,YAAQ,MAAM,GAAG;AACjB,YAAQ,KAAK,CAAC;AAAA,EAChB,CAAC;AACH;","names":["Graph","louvain","result","betweennessCentrality","pathResolve","nodeCommunityMap","import_node_fs","import_node_crypto","import_node_fs","import_node_path","Parser","module","walkDir","import_node_fs","import_node_path","FileType","import_node_fs","import_node_path","import_node_fs","import_node_path","CODE_EXTENSIONS","PAPER_EXTENSIONS","IMAGE_EXTENSIONS","import_node_fs","import_graphology","Graph","import_node_fs","import_node_path","safeFilename","pathResolve","import_node_fs","import_graphology","import_node_path","loadGraph","Graph","nid","d","resolve","isDirectExecution","import_node_fs","import_node_path","CODE_EXTENSIONS","collectFiles","extractWithDiagnostics","buildFromJson","cluster","scoreAll","godNodes","surprisingConnections","suggestQuestions","generate","toJson","pathResolve","isDirectExecution"]}
1
+ {"version":3,"sources":["../src/types.ts","../src/validate.ts","../src/graph.ts","../src/build.ts","../src/collections.ts","../src/cluster.ts","../src/detect.ts","../src/analyze.ts","../src/report.ts","../src/security.ts","../src/export.ts","../src/cache.ts","../src/extract.ts","../src/index.ts","../src/wiki.ts","../src/benchmark.ts","../src/ingest.ts","../src/transcribe.ts","../src/serve.ts","../src/watch.ts"],"sourcesContent":["/** File type classification for corpus files. */\nexport enum FileType {\n CODE = \"code\",\n DOCUMENT = \"document\",\n PAPER = \"paper\",\n IMAGE = \"image\",\n VIDEO = \"video\",\n}\n\n/** Confidence level for extracted relationships. */\nexport type Confidence = \"EXTRACTED\" | \"INFERRED\" | \"AMBIGUOUS\";\n\n/** A node in the knowledge graph. */\nexport interface GraphNode {\n id: string;\n label: string;\n file_type: \"code\" | \"document\" | \"paper\" | \"image\" | \"rationale\";\n source_file: string;\n source_location?: string;\n confidence?: Confidence;\n community?: number;\n [key: string]: unknown;\n}\n\n/** An edge in the knowledge graph. */\nexport interface GraphEdge {\n source: string;\n target: string;\n relation: string;\n confidence: Confidence;\n source_file: string;\n source_location?: string;\n confidence_score?: number;\n weight?: number;\n /** Original source direction (preserved for display). */\n _src?: string;\n /** Original target direction (preserved for display). */\n _tgt?: string;\n [key: string]: unknown;\n}\n\n/** A hyperedge grouping multiple nodes. */\nexport interface Hyperedge {\n id: string;\n label: string;\n nodes: string[];\n relation: string;\n confidence: Confidence;\n source_file: string;\n confidence_score?: number;\n [key: string]: unknown;\n}\n\n/** Output of an extraction pass. */\nexport interface Extraction {\n nodes: GraphNode[];\n edges: GraphEdge[];\n hyperedges?: Hyperedge[];\n input_tokens: number;\n output_tokens: number;\n}\n\n/** Output of the detect() function. */\nexport interface DetectionResult {\n files: Record<string, string[]>;\n total_files: number;\n total_words: number;\n needs_graph: boolean;\n warning: string | null;\n skipped_sensitive: string[];\n graphifyignore_patterns: number;\n /** Present in incremental mode. */\n incremental?: boolean;\n new_files?: Record<string, string[]>;\n unchanged_files?: Record<string, string[]>;\n new_total?: number;\n deleted_files?: string[];\n}\n\n/** A god node (most connected entity). */\nexport interface GodNodeEntry {\n id: string;\n label: string;\n edges: number;\n}\n\n/** A surprising connection. */\nexport interface SurpriseEntry {\n source: string;\n target: string;\n source_files: [string, string];\n confidence: Confidence;\n relation: string;\n note?: string;\n why?: string;\n confidence_score?: number;\n}\n\n/** A suggested question. */\nexport interface SuggestedQuestion {\n type: string;\n question: string | null;\n why: string;\n}\n\n/** Benchmark result. */\nexport interface BenchmarkResult {\n corpus_tokens?: number;\n corpus_words?: number;\n nodes?: number;\n edges?: number;\n avg_query_tokens?: number;\n reduction_ratio?: number;\n per_question?: Array<{ question: string; query_tokens: number; reduction: number }>;\n error?: string;\n}\n\n/** Graph diff between two snapshots. */\nexport interface GraphDiffResult {\n new_nodes: Array<{ id: string; label: string }>;\n removed_nodes: Array<{ id: string; label: string }>;\n new_edges: Array<{ source: string; target: string; relation: string; confidence: string }>;\n removed_edges: Array<{ source: string; target: string; relation: string; confidence: string }>;\n summary: string;\n}\n\n/** Platform configuration for skill installation. */\nexport interface PlatformConfig {\n skill_file: string;\n skill_dst: string;\n claude_md: boolean;\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","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 * 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","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","/**\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 * 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","/**\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","/**\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, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/'/g, \"&#39;\");\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 &middot; ${G.size} edges &middot; ${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, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/'/g, \"&apos;\");\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, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\");\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 * 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 * 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 * graphify - extract · build · cluster · analyze · report.\n */\n\nexport { type GraphNode, type GraphEdge, type Extraction, type Hyperedge, type DetectionResult, FileType } from \"./types.js\";\nexport { validateExtraction, assertValid } from \"./validate.js\";\nexport { buildFromJson, build } from \"./build.js\";\nexport { cluster, cohesionScore, scoreAll } from \"./cluster.js\";\nexport { godNodes, surprisingConnections, suggestQuestions, graphDiff } from \"./analyze.js\";\nexport { generate as generateReport } from \"./report.js\";\nexport { toJson, toHtml, toSvg, toGraphml, toCypher, toCanvas, pushToNeo4j } from \"./export.js\";\nexport { toWiki } from \"./wiki.js\";\nexport { detect, classifyFile, detectIncremental, saveManifest } from \"./detect.js\";\nexport { extract, collectFiles } from \"./extract.js\";\nexport { fileHash, loadCached, saveCached, checkSemanticCache, saveSemanticCache } from \"./cache.js\";\nexport { validateUrl, safeFetch, safeFetchText, validateGraphPath, sanitizeLabel } from \"./security.js\";\nexport { runBenchmark, printBenchmark } from \"./benchmark.js\";\nexport { ingest, saveQueryResult } from \"./ingest.js\";\nexport { downloadAudio, buildWhisperPrompt, transcribe, transcribeAll, augmentDetectionWithTranscripts } from \"./transcribe.js\";\nexport { serve } from \"./serve.js\";\nexport { watch, rebuildCode } from \"./watch.js\";\n","/**\n * Wiki export - Wikipedia-style markdown articles from the knowledge graph.\n * Generates an agent-crawlable wiki: index.md + one article per community + god node articles.\n */\nimport { mkdirSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport Graph from \"graphology\";\nimport type { GodNodeEntry } from \"./types.js\";\nimport { type NumericMapLike, toNumericMap } from \"./collections.js\";\nimport { traversalNeighbors } from \"./graph.js\";\n\nfunction safeFilename(name: string): string {\n return name\n .replace(/\\r\\n/g, \" \")\n .replace(/\\r/g, \" \")\n .replace(/\\n/g, \" \")\n .replace(/\\//g, \"-\")\n .replace(/ /g, \"_\")\n .replace(/:/g, \"-\");\n}\n\nfunction crossCommunityLinks(\n G: Graph,\n nodes: string[],\n ownCid: number,\n labels: NumericMapLike<string>,\n): [string, number][] {\n const labelMap = toNumericMap(labels);\n const counts = new Map<string, number>();\n for (const nid of nodes) {\n for (const neighbor of traversalNeighbors(G, nid)) {\n const ncid = G.getNodeAttribute(neighbor, \"community\") as number | undefined;\n if (ncid !== undefined && ncid !== ownCid) {\n const label = labelMap.get(ncid) ?? `Community ${ncid}`;\n counts.set(label, (counts.get(label) ?? 0) + 1);\n }\n }\n }\n return [...counts.entries()].sort((a, b) => b[1] - a[1]);\n}\n\nfunction communityArticle(\n G: Graph,\n cid: number,\n nodes: string[],\n label: string,\n labels: Map<number, string>,\n cohesion: number | undefined,\n): string {\n const topNodes = [...nodes].sort((a, b) => G.degree(b) - G.degree(a)).slice(0, 25);\n const cross = crossCommunityLinks(G, nodes, cid, labels);\n\n const confCounts: Record<string, number> = { EXTRACTED: 0, INFERRED: 0, AMBIGUOUS: 0 };\n for (const nid of nodes) {\n G.forEachEdge(nid, (_, data) => {\n const conf = (data.confidence as string) ?? \"EXTRACTED\";\n confCounts[conf] = (confCounts[conf] ?? 0) + 1;\n });\n }\n const totalEdges = Object.values(confCounts).reduce((s, n) => s + n, 0) || 1;\n\n const sources = [...new Set(nodes.map((n) => (G.getNodeAttribute(n, \"source_file\") as string) ?? \"\").filter(Boolean))].sort();\n\n const lines: string[] = [];\n lines.push(`# ${label}`, \"\");\n\n const metaParts = [`${nodes.length} nodes`];\n if (cohesion !== undefined) metaParts.push(`cohesion ${cohesion.toFixed(2)}`);\n lines.push(`> ${metaParts.join(\" · \")}`, \"\");\n\n lines.push(\"## Key Concepts\", \"\");\n for (const nid of topNodes) {\n const d = G.getNodeAttributes(nid);\n const nodeLabel = (d.label as string) ?? nid;\n const src = (d.source_file as string) ?? \"\";\n const degree = G.degree(nid);\n const srcStr = src ? ` — \\`${src}\\`` : \"\";\n lines.push(`- **${nodeLabel}** (${degree} connections)${srcStr}`);\n }\n const remaining = nodes.length - topNodes.length;\n if (remaining > 0) lines.push(`- *... and ${remaining} more nodes in this community*`);\n lines.push(\"\");\n\n lines.push(\"## Relationships\", \"\");\n if (cross.length > 0) {\n for (const [otherLabel, count] of cross.slice(0, 12)) {\n lines.push(`- [[${otherLabel}]] (${count} shared connections)`);\n }\n } else {\n lines.push(\"- No strong cross-community connections detected\");\n }\n lines.push(\"\");\n\n if (sources.length > 0) {\n lines.push(\"## Source Files\", \"\");\n for (const src of sources.slice(0, 20)) {\n lines.push(`- \\`${src}\\``);\n }\n lines.push(\"\");\n }\n\n lines.push(\"## Audit Trail\", \"\");\n for (const conf of [\"EXTRACTED\", \"INFERRED\", \"AMBIGUOUS\"]) {\n const n = confCounts[conf] ?? 0;\n const pct = Math.round((n / totalEdges) * 100);\n lines.push(`- ${conf}: ${n} (${pct}%)`);\n }\n lines.push(\"\");\n\n lines.push(\"---\", \"\", \"*Part of the graphify knowledge wiki. See [[index]] to navigate.*\");\n return lines.join(\"\\n\");\n}\n\nfunction godNodeArticle(G: Graph, nid: string, labels: Map<number, string>): string {\n const d = G.getNodeAttributes(nid);\n const nodeLabel = (d.label as string) ?? nid;\n const src = (d.source_file as string) ?? \"\";\n const cid = d.community as number | undefined;\n const communityName = cid !== undefined ? (labels.get(cid) ?? `Community ${cid}`) : undefined;\n\n const lines: string[] = [];\n lines.push(`# ${nodeLabel}`, \"\");\n lines.push(`> God node · ${G.degree(nid)} connections · \\`${src}\\``, \"\");\n\n if (communityName) {\n lines.push(`**Community:** [[${communityName}]]`, \"\");\n }\n\n const byRelation = new Map<string, string[]>();\n const neighbors = traversalNeighbors(G, nid).sort((a, b) => G.degree(b) - G.degree(a));\n for (const neighbor of neighbors) {\n const ed = G.getEdgeAttributes(G.edge(nid, neighbor)!);\n const rel = (ed.relation as string) ?? \"related\";\n const neighborLabel = (G.getNodeAttribute(neighbor, \"label\") as string) ?? neighbor;\n const conf = (ed.confidence as string) ?? \"\";\n const confStr = conf ? ` \\`${conf}\\`` : \"\";\n if (!byRelation.has(rel)) byRelation.set(rel, []);\n byRelation.get(rel)!.push(`[[${neighborLabel}]]${confStr}`);\n }\n\n lines.push(\"## Connections by Relation\", \"\");\n for (const [rel, targets] of [...byRelation.entries()].sort()) {\n lines.push(`### ${rel}`);\n for (const t of targets.slice(0, 20)) {\n lines.push(`- ${t}`);\n }\n lines.push(\"\");\n }\n\n lines.push(\"---\", \"\", \"*Part of the graphify knowledge wiki. See [[index]] to navigate.*\");\n return lines.join(\"\\n\");\n}\n\nfunction indexMd(\n communities: Map<number, string[]>,\n labels: Map<number, string>,\n godNodesData: GodNodeEntry[],\n totalNodes: number,\n totalEdges: number,\n): string {\n const lines: string[] = [\n \"# Knowledge Graph Index\",\n \"\",\n \"> Auto-generated by graphify. Start here — read community articles for context, then drill into god nodes for detail.\",\n \"\",\n `**${totalNodes} nodes · ${totalEdges} edges · ${communities.size} communities**`,\n \"\",\n \"---\",\n \"\",\n \"## Communities\",\n \"(sorted by size, largest first)\",\n \"\",\n ];\n\n const sorted = [...communities.entries()].sort((a, b) => b[1].length - a[1].length);\n for (const [cid, nodes] of sorted) {\n const label = labels.get(cid) ?? `Community ${cid}`;\n lines.push(`- [[${label}]] — ${nodes.length} nodes`);\n }\n lines.push(\"\");\n\n if (godNodesData.length > 0) {\n lines.push(\"## God Nodes\", \"(most connected concepts — the load-bearing abstractions)\", \"\");\n for (const node of godNodesData) {\n lines.push(`- [[${node.label}]] — ${node.edges} connections`);\n }\n lines.push(\"\");\n }\n\n lines.push(\n \"---\",\n \"\",\n \"*Generated by [graphify](https://github.com/safishamsi/graphify)*\",\n );\n return lines.join(\"\\n\");\n}\n\nexport function toWiki(\n G: Graph,\n communities: NumericMapLike<string[]>,\n outputDir: string,\n options?: {\n communityLabels?: NumericMapLike<string>;\n cohesion?: NumericMapLike<number>;\n godNodesData?: GodNodeEntry[];\n },\n): number {\n const communityMap = toNumericMap(communities);\n mkdirSync(outputDir, { recursive: true });\n\n const labels = options?.communityLabels\n ? toNumericMap(options.communityLabels)\n : new Map([...communityMap.keys()].map((cid) => [cid, `Community ${cid}`]));\n const cohesion = toNumericMap(options?.cohesion);\n const godNodesData = options?.godNodesData ?? [];\n\n let count = 0;\n\n // Community articles\n for (const [cid, nodes] of communityMap) {\n const label = labels.get(cid) ?? `Community ${cid}`;\n const article = communityArticle(G, cid, nodes, label, labels, cohesion.get(cid));\n writeFileSync(join(outputDir, `${safeFilename(label)}.md`), article);\n count++;\n }\n\n // God node articles\n for (const nodeData of godNodesData) {\n const nid = nodeData.id;\n if (nid && G.hasNode(nid)) {\n const article = godNodeArticle(G, nid, labels);\n writeFileSync(join(outputDir, `${safeFilename(nodeData.label)}.md`), article);\n count++;\n }\n }\n\n // Index\n writeFileSync(\n join(outputDir, \"index.md\"),\n indexMd(communityMap, labels, godNodesData, G.order, G.size),\n );\n\n return count;\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 * 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 * MCP stdio server - exposes graph query tools to Claude and other agents.\n *\n * Uses @modelcontextprotocol/sdk for the server and graphology for the graph.\n */\nimport { readFileSync } from \"node:fs\";\nimport Graph from \"graphology\";\nimport { bidirectional } from \"graphology-shortest-path/unweighted.js\";\nimport { basename, dirname, resolve } from \"node:path\";\nimport {\n forEachTraversalNeighbor,\n loadGraphFromData,\n type SerializedGraphData,\n} from \"./graph.js\";\nimport { validateGraphPath, sanitizeLabel } from \"./security.js\";\nimport { godNodes as computeGodNodes } from \"./analyze.js\";\nimport type { Transport } from \"@modelcontextprotocol/sdk/shared/transport.js\";\n\n// ---------------------------------------------------------------------------\n// Graph loading\n// ---------------------------------------------------------------------------\n\nfunction loadGraph(graphPath: string): Graph {\n let safePath: string;\n try {\n safePath = validateGraphPath(graphPath, dirname(resolve(graphPath)));\n } catch (err) {\n console.error(`error: ${err instanceof Error ? err.message : err}`);\n process.exit(1);\n }\n\n let data: SerializedGraphData;\n try {\n data = JSON.parse(readFileSync(safePath, \"utf-8\")) as SerializedGraphData;\n } catch (err) {\n console.error(\n `error: graph.json is corrupted (${err instanceof Error ? err.message : err}). Re-run the graphify skill to rebuild it (for Codex: $graphify .).`,\n );\n process.exit(1);\n }\n\n return loadGraphFromData(data);\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction communitiesFromGraph(G: Graph): Map<number, string[]> {\n const communities = new Map<number, string[]>();\n G.forEachNode((nodeId, data) => {\n const cid = data.community as number | undefined;\n if (cid !== undefined && cid !== null) {\n if (!communities.has(cid)) communities.set(cid, []);\n communities.get(cid)!.push(nodeId);\n }\n });\n return communities;\n}\n\nfunction communityName(G: Graph, cid: number | string | null | undefined): string | null {\n if (cid === undefined || cid === null) return null;\n const labels = G.getAttribute(\"community_labels\") as Record<string, unknown> | undefined;\n const fromGraph = labels?.[String(cid)];\n if (typeof fromGraph === \"string\" && fromGraph.length > 0) {\n return sanitizeLabel(fromGraph);\n }\n return null;\n}\n\nfunction scoreNodes(G: Graph, terms: string[]): Array<[number, string]> {\n const scored: Array<[number, string]> = [];\n G.forEachNode((nid, data) => {\n const label = ((data.label as string) ?? \"\").toLowerCase();\n const source = ((data.source_file as string) ?? \"\").toLowerCase();\n const score =\n terms.reduce((s, t) => s + (label.includes(t) ? 1 : 0), 0) +\n terms.reduce((s, t) => s + (source.includes(t) ? 0.5 : 0), 0);\n if (score > 0) scored.push([score, nid]);\n });\n scored.sort((a, b) => b[0] - a[0]);\n return scored;\n}\n\nfunction bfs(\n G: Graph,\n startNodes: string[],\n depth: number,\n): { visited: Set<string>; edges: Array<[string, string]> } {\n const visited = new Set<string>(startNodes);\n let frontier = new Set<string>(startNodes);\n const edges: Array<[string, string]> = [];\n for (let i = 0; i < depth; i++) {\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 edges.push([n, neighbor]);\n }\n });\n }\n for (const n of nextFrontier) visited.add(n);\n frontier = nextFrontier;\n }\n return { visited, edges };\n}\n\nfunction dfs(\n G: Graph,\n startNodes: string[],\n depth: number,\n): { visited: Set<string>; edges: Array<[string, string]> } {\n const visited = new Set<string>();\n const edges: Array<[string, string]> = [];\n const stack: Array<[string, number]> = [...startNodes].reverse().map((n) => [n, 0]);\n while (stack.length > 0) {\n const [node, d] = stack.pop()!;\n if (visited.has(node) || d > depth) continue;\n visited.add(node);\n forEachTraversalNeighbor(G, node, (neighbor) => {\n if (!visited.has(neighbor)) {\n stack.push([neighbor, d + 1]);\n edges.push([node, neighbor]);\n }\n });\n }\n return { visited, edges };\n}\n\nfunction subgraphToText(\n G: Graph,\n nodes: Set<string>,\n edges: Array<[string, string]>,\n tokenBudget: number = 2000,\n): string {\n const charBudget = tokenBudget * 3;\n const lines: string[] = [];\n\n const sorted = [...nodes].sort((a, b) => G.degree(b) - G.degree(a));\n for (const nid of sorted) {\n const d = G.getNodeAttributes(nid);\n lines.push(\n `NODE ${sanitizeLabel((d.label as string) ?? nid)} [src=${d.source_file ?? \"\"} loc=${d.source_location ?? \"\"} community=${d.community ?? \"\"}]`,\n );\n }\n for (const [u, v] of edges) {\n if (nodes.has(u) && nodes.has(v)) {\n const edgeKey = G.edge(u, v);\n if (!edgeKey) continue;\n const d = G.getEdgeAttributes(edgeKey);\n lines.push(\n `EDGE ${sanitizeLabel((G.getNodeAttribute(u, \"label\") as string) ?? u)} --${d.relation ?? \"\"} [${d.confidence ?? \"\"}]--> ${sanitizeLabel((G.getNodeAttribute(v, \"label\") as string) ?? v)}`,\n );\n }\n }\n let output = lines.join(\"\\n\");\n if (output.length > charBudget) {\n output = output.slice(0, charBudget) + `\\n... (truncated to ~${tokenBudget} token budget)`;\n }\n return output;\n}\n\nfunction findNode(G: Graph, label: string): string[] {\n const term = label.toLowerCase();\n const result: string[] = [];\n G.forEachNode((nid, d) => {\n if (\n ((d.label as string) ?? \"\").toLowerCase().includes(term) ||\n nid.toLowerCase() === term\n ) {\n result.push(nid);\n }\n });\n return result;\n}\n\n// ---------------------------------------------------------------------------\n// Tool handlers\n// ---------------------------------------------------------------------------\n\nfunction toolQueryGraph(G: Graph, args: Record<string, unknown>): string {\n const question = args.question as string;\n const mode = (args.mode as string) ?? \"bfs\";\n const depth = Math.min(Number(args.depth ?? 3), 6);\n const budget = Number(args.token_budget ?? 2000);\n const terms = question\n .split(/\\s+/)\n .filter((t) => t.length > 2)\n .map((t) => t.toLowerCase());\n\n const scored = scoreNodes(G, terms);\n const startNodes = scored.slice(0, 3).map(([, nid]) => nid);\n if (startNodes.length === 0) return \"No matching nodes found.\";\n\n const { visited, edges } =\n mode === \"dfs\" ? dfs(G, startNodes, depth) : bfs(G, startNodes, depth);\n\n const startLabels = startNodes.map(\n (n) => (G.getNodeAttribute(n, \"label\") as string) ?? n,\n );\n const header = `Traversal: ${mode.toUpperCase()} depth=${depth} | Start: [${startLabels.join(\", \")}] | ${visited.size} nodes found\\n\\n`;\n return header + subgraphToText(G, visited, edges, budget);\n}\n\nfunction toolGetNode(G: Graph, args: Record<string, unknown>): string {\n const label = (args.label as string).toLowerCase();\n const matches: Array<[string, Record<string, unknown>]> = [];\n G.forEachNode((nid, d) => {\n if (\n ((d.label as string) ?? \"\").toLowerCase().includes(label) ||\n nid.toLowerCase() === label\n ) {\n matches.push([nid, d]);\n }\n });\n if (matches.length === 0) return `No node matching '${label}' found.`;\n const [nid, d] = matches[0]!;\n return [\n `Node: ${d.label ?? nid}`,\n ` ID: ${nid}`,\n ` Source: ${d.source_file ?? \"\"} ${d.source_location ?? \"\"}`,\n ` Type: ${d.file_type ?? \"\"}`,\n ` Community: ${\n d.community_name\n ? `${d.community ?? \"\"} (${d.community_name as string})`\n : (communityName(G, d.community as number | undefined) ?? String(d.community ?? \"\"))\n }`,\n ` Degree: ${G.degree(nid)}`,\n ].join(\"\\n\");\n}\n\nfunction toolGetNeighbors(G: Graph, args: Record<string, unknown>): string {\n const label = (args.label as string).toLowerCase();\n const relFilter = ((args.relation_filter as string) ?? \"\").toLowerCase();\n const matches = findNode(G, label);\n if (matches.length === 0) return `No node matching '${label}' found.`;\n const nid = matches[0]!;\n const lines = [`Neighbors of ${(G.getNodeAttribute(nid, \"label\") as string) ?? nid}:`];\n forEachTraversalNeighbor(G, nid, (neighbor) => {\n const edgeKey = G.edge(nid, neighbor);\n if (!edgeKey) return;\n const d = G.getEdgeAttributes(edgeKey);\n const rel = (d.relation as string) ?? \"\";\n if (relFilter && !rel.toLowerCase().includes(relFilter)) return;\n lines.push(\n ` --> ${(G.getNodeAttribute(neighbor, \"label\") as string) ?? neighbor} [${rel}] [${d.confidence ?? \"\"}]`,\n );\n });\n return lines.join(\"\\n\");\n}\n\nfunction toolGetCommunity(\n communities: Map<number, string[]>,\n G: Graph,\n args: Record<string, unknown>,\n): string {\n const cid = Number(args.community_id);\n const nodes = communities.get(cid);\n if (!nodes || nodes.length === 0) return `Community ${cid} not found.`;\n const label = communityName(G, cid);\n const lines = [label\n ? `Community ${cid} - ${label} (${nodes.length} nodes):`\n : `Community ${cid} (${nodes.length} nodes):`];\n for (const n of nodes) {\n const d = G.getNodeAttributes(n);\n lines.push(` ${d.label ?? n} [${d.source_file ?? \"\"}]`);\n }\n return lines.join(\"\\n\");\n}\n\nfunction toolGodNodes(G: Graph, args: Record<string, unknown>): string {\n const topN = Number(args.top_n ?? 10);\n const nodes = computeGodNodes(G, topN);\n const lines = [\"God nodes (most connected):\"];\n nodes.forEach((n, i) => {\n lines.push(` ${i + 1}. ${n.label} - ${n.edges} edges`);\n });\n return lines.join(\"\\n\");\n}\n\nfunction toolGraphStats(\n G: Graph,\n communities: Map<number, string[]>,\n): string {\n const confs: string[] = [];\n G.forEachEdge((_, data) => {\n confs.push((data.confidence as string) ?? \"EXTRACTED\");\n });\n const total = confs.length || 1;\n return [\n `Nodes: ${G.order}`,\n `Edges: ${G.size}`,\n `Communities: ${communities.size}`,\n `EXTRACTED: ${Math.round((confs.filter((c) => c === \"EXTRACTED\").length / total) * 100)}%`,\n `INFERRED: ${Math.round((confs.filter((c) => c === \"INFERRED\").length / total) * 100)}%`,\n `AMBIGUOUS: ${Math.round((confs.filter((c) => c === \"AMBIGUOUS\").length / total) * 100)}%`,\n ].join(\"\\n\");\n}\n\nfunction toolShortestPath(G: Graph, args: Record<string, unknown>): string {\n const srcTerms = (args.source as string)\n .split(/\\s+/)\n .map((t) => t.toLowerCase());\n const tgtTerms = (args.target as string)\n .split(/\\s+/)\n .map((t) => t.toLowerCase());\n const srcScored = scoreNodes(G, srcTerms);\n const tgtScored = scoreNodes(G, tgtTerms);\n\n if (srcScored.length === 0)\n return `No node matching source '${args.source}' found.`;\n if (tgtScored.length === 0)\n return `No node matching target '${args.target}' found.`;\n\n const srcNid = srcScored[0]![1];\n const tgtNid = tgtScored[0]![1];\n const maxHops = Number(args.max_hops ?? 8);\n\n const pathNodes = bidirectional(G, srcNid, tgtNid);\n if (!pathNodes) {\n return `No path found between '${(G.getNodeAttribute(srcNid, \"label\") as string) ?? srcNid}' and '${(G.getNodeAttribute(tgtNid, \"label\") as string) ?? tgtNid}'.`;\n }\n\n const hops = pathNodes.length - 1;\n if (hops > maxHops) return `Path exceeds max_hops=${maxHops} (${hops} hops found).`;\n\n const segments: string[] = [];\n for (let i = 0; i < pathNodes.length - 1; i++) {\n const u = pathNodes[i]!;\n const v = pathNodes[i + 1]!;\n const edgeKey = G.edge(u, v);\n const edata = edgeKey ? G.getEdgeAttributes(edgeKey) : {};\n const rel = (edata.relation as string) ?? \"\";\n const conf = (edata.confidence as string) ?? \"\";\n const confStr = conf ? ` [${conf}]` : \"\";\n if (i === 0) {\n segments.push((G.getNodeAttribute(u, \"label\") as string) ?? u);\n }\n segments.push(\n `--${rel}${confStr}--> ${(G.getNodeAttribute(v, \"label\") as string) ?? v}`,\n );\n }\n return `Shortest path (${hops} hops):\\n ${segments.join(\" \")}`;\n}\n\n// ---------------------------------------------------------------------------\n// Server\n// ---------------------------------------------------------------------------\n\nexport async function serve(\n graphPath: string = \"graphify-out/graph.json\",\n transport?: Transport,\n): Promise<void> {\n let Server: typeof import(\"@modelcontextprotocol/sdk/server/index.js\").Server;\n let StdioServerTransport: typeof import(\"@modelcontextprotocol/sdk/server/stdio.js\").StdioServerTransport;\n let ListToolsRequestSchema: typeof import(\"@modelcontextprotocol/sdk/types.js\").ListToolsRequestSchema;\n let CallToolRequestSchema: typeof import(\"@modelcontextprotocol/sdk/types.js\").CallToolRequestSchema;\n\n try {\n const serverMod = await import(\"@modelcontextprotocol/sdk/server/index.js\");\n const stdioMod = await import(\"@modelcontextprotocol/sdk/server/stdio.js\");\n const typesMod = await import(\"@modelcontextprotocol/sdk/types.js\");\n Server = serverMod.Server;\n StdioServerTransport = stdioMod.StdioServerTransport;\n ListToolsRequestSchema = typesMod.ListToolsRequestSchema;\n CallToolRequestSchema = typesMod.CallToolRequestSchema;\n } catch {\n throw new Error(\n \"@modelcontextprotocol/sdk not installed. Run: npm install @modelcontextprotocol/sdk\",\n );\n }\n\n const G = loadGraph(graphPath);\n const communities = communitiesFromGraph(G);\n\n const server = new Server(\n { name: \"graphify\", version: \"0.3.17\" },\n { capabilities: { tools: {} } },\n );\n\n server.setRequestHandler(ListToolsRequestSchema, async () => ({\n tools: [\n {\n name: \"query_graph\",\n description:\n \"Search the knowledge graph using BFS or DFS. Returns relevant nodes and edges as text context.\",\n inputSchema: {\n type: \"object\" as const,\n properties: {\n question: {\n type: \"string\",\n description: \"Natural language question or keyword search\",\n },\n mode: {\n type: \"string\",\n enum: [\"bfs\", \"dfs\"],\n default: \"bfs\",\n description: \"bfs=broad context, dfs=trace a specific path\",\n },\n depth: {\n type: \"integer\",\n default: 3,\n description: \"Traversal depth (1-6)\",\n },\n token_budget: {\n type: \"integer\",\n default: 2000,\n description: \"Max output tokens\",\n },\n },\n required: [\"question\"],\n },\n },\n {\n name: \"get_node\",\n description: \"Get full details for a specific node by label or ID.\",\n inputSchema: {\n type: \"object\" as const,\n properties: {\n label: {\n type: \"string\",\n description: \"Node label or ID to look up\",\n },\n },\n required: [\"label\"],\n },\n },\n {\n name: \"get_neighbors\",\n description:\n \"Get all direct neighbors of a node with edge details.\",\n inputSchema: {\n type: \"object\" as const,\n properties: {\n label: { type: \"string\" },\n relation_filter: {\n type: \"string\",\n description: \"Optional: filter by relation type\",\n },\n },\n required: [\"label\"],\n },\n },\n {\n name: \"get_community\",\n description: \"Get all nodes in a community by community ID.\",\n inputSchema: {\n type: \"object\" as const,\n properties: {\n community_id: {\n type: \"integer\",\n description: \"Community ID (0-indexed by size)\",\n },\n },\n required: [\"community_id\"],\n },\n },\n {\n name: \"god_nodes\",\n description:\n \"Return the most connected nodes - the core abstractions of the knowledge graph.\",\n inputSchema: {\n type: \"object\" as const,\n properties: {\n top_n: { type: \"integer\", default: 10 },\n },\n },\n },\n {\n name: \"graph_stats\",\n description:\n \"Return summary statistics: node count, edge count, communities, confidence breakdown.\",\n inputSchema: { type: \"object\" as const, properties: {} },\n },\n {\n name: \"shortest_path\",\n description:\n \"Find the shortest path between two concepts in the knowledge graph.\",\n inputSchema: {\n type: \"object\" as const,\n properties: {\n source: {\n type: \"string\",\n description: \"Source concept label or keyword\",\n },\n target: {\n type: \"string\",\n description: \"Target concept label or keyword\",\n },\n max_hops: {\n type: \"integer\",\n default: 8,\n description: \"Maximum hops to consider\",\n },\n },\n required: [\"source\", \"target\"],\n },\n },\n ],\n }));\n\n const handlers: Record<\n string,\n (args: Record<string, unknown>) => string\n > = {\n query_graph: (a) => toolQueryGraph(G, a),\n get_node: (a) => toolGetNode(G, a),\n get_neighbors: (a) => toolGetNeighbors(G, a),\n get_community: (a) => toolGetCommunity(communities, G, a),\n god_nodes: (a) => toolGodNodes(G, a),\n graph_stats: () => toolGraphStats(G, communities),\n shortest_path: (a) => toolShortestPath(G, a),\n };\n\n server.setRequestHandler(CallToolRequestSchema, async (request) => {\n const { name, arguments: args } = request.params;\n const handler = handlers[name];\n if (!handler) {\n return { content: [{ type: \"text\" as const, text: `Unknown tool: ${name}` }] };\n }\n try {\n const text = handler((args ?? {}) as Record<string, unknown>);\n return { content: [{ type: \"text\" as const, text }] };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n return { content: [{ type: \"text\" as const, text: `Error executing ${name}: ${message}` }] };\n }\n });\n\n const serverTransport = transport ?? new StdioServerTransport();\n let keepAlive: NodeJS.Timeout | undefined;\n if (!transport) {\n keepAlive = setInterval(() => undefined, 60_000);\n process.stdin?.resume();\n }\n\n const closed = new Promise<void>((resolve) => {\n const previousOnClose = server.onclose;\n server.onclose = () => {\n if (keepAlive) {\n clearInterval(keepAlive);\n }\n previousOnClose?.();\n resolve();\n };\n });\n\n await server.connect(serverTransport);\n if (transport) {\n await closed;\n }\n}\n\n// ---------------------------------------------------------------------------\n// CLI entry point\n// ---------------------------------------------------------------------------\n\nconst isDirectExecution = typeof process !== \"undefined\" &&\n typeof process.argv[1] === \"string\" &&\n /^serve\\.(?:js|mjs|cjs|ts)$/.test(basename(process.argv[1]));\n\nif (isDirectExecution) {\n const graphPath = process.argv[2] ?? \"graphify-out/graph.json\";\n serve(graphPath).catch((err) => {\n console.error(err);\n process.exit(1);\n });\n}\n","/**\n * File watcher - monitor a folder and auto-trigger graph rebuild when files change.\n *\n * Uses chokidar instead of Python watchdog.\n * Code-only changes rebuild graph automatically (no LLM needed).\n * Doc/paper/image changes write a flag and notify the user.\n */\nimport { existsSync, mkdirSync, writeFileSync, unlinkSync } from \"node:fs\";\nimport { resolve as pathResolve, extname, basename } from \"node:path\";\nimport {\n CODE_EXTENSIONS,\n DOC_EXTENSIONS,\n PAPER_EXTENSIONS,\n IMAGE_EXTENSIONS,\n} from \"./detect.js\";\n\nconst WATCHED_EXTENSIONS = new Set([\n ...CODE_EXTENSIONS,\n ...DOC_EXTENSIONS,\n ...PAPER_EXTENSIONS,\n ...IMAGE_EXTENSIONS,\n]);\n\n// ---------------------------------------------------------------------------\n// Rebuild pipeline (code-only, no LLM)\n// ---------------------------------------------------------------------------\n\nexport async function rebuildCode(\n watchPath: string,\n followSymlinks: boolean = false,\n): Promise<boolean> {\n try {\n // Dynamic imports - these modules are in the same package\n const { collectFiles, extractWithDiagnostics } = await import(\"./extract.js\");\n const { buildFromJson } = await import(\"./build.js\");\n const { cluster, scoreAll } = await import(\"./cluster.js\");\n const { godNodes, surprisingConnections, suggestQuestions } = await import(\"./analyze.js\");\n const { generate } = await import(\"./report.js\");\n const { toJson } = await import(\"./export.js\");\n\n let codeFiles = await collectFiles(watchPath, { followSymlinks });\n codeFiles = codeFiles.filter(\n (f: string) =>\n !f.includes(\"graphify-out\") &&\n !f.includes(\"__pycache__\") &&\n !f.includes(\"node_modules\"),\n );\n\n if (codeFiles.length === 0) {\n console.log(\"[graphify watch] No code files found - nothing to rebuild.\");\n return false;\n }\n\n const { extraction: result, diagnostics } = await extractWithDiagnostics(codeFiles);\n if (diagnostics.length > 0) {\n console.log(\n `[graphify watch] AST extraction failed for ${diagnostics.length} file(s): ` +\n `${diagnostics.slice(0, 3).map((d) => `${d.filePath}: ${d.error}`).join(\" | \")}`,\n );\n }\n if (result.nodes.length === 0) {\n console.log(\"[graphify watch] Rebuild failed: AST extraction produced no graph nodes.\");\n return false;\n }\n\n const detection = {\n files: {\n code: codeFiles,\n document: [] as string[],\n paper: [] as string[],\n image: [] as string[],\n },\n total_files: codeFiles.length,\n total_words: 0,\n needs_graph: true,\n warning: null,\n skipped_sensitive: [] as string[],\n graphifyignore_patterns: 0,\n };\n\n const G = buildFromJson(result);\n const communities = cluster(G);\n const cohesion = scoreAll(G, communities);\n const gods = godNodes(G);\n const surprises = surprisingConnections(G, communities);\n const labels = new Map<number, string>();\n for (const cid of communities.keys()) {\n labels.set(cid, `Community ${cid}`);\n }\n const questions = suggestQuestions(G, communities, labels);\n\n const outDir = pathResolve(watchPath, \"graphify-out\");\n mkdirSync(outDir, { recursive: true });\n\n const report = generate(\n G,\n communities,\n cohesion,\n labels,\n gods,\n surprises,\n detection,\n { input: 0, output: 0 },\n watchPath,\n questions,\n );\n writeFileSync(pathResolve(outDir, \"GRAPH_REPORT.md\"), report, \"utf-8\");\n toJson(G, communities, pathResolve(outDir, \"graph.json\"), { communityLabels: labels });\n\n // Clear stale needs_update flag if present\n const flagPath = pathResolve(outDir, \"needs_update\");\n if (existsSync(flagPath)) {\n unlinkSync(flagPath);\n }\n\n console.log(\n `[graphify watch] Rebuilt: ${G.order} nodes, ${G.size} edges, ${communities.size} communities`,\n );\n console.log(\n `[graphify watch] graph.json and GRAPH_REPORT.md updated in ${outDir}`,\n );\n return true;\n } catch (err) {\n console.log(\n `[graphify watch] Rebuild failed: ${err instanceof Error ? err.message : err}`,\n );\n return false;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Notification fallback (non-code changes)\n// ---------------------------------------------------------------------------\n\nfunction notifyOnly(watchPath: string): void {\n const outDir = pathResolve(watchPath, \"graphify-out\");\n mkdirSync(outDir, { recursive: true });\n const flagPath = pathResolve(outDir, \"needs_update\");\n writeFileSync(flagPath, \"1\", \"utf-8\");\n console.log(`\\n[graphify watch] New or changed files detected in ${watchPath}`);\n console.log(\n \"[graphify watch] Non-code files changed - semantic re-extraction requires LLM.\",\n );\n console.log(\n \"[graphify watch] Run the graphify skill with `--update` to refresh semantic data (for Codex: `$graphify . --update`).\",\n );\n console.log(`[graphify watch] Flag written to ${flagPath}`);\n}\n\nfunction hasNonCode(changedPaths: string[]): boolean {\n return changedPaths.some((p) => !CODE_EXTENSIONS.has(extname(p).toLowerCase()));\n}\n\n// ---------------------------------------------------------------------------\n// Main watcher\n// ---------------------------------------------------------------------------\n\nexport async function watch(\n watchPath: string,\n debounce: number = 3.0,\n): Promise<void> {\n let chokidar: typeof import(\"chokidar\");\n try {\n chokidar = await import(\"chokidar\");\n } catch {\n throw new Error(\"chokidar not installed. Run: npm install chokidar\");\n }\n\n const resolvedPath = pathResolve(watchPath);\n let lastTrigger = 0;\n let pending = false;\n const changed = new Set<string>();\n\n const watcher = chokidar.watch(resolvedPath, {\n persistent: true,\n ignoreInitial: true,\n followSymlinks: false,\n ignored: [\n /node_modules/,\n /\\.git/,\n /graphify-out/,\n ],\n });\n\n watcher.on(\"all\", (_event: string, filePath: string) => {\n const ext = extname(filePath).toLowerCase();\n if (!WATCHED_EXTENSIONS.has(ext)) return;\n\n // Skip hidden directories\n const parts = filePath.split(\"/\");\n if (parts.some((part) => part.startsWith(\".\") && part !== \".\")) return;\n\n lastTrigger = Date.now();\n pending = true;\n changed.add(filePath);\n });\n\n console.log(\n `[graphify watch] Watching ${resolvedPath} - press Ctrl+C to stop`,\n );\n console.log(\n \"[graphify watch] Code changes rebuild graph automatically. Doc/image changes require a graphify skill `--update` run.\",\n );\n console.log(`[graphify watch] Debounce: ${debounce}s`);\n\n const debounceMs = debounce * 1000;\n\n const poll = setInterval(async () => {\n if (pending && Date.now() - lastTrigger >= debounceMs) {\n pending = false;\n const batch = [...changed];\n changed.clear();\n console.log(`\\n[graphify watch] ${batch.length} file(s) changed`);\n if (hasNonCode(batch)) {\n notifyOnly(watchPath);\n } else {\n await rebuildCode(watchPath);\n }\n }\n }, 500);\n\n // Graceful shutdown\n const cleanup = () => {\n console.log(\"\\n[graphify watch] Stopped.\");\n clearInterval(poll);\n watcher.close();\n process.exit(0);\n };\n\n process.on(\"SIGINT\", cleanup);\n process.on(\"SIGTERM\", cleanup);\n}\n\n// ---------------------------------------------------------------------------\n// CLI entry point\n// ---------------------------------------------------------------------------\n\nconst isDirectExecution = typeof process !== \"undefined\" &&\n typeof process.argv[1] === \"string\" &&\n /^watch\\.(?:js|mjs|cjs|ts)$/.test(basename(process.argv[1]));\n\nif (isDirectExecution) {\n const watchPath = process.argv[2] ?? \".\";\n const debounce = process.argv[3] ? parseFloat(process.argv[3]) : 3.0;\n watch(watchPath, debounce).catch((err) => {\n console.error(err);\n process.exit(1);\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IACY;AADZ;AAAA;AACO,IAAK,WAAL,kBAAKA,cAAL;AACL,MAAAA,UAAA,UAAO;AACP,MAAAA,UAAA,cAAW;AACX,MAAAA,UAAA,WAAQ;AACR,MAAAA,UAAA,WAAQ;AACR,MAAAA,UAAA,WAAQ;AALE,aAAAA;AAAA,OAAA;AAAA;AAAA;;;ACYL,SAAS,mBAAmB,MAAyB;AAC1D,MAAI,OAAO,SAAS,YAAY,SAAS,QAAQ,MAAM,QAAQ,IAAI,GAAG;AACpE,WAAO,CAAC,kCAAkC;AAAA,EAC5C;AAEA,QAAM,IAAI;AACV,QAAM,SAAmB,CAAC;AAG1B,MAAI,EAAE,WAAW,IAAI;AACnB,WAAO,KAAK,8BAA8B;AAAA,EAC5C,WAAW,CAAC,MAAM,QAAQ,EAAE,KAAK,GAAG;AAClC,WAAO,KAAK,wBAAwB;AAAA,EACtC,OAAO;AACL,aAAS,IAAI,GAAG,IAAI,EAAE,MAAM,QAAQ,KAAK;AACvC,YAAM,OAAO,EAAE,MAAM,CAAC;AACtB,UAAI,OAAO,SAAS,YAAY,SAAS,QAAQ,MAAM,QAAQ,IAAI,GAAG;AACpE,eAAO,KAAK,QAAQ,CAAC,oBAAoB;AACzC;AAAA,MACF;AACA,iBAAW,SAAS,sBAAsB;AACxC,YAAI,EAAE,SAAS,OAAO;AACpB,iBAAO;AAAA,YACL,QAAQ,CAAC,QAAQ,KAAK,UAAU,KAAK,MAAM,GAAG,CAAC,6BAA6B,KAAK;AAAA,UACnF;AAAA,QACF;AAAA,MACF;AACA,UAAI,eAAe,QAAQ,CAAC,iBAAiB,IAAI,KAAK,SAAmB,GAAG;AAC1E,eAAO;AAA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B,cAAQ,MAAM;AACd,cAAQ,IAAI;AAAA,mBAAsB,MAAM,MAAM,kBAAkB;AAChE,UAAI,WAAW,KAAK,GAAG;AACrB,mBAAW,SAAS;AAAA,MACtB,OAAO;AACL,cAAM,YAAY,SAAS;AAAA,MAC7B;AAAA,IACF;AAAA,EACF,GAAG,GAAG;AAGN,QAAM,UAAU,MAAM;AACpB,YAAQ,IAAI,6BAA6B;AACzC,kBAAc,IAAI;AAClB,YAAQ,MAAM;AACd,YAAQ,KAAK,CAAC;AAAA,EAChB;AAEA,UAAQ,GAAG,UAAU,OAAO;AAC5B,UAAQ,GAAG,WAAW,OAAO;AAC/B;AAMA,IAAMC,qBAAoB,OAAO,YAAY,eAC3C,OAAO,QAAQ,KAAK,CAAC,MAAM,YAC3B,6BAA6B,SAAK,4BAAS,QAAQ,KAAK,CAAC,CAAC,CAAC;AAE7D,IAAIA,oBAAmB;AACrB,QAAM,YAAY,QAAQ,KAAK,CAAC,KAAK;AACrC,QAAM,WAAW,QAAQ,KAAK,CAAC,IAAI,WAAW,QAAQ,KAAK,CAAC,CAAC,IAAI;AACjE,QAAM,WAAW,QAAQ,EAAE,MAAM,CAAC,QAAQ;AACxC,YAAQ,MAAM,GAAG;AACjB,YAAQ,KAAK,CAAC;AAAA,EAChB,CAAC;AACH;","names":["FileType","Graph","louvain","result","betweennessCentrality","pathResolve","import_node_path","import_node_fs","nodeCommunityMap","communityName","import_node_fs","import_node_crypto","import_node_fs","import_node_path","Parser","module","walkDir","import_node_fs","import_node_path","import_node_fs","import_node_path","communityName","import_node_fs","import_node_fs","import_node_path","import_node_crypto","import_node_fs","import_node_path","godNodes","safeFilename","pathResolve","import_node_fs","import_node_path","loadGraph","nid","d","resolve","isDirectExecution","import_node_fs","import_node_path","collectFiles","extractWithDiagnostics","buildFromJson","cluster","scoreAll","godNodes","surprisingConnections","suggestQuestions","generate","toJson","pathResolve","isDirectExecution"]}