Coverage for /Users/les/Projects/crackerjack/crackerjack/agents/base.py: 0%
101 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 typing as t
3from abc import ABC, abstractmethod
4from dataclasses import dataclass, field
5from enum import Enum
6from pathlib import Path
9class Priority(Enum):
10 LOW = "low"
11 MEDIUM = "medium"
12 HIGH = "high"
13 CRITICAL = "critical"
16class IssueType(Enum):
17 FORMATTING = "formatting"
18 TYPE_ERROR = "type_error"
19 SECURITY = "security"
20 TEST_FAILURE = "test_failure"
21 IMPORT_ERROR = "import_error"
22 COMPLEXITY = "complexity"
23 DEAD_CODE = "dead_code"
24 DEPENDENCY = "dependency"
25 DRY_VIOLATION = "dry_violation"
26 PERFORMANCE = "performance"
27 DOCUMENTATION = "documentation"
28 TEST_ORGANIZATION = "test_organization"
29 COVERAGE_IMPROVEMENT = "coverage_improvement"
32@dataclass
33class Issue:
34 id: str
35 type: IssueType
36 severity: Priority
37 message: str
38 file_path: str | None = None
39 line_number: int | None = None
40 details: list[str] = field(default_factory=list)
41 stage: str = "unknown"
43 @property
44 def context_key(self) -> str:
45 return f"{self.type.value}: {self.file_path}: {self.line_number}"
48@dataclass
49class FixResult:
50 success: bool
51 confidence: float
52 fixes_applied: list[str] = field(default_factory=list)
53 remaining_issues: list[str] = field(default_factory=list)
54 recommendations: list[str] = field(default_factory=list)
55 files_modified: list[str] = field(default_factory=list)
57 def merge_with(self, other: "FixResult") -> "FixResult":
58 return FixResult(
59 success=self.success and other.success,
60 confidence=max(self.confidence, other.confidence),
61 fixes_applied=self.fixes_applied + other.fixes_applied,
62 remaining_issues=list(set(self.remaining_issues + other.remaining_issues)),
63 recommendations=self.recommendations + other.recommendations,
64 files_modified=list(set(self.files_modified + other.files_modified)),
65 )
68@dataclass
69class AgentContext:
70 project_path: Path
71 temp_dir: Path | None = None
72 config: dict[str, t.Any] = field(default_factory=dict)
73 session_id: str | None = None
75 subprocess_timeout: int = 300
76 max_file_size: int = 10_000_000
78 def get_file_content(self, file_path: str | Path) -> str | None:
79 try:
80 path = Path(file_path)
81 if not path.is_file():
82 return None
83 if path.stat().st_size > self.max_file_size:
84 return None
85 return path.read_text(encoding="utf-8")
86 except Exception:
87 return None
89 def write_file_content(self, file_path: str | Path, content: str) -> bool:
90 try:
91 path = Path(file_path)
92 path.write_text(content, encoding="utf-8")
93 return True
94 except Exception:
95 return False
98class SubAgent(ABC):
99 def __init__(self, context: AgentContext) -> None:
100 self.context = context
101 self.name = self.__class__.__name__
103 @abstractmethod
104 async def can_handle(self, issue: Issue) -> float:
105 pass
107 @abstractmethod
108 async def analyze_and_fix(self, issue: Issue) -> FixResult:
109 pass
111 @abstractmethod
112 def get_supported_types(self) -> set[IssueType]:
113 pass
115 async def run_command(
116 self,
117 cmd: list[str],
118 cwd: Path | None = None,
119 timeout: int | None = None,
120 ) -> tuple[int, str, str]:
121 try:
122 process = await asyncio.create_subprocess_exec(
123 *cmd,
124 cwd=cwd or self.context.project_path,
125 stdout=asyncio.subprocess.PIPE,
126 stderr=asyncio.subprocess.PIPE,
127 )
129 stdout, stderr = await asyncio.wait_for(
130 process.communicate(),
131 timeout=timeout or self.context.subprocess_timeout,
132 )
134 return (
135 process.returncode or 0,
136 stdout.decode() if stdout else "",
137 stderr.decode() if stderr else "",
138 )
139 except TimeoutError:
140 return (-1, "", "Command timed out")
141 except Exception as e:
142 return (-1, "", f"Command failed: {e}")
144 def log(self, message: str, level: str = "INFO") -> None:
145 pass
147 async def plan_before_action(self, issue: Issue) -> dict[str, t.Any]:
148 return {"strategy": "default", "confidence": 0.5}
150 def get_cached_patterns(self) -> dict[str, t.Any]:
151 return {}
154class AgentRegistry:
155 def __init__(self) -> None:
156 self._agents: dict[str, type[SubAgent]] = {}
158 def register(self, agent_class: type[SubAgent]) -> None:
159 self._agents[agent_class.__name__] = agent_class
161 def create_all(self, context: AgentContext) -> list[SubAgent]:
162 return [agent_cls(context) for agent_cls in self._agents.values()]
164 def get_by_name(self, name: str) -> type[SubAgent] | None:
165 return self._agents.get(name)
168agent_registry = AgentRegistry()