Graphs that teach > graphs that impress. Turn any code into an interactive knowledge graph you can explore, search, and ask questions about. Works with Claude Code, Codex, Cursor, Copilot, Gemini CLI, and more.
TypeScript antigravity-skillsbusiness-knowledgeclaude-codeclaude-skillscodebase-analysiscodexcodex-skillsdeveloper-tools-ai-agentgemini-cli-skillskarpathy-llm-wikiknowledge-baseknowledge-graphmemoryopencode-skillspi-agentunderstandcodevibe-coding
import Graph from "graphology";
import louvain from "graphology-communities-louvain";
import type { GraphEdge } from "@understand-anything/core/types";
/**
* Run Louvain community detection over the provided node set and the
* subset of edges whose endpoints are both in the set. Returns a map of
* nodeId → communityId.
*
* graphology-communities-louvain v2 already gives each disconnected node
* its own community id, but the contract isn't documented. The
* post-Louvain reassignment loop below is defensive: if a future version
* starts returning -1 (or omits a node, which the `?? -1` catches) for
* unmatched nodes, we'll still hand back unique ids rather than letting
* them collapse into a single cluster.
*/
export function detectCommunities(
nodeIds: string[],
edges: GraphEdge[],
): Map<string, number> {
const ids = new Set(nodeIds);
const g = new Graph({ type: "undirected", multi: false });
for (const id of nodeIds) g.addNode(id);
for (const e of edges) {
if (!ids.has(e.source) || !ids.has(e.target)) continue;
if (e.source === e.target) continue;
if (g.hasEdge(e.source, e.target)) continue;
g.addEdge(e.source, e.target);
}
// graphology-communities-louvain returns Record<nodeId, communityId>
const result = louvain(g) as Record<string, number>;
const map = new Map<string, number>();
for (const id of nodeIds) {
map.set(id, result[id] ?? -1);
}
// Defensive: reassign any -1 sentinels to unique ids past the max.
// See the JSDoc on detectCommunities for why this is kept despite the
// current library already producing unique ids for disconnected nodes.
// Reduce instead of `Math.max(...spread)`: spreading every community id as
// call arguments throws `RangeError: Maximum call stack size exceeded` once
// the node count crosses the engine's argument limit — reachable on the
// ~3k+ node graphs this dashboard targets. Same result, no spread, no
// throwaway filtered array.
let maxCommunity = -1;
for (const v of map.values()) {
if (v >= 0 && v > maxCommunity) maxCommunity = v;
}
let next = maxCommunity + 1;
for (const [id, c] of map) {
if (c === -1) {
map.set(id, next++);
}
}
return map;
}