Coverage for /Users/les/Projects/crackerjack/crackerjack/agents/coordinator.py: 0%
257 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 operator
4import typing as t
5from collections import defaultdict
7from crackerjack.services.debug import get_ai_agent_debugger
9from .base import (
10 AgentContext,
11 FixResult,
12 Issue,
13 IssueType,
14 Priority,
15 SubAgent,
16 agent_registry,
17)
18from .tracker import get_agent_tracker
21class AgentCoordinator:
22 def __init__(self, context: AgentContext) -> None:
23 self.context = context
24 self.agents: list[SubAgent] = []
25 self.logger = logging.getLogger(__name__)
26 self._issue_cache: dict[str, FixResult] = {}
27 self._collaboration_threshold = 0.7
28 self.tracker = get_agent_tracker()
29 self.debugger = get_ai_agent_debugger()
30 self.proactive_mode = True
32 def initialize_agents(self) -> None:
33 self.agents = agent_registry.create_all(self.context)
34 agent_types = [a.name for a in self.agents]
35 self.logger.info(f"Initialized {len(self.agents)} agents: {agent_types}")
37 self.tracker.register_agents(agent_types)
38 self.tracker.set_coordinator_status("active")
40 self.debugger.log_agent_activity(
41 agent_name="coordinator",
42 activity="agents_initialized",
43 metadata={"agent_count": len(self.agents), "agent_types": agent_types},
44 )
46 async def handle_issues(self, issues: list[Issue]) -> FixResult:
47 if not self.agents:
48 self.initialize_agents()
50 if not issues:
51 return FixResult(success=True, confidence=1.0)
53 self.logger.info(f"Handling {len(issues)} issues")
55 issues_by_type = self._group_issues_by_type(issues)
57 overall_result = FixResult(success=True, confidence=1.0)
59 for issue_type, type_issues in issues_by_type.items():
60 type_result = await self._handle_issues_by_type(issue_type, type_issues)
61 overall_result = overall_result.merge_with(type_result)
63 return overall_result
65 async def handle_single_issue(self, issue: Issue) -> FixResult:
66 if not self.agents:
67 self.initialize_agents()
69 cache_key = issue.context_key
70 if cache_key in self._issue_cache:
71 cached_result = self._issue_cache[cache_key]
72 self.logger.info(f"Using cached result for {cache_key}")
73 self.tracker.track_cache_hit()
74 return cached_result
76 self.tracker.track_cache_miss()
78 agent_scores = await self._evaluate_agents_for_issue(issue)
80 if not agent_scores:
81 self.logger.warning(f"No agents can handle issue: {issue.message}")
82 return FixResult(
83 success=False,
84 confidence=0.0,
85 remaining_issues=[f"No agent available for: {issue.message}"],
86 recommendations=["Manual intervention required"],
87 )
89 best_agent, best_score = agent_scores[0]
91 if best_score >= self._collaboration_threshold:
92 result = await self._handle_with_single_agent(best_agent, issue)
93 else:
94 result = await self._handle_with_collaboration(agent_scores[:3], issue)
96 self._issue_cache[cache_key] = result
98 return result
100 async def _handle_issues_by_type(
101 self,
102 issue_type: IssueType,
103 issues: list[Issue],
104 ) -> FixResult:
105 self.logger.info(f"Handling {len(issues)} {issue_type.value} issues")
107 specialist_agents = [
108 agent for agent in self.agents if issue_type in agent.get_supported_types()
109 ]
111 if not specialist_agents:
112 self.logger.warning(f"No specialist agents for {issue_type.value}")
113 return FixResult(
114 success=False,
115 confidence=0.0,
116 remaining_issues=[f"No agents for {issue_type.value} issues"],
117 )
119 tasks: list[t.Coroutine[t.Any, t.Any, FixResult]] = []
120 for issue in issues:
121 best_specialist = await self._find_best_specialist(specialist_agents, issue)
122 if best_specialist:
123 task = self._handle_with_single_agent(best_specialist, issue)
124 tasks.append(task)
126 if not tasks:
127 return FixResult(success=False, confidence=0.0)
129 results = await asyncio.gather(*tasks, return_exceptions=True)
131 combined_result = FixResult(success=True, confidence=1.0)
132 for result in results:
133 if isinstance(result, FixResult):
134 combined_result = combined_result.merge_with(result)
135 else:
136 self.logger.error(f"Agent task failed: {result}")
137 combined_result.success = False
138 combined_result.remaining_issues.append(f"Agent failed: {result}")
140 return combined_result
142 async def _evaluate_agents_for_issue(
143 self,
144 issue: Issue,
145 ) -> list[tuple[SubAgent, float]]:
146 evaluations: list[tuple[SubAgent, float]] = []
148 for agent in self.agents:
149 try:
150 confidence = await agent.can_handle(issue)
151 if confidence > 0.0:
152 evaluations.append((agent, confidence))
153 except Exception as e:
154 self.logger.exception(f"Error evaluating {agent.name} for issue: {e}")
156 evaluations.sort(key=operator.itemgetter(1), reverse=True)
157 return evaluations
159 async def _find_best_specialist(
160 self,
161 specialists: list[SubAgent],
162 issue: Issue,
163 ) -> SubAgent | None:
164 best_agent = None
165 best_score = 0.0
167 for agent in specialists:
168 try:
169 score = await agent.can_handle(issue)
170 if score > best_score:
171 best_score = score
172 best_agent = agent
173 except Exception as e:
174 self.logger.exception(f"Error evaluating specialist {agent.name}: {e}")
176 return best_agent
178 async def _handle_with_single_agent(
179 self,
180 agent: SubAgent,
181 issue: Issue,
182 ) -> FixResult:
183 self.logger.info(f"Handling issue with {agent.name}: {issue.message[:100]}")
185 confidence = await agent.can_handle(issue)
186 self.tracker.track_agent_processing(agent.name, issue, confidence)
188 self.debugger.log_agent_activity(
189 agent_name=agent.name,
190 activity="processing_started",
191 issue_id=issue.id,
192 confidence=confidence,
193 metadata={"issue_type": issue.type.value, "severity": issue.severity.value},
194 )
196 try:
197 result = await agent.analyze_and_fix(issue)
198 if result.success:
199 self.logger.info(f"{agent.name} successfully fixed issue")
200 else:
201 self.logger.warning(f"{agent.name} failed to fix issue")
203 self.tracker.track_agent_complete(agent.name, result)
205 self.debugger.log_agent_activity(
206 agent_name=agent.name,
207 activity="processing_completed",
208 issue_id=issue.id,
209 confidence=result.confidence,
210 result={
211 "success": result.success,
212 "remaining_issues": len(result.remaining_issues),
213 },
214 metadata={"fix_applied": result.success},
215 )
217 return result
218 except Exception as e:
219 self.logger.exception(f"{agent.name} threw exception: {e}")
220 error_result = FixResult(
221 success=False,
222 confidence=0.0,
223 remaining_issues=[f"{agent.name} failed with exception: {e}"],
224 )
226 self.tracker.track_agent_complete(agent.name, error_result)
227 return error_result
229 async def _handle_with_collaboration(
230 self,
231 agent_scores: list[tuple[SubAgent, float]],
232 issue: Issue,
233 ) -> FixResult:
234 self.logger.info(
235 f"Using collaborative approach for issue: {issue.message[:100]}",
236 )
238 results: list[FixResult] = []
240 for agent, _ in agent_scores:
241 try:
242 result = await agent.analyze_and_fix(issue)
243 results.append(result)
245 if result.success and result.confidence >= 0.8:
246 self.logger.info(f"{agent.name} solved issue with high confidence")
247 break
249 except Exception as e:
250 self.logger.exception(f"Collaborative agent {agent.name} failed: {e}")
251 results.append(
252 FixResult(
253 success=False,
254 confidence=0.0,
255 remaining_issues=[f"{agent.name} failed: {e}"],
256 ),
257 )
259 if not results:
260 return FixResult(success=False, confidence=0.0)
262 combined_result = results[0]
263 for result in results[1:]:
264 combined_result = combined_result.merge_with(result)
266 return combined_result
268 def _group_issues_by_type(
269 self,
270 issues: list[Issue],
271 ) -> dict[IssueType, list[Issue]]:
272 grouped: defaultdict[IssueType, list[Issue]] = defaultdict(list)
273 for issue in issues:
274 grouped[issue.type].append(issue)
275 return dict(grouped)
277 def get_agent_capabilities(self) -> dict[str, dict[str, t.Any]]:
278 if not self.agents:
279 self.initialize_agents()
281 capabilities = {}
282 for agent in self.agents:
283 capabilities[agent.name] = {
284 "supported_types": [t.value for t in agent.get_supported_types()],
285 "class": agent.__class__.__name__,
286 }
287 return capabilities
289 def clear_cache(self) -> None:
290 self._issue_cache.clear()
291 self.logger.info("Cleared issue cache")
293 async def test_agent_connectivity(self) -> dict[str, bool]:
294 if not self.agents:
295 self.initialize_agents()
297 test_issue = Issue(
298 id="test",
299 type=IssueType.FORMATTING,
300 severity=Priority.LOW,
301 message="Test connectivity",
302 )
304 connectivity = {}
305 for agent in self.agents:
306 try:
307 confidence = await agent.can_handle(test_issue)
308 connectivity[agent.name] = confidence >= 0.0
309 except Exception as e:
310 self.logger.exception(f"Connectivity test failed for {agent.name}: {e}")
311 connectivity[agent.name] = False
313 return connectivity
315 async def handle_issues_proactively(self, issues: list[Issue]) -> FixResult:
316 if not self.proactive_mode:
317 return await self.handle_issues(issues)
319 if not self.agents:
320 self.initialize_agents()
322 if not issues:
323 return FixResult(success=True, confidence=1.0)
325 self.logger.info(f"Handling {len(issues)} issues with proactive planning")
327 architectural_plan = await self._create_architectural_plan(issues)
329 overall_result = await self._apply_fixes_with_plan(issues, architectural_plan)
331 validation_result = await self._validate_against_plan(
332 overall_result, architectural_plan
333 )
335 return validation_result
337 async def _create_architectural_plan(self, issues: list[Issue]) -> dict[str, t.Any]:
338 architect = self._get_architect_agent()
340 if not architect:
341 self.logger.warning("No ArchitectAgent available for planning")
342 return {"strategy": "reactive_fallback", "patterns": []}
344 complex_issues = [
345 issue
346 for issue in issues
347 if issue.type
348 in {IssueType.COMPLEXITY, IssueType.DRY_VIOLATION, IssueType.PERFORMANCE}
349 ]
351 if not complex_issues:
352 return {"strategy": "simple_fixes", "patterns": ["standard_patterns"]}
354 primary_issue = complex_issues[0]
356 try:
357 plan = await architect.plan_before_action(primary_issue)
359 plan["all_issues"] = [issue.id for issue in issues]
360 plan["issue_types"] = list({issue.type.value for issue in issues})
362 self.logger.info(
363 f"Created architectural plan: {plan.get('strategy', 'unknown')}"
364 )
365 return plan
367 except Exception as e:
368 self.logger.exception(f"Failed to create architectural plan: {e}")
369 return {"strategy": "reactive_fallback", "patterns": [], "error": str(e)}
371 async def _apply_fixes_with_plan(
372 self, issues: list[Issue], plan: dict[str, t.Any]
373 ) -> FixResult:
374 strategy = plan.get("strategy", "reactive_fallback")
376 if strategy == "reactive_fallback":
377 return await self.handle_issues(issues)
379 self.logger.info(f"Applying fixes with {strategy} strategy")
381 prioritized_issues = self._prioritize_issues_by_plan(issues, plan)
383 overall_result = FixResult(success=True, confidence=1.0)
385 for issue_group in prioritized_issues:
386 group_result = await self._handle_issue_group_with_plan(issue_group, plan)
387 overall_result = overall_result.merge_with(group_result)
389 if not group_result.success and self._is_critical_group(issue_group, plan):
390 overall_result.success = False
391 overall_result.remaining_issues.append(
392 f"Critical issue group failed: {[i.id for i in issue_group]}"
393 )
395 return overall_result
397 async def _validate_against_plan(
398 self, result: FixResult, plan: dict[str, t.Any]
399 ) -> FixResult:
400 validation_steps = plan.get("validation", [])
402 if not validation_steps:
403 return result
405 self.logger.info(f"Validating against plan: {validation_steps}")
407 result.recommendations.extend(
408 [
409 f"Validate with: {', '.join(validation_steps)}",
410 f"Applied strategy: {plan.get('strategy', 'unknown')}",
411 f"Used patterns: {', '.join(plan.get('patterns', []))}",
412 ]
413 )
415 return result
417 def _get_architect_agent(self) -> SubAgent | None:
418 for agent in self.agents:
419 if agent.__class__.__name__ == "ArchitectAgent":
420 return agent
421 return None
423 def _prioritize_issues_by_plan(
424 self, issues: list[Issue], plan: dict[str, t.Any]
425 ) -> list[list[Issue]]:
426 strategy = plan.get("strategy", "reactive_fallback")
428 if strategy == "external_specialist_guided":
429 complex_issues = [
430 issue
431 for issue in issues
432 if issue.type in {IssueType.COMPLEXITY, IssueType.DRY_VIOLATION}
433 ]
434 other_issues = [issue for issue in issues if issue not in complex_issues]
435 return [complex_issues, other_issues] if complex_issues else [other_issues]
437 groups = self._group_issues_by_type(issues)
438 return list(groups.values())
440 async def _handle_issue_group_with_plan(
441 self, issues: list[Issue], plan: dict[str, t.Any]
442 ) -> FixResult:
443 if not issues:
444 return FixResult(success=True, confidence=1.0)
446 representative_issue = issues[0]
448 if self._should_use_architect_for_group(issues, plan):
449 architect = self._get_architect_agent()
450 if architect:
451 group_result = FixResult(success=True, confidence=1.0)
453 for issue in issues:
454 issue_result = await architect.analyze_and_fix(issue)
455 group_result = group_result.merge_with(issue_result)
457 return group_result
459 return await self._handle_issues_by_type(representative_issue.type, issues)
461 def _should_use_architect_for_group(
462 self, issues: list[Issue], plan: dict[str, t.Any]
463 ) -> bool:
464 strategy = plan.get("strategy", "")
466 if strategy == "external_specialist_guided":
467 return True
469 architectural_types = {
470 IssueType.COMPLEXITY,
471 IssueType.DRY_VIOLATION,
472 IssueType.PERFORMANCE,
473 }
475 return any(issue.type in architectural_types for issue in issues)
477 def _is_critical_group(self, issues: list[Issue], plan: dict[str, t.Any]) -> bool:
478 critical_types = {IssueType.COMPLEXITY, IssueType.DRY_VIOLATION}
479 return any(issue.type in critical_types for issue in issues)
481 def set_proactive_mode(self, enabled: bool) -> None:
482 self.proactive_mode = enabled
483 self.logger.info(f"Proactive mode {'enabled' if enabled else 'disabled'}")