Coverage for /Users/les/Projects/crackerjack/crackerjack/intelligence/integration.py: 0%
96 statements
« prev ^ index » next coverage.py v7.10.6, created at 2025-09-03 15:39 -0700
« prev ^ index » next coverage.py v7.10.6, created at 2025-09-03 15:39 -0700
1import logging
2import typing as t
3from dataclasses import dataclass
5from crackerjack.agents.base import AgentContext, FixResult, Issue
7from .adaptive_learning import get_learning_system
8from .agent_orchestrator import (
9 ExecutionRequest,
10 ExecutionStrategy,
11 get_agent_orchestrator,
12)
13from .agent_registry import get_agent_registry
14from .agent_selector import TaskContext, TaskDescription
17@dataclass
18class SmartAgentResult:
19 success: bool
20 result: t.Any
21 agents_used: list[str]
22 execution_time: float
23 confidence: float
24 recommendations: list[str]
25 learning_applied: bool = False
28class IntelligentAgentSystem:
29 def __init__(self) -> None:
30 self.logger = logging.getLogger(__name__)
31 self._initialized = False
33 async def initialize(self) -> None:
34 if self._initialized:
35 return
37 self.logger.info("Initializing Intelligent Agent System")
39 self.registry = await get_agent_registry()
40 self.orchestrator = await get_agent_orchestrator()
41 self.learning_system = await get_learning_system()
43 self._initialized = True
45 stats = self.registry.get_agent_stats()
46 self.logger.info(
47 f"System initialized: {stats['total_agents']} agents available "
48 f"({stats['by_source']})"
49 )
51 async def execute_smart_task(
52 self,
53 description: str,
54 context: TaskContext | None = None,
55 strategy: ExecutionStrategy = ExecutionStrategy.SINGLE_BEST,
56 context_data: AgentContext | None = None,
57 ) -> SmartAgentResult:
58 await self.initialize()
60 task = TaskDescription(
61 description=description,
62 context=context,
63 )
65 candidates = await self.orchestrator.selector.select_agents(
66 task, max_candidates=5
67 )
68 candidate_names = [c.agent.metadata.name for c in candidates]
70 learning_recommendations = self.learning_system.get_agent_recommendations(
71 task, candidate_names
72 )
74 for candidate in candidates:
75 agent_name = candidate.agent.metadata.name
76 if agent_name in learning_recommendations:
77 learning_boost = learning_recommendations[agent_name] * 0.2
78 candidate.final_score = min(1.0, candidate.final_score + learning_boost)
80 candidates.sort(key=lambda c: c.final_score, reverse=True)
82 request = ExecutionRequest(
83 task=task,
84 strategy=strategy,
85 max_agents=min(3, len(candidates)),
86 context=context_data,
87 )
89 result = await self.orchestrator.execute(request)
91 if candidates:
92 best_candidate = candidates[0]
93 await self.learning_system.record_execution(
94 agent=best_candidate.agent,
95 task=task,
96 success=result.success,
97 execution_time=result.execution_time,
98 agent_score=best_candidate,
99 error_message=result.error_message,
100 )
102 return SmartAgentResult(
103 success=result.success,
104 result=result.primary_result,
105 agents_used=result.agents_used,
106 execution_time=result.execution_time,
107 confidence=candidates[0].final_score if candidates else 0.0,
108 recommendations=result.recommendations or [],
109 learning_applied=bool(learning_recommendations),
110 )
112 async def handle_crackerjack_issue(
113 self,
114 issue: Issue,
115 context: AgentContext,
116 use_learning: bool = True,
117 ) -> FixResult:
118 await self.initialize()
120 task_context = self._map_issue_to_task_context(issue)
122 task = TaskDescription(
123 description=f"Fix {issue.type.value} issue: {issue.message}",
124 context=task_context,
125 error_types=[issue.type.value],
126 priority=self._map_severity_to_priority(issue.severity),
127 )
129 smart_result = await self.execute_smart_task(
130 description=task.description,
131 context=task_context,
132 context_data=context,
133 )
135 if smart_result.success and isinstance(smart_result.result, FixResult):
136 return smart_result.result
138 return FixResult(
139 success=smart_result.success,
140 confidence=smart_result.confidence,
141 remaining_issues=[issue.message] if not smart_result.success else [],
142 recommendations=smart_result.recommendations,
143 fixes_applied=[
144 f"Applied using intelligent agent: {', '.join(smart_result.agents_used)}"
145 ]
146 if smart_result.success
147 else [],
148 )
150 async def get_best_agent_for_task(
151 self,
152 description: str,
153 context: TaskContext | None = None,
154 ) -> tuple[str, float] | None:
155 await self.initialize()
157 task = TaskDescription(description=description, context=context)
158 best_candidate = await self.orchestrator.selector.select_best_agent(task)
160 if best_candidate:
161 return best_candidate.agent.metadata.name, best_candidate.final_score
162 return None
164 async def analyze_task_complexity(self, description: str) -> dict[str, t.Any]:
165 await self.initialize()
167 task = TaskDescription(description=description)
168 return await self.orchestrator.selector.analyze_task_complexity(task)
170 def _map_issue_to_task_context(self, issue: Issue) -> TaskContext | None:
171 from crackerjack.agents.base import IssueType
173 mapping = {
174 IssueType.COMPLEXITY: TaskContext.REFACTORING,
175 IssueType.DRY_VIOLATION: TaskContext.REFACTORING,
176 IssueType.PERFORMANCE: TaskContext.PERFORMANCE,
177 IssueType.SECURITY: TaskContext.SECURITY,
178 IssueType.TEST_FAILURE: TaskContext.TESTING,
179 IssueType.FORMATTING: TaskContext.CODE_QUALITY,
180 IssueType.IMPORT_ERROR: TaskContext.CODE_QUALITY,
181 IssueType.TYPE_ERROR: TaskContext.CODE_QUALITY,
182 IssueType.DOCUMENTATION: TaskContext.DOCUMENTATION,
183 IssueType.DEAD_CODE: TaskContext.REFACTORING,
184 IssueType.DEPENDENCY: TaskContext.CODE_QUALITY,
185 IssueType.TEST_ORGANIZATION: TaskContext.TESTING,
186 }
188 return mapping.get(issue.type) or TaskContext.GENERAL
190 def _map_severity_to_priority(self, severity: t.Any) -> int:
191 from crackerjack.agents.base import Priority
193 mapping = {
194 Priority.HIGH: 90,
195 Priority.MEDIUM: 60,
196 Priority.LOW: 30,
197 }
199 return mapping.get(severity) or 50
201 async def get_system_status(self) -> dict[str, t.Any]:
202 await self.initialize()
204 registry_stats = self.registry.get_agent_stats()
205 orchestrator_stats = self.orchestrator.get_execution_stats()
206 learning_summary = self.learning_system.get_learning_summary()
208 return {
209 "initialized": self._initialized,
210 "registry": registry_stats,
211 "orchestration": orchestrator_stats,
212 "learning": learning_summary,
213 }
216_intelligent_system_instance: IntelligentAgentSystem | None = None
219async def get_intelligent_agent_system() -> IntelligentAgentSystem:
220 global _intelligent_system_instance
222 if _intelligent_system_instance is None:
223 _intelligent_system_instance = IntelligentAgentSystem()
225 return _intelligent_system_instance
228async def smart_fix_issue(
229 issue: Issue,
230 context: AgentContext,
231) -> FixResult:
232 system = await get_intelligent_agent_system()
233 return await system.handle_crackerjack_issue(issue, context)
236async def smart_execute_task(
237 description: str,
238 context: TaskContext | None = None,
239 strategy: ExecutionStrategy = ExecutionStrategy.SINGLE_BEST,
240) -> SmartAgentResult:
241 system = await get_intelligent_agent_system()
242 return await system.execute_smart_task(description, context, strategy)
245async def get_smart_recommendation(
246 description: str,
247 context: TaskContext | None = None,
248) -> tuple[str, float] | None:
249 system = await get_intelligent_agent_system()
250 return await system.get_best_agent_for_task(description, context)