@triedotdev/mcp 1.0.113 → 1.0.115

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/dist/auto-fix-apply-PCAHWLXF.js +10 -0
  2. package/dist/autonomy-config-JXB7WCZ2.js +30 -0
  3. package/dist/chunk-2GIAROBF.js +173 -0
  4. package/dist/chunk-2GIAROBF.js.map +1 -0
  5. package/dist/{chunk-33WL3D7A.js → chunk-2SIFK7OW.js} +7 -419
  6. package/dist/chunk-2SIFK7OW.js.map +1 -0
  7. package/dist/chunk-43X6JBEM.js +36 -0
  8. package/dist/chunk-43X6JBEM.js.map +1 -0
  9. package/dist/chunk-55DOQNHJ.js +772 -0
  10. package/dist/chunk-55DOQNHJ.js.map +1 -0
  11. package/dist/chunk-6LXSA2OZ.js +425 -0
  12. package/dist/chunk-6LXSA2OZ.js.map +1 -0
  13. package/dist/{chunk-SDS3UVFY.js → chunk-AOFYU6T3.js} +113 -559
  14. package/dist/chunk-AOFYU6T3.js.map +1 -0
  15. package/dist/{chunk-6QR6QZIX.js → chunk-D3EXBJE2.js} +25 -658
  16. package/dist/chunk-D3EXBJE2.js.map +1 -0
  17. package/dist/chunk-DJ2YAGHK.js +50 -0
  18. package/dist/chunk-DJ2YAGHK.js.map +1 -0
  19. package/dist/chunk-DZREHOGW.js +706 -0
  20. package/dist/chunk-DZREHOGW.js.map +1 -0
  21. package/dist/chunk-I2GFI3AM.js +340 -0
  22. package/dist/chunk-I2GFI3AM.js.map +1 -0
  23. package/dist/chunk-KRH642MT.js +947 -0
  24. package/dist/chunk-KRH642MT.js.map +1 -0
  25. package/dist/{chunk-QYOACM2C.js → chunk-MVNJPJBK.js} +22 -252
  26. package/dist/chunk-MVNJPJBK.js.map +1 -0
  27. package/dist/chunk-NS2MSZMB.js +394 -0
  28. package/dist/chunk-NS2MSZMB.js.map +1 -0
  29. package/dist/chunk-SWSK7ANT.js +340 -0
  30. package/dist/chunk-SWSK7ANT.js.map +1 -0
  31. package/dist/chunk-VRLMTOB6.js +566 -0
  32. package/dist/chunk-VRLMTOB6.js.map +1 -0
  33. package/dist/chunk-YR4BMGYO.js +130 -0
  34. package/dist/chunk-YR4BMGYO.js.map +1 -0
  35. package/dist/chunk-ZV2K6M7T.js +74 -0
  36. package/dist/chunk-ZV2K6M7T.js.map +1 -0
  37. package/dist/{chunk-2764KZZQ.js → chunk-ZYKEILVK.js} +451 -1069
  38. package/dist/chunk-ZYKEILVK.js.map +1 -0
  39. package/dist/cli/main.js +107 -375
  40. package/dist/cli/main.js.map +1 -1
  41. package/dist/cli/yolo-daemon.js +18 -8
  42. package/dist/cli/yolo-daemon.js.map +1 -1
  43. package/dist/client-7XZHCMD3.js +28 -0
  44. package/dist/client-7XZHCMD3.js.map +1 -0
  45. package/dist/{goal-manager-AP4LTE6U.js → goal-manager-LMS6ZJB7.js} +7 -3
  46. package/dist/goal-manager-LMS6ZJB7.js.map +1 -0
  47. package/dist/goal-validator-T5HEYBC5.js +186 -0
  48. package/dist/goal-validator-T5HEYBC5.js.map +1 -0
  49. package/dist/graph-U5JWSAB5.js +10 -0
  50. package/dist/graph-U5JWSAB5.js.map +1 -0
  51. package/dist/guardian-agent-EXP7APLC.js +25 -0
  52. package/dist/guardian-agent-EXP7APLC.js.map +1 -0
  53. package/dist/hypothesis-KGC3P54C.js +19 -0
  54. package/dist/hypothesis-KGC3P54C.js.map +1 -0
  55. package/dist/incident-index-PNIVT47T.js +11 -0
  56. package/dist/incident-index-PNIVT47T.js.map +1 -0
  57. package/dist/index.js +369 -43
  58. package/dist/index.js.map +1 -1
  59. package/dist/ledger-SR6OEBLO.js +15 -0
  60. package/dist/ledger-SR6OEBLO.js.map +1 -0
  61. package/dist/output-manager-BOTMXSND.js +13 -0
  62. package/dist/output-manager-BOTMXSND.js.map +1 -0
  63. package/dist/pattern-discovery-F7LU5K6E.js +8 -0
  64. package/dist/pattern-discovery-F7LU5K6E.js.map +1 -0
  65. package/package.json +1 -1
  66. package/dist/chunk-2764KZZQ.js.map +0 -1
  67. package/dist/chunk-33WL3D7A.js.map +0 -1
  68. package/dist/chunk-6JPPYG7F.js +0 -1813
  69. package/dist/chunk-6JPPYG7F.js.map +0 -1
  70. package/dist/chunk-6QR6QZIX.js.map +0 -1
  71. package/dist/chunk-QYOACM2C.js.map +0 -1
  72. package/dist/chunk-SDS3UVFY.js.map +0 -1
  73. package/dist/guardian-agent-XEYNG7RH.js +0 -18
  74. /package/dist/{goal-manager-AP4LTE6U.js.map → auto-fix-apply-PCAHWLXF.js.map} +0 -0
  75. /package/dist/{guardian-agent-XEYNG7RH.js.map → autonomy-config-JXB7WCZ2.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/guardian/guardian-agent.ts","../src/guardian/risk-predictor.ts","../src/guardian/hypothesis.ts","../src/integrations/slack.ts","../src/guardian/escalation.ts","../src/guardian/meta-learning.ts"],"sourcesContent":["/**\n * Guardian Agent - A proactive, intelligent agent that watches over your codebase\n * \n * Unlike passive notification systems, the Guardian:\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 * Phase 1+ Guardian Agency: Full persistence support\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 GuardianInsight } from './insight-store.js';\nimport { getGuardianState } from './guardian-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';\n\n// Re-export GuardianInsight type from insight-store for backward compatibility\nexport type { GuardianInsight } 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 GuardianAgent {\n private projectPath: string;\n private projectName: string;\n private lastIssueHashes: Set<string> = new Set();\n private initialized: boolean = false;\n \n // Persistent stores (Phase 1 Guardian Agency)\n private insightStore;\n private guardianState;\n \n // Agency modules (Phases 2-4)\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 (Phase 1)\n this.insightStore = getInsightStore(projectPath);\n this.guardianState = getGuardianState(projectPath);\n \n // Initialize agency modules (Phases 2-4)\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 Guardian - loads persistent state and historical data\n */\n async initialize(): Promise<void> {\n if (this.initialized) return;\n \n try {\n // Load persistent stores (Phase 1 Guardian Agency)\n await this.insightStore.load();\n await this.guardianState.load();\n \n // Update last active timestamp\n await this.guardianState.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: GuardianInsight): Promise<boolean> {\n return this.insightStore.addInsight(insight);\n }\n \n /**\n * Restart the Guardian (reload state from disk)\n */\n async restart(): Promise<void> {\n this.initialized = false;\n await this.insightStore.reload();\n await this.guardianState.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.guardianState.load();\n return {\n goals: this.guardianState.getAllGoals(),\n riskBudget: this.guardianState.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<GuardianInsight[]> {\n const newInsights: GuardianInsight[] = [];\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 Guardian\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 // 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.slice(0, 40)}...\" 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<GuardianInsight['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. GUARDIAN AGENCY: Phases 2-4 Integration\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.guardianState.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\n // NEW: Gotcha Predictor Integration\n const gotchas = await this.gotchaPredictor.predictGotchas(context.filesChanged);\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 }\n } catch {\n // Risk/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.guardianState.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 (Phase 1 Guardian Agency)\n await this.guardianState.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.guardianState.setScanFrequency(result.frequencyMs);\n } catch {\n // Scan frequency adaptation is optional\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<GuardianInsight[]> {\n const insights: GuardianInsight[] = [];\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 guardian. 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 * Now uses persistent storage (Phase 1 Guardian Agency)\n */\n getActiveInsights(): GuardianInsight[] {\n return this.insightStore.getActiveInsights();\n }\n \n /**\n * Dismiss an insight\n * Now persists to disk (Phase 1 Guardian Agency)\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.guardianState.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.guardianState.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.guardianState.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.guardianState.getMetrics();\n }\n \n /**\n * Check if in quiet hours\n */\n isQuietHours(): boolean {\n return this.guardianState.isQuietHours();\n }\n \n /**\n * Check if in crunch mode\n */\n isInCrunchMode(): boolean {\n return this.guardianState.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 guardian state (for advanced operations)\n */\n getGuardianState() {\n return this.guardianState;\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.guardianState.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.guardianState.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.guardianState.getMetrics();\n const budget = this.guardianState.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.guardianState.getScanFrequencyMs(),\n effectiveness,\n isQuietHours: this.guardianState.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 * Now uses persistent storage (Phase 1 Guardian Agency)\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 * Now persists to disk (Phase 1 Guardian Agency)\n */\n private async markInsightCreated(insightKey: string): Promise<void> {\n await this.insightStore.markInsightCreated(insightKey);\n }\n \n private createInsight(params: Omit<GuardianInsight, 'id' | 'timestamp' | 'dismissed' | 'relatedIssues'> & { relatedIssues?: string[] }): GuardianInsight {\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 guardianInstances: Map<string, GuardianAgent> = new Map();\n\nexport function getGuardian(projectPath: string): GuardianAgent {\n let guardian = guardianInstances.get(projectPath);\n if (!guardian) {\n guardian = new GuardianAgent(projectPath);\n guardianInstances.set(projectPath, guardian);\n }\n return guardian;\n}\n","/**\n * Risk Predictor - Predictive risk scoring with trend analysis\n * \n * Phase 3 of Guardian Agency Plan: Predictive Intelligence\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 { GuardianInsight } from './insight-store.js';\nimport { getInsightStore } from './insight-store.js';\n// Note: getGuardianState is not used here but could be used for timing context\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<GuardianInsight | 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: GuardianInsight = {\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 * Hypothesis System - Self-improving hypothesis generation and validation\n * \n * Phase 3 of Guardian Agency Plan: Predictive Intelligence\n * \n * Features:\n * - Generate hypotheses from patterns\n * - Track evidence for/against hypotheses\n * - Auto-validate/invalidate based on evidence\n * - Adjust confidence over time\n * - Learn from hypothesis outcomes\n */\n\nimport type { Hypothesis } from './guardian-state.js';\nimport { getGuardianState } from './guardian-state.js';\nimport { getInsightStore, type GuardianInsight } from './insight-store.js';\nimport { searchIssues } from '../memory/issue-store.js';\nimport { dirname } from 'path';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Hypothesis template for auto-generation\n */\nexport interface HypothesisTemplate {\n category: 'timing' | 'pattern' | 'team' | 'code' | 'general';\n statement: string;\n testCriteria: string;\n minConfidence: number;\n dataRequired: string[];\n}\n\n/**\n * Evidence for a hypothesis\n */\nexport interface HypothesisEvidence {\n type: 'supporting' | 'contradicting';\n description: string;\n weight: number; // 0-1\n timestamp: string;\n}\n\n/**\n * Hypothesis analysis result\n */\nexport interface HypothesisAnalysis {\n hypothesis: Hypothesis;\n recentEvidence: HypothesisEvidence[];\n confidenceChange: number;\n statusChange?: 'validated' | 'invalidated';\n actionRequired: boolean;\n}\n\n// ============================================================================\n// Hypothesis Templates\n// ============================================================================\n\nconst HYPOTHESIS_TEMPLATES: HypothesisTemplate[] = [\n {\n category: 'timing',\n statement: 'Issues spike after weekend deployments',\n testCriteria: 'Compare Monday issue counts to other days',\n minConfidence: 0.3,\n dataRequired: ['issue_timestamps', 'deployment_data'],\n },\n {\n category: 'timing',\n statement: 'Code quality declines on Fridays',\n testCriteria: 'Compare Friday issue introduction rate to weekly average',\n minConfidence: 0.3,\n dataRequired: ['issue_timestamps'],\n },\n {\n category: 'pattern',\n statement: 'Auth-related code has the highest incident rate',\n testCriteria: 'Compare auth/ issue count to other directories',\n minConfidence: 0.4,\n dataRequired: ['issue_files'],\n },\n {\n category: 'pattern',\n statement: 'Security issues cluster in specific directories',\n testCriteria: 'Check if security issues are concentrated (>50% in <3 dirs)',\n minConfidence: 0.4,\n dataRequired: ['issue_files', 'issue_agents'],\n },\n {\n category: 'code',\n statement: 'Files with multiple authors have more issues',\n testCriteria: 'Correlate file author count with issue count',\n minConfidence: 0.4,\n dataRequired: ['issue_files', 'git_blame'],\n },\n {\n category: 'code',\n statement: 'Recently modified files are more likely to have issues',\n testCriteria: 'Compare issue rate for recent vs old files',\n minConfidence: 0.3,\n dataRequired: ['issue_timestamps', 'file_modification_times'],\n },\n {\n category: 'pattern',\n statement: 'Critical issues often come in clusters',\n testCriteria: 'Check temporal clustering of critical issues',\n minConfidence: 0.3,\n dataRequired: ['issue_timestamps', 'issue_severities'],\n },\n];\n\n// ============================================================================\n// HypothesisEngine Class\n// ============================================================================\n\n/**\n * Engine for generating and validating hypotheses\n */\nexport class HypothesisEngine {\n private projectPath: string;\n private guardianState;\n private insightStore;\n \n constructor(projectPath: string) {\n this.projectPath = projectPath;\n this.guardianState = getGuardianState(projectPath);\n this.insightStore = getInsightStore(projectPath);\n }\n \n /**\n * Create a new hypothesis\n */\n async createHypothesis(statement: string, options?: {\n category?: Hypothesis['category'];\n testCriteria?: string;\n initialConfidence?: number;\n }): Promise<Hypothesis> {\n const hypothesis: Hypothesis = {\n id: `hyp-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,\n statement,\n confidence: options?.initialConfidence ?? 0.5,\n status: 'proposed',\n evidence: [],\n createdAt: new Date().toISOString(),\n updatedAt: new Date().toISOString(),\n testCriteria: options?.testCriteria,\n category: options?.category ?? 'general',\n };\n \n await this.guardianState.addHypothesis(hypothesis);\n \n return hypothesis;\n }\n \n /**\n * Auto-generate hypotheses based on detected patterns\n */\n async autoGenerateHypotheses(): Promise<Hypothesis[]> {\n const generated: Hypothesis[] = [];\n \n try {\n // Get existing hypotheses to avoid duplicates\n await this.guardianState.load();\n const existing = this.guardianState.getAllHypotheses();\n const existingStatements = new Set(existing.map(h => h.statement.toLowerCase()));\n \n // Get data for pattern detection\n const issues = await searchIssues('', {\n workDir: this.projectPath,\n limit: 500,\n includeResolved: true,\n });\n \n if (issues.length < 10) {\n return generated; // Not enough data\n }\n \n // Check each template for applicability\n for (const template of HYPOTHESIS_TEMPLATES) {\n // Skip if already have similar hypothesis\n if (existingStatements.has(template.statement.toLowerCase())) {\n continue;\n }\n \n // Check if we have enough evidence to propose this hypothesis\n const evidence = await this.gatherInitialEvidence(template, issues);\n \n if (evidence.length > 0 && evidence[0]!.weight >= template.minConfidence) {\n const hypothesis = await this.createHypothesis(template.statement, {\n category: template.category,\n testCriteria: template.testCriteria,\n initialConfidence: evidence[0]!.weight,\n });\n \n // Add initial evidence\n for (const e of evidence) {\n await this.guardianState.addEvidence(hypothesis.id, e);\n }\n \n generated.push(hypothesis);\n \n // Limit to 2 new hypotheses per run\n if (generated.length >= 2) break;\n }\n }\n \n } catch (error) {\n console.error('Failed to auto-generate hypotheses:', error);\n }\n \n return generated;\n }\n \n /**\n * Gather initial evidence for a hypothesis template\n */\n private async gatherInitialEvidence(\n template: HypothesisTemplate,\n issues: Array<{ issue: any; score: number }>\n ): Promise<HypothesisEvidence[]> {\n const evidence: HypothesisEvidence[] = [];\n \n switch (template.category) {\n case 'timing':\n evidence.push(...this.analyzeTimingPatterns(template, issues));\n break;\n case 'pattern':\n evidence.push(...this.analyzeLocationPatterns(template, issues));\n break;\n case 'code':\n evidence.push(...this.analyzeCodePatterns(template, issues));\n break;\n }\n \n return evidence;\n }\n \n /**\n * Analyze timing patterns in issues\n */\n private analyzeTimingPatterns(\n template: HypothesisTemplate,\n issues: Array<{ issue: any; score: number }>\n ): HypothesisEvidence[] {\n const evidence: HypothesisEvidence[] = [];\n \n // Analyze day-of-week patterns\n const dayOfWeekCounts: Record<number, number> = {};\n for (const { issue } of issues) {\n const date = new Date(issue.timestamp);\n const day = date.getDay();\n dayOfWeekCounts[day] = (dayOfWeekCounts[day] || 0) + 1;\n }\n \n // Check for Friday pattern\n if (template.statement.includes('Friday')) {\n const fridayCount = dayOfWeekCounts[5] || 0;\n const avgOtherDays = (Object.values(dayOfWeekCounts).reduce((a, b) => a + b, 0) - fridayCount) / 4;\n \n if (fridayCount > avgOtherDays * 1.5) {\n evidence.push({\n type: 'supporting',\n description: `Friday has ${((fridayCount / avgOtherDays - 1) * 100).toFixed(0)}% more issues than average`,\n weight: Math.min(0.8, 0.3 + (fridayCount / avgOtherDays - 1) * 0.2),\n timestamp: new Date().toISOString(),\n });\n } else {\n evidence.push({\n type: 'contradicting',\n description: 'Friday issue count is not significantly higher',\n weight: 0.3,\n timestamp: new Date().toISOString(),\n });\n }\n }\n \n // Check for Monday/weekend pattern\n if (template.statement.includes('weekend') || template.statement.includes('Monday')) {\n const mondayCount = dayOfWeekCounts[1] || 0;\n const avgOtherDays = (Object.values(dayOfWeekCounts).reduce((a, b) => a + b, 0) - mondayCount) / 4;\n \n if (mondayCount > avgOtherDays * 1.5) {\n evidence.push({\n type: 'supporting',\n description: `Monday has ${((mondayCount / avgOtherDays - 1) * 100).toFixed(0)}% more issues than average`,\n weight: Math.min(0.8, 0.3 + (mondayCount / avgOtherDays - 1) * 0.2),\n timestamp: new Date().toISOString(),\n });\n }\n }\n \n return evidence;\n }\n \n /**\n * Analyze location patterns in issues\n */\n private analyzeLocationPatterns(\n template: HypothesisTemplate,\n issues: Array<{ issue: any; score: number }>\n ): HypothesisEvidence[] {\n const evidence: HypothesisEvidence[] = [];\n \n // Analyze directory distribution\n const dirCounts: Record<string, number> = {};\n for (const { issue } of issues) {\n const dir = dirname(issue.file);\n dirCounts[dir] = (dirCounts[dir] || 0) + 1;\n }\n \n const sortedDirs = Object.entries(dirCounts)\n .sort(([, a], [, b]) => b - a);\n \n // Check for auth pattern\n if (template.statement.includes('Auth')) {\n const authDirs = sortedDirs.filter(([dir]) => \n dir.toLowerCase().includes('auth') || \n dir.toLowerCase().includes('login') ||\n dir.toLowerCase().includes('session')\n );\n \n const authCount = authDirs.reduce((sum, [, count]) => sum + count, 0);\n const percentage = (authCount / issues.length) * 100;\n \n if (percentage >= 20) {\n evidence.push({\n type: 'supporting',\n description: `Auth-related code has ${percentage.toFixed(0)}% of issues`,\n weight: Math.min(0.85, 0.4 + percentage / 100),\n timestamp: new Date().toISOString(),\n });\n }\n }\n \n // Check for clustering pattern\n if (template.statement.includes('cluster')) {\n const topThreeDirs = sortedDirs.slice(0, 3);\n const topThreeCount = topThreeDirs.reduce((sum, [, count]) => sum + count, 0);\n const percentage = (topThreeCount / issues.length) * 100;\n \n if (percentage >= 50) {\n evidence.push({\n type: 'supporting',\n description: `Top 3 directories have ${percentage.toFixed(0)}% of issues`,\n weight: Math.min(0.8, 0.3 + percentage / 100),\n timestamp: new Date().toISOString(),\n });\n }\n }\n \n return evidence;\n }\n \n /**\n * Analyze code patterns\n */\n private analyzeCodePatterns(\n template: HypothesisTemplate,\n issues: Array<{ issue: any; score: number }>\n ): HypothesisEvidence[] {\n const evidence: HypothesisEvidence[] = [];\n \n // Analyze temporal clustering (critical issues in bursts)\n if (template.statement.includes('cluster')) {\n const criticalIssues = issues.filter(r => r.issue.severity === 'critical');\n \n if (criticalIssues.length >= 3) {\n // Check if critical issues are clustered in time\n const timestamps = criticalIssues\n .map(r => new Date(r.issue.timestamp).getTime())\n .sort((a, b) => a - b);\n \n let clusteredCount = 0;\n for (let i = 1; i < timestamps.length; i++) {\n // If within 24 hours of previous\n if (timestamps[i]! - timestamps[i - 1]! < 24 * 60 * 60 * 1000) {\n clusteredCount++;\n }\n }\n \n const clusterRatio = clusteredCount / (timestamps.length - 1);\n \n if (clusterRatio >= 0.5) {\n evidence.push({\n type: 'supporting',\n description: `${(clusterRatio * 100).toFixed(0)}% of critical issues occur within 24h of another`,\n weight: Math.min(0.75, 0.3 + clusterRatio * 0.4),\n timestamp: new Date().toISOString(),\n });\n }\n }\n }\n \n return evidence;\n }\n \n /**\n * Update confidence scores based on new data\n */\n async updateConfidenceFromOutcomes(): Promise<HypothesisAnalysis[]> {\n const analyses: HypothesisAnalysis[] = [];\n \n try {\n await this.guardianState.load();\n const activeHypotheses = this.guardianState.getActiveHypotheses();\n \n for (const hypothesis of activeHypotheses) {\n const analysis = await this.analyzeHypothesis(hypothesis);\n analyses.push(analysis);\n \n // Create insight if hypothesis was validated or invalidated\n if (analysis.statusChange && this.insightStore.canCreateInsight('hypothesis-update')) {\n const insight = this.createHypothesisInsight(analysis);\n await this.insightStore.addInsight(insight);\n await this.insightStore.markInsightCreated('hypothesis-update');\n }\n }\n \n // Update hypothesis accuracy metric\n await this.guardianState.updateHypothesisAccuracy();\n \n } catch (error) {\n console.error('Failed to update hypothesis confidence:', error);\n }\n \n return analyses;\n }\n \n /**\n * Analyze a single hypothesis\n */\n private async analyzeHypothesis(hypothesis: Hypothesis): Promise<HypothesisAnalysis> {\n // Get recent issues for new evidence\n const issues = await searchIssues('', {\n workDir: this.projectPath,\n limit: 100,\n includeResolved: false,\n });\n \n // Find the matching template\n const template = HYPOTHESIS_TEMPLATES.find(t => \n t.statement.toLowerCase() === hypothesis.statement.toLowerCase()\n );\n \n const recentEvidence: HypothesisEvidence[] = [];\n \n if (template) {\n recentEvidence.push(...await this.gatherInitialEvidence(template, issues));\n } else {\n // For user-created hypotheses, use semantic evidence gathering\n recentEvidence.push(...this.gatherSemanticEvidence(hypothesis, issues));\n }\n \n // Calculate confidence change\n const oldConfidence = hypothesis.confidence;\n let newConfidence = oldConfidence;\n \n for (const evidence of recentEvidence) {\n if (evidence.type === 'supporting') {\n newConfidence = Math.min(1, newConfidence + evidence.weight * 0.1);\n } else {\n newConfidence = Math.max(0, newConfidence - evidence.weight * 0.1);\n }\n }\n \n // Determine status change\n let statusChange: 'validated' | 'invalidated' | undefined;\n \n if (newConfidence >= 0.8 && hypothesis.evidence.length >= 3) {\n statusChange = 'validated';\n await this.guardianState.updateHypothesis(hypothesis.id, {\n status: 'validated',\n confidence: newConfidence,\n validatedAt: new Date().toISOString(),\n });\n } else if (newConfidence <= 0.2 && hypothesis.evidence.length >= 3) {\n statusChange = 'invalidated';\n await this.guardianState.updateHypothesis(hypothesis.id, {\n status: 'invalidated',\n confidence: newConfidence,\n });\n } else {\n // Just update confidence\n await this.guardianState.updateHypothesis(hypothesis.id, {\n confidence: newConfidence,\n });\n }\n \n // Add new evidence\n for (const evidence of recentEvidence) {\n await this.guardianState.addEvidence(hypothesis.id, evidence);\n }\n \n const analysis: HypothesisAnalysis = {\n hypothesis: { ...hypothesis, confidence: newConfidence },\n recentEvidence,\n confidenceChange: newConfidence - oldConfidence,\n actionRequired: statusChange !== undefined,\n };\n \n if (statusChange) {\n analysis.statusChange = statusChange;\n }\n \n return analysis;\n }\n \n /**\n * Gather evidence for user-created hypotheses using semantic matching\n * \n * This enables agentic tracking for natural language hypotheses like:\n * - \"Mondays have more bugs than Fridays\"\n * - \"Code reviews reduce bug rate\"\n * - \"Security issues cluster in auth code\"\n */\n private gatherSemanticEvidence(\n hypothesis: Hypothesis,\n issues: Array<{ issue: any; score: number }>\n ): HypothesisEvidence[] {\n const evidence: HypothesisEvidence[] = [];\n const stmt = hypothesis.statement.toLowerCase();\n \n // Time-based hypotheses (days of week patterns)\n if (stmt.includes('monday') || stmt.includes('friday') || stmt.includes('weekend') ||\n stmt.includes('morning') || stmt.includes('afternoon')) {\n const dayNames = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];\n const dayOfWeekCounts: Record<number, number> = { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0 };\n \n for (const { issue } of issues) {\n const date = new Date(issue.timestamp);\n const day = date.getDay();\n dayOfWeekCounts[day] = (dayOfWeekCounts[day] || 0) + 1;\n }\n \n const totalIssues = Object.values(dayOfWeekCounts).reduce((a, b) => a + b, 0);\n const avgPerDay = totalIssues / 7;\n \n // Check each day mentioned\n for (let dayIdx = 0; dayIdx < 7; dayIdx++) {\n const dayName = dayNames[dayIdx]!;\n if (stmt.includes(dayName)) {\n const dayCount = dayOfWeekCounts[dayIdx] || 0;\n \n if (stmt.includes('more') || stmt.includes('higher') || stmt.includes('spike')) {\n // Testing if this day has MORE issues\n if (dayCount > avgPerDay * 1.3) {\n evidence.push({\n type: 'supporting',\n description: `${dayName.charAt(0).toUpperCase() + dayName.slice(1)} has ${dayCount} issues (${((dayCount/avgPerDay - 1) * 100).toFixed(0)}% above average)`,\n weight: Math.min(0.7, 0.3 + (dayCount / avgPerDay - 1) * 0.3),\n timestamp: new Date().toISOString(),\n });\n } else {\n evidence.push({\n type: 'contradicting',\n description: `${dayName.charAt(0).toUpperCase() + dayName.slice(1)} has average or below average issue count`,\n weight: 0.3,\n timestamp: new Date().toISOString(),\n });\n }\n } else if (stmt.includes('fewer') || stmt.includes('less') || stmt.includes('reduce')) {\n // Testing if this day has FEWER issues\n if (dayCount < avgPerDay * 0.7) {\n evidence.push({\n type: 'supporting',\n description: `${dayName.charAt(0).toUpperCase() + dayName.slice(1)} has ${dayCount} issues (${((1 - dayCount/avgPerDay) * 100).toFixed(0)}% below average)`,\n weight: Math.min(0.7, 0.3 + (1 - dayCount / avgPerDay) * 0.3),\n timestamp: new Date().toISOString(),\n });\n }\n }\n }\n }\n }\n \n // Code review hypotheses\n if (stmt.includes('review') || stmt.includes('pr') || stmt.includes('pull request')) {\n // Look for patterns in reviewed vs unreviewed code (approximated by commit patterns)\n const recentIssues = issues.slice(0, 30); // Most recent\n const olderIssues = issues.slice(30); // Older\n \n if (recentIssues.length >= 10 && olderIssues.length >= 10) {\n const recentRate = recentIssues.length;\n const olderRate = olderIssues.length;\n \n if (stmt.includes('reduce') || stmt.includes('fewer') || stmt.includes('less')) {\n if (recentRate < olderRate) {\n evidence.push({\n type: 'supporting',\n description: `Recent period has ${((1 - recentRate/olderRate) * 100).toFixed(0)}% fewer issues`,\n weight: Math.min(0.6, 0.3 + (1 - recentRate/olderRate) * 0.3),\n timestamp: new Date().toISOString(),\n });\n } else {\n evidence.push({\n type: 'contradicting',\n description: `Issue rate has not decreased recently`,\n weight: 0.2,\n timestamp: new Date().toISOString(),\n });\n }\n }\n }\n }\n \n // Directory/location clustering hypotheses\n if (stmt.includes('cluster') || stmt.includes('concentrate') || stmt.includes('auth') ||\n stmt.includes('specific') || stmt.includes('certain files')) {\n const dirCounts: Record<string, number> = {};\n for (const { issue } of issues) {\n const dir = dirname(issue.file);\n dirCounts[dir] = (dirCounts[dir] || 0) + 1;\n }\n \n const sortedDirs = Object.entries(dirCounts).sort(([, a], [, b]) => b - a);\n const topThreeCount = sortedDirs.slice(0, 3).reduce((sum, [, count]) => sum + count, 0);\n const totalCount = issues.length;\n const concentration = topThreeCount / totalCount;\n \n if (concentration >= 0.5) {\n evidence.push({\n type: 'supporting',\n description: `Top 3 directories have ${(concentration * 100).toFixed(0)}% of issues (concentrated)`,\n weight: Math.min(0.7, 0.3 + concentration * 0.4),\n timestamp: new Date().toISOString(),\n });\n } else {\n evidence.push({\n type: 'contradicting',\n description: `Issues are distributed across many directories`,\n weight: 0.3,\n timestamp: new Date().toISOString(),\n });\n }\n }\n \n // Severity trend hypotheses\n if (stmt.includes('critical') || stmt.includes('security') || stmt.includes('severity')) {\n const criticalCount = issues.filter(r => r.issue.severity === 'critical').length;\n const seriousCount = issues.filter(r => r.issue.severity === 'serious').length;\n const highSeverityRatio = (criticalCount + seriousCount) / issues.length;\n \n if (stmt.includes('increase') || stmt.includes('more') || stmt.includes('rise')) {\n if (highSeverityRatio > 0.3) {\n evidence.push({\n type: 'supporting',\n description: `${(highSeverityRatio * 100).toFixed(0)}% of issues are high severity`,\n weight: Math.min(0.7, 0.3 + highSeverityRatio),\n timestamp: new Date().toISOString(),\n });\n }\n } else if (stmt.includes('decrease') || stmt.includes('fewer') || stmt.includes('reduce')) {\n if (highSeverityRatio < 0.2) {\n evidence.push({\n type: 'supporting',\n description: `Only ${(highSeverityRatio * 100).toFixed(0)}% of issues are high severity`,\n weight: 0.5,\n timestamp: new Date().toISOString(),\n });\n }\n }\n }\n \n // Agent/skill specific hypotheses\n const agents = ['security', 'performance', 'accessibility', 'test', 'typecheck', 'bug-finding'];\n for (const agent of agents) {\n if (stmt.includes(agent) || stmt.includes(agent.replace('-', ' '))) {\n const agentIssues = issues.filter(r => r.issue.agent === agent);\n const agentRatio = agentIssues.length / issues.length;\n \n if (stmt.includes('most') || stmt.includes('majority') || stmt.includes('main')) {\n if (agentRatio > 0.4) {\n evidence.push({\n type: 'supporting',\n description: `${agent} accounts for ${(agentRatio * 100).toFixed(0)}% of issues`,\n weight: Math.min(0.7, 0.3 + agentRatio),\n timestamp: new Date().toISOString(),\n });\n } else {\n evidence.push({\n type: 'contradicting',\n description: `${agent} only accounts for ${(agentRatio * 100).toFixed(0)}% of issues`,\n weight: 0.3,\n timestamp: new Date().toISOString(),\n });\n }\n }\n }\n }\n \n return evidence;\n }\n \n /**\n * Create an insight for hypothesis status change\n */\n private createHypothesisInsight(analysis: HypothesisAnalysis): GuardianInsight {\n const isValidated = analysis.statusChange === 'validated';\n \n return {\n id: `insight-hyp-${analysis.hypothesis.id}`,\n type: isValidated ? 'celebration' : 'observation',\n message: isValidated\n ? `Hypothesis confirmed: \"${analysis.hypothesis.statement}\"`\n : `Hypothesis disproven: \"${analysis.hypothesis.statement}\"`,\n context: `Confidence: ${(analysis.hypothesis.confidence * 100).toFixed(0)}%. ${analysis.recentEvidence.length} evidence points analyzed.`,\n relatedIssues: [],\n priority: 5,\n timestamp: Date.now(),\n dismissed: false,\n category: 'pattern',\n details: {\n examples: analysis.recentEvidence.map(e => `${e.type}: ${e.description}`),\n },\n };\n }\n \n /**\n * Get hypothesis by ID\n */\n async getHypothesis(hypothesisId: string): Promise<Hypothesis | undefined> {\n await this.guardianState.load();\n return this.guardianState.getHypothesis(hypothesisId);\n }\n \n /**\n * Get all hypotheses\n */\n async getAllHypotheses(): Promise<Hypothesis[]> {\n await this.guardianState.load();\n return this.guardianState.getAllHypotheses();\n }\n \n /**\n * Get validated hypotheses\n */\n async getValidatedHypotheses(): Promise<Hypothesis[]> {\n await this.guardianState.load();\n return this.guardianState.getValidatedHypotheses();\n }\n \n /**\n * Get hypothesis accuracy stats\n */\n getAccuracy(): number {\n const metrics = this.guardianState.getMetrics();\n return metrics.hypothesisAccuracy;\n }\n}\n\n// ============================================================================\n// Singleton Management\n// ============================================================================\n\nconst hypothesisEngines: Map<string, HypothesisEngine> = new Map();\n\n/**\n * Get the HypothesisEngine for a project (singleton per project)\n */\nexport function getHypothesisEngine(projectPath: string): HypothesisEngine {\n let engine = hypothesisEngines.get(projectPath);\n if (!engine) {\n engine = new HypothesisEngine(projectPath);\n hypothesisEngines.set(projectPath, engine);\n }\n return engine;\n}\n\n/**\n * Clear all HypothesisEngine instances (for testing)\n */\nexport function clearHypothesisEngines(): void {\n hypothesisEngines.clear();\n}\n","import type { Issue } from '../types/index.js';\nimport type { IssueGroup, PriorityReport } from '../utils/issue-analyzer.js';\nimport type { TeamNotification } from './team-collaboration.js';\n\ninterface SlackConfig {\n webhookUrl: string;\n channel?: string | undefined;\n username?: string | undefined;\n iconEmoji?: string | undefined;\n}\n\ninterface SlackMessage {\n text?: string;\n blocks?: SlackBlock[];\n attachments?: SlackAttachment[];\n channel?: string;\n username?: string;\n icon_emoji?: string;\n}\n\ninterface SlackBlock {\n type: string;\n text?: {\n type: string;\n text: string;\n };\n fields?: Array<{\n type: string;\n text: string;\n }>;\n accessory?: any;\n}\n\ninterface SlackAttachment {\n color: string;\n title?: string | undefined;\n text?: string | undefined;\n fields?: Array<{\n title: string;\n value: string;\n short?: boolean;\n }> | undefined;\n footer?: string | undefined;\n ts?: number | undefined;\n}\n\n/**\n * Slack integration for Trie team notifications\n */\nexport class SlackIntegration {\n constructor(private config: SlackConfig) {}\n\n /**\n * Send scan completion notification\n */\n async sendScanNotification(\n _issues: Issue[],\n priorityReport: PriorityReport,\n repositoryName: string,\n branch: string = 'main'\n ): Promise<void> {\n const { urgent, high, medium, low } = priorityReport;\n const statusEmoji = urgent.length > 0 ? '[URGENT]' : high.length > 0 ? '[HIGH]' : '[OK]';\n\n const message: SlackMessage = {\n blocks: [\n {\n type: 'section',\n text: {\n type: 'mrkdwn',\n text: `${statusEmoji} *Trie Security Scan Complete*\\n*Repository:* ${repositoryName} (${branch})`\n }\n },\n {\n type: 'section',\n fields: [\n {\n type: 'mrkdwn',\n text: `*Urgent:* ${urgent.length}`\n },\n {\n type: 'mrkdwn',\n text: `*High:* ${high.length}`\n },\n {\n type: 'mrkdwn',\n text: `*Medium:* ${medium.length}`\n },\n {\n type: 'mrkdwn',\n text: `*🔹 Low:* ${low.length}`\n }\n ]\n }\n ],\n attachments: []\n };\n\n // Add urgent issues details\n if (urgent.length > 0) {\n const urgentDetails = urgent.slice(0, 5).map(group =>\n `• ${group.description} (${group.count} instances)`\n ).join('\\n');\n\n message.attachments!.push({\n color: 'danger',\n title: 'Urgent Issues - Immediate Action Required',\n text: urgentDetails,\n footer: urgent.length > 5 ? `... and ${urgent.length - 5} more urgent issues` : undefined\n });\n }\n\n // Add high priority issues\n if (high.length > 0) {\n const highDetails = high.slice(0, 3).map(group =>\n `• ${group.description} (${group.count} instances)`\n ).join('\\n');\n\n message.attachments!.push({\n color: 'warning',\n title: 'High Priority Issues',\n text: highDetails,\n footer: high.length > 3 ? `... and ${high.length - 3} more high priority issues` : undefined\n });\n }\n\n // Add recommendations\n if (priorityReport.recommendations.length > 0) {\n message.attachments!.push({\n color: 'good',\n title: 'Recommendations',\n text: priorityReport.recommendations.slice(0, 3).join('\\n')\n });\n }\n\n await this.sendMessage(message);\n }\n\n /**\n * Send critical issue alert\n */\n async sendCriticalAlert(issues: Issue[], repositoryName: string): Promise<void> {\n const message: SlackMessage = {\n text: `CRITICAL SECURITY ALERT: ${repositoryName}`,\n blocks: [\n {\n type: 'section',\n text: {\n type: 'mrkdwn',\n text: `*CRITICAL SECURITY ALERT*\\n*Repository:* ${repositoryName}\\n*Critical Issues:* ${issues.length}`\n }\n }\n ],\n attachments: issues.slice(0, 5).map(issue => ({\n color: 'danger',\n title: `${issue.file}:${issue.line || '?'}`,\n text: issue.issue.slice(0, 200),\n fields: [\n {\n title: 'Fix',\n value: issue.fix.slice(0, 100),\n short: false\n }\n ],\n footer: `Agent: ${issue.agent}`,\n ts: Math.floor(Date.now() / 1000)\n }))\n };\n\n if (issues.length > 5) {\n message.attachments!.push({\n color: 'danger',\n text: `... and ${issues.length - 5} more critical issues. View full report for details.`\n });\n }\n\n await this.sendMessage(message);\n }\n\n /**\n * Send team notification\n */\n async sendTeamNotification(notification: TeamNotification): Promise<void> {\n const emoji = this.getNotificationEmoji(notification.type);\n\n const message: SlackMessage = {\n blocks: [\n {\n type: 'section',\n text: {\n type: 'mrkdwn',\n text: `${emoji} *${notification.title}*\\n${notification.message}`\n }\n }\n ]\n };\n\n // Add specific data based on notification type\n if (notification.type === 'assignment' && notification.data) {\n const { assignment, issue } = notification.data;\n message.attachments = [{\n color: this.getAssignmentColor(assignment.priority),\n fields: [\n {\n title: 'Priority',\n value: assignment.priority.toUpperCase(),\n short: true\n },\n {\n title: 'Due Date',\n value: assignment.dueDate ? new Date(assignment.dueDate).toLocaleDateString() : 'Not set',\n short: true\n },\n {\n title: 'File',\n value: issue.file,\n short: false\n }\n ]\n }];\n }\n\n await this.sendMessage(message);\n }\n\n /**\n * Send daily/weekly team summary\n */\n async sendTeamSummary(\n period: 'daily' | 'weekly',\n stats: {\n newIssues: number;\n resolvedIssues: number;\n overdueIssues: number;\n topCategories: Array<{ category: string; count: number }>;\n topContributors: Array<{ name: string; resolved: number }>;\n }\n ): Promise<void> {\n const emoji = period === 'daily' ? '[DAILY]' : '[WEEKLY]';\n const title = `${emoji} ${period.charAt(0).toUpperCase() + period.slice(1)} Security Summary`;\n\n const message: SlackMessage = {\n blocks: [\n {\n type: 'section',\n text: {\n type: 'mrkdwn',\n text: `*${title}*`\n }\n },\n {\n type: 'section',\n fields: [\n {\n type: 'mrkdwn',\n text: `*New Issues:* ${stats.newIssues}`\n },\n {\n type: 'mrkdwn',\n text: `*✅ Resolved:* ${stats.resolvedIssues}`\n },\n {\n type: 'mrkdwn',\n text: `*Overdue:* ${stats.overdueIssues}`\n },\n {\n type: 'mrkdwn',\n text: `*Net Change:* ${stats.resolvedIssues - stats.newIssues > 0 ? '+' : ''}${stats.resolvedIssues - stats.newIssues}`\n }\n ]\n }\n ],\n attachments: []\n };\n\n // Top issue categories\n if (stats.topCategories.length > 0) {\n const categoriesText = stats.topCategories\n .slice(0, 5)\n .map(cat => `• ${cat.category}: ${cat.count}`)\n .join('\\n');\n\n message.attachments!.push({\n color: 'good',\n title: 'Top Issue Categories',\n text: categoriesText\n });\n }\n\n // Top contributors\n if (stats.topContributors.length > 0) {\n const contributorsText = stats.topContributors\n .slice(0, 5)\n .map(contrib => `• ${contrib.name}: ${contrib.resolved} resolved`)\n .join('\\n');\n\n message.attachments!.push({\n color: 'good',\n title: 'Top Contributors',\n text: contributorsText\n });\n }\n\n await this.sendMessage(message);\n }\n\n /**\n * Send bulk fix notification\n */\n async sendBulkFixNotification(\n fixedGroups: IssueGroup[],\n totalFixed: number,\n repositoryName: string\n ): Promise<void> {\n const message: SlackMessage = {\n blocks: [\n {\n type: 'section',\n text: {\n type: 'mrkdwn',\n text: `*Bulk Fix Applied*\\n*Repository:* ${repositoryName}\\n*Issues Fixed:* ${totalFixed}`\n }\n }\n ],\n attachments: [{\n color: 'good',\n title: '🔧 Fixed Issue Groups',\n text: fixedGroups.map(group =>\n `• ${group.description} (${group.count} instances)`\n ).join('\\n')\n }]\n };\n\n await this.sendMessage(message);\n }\n\n /**\n * Send escalation notification\n */\n async sendEscalationNotification(\n overdueAssignments: Array<{\n issueId: string;\n assignee: string;\n daysOverdue: number;\n priority: string;\n }>\n ): Promise<void> {\n const message: SlackMessage = {\n text: 'OVERDUE ISSUE ESCALATION',\n blocks: [\n {\n type: 'section',\n text: {\n type: 'mrkdwn',\n text: `*Overdue Issue Escalation*\\n${overdueAssignments.length} issues are overdue and require attention.`\n }\n }\n ],\n attachments: overdueAssignments.map(assignment => ({\n color: 'warning',\n title: `Issue ${assignment.issueId}`,\n fields: [\n {\n title: 'Assignee',\n value: assignment.assignee,\n short: true\n },\n {\n title: 'Days Overdue',\n value: assignment.daysOverdue.toString(),\n short: true\n },\n {\n title: 'Priority',\n value: assignment.priority.toUpperCase(),\n short: true\n }\n ]\n }))\n };\n\n await this.sendMessage(message);\n }\n\n /**\n * Send message to Slack\n */\n private async sendMessage(message: SlackMessage): Promise<void> {\n const payload = {\n ...message,\n channel: this.config.channel || message.channel,\n username: this.config.username || 'Trie Security Bot',\n icon_emoji: this.config.iconEmoji || ':shield:'\n };\n\n try {\n const response = await fetch(this.config.webhookUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(payload)\n });\n\n if (!response.ok) {\n throw new Error(`Slack API error: ${response.status} ${response.statusText}`);\n }\n } catch (error) {\n console.error('Failed to send Slack notification:', error);\n throw error;\n }\n }\n\n /**\n * Get emoji for notification type\n */\n private getNotificationEmoji(type: string): string {\n const emojis: Record<string, string> = {\n assignment: '[ASSIGN]',\n escalation: '[ESCALATE]',\n completion: '[DONE]',\n reminder: '[REMIND]'\n };\n return emojis[type] ?? '[NOTIFY]';\n }\n\n /**\n * Get color for assignment priority\n */\n private getAssignmentColor(priority: string): string {\n const colors: Record<string, string> = {\n urgent: 'danger',\n high: 'warning',\n medium: 'good',\n low: '#36a64f'\n };\n return colors[priority] ?? 'good';\n }\n\n /**\n * Test Slack connection\n */\n async testConnection(): Promise<boolean> {\n try {\n await this.sendMessage({\n text: 'Trie Slack Integration Test',\n blocks: [{\n type: 'section',\n text: {\n type: 'mrkdwn',\n text: '*Trie Slack Integration Test*\\nIf you see this message, the integration is working correctly!'\n }\n }]\n });\n return true;\n } catch (error) {\n console.error('Slack connection test failed:', error);\n return false;\n }\n }\n}","/**\n * Auto-Escalation System - Autonomous issue escalation\n * \n * Phase 4 of Guardian Agency Plan: Autonomous Actions\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 { GuardianInsight } from './insight-store.js';\nimport { getInsightStore } from './insight-store.js';\nimport { getGuardianState } from './guardian-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 guardianState;\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.guardianState = getGuardianState(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.guardianState.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.guardianState.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.guardianState.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.guardianState.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 Guardian',\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: GuardianInsight = {\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 * Phase 4 of Guardian Agency Plan: Autonomous Actions\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 { GuardianInsight } from './insight-store.js';\nimport { getInsightStore } from './insight-store.js';\nimport { getGuardianState, type AgentMetrics } from './guardian-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: GuardianInsight['type'];\n insightCategory: GuardianInsight['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 guardianState;\n private insightStore;\n private feedbackHistory: InsightFeedback[] = [];\n private weights: InsightWeights;\n \n constructor(projectPath: string) {\n this.guardianState = getGuardianState(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 guardian state metrics\n await this.guardianState.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: GuardianInsight['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.guardianState.getMetrics();\n }\n \n /**\n * Generate a comprehensive effectiveness report\n */\n async generateEffectivenessReport(): Promise<EffectivenessReport> {\n await this.guardianState.load();\n const metrics = this.guardianState.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: GuardianInsight): 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: GuardianInsight): 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":";;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAS,YAAAA,iBAAgB;;;ACPzB,SAAS,UAAU,eAAe;AA2DlC,IAAM,iBAAuC;AAAA,EAC3C,aAAa;AAA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D;AACF;AAGA,IAAM,oBAAgD,oBAAI,IAAI;AAEvD,SAAS,YAAY,aAAoC;AAC9D,MAAI,WAAW,kBAAkB,IAAI,WAAW;AAChD,MAAI,CAAC,UAAU;AACb,eAAW,IAAI,cAAc,WAAW;AACxC,sBAAkB,IAAI,aAAa,QAAQ;AAAA,EAC7C;AACA,SAAO;AACT;","names":["basename","issues","dirname","DEFAULT_CONFIG","basename","currentHashes"]}
@@ -1,18 +0,0 @@
1
- import {
2
- GuardianAgent,
3
- getGuardian
4
- } from "./chunk-SDS3UVFY.js";
5
- import "./chunk-6QR6QZIX.js";
6
- import "./chunk-IXO4G4D3.js";
7
- import "./chunk-33WL3D7A.js";
8
- import "./chunk-6JPPYG7F.js";
9
- import "./chunk-R4AAPFXC.js";
10
- import "./chunk-F4NJ4CBP.js";
11
- import "./chunk-6NLHFIYA.js";
12
- import "./chunk-APMV77PU.js";
13
- import "./chunk-DGUM43GV.js";
14
- export {
15
- GuardianAgent,
16
- getGuardian
17
- };
18
- //# sourceMappingURL=guardian-agent-XEYNG7RH.js.map