bada-terminal / src /code-intel-manager.js
VanyaJ's picture
Release BADA Terminal v2.1.0 (Enterprise Ontology, NVIDIA auto-ontology, Release Preflight)
d739b1b verified
Raw History Blame Contribute Delete
18.6 kB
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<string>} 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<Array>}
*/
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<Object>} { 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();