Coverage for /Users/les/Projects/crackerjack/crackerjack/mcp/tools/intelligence_tools.py: 0%
89 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 asyncio
2import logging
3import typing as t
5from crackerjack.intelligence import ExecutionStrategy, TaskContext
6from crackerjack.intelligence.integration import get_intelligent_agent_system
7from crackerjack.mcp.context import get_context
10async def execute_smart_agent_task(
11 task_description: str,
12 context_type: str = "general",
13 strategy: str = "single_best",
14 max_agents: int = 3,
15 use_learning: bool = True,
16) -> dict[str, t.Any]:
17 get_context()
18 logger = logging.getLogger(__name__)
20 try:
21 task_context = None
22 context_map = {
23 "architecture": TaskContext.ARCHITECTURE,
24 "refactoring": TaskContext.REFACTORING,
25 "testing": TaskContext.TESTING,
26 "security": TaskContext.SECURITY,
27 "performance": TaskContext.PERFORMANCE,
28 "documentation": TaskContext.DOCUMENTATION,
29 "code_quality": TaskContext.CODE_QUALITY,
30 "debugging": TaskContext.DEBUGGING,
31 "project_setup": TaskContext.PROJECT_SETUP,
32 "general": TaskContext.GENERAL,
33 }
35 if context_type.lower() in context_map:
36 task_context = context_map[context_type.lower()]
38 strategy_map = {
39 "single_best": ExecutionStrategy.SINGLE_BEST,
40 "parallel": ExecutionStrategy.PARALLEL,
41 "sequential": ExecutionStrategy.SEQUENTIAL,
42 "consensus": ExecutionStrategy.CONSENSUS,
43 }
45 execution_strategy = strategy_map.get(
46 strategy.lower(), ExecutionStrategy.SINGLE_BEST
47 )
49 system = await get_intelligent_agent_system()
51 logger.info(
52 f"Executing smart task: '{task_description[:50]}...' "
53 f"(context: {context_type}, strategy: {strategy})"
54 )
56 result = await system.execute_smart_task(
57 description=task_description,
58 context=task_context,
59 strategy=execution_strategy,
60 )
62 response = {
63 "success": result.success,
64 "agents_used": result.agents_used,
65 "execution_time": result.execution_time,
66 "confidence": result.confidence,
67 "recommendations": result.recommendations,
68 "learning_applied": result.learning_applied,
69 "task_description": task_description,
70 "context_type": context_type,
71 "strategy_used": strategy,
72 }
74 if hasattr(result.result, "__dict__"):
75 try:
76 if hasattr(result.result, "success"):
77 response["fix_result"] = {
78 "success": getattr(result.result, "success", False),
79 "confidence": getattr(result.result, "confidence", 0.0),
80 "fixes_applied": getattr(result.result, "fixes_applied", []),
81 "remaining_issues": getattr(
82 result.result, "remaining_issues", []
83 ),
84 "recommendations": getattr(
85 result.result, "recommendations", []
86 ),
87 "files_modified": getattr(result.result, "files_modified", []),
88 }
89 else:
90 response["result"] = str(result.result)
91 except Exception:
92 response["result"] = str(result.result)
93 else:
94 response["result"] = result.result
96 if result.success:
97 logger.info(
98 f"Smart task completed successfully using {len(result.agents_used)} agents "
99 f"in {result.execution_time: .2f}s"
100 )
101 else:
102 logger.warning(f"Smart task failed: {result.recommendations}")
104 return response
106 except Exception as e:
107 logger.exception(f"Error in smart agent execution: {e}")
108 return {
109 "success": False,
110 "error": str(e),
111 "task_description": task_description,
112 "context_type": context_type,
113 "strategy_used": strategy,
114 }
117async def get_smart_agent_recommendation(
118 task_description: str,
119 context_type: str = "general",
120 include_analysis: bool = True,
121) -> dict[str, t.Any]:
122 logger = logging.getLogger(__name__)
124 try:
125 task_context = None
126 context_map = {
127 "architecture": TaskContext.ARCHITECTURE,
128 "refactoring": TaskContext.REFACTORING,
129 "testing": TaskContext.TESTING,
130 "security": TaskContext.SECURITY,
131 "performance": TaskContext.PERFORMANCE,
132 "documentation": TaskContext.DOCUMENTATION,
133 "code_quality": TaskContext.CODE_QUALITY,
134 "debugging": TaskContext.DEBUGGING,
135 "project_setup": TaskContext.PROJECT_SETUP,
136 "general": TaskContext.GENERAL,
137 }
139 if context_type.lower() in context_map:
140 task_context = context_map[context_type.lower()]
142 system = await get_intelligent_agent_system()
144 recommendation = await system.get_best_agent_for_task(
145 description=task_description,
146 context=task_context,
147 )
149 response = {
150 "task_description": task_description,
151 "context_type": context_type,
152 }
154 if recommendation:
155 agent_name, confidence = recommendation
156 response.update(
157 {
158 "recommended_agent": agent_name,
159 "confidence": confidence,
160 "has_recommendation": True,
161 }
162 )
163 else:
164 response.update(
165 {
166 "recommended_agent": None,
167 "confidence": 0.0,
168 "has_recommendation": False,
169 "message": "No suitable agent found for this task",
170 }
171 )
173 if include_analysis:
174 try:
175 analysis = await system.analyze_task_complexity(task_description)
176 response["complexity_analysis"] = analysis
177 except Exception as e:
178 logger.warning(f"Failed to analyze task complexity: {e}")
179 response["complexity_analysis"] = {"error": str(e)}
181 logger.debug(f"Generated recommendation for task: {task_description[:50]}...")
182 return response
184 except Exception as e:
185 logger.exception(f"Error getting smart recommendation: {e}")
186 return {
187 "task_description": task_description,
188 "context_type": context_type,
189 "error": str(e),
190 "has_recommendation": False,
191 }
194async def get_intelligence_system_status() -> dict[str, t.Any]:
195 logger = logging.getLogger(__name__)
197 try:
198 system = await get_intelligent_agent_system()
199 status = await system.get_system_status()
201 status["runtime_info"] = {
202 "system_initialized": system._initialized,
203 "components_loaded": {
204 "registry": system.registry is not None,
205 "orchestrator": system.orchestrator is not None,
206 "learning_system": system.learning_system is not None,
207 },
208 }
210 logger.debug("Generated intelligence system status")
211 return status
213 except Exception as e:
214 logger.exception(f"Error getting intelligence system status: {e}")
215 return {
216 "error": str(e),
217 "initialized": False,
218 }
221async def analyze_agent_performance() -> dict[str, t.Any]:
222 logger = logging.getLogger(__name__)
224 try:
225 system = await get_intelligent_agent_system()
226 await system.initialize()
228 learning_summary = system.learning_system.get_learning_summary()
230 orchestration_stats = system.orchestrator.get_execution_stats()
232 registry_stats = system.registry.get_agent_stats()
234 performance_analysis = {
235 "learning_summary": learning_summary,
236 "orchestration_stats": orchestration_stats,
237 "registry_overview": registry_stats,
238 "analysis_timestamp": asyncio.get_event_loop().time(),
239 }
241 if hasattr(system.learning_system, "_learning_insights"):
242 recent_insights = [
243 {
244 "type": insight.insight_type,
245 "agent": insight.agent_name,
246 "confidence": insight.confidence,
247 "description": insight.description,
248 }
249 for insight in system.learning_system._learning_insights[-10:]
250 ]
251 performance_analysis["recent_insights"] = recent_insights
253 logger.debug("Generated agent performance analysis")
254 return performance_analysis
256 except Exception as e:
257 logger.exception(f"Error analyzing agent performance: {e}")
258 return {
259 "error": str(e),
260 "analysis_available": False,
261 }