lakonai 0.17.1 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,275 @@
1
+ 'use strict';
2
+
3
+ const { communityLabels } = require('./leiden');
4
+
5
+ // Palette for community colors (cycles if more than palette length)
6
+ const PALETTE = [
7
+ '#4e79a7', '#f28e2b', '#e15759', '#76b7b2', '#59a14f',
8
+ '#edc948', '#b07aa1', '#ff9da7', '#9c755f', '#bab0ac',
9
+ ];
10
+
11
+ function buildHtml(graph) {
12
+ const { nodes, edges } = graph;
13
+ const communities = {};
14
+ for (const n of nodes) communities[n.id] = n.community ?? 0;
15
+ const commLabels = communityLabels(nodes, edges, communities);
16
+
17
+ const numComm = Math.max(...Object.values(communities), 0) + 1;
18
+ const colorMap = {};
19
+ for (let i = 0; i < numComm; i++) colorMap[i] = PALETTE[i % PALETTE.length];
20
+
21
+ // Encode data as JSON embedded in script
22
+ const graphData = JSON.stringify({ nodes, edges, commLabels, colorMap });
23
+
24
+ return `<!DOCTYPE html>
25
+ <html lang="en">
26
+ <head>
27
+ <meta charset="utf-8">
28
+ <title>lakonai graph</title>
29
+ <style>
30
+ * { box-sizing: border-box; margin: 0; padding: 0; }
31
+ body { background: #1a1a2e; color: #eee; font-family: monospace; overflow: hidden; }
32
+ #canvas { display: block; }
33
+ #tooltip {
34
+ position: fixed; background: rgba(0,0,0,.85); border: 1px solid #444;
35
+ padding: 10px 14px; border-radius: 6px; font-size: 12px; pointer-events: none;
36
+ max-width: 320px; display: none; line-height: 1.5; z-index: 10;
37
+ }
38
+ #legend {
39
+ position: fixed; top: 12px; left: 12px; background: rgba(0,0,0,.7);
40
+ padding: 10px; border-radius: 6px; font-size: 11px; line-height: 1.8;
41
+ }
42
+ #info {
43
+ position: fixed; bottom: 12px; left: 12px; font-size: 11px; opacity: .5;
44
+ }
45
+ #search {
46
+ position: fixed; top: 12px; right: 12px; background: rgba(0,0,0,.7);
47
+ padding: 6px; border-radius: 6px;
48
+ }
49
+ #search input {
50
+ background: #333; border: 1px solid #555; color: #eee;
51
+ padding: 4px 8px; border-radius: 4px; font-size: 12px; width: 180px;
52
+ }
53
+ </style>
54
+ </head>
55
+ <body>
56
+ <canvas id="canvas"></canvas>
57
+ <div id="tooltip"></div>
58
+ <div id="legend"></div>
59
+ <div id="info">scroll to zoom · drag to pan · hover nodes</div>
60
+ <div id="search"><input id="searchInput" placeholder="search nodes…" /></div>
61
+ <script>
62
+ (function() {
63
+ const RAW = ${graphData};
64
+ const { nodes: rawNodes, edges: rawEdges, commLabels, colorMap } = RAW;
65
+
66
+ const canvas = document.getElementById('canvas');
67
+ const ctx = canvas.getContext('2d');
68
+ const tooltip = document.getElementById('tooltip');
69
+ const legend = document.getElementById('legend');
70
+
71
+ // Layout
72
+ let W = canvas.width = window.innerWidth;
73
+ let H = canvas.height = window.innerHeight;
74
+ window.addEventListener('resize', () => {
75
+ W = canvas.width = window.innerWidth;
76
+ H = canvas.height = window.innerHeight;
77
+ restart();
78
+ });
79
+
80
+ // Filter to show only file nodes + their symbols (cap at 400 for perf)
81
+ const MAX_NODES = 400;
82
+ const nodes = rawNodes.slice(0, MAX_NODES).map((n, i) => ({
83
+ ...n,
84
+ x: W/2 + (Math.random() - 0.5) * W * 0.6,
85
+ y: H/2 + (Math.random() - 0.5) * H * 0.6,
86
+ vx: 0, vy: 0,
87
+ }));
88
+ const nodeIdx = new Map(nodes.map((n, i) => [n.id, i]));
89
+
90
+ const edges = rawEdges.filter(e => nodeIdx.has(e.from) && nodeIdx.has(e.to));
91
+
92
+ // Radius by kind
93
+ function r(kind) {
94
+ if (kind === 'file') return 9;
95
+ if (kind === 'class' || kind === 'struct') return 7;
96
+ return 5;
97
+ }
98
+
99
+ // Force simulation (simple spring + repulsion)
100
+ const REPULSION = 800;
101
+ const SPRING_LEN = 80;
102
+ const SPRING_K = 0.05;
103
+ const DAMPING = 0.85;
104
+ const DT = 0.6;
105
+
106
+ function tick() {
107
+ const n = nodes.length;
108
+ // Repulsion (O(n^2) capped by node count)
109
+ for (let i = 0; i < n; i++) {
110
+ for (let j = i + 1; j < n; j++) {
111
+ const dx = nodes[j].x - nodes[i].x;
112
+ const dy = nodes[j].y - nodes[i].y;
113
+ const dist2 = dx*dx + dy*dy + 1;
114
+ const force = REPULSION / dist2;
115
+ const fx = force * dx / Math.sqrt(dist2);
116
+ const fy = force * dy / Math.sqrt(dist2);
117
+ nodes[i].vx -= fx; nodes[i].vy -= fy;
118
+ nodes[j].vx += fx; nodes[j].vy += fy;
119
+ }
120
+ }
121
+ // Spring
122
+ for (const e of edges) {
123
+ const a = nodes[nodeIdx.get(e.from)];
124
+ const b = nodes[nodeIdx.get(e.to)];
125
+ const dx = b.x - a.x, dy = b.y - a.y;
126
+ const dist = Math.sqrt(dx*dx + dy*dy) || 1;
127
+ const f = SPRING_K * (dist - SPRING_LEN);
128
+ const fx = f * dx/dist, fy = f * dy/dist;
129
+ a.vx += fx; a.vy += fy;
130
+ b.vx -= fx; b.vy -= fy;
131
+ }
132
+ // Center gravity
133
+ for (const n of nodes) {
134
+ n.vx += (W/2 - n.x) * 0.002;
135
+ n.vy += (H/2 - n.y) * 0.002;
136
+ n.vx *= DAMPING; n.vy *= DAMPING;
137
+ n.x += n.vx * DT; n.y += n.vy * DT;
138
+ }
139
+ }
140
+
141
+ // Camera
142
+ let camX = 0, camY = 0, camZ = 1;
143
+ function toScreen(wx, wy) { return [(wx + camX) * camZ + W/2, (wy + camY) * camZ + H/2]; }
144
+ function toWorld(sx, sy) { return [(sx - W/2) / camZ - camX, (sy - H/2) / camZ - camY]; }
145
+
146
+ // Draw
147
+ let highlighted = null;
148
+ let searchHit = null;
149
+
150
+ function draw() {
151
+ ctx.clearRect(0, 0, W, H);
152
+ ctx.save();
153
+
154
+ // Edges
155
+ ctx.lineWidth = 0.8;
156
+ for (const e of edges) {
157
+ const a = nodes[nodeIdx.get(e.from)];
158
+ const b = nodes[nodeIdx.get(e.to)];
159
+ const [ax, ay] = toScreen(a.x, a.y);
160
+ const [bx, by] = toScreen(b.x, b.y);
161
+ const isHighlit = highlighted && (a.id === highlighted || b.id === highlighted);
162
+ ctx.strokeStyle = isHighlit ? 'rgba(255,255,180,0.7)' : 'rgba(120,120,160,0.3)';
163
+ ctx.lineWidth = isHighlit ? 1.5 : 0.8;
164
+ ctx.beginPath(); ctx.moveTo(ax, ay); ctx.lineTo(bx, by); ctx.stroke();
165
+ }
166
+
167
+ // Nodes
168
+ for (const n of nodes) {
169
+ const [sx, sy] = toScreen(n.x, n.y);
170
+ const radius = r(n.kind) * camZ;
171
+ const col = colorMap[n.community ?? 0] || '#888';
172
+ const isHit = n.id === searchHit;
173
+ ctx.beginPath();
174
+ ctx.arc(sx, sy, Math.max(radius, 2), 0, Math.PI*2);
175
+ ctx.fillStyle = isHit ? '#fff' : col;
176
+ ctx.globalAlpha = highlighted && n.id !== highlighted ? 0.35 : 1;
177
+ ctx.fill();
178
+ if (n.kind === 'file' || n.id === highlighted || isHit) {
179
+ ctx.fillStyle = '#eee';
180
+ ctx.font = \`\${Math.max(9, 11*camZ)}px monospace\`;
181
+ ctx.fillText(n.label, sx + radius + 2, sy + 4);
182
+ }
183
+ ctx.globalAlpha = 1;
184
+ }
185
+ ctx.restore();
186
+ }
187
+
188
+ let simRunning = true;
189
+ let frame = 0;
190
+
191
+ function loop() {
192
+ if (simRunning) { tick(); frame++; if (frame > 300) simRunning = false; }
193
+ draw();
194
+ requestAnimationFrame(loop);
195
+ }
196
+
197
+ function restart() {
198
+ simRunning = true; frame = 0;
199
+ for (const n of nodes) { n.vx = 0; n.vy = 0; }
200
+ }
201
+
202
+ loop();
203
+
204
+ // Build legend
205
+ const seen = new Set();
206
+ let legendHtml = '<b>communities</b><br>';
207
+ for (const n of nodes) {
208
+ const c = n.community ?? 0;
209
+ if (!seen.has(c)) {
210
+ seen.add(c);
211
+ const col = colorMap[c] || '#888';
212
+ legendHtml += \`<span style="color:\${col}">■</span> \${commLabels[c] || c}<br>\`;
213
+ }
214
+ }
215
+ legend.innerHTML = legendHtml;
216
+
217
+ // Hover
218
+ canvas.addEventListener('mousemove', (ev) => {
219
+ const [wx, wy] = toWorld(ev.clientX, ev.clientY);
220
+ let found = null;
221
+ for (const n of nodes) {
222
+ const dx = n.x - wx, dy = n.y - wy;
223
+ if (Math.sqrt(dx*dx+dy*dy) < r(n.kind) + 2) { found = n; break; }
224
+ }
225
+ highlighted = found ? found.id : null;
226
+ if (found) {
227
+ const outgoing = rawEdges.filter(e => e.from === found.id).slice(0, 6);
228
+ const incoming = rawEdges.filter(e => e.to === found.id).slice(0, 6);
229
+ tooltip.style.display = 'block';
230
+ tooltip.style.left = (ev.clientX + 14) + 'px';
231
+ tooltip.style.top = (ev.clientY - 10) + 'px';
232
+ tooltip.innerHTML =
233
+ \`<b>\${found.label}</b> [\${found.kind}]<br>\${found.file}:\${found.line}\` +
234
+ (outgoing.length ? '<br><br><b>→</b> ' + outgoing.map(e=>e.to.split('#').pop()).join(', ') : '') +
235
+ (incoming.length ? '<br><b>←</b> ' + incoming.map(e=>e.from.split('#').pop()).join(', ') : '');
236
+ } else {
237
+ tooltip.style.display = 'none';
238
+ }
239
+ });
240
+
241
+ // Pan
242
+ let drag = false, dragStart = [0,0], camStart = [0,0];
243
+ canvas.addEventListener('mousedown', ev => { drag = true; dragStart = [ev.clientX, ev.clientY]; camStart = [camX, camY]; });
244
+ canvas.addEventListener('mouseup', () => drag = false);
245
+ canvas.addEventListener('mousemove', ev => {
246
+ if (!drag) return;
247
+ camX = camStart[0] + (ev.clientX - dragStart[0]) / camZ;
248
+ camY = camStart[1] + (ev.clientY - dragStart[1]) / camZ;
249
+ });
250
+
251
+ // Zoom
252
+ canvas.addEventListener('wheel', ev => {
253
+ ev.preventDefault();
254
+ const factor = ev.deltaY > 0 ? 0.9 : 1.1;
255
+ camZ = Math.max(0.1, Math.min(5, camZ * factor));
256
+ }, { passive: false });
257
+
258
+ // Search
259
+ document.getElementById('searchInput').addEventListener('input', ev => {
260
+ const q = ev.target.value.toLowerCase();
261
+ if (!q) { searchHit = null; return; }
262
+ const hit = nodes.find(n => n.label.toLowerCase().includes(q) || n.file.toLowerCase().includes(q));
263
+ if (hit) {
264
+ searchHit = hit.id;
265
+ camX = -hit.x; camY = -hit.y; camZ = 1.5;
266
+ }
267
+ });
268
+
269
+ })();
270
+ </script>
271
+ </body>
272
+ </html>`;
273
+ }
274
+
275
+ module.exports = { buildHtml };
@@ -0,0 +1,189 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const { parseDir } = require('./parser');
6
+ const { buildGraph, writeGraph, readGraph, graphDir, GRAPH_FILE } = require('./store');
7
+ const { detectCommunities } = require('./leiden');
8
+ const { buildReport } = require('./report');
9
+ const { buildHtml } = require('./html');
10
+ const { explain, shortestPath, nlQuery, nlQuerySemantic, nlQueryHybrid, formatExplain, formatPath, formatNlQuery } = require('./query');
11
+ const { hasXenova, generateEmbeddings, embedQuery } = require('./embed');
12
+ const { watchDir } = require('./watch');
13
+
14
+ const REPORT_FILE = 'GRAPH_REPORT.md';
15
+ const HTML_FILE = 'graph.html';
16
+ const EMBEDDINGS_FILE = 'embeddings.json';
17
+
18
+ // Ensure lakonai-graph/ is in .gitignore — it's generated output, not source.
19
+ function ensureGitignore(rootDir) {
20
+ const gitignorePath = path.join(rootDir, '.gitignore');
21
+ const entry = 'lakonai-graph/';
22
+ try {
23
+ let content = '';
24
+ try { content = fs.readFileSync(gitignorePath, 'utf8'); } catch { /* new file */ }
25
+ if (!content.split('\n').some((l) => l.trim() === entry)) {
26
+ fs.writeFileSync(gitignorePath, content + (content.endsWith('\n') || !content ? '' : '\n') + entry + '\n');
27
+ }
28
+ } catch { /* best-effort */ }
29
+ }
30
+
31
+ // Build graph from rootDir, write all output files, return graph.
32
+ // Also generates embeddings if @xenova/transformers is installed.
33
+ async function build(rootDir) {
34
+ const absRoot = path.resolve(rootDir);
35
+ ensureGitignore(absRoot);
36
+ const parsed = parseDir(absRoot);
37
+ const communities = detectCommunities(parsed.nodes, parsed.edges);
38
+ const graph = buildGraph(parsed, communities);
39
+
40
+ writeGraph(absRoot, graph);
41
+
42
+ const dir = graphDir(absRoot);
43
+ fs.writeFileSync(path.join(dir, REPORT_FILE), buildReport(graph));
44
+ fs.writeFileSync(path.join(dir, HTML_FILE), buildHtml(graph));
45
+
46
+ if (hasXenova()) {
47
+ try {
48
+ const embeddings = await generateEmbeddings(graph.nodes);
49
+ fs.writeFileSync(path.join(dir, EMBEDDINGS_FILE), JSON.stringify(embeddings));
50
+ graph._embeddingsGenerated = true;
51
+ } catch {
52
+ // best-effort — graph still works without embeddings
53
+ }
54
+ }
55
+
56
+ return graph;
57
+ }
58
+
59
+ // Synchronous build for callers that can't await (watch, tests).
60
+ function buildSync(rootDir) {
61
+ const absRoot = path.resolve(rootDir);
62
+ ensureGitignore(absRoot);
63
+ const parsed = parseDir(absRoot);
64
+ const communities = detectCommunities(parsed.nodes, parsed.edges);
65
+ const graph = buildGraph(parsed, communities);
66
+
67
+ writeGraph(absRoot, graph);
68
+
69
+ const dir = graphDir(absRoot);
70
+ fs.writeFileSync(path.join(dir, REPORT_FILE), buildReport(graph));
71
+ fs.writeFileSync(path.join(dir, HTML_FILE), buildHtml(graph));
72
+
73
+ return graph;
74
+ }
75
+
76
+ // CLI command handler
77
+ function runGraph(args) {
78
+ const [sub, ...rest] = args;
79
+
80
+ if (!sub || sub === 'build') {
81
+ const rootDir = rest[0] || '.';
82
+ process.stdout.write(`lakonai graph: building ${path.resolve(rootDir)}\n`);
83
+ const t0 = Date.now();
84
+ const graph = buildSync(rootDir);
85
+ const elapsed = ((Date.now() - t0) / 1000).toFixed(1);
86
+ process.stdout.write(
87
+ `\ndone in ${elapsed}s\n` +
88
+ ` nodes: ${graph.meta.nodeCount} edges: ${graph.meta.edgeCount} files: ${graph.meta.fileCount}\n` +
89
+ ` output: ${path.join(path.resolve(rootDir), 'lakonai-graph/')}\n` +
90
+ ` ${GRAPH_FILE} — queryable graph\n` +
91
+ ` ${REPORT_FILE} — highlights\n` +
92
+ ` ${HTML_FILE} — interactive viz\n`
93
+ );
94
+ // Fire-and-forget embedding generation (non-blocking)
95
+ if (hasXenova()) {
96
+ process.stdout.write(' embeddings: generating (first run downloads ~23MB model)…\n');
97
+ const absRoot = path.resolve(rootDir);
98
+ const dir = graphDir(absRoot);
99
+ generateEmbeddings(graph.nodes).then((embeddings) => {
100
+ fs.writeFileSync(path.join(dir, EMBEDDINGS_FILE), JSON.stringify(embeddings));
101
+ process.stdout.write(` embeddings: ${graph.meta.nodeCount} vectors written (semantic query enabled)\n ${EMBEDDINGS_FILE} — semantic embeddings\n`);
102
+ }).catch(() => { /* best-effort */ });
103
+ }
104
+ return;
105
+ }
106
+
107
+ if (sub === 'explain') {
108
+ const [nodeId] = rest;
109
+ if (!nodeId) { process.stderr.write('usage: lakonai graph explain <nodeId>\n'); process.exitCode = 1; return; }
110
+ const graph = readGraph('.');
111
+ if (!graph) { process.stderr.write('no graph.json found — run: lakonai graph build\n'); process.exitCode = 1; return; }
112
+ process.stdout.write(formatExplain(explain(graph, nodeId)) + '\n');
113
+ return;
114
+ }
115
+
116
+ if (sub === 'path') {
117
+ const [fromId, toId] = rest;
118
+ if (!fromId || !toId) { process.stderr.write('usage: lakonai graph path <from> <to>\n'); process.exitCode = 1; return; }
119
+ const graph = readGraph('.');
120
+ if (!graph) { process.stderr.write('no graph.json found — run: lakonai graph build\n'); process.exitCode = 1; return; }
121
+ process.stdout.write(formatPath(shortestPath(graph, fromId, toId), graph) + '\n');
122
+ return;
123
+ }
124
+
125
+ if (sub === 'query') {
126
+ const question = rest.join(' ');
127
+ if (!question) { process.stderr.write('usage: lakonai graph query "<question>"\n'); process.exitCode = 1; return; }
128
+ const graph = readGraph('.');
129
+ if (!graph) { process.stderr.write('no graph.json found — run: lakonai graph build\n'); process.exitCode = 1; return; }
130
+
131
+ const embPath = path.join('.', 'lakonai-graph', EMBEDDINGS_FILE);
132
+ const hasEmb = fs.existsSync(embPath);
133
+
134
+ if (hasEmb && hasXenova()) {
135
+ // Async hybrid query (BM25 + semantic RRF)
136
+ const embeddingsData = JSON.parse(fs.readFileSync(embPath, 'utf8'));
137
+ embedQuery(question).then((queryVec) => {
138
+ const result = nlQueryHybrid(graph, embeddingsData, question, queryVec);
139
+ process.stdout.write(`[hybrid]\n${formatNlQuery(result, graph)}\n`);
140
+ }).catch(() => {
141
+ process.stdout.write(`[bm25]\n${formatNlQuery(nlQuery(graph, question), graph)}\n`);
142
+ });
143
+ } else {
144
+ process.stdout.write(`[bm25]\n${formatNlQuery(nlQuery(graph, question), graph)}\n`);
145
+ }
146
+ return;
147
+ }
148
+
149
+ if (sub === 'html') {
150
+ const rootDir = rest[0] || '.';
151
+ const htmlPath = path.join(path.resolve(rootDir), 'lakonai-graph', HTML_FILE);
152
+ if (!fs.existsSync(htmlPath)) {
153
+ process.stderr.write(`no graph.html found — run: lakonai graph build ${rootDir}\n`);
154
+ process.exitCode = 1;
155
+ return;
156
+ }
157
+ // Open in default browser
158
+ /* istanbul ignore next */
159
+ const open = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'start' : 'xdg-open';
160
+ require('child_process').spawn(open, [htmlPath], { detached: true, stdio: 'ignore' }).unref();
161
+ process.stdout.write(`opened: ${htmlPath}\n`);
162
+ return;
163
+ }
164
+
165
+ /* istanbul ignore next -- long-running interactive; SIGINT tested manually */
166
+ if (sub === 'watch') {
167
+ const rootDir = rest[0] || '.';
168
+ const absRoot = path.resolve(rootDir);
169
+ process.stdout.write(`lakonai graph watch: ${absRoot}\n`);
170
+ buildSync(rootDir);
171
+ process.stdout.write('watching for changes (ctrl+c to stop)…\n');
172
+ const watcher = watchDir(absRoot, (changed) => {
173
+ process.stdout.write(`changed: ${changed.map((f) => path.relative(absRoot, f)).join(', ')} — rebuilding…\n`);
174
+ try {
175
+ buildSync(rootDir);
176
+ process.stdout.write('rebuilt\n');
177
+ } catch (err) {
178
+ process.stderr.write(`rebuild error: ${err.message}\n`);
179
+ }
180
+ });
181
+ process.on('SIGINT', () => { watcher.close(); process.exit(0); });
182
+ return;
183
+ }
184
+
185
+ process.stderr.write(`lakonai graph: unknown subcommand "${sub}"\nuse: build | explain | path | query | html | watch\n`);
186
+ process.exitCode = 1;
187
+ }
188
+
189
+ module.exports = { build, buildSync, runGraph, explain, shortestPath, nlQuery, nlQuerySemantic, nlQueryHybrid };
@@ -0,0 +1,109 @@
1
+ 'use strict';
2
+
3
+ // Label propagation community detection — approximates Leiden/Louvain.
4
+ // Pure JS, zero deps. O(nodes * edges * iterations).
5
+ // Nodes with no edges each form their own community.
6
+
7
+ function detectCommunities(nodes, edges, { iterations = 10, seed = 42 } = {}) {
8
+ if (!nodes.length) return {};
9
+
10
+ // Build adjacency: nodeId → Set of neighbour nodeIds
11
+ const nodeIds = nodes.map((n) => n.id);
12
+ const nodeSet = new Set(nodeIds);
13
+ const adj = new Map();
14
+ for (const id of nodeIds) adj.set(id, new Set());
15
+
16
+ for (const e of edges) {
17
+ if (nodeSet.has(e.from) && nodeSet.has(e.to)) {
18
+ adj.get(e.from).add(e.to);
19
+ adj.get(e.to).add(e.from); // treat as undirected for community purposes
20
+ }
21
+ }
22
+
23
+ // Initialise: each node gets its own community label = its own id
24
+ const label = new Map();
25
+ for (const id of nodeIds) label.set(id, id);
26
+
27
+ // Deterministic shuffle using simple LCG
28
+ function lcgShuffle(arr, s) {
29
+ let state = s >>> 0;
30
+ for (let i = arr.length - 1; i > 0; i--) {
31
+ state = (Math.imul(state, 1664525) + 1013904223) >>> 0;
32
+ const j = state % (i + 1);
33
+ [arr[i], arr[j]] = [arr[j], arr[i]];
34
+ }
35
+ return arr;
36
+ }
37
+
38
+ const order = [...nodeIds];
39
+ for (let iter = 0; iter < iterations; iter++) {
40
+ lcgShuffle(order, seed + iter);
41
+ let changed = false;
42
+ for (const id of order) {
43
+ const neighbours = adj.get(id);
44
+ if (!neighbours.size) continue;
45
+
46
+ // Count label frequency among neighbours
47
+ const freq = new Map();
48
+ for (const nb of neighbours) {
49
+ const l = label.get(nb);
50
+ freq.set(l, (freq.get(l) || 0) + 1);
51
+ }
52
+
53
+ // Pick most frequent label (deterministic tie-break: lexicographic)
54
+ let best = label.get(id);
55
+ let bestCount = freq.get(best) || 0;
56
+ for (const [l, c] of freq) {
57
+ if (c > bestCount || (c === bestCount && l < best)) {
58
+ best = l;
59
+ bestCount = c;
60
+ }
61
+ }
62
+
63
+ if (best !== label.get(id)) {
64
+ label.set(id, best);
65
+ changed = true;
66
+ }
67
+ }
68
+ if (!changed) break;
69
+ }
70
+
71
+ // Map string labels → integer community ids
72
+ const labelToInt = new Map();
73
+ let nextId = 0;
74
+
75
+ // Sort label strings for deterministic int assignment
76
+ const uniqueLabels = [...new Set(label.values())].sort();
77
+ for (const l of uniqueLabels) labelToInt.set(l, nextId++);
78
+
79
+ const result = {};
80
+ for (const id of nodeIds) {
81
+ result[id] = labelToInt.get(label.get(id));
82
+ }
83
+ return result;
84
+ }
85
+
86
+ // Returns a human-readable label for each community (most-connected node name).
87
+ function communityLabels(nodes, edges, communities) {
88
+ const degree = new Map();
89
+ for (const e of edges) {
90
+ degree.set(e.from, (degree.get(e.from) || 0) + 1);
91
+ degree.set(e.to, (degree.get(e.to) || 0) + 1);
92
+ }
93
+
94
+ const groups = new Map(); // communityId → [node, ...]
95
+ for (const n of nodes) {
96
+ const c = communities[n.id] ?? 0;
97
+ if (!groups.has(c)) groups.set(c, []);
98
+ groups.get(c).push(n);
99
+ }
100
+
101
+ const labels = {};
102
+ for (const [c, members] of groups) {
103
+ const top = members.slice().sort((a, b) => (degree.get(b.id) || 0) - (degree.get(a.id) || 0))[0];
104
+ labels[c] = top ? top.label : `cluster-${c}`;
105
+ }
106
+ return labels;
107
+ }
108
+
109
+ module.exports = { detectCommunities, communityLabels };