Coverage for /Users/les/Projects/crackerjack/crackerjack/services/debug.py: 0%
317 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 json
2import logging
3import os
4import time
5import typing as t
6from contextlib import contextmanager
7from datetime import datetime
8from pathlib import Path
9from typing import Any
11from rich.console import Console
12from rich.panel import Panel
13from rich.table import Table
15from .log_manager import get_log_manager
16from .logging import get_logger
19class AIAgentDebugger:
20 def __init__(self, enabled: bool = False, verbose: bool = False) -> None:
21 self.enabled = enabled
22 self.verbose = verbose
23 self.console = Console(force_terminal=True, stderr=True)
24 self.logger = get_logger("crackerjack.ai_agent.debug")
25 self.session_id = f"debug_{int(time.time())}"
27 if self.enabled:
28 log_manager = get_log_manager()
29 self.debug_log_path = log_manager.create_debug_log_file(
30 f"ai-agent -{self.session_id}",
31 )
32 else:
33 self.debug_log_path = None
35 self.mcp_operations: list[dict[str, Any]] = []
36 self.agent_activities: list[dict[str, Any]] = []
37 self.workflow_phases: list[dict[str, Any]] = []
38 self.error_events: list[dict[str, Any]] = []
40 self.iteration_stats: list[dict[str, Any]] = []
41 self.current_iteration = 0
42 self.total_test_failures = 0
43 self.total_test_fixes = 0
44 self.total_hook_failures = 0
45 self.total_hook_fixes = 0
46 self.workflow_success = False
48 self._debug_logging_setup = False
50 if self.enabled:
51 self._print_debug_header()
53 def _ensure_debug_logging_setup(self) -> None:
54 if not self._debug_logging_setup and self.enabled:
55 self._setup_debug_logging()
56 self._debug_logging_setup = True
58 def _setup_debug_logging(self) -> None:
59 if not self.debug_log_path:
60 return
62 debug_handler = logging.FileHandler(self.debug_log_path)
63 debug_handler.setLevel(logging.DEBUG)
64 debug_formatter = logging.Formatter(
65 "%(asctime)s | %(name)s | %(levelname)s | %(message)s",
66 )
67 debug_handler.setFormatter(debug_formatter)
69 loggers = [
70 "crackerjack.ai_agent",
71 "crackerjack.mcp",
72 "crackerjack.agents",
73 "crackerjack.workflow",
74 ]
76 for logger_name in loggers:
77 logger = logging.getLogger(logger_name)
78 logger.addHandler(debug_handler)
79 logger.setLevel(logging.DEBUG)
81 def _print_debug_header(self) -> None:
82 debug_log_info = (
83 f"Debug Log: {self.debug_log_path}"
84 if self.debug_log_path
85 else "Debug Log: None (disabled)"
86 )
87 header = Panel(
88 f"[bold cyan]🐛 AI Agent Debug Mode Active[/ bold cyan]\n"
89 f"Session ID: {self.session_id}\n"
90 f"{debug_log_info}\n"
91 f"Verbose Mode: {'✅' if self.verbose else '❌'}",
92 title="Debug Session",
93 border_style="cyan",
94 )
95 self.console.print(header)
96 self.console.print()
98 @contextmanager
99 def debug_operation(self, operation: str, **kwargs: Any) -> t.Iterator[str]:
100 if not self.enabled:
101 yield ""
102 return
104 self._ensure_debug_logging_setup()
105 op_id = f"{operation}_{int(time.time() * 1000)}"
106 start_time = time.time()
108 self.logger.debug(f"Starting operation: {operation}", extra=kwargs)
110 if self.verbose:
111 self.console.print(f"[dim]🔍 {operation} starting...[/ dim]")
113 try:
114 yield op_id
115 duration = time.time() - start_time
116 self.logger.debug(
117 f"Operation completed: {operation}",
118 extra={"duration": duration} | kwargs,
119 )
121 if self.verbose:
122 self.console.print(
123 f"[dim green]✅ {operation} completed ({duration: .2f}s)[/ dim green]",
124 )
126 except Exception as e:
127 duration = time.time() - start_time
128 self.logger.exception(
129 f"Operation failed: {operation}",
130 extra={"error": str(e), "duration": duration} | kwargs,
131 )
133 if self.verbose:
134 self.console.print(
135 f"[dim red]❌ {operation} failed ({duration: .2f}s): {e}[/ dim red]",
136 )
137 raise
139 def log_mcp_operation(
140 self,
141 operation_type: str,
142 tool_name: str,
143 params: dict[str, Any] | None = None,
144 result: dict[str, Any] | None = None,
145 error: str | None = None,
146 duration: float | None = None,
147 ) -> None:
148 if not self.enabled:
149 return
151 self._ensure_debug_logging_setup()
153 event = {
154 "timestamp": datetime.now().isoformat(),
155 "type": "mcp_operation",
156 "operation": operation_type,
157 "tool": tool_name,
158 "params": params or {},
159 "result": result,
160 "error": error,
161 "duration": duration,
162 }
164 self.mcp_operations.append(event)
166 self.logger.info(
167 f"MCP {operation_type}: {tool_name}",
168 extra={
169 "tool": tool_name,
170 "params_count": len(params) if params else 0,
171 "success": error is None,
172 "duration": duration,
173 },
174 )
176 if self.verbose:
177 status_color = "green" if error is None else "red"
178 status_icon = "✅" if error is None else "❌"
180 self.console.print(
181 f"[{status_color}]{status_icon} MCP {operation_type}[/{status_color}]: "
182 f"[bold]{tool_name}[/ bold]"
183 + (f" ({duration: .2f}s)" if duration else ""),
184 )
186 if error and self.verbose:
187 self.console.print(f" [red]Error: {error}[/ red]")
188 self.console.print()
190 def log_agent_activity(
191 self,
192 agent_name: str,
193 activity: str,
194 issue_id: str | None = None,
195 confidence: float | None = None,
196 result: dict[str, Any] | None = None,
197 metadata: dict[str, Any] | None = None,
198 ) -> None:
199 if not self.enabled:
200 return
202 self._ensure_debug_logging_setup()
204 event = {
205 "timestamp": datetime.now().isoformat(),
206 "type": "agent_activity",
207 "agent": agent_name,
208 "activity": activity,
209 "issue_id": issue_id,
210 "confidence": confidence,
211 "result": result,
212 "metadata": metadata or {},
213 }
215 self.agent_activities.append(event)
217 self.logger.info(
218 f"Agent {activity}: {agent_name}",
219 extra={
220 "agent": agent_name,
221 "activity": activity,
222 "issue_id": issue_id,
223 "confidence": confidence,
224 },
225 )
227 if self.verbose:
228 confidence_text = f" (confidence: {confidence: .2f})" if confidence else ""
229 issue_text = f" [issue: {issue_id}]" if issue_id else ""
231 self.console.print(
232 f"[blue]🤖 {agent_name}[/ blue]: {activity}{confidence_text}{issue_text}",
233 )
235 def log_workflow_phase(
236 self,
237 phase: str,
238 status: str,
239 details: dict[str, Any] | None = None,
240 duration: float | None = None,
241 ) -> None:
242 if not self.enabled:
243 return
245 self._ensure_debug_logging_setup()
247 event = {
248 "timestamp": datetime.now().isoformat(),
249 "type": "workflow_phase",
250 "phase": phase,
251 "status": status,
252 "details": details or {},
253 "duration": duration,
254 }
256 self.workflow_phases.append(event)
258 self.logger.info(
259 f"Workflow {status}: {phase}",
260 extra={"phase": phase, "status": status, "duration": duration},
261 )
263 if self.verbose:
264 status_colors = {
265 "started": "yellow",
266 "completed": "green",
267 "failed": "red",
268 "skipped": "dim",
269 }
271 color = status_colors.get(status, "white")
272 duration_text = f" ({duration: .2f}s)" if duration else ""
274 self.console.print(
275 f"[{color}]📋 Workflow {status}: {phase}{duration_text}[/{color}]",
276 )
278 def log_error_event(
279 self,
280 error_type: str,
281 message: str,
282 context: dict[str, Any] | None = None,
283 traceback_info: str | None = None,
284 ) -> None:
285 if not self.enabled:
286 return
288 self._ensure_debug_logging_setup()
290 event = {
291 "timestamp": datetime.now().isoformat(),
292 "type": "error_event",
293 "error_type": error_type,
294 "message": message,
295 "context": context or {},
296 "traceback": traceback_info,
297 }
299 self.error_events.append(event)
301 self.logger.error(
302 f"Error: {error_type}",
303 extra={"error_type": error_type, "message": message, "context": context},
304 )
306 if self.verbose:
307 self.console.print(f"[red]💥 {error_type}: {message}[/ red]")
309 def print_debug_summary(self) -> None:
310 if not self.enabled:
311 return
313 border_style = "green" if self.workflow_success else "red"
314 title_style = "green" if self.workflow_success else "red"
316 table = Table(
317 title=f"[{title_style}]AI Agent Debug Summary[/{title_style}]",
318 border_style=border_style,
319 )
320 table.add_column("Category", style="cyan")
321 table.add_column("Count", justify="right", style="green")
322 table.add_column("Details", style="dim")
324 table.add_row(
325 "MCP Operations",
326 str(len(self.mcp_operations)),
327 f"Tools used: {len({op['tool'] for op in self.mcp_operations})}",
328 )
330 table.add_row(
331 "Agent Activities",
332 str(len(self.agent_activities)),
333 f"Agents active: {len({act['agent'] for act in self.agent_activities})}",
334 )
336 table.add_row(
337 "Workflow Phases",
338 str(len(self.workflow_phases)),
339 f"Completed: {len([p for p in self.workflow_phases if p['status'] == 'completed'])}",
340 )
342 table.add_row(
343 "Error Events",
344 str(len(self.error_events)),
345 f"Types: {len({err['error_type'] for err in self.error_events})}",
346 )
348 table.add_row(
349 "Iterations Completed",
350 str(self.current_iteration),
351 f"Total test fixes: {self.total_test_fixes}, hook fixes: {self.total_hook_fixes}",
352 )
354 self.console.print(table)
356 if self.iteration_stats:
357 self._print_iteration_breakdown(border_style)
359 if self.verbose and self.agent_activities:
360 self._print_agent_activity_breakdown(border_style)
362 if self.verbose and self.mcp_operations:
363 self._print_mcp_operation_breakdown(border_style)
365 self._print_total_statistics(border_style)
367 self.console.print(
368 f"\n[dim]📝 Full debug log available at: {self.debug_log_path}[/ dim]"
369 if self.debug_log_path
370 else "",
371 )
373 def _print_iteration_breakdown(self, border_style: str = "red") -> None:
374 if not self.iteration_stats:
375 return
377 table = Table(
378 title="[cyan]Iteration Breakdown[/ cyan]",
379 border_style=border_style,
380 )
381 table.add_column("Iteration", style="yellow")
382 table.add_column("Test Failures", justify="right", style="red")
383 table.add_column("Test Fixes", justify="right", style="green")
384 table.add_column("Hook Failures", justify="right", style="red")
385 table.add_column("Hook Fixes", justify="right", style="green")
386 table.add_column("Duration", justify="right", style="cyan")
388 for iteration in self.iteration_stats:
389 table.add_row(
390 str(iteration["iteration"]),
391 str(iteration["test_failures"]),
392 str(iteration["test_fixes"]),
393 str(iteration["hook_failures"]),
394 str(iteration["hook_fixes"]),
395 f"{iteration['duration']: .1f}s"
396 if iteration.get("duration")
397 else "N / A",
398 )
400 self.console.print(table)
402 def _print_agent_activity_breakdown(self, border_style: str = "red") -> None:
403 agent_stats = {}
404 for activity in self.agent_activities:
405 agent = activity["agent"]
406 if agent not in agent_stats:
407 agent_stats[agent] = {
408 "activities": 0,
409 "avg_confidence": 0.0,
410 "confidences": [],
411 }
413 agent_stats[agent]["activities"] += 1
414 if activity.get("confidence"):
415 agent_stats[agent]["confidences"].append(activity["confidence"])
417 for stats in agent_stats.values():
418 if stats["confidences"]:
419 stats["avg_confidence"] = sum(stats["confidences"]) / len(
420 stats["confidences"],
421 )
423 table = Table(
424 title="[cyan]Agent Activity Breakdown[/ cyan]",
425 border_style=border_style,
426 )
427 table.add_column("Agent", style="blue")
428 table.add_column("Activities", justify="right", style="green")
429 table.add_column("Avg Confidence", justify="right", style="yellow")
431 for agent, stats in sorted(agent_stats.items()):
432 confidence_text = (
433 f"{stats['avg_confidence']: .2f}"
434 if stats["avg_confidence"] > 0
435 else "N / A"
436 )
437 table.add_row(agent, str(stats["activities"]), confidence_text)
439 self.console.print(table)
441 def _print_total_statistics(self, border_style: str = "red") -> None:
442 success_icon = "✅" if self.workflow_success else "❌"
443 status_text = "SUCCESS" if self.workflow_success else "IN PROGRESS"
444 status_style = "green" if self.workflow_success else "red"
446 table = Table(
447 title=f"[{status_style}]{success_icon} TOTAL WORKFLOW STATISTICS {success_icon}[/{status_style}]",
448 border_style=border_style,
449 )
450 table.add_column("Metric", style="cyan")
451 table.add_column("Total", justify="right", style=status_style)
452 table.add_column("Status", style=status_style)
454 table.add_row("Iterations Completed", str(self.current_iteration), status_text)
456 table.add_row(
457 "Total Test Failures Found",
458 str(self.total_test_failures),
459 f"Fixed: {self.total_test_fixes}",
460 )
462 table.add_row(
463 "Total Hook Failures Found",
464 str(self.total_hook_failures),
465 f"Fixed: {self.total_hook_fixes}",
466 )
468 total_issues = self.total_test_failures + self.total_hook_failures
469 total_fixes = self.total_test_fixes + self.total_hook_fixes
470 fix_rate = (total_fixes / total_issues * 100) if total_issues > 0 else 100
472 table.add_row(
473 "Overall Fix Rate",
474 f"{fix_rate: .1f}%",
475 f"{total_fixes}/{total_issues} issues resolved",
476 )
478 self.console.print(table)
480 def _print_mcp_operation_breakdown(self, border_style: str = "red") -> None:
481 tool_stats = {}
482 for op in self.mcp_operations:
483 tool = op["tool"]
484 if tool not in tool_stats:
485 tool_stats[tool] = {"calls": 0, "errors": 0, "total_duration": 0.0}
487 tool_stats[tool]["calls"] += 1
488 if op.get("error"):
489 tool_stats[tool]["errors"] += 1
490 if op.get("duration"):
491 tool_stats[tool]["total_duration"] += op["duration"]
493 table = Table(
494 title="[cyan]MCP Tool Usage[/ cyan]",
495 border_style=border_style,
496 )
497 table.add_column("Tool", style="cyan")
498 table.add_column("Calls", justify="right", style="green")
499 table.add_column("Errors", justify="right", style="red")
500 table.add_column("Avg Duration", justify="right", style="yellow")
502 for tool, stats in sorted(tool_stats.items()):
503 avg_duration = (
504 stats["total_duration"] / stats["calls"] if stats["calls"] > 0 else 0
505 )
506 table.add_row(
507 tool,
508 str(stats["calls"]),
509 str(stats["errors"]),
510 f"{avg_duration: .2f}s" if avg_duration > 0 else "N / A",
511 )
513 self.console.print(table)
515 def log_iteration_start(self, iteration_number: int) -> None:
516 if not self.enabled:
517 return
519 self.current_iteration = iteration_number
520 iteration_data = {
521 "iteration": iteration_number,
522 "start_time": time.time(),
523 "test_failures": 0,
524 "test_fixes": 0,
525 "hook_failures": 0,
526 "hook_fixes": 0,
527 "duration": 0.0,
528 }
529 self.iteration_stats.append(iteration_data)
531 if self.verbose:
532 self.console.print(
533 f"[yellow]🔄 Starting Iteration {iteration_number}[/ yellow]",
534 )
536 def log_iteration_end(self, iteration_number: int, success: bool) -> None:
537 if not self.enabled or not self.iteration_stats:
538 return
540 iteration_data = None
541 for data in self.iteration_stats:
542 if data["iteration"] == iteration_number:
543 iteration_data = data
544 break
546 if iteration_data:
547 iteration_data["duration"] = time.time() - iteration_data["start_time"]
549 if self.verbose:
550 status = "✅ PASSED" if success else "❌ FAILED"
551 self.console.print(
552 f"[{'green' if success else 'red'}]🏁 Iteration {iteration_number} {status}[/{'green' if success else 'red'}]",
553 )
555 def log_test_failures(self, count: int) -> None:
556 if not self.enabled or not self.iteration_stats:
557 return
559 if self.iteration_stats:
560 self.iteration_stats[-1]["test_failures"] = count
561 self.total_test_failures += count
563 def log_test_fixes(self, count: int) -> None:
564 if not self.enabled or not self.iteration_stats:
565 return
567 if self.iteration_stats:
568 self.iteration_stats[-1]["test_fixes"] = count
569 self.total_test_fixes += count
571 def log_hook_failures(self, count: int) -> None:
572 if not self.enabled or not self.iteration_stats:
573 return
575 if self.iteration_stats:
576 self.iteration_stats[-1]["hook_failures"] = count
577 self.total_hook_failures += count
579 def log_hook_fixes(self, count: int) -> None:
580 if not self.enabled or not self.iteration_stats:
581 return
583 if self.iteration_stats:
584 self.iteration_stats[-1]["hook_fixes"] = count
585 self.total_hook_fixes += count
587 def set_workflow_success(self, success: bool) -> None:
588 if not self.enabled:
589 return
591 self.workflow_success = success
593 def export_debug_data(self, output_path: Path | None = None) -> Path:
594 if not self.enabled:
595 return Path("debug_not_enabled.json")
597 if output_path is None:
598 output_path = Path(f"crackerjack - debug-export -{self.session_id}.json")
600 debug_data = {
601 "session_id": self.session_id,
602 "timestamp": datetime.now().isoformat(),
603 "mcp_operations": self.mcp_operations,
604 "agent_activities": self.agent_activities,
605 "workflow_phases": self.workflow_phases,
606 "error_events": self.error_events,
607 }
609 with output_path.open("w") as f:
610 json.dump(debug_data, f, indent=2, default=str)
612 self.logger.info(f"Debug data exported to {output_path}")
613 return output_path
616class NoOpDebugger:
617 def __init__(self) -> None:
618 self.enabled = False
619 self.verbose = False
620 self.debug_log_path = None
621 self.session_id = "disabled"
623 def debug_operation(self, operation: str, **kwargs: Any) -> t.Iterator[str]:
624 yield ""
626 def log_mcp_operation(
627 self,
628 operation_type: str,
629 tool_name: str,
630 params: dict[str, Any] | None = None,
631 result: dict[str, Any] | None = None,
632 error: str | None = None,
633 duration: float | None = None,
634 ) -> None:
635 pass
637 def log_agent_activity(
638 self,
639 agent_name: str,
640 activity: str,
641 issue_id: str | None = None,
642 confidence: float | None = None,
643 result: dict[str, Any] | None = None,
644 metadata: dict[str, Any] | None = None,
645 ) -> None:
646 pass
648 def log_workflow_phase(
649 self,
650 phase: str,
651 status: str,
652 details: dict[str, Any] | None = None,
653 duration: float | None = None,
654 ) -> None:
655 pass
657 def log_error_event(
658 self,
659 error_type: str,
660 message: str,
661 context: dict[str, Any] | None = None,
662 traceback_info: str | None = None,
663 ) -> None:
664 pass
666 def print_debug_summary(self) -> None:
667 pass
669 def export_debug_data(self, output_path: Path | None = None) -> Path:
670 return Path("debug_not_enabled.json")
672 def log_iteration_start(self, iteration_number: int) -> None:
673 pass
675 def log_iteration_end(self, iteration_number: int, success: bool) -> None:
676 pass
678 def log_test_failures(self, count: int) -> None:
679 pass
681 def log_test_fixes(self, count: int) -> None:
682 pass
684 def log_hook_failures(self, count: int) -> None:
685 pass
687 def log_hook_fixes(self, count: int) -> None:
688 pass
690 def set_workflow_success(self, success: bool) -> None:
691 pass
694_ai_agent_debugger: AIAgentDebugger | NoOpDebugger | None = None
697def get_ai_agent_debugger() -> AIAgentDebugger | NoOpDebugger:
698 global _ai_agent_debugger
699 if _ai_agent_debugger is None:
700 debug_enabled = os.environ.get("AI_AGENT_DEBUG", "0") == "1"
701 verbose_mode = os.environ.get("AI_AGENT_VERBOSE", "0") == "1"
703 if debug_enabled:
704 _ai_agent_debugger = AIAgentDebugger(
705 enabled=debug_enabled,
706 verbose=verbose_mode,
707 )
708 else:
709 _ai_agent_debugger = NoOpDebugger()
710 return _ai_agent_debugger
713def enable_ai_agent_debugging(verbose: bool = False) -> AIAgentDebugger:
714 global _ai_agent_debugger
715 _ai_agent_debugger = AIAgentDebugger(enabled=True, verbose=verbose)
716 return _ai_agent_debugger
719def disable_ai_agent_debugging() -> None:
720 global _ai_agent_debugger
721 if _ai_agent_debugger:
722 _ai_agent_debugger.enabled = False