kirograph 0.16.1 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +225 -8
  2. package/dist/bin/commands/affected.js +40 -5
  3. package/dist/bin/commands/affected.js.map +2 -2
  4. package/dist/bin/commands/data.js +665 -0
  5. package/dist/bin/commands/data.js.map +7 -0
  6. package/dist/bin/commands/help.js +5 -0
  7. package/dist/bin/commands/help.js.map +2 -2
  8. package/dist/bin/installer/config-prompt.js +28 -1
  9. package/dist/bin/installer/config-prompt.js.map +2 -2
  10. package/dist/bin/installer/index.js +28 -1
  11. package/dist/bin/installer/index.js.map +2 -2
  12. package/dist/bin/installer/steering.js +33 -0
  13. package/dist/bin/installer/steering.js.map +2 -2
  14. package/dist/bin/installer/targets/index.js.map +1 -1
  15. package/dist/bin/installer/targets/kiro.js +2 -2
  16. package/dist/bin/installer/targets/kiro.js.map +2 -2
  17. package/dist/bin/kirograph.js +3 -1
  18. package/dist/bin/kirograph.js.map +3 -3
  19. package/dist/bin/progress.js +30 -0
  20. package/dist/bin/progress.js.map +2 -2
  21. package/dist/compression/naive-cost.js +25 -0
  22. package/dist/compression/naive-cost.js.map +2 -2
  23. package/dist/compression/tracker.js +11 -2
  24. package/dist/compression/tracker.js.map +2 -2
  25. package/dist/compression/types.js.map +1 -1
  26. package/dist/config.js +37 -1
  27. package/dist/config.js.map +2 -2
  28. package/dist/core/pipeline.js +56 -2
  29. package/dist/core/pipeline.js.map +2 -2
  30. package/dist/data/filters.js +105 -0
  31. package/dist/data/filters.js.map +7 -0
  32. package/dist/data/indexer.js +225 -0
  33. package/dist/data/indexer.js.map +7 -0
  34. package/dist/data/linker.js +150 -0
  35. package/dist/data/linker.js.map +7 -0
  36. package/dist/data/lint.js +109 -0
  37. package/dist/data/lint.js.map +7 -0
  38. package/dist/data/parsers/csv.js +132 -0
  39. package/dist/data/parsers/csv.js.map +7 -0
  40. package/dist/data/parsers/excel.js +88 -0
  41. package/dist/data/parsers/excel.js.map +7 -0
  42. package/dist/data/parsers/index.js +79 -0
  43. package/dist/data/parsers/index.js.map +7 -0
  44. package/dist/data/parsers/json-array.js +89 -0
  45. package/dist/data/parsers/json-array.js.map +7 -0
  46. package/dist/data/parsers/jsonl.js +84 -0
  47. package/dist/data/parsers/jsonl.js.map +7 -0
  48. package/dist/data/parsers/parquet.js +95 -0
  49. package/dist/data/parsers/parquet.js.map +7 -0
  50. package/dist/data/profiler.js +182 -0
  51. package/dist/data/profiler.js.map +7 -0
  52. package/dist/data/queries.js +512 -0
  53. package/dist/data/queries.js.map +7 -0
  54. package/dist/data/types.js +17 -0
  55. package/dist/data/types.js.map +7 -0
  56. package/dist/db/data-schema.sql +61 -0
  57. package/dist/db/database.js +11 -0
  58. package/dist/db/database.js.map +2 -2
  59. package/dist/mcp/tool-names.js +9 -1
  60. package/dist/mcp/tool-names.js.map +2 -2
  61. package/dist/mcp/tools.js +423 -0
  62. package/dist/mcp/tools.js.map +2 -2
  63. package/dist/types.js.map +1 -1
  64. package/package.json +4 -2
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/compression/tracker.ts"],
4
- "sourcesContent": ["/**\n * KiroGraph Token Savings Tracker\n *\n * Records compression results to a local JSON file for analytics.\n * Uses a simple append-only JSON lines file to avoid SQLite dependency\n * in the compression module (keeps it lightweight and independent).\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as crypto from 'crypto';\nimport type { TokenSavingsRecord } from './types';\n\nconst TRACKER_DIR = '.kirograph';\nconst TRACKER_FILE = 'token-savings.jsonl';\nconst MAX_RECORDS = 5000; // Rotate after this many records\n\nexport interface GainStats {\n totalCommands: number;\n totalOriginal: number;\n totalCompressed: number;\n totalSaved: number;\n savingsPercent: number;\n byFamily: Record<string, { count: number; savings: number }>;\n recentCommands: Array<{ command: string; savings: number; timestamp: number; source?: string }>;\n /** Breakdown by source type */\n bySource: {\n exec: { count: number; saved: number };\n graph: { count: number; saved: number };\n memory: { count: number; saved: number };\n docs: { count: number; saved: number };\n };\n}\n\nexport class TokenTracker {\n private filePath: string;\n private sessionId: string;\n\n constructor(projectRoot: string) {\n const dir = path.join(projectRoot, TRACKER_DIR);\n fs.mkdirSync(dir, { recursive: true });\n this.filePath = path.join(dir, TRACKER_FILE);\n this.sessionId = this.getOrCreateSessionId(dir);\n }\n\n private getOrCreateSessionId(dir: string): string {\n const sessionFile = path.join(dir, '.session-id');\n try {\n const existing = fs.readFileSync(sessionFile, 'utf8').trim();\n if (existing) return existing;\n } catch { /* file doesn't exist */ }\n\n const id = crypto.randomBytes(8).toString('hex');\n try {\n fs.writeFileSync(sessionFile, id, 'utf8');\n } catch { /* ignore write errors */ }\n return id;\n }\n\n /**\n * Record a compression result.\n */\n record(command: string, originalTokens: number, compressedTokens: number, strategy: string, source: 'exec' | 'graph' | 'memory' | 'docs' = 'exec'): void {\n const record: TokenSavingsRecord = {\n timestamp: Date.now(),\n command: command.slice(0, 200), // Truncate long commands\n originalTokens,\n compressedTokens,\n strategy,\n sessionId: this.sessionId,\n source,\n };\n\n try {\n fs.appendFileSync(this.filePath, JSON.stringify(record) + '\\n', 'utf8');\n this.maybeRotate();\n } catch {\n // Non-critical \u2014 don't crash on tracking failure\n }\n }\n\n /**\n * Record a graph tool saving.\n * @param toolName - The MCP tool that was called\n * @param outputTokens - Actual tokens returned by the tool\n * @param naiveCost - Estimated tokens the agent would have used without the tool\n */\n recordGraphSaving(toolName: string, outputTokens: number, naiveCost: number): void {\n this.record(toolName, naiveCost, outputTokens, `graph:${toolName}`, 'graph');\n }\n\n /**\n * Record a memory tool saving.\n * @param toolName - The MCP tool that was called\n * @param outputTokens - Actual tokens returned by the tool\n * @param naiveCost - Estimated tokens the agent would have used without memory\n */\n recordMemorySaving(toolName: string, outputTokens: number, naiveCost: number): void {\n this.record(toolName, naiveCost, outputTokens, `memory:${toolName}`, 'memory');\n }\n\n /**\n * Record a docs tool saving.\n * @param toolName - The MCP tool that was called\n * @param outputTokens - Actual tokens returned by the tool\n * @param naiveCost - Estimated tokens the agent would have used without docs indexing\n */\n recordDocsSaving(toolName: string, outputTokens: number, naiveCost: number): void {\n this.record(toolName, naiveCost, outputTokens, `docs:${toolName}`, 'docs');\n }\n\n /**\n * Get aggregated statistics for a time period.\n */\n getStats(period: 'session' | 'today' | 'week' | 'all'): GainStats {\n const records = this.loadRecords(period);\n\n if (records.length === 0) {\n return {\n totalCommands: 0,\n totalOriginal: 0,\n totalCompressed: 0,\n totalSaved: 0,\n savingsPercent: 0,\n byFamily: {},\n recentCommands: [],\n bySource: { exec: { count: 0, saved: 0 }, graph: { count: 0, saved: 0 }, memory: { count: 0, saved: 0 }, docs: { count: 0, saved: 0 } },\n };\n }\n\n let totalOriginal = 0;\n let totalCompressed = 0;\n const byFamily = new Map<string, { count: number; totalOriginal: number; totalCompressed: number }>();\n const bySource = { exec: { count: 0, saved: 0 }, graph: { count: 0, saved: 0 }, memory: { count: 0, saved: 0 }, docs: { count: 0, saved: 0 } };\n\n for (const r of records) {\n totalOriginal += r.originalTokens;\n totalCompressed += r.compressedTokens;\n\n const family = this.extractFamily(r.strategy);\n const existing = byFamily.get(family) || { count: 0, totalOriginal: 0, totalCompressed: 0 };\n existing.count++;\n existing.totalOriginal += r.originalTokens;\n existing.totalCompressed += r.compressedTokens;\n byFamily.set(family, existing);\n\n const source = (r.source || 'exec') as 'exec' | 'graph' | 'memory' | 'docs';\n if (bySource[source]) {\n bySource[source].count++;\n bySource[source].saved += r.originalTokens - r.compressedTokens;\n } else {\n bySource.exec.count++;\n bySource.exec.saved += r.originalTokens - r.compressedTokens;\n }\n }\n\n const totalSaved = totalOriginal - totalCompressed;\n const savingsPercent = totalOriginal > 0 ? Math.round((totalSaved / totalOriginal) * 100) : 0;\n\n // Convert byFamily map to sorted object\n const byFamilyObj: Record<string, { count: number; savings: number }> = {};\n const sortedFamilies = [...byFamily.entries()].sort((a, b) => b[1].count - a[1].count);\n for (const [family, data] of sortedFamilies) {\n const familySaved = data.totalOriginal - data.totalCompressed;\n const familyPercent = data.totalOriginal > 0 ? Math.round((familySaved / data.totalOriginal) * 100) : 0;\n byFamilyObj[family] = { count: data.count, savings: familyPercent };\n }\n\n // Recent commands (last 10)\n const recentCommands = records.slice(-10).reverse().map(r => ({\n command: r.command,\n savings: r.originalTokens > 0\n ? Math.round(((r.originalTokens - r.compressedTokens) / r.originalTokens) * 100)\n : 0,\n timestamp: r.timestamp,\n source: r.source,\n }));\n\n return {\n totalCommands: records.length,\n totalOriginal,\n totalCompressed,\n totalSaved,\n savingsPercent,\n byFamily: byFamilyObj,\n recentCommands,\n bySource,\n };\n }\n\n /**\n * Get raw history for CLI display.\n */\n getHistory(limit: number = 20): TokenSavingsRecord[] {\n const records = this.loadRecords('all');\n return records.slice(-limit).reverse();\n }\n\n /**\n * Get daily breakdown for graph display.\n */\n getDailyBreakdown(days: number = 30): Array<{ date: string; commands: number; saved: number }> {\n const records = this.loadRecords('all');\n const now = Date.now();\n const cutoff = now - days * 24 * 60 * 60 * 1000;\n\n const byDay = new Map<string, { commands: number; saved: number }>();\n\n for (const r of records) {\n if (r.timestamp < cutoff) continue;\n const date = new Date(r.timestamp).toISOString().slice(0, 10);\n const existing = byDay.get(date) || { commands: 0, saved: 0 };\n existing.commands++;\n existing.saved += r.originalTokens - r.compressedTokens;\n byDay.set(date, existing);\n }\n\n return [...byDay.entries()]\n .sort((a, b) => a[0].localeCompare(b[0]))\n .map(([date, data]) => ({ date, ...data }));\n }\n\n // \u2500\u2500 Private \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n private loadRecords(period: 'session' | 'today' | 'week' | 'all'): TokenSavingsRecord[] {\n if (!fs.existsSync(this.filePath)) return [];\n\n let lines: string[];\n try {\n lines = fs.readFileSync(this.filePath, 'utf8').split('\\n').filter(l => l.trim());\n } catch {\n return [];\n }\n\n const records: TokenSavingsRecord[] = [];\n for (const line of lines) {\n try {\n records.push(JSON.parse(line));\n } catch {\n // Skip malformed lines\n }\n }\n\n // Filter by period\n const now = Date.now();\n switch (period) {\n case 'session':\n return records.filter(r => r.sessionId === this.sessionId);\n case 'today': {\n const startOfDay = new Date();\n startOfDay.setHours(0, 0, 0, 0);\n return records.filter(r => r.timestamp >= startOfDay.getTime());\n }\n case 'week':\n return records.filter(r => r.timestamp >= now - 7 * 24 * 60 * 60 * 1000);\n case 'all':\n return records;\n }\n }\n\n private extractFamily(strategy: string): string {\n // \"git:status:ultra\" \u2192 \"git\"\n // \"jest:failures\" \u2192 \"jest\"\n const colon = strategy.indexOf(':');\n return colon > 0 ? strategy.slice(0, colon) : strategy;\n }\n\n private maybeRotate(): void {\n try {\n const stat = fs.statSync(this.filePath);\n // Rotate if file exceeds ~500KB\n if (stat.size > 500 * 1024) {\n const lines = fs.readFileSync(this.filePath, 'utf8').split('\\n').filter(l => l.trim());\n if (lines.length > MAX_RECORDS) {\n // Keep last half\n const keep = lines.slice(-Math.floor(MAX_RECORDS / 2));\n fs.writeFileSync(this.filePath, keep.join('\\n') + '\\n', 'utf8');\n }\n }\n } catch {\n // Non-critical\n }\n }\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAQA,SAAoB;AACpB,WAAsB;AACtB,aAAwB;AAGxB,MAAM,cAAc;AACpB,MAAM,eAAe;AACrB,MAAM,cAAc;AAmBb,MAAM,aAAa;AAAA,EAIxB,YAAY,aAAqB;AAC/B,UAAM,MAAM,KAAK,KAAK,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OAAO,OAAK,EAAE,cAAc,KAAK,SAAS;AAAA,MAC3D,KAAK,SAAS;AACZ,cAAM,aAAa,oBAAI,KAAK;AAC5B,mBAAW,SAAS,GAAG,GAAG,GAAG,CAAC;AAC9B,eAAO,QAAQ,OAAO,OAAK,EAAE,aAAa,WAAW,QAAQ,CAAC;AAAA,MAChE;AAAA,MACA,KAAK;AACH,eAAO,QAAQ,OAAO,OAAK,EAAE,aAAa,MAAM,IAAI,KAAK,KAAK,KAAK,GAAI;AAAA,MACzE,KAAK;AACH,eAAO;AAAA,IACX;AAAA,EACF;AAAA,EAEQ,cAAc,UAA0B;AAG9C,UAAM,QAAQ,SAAS,QAAQ,GAAG;AAClC,WAAO,QAAQ,IAAI,SAAS,MAAM,GAAG,KAAK,IAAI;AAAA,EAChD;AAAA,EAEQ,cAAoB;AAC1B,QAAI;AACF,YAAM,OAAO,GAAG,SAAS,KAAK,QAAQ;AAEtC,UAAI,KAAK,OAAO,MAAM,MAAM;AAC1B,cAAM,QAAQ,GAAG,aAAa,KAAK,UAAU,MAAM,EAAE,MAAM,IAAI,EAAE,OAAO,OAAK,EAAE,KAAK,CAAC;AACrF,YAAI,MAAM,SAAS,aAAa;AAE9B,gBAAM,OAAO,MAAM,MAAM,CAAC,KAAK,MAAM,cAAc,CAAC,CAAC;AACrD,aAAG,cAAc,KAAK,UAAU,KAAK,KAAK,IAAI,IAAI,MAAM,MAAM;AAAA,QAChE;AAAA,MACF;AAAA,IACF,QAAQ;AAAA,IAER;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["/**\n * KiroGraph Token Savings Tracker\n *\n * Records compression results to a local JSON file for analytics.\n * Uses a simple append-only JSON lines file to avoid SQLite dependency\n * in the compression module (keeps it lightweight and independent).\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as crypto from 'crypto';\nimport type { TokenSavingsRecord } from './types';\n\nconst TRACKER_DIR = '.kirograph';\nconst TRACKER_FILE = 'token-savings.jsonl';\nconst MAX_RECORDS = 5000; // Rotate after this many records\n\nexport interface GainStats {\n totalCommands: number;\n totalOriginal: number;\n totalCompressed: number;\n totalSaved: number;\n savingsPercent: number;\n byFamily: Record<string, { count: number; savings: number }>;\n recentCommands: Array<{ command: string; savings: number; timestamp: number; source?: string }>;\n /** Breakdown by source type */\n bySource: {\n exec: { count: number; saved: number };\n graph: { count: number; saved: number };\n memory: { count: number; saved: number };\n docs: { count: number; saved: number };\n data: { count: number; saved: number };\n };\n}\n\nexport class TokenTracker {\n private filePath: string;\n private sessionId: string;\n\n constructor(projectRoot: string) {\n const dir = path.join(projectRoot, TRACKER_DIR);\n fs.mkdirSync(dir, { recursive: true });\n this.filePath = path.join(dir, TRACKER_FILE);\n this.sessionId = this.getOrCreateSessionId(dir);\n }\n\n private getOrCreateSessionId(dir: string): string {\n const sessionFile = path.join(dir, '.session-id');\n try {\n const existing = fs.readFileSync(sessionFile, 'utf8').trim();\n if (existing) return existing;\n } catch { /* file doesn't exist */ }\n\n const id = crypto.randomBytes(8).toString('hex');\n try {\n fs.writeFileSync(sessionFile, id, 'utf8');\n } catch { /* ignore write errors */ }\n return id;\n }\n\n /**\n * Record a compression result.\n */\n record(command: string, originalTokens: number, compressedTokens: number, strategy: string, source: 'exec' | 'graph' | 'memory' | 'docs' | 'data' = 'exec'): void {\n const record: TokenSavingsRecord = {\n timestamp: Date.now(),\n command: command.slice(0, 200), // Truncate long commands\n originalTokens,\n compressedTokens,\n strategy,\n sessionId: this.sessionId,\n source,\n };\n\n try {\n fs.appendFileSync(this.filePath, JSON.stringify(record) + '\\n', 'utf8');\n this.maybeRotate();\n } catch {\n // Non-critical \u2014 don't crash on tracking failure\n }\n }\n\n /**\n * Record a graph tool saving.\n * @param toolName - The MCP tool that was called\n * @param outputTokens - Actual tokens returned by the tool\n * @param naiveCost - Estimated tokens the agent would have used without the tool\n */\n recordGraphSaving(toolName: string, outputTokens: number, naiveCost: number): void {\n this.record(toolName, naiveCost, outputTokens, `graph:${toolName}`, 'graph');\n }\n\n /**\n * Record a memory tool saving.\n * @param toolName - The MCP tool that was called\n * @param outputTokens - Actual tokens returned by the tool\n * @param naiveCost - Estimated tokens the agent would have used without memory\n */\n recordMemorySaving(toolName: string, outputTokens: number, naiveCost: number): void {\n this.record(toolName, naiveCost, outputTokens, `memory:${toolName}`, 'memory');\n }\n\n /**\n * Record a docs tool saving.\n * @param toolName - The MCP tool that was called\n * @param outputTokens - Actual tokens returned by the tool\n * @param naiveCost - Estimated tokens the agent would have used without docs indexing\n */\n recordDocsSaving(toolName: string, outputTokens: number, naiveCost: number): void {\n this.record(toolName, naiveCost, outputTokens, `docs:${toolName}`, 'docs');\n }\n\n /**\n * Record a data tool saving.\n * @param toolName - The MCP tool that was called\n * @param outputTokens - Actual tokens returned by the tool\n * @param naiveCost - Estimated tokens the agent would have used without data indexing\n */\n recordDataSaving(toolName: string, outputTokens: number, naiveCost: number): void {\n this.record(toolName, naiveCost, outputTokens, `data:${toolName}`, 'data');\n }\n\n /**\n * Get aggregated statistics for a time period.\n */\n getStats(period: 'session' | 'today' | 'week' | 'all'): GainStats {\n const records = this.loadRecords(period);\n\n if (records.length === 0) {\n return {\n totalCommands: 0,\n totalOriginal: 0,\n totalCompressed: 0,\n totalSaved: 0,\n savingsPercent: 0,\n byFamily: {},\n recentCommands: [],\n bySource: { exec: { count: 0, saved: 0 }, graph: { count: 0, saved: 0 }, memory: { count: 0, saved: 0 }, docs: { count: 0, saved: 0 }, data: { count: 0, saved: 0 } },\n };\n }\n\n let totalOriginal = 0;\n let totalCompressed = 0;\n const byFamily = new Map<string, { count: number; totalOriginal: number; totalCompressed: number }>();\n const bySource = { exec: { count: 0, saved: 0 }, graph: { count: 0, saved: 0 }, memory: { count: 0, saved: 0 }, docs: { count: 0, saved: 0 }, data: { count: 0, saved: 0 } };\n\n for (const r of records) {\n totalOriginal += r.originalTokens;\n totalCompressed += r.compressedTokens;\n\n const family = this.extractFamily(r.strategy);\n const existing = byFamily.get(family) || { count: 0, totalOriginal: 0, totalCompressed: 0 };\n existing.count++;\n existing.totalOriginal += r.originalTokens;\n existing.totalCompressed += r.compressedTokens;\n byFamily.set(family, existing);\n\n const source = (r.source || 'exec') as 'exec' | 'graph' | 'memory' | 'docs' | 'data';\n if (bySource[source]) {\n bySource[source].count++;\n bySource[source].saved += r.originalTokens - r.compressedTokens;\n } else {\n bySource.exec.count++;\n bySource.exec.saved += r.originalTokens - r.compressedTokens;\n }\n }\n\n const totalSaved = totalOriginal - totalCompressed;\n const savingsPercent = totalOriginal > 0 ? Math.round((totalSaved / totalOriginal) * 100) : 0;\n\n // Convert byFamily map to sorted object\n const byFamilyObj: Record<string, { count: number; savings: number }> = {};\n const sortedFamilies = [...byFamily.entries()].sort((a, b) => b[1].count - a[1].count);\n for (const [family, data] of sortedFamilies) {\n const familySaved = data.totalOriginal - data.totalCompressed;\n const familyPercent = data.totalOriginal > 0 ? Math.round((familySaved / data.totalOriginal) * 100) : 0;\n byFamilyObj[family] = { count: data.count, savings: familyPercent };\n }\n\n // Recent commands (last 10)\n const recentCommands = records.slice(-10).reverse().map(r => ({\n command: r.command,\n savings: r.originalTokens > 0\n ? Math.round(((r.originalTokens - r.compressedTokens) / r.originalTokens) * 100)\n : 0,\n timestamp: r.timestamp,\n source: r.source,\n }));\n\n return {\n totalCommands: records.length,\n totalOriginal,\n totalCompressed,\n totalSaved,\n savingsPercent,\n byFamily: byFamilyObj,\n recentCommands,\n bySource,\n };\n }\n\n /**\n * Get raw history for CLI display.\n */\n getHistory(limit: number = 20): TokenSavingsRecord[] {\n const records = this.loadRecords('all');\n return records.slice(-limit).reverse();\n }\n\n /**\n * Get daily breakdown for graph display.\n */\n getDailyBreakdown(days: number = 30): Array<{ date: string; commands: number; saved: number }> {\n const records = this.loadRecords('all');\n const now = Date.now();\n const cutoff = now - days * 24 * 60 * 60 * 1000;\n\n const byDay = new Map<string, { commands: number; saved: number }>();\n\n for (const r of records) {\n if (r.timestamp < cutoff) continue;\n const date = new Date(r.timestamp).toISOString().slice(0, 10);\n const existing = byDay.get(date) || { commands: 0, saved: 0 };\n existing.commands++;\n existing.saved += r.originalTokens - r.compressedTokens;\n byDay.set(date, existing);\n }\n\n return [...byDay.entries()]\n .sort((a, b) => a[0].localeCompare(b[0]))\n .map(([date, data]) => ({ date, ...data }));\n }\n\n // \u2500\u2500 Private \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n private loadRecords(period: 'session' | 'today' | 'week' | 'all'): TokenSavingsRecord[] {\n if (!fs.existsSync(this.filePath)) return [];\n\n let lines: string[];\n try {\n lines = fs.readFileSync(this.filePath, 'utf8').split('\\n').filter(l => l.trim());\n } catch {\n return [];\n }\n\n const records: TokenSavingsRecord[] = [];\n for (const line of lines) {\n try {\n records.push(JSON.parse(line));\n } catch {\n // Skip malformed lines\n }\n }\n\n // Filter by period\n const now = Date.now();\n switch (period) {\n case 'session':\n return records.filter(r => r.sessionId === this.sessionId);\n case 'today': {\n const startOfDay = new Date();\n startOfDay.setHours(0, 0, 0, 0);\n return records.filter(r => r.timestamp >= startOfDay.getTime());\n }\n case 'week':\n return records.filter(r => r.timestamp >= now - 7 * 24 * 60 * 60 * 1000);\n case 'all':\n return records;\n }\n }\n\n private extractFamily(strategy: string): string {\n // \"git:status:ultra\" \u2192 \"git\"\n // \"jest:failures\" \u2192 \"jest\"\n const colon = strategy.indexOf(':');\n return colon > 0 ? strategy.slice(0, colon) : strategy;\n }\n\n private maybeRotate(): void {\n try {\n const stat = fs.statSync(this.filePath);\n // Rotate if file exceeds ~500KB\n if (stat.size > 500 * 1024) {\n const lines = fs.readFileSync(this.filePath, 'utf8').split('\\n').filter(l => l.trim());\n if (lines.length > MAX_RECORDS) {\n // Keep last half\n const keep = lines.slice(-Math.floor(MAX_RECORDS / 2));\n fs.writeFileSync(this.filePath, keep.join('\\n') + '\\n', 'utf8');\n }\n }\n } catch {\n // Non-critical\n }\n }\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAQA,SAAoB;AACpB,WAAsB;AACtB,aAAwB;AAGxB,MAAM,cAAc;AACpB,MAAM,eAAe;AACrB,MAAM,cAAc;AAoBb,MAAM,aAAa;AAAA,EAIxB,YAAY,aAAqB;AAC/B,UAAM,MAAM,KAAK,KAAK,aAAa,WAAW;AAC9C,OAAG,UAAU,KAAK,EAAE,WAAW,KAAK,CAAC;AACrC,SAAK,WAAW,KAAK,KAAK,KAAK,YAAY;AAC3C,SAAK,YAAY,KAAK,qBAAqB,GAAG;AAAA,EAChD;AAAA,EAEQ,qBAAqB,KAAqB;AAChD,UAAM,cAAc,KAAK,KAAK,KAAK,aAAa;AAChD,QAAI;AACF,YAAM,WAAW,GAAG,aAAa,aAAa,MAAM,EAAE,KAAK;AAC3D,UAAI,SAAU,QAAO;AAAA,IACvB,QAAQ;AAAA,IAA2B;AAEnC,UAAM,KAAK,OAAO,YAAY,CAAC,EAAE,SAAS,KAAK;AAC/C,QAAI;AACF,SAAG,cAAc,aAAa,IAAI,MAAM;AAAA,IAC1C,QAAQ;AAAA,IAA4B;AACpC,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA,EAKA,OAAO,SAAiB,gBAAwB,kBAA0B,UAAkB,SAAwD,QAAc;AAChK,UAAM,SAA6B;AAAA,MACjC,WAAW,KAAK,IAAI;AAAA,MACpB,SAAS,QAAQ,MAAM,GAAG,GAAG;AAAA;AAAA,MAC7B;AAAA,MACA;AAAA,MACA;AAAA,MACA,WAAW,KAAK;AAAA,MAChB;AAAA,IACF;A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AM,OAAO,GAAG,SAAS,KAAK,QAAQ;AAEtC,UAAI,KAAK,OAAO,MAAM,MAAM;AAC1B,cAAM,QAAQ,GAAG,aAAa,KAAK,UAAU,MAAM,EAAE,MAAM,IAAI,EAAE,OAAO,OAAK,EAAE,KAAK,CAAC;AACrF,YAAI,MAAM,SAAS,aAAa;AAE9B,gBAAM,OAAO,MAAM,MAAM,CAAC,KAAK,MAAM,cAAc,CAAC,CAAC;AACrD,aAAG,cAAc,KAAK,UAAU,KAAK,KAAK,IAAI,IAAI,MAAM,MAAM;AAAA,QAChE;AAAA,MACF;AAAA,IACF,QAAQ;AAAA,IAER;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/compression/types.ts"],
4
- "sourcesContent": ["/**\n * KiroGraph Shell Compression \u2014 Type Definitions\n */\n\nexport interface CompressionResult {\n /** Compressed output text */\n output: string;\n /** Estimated original token count */\n originalTokens: number;\n /** Estimated compressed token count */\n compressedTokens: number;\n /** Percentage saved (0-100) */\n savings: number;\n /** Which strategy was applied */\n strategy: string;\n /** The detected command family */\n commandFamily: string;\n}\n\nexport interface CompressorOptions {\n /** Compression aggressiveness */\n level: 'normal' | 'aggressive' | 'ultra';\n /** Max output tokens (truncate beyond this) */\n maxOutputTokens?: number;\n /** Never compress error details (default: true) */\n preserveErrors?: boolean;\n}\n\nexport interface FilterResult {\n output: string;\n strategy: string;\n}\n\nexport interface CommandFilter {\n /** Name of this filter family */\n name: string;\n /** Test if this filter handles the given command */\n matches(command: string): boolean;\n /** Apply the filter to raw output */\n filter(command: string, rawOutput: string, level: CompressorOptions['level']): FilterResult;\n}\n\nexport interface TokenSavingsRecord {\n id?: number;\n timestamp: number;\n command: string;\n originalTokens: number;\n compressedTokens: number;\n strategy: string;\n sessionId: string;\n /** Source of the saving: 'exec' for compression, 'graph' for MCP graph tools, 'memory' for memory tools, 'docs' for documentation tools */\n source?: 'exec' | 'graph' | 'memory' | 'docs';\n}\n"],
4
+ "sourcesContent": ["/**\n * KiroGraph Shell Compression \u2014 Type Definitions\n */\n\nexport interface CompressionResult {\n /** Compressed output text */\n output: string;\n /** Estimated original token count */\n originalTokens: number;\n /** Estimated compressed token count */\n compressedTokens: number;\n /** Percentage saved (0-100) */\n savings: number;\n /** Which strategy was applied */\n strategy: string;\n /** The detected command family */\n commandFamily: string;\n}\n\nexport interface CompressorOptions {\n /** Compression aggressiveness */\n level: 'normal' | 'aggressive' | 'ultra';\n /** Max output tokens (truncate beyond this) */\n maxOutputTokens?: number;\n /** Never compress error details (default: true) */\n preserveErrors?: boolean;\n}\n\nexport interface FilterResult {\n output: string;\n strategy: string;\n}\n\nexport interface CommandFilter {\n /** Name of this filter family */\n name: string;\n /** Test if this filter handles the given command */\n matches(command: string): boolean;\n /** Apply the filter to raw output */\n filter(command: string, rawOutput: string, level: CompressorOptions['level']): FilterResult;\n}\n\nexport interface TokenSavingsRecord {\n id?: number;\n timestamp: number;\n command: string;\n originalTokens: number;\n compressedTokens: number;\n strategy: string;\n sessionId: string;\n /** Source of the saving: 'exec' for compression, 'graph' for MCP graph tools, 'memory' for memory tools, 'docs' for documentation tools, 'data' for data tools */\n source?: 'exec' | 'graph' | 'memory' | 'docs' | 'data';\n}\n"],
5
5
  "mappings": ";;;;;;;;;;;;;;AAAA;AAAA;",
6
6
  "names": []
7
7
  }
package/dist/config.js CHANGED
@@ -84,6 +84,15 @@ const KNOWN_FIELDS = /* @__PURE__ */ new Set([
84
84
  "docsContextThreshold",
85
85
  "docsMaxFileSize",
86
86
  "docsSummarization",
87
+ "enableData",
88
+ "dataInclude",
89
+ "dataExclude",
90
+ "dataLinkCode",
91
+ "dataContextLimit",
92
+ "dataMaxFileSize",
93
+ "dataMaxRows",
94
+ "dataQueryLimit",
95
+ "dataMaxResponseTokens",
87
96
  // Legacy aliases (still accepted, mapped during validation)
88
97
  "enableCompression",
89
98
  "compressionLevel"
@@ -133,7 +142,16 @@ function createDefaultConfig(_projectRoot) {
133
142
  docsContextLimit: 0,
134
143
  docsContextThreshold: 0.3,
135
144
  docsMaxFileSize: 1048576,
136
- docsSummarization: "first-sentence"
145
+ docsSummarization: "first-sentence",
146
+ enableData: false,
147
+ dataInclude: ["**/*.csv", "**/*.tsv", "**/*.jsonl", "**/*.ndjson", "**/*.xlsx", "**/*.xls", "**/*.parquet", "data/**/*.json"],
148
+ dataExclude: ["node_modules/**", "dist/**", "build/**", ".git/**", "**/package-lock.json", "**/yarn.lock", "**/pnpm-lock.yaml", "**/tsconfig.json", "**/jsconfig.json", "coverage/**", "**/generated/**"],
149
+ dataLinkCode: true,
150
+ dataContextLimit: 0,
151
+ dataMaxFileSize: 52428800,
152
+ dataMaxRows: 1e6,
153
+ dataQueryLimit: 500,
154
+ dataMaxResponseTokens: 8e3
137
155
  };
138
156
  }
139
157
  function validateConfig(config) {
@@ -196,6 +214,15 @@ function validateConfig(config) {
196
214
  const docsMaxFileSize = typeof raw.docsMaxFileSize === "number" && raw.docsMaxFileSize > 0 ? raw.docsMaxFileSize : defaults.docsMaxFileSize;
197
215
  const DOCS_SUMMARIZATION_MODES = /* @__PURE__ */ new Set(["embedding", "first-sentence", "off"]);
198
216
  const docsSummarization = typeof raw.docsSummarization === "string" && DOCS_SUMMARIZATION_MODES.has(raw.docsSummarization) ? raw.docsSummarization : defaults.docsSummarization;
217
+ const enableData = typeof raw.enableData === "boolean" ? raw.enableData : defaults.enableData;
218
+ const dataInclude = Array.isArray(raw.dataInclude) && raw.dataInclude.every((p) => typeof p === "string") ? raw.dataInclude : defaults.dataInclude;
219
+ const dataExclude = Array.isArray(raw.dataExclude) && raw.dataExclude.every((p) => typeof p === "string") ? raw.dataExclude : defaults.dataExclude;
220
+ const dataLinkCode = typeof raw.dataLinkCode === "boolean" ? raw.dataLinkCode : defaults.dataLinkCode;
221
+ const dataContextLimit = typeof raw.dataContextLimit === "number" && raw.dataContextLimit >= 0 ? Math.round(raw.dataContextLimit) : defaults.dataContextLimit;
222
+ const dataMaxFileSize = typeof raw.dataMaxFileSize === "number" && raw.dataMaxFileSize > 0 ? raw.dataMaxFileSize : defaults.dataMaxFileSize;
223
+ const dataMaxRows = typeof raw.dataMaxRows === "number" && raw.dataMaxRows > 0 ? Math.round(raw.dataMaxRows) : defaults.dataMaxRows;
224
+ const dataQueryLimit = typeof raw.dataQueryLimit === "number" && raw.dataQueryLimit > 0 ? Math.min(Math.round(raw.dataQueryLimit), 500) : defaults.dataQueryLimit;
225
+ const dataMaxResponseTokens = typeof raw.dataMaxResponseTokens === "number" && raw.dataMaxResponseTokens > 0 ? Math.round(raw.dataMaxResponseTokens) : defaults.dataMaxResponseTokens;
199
226
  const include = _validatePatterns(raw.include, defaults.include);
200
227
  const exclude = _validatePatterns(raw.exclude, defaults.exclude);
201
228
  return {
@@ -236,6 +263,15 @@ function validateConfig(config) {
236
263
  docsContextThreshold,
237
264
  docsMaxFileSize,
238
265
  docsSummarization,
266
+ enableData,
267
+ dataInclude,
268
+ dataExclude,
269
+ dataLinkCode,
270
+ dataContextLimit,
271
+ dataMaxFileSize,
272
+ dataMaxRows,
273
+ dataQueryLimit,
274
+ dataMaxResponseTokens,
239
275
  ...architectureLayers !== void 0 ? { architectureLayers } : {}
240
276
  };
241
277
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/config.ts"],
4
- "sourcesContent": ["/**\n * KiroGraph Config System\n *\n * Mirrors CodeGraph src/config.ts \u2014 load, save, validate, and provide defaults\n * for KiroGraph configuration.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport picomatch from 'picomatch';\nimport { logWarn, logError } from './errors';\n\n// \u2500\u2500 Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface KiroGraphConfig {\n version: number;\n languages: string[];\n include: string[];\n exclude: string[];\n maxFileSize: number;\n extractDocstrings: boolean;\n trackCallSites: boolean;\n // Parity fields:\n enableEmbeddings: boolean;\n embeddingModel: string;\n embeddingDim: number;\n /** @deprecated Use semanticEngine instead. Kept for backwards compatibility. */\n useVecIndex: boolean;\n semanticEngine: 'cosine' | 'sqlite-vec' | 'orama' | 'pglite' | 'lancedb' | 'qdrant' | 'typesense';\n typesenseDashboard: boolean;\n qdrantDashboard: boolean;\n minLogLevel: 'debug' | 'info' | 'warn' | 'error';\n frameworkHints: string[];\n fuzzyResolutionThreshold: number; // 0.0\u20131.0\n /** Enable architecture analysis (package graph + layer detection). Default: false. */\n enableArchitecture: boolean;\n /**\n * User-defined layer \u2192 glob pattern overrides.\n * When set, config-defined layers win over auto-detected ones.\n * Example: { \"api\": [\"src/routes/**\", \"src/controllers/**\"] }\n */\n architectureLayers?: Record<string, string[]>;\n /** Agent communication style injected at agentSpawn. Default: 'off'. */\n cavemanMode: 'off' | 'lite' | 'full' | 'ultra';\n /** Shell compression level for kirograph_exec. 'off' disables the hook/steering. Default: 'normal'. */\n shellCompressionLevel: 'off' | 'normal' | 'aggressive' | 'ultra';\n /**\n * Number of pending (unindexed) files above which kirograph_status warns the agent.\n * Set to 0 to disable the warning. Default: 10.\n */\n syncWarningThreshold: number;\n /** Enable persistent cross-session memory. Default: false. */\n enableMemory: boolean;\n /** FTS/vector blend for memory search: 0 = FTS only, 1 = vector only. Default: 0.5. */\n memorySearchAlpha: number;\n /** Store uncompressed originals when caveman is on. Default: false. */\n memoryKeepRaw: boolean;\n /** Auto-prune threshold (max observations). 0 = no limit. Default: 10000. */\n memoryMaxObservations: number;\n /** Seconds of inactivity before auto-closing a session. Default: 7200. */\n memorySessionTimeout: number;\n /** Max observations shown in kirograph_context. Default: 3. */\n memoryContextLimit: number;\n /** Min relevance score to include memory in context. Default: 0.3. */\n memoryContextThreshold: number;\n /** Glob patterns for paths to never capture in memory. Default: []. */\n memoryExcludePatterns: string[];\n /** Enable documentation indexing and navigation. Default: false. */\n enableDocs: boolean;\n /** Glob patterns for documentation files to include. */\n docsInclude: string[];\n /** Glob patterns for documentation files to exclude. */\n docsExclude: string[];\n /** Enable auto-linking of doc sections to code symbols. Default: true. */\n docsLinkCode: boolean;\n /** Max doc sections to include in kirograph_context. 0 = disabled. Default: 0. */\n docsContextLimit: number;\n /** Min relevance score to include a doc section in context. Default: 0.3. */\n docsContextThreshold: number;\n /** Max file size for doc files (bytes). Default: 1MB. */\n docsMaxFileSize: number;\n /** Summarization strategy. Default: 'first-sentence'. */\n docsSummarization: 'embedding' | 'first-sentence' | 'off';\n}\n\n// \u2500\u2500 Constants \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst KIROGRAPH_DIR = '.kirograph';\nconst CONFIG_FILE = 'config.json';\n\nconst KNOWN_FIELDS = new Set<string>([\n 'version', 'languages', 'include', 'exclude', 'maxFileSize',\n 'extractDocstrings', 'trackCallSites', 'enableEmbeddings', 'embeddingModel', 'embeddingDim',\n 'useVecIndex', 'semanticEngine', 'typesenseDashboard', 'qdrantDashboard',\n 'minLogLevel', 'frameworkHints', 'fuzzyResolutionThreshold',\n 'enableArchitecture', 'architectureLayers', 'cavemanMode', 'shellCompressionLevel', 'syncWarningThreshold',\n 'enableMemory', 'memorySearchAlpha', 'memoryKeepRaw', 'memoryMaxObservations',\n 'memorySessionTimeout', 'memoryContextLimit', 'memoryContextThreshold', 'memoryExcludePatterns',\n 'enableDocs', 'docsInclude', 'docsExclude', 'docsLinkCode',\n 'docsContextLimit', 'docsContextThreshold', 'docsMaxFileSize', 'docsSummarization',\n // Legacy aliases (still accepted, mapped during validation)\n 'enableCompression', 'compressionLevel',\n]);\n\nconst LOG_LEVELS = new Set(['debug', 'info', 'warn', 'error']);\n\n// \u2500\u2500 ReDoS-safe regex check \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Returns false if the pattern is potentially dangerous (ReDoS risk) or too long.\n * Checks for catastrophic backtracking patterns like (a+)+ or (a|a)+.\n */\nexport function isSafeRegex(pattern: string): boolean {\n if (pattern.length > 100) return false;\n // Detect nested quantifiers: (x+)+ or (x*)+ or (x+)* etc.\n if (/\\([^)]*[+*][^)]*\\)[+*?]/.test(pattern)) return false;\n // Detect alternation with overlap: (a|a)+ style\n if (/\\([^)]*\\|[^)]*\\)[+*]/.test(pattern)) return false;\n return true;\n}\n\n// \u2500\u2500 Default config \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport function createDefaultConfig(_projectRoot?: string): KiroGraphConfig {\n return {\n version: 2,\n languages: [],\n include: [],\n exclude: ['**/node_modules/**', '**/dist/**', '**/build/**', '**/.git/**', '*.min.js', '**/.kirograph/**'],\n maxFileSize: 1_048_576,\n extractDocstrings: true,\n trackCallSites: true,\n enableEmbeddings: false,\n embeddingModel: 'nomic-ai/nomic-embed-text-v1.5',\n embeddingDim: 768,\n useVecIndex: false,\n semanticEngine: 'cosine',\n typesenseDashboard: false,\n qdrantDashboard: false,\n minLogLevel: 'warn',\n frameworkHints: [],\n fuzzyResolutionThreshold: 0.5,\n enableArchitecture: false,\n cavemanMode: 'off',\n shellCompressionLevel: 'normal',\n syncWarningThreshold: 10,\n enableMemory: false,\n memorySearchAlpha: 0.5,\n memoryKeepRaw: false,\n memoryMaxObservations: 10000,\n memorySessionTimeout: 7200,\n memoryContextLimit: 3,\n memoryContextThreshold: 0.3,\n memoryExcludePatterns: [],\n enableDocs: false,\n docsInclude: ['**/*.md', '**/*.mdx', '**/*.rst', '**/*.adoc', '**/*.asciidoc', '**/*.rdoc', '**/*.org', '**/*.cheatmd', 'docs/**/*.txt', 'docs/**/*.html'],\n docsExclude: ['node_modules/**', '**/CHANGELOG*', '**/LICENSE*', '**/CHANGES*', 'dist/**', 'build/**', 'coverage/**', '.git/**', '**/generated/**', '**/auto-generated/**', '**/vendor/**', '_build/**'],\n docsLinkCode: true,\n docsContextLimit: 0,\n docsContextThreshold: 0.3,\n docsMaxFileSize: 1_048_576,\n docsSummarization: 'first-sentence',\n };\n}\n\n// \u2500\u2500 Validation \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport function validateConfig(config: unknown): KiroGraphConfig {\n const defaults = createDefaultConfig();\n\n if (typeof config !== 'object' || config === null) {\n return defaults;\n }\n\n const raw = config as Record<string, unknown>;\n\n // Warn about unknown fields\n for (const key of Object.keys(raw)) {\n if (!KNOWN_FIELDS.has(key)) {\n logWarn(`Unknown config field: ${key}`);\n }\n }\n\n // Validate and coerce each field\n const version = typeof raw.version === 'number' ? raw.version : defaults.version;\n const languages = Array.isArray(raw.languages) && raw.languages.every(l => typeof l === 'string')\n ? (raw.languages as string[])\n : defaults.languages;\n const maxFileSize = typeof raw.maxFileSize === 'number' && raw.maxFileSize > 0\n ? raw.maxFileSize\n : defaults.maxFileSize;\n const extractDocstrings = typeof raw.extractDocstrings === 'boolean'\n ? raw.extractDocstrings\n : defaults.extractDocstrings;\n const trackCallSites = typeof raw.trackCallSites === 'boolean'\n ? raw.trackCallSites\n : defaults.trackCallSites;\n const enableEmbeddings = typeof raw.enableEmbeddings === 'boolean'\n ? raw.enableEmbeddings\n : defaults.enableEmbeddings;\n const embeddingModel = typeof raw.embeddingModel === 'string' && raw.embeddingModel.length > 0\n ? raw.embeddingModel\n : defaults.embeddingModel;\n const embeddingDim = typeof raw.embeddingDim === 'number' && raw.embeddingDim > 0\n ? raw.embeddingDim\n : defaults.embeddingDim;\n const useVecIndex = typeof raw.useVecIndex === 'boolean'\n ? raw.useVecIndex\n : defaults.useVecIndex;\n const SEMANTIC_ENGINES = new Set(['cosine', 'sqlite-vec', 'orama', 'pglite', 'lancedb', 'qdrant', 'typesense']);\n // useVecIndex is a legacy alias: if set and no explicit semanticEngine, map it\n const semanticEngine = typeof raw.semanticEngine === 'string' && SEMANTIC_ENGINES.has(raw.semanticEngine)\n ? (raw.semanticEngine as KiroGraphConfig['semanticEngine'])\n : useVecIndex ? 'sqlite-vec' : defaults.semanticEngine;\n const typesenseDashboard = typeof raw.typesenseDashboard === 'boolean'\n ? raw.typesenseDashboard\n : defaults.typesenseDashboard;\n const qdrantDashboard = typeof raw.qdrantDashboard === 'boolean'\n ? raw.qdrantDashboard\n : defaults.qdrantDashboard;\n const minLogLevel = typeof raw.minLogLevel === 'string' && LOG_LEVELS.has(raw.minLogLevel)\n ? (raw.minLogLevel as KiroGraphConfig['minLogLevel'])\n : defaults.minLogLevel;\n const frameworkHints = Array.isArray(raw.frameworkHints) && raw.frameworkHints.every(h => typeof h === 'string')\n ? (raw.frameworkHints as string[])\n : defaults.frameworkHints;\n const fuzzyResolutionThreshold = typeof raw.fuzzyResolutionThreshold === 'number'\n && raw.fuzzyResolutionThreshold >= 0\n && raw.fuzzyResolutionThreshold <= 1\n ? raw.fuzzyResolutionThreshold\n : defaults.fuzzyResolutionThreshold;\n const enableArchitecture = typeof raw.enableArchitecture === 'boolean'\n ? raw.enableArchitecture\n : defaults.enableArchitecture;\n const architectureLayers = _validateArchitectureLayers(raw.architectureLayers);\n const CAVEMAN_MODES = new Set(['off', 'lite', 'full', 'ultra']);\n const cavemanMode = typeof raw.cavemanMode === 'string' && CAVEMAN_MODES.has(raw.cavemanMode)\n ? (raw.cavemanMode as KiroGraphConfig['cavemanMode'])\n : defaults.cavemanMode;\n const COMPRESSION_LEVELS = new Set(['off', 'normal', 'aggressive', 'ultra']);\n // Support legacy field names: enableCompression (boolean) and compressionLevel (string)\n let shellCompressionLevel: KiroGraphConfig['shellCompressionLevel'];\n if (typeof raw.shellCompressionLevel === 'string' && COMPRESSION_LEVELS.has(raw.shellCompressionLevel)) {\n shellCompressionLevel = raw.shellCompressionLevel as KiroGraphConfig['shellCompressionLevel'];\n } else if (typeof raw.compressionLevel === 'string' && COMPRESSION_LEVELS.has(raw.compressionLevel)) {\n shellCompressionLevel = raw.compressionLevel as KiroGraphConfig['shellCompressionLevel'];\n } else if (typeof raw.enableCompression === 'boolean') {\n shellCompressionLevel = raw.enableCompression ? 'normal' : 'off';\n } else {\n shellCompressionLevel = defaults.shellCompressionLevel;\n }\n const syncWarningThreshold = typeof raw.syncWarningThreshold === 'number' && raw.syncWarningThreshold >= 0\n ? Math.round(raw.syncWarningThreshold)\n : defaults.syncWarningThreshold;\n\n // \u2500\u2500 Memory config \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const enableMemory = typeof raw.enableMemory === 'boolean'\n ? raw.enableMemory\n : defaults.enableMemory;\n const memorySearchAlpha = typeof raw.memorySearchAlpha === 'number'\n && raw.memorySearchAlpha >= 0 && raw.memorySearchAlpha <= 1\n ? raw.memorySearchAlpha\n : defaults.memorySearchAlpha;\n const memoryKeepRaw = typeof raw.memoryKeepRaw === 'boolean'\n ? raw.memoryKeepRaw\n : defaults.memoryKeepRaw;\n const memoryMaxObservations = typeof raw.memoryMaxObservations === 'number' && raw.memoryMaxObservations >= 0\n ? Math.round(raw.memoryMaxObservations)\n : defaults.memoryMaxObservations;\n const memorySessionTimeout = typeof raw.memorySessionTimeout === 'number' && raw.memorySessionTimeout > 0\n ? Math.round(raw.memorySessionTimeout)\n : defaults.memorySessionTimeout;\n const memoryContextLimit = typeof raw.memoryContextLimit === 'number' && raw.memoryContextLimit >= 0\n ? Math.round(raw.memoryContextLimit)\n : defaults.memoryContextLimit;\n const memoryContextThreshold = typeof raw.memoryContextThreshold === 'number'\n && raw.memoryContextThreshold >= 0 && raw.memoryContextThreshold <= 1\n ? raw.memoryContextThreshold\n : defaults.memoryContextThreshold;\n const memoryExcludePatterns = Array.isArray(raw.memoryExcludePatterns)\n && raw.memoryExcludePatterns.every((p: unknown) => typeof p === 'string')\n ? (raw.memoryExcludePatterns as string[])\n : defaults.memoryExcludePatterns;\n\n // \u2500\u2500 Docs config \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const enableDocs = typeof raw.enableDocs === 'boolean'\n ? raw.enableDocs\n : defaults.enableDocs;\n const docsInclude = Array.isArray(raw.docsInclude)\n && raw.docsInclude.every((p: unknown) => typeof p === 'string')\n ? (raw.docsInclude as string[])\n : defaults.docsInclude;\n const docsExclude = Array.isArray(raw.docsExclude)\n && raw.docsExclude.every((p: unknown) => typeof p === 'string')\n ? (raw.docsExclude as string[])\n : defaults.docsExclude;\n const docsLinkCode = typeof raw.docsLinkCode === 'boolean'\n ? raw.docsLinkCode\n : defaults.docsLinkCode;\n const docsContextLimit = typeof raw.docsContextLimit === 'number' && raw.docsContextLimit >= 0\n ? Math.round(raw.docsContextLimit)\n : defaults.docsContextLimit;\n const docsContextThreshold = typeof raw.docsContextThreshold === 'number'\n && raw.docsContextThreshold >= 0 && raw.docsContextThreshold <= 1\n ? raw.docsContextThreshold\n : defaults.docsContextThreshold;\n const docsMaxFileSize = typeof raw.docsMaxFileSize === 'number' && raw.docsMaxFileSize > 0\n ? raw.docsMaxFileSize\n : defaults.docsMaxFileSize;\n const DOCS_SUMMARIZATION_MODES = new Set(['embedding', 'first-sentence', 'off']);\n const docsSummarization = typeof raw.docsSummarization === 'string' && DOCS_SUMMARIZATION_MODES.has(raw.docsSummarization)\n ? (raw.docsSummarization as KiroGraphConfig['docsSummarization'])\n : defaults.docsSummarization;\n\n // Validate glob patterns \u2014 exclude unsafe regex patterns\n const include = _validatePatterns(raw.include, defaults.include);\n const exclude = _validatePatterns(raw.exclude, defaults.exclude);\n\n return {\n version,\n languages,\n include,\n exclude,\n maxFileSize,\n extractDocstrings,\n trackCallSites,\n enableEmbeddings,\n embeddingModel,\n embeddingDim,\n useVecIndex,\n semanticEngine,\n typesenseDashboard,\n qdrantDashboard,\n minLogLevel,\n frameworkHints,\n fuzzyResolutionThreshold,\n enableArchitecture,\n cavemanMode,\n shellCompressionLevel,\n syncWarningThreshold,\n enableMemory,\n memorySearchAlpha,\n memoryKeepRaw,\n memoryMaxObservations,\n memorySessionTimeout,\n memoryContextLimit,\n memoryContextThreshold,\n memoryExcludePatterns,\n enableDocs,\n docsInclude,\n docsExclude,\n docsLinkCode,\n docsContextLimit,\n docsContextThreshold,\n docsMaxFileSize,\n docsSummarization,\n ...(architectureLayers !== undefined ? { architectureLayers } : {}),\n };\n}\n\nfunction _validateArchitectureLayers(raw: unknown): Record<string, string[]> | undefined {\n if (raw === undefined || raw === null) return undefined;\n if (typeof raw !== 'object' || Array.isArray(raw)) return undefined;\n const result: Record<string, string[]> = {};\n for (const [key, val] of Object.entries(raw as Record<string, unknown>)) {\n if (typeof key !== 'string') continue;\n if (!Array.isArray(val)) continue;\n const patterns = val.filter((p): p is string => typeof p === 'string' && isSafeRegex(p));\n if (patterns.length > 0) result[key] = patterns;\n }\n return Object.keys(result).length > 0 ? result : undefined;\n}\n\nfunction _validatePatterns(raw: unknown, fallback: string[]): string[] {\n if (!Array.isArray(raw)) return fallback;\n const valid: string[] = [];\n for (const p of raw) {\n if (typeof p !== 'string') continue;\n if (!isSafeRegex(p)) {\n logWarn(`Unsafe regex pattern skipped: ${p}`);\n continue;\n }\n valid.push(p);\n }\n return valid;\n}\n\n// \u2500\u2500 Migration helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Upgrades shallow exclude patterns (e.g. \"node_modules/**\") to recursive ones\n * (e.g. \"** /node_modules/**\") so nested directories are excluded at any depth.\n */\nconst SHALLOW_TO_RECURSIVE: Record<string, string> = {\n 'node_modules/**': '**/node_modules/**',\n 'dist/**': '**/dist/**',\n 'build/**': '**/build/**',\n '.git/**': '**/.git/**',\n '.kirograph/**': '**/.kirograph/**',\n};\n\nfunction migrateExcludePatterns(patterns: string[]): string[] {\n return patterns.map(p => SHALLOW_TO_RECURSIVE[p] ?? p);\n}\n\n// \u2500\u2500 Load / Save \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport async function loadConfig(projectRoot: string): Promise<KiroGraphConfig> {\n const dir = path.join(projectRoot, KIROGRAPH_DIR);\n const cfgPath = path.join(dir, CONFIG_FILE);\n\n if (!fs.existsSync(cfgPath)) {\n // Create default config file\n const defaults = createDefaultConfig(projectRoot);\n await fs.promises.mkdir(dir, { recursive: true });\n await _writeAtomic(cfgPath, defaults);\n return defaults;\n }\n\n let raw: unknown;\n try {\n const text = await fs.promises.readFile(cfgPath, 'utf8');\n raw = JSON.parse(text);\n } catch (err) {\n logError('Config parse error', { path: cfgPath, error: err instanceof Error ? err.message : String(err) });\n return createDefaultConfig(projectRoot);\n }\n\n const config = validateConfig(raw);\n\n // Migrate v1 \u2192 v2: upgrade shallow exclude patterns to recursive\n if (config.version < 2) {\n config.version = 2;\n config.exclude = migrateExcludePatterns(config.exclude);\n await fs.promises.mkdir(dir, { recursive: true });\n await _writeAtomic(cfgPath, config);\n }\n\n return config;\n}\n\nexport async function saveConfig(projectRoot: string, config: KiroGraphConfig): Promise<void> {\n const dir = path.join(projectRoot, KIROGRAPH_DIR);\n const cfgPath = path.join(dir, CONFIG_FILE);\n await fs.promises.mkdir(dir, { recursive: true });\n await _writeAtomic(cfgPath, config);\n}\n\nasync function _writeAtomic(cfgPath: string, config: KiroGraphConfig): Promise<void> {\n const tmp = cfgPath + '.tmp';\n await fs.promises.writeFile(tmp, JSON.stringify(config, null, 2), 'utf8');\n await fs.promises.rename(tmp, cfgPath);\n}\n\n// \u2500\u2500 Update helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport async function updateConfig(\n projectRoot: string,\n patch: Partial<KiroGraphConfig>\n): Promise<KiroGraphConfig> {\n const current = await loadConfig(projectRoot);\n const updated = validateConfig({ ...current, ...patch });\n await saveConfig(projectRoot, updated);\n return updated;\n}\n\nexport async function addIncludePatterns(projectRoot: string, patterns: string[]): Promise<void> {\n const config = await loadConfig(projectRoot);\n const existing = new Set(config.include);\n const toAdd = patterns.filter(p => isSafeRegex(p) && !existing.has(p));\n if (toAdd.length === 0) return;\n await saveConfig(projectRoot, { ...config, include: [...config.include, ...toAdd] });\n}\n\nexport async function addExcludePatterns(projectRoot: string, patterns: string[]): Promise<void> {\n const config = await loadConfig(projectRoot);\n const existing = new Set(config.exclude);\n const toAdd = patterns.filter(p => isSafeRegex(p) && !existing.has(p));\n if (toAdd.length === 0) return;\n await saveConfig(projectRoot, { ...config, exclude: [...config.exclude, ...toAdd] });\n}\n\n// \u2500\u2500 File inclusion check \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport function shouldIncludeFile(config: KiroGraphConfig, relPath: string): boolean {\n // Check exclude patterns first\n for (const pattern of config.exclude) {\n if (picomatch(pattern)(relPath)) return false;\n }\n // If include patterns are specified, file must match at least one\n if (config.include.length > 0) {\n return config.include.some(pattern => picomatch(pattern)(relPath));\n }\n return true;\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,SAAoB;AACpB,WAAsB;AACtB,uBAAsB;AACtB,oBAAkC;AA6ElC,MAAM,gBAAgB;AACtB,MAAM,cAAc;AAEpB,MAAM,eAAe,oBAAI,IAAY;AAAA,EACnC;AAAA,EAAW;AAAA,EAAa;AAAA,EAAW;AAAA,EAAW;AAAA,EAC9C;AAAA,EAAqB;AAAA,EAAkB;AAAA,EAAoB;AAAA,EAAkB;AAAA,EAC7E;AAAA,EAAe;AAAA,EAAkB;AAAA,EAAsB;AAAA,EACvD;AAAA,EAAe;AAAA,EAAkB;AAAA,EACjC;AAAA,EAAsB;AAAA,EAAsB;AAAA,EAAe;AAAA,EAAyB;AAAA,EACpF;AAAA,EAAgB;AAAA,EAAqB;AAAA,EAAiB;AAAA,EACtD;AAAA,EAAwB;AAAA,EAAsB;AAAA,EAA0B;AAAA,EACxE;AAAA,EAAc;AAAA,EAAe;AAAA,EAAe;AAA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C,GAAG,OAAO,SAAS,GAAG,KAAK,EAAE,CAAC;AACrF;AAEA,eAAsB,mBAAmB,aAAqB,UAAmC;AAC/F,QAAM,SAAS,MAAM,WAAW,WAAW;AAC3C,QAAM,WAAW,IAAI,IAAI,OAAO,OAAO;AACvC,QAAM,QAAQ,SAAS,OAAO,OAAK,YAAY,CAAC,KAAK,CAAC,SAAS,IAAI,CAAC,CAAC;AACrE,MAAI,MAAM,WAAW,EAAG;AACxB,QAAM,WAAW,aAAa,EAAE,GAAG,QAAQ,SAAS,CAAC,GAAG,OAAO,SAAS,GAAG,KAAK,EAAE,CAAC;AACrF;AAIO,SAAS,kBAAkB,QAAyB,SAA0B;AAEnF,aAAW,WAAW,OAAO,SAAS;AACpC,YAAI,iBAAAA,SAAU,OAAO,EAAE,OAAO,EAAG,QAAO;AAAA,EAC1C;AAEA,MAAI,OAAO,QAAQ,SAAS,GAAG;AAC7B,WAAO,OAAO,QAAQ,KAAK,iBAAW,iBAAAA,SAAU,OAAO,EAAE,OAAO,CAAC;AAAA,EACnE;AACA,SAAO;AACT;",
4
+ "sourcesContent": ["/**\n * KiroGraph Config System\n *\n * Mirrors CodeGraph src/config.ts \u2014 load, save, validate, and provide defaults\n * for KiroGraph configuration.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport picomatch from 'picomatch';\nimport { logWarn, logError } from './errors';\n\n// \u2500\u2500 Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface KiroGraphConfig {\n version: number;\n languages: string[];\n include: string[];\n exclude: string[];\n maxFileSize: number;\n extractDocstrings: boolean;\n trackCallSites: boolean;\n // Parity fields:\n enableEmbeddings: boolean;\n embeddingModel: string;\n embeddingDim: number;\n /** @deprecated Use semanticEngine instead. Kept for backwards compatibility. */\n useVecIndex: boolean;\n semanticEngine: 'cosine' | 'sqlite-vec' | 'orama' | 'pglite' | 'lancedb' | 'qdrant' | 'typesense';\n typesenseDashboard: boolean;\n qdrantDashboard: boolean;\n minLogLevel: 'debug' | 'info' | 'warn' | 'error';\n frameworkHints: string[];\n fuzzyResolutionThreshold: number; // 0.0\u20131.0\n /** Enable architecture analysis (package graph + layer detection). Default: false. */\n enableArchitecture: boolean;\n /**\n * User-defined layer \u2192 glob pattern overrides.\n * When set, config-defined layers win over auto-detected ones.\n * Example: { \"api\": [\"src/routes/**\", \"src/controllers/**\"] }\n */\n architectureLayers?: Record<string, string[]>;\n /** Agent communication style injected at agentSpawn. Default: 'off'. */\n cavemanMode: 'off' | 'lite' | 'full' | 'ultra';\n /** Shell compression level for kirograph_exec. 'off' disables the hook/steering. Default: 'normal'. */\n shellCompressionLevel: 'off' | 'normal' | 'aggressive' | 'ultra';\n /**\n * Number of pending (unindexed) files above which kirograph_status warns the agent.\n * Set to 0 to disable the warning. Default: 10.\n */\n syncWarningThreshold: number;\n /** Enable persistent cross-session memory. Default: false. */\n enableMemory: boolean;\n /** FTS/vector blend for memory search: 0 = FTS only, 1 = vector only. Default: 0.5. */\n memorySearchAlpha: number;\n /** Store uncompressed originals when caveman is on. Default: false. */\n memoryKeepRaw: boolean;\n /** Auto-prune threshold (max observations). 0 = no limit. Default: 10000. */\n memoryMaxObservations: number;\n /** Seconds of inactivity before auto-closing a session. Default: 7200. */\n memorySessionTimeout: number;\n /** Max observations shown in kirograph_context. Default: 3. */\n memoryContextLimit: number;\n /** Min relevance score to include memory in context. Default: 0.3. */\n memoryContextThreshold: number;\n /** Glob patterns for paths to never capture in memory. Default: []. */\n memoryExcludePatterns: string[];\n /** Enable documentation indexing and navigation. Default: false. */\n enableDocs: boolean;\n /** Glob patterns for documentation files to include. */\n docsInclude: string[];\n /** Glob patterns for documentation files to exclude. */\n docsExclude: string[];\n /** Enable auto-linking of doc sections to code symbols. Default: true. */\n docsLinkCode: boolean;\n /** Max doc sections to include in kirograph_context. 0 = disabled. Default: 0. */\n docsContextLimit: number;\n /** Min relevance score to include a doc section in context. Default: 0.3. */\n docsContextThreshold: number;\n /** Max file size for doc files (bytes). Default: 1MB. */\n docsMaxFileSize: number;\n /** Summarization strategy. Default: 'first-sentence'. */\n docsSummarization: 'embedding' | 'first-sentence' | 'off';\n /** Enable tabular data indexing and querying. Default: false. */\n enableData: boolean;\n /** Glob patterns for data files to include. */\n dataInclude: string[];\n /** Glob patterns for data files to exclude. */\n dataExclude: string[];\n /** Enable auto-linking of data files to code symbols. Default: true. */\n dataLinkCode: boolean;\n /** Max datasets to include in kirograph_context. 0 = disabled. Default: 0. */\n dataContextLimit: number;\n /** Max file size for data files (bytes). Default: 50MB. */\n dataMaxFileSize: number;\n /** Max rows to index per file. Default: 1,000,000. */\n dataMaxRows: number;\n /** Max rows returned per query. Default: 500. */\n dataQueryLimit: number;\n /** Max token budget per response. Default: 8000. */\n dataMaxResponseTokens: number;\n}\n\n// \u2500\u2500 Constants \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst KIROGRAPH_DIR = '.kirograph';\nconst CONFIG_FILE = 'config.json';\n\nconst KNOWN_FIELDS = new Set<string>([\n 'version', 'languages', 'include', 'exclude', 'maxFileSize',\n 'extractDocstrings', 'trackCallSites', 'enableEmbeddings', 'embeddingModel', 'embeddingDim',\n 'useVecIndex', 'semanticEngine', 'typesenseDashboard', 'qdrantDashboard',\n 'minLogLevel', 'frameworkHints', 'fuzzyResolutionThreshold',\n 'enableArchitecture', 'architectureLayers', 'cavemanMode', 'shellCompressionLevel', 'syncWarningThreshold',\n 'enableMemory', 'memorySearchAlpha', 'memoryKeepRaw', 'memoryMaxObservations',\n 'memorySessionTimeout', 'memoryContextLimit', 'memoryContextThreshold', 'memoryExcludePatterns',\n 'enableDocs', 'docsInclude', 'docsExclude', 'docsLinkCode',\n 'docsContextLimit', 'docsContextThreshold', 'docsMaxFileSize', 'docsSummarization',\n 'enableData', 'dataInclude', 'dataExclude', 'dataLinkCode',\n 'dataContextLimit', 'dataMaxFileSize', 'dataMaxRows', 'dataQueryLimit', 'dataMaxResponseTokens',\n // Legacy aliases (still accepted, mapped during validation)\n 'enableCompression', 'compressionLevel',\n]);\n\nconst LOG_LEVELS = new Set(['debug', 'info', 'warn', 'error']);\n\n// \u2500\u2500 ReDoS-safe regex check \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Returns false if the pattern is potentially dangerous (ReDoS risk) or too long.\n * Checks for catastrophic backtracking patterns like (a+)+ or (a|a)+.\n */\nexport function isSafeRegex(pattern: string): boolean {\n if (pattern.length > 100) return false;\n // Detect nested quantifiers: (x+)+ or (x*)+ or (x+)* etc.\n if (/\\([^)]*[+*][^)]*\\)[+*?]/.test(pattern)) return false;\n // Detect alternation with overlap: (a|a)+ style\n if (/\\([^)]*\\|[^)]*\\)[+*]/.test(pattern)) return false;\n return true;\n}\n\n// \u2500\u2500 Default config \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport function createDefaultConfig(_projectRoot?: string): KiroGraphConfig {\n return {\n version: 2,\n languages: [],\n include: [],\n exclude: ['**/node_modules/**', '**/dist/**', '**/build/**', '**/.git/**', '*.min.js', '**/.kirograph/**'],\n maxFileSize: 1_048_576,\n extractDocstrings: true,\n trackCallSites: true,\n enableEmbeddings: false,\n embeddingModel: 'nomic-ai/nomic-embed-text-v1.5',\n embeddingDim: 768,\n useVecIndex: false,\n semanticEngine: 'cosine',\n typesenseDashboard: false,\n qdrantDashboard: false,\n minLogLevel: 'warn',\n frameworkHints: [],\n fuzzyResolutionThreshold: 0.5,\n enableArchitecture: false,\n cavemanMode: 'off',\n shellCompressionLevel: 'normal',\n syncWarningThreshold: 10,\n enableMemory: false,\n memorySearchAlpha: 0.5,\n memoryKeepRaw: false,\n memoryMaxObservations: 10000,\n memorySessionTimeout: 7200,\n memoryContextLimit: 3,\n memoryContextThreshold: 0.3,\n memoryExcludePatterns: [],\n enableDocs: false,\n docsInclude: ['**/*.md', '**/*.mdx', '**/*.rst', '**/*.adoc', '**/*.asciidoc', '**/*.rdoc', '**/*.org', '**/*.cheatmd', 'docs/**/*.txt', 'docs/**/*.html'],\n docsExclude: ['node_modules/**', '**/CHANGELOG*', '**/LICENSE*', '**/CHANGES*', 'dist/**', 'build/**', 'coverage/**', '.git/**', '**/generated/**', '**/auto-generated/**', '**/vendor/**', '_build/**'],\n docsLinkCode: true,\n docsContextLimit: 0,\n docsContextThreshold: 0.3,\n docsMaxFileSize: 1_048_576,\n docsSummarization: 'first-sentence',\n enableData: false,\n dataInclude: ['**/*.csv', '**/*.tsv', '**/*.jsonl', '**/*.ndjson', '**/*.xlsx', '**/*.xls', '**/*.parquet', 'data/**/*.json'],\n dataExclude: ['node_modules/**', 'dist/**', 'build/**', '.git/**', '**/package-lock.json', '**/yarn.lock', '**/pnpm-lock.yaml', '**/tsconfig.json', '**/jsconfig.json', 'coverage/**', '**/generated/**'],\n dataLinkCode: true,\n dataContextLimit: 0,\n dataMaxFileSize: 52_428_800,\n dataMaxRows: 1_000_000,\n dataQueryLimit: 500,\n dataMaxResponseTokens: 8000,\n };\n}\n\n// \u2500\u2500 Validation \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport function validateConfig(config: unknown): KiroGraphConfig {\n const defaults = createDefaultConfig();\n\n if (typeof config !== 'object' || config === null) {\n return defaults;\n }\n\n const raw = config as Record<string, unknown>;\n\n // Warn about unknown fields\n for (const key of Object.keys(raw)) {\n if (!KNOWN_FIELDS.has(key)) {\n logWarn(`Unknown config field: ${key}`);\n }\n }\n\n // Validate and coerce each field\n const version = typeof raw.version === 'number' ? raw.version : defaults.version;\n const languages = Array.isArray(raw.languages) && raw.languages.every(l => typeof l === 'string')\n ? (raw.languages as string[])\n : defaults.languages;\n const maxFileSize = typeof raw.maxFileSize === 'number' && raw.maxFileSize > 0\n ? raw.maxFileSize\n : defaults.maxFileSize;\n const extractDocstrings = typeof raw.extractDocstrings === 'boolean'\n ? raw.extractDocstrings\n : defaults.extractDocstrings;\n const trackCallSites = typeof raw.trackCallSites === 'boolean'\n ? raw.trackCallSites\n : defaults.trackCallSites;\n const enableEmbeddings = typeof raw.enableEmbeddings === 'boolean'\n ? raw.enableEmbeddings\n : defaults.enableEmbeddings;\n const embeddingModel = typeof raw.embeddingModel === 'string' && raw.embeddingModel.length > 0\n ? raw.embeddingModel\n : defaults.embeddingModel;\n const embeddingDim = typeof raw.embeddingDim === 'number' && raw.embeddingDim > 0\n ? raw.embeddingDim\n : defaults.embeddingDim;\n const useVecIndex = typeof raw.useVecIndex === 'boolean'\n ? raw.useVecIndex\n : defaults.useVecIndex;\n const SEMANTIC_ENGINES = new Set(['cosine', 'sqlite-vec', 'orama', 'pglite', 'lancedb', 'qdrant', 'typesense']);\n // useVecIndex is a legacy alias: if set and no explicit semanticEngine, map it\n const semanticEngine = typeof raw.semanticEngine === 'string' && SEMANTIC_ENGINES.has(raw.semanticEngine)\n ? (raw.semanticEngine as KiroGraphConfig['semanticEngine'])\n : useVecIndex ? 'sqlite-vec' : defaults.semanticEngine;\n const typesenseDashboard = typeof raw.typesenseDashboard === 'boolean'\n ? raw.typesenseDashboard\n : defaults.typesenseDashboard;\n const qdrantDashboard = typeof raw.qdrantDashboard === 'boolean'\n ? raw.qdrantDashboard\n : defaults.qdrantDashboard;\n const minLogLevel = typeof raw.minLogLevel === 'string' && LOG_LEVELS.has(raw.minLogLevel)\n ? (raw.minLogLevel as KiroGraphConfig['minLogLevel'])\n : defaults.minLogLevel;\n const frameworkHints = Array.isArray(raw.frameworkHints) && raw.frameworkHints.every(h => typeof h === 'string')\n ? (raw.frameworkHints as string[])\n : defaults.frameworkHints;\n const fuzzyResolutionThreshold = typeof raw.fuzzyResolutionThreshold === 'number'\n && raw.fuzzyResolutionThreshold >= 0\n && raw.fuzzyResolutionThreshold <= 1\n ? raw.fuzzyResolutionThreshold\n : defaults.fuzzyResolutionThreshold;\n const enableArchitecture = typeof raw.enableArchitecture === 'boolean'\n ? raw.enableArchitecture\n : defaults.enableArchitecture;\n const architectureLayers = _validateArchitectureLayers(raw.architectureLayers);\n const CAVEMAN_MODES = new Set(['off', 'lite', 'full', 'ultra']);\n const cavemanMode = typeof raw.cavemanMode === 'string' && CAVEMAN_MODES.has(raw.cavemanMode)\n ? (raw.cavemanMode as KiroGraphConfig['cavemanMode'])\n : defaults.cavemanMode;\n const COMPRESSION_LEVELS = new Set(['off', 'normal', 'aggressive', 'ultra']);\n // Support legacy field names: enableCompression (boolean) and compressionLevel (string)\n let shellCompressionLevel: KiroGraphConfig['shellCompressionLevel'];\n if (typeof raw.shellCompressionLevel === 'string' && COMPRESSION_LEVELS.has(raw.shellCompressionLevel)) {\n shellCompressionLevel = raw.shellCompressionLevel as KiroGraphConfig['shellCompressionLevel'];\n } else if (typeof raw.compressionLevel === 'string' && COMPRESSION_LEVELS.has(raw.compressionLevel)) {\n shellCompressionLevel = raw.compressionLevel as KiroGraphConfig['shellCompressionLevel'];\n } else if (typeof raw.enableCompression === 'boolean') {\n shellCompressionLevel = raw.enableCompression ? 'normal' : 'off';\n } else {\n shellCompressionLevel = defaults.shellCompressionLevel;\n }\n const syncWarningThreshold = typeof raw.syncWarningThreshold === 'number' && raw.syncWarningThreshold >= 0\n ? Math.round(raw.syncWarningThreshold)\n : defaults.syncWarningThreshold;\n\n // \u2500\u2500 Memory config \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const enableMemory = typeof raw.enableMemory === 'boolean'\n ? raw.enableMemory\n : defaults.enableMemory;\n const memorySearchAlpha = typeof raw.memorySearchAlpha === 'number'\n && raw.memorySearchAlpha >= 0 && raw.memorySearchAlpha <= 1\n ? raw.memorySearchAlpha\n : defaults.memorySearchAlpha;\n const memoryKeepRaw = typeof raw.memoryKeepRaw === 'boolean'\n ? raw.memoryKeepRaw\n : defaults.memoryKeepRaw;\n const memoryMaxObservations = typeof raw.memoryMaxObservations === 'number' && raw.memoryMaxObservations >= 0\n ? Math.round(raw.memoryMaxObservations)\n : defaults.memoryMaxObservations;\n const memorySessionTimeout = typeof raw.memorySessionTimeout === 'number' && raw.memorySessionTimeout > 0\n ? Math.round(raw.memorySessionTimeout)\n : defaults.memorySessionTimeout;\n const memoryContextLimit = typeof raw.memoryContextLimit === 'number' && raw.memoryContextLimit >= 0\n ? Math.round(raw.memoryContextLimit)\n : defaults.memoryContextLimit;\n const memoryContextThreshold = typeof raw.memoryContextThreshold === 'number'\n && raw.memoryContextThreshold >= 0 && raw.memoryContextThreshold <= 1\n ? raw.memoryContextThreshold\n : defaults.memoryContextThreshold;\n const memoryExcludePatterns = Array.isArray(raw.memoryExcludePatterns)\n && raw.memoryExcludePatterns.every((p: unknown) => typeof p === 'string')\n ? (raw.memoryExcludePatterns as string[])\n : defaults.memoryExcludePatterns;\n\n // \u2500\u2500 Docs config \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const enableDocs = typeof raw.enableDocs === 'boolean'\n ? raw.enableDocs\n : defaults.enableDocs;\n const docsInclude = Array.isArray(raw.docsInclude)\n && raw.docsInclude.every((p: unknown) => typeof p === 'string')\n ? (raw.docsInclude as string[])\n : defaults.docsInclude;\n const docsExclude = Array.isArray(raw.docsExclude)\n && raw.docsExclude.every((p: unknown) => typeof p === 'string')\n ? (raw.docsExclude as string[])\n : defaults.docsExclude;\n const docsLinkCode = typeof raw.docsLinkCode === 'boolean'\n ? raw.docsLinkCode\n : defaults.docsLinkCode;\n const docsContextLimit = typeof raw.docsContextLimit === 'number' && raw.docsContextLimit >= 0\n ? Math.round(raw.docsContextLimit)\n : defaults.docsContextLimit;\n const docsContextThreshold = typeof raw.docsContextThreshold === 'number'\n && raw.docsContextThreshold >= 0 && raw.docsContextThreshold <= 1\n ? raw.docsContextThreshold\n : defaults.docsContextThreshold;\n const docsMaxFileSize = typeof raw.docsMaxFileSize === 'number' && raw.docsMaxFileSize > 0\n ? raw.docsMaxFileSize\n : defaults.docsMaxFileSize;\n const DOCS_SUMMARIZATION_MODES = new Set(['embedding', 'first-sentence', 'off']);\n const docsSummarization = typeof raw.docsSummarization === 'string' && DOCS_SUMMARIZATION_MODES.has(raw.docsSummarization)\n ? (raw.docsSummarization as KiroGraphConfig['docsSummarization'])\n : defaults.docsSummarization;\n\n // \u2500\u2500 Data config \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const enableData = typeof raw.enableData === 'boolean' ? raw.enableData : defaults.enableData;\n const dataInclude = Array.isArray(raw.dataInclude) && raw.dataInclude.every((p: unknown) => typeof p === 'string')\n ? (raw.dataInclude as string[]) : defaults.dataInclude;\n const dataExclude = Array.isArray(raw.dataExclude) && raw.dataExclude.every((p: unknown) => typeof p === 'string')\n ? (raw.dataExclude as string[]) : defaults.dataExclude;\n const dataLinkCode = typeof raw.dataLinkCode === 'boolean' ? raw.dataLinkCode : defaults.dataLinkCode;\n const dataContextLimit = typeof raw.dataContextLimit === 'number' && raw.dataContextLimit >= 0\n ? Math.round(raw.dataContextLimit) : defaults.dataContextLimit;\n const dataMaxFileSize = typeof raw.dataMaxFileSize === 'number' && raw.dataMaxFileSize > 0\n ? raw.dataMaxFileSize : defaults.dataMaxFileSize;\n const dataMaxRows = typeof raw.dataMaxRows === 'number' && raw.dataMaxRows > 0\n ? Math.round(raw.dataMaxRows) : defaults.dataMaxRows;\n const dataQueryLimit = typeof raw.dataQueryLimit === 'number' && raw.dataQueryLimit > 0\n ? Math.min(Math.round(raw.dataQueryLimit), 500) : defaults.dataQueryLimit;\n const dataMaxResponseTokens = typeof raw.dataMaxResponseTokens === 'number' && raw.dataMaxResponseTokens > 0\n ? Math.round(raw.dataMaxResponseTokens) : defaults.dataMaxResponseTokens;\n\n // Validate glob patterns \u2014 exclude unsafe regex patterns\n const include = _validatePatterns(raw.include, defaults.include);\n const exclude = _validatePatterns(raw.exclude, defaults.exclude);\n\n return {\n version,\n languages,\n include,\n exclude,\n maxFileSize,\n extractDocstrings,\n trackCallSites,\n enableEmbeddings,\n embeddingModel,\n embeddingDim,\n useVecIndex,\n semanticEngine,\n typesenseDashboard,\n qdrantDashboard,\n minLogLevel,\n frameworkHints,\n fuzzyResolutionThreshold,\n enableArchitecture,\n cavemanMode,\n shellCompressionLevel,\n syncWarningThreshold,\n enableMemory,\n memorySearchAlpha,\n memoryKeepRaw,\n memoryMaxObservations,\n memorySessionTimeout,\n memoryContextLimit,\n memoryContextThreshold,\n memoryExcludePatterns,\n enableDocs,\n docsInclude,\n docsExclude,\n docsLinkCode,\n docsContextLimit,\n docsContextThreshold,\n docsMaxFileSize,\n docsSummarization,\n enableData,\n dataInclude,\n dataExclude,\n dataLinkCode,\n dataContextLimit,\n dataMaxFileSize,\n dataMaxRows,\n dataQueryLimit,\n dataMaxResponseTokens,\n ...(architectureLayers !== undefined ? { architectureLayers } : {}),\n };\n}\n\nfunction _validateArchitectureLayers(raw: unknown): Record<string, string[]> | undefined {\n if (raw === undefined || raw === null) return undefined;\n if (typeof raw !== 'object' || Array.isArray(raw)) return undefined;\n const result: Record<string, string[]> = {};\n for (const [key, val] of Object.entries(raw as Record<string, unknown>)) {\n if (typeof key !== 'string') continue;\n if (!Array.isArray(val)) continue;\n const patterns = val.filter((p): p is string => typeof p === 'string' && isSafeRegex(p));\n if (patterns.length > 0) result[key] = patterns;\n }\n return Object.keys(result).length > 0 ? result : undefined;\n}\n\nfunction _validatePatterns(raw: unknown, fallback: string[]): string[] {\n if (!Array.isArray(raw)) return fallback;\n const valid: string[] = [];\n for (const p of raw) {\n if (typeof p !== 'string') continue;\n if (!isSafeRegex(p)) {\n logWarn(`Unsafe regex pattern skipped: ${p}`);\n continue;\n }\n valid.push(p);\n }\n return valid;\n}\n\n// \u2500\u2500 Migration helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Upgrades shallow exclude patterns (e.g. \"node_modules/**\") to recursive ones\n * (e.g. \"** /node_modules/**\") so nested directories are excluded at any depth.\n */\nconst SHALLOW_TO_RECURSIVE: Record<string, string> = {\n 'node_modules/**': '**/node_modules/**',\n 'dist/**': '**/dist/**',\n 'build/**': '**/build/**',\n '.git/**': '**/.git/**',\n '.kirograph/**': '**/.kirograph/**',\n};\n\nfunction migrateExcludePatterns(patterns: string[]): string[] {\n return patterns.map(p => SHALLOW_TO_RECURSIVE[p] ?? p);\n}\n\n// \u2500\u2500 Load / Save \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport async function loadConfig(projectRoot: string): Promise<KiroGraphConfig> {\n const dir = path.join(projectRoot, KIROGRAPH_DIR);\n const cfgPath = path.join(dir, CONFIG_FILE);\n\n if (!fs.existsSync(cfgPath)) {\n // Create default config file\n const defaults = createDefaultConfig(projectRoot);\n await fs.promises.mkdir(dir, { recursive: true });\n await _writeAtomic(cfgPath, defaults);\n return defaults;\n }\n\n let raw: unknown;\n try {\n const text = await fs.promises.readFile(cfgPath, 'utf8');\n raw = JSON.parse(text);\n } catch (err) {\n logError('Config parse error', { path: cfgPath, error: err instanceof Error ? err.message : String(err) });\n return createDefaultConfig(projectRoot);\n }\n\n const config = validateConfig(raw);\n\n // Migrate v1 \u2192 v2: upgrade shallow exclude patterns to recursive\n if (config.version < 2) {\n config.version = 2;\n config.exclude = migrateExcludePatterns(config.exclude);\n await fs.promises.mkdir(dir, { recursive: true });\n await _writeAtomic(cfgPath, config);\n }\n\n return config;\n}\n\nexport async function saveConfig(projectRoot: string, config: KiroGraphConfig): Promise<void> {\n const dir = path.join(projectRoot, KIROGRAPH_DIR);\n const cfgPath = path.join(dir, CONFIG_FILE);\n await fs.promises.mkdir(dir, { recursive: true });\n await _writeAtomic(cfgPath, config);\n}\n\nasync function _writeAtomic(cfgPath: string, config: KiroGraphConfig): Promise<void> {\n const tmp = cfgPath + '.tmp';\n await fs.promises.writeFile(tmp, JSON.stringify(config, null, 2), 'utf8');\n await fs.promises.rename(tmp, cfgPath);\n}\n\n// \u2500\u2500 Update helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport async function updateConfig(\n projectRoot: string,\n patch: Partial<KiroGraphConfig>\n): Promise<KiroGraphConfig> {\n const current = await loadConfig(projectRoot);\n const updated = validateConfig({ ...current, ...patch });\n await saveConfig(projectRoot, updated);\n return updated;\n}\n\nexport async function addIncludePatterns(projectRoot: string, patterns: string[]): Promise<void> {\n const config = await loadConfig(projectRoot);\n const existing = new Set(config.include);\n const toAdd = patterns.filter(p => isSafeRegex(p) && !existing.has(p));\n if (toAdd.length === 0) return;\n await saveConfig(projectRoot, { ...config, include: [...config.include, ...toAdd] });\n}\n\nexport async function addExcludePatterns(projectRoot: string, patterns: string[]): Promise<void> {\n const config = await loadConfig(projectRoot);\n const existing = new Set(config.exclude);\n const toAdd = patterns.filter(p => isSafeRegex(p) && !existing.has(p));\n if (toAdd.length === 0) return;\n await saveConfig(projectRoot, { ...config, exclude: [...config.exclude, ...toAdd] });\n}\n\n// \u2500\u2500 File inclusion check \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport function shouldIncludeFile(config: KiroGraphConfig, relPath: string): boolean {\n // Check exclude patterns first\n for (const pattern of config.exclude) {\n if (picomatch(pattern)(relPath)) return false;\n }\n // If include patterns are specified, file must match at least one\n if (config.include.length > 0) {\n return config.include.some(pattern => picomatch(pattern)(relPath));\n }\n return true;\n}\n"],
5
+ "mappings": ";;;;;;;;;;;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EAAE,CAAC;AACrF;AAIO,SAAS,kBAAkB,QAAyB,SAA0B;AAEnF,aAAW,WAAW,OAAO,SAAS;AACpC,YAAI,iBAAAA,SAAU,OAAO,EAAE,OAAO,EAAG,QAAO;AAAA,EAC1C;AAEA,MAAI,OAAO,QAAQ,SAAS,GAAG;AAC7B,WAAO,OAAO,QAAQ,KAAK,iBAAW,iBAAAA,SAAU,OAAO,EAAE,OAAO,CAAC;AAAA,EACnE;AACA,SAAO;AACT;",
6
6
  "names": ["picomatch"]
7
7
  }
@@ -207,11 +207,38 @@ class IndexPipeline {
207
207
  const docsIndexer = new DocsIndexer(this.db.getRawDb(), this.config, this.projectRoot);
208
208
  await docsIndexer.indexAll({
209
209
  force: opts?.force,
210
- onProgress: (msg) => opts?.onProgress?.({ phase: "architecture", current: 0, total: 1, meta: { msg } })
210
+ onProgress: (msg) => opts?.onProgress?.({ phase: "docs", current: 0, total: 1, meta: { msg } })
211
211
  });
212
212
  } catch {
213
213
  }
214
214
  }
215
+ if (this.config.enableData) {
216
+ try {
217
+ const { DataIndexer } = await Promise.resolve().then(() => require("../data/indexer.js"));
218
+ this.db.applyDataSchema();
219
+ const dataIndexer = new DataIndexer(this.db.getRawDb(), this.config, this.projectRoot);
220
+ await dataIndexer.indexAll({
221
+ onProgress: (msg) => opts?.onProgress?.({ phase: "data", current: 0, total: 1, meta: { msg } })
222
+ });
223
+ if (this.config.enableArchitecture) {
224
+ try {
225
+ const rawDb = this.db.getRawDb();
226
+ const tableExists = rawDb.get("SELECT name FROM sqlite_master WHERE type='table' AND name='arch_file_layers'");
227
+ if (tableExists) {
228
+ const datasets = rawDb.all("SELECT file_path FROM data_datasets");
229
+ for (const ds of datasets) {
230
+ rawDb.run(
231
+ `INSERT OR REPLACE INTO arch_file_layers (file_path, layer_id, confidence) VALUES (?, ?, ?)`,
232
+ [ds.file_path, "layer:data", 1]
233
+ );
234
+ }
235
+ }
236
+ } catch {
237
+ }
238
+ }
239
+ } catch {
240
+ }
241
+ }
215
242
  this.lock.clearDirty();
216
243
  return { success: errors.length === 0, filesIndexed, nodesCreated, edgesCreated, errors, duration: Date.now() - start };
217
244
  } finally {
@@ -377,11 +404,38 @@ class IndexPipeline {
377
404
  this.db.applyDocsSchema();
378
405
  const docsIndexer = new DocsIndexer(this.db.getRawDb(), this.config, this.projectRoot);
379
406
  await docsIndexer.indexAll({
380
- onProgress: (msg) => onProgress?.({ phase: "architecture", current: 0, total: 1, meta: { msg } })
407
+ onProgress: (msg) => onProgress?.({ phase: "docs", current: 0, total: 1, meta: { msg } })
381
408
  });
382
409
  } catch {
383
410
  }
384
411
  }
412
+ if (this.config.enableData) {
413
+ try {
414
+ const { DataIndexer } = await Promise.resolve().then(() => require("../data/indexer.js"));
415
+ this.db.applyDataSchema();
416
+ const dataIndexer = new DataIndexer(this.db.getRawDb(), this.config, this.projectRoot);
417
+ await dataIndexer.indexAll({
418
+ onProgress: (msg) => onProgress?.({ phase: "data", current: 0, total: 1, meta: { msg } })
419
+ });
420
+ if (this.config.enableArchitecture) {
421
+ try {
422
+ const rawDb = this.db.getRawDb();
423
+ const tableExists = rawDb.get("SELECT name FROM sqlite_master WHERE type='table' AND name='arch_file_layers'");
424
+ if (tableExists) {
425
+ const datasets = rawDb.all("SELECT file_path FROM data_datasets");
426
+ for (const ds of datasets) {
427
+ rawDb.run(
428
+ `INSERT OR REPLACE INTO arch_file_layers (file_path, layer_id, confidence) VALUES (?, ?, ?)`,
429
+ [ds.file_path, "layer:data", 1]
430
+ );
431
+ }
432
+ }
433
+ } catch {
434
+ }
435
+ }
436
+ } catch {
437
+ }
438
+ }
385
439
  this.lock.clearDirty();
386
440
  result.duration = Date.now() - start;
387
441
  return result;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/core/pipeline.ts"],
4
- "sourcesContent": ["/**\n * IndexPipeline \u2014 full-index and incremental-sync pipelines.\n *\n * Owns the two heavy workflows:\n * - indexAll(): scan all files, extract, store, resolve, detect frameworks,\n * generate embeddings, analyze architecture.\n * - sync(): detect changed files via git (or full scan fallback),\n * re-extract only what changed, then run the same tail pipeline.\n *\n * Everything that touches the filesystem or sub-systems is injected via the\n * constructor, keeping this class testable and free of global state.\n */\n\nimport * as path from 'path';\nimport * as fs from 'fs';\nimport { GraphDatabase } from '../db/database';\nimport { scanDirectory, hashContent, getChangedFiles, shouldIncludeFile } from '../sync/index';\nimport { extractFile } from '../extraction/extractor';\nimport { clearParserCache, initGrammars, hasWasmGrammar } from '../extraction/grammars';\nimport { detectFrameworks } from '../frameworks/index';\nimport { ReferenceResolver } from '../resolution/index';\nimport { VectorManager } from '../vectors/index';\nimport { ArchitectureAnalyzer } from '../architecture/index';\nimport type { KiroGraphConfig } from '../config';\nimport type { IndexResult, IndexProgress, SyncResult } from '../types';\nimport { LockManager } from './lock-manager';\nimport { Mutex } from '../utils';\n\nconst FILE_IO_BATCH_SIZE = 10;\n\nexport class IndexPipeline {\n private readonly mutex = new Mutex();\n\n constructor(\n private readonly db: GraphDatabase,\n private readonly vectors: VectorManager,\n private readonly resolver: ReferenceResolver,\n private readonly arch: ArchitectureAnalyzer,\n private readonly lock: LockManager,\n private readonly config: KiroGraphConfig,\n private readonly projectRoot: string,\n ) {}\n\n async indexAll(opts?: {\n onProgress?: (p: IndexProgress) => void;\n force?: boolean;\n signal?: AbortSignal;\n }): Promise<IndexResult> {\n const release = await this.mutex.acquire();\n this.lock.acquire();\n const start = Date.now();\n const errors: string[] = [];\n let filesIndexed = 0;\n let nodesCreated = 0;\n let edgesCreated = 0;\n\n // Track languages whose WASM parser is currently poisoned (ABORT=true on the module).\n // Once a language's parser aborts, every subsequent parse call for that language\n // fails instantly. We skip those files until clearParserCache + initGrammars succeeds.\n const poisonedLanguages = new Set<string>();\n\n try {\n const files = await scanDirectory(this.projectRoot, this.config, opts?.signal);\n opts?.onProgress?.({ phase: 'scanning', current: files.length, total: files.length });\n\n // Batch-read files in parallel\n const contentMap = new Map<string, Buffer>();\n for (let b = 0; b < files.length; b += FILE_IO_BATCH_SIZE) {\n const batch = files.slice(b, b + FILE_IO_BATCH_SIZE);\n const results = await Promise.all(batch.map(f => fs.promises.readFile(f).catch(() => null)));\n for (let i = 0; i < batch.length; i++) {\n if (results[i]) contentMap.set(batch[i], results[i]!);\n }\n }\n\n for (let i = 0; i < files.length; i++) {\n const file = files[i];\n opts?.onProgress?.({ phase: 'parsing', current: i + 1, total: files.length, currentFile: file });\n\n try {\n const content = contentMap.get(file);\n if (!content) continue;\n if (content.length > this.config.maxFileSize) continue;\n\n const relPath = path.relative(this.projectRoot, file).replace(/\\\\/g, '/');\n\n if (!opts?.force) {\n const existing = this.db.getFile(relPath);\n if (existing && hashContent(content) === existing.contentHash) continue;\n }\n\n // Skip files whose language parser is currently poisoned\n const { detectLanguage } = await Promise.resolve().then(() => require('../extraction/languages.js'));\n const lang = detectLanguage(file);\n if (poisonedLanguages.has(lang)) continue;\n\n const extracted = await extractFile(file, this.projectRoot, content);\n if (!extracted) continue;\n\n const oldNodes = this.db.getNodesByFile(extracted.filePath);\n if (oldNodes.length > 0) await this.vectors.deleteEmbeddings(oldNodes.map(n => n.id));\n\n this.db.transaction(() => {\n this.db.deleteNodesByFile(extracted.filePath);\n this.db.deleteUnresolvedRefsByFile(extracted.filePath);\n this.db.upsertFile({\n path: extracted.filePath,\n contentHash: extracted.contentHash,\n language: extracted.language,\n fileSize: extracted.fileSize,\n symbolCount: extracted.nodes.length,\n indexedAt: Date.now(),\n });\n for (const node of extracted.nodes) { this.db.upsertNode(node); nodesCreated++; }\n for (const edge of extracted.edges) { this.db.insertEdge(edge); edgesCreated++; }\n for (const ref of extracted.unresolvedRefs) {\n this.db.insertUnresolvedRef(ref.sourceId, ref.refName, ref.refKind, extracted.filePath, ref.line, ref.column);\n }\n });\n\n filesIndexed++;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n errors.push(`${file}: ${msg}`);\n\n // Detect WASM runtime abort and attempt recovery\n const isWasmCrash = (err as any)?.constructor?.name === 'RuntimeError'\n || msg.includes('Aborted(') \n || msg.includes('RuntimeError')\n || msg.includes('WASM grammar exists but failed to load');\n if (isWasmCrash) {\n // Mark the language as poisoned so we skip remaining files of this language\n const { detectLanguage } = await Promise.resolve().then(() => require('../extraction/languages.js'));\n const lang = detectLanguage(file);\n poisonedLanguages.add(lang);\n\n clearParserCache();\n try {\n await initGrammars();\n // Recovery succeeded \u2014 un-poison all languages\n poisonedLanguages.clear();\n } catch {\n errors.push('WASM runtime unrecoverable after crash \u2014 aborting batch');\n break;\n }\n }\n }\n }\n\n // Re-process files that have symbolCount=0 but should have symbols (WASM recovery)\n const emptyFiles = this.db.getAllFiles().filter(\n (f: any) => f.symbolCount === 0 && hasWasmGrammar(f.language)\n );\n if (emptyFiles.length > 0) {\n opts?.onProgress?.({ phase: 'retrying', current: 0, total: emptyFiles.length });\n for (let i = 0; i < emptyFiles.length; i++) {\n const ef = emptyFiles[i];\n const absPath = path.join(this.projectRoot, ef.path);\n opts?.onProgress?.({ phase: 'retrying', current: i + 1, total: emptyFiles.length, currentFile: absPath });\n try {\n const extracted = await extractFile(absPath, this.projectRoot);\n if (!extracted || extracted.nodes.length === 0) continue;\n\n const oldNodes = this.db.getNodesByFile(extracted.filePath);\n if (oldNodes.length > 0) await this.vectors.deleteEmbeddings(oldNodes.map(n => n.id));\n\n this.db.transaction(() => {\n this.db.deleteNodesByFile(extracted.filePath);\n this.db.deleteUnresolvedRefsByFile(extracted.filePath);\n this.db.upsertFile({\n path: extracted.filePath,\n contentHash: extracted.contentHash,\n language: extracted.language,\n fileSize: extracted.fileSize,\n symbolCount: extracted.nodes.length,\n indexedAt: Date.now(),\n });\n for (const node of extracted.nodes) { this.db.upsertNode(node); nodesCreated++; }\n for (const edge of extracted.edges) { this.db.insertEdge(edge); edgesCreated++; }\n for (const ref of extracted.unresolvedRefs) {\n this.db.insertUnresolvedRef(ref.sourceId, ref.refName, ref.refKind, extracted.filePath, ref.line, ref.column);\n }\n });\n filesIndexed++;\n } catch {\n // Already logged in first pass or genuinely broken \u2014 skip\n }\n }\n }\n\n // Resolve cross-file references\n opts?.onProgress?.({ phase: 'resolving', current: 0, total: 1 });\n await this.resolver.resolveAll((current, total) => {\n opts?.onProgress?.({ phase: 'resolving', current, total });\n });\n\n // Detect frameworks\n opts?.onProgress?.({ phase: 'detecting frameworks', current: 0, total: 1 });\n const detectedFrameworks = await detectFrameworks(this.projectRoot, this.db);\n const languages = [...new Set(this.db.getAllFiles().map(f => (f as any).language).filter(Boolean))];\n opts?.onProgress?.({\n phase: 'detecting frameworks', current: 1, total: 1,\n meta: { frameworks: detectedFrameworks.map(f => f.name), languages },\n });\n\n // Generate embeddings (if enabled)\n if (this.vectors.isInitialized()) {\n opts?.onProgress?.({ phase: 'embeddings', current: 0, total: 1 });\n await this.vectors.embedAll((current, total) =>\n opts?.onProgress?.({ phase: 'embeddings', current, total })\n );\n }\n\n // Analyze architecture (if enabled)\n if (this.config.enableArchitecture) {\n opts?.onProgress?.({ phase: 'architecture', current: 0, total: 1 });\n await this.arch.analyze(msg =>\n opts?.onProgress?.({ phase: 'architecture', current: 0, total: 1, meta: { msg } })\n );\n opts?.onProgress?.({ phase: 'architecture', current: 1, total: 1 });\n }\n\n // Index documentation (if enabled)\n if (this.config.enableDocs) {\n try {\n const { DocsIndexer } = await Promise.resolve().then(() => require('../docs/indexer.js'));\n this.db.applyDocsSchema();\n const docsIndexer = new DocsIndexer(this.db.getRawDb(), this.config, this.projectRoot);\n await docsIndexer.indexAll({\n force: opts?.force,\n onProgress: msg => opts?.onProgress?.({ phase: 'architecture', current: 0, total: 1, meta: { msg } }),\n });\n } catch { /* docs indexing is non-critical */ }\n }\n\n this.lock.clearDirty();\n return { success: errors.length === 0, filesIndexed, nodesCreated, edgesCreated, errors, duration: Date.now() - start };\n } finally {\n this.lock.release();\n release();\n }\n }\n\n async sync(opts?: {\n changedFiles?: string[];\n onProgress?: (p: IndexProgress) => void;\n }): Promise<SyncResult> {\n const release = await this.mutex.acquire();\n this.lock.acquire();\n const start = Date.now();\n const changedFiles = opts?.changedFiles;\n const onProgress = opts?.onProgress;\n const result: SyncResult = {\n added: [], modified: [], removed: [],\n nodesCreated: 0, nodesUpdated: 0, nodesRemoved: 0,\n edgesCreated: 0, edgesRemoved: 0,\n filesScanned: 0, errors: [], duration: 0,\n };\n\n try {\n const removeFile = async (rel: string) => {\n const oldNodes = this.db.getNodesByFile(rel);\n const oldEdgeCount = this.db.getEdgesForNodes(oldNodes.map(n => n.id)).length;\n result.nodesRemoved += oldNodes.length;\n result.edgesRemoved += oldEdgeCount;\n await this.vectors.deleteEmbeddings(oldNodes.map(n => n.id));\n this.db.deleteFile(rel);\n this.db.deleteUnresolvedRefsByFile(rel);\n result.removed.push(rel);\n };\n\n // \u2500\u2500 Exclude-rule cleanup \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Remove any indexed files that now match the current exclude patterns.\n // This handles the case where a user adds a new exclude pattern (e.g.\n // \"**/.vite/**\") and expects those files to disappear from the index on\n // the next sync without needing a full --force re-index.\n const allIndexed = this.db.getAllFiles();\n for (const f of allIndexed) {\n if (!shouldIncludeFile(f.path, this.config)) {\n onProgress?.({ phase: 'scanning', current: 0, total: 0, meta: { excludeCleanup: true, file: f.path } });\n await removeFile(f.path);\n }\n }\n\n let filesToProcess: string[];\n\n onProgress?.({ phase: 'scanning', current: 0, total: 0 });\n\n if (changedFiles) {\n filesToProcess = changedFiles.map(f => path.resolve(this.projectRoot, f));\n } else {\n const gitChanged = await getChangedFiles(this.projectRoot, this.config);\n const hasChanges = gitChanged.added.length > 0 || gitChanged.modified.length > 0 || gitChanged.removed.length > 0;\n\n if (hasChanges) {\n for (const p of gitChanged.removed) {\n await removeFile(path.relative(this.projectRoot, p).replace(/\\\\/g, '/'));\n }\n filesToProcess = [...gitChanged.added, ...gitChanged.modified];\n } else {\n // Fallback: full scan + detect removed files\n const indexed = new Set(this.db.getAllFiles().map(f => f.path));\n const current = new Set(\n (await scanDirectory(this.projectRoot, this.config))\n .map(f => path.relative(this.projectRoot, f).replace(/\\\\/g, '/'))\n );\n result.filesScanned = current.size;\n for (const p of indexed) {\n if (!current.has(p)) await removeFile(p);\n }\n filesToProcess = await scanDirectory(this.projectRoot, this.config);\n }\n }\n\n result.filesScanned = result.filesScanned || filesToProcess.length;\n onProgress?.({ phase: 'scanning', current: result.filesScanned, total: result.filesScanned });\n\n const poisonedLanguages = new Set<string>();\n\n for (let i = 0; i < filesToProcess.length; i++) {\n const file = filesToProcess[i];\n onProgress?.({ phase: 'parsing', current: i + 1, total: filesToProcess.length, currentFile: file });\n\n if (!fs.existsSync(file)) {\n const rel = path.relative(this.projectRoot, file).replace(/\\\\/g, '/');\n await removeFile(rel);\n continue;\n }\n\n try {\n // Skip files whose language parser is currently poisoned\n const { detectLanguage } = await Promise.resolve().then(() => require('../extraction/languages.js'));\n const lang = detectLanguage(file);\n if (poisonedLanguages.has(lang)) continue;\n\n const extracted = await extractFile(file, this.projectRoot);\n if (!extracted) continue;\n\n const existing = this.db.getFile(extracted.filePath);\n const isNew = !existing;\n if (!isNew && existing!.contentHash === extracted.contentHash) continue;\n\n const oldNodes = this.db.getNodesByFile(extracted.filePath);\n const oldEdgeCount = this.db.getEdgesForNodes(oldNodes.map(n => n.id)).length;\n await this.vectors.deleteEmbeddings(oldNodes.map(n => n.id));\n\n this.db.transaction(() => {\n result.nodesRemoved += oldNodes.length;\n result.edgesRemoved += oldEdgeCount;\n this.db.deleteNodesByFile(extracted.filePath);\n this.db.deleteUnresolvedRefsByFile(extracted.filePath);\n this.db.upsertFile({\n path: extracted.filePath,\n contentHash: extracted.contentHash,\n language: extracted.language,\n fileSize: extracted.fileSize,\n symbolCount: extracted.nodes.length,\n indexedAt: Date.now(),\n });\n for (const node of extracted.nodes) { this.db.upsertNode(node); result.nodesCreated++; }\n for (const edge of extracted.edges) { this.db.insertEdge(edge); result.edgesCreated++; }\n for (const ref of extracted.unresolvedRefs) {\n this.db.insertUnresolvedRef(ref.sourceId, ref.refName, ref.refKind, extracted.filePath, ref.line, ref.column);\n }\n });\n\n this.resolver.invalidateFile(extracted.filePath);\n if (isNew) result.added.push(extracted.filePath);\n else { result.modified.push(extracted.filePath); result.nodesUpdated += extracted.nodes.length; }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n result.errors.push(`${file}: ${msg}`);\n\n // Detect WASM runtime abort and attempt recovery\n const isWasmCrash = (err as any)?.constructor?.name === 'RuntimeError'\n || msg.includes('Aborted(') \n || msg.includes('RuntimeError')\n || msg.includes('WASM grammar exists but failed to load');\n if (isWasmCrash) {\n const { detectLanguage } = await Promise.resolve().then(() => require('../extraction/languages.js'));\n const lang = detectLanguage(file);\n poisonedLanguages.add(lang);\n\n clearParserCache();\n try {\n await initGrammars();\n poisonedLanguages.clear();\n } catch {\n result.errors.push('WASM runtime unrecoverable after crash \u2014 aborting sync');\n break;\n }\n }\n }\n }\n\n // Resolve cross-file references\n onProgress?.({ phase: 'resolving', current: 0, total: 1 });\n await this.resolver.resolveAll((current, total) => {\n onProgress?.({ phase: 'resolving', current, total });\n });\n\n await detectFrameworks(this.projectRoot);\n\n // Generate embeddings (if enabled)\n if (this.vectors.isInitialized()) {\n onProgress?.({ phase: 'embeddings', current: 0, total: 1 });\n await this.vectors.embedAll((current, total) =>\n onProgress?.({ phase: 'embeddings', current, total })\n );\n }\n\n // Analyze architecture (if enabled)\n if (this.config.enableArchitecture) {\n onProgress?.({ phase: 'architecture', current: 0, total: 1 });\n await this.arch.analyze(msg =>\n onProgress?.({ phase: 'architecture', current: 0, total: 1, meta: { msg } })\n );\n onProgress?.({ phase: 'architecture', current: 1, total: 1 });\n }\n\n // Re-index documentation (if enabled)\n if (this.config.enableDocs) {\n try {\n const { DocsIndexer } = await Promise.resolve().then(() => require('../docs/indexer.js'));\n this.db.applyDocsSchema();\n const docsIndexer = new DocsIndexer(this.db.getRawDb(), this.config, this.projectRoot);\n await docsIndexer.indexAll({\n onProgress: msg => onProgress?.({ phase: 'architecture', current: 0, total: 1, meta: { msg } }),\n });\n } catch { /* docs indexing is non-critical */ }\n }\n\n this.lock.clearDirty();\n result.duration = Date.now() - start;\n return result;\n } finally {\n this.lock.release();\n release();\n }\n }\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAaA,WAAsB;AACtB,SAAoB;AAEpB,kBAA+E;AAC/E,uBAA4B;AAC5B,sBAA+D;AAC/D,wBAAiC;AAOjC,mBAAsB;AAEtB,MAAM,qBAAqB;AAEpB,MAAM,cAAc;AAAA,EAGzB,YACmB,IACA,SACA,UACA,MACA,MACA,QACA,aACjB;AAPiB;AACA;AACA;AACA;AACA;AACA;AACA;AATnB,SAAiB,QAAQ,IAAI,mBAAM;AAAA,EAUhC;AAAA,EAEH,MAAM,SAAS,MAIU;AACvB,UAAM,UAAU,MAAM,KAAK,MAAM,QAAQ;AACzC,SAAK,KAAK,QAAQ;AAClB,UAAM,QAAQ,KAAK,IAAI;AACvB,UAAM,SAAmB,CAAC;AAC1B,QAAI,eAAe;AACnB,QAAI,eAAe;AACnB,QAAI,eAAe;AAKnB,UAAM,oBAAoB,oBAAI,IAAY;AAE1C,QAAI;AACF,YAAM,QAAQ,UAAM,2BAAc,KAAK,aAAa,KAAK,QAAQ,MAAM,MAAM;AAC7E,YAAM,aAAa,EAAE,OAAO,YAAY,SAAS,MAAM,QAAQ,OAAO,MAAM,OAAO,CAAC;AAGpF,YAAM,aAAa,oBAAI,IAAoB;AAC3C,eAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK,oBAAoB;AACzD,cAAM,QAAQ,MAAM,MAAM,GAAG,IAAI,kBAAk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E,YAAY,IAAI,MAAM,QAAQ,QAAQ,EAAE,KAAK,MAAM,QAAQ,oBAAoB,CAAC;AACxF,eAAK,GAAG,gBAAgB;AACxB,gBAAM,cAAc,IAAI,YAAY,KAAK,GAAG,SAAS,GAAG,KAAK,QAAQ,KAAK,WAAW;AACrF,gBAAM,YAAY,SAAS;AAAA,YACzB,YAAY,SAAO,aAAa,EAAE,OAAO,gBAAgB,SAAS,GAAG,OAAO,GAAG,MAAM,EAAE,IAAI,EAAE,CAAC;AAAA,UAChG,CAAC;AAAA,QACH,QAAQ;AAAA,QAAsC;AAAA,MAChD;AAEA,WAAK,KAAK,WAAW;AACrB,aAAO,WAAW,KAAK,IAAI,IAAI;AAC/B,aAAO;AAAA,IACT,UAAE;AACA,WAAK,KAAK,QAAQ;AAClB,cAAQ;AAAA,IACV;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["/**\n * IndexPipeline \u2014 full-index and incremental-sync pipelines.\n *\n * Owns the two heavy workflows:\n * - indexAll(): scan all files, extract, store, resolve, detect frameworks,\n * generate embeddings, analyze architecture.\n * - sync(): detect changed files via git (or full scan fallback),\n * re-extract only what changed, then run the same tail pipeline.\n *\n * Everything that touches the filesystem or sub-systems is injected via the\n * constructor, keeping this class testable and free of global state.\n */\n\nimport * as path from 'path';\nimport * as fs from 'fs';\nimport { GraphDatabase } from '../db/database';\nimport { scanDirectory, hashContent, getChangedFiles, shouldIncludeFile } from '../sync/index';\nimport { extractFile } from '../extraction/extractor';\nimport { clearParserCache, initGrammars, hasWasmGrammar } from '../extraction/grammars';\nimport { detectFrameworks } from '../frameworks/index';\nimport { ReferenceResolver } from '../resolution/index';\nimport { VectorManager } from '../vectors/index';\nimport { ArchitectureAnalyzer } from '../architecture/index';\nimport type { KiroGraphConfig } from '../config';\nimport type { IndexResult, IndexProgress, SyncResult } from '../types';\nimport { LockManager } from './lock-manager';\nimport { Mutex } from '../utils';\n\nconst FILE_IO_BATCH_SIZE = 10;\n\nexport class IndexPipeline {\n private readonly mutex = new Mutex();\n\n constructor(\n private readonly db: GraphDatabase,\n private readonly vectors: VectorManager,\n private readonly resolver: ReferenceResolver,\n private readonly arch: ArchitectureAnalyzer,\n private readonly lock: LockManager,\n private readonly config: KiroGraphConfig,\n private readonly projectRoot: string,\n ) {}\n\n async indexAll(opts?: {\n onProgress?: (p: IndexProgress) => void;\n force?: boolean;\n signal?: AbortSignal;\n }): Promise<IndexResult> {\n const release = await this.mutex.acquire();\n this.lock.acquire();\n const start = Date.now();\n const errors: string[] = [];\n let filesIndexed = 0;\n let nodesCreated = 0;\n let edgesCreated = 0;\n\n // Track languages whose WASM parser is currently poisoned (ABORT=true on the module).\n // Once a language's parser aborts, every subsequent parse call for that language\n // fails instantly. We skip those files until clearParserCache + initGrammars succeeds.\n const poisonedLanguages = new Set<string>();\n\n try {\n const files = await scanDirectory(this.projectRoot, this.config, opts?.signal);\n opts?.onProgress?.({ phase: 'scanning', current: files.length, total: files.length });\n\n // Batch-read files in parallel\n const contentMap = new Map<string, Buffer>();\n for (let b = 0; b < files.length; b += FILE_IO_BATCH_SIZE) {\n const batch = files.slice(b, b + FILE_IO_BATCH_SIZE);\n const results = await Promise.all(batch.map(f => fs.promises.readFile(f).catch(() => null)));\n for (let i = 0; i < batch.length; i++) {\n if (results[i]) contentMap.set(batch[i], results[i]!);\n }\n }\n\n for (let i = 0; i < files.length; i++) {\n const file = files[i];\n opts?.onProgress?.({ phase: 'parsing', current: i + 1, total: files.length, currentFile: file });\n\n try {\n const content = contentMap.get(file);\n if (!content) continue;\n if (content.length > this.config.maxFileSize) continue;\n\n const relPath = path.relative(this.projectRoot, file).replace(/\\\\/g, '/');\n\n if (!opts?.force) {\n const existing = this.db.getFile(relPath);\n if (existing && hashContent(content) === existing.contentHash) continue;\n }\n\n // Skip files whose language parser is currently poisoned\n const { detectLanguage } = await Promise.resolve().then(() => require('../extraction/languages.js'));\n const lang = detectLanguage(file);\n if (poisonedLanguages.has(lang)) continue;\n\n const extracted = await extractFile(file, this.projectRoot, content);\n if (!extracted) continue;\n\n const oldNodes = this.db.getNodesByFile(extracted.filePath);\n if (oldNodes.length > 0) await this.vectors.deleteEmbeddings(oldNodes.map(n => n.id));\n\n this.db.transaction(() => {\n this.db.deleteNodesByFile(extracted.filePath);\n this.db.deleteUnresolvedRefsByFile(extracted.filePath);\n this.db.upsertFile({\n path: extracted.filePath,\n contentHash: extracted.contentHash,\n language: extracted.language,\n fileSize: extracted.fileSize,\n symbolCount: extracted.nodes.length,\n indexedAt: Date.now(),\n });\n for (const node of extracted.nodes) { this.db.upsertNode(node); nodesCreated++; }\n for (const edge of extracted.edges) { this.db.insertEdge(edge); edgesCreated++; }\n for (const ref of extracted.unresolvedRefs) {\n this.db.insertUnresolvedRef(ref.sourceId, ref.refName, ref.refKind, extracted.filePath, ref.line, ref.column);\n }\n });\n\n filesIndexed++;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n errors.push(`${file}: ${msg}`);\n\n // Detect WASM runtime abort and attempt recovery\n const isWasmCrash = (err as any)?.constructor?.name === 'RuntimeError'\n || msg.includes('Aborted(') \n || msg.includes('RuntimeError')\n || msg.includes('WASM grammar exists but failed to load');\n if (isWasmCrash) {\n // Mark the language as poisoned so we skip remaining files of this language\n const { detectLanguage } = await Promise.resolve().then(() => require('../extraction/languages.js'));\n const lang = detectLanguage(file);\n poisonedLanguages.add(lang);\n\n clearParserCache();\n try {\n await initGrammars();\n // Recovery succeeded \u2014 un-poison all languages\n poisonedLanguages.clear();\n } catch {\n errors.push('WASM runtime unrecoverable after crash \u2014 aborting batch');\n break;\n }\n }\n }\n }\n\n // Re-process files that have symbolCount=0 but should have symbols (WASM recovery)\n const emptyFiles = this.db.getAllFiles().filter(\n (f: any) => f.symbolCount === 0 && hasWasmGrammar(f.language)\n );\n if (emptyFiles.length > 0) {\n opts?.onProgress?.({ phase: 'retrying', current: 0, total: emptyFiles.length });\n for (let i = 0; i < emptyFiles.length; i++) {\n const ef = emptyFiles[i];\n const absPath = path.join(this.projectRoot, ef.path);\n opts?.onProgress?.({ phase: 'retrying', current: i + 1, total: emptyFiles.length, currentFile: absPath });\n try {\n const extracted = await extractFile(absPath, this.projectRoot);\n if (!extracted || extracted.nodes.length === 0) continue;\n\n const oldNodes = this.db.getNodesByFile(extracted.filePath);\n if (oldNodes.length > 0) await this.vectors.deleteEmbeddings(oldNodes.map(n => n.id));\n\n this.db.transaction(() => {\n this.db.deleteNodesByFile(extracted.filePath);\n this.db.deleteUnresolvedRefsByFile(extracted.filePath);\n this.db.upsertFile({\n path: extracted.filePath,\n contentHash: extracted.contentHash,\n language: extracted.language,\n fileSize: extracted.fileSize,\n symbolCount: extracted.nodes.length,\n indexedAt: Date.now(),\n });\n for (const node of extracted.nodes) { this.db.upsertNode(node); nodesCreated++; }\n for (const edge of extracted.edges) { this.db.insertEdge(edge); edgesCreated++; }\n for (const ref of extracted.unresolvedRefs) {\n this.db.insertUnresolvedRef(ref.sourceId, ref.refName, ref.refKind, extracted.filePath, ref.line, ref.column);\n }\n });\n filesIndexed++;\n } catch {\n // Already logged in first pass or genuinely broken \u2014 skip\n }\n }\n }\n\n // Resolve cross-file references\n opts?.onProgress?.({ phase: 'resolving', current: 0, total: 1 });\n await this.resolver.resolveAll((current, total) => {\n opts?.onProgress?.({ phase: 'resolving', current, total });\n });\n\n // Detect frameworks\n opts?.onProgress?.({ phase: 'detecting frameworks', current: 0, total: 1 });\n const detectedFrameworks = await detectFrameworks(this.projectRoot, this.db);\n const languages = [...new Set(this.db.getAllFiles().map(f => (f as any).language).filter(Boolean))];\n opts?.onProgress?.({\n phase: 'detecting frameworks', current: 1, total: 1,\n meta: { frameworks: detectedFrameworks.map(f => f.name), languages },\n });\n\n // Generate embeddings (if enabled)\n if (this.vectors.isInitialized()) {\n opts?.onProgress?.({ phase: 'embeddings', current: 0, total: 1 });\n await this.vectors.embedAll((current, total) =>\n opts?.onProgress?.({ phase: 'embeddings', current, total })\n );\n }\n\n // Analyze architecture (if enabled)\n if (this.config.enableArchitecture) {\n opts?.onProgress?.({ phase: 'architecture', current: 0, total: 1 });\n await this.arch.analyze(msg =>\n opts?.onProgress?.({ phase: 'architecture', current: 0, total: 1, meta: { msg } })\n );\n opts?.onProgress?.({ phase: 'architecture', current: 1, total: 1 });\n }\n\n // Index documentation (if enabled)\n if (this.config.enableDocs) {\n try {\n const { DocsIndexer } = await Promise.resolve().then(() => require('../docs/indexer.js'));\n this.db.applyDocsSchema();\n const docsIndexer = new DocsIndexer(this.db.getRawDb(), this.config, this.projectRoot);\n await docsIndexer.indexAll({\n force: opts?.force,\n onProgress: msg => opts?.onProgress?.({ phase: 'docs', current: 0, total: 1, meta: { msg } }),\n });\n } catch { /* docs indexing is non-critical */ }\n }\n\n // Index data files (if enabled)\n if ((this.config as any).enableData) {\n try {\n const { DataIndexer } = await Promise.resolve().then(() => require('../data/indexer.js'));\n this.db.applyDataSchema();\n const dataIndexer = new DataIndexer(this.db.getRawDb(), this.config, this.projectRoot);\n await dataIndexer.indexAll({\n onProgress: msg => opts?.onProgress?.({ phase: 'data', current: 0, total: 1, meta: { msg } }),\n });\n\n // Assign data files to 'data' architecture layer if architecture is enabled\n if (this.config.enableArchitecture) {\n try {\n const rawDb = this.db.getRawDb();\n // Check if arch_file_layers table exists\n const tableExists = rawDb.get(\"SELECT name FROM sqlite_master WHERE type='table' AND name='arch_file_layers'\");\n if (tableExists) {\n const datasets = rawDb.all('SELECT file_path FROM data_datasets') as Array<{ file_path: string }>;\n for (const ds of datasets) {\n rawDb.run(\n `INSERT OR REPLACE INTO arch_file_layers (file_path, layer_id, confidence) VALUES (?, ?, ?)`,\n [ds.file_path, 'layer:data', 1.0],\n );\n }\n }\n } catch { /* non-critical */ }\n }\n } catch { /* data indexing is non-critical */ }\n }\n\n this.lock.clearDirty();\n return { success: errors.length === 0, filesIndexed, nodesCreated, edgesCreated, errors, duration: Date.now() - start };\n } finally {\n this.lock.release();\n release();\n }\n }\n\n async sync(opts?: {\n changedFiles?: string[];\n onProgress?: (p: IndexProgress) => void;\n }): Promise<SyncResult> {\n const release = await this.mutex.acquire();\n this.lock.acquire();\n const start = Date.now();\n const changedFiles = opts?.changedFiles;\n const onProgress = opts?.onProgress;\n const result: SyncResult = {\n added: [], modified: [], removed: [],\n nodesCreated: 0, nodesUpdated: 0, nodesRemoved: 0,\n edgesCreated: 0, edgesRemoved: 0,\n filesScanned: 0, errors: [], duration: 0,\n };\n\n try {\n const removeFile = async (rel: string) => {\n const oldNodes = this.db.getNodesByFile(rel);\n const oldEdgeCount = this.db.getEdgesForNodes(oldNodes.map(n => n.id)).length;\n result.nodesRemoved += oldNodes.length;\n result.edgesRemoved += oldEdgeCount;\n await this.vectors.deleteEmbeddings(oldNodes.map(n => n.id));\n this.db.deleteFile(rel);\n this.db.deleteUnresolvedRefsByFile(rel);\n result.removed.push(rel);\n };\n\n // \u2500\u2500 Exclude-rule cleanup \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Remove any indexed files that now match the current exclude patterns.\n // This handles the case where a user adds a new exclude pattern (e.g.\n // \"**/.vite/**\") and expects those files to disappear from the index on\n // the next sync without needing a full --force re-index.\n const allIndexed = this.db.getAllFiles();\n for (const f of allIndexed) {\n if (!shouldIncludeFile(f.path, this.config)) {\n onProgress?.({ phase: 'scanning', current: 0, total: 0, meta: { excludeCleanup: true, file: f.path } });\n await removeFile(f.path);\n }\n }\n\n let filesToProcess: string[];\n\n onProgress?.({ phase: 'scanning', current: 0, total: 0 });\n\n if (changedFiles) {\n filesToProcess = changedFiles.map(f => path.resolve(this.projectRoot, f));\n } else {\n const gitChanged = await getChangedFiles(this.projectRoot, this.config);\n const hasChanges = gitChanged.added.length > 0 || gitChanged.modified.length > 0 || gitChanged.removed.length > 0;\n\n if (hasChanges) {\n for (const p of gitChanged.removed) {\n await removeFile(path.relative(this.projectRoot, p).replace(/\\\\/g, '/'));\n }\n filesToProcess = [...gitChanged.added, ...gitChanged.modified];\n } else {\n // Fallback: full scan + detect removed files\n const indexed = new Set(this.db.getAllFiles().map(f => f.path));\n const current = new Set(\n (await scanDirectory(this.projectRoot, this.config))\n .map(f => path.relative(this.projectRoot, f).replace(/\\\\/g, '/'))\n );\n result.filesScanned = current.size;\n for (const p of indexed) {\n if (!current.has(p)) await removeFile(p);\n }\n filesToProcess = await scanDirectory(this.projectRoot, this.config);\n }\n }\n\n result.filesScanned = result.filesScanned || filesToProcess.length;\n onProgress?.({ phase: 'scanning', current: result.filesScanned, total: result.filesScanned });\n\n const poisonedLanguages = new Set<string>();\n\n for (let i = 0; i < filesToProcess.length; i++) {\n const file = filesToProcess[i];\n onProgress?.({ phase: 'parsing', current: i + 1, total: filesToProcess.length, currentFile: file });\n\n if (!fs.existsSync(file)) {\n const rel = path.relative(this.projectRoot, file).replace(/\\\\/g, '/');\n await removeFile(rel);\n continue;\n }\n\n try {\n // Skip files whose language parser is currently poisoned\n const { detectLanguage } = await Promise.resolve().then(() => require('../extraction/languages.js'));\n const lang = detectLanguage(file);\n if (poisonedLanguages.has(lang)) continue;\n\n const extracted = await extractFile(file, this.projectRoot);\n if (!extracted) continue;\n\n const existing = this.db.getFile(extracted.filePath);\n const isNew = !existing;\n if (!isNew && existing!.contentHash === extracted.contentHash) continue;\n\n const oldNodes = this.db.getNodesByFile(extracted.filePath);\n const oldEdgeCount = this.db.getEdgesForNodes(oldNodes.map(n => n.id)).length;\n await this.vectors.deleteEmbeddings(oldNodes.map(n => n.id));\n\n this.db.transaction(() => {\n result.nodesRemoved += oldNodes.length;\n result.edgesRemoved += oldEdgeCount;\n this.db.deleteNodesByFile(extracted.filePath);\n this.db.deleteUnresolvedRefsByFile(extracted.filePath);\n this.db.upsertFile({\n path: extracted.filePath,\n contentHash: extracted.contentHash,\n language: extracted.language,\n fileSize: extracted.fileSize,\n symbolCount: extracted.nodes.length,\n indexedAt: Date.now(),\n });\n for (const node of extracted.nodes) { this.db.upsertNode(node); result.nodesCreated++; }\n for (const edge of extracted.edges) { this.db.insertEdge(edge); result.edgesCreated++; }\n for (const ref of extracted.unresolvedRefs) {\n this.db.insertUnresolvedRef(ref.sourceId, ref.refName, ref.refKind, extracted.filePath, ref.line, ref.column);\n }\n });\n\n this.resolver.invalidateFile(extracted.filePath);\n if (isNew) result.added.push(extracted.filePath);\n else { result.modified.push(extracted.filePath); result.nodesUpdated += extracted.nodes.length; }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n result.errors.push(`${file}: ${msg}`);\n\n // Detect WASM runtime abort and attempt recovery\n const isWasmCrash = (err as any)?.constructor?.name === 'RuntimeError'\n || msg.includes('Aborted(') \n || msg.includes('RuntimeError')\n || msg.includes('WASM grammar exists but failed to load');\n if (isWasmCrash) {\n const { detectLanguage } = await Promise.resolve().then(() => require('../extraction/languages.js'));\n const lang = detectLanguage(file);\n poisonedLanguages.add(lang);\n\n clearParserCache();\n try {\n await initGrammars();\n poisonedLanguages.clear();\n } catch {\n result.errors.push('WASM runtime unrecoverable after crash \u2014 aborting sync');\n break;\n }\n }\n }\n }\n\n // Resolve cross-file references\n onProgress?.({ phase: 'resolving', current: 0, total: 1 });\n await this.resolver.resolveAll((current, total) => {\n onProgress?.({ phase: 'resolving', current, total });\n });\n\n await detectFrameworks(this.projectRoot);\n\n // Generate embeddings (if enabled)\n if (this.vectors.isInitialized()) {\n onProgress?.({ phase: 'embeddings', current: 0, total: 1 });\n await this.vectors.embedAll((current, total) =>\n onProgress?.({ phase: 'embeddings', current, total })\n );\n }\n\n // Analyze architecture (if enabled)\n if (this.config.enableArchitecture) {\n onProgress?.({ phase: 'architecture', current: 0, total: 1 });\n await this.arch.analyze(msg =>\n onProgress?.({ phase: 'architecture', current: 0, total: 1, meta: { msg } })\n );\n onProgress?.({ phase: 'architecture', current: 1, total: 1 });\n }\n\n // Re-index documentation (if enabled)\n if (this.config.enableDocs) {\n try {\n const { DocsIndexer } = await Promise.resolve().then(() => require('../docs/indexer.js'));\n this.db.applyDocsSchema();\n const docsIndexer = new DocsIndexer(this.db.getRawDb(), this.config, this.projectRoot);\n await docsIndexer.indexAll({\n onProgress: msg => onProgress?.({ phase: 'docs', current: 0, total: 1, meta: { msg } }),\n });\n } catch { /* docs indexing is non-critical */ }\n }\n\n // Re-index data files (if enabled)\n if ((this.config as any).enableData) {\n try {\n const { DataIndexer } = await Promise.resolve().then(() => require('../data/indexer.js'));\n this.db.applyDataSchema();\n const dataIndexer = new DataIndexer(this.db.getRawDb(), this.config, this.projectRoot);\n await dataIndexer.indexAll({\n onProgress: msg => onProgress?.({ phase: 'data', current: 0, total: 1, meta: { msg } }),\n });\n\n // Assign data files to 'data' architecture layer if architecture is enabled\n if (this.config.enableArchitecture) {\n try {\n const rawDb = this.db.getRawDb();\n const tableExists = rawDb.get(\"SELECT name FROM sqlite_master WHERE type='table' AND name='arch_file_layers'\");\n if (tableExists) {\n const datasets = rawDb.all('SELECT file_path FROM data_datasets') as Array<{ file_path: string }>;\n for (const ds of datasets) {\n rawDb.run(\n `INSERT OR REPLACE INTO arch_file_layers (file_path, layer_id, confidence) VALUES (?, ?, ?)`,\n [ds.file_path, 'layer:data', 1.0],\n );\n }\n }\n } catch { /* non-critical */ }\n }\n } catch { /* data indexing is non-critical */ }\n }\n\n this.lock.clearDirty();\n result.duration = Date.now() - start;\n return result;\n } finally {\n this.lock.release();\n release();\n }\n }\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAaA,WAAsB;AACtB,SAAoB;AAEpB,kBAA+E;AAC/E,uBAA4B;AAC5B,sBAA+D;AAC/D,wBAAiC;AAOjC,mBAAsB;AAEtB,MAAM,qBAAqB;AAEpB,MAAM,cAAc;AAAA,EAGzB,YACmB,IACA,SAC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