Coverage for /Users/les/Projects/crackerjack/crackerjack/orchestration/advanced_orchestrator.py: 0%
346 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 time
2import typing as t
3from contextlib import suppress
4from pathlib import Path
6from rich.console import Console, Group
7from rich.panel import Panel
8from rich.table import Table
10from crackerjack.agents import (
11 AgentContext,
12 AgentCoordinator,
13 Issue,
14 IssueType,
15 Priority,
16)
17from crackerjack.config.hooks import HookConfigLoader, HookStrategy
18from crackerjack.core.session_coordinator import SessionCoordinator
19from crackerjack.executors.hook_executor import HookExecutor
20from crackerjack.executors.individual_hook_executor import (
21 HookProgress,
22 IndividualHookExecutor,
23)
24from crackerjack.managers.test_manager import TestManagementImpl
25from crackerjack.models.protocols import OptionsProtocol
26from crackerjack.models.task import HookResult
27from crackerjack.services.metrics import get_metrics_collector
29from .execution_strategies import (
30 AICoordinationMode,
31 ExecutionContext,
32 ExecutionPlan,
33 ExecutionStrategy,
34 OrchestrationConfig,
35 OrchestrationPlanner,
36)
37from .test_progress_streamer import TestProgressStreamer, TestSuiteProgress
40class CorrelationTracker:
41 def __init__(self) -> None:
42 self.iteration_data: list[dict[str, t.Any]] = []
43 self.failure_patterns: dict[str, list[str]] = {}
44 self.fix_success_rates: dict[str, float] = {}
46 def record_iteration(
47 self,
48 iteration: int,
49 hook_results: list[HookResult],
50 test_results: dict[str, t.Any],
51 ai_fixes: list[str],
52 ) -> None:
53 failed_hooks = [r.name for r in hook_results if r.status == "failed"]
55 iteration_data = {
56 "iteration": iteration,
57 "timestamp": time.time(),
58 "failed_hooks": failed_hooks,
59 "test_failures": test_results.get("failed_tests", []),
60 "ai_fixes_applied": ai_fixes,
61 "total_errors": sum(
62 len(getattr(r, "error_details", [])) for r in hook_results
63 ),
64 }
66 self.iteration_data.append(iteration_data)
67 self._analyze_failure_patterns()
69 def _analyze_failure_patterns(self) -> None:
70 if len(self.iteration_data) < 2:
71 return
73 for i in range(1, len(self.iteration_data)):
74 current = self.iteration_data[i]
75 previous = self.iteration_data[i - 1]
77 recurring_failures = set(current["failed_hooks"]) & set(
78 previous["failed_hooks"],
79 )
81 for hook in recurring_failures:
82 if hook not in self.failure_patterns:
83 self.failure_patterns[hook] = []
84 self.failure_patterns[hook].append(f"iteration_{current['iteration']}")
86 def get_problematic_hooks(self) -> list[str]:
87 return [
88 hook
89 for hook, failures in self.failure_patterns.items()
90 if len(failures) >= 2
91 ]
93 def get_correlation_data(self) -> dict[str, t.Any]:
94 return {
95 "iteration_count": len(self.iteration_data),
96 "failure_patterns": self.failure_patterns,
97 "problematic_hooks": self.get_problematic_hooks(),
98 "recent_trends": self.iteration_data[-3:]
99 if len(self.iteration_data) >= 3
100 else self.iteration_data,
101 }
104class MinimalProgressStreamer:
105 def __init__(self) -> None:
106 pass
108 def update_stage(self, stage: str, substage: str = "") -> None:
109 pass
111 def update_hook_progress(self, progress: HookProgress) -> None:
112 pass
114 def _stream_update(self, data: dict[str, t.Any]) -> None:
115 pass
118class ProgressStreamer:
119 def __init__(
120 self,
121 config: OrchestrationConfig,
122 session: SessionCoordinator,
123 ) -> None:
124 self.config = config
125 self.session = session
126 self.current_stage = "initialization"
127 self.current_substage = ""
128 self.hook_progress: dict[str, HookProgress] = {}
130 def update_stage(self, stage: str, substage: str = "") -> None:
131 self.current_stage = stage
132 self.current_substage = substage
133 self._stream_update(
134 {
135 "type": "stage_update",
136 "stage": stage,
137 "substage": substage,
138 "timestamp": time.time(),
139 },
140 )
142 def update_hook_progress(self, progress: HookProgress) -> None:
143 self.hook_progress[progress.hook_name] = progress
144 self._stream_update(
145 {
146 "type": "hook_progress",
147 "hook_name": progress.hook_name,
148 "progress": progress.to_dict(),
149 "timestamp": time.time(),
150 },
151 )
153 def _stream_update(self, update_data: dict[str, t.Any]) -> None:
154 self.session.update_stage(
155 self.current_stage,
156 f"{self.current_substage}: {update_data.get('hook_name', 'processing')}",
157 )
159 if hasattr(self.session, "web_job_id") and self.session.web_job_id:
160 self._update_websocket_progress(update_data)
162 def _update_websocket_progress(self, update_data: dict[str, t.Any]) -> None:
163 with suppress(Exception):
164 if hasattr(self.session, "progress_file") and self.session.progress_file:
165 import json
167 progress_data: dict[str, t.Any] = {}
168 if self.session.progress_file.exists():
169 with self.session.progress_file.open() as f:
170 progress_data = json.load(f)
172 progress_data.update(
173 {
174 "current_stage": self.current_stage,
175 "current_substage": self.current_substage,
176 "hook_progress": {
177 name: prog.to_dict()
178 for name, prog in self.hook_progress.items()
179 },
180 "last_update": update_data,
181 "updated_at": time.time(),
182 },
183 )
185 with self.session.progress_file.open("w") as f:
186 json.dump(progress_data, f, indent=2)
189class AdvancedWorkflowOrchestrator:
190 def __init__(
191 self,
192 console: Console,
193 pkg_path: Path,
194 session: SessionCoordinator,
195 config: OrchestrationConfig | None = None,
196 ) -> None:
197 self.console = console
198 self.pkg_path = pkg_path
199 self.session = session
200 self.config = config or OrchestrationConfig()
202 self.hook_config_loader = HookConfigLoader()
203 self.batch_executor = HookExecutor(console, pkg_path, quiet=True)
204 self.individual_executor = IndividualHookExecutor(console, pkg_path)
205 self.test_manager = TestManagementImpl(console, pkg_path)
206 self.test_streamer = TestProgressStreamer(console, pkg_path)
207 self.planner = OrchestrationPlanner(console)
209 self.correlation_tracker = CorrelationTracker()
210 try:
211 self.progress_streamer = ProgressStreamer(self.config, session)
212 except Exception as e:
213 console.print(
214 f"[yellow]Warning: ProgressStreamer initialization failed: {e}[/ yellow]",
215 )
216 self.progress_streamer = MinimalProgressStreamer()
217 self.metrics = get_metrics_collector()
219 self._detect_and_configure_mcp_mode()
221 self.agent_coordinator: AgentCoordinator | None = None
223 def _detect_and_configure_mcp_mode(self) -> None:
224 is_mcp_mode = (
225 hasattr(self.console.file, "getvalue")
226 or not self.console.is_terminal
227 or hasattr(self.session, "job_id")
228 )
230 if is_mcp_mode:
231 self.individual_executor.set_mcp_mode(True)
232 self.console.print(
233 "[dim]🔧 MCP mode detected-using minimal output mode[/ dim]",
234 )
235 if self.config.ai_coordination_mode in (
236 AICoordinationMode.MULTI_AGENT,
237 AICoordinationMode.COORDINATOR,
238 ):
239 self._initialize_multi_agent_system()
241 self.individual_executor.set_progress_callback(
242 self.progress_streamer.update_hook_progress,
243 )
244 self.test_streamer.set_progress_callback(self._update_test_suite_progress)
246 def _configure_verbose_mode(self, options: OptionsProtocol) -> None:
247 verbose_mode = getattr(options, "verbose", False)
249 if not hasattr(self.console.file, "getvalue"):
250 quiet_mode = not verbose_mode
251 self.individual_executor.set_mcp_mode(quiet_mode)
253 if verbose_mode:
254 self.console.print(
255 "[dim]🔧 Verbose mode enabled-showing detailed hook output[/ dim]",
256 )
258 def _initialize_multi_agent_system(self) -> None:
259 self.console.print(
260 "[bold cyan]🤖 Initializing Multi-Agent AI System[/ bold cyan]",
261 )
263 agent_context = AgentContext(
264 project_path=self.pkg_path,
265 session_id=getattr(self.session, "job_id", None),
266 )
268 self.agent_coordinator = AgentCoordinator(agent_context)
269 self.agent_coordinator.initialize_agents()
271 capabilities = self.agent_coordinator.get_agent_capabilities()
272 self.console.print(
273 f"[green]✅ Initialized {len(capabilities)} specialized agents: [/ green]",
274 )
275 for agent_name, info in capabilities.items():
276 types_str = ", ".join(info["supported_types"])
277 self.console.print(f" • {agent_name}: {types_str}")
279 self.console.print(
280 f"[cyan]AI Coordination Mode: {self.config.ai_coordination_mode.value}[/ cyan]",
281 )
283 def _display_iteration_stats(
284 self,
285 iteration: int,
286 max_iterations: int,
287 iteration_times: dict[str, float],
288 hooks_time: float,
289 tests_time: float,
290 ai_time: float,
291 context: t.Any,
292 ) -> None:
293 timing_table = Table(show_header=True, header_style="bold cyan")
294 timing_table.add_column("Phase", style="cyan")
295 timing_table.add_column("This Iteration", justify="right", style="yellow")
296 timing_table.add_column("Cumulative", justify="right", style="green")
298 timing_table.add_row(
299 "🔧 Hooks",
300 f"{iteration_times.get('hooks', 0): .1f}s",
301 f"{hooks_time: .1f}s",
302 )
303 timing_table.add_row(
304 "🧪 Tests",
305 f"{iteration_times.get('tests', 0): .1f}s",
306 f"{tests_time: .1f}s",
307 )
308 timing_table.add_row(
309 "🤖 AI Analysis",
310 f"{iteration_times.get('ai', 0): .1f}s",
311 f"{ai_time: .1f}s",
312 )
314 total_iteration_time = sum(iteration_times.values())
315 total_cumulative_time = hooks_time + tests_time + ai_time
316 timing_table.add_row(
317 "📊 Total",
318 f"{total_iteration_time: .1f}s",
319 f"{total_cumulative_time: .1f}s",
320 style="bold",
321 )
323 status_table = Table(show_header=True, header_style="bold magenta")
324 status_table.add_column("Metric", style="magenta")
325 status_table.add_column("Value", justify="right", style="white")
327 status_table.add_row("🔄 Iteration", f"{iteration}/{max_iterations}")
328 status_table.add_row(
329 "📈 Progress",
330 f"{(iteration / max_iterations) * 100: .1f}%",
331 )
333 if hasattr(context, "hook_failures"):
334 status_table.add_row("❌ Hook Failures", str(len(context.hook_failures)))
335 if hasattr(context, "test_failures"):
336 status_table.add_row("🧪 Test Failures", str(len(context.test_failures)))
338 panel_content = Group(
339 "[bold white]Timing Breakdown[/ bold white]",
340 timing_table,
341 "",
342 "[bold white]Status Summary[/ bold white]",
343 status_table,
344 )
346 iteration_panel = Panel(
347 panel_content,
348 title=f"[bold bright_blue]📊 Iteration {iteration} Statistics[/ bold bright_blue]",
349 border_style="bright_blue",
350 padding=(1, 2),
351 )
353 self.console.print()
354 self.console.print(iteration_panel)
355 self.console.print()
357 async def execute_orchestrated_workflow(
358 self,
359 options: OptionsProtocol,
360 max_iterations: int = 10,
361 ) -> bool:
362 self._configure_verbose_mode(options)
364 workflow_start_time = time.time()
365 job_id = (
366 getattr(self.session, "job_id", None) or f"orchestration_{int(time.time())}"
367 )
369 self.console.print(
370 "\n[bold bright_blue]🚀 STARTING ORCHESTRATED WORKFLOW[/ bold bright_blue]",
371 )
373 context = ExecutionContext(self.pkg_path, options)
375 hook_strategies = [
376 self.hook_config_loader.load_strategy("fast"),
377 self.hook_config_loader.load_strategy("comprehensive"),
378 ]
380 execution_plan = self.planner.create_execution_plan(
381 self.config,
382 context,
383 hook_strategies,
384 )
386 execution_plan.print_plan_summary(self.console)
388 success = False
389 strategy_switches = 0
390 hooks_time = 0
391 tests_time = 0
392 ai_time = 0
394 for iteration in range(1, max_iterations + 1):
395 self.console.print(
396 f"\n[bold bright_yellow]🔄 ITERATION {iteration} / {max_iterations}[/ bold bright_yellow]",
397 )
399 context.iteration_count = iteration
401 time.time()
402 iteration_success, iteration_times = await self._execute_single_iteration(
403 execution_plan,
404 context,
405 iteration,
406 )
408 hooks_time += iteration_times.get("hooks", 0)
409 tests_time += iteration_times.get("tests", 0)
410 ai_time += iteration_times.get("ai", 0)
412 self._display_iteration_stats(
413 iteration,
414 max_iterations,
415 iteration_times,
416 hooks_time,
417 tests_time,
418 ai_time,
419 context,
420 )
422 if iteration_success:
423 self.console.print(
424 f"\n[bold green]🎉 WORKFLOW COMPLETED SUCCESSFULLY IN {iteration} ITERATIONS ![/ bold green]",
425 )
426 success = True
427 break
429 if iteration < max_iterations:
430 old_strategy = execution_plan.execution_strategy
431 execution_plan = self._adapt_execution_plan(execution_plan, context)
432 if execution_plan.execution_strategy != old_strategy:
433 strategy_switches += 1
435 if not success:
436 self.console.print(
437 f"\n[bold red]❌ WORKFLOW INCOMPLETE AFTER {max_iterations} ITERATIONS[/ bold red]",
438 )
440 self._print_final_analysis()
442 total_time = int((time.time() - workflow_start_time) * 1000)
443 correlation_data = self.correlation_tracker.get_correlation_data()
445 self.metrics.record_orchestration_execution(
446 job_id=job_id,
447 execution_strategy=execution_plan.execution_strategy.value,
448 progress_level=self.config.progress_level.value,
449 ai_mode=self.config.ai_coordination_mode.value,
450 iteration_count=context.iteration_count,
451 strategy_switches=strategy_switches,
452 correlation_insights=correlation_data,
453 total_execution_time_ms=total_time,
454 hooks_execution_time_ms=round(hooks_time * 1000),
455 tests_execution_time_ms=round(tests_time * 1000),
456 ai_analysis_time_ms=round(ai_time * 1000),
457 )
459 return success
461 async def _execute_single_iteration(
462 self,
463 plan: ExecutionPlan,
464 context: ExecutionContext,
465 iteration: int,
466 ) -> tuple[bool, dict[str, float]]:
467 self.progress_streamer.update_stage("iteration_start", f"iteration_{iteration}")
469 phase_times: dict[str, float] = {"hooks": 0.0, "tests": 0.0, "ai": 0.0}
471 hooks_start = time.time()
472 hook_results = await self._execute_hooks_phase(plan, context)
473 phase_times["hooks"] = time.time() - hooks_start
475 tests_start = time.time()
476 test_results = await self._execute_tests_phase(plan, context)
477 phase_times["tests"] = time.time() - tests_start
479 ai_fixes = []
480 if not (
481 all(r.status == "passed" for r in hook_results)
482 and test_results.get("success", False)
483 ):
484 ai_start = time.time()
485 ai_fixes = await self._execute_ai_phase(plan, hook_results, test_results)
486 phase_times["ai"] = time.time() - ai_start
488 job_id = (
489 getattr(self.session, "job_id", None) or f"orchestration_{int(time.time())}"
490 )
491 self.metrics.record_strategy_decision(
492 job_id=job_id,
493 iteration=iteration,
494 previous_strategy=getattr(context, "previous_strategy", None),
495 selected_strategy=plan.execution_strategy.value,
496 decision_reason=f"Iteration {iteration} execution strategy",
497 context_data={
498 "failed_hooks": len([r for r in hook_results if r.status == "failed"]),
499 "failed_tests": len(test_results.get("failed_tests", [])),
500 "ai_fixes_applied": len(ai_fixes),
501 },
502 effectiveness_score=None,
503 )
505 self.correlation_tracker.record_iteration(
506 iteration,
507 hook_results,
508 test_results,
509 ai_fixes,
510 )
512 all_hooks_passed = all(r.status == "passed" for r in hook_results)
513 all_tests_passed = test_results.get("success", False)
515 return all_hooks_passed and all_tests_passed, phase_times
517 async def _execute_hooks_phase(
518 self,
519 plan: ExecutionPlan,
520 context: ExecutionContext,
521 ) -> list[HookResult]:
522 self.progress_streamer.update_stage("hooks", "starting")
524 all_results = []
526 for hook_plan in plan.hook_plans:
527 strategy = hook_plan["strategy"]
528 execution_mode = hook_plan["execution_mode"]
530 if strategy.name == "fast":
531 fast_results = await self._execute_fast_hooks_with_autofix(
532 strategy,
533 execution_mode,
534 context,
535 )
536 all_results.extend(fast_results)
537 else:
538 self.progress_streamer.update_stage(
539 "hooks",
540 f"executing_{strategy.name}",
541 )
543 if execution_mode == ExecutionStrategy.INDIVIDUAL:
544 result = await self.individual_executor.execute_strategy_individual(
545 strategy,
546 )
547 all_results.extend(result.hook_results)
548 else:
549 results = self.batch_executor.execute_strategy(strategy)
550 all_results.extend(results.results)
552 self.progress_streamer.update_stage("hooks", "completed")
553 return all_results
555 async def _execute_fast_hooks_with_autofix(
556 self,
557 strategy: HookStrategy,
558 execution_mode: ExecutionStrategy,
559 context: ExecutionContext,
560 ) -> list[HookResult]:
561 self.progress_streamer.update_stage("hooks", "fast_hooks_with_autofix")
563 max_autofix_cycles = 2
564 autofix_cycle = 0
566 while autofix_cycle < max_autofix_cycles:
567 self.console.print(
568 f"[cyan]🚀 Fast hooks execution (autofix cycle {autofix_cycle + 1}/{max_autofix_cycles})[/ cyan]",
569 )
571 first_attempt = await self._execute_fast_hooks_attempt(
572 strategy,
573 execution_mode,
574 )
576 if all(r.status == "passed" for r in first_attempt):
577 self.console.print(
578 "[green]✅ Fast hooks passed on first attempt[/ green]",
579 )
580 return first_attempt
582 self.console.print(
583 "[yellow]⚠️ Fast hooks failed on first attempt, retrying...[/ yellow]",
584 )
585 second_attempt = await self._execute_fast_hooks_attempt(
586 strategy,
587 execution_mode,
588 )
590 if all(r.status == "passed" for r in second_attempt):
591 self.console.print(
592 "[green]✅ Fast hooks passed on second attempt[/ green]",
593 )
594 return second_attempt
596 autofix_cycle += 1
597 if autofix_cycle < max_autofix_cycles:
598 self.console.print(
599 "[red]❌ Fast hooks failed twice, triggering autofix cycle...[/ red]",
600 )
601 await self._trigger_autofix_for_fast_hooks(second_attempt)
602 else:
603 self.console.print(
604 "[red]❌ Fast hooks failed after maximum autofix cycles[/ red]",
605 )
606 return second_attempt
608 return []
610 async def _execute_fast_hooks_attempt(
611 self,
612 strategy: HookStrategy,
613 execution_mode: ExecutionStrategy,
614 ) -> list[HookResult]:
615 if execution_mode == ExecutionStrategy.INDIVIDUAL:
616 result = await self.individual_executor.execute_strategy_individual(
617 strategy,
618 )
619 return result.hook_results
620 results = self.batch_executor.execute_strategy(strategy)
621 return results.results
623 async def _trigger_autofix_for_fast_hooks(
624 self,
625 failed_results: list[HookResult],
626 ) -> None:
627 self.console.print(
628 "[magenta]🤖 Starting AI autofix cycle for fast hooks...[/ magenta]",
629 )
631 mock_test_results = {
632 "success": True,
633 "failed_tests": [],
634 "individual_tests": [],
635 }
637 from .execution_strategies import ExecutionPlan, ExecutionStrategy
639 mock_plan = ExecutionPlan(
640 config=self.config,
641 execution_strategy=ExecutionStrategy.BATCH,
642 hook_plans=[],
643 test_plan={"mode": "full_suite", "estimated_duration": 0},
644 ai_plan={
645 "mode": self.config.ai_coordination_mode,
646 "intelligence_level": self.config.ai_intelligence,
647 "batch_processing": True,
648 "correlation_tracking": self.config.correlation_tracking,
649 "failure_analysis": self.config.failure_analysis,
650 "adaptive_retry": self.config.intelligent_retry,
651 },
652 estimated_total_duration=0,
653 )
655 ai_fixes = await self._execute_ai_phase(
656 mock_plan,
657 failed_results,
658 mock_test_results,
659 )
661 if ai_fixes:
662 self.console.print(
663 f"[green]✅ Applied {len(ai_fixes)} AI fixes for fast hooks[/ green]",
664 )
665 else:
666 self.console.print("[yellow]⚠️ No AI fixes could be applied[/ yellow]")
668 async def _execute_tests_phase(
669 self,
670 plan: ExecutionPlan,
671 context: ExecutionContext,
672 ) -> dict[str, t.Any]:
673 self.progress_streamer.update_stage("tests", "starting")
675 test_mode = plan.test_plan.get("mode", "full_suite")
677 if test_mode in ("individual_with_progress", "selective"):
678 test_results = await self.test_streamer.run_tests_with_streaming(
679 context.options,
680 test_mode,
681 )
683 job_id = (
684 getattr(self.session, "job_id", None)
685 or f"orchestration_{int(time.time())}"
686 )
687 individual_tests = test_results.get("individual_tests", [])
689 for test in individual_tests:
690 self.metrics.record_individual_test(
691 job_id=job_id,
692 test_id=test.test_id,
693 test_file=test.test_file,
694 test_class=test.test_class,
695 test_method=test.test_method,
696 status=test.status,
697 execution_time_ms=int((test.duration or 0) * 1000),
698 error_message=test.error_message,
699 error_traceback=test.failure_traceback,
700 )
701 else:
702 test_success = self.test_manager.run_tests(context.options)
703 test_results = {
704 "success": test_success,
705 "failed_tests": [],
706 "suite_progress": None,
707 "individual_tests": [],
708 }
710 self.progress_streamer.update_stage("tests", "completed")
711 return test_results
713 def _update_test_suite_progress(self, suite_progress: TestSuiteProgress) -> None:
714 current_test = suite_progress.current_test or "running tests"
715 self.progress_streamer.update_stage(
716 "tests",
717 f"{suite_progress.completed_tests} / {suite_progress.total_tests}-{current_test}",
718 )
720 async def _execute_ai_phase(
721 self,
722 plan: ExecutionPlan,
723 hook_results: list[HookResult],
724 test_results: dict[str, t.Any],
725 ) -> list[str]:
726 self.progress_streamer.update_stage("ai_analysis", "analyzing_failures")
728 failed_hooks = [r for r in hook_results if r.status == "failed"]
729 failed_tests = test_results.get("failed_tests", [])
731 individual_tests = test_results.get("individual_tests", [])
732 failed_individual_tests = [t for t in individual_tests if t.status == "failed"]
734 correlation_data = self.correlation_tracker.get_correlation_data()
736 self.console.print("\n[bold magenta]🤖 AI ANALYSIS PHASE[/ bold magenta]")
737 self.console.print(f"AI Mode: {self.config.ai_coordination_mode.value}")
738 self.console.print(f"Failed hooks: {len(failed_hooks)}")
739 self.console.print(f"Failed tests: {len(failed_tests)}")
741 if failed_individual_tests:
742 self.console.print(
743 f"Individual test failures: {len(failed_individual_tests)}",
744 )
745 for test in failed_individual_tests[:3]:
746 self.console.print(f" ❌ {test.test_id}")
748 if correlation_data["problematic_hooks"]:
749 self.console.print(
750 f"Problematic hooks (recurring): {', '.join(correlation_data['problematic_hooks'])}",
751 )
753 if self.agent_coordinator and self.config.ai_coordination_mode in (
754 AICoordinationMode.MULTI_AGENT,
755 AICoordinationMode.COORDINATOR,
756 ):
757 ai_fixes = await self._execute_multi_agent_analysis(
758 failed_hooks,
759 failed_tests,
760 failed_individual_tests,
761 correlation_data,
762 )
763 else:
764 ai_fixes = await self._execute_single_agent_analysis(
765 failed_hooks,
766 failed_tests,
767 failed_individual_tests,
768 correlation_data,
769 )
771 self.progress_streamer.update_stage("ai_analysis", "completed")
772 return ai_fixes
774 async def _execute_multi_agent_analysis(
775 self,
776 failed_hooks: list[HookResult],
777 failed_tests: list[str],
778 failed_individual_tests: list[t.Any],
779 correlation_data: dict[str, t.Any],
780 ) -> list[str]:
781 self.console.print("[bold cyan]🤖 Multi-Agent Analysis Started[/ bold cyan]")
783 issues = []
785 for hook_result in failed_hooks:
786 issue_type = self._map_hook_to_issue_type(hook_result.name)
787 issue = Issue(
788 id=f"hook_{hook_result.name}_{hash(str(hook_result.issues_found))}",
789 type=issue_type,
790 severity=Priority.HIGH
791 if hook_result.name in correlation_data.get("problematic_hooks", [])
792 else Priority.MEDIUM,
793 message=(
794 hook_result.issues_found[0]
795 if hook_result.issues_found
796 else f"{hook_result.name} failed"
797 ),
798 stage="hooks",
799 details=getattr(hook_result, "error_details", []),
800 )
801 issues.append(issue)
803 for test_failure in failed_individual_tests:
804 issue = Issue(
805 id=f"test_{test_failure.test_id}",
806 type=IssueType.TEST_FAILURE,
807 severity=Priority.HIGH,
808 message=test_failure.error_message
809 or f"Test failed: {test_failure.test_id}",
810 file_path=getattr(test_failure, "test_file", None),
811 stage="tests",
812 details=[test_failure.failure_traceback]
813 if hasattr(test_failure, "failure_traceback")
814 else [],
815 )
816 issues.append(issue)
818 if not issues:
819 return ["No issues identified for multi-agent analysis"]
821 self.console.print(
822 f"[cyan]Processing {len(issues)} issues with specialized agents...[/ cyan]",
823 )
825 assert self.agent_coordinator is not None
827 result = await self.agent_coordinator.handle_issues_proactively(issues)
829 ai_fixes = []
830 if result.fixes_applied:
831 ai_fixes.extend(result.fixes_applied)
832 else:
833 ai_fixes.append(
834 f"Multi-agent analysis completed with {result.confidence: .2f} confidence",
835 )
837 if result.remaining_issues:
838 ai_fixes.append(f"Remaining issues: {len(result.remaining_issues)}")
840 if result.recommendations:
841 ai_fixes.extend(
842 [f"Recommendation: {rec}" for rec in result.recommendations[:3]],
843 )
845 self.console.print(
846 f"[green]✅ Multi-agent analysis completed: {len(result.fixes_applied)} fixes applied[/ green]",
847 )
848 return ai_fixes
850 async def _execute_single_agent_analysis(
851 self,
852 failed_hooks: list[HookResult],
853 failed_tests: list[str],
854 failed_individual_tests: list[t.Any],
855 correlation_data: dict[str, t.Any],
856 ) -> list[str]:
857 return [
858 f"[Single Agent] Analyzed {len(failed_hooks)} hook failures",
859 f"[Single Agent] Analyzed {len(failed_tests)} test failures",
860 f"[Single Agent] Analyzed {len(failed_individual_tests)} individual test failures",
861 "[Single Agent] Applied batch fixes based on correlation analysis",
862 ]
864 def _map_hook_to_issue_type(self, hook_name: str) -> IssueType:
865 hook_type_mapping = {
866 "ruff-format": IssueType.FORMATTING,
867 "ruff-check": IssueType.FORMATTING,
868 "pyright": IssueType.TYPE_ERROR,
869 "bandit": IssueType.SECURITY,
870 "vulture": IssueType.DEAD_CODE,
871 "refurb": IssueType.COMPLEXITY,
872 "creosote": IssueType.DEPENDENCY,
873 "gitleaks": IssueType.SECURITY,
874 "trailing-whitespace": IssueType.FORMATTING,
875 "end-of-file-fixer": IssueType.FORMATTING,
876 }
878 return hook_type_mapping.get(hook_name) or IssueType.FORMATTING
880 def _adapt_execution_plan(
881 self,
882 current_plan: ExecutionPlan,
883 context: ExecutionContext,
884 ) -> ExecutionPlan:
885 problematic_hooks = self.correlation_tracker.get_problematic_hooks()
887 if problematic_hooks:
888 self.console.print(
889 f"[yellow]🧠 Adapting strategy due to recurring failures in: {', '.join(problematic_hooks)}[/ yellow]",
890 )
892 if current_plan.execution_strategy == ExecutionStrategy.BATCH:
893 self.config.execution_strategy = ExecutionStrategy.INDIVIDUAL
894 self.console.print(
895 "[cyan]📋 Switching to individual execution for better debugging[/ cyan]",
896 )
898 hook_strategies = [
899 self.hook_config_loader.load_strategy("fast"),
900 self.hook_config_loader.load_strategy("comprehensive"),
901 ]
903 return self.planner.create_execution_plan(self.config, context, hook_strategies)
905 def _print_final_analysis(self) -> None:
906 correlation_data = self.correlation_tracker.get_correlation_data()
908 if correlation_data["iteration_count"] == 0:
909 return
911 self.console.print("\n" + "=" * 80)
912 self.console.print(
913 "[bold bright_magenta]🔍 CORRELATION ANALYSIS[/ bold bright_magenta]",
914 )
915 self.console.print("=" * 80)
917 self.console.print(f"Total iterations: {correlation_data['iteration_count']}")
919 if correlation_data["problematic_hooks"]:
920 self.console.print(
921 "\n[bold red]Problematic hooks (recurring failures): [/ bold red]",
922 )
923 for hook in correlation_data["problematic_hooks"]:
924 failures = correlation_data["failure_patterns"][hook]
925 self.console.print(f" ❌ {hook}-failed in {len(failures)} iterations")
927 if correlation_data["recent_trends"]:
928 self.console.print("\n[bold yellow]Recent trends: [/ bold yellow]")
929 for trend in correlation_data["recent_trends"][-2:]:
930 failed_count = len(trend["failed_hooks"])
931 self.console.print(
932 f" Iteration {trend['iteration']}: {failed_count} failed hooks, "
933 f"{trend['total_errors']} total errors",
934 )
936 self.console.print("=" * 80)