Coverage for /Users/les/Projects/crackerjack/crackerjack/core/async_workflow_orchestrator.py: 0%
335 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 time
4import typing as t
5from pathlib import Path
7from rich.console import Console
9from crackerjack.agents.base import FixResult, Issue, IssueType, Priority
10from crackerjack.models.protocols import OptionsProtocol
12from .phase_coordinator import PhaseCoordinator
13from .session_coordinator import SessionCoordinator
14from .timeout_manager import TimeoutStrategy, get_timeout_manager
17class AsyncWorkflowPipeline:
18 def __init__(
19 self,
20 console: Console,
21 pkg_path: Path,
22 session: SessionCoordinator,
23 phases: PhaseCoordinator,
24 ) -> None:
25 self.console = console
26 self.pkg_path = pkg_path
27 self.session = session
28 self.phases = phases
29 self.logger = logging.getLogger("crackerjack.async_pipeline")
30 self.timeout_manager = get_timeout_manager()
32 async def run_complete_workflow_async(self, options: OptionsProtocol) -> bool:
33 start_time = time.time()
34 self.session.initialize_session_tracking(options)
35 self.session.track_task("workflow", "Complete async crackerjack workflow")
37 try:
38 async with self.timeout_manager.timeout_context(
39 "complete_workflow", strategy=TimeoutStrategy.GRACEFUL_DEGRADATION
40 ):
41 if hasattr(options, "ai_agent") and options.ai_agent:
42 success = await self._execute_ai_agent_workflow_async(options)
43 else:
44 success = await self._execute_workflow_phases_async(options)
45 self.session.finalize_session(start_time, success)
46 return success
47 except KeyboardInterrupt:
48 self.console.print("Interrupted by user")
49 self.session.fail_task("workflow", "Interrupted by user")
50 return False
51 except Exception as e:
52 self.console.print(f"Error: {e}")
53 self.session.fail_task("workflow", f"Unexpected error: {e}")
54 return False
55 finally:
56 self.session.cleanup_resources()
58 async def _execute_workflow_phases_async(self, options: OptionsProtocol) -> bool:
59 success = True
61 self.phases.run_configuration_phase(options)
63 if not await self._execute_cleaning_phase_async(options):
64 success = False
66 self.session.fail_task("workflow", "Cleaning phase failed")
67 return False
69 if not await self._execute_quality_phase_async(options):
70 success = False
72 return False
74 if not self.phases.run_publishing_phase(options):
75 success = False
76 self.session.fail_task("workflow", "Publishing failed")
77 return False
79 if not self.phases.run_commit_phase(options):
80 success = False
82 return success
84 async def _cleanup_active_tasks(self) -> None:
85 """Clean up all active tasks."""
86 if not self._active_tasks:
87 return
89 self.logger.info(f"Cleaning up {len(self._active_tasks)} active tasks")
91 # Cancel all active tasks
92 for task in self._active_tasks:
93 if not task.done():
94 task.cancel()
96 # Wait for tasks to complete with timeout
97 if self._active_tasks:
98 try:
99 await asyncio.wait_for(
100 asyncio.gather(*self._active_tasks, return_exceptions=True),
101 timeout=30.0,
102 )
103 except TimeoutError:
104 self.logger.warning("Timeout waiting for task cleanup")
106 self._active_tasks.clear()
108 async def _execute_cleaning_phase_async(self, options: OptionsProtocol) -> bool:
109 if not options.clean:
110 return True
112 return await self.timeout_manager.with_timeout(
113 "file_operations",
114 asyncio.to_thread(self.phases.run_cleaning_phase, options),
115 strategy=TimeoutStrategy.RETRY_WITH_BACKOFF,
116 )
118 async def _execute_quality_phase_async(self, options: OptionsProtocol) -> bool:
119 if hasattr(options, "fast") and options.fast:
120 return await self._run_fast_hooks_async(options)
121 if hasattr(options, "comp") and options.comp:
122 return await self._run_comprehensive_hooks_async(options)
123 if options.test:
124 return await self._execute_test_workflow_async(options)
125 return await self._execute_standard_hooks_workflow_async(options)
127 async def _execute_test_workflow_async(self, options: OptionsProtocol) -> bool:
128 overall_success = True
130 # Fast hooks with timeout
131 if not await self._run_fast_hooks_async(options):
132 overall_success = False
133 self.session.fail_task("workflow", "Fast hooks failed")
134 return False
136 # Run tests and comprehensive hooks in parallel with proper timeout handling
137 try:
138 # Create tasks with individual timeout handling
139 test_task = asyncio.create_task(
140 self.timeout_manager.with_timeout(
141 "test_execution",
142 self._run_testing_phase_async(options),
143 strategy=TimeoutStrategy.GRACEFUL_DEGRADATION,
144 )
145 )
146 hooks_task = asyncio.create_task(
147 self.timeout_manager.with_timeout(
148 "comprehensive_hooks",
149 self._run_comprehensive_hooks_async(options),
150 strategy=TimeoutStrategy.GRACEFUL_DEGRADATION,
151 )
152 )
154 # Use asyncio.wait with timeout for the gather operation
155 done, pending = await asyncio.wait(
156 [test_task, hooks_task],
157 timeout=self.timeout_manager.get_timeout("test_execution")
158 + self.timeout_manager.get_timeout("comprehensive_hooks")
159 + 60, # Extra buffer
160 return_when=asyncio.ALL_COMPLETED,
161 )
163 # Cancel any pending tasks
164 for task in pending:
165 task.cancel()
166 try:
167 await task
168 except asyncio.CancelledError:
169 pass
171 # Process results
172 test_success = hooks_success = False
173 for task in done:
174 try:
175 result = await task
176 if task == test_task:
177 test_success = result
178 elif task == hooks_task:
179 hooks_success = result
180 except Exception as e:
181 self.logger.error(f"Task execution error: {e}")
182 if task == test_task:
183 test_success = False
184 elif task == hooks_task:
185 hooks_success = False
187 if not test_success:
188 overall_success = False
189 self.session.fail_task("workflow", "Testing failed")
190 return False
192 if not hooks_success:
193 overall_success = False
194 self.session.fail_task("workflow", "Comprehensive hooks failed")
195 return False
197 return overall_success
199 except Exception as e:
200 self.logger.error(f"Test workflow execution error: {e}")
201 self.session.fail_task("workflow", f"Test workflow error: {e}")
202 return False
204 async def _execute_standard_hooks_workflow_async(
205 self,
206 options: OptionsProtocol,
207 ) -> bool:
208 hooks_success = await self._run_hooks_phase_async(options)
209 if not hooks_success:
210 self.session.fail_task("workflow", "Hooks failed")
211 return False
212 return True
214 async def _create_managed_task(
215 self,
216 coro: t.Awaitable[t.Any],
217 timeout: float = 300.0,
218 task_name: str = "workflow_task",
219 ) -> asyncio.Task:
220 """Create a managed task with automatic cleanup."""
221 task = asyncio.create_task(coro, name=task_name)
223 if self.resource_context:
224 self.resource_context.managed_task(task, timeout)
226 self._active_tasks.append(task)
227 return task
229 async def _run_fast_hooks_async(self, options: OptionsProtocol) -> bool:
230 return await self.timeout_manager.with_timeout(
231 "fast_hooks",
232 asyncio.to_thread(self.phases.run_fast_hooks_only, options),
233 strategy=TimeoutStrategy.RETRY_WITH_BACKOFF,
234 )
236 async def _run_comprehensive_hooks_async(self, options: OptionsProtocol) -> bool:
237 return await self.timeout_manager.with_timeout(
238 "comprehensive_hooks",
239 asyncio.to_thread(self.phases.run_comprehensive_hooks_only, options),
240 strategy=TimeoutStrategy.GRACEFUL_DEGRADATION,
241 )
243 async def _run_hooks_phase_async(self, options: OptionsProtocol) -> bool:
244 return await self.timeout_manager.with_timeout(
245 "comprehensive_hooks",
246 asyncio.to_thread(self.phases.run_hooks_phase, options),
247 strategy=TimeoutStrategy.GRACEFUL_DEGRADATION,
248 )
250 async def _run_testing_phase_async(self, options: OptionsProtocol) -> bool:
251 return await self.timeout_manager.with_timeout(
252 "test_execution",
253 asyncio.to_thread(self.phases.run_testing_phase, options),
254 strategy=TimeoutStrategy.GRACEFUL_DEGRADATION,
255 )
257 async def _execute_ai_agent_workflow_async(
258 self, options: OptionsProtocol, max_iterations: int = 10
259 ) -> bool:
260 self.console.print(
261 f"🤖 Starting AI Agent workflow (max {max_iterations} iterations)"
262 )
264 self.phases.run_configuration_phase(options)
266 if not await self._execute_cleaning_phase_async(options):
267 self.session.fail_task("workflow", "Cleaning phase failed")
268 return False
270 iteration_success = await self._run_iterative_quality_improvement(
271 options, max_iterations
272 )
273 if not iteration_success:
274 return False
276 return await self._run_final_workflow_phases(options)
278 async def _run_iterative_quality_improvement(
279 self, options: OptionsProtocol, max_iterations: int
280 ) -> bool:
281 for iteration in range(1, max_iterations + 1):
282 self.console.print(f"\n🔄 Iteration {iteration}/{max_iterations}")
284 try:
285 # Each iteration has its own timeout
286 iteration_result = await self.timeout_manager.with_timeout(
287 "workflow_iteration",
288 self._execute_single_iteration(options, iteration),
289 strategy=TimeoutStrategy.GRACEFUL_DEGRADATION,
290 )
292 if iteration_result == "success":
293 self.console.print("✅ All quality checks passed !")
294 return True
295 elif iteration_result == "failed":
296 return False
298 except Exception as e:
299 self.logger.error(f"Iteration {iteration} failed with error: {e}")
300 self.console.print(f"⚠️ Iteration {iteration} failed: {e}")
301 # Continue to next iteration unless it's a critical error
302 if iteration == max_iterations:
303 return False
305 self.console.print(
306 f"❌ Failed to achieve code quality after {max_iterations} iterations"
307 )
308 self.session.fail_task("workflow", f"Failed after {max_iterations} iterations")
309 return False
311 async def _execute_single_iteration(
312 self, options: OptionsProtocol, iteration: int
313 ) -> str:
314 fast_hooks_success = await self._run_fast_hooks_with_retry_async(options)
316 test_issues = await self._collect_test_issues_async(options)
317 hook_issues = await self._collect_comprehensive_hook_issues_async(options)
319 if fast_hooks_success and not test_issues and not hook_issues:
320 return "success"
322 if test_issues or hook_issues:
323 fix_success = await self._apply_ai_fixes_async(
324 options, test_issues, hook_issues, iteration
325 )
326 if not fix_success:
327 self.console.print(f"❌ AI fixing failed in iteration {iteration}")
328 self.session.fail_task(
329 "workflow", f"AI fixing failed in iteration {iteration}"
330 )
331 return "failed"
333 return "continue"
335 def _parse_issues_for_agents(
336 self, test_issues: list[str], hook_issues: list[str]
337 ) -> list[Issue]:
338 structured_issues = []
340 for issue in hook_issues:
341 parsed_issue = self._parse_single_hook_issue(issue)
342 structured_issues.append(parsed_issue)
344 for issue in test_issues:
345 parsed_issue = self._parse_single_test_issue(issue)
346 structured_issues.append(parsed_issue)
348 return structured_issues
350 def _parse_single_hook_issue(self, issue: str) -> Issue:
351 from crackerjack.agents.base import IssueType, Priority
353 if "refurb: " in issue and "[FURB" in issue:
354 return self._parse_refurb_issue(issue)
356 hook_type_mapping = {
357 "pyright: ": (IssueType.TYPE_ERROR, Priority.HIGH, "pyright"),
358 "Type error": (IssueType.TYPE_ERROR, Priority.HIGH, "pyright"),
359 "bandit: ": (IssueType.SECURITY, Priority.HIGH, "bandit"),
360 "vulture: ": (IssueType.DEAD_CODE, Priority.MEDIUM, "vulture"),
361 "complexipy: ": (IssueType.COMPLEXITY, Priority.MEDIUM, "complexipy"),
362 }
364 for keyword, (issue_type, priority, stage) in hook_type_mapping.items():
365 if keyword in issue:
366 return self._create_generic_issue(issue, issue_type, priority, stage)
368 return self._create_generic_issue(
369 issue, IssueType.FORMATTING, Priority.MEDIUM, "hook"
370 )
372 def _parse_refurb_issue(self, issue: str) -> Issue:
373 import re
374 import uuid
376 from crackerjack.agents.base import Issue, IssueType, Priority
378 match = re.search(
379 r"refurb: \s *(.+?): (\d +): (\d +)\s +\[(\w +)\]: \s *(.+)", issue
380 )
381 if match:
382 file_path, line_num, _, error_code, message = match.groups()
383 return Issue(
384 id=str(uuid.uuid4()),
385 type=IssueType.FORMATTING,
386 severity=Priority.MEDIUM,
387 message=f"[{error_code}] {message}",
388 file_path=file_path,
389 line_number=int(line_num),
390 details=[issue],
391 stage="refurb",
392 )
394 return self._create_generic_issue(
395 issue, IssueType.FORMATTING, Priority.MEDIUM, "refurb"
396 )
398 def _parse_single_test_issue(self, issue: str) -> Issue:
399 import uuid
401 from crackerjack.agents.base import Issue, IssueType, Priority
403 if "FAILED" in issue or "ERROR" in issue:
404 severity = Priority.HIGH
405 else:
406 severity = Priority.MEDIUM
408 return Issue(
409 id=str(uuid.uuid4()),
410 type=IssueType.TEST_FAILURE,
411 severity=severity,
412 message=issue,
413 details=[issue],
414 stage="test",
415 )
417 def _create_generic_issue(
418 self, issue: str, issue_type: IssueType, priority: Priority, stage: str
419 ) -> Issue:
420 import uuid
422 from crackerjack.agents.base import Issue
424 return Issue(
425 id=str(uuid.uuid4()),
426 type=issue_type,
427 severity=priority,
428 message=issue,
429 details=[issue],
430 stage=stage,
431 )
433 async def _run_final_workflow_phases(self, options: OptionsProtocol) -> bool:
434 if not self.phases.run_publishing_phase(options):
435 self.session.fail_task("workflow", "Publishing failed")
436 return False
438 if not self.phases.run_commit_phase(options):
439 self.session.fail_task("workflow", "Commit failed")
440 return False
442 return True
444 async def _run_fast_hooks_with_retry_async(self, options: OptionsProtocol) -> bool:
445 return await asyncio.to_thread(self.phases.run_fast_hooks_only, options)
447 async def _collect_test_issues_async(self, options: OptionsProtocol) -> list[str]:
448 if not options.test:
449 return []
451 try:
452 success = await self.timeout_manager.with_timeout(
453 "test_execution",
454 self._run_testing_phase_async(options),
455 strategy=TimeoutStrategy.GRACEFUL_DEGRADATION,
456 )
457 if success:
458 return []
459 else:
460 test_failures = self.phases.test_manager.get_test_failures()
461 if test_failures:
462 return [f"Test failure: {failure}" for failure in test_failures]
463 else:
464 return ["Test failures detected-see logs for details"]
465 except Exception as e:
466 return [f"Test execution error: {e}"]
468 async def _collect_comprehensive_hook_issues_async(
469 self, options: OptionsProtocol
470 ) -> list[str]:
471 try:
472 hook_results = await self.timeout_manager.with_timeout(
473 "comprehensive_hooks",
474 asyncio.to_thread(self.phases.hook_manager.run_comprehensive_hooks),
475 strategy=TimeoutStrategy.GRACEFUL_DEGRADATION,
476 )
478 all_issues = []
479 for result in hook_results:
480 if (
481 result.status in ("failed", "error", "timeout")
482 and result.issues_found
483 ):
484 hook_context = f"{result.name}: "
485 for issue in result.issues_found:
486 all_issues.append(hook_context + issue)
488 return all_issues
490 except Exception as e:
491 return [f"Comprehensive hooks error: {e}"]
493 async def _apply_ai_fixes_async(
494 self,
495 options: OptionsProtocol,
496 test_issues: list[str],
497 hook_issues: list[str],
498 iteration: int,
499 ) -> bool:
500 all_issues = test_issues + hook_issues
501 if not all_issues:
502 return True
504 self.console.print(
505 f"🔧 Applying AI fixes for {len(all_issues)} issues in iteration {iteration}"
506 )
508 try:
509 return await self.timeout_manager.with_timeout(
510 "ai_agent_processing",
511 self._execute_ai_fix_workflow(test_issues, hook_issues, iteration),
512 strategy=TimeoutStrategy.GRACEFUL_DEGRADATION,
513 )
514 except Exception as e:
515 return self._handle_ai_fix_error(e)
517 async def _execute_ai_fix_workflow(
518 self, test_issues: list[str], hook_issues: list[str], iteration: int
519 ) -> bool:
520 structured_issues = self._parse_issues_for_agents(test_issues, hook_issues)
522 if not structured_issues:
523 self.console.print("⚠️ No actionable issues found for AI agents")
524 return True
526 coordinator = self._create_agent_coordinator()
528 # Apply timeout to AI coordinator processing
529 fix_result = await self.timeout_manager.with_timeout(
530 "ai_agent_processing",
531 coordinator.handle_issues(structured_issues),
532 strategy=TimeoutStrategy.GRACEFUL_DEGRADATION,
533 )
535 self._report_fix_results(fix_result, iteration)
536 return fix_result.success
538 def _create_agent_coordinator(self):
539 from crackerjack.agents.base import AgentContext
540 from crackerjack.agents.coordinator import AgentCoordinator
542 context = AgentContext(project_path=self.pkg_path)
543 return AgentCoordinator(context)
545 def _report_fix_results(self, fix_result: FixResult, iteration: int) -> None:
546 if fix_result.success:
547 self._report_successful_fixes(fix_result, iteration)
548 else:
549 self._report_failed_fixes(fix_result, iteration)
551 def _report_successful_fixes(self, fix_result: FixResult, iteration: int) -> None:
552 self.console.print(f"✅ AI fixes applied successfully in iteration {iteration}")
553 if fix_result.fixes_applied:
554 self.console.print(f" Applied {len(fix_result.fixes_applied)} fixes")
556 def _report_failed_fixes(self, fix_result: FixResult, iteration: int) -> None:
557 self.console.print(f"⚠️ Some AI fixes failed in iteration {iteration}")
558 if fix_result.remaining_issues:
559 for error in fix_result.remaining_issues[:3]:
560 self.console.print(f" Error: {error}")
562 def _handle_ai_fix_error(self, error: Exception) -> bool:
563 self.logger.error(f"AI fixing failed: {error}")
564 self.console.print(f"❌ AI agent system error: {error}")
565 return False
568class AsyncWorkflowOrchestrator:
569 def __init__(
570 self,
571 console: Console | None = None,
572 pkg_path: Path | None = None,
573 dry_run: bool = False,
574 web_job_id: str | None = None,
575 ) -> None:
576 self.console = console or Console(force_terminal=True)
577 self.pkg_path = pkg_path or Path.cwd()
578 self.dry_run = dry_run
579 self.web_job_id = web_job_id
581 from crackerjack.models.protocols import (
582 FileSystemInterface,
583 GitInterface,
584 HookManager,
585 PublishManager,
586 TestManagerProtocol,
587 )
589 from .container import create_container
591 self.container = create_container(
592 console=self.console,
593 pkg_path=self.pkg_path,
594 dry_run=self.dry_run,
595 )
597 self.session = SessionCoordinator(self.console, self.pkg_path, self.web_job_id)
598 self.phases = PhaseCoordinator(
599 console=self.console,
600 pkg_path=self.pkg_path,
601 session=self.session,
602 filesystem=self.container.get(FileSystemInterface),
603 git_service=self.container.get(GitInterface),
604 hook_manager=self.container.get(HookManager),
605 test_manager=self.container.get(TestManagerProtocol),
606 publish_manager=self.container.get(PublishManager),
607 )
609 self.async_pipeline = AsyncWorkflowPipeline(
610 console=self.console,
611 pkg_path=self.pkg_path,
612 session=self.session,
613 phases=self.phases,
614 )
616 self.logger = logging.getLogger("crackerjack.async_orchestrator")
618 async def run_complete_workflow_async(self, options: OptionsProtocol) -> bool:
619 return await self.async_pipeline.run_complete_workflow_async(options)
621 def run_complete_workflow(self, options: OptionsProtocol) -> bool:
622 return asyncio.run(self.run_complete_workflow_async(options))
624 def run_cleaning_phase(self, options: OptionsProtocol) -> bool:
625 return self.phases.run_cleaning_phase(options)
627 def run_fast_hooks_only(self, options: OptionsProtocol) -> bool:
628 return self.phases.run_fast_hooks_only(options)
630 def run_comprehensive_hooks_only(self, options: OptionsProtocol) -> bool:
631 return self.phases.run_comprehensive_hooks_only(options)
633 def run_hooks_phase(self, options: OptionsProtocol) -> bool:
634 return self.phases.run_hooks_phase(options)
636 def run_testing_phase(self, options: OptionsProtocol) -> bool:
637 return self.phases.run_testing_phase(options)
639 def run_publishing_phase(self, options: OptionsProtocol) -> bool:
640 return self.phases.run_publishing_phase(options)
642 def run_commit_phase(self, options: OptionsProtocol) -> bool:
643 return self.phases.run_commit_phase(options)
645 def run_configuration_phase(self, options: OptionsProtocol) -> bool:
646 return self.phases.run_configuration_phase(options)
648 def _cleanup_resources(self) -> None:
649 self.session.cleanup_resources()
651 def _register_cleanup(self, cleanup_handler: t.Callable[[], None]) -> None:
652 self.session.register_cleanup(cleanup_handler)
654 def _track_lock_file(self, lock_file_path: Path) -> None:
655 self.session.track_lock_file(lock_file_path)