const db = require('../../knowledge-db'); /** * Pure JS 기반의 경량 Louvain 커뮤니티 탐지 및 그래프 인텔리전스 모듈 */ /** * 그래프의 커뮤니티를 분류하고 밀집성(Cohesion)을 연산합니다. * @param {object} graphData { nodes, edges } 구조의 그래프 데이터 * @returns {object} { communityMap, communitiesDetail } */ function detectCommunities(graphData) { const nodes = graphData.nodes || []; const edges = graphData.edges || []; if (nodes.length === 0) { return { communityMap: {}, communitiesDetail: {} }; } // 1. 초기화: 각 노드를 고유 커뮤니티 ID로 지정 const communityMap = {}; nodes.forEach((n, idx) => { communityMap[n.id] = idx; }); // 노드 차수(degree) 및 가중치 합 계산 const degrees = {}; nodes.forEach(n => { degrees[n.id] = 0; }); const adj = {}; nodes.forEach(n => { adj[n.id] = {}; }); edges.forEach(e => { if (degrees[e.source] !== undefined && degrees[e.target] !== undefined) { degrees[e.source]++; degrees[e.target]++; // 가중치(기본값 1.0) const weight = parseFloat(e.properties?.weight) || 1.0; adj[e.source][e.target] = (adj[e.source][e.target] || 0) + weight; adj[e.target][e.source] = (adj[e.target][e.source] || 0) + weight; } }); // 전체 차수 합 (2m) let totalWeight2m = 0; nodes.forEach(n => { Object.keys(adj[n.id]).forEach(nbr => { totalWeight2m += adj[n.id][nbr]; }); }); if (totalWeight2m === 0) { totalWeight2m = nodes.length; // fallback } // 2. Modularity 최적화 루프 (최대 15회 반복) let improvement = true; let iterations = 0; while (improvement && iterations < 15) { improvement = false; iterations++; // 각 노드 순회하며 이웃 커뮤니티로 이식하여 modularity delta 계산 for (const node of nodes) { const u = node.id; const currentComm = communityMap[u]; const neighbors = Object.keys(adj[u]); if (neighbors.length === 0) continue; // 이웃 노드들이 속해있는 커뮤니티 리스트 추출 const neighborComms = new Set(); neighbors.forEach(v => neighborComms.add(communityMap[v])); let bestComm = currentComm; let maxDeltaQ = 0; // 각 이웃 커뮤니티로 u를 옮겼을 때의 Delta Q 연산 neighborComms.forEach(c => { if (c === currentComm) return; // u와 커뮤니티 c 내의 노드들 간의 가중치 합 (Ki,in) let k_i_in = 0; neighbors.forEach(v => { if (communityMap[v] === c) { k_i_in += adj[u][v] || 0; } }); // 커뮤니티 c에 속한 전체 노드들의 차수 합 (Sigma_tot) let sigma_tot = 0; nodes.forEach(n => { if (communityMap[n.id] === c) { Object.keys(adj[n.id]).forEach(nbr => { sigma_tot += adj[n.id][nbr] || 0; }); } }); // u의 자체 차수 (Ki) let k_i = 0; Object.keys(adj[u]).forEach(nbr => { k_i += adj[u][nbr] || 0; }); // Delta Q 간소 계산 공식 const deltaQ = (k_i_in / totalWeight2m) - (sigma_tot * k_i) / (totalWeight2m * totalWeight2m); if (deltaQ > maxDeltaQ) { maxDeltaQ = deltaQ; bestComm = c; } }); if (bestComm !== currentComm) { communityMap[u] = bestComm; improvement = true; } } } // 3. 커뮤니티 상세 지표 및 Cohesion 계산 const communitiesDetail = {}; nodes.forEach(n => { const cId = communityMap[n.id]; if (!communitiesDetail[cId]) { communitiesDetail[cId] = { id: cId, nodes: [], internalEdgesCount: 0, cohesion: 1.0 }; } communitiesDetail[cId].nodes.push(n.id); }); // 각 커뮤니티 내부 엣지 수 계산 edges.forEach(e => { const cSrc = communityMap[e.source]; const cTgt = communityMap[e.target]; if (cSrc === cTgt && communitiesDetail[cSrc]) { communitiesDetail[cSrc].internalEdgesCount++; } }); // Cohesion 점수 공식 적용 Object.keys(communitiesDetail).forEach(cId => { const comm = communitiesDetail[cId]; const n = comm.nodes.length; if (n >= 2) { const maxPossibleEdges = (n * (n - 1)) / 2; comm.cohesion = comm.internalEdgesCount / maxPossibleEdges; } else { comm.cohesion = 1.0; } }); return { communityMap, communitiesDetail }; } /** * 프로젝트 지식에 기반한 Heuristics Graph Insights를 생성합니다. * @param {string} projectId 프로젝트 폴더명 * @returns {object} { surprisingConnections, knowledgeGaps } */ function generateGraphInsights(projectId) { const graphData = db.exportProjectData(projectId); if (!graphData || !graphData.nodes || graphData.nodes.length === 0) { return { surprisingConnections: [], knowledgeGaps: { isolatedNodes: [], sparseCommunities: [], bridgeNodes: [] } }; } const { communityMap, communitiesDetail } = detectCommunities(graphData); // 1. 차수(degree) 및 인접 리스트 생성 const degrees = {}; const adj = {}; graphData.nodes.forEach(n => { degrees[n.id] = 0; adj[n.id] = new Set(); }); graphData.edges.forEach(e => { if (degrees[e.source] !== undefined && degrees[e.target] !== undefined) { degrees[e.source]++; degrees[e.target]++; adj[e.source].add(e.target); adj[e.target].add(e.source); } }); // 2. Surprising Connections (의외의 연결) 탐지 규칙 Heuristics const surprisingConnections = []; graphData.edges.forEach(e => { // 구조 노드(index, log 등)는 노이즈 유발하므로 제외 if (e.source.includes('index') || e.target.includes('index')) return; let score = 0; const cSrc = communityMap[e.source]; const cTgt = communityMap[e.target]; // 규칙 1: 서로 다른 커뮤니티 간의 연결 if (cSrc !== undefined && cTgt !== undefined && cSrc !== cTgt) { score += 3.0; } const nodeSrc = graphData.nodes.find(n => n.id === e.source); const nodeTgt = graphData.nodes.find(n => n.id === e.target); if (nodeSrc && nodeTgt) { // 규칙 2: 크로스 타입 (예: 소스파일과 세션 또는 소스파일과 위키가 먼 결합을 가질 때) if (nodeSrc.type !== nodeTgt.type) { if ((nodeSrc.type === 'file' && nodeTgt.type === 'session') || (nodeSrc.type === 'session' && nodeTgt.type === 'file')) { score += 2.0; } else { score += 1.0; } } // 규칙 3: 변두리 노드(차수 <= 2)와 허브 노드(차수 >= 8) 간의 연결 const degSrc = degrees[e.source] || 0; const degTgt = degrees[e.target] || 0; if ((degSrc <= 2 && degTgt >= 8) || (degTgt <= 2 && degSrc >= 8)) { score += 2.0; } } if (score >= 4.0) { surprisingConnections.push({ edge: e, sourceLabel: nodeSrc ? nodeSrc.label : e.source, targetLabel: nodeTgt ? nodeTgt.label : e.target, score }); } }); // 중복 엣지 제거 및 정렬 const uniqueSurprising = surprisingConnections .sort((a, b) => b.score - a.score) .slice(0, 10); // 3. Knowledge Gaps (지식 결함) 탐지 규칙 Heuristics // A. Isolated Nodes (고립 노드: 연결 차수 <= 1 인 위키/노트 및 소스 파일) const isolatedNodes = graphData.nodes .filter(n => { if (n.id.includes('index') || n.id.includes('claude')) return false; const deg = degrees[n.id] || 0; return deg <= 1 && (n.type === 'note' || n.type === 'wiki' || n.type === 'file'); }) .map(n => ({ id: n.id, label: n.label, type: n.type })); // B. Sparse Communities (희소 커뮤니티: 노드 >= 3개, Cohesion < 0.2) const sparseCommunities = []; Object.keys(communitiesDetail).forEach(cId => { const comm = communitiesDetail[cId]; if (comm.nodes.length >= 3 && comm.cohesion < 0.20) { // 해당 커뮤니티의 노드 라벨 수집 const commLabels = comm.nodes.map(nId => { const found = graphData.nodes.find(n => n.id === nId); return found ? found.label : nId; }); sparseCommunities.push({ communityId: cId, nodeCount: comm.nodes.length, cohesion: comm.cohesion, nodes: commLabels }); } }); // C. Bridge Nodes (브리지 노드: 3개 이상의 다른 커뮤니티의 노드들과 각각 엣지를 가지는 노드) const bridgeNodes = []; graphData.nodes.forEach(n => { const connectedComms = new Set(); const neighbors = adj[n.id] || new Set(); neighbors.forEach(nbrId => { const cNbr = communityMap[nbrId]; if (cNbr !== undefined && cNbr !== communityMap[n.id]) { connectedComms.add(cNbr); } }); if (connectedComms.size >= 3) { bridgeNodes.push({ id: n.id, label: n.label, type: n.type, connectedCommunitiesCount: connectedComms.size }); } }); return { surprisingConnections: uniqueSurprising, knowledgeGaps: { isolatedNodes, sparseCommunities, bridgeNodes } }; } module.exports = { detectCommunities, generateGraphInsights };