Coverage for /Users/les/Projects/crackerjack/crackerjack/intelligence/agent_selector.py: 0%
215 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 re
3import typing as t
4from dataclasses import dataclass
5from enum import Enum
7from .agent_registry import (
8 AgentCapability,
9 AgentRegistry,
10 RegisteredAgent,
11 get_agent_registry,
12)
15class TaskContext(Enum):
16 CODE_QUALITY = "code_quality"
17 ARCHITECTURE = "architecture"
18 TESTING = "testing"
19 REFACTORING = "refactoring"
20 DOCUMENTATION = "documentation"
21 SECURITY = "security"
22 PERFORMANCE = "performance"
23 DEBUGGING = "debugging"
24 PROJECT_SETUP = "project_setup"
25 GENERAL = "general"
28@dataclass
29class TaskDescription:
30 description: str
31 context: TaskContext | None = None
32 keywords: list[str] | None = None
33 file_patterns: list[str] | None = None
34 error_types: list[str] | None = None
35 priority: int = 50
38@dataclass
39class AgentScore:
40 agent: RegisteredAgent
41 base_score: float
42 context_score: float
43 priority_bonus: float
44 confidence_factor: float
45 final_score: float
46 reasoning: str
49class AgentSelector:
50 def __init__(self, registry: AgentRegistry | None = None) -> None:
51 self.logger = logging.getLogger(__name__)
52 self.registry = registry
53 self._task_patterns: dict[str, list[AgentCapability]] = {}
54 self._initialize_task_patterns()
56 def _initialize_task_patterns(self) -> None:
57 self._task_patterns = {
58 r"architect | design | structure | pattern | refactor.* complex": [
59 AgentCapability.ARCHITECTURE,
60 AgentCapability.REFACTORING,
61 ],
62 r"refurb | ruff | format | lint | style | clean.* code": [
63 AgentCapability.FORMATTING,
64 AgentCapability.CODE_ANALYSIS,
65 ],
66 r"test | pytest | coverage | mock | fixture": [
67 AgentCapability.TESTING,
68 ],
69 r"security | vulnerability | audit | bandit | safe": [
70 AgentCapability.SECURITY,
71 ],
72 r"performance | optimize | speed | efficient | complexity": [
73 AgentCapability.PERFORMANCE,
74 AgentCapability.CODE_ANALYSIS,
75 ],
76 r"document | readme | comment | explain | changelog": [
77 AgentCapability.DOCUMENTATION,
78 ],
79 r"refactor | improve | simplify | dry.* violation": [
80 AgentCapability.REFACTORING,
81 AgentCapability.CODE_ANALYSIS,
82 ],
83 r"debug | fix | error | bug | failure": [
84 AgentCapability.DEBUGGING,
85 AgentCapability.CODE_ANALYSIS,
86 ],
87 }
89 async def get_registry(self) -> AgentRegistry:
90 if self.registry is None:
91 self.registry = await get_agent_registry()
92 return self.registry
94 async def select_best_agent(
95 self,
96 task: TaskDescription,
97 max_candidates: int = 5,
98 ) -> AgentScore | None:
99 candidates = await self.select_agents(task, max_candidates)
100 return candidates[0] if candidates else None
102 async def select_agents(
103 self,
104 task: TaskDescription,
105 max_candidates: int = 3,
106 ) -> list[AgentScore]:
107 registry = await self.get_registry()
109 required_capabilities = self._analyze_task_capabilities(task)
111 scores: list[AgentScore] = []
113 for agent in registry.list_all_agents():
114 score = await self._score_agent_for_task(agent, task, required_capabilities)
115 if score.final_score > 0.1:
116 scores.append(score)
118 scores.sort(key=lambda s: s.final_score, reverse=True)
120 selected = scores[:max_candidates]
122 self.logger.debug(
123 f"Selected {len(selected)} agents for task '{task.description[:50]}...': "
124 f"{[f'{s.agent.metadata.name}({s.final_score: .2f})' for s in selected]}"
125 )
127 return selected
129 def _analyze_task_capabilities(self, task: TaskDescription) -> set[AgentCapability]:
130 capabilities = set()
132 capabilities.update(self._analyze_text_patterns(task))
133 capabilities.update(self._analyze_context(task))
134 capabilities.update(self._analyze_file_patterns(task))
135 capabilities.update(self._analyze_error_types(task))
137 return capabilities or {AgentCapability.CODE_ANALYSIS}
139 def _analyze_text_patterns(self, task: TaskDescription) -> set[AgentCapability]:
140 text = task.description.lower()
141 if task.keywords:
142 text += " " + " ".join(task.keywords).lower()
144 capabilities = set()
145 for pattern, caps in self._task_patterns.items():
146 if re.search(pattern, text, re.IGNORECASE):
147 capabilities.update(caps)
149 return capabilities
151 def _analyze_context(self, task: TaskDescription) -> set[AgentCapability]:
152 if not task.context:
153 return set()
155 context_map = {
156 TaskContext.CODE_QUALITY: [
157 AgentCapability.CODE_ANALYSIS,
158 AgentCapability.FORMATTING,
159 ],
160 TaskContext.ARCHITECTURE: [
161 AgentCapability.ARCHITECTURE,
162 AgentCapability.CODE_ANALYSIS,
163 ],
164 TaskContext.TESTING: [AgentCapability.TESTING],
165 TaskContext.REFACTORING: [
166 AgentCapability.REFACTORING,
167 AgentCapability.CODE_ANALYSIS,
168 ],
169 TaskContext.DOCUMENTATION: [AgentCapability.DOCUMENTATION],
170 TaskContext.SECURITY: [AgentCapability.SECURITY],
171 TaskContext.PERFORMANCE: [
172 AgentCapability.PERFORMANCE,
173 AgentCapability.CODE_ANALYSIS,
174 ],
175 TaskContext.DEBUGGING: [
176 AgentCapability.DEBUGGING,
177 AgentCapability.CODE_ANALYSIS,
178 ],
179 TaskContext.PROJECT_SETUP: [AgentCapability.PROJECT_MANAGEMENT],
180 TaskContext.GENERAL: [AgentCapability.CODE_ANALYSIS],
181 }
183 return set(context_map.get(task.context, []))
185 def _analyze_file_patterns(self, task: TaskDescription) -> set[AgentCapability]:
186 if not task.file_patterns:
187 return set()
189 capabilities = set()
190 for pattern in task.file_patterns:
191 pattern_lower = pattern.lower()
192 if any(ext in pattern_lower for ext in (".py", ".pyi")):
193 capabilities.add(AgentCapability.CODE_ANALYSIS)
194 if any(test in pattern_lower for test in ("test_", "_test", "tests /")):
195 capabilities.add(AgentCapability.TESTING)
197 return capabilities
199 def _analyze_error_types(self, task: TaskDescription) -> set[AgentCapability]:
200 if not task.error_types:
201 return set()
203 capabilities = set()
204 for error_type in task.error_types:
205 error_lower = error_type.lower()
206 if "furb" in error_lower or "refurb" in error_lower:
207 capabilities.update(
208 [AgentCapability.REFACTORING, AgentCapability.CODE_ANALYSIS]
209 )
210 elif "test" in error_lower:
211 capabilities.add(AgentCapability.TESTING)
212 elif "type" in error_lower or "pyright" in error_lower:
213 capabilities.add(AgentCapability.CODE_ANALYSIS)
214 elif "security" in error_lower or "bandit" in error_lower:
215 capabilities.add(AgentCapability.SECURITY)
217 return capabilities
219 async def _score_agent_for_task(
220 self,
221 agent: RegisteredAgent,
222 task: TaskDescription,
223 required_capabilities: set[AgentCapability],
224 ) -> AgentScore:
225 agent_capabilities = agent.metadata.capabilities
226 overlap = len(required_capabilities & agent_capabilities)
227 max_overlap = len(required_capabilities)
229 base_score = overlap / max_overlap if max_overlap > 0 else 0.0
231 context_score = self._calculate_context_score(agent, task)
233 priority_bonus = min(agent.metadata.priority / 100.0, 1.0)
235 confidence_factor = agent.metadata.confidence_factor
237 weights = {
238 "base": 0.4,
239 "context": 0.3,
240 "priority": 0.2,
241 "bonus": 0.1,
242 }
244 weighted_score = (
245 base_score * weights["base"]
246 + context_score * weights["context"]
247 + priority_bonus * weights["priority"]
248 )
250 final_score = weighted_score * confidence_factor
252 reasoning = self._generate_score_reasoning(
253 agent, base_score, context_score, priority_bonus, required_capabilities
254 )
256 return AgentScore(
257 agent=agent,
258 base_score=base_score,
259 context_score=context_score,
260 priority_bonus=priority_bonus,
261 confidence_factor=confidence_factor,
262 final_score=final_score,
263 reasoning=reasoning,
264 )
266 def _calculate_context_score(
267 self, agent: RegisteredAgent, task: TaskDescription
268 ) -> float:
269 score = 0.0
271 agent_name_lower = agent.metadata.name.lower()
272 task_text = task.description.lower()
274 score += self._score_name_matches(agent_name_lower, task_text)
275 score += self._score_description_matches(agent, task_text)
276 score += self._score_keyword_matches(agent, task)
277 score += self._score_special_patterns(agent_name_lower, task_text)
279 return min(score, 1.0)
281 def _score_name_matches(self, agent_name_lower: str, task_text: str) -> float:
282 if any(keyword in agent_name_lower for keyword in task_text.split()):
283 return 0.3
284 return 0.0
286 def _score_description_matches(
287 self, agent: RegisteredAgent, task_text: str
288 ) -> float:
289 if not agent.metadata.description:
290 return 0.0
292 desc_words = set(agent.metadata.description.lower().split())
293 task_words = set(task_text.split())
294 common_words = desc_words & task_words
296 if common_words:
297 return len(common_words) / max(len(task_words), 1) * 0.2
298 return 0.0
300 def _score_keyword_matches(
301 self, agent: RegisteredAgent, task: TaskDescription
302 ) -> float:
303 if not task.keywords or not agent.metadata.tags:
304 return 0.0
306 task_keywords = {k.lower() for k in task.keywords}
307 agent_tags = {t.lower() for t in agent.metadata.tags}
308 overlap = len(task_keywords & agent_tags)
310 if overlap > 0:
311 return overlap / len(task_keywords) * 0.3
312 return 0.0
314 def _score_special_patterns(self, agent_name_lower: str, task_text: str) -> float:
315 score = 0.0
317 if "architect" in agent_name_lower and (
318 "architect" in task_text or "design" in task_text
319 ):
320 score += 0.2
321 if "refactor" in agent_name_lower and "refurb" in task_text:
322 score += 0.2
323 if "test" in agent_name_lower and "test" in task_text:
324 score += 0.2
326 return score
328 def _generate_score_reasoning(
329 self,
330 agent: RegisteredAgent,
331 base_score: float,
332 context_score: float,
333 priority_bonus: float,
334 required_capabilities: set[AgentCapability],
335 ) -> str:
336 parts = []
338 overlap = len(required_capabilities & agent.metadata.capabilities)
339 parts.append(f"Capabilities: {overlap}/{len(required_capabilities)} match")
341 if context_score > 0.5:
342 parts.append("High context relevance")
343 elif context_score > 0.2:
344 parts.append("Moderate context relevance")
345 else:
346 parts.append("Low context relevance")
348 source_desc = {
349 "crackerjack": "Built-in specialist",
350 "user": "User agent",
351 "system": "System agent",
352 }
353 parts.append(source_desc.get(agent.metadata.source.value, "Unknown source"))
355 if agent.metadata.capabilities:
356 top_caps = list(agent.metadata.capabilities)[:2]
357 cap_names = [cap.value.replace("_", " ") for cap in top_caps]
358 parts.append(f"Strengths: {', '.join(cap_names)}")
360 return " | ".join(parts)
362 async def analyze_task_complexity(self, task: TaskDescription) -> dict[str, t.Any]:
363 registry = await self.get_registry()
364 required_capabilities = self._analyze_task_capabilities(task)
366 all_scores = []
367 for agent in registry.list_all_agents():
368 score = await self._score_agent_for_task(agent, task, required_capabilities)
369 if score.final_score > 0.1:
370 all_scores.append(score)
372 all_scores.sort(key=lambda s: s.final_score, reverse=True)
374 analysis = {
375 "required_capabilities": [cap.value for cap in required_capabilities],
376 "complexity_level": self._assess_complexity(
377 required_capabilities, all_scores
378 ),
379 "candidate_count": len(all_scores),
380 "top_agents": [
381 {
382 "name": score.agent.metadata.name,
383 "source": score.agent.metadata.source.value,
384 "score": score.final_score,
385 "reasoning": score.reasoning,
386 }
387 for score in all_scores[:5]
388 ],
389 "recommendations": self._generate_recommendations(
390 required_capabilities, all_scores
391 ),
392 }
394 return analysis
396 def _assess_complexity(
397 self, capabilities: set[AgentCapability], scores: list[AgentScore]
398 ) -> str:
399 if len(capabilities) >= 4:
400 return "high"
401 elif len(capabilities) >= 2:
402 return "medium"
403 elif not scores or scores[0].final_score < 0.3:
404 return "high"
406 return "low"
408 def _generate_recommendations(
409 self,
410 capabilities: set[AgentCapability],
411 scores: list[AgentScore],
412 ) -> list[str]:
413 recommendations = []
415 if not scores:
416 recommendations.append("No suitable agents found-consider manual approach")
417 return recommendations
419 top_score = scores[0].final_score
421 if top_score > 0.8:
422 recommendations.append(
423 "Excellent agent match found-high confidence execution"
424 )
425 elif top_score > 0.6:
426 recommendations.append("Good agent match-should handle task well")
427 elif top_score > 0.4:
428 recommendations.append("Moderate match-may need supervision")
429 else:
430 recommendations.append("Weak matches-consider alternative approaches")
432 if len(capabilities) > 2:
433 recommendations.append("Consider multi-agent approach for complex task")
435 sources = {score.agent.metadata.source for score in scores[:3]}
436 if len(sources) > 1:
437 recommendations.append("Multiple agent sources available for redundancy")
439 return recommendations