File size: 18,648 Bytes
d739b1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
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();