Coverage for /Users/les/Projects/crackerjack/crackerjack/core/proactive_workflow.py: 0%
123 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 time
3import typing as t
4from pathlib import Path
6from ..agents.base import AgentContext, Issue, IssueType, Priority
7from ..agents.coordinator import AgentCoordinator
8from ..models.protocols import OptionsProtocol
11class ProactiveWorkflowPipeline:
12 def __init__(self, project_path: Path) -> None:
13 self.project_path = project_path
14 self.logger = logging.getLogger(__name__)
15 self._architect_agent_coordinator: AgentCoordinator | None = None
17 async def run_complete_workflow_with_planning(
18 self, options: OptionsProtocol
19 ) -> bool:
20 self.logger.info("Starting proactive workflow with architectural planning")
22 start_time = time.time()
24 try:
25 assessment = await self._assess_codebase_architecture()
27 if assessment.needs_planning:
28 self.logger.info("Codebase requires architectural planning")
30 architectural_plan = await self._create_comprehensive_plan(assessment)
32 result = await self._execute_planned_workflow(
33 options, architectural_plan
34 )
35 else:
36 self.logger.info(
37 "Codebase is architecturally sound, using standard workflow"
38 )
40 result = await self._execute_standard_workflow(options)
42 execution_time = time.time() - start_time
43 self.logger.info(f"Proactive workflow completed in {execution_time: .2f}s")
45 return result
47 except Exception as e:
48 self.logger.exception(f"Proactive workflow failed: {e}")
50 return await self._execute_standard_workflow(options)
52 async def _assess_codebase_architecture(self) -> "ArchitecturalAssessment":
53 self.logger.info("Assessing codebase architecture...")
55 if not self._architect_agent_coordinator:
56 agent_context = AgentContext(project_path=self.project_path)
57 self._architect_agent_coordinator = AgentCoordinator(agent_context)
58 self._architect_agent_coordinator.initialize_agents()
60 test_issues = await self._identify_potential_issues()
62 needs_planning = self._evaluate_planning_need(test_issues)
64 return ArchitecturalAssessment(
65 needs_planning=needs_planning,
66 complexity_score=len(test_issues),
67 potential_issues=test_issues,
68 recommended_strategy="proactive" if needs_planning else "standard",
69 )
71 async def _identify_potential_issues(self) -> list[Issue]:
72 potential_issues = []
74 potential_issues.extend(
75 (
76 Issue(
77 id="arch_assessment_complexity",
78 type=IssueType.COMPLEXITY,
79 severity=Priority.HIGH,
80 message="Potential complexity hotspots detected",
81 file_path=str(self.project_path),
82 details=["Multiple functions may exceed complexity threshold"],
83 ),
84 Issue(
85 id="arch_assessment_dry",
86 type=IssueType.DRY_VIOLATION,
87 severity=Priority.MEDIUM,
88 message="Potential code duplication patterns",
89 file_path=str(self.project_path),
90 details=["Similar patterns may exist across modules"],
91 ),
92 )
93 )
95 return potential_issues
97 def _evaluate_planning_need(self, issues: list[Issue]) -> bool:
98 complex_issues = [
99 issue
100 for issue in issues
101 if issue.type
102 in {IssueType.COMPLEXITY, IssueType.DRY_VIOLATION, IssueType.PERFORMANCE}
103 ]
105 return len(complex_issues) >= 2
107 async def _create_comprehensive_plan(
108 self, assessment: "ArchitecturalAssessment"
109 ) -> dict[str, t.Any]:
110 self.logger.info("Creating comprehensive architectural plan...")
112 assert self._architect_agent_coordinator is not None
114 architect = self._architect_agent_coordinator._get_architect_agent()
116 if not architect:
117 self.logger.warning("No ArchitectAgent available, creating basic plan")
118 return {
119 "strategy": "basic_reactive",
120 "phases": ["standard_workflow"],
121 "patterns": ["default"],
122 }
124 complex_issues = [
125 issue
126 for issue in assessment.potential_issues
127 if issue.type in {IssueType.COMPLEXITY, IssueType.DRY_VIOLATION}
128 ]
130 if complex_issues:
131 primary_issue = complex_issues[0]
132 base_plan = await architect.plan_before_action(primary_issue)
134 comprehensive_plan = base_plan | {
135 "phases": [
136 "configuration_setup",
137 "fast_hooks_with_architecture",
138 "architectural_refactoring",
139 "comprehensive_validation",
140 "pattern_learning",
141 ],
142 "integration_points": [
143 "architect_guided_fixing",
144 "pattern_caching",
145 "validation_against_plan",
146 ],
147 }
148 else:
149 comprehensive_plan = {
150 "strategy": "lightweight_proactive",
151 "phases": ["standard_workflow_enhanced"],
152 "patterns": ["cached_patterns"],
153 }
155 self.logger.info(
156 f"Created plan with strategy: {comprehensive_plan.get('strategy')}"
157 )
158 return comprehensive_plan
160 async def _execute_planned_workflow(
161 self, options: OptionsProtocol, plan: dict[str, t.Any]
162 ) -> bool:
163 strategy = plan.get("strategy", "basic_reactive")
164 phases = plan.get("phases", ["standard_workflow"])
166 self.logger.info(f"Executing {strategy} workflow with {len(phases)} phases")
168 for phase in phases:
169 success = await self._execute_workflow_phase(phase, options, plan)
170 if not success and phase in (
171 "configuration_setup",
172 "architectural_refactoring",
173 ):
174 self.logger.error(f"Critical phase {phase} failed")
175 return False
176 elif not success:
177 self.logger.warning(f"Phase {phase} had issues but continuing")
179 return True
181 async def _execute_workflow_phase(
182 self, phase: str, options: OptionsProtocol, plan: dict[str, t.Any]
183 ) -> bool:
184 self.logger.info(f"Executing phase: {phase}")
186 if phase == "configuration_setup":
187 return await self._setup_with_architecture(options, plan)
188 elif phase == "fast_hooks_with_architecture":
189 return await self._run_fast_hooks_with_planning(options, plan)
190 elif phase == "architectural_refactoring":
191 return await self._perform_architectural_refactoring(options, plan)
192 elif phase == "comprehensive_validation":
193 return await self._comprehensive_validation(options, plan)
194 elif phase == "pattern_learning":
195 return await self._learn_and_cache_patterns(plan)
197 return await self._execute_standard_workflow(options)
199 async def _setup_with_architecture(
200 self, options: OptionsProtocol, plan: dict[str, t.Any]
201 ) -> bool:
202 self.logger.info("Setting up project with architectural planning")
204 return True
206 async def _run_fast_hooks_with_planning(
207 self, options: OptionsProtocol, plan: dict[str, t.Any]
208 ) -> bool:
209 self.logger.info("Running fast hooks with architectural planning")
211 return True
213 async def _perform_architectural_refactoring(
214 self, options: OptionsProtocol, plan: dict[str, t.Any]
215 ) -> bool:
216 self.logger.info("Performing architectural refactoring")
218 if self._architect_agent_coordinator:
219 architect = self._architect_agent_coordinator._get_architect_agent()
220 if architect:
221 patterns = plan.get("patterns", [])
222 self.logger.info(f"Applying architectural patterns: {patterns}")
223 return True
225 return True
227 async def _comprehensive_validation(
228 self, options: OptionsProtocol, plan: dict[str, t.Any]
229 ) -> bool:
230 self.logger.info("Performing comprehensive validation")
231 validation_steps = plan.get("validation", [])
233 for step in validation_steps:
234 self.logger.info(f"Validating: {step}")
236 return True
238 async def _learn_and_cache_patterns(self, plan: dict[str, t.Any]) -> bool:
239 self.logger.info("Learning and caching successful patterns")
241 if self._architect_agent_coordinator:
242 architect = self._architect_agent_coordinator._get_architect_agent()
243 if architect and hasattr(architect, "get_cached_patterns"):
244 cached_patterns = architect.get_cached_patterns()
245 self.logger.info(f"Cached {len(cached_patterns)} patterns")
247 return True
249 async def _execute_standard_workflow(self, options: OptionsProtocol) -> bool:
250 self.logger.info("Executing standard workflow (fallback)")
252 return True
255class ArchitecturalAssessment:
256 def __init__(
257 self,
258 needs_planning: bool,
259 complexity_score: int,
260 potential_issues: list[Issue],
261 recommended_strategy: str,
262 ) -> None:
263 self.needs_planning = needs_planning
264 self.complexity_score = complexity_score
265 self.potential_issues = potential_issues
266 self.recommended_strategy = recommended_strategy