const fs = require('fs'); const path = require('path'); const { execSync } = require('child_process'); class CodeDiffEngine { constructor(db) { this.db = db; } /** * Capture a snapshot of code symbols and relations at a specific commit. * @param {string} projectId * @param {string} commitHash * @returns {Object} The snapshot data */ async captureSnapshot(projectId, commitHash) { // 1. Get code symbols const symbols = await this.db.searchCodeSymbols(projectId, ''); // 2. Get relations (we can load all relations by querying with empty symbol ID if we support it, // or we can query for each symbol, or query direct relations) // Wait, let's make sure getCodeRelations supports retrieving all relations if we pass empty string or if we fetch all. // Let's check getCodeRelations implementation in sqlite-db.js: // It queries: SELECT * FROM code_relations WHERE project_id = ? AND (source_symbol_id = ? OR target_symbol_id = ?) // To get all relations, we can implement a helper or query directly. // Let's implement a simple query helper in our diff engine if we have direct access to database instance, // or just fetch relations for each symbol. // Wait! Since SqliteDb is used, if we use the JSON database fallback, we can access the data directly. // Let's design a clean way: const relations = []; const symbolIds = symbols.map(s => s.id); const seenRels = new Set(); for (const symId of symbolIds) { const rels = await this.db.getCodeRelations(projectId, symId); for (const r of rels) { const key = `${r.source_symbol_id}->${r.target_symbol_id}[${r.relation_type}]`; if (!seenRels.has(key)) { seenRels.add(key); relations.push(r); } } } return { commitHash, timestamp: new Date().toISOString(), symbols, relations }; } /** * Diff two codebase snapshots. * @param {Object} fromSnapshot * @param {Object} toSnapshot * @returns {Object} { added: Array, removed: Array, modified: Array } */ diffSnapshots(fromSnapshot, toSnapshot) { const fromSymbols = fromSnapshot.symbols || []; const toSymbols = toSnapshot.symbols || []; const fromMap = new Map(fromSymbols.map(s => [s.id, s])); const toMap = new Map(toSymbols.map(s => [s.id, s])); const added = []; const removed = []; const modified = []; // Check for added or modified for (const [id, toSym] of toMap.entries()) { if (!fromMap.has(id)) { added.push(toSym); } else { const fromSym = fromMap.get(id); // Basic check for modification: line range, signature, or properties changed if ( fromSym.signature !== toSym.signature || fromSym.start_line !== toSym.start_line || fromSym.end_line !== toSym.end_line || JSON.stringify(fromSym.properties) !== JSON.stringify(toSym.properties) ) { modified.push(toSym); } } } // Check for removed for (const [id, fromSym] of fromMap.entries()) { if (!toMap.has(id)) { removed.push(fromSym); } } return { added, removed, modified }; } /** * Install the post-commit git hook to trigger incremental updates. * @param {string} projectPath */ setupGitHook(projectPath) { const gitDir = path.join(projectPath, '.git'); if (!fs.existsSync(gitDir)) { return false; // Not a git repository } const hooksDir = path.join(gitDir, 'hooks'); if (!fs.existsSync(hooksDir)) { fs.mkdirSync(hooksDir, { recursive: true }); } const hookPath = path.join(hooksDir, 'post-commit'); const hookScript = `#!/usr/bin/env node const net = require('net'); const path = require('path'); const projectPath = path.resolve(__dirname, '../..'); // 인증값이 없는 외부 Git 실행은 앱의 코드 분석 권한을 얻지 않는다. const token = process.env.BADA_MCP_TOKEN; if (typeof token !== 'string' || !/^[a-f0-9]{64}$/.test(token)) process.exit(0); const request = { jsonrpc: '2.0', id: Date.now(), method: 'tools/call', params: { name: 'bada_code_analyze', arguments: { project_path: projectPath, incremental: true } } }; const client = net.createConnection({ port: 55055, host: '127.0.0.1' }, () => { client.write(JSON.stringify({ badaAuth: token }) + '\\n' + JSON.stringify(request) + '\\n'); }); let responseBuffer = ''; client.setEncoding('utf8'); client.on('data', chunk => { responseBuffer += chunk; let boundary; while ((boundary = responseBuffer.indexOf('\\n')) >= 0) { const line = responseBuffer.slice(0, boundary); responseBuffer = responseBuffer.slice(boundary + 1); try { const response = JSON.parse(line); if (response.id === request.id) { client.end(); process.exit(0); } } catch { client.end(); process.exit(0); } } }); client.on('error', () => { process.exit(0); }); setTimeout(() => { process.exit(0); }, 2000); `; fs.writeFileSync(hookPath, hookScript, { encoding: 'utf-8', mode: 0o755 }); // On macOS/Linux, ensure it's executable via chmod if (process.platform !== 'win32') { try { execSync(`chmod +x "${hookPath}"`); } catch (e) { console.error('[CodeDiffEngine] Failed to chmod post-commit hook:', e.message); } } return true; } } module.exports = CodeDiffEngine;