@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.
- package/dist/auto-fix-apply-PCAHWLXF.js +10 -0
- package/dist/autonomy-config-JXB7WCZ2.js +30 -0
- package/dist/chunk-2GIAROBF.js +173 -0
- package/dist/chunk-2GIAROBF.js.map +1 -0
- package/dist/{chunk-33WL3D7A.js → chunk-2SIFK7OW.js} +7 -419
- package/dist/chunk-2SIFK7OW.js.map +1 -0
- package/dist/chunk-43X6JBEM.js +36 -0
- package/dist/chunk-43X6JBEM.js.map +1 -0
- package/dist/chunk-55DOQNHJ.js +772 -0
- package/dist/chunk-55DOQNHJ.js.map +1 -0
- package/dist/chunk-6LXSA2OZ.js +425 -0
- package/dist/chunk-6LXSA2OZ.js.map +1 -0
- package/dist/{chunk-SDS3UVFY.js → chunk-AOFYU6T3.js} +113 -559
- package/dist/chunk-AOFYU6T3.js.map +1 -0
- package/dist/{chunk-6QR6QZIX.js → chunk-D3EXBJE2.js} +25 -658
- package/dist/chunk-D3EXBJE2.js.map +1 -0
- package/dist/chunk-DJ2YAGHK.js +50 -0
- package/dist/chunk-DJ2YAGHK.js.map +1 -0
- package/dist/chunk-DZREHOGW.js +706 -0
- package/dist/chunk-DZREHOGW.js.map +1 -0
- package/dist/chunk-I2GFI3AM.js +340 -0
- package/dist/chunk-I2GFI3AM.js.map +1 -0
- package/dist/chunk-KRH642MT.js +947 -0
- package/dist/chunk-KRH642MT.js.map +1 -0
- package/dist/{chunk-QYOACM2C.js → chunk-MVNJPJBK.js} +22 -252
- package/dist/chunk-MVNJPJBK.js.map +1 -0
- package/dist/chunk-NS2MSZMB.js +394 -0
- package/dist/chunk-NS2MSZMB.js.map +1 -0
- package/dist/chunk-SWSK7ANT.js +340 -0
- package/dist/chunk-SWSK7ANT.js.map +1 -0
- package/dist/chunk-VRLMTOB6.js +566 -0
- package/dist/chunk-VRLMTOB6.js.map +1 -0
- package/dist/chunk-YR4BMGYO.js +130 -0
- package/dist/chunk-YR4BMGYO.js.map +1 -0
- package/dist/chunk-ZV2K6M7T.js +74 -0
- package/dist/chunk-ZV2K6M7T.js.map +1 -0
- package/dist/{chunk-2764KZZQ.js → chunk-ZYKEILVK.js} +451 -1069
- package/dist/chunk-ZYKEILVK.js.map +1 -0
- package/dist/cli/main.js +107 -375
- package/dist/cli/main.js.map +1 -1
- package/dist/cli/yolo-daemon.js +18 -8
- package/dist/cli/yolo-daemon.js.map +1 -1
- package/dist/client-7XZHCMD3.js +28 -0
- package/dist/client-7XZHCMD3.js.map +1 -0
- package/dist/{goal-manager-AP4LTE6U.js → goal-manager-LMS6ZJB7.js} +7 -3
- package/dist/goal-manager-LMS6ZJB7.js.map +1 -0
- package/dist/goal-validator-T5HEYBC5.js +186 -0
- package/dist/goal-validator-T5HEYBC5.js.map +1 -0
- package/dist/graph-U5JWSAB5.js +10 -0
- package/dist/graph-U5JWSAB5.js.map +1 -0
- package/dist/guardian-agent-EXP7APLC.js +25 -0
- package/dist/guardian-agent-EXP7APLC.js.map +1 -0
- package/dist/hypothesis-KGC3P54C.js +19 -0
- package/dist/hypothesis-KGC3P54C.js.map +1 -0
- package/dist/incident-index-PNIVT47T.js +11 -0
- package/dist/incident-index-PNIVT47T.js.map +1 -0
- package/dist/index.js +369 -43
- package/dist/index.js.map +1 -1
- package/dist/ledger-SR6OEBLO.js +15 -0
- package/dist/ledger-SR6OEBLO.js.map +1 -0
- package/dist/output-manager-BOTMXSND.js +13 -0
- package/dist/output-manager-BOTMXSND.js.map +1 -0
- package/dist/pattern-discovery-F7LU5K6E.js +8 -0
- package/dist/pattern-discovery-F7LU5K6E.js.map +1 -0
- package/package.json +1 -1
- package/dist/chunk-2764KZZQ.js.map +0 -1
- package/dist/chunk-33WL3D7A.js.map +0 -1
- package/dist/chunk-6JPPYG7F.js +0 -1813
- package/dist/chunk-6JPPYG7F.js.map +0 -1
- package/dist/chunk-6QR6QZIX.js.map +0 -1
- package/dist/chunk-QYOACM2C.js.map +0 -1
- package/dist/chunk-SDS3UVFY.js.map +0 -1
- package/dist/guardian-agent-XEYNG7RH.js +0 -18
- /package/dist/{goal-manager-AP4LTE6U.js.map → auto-fix-apply-PCAHWLXF.js.map} +0 -0
- /package/dist/{guardian-agent-XEYNG7RH.js.map → autonomy-config-JXB7WCZ2.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/guardian/hypothesis.ts"],"sourcesContent":["/**\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 * Use Claude AI to generate novel hypotheses from observed patterns\n * This enables fully agentic hypothesis creation based on actual codebase observations\n */\n async generateHypothesesWithAI(context: {\n recentIssues?: any[];\n patterns?: string[];\n observations?: string[];\n }): Promise<Hypothesis[]> {\n const { isAIAvailable, runAIAnalysis } = await import('../ai/client.js');\n \n if (!isAIAvailable()) {\n return []; // Fall back to template-based generation\n }\n \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 = existing.map(h => h.statement);\n \n // Get recent issue data\n const issues = context.recentIssues || await searchIssues('', {\n workDir: this.projectPath,\n limit: 100,\n includeResolved: true,\n });\n \n if (issues.length < 5) {\n return generated; // Not enough data for AI\n }\n \n // Build context for Claude\n const issuesSummary = this.summarizeIssuesForAI(issues);\n const patternsSummary = context.patterns?.join('\\n') || 'No explicit patterns provided';\n const observationsSummary = context.observations?.join('\\n') || 'No explicit observations provided';\n \n const prompt = `You are an AI agent observing a codebase over time. Based on the patterns below, generate 1-3 testable hypotheses about this codebase's quality patterns.\n\n## Recent Issues Summary\n${issuesSummary}\n\n## Observed Patterns\n${patternsSummary}\n\n## Additional Observations\n${observationsSummary}\n\n## Existing Hypotheses (avoid duplicates)\n${existingStatements.length > 0 ? existingStatements.map(s => `- ${s}`).join('\\n') : 'None yet'}\n\nGenerate hypotheses that are:\n1. Specific and testable (can be validated with data)\n2. Actionable (if validated, can guide improvements)\n3. Novel (not duplicates of existing hypotheses)\n4. Based on real patterns in the data above\n\nReturn ONLY a JSON array of hypotheses. Each hypothesis must have:\n- \"statement\": Clear, concise hypothesis statement\n- \"category\": One of: \"timing\", \"pattern\", \"team\", \"code\", \"general\"\n- \"testCriteria\": How to test this hypothesis\n- \"confidence\": Initial confidence (0-1)\n- \"reasoning\": Why you think this hypothesis is worth testing\n\nExample format:\n[\n {\n \"statement\": \"Authentication code changes correlate with security issues\",\n \"category\": \"pattern\",\n \"testCriteria\": \"Track auth file changes and subsequent security issue rates\",\n \"confidence\": 0.6,\n \"reasoning\": \"65% of security issues occur in files modified in the past week\"\n }\n]\n\nReturn empty array [] if no novel hypotheses can be generated from the data.`;\n \n const result = await runAIAnalysis({\n systemPrompt: 'You are an expert code quality analyst who identifies patterns and generates testable hypotheses.',\n userPrompt: prompt,\n maxTokens: 1024,\n temperature: 0.7, // Higher temperature for creative hypothesis generation\n });\n \n if (!result.success || !result.content.trim()) {\n return generated;\n }\n \n // Parse AI response\n let aiHypotheses: Array<{\n statement: string;\n category: Hypothesis['category'];\n testCriteria: string;\n confidence: number;\n reasoning: string;\n }> = [];\n \n try {\n const cleaned = result.content.replace(/```json?\\n?|\\n?```/g, '').trim();\n aiHypotheses = JSON.parse(cleaned);\n if (!Array.isArray(aiHypotheses)) aiHypotheses = [];\n } catch {\n return generated; // AI response wasn't valid JSON\n }\n \n // Create hypotheses from AI suggestions\n for (const aiHypo of aiHypotheses.slice(0, 3)) {\n // Check for duplicates\n const isDuplicate = existingStatements.some(existing => \n existing.toLowerCase().includes(aiHypo.statement.toLowerCase().slice(0, 30))\n );\n \n if (isDuplicate) continue;\n \n const hypothesis = await this.createHypothesis(aiHypo.statement, {\n category: aiHypo.category,\n testCriteria: aiHypo.testCriteria,\n initialConfidence: Math.max(0.3, Math.min(0.7, aiHypo.confidence)),\n });\n \n // Add AI reasoning as initial evidence\n await this.guardianState.addEvidence(hypothesis.id, {\n type: 'supporting',\n description: `AI observed: ${aiHypo.reasoning}`,\n weight: aiHypo.confidence,\n timestamp: new Date().toISOString(),\n });\n \n generated.push(hypothesis);\n }\n \n } catch (error) {\n console.error('Failed to generate hypotheses with AI:', error);\n }\n \n return generated;\n }\n \n /**\n * Summarize issues for AI context\n */\n private summarizeIssuesForAI(issues: Array<{ issue: any; score: number }>): string {\n const totalIssues = issues.length;\n \n // Severity breakdown\n const severityCounts: Record<string, number> = {};\n for (const { issue } of issues) {\n severityCounts[issue.severity] = (severityCounts[issue.severity] || 0) + 1;\n }\n \n // Agent breakdown\n const agentCounts: Record<string, number> = {};\n for (const { issue } of issues) {\n agentCounts[issue.agent] = (agentCounts[issue.agent] || 0) + 1;\n }\n \n // File/directory patterns\n const fileCounts: Record<string, number> = {};\n for (const { issue } of issues) {\n const dir = dirname(issue.file);\n fileCounts[dir] = (fileCounts[dir] || 0) + 1;\n }\n \n // Time 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 const dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];\n const dayDistribution = Object.entries(dayOfWeekCounts)\n .sort(([a], [b]) => Number(a) - Number(b))\n .map(([day, count]) => `${dayNames[Number(day)]}: ${count}`)\n .join(', ');\n \n const topDirs = Object.entries(fileCounts)\n .sort(([, a], [, b]) => b - a)\n .slice(0, 5)\n .map(([dir, count]) => `${dir}: ${count}`)\n .join(', ');\n \n const topAgents = Object.entries(agentCounts)\n .sort(([, a], [, b]) => b - a)\n .slice(0, 5)\n .map(([agent, count]) => `${agent}: ${count}`)\n .join(', ');\n \n return `Total Issues: ${totalIssues}\nSeverities: ${Object.entries(severityCounts).map(([s, c]) => `${s}=${c}`).join(', ')}\nTop Agents: ${topAgents}\nTop Directories: ${topDirs}\nDay Distribution: ${dayDistribution}`;\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"],"mappings":";;;;;;;;;;;AAiBA,SAAS,eAAe;AA0CxB,IAAM,uBAA6C;AAAA,EACjD;AAAA,IACE,UAAU;AAAA,IACV,WAAW;AAAA,IACX,cAAc;AAAA,IACd,eAAe;AAAA,IACf,cAAc,CAAC,oBAAoB,iBAAiB;AAAA,EACtD;AAAA,EACA;AAAA,IACE,UAAU;AAAA,IACV,WAAW;AAAA,IACX,cAAc;AAAA,IACd,eAAe;AAAA,IACf,cAAc,CAAC,kBAAkB;AAAA,EACnC;AAAA,EACA;AAAA,IACE,UAAU;AAAA,IACV,WAAW;AAAA,IACX,cAAc;AAAA,IACd,eAAe;AAAA,IACf,cAAc,CAAC,aAAa;AAAA,EAC9B;AAAA,EACA;AAAA,IACE,UAAU;AAAA,IACV,WAAW;AAAA,IACX,cAAc;AAAA,IACd,eAAe;AAAA,IACf,cAAc,CAAC,eAAe,cAAc;AAAA,EAC9C;AAAA,EACA;AAAA,IACE,UAAU;AAAA,IACV,WAAW;AAAA,IACX,cAAc;AAAA,IACd,eAAe;AAAA,IACf,cAAc,CAAC,eAAe,WAAW;AAAA,EAC3C;AAAA,EACA;AAAA,IACE,UAAU;AAAA,IACV,WAAW;AAAA,IACX,cAAc;AAAA,IACd,eAAe;AAAA,IACf,cAAc,CAAC,oBAAoB,yBAAyB;AAAA,EAC9D;AAAA,EACA;AAAA,IACE,U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pD,UAAM,KAAK,cAAc,KAAK;AAC9B,WAAO,KAAK,cAAc,uBAAuB;AAAA,EACnD;AAAA;AAAA;AAAA;AAAA,EAKA,cAAsB;AACpB,UAAM,UAAU,KAAK,cAAc,WAAW;AAC9C,WAAO,QAAQ;AAAA,EACjB;AACF;AAMA,IAAM,oBAAmD,oBAAI,IAAI;AAK1D,SAAS,oBAAoB,aAAuC;AACzE,MAAI,SAAS,kBAAkB,IAAI,WAAW;AAC9C,MAAI,CAAC,QAAQ;AACX,aAAS,IAAI,iBAAiB,WAAW;AACzC,sBAAkB,IAAI,aAAa,MAAM;AAAA,EAC3C;AACA,SAAO;AACT;AAKO,SAAS,yBAA+B;AAC7C,oBAAkB,MAAM;AAC1B;","names":["existing"]}
|
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
import {
|
|
2
|
+
getTrieDirectory
|
|
3
|
+
} from "./chunk-R4AAPFXC.js";
|
|
4
|
+
|
|
5
|
+
// src/utils/autonomy-config.ts
|
|
6
|
+
import { readFile, writeFile, mkdir } from "fs/promises";
|
|
7
|
+
import { existsSync } from "fs";
|
|
8
|
+
import { join } from "path";
|
|
9
|
+
|
|
10
|
+
// src/types/autonomy.ts
|
|
11
|
+
var DEFAULT_AUTONOMY_CONFIG = {
|
|
12
|
+
level: "proactive",
|
|
13
|
+
autoCheck: {
|
|
14
|
+
enabled: true,
|
|
15
|
+
threshold: 5,
|
|
16
|
+
onCritical: true,
|
|
17
|
+
cooldownMs: 3e4
|
|
18
|
+
// 30 seconds
|
|
19
|
+
},
|
|
20
|
+
autoFix: {
|
|
21
|
+
enabled: true,
|
|
22
|
+
askFirst: true,
|
|
23
|
+
// Always ask (human-in-the-loop)
|
|
24
|
+
categories: ["trivial", "safe"],
|
|
25
|
+
allowedFixTypes: [
|
|
26
|
+
"remove-console-log",
|
|
27
|
+
"remove-debugger",
|
|
28
|
+
"remove-emoji",
|
|
29
|
+
"remove-unused-import",
|
|
30
|
+
"add-missing-await",
|
|
31
|
+
"fix-typo"
|
|
32
|
+
]
|
|
33
|
+
},
|
|
34
|
+
pushBlocking: {
|
|
35
|
+
enabled: true,
|
|
36
|
+
allowBypass: true,
|
|
37
|
+
blockOn: ["critical"],
|
|
38
|
+
bypassMethods: ["env", "flag", "confirm"],
|
|
39
|
+
logBypasses: true
|
|
40
|
+
},
|
|
41
|
+
progressiveEscalation: {
|
|
42
|
+
enabled: true,
|
|
43
|
+
thresholds: {
|
|
44
|
+
suggest: 1,
|
|
45
|
+
autoCheck: 3,
|
|
46
|
+
escalate: 5,
|
|
47
|
+
block: 10
|
|
48
|
+
},
|
|
49
|
+
windowMs: 24 * 60 * 60 * 1e3
|
|
50
|
+
// 24 hours
|
|
51
|
+
},
|
|
52
|
+
aiWatcher: {
|
|
53
|
+
enabled: true,
|
|
54
|
+
hourlyTokenLimit: 5e4,
|
|
55
|
+
scanCooldownSec: 30,
|
|
56
|
+
cleanFileCooldownSec: 300,
|
|
57
|
+
maxFilesPerScan: 5,
|
|
58
|
+
maxCharsPerFile: 4e3
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
// src/utils/autonomy-config.ts
|
|
63
|
+
import { createHash } from "crypto";
|
|
64
|
+
async function loadAutonomyConfig(projectPath) {
|
|
65
|
+
const configPath = join(getTrieDirectory(projectPath), "config.json");
|
|
66
|
+
try {
|
|
67
|
+
if (!existsSync(configPath)) {
|
|
68
|
+
return { ...DEFAULT_AUTONOMY_CONFIG };
|
|
69
|
+
}
|
|
70
|
+
const content = await readFile(configPath, "utf-8");
|
|
71
|
+
const config = JSON.parse(content);
|
|
72
|
+
return mergeWithDefaults(config.autonomy || {});
|
|
73
|
+
} catch (error) {
|
|
74
|
+
console.error("Failed to load autonomy config:", error);
|
|
75
|
+
return { ...DEFAULT_AUTONOMY_CONFIG };
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
async function saveAutonomyConfig(projectPath, autonomyConfig) {
|
|
79
|
+
const configPath = join(getTrieDirectory(projectPath), "config.json");
|
|
80
|
+
const trieDir = getTrieDirectory(projectPath);
|
|
81
|
+
try {
|
|
82
|
+
if (!existsSync(trieDir)) {
|
|
83
|
+
await mkdir(trieDir, { recursive: true });
|
|
84
|
+
}
|
|
85
|
+
let fullConfig = {};
|
|
86
|
+
if (existsSync(configPath)) {
|
|
87
|
+
const content = await readFile(configPath, "utf-8");
|
|
88
|
+
fullConfig = JSON.parse(content);
|
|
89
|
+
}
|
|
90
|
+
fullConfig.autonomy = mergeWithDefaults(autonomyConfig);
|
|
91
|
+
const tempPath = configPath + ".tmp";
|
|
92
|
+
await writeFile(tempPath, JSON.stringify(fullConfig, null, 2));
|
|
93
|
+
await writeFile(configPath, JSON.stringify(fullConfig, null, 2));
|
|
94
|
+
} catch (error) {
|
|
95
|
+
console.error("Failed to save autonomy config:", error);
|
|
96
|
+
throw error;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
function mergeWithDefaults(partial) {
|
|
100
|
+
return {
|
|
101
|
+
level: partial.level ?? DEFAULT_AUTONOMY_CONFIG.level,
|
|
102
|
+
autoCheck: {
|
|
103
|
+
...DEFAULT_AUTONOMY_CONFIG.autoCheck,
|
|
104
|
+
...partial.autoCheck || {}
|
|
105
|
+
},
|
|
106
|
+
autoFix: {
|
|
107
|
+
...DEFAULT_AUTONOMY_CONFIG.autoFix,
|
|
108
|
+
...partial.autoFix || {}
|
|
109
|
+
},
|
|
110
|
+
pushBlocking: {
|
|
111
|
+
...DEFAULT_AUTONOMY_CONFIG.pushBlocking,
|
|
112
|
+
...partial.pushBlocking || {}
|
|
113
|
+
},
|
|
114
|
+
progressiveEscalation: {
|
|
115
|
+
...DEFAULT_AUTONOMY_CONFIG.progressiveEscalation,
|
|
116
|
+
...partial.progressiveEscalation || {},
|
|
117
|
+
thresholds: {
|
|
118
|
+
...DEFAULT_AUTONOMY_CONFIG.progressiveEscalation.thresholds,
|
|
119
|
+
...partial.progressiveEscalation?.thresholds || {}
|
|
120
|
+
}
|
|
121
|
+
},
|
|
122
|
+
aiWatcher: {
|
|
123
|
+
...DEFAULT_AUTONOMY_CONFIG.aiWatcher,
|
|
124
|
+
...partial.aiWatcher || {}
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
var occurrenceCache = /* @__PURE__ */ new Map();
|
|
129
|
+
async function getOccurrences(projectPath) {
|
|
130
|
+
if (occurrenceCache.has(projectPath)) {
|
|
131
|
+
return occurrenceCache.get(projectPath);
|
|
132
|
+
}
|
|
133
|
+
const occurrencesPath = join(getTrieDirectory(projectPath), "memory", "occurrences.json");
|
|
134
|
+
const occurrences = /* @__PURE__ */ new Map();
|
|
135
|
+
try {
|
|
136
|
+
if (existsSync(occurrencesPath)) {
|
|
137
|
+
const content = await readFile(occurrencesPath, "utf-8");
|
|
138
|
+
const data = JSON.parse(content);
|
|
139
|
+
for (const [hash, occ] of Object.entries(data)) {
|
|
140
|
+
occurrences.set(hash, occ);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
} catch {
|
|
144
|
+
}
|
|
145
|
+
occurrenceCache.set(projectPath, occurrences);
|
|
146
|
+
return occurrences;
|
|
147
|
+
}
|
|
148
|
+
async function saveOccurrences(projectPath) {
|
|
149
|
+
const occurrences = occurrenceCache.get(projectPath);
|
|
150
|
+
if (!occurrences) return;
|
|
151
|
+
const occurrencesPath = join(getTrieDirectory(projectPath), "memory", "occurrences.json");
|
|
152
|
+
const memoryDir = join(getTrieDirectory(projectPath), "memory");
|
|
153
|
+
try {
|
|
154
|
+
if (!existsSync(memoryDir)) {
|
|
155
|
+
await mkdir(memoryDir, { recursive: true });
|
|
156
|
+
}
|
|
157
|
+
const data = {};
|
|
158
|
+
for (const [hash, occ] of occurrences.entries()) {
|
|
159
|
+
data[hash] = occ;
|
|
160
|
+
}
|
|
161
|
+
await writeFile(occurrencesPath, JSON.stringify(data, null, 2));
|
|
162
|
+
} catch (error) {
|
|
163
|
+
console.error("Failed to save occurrences:", error);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
function createIssueHash(file, line, issueType) {
|
|
167
|
+
const input = `${file}:${line || 0}:${issueType}`;
|
|
168
|
+
return createHash("md5").update(input).digest("hex").slice(0, 12);
|
|
169
|
+
}
|
|
170
|
+
async function trackIssueOccurrence(projectPath, file, line, issueType, config) {
|
|
171
|
+
const occurrences = await getOccurrences(projectPath);
|
|
172
|
+
const hash = createIssueHash(file, line, issueType);
|
|
173
|
+
const now = Date.now();
|
|
174
|
+
let occurrence = occurrences.get(hash);
|
|
175
|
+
if (occurrence) {
|
|
176
|
+
const windowMs = config.progressiveEscalation.windowMs;
|
|
177
|
+
if (now - occurrence.firstSeen > windowMs) {
|
|
178
|
+
occurrence = {
|
|
179
|
+
hash,
|
|
180
|
+
firstSeen: now,
|
|
181
|
+
lastSeen: now,
|
|
182
|
+
count: 1,
|
|
183
|
+
escalationLevel: "suggest",
|
|
184
|
+
notified: false,
|
|
185
|
+
bypassed: false,
|
|
186
|
+
bypassHistory: occurrence.bypassHistory
|
|
187
|
+
// Keep bypass history
|
|
188
|
+
};
|
|
189
|
+
} else {
|
|
190
|
+
occurrence.lastSeen = now;
|
|
191
|
+
occurrence.count++;
|
|
192
|
+
const thresholds = config.progressiveEscalation.thresholds;
|
|
193
|
+
if (occurrence.count >= thresholds.block) {
|
|
194
|
+
occurrence.escalationLevel = "block";
|
|
195
|
+
} else if (occurrence.count >= thresholds.escalate) {
|
|
196
|
+
occurrence.escalationLevel = "escalate";
|
|
197
|
+
} else if (occurrence.count >= thresholds.autoCheck) {
|
|
198
|
+
occurrence.escalationLevel = "autoCheck";
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
} else {
|
|
202
|
+
occurrence = {
|
|
203
|
+
hash,
|
|
204
|
+
firstSeen: now,
|
|
205
|
+
lastSeen: now,
|
|
206
|
+
count: 1,
|
|
207
|
+
escalationLevel: "suggest",
|
|
208
|
+
notified: false,
|
|
209
|
+
bypassed: false,
|
|
210
|
+
bypassHistory: []
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
occurrences.set(hash, occurrence);
|
|
214
|
+
await saveOccurrences(projectPath);
|
|
215
|
+
return occurrence;
|
|
216
|
+
}
|
|
217
|
+
async function getEscalationLevel(projectPath, file, line, issueType) {
|
|
218
|
+
const occurrences = await getOccurrences(projectPath);
|
|
219
|
+
const hash = createIssueHash(file, line, issueType);
|
|
220
|
+
const occurrence = occurrences.get(hash);
|
|
221
|
+
return occurrence?.escalationLevel ?? "suggest";
|
|
222
|
+
}
|
|
223
|
+
async function recordBypass(projectPath, file, line, issueType, method, reason) {
|
|
224
|
+
const occurrences = await getOccurrences(projectPath);
|
|
225
|
+
const hash = createIssueHash(file, line, issueType);
|
|
226
|
+
const occurrence = occurrences.get(hash);
|
|
227
|
+
if (occurrence) {
|
|
228
|
+
occurrence.bypassed = true;
|
|
229
|
+
occurrence.bypassHistory.push({
|
|
230
|
+
timestamp: Date.now(),
|
|
231
|
+
method,
|
|
232
|
+
...reason !== void 0 ? { reason } : {}
|
|
233
|
+
});
|
|
234
|
+
await saveOccurrences(projectPath);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
function shouldAutoFix(fix, config) {
|
|
238
|
+
if (!config.autoFix.enabled) {
|
|
239
|
+
return false;
|
|
240
|
+
}
|
|
241
|
+
const allowedCategories = config.autoFix.categories;
|
|
242
|
+
if (!allowedCategories.includes(fix.category) && !allowedCategories.includes("all")) {
|
|
243
|
+
return false;
|
|
244
|
+
}
|
|
245
|
+
if (config.autoFix.allowedFixTypes.length > 0 && !config.autoFix.allowedFixTypes.includes(fix.type)) {
|
|
246
|
+
return false;
|
|
247
|
+
}
|
|
248
|
+
if (fix.confidence < 0.9) {
|
|
249
|
+
return false;
|
|
250
|
+
}
|
|
251
|
+
return true;
|
|
252
|
+
}
|
|
253
|
+
function groupFixesByFile(fixes) {
|
|
254
|
+
const grouped = /* @__PURE__ */ new Map();
|
|
255
|
+
for (const fix of fixes) {
|
|
256
|
+
const existing = grouped.get(fix.file) || [];
|
|
257
|
+
existing.push(fix);
|
|
258
|
+
grouped.set(fix.file, existing);
|
|
259
|
+
}
|
|
260
|
+
return grouped;
|
|
261
|
+
}
|
|
262
|
+
function shouldBlockPush(issues, config) {
|
|
263
|
+
if (!config.pushBlocking.enabled) {
|
|
264
|
+
return {
|
|
265
|
+
blocked: false,
|
|
266
|
+
blockingIssues: [],
|
|
267
|
+
bypassed: false
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
const blockingIssues = issues.filter(
|
|
271
|
+
(issue) => config.pushBlocking.blockOn.includes(issue.severity)
|
|
272
|
+
);
|
|
273
|
+
if (blockingIssues.length === 0) {
|
|
274
|
+
return {
|
|
275
|
+
blocked: false,
|
|
276
|
+
blockingIssues: [],
|
|
277
|
+
bypassed: false
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
const envBypass = process.env.TRIE_BYPASS === "1" || process.env.TRIE_BYPASS === "true";
|
|
281
|
+
if (envBypass && config.pushBlocking.allowBypass) {
|
|
282
|
+
return {
|
|
283
|
+
blocked: false,
|
|
284
|
+
blockingIssues,
|
|
285
|
+
bypassed: true,
|
|
286
|
+
bypassMethod: "env"
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
const bypassInstructions = buildBypassInstructions(config);
|
|
290
|
+
return {
|
|
291
|
+
blocked: true,
|
|
292
|
+
reason: `${blockingIssues.length} ${blockingIssues[0]?.severity || "critical"} issue(s) must be fixed before pushing`,
|
|
293
|
+
blockingIssues,
|
|
294
|
+
bypassInstructions,
|
|
295
|
+
bypassed: false
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
function buildBypassInstructions(config) {
|
|
299
|
+
const instructions = [];
|
|
300
|
+
if (config.pushBlocking.bypassMethods.includes("env")) {
|
|
301
|
+
instructions.push("\u2022 Set TRIE_BYPASS=1 to bypass: TRIE_BYPASS=1 git push");
|
|
302
|
+
}
|
|
303
|
+
if (config.pushBlocking.bypassMethods.includes("flag")) {
|
|
304
|
+
instructions.push("\u2022 Use --no-verify flag: git push --no-verify");
|
|
305
|
+
}
|
|
306
|
+
if (config.pushBlocking.bypassMethods.includes("confirm")) {
|
|
307
|
+
instructions.push("\u2022 Run: trie bypass --confirm to bypass this push");
|
|
308
|
+
}
|
|
309
|
+
return instructions.join("\n");
|
|
310
|
+
}
|
|
311
|
+
var configCache = /* @__PURE__ */ new Map();
|
|
312
|
+
var CACHE_TTL = 6e4;
|
|
313
|
+
async function getAutonomyConfig(projectPath) {
|
|
314
|
+
const cached = configCache.get(projectPath);
|
|
315
|
+
if (cached && Date.now() - cached.loadedAt < CACHE_TTL) {
|
|
316
|
+
return cached.config;
|
|
317
|
+
}
|
|
318
|
+
const config = await loadAutonomyConfig(projectPath);
|
|
319
|
+
configCache.set(projectPath, { config, loadedAt: Date.now() });
|
|
320
|
+
return config;
|
|
321
|
+
}
|
|
322
|
+
function clearConfigCache() {
|
|
323
|
+
configCache.clear();
|
|
324
|
+
occurrenceCache.clear();
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
export {
|
|
328
|
+
loadAutonomyConfig,
|
|
329
|
+
saveAutonomyConfig,
|
|
330
|
+
createIssueHash,
|
|
331
|
+
trackIssueOccurrence,
|
|
332
|
+
getEscalationLevel,
|
|
333
|
+
recordBypass,
|
|
334
|
+
shouldAutoFix,
|
|
335
|
+
groupFixesByFile,
|
|
336
|
+
shouldBlockPush,
|
|
337
|
+
getAutonomyConfig,
|
|
338
|
+
clearConfigCache
|
|
339
|
+
};
|
|
340
|
+
//# sourceMappingURL=chunk-I2GFI3AM.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utils/autonomy-config.ts","../src/types/autonomy.ts"],"sourcesContent":["/**\n * Autonomy Configuration Loader\n * \n * Loads, saves, and manages autonomy settings from .trie/config.json\n */\n\nimport { readFile, writeFile, mkdir } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { join } from 'path';\nimport { getTrieDirectory } from './workspace.js';\nimport type { \n AutonomyConfig, \n IssueOccurrence,\n AutoFixAction,\n PushBlockResult \n} from '../types/autonomy.js';\nimport { DEFAULT_AUTONOMY_CONFIG } from '../types/autonomy.js';\nimport { createHash } from 'crypto';\n\n// ============================================================================\n// Config Loading/Saving\n// ============================================================================\n\n/**\n * Load autonomy config from .trie/config.json\n */\nexport async function loadAutonomyConfig(projectPath: string): Promise<AutonomyConfig> {\n const configPath = join(getTrieDirectory(projectPath), 'config.json');\n \n try {\n if (!existsSync(configPath)) {\n return { ...DEFAULT_AUTONOMY_CONFIG };\n }\n \n const content = await readFile(configPath, 'utf-8');\n const config = JSON.parse(content);\n \n // Merge with defaults to ensure all fields exist\n return mergeWithDefaults(config.autonomy || {});\n } catch (error) {\n console.error('Failed to load autonomy config:', error);\n return { ...DEFAULT_AUTONOMY_CONFIG };\n }\n}\n\n/**\n * Save autonomy config to .trie/config.json\n */\nexport async function saveAutonomyConfig(\n projectPath: string, \n autonomyConfig: Partial<AutonomyConfig>\n): Promise<void> {\n const configPath = join(getTrieDirectory(projectPath), 'config.json');\n const trieDir = getTrieDirectory(projectPath);\n \n try {\n // Ensure .trie directory exists\n if (!existsSync(trieDir)) {\n await mkdir(trieDir, { recursive: true });\n }\n \n // Load existing config\n let fullConfig: Record<string, unknown> = {};\n if (existsSync(configPath)) {\n const content = await readFile(configPath, 'utf-8');\n fullConfig = JSON.parse(content);\n }\n \n // Merge autonomy config\n fullConfig.autonomy = mergeWithDefaults(autonomyConfig);\n \n // Save atomically\n const tempPath = configPath + '.tmp';\n await writeFile(tempPath, JSON.stringify(fullConfig, null, 2));\n await writeFile(configPath, JSON.stringify(fullConfig, null, 2));\n \n } catch (error) {\n console.error('Failed to save autonomy config:', error);\n throw error;\n }\n}\n\n/**\n * Merge partial config with defaults\n */\nfunction mergeWithDefaults(partial: Partial<AutonomyConfig>): AutonomyConfig {\n return {\n level: partial.level ?? DEFAULT_AUTONOMY_CONFIG.level,\n autoCheck: {\n ...DEFAULT_AUTONOMY_CONFIG.autoCheck,\n ...(partial.autoCheck || {}),\n },\n autoFix: {\n ...DEFAULT_AUTONOMY_CONFIG.autoFix,\n ...(partial.autoFix || {}),\n },\n pushBlocking: {\n ...DEFAULT_AUTONOMY_CONFIG.pushBlocking,\n ...(partial.pushBlocking || {}),\n },\n progressiveEscalation: {\n ...DEFAULT_AUTONOMY_CONFIG.progressiveEscalation,\n ...(partial.progressiveEscalation || {}),\n thresholds: {\n ...DEFAULT_AUTONOMY_CONFIG.progressiveEscalation.thresholds,\n ...(partial.progressiveEscalation?.thresholds || {}),\n },\n },\n aiWatcher: {\n ...DEFAULT_AUTONOMY_CONFIG.aiWatcher,\n ...(partial.aiWatcher || {}),\n },\n };\n}\n\n// ============================================================================\n// Issue Occurrence Tracking (for progressive escalation)\n// ============================================================================\n\nconst occurrenceCache = new Map<string, Map<string, IssueOccurrence>>();\n\n/**\n * Get occurrence tracker for a project\n */\nasync function getOccurrences(projectPath: string): Promise<Map<string, IssueOccurrence>> {\n if (occurrenceCache.has(projectPath)) {\n return occurrenceCache.get(projectPath)!;\n }\n \n const occurrencesPath = join(getTrieDirectory(projectPath), 'memory', 'occurrences.json');\n const occurrences = new Map<string, IssueOccurrence>();\n \n try {\n if (existsSync(occurrencesPath)) {\n const content = await readFile(occurrencesPath, 'utf-8');\n const data = JSON.parse(content);\n for (const [hash, occ] of Object.entries(data)) {\n occurrences.set(hash, occ as IssueOccurrence);\n }\n }\n } catch {\n // Start fresh\n }\n \n occurrenceCache.set(projectPath, occurrences);\n return occurrences;\n}\n\n/**\n * Save occurrences to disk\n */\nasync function saveOccurrences(projectPath: string): Promise<void> {\n const occurrences = occurrenceCache.get(projectPath);\n if (!occurrences) return;\n \n const occurrencesPath = join(getTrieDirectory(projectPath), 'memory', 'occurrences.json');\n const memoryDir = join(getTrieDirectory(projectPath), 'memory');\n \n try {\n if (!existsSync(memoryDir)) {\n await mkdir(memoryDir, { recursive: true });\n }\n \n const data: Record<string, IssueOccurrence> = {};\n for (const [hash, occ] of occurrences.entries()) {\n data[hash] = occ;\n }\n \n await writeFile(occurrencesPath, JSON.stringify(data, null, 2));\n } catch (error) {\n console.error('Failed to save occurrences:', error);\n }\n}\n\n/**\n * Create a hash for an issue (for deduplication)\n */\nexport function createIssueHash(file: string, line: number | undefined, issueType: string): string {\n const input = `${file}:${line || 0}:${issueType}`;\n return createHash('md5').update(input).digest('hex').slice(0, 12);\n}\n\n/**\n * Track an issue occurrence\n */\nexport async function trackIssueOccurrence(\n projectPath: string,\n file: string,\n line: number | undefined,\n issueType: string,\n config: AutonomyConfig\n): Promise<IssueOccurrence> {\n const occurrences = await getOccurrences(projectPath);\n const hash = createIssueHash(file, line, issueType);\n const now = Date.now();\n \n let occurrence = occurrences.get(hash);\n \n if (occurrence) {\n // Check if within time window\n const windowMs = config.progressiveEscalation.windowMs;\n if (now - occurrence.firstSeen > windowMs) {\n // Reset if outside window\n occurrence = {\n hash,\n firstSeen: now,\n lastSeen: now,\n count: 1,\n escalationLevel: 'suggest',\n notified: false,\n bypassed: false,\n bypassHistory: occurrence.bypassHistory, // Keep bypass history\n };\n } else {\n // Increment within window\n occurrence.lastSeen = now;\n occurrence.count++;\n \n // Update escalation level\n const thresholds = config.progressiveEscalation.thresholds;\n if (occurrence.count >= thresholds.block) {\n occurrence.escalationLevel = 'block';\n } else if (occurrence.count >= thresholds.escalate) {\n occurrence.escalationLevel = 'escalate';\n } else if (occurrence.count >= thresholds.autoCheck) {\n occurrence.escalationLevel = 'autoCheck';\n }\n }\n } else {\n // New occurrence\n occurrence = {\n hash,\n firstSeen: now,\n lastSeen: now,\n count: 1,\n escalationLevel: 'suggest',\n notified: false,\n bypassed: false,\n bypassHistory: [],\n };\n }\n \n occurrences.set(hash, occurrence);\n await saveOccurrences(projectPath);\n \n return occurrence;\n}\n\n/**\n * Get escalation level for an issue\n */\nexport async function getEscalationLevel(\n projectPath: string,\n file: string,\n line: number | undefined,\n issueType: string\n): Promise<IssueOccurrence['escalationLevel']> {\n const occurrences = await getOccurrences(projectPath);\n const hash = createIssueHash(file, line, issueType);\n \n const occurrence = occurrences.get(hash);\n return occurrence?.escalationLevel ?? 'suggest';\n}\n\n/**\n * Record a bypass\n */\nexport async function recordBypass(\n projectPath: string,\n file: string,\n line: number | undefined,\n issueType: string,\n method: string,\n reason?: string\n): Promise<void> {\n const occurrences = await getOccurrences(projectPath);\n const hash = createIssueHash(file, line, issueType);\n \n const occurrence = occurrences.get(hash);\n if (occurrence) {\n occurrence.bypassed = true;\n occurrence.bypassHistory.push({\n timestamp: Date.now(),\n method,\n ...(reason !== undefined ? { reason } : {}),\n });\n await saveOccurrences(projectPath);\n }\n}\n\n// ============================================================================\n// Auto-fix Helpers\n// ============================================================================\n\n/**\n * Check if a fix should be auto-applied based on config\n */\nexport function shouldAutoFix(\n fix: AutoFixAction,\n config: AutonomyConfig\n): boolean {\n if (!config.autoFix.enabled) {\n return false;\n }\n \n // Check if category is allowed\n const allowedCategories = config.autoFix.categories as string[];\n if (!allowedCategories.includes(fix.category) && \n !allowedCategories.includes('all')) {\n return false;\n }\n \n // Check if specific fix type is allowed\n if (config.autoFix.allowedFixTypes.length > 0 &&\n !config.autoFix.allowedFixTypes.includes(fix.type)) {\n return false;\n }\n \n // Check confidence threshold (require high confidence for auto-fix)\n if (fix.confidence < 0.9) {\n return false;\n }\n \n return true;\n}\n\n/**\n * Group fixes by file for batch application\n */\nexport function groupFixesByFile(fixes: AutoFixAction[]): Map<string, AutoFixAction[]> {\n const grouped = new Map<string, AutoFixAction[]>();\n \n for (const fix of fixes) {\n const existing = grouped.get(fix.file) || [];\n existing.push(fix);\n grouped.set(fix.file, existing);\n }\n \n return grouped;\n}\n\n// ============================================================================\n// Push Blocking Helpers\n// ============================================================================\n\n/**\n * Check if push should be blocked\n */\nexport function shouldBlockPush(\n issues: Array<{ severity: string; file: string; line?: number; issue: string }>,\n config: AutonomyConfig\n): PushBlockResult {\n if (!config.pushBlocking.enabled) {\n return {\n blocked: false,\n blockingIssues: [],\n bypassed: false,\n };\n }\n \n // Find blocking issues\n const blockingIssues = issues.filter(issue => \n config.pushBlocking.blockOn.includes(issue.severity as 'critical' | 'serious' | 'moderate')\n );\n \n if (blockingIssues.length === 0) {\n return {\n blocked: false,\n blockingIssues: [],\n bypassed: false,\n };\n }\n \n // Check for bypass\n const envBypass = process.env.TRIE_BYPASS === '1' || process.env.TRIE_BYPASS === 'true';\n \n if (envBypass && config.pushBlocking.allowBypass) {\n return {\n blocked: false,\n blockingIssues,\n bypassed: true,\n bypassMethod: 'env',\n };\n }\n \n // Build bypass instructions\n const bypassInstructions = buildBypassInstructions(config);\n \n return {\n blocked: true,\n reason: `${blockingIssues.length} ${blockingIssues[0]?.severity || 'critical'} issue(s) must be fixed before pushing`,\n blockingIssues,\n bypassInstructions,\n bypassed: false,\n };\n}\n\n/**\n * Build bypass instructions based on config\n */\nfunction buildBypassInstructions(config: AutonomyConfig): string {\n const instructions: string[] = [];\n \n if (config.pushBlocking.bypassMethods.includes('env')) {\n instructions.push('• Set TRIE_BYPASS=1 to bypass: TRIE_BYPASS=1 git push');\n }\n \n if (config.pushBlocking.bypassMethods.includes('flag')) {\n instructions.push('• Use --no-verify flag: git push --no-verify');\n }\n \n if (config.pushBlocking.bypassMethods.includes('confirm')) {\n instructions.push('• Run: trie bypass --confirm to bypass this push');\n }\n \n return instructions.join('\\n');\n}\n\n// ============================================================================\n// Singleton Config Cache\n// ============================================================================\n\nconst configCache = new Map<string, { config: AutonomyConfig; loadedAt: number }>();\nconst CACHE_TTL = 60000; // 1 minute\n\n/**\n * Get autonomy config with caching\n */\nexport async function getAutonomyConfig(projectPath: string): Promise<AutonomyConfig> {\n const cached = configCache.get(projectPath);\n \n if (cached && Date.now() - cached.loadedAt < CACHE_TTL) {\n return cached.config;\n }\n \n const config = await loadAutonomyConfig(projectPath);\n configCache.set(projectPath, { config, loadedAt: Date.now() });\n \n return config;\n}\n\n/**\n * Clear config cache (for testing or after config changes)\n */\nexport function clearConfigCache(): void {\n configCache.clear();\n occurrenceCache.clear();\n}\n","/**\n * Autonomy Configuration Types\n * \n * Controls how autonomous Trie behaves:\n * - Auto-check: Run full checks when issues detected\n * - Auto-fix: Apply fixes with human confirmation\n * - Push blocking: Block git push on critical issues\n * - Progressive escalation: Escalate based on occurrence count\n */\n\n/**\n * Overall autonomy level\n */\nexport type AutonomyLevel = \n | 'passive' // Only report, never act\n | 'suggest' // Suggest actions, don't execute\n | 'proactive' // Auto-check, ask before fixing\n | 'aggressive'; // Auto-check, auto-fix trivial, block on critical\n\n/**\n * Auto-check configuration\n */\nexport interface AutoCheckConfig {\n /** Enable auto-running full checks */\n enabled: boolean;\n /** Issue count threshold to trigger auto-check */\n threshold: number;\n /** Always trigger on critical issues */\n onCritical: boolean;\n /** Cooldown between auto-checks (ms) */\n cooldownMs: number;\n}\n\n/**\n * Auto-fix configuration\n */\nexport interface AutoFixConfig {\n /** Enable auto-fix suggestions */\n enabled: boolean;\n /** Always ask user before applying fixes (human-in-the-loop) */\n askFirst: boolean;\n /** Categories of fixes to auto-apply */\n categories: ('trivial' | 'safe' | 'moderate' | 'all')[];\n /** Specific fix types to auto-apply */\n allowedFixTypes: string[];\n}\n\n/**\n * Push blocking configuration\n */\nexport interface PushBlockingConfig {\n /** Enable push blocking */\n enabled: boolean;\n /** Allow user to bypass with flag */\n allowBypass: boolean;\n /** Severities that trigger blocking */\n blockOn: ('critical' | 'serious' | 'moderate')[];\n /** Bypass methods */\n bypassMethods: ('env' | 'flag' | 'confirm')[];\n /** Log bypasses for audit */\n logBypasses: boolean;\n}\n\n/**\n * Progressive escalation thresholds\n */\nexport interface ProgressiveEscalationConfig {\n /** Enable progressive escalation */\n enabled: boolean;\n /** Thresholds for different actions */\n thresholds: {\n /** First occurrence: suggest fix */\n suggest: number;\n /** N occurrences: auto-run full check */\n autoCheck: number;\n /** N occurrences: escalate to Slack/email */\n escalate: number;\n /** N occurrences: block until fixed */\n block: number;\n };\n /** Time window for counting occurrences (ms) */\n windowMs: number;\n}\n\n/**\n * AI Watcher configuration -- controls the Claude-powered file watcher\n */\nexport interface AIWatcherConfig {\n /** Enable AI-powered file watching */\n enabled: boolean;\n /** Max tokens to spend per hour on AI scans */\n hourlyTokenLimit: number;\n /** Minimum seconds between AI scans */\n scanCooldownSec: number;\n /** Seconds before re-scanning a file that was clean */\n cleanFileCooldownSec: number;\n /** Max files to include in a single AI scan */\n maxFilesPerScan: number;\n /** Max characters to send per file */\n maxCharsPerFile: number;\n}\n\n/**\n * Full autonomy configuration\n */\nexport interface AutonomyConfig {\n /** Overall autonomy level (can be overridden by specific settings) */\n level: AutonomyLevel;\n /** Auto-check settings */\n autoCheck: AutoCheckConfig;\n /** Auto-fix settings */\n autoFix: AutoFixConfig;\n /** Push blocking settings */\n pushBlocking: PushBlockingConfig;\n /** Progressive escalation settings */\n progressiveEscalation: ProgressiveEscalationConfig;\n /** AI watcher settings (Claude-powered file scanning) */\n aiWatcher: AIWatcherConfig;\n}\n\n/**\n * Default autonomy configuration - proactive but safe\n */\nexport const DEFAULT_AUTONOMY_CONFIG: AutonomyConfig = {\n level: 'proactive',\n autoCheck: {\n enabled: true,\n threshold: 5,\n onCritical: true,\n cooldownMs: 30000, // 30 seconds\n },\n autoFix: {\n enabled: true,\n askFirst: true, // Always ask (human-in-the-loop)\n categories: ['trivial', 'safe'],\n allowedFixTypes: [\n 'remove-console-log',\n 'remove-debugger',\n 'remove-emoji',\n 'remove-unused-import',\n 'add-missing-await',\n 'fix-typo',\n ],\n },\n pushBlocking: {\n enabled: true,\n allowBypass: true,\n blockOn: ['critical'],\n bypassMethods: ['env', 'flag', 'confirm'],\n logBypasses: true,\n },\n progressiveEscalation: {\n enabled: true,\n thresholds: {\n suggest: 1,\n autoCheck: 3,\n escalate: 5,\n block: 10,\n },\n windowMs: 24 * 60 * 60 * 1000, // 24 hours\n },\n aiWatcher: {\n enabled: true,\n hourlyTokenLimit: 50_000,\n scanCooldownSec: 30,\n cleanFileCooldownSec: 300,\n maxFilesPerScan: 5,\n maxCharsPerFile: 4000,\n },\n};\n\n/**\n * Issue occurrence tracking for progressive escalation\n */\nexport interface IssueOccurrence {\n /** Issue hash (file + line + type) */\n hash: string;\n /** First seen timestamp */\n firstSeen: number;\n /** Last seen timestamp */\n lastSeen: number;\n /** Total occurrence count */\n count: number;\n /** Current escalation level */\n escalationLevel: 'suggest' | 'autoCheck' | 'escalate' | 'block';\n /** Whether user has been notified at current level */\n notified: boolean;\n /** Whether issue has been bypassed */\n bypassed: boolean;\n /** Bypass history */\n bypassHistory: Array<{\n timestamp: number;\n method: string;\n reason?: string;\n }>;\n}\n\n/**\n * Auto-fix action\n */\nexport interface AutoFixAction {\n /** Unique ID for this fix */\n id: string;\n /** File to fix */\n file: string;\n /** Line number */\n line?: number;\n /** Original code */\n original: string;\n /** Fixed code */\n fixed: string;\n /** Type of fix */\n type: 'remove-console-log' | 'remove-debugger' | 'remove-emoji' | 'remove-unused-import' | \n 'add-missing-await' | 'fix-typo' | 'goal-violation' | 'custom' | string;\n /** Category of fix */\n category: 'trivial' | 'safe' | 'moderate' | 'risky' | 'goal-violation';\n /** Description of what the fix does */\n description: string;\n /** Confidence in the fix (0-1) */\n confidence: number;\n}\n\n/**\n * Push block result\n */\nexport interface PushBlockResult {\n /** Whether push is blocked */\n blocked: boolean;\n /** Reason for blocking */\n reason?: string;\n /** Issues causing the block */\n blockingIssues: Array<{\n file: string;\n line?: number;\n severity: string;\n issue: string;\n }>;\n /** Bypass instructions */\n bypassInstructions?: string;\n /** Whether user chose to bypass */\n bypassed: boolean;\n /** Bypass method used */\n bypassMethod?: string;\n}\n"],"mappings":";;;;;AAMA,SAAS,UAAU,WAAW,aAAa;AAC3C,SAAS,kBAAkB;AAC3B,SAAS,YAAY;;;ACmHd,IAAM,0BAA0C;AAAA,EACrD,OAAO;AAAA,EACP,WAAW;AAAA,IACT,SAAS;AAAA,IACT,WAAW;AAAA,IACX,YAAY;AAAA,IACZ,YAAY;AAAA;AAAA,EACd;AAAA,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