const fs = require('fs'); const path = require('path'); const { execSync } = require('child_process'); const crypto = require('crypto'); const db = require('../knowledge-db'); const { SecurityGateway } = require('./security-gateway'); const CodeDiffEngine = require('./code-diff-engine'); class CodeIntelManager { constructor() { this.projects = new Map(); // projectId -> projectConfig this.securityGateway = new SecurityGateway(); this.diffEngine = new CodeDiffEngine(db); this.loadProjectsFromPreferences(); } /** * Load registered projects from dev_preferences database. */ async loadProjectsFromPreferences() { try { // Find all global project registrations // Category: 'project_config', Key: 'metadata' const prefs = await db.getDevPreferences('global', 'project_config'); for (const p of prefs) { try { const config = JSON.parse(p.preference_value); // 주의: 모든 등록 행의 project_id 는 'global' 이므로, 반드시 config.projectId 를 맵 키로 사용해야 한다. // (이전 구현은 p.project_id 를 사용해 모든 프로젝트가 'global' 키 하나로 덮어써지는 버그가 있었음) if (config && config.projectId) { this.projects.set(config.projectId, config); } } catch (e) { /* intentional: JSON 파싱 실패 시 원본 유지 */ } } } catch (e) { console.warn('[CodeIntelManager] Failed to load projects from preferences:', e.message); } } /** * Get project config by path. */ getProjectId(projectPath) { return crypto.createHash('md5').update(path.resolve(projectPath)).digest('hex').substring(0, 16); } /** * Register a new project for code intelligence. * @param {string} projectPath * @param {Object} options - { role: 'main'|'reference', securityLevel: 1|2|3, autoIndex: true, preferredLlm: 'auto' } */ async registerProject(projectPath, options = {}) { const resolvedPath = path.resolve(projectPath); if (!fs.existsSync(resolvedPath)) { throw new Error(`프로젝트 경로가 존재하지 않습니다: ${projectPath}`); } const projectId = this.getProjectId(resolvedPath); const role = options.role || 'main'; const securityLevel = options.securityLevel || 1; const preferredLlm = options.preferredLlm || 'auto'; const projectConfig = { projectId, path: resolvedPath, name: path.basename(resolvedPath), role, securityLevel, preferredLlm, registeredAt: new Date().toISOString() }; // Save project registration to dev_preferences (global scope) await db.saveDevPreference('global', { category: 'project_config', preference_key: `project_${projectId}`, preference_value: JSON.stringify(projectConfig), confidence: 1.0, source: 'user_explicit' }); this.projects.set(projectId, projectConfig); // Setup Git Hook const gitHookInstalled = this.diffEngine.setupGitHook(resolvedPath); projectConfig.gitHookInstalled = gitHookInstalled; // Trigger Initial Code Analysis if (options.autoIndex !== false) { // Run CodeParser analyze const CodeParser = require('../code-parser'); // 루트의 code-parser.js (src 기준 한 단계 위). 순환 참조 방지 위해 동적 로드 console.log(`[CodeIntelManager] Starting initial analysis for project: ${projectConfig.name}`); const result = await CodeParser.analyze(projectId, resolvedPath); // Capture initial git commit snapshot if available try { const commitHash = execSync('git rev-parse HEAD', { cwd: resolvedPath, encoding: 'utf-8' }).trim(); const author = execSync('git log -1 --format=%an', { cwd: resolvedPath, encoding: 'utf-8' }).trim(); const message = execSync('git log -1 --format=%s', { cwd: resolvedPath, encoding: 'utf-8' }).trim(); const timestamp = execSync('git log -1 --format=%cI', { cwd: resolvedPath, encoding: 'utf-8' }).trim(); const snapshot = await this.diffEngine.captureSnapshot(projectId, commitHash); await db.saveChangeHistory(projectId, { commit_hash: commitHash, commit_message: message, commit_author: author, commit_timestamp: timestamp, changed_symbols: [], diff_summary: { added: snapshot.symbols.length, modified: 0, deleted: 0 }, snapshot_json: JSON.stringify(snapshot) }); } catch (gitErr) { console.warn(`[CodeIntelManager] Git snapshot skip for initial index of ${resolvedPath}:`, gitErr.message); } } return projectConfig; } /** * Run incremental update for changed files. * @param {string} projectId * @param {Array} changedFiles */ async incrementalUpdate(projectId, changedFiles = null) { const config = this.projects.get(projectId); if (!config) { throw new Error(`등록되지 않은 프로젝트 ID입니다: ${projectId}`); } const projectPath = config.path; let filesToUpdate = changedFiles; // If no changed files list, try to find via git diff if (!filesToUpdate) { try { const diffOutput = execSync('git diff --name-only HEAD~1', { cwd: projectPath, encoding: 'utf-8' }); filesToUpdate = diffOutput.split('\n').map(f => f.trim()).filter(f => f && fs.existsSync(path.join(projectPath, f))); } catch (e) { console.warn(`[CodeIntelManager] Git diff failed for incremental update, running full analysis:`, e.message); } } const CodeParser = require('../code-parser'); // 루트의 code-parser.js (src 기준 한 단계 위) if (filesToUpdate && filesToUpdate.length > 0) { console.log(`[CodeIntelManager] Running incremental update for ${filesToUpdate.length} files in ${config.name}`); // Update only changed files in DB for (const fileRelPath of filesToUpdate) { const fullPath = path.join(projectPath, fileRelPath); const fileExt = path.extname(fileRelPath).toLowerCase(); if (!['.js', '.jsx', '.ts', '.tsx', '.py'].includes(fileExt)) continue; const content = fs.readFileSync(fullPath, 'utf-8'); let parsedData = { entities: [], imports: [] }; if (['.js', '.jsx', '.ts', '.tsx'].includes(fileExt)) { parsedData = CodeParser.parseJsTs(fullPath, content); } else if (fileExt === '.py') { parsedData = CodeParser.parsePython(content); } // Save Code Symbols for (const entity of parsedData.entities) { const entityId = `code-${fullPath}#${entity.name}`; await db.saveCodeSymbol(projectId, { id: entityId, symbol_type: entity.type, name: entity.name, file_path: fileRelPath, start_line: entity.startLine, end_line: entity.endLine, signature: entity.type === 'class' ? `class ${entity.name}` : `${entity.name}()`, properties: { file: fullPath } }); // Save Code Relation await db.saveCodeRelation(projectId, { source_symbol_id: `file-${fullPath}`, target_symbol_id: entityId, relation_type: entity.type === 'class' ? 'defines_class' : 'defines_function' }); } } // Record commit snapshot try { const commitHash = execSync('git rev-parse HEAD', { cwd: projectPath, encoding: 'utf-8' }).trim(); const author = execSync('git log -1 --format=%an', { cwd: projectPath, encoding: 'utf-8' }).trim(); const message = execSync('git log -1 --format=%s', { cwd: projectPath, encoding: 'utf-8' }).trim(); const timestamp = execSync('git log -1 --format=%cI', { cwd: projectPath, encoding: 'utf-8' }).trim(); const latestHistories = await db.getChangeHistory(projectId); const prevSnapshot = latestHistories.length > 0 && latestHistories[0].snapshot_json ? JSON.parse(latestHistories[0].snapshot_json) : { symbols: [], relations: [] }; const currentSnapshot = await this.diffEngine.captureSnapshot(projectId, commitHash); const diff = this.diffEngine.diffSnapshots(prevSnapshot, currentSnapshot); await db.saveChangeHistory(projectId, { commit_hash: commitHash, commit_message: message, commit_author: author, commit_timestamp: timestamp, changed_symbols: diff.modified.concat(diff.added).map(s => s.id), diff_summary: { added: diff.added.length, modified: diff.modified.length, deleted: diff.removed.length }, snapshot_json: JSON.stringify(currentSnapshot) }); } catch (gitErr) { console.warn('[CodeIntelManager] Failed to record git commit history:', gitErr.message); } } else { // Full run as backup await CodeParser.analyze(projectId, projectPath); } } /** * Get all registered projects. */ getProjects() { // 렌더러 호환을 위해 정규화된 필드(id/status/last_analyzed_at)를 함께 제공한다. return Array.from(this.projects.values()).map(c => ({ ...c, id: c.projectId, status: c.lastAnalyzedAt ? 'analyzed' : 'pending', last_analyzed_at: c.lastAnalyzedAt || c.registeredAt || null })); } /** * Compare main and reference projects. * @param {string} mainProjectId * @param {string} referenceProjectId * @param {string} query */ async compareProjects(mainProjectId, referenceProjectId, query = '') { const mainSymbols = await db.searchCodeSymbols(mainProjectId, query); const refSymbols = await db.searchCodeSymbols(referenceProjectId, query); const mainMap = new Map(mainSymbols.map(s => [s.name, s])); const refMap = new Map(refSymbols.map(s => [s.name, s])); const common = []; const uniqueToMain = []; const uniqueToRef = []; for (const [name, mainSym] of mainMap.entries()) { if (refMap.has(name)) { common.push({ name, mainSymbol: mainSym, refSymbol: refMap.get(name) }); } else { uniqueToMain.push(mainSym); } } for (const [name, refSym] of refMap.entries()) { if (!mainMap.has(name)) { uniqueToRef.push(refSym); } } const totalSymbols = mainSymbols.length + refSymbols.length; const similarityScore = totalSymbols > 0 ? (common.length * 2) / totalSymbols : 0; return { similarityScore, commonCount: common.length, mainOnlyCount: uniqueToMain.length, refOnlyCount: uniqueToRef.length, common: common.slice(0, 100), // Cap for display uniqueToMain: uniqueToMain.slice(0, 100), uniqueToRef: uniqueToRef.slice(0, 100) }; } /** * 등록된 프로젝트를 재분석한다. (UI '재분석' 버튼 → analyze-code-project IPC) * CodeParser.analyze 로 심볼 전체를 다시 인덱싱하고, 가능하면 git 스냅샷을 갱신한다. * @param {string} projectId * @returns {Promise<{success:boolean, projectId:string, symbolCount:number, name:string}>} */ async analyzeProject(projectId) { const config = this.projects.get(projectId); if (!config) { throw new Error(`등록되지 않은 프로젝트 ID입니다: ${projectId}`); } const resolvedPath = config.path; if (!fs.existsSync(resolvedPath)) { throw new Error(`프로젝트 경로가 존재하지 않습니다: ${resolvedPath}`); } const CodeParser = require('../code-parser'); // 루트의 code-parser.js (src 기준 한 단계 위) console.log(`[CodeIntelManager] 프로젝트 재분석 시작: ${config.name}`); const result = await CodeParser.analyze(projectId, resolvedPath); // git 스냅샷 갱신(선택) — git 저장소가 아니면 조용히 건너뛴다. await this._captureGitSnapshot(projectId, resolvedPath); // 최신 분석 시각 기록 config.lastAnalyzedAt = new Date().toISOString(); await db.saveDevPreference('global', { category: 'project_config', preference_key: `project_${projectId}`, preference_value: JSON.stringify(config), confidence: 1.0, source: 'user_explicit' }); const symbols = await db.searchCodeSymbols(projectId, ''); console.log(`[CodeIntelManager] 재분석 완료: ${config.name} (심볼 ${symbols.length}개)`); return { success: true, projectId, name: config.name, symbolCount: symbols.length, result: result || null }; } /** * git 커밋 스냅샷을 캡처해 변경 이력에 저장한다(git 저장소가 아니면 무시). * registerProject 의 초기 인덱싱 로직과 동일 책임을 재사용 목적. * @private */ async _captureGitSnapshot(projectId, resolvedPath) { try { const commitHash = execSync('git rev-parse HEAD', { cwd: resolvedPath, encoding: 'utf-8' }).trim(); const author = execSync('git log -1 --format=%an', { cwd: resolvedPath, encoding: 'utf-8' }).trim(); const message = execSync('git log -1 --format=%s', { cwd: resolvedPath, encoding: 'utf-8' }).trim(); const timestamp = execSync('git log -1 --format=%cI', { cwd: resolvedPath, encoding: 'utf-8' }).trim(); const snapshot = await this.diffEngine.captureSnapshot(projectId, commitHash); await db.saveChangeHistory(projectId, { commit_hash: commitHash, commit_message: message, commit_author: author, commit_timestamp: timestamp, changed_symbols: [], diff_summary: { added: snapshot.symbols.length, modified: 0, deleted: 0 }, snapshot_json: JSON.stringify(snapshot) }); } catch (gitErr) { console.warn(`[CodeIntelManager] git 스냅샷 건너뜀(${resolvedPath}):`, gitErr.message); } } /** * 프로젝트의 코드 심볼 목록을 조회한다. (get-code-symbols IPC) * @param {string} projectId * @param {Object} options - { limit, query } * @returns {Promise} */ async getSymbols(projectId, options = {}) { const query = options.query || ''; const symbols = await db.searchCodeSymbols(projectId, query); const limit = options.limit || 0; return limit > 0 ? symbols.slice(0, limit) : symbols; } /** * 등록된 프로젝트를 삭제한다. 등록 정보(dev_preferences)와 인덱싱된 코드 데이터를 함께 제거한다. * @param {string} projectId * @returns {Promise<{success:boolean, projectId:string}>} */ async deleteProject(projectId) { if (!this.projects.has(projectId)) { throw new Error(`등록되지 않은 프로젝트 ID입니다: ${projectId}`); } // 1) 인덱싱된 코드 심볼/관계/이력 제거 try { await db.deleteCodeProjectData(projectId); } catch (e) { console.warn('[CodeIntelManager] 코드 데이터 삭제 경고:', e.message); } // 1-2) 코드맵 그래프 노드/엣지 제거 (해시 projectId 는 코드인텔 전용이라 안전) try { await db.clearProjectData(projectId); } catch (e) { console.warn('[CodeIntelManager] 코드맵 그래프 삭제 경고:', e.message); } // 2) 등록 정보(dev_preferences) 제거 await db.deleteDevPreference('global', 'project_config', `project_${projectId}`); // 3) 메모리 캐시에서 제거 this.projects.delete(projectId); console.log(`[CodeIntelManager] 프로젝트 삭제 완료: ${projectId}`); return { success: true, projectId }; } /** * 프로젝트 코드 인텔리전스 데이터를 직렬화 가능한 번들로 내보낸다. (파일 저장용) * @param {string} projectId * @returns {Promise} { version, config, symbols, relations, history } */ async exportProject(projectId) { const config = this.projects.get(projectId); if (!config) { throw new Error(`등록되지 않은 프로젝트 ID입니다: ${projectId}`); } const symbols = await db.searchCodeSymbols(projectId, ''); const relations = await db.getAllCodeRelations(projectId); const history = await db.getChangeHistory(projectId); return { version: 1, exportedAt: new Date().toISOString(), config, symbols, relations, history }; } /** * 내보낸 번들을 현재 DB로 불러온다(가져오기). 동일 ID 존재 시 데이터를 병합/갱신한다. * 보안: 경로는 원본 그대로 복원하되, 신뢰할 수 있는 사용자 내보내기 파일만 대상으로 한다. * @param {Object} bundle - exportProject 결과 구조 * @returns {Promise<{success:boolean, projectId:string, symbolCount:number}>} */ async importProject(bundle) { if (!bundle || typeof bundle !== 'object' || !bundle.config || !bundle.config.projectId) { throw new Error('올바르지 않은 가져오기 파일 형식입니다. (config.projectId 누락)'); } const config = bundle.config; const projectId = config.projectId; // 1) 등록 정보 복원 config.importedAt = new Date().toISOString(); await db.saveDevPreference('global', { category: 'project_config', preference_key: `project_${projectId}`, preference_value: JSON.stringify(config), confidence: 1.0, source: 'user_explicit' }); this.projects.set(projectId, config); // 2) 심볼 복원 let symbolCount = 0; for (const s of (bundle.symbols || [])) { try { await db.saveCodeSymbol(projectId, s); symbolCount++; } catch (e) { /* 개별 심볼 실패 무시 */ } } // 3) 관계 복원 for (const r of (bundle.relations || [])) { try { await db.saveCodeRelation(projectId, r); } catch (e) { /* 개별 관계 실패 무시 */ } } // 4) 변경 이력 복원 for (const h of (bundle.history || [])) { try { await db.saveChangeHistory(projectId, { commit_hash: h.commit_hash, commit_message: h.commit_message, commit_author: h.commit_author, commit_timestamp: h.commit_timestamp, changed_symbols: h.changed_symbols, diff_summary: h.diff_summary, snapshot_json: h.snapshot_json }); } catch (e) { /* 개별 이력 실패 무시 */ } } console.log(`[CodeIntelManager] 프로젝트 가져오기 완료: ${config.name} (심볼 ${symbolCount}개)`); return { success: true, projectId, name: config.name, symbolCount }; } } // Singleton instance module.exports = new CodeIntelManager();