@triedotdev/mcp 1.0.166 → 1.0.168
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.
- package/README.md +333 -805
- package/dist/chunk-2HF65EHQ.js +311 -0
- package/dist/chunk-2HF65EHQ.js.map +1 -0
- package/dist/{chunk-JNUOW2JS.js → chunk-4MXH2ZPT.js} +12 -12
- package/dist/chunk-4MXH2ZPT.js.map +1 -0
- package/dist/{chunk-LR5M4RTN.js → chunk-575YT2SD.js} +1 -1
- package/dist/chunk-575YT2SD.js.map +1 -0
- package/dist/{chunk-ZKKKLRZZ.js → chunk-5BRRRTN6.js} +4 -4
- package/dist/{chunk-TQOO6A4G.js → chunk-7WITSO22.js} +3 -3
- package/dist/{chunk-ACU2RJUJ.js → chunk-F6WFNUAY.js} +2 -2
- package/dist/{chunk-VR4VWXXU.js → chunk-G2TGF6TR.js} +9 -2
- package/dist/chunk-G2TGF6TR.js.map +1 -0
- package/dist/{chunk-ZBXW244P.js → chunk-HVCDY3AK.js} +3 -3
- package/dist/chunk-HVCDY3AK.js.map +1 -0
- package/dist/{chunk-HOGKPDZA.js → chunk-LQIMKE3P.js} +678 -151
- package/dist/chunk-LQIMKE3P.js.map +1 -0
- package/dist/{chunk-2Z3TQNNK.js → chunk-MRHKX5M5.js} +3 -3
- package/dist/{chunk-OLNZJ3XV.js → chunk-Q63FFI6D.js} +2 -2
- package/dist/{chunk-S36IO3EE.js → chunk-XE6KQRKZ.js} +9 -8
- package/dist/chunk-XE6KQRKZ.js.map +1 -0
- package/dist/{chunk-GDWA3CH3.js → chunk-XPZZFPBZ.js} +30 -6
- package/dist/chunk-XPZZFPBZ.js.map +1 -0
- package/dist/{chunk-JEZ7XJQN.js → chunk-XTFWT2XM.js} +2 -2
- package/dist/{chunk-UXRW2YSP.js → chunk-YDHUCDHM.js} +18 -112
- package/dist/chunk-YDHUCDHM.js.map +1 -0
- package/dist/{chunk-LG5CBK6A.js → chunk-YZ6Y2H3P.js} +21 -196
- package/dist/chunk-YZ6Y2H3P.js.map +1 -0
- package/dist/{chunk-MVVPJ73K.js → chunk-ZJF5FTBX.js} +126 -358
- package/dist/chunk-ZJF5FTBX.js.map +1 -0
- package/dist/cli/create-agent.js +1 -1
- package/dist/cli/create-agent.js.map +1 -1
- package/dist/cli/main.js +194 -849
- package/dist/cli/main.js.map +1 -1
- package/dist/cli/yolo-daemon.js +15 -14
- package/dist/cli/yolo-daemon.js.map +1 -1
- package/dist/{fast-analyzer-NJQO3TFD.js → fast-analyzer-XXYMOXRK.js} +3 -3
- package/dist/git-EO5SRFMN.js +28 -0
- package/dist/{github-ingester-TFBDUDIY.js → github-ingester-ZOKK6GRS.js} +3 -3
- package/dist/{goal-manager-DVX24UPZ.js → goal-manager-YOB7VWK7.js} +5 -4
- package/dist/{goal-validator-6Y5CDEMJ.js → goal-validator-ULKIBDPX.js} +5 -4
- package/dist/{hypothesis-UKPGOYY2.js → hypothesis-7BFFT5JY.js} +5 -4
- package/dist/index.js +19 -18
- package/dist/index.js.map +1 -1
- package/dist/{issue-store-UZAPI5DU.js → issue-store-ZIRP23EP.js} +4 -3
- package/dist/{ledger-CNFCJKHX.js → ledger-TWZTGDFA.js} +3 -2
- package/dist/{linear-ingester-PLES2BRS.js → linear-ingester-XXPAZZRW.js} +3 -3
- package/dist/{output-manager-JNMEAXFO.js → output-manager-RVJ37XKA.js} +2 -2
- package/dist/server/mcp-server.js +19 -18
- package/dist/{tiered-storage-OP74NPJY.js → tiered-storage-Z3YCR465.js} +2 -2
- package/dist/{trie-agent-6SWUHCVO.js → trie-agent-3YDPEGHJ.js} +9 -8
- package/dist/trie-agent-3YDPEGHJ.js.map +1 -0
- package/package.json +3 -2
- package/dist/chunk-GDWA3CH3.js.map +0 -1
- package/dist/chunk-HOGKPDZA.js.map +0 -1
- package/dist/chunk-JNUOW2JS.js.map +0 -1
- package/dist/chunk-LG5CBK6A.js.map +0 -1
- package/dist/chunk-LR5M4RTN.js.map +0 -1
- package/dist/chunk-MVVPJ73K.js.map +0 -1
- package/dist/chunk-S36IO3EE.js.map +0 -1
- package/dist/chunk-UXRW2YSP.js.map +0 -1
- package/dist/chunk-VR4VWXXU.js.map +0 -1
- package/dist/chunk-ZBXW244P.js.map +0 -1
- /package/dist/{chunk-ZKKKLRZZ.js.map → chunk-5BRRRTN6.js.map} +0 -0
- /package/dist/{chunk-TQOO6A4G.js.map → chunk-7WITSO22.js.map} +0 -0
- /package/dist/{chunk-ACU2RJUJ.js.map → chunk-F6WFNUAY.js.map} +0 -0
- /package/dist/{chunk-2Z3TQNNK.js.map → chunk-MRHKX5M5.js.map} +0 -0
- /package/dist/{chunk-OLNZJ3XV.js.map → chunk-Q63FFI6D.js.map} +0 -0
- /package/dist/{chunk-JEZ7XJQN.js.map → chunk-XTFWT2XM.js.map} +0 -0
- /package/dist/{fast-analyzer-NJQO3TFD.js.map → fast-analyzer-XXYMOXRK.js.map} +0 -0
- /package/dist/{github-ingester-TFBDUDIY.js.map → git-EO5SRFMN.js.map} +0 -0
- /package/dist/{goal-manager-DVX24UPZ.js.map → github-ingester-ZOKK6GRS.js.map} +0 -0
- /package/dist/{goal-validator-6Y5CDEMJ.js.map → goal-manager-YOB7VWK7.js.map} +0 -0
- /package/dist/{hypothesis-UKPGOYY2.js.map → goal-validator-ULKIBDPX.js.map} +0 -0
- /package/dist/{issue-store-UZAPI5DU.js.map → hypothesis-7BFFT5JY.js.map} +0 -0
- /package/dist/{ledger-CNFCJKHX.js.map → issue-store-ZIRP23EP.js.map} +0 -0
- /package/dist/{linear-ingester-PLES2BRS.js.map → ledger-TWZTGDFA.js.map} +0 -0
- /package/dist/{output-manager-JNMEAXFO.js.map → linear-ingester-XXPAZZRW.js.map} +0 -0
- /package/dist/{tiered-storage-OP74NPJY.js.map → output-manager-RVJ37XKA.js.map} +0 -0
- /package/dist/{trie-agent-6SWUHCVO.js.map → tiered-storage-Z3YCR465.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/agent/trie-agent.ts","../src/agent/risk-predictor.ts","../src/agent/escalation.ts","../src/agent/meta-learning.ts"],"sourcesContent":["/**\n * Trie Agent - A proactive, intelligent agent that watches over your codebase\n * \n * The Trie Agent:\n * - Synthesizes insights from multiple skills\n * - Speaks conversationally, like a helpful colleague\n * - Suggests specific actions, not just problems\n * - Tracks patterns over time and learns\n * - Anticipates issues before they become critical\n * \n * Integration:\n * - Uses existing memory infrastructure (issue-store, global-memory)\n * - Persistent insight storage (survives restarts)\n * - Goal tracking and hypothesis validation\n * - Optionally enhances with LLM when ANTHROPIC_API_KEY is available\n */\n\nimport type { Issue } from '../types/index.js';\nimport { storeIssues, autoResolveIssues, getIssueHash } from '../memory/issue-store.js';\nimport { recordToGlobalMemory, findCrossProjectPatterns } from '../memory/global-memory.js';\nimport { getHistoricalInsights } from '../memory/compactor.js';\nimport { isAIAvailable, runAIAnalysis } from '../ai/client.js';\nimport { basename } from 'path';\nimport { getInsightStore, type Insight } from './insight-store.js';\nimport { getProjectState } from './project-state.js';\nimport { getGoalManager } from './goal-manager.js';\nimport { getRiskPredictor } from './risk-predictor.js';\nimport { getHypothesisEngine } from './hypothesis.js';\nimport { getEscalationManager } from './escalation.js';\nimport { getMetaLearner } from './meta-learning.js';\nimport { GotchaPredictor } from './gotcha-predictor.js';\nimport { ContextGraph } from '../context/graph.js';\nimport { getStorage } from '../storage/tiered-storage.js';\nimport type { Gotcha } from '../types/signal.js';\n\nexport type { Insight } from './insight-store.js';\n\n// Personality phrases for different situations\nconst PERSONALITY = {\n greetings: [\n \"Hey, quick heads up...\",\n \"Noticed something while scanning...\",\n \"Worth mentioning...\",\n \"Just so you know...\",\n \"Spotted this...\",\n ],\n warnings: [\n \"This needs your attention:\",\n \"I'd pause on this:\",\n \"Before you push...\",\n \"Hold up —\",\n \"Important:\",\n ],\n celebrations: [\n \"Nice work!\",\n \"Good catch!\",\n \"That's better.\",\n \"Clean.\",\n \"Progress.\",\n ],\n suggestions: [\n \"You might want to\",\n \"Consider\",\n \"Suggestion:\",\n \"Quick win:\",\n \"Idea:\",\n ],\n questions: [\n \"Did you mean to\",\n \"Should this\",\n \"Is it intentional that\",\n \"Quick question:\",\n ],\n};\n\nexport class TrieAgent {\n private projectPath: string;\n private projectName: string;\n private lastIssueHashes: Set<string> = new Set();\n private initialized: boolean = false;\n \n // Persistent stores\n private insightStore;\n private projectState;\n \n // Agency modules\n private goalManager;\n private riskPredictor;\n private hypothesisEngine;\n private escalationManager;\n private metaLearner;\n private gotchaPredictor;\n \n constructor(projectPath: string) {\n this.projectPath = projectPath;\n this.projectName = basename(projectPath);\n \n // Initialize persistent stores\n this.insightStore = getInsightStore(projectPath);\n this.projectState = getProjectState(projectPath);\n \n // Initialize agency modules\n this.goalManager = getGoalManager(projectPath);\n this.riskPredictor = getRiskPredictor(projectPath);\n this.hypothesisEngine = getHypothesisEngine(projectPath);\n this.escalationManager = getEscalationManager(projectPath);\n this.metaLearner = getMetaLearner(projectPath);\n this.gotchaPredictor = new GotchaPredictor(projectPath, new ContextGraph(projectPath));\n }\n \n /**\n * Initialize the agent - loads persistent state and historical data\n */\n async initialize(): Promise<void> {\n if (this.initialized) return;\n \n try {\n // Load persistent stores\n await this.insightStore.load();\n await this.projectState.load();\n \n // Update last active timestamp\n await this.projectState.touchActive();\n \n // Get historical context from existing memory infrastructure\n const historical = await getHistoricalInsights(this.projectPath);\n \n // If we have history, we can detect trends\n if (historical && historical.totalHistoricalIssues > 0) {\n const trend = historical.improvementTrend;\n if (trend === 'improving' && this.canCreateInsight('progress-trend')) {\n await this.addInsight(this.createInsight({\n type: 'celebration',\n message: `${this.pick(PERSONALITY.celebrations)} Your code quality has been improving over time.`,\n priority: 2,\n category: 'progress',\n }));\n await this.markInsightCreated('progress-trend');\n } else if (trend === 'declining' && this.canCreateInsight('progress-trend')) {\n await this.addInsight(this.createInsight({\n type: 'observation',\n message: `${this.pick(PERSONALITY.greetings)} Issue count has been trending up. Might be worth a focused cleanup session.`,\n suggestedAction: 'Run `trie scan` and address top issues',\n priority: 5,\n category: 'quality',\n }));\n await this.markInsightCreated('progress-trend');\n }\n }\n \n this.initialized = true;\n } catch {\n // Memory might not exist yet - that's fine\n this.initialized = true;\n }\n }\n \n /**\n * Add an insight to persistent storage\n */\n async addInsight(insight: Insight): Promise<boolean> {\n return this.insightStore.addInsight(insight);\n }\n \n /**\n * Restart the agent (reload state from disk)\n */\n async restart(): Promise<void> {\n this.initialized = false;\n await this.insightStore.reload();\n await this.projectState.reload();\n await this.initialize();\n }\n \n /**\n * Load state from disk (for testing)\n */\n async loadState(): Promise<{ goals: any[]; riskBudget: any }> {\n await this.projectState.load();\n return {\n goals: this.projectState.getAllGoals(),\n riskBudget: this.projectState.getRiskBudget(),\n };\n }\n \n /**\n * Process new issues from a scan and generate insights\n * Stores issues in memory and optionally uses LLM for deeper analysis\n */\n async processIssues(issues: Issue[], context: { filesChanged?: string[]; isWatchMode: boolean }): Promise<Insight[]> {\n const newInsights: Insight[] = [];\n \n // 1. Store issues in memory infrastructure\n try {\n await storeIssues(issues, this.projectName, this.projectPath);\n await recordToGlobalMemory(issues, this.projectName, this.projectPath);\n \n // Auto-resolve issues no longer detected in changed files\n if (context.filesChanged && context.filesChanged.length > 0) {\n const currentHashes = new Set(issues.map(i => getIssueHash(i)));\n await autoResolveIssues(currentHashes, context.filesChanged, this.projectPath);\n }\n } catch {\n // Memory errors shouldn't break the agent\n }\n \n // 2. Detect changes from last scan\n const currentHashes = new Set(issues.map(i => `${i.file}:${i.line}:${i.issue.slice(0, 50)}`));\n const newIssues = issues.filter(i => !this.lastIssueHashes.has(`${i.file}:${i.line}:${i.issue.slice(0, 50)}`));\n const fixedCount = [...this.lastIssueHashes].filter(h => !currentHashes.has(h)).length;\n \n // 3. Generate heuristic insights (with cooldowns to avoid duplicates)\n \n // Accessibility issues with visual QA recommendation\n const accessibilityIssues = issues.filter(i => \n i.agent === 'accessibility' && \n (i.severity === 'critical' || i.severity === 'serious')\n );\n \n if (accessibilityIssues.length >= 2 && this.canCreateInsight('accessibility-visual-qa')) {\n const critical = accessibilityIssues.filter(i => i.severity === 'critical');\n const serious = accessibilityIssues.filter(i => i.severity === 'serious');\n \n const breakdown: Record<string, number> = {};\n if (critical.length > 0) breakdown['critical'] = critical.length;\n if (serious.length > 0) breakdown['serious'] = serious.length;\n \n const affectedFiles = [...new Set(accessibilityIssues.map(i => i.file))];\n const examples = [...critical, ...serious]\n .slice(0, 3)\n .map(i => `${basename(i.file)}:${i.line} - ${i.issue.slice(0, 60)}`);\n \n const insight = this.createInsight({\n type: 'suggestion',\n message: `Found ${accessibilityIssues.length} accessibility issue${accessibilityIssues.length > 1 ? 's' : ''} that could block users. Screenshots would help validate real impact.`,\n suggestedAction: 'Capture screenshots for visual analysis',\n actionCommand: 'trie_visual_qa_browser url:\"http://localhost:3000\"',\n priority: 7,\n category: 'quality',\n relatedIssues: accessibilityIssues.map(i => i.id),\n details: {\n affectedFiles: affectedFiles.map(f => basename(f)),\n issueBreakdown: breakdown,\n examples,\n },\n });\n newInsights.push(insight);\n await this.addInsight(insight);\n await this.markInsightCreated('accessibility-visual-qa');\n }\n \n // Security concerns get immediate attention\n const securityIssues = issues.filter(i => \n i.category === 'security' || \n i.issue.toLowerCase().includes('secret') ||\n i.issue.toLowerCase().includes('vulnerability') ||\n i.issue.toLowerCase().includes('injection') ||\n i.issue.toLowerCase().includes('xss')\n );\n \n if (securityIssues.length > 0 && this.canCreateInsight('security-warning')) {\n const critical = securityIssues.filter(i => i.severity === 'critical');\n const serious = securityIssues.filter(i => i.severity === 'serious');\n if (critical.length > 0 || serious.length >= 2) {\n // Build severity breakdown\n const breakdown: Record<string, number> = {};\n if (critical.length > 0) breakdown['critical'] = critical.length;\n if (serious.length > 0) breakdown['serious'] = serious.length;\n \n // Get unique affected files\n const affectedFiles = [...new Set(securityIssues.map(i => i.file))];\n \n // Get example issues (most severe first)\n const examples = [...critical, ...serious]\n .slice(0, 3)\n .map(i => `${basename(i.file)}:${i.line} - ${i.issue.slice(0, 60)}`);\n \n const insight = this.createInsight({\n type: 'warning',\n message: `Found ${securityIssues.length} security issue${securityIssues.length > 1 ? 's' : ''} that could expose your app.`,\n suggestedAction: `Review ${affectedFiles.length} file${affectedFiles.length > 1 ? 's' : ''} immediately`,\n actionCommand: 'trie scan --skill security',\n priority: 10,\n category: 'security',\n relatedIssues: securityIssues.map(i => i.id),\n details: {\n affectedFiles: affectedFiles.map(f => basename(f)),\n issueBreakdown: breakdown,\n examples,\n },\n });\n newInsights.push(insight);\n await this.addInsight(insight);\n await this.markInsightCreated('security-warning');\n }\n }\n \n // New issues from recent changes\n if (newIssues.length >= 3 && context.filesChanged && context.filesChanged.length > 0 && this.canCreateInsight('new-issues')) {\n const affectedFiles = [...new Set(newIssues.map(i => basename(i.file)))];\n const filesChanged = context.filesChanged.map(f => basename(f));\n \n // Breakdown by severity\n const breakdown: Record<string, number> = {};\n const critical = newIssues.filter(i => i.severity === 'critical');\n const serious = newIssues.filter(i => i.severity === 'serious');\n const moderate = newIssues.filter(i => i.severity === 'moderate');\n if (critical.length > 0) breakdown['critical'] = critical.length;\n if (serious.length > 0) breakdown['serious'] = serious.length;\n if (moderate.length > 0) breakdown['moderate'] = moderate.length;\n \n // Get example issues\n const examples = newIssues\n .sort((a, b) => {\n const sev: Record<string, number> = { critical: 3, serious: 2, moderate: 1, minor: 0, low: 0 };\n return (sev[b.severity] || 0) - (sev[a.severity] || 0);\n })\n .slice(0, 3)\n .map(i => `${basename(i.file)}:${i.line} - ${i.issue.slice(0, 50)}`);\n \n const insight = this.createInsight({\n type: 'observation',\n message: `Recent changes introduced ${newIssues.length} new issues in ${affectedFiles.slice(0, 3).join(', ')}.`,\n suggestedAction: `Review ${affectedFiles.length} affected file${affectedFiles.length > 1 ? 's' : ''}`,\n priority: 6,\n category: 'quality',\n details: {\n affectedFiles: affectedFiles.slice(0, 8),\n issueBreakdown: breakdown,\n examples,\n comparison: `Changed: ${filesChanged.slice(0, 3).join(', ')}${filesChanged.length > 3 ? ` +${filesChanged.length - 3} more` : ''}`,\n },\n });\n newInsights.push(insight);\n await this.addInsight(insight);\n await this.markInsightCreated('new-issues');\n }\n \n // Celebrate fixes\n if (fixedCount > 0 && newIssues.length === 0 && this.canCreateInsight('celebration')) {\n const insight = this.createInsight({\n type: 'celebration',\n message: `${this.pick(PERSONALITY.celebrations)} ${fixedCount} issue${fixedCount > 1 ? 's' : ''} resolved.`,\n priority: 3,\n category: 'progress',\n });\n newInsights.push(insight);\n await this.addInsight(insight);\n await this.markInsightCreated('celebration');\n }\n \n // === AUTONOMOUS HYPOTHESIS GENERATION ===\n // After every scan, check if Claude should generate new hypotheses\n // This enables the agent to continuously learn and form theories about code quality\n if (issues.length >= 10 && this.canCreateInsight('hypothesis-generation')) {\n try {\n const patterns: string[] = [];\n const observations: string[] = [];\n \n // Observe patterns from this scan\n if (newIssues.length > issues.length * 0.3) {\n observations.push(`High new issue rate: ${newIssues.length} new out of ${issues.length} total`);\n }\n \n const fileFreq: Record<string, number> = {};\n for (const issue of issues) {\n fileFreq[issue.file] = (fileFreq[issue.file] || 0) + 1;\n }\n const hotFiles = Object.entries(fileFreq).filter(([, count]) => count >= 3);\n if (hotFiles.length > 0) {\n patterns.push(`Hotspot files: ${hotFiles.map(([f]) => basename(f)).join(', ')}`);\n }\n \n // Try AI-powered hypothesis generation\n const generated = await this.hypothesisEngine.generateHypothesesWithAI({\n recentIssues: issues.map(i => ({ issue: i, score: 1 })),\n patterns,\n observations,\n });\n \n // Create insights for new hypotheses\n for (const hypothesis of generated) {\n const insight = this.createInsight({\n type: 'observation',\n message: `${this.pick(PERSONALITY.questions)} New hypothesis to test: \"${hypothesis.statement}\"`,\n context: `Confidence: ${Math.round(hypothesis.confidence * 100)}%`,\n suggestedAction: `Monitor this pattern over time`,\n priority: 4,\n category: 'pattern',\n details: {\n hypothesis: hypothesis.statement,\n testCriteria: hypothesis.testCriteria || 'Collecting evidence...',\n confidence: Math.round(hypothesis.confidence * 100),\n },\n });\n newInsights.push(insight);\n await this.addInsight(insight);\n }\n \n if (generated.length > 0) {\n await this.markInsightCreated('hypothesis-generation');\n }\n } catch (error) {\n // Hypothesis generation is best-effort, don't break the scan\n }\n }\n \n // === AUTONOMOUS PATTERN DISCOVERY ===\n // Discover patterns from accumulated issues automatically\n // This makes patterns appear naturally from your workflow\n if (issues.length >= 5 && this.canCreateInsight('pattern-discovery')) {\n try {\n const { IncidentIndex } = await import('../context/incident-index.js');\n const { TriePatternDiscovery } = await import('../agent/pattern-discovery.js');\n const { ContextGraph } = await import('../context/graph.js');\n \n const graph = new ContextGraph(this.projectPath);\n const incidentIndex = await IncidentIndex.build(graph, this.projectPath);\n const discovery = new TriePatternDiscovery(graph, incidentIndex);\n \n // Discover hot patterns with lower threshold for faster discovery\n const hotPatterns = discovery.discoverHotPatterns(2);\n let patternsAdded = 0;\n \n for (const hot of hotPatterns.slice(0, 5)) { // Top 5 hot patterns\n const existingPatterns = await graph.listNodes();\n const alreadyExists = existingPatterns.some(\n n => n.type === 'pattern' && (n.data as any).description?.includes(hot.path)\n );\n \n if (!alreadyExists) {\n await graph.addNode('pattern', {\n description: `${hot.type === 'directory' ? 'Directory' : 'File'} hot zone: ${hot.path}`,\n appliesTo: [hot.path],\n confidence: Math.min(0.95, hot.confidence),\n occurrences: hot.incidentCount,\n firstSeen: new Date().toISOString(),\n lastSeen: new Date().toISOString(),\n isAntiPattern: hot.incidentCount >= 3,\n source: 'local'\n });\n patternsAdded++;\n }\n }\n \n // Create insight if patterns were discovered\n if (patternsAdded > 0) {\n const insight = this.createInsight({\n type: 'observation',\n message: `${this.pick(PERSONALITY.greetings)} Discovered ${patternsAdded} pattern${patternsAdded > 1 ? 's' : ''} in your codebase.`,\n suggestedAction: `Check Memory → Learned Patterns to see`,\n priority: 5,\n category: 'pattern',\n details: {\n patternsCount: patternsAdded,\n topPattern: hotPatterns[0]?.path,\n },\n });\n newInsights.push(insight);\n await this.addInsight(insight);\n await this.markInsightCreated('pattern-discovery');\n }\n } catch (error) {\n // Pattern discovery is best-effort\n }\n }\n \n // Check for recurring patterns across projects (from global memory)\n if (this.canCreateInsight('pattern-suggestion')) {\n try {\n const globalPatterns = await findCrossProjectPatterns();\n const crossProjectPattern = globalPatterns.find(p => p.projects.length > 1 && p.occurrences > 3);\n if (crossProjectPattern) {\n const insight = this.createInsight({\n type: 'suggestion',\n message: `\"${crossProjectPattern.description}\" appears in ${crossProjectPattern.projects.length} projects. Consider a shared lint rule.`,\n priority: 4,\n category: 'pattern',\n });\n newInsights.push(insight);\n await this.addInsight(insight);\n await this.markInsightCreated('pattern-suggestion');\n }\n } catch {\n // Global memory might not be available\n }\n }\n \n // Pre-push warning (with cooldown)\n if (context.isWatchMode && this.shouldWarnBeforePush(issues) && this.canCreateInsight('pre-push-warning')) {\n const criticalIssues = issues.filter(i => i.severity === 'critical');\n const seriousIssues = issues.filter(i => i.severity === 'serious');\n const moderateIssues = issues.filter(i => i.severity === 'moderate');\n \n // Build severity breakdown\n const breakdown: Record<string, number> = {};\n if (criticalIssues.length > 0) breakdown['critical'] = criticalIssues.length;\n if (seriousIssues.length > 0) breakdown['serious'] = seriousIssues.length;\n if (moderateIssues.length > 0) breakdown['moderate'] = moderateIssues.length;\n \n // Get affected files by severity\n const criticalFiles = [...new Set(criticalIssues.map(i => basename(i.file)))];\n const seriousFiles = [...new Set(seriousIssues.map(i => basename(i.file)))];\n const affectedFiles = [...new Set([...criticalFiles, ...seriousFiles])].slice(0, 5);\n \n // Get example issues (highest severity first)\n const examples = [...criticalIssues, ...seriousIssues]\n .slice(0, 4)\n .map(i => `${basename(i.file)}:${i.line} - ${i.issue.slice(0, 50)}`);\n \n // Determine trend if we have history\n const totalBlocking = criticalIssues.length + seriousIssues.length;\n const trend = this.lastIssueHashes.size > 0 \n ? (totalBlocking > this.lastIssueHashes.size ? 'worsening' : 'improving')\n : undefined;\n \n // Build details object, only including defined values\n const insightDetails: NonNullable<Insight['details']> = {\n affectedFiles,\n issueBreakdown: breakdown,\n examples,\n };\n if (trend) insightDetails.trend = trend;\n if (moderateIssues.length > 0) insightDetails.comparison = `+${moderateIssues.length} moderate (non-blocking)`;\n \n const insight = this.createInsight({\n type: 'warning',\n message: `${totalBlocking} issue${totalBlocking > 1 ? 's' : ''} need attention before pushing.`,\n suggestedAction: 'Run pre-push check',\n actionCommand: 'trie check',\n priority: 8,\n category: 'quality',\n details: insightDetails,\n });\n newInsights.push(insight);\n await this.addInsight(insight);\n await this.markInsightCreated('pre-push-warning');\n }\n \n // 4. Optionally enhance with LLM for deeper insights\n if (isAIAvailable() && issues.length > 0 && newIssues.length > 0) {\n const aiInsights = await this.generateAIInsights(issues, newIssues);\n newInsights.push(...aiInsights);\n }\n \n // ==========================================================================\n // 5. AGENCY: Goals, Hypotheses, Risk Prediction\n // ==========================================================================\n \n // Phase 2: Autonomous Goals - Analyze patterns and track progress\n if (this.canCreateInsight('goal-progress')) {\n try {\n const patterns = await this.goalManager.analyzeIncidentPatterns();\n \n // Generate goals from significant patterns (high confidence, enough occurrences)\n const significantPatterns = patterns.filter(p => p.confidence >= 0.6 && p.currentValue >= 3);\n if (significantPatterns.length > 0) {\n // Auto-generate goals which creates insights internally\n await this.goalManager.autoGenerateGoals();\n }\n \n // Update goal progress and check achievements\n await this.goalManager.updateGoalProgress();\n \n // Check goal progress and create insights for major milestones\n const goals = this.projectState.getAllGoals();\n for (const goal of goals.filter(g => g.status === 'active')) {\n // Calculate percent complete\n const startVal = goal.startValue ?? goal.currentValue;\n if (startVal > 0 && goal.currentValue <= startVal) {\n const percentComplete = Math.round((1 - goal.currentValue / startVal) * 100);\n if (percentComplete >= 50 && this.canCreateInsight(`goal-${goal.id}`)) {\n const insight = this.createInsight({\n type: 'celebration',\n message: `Goal \"${goal.description}\" is ${percentComplete}% complete! ${goal.currentValue} issues remaining (started at ${startVal}).`,\n priority: 4,\n category: 'progress',\n details: {\n affectedFiles: goal.category ? [goal.category] : [],\n comparison: `${startVal} → ${goal.currentValue}`,\n },\n });\n newInsights.push(insight);\n await this.addInsight(insight);\n await this.markInsightCreated(`goal-${goal.id}`);\n }\n }\n }\n \n await this.markInsightCreated('goal-progress');\n } catch {\n // Goal analysis is optional\n }\n }\n \n // Phase 3: Risk Prediction - Warn about high-risk files\n if (context.filesChanged && context.filesChanged.length > 0 && this.canCreateInsight('risk-prediction')) {\n try {\n const riskSummary = await this.riskPredictor.predictRiskTrend(context.filesChanged);\n \n if (riskSummary.overallRisk >= 50) {\n const highRiskFactors = riskSummary.factors.filter(f => f.reasons.length > 0);\n \n if (highRiskFactors.length > 0) {\n const topFile = highRiskFactors[0];\n const insight = this.createInsight({\n type: 'warning',\n message: `Risk score ${Math.round(riskSummary.overallRisk)}/100 for changed files (${riskSummary.trend}). ${topFile ? basename(topFile.file) + ' is high-risk.' : ''}`,\n suggestedAction: 'Consider extra review before pushing',\n priority: 7,\n category: 'quality',\n details: {\n affectedFiles: highRiskFactors.slice(0, 5).map(f => basename(f.file)),\n trend: riskSummary.trend === 'increasing' ? 'worsening' : riskSummary.trend === 'decreasing' ? 'improving' : 'stable',\n },\n });\n newInsights.push(insight);\n await this.addInsight(insight);\n await this.markInsightCreated('risk-prediction');\n }\n }\n } catch {\n // Risk prediction is optional\n }\n }\n\n // Phase 3b: Gotcha Prediction - Store potential risks in ledger (runs independently of risk-prediction)\n if (context.filesChanged && context.filesChanged.length > 0) {\n try {\n const gotchas = await this.gotchaPredictor.predictGotchas(context.filesChanged);\n const storage = getStorage(this.projectPath);\n for (const gotcha of gotchas) {\n if (this.canCreateInsight(`gotcha-${gotcha.id}`)) {\n const explanation = await this.gotchaPredictor.synthesizeGotchaExplanation(gotcha);\n const insight = this.createInsight({\n type: 'warning',\n message: `[Gotcha] ${gotcha.message}`,\n context: explanation,\n suggestedAction: gotcha.recommendation,\n priority: gotcha.riskLevel === 'critical' ? 9 : 7,\n category: 'quality',\n details: {\n affectedFiles: context.filesChanged.map(f => basename(f)),\n examples: [gotcha.message, explanation],\n }\n });\n newInsights.push(insight);\n await this.addInsight(insight);\n await this.markInsightCreated(`gotcha-${gotcha.id}`);\n }\n // Store gotcha in ledger for Ledger view (always store, regardless of insight cooldown)\n const primaryFile = context.filesChanged?.[0];\n const ledgerGotcha: Gotcha = {\n id: gotcha.id,\n message: gotcha.message,\n confidence: gotcha.confidence,\n riskLevel: gotcha.riskLevel,\n recommendation: gotcha.recommendation,\n ...(primaryFile && { file: primaryFile }),\n timestamp: new Date().toISOString(),\n ...(gotcha.precedentId && { precedentId: gotcha.precedentId }),\n tags: gotcha.evidence.matchingPatterns,\n evidence: gotcha.evidence,\n resolved: false,\n };\n await storage.storeGotcha(ledgerGotcha);\n }\n } catch {\n // Gotcha prediction is optional\n }\n }\n \n // Phase 3: Hypothesis Validation - Check and update hypotheses\n if (this.canCreateInsight('hypothesis-update')) {\n try {\n // Auto-generate hypotheses if we don't have many\n const hypotheses = this.projectState.getAllHypotheses();\n const testingHypotheses = hypotheses.filter(h => h.status === 'testing');\n \n if (testingHypotheses.length < 3) {\n await this.hypothesisEngine.autoGenerateHypotheses();\n }\n \n // Check for newly validated/invalidated hypotheses and create insights\n const validatedHypotheses = hypotheses.filter(h => \n h.status === 'validated' && \n h.validatedAt && \n Date.now() - new Date(h.validatedAt).getTime() < 24 * 60 * 60 * 1000 // Within last 24h\n );\n \n for (const hypothesis of validatedHypotheses.slice(0, 2)) {\n if (this.canCreateInsight(`hypothesis-${hypothesis.id}`)) {\n const insight = this.createInsight({\n type: 'celebration',\n message: `Hypothesis validated: \"${hypothesis.statement}\" (${Math.round(hypothesis.confidence * 100)}% confidence)`,\n priority: 5,\n category: 'pattern',\n });\n newInsights.push(insight);\n await this.addInsight(insight);\n await this.markInsightCreated(`hypothesis-${hypothesis.id}`);\n }\n }\n \n await this.markInsightCreated('hypothesis-update');\n } catch {\n // Hypothesis validation is optional\n }\n }\n \n // Phase 4: Auto-Escalation - Escalate critical security issues\n const criticalSecurityIssues = issues.filter(i => \n i.severity === 'critical' && \n (i.category === 'security' || i.issue.toLowerCase().includes('secret'))\n );\n \n if (criticalSecurityIssues.length > 0) {\n try {\n const result = await this.escalationManager.escalateIssues(criticalSecurityIssues);\n if (result.action === 'auto_escalated' && result.message) {\n const insight = this.createInsight({\n type: 'observation',\n message: `Auto-escalated ${criticalSecurityIssues.length} critical security issue(s). Check your notifications.`,\n priority: 9,\n category: 'security',\n details: {\n affectedFiles: criticalSecurityIssues.slice(0, 5).map(i => basename(i.file)),\n examples: criticalSecurityIssues.slice(0, 3).map(i => i.issue.slice(0, 60)),\n },\n });\n newInsights.push(insight);\n await this.addInsight(insight);\n }\n } catch {\n // Escalation is best-effort\n }\n }\n \n // Phase 4: Meta-Learning - Note: actual feedback recording happens when user interacts\n // Here we just track that insights were shown (for latency tracking)\n // The user feedback is recorded via markInsightHelpful/dismissInsight/markInsightActedOn\n \n // Update state\n this.lastIssueHashes = currentHashes;\n \n // Record scan timestamp\n await this.projectState.recordScan();\n \n // Adapt scan frequency based on risk (Phase 2)\n try {\n const riskLevel = issues.filter(i => i.severity === 'critical').length > 0 ? 'critical' :\n issues.filter(i => i.severity === 'serious').length >= 3 ? 'high' :\n issues.length > 10 ? 'medium' : 'low';\n \n // Calculate and store adaptive scan frequency\n const { calculateAdaptiveScanFrequency } = await import('./goal-manager.js');\n const result = await calculateAdaptiveScanFrequency(riskLevel);\n await this.projectState.setScanFrequency(result.frequencyMs);\n } catch {\n // Scan frequency adaptation is optional\n }\n \n // Auto-resolve nudges for issues that were fixed\n try {\n const { getStorage } = await import('../storage/tiered-storage.js');\n const storage = getStorage(this.projectPath);\n \n // Get issue IDs that were resolved (no longer in current scan)\n const resolvedIssueIds = [...this.lastIssueHashes]\n .filter(h => !currentHashes.has(h))\n .map(h => {\n // Convert hash to potential issue ID\n // Hash format is \"file:line:issue_start\"\n // Issue IDs are typically like \"issueId\" or include file/line info\n return h.split(':').join('-');\n });\n \n if (resolvedIssueIds.length > 0) {\n const resolvedCount = await storage.autoResolveFixedNudges(resolvedIssueIds);\n if (resolvedCount > 0) {\n console.debug(`[Agent] Auto-resolved ${resolvedCount} nudge${resolvedCount !== 1 ? 's' : ''} for fixed issues`);\n }\n }\n } catch {\n // Auto-resolve is best-effort, don't break the scan\n }\n \n return newInsights;\n }\n \n /**\n * Use LLM to generate deeper insights (optional, requires ANTHROPIC_API_KEY)\n */\n private async generateAIInsights(_allIssues: Issue[], newIssues: Issue[]): Promise<Insight[]> {\n const insights: Insight[] = [];\n \n try {\n // Only analyze if we have significant new issues\n if (newIssues.length < 2) return insights;\n \n const issuesSummary = newIssues.slice(0, 10).map(i => ({\n severity: i.severity,\n issue: i.issue.slice(0, 100),\n file: basename(i.file),\n agent: i.agent\n }));\n \n const result = await runAIAnalysis({\n systemPrompt: `You are a helpful code reviewer. Analyze these issues and provide ONE brief, conversational insight.\nBe specific and actionable. Speak like a helpful colleague, not a system.\nKeep your response under 100 words. Focus on the most important pattern or concern.`,\n userPrompt: `New issues found:\\n${JSON.stringify(issuesSummary, null, 2)}\n\nWhat's the most important thing the developer should know? Provide a brief, conversational insight.`,\n maxTokens: 200,\n temperature: 0.7\n });\n \n if (result.success && result.content) {\n const insight = this.createInsight({\n type: 'observation',\n message: result.content.trim(),\n priority: 5,\n category: 'general',\n });\n insights.push(insight);\n await this.addInsight(insight);\n }\n } catch {\n // AI analysis is optional, don't fail\n }\n \n return insights;\n }\n \n /**\n * Get active insights (not dismissed, still relevant)\n */\n getActiveInsights(): Insight[] {\n return this.insightStore.getActiveInsights();\n }\n \n /**\n * Dismiss an insight\n */\n async dismissInsight(insightId: string): Promise<boolean> {\n const result = await this.insightStore.dismissInsight(insightId);\n \n // Record feedback for meta-learning (Phase 4)\n if (result) {\n await this.projectState.recordInsightFeedback('dismissed');\n }\n \n return result;\n }\n \n /**\n * Record that a user found an insight helpful\n */\n async markInsightHelpful(_insightId: string): Promise<void> {\n await this.projectState.recordInsightFeedback('helpful');\n }\n \n /**\n * Record that a user acted on an insight\n */\n async markInsightActedOn(_insightId: string): Promise<void> {\n await this.projectState.recordInsightFeedback('acted');\n }\n \n /**\n * Get insight statistics\n */\n getInsightStats() {\n return this.insightStore.getStats();\n }\n \n /**\n * Get agent metrics (for dashboard display)\n */\n getAgentMetrics() {\n return this.projectState.getMetrics();\n }\n \n /**\n * Check if in quiet hours\n */\n isQuietHours(): boolean {\n return this.projectState.isQuietHours();\n }\n \n /**\n * Check if in crunch mode\n */\n isInCrunchMode(): boolean {\n return this.projectState.isInCrunchMode();\n }\n \n /**\n * Get the insight store (for advanced operations)\n */\n getInsightStore() {\n return this.insightStore;\n }\n \n /**\n * Get the project state (for advanced operations)\n */\n getProjectState() {\n return this.projectState;\n }\n \n /**\n * Get agency modules (for watch mode integration)\n */\n getGoalManager() {\n return this.goalManager;\n }\n \n getRiskPredictor() {\n return this.riskPredictor;\n }\n \n getHypothesisEngine() {\n return this.hypothesisEngine;\n }\n \n getEscalationManager() {\n return this.escalationManager;\n }\n \n getMetaLearner() {\n return this.metaLearner;\n }\n \n /**\n * Get a rich agency status for display in watch mode\n */\n async getAgencyStatus(): Promise<{\n goals: { active: number; completed: number; topGoal?: string };\n hypotheses: { testing: number; validated: number; topHypothesis?: string };\n riskLevel: 'low' | 'medium' | 'high' | 'critical';\n scanFrequency: number;\n effectiveness: number;\n isQuietHours: boolean;\n }> {\n const goals = this.projectState.getAllGoals();\n const activeGoals = goals.filter((g: { status: string }) => g.status === 'active');\n const completedGoals = goals.filter((g: { status: string }) => g.status === 'achieved');\n \n const hypotheses = this.projectState.getAllHypotheses();\n const testingHypotheses = hypotheses.filter((h: { status: string }) => h.status === 'testing');\n const validatedHypotheses = hypotheses.filter((h: { status: string }) => h.status === 'validated');\n \n const metrics = this.projectState.getMetrics();\n const budget = this.projectState.getRiskBudget();\n \n // Calculate daily actions remaining\n const dailyActionsRemaining = budget.daily - budget.usedToday;\n \n // Calculate overall risk level\n let riskLevel: 'low' | 'medium' | 'high' | 'critical' = 'low';\n if (dailyActionsRemaining <= 1) riskLevel = 'critical';\n else if (dailyActionsRemaining <= 3) riskLevel = 'high';\n else if (dailyActionsRemaining <= 5) riskLevel = 'medium';\n \n // Calculate effectiveness using correct property names\n const totalFeedback = metrics.helpfulInsights + metrics.dismissedInsights + metrics.actedOnInsights;\n const effectiveness = totalFeedback > 0 \n ? Math.round(((metrics.helpfulInsights + metrics.actedOnInsights) / totalFeedback) * 100)\n : 100; // Default to 100% if no feedback yet\n \n // Build result with conditional optional properties\n const topGoal = activeGoals[0]?.description;\n const topHypothesis = testingHypotheses[0]?.statement?.slice(0, 50);\n \n const result: {\n goals: { active: number; completed: number; topGoal?: string };\n hypotheses: { testing: number; validated: number; topHypothesis?: string };\n riskLevel: 'low' | 'medium' | 'high' | 'critical';\n scanFrequency: number;\n effectiveness: number;\n isQuietHours: boolean;\n } = {\n goals: {\n active: activeGoals.length,\n completed: completedGoals.length,\n },\n hypotheses: {\n testing: testingHypotheses.length,\n validated: validatedHypotheses.length,\n },\n riskLevel,\n scanFrequency: this.projectState.getScanFrequencyMs(),\n effectiveness,\n isQuietHours: this.projectState.isQuietHours(),\n };\n \n if (topGoal) result.goals.topGoal = topGoal;\n if (topHypothesis) result.hypotheses.topHypothesis = topHypothesis;\n \n return result;\n }\n \n /**\n * Get a summary for the current state\n */\n getSummary(issues: Issue[]): string {\n const critical = issues.filter(i => i.severity === 'critical').length;\n const serious = issues.filter(i => i.severity === 'serious').length;\n const total = issues.length;\n \n if (total === 0) {\n return \"All clear. Your code looks good.\";\n }\n \n if (critical > 0) {\n return `${critical} critical issue${critical > 1 ? 's' : ''} need${critical === 1 ? 's' : ''} immediate attention.`;\n }\n \n if (serious > 0) {\n return `${serious} serious issue${serious > 1 ? 's' : ''} worth reviewing before shipping.`;\n }\n \n return `${total} minor thing${total > 1 ? 's' : ''} to polish when you have time.`;\n }\n \n // === Private helpers ===\n \n private shouldWarnBeforePush(issues: Issue[]): boolean {\n const critical = issues.filter(i => i.severity === 'critical').length;\n const serious = issues.filter(i => i.severity === 'serious').length;\n return critical > 0 || serious >= 3;\n }\n \n /**\n * Check if we should create an insight of this type (cooldown not expired)\n */\n private canCreateInsight(insightKey: string): boolean {\n return this.insightStore.canCreateInsight(insightKey);\n }\n \n /**\n * Mark that we created an insight of this type\n */\n private async markInsightCreated(insightKey: string): Promise<void> {\n await this.insightStore.markInsightCreated(insightKey);\n }\n \n private createInsight(params: Omit<Insight, 'id' | 'timestamp' | 'dismissed' | 'relatedIssues'> & { relatedIssues?: string[] }): Insight {\n return {\n id: `insight-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,\n timestamp: Date.now(),\n dismissed: false,\n relatedIssues: params.relatedIssues || [],\n ...params,\n };\n }\n \n private pick<T>(arr: T[]): T {\n return arr[Math.floor(Math.random() * arr.length)] as T;\n }\n}\n\n// Singleton instance per project\nconst agentInstances: Map<string, TrieAgent> = new Map();\n\nexport function getTrieAgent(projectPath: string): TrieAgent {\n let agent = agentInstances.get(projectPath);\n if (!agent) {\n agent = new TrieAgent(projectPath);\n agentInstances.set(projectPath, agent);\n }\n return agent;\n}\n\n","/**\n * Risk Predictor - Predictive risk scoring with trend analysis\n * \n * Features:\n * - Multi-factor risk scoring\n * - Trend analysis (increasing/stable/decreasing)\n * - File-level risk predictions\n * - Historical incident correlation\n * - Proactive risk warnings\n */\n\nimport type { Insight } from './insight-store.js';\nimport { getInsightStore } from './insight-store.js';\nimport { searchIssues, type StoredIssue } from '../memory/issue-store.js';\nimport { basename, dirname } from 'path';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Risk factor contributing to overall risk\n */\nexport interface RiskFactor {\n name: string;\n weight: number; // 0-1, contribution to risk\n value: number; // Current measured value\n description: string;\n trend?: 'increasing' | 'stable' | 'decreasing';\n}\n\n/**\n * Risk prediction for a file or directory\n */\nexport interface RiskPrediction {\n target: string; // File or directory path\n currentRisk: number; // 0-100\n predictedRisk: number; // 0-100 (future prediction)\n trend: 'increasing' | 'stable' | 'decreasing';\n factors: RiskFactor[];\n confidence: number; // 0-1\n recommendations: string[];\n lastIncidentDaysAgo?: number;\n incidentCount: number;\n}\n\n/**\n * Overall project risk summary\n */\nexport interface ProjectRiskSummary {\n overallRisk: number; // 0-100\n trend: 'increasing' | 'stable' | 'decreasing';\n hotspots: RiskPrediction[];\n lowRiskAreas: string[];\n predictions: RiskPrediction[];\n confidence: number;\n}\n\n/**\n * Risk prediction configuration\n */\nexport interface RiskPredictionConfig {\n historyDays: number; // Days of history to consider\n incidentThreshold: number; // Min incidents to flag as hotspot\n riskWeights: {\n incidentCount: number;\n recency: number;\n severity: number;\n complexity: number;\n churn: number;\n };\n}\n\nconst DEFAULT_CONFIG: RiskPredictionConfig = {\n historyDays: 30,\n incidentThreshold: 3,\n riskWeights: {\n incidentCount: 0.35,\n recency: 0.25,\n severity: 0.20,\n complexity: 0.10,\n churn: 0.10,\n },\n};\n\n// ============================================================================\n// RiskPredictor Class\n// ============================================================================\n\n/**\n * Predictive risk analysis engine\n */\nexport class RiskPredictor {\n private projectPath: string;\n private config: RiskPredictionConfig;\n private insightStore;\n \n constructor(projectPath: string, config: Partial<RiskPredictionConfig> = {}) {\n this.projectPath = projectPath;\n this.config = { ...DEFAULT_CONFIG, ...config };\n this.insightStore = getInsightStore(projectPath);\n }\n \n /**\n * Calculate risk for a specific file or directory\n */\n async calculateRisk(target: string): Promise<RiskPrediction> {\n const factors: RiskFactor[] = [];\n let totalRisk = 0;\n \n try {\n // Get historical issues for this target\n const issues = await searchIssues(target, {\n workDir: this.projectPath,\n limit: 500,\n includeResolved: true,\n });\n \n const targetIssues = issues.filter(r => \n r.issue.file === target || \n r.issue.file.startsWith(target + '/') ||\n dirname(r.issue.file) === target\n );\n \n // 1. Incident count factor\n const incidentCount = targetIssues.length;\n const incidentWeight = this.config.riskWeights.incidentCount;\n const incidentScore = Math.min(100, incidentCount * 10);\n factors.push({\n name: 'Incident Count',\n weight: incidentWeight,\n value: incidentCount,\n description: `${incidentCount} historical incidents`,\n trend: this.calculateTrend(targetIssues.map(i => i.issue)),\n });\n totalRisk += incidentScore * incidentWeight;\n \n // 2. Recency factor (when was the last incident?)\n let recencyScore = 0;\n let lastIncidentDaysAgo: number | undefined;\n if (targetIssues.length > 0) {\n const latestIssue = targetIssues\n .sort((a, b) => new Date(b.issue.timestamp).getTime() - new Date(a.issue.timestamp).getTime())[0];\n \n if (latestIssue) {\n const daysSince = (Date.now() - new Date(latestIssue.issue.timestamp).getTime()) / (1000 * 60 * 60 * 24);\n lastIncidentDaysAgo = Math.floor(daysSince);\n \n // More recent = higher risk\n if (daysSince < 1) recencyScore = 100;\n else if (daysSince < 7) recencyScore = 80;\n else if (daysSince < 14) recencyScore = 60;\n else if (daysSince < 30) recencyScore = 40;\n else recencyScore = 20;\n }\n }\n \n factors.push({\n name: 'Recency',\n weight: this.config.riskWeights.recency,\n value: lastIncidentDaysAgo ?? 999,\n description: lastIncidentDaysAgo !== undefined \n ? `Last incident ${lastIncidentDaysAgo} days ago`\n : 'No recent incidents',\n });\n totalRisk += recencyScore * this.config.riskWeights.recency;\n \n // 3. Severity factor\n const criticalCount = targetIssues.filter(r => r.issue.severity === 'critical').length;\n const seriousCount = targetIssues.filter(r => r.issue.severity === 'serious').length;\n const severityScore = Math.min(100, (criticalCount * 25) + (seriousCount * 10));\n \n factors.push({\n name: 'Severity',\n weight: this.config.riskWeights.severity,\n value: severityScore,\n description: `${criticalCount} critical, ${seriousCount} serious`,\n });\n totalRisk += severityScore * this.config.riskWeights.severity;\n \n // 4. Complexity factor (approximated by issue diversity)\n const uniqueAgents = new Set(targetIssues.map(r => r.issue.agent)).size;\n const complexityScore = Math.min(100, uniqueAgents * 20);\n \n factors.push({\n name: 'Complexity',\n weight: this.config.riskWeights.complexity,\n value: uniqueAgents,\n description: `Issues from ${uniqueAgents} different analysis types`,\n });\n totalRisk += complexityScore * this.config.riskWeights.complexity;\n \n // 5. Churn factor (how often this file has issues)\n // Approximate by counting unique dates with issues\n const uniqueDates = new Set(\n targetIssues.map(r => r.issue.timestamp.split('T')[0])\n ).size;\n const churnScore = Math.min(100, uniqueDates * 10);\n \n factors.push({\n name: 'Churn',\n weight: this.config.riskWeights.churn,\n value: uniqueDates,\n description: `Issues found on ${uniqueDates} different days`,\n });\n totalRisk += churnScore * this.config.riskWeights.churn;\n \n // Calculate trend\n const trend = this.calculateTrend(targetIssues.map(i => i.issue));\n \n // Predict future risk based on trend\n let predictedRisk = totalRisk;\n if (trend === 'increasing') {\n predictedRisk = Math.min(100, totalRisk * 1.2);\n } else if (trend === 'decreasing') {\n predictedRisk = Math.max(0, totalRisk * 0.8);\n }\n \n // Generate recommendations\n const recommendations = this.generateRecommendations(factors, totalRisk);\n \n // Calculate confidence based on data quality\n const confidence = Math.min(0.95, 0.3 + (incidentCount * 0.05));\n \n const prediction: RiskPrediction = {\n target,\n currentRisk: Math.round(totalRisk),\n predictedRisk: Math.round(predictedRisk),\n trend,\n factors,\n confidence,\n recommendations,\n incidentCount,\n };\n \n if (lastIncidentDaysAgo !== undefined) {\n prediction.lastIncidentDaysAgo = lastIncidentDaysAgo;\n }\n \n return prediction;\n \n } catch (error) {\n console.error(`Failed to calculate risk for ${target}:`, error);\n return {\n target,\n currentRisk: 50,\n predictedRisk: 50,\n trend: 'stable',\n factors: [],\n confidence: 0.1,\n recommendations: ['Unable to analyze - insufficient data'],\n incidentCount: 0,\n };\n }\n }\n \n /**\n * Calculate trend from issues\n */\n private calculateTrend(issues: StoredIssue[]): 'increasing' | 'stable' | 'decreasing' {\n if (issues.length < 3) return 'stable';\n \n const now = Date.now();\n const recentCutoff = now - (7 * 24 * 60 * 60 * 1000); // 7 days\n const olderCutoff = now - (30 * 24 * 60 * 60 * 1000); // 30 days\n \n const recentIssues = issues.filter(i => new Date(i.timestamp).getTime() > recentCutoff).length;\n const olderIssues = issues.filter(i => {\n const time = new Date(i.timestamp).getTime();\n return time > olderCutoff && time <= recentCutoff;\n }).length;\n \n // Normalize by time period\n const recentRate = recentIssues / 7;\n const olderRate = olderIssues / 23;\n \n if (recentRate > olderRate * 1.5) return 'increasing';\n if (recentRate < olderRate * 0.5) return 'decreasing';\n return 'stable';\n }\n \n /**\n * Generate recommendations based on risk factors\n */\n private generateRecommendations(factors: RiskFactor[], totalRisk: number): string[] {\n const recommendations: string[] = [];\n \n if (totalRisk >= 70) {\n recommendations.push('Consider extra code review before merging changes');\n }\n \n const incidentFactor = factors.find(f => f.name === 'Incident Count');\n if (incidentFactor && incidentFactor.value >= 5) {\n recommendations.push('This area has recurring issues - consider refactoring');\n }\n \n const recencyFactor = factors.find(f => f.name === 'Recency');\n if (recencyFactor && recencyFactor.value < 7) {\n recommendations.push('Recent incident activity - monitor closely');\n }\n \n const severityFactor = factors.find(f => f.name === 'Severity');\n if (severityFactor && severityFactor.value >= 25) {\n recommendations.push('High severity issues present - prioritize fixes');\n }\n \n const complexityFactor = factors.find(f => f.name === 'Complexity');\n if (complexityFactor && complexityFactor.value >= 4) {\n recommendations.push('Multiple issue types - consider comprehensive review');\n }\n \n if (recommendations.length === 0) {\n recommendations.push('No specific concerns - maintain normal review process');\n }\n \n return recommendations;\n }\n \n /**\n * Predict risk trend for files that have recently changed\n */\n async predictRiskTrend(changedFiles: string[]): Promise<{\n trend: 'increasing' | 'stable' | 'decreasing';\n factors: Array<{ file: string; reasons: string[] }>;\n overallRisk: number;\n }> {\n const predictions = await Promise.all(\n changedFiles.map(f => this.calculateRisk(f))\n );\n \n const highRiskFiles = predictions.filter(p => p.currentRisk >= 50);\n const totalRisk = predictions.reduce((sum, p) => sum + p.currentRisk, 0) / Math.max(1, predictions.length);\n \n // Determine overall trend\n const trends = predictions.map(p => p.trend);\n const increasingCount = trends.filter(t => t === 'increasing').length;\n const decreasingCount = trends.filter(t => t === 'decreasing').length;\n \n let overallTrend: 'increasing' | 'stable' | 'decreasing' = 'stable';\n if (increasingCount > decreasingCount + 1) {\n overallTrend = 'increasing';\n } else if (decreasingCount > increasingCount + 1) {\n overallTrend = 'decreasing';\n }\n \n // Collect factors for high-risk files\n const factors = highRiskFiles.map(p => ({\n file: p.target,\n reasons: p.incidentCount > 0 \n ? ['past incidents', ...p.recommendations.slice(0, 2)]\n : ['no historical data'],\n }));\n \n return {\n trend: overallTrend,\n factors,\n overallRisk: Math.round(totalRisk),\n };\n }\n \n /**\n * Get project-wide risk summary\n */\n async getProjectRiskSummary(): Promise<ProjectRiskSummary> {\n try {\n const issues = await searchIssues('', {\n workDir: this.projectPath,\n limit: 1000,\n includeResolved: true,\n });\n \n // Group by directory\n const dirIssueCount = new Map<string, StoredIssue[]>();\n for (const { issue } of issues) {\n const dir = dirname(issue.file);\n const existing = dirIssueCount.get(dir) || [];\n existing.push(issue);\n dirIssueCount.set(dir, existing);\n }\n \n // Find hotspots (directories with many issues)\n const hotspotDirs = [...dirIssueCount.entries()]\n .filter(([_, issues]) => issues.length >= this.config.incidentThreshold)\n .sort((a, b) => b[1].length - a[1].length)\n .slice(0, 5);\n \n // Calculate risk for each hotspot\n const hotspots = await Promise.all(\n hotspotDirs.map(([dir]) => this.calculateRisk(dir))\n );\n \n // Find low-risk areas\n const allDirs = [...dirIssueCount.keys()];\n const lowRiskPredictions = await Promise.all(\n allDirs.map(dir => this.calculateRisk(dir))\n );\n const lowRiskAreas = lowRiskPredictions\n .filter(p => p.currentRisk < 20 && p.incidentCount === 0)\n .map(p => p.target)\n .slice(0, 5);\n \n // Calculate overall risk\n const overallRisk = hotspots.length > 0\n ? hotspots.reduce((sum, p) => sum + p.currentRisk, 0) / hotspots.length\n : 0;\n \n // Determine trend\n const trends = hotspots.map(p => p.trend);\n const increasingCount = trends.filter(t => t === 'increasing').length;\n const decreasingCount = trends.filter(t => t === 'decreasing').length;\n \n let trend: 'increasing' | 'stable' | 'decreasing' = 'stable';\n if (increasingCount > decreasingCount) {\n trend = 'increasing';\n } else if (decreasingCount > increasingCount) {\n trend = 'decreasing';\n }\n \n // Calculate confidence\n const confidence = Math.min(0.9, 0.4 + (issues.length * 0.001));\n \n return {\n overallRisk: Math.round(overallRisk),\n trend,\n hotspots,\n lowRiskAreas,\n predictions: hotspots,\n confidence,\n };\n \n } catch (error) {\n console.error('Failed to get project risk summary:', error);\n return {\n overallRisk: 0,\n trend: 'stable',\n hotspots: [],\n lowRiskAreas: [],\n predictions: [],\n confidence: 0.1,\n };\n }\n }\n \n /**\n * Create risk prediction insight\n */\n async generateRiskInsight(): Promise<Insight | null> {\n if (!this.insightStore.canCreateInsight('risk-prediction')) {\n return null;\n }\n \n const summary = await this.getProjectRiskSummary();\n \n // Only generate insight if there's meaningful risk\n if (summary.hotspots.length === 0 || summary.overallRisk < 30) {\n return null;\n }\n \n const topHotspot = summary.hotspots[0];\n if (!topHotspot) return null;\n \n // Convert trend format for insight display\n const trendMap: Record<'increasing' | 'stable' | 'decreasing', 'worsening' | 'stable' | 'improving'> = {\n 'increasing': 'worsening',\n 'stable': 'stable',\n 'decreasing': 'improving',\n };\n \n const insight: Insight = {\n id: `insight-risk-${Date.now()}`,\n type: 'warning',\n message: `[!] ${basename(topHotspot.target)}/ has elevated risk (${topHotspot.currentRisk}/100)`,\n context: `${topHotspot.incidentCount} past incidents. ${topHotspot.recommendations[0]}`,\n suggestedAction: 'Request extra review before merging changes to this area',\n relatedIssues: [],\n priority: Math.min(9, 5 + Math.floor(topHotspot.currentRisk / 20)),\n timestamp: Date.now(),\n dismissed: false,\n category: 'security',\n details: {\n affectedFiles: summary.hotspots.map(h => basename(h.target)),\n trend: trendMap[summary.trend],\n examples: topHotspot.recommendations,\n },\n };\n \n await this.insightStore.addInsight(insight);\n await this.insightStore.markInsightCreated('risk-prediction');\n \n return insight;\n }\n}\n\n// ============================================================================\n// Singleton Management\n// ============================================================================\n\nconst riskPredictors: Map<string, RiskPredictor> = new Map();\n\n/**\n * Get the RiskPredictor for a project (singleton per project)\n */\nexport function getRiskPredictor(projectPath: string): RiskPredictor {\n let predictor = riskPredictors.get(projectPath);\n if (!predictor) {\n predictor = new RiskPredictor(projectPath);\n riskPredictors.set(projectPath, predictor);\n }\n return predictor;\n}\n\n/**\n * Clear all RiskPredictor instances (for testing)\n */\nexport function clearRiskPredictors(): void {\n riskPredictors.clear();\n}\n","/**\n * Auto-Escalation System - Autonomous issue escalation\n * \n * Features:\n * - Auto-escalate critical security issues\n * - Respect quiet hours and cooldowns\n * - Multi-channel support (Slack, email, webhook)\n * - Escalation tracking and history\n * - Fallback to draft mode during quiet hours\n */\n\nimport type { Issue } from '../types/index.js';\nimport type { Insight } from './insight-store.js';\nimport { getInsightStore } from './insight-store.js';\nimport { getProjectState } from './project-state.js';\nimport { SlackIntegration } from '../integrations/slack.js';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Escalation target configuration\n */\nexport interface EscalationTarget {\n type: 'slack' | 'email' | 'webhook';\n config: {\n webhookUrl?: string;\n email?: string;\n channel?: string;\n username?: string;\n };\n enabled: boolean;\n forSeverities: ('critical' | 'serious' | 'moderate')[];\n forCategories: ('security' | 'quality' | 'performance' | 'all')[];\n}\n\n/**\n * Escalation message\n */\nexport interface EscalationMessage {\n id: string;\n severity: 'critical' | 'serious' | 'moderate';\n title: string;\n body: string;\n issues: Issue[];\n timestamp: number;\n sent: boolean;\n sentAt?: number;\n channel?: string;\n error?: string;\n}\n\n/**\n * Escalation result\n */\nexport interface EscalationResult {\n action: 'auto_escalated' | 'draft_only' | 'blocked' | 'failed' | 'no_action';\n reason: string;\n message?: EscalationMessage;\n draftLocation?: string;\n}\n\n/**\n * Escalation configuration\n */\nexport interface EscalationConfig {\n enabled: boolean;\n targets: EscalationTarget[];\n cooldownMinutes: number;\n maxEscalationsPerHour: number;\n respectQuietHours: boolean;\n criticalBypassQuietHours: boolean;\n draftFallbackEnabled: boolean;\n}\n\nconst DEFAULT_CONFIG: EscalationConfig = {\n enabled: true,\n targets: [],\n cooldownMinutes: 15,\n maxEscalationsPerHour: 5,\n respectQuietHours: true,\n criticalBypassQuietHours: true,\n draftFallbackEnabled: true,\n};\n\n// ============================================================================\n// EscalationManager Class\n// ============================================================================\n\n/**\n * Manages autonomous escalation of critical issues\n */\nexport class EscalationManager {\n private projectPath: string;\n private config: EscalationConfig;\n private projectState;\n private insightStore;\n private escalationHistory: EscalationMessage[] = [];\n private slackClient?: SlackIntegration;\n \n constructor(projectPath: string, config: Partial<EscalationConfig> = {}) {\n this.projectPath = projectPath;\n this.config = { ...DEFAULT_CONFIG, ...config };\n this.projectState = getProjectState(projectPath);\n this.insightStore = getInsightStore(projectPath);\n \n // Initialize Slack client if configured\n const slackTarget = this.config.targets.find(t => t.type === 'slack' && t.enabled);\n if (slackTarget?.config.webhookUrl) {\n this.slackClient = new SlackIntegration({\n webhookUrl: slackTarget.config.webhookUrl,\n channel: slackTarget.config.channel,\n username: slackTarget.config.username,\n });\n }\n }\n \n /**\n * Check if an issue should be auto-escalated\n */\n shouldAutoEscalate(issue: Issue): boolean {\n // Must be enabled\n if (!this.config.enabled) {\n return false;\n }\n \n // Must be critical severity\n if (issue.severity !== 'critical') {\n return false;\n }\n \n // Check category (security issues get priority)\n const isSecurityIssue = \n issue.category === 'security' ||\n issue.agent === 'security' ||\n issue.issue.toLowerCase().includes('security') ||\n issue.issue.toLowerCase().includes('vulnerability') ||\n issue.issue.toLowerCase().includes('injection') ||\n issue.issue.toLowerCase().includes('xss') ||\n issue.issue.toLowerCase().includes('secret');\n \n if (!isSecurityIssue) {\n return false;\n }\n \n // Check quiet hours (unless critical bypasses)\n if (this.projectState.isQuietHours()) {\n if (!this.config.criticalBypassQuietHours) {\n return false;\n }\n }\n \n // Check cooldown\n if (!this.insightStore.canCreateInsight('auto-escalation')) {\n return false;\n }\n \n // Check hourly limit\n const recentEscalations = this.escalationHistory.filter(e => \n e.timestamp > Date.now() - (60 * 60 * 1000)\n );\n if (recentEscalations.length >= this.config.maxEscalationsPerHour) {\n return false;\n }\n \n // Check if recently escalated same file\n const recentlyEscalated = this.escalationHistory.some(e =>\n e.issues.some(i => i.file === issue.file) &&\n e.timestamp > Date.now() - (this.config.cooldownMinutes * 60 * 1000)\n );\n if (recentlyEscalated) {\n return false;\n }\n \n // Must have a valid target\n return this.hasValidEscalationTarget('critical', 'security');\n }\n \n /**\n * Check if we have a valid escalation target\n */\n private hasValidEscalationTarget(severity: string, category: string): boolean {\n return this.config.targets.some(t => \n t.enabled &&\n t.forSeverities.includes(severity as any) &&\n (t.forCategories.includes(category as any) || t.forCategories.includes('all'))\n );\n }\n \n /**\n * Auto-escalate if issue is critical\n */\n async autoEscalateIfCritical(issue: Issue): Promise<EscalationResult> {\n // Check if should escalate\n if (!this.shouldAutoEscalate(issue)) {\n // Check if we should create a draft instead\n if (issue.severity === 'critical' && this.config.draftFallbackEnabled) {\n if (this.projectState.isQuietHours()) {\n return this.createDraftEscalation([issue], 'Blocked by quiet hours');\n }\n }\n \n return {\n action: 'no_action',\n reason: 'Issue does not meet escalation criteria',\n };\n }\n \n // Create escalation message\n const message = this.createEscalationMessage([issue]);\n \n // Try to send\n try {\n await this.sendEscalation(message);\n \n // Record escalation\n this.escalationHistory.push(message);\n await this.insightStore.markInsightCreated('auto-escalation');\n \n // Create insight about escalation\n await this.createEscalationInsight(message);\n \n // Use risk budget\n await this.projectState.useRiskBudget(1);\n \n return {\n action: 'auto_escalated',\n reason: 'Critical security issue auto-escalated',\n message,\n };\n \n } catch (error) {\n console.error('Failed to send escalation:', error);\n \n // Fallback to draft\n if (this.config.draftFallbackEnabled) {\n return this.createDraftEscalation([issue], String(error));\n }\n \n return {\n action: 'failed',\n reason: `Send failed: ${error}`,\n message,\n };\n }\n }\n \n /**\n * Escalate multiple issues at once\n */\n async escalateIssues(issues: Issue[]): Promise<EscalationResult> {\n // Filter to only critical security issues\n const criticalSecurityIssues = issues.filter(i => \n i.severity === 'critical' &&\n (i.category === 'security' || i.agent === 'security')\n );\n \n if (criticalSecurityIssues.length === 0) {\n return {\n action: 'no_action',\n reason: 'No critical security issues to escalate',\n };\n }\n \n // Check quiet hours\n if (this.projectState.isQuietHours() && !this.config.criticalBypassQuietHours) {\n return this.createDraftEscalation(criticalSecurityIssues, 'Blocked by quiet hours');\n }\n \n // Create and send message\n const message = this.createEscalationMessage(criticalSecurityIssues);\n \n try {\n await this.sendEscalation(message);\n \n this.escalationHistory.push(message);\n await this.insightStore.markInsightCreated('auto-escalation');\n await this.createEscalationInsight(message);\n \n return {\n action: 'auto_escalated',\n reason: `Escalated ${criticalSecurityIssues.length} critical security issues`,\n message,\n };\n \n } catch (error) {\n if (this.config.draftFallbackEnabled) {\n return this.createDraftEscalation(criticalSecurityIssues, String(error));\n }\n \n return {\n action: 'failed',\n reason: `Send failed: ${error}`,\n message,\n };\n }\n }\n \n /**\n * Create an escalation message\n */\n private createEscalationMessage(issues: Issue[]): EscalationMessage {\n const severity = issues.some(i => i.severity === 'critical') ? 'critical' : 'serious';\n \n return {\n id: `esc-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,\n severity,\n title: `${severity.toUpperCase()} Security Alert: ${issues.length} issue${issues.length > 1 ? 's' : ''} detected`,\n body: this.formatEscalationBody(issues),\n issues,\n timestamp: Date.now(),\n sent: false,\n };\n }\n \n /**\n * Format escalation body text\n */\n private formatEscalationBody(issues: Issue[]): string {\n const lines: string[] = [\n `**Critical Security Issues Detected**`,\n ``,\n `**Project:** ${this.projectPath.split('/').pop()}`,\n `**Issues:** ${issues.length}`,\n `**Detected:** ${new Date().toISOString()}`,\n ``,\n `**Summary:**`,\n ];\n \n for (const issue of issues.slice(0, 5)) {\n lines.push(`- \\`${issue.file}:${issue.line || '?'}\\`: ${issue.issue.slice(0, 100)}`);\n }\n \n if (issues.length > 5) {\n lines.push(`- ... and ${issues.length - 5} more`);\n }\n \n lines.push('');\n lines.push('**Action Required:** Review and address these issues immediately.');\n \n return lines.join('\\n');\n }\n \n /**\n * Send escalation through configured channels\n */\n private async sendEscalation(message: EscalationMessage): Promise<void> {\n const enabledTargets = this.config.targets.filter(t => t.enabled);\n \n if (enabledTargets.length === 0) {\n throw new Error('No enabled escalation targets configured');\n }\n \n const errors: string[] = [];\n \n for (const target of enabledTargets) {\n try {\n switch (target.type) {\n case 'slack':\n await this.sendToSlack(message, target);\n break;\n case 'email':\n await this.sendToEmail(message, target);\n break;\n case 'webhook':\n await this.sendToWebhook(message, target);\n break;\n }\n message.sent = true;\n message.sentAt = Date.now();\n message.channel = target.type;\n } catch (error) {\n errors.push(`${target.type}: ${error}`);\n }\n }\n \n if (errors.length === enabledTargets.length) {\n // All failed\n throw new Error(`All escalation channels failed: ${errors.join('; ')}`);\n }\n }\n \n /**\n * Send to Slack\n */\n private async sendToSlack(message: EscalationMessage, target: EscalationTarget): Promise<void> {\n if (!target.config.webhookUrl) {\n throw new Error('Slack webhook URL not configured');\n }\n \n // Use existing SlackIntegration if available\n if (this.slackClient) {\n await this.slackClient.sendCriticalAlert(message.issues, this.projectPath.split('/').pop() || 'Unknown');\n } else {\n // Direct webhook call\n const slack = new SlackIntegration({\n webhookUrl: target.config.webhookUrl,\n channel: target.config.channel,\n username: target.config.username || 'Trie Agent',\n });\n \n await slack.sendCriticalAlert(message.issues, this.projectPath.split('/').pop() || 'Unknown');\n }\n }\n \n /**\n * Send to email (placeholder - would need email provider integration)\n */\n private async sendToEmail(message: EscalationMessage, target: EscalationTarget): Promise<void> {\n if (!target.config.email) {\n throw new Error('Email address not configured');\n }\n \n // In a real implementation, this would use an email provider (SendGrid, SES, etc.)\n // For now, we'll log and simulate success\n console.log(`[EMAIL ESCALATION] To: ${target.config.email}`);\n console.log(`Subject: ${message.title}`);\n console.log(`Body: ${message.body}`);\n \n // Note: In production, replace with actual email sending:\n // await sendEmail({\n // to: target.config.email,\n // subject: message.title,\n // body: message.body,\n // });\n }\n \n /**\n * Send to webhook\n */\n private async sendToWebhook(message: EscalationMessage, target: EscalationTarget): Promise<void> {\n if (!target.config.webhookUrl) {\n throw new Error('Webhook URL not configured');\n }\n \n const response = await fetch(target.config.webhookUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n id: message.id,\n severity: message.severity,\n title: message.title,\n body: message.body,\n issues: message.issues.map(i => ({\n file: i.file,\n line: i.line,\n severity: i.severity,\n issue: i.issue,\n agent: i.agent,\n })),\n timestamp: message.timestamp,\n project: this.projectPath,\n }),\n });\n \n if (!response.ok) {\n throw new Error(`Webhook returned ${response.status}: ${response.statusText}`);\n }\n }\n \n /**\n * Create a draft escalation (when sending is blocked)\n */\n private createDraftEscalation(issues: Issue[], reason: string): EscalationResult {\n const message = this.createEscalationMessage(issues);\n message.error = reason;\n \n // Store as draft\n this.escalationHistory.push(message);\n \n return {\n action: 'draft_only',\n reason,\n message,\n draftLocation: `.trie/drafts/escalation-${message.id}.json`,\n };\n }\n \n /**\n * Create insight about escalation\n */\n private async createEscalationInsight(message: EscalationMessage): Promise<void> {\n const insight: Insight = {\n id: `insight-esc-${message.id}`,\n type: 'warning',\n message: `Auto-escalated: ${message.issues.length} critical security issue${message.issues.length > 1 ? 's' : ''}`,\n context: `Sent to ${message.channel}. Issues in: ${[...new Set(message.issues.map(i => i.file))].slice(0, 3).join(', ')}`,\n relatedIssues: message.issues.map(i => i.id),\n priority: 10,\n timestamp: Date.now(),\n dismissed: false,\n category: 'security',\n details: {\n affectedFiles: [...new Set(message.issues.map(i => i.file))],\n },\n };\n \n await this.insightStore.addInsight(insight);\n }\n \n /**\n * Get escalation history\n */\n getEscalationHistory(): EscalationMessage[] {\n return [...this.escalationHistory];\n }\n \n /**\n * Get pending draft escalations\n */\n getPendingDrafts(): EscalationMessage[] {\n return this.escalationHistory.filter(e => !e.sent);\n }\n \n /**\n * Retry a failed/draft escalation\n */\n async retryEscalation(messageId: string): Promise<EscalationResult> {\n const message = this.escalationHistory.find(e => e.id === messageId);\n if (!message) {\n return {\n action: 'failed',\n reason: 'Escalation message not found',\n };\n }\n \n try {\n await this.sendEscalation(message);\n \n return {\n action: 'auto_escalated',\n reason: 'Retry successful',\n message,\n };\n } catch (error) {\n return {\n action: 'failed',\n reason: `Retry failed: ${error}`,\n message,\n };\n }\n }\n \n /**\n * Configure escalation targets\n */\n addEscalationTarget(target: EscalationTarget): void {\n this.config.targets.push(target);\n \n // Re-initialize Slack client if needed\n if (target.type === 'slack' && target.enabled && target.config.webhookUrl) {\n this.slackClient = new SlackIntegration({\n webhookUrl: target.config.webhookUrl,\n channel: target.config.channel,\n username: target.config.username,\n });\n }\n }\n \n /**\n * Get current configuration\n */\n getConfig(): EscalationConfig {\n return { ...this.config };\n }\n \n /**\n * Update configuration\n */\n setConfig(config: Partial<EscalationConfig>): void {\n this.config = { ...this.config, ...config };\n }\n}\n\n// ============================================================================\n// Singleton Management\n// ============================================================================\n\nconst escalationManagers: Map<string, EscalationManager> = new Map();\n\n/**\n * Get the EscalationManager for a project (singleton per project)\n */\nexport function getEscalationManager(projectPath: string): EscalationManager {\n let manager = escalationManagers.get(projectPath);\n if (!manager) {\n manager = new EscalationManager(projectPath);\n escalationManagers.set(projectPath, manager);\n }\n return manager;\n}\n\n/**\n * Clear all EscalationManager instances (for testing)\n */\nexport function clearEscalationManagers(): void {\n escalationManagers.clear();\n}\n","/**\n * Meta-Learning System - Self-improving agent behavior\n * \n * Features:\n * - Track user feedback on insights\n * - Adjust insight weights based on feedback\n * - Calculate agent effectiveness metrics\n * - Learn which insights are most valuable\n * - Improve prediction accuracy over time\n */\n\nimport type { Insight } from './insight-store.js';\nimport { getInsightStore } from './insight-store.js';\nimport { getProjectState, type AgentMetrics } from './project-state.js';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Feedback types from users\n */\nexport type FeedbackType = 'helpful' | 'dismissed' | 'acted' | 'ignored';\n\n/**\n * Insight feedback record\n */\nexport interface InsightFeedback {\n insightId: string;\n insightType: Insight['type'];\n insightCategory: Insight['category'];\n feedback: FeedbackType;\n timestamp: number;\n latencyMs?: number; // Time from insight shown to feedback\n}\n\n/**\n * Category effectiveness stats\n */\nexport interface CategoryEffectiveness {\n category: string;\n totalInsights: number;\n helpfulCount: number;\n dismissedCount: number;\n actedCount: number;\n effectivenessScore: number; // 0-1\n}\n\n/**\n * Learning weights for insight generation\n */\nexport interface InsightWeights {\n security: number;\n quality: number;\n performance: number;\n pattern: number;\n progress: number;\n general: number;\n}\n\n/**\n * Agent effectiveness report\n */\nexport interface EffectivenessReport {\n overallScore: number;\n predictiveAccuracy: number;\n userSatisfaction: number;\n falsePositiveRate: number;\n categoryBreakdown: CategoryEffectiveness[];\n recommendations: string[];\n trends: {\n period: string;\n direction: 'improving' | 'stable' | 'declining';\n };\n}\n\n// ============================================================================\n// MetaLearner Class\n// ============================================================================\n\n/**\n * Meta-learning engine for agent self-improvement\n */\nexport class MetaLearner {\n private projectState;\n private insightStore;\n private feedbackHistory: InsightFeedback[] = [];\n private weights: InsightWeights;\n \n constructor(projectPath: string) {\n this.projectState = getProjectState(projectPath);\n this.insightStore = getInsightStore(projectPath);\n \n // Initialize with default weights\n this.weights = {\n security: 1.0,\n quality: 1.0,\n performance: 1.0,\n pattern: 1.0,\n progress: 1.0,\n general: 1.0,\n };\n }\n \n /**\n * Record user feedback on an insight\n */\n async recordFeedback(\n feedback: FeedbackType,\n context: {\n insightId: string;\n latencyMs?: number;\n }\n ): Promise<void> {\n await this.insightStore.load();\n const insight = this.insightStore.getInsight(context.insightId);\n \n if (!insight) {\n console.error(`Insight not found: ${context.insightId}`);\n return;\n }\n \n // Record feedback\n const record: InsightFeedback = {\n insightId: context.insightId,\n insightType: insight.type,\n insightCategory: insight.category,\n feedback,\n timestamp: Date.now(),\n };\n \n if (context.latencyMs !== undefined) {\n record.latencyMs = context.latencyMs;\n }\n \n this.feedbackHistory.push(record);\n \n // Update project state metrics\n await this.projectState.recordInsightFeedback(\n feedback === 'dismissed' ? 'dismissed' : \n feedback === 'acted' ? 'acted' : 'helpful'\n );\n \n // Adjust weights based on feedback\n await this.adjustWeights(record);\n }\n \n /**\n * Adjust insight weights based on feedback\n */\n private async adjustWeights(feedback: InsightFeedback): Promise<void> {\n const category = feedback.insightCategory as keyof InsightWeights;\n const currentWeight = this.weights[category];\n \n if (currentWeight === undefined) return;\n \n // Positive feedback increases weight, dismissal decreases\n let adjustment = 0;\n switch (feedback.feedback) {\n case 'acted':\n adjustment = 0.05; // Strong positive signal\n break;\n case 'helpful':\n adjustment = 0.02; // Moderate positive\n break;\n case 'dismissed':\n adjustment = -0.03; // Negative signal\n break;\n case 'ignored':\n adjustment = -0.01; // Weak negative\n break;\n }\n \n // Apply adjustment with bounds\n this.weights[category] = Math.max(0.3, Math.min(1.5, currentWeight + adjustment));\n }\n \n /**\n * Get current insight weights\n */\n getWeights(): InsightWeights {\n return { ...this.weights };\n }\n \n /**\n * Get weight for a category (used to adjust insight priority)\n */\n getCategoryWeight(category: Insight['category']): number {\n return this.weights[category] ?? 1.0;\n }\n \n /**\n * Calculate category effectiveness\n */\n calculateCategoryEffectiveness(): CategoryEffectiveness[] {\n const categories = ['security', 'quality', 'performance', 'pattern', 'progress', 'general'];\n const effectiveness: CategoryEffectiveness[] = [];\n \n for (const category of categories) {\n const categoryFeedback = this.feedbackHistory.filter(f => f.insightCategory === category);\n \n if (categoryFeedback.length === 0) {\n effectiveness.push({\n category,\n totalInsights: 0,\n helpfulCount: 0,\n dismissedCount: 0,\n actedCount: 0,\n effectivenessScore: 0.5, // Neutral when no data\n });\n continue;\n }\n \n const helpfulCount = categoryFeedback.filter(f => f.feedback === 'helpful' || f.feedback === 'acted').length;\n const dismissedCount = categoryFeedback.filter(f => f.feedback === 'dismissed').length;\n const actedCount = categoryFeedback.filter(f => f.feedback === 'acted').length;\n \n // Effectiveness = (helpful + 2*acted) / (total + dismissed)\n const score = (helpfulCount + actedCount) / Math.max(1, categoryFeedback.length);\n \n effectiveness.push({\n category,\n totalInsights: categoryFeedback.length,\n helpfulCount,\n dismissedCount,\n actedCount,\n effectivenessScore: score,\n });\n }\n \n return effectiveness;\n }\n \n /**\n * Get agent effectiveness metrics\n */\n getEffectiveness(): AgentMetrics {\n return this.projectState.getMetrics();\n }\n \n /**\n * Generate a comprehensive effectiveness report\n */\n async generateEffectivenessReport(): Promise<EffectivenessReport> {\n await this.projectState.load();\n const metrics = this.projectState.getMetrics();\n const categoryBreakdown = this.calculateCategoryEffectiveness();\n \n // Calculate overall score (weighted average of metrics)\n const overallScore = (\n metrics.userSatisfaction * 0.4 +\n metrics.predictiveAccuracy * 0.3 +\n (1 - metrics.falsePositiveRate) * 0.3\n );\n \n // Generate recommendations\n const recommendations = this.generateRecommendations(metrics, categoryBreakdown);\n \n // Determine trend\n const trend = this.calculateTrend();\n \n return {\n overallScore,\n predictiveAccuracy: metrics.predictiveAccuracy,\n userSatisfaction: metrics.userSatisfaction,\n falsePositiveRate: metrics.falsePositiveRate,\n categoryBreakdown,\n recommendations,\n trends: trend,\n };\n }\n \n /**\n * Generate improvement recommendations\n */\n private generateRecommendations(\n metrics: AgentMetrics,\n categoryBreakdown: CategoryEffectiveness[]\n ): string[] {\n const recommendations: string[] = [];\n \n // Check false positive rate\n if (metrics.falsePositiveRate > 0.3) {\n recommendations.push('High dismissal rate detected. Consider raising insight thresholds.');\n }\n \n // Check user satisfaction\n if (metrics.userSatisfaction < 0.5) {\n recommendations.push('User satisfaction is low. Review insight quality and relevance.');\n }\n \n // Check category effectiveness\n const weakCategories = categoryBreakdown\n .filter(c => c.totalInsights >= 5 && c.effectivenessScore < 0.4)\n .map(c => c.category);\n \n if (weakCategories.length > 0) {\n recommendations.push(\n `Low effectiveness in: ${weakCategories.join(', ')}. Consider adjusting insight generation for these categories.`\n );\n }\n \n // Check for high-performing categories\n const strongCategories = categoryBreakdown\n .filter(c => c.totalInsights >= 5 && c.effectivenessScore > 0.7)\n .map(c => c.category);\n \n if (strongCategories.length > 0) {\n recommendations.push(\n `Strong performance in: ${strongCategories.join(', ')}. Consider emphasizing these insights.`\n );\n }\n \n // Check prediction accuracy\n if (metrics.predictiveAccuracy < 0.6 && metrics.totalPredictions >= 10) {\n recommendations.push('Prediction accuracy below target. Review risk scoring factors.');\n }\n \n // Positive reinforcement if doing well\n if (metrics.userSatisfaction >= 0.7 && metrics.falsePositiveRate <= 0.2) {\n recommendations.push('Agent performance is excellent. Keep up the good work!');\n }\n \n return recommendations;\n }\n \n /**\n * Calculate trend direction\n */\n private calculateTrend(): { period: string; direction: 'improving' | 'stable' | 'declining' } {\n // Compare recent feedback to older feedback\n const now = Date.now();\n const recentCutoff = now - (7 * 24 * 60 * 60 * 1000); // 7 days\n const olderCutoff = now - (30 * 24 * 60 * 60 * 1000); // 30 days\n \n const recentFeedback = this.feedbackHistory.filter(f => f.timestamp > recentCutoff);\n const olderFeedback = this.feedbackHistory.filter(f => \n f.timestamp > olderCutoff && f.timestamp <= recentCutoff\n );\n \n if (recentFeedback.length < 5 || olderFeedback.length < 5) {\n return { period: 'last 30 days', direction: 'stable' };\n }\n \n // Calculate satisfaction rates\n const recentPositive = recentFeedback.filter(f => \n f.feedback === 'helpful' || f.feedback === 'acted'\n ).length / recentFeedback.length;\n \n const olderPositive = olderFeedback.filter(f => \n f.feedback === 'helpful' || f.feedback === 'acted'\n ).length / olderFeedback.length;\n \n const diff = recentPositive - olderPositive;\n \n if (diff > 0.1) {\n return { period: 'last 30 days', direction: 'improving' };\n } else if (diff < -0.1) {\n return { period: 'last 30 days', direction: 'declining' };\n }\n \n return { period: 'last 30 days', direction: 'stable' };\n }\n \n /**\n * Should an insight be shown based on learning?\n * \n * Uses weights and user patterns to filter low-value insights.\n */\n shouldShowInsight(insight: Insight): boolean {\n const weight = this.getCategoryWeight(insight.category);\n \n // If weight is very low, filter out low-priority insights\n if (weight < 0.5 && insight.priority < 5) {\n return false;\n }\n \n // Adjust priority threshold based on category weight\n const adjustedPriority = insight.priority * weight;\n \n // Show if adjusted priority is above threshold\n return adjustedPriority >= 3;\n }\n \n /**\n * Adjust insight priority based on learning\n */\n adjustInsightPriority(insight: Insight): number {\n const weight = this.getCategoryWeight(insight.category);\n return Math.round(insight.priority * weight);\n }\n \n /**\n * Get feedback history stats\n */\n getFeedbackStats(): {\n total: number;\n helpful: number;\n dismissed: number;\n acted: number;\n ignored: number;\n averageLatencyMs: number | null;\n } {\n const stats = {\n total: this.feedbackHistory.length,\n helpful: 0,\n dismissed: 0,\n acted: 0,\n ignored: 0,\n averageLatencyMs: null as number | null,\n };\n \n let totalLatency = 0;\n let latencyCount = 0;\n \n for (const feedback of this.feedbackHistory) {\n switch (feedback.feedback) {\n case 'helpful': stats.helpful++; break;\n case 'dismissed': stats.dismissed++; break;\n case 'acted': stats.acted++; break;\n case 'ignored': stats.ignored++; break;\n }\n \n if (feedback.latencyMs !== undefined) {\n totalLatency += feedback.latencyMs;\n latencyCount++;\n }\n }\n \n if (latencyCount > 0) {\n stats.averageLatencyMs = Math.round(totalLatency / latencyCount);\n }\n \n return stats;\n }\n \n /**\n * Reset learning (for testing)\n */\n reset(): void {\n this.feedbackHistory = [];\n this.weights = {\n security: 1.0,\n quality: 1.0,\n performance: 1.0,\n pattern: 1.0,\n progress: 1.0,\n general: 1.0,\n };\n }\n}\n\n// ============================================================================\n// Singleton Management\n// ============================================================================\n\nconst metaLearners: Map<string, MetaLearner> = new Map();\n\n/**\n * Get the MetaLearner for a project (singleton per project)\n */\nexport function getMetaLearner(projectPath: string): MetaLearner {\n let learner = metaLearners.get(projectPath);\n if (!learner) {\n learner = new MetaLearner(projectPath);\n metaLearners.set(projectPath, learner);\n }\n return learner;\n}\n\n/**\n * Clear all MetaLearner instances (for testing)\n */\nexport function clearMetaLearners(): void {\n metaLearners.clear();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAS,YAAAA,iBAAgB;;;ACRzB,SAAS,UAAU,eAAe;AA2DlC,IAAM,iBAAuC;AAAA,EAC3C,aAAa;AAAA,EACb,mBAAmB;AAAA,EACnB,aAAa;AAAA,IACX,eAAe;AAAA,IACf,SAAS;AAAA,IACT,UAAU;AAAA,IACV,YAAY;AAAA,IACZ,OAAO;AAAA,EACT;AACF;AASO,IAAM,gBAAN,MAAoB;AAAA,EACjB;AAAA,EACA;AAAA,EACA;AAAA,EAER,YAAY,aAAqB,SAAwC,CAAC,GAAG;AAC3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;AAAA,MACxC,GAAG;AAAA,IACL;AAAA,EACF;AAAA,EAEQ,KAAQ,KAAa;AAC3B,WAAO,IAAI,KAAK,MAAM,KAAK,OAAO,IAAI,IAAI,MAAM,CAAC;AAAA,EACnD;AACF;AAGA,IAAM,iBAAyC,oBAAI,IAAI;AAEhD,SAAS,aAAa,aAAgC;AAC3D,MAAI,QAAQ,eAAe,IAAI,WAAW;AAC1C,MAAI,CAAC,OAAO;AACV,YAAQ,IAAI,UAAU,WAAW;AACjC,mBAAe,IAAI,aAAa,KAAK;AAAA,EACvC;AACA,SAAO;AACT;","names":["basename","issues","DEFAULT_CONFIG","basename","currentHashes","ContextGraph","getStorage"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli/checkpoint.ts","../src/utils/trie-init.ts","../src/utils/errors.ts","../src/agent/confidence.ts","../src/agent/learning.ts","../src/agent/learning-engine.ts","../src/agent/perceive.ts","../src/agent/diff-analyzer.ts","../src/agent/risk-scorer.ts","../src/agent/pattern-matcher.ts","../src/orchestrator/triager.ts","../src/utils/parallel-executor.ts","../src/utils/cache-manager.ts","../src/orchestrator/executor.ts","../src/agent/reason.ts"],"sourcesContent":["/**\n * Checkpoint CLI\n * \n * Save your work context to .trie/ without running a full scan.\n * Think of it as a quick save - captures what you're working on.\n */\n\nimport { existsSync } from 'fs';\nimport { mkdir, writeFile, readFile } from 'fs/promises';\nimport { join } from 'path';\nimport { getWorkingDirectory, getTrieDirectory } from '../utils/workspace.js';\n\nexport interface Checkpoint {\n id: string;\n timestamp: string;\n message?: string;\n files: string[];\n notes?: string;\n createdBy: 'cli' | 'mcp';\n}\n\nexport interface CheckpointLog {\n checkpoints: Checkpoint[];\n lastCheckpoint?: string;\n}\n\n/**\n * Save a checkpoint\n */\nexport async function saveCheckpoint(options: {\n message?: string;\n files?: string[];\n notes?: string;\n workDir?: string;\n createdBy?: 'cli' | 'mcp';\n}): Promise<Checkpoint> {\n const workDir = options.workDir || getWorkingDirectory(undefined, true);\n const trieDir = getTrieDirectory(workDir);\n const checkpointPath = join(trieDir, 'checkpoints.json');\n \n await mkdir(trieDir, { recursive: true });\n \n // Load existing checkpoints\n let log: CheckpointLog = { checkpoints: [] };\n try {\n if (existsSync(checkpointPath)) {\n log = JSON.parse(await readFile(checkpointPath, 'utf-8'));\n }\n } catch {\n log = { checkpoints: [] };\n }\n \n // Create new checkpoint\n const checkpoint: Checkpoint = {\n id: `cp-${Date.now().toString(36)}`,\n timestamp: new Date().toISOString(),\n files: options.files || [],\n createdBy: options.createdBy || 'cli',\n };\n if (options.message) checkpoint.message = options.message;\n if (options.notes) checkpoint.notes = options.notes;\n \n // Add to log\n log.checkpoints.push(checkpoint);\n log.lastCheckpoint = checkpoint.id;\n \n // Keep last 50 checkpoints\n if (log.checkpoints.length > 50) {\n log.checkpoints = log.checkpoints.slice(-50);\n }\n \n // Save\n await writeFile(checkpointPath, JSON.stringify(log, null, 2));\n \n // Also update AGENTS.md with checkpoint note\n await updateAgentsMdWithCheckpoint(checkpoint, workDir);\n \n return checkpoint;\n}\n\n/**\n * List checkpoints\n */\nexport async function listCheckpoints(workDir?: string): Promise<Checkpoint[]> {\n const dir = workDir || getWorkingDirectory(undefined, true);\n const checkpointPath = join(getTrieDirectory(dir), 'checkpoints.json');\n \n try {\n if (existsSync(checkpointPath)) {\n const log: CheckpointLog = JSON.parse(await readFile(checkpointPath, 'utf-8'));\n return log.checkpoints;\n }\n } catch {\n // File doesn't exist or is corrupted\n }\n \n return [];\n}\n\n/**\n * Get the last checkpoint\n */\nexport async function getLastCheckpoint(workDir?: string): Promise<Checkpoint | null> {\n const checkpoints = await listCheckpoints(workDir);\n const last = checkpoints[checkpoints.length - 1];\n return last ?? null;\n}\n\n/**\n * Update AGENTS.md with checkpoint info\n */\nasync function updateAgentsMdWithCheckpoint(checkpoint: Checkpoint, workDir: string): Promise<void> {\n const agentsPath = join(getTrieDirectory(workDir), 'AGENTS.md');\n \n let content = '';\n try {\n if (existsSync(agentsPath)) {\n content = await readFile(agentsPath, 'utf-8');\n }\n } catch {\n content = '';\n }\n \n // Find or create checkpoint section\n const checkpointSection = `\n## Last Checkpoint\n\n- **ID:** ${checkpoint.id}\n- **Time:** ${checkpoint.timestamp}\n${checkpoint.message ? `- **Message:** ${checkpoint.message}` : ''}\n${checkpoint.files.length > 0 ? `- **Files:** ${checkpoint.files.length} files` : ''}\n${checkpoint.notes ? `- **Notes:** ${checkpoint.notes}` : ''}\n`;\n \n // Replace existing checkpoint section or append\n const checkpointRegex = /## Last Checkpoint[\\s\\S]*?(?=\\n## |\\n---|\\Z)/;\n if (checkpointRegex.test(content)) {\n content = content.replace(checkpointRegex, checkpointSection.trim());\n } else {\n content = content.trim() + '\\n\\n' + checkpointSection.trim() + '\\n';\n }\n \n await writeFile(agentsPath, content);\n}\n\n/**\n * CLI handler for checkpoint command\n */\nexport async function handleCheckpointCommand(args: string[]): Promise<void> {\n const subcommand = args[0] || 'save';\n \n switch (subcommand) {\n case 'save': {\n // Parse options\n let message: string | undefined;\n let notes: string | undefined;\n const files: string[] = [];\n \n for (let i = 1; i < args.length; i++) {\n const arg = args[i];\n if (arg === '-m' || arg === '--message') {\n message = args[++i] ?? '';\n } else if (arg === '-n' || arg === '--notes') {\n notes = args[++i] ?? '';\n } else if (arg === '-f' || arg === '--file') {\n const file = args[++i];\n if (file) files.push(file);\n } else if (arg && !arg.startsWith('-')) {\n // Treat as message if no flag\n message = arg;\n }\n }\n \n const opts: { message?: string; files?: string[]; notes?: string } = { files };\n if (message) opts.message = message;\n if (notes) opts.notes = notes;\n const checkpoint = await saveCheckpoint(opts);\n \n console.log('\\n Checkpoint saved\\n');\n console.log(` ID: ${checkpoint.id}`);\n console.log(` Time: ${checkpoint.timestamp}`);\n if (checkpoint.message) {\n console.log(` Message: ${checkpoint.message}`);\n }\n if (checkpoint.files.length > 0) {\n console.log(` Files: ${checkpoint.files.join(', ')}`);\n }\n console.log('\\n Context saved to .trie/\\n');\n break;\n }\n \n case 'list': {\n const checkpoints = await listCheckpoints();\n \n if (checkpoints.length === 0) {\n console.log('\\n No checkpoints yet. Run `trie checkpoint` to save one.\\n');\n return;\n }\n \n console.log('\\n Checkpoints:\\n');\n for (const cp of checkpoints.slice(-10).reverse()) {\n const date = new Date(cp.timestamp).toLocaleString();\n console.log(` ${cp.id} ${date} ${cp.message || '(no message)'}`);\n }\n console.log('');\n break;\n }\n \n case 'last': {\n const checkpoint = await getLastCheckpoint();\n \n if (!checkpoint) {\n console.log('\\n No checkpoints yet. Run `trie checkpoint` to save one.\\n');\n return;\n }\n \n console.log('\\n Last Checkpoint:\\n');\n console.log(` ID: ${checkpoint.id}`);\n console.log(` Time: ${new Date(checkpoint.timestamp).toLocaleString()}`);\n if (checkpoint.message) {\n console.log(` Message: ${checkpoint.message}`);\n }\n if (checkpoint.notes) {\n console.log(` Notes: ${checkpoint.notes}`);\n }\n if (checkpoint.files.length > 0) {\n console.log(` Files: ${checkpoint.files.join(', ')}`);\n }\n console.log('');\n break;\n }\n \n default:\n console.log(`\n Usage: trie checkpoint [command] [options]\n\n Commands:\n save [message] Save a checkpoint (default)\n list List recent checkpoints\n last Show the last checkpoint\n\n Options:\n -m, --message Checkpoint message\n -n, --notes Additional notes\n -f, --file File to include (can be repeated)\n\n Examples:\n trie checkpoint \"finished auth flow\"\n trie checkpoint save -m \"WIP: payment integration\" -n \"needs testing\"\n trie checkpoint list\n`);\n }\n}\n","import { existsSync } from 'fs';\nimport { join } from 'path';\nimport { getWorkingDirectory, getTrieDirectory } from './workspace.js';\n\nconst INIT_MARKERS = [\n 'PROJECT.md',\n 'RULES.md',\n 'TEAM.md',\n 'BOOTSTRAP.md',\n 'AGENTS.md',\n 'config.json',\n];\n\nexport function isTrieInitialized(workDir?: string): boolean {\n const dir = workDir || getWorkingDirectory(undefined, true);\n const trieDir = getTrieDirectory(dir);\n return INIT_MARKERS.some((marker) => existsSync(join(trieDir, marker)));\n}\n","export class TrieError extends Error {\n code: string;\n recoverable: boolean;\n userMessage: string;\n\n constructor(message: string, code: string, userMessage: string, recoverable = true) {\n super(message);\n this.code = code;\n this.recoverable = recoverable;\n this.userMessage = userMessage;\n }\n}\n\nexport class GraphError extends TrieError {\n constructor(message: string) {\n super(\n message,\n 'GRAPH_ERROR',\n 'Trie had trouble accessing its memory. Try again or re-run trie reconcile.',\n true\n );\n }\n}\n\nexport class GitError extends TrieError {\n constructor(message: string) {\n super(\n message,\n 'GIT_ERROR',\n 'Git info is unavailable. Is this a git repo? Commit once, or pass --files to trie check.',\n true\n );\n }\n}\n\nexport class NetworkError extends TrieError {\n constructor(message: string) {\n super(\n message,\n 'NETWORK_ERROR',\n 'Network unavailable. Running in offline mode; AI calls skipped.',\n true\n );\n }\n}\n\nexport class MissingAPIKeyError extends TrieError {\n constructor(message = 'Missing ANTHROPIC_API_KEY') {\n super(\n message,\n 'MISSING_API_KEY',\n 'No API key detected. Set ANTHROPIC_API_KEY for AI-powered analysis (deeper issue detection, smarter fixes). Running in pattern-only mode.',\n true\n );\n }\n}\n\nexport function formatFriendlyError(error: unknown): { userMessage: string; code: string } {\n if (error instanceof TrieError) {\n return { userMessage: error.userMessage, code: error.code };\n }\n return {\n userMessage: 'Something went wrong. Try again or run with --offline.',\n code: 'UNKNOWN'\n };\n}\n","/**\n * Lightweight Bayesian-style confidence updater.\n * Treats confidence as probability in [0,1].\n */\n\nexport function bayesianUpdate(prior: number, evidence: number, weight = 1): number {\n const p = clamp(prior);\n const e = clamp(evidence);\n const w = Math.max(0, weight);\n // Blend prior with evidence weighted by w\n const posterior = (p * (1 - w)) + (e * w);\n return clamp(posterior);\n}\n\nexport function adjustConfidence(current: number, outcome: 'positive' | 'negative', step = 0.1): number {\n const delta = outcome === 'positive' ? step : -step;\n return clamp(current + delta);\n}\n\nfunction clamp(value: number): number {\n if (Number.isNaN(value)) return 0.5;\n return Math.min(1, Math.max(0, value));\n}\n","import { ContextGraph } from '../context/graph.js';\nimport type { IncidentNode, PatternNode } from '../context/nodes.js';\nimport { IncidentIndex } from '../context/incident-index.js';\nimport { adjustConfidence } from './confidence.js';\nimport { TriePatternDiscovery } from './pattern-discovery.js';\n\nexport class LearningSystem {\n private incidentIndex: IncidentIndex;\n private discovery: TriePatternDiscovery;\n\n constructor(private graph: ContextGraph, projectPath: string) {\n this.incidentIndex = new IncidentIndex(graph, projectPath);\n this.discovery = new TriePatternDiscovery(graph, this.incidentIndex);\n }\n\n async onWarningHeeded(files: string[]): Promise<void> {\n await this.adjustPatterns(files, 'positive');\n }\n\n async onWarningIgnored(files: string[]): Promise<void> {\n await this.adjustPatterns(files, 'negative');\n }\n\n async onIncidentReported(incidentId: string, files: string[]): Promise<void> {\n const incident = await this.graph.getNode('incident', incidentId);\n if (incident && incident.type === 'incident') {\n this.incidentIndex.addIncidentToTrie(incident as IncidentNode, files);\n }\n await this.discoverAndStorePatterns();\n }\n\n async onFeedback(helpful: boolean, files: string[] = []): Promise<void> {\n await this.adjustPatterns(files, helpful ? 'positive' : 'negative');\n }\n\n private async adjustPatterns(files: string[], outcome: 'positive' | 'negative'): Promise<void> {\n if (!files.length) return;\n for (const file of files) {\n const patterns = await this.graph.getPatternsForFile(file);\n await Promise.all(patterns.map((p) => this.updatePatternConfidence(p, outcome)));\n }\n }\n\n private async updatePatternConfidence(pattern: PatternNode, outcome: 'positive' | 'negative'): Promise<void> {\n const current = pattern.data.confidence ?? 0.5;\n const updated = adjustConfidence(current, outcome, 0.05);\n await this.graph.updateNode('pattern', pattern.id, { confidence: updated, lastSeen: new Date().toISOString() });\n }\n\n private async discoverAndStorePatterns(): Promise<void> {\n const hotPatterns = this.discovery.discoverHotPatterns();\n for (const hot of hotPatterns) {\n await this.graph.addNode('pattern', {\n description: `${hot.type === 'directory' ? 'Directory' : 'File'} hot zone: ${hot.path}`,\n appliesTo: [hot.path],\n confidence: hot.confidence,\n occurrences: hot.incidentCount,\n firstSeen: new Date().toISOString(),\n lastSeen: new Date().toISOString(),\n isAntiPattern: true,\n source: 'local'\n });\n }\n }\n}\n","import { getRecentCommits, getDiff } from '../agent/git.js';\nimport { storeIssues } from '../memory/issue-store.js';\nimport { scanForVulnerabilities } from '../trie/vulnerability-signatures.js';\nimport { scanForVibeCodeIssues } from '../trie/vibe-code-signatures.js';\nimport type { Issue } from '../types/index.js';\nimport { ContextGraph } from '../context/graph.js';\nimport type { DecisionNodeData } from '../context/nodes.js';\nimport { LearningSystem } from '../agent/learning.js';\nimport path from 'node:path';\n\nexport interface LearningResult {\n learned: number;\n source: 'git-history' | 'manual-feedback';\n}\n\nexport class LearningEngine {\n private readonly projectPath: string;\n private readonly graph: ContextGraph;\n private readonly learningSystem: LearningSystem;\n\n constructor(projectPath: string, graph?: ContextGraph) {\n this.projectPath = projectPath;\n this.graph = graph || new ContextGraph(projectPath);\n this.learningSystem = new LearningSystem(this.graph, projectPath);\n }\n\n /**\n * Unified learning method: Scans history AND processes manual feedback\n */\n async learn(options: { \n limit?: number; \n manualFeedback?: { helpful: boolean; files: string[]; note?: string } \n } = {}): Promise<LearningResult[]> {\n const results: LearningResult[] = [];\n\n // 1. Implicit Learning from Git History\n if (!options.manualFeedback) {\n const implicitCount = await this.learnFromHistory(options.limit || 20);\n results.push({ learned: implicitCount, source: 'git-history' });\n }\n\n // 2. Manual Feedback Learning\n if (options.manualFeedback) {\n await this.recordManualFeedback(\n options.manualFeedback.helpful, \n options.manualFeedback.files, \n options.manualFeedback.note\n );\n results.push({ learned: options.manualFeedback.files.length || 1, source: 'manual-feedback' });\n }\n\n return results;\n }\n\n /**\n * Scan recent commits for implicit failure signals (reverts, fixes)\n */\n private async learnFromHistory(limit: number = 20): Promise<number> {\n const commits = await getRecentCommits(this.projectPath, limit);\n const issuesToStore: Issue[] = [];\n\n for (const commit of commits) {\n const isRevert = commit.message.toLowerCase().includes('revert') || commit.message.startsWith('Revert \"');\n const isFix = /fix(es|ed)?\\s+#\\d+/i.test(commit.message) || commit.message.toLowerCase().includes('bugfix');\n\n if (isRevert || isFix) {\n const type = isRevert ? 'revert' : 'fix';\n const diff = await getDiff(this.projectPath, commit.hash);\n const files = this.extractFilesFromDiff(diff);\n \n for (const file of files) {\n const learnedIssues = await this.extractIssuesFromDiff(diff, file, type, commit.message);\n issuesToStore.push(...learnedIssues);\n }\n }\n }\n\n if (issuesToStore.length > 0) {\n const result = await storeIssues(issuesToStore, path.basename(this.projectPath), this.projectPath);\n return result.stored;\n }\n\n return 0;\n }\n\n /**\n * Record manual feedback (trie ok/bad) and adjust pattern confidence\n */\n private async recordManualFeedback(helpful: boolean, files: string[], note?: string): Promise<void> {\n const context = files[0] ?? 'unspecified';\n const decision = await this.graph.addNode('decision', {\n context,\n decision: helpful ? 'helpful' : 'not helpful',\n reasoning: note ?? null,\n outcome: helpful ? 'good' : 'bad',\n timestamp: new Date().toISOString(),\n } satisfies DecisionNodeData);\n\n if (files.length > 0) {\n for (const file of files) {\n const fileNode = await this.graph.getNode('file', file);\n if (fileNode) {\n await this.graph.addEdge(decision.id, fileNode.id, 'affects');\n }\n }\n await this.learningSystem.onFeedback(helpful, files);\n }\n }\n\n private extractFilesFromDiff(diff: string): string[] {\n const files = new Set<string>();\n const lines = diff.split('\\n');\n for (const line of lines) {\n if (line.startsWith('+++ b/')) {\n files.add(line.slice(6));\n }\n }\n return Array.from(files);\n }\n\n private async extractIssuesFromDiff(diff: string, file: string, type: 'revert' | 'fix', message: string): Promise<Issue[]> {\n const issues: Issue[] = [];\n const badLines = this.getBadLinesFromDiff(diff, file, type);\n const content = badLines.join('\\n');\n\n if (!content) return [];\n\n const vulnerabilities = await scanForVulnerabilities(content, file);\n const vibeIssues = await scanForVibeCodeIssues(content, file);\n\n const allMatches = [...vulnerabilities, ...vibeIssues];\n\n for (const match of allMatches) {\n issues.push({\n id: `implicit-${type}-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`,\n severity: 'serious',\n issue: `Implicit failure detected via ${type}: ${message}. Linked to pattern: ${match.category}`,\n fix: `Review the ${type} commit and avoid this pattern in ${file}.`,\n file: file,\n confidence: 0.7,\n autoFixable: false,\n agent: 'implicit-learning',\n category: match.category\n });\n }\n\n if (issues.length === 0) {\n issues.push({\n id: `implicit-${type}-${Date.now()}`,\n severity: 'moderate',\n issue: `Historical ${type} detected: ${message}`,\n fix: `Review the changes in ${file} from this commit to avoid regression.`,\n file: file,\n confidence: 0.5,\n autoFixable: false,\n agent: 'implicit-learning'\n });\n }\n\n return issues;\n }\n\n private getBadLinesFromDiff(diff: string, file: string, type: 'revert' | 'fix'): string[] {\n const badLines: string[] = [];\n const lines = diff.split('\\n');\n let inTargetFile = false;\n\n for (const line of lines) {\n if (line.startsWith('+++ b/') || line.startsWith('--- a/')) {\n inTargetFile = line.includes(file);\n continue;\n }\n\n if (!inTargetFile) continue;\n\n if (type === 'fix' && line.startsWith('-') && !line.startsWith('---')) {\n badLines.push(line.slice(1));\n } else if (type === 'revert' && line.startsWith('+') && !line.startsWith('+++')) {\n badLines.push(line.slice(1));\n }\n }\n\n return badLines;\n }\n}\n","import path from 'node:path';\n\nimport { analyzeDiff, type DiffSummary } from './diff-analyzer.js';\nimport {\n getStagedChanges,\n getUncommittedChanges,\n getWorkingTreeDiff,\n type Change\n} from './git.js';\nimport { ContextGraph } from '../context/graph.js';\nimport type { FileNode, FileNodeData } from '../context/nodes.js';\n\nexport interface PerceptionResult {\n staged: Change[];\n unstaged: Change[];\n diffSummary: DiffSummary;\n changeNodeId?: string;\n}\n\nexport async function perceiveCurrentChanges(\n projectPath: string,\n graph?: ContextGraph\n): Promise<PerceptionResult> {\n const ctxGraph = graph ?? new ContextGraph(projectPath);\n\n const [staged, unstaged] = await Promise.all([\n getStagedChanges(projectPath),\n getUncommittedChanges(projectPath)\n ]);\n\n const stagedDiff = await getWorkingTreeDiff(projectPath, true);\n const unstagedDiff = await getWorkingTreeDiff(projectPath, false);\n const combinedDiff = [stagedDiff, unstagedDiff].filter(Boolean).join('\\n');\n const diffSummary = analyzeDiff(combinedDiff);\n\n const filesTouched = new Set<string>();\n staged.forEach((c) => filesTouched.add(c.path));\n unstaged.forEach((c) => filesTouched.add(c.path));\n diffSummary.files.forEach((f) => filesTouched.add(f.filePath));\n\n const changeId = await upsertWorkingChange(ctxGraph, Array.from(filesTouched), projectPath);\n\n const result: PerceptionResult = {\n staged,\n unstaged,\n diffSummary\n };\n if (changeId) result.changeNodeId = changeId;\n return result;\n}\n\nasync function upsertWorkingChange(\n graph: ContextGraph,\n files: string[],\n projectPath: string\n): Promise<string | undefined> {\n if (files.length === 0) return undefined;\n\n const now = new Date().toISOString();\n const change = await graph.addNode('change', {\n commitHash: null,\n files,\n message: 'workspace changes',\n diff: null,\n author: null,\n timestamp: now,\n outcome: 'unknown'\n });\n\n for (const filePath of files) {\n const fileNode = await ensureFileNode(graph, filePath, projectPath);\n await graph.addEdge(change.id, fileNode.id, 'affects');\n }\n\n return change.id;\n}\n\nasync function ensureFileNode(\n graph: ContextGraph,\n filePath: string,\n projectPath: string\n): Promise<FileNode> {\n const normalized = path.resolve(projectPath, filePath);\n const existing = await graph.getNode('file', normalized);\n\n const now = new Date().toISOString();\n if (existing) {\n const data = existing.data as FileNodeData;\n await graph.updateNode('file', existing.id, {\n changeCount: (data.changeCount ?? 0) + 1,\n lastChanged: now\n });\n return (await graph.getNode('file', existing.id)) as FileNode;\n }\n\n const data: FileNodeData = {\n path: filePath,\n extension: path.extname(filePath),\n purpose: '',\n riskLevel: 'medium',\n whyRisky: null,\n changeCount: 1,\n lastChanged: now,\n incidentCount: 0,\n createdAt: now\n };\n\n return (await graph.addNode('file', data)) as FileNode;\n}\n","export interface DiffFileSummary {\n filePath: string;\n added: number;\n removed: number;\n functionsModified: string[];\n riskyPatterns: string[];\n}\n\nexport interface DiffSummary {\n files: DiffFileSummary[];\n totalAdded: number;\n totalRemoved: number;\n riskyFiles: string[];\n}\n\nconst RISKY_PATTERNS = [/auth/i, /token/i, /password/i, /secret/i, /validate/i, /sanitize/i];\n\nexport function analyzeDiff(diff: string): DiffSummary {\n const files: DiffFileSummary[] = [];\n let current: DiffFileSummary | null = null;\n\n const lines = diff.split('\\n');\n\n for (const line of lines) {\n if (line.startsWith('+++ b/')) {\n const filePath = line.replace('+++ b/', '').trim();\n current = {\n filePath,\n added: 0,\n removed: 0,\n functionsModified: [],\n riskyPatterns: []\n };\n files.push(current);\n continue;\n }\n\n if (!current) {\n continue;\n }\n\n if (line.startsWith('@@')) {\n // Capture function names or signatures in hunk headers\n const match = line.match(/@@.*?(function\\s+([\\w$]+)|class\\s+([\\w$]+)|([\\w$]+\\s*\\())/i);\n const fnName = match?.[2] || match?.[3] || match?.[4];\n if (fnName) {\n current.functionsModified.push(fnName.replace('(', '').trim());\n }\n continue;\n }\n\n if (line.startsWith('+') && !line.startsWith('+++')) {\n current.added += 1;\n markRisk(line, current);\n } else if (line.startsWith('-') && !line.startsWith('---')) {\n current.removed += 1;\n markRisk(line, current);\n }\n }\n\n const totalAdded = files.reduce((acc, f) => acc + f.added, 0);\n const totalRemoved = files.reduce((acc, f) => acc + f.removed, 0);\n const riskyFiles = files.filter((f) => f.riskyPatterns.length > 0).map((f) => f.filePath);\n\n return {\n files,\n totalAdded,\n totalRemoved,\n riskyFiles\n };\n}\n\nfunction markRisk(line: string, file: DiffFileSummary): void {\n for (const pattern of RISKY_PATTERNS) {\n if (pattern.test(line)) {\n const label = pattern.toString();\n if (!file.riskyPatterns.includes(label)) {\n file.riskyPatterns.push(label);\n }\n }\n }\n}\n","import * as path from 'node:path';\n\nimport type { RiskLevel } from '../types/index.js';\nimport type { PatternNode } from '../context/types.js';\nimport type { ContextGraph } from '../context/graph.js';\nimport type { FileNodeData, IncidentNode } from '../context/nodes.js';\n\nexport interface FileRiskResult {\n file: string;\n score: number;\n level: RiskLevel;\n reasons: string[];\n incidents: IncidentNode[];\n matchedPatterns: PatternNode[];\n}\n\nexport interface ChangeRiskResult {\n files: FileRiskResult[];\n overall: RiskLevel;\n score: number;\n shouldEscalate: boolean;\n}\n\nconst BASE_RISK: Record<RiskLevel, number> = {\n low: 10,\n medium: 35,\n high: 65,\n critical: 85\n};\n\nconst SENSITIVE_PATHS: { pattern: RegExp; weight: number; reason: string }[] = [\n { pattern: /auth|login|token|session/i, weight: 20, reason: 'touches authentication' },\n { pattern: /payment|billing|stripe|paypal|checkout/i, weight: 25, reason: 'touches payments' },\n { pattern: /secret|credential|env|config\\/security/i, weight: 15, reason: 'touches secrets/security config' },\n];\n\nfunction levelFromScore(score: number): RiskLevel {\n if (score >= 90) return 'critical';\n if (score >= 65) return 'high';\n if (score >= 40) return 'medium';\n return 'low';\n}\n\nexport async function scoreFile(\n graph: ContextGraph,\n filePath: string,\n matchedPatterns: PatternNode[] = []\n): Promise<FileRiskResult> {\n const reasons: string[] = [];\n const normalized = path.resolve(graph.projectRoot, filePath);\n const node = await graph.getNode('file', normalized);\n const incidents = await graph.getIncidentsForFile(filePath);\n\n let score = 10;\n const data = node?.data as FileNodeData | undefined;\n\n if (data) {\n score = BASE_RISK[data.riskLevel] ?? score;\n reasons.push(`baseline ${data.riskLevel}`);\n\n if (data.incidentCount > 0) {\n const incBoost = Math.min(data.incidentCount * 12, 36);\n score += incBoost;\n reasons.push(`historical incidents (+${incBoost})`);\n }\n\n if (data.changeCount > 5) {\n const changeBoost = Math.min((data.changeCount - 5) * 2, 12);\n score += changeBoost;\n reasons.push(`frequent changes (+${changeBoost})`);\n }\n\n if (data.lastChanged) {\n const lastChanged = new Date(data.lastChanged).getTime();\n const days = (Date.now() - lastChanged) / (1000 * 60 * 60 * 24);\n if (days > 60 && data.incidentCount === 0) {\n score -= 5;\n reasons.push('stable for 60d (-5)');\n }\n }\n }\n\n for (const { pattern, weight, reason } of SENSITIVE_PATHS) {\n if (pattern.test(filePath)) {\n score += weight;\n reasons.push(reason);\n }\n }\n\n if (matchedPatterns.length > 0) {\n const patternBoost = Math.min(\n matchedPatterns.reduce((acc, p) => acc + (p.data.confidence ?? 50) / 10, 0),\n 20\n );\n score += patternBoost;\n reasons.push(`pattern match (+${Math.round(patternBoost)})`);\n }\n\n if (incidents.length > 0) {\n const timestamps = incidents\n .map((i) => new Date(i.data.timestamp).getTime())\n .sort((a, b) => b - a);\n const recent = timestamps[0]!;\n const daysSince = (Date.now() - recent) / (1000 * 60 * 60 * 24);\n if (daysSince > 90) {\n score -= 5;\n reasons.push('no incidents in 90d (-5)');\n } else {\n score += 8;\n reasons.push('recent incident (+8)');\n }\n }\n\n const level = levelFromScore(score);\n return {\n file: filePath,\n score,\n level,\n reasons,\n incidents,\n matchedPatterns\n };\n}\n\nexport async function scoreChangeSet(\n graph: ContextGraph,\n files: string[],\n patternMatches: Record<string, PatternNode[]> = {}\n): Promise<ChangeRiskResult> {\n const fileResults: FileRiskResult[] = [];\n\n for (const file of files) {\n const patterns = patternMatches[file] ?? [];\n fileResults.push(await scoreFile(graph, file, patterns));\n }\n\n // Aggregate: use max file score, but boost if many files touched\n const maxScore = Math.max(...fileResults.map((f) => f.score), 10);\n const spreadBoost = files.length > 5 ? Math.min((files.length - 5) * 2, 10) : 0;\n const overallScore = maxScore + spreadBoost;\n const overall = levelFromScore(overallScore);\n\n const shouldEscalate = overall === 'critical' || overall === 'high';\n\n return {\n files: fileResults,\n overall,\n score: overallScore,\n shouldEscalate\n };\n}\n","import { ContextGraph } from '../context/graph.js';\nimport type { PatternNode } from '../context/nodes.js';\n\nexport interface PatternMatch {\n file: string;\n pattern: PatternNode;\n confidence: number;\n isAntiPattern: boolean;\n}\n\nexport async function matchPatternsForFiles(\n graph: ContextGraph,\n files: string[]\n): Promise<{ matches: PatternMatch[]; byFile: Record<string, PatternNode[]> }> {\n const matches: PatternMatch[] = [];\n const byFile: Record<string, PatternNode[]> = {};\n\n for (const file of files) {\n const patterns = await graph.getPatternsForFile(file);\n if (patterns.length === 0) continue;\n\n byFile[file] = patterns;\n\n for (const pattern of patterns) {\n matches.push({\n file,\n pattern,\n confidence: pattern.data.confidence,\n isAntiPattern: pattern.data.isAntiPattern\n });\n }\n }\n\n return { matches, byFile };\n}\n","import type { CodeContext, Agent, TriagingConfig } from '../types/index.js';\n\nexport class Triager {\n constructor(_config?: Partial<TriagingConfig>) {\n // Config no longer used - Trie is now purely a decision ledger\n }\n\n /**\n * Triage a change to select appropriate agents\n * Note: Skills/agents have been removed - Trie is now purely a decision ledger\n */\n async triage(\n _context: CodeContext,\n _forceAgents?: string[]\n ): Promise<Agent[]> {\n // No skills to triage - return empty array\n // Trie now focuses on decision ledger and learning from incidents\n return [];\n }\n\n /**\n * Get all available agent names (deprecated - returns empty array)\n */\n getAvailableAgents(): string[] {\n return [];\n }\n}\n","import { Worker } from 'worker_threads';\nimport { cpus } from 'os';\nimport { existsSync } from 'fs';\nimport { fileURLToPath } from 'url';\nimport type { Agent, AgentResult, ScanContext } from '../types/index.js';\nimport { StreamingManager } from './streaming.js';\nimport { CacheManager } from './cache-manager.js';\nimport { isInteractiveMode } from './progress.js';\n\ninterface ParallelTask {\n agent: Agent;\n files: string[];\n context: ScanContext;\n priority: number;\n timeoutMs: number;\n}\n\ninterface ParallelResult {\n agent: string;\n result: AgentResult;\n fromCache: boolean;\n executionTime: number;\n}\n\n/**\n * Parallel execution engine for Trie agents\n *\n * Features:\n * - True parallel execution using worker threads\n * - Intelligent scheduling based on agent priority\n * - Result caching and cache-aware scheduling\n * - Real-time progress streaming\n * - Dynamic resource management\n */\nexport class ParallelExecutor {\n private maxWorkers: number;\n private cache: CacheManager | null;\n private streaming?: StreamingManager;\n private activeWorkers: Set<Worker> = new Set();\n private cacheEnabled: boolean = true;\n private useWorkerThreads: boolean = false;\n private workerAvailable: boolean | null = null;\n private warnedWorkerFallback: boolean = false;\n\n constructor(\n cacheManager: CacheManager | null,\n maxWorkers: number = Math.max(2, Math.min(cpus().length - 1, 8)),\n options?: { cacheEnabled?: boolean; useWorkerThreads?: boolean }\n ) {\n this.maxWorkers = maxWorkers;\n this.cache = cacheManager;\n this.cacheEnabled = options?.cacheEnabled ?? true;\n this.useWorkerThreads = options?.useWorkerThreads ?? false;\n }\n\n /**\n * Set streaming manager for real-time updates\n */\n setStreaming(streaming: StreamingManager): void {\n this.streaming = streaming;\n }\n\n /**\n * Execute agents in parallel with intelligent scheduling\n */\n async executeAgents(\n agents: Agent[],\n files: string[],\n context: ScanContext\n ): Promise<Map<string, AgentResult>> {\n if (agents.length === 0) {\n return new Map();\n }\n\n // Initialize streaming\n if (this.streaming && this.streaming.getProgress().totalFiles === 0) {\n this.streaming.startScan(files.length);\n }\n\n // Check cache for existing results\n const cacheResults = new Map<string, AgentResult>();\n const uncachedTasks: ParallelTask[] = [];\n\n for (const agent of agents) {\n const cached = await this.checkAgentCache(agent, files);\n if (cached) {\n cacheResults.set(agent.name, cached);\n this.streaming?.completeAgent(agent.name, cached.issues);\n } else {\n uncachedTasks.push({\n agent,\n files,\n context,\n priority: agent.priority?.tier || 2,\n timeoutMs: context?.config?.timeoutMs || 120000\n });\n }\n }\n\n // Sort tasks by priority (tier 1 = highest priority)\n uncachedTasks.sort((a, b) => a.priority - b.priority);\n\n // Execute uncached tasks in parallel\n const parallelResults = await this.executeTasksParallel(uncachedTasks);\n\n // Cache new results\n await this.cacheResults(parallelResults);\n\n // Combine cached and new results\n const allResults = new Map<string, AgentResult>();\n\n // Add cached results\n for (const [agent, result] of Array.from(cacheResults.entries())) {\n allResults.set(agent, result);\n }\n\n // Add new results\n for (const result of parallelResults) {\n allResults.set(result.agent, result.result);\n }\n\n // Complete streaming\n const allIssues = Array.from(allResults.values()).flatMap(r => r.issues);\n this.streaming?.completeScan(allIssues);\n\n return allResults;\n }\n\n /**\n * Check if agent has cached results for given files\n */\n private async checkAgentCache(agent: Agent, files: string[]): Promise<AgentResult | null> {\n if (!this.cacheEnabled || !this.cache) {\n return null;\n }\n\n const cachedIssues = await this.cache.getCachedBatch(files, agent.name);\n\n // Only use cache if we have results for ALL files\n if (cachedIssues.size === files.length) {\n const allIssues = Array.from(cachedIssues.values()).flat();\n return {\n agent: agent.name,\n issues: allIssues,\n executionTime: 0, // Cached\n success: true,\n metadata: {\n filesAnalyzed: files.length,\n linesAnalyzed: 0\n }\n };\n }\n\n return null;\n }\n\n /**\n * Execute tasks in parallel batches\n */\n private async executeTasksParallel(tasks: ParallelTask[]): Promise<ParallelResult[]> {\n if (tasks.length === 0) {\n return [];\n }\n\n const results: ParallelResult[] = [];\n const batches = this.createBatches(tasks, this.maxWorkers);\n\n for (const batch of batches) {\n const batchResults = await Promise.all(\n batch.map(task => this.executeTask(task))\n );\n results.push(...batchResults);\n }\n\n return results;\n }\n\n /**\n * Create batches for parallel execution\n */\n private createBatches(tasks: ParallelTask[], batchSize: number): ParallelTask[][] {\n const batches: ParallelTask[][] = [];\n\n for (let i = 0; i < tasks.length; i += batchSize) {\n batches.push(tasks.slice(i, i + batchSize));\n }\n\n return batches;\n }\n\n /**\n * Execute a single task\n */\n private async executeTask(task: ParallelTask): Promise<ParallelResult> {\n const startTime = Date.now();\n\n this.streaming?.startAgent(task.agent.name);\n\n try {\n const result = this.canUseWorkers()\n ? await this.executeTaskInWorker(task)\n : await task.agent.scan(task.files, task.context);\n const executionTime = Date.now() - startTime;\n\n this.streaming?.completeAgent(task.agent.name, result.issues);\n\n return {\n agent: task.agent.name,\n result,\n fromCache: false,\n executionTime\n };\n } catch (error) {\n const executionTime = Date.now() - startTime;\n const errorMessage = error instanceof Error ? error.message : String(error);\n\n this.streaming?.reportError(new Error(errorMessage), `Agent: ${task.agent.name}`);\n\n return {\n agent: task.agent.name,\n result: {\n agent: task.agent.name,\n issues: [],\n executionTime,\n success: false,\n error: errorMessage\n },\n fromCache: false,\n executionTime\n };\n }\n }\n\n private canUseWorkers(): boolean {\n if (!this.useWorkerThreads) {\n return false;\n }\n if (this.workerAvailable !== null) {\n return this.workerAvailable;\n }\n const workerUrl = this.getWorkerUrl();\n this.workerAvailable = existsSync(fileURLToPath(workerUrl));\n if (!this.workerAvailable && !this.warnedWorkerFallback && !isInteractiveMode()) {\n console.error('Worker threads unavailable; falling back to in-process agents.');\n this.warnedWorkerFallback = true;\n }\n return this.workerAvailable;\n }\n\n private getWorkerUrl(): URL {\n const distDir = new URL('.', import.meta.url);\n return new URL('workers/agent-worker.js', distDir);\n }\n\n private async executeTaskInWorker(task: ParallelTask): Promise<AgentResult> {\n // Use dirname to get the dist folder, then resolve to workers subfolder\n // This works whether the code is bundled into chunks or in utils/ folder\n const workerUrl = this.getWorkerUrl();\n\n return new Promise((resolve, reject) => {\n const worker = new Worker(workerUrl, {\n workerData: {\n agentName: task.agent.name,\n files: task.files,\n context: task.context\n }\n } as ConstructorParameters<typeof Worker>[1]);\n\n this.activeWorkers.add(worker);\n\n const timeout = setTimeout(() => {\n worker.terminate().catch(() => undefined);\n reject(new Error(`Agent ${task.agent.name} timed out after ${task.timeoutMs}ms`));\n }, task.timeoutMs);\n\n worker.on('message', (message) => {\n if (message?.type === 'result') {\n clearTimeout(timeout);\n resolve(message.result as AgentResult);\n } else if (message?.type === 'error') {\n clearTimeout(timeout);\n reject(new Error(message.error));\n }\n });\n\n worker.on('error', (error) => {\n clearTimeout(timeout);\n reject(error);\n });\n\n worker.on('exit', (code) => {\n this.activeWorkers.delete(worker);\n if (code !== 0) {\n clearTimeout(timeout);\n reject(new Error(`Worker stopped with exit code ${code}`));\n }\n });\n });\n }\n\n /**\n * Cache results for future use\n */\n private async cacheResults(results: ParallelResult[]): Promise<void> {\n if (!this.cacheEnabled || !this.cache) {\n return;\n }\n\n const cachePromises = results\n .filter(r => r.result.success && !r.fromCache)\n .map(r => {\n const issuesByFile = this.groupIssuesByFile(r.result.issues);\n const perFilePromises = Object.entries(issuesByFile).map(([file, issues]) =>\n this.cache!.setCached(file, r.agent, issues, r.executionTime)\n );\n return Promise.all(perFilePromises);\n });\n\n await Promise.allSettled(cachePromises);\n }\n\n /**\n * Cleanup resources\n */\n async cleanup(): Promise<void> {\n // Terminate any active workers\n const terminationPromises = Array.from(this.activeWorkers).map(worker =>\n worker.terminate()\n );\n\n await Promise.allSettled(terminationPromises);\n this.activeWorkers.clear();\n }\n\n private groupIssuesByFile(issues: AgentResult['issues']): Record<string, AgentResult['issues']> {\n const grouped: Record<string, AgentResult['issues']> = {};\n\n for (const issue of issues) {\n if (!grouped[issue.file]) {\n grouped[issue.file] = [];\n }\n grouped[issue.file]!.push(issue);\n }\n\n return grouped;\n }\n}\n\n/**\n * Smart agent prioritization based on dependencies and execution characteristics\n */\nexport function prioritizeAgents(agents: Agent[]): Agent[] {\n const prioritized = [...agents];\n\n // Sort by priority tier, then by estimated execution time\n prioritized.sort((a, b) => {\n const aTier = a.priority?.tier || 2;\n const bTier = b.priority?.tier || 2;\n\n if (aTier !== bTier) {\n return aTier - bTier; // Lower tier = higher priority\n }\n\n // Within same tier, prioritize faster agents\n const aTime = a.priority?.estimatedTimeMs || 1000;\n const bTime = b.priority?.estimatedTimeMs || 1000;\n\n return aTime - bTime;\n });\n\n return prioritized;\n}\n\n/**\n * Calculate optimal concurrency based on system resources and agent characteristics\n */\nexport function calculateOptimalConcurrency(): number {\n const numCPUs = cpus().length;\n const availableMemoryGB = process.memoryUsage().rss / 1024 / 1024 / 1024;\n\n // Conservative concurrency for stability\n let optimal = Math.max(2, Math.min(numCPUs - 1, 8));\n\n // Reduce concurrency if low memory\n if (availableMemoryGB < 2) {\n optimal = Math.max(2, Math.floor(optimal / 2));\n }\n\n // Increase slightly for systems with lots of CPU cores\n if (numCPUs > 8) {\n optimal = Math.min(optimal + 2, 12);\n }\n\n return optimal;\n}","import { readFile, writeFile, mkdir, stat } from 'fs/promises';\nimport { join } from 'path';\nimport { createHash } from 'crypto';\nimport type { Issue } from '../types/index.js';\nimport { isInteractiveMode } from './progress.js';\nimport { getTrieDirectory } from './workspace.js';\n\ninterface CacheEntry {\n version: string;\n timestamp: number;\n fileHash: string;\n fileSize: number;\n agent: string;\n issues: Issue[];\n executionTime: number;\n}\n\ninterface CacheIndex {\n version: string;\n created: number;\n entries: Record<string, CacheEntry>;\n}\n\nexport class CacheManager {\n private cacheDir: string;\n private indexPath: string;\n private readonly VERSION = '1.0.0';\n private readonly MAX_AGE_MS = 24 * 60 * 60 * 1000; // 24 hours\n private readonly MAX_ENTRIES = 1000;\n\n constructor(baseDir: string) {\n this.cacheDir = join(getTrieDirectory(baseDir), 'cache');\n this.indexPath = join(this.cacheDir, 'index.json');\n }\n\n /**\n * Generate cache key for a file and agent combination\n */\n private generateCacheKey(filePath: string, agent: string, fileHash: string): string {\n const key = `${filePath}:${agent}:${fileHash}`;\n return createHash('sha256').update(key).digest('hex').slice(0, 16);\n }\n\n /**\n * Get file hash for cache validation\n */\n private async getFileHash(filePath: string): Promise<{ hash: string; size: number; mtime: number }> {\n try {\n const content = await readFile(filePath, 'utf-8');\n const stats = await stat(filePath);\n const hash = createHash('sha256').update(content).digest('hex').slice(0, 16);\n return {\n hash,\n size: stats.size,\n mtime: stats.mtime.getTime()\n };\n } catch {\n return { hash: '', size: 0, mtime: 0 };\n }\n }\n\n /**\n * Load cache index\n */\n private async loadIndex(): Promise<CacheIndex> {\n try {\n const content = await readFile(this.indexPath, 'utf-8');\n return JSON.parse(content);\n } catch {\n return {\n version: this.VERSION,\n created: Date.now(),\n entries: {}\n };\n }\n }\n\n /**\n * Save cache index\n */\n private async saveIndex(index: CacheIndex): Promise<void> {\n try {\n await mkdir(this.cacheDir, { recursive: true });\n await writeFile(this.indexPath, JSON.stringify(index, null, 2));\n } catch (error) {\n if (!isInteractiveMode()) {\n console.warn('Failed to save cache index:', error);\n }\n }\n }\n\n /**\n * Clean up expired entries\n */\n private cleanupExpired(index: CacheIndex): CacheIndex {\n const now = Date.now();\n const validEntries: Record<string, CacheEntry> = {};\n\n for (const [key, entry] of Object.entries(index.entries)) {\n if (now - entry.timestamp < this.MAX_AGE_MS) {\n validEntries[key] = entry;\n }\n }\n\n // If still too many, keep the most recent ones\n const entries = Object.entries(validEntries);\n if (entries.length > this.MAX_ENTRIES) {\n entries.sort((a, b) => b[1].timestamp - a[1].timestamp);\n const limited = entries.slice(0, this.MAX_ENTRIES);\n return {\n ...index,\n entries: Object.fromEntries(limited)\n };\n }\n\n return {\n ...index,\n entries: validEntries\n };\n }\n\n /**\n * Get cached result for a file and agent\n * \n * Cache automatically invalidates when files change:\n * - Cache key includes file hash: hash(filePath:agent:fileHash)\n * - When file changes, hash changes, so cache key changes\n * - Old cache entry won't be found (different key)\n * - File is automatically rescanned\n * \n * This means cache auto-updates when Claude fixes code - no manual invalidation needed!\n */\n async getCached(filePath: string, agent: string): Promise<Issue[] | null> {\n try {\n const { hash, size: _size, mtime: _mtime } = await this.getFileHash(filePath);\n if (!hash) return null;\n\n const index = await this.loadIndex();\n const cacheKey = this.generateCacheKey(filePath, agent, hash);\n const entry = index.entries[cacheKey];\n\n if (!entry) return null;\n\n // Validate entry is still fresh\n // Double-check hash matches (defense in depth)\n const isValid = entry.fileHash === hash &&\n entry.version === this.VERSION &&\n (Date.now() - entry.timestamp) < this.MAX_AGE_MS;\n\n if (!isValid) {\n delete index.entries[cacheKey];\n await this.saveIndex(index);\n return null;\n }\n\n return entry.issues;\n } catch {\n return null;\n }\n }\n\n /**\n * Cache result for a file and agent\n */\n async setCached(\n filePath: string,\n agent: string,\n issues: Issue[],\n executionTime: number\n ): Promise<void> {\n try {\n const { hash, size } = await this.getFileHash(filePath);\n if (!hash) return;\n\n const index = await this.loadIndex();\n const cacheKey = this.generateCacheKey(filePath, agent, hash);\n\n index.entries[cacheKey] = {\n version: this.VERSION,\n timestamp: Date.now(),\n fileHash: hash,\n fileSize: size,\n agent,\n issues,\n executionTime\n };\n\n // Clean up old entries\n const cleanedIndex = this.cleanupExpired(index);\n await this.saveIndex(cleanedIndex);\n } catch (error) {\n if (!isInteractiveMode()) {\n console.warn('Failed to cache result:', error);\n }\n }\n }\n\n /**\n * Check if multiple files have cached results\n */\n async getCachedBatch(files: string[], agent: string): Promise<Map<string, Issue[]>> {\n const results = new Map<string, Issue[]>();\n\n await Promise.all(\n files.map(async (file) => {\n const cached = await this.getCached(file, agent);\n if (cached) {\n results.set(file, cached);\n }\n })\n );\n\n return results;\n }\n\n /**\n * Get cache statistics\n */\n async getStats(): Promise<{\n totalEntries: number;\n totalSizeKB: number;\n oldestEntry: number | null;\n newestEntry: number | null;\n agents: string[];\n hitRate?: number;\n }> {\n try {\n const index = await this.loadIndex();\n const entries = Object.values(index.entries);\n\n const totalSizeKB = entries.reduce((acc, entry) => acc + entry.fileSize, 0) / 1024;\n const timestamps = entries.map(e => e.timestamp);\n const agents = Array.from(new Set(entries.map(e => e.agent)));\n\n return {\n totalEntries: entries.length,\n totalSizeKB: Math.round(totalSizeKB),\n oldestEntry: timestamps.length > 0 ? Math.min(...timestamps) : null,\n newestEntry: timestamps.length > 0 ? Math.max(...timestamps) : null,\n agents\n };\n } catch {\n return {\n totalEntries: 0,\n totalSizeKB: 0,\n oldestEntry: null,\n newestEntry: null,\n agents: []\n };\n }\n }\n\n /**\n * Clean up stale cache entries by verifying file hashes\n * This removes entries where files have changed or no longer exist\n * Called periodically to keep cache clean\n * \n * Note: Since cache keys are hashed, we can't easily reverse-engineer file paths.\n * However, when getCached() is called, it naturally invalidates stale entries\n * by checking if the current file hash matches the cached hash. This method\n * proactively cleans up entries for known changed files.\n */\n async cleanupStaleEntries(filePaths?: string[]): Promise<number> {\n try {\n const index = await this.loadIndex();\n let removedCount = 0;\n const keysToRemove: string[] = [];\n\n // If specific files provided, check those files against all cache entries\n // We can't perfectly match entries to files without storing paths, but we can\n // try to identify likely matches by checking if regenerating keys matches\n if (filePaths && filePaths.length > 0) {\n // Get all unique agents from cache entries\n const agents = new Set<string>();\n for (const entry of Object.values(index.entries)) {\n agents.add(entry.agent);\n }\n\n // For each file+agent combination, check if cache entry is stale\n for (const filePath of filePaths) {\n try {\n const { hash: currentHash } = await this.getFileHash(filePath);\n if (!currentHash) {\n // File doesn't exist - can't clean up without knowing which entries are for it\n continue;\n }\n\n // Check each agent's potential cache entries for this file\n for (const agent of Array.from(agents)) {\n // Check all entries to find ones that might be for this file\n for (const [key, entry] of Object.entries(index.entries)) {\n if (entry.agent !== agent) continue;\n \n // If entry hash doesn't match current hash, it might be stale\n if (entry.fileHash !== currentHash) {\n // Check if this key was generated with the old hash for this file\n const oldKey = this.generateCacheKey(filePath, agent, entry.fileHash);\n if (oldKey === key) {\n // This entry is for this file but hash doesn't match - stale!\n keysToRemove.push(key);\n removedCount++;\n }\n }\n }\n }\n } catch {\n // File doesn't exist or can't be read - skip\n continue;\n }\n }\n }\n\n // Remove stale entries (avoid duplicates)\n const uniqueKeys = Array.from(new Set(keysToRemove));\n for (const key of uniqueKeys) {\n delete index.entries[key];\n }\n\n if (removedCount > 0) {\n await this.saveIndex(index);\n }\n\n return removedCount;\n } catch (error) {\n if (!isInteractiveMode()) {\n console.warn('Failed to cleanup stale cache entries:', error);\n }\n return 0;\n }\n }\n\n /**\n * Clear all cache\n */\n async clear(): Promise<void> {\n try {\n const emptyIndex: CacheIndex = {\n version: this.VERSION,\n created: Date.now(),\n entries: {}\n };\n await this.saveIndex(emptyIndex);\n } catch (error) {\n if (!isInteractiveMode()) {\n console.warn('Failed to clear cache:', error);\n }\n }\n }\n}","import type { Agent, AgentResult, ScanContext } from '../types/index.js';\nimport { ParallelExecutor, calculateOptimalConcurrency } from '../utils/parallel-executor.js';\nimport { CacheManager } from '../utils/cache-manager.js';\nimport type { StreamingManager } from '../utils/streaming.js';\nimport { isInteractiveMode } from '../utils/progress.js';\n\nexport class Executor {\n async executeAgents(\n agents: Agent[],\n files: string[],\n context: ScanContext,\n options?: {\n streaming?: StreamingManager;\n parallel?: boolean;\n cacheEnabled?: boolean;\n maxConcurrency?: number;\n useWorkerThreads?: boolean;\n timeoutMs?: number;\n }\n ): Promise<AgentResult[]> {\n const parallel = options?.parallel ?? true;\n const cacheEnabled = options?.cacheEnabled ?? true;\n const maxConcurrency = options?.maxConcurrency ?? calculateOptimalConcurrency();\n const useWorkerThreads = options?.useWorkerThreads ?? false;\n\n if (!isInteractiveMode()) {\n console.error(`Executing ${agents.length} scouts ${parallel ? 'in parallel' : 'sequentially'}...`);\n }\n\n if (parallel) {\n const cacheManager = cacheEnabled ? new CacheManager(context.workingDir) : null;\n const executor = new ParallelExecutor(cacheManager, maxConcurrency, {\n cacheEnabled,\n useWorkerThreads\n });\n\n if (options?.streaming) {\n executor.setStreaming(options.streaming);\n }\n\n const results = await executor.executeAgents(agents, files, {\n ...context,\n config: { timeoutMs: options?.timeoutMs ?? 120000 }\n });\n\n return agents.map(agent => results.get(agent.name)!).filter(Boolean);\n }\n\n // Execute scouts in parallel with timeout\n const promises = agents.map(agent =>\n this.executeAgentWithTimeout(agent, files, context, options?.timeoutMs ?? 30000)\n );\n\n try {\n const results = await Promise.allSettled(promises);\n return results.map((result, index) => {\n if (result.status === 'fulfilled') {\n if (!isInteractiveMode()) {\n console.error(`${agents[index]!.name} completed in ${result.value.executionTime}ms`);\n }\n return result.value;\n } else {\n if (!isInteractiveMode()) {\n console.error(`${agents[index]!.name} failed:`, result.reason);\n }\n return {\n agent: agents[index]!.name,\n issues: [],\n executionTime: 0,\n success: false,\n error: result.reason instanceof Error ? result.reason.message : String(result.reason)\n };\n }\n });\n } catch (error) {\n if (!isInteractiveMode()) {\n console.error('Executor error:', error);\n }\n return agents.map(agent => ({\n agent: agent.name,\n issues: [],\n executionTime: 0,\n success: false,\n error: 'Execution failed'\n }));\n }\n }\n\n private async executeAgentWithTimeout(\n agent: Agent,\n files: string[],\n context: ScanContext,\n timeoutMs: number = 30000 // 30 second timeout\n ): Promise<AgentResult> {\n return new Promise(async (resolve, reject) => {\n const timeout = setTimeout(() => {\n reject(new Error(`Agent ${agent.name} timed out after ${timeoutMs}ms`));\n }, timeoutMs);\n\n try {\n const result = await agent.scan(files, context);\n clearTimeout(timeout);\n resolve(result);\n } catch (error) {\n clearTimeout(timeout);\n reject(error);\n }\n });\n }\n}","import { ContextGraph } from '../context/graph.js';\nimport type { IncidentNode, PatternNode } from '../context/nodes.js';\nimport type { RiskLevel, AgentResult, CodeContext, ScanContext } from '../types/index.js';\nimport { scoreChangeSet, type ChangeRiskResult, type FileRiskResult } from './risk-scorer.js';\nimport { matchPatternsForFiles } from './pattern-matcher.js';\nimport { Triager } from '../orchestrator/triager.js';\nimport { Executor } from '../orchestrator/executor.js';\n\nexport interface Reasoning {\n riskLevel: RiskLevel;\n shouldBlock: boolean;\n explanation: string;\n relevantIncidents: IncidentNode[];\n matchedPatterns: PatternNode[];\n recommendation: string;\n files: FileRiskResult[];\n agentResults?: AgentResult[];\n}\n\nexport interface HumanReadableReasoning {\n summary: string;\n whatIFound: string;\n howBad: string;\n whatToDo: string;\n original: Reasoning;\n}\n\nexport interface ReasonOptions {\n runAgents?: boolean;\n codeContext?: CodeContext;\n scanContext?: Partial<ScanContext>;\n}\n\nfunction buildDefaultCodeContext(): CodeContext {\n return {\n changeType: 'general',\n isNewFeature: false,\n touchesUserData: false,\n touchesAuth: false,\n touchesPayments: false,\n touchesDatabase: false,\n touchesAPI: false,\n touchesUI: false,\n touchesHealthData: false,\n touchesSecurityConfig: false,\n linesChanged: 50,\n filePatterns: [],\n framework: 'unknown',\n language: 'typescript',\n touchesCrypto: false,\n touchesFileSystem: false,\n touchesThirdPartyAPI: false,\n touchesLogging: false,\n touchesErrorHandling: false,\n hasTests: false,\n complexity: 'medium',\n patterns: {\n hasAsyncCode: false,\n hasFormHandling: false,\n hasFileUploads: false,\n hasEmailHandling: false,\n hasRateLimiting: false,\n hasWebSockets: false,\n hasCaching: false,\n hasQueue: false\n }\n };\n}\n\nfunction buildExplanation(result: ChangeRiskResult): string {\n const top = [...result.files].sort((a, b) => b.score - a.score)[0];\n if (!top) return `Risk level ${result.overall} (no files provided)`;\n return `Risk level ${result.overall} because ${top.file} ${top.reasons.join(', ')}`;\n}\n\nfunction buildRecommendation(risk: RiskLevel, hasAntiPattern: boolean): string {\n if (hasAntiPattern || risk === 'critical') {\n return 'Block until reviewed: address anti-patterns and rerun targeted tests.';\n }\n if (risk === 'high') {\n return 'Require senior review and run full test suite before merge.';\n }\n if (risk === 'medium') {\n return 'Proceed with caution; run impacted tests and sanity checks.';\n }\n return 'Low risk; proceed but keep an eye on recent changes.';\n}\n\nexport async function reasonAboutChanges(\n projectPath: string,\n files: string[],\n options: ReasonOptions = {}\n): Promise<Reasoning> {\n const graph = new ContextGraph(projectPath);\n const { matches, byFile } = await matchPatternsForFiles(graph, files);\n const changeRisk = await scoreChangeSet(graph, files, byFile);\n\n const incidents: IncidentNode[] = [];\n for (const file of files) {\n const fileIncidents = await graph.getIncidentsForFile(file);\n incidents.push(...fileIncidents);\n }\n\n const hasAntiPattern = matches.some((m) => m.isAntiPattern);\n const riskLevel: RiskLevel = hasAntiPattern ? 'critical' : changeRisk.overall;\n const shouldBlock = hasAntiPattern || riskLevel === 'critical' || riskLevel === 'high';\n\n const reasoning: Reasoning = {\n riskLevel,\n shouldBlock,\n explanation: buildExplanation(changeRisk),\n relevantIncidents: incidents,\n matchedPatterns: matches.map((m) => m.pattern),\n recommendation: buildRecommendation(riskLevel, hasAntiPattern),\n files: changeRisk.files\n };\n\n if (options.runAgents) {\n const codeContext = options.codeContext ?? buildDefaultCodeContext();\n const triager = new Triager();\n // Skills removed - decision ledger now handles risk analysis\n const agents = await triager.triage(codeContext);\n\n if (agents.length > 0) {\n const executor = new Executor();\n const scanContext: ScanContext = {\n workingDir: projectPath,\n ...options.scanContext\n };\n if (codeContext.framework) scanContext.framework = codeContext.framework;\n if (codeContext.language) scanContext.language = codeContext.language;\n\n reasoning.agentResults = await executor.executeAgents(agents, files, scanContext, {\n parallel: true,\n timeoutMs: options.scanContext?.config?.timeoutMs ?? 60000\n });\n } else {\n reasoning.agentResults = [];\n }\n }\n\n return reasoning;\n}\n\n// Convenience wrapper to keep future CLI/MCP integration simple\nexport async function reasonAboutChangesHumanReadable(\n projectPath: string,\n files: string[],\n options: ReasonOptions = {}\n): Promise<HumanReadableReasoning> {\n const reasoning = await reasonAboutChanges(projectPath, files, options);\n\n const topFile = [...reasoning.files].sort((a, b) => b.score - a.score)[0];\n const topReasons = topFile?.reasons?.slice(0, 3) ?? [];\n\n const summaryParts: string[] = [];\n summaryParts.push(`Risk ${reasoning.riskLevel.toUpperCase()} (${reasoning.shouldBlock ? 'block' : 'allow'})`);\n if (topFile) summaryParts.push(`Most sensitive file: ${topFile.file}`);\n if (topReasons.length) summaryParts.push(`Top reasons: ${topReasons.join('; ')}`);\n\n const patterns = reasoning.matchedPatterns;\n const incidents = reasoning.relevantIncidents;\n\n const firstPattern = patterns[0];\n const patternLine = firstPattern\n ? `Pattern match: ${firstPattern.data.description}`\n : 'No known risky patterns matched.';\n\n const incidentLine = incidents[0]\n ? `Relevant prior incident: ${incidents[0].data.description} (${incidents[0].data.severity})`\n : 'No prior incidents linked to these files.';\n\n const howBad = [\n `Overall risk is ${reasoning.riskLevel}.`,\n reasoning.shouldBlock ? 'This is likely to break things or violate policy if pushed without review.' : 'This is unlikely to cause major issues if you follow normal review/testing.',\n incidentLine,\n ].join(' ');\n\n const whatToDo = [\n reasoning.recommendation,\n patterns.length ? `Double-check the pattern(s): ${patterns.slice(0, 2).map((p) => p.data.description).join(' | ')}.` : '',\n ].filter(Boolean).join(' ');\n\n return {\n summary: summaryParts.join(' — '),\n whatIFound: [patternLine, `Incidents considered: ${incidents.length}. Patterns considered: ${patterns.length}.`].join(' '),\n howBad,\n whatToDo,\n original: reasoning,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAOA,SAAS,kBAAkB;AAC3B,SAAS,OAAO,WAAW,gBAAgB;AAC3C,SAAS,YAAY;AAoBrB,eAAsB,eAAe,SAMb;AACtB,QAAM,UAAU,QAAQ,WAAW,oBAAoB,QAAW,IAAI;AACtE,QAAM,UAAU,iBAAiB,OAAO;AACxC,QAAM,iBAAiB,KAAK,SAAS,kBAAkB;AAEvD,QAAM,MAAM,SAAS,EAAE,WAAW,KAAK,CAAC;AAGxC,MAAI,MAAqB,EAAE,aAAa,CAAC,EAAE;AAC3C,MAAI;AACF,QAAI,WAAW,cAAc,GAAG;AAC9B,YAAM,KAAK,MAAM,MAAM,SAAS,gBAAgB,OAAO,CAAC;A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B,QAAM,YAAY,UAAU;AAE5B,QAAM,eAAe,SAAS,CAAC;AAC/B,QAAM,cAAc,eAChB,kBAAkB,aAAa,KAAK,WAAW,KAC/C;AAEJ,QAAM,eAAe,UAAU,CAAC,IAC5B,4BAA4B,UAAU,CAAC,EAAE,KAAK,WAAW,KAAK,UAAU,CAAC,EAAE,KAAK,QAAQ,MACxF;AAEJ,QAAM,SAAS;AAAA,IACb,mBAAmB,UAAU,SAAS;AAAA,IACtC,UAAU,cAAc,+EAA+E;AAAA,IACvG;AAAA,EACF,EAAE,KAAK,GAAG;AAEV,QAAM,WAAW;AAAA,IACf,UAAU;AAAA,IACV,SAAS,SAAS,gCAAgC,SAAS,MAAM,GAAG,CAAC,EAAE,IAAI,CAAC,MAAM,EAAE,KAAK,WAAW,EAAE,KAAK,KAAK,CAAC,MAAM;AAAA,EACzH,EAAE,OAAO,OAAO,EAAE,KAAK,GAAG;AAE1B,SAAO;AAAA,IACL,SAAS,aAAa,KAAK,UAAK;AAAA,IAChC,YAAY,CAAC,aAAa,yBAAyB,UAAU,MAAM,0BAA0B,SAAS,MAAM,GAAG,EAAE,KAAK,GAAG;AAAA,IACzH;AAAA,IACA;AAAA,IACA,UAAU;AAAA,EACZ;AACF;","names":["existsSync","join","existsSync","join","path","path","data","path","existsSync","existsSync","resolve","readFile","writeFile","mkdir","join","join","readFile","mkdir","writeFile","resolve"]}
|