Coverage for /Users/les/Projects/crackerjack/crackerjack/services/contextual_ai_assistant.py: 0%
243 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 subprocess
3import time
4import tomllib
5from dataclasses import dataclass, field
6from pathlib import Path
8from rich.console import Console
10from crackerjack.models.protocols import FileSystemInterface
13@dataclass
14class AIRecommendation:
15 category: str
16 priority: str
17 title: str
18 description: str
19 action_command: str | None = None
20 reasoning: str = ""
21 confidence: float = 0.0
24@dataclass
25class ProjectContext:
26 has_tests: bool = False
27 test_coverage: float = 0.0
28 lint_errors_count: int = 0
29 security_issues: list[str] = field(default_factory=list)
30 outdated_dependencies: list[str] = field(default_factory=list)
31 last_commit_days: int = 0
32 project_size: str = "small"
33 main_languages: list[str] = field(default_factory=list)
34 has_ci_cd: bool = False
35 has_documentation: bool = False
36 project_type: str = "library"
39class ContextualAIAssistant:
40 def __init__(
41 self,
42 filesystem: FileSystemInterface,
43 console: Console | None = None,
44 ) -> None:
45 self.filesystem = filesystem
46 self.console = console or Console()
47 self.project_root = Path.cwd()
48 self.pyproject_path = self.project_root / "pyproject.toml"
49 self.cache_file = self.project_root / ".crackerjack" / "ai_context.json"
51 def get_contextual_recommendations(
52 self,
53 max_recommendations: int = 5,
54 ) -> list[AIRecommendation]:
55 context = self._analyze_project_context()
56 recommendations = self._generate_recommendations(context)
58 recommendations.sort(
59 key=lambda r: (
60 {"high": 3, "medium": 2, "low": 1}[r.priority],
61 r.confidence,
62 ),
63 reverse=True,
64 )
66 return recommendations[:max_recommendations]
68 def _analyze_project_context(self) -> ProjectContext:
69 context = ProjectContext()
71 context.has_tests = self._has_test_directory()
72 context.test_coverage = self._get_current_coverage()
73 context.lint_errors_count = self._count_current_lint_errors()
74 context.project_size = self._determine_project_size()
75 context.main_languages = self._detect_main_languages()
76 context.has_ci_cd = self._has_ci_cd_config()
77 context.has_documentation = self._has_documentation()
78 context.project_type = self._determine_project_type()
79 context.last_commit_days = self._days_since_last_commit()
81 context.security_issues = self._detect_security_issues()
82 context.outdated_dependencies = self._get_outdated_dependencies()
84 return context
86 def _generate_recommendations(
87 self,
88 context: ProjectContext,
89 ) -> list[AIRecommendation]:
90 recommendations: list[AIRecommendation] = []
92 recommendations.extend(self._get_testing_recommendations(context))
93 recommendations.extend(self._get_code_quality_recommendations(context))
94 recommendations.extend(self._get_security_recommendations(context))
95 recommendations.extend(self._get_maintenance_recommendations(context))
96 recommendations.extend(self._get_workflow_recommendations(context))
97 recommendations.extend(self._get_documentation_recommendations(context))
99 return recommendations
101 def _get_testing_recommendations(
102 self,
103 context: ProjectContext,
104 ) -> list[AIRecommendation]:
105 recommendations = []
107 if not context.has_tests:
108 recommendations.append(
109 AIRecommendation(
110 category="testing",
111 priority="high",
112 title="Add Test Suite",
113 description="No test directory found. Adding tests improves code reliability and enables CI / CD.",
114 action_command="python - m crackerjack-t",
115 reasoning="Projects without tests have 40 % more bugs in production",
116 confidence=0.9,
117 ),
118 )
119 elif context.test_coverage < 75:
120 milestones = [15, 20, 25, 30, 40, 50, 60, 70, 80, 90, 100]
121 next_milestone = next(
122 (m for m in milestones if m > context.test_coverage), 100
123 )
125 recommendations.append(
126 AIRecommendation(
127 category="testing",
128 priority="medium",
129 title="Progress Toward 100 % Coverage",
130 description=f"Current coverage: {context.test_coverage: .1f}%. Next milestone: {next_milestone}% on the journey to 100 %.",
131 action_command="python - m crackerjack-t",
132 reasoning="Coverage ratchet system prevents regression and targets 100 % coverage incrementally",
133 confidence=0.85,
134 ),
135 )
137 return recommendations
139 def _get_code_quality_recommendations(
140 self,
141 context: ProjectContext,
142 ) -> list[AIRecommendation]:
143 recommendations = []
145 if context.lint_errors_count > 20:
146 recommendations.append(
147 AIRecommendation(
148 category="code_quality",
149 priority="high",
150 title="Fix Lint Errors",
151 description=f"Found {context.lint_errors_count} lint errors that should be addressed.",
152 action_command="python - m crackerjack - - ai-agent",
153 reasoning="High lint error count indicates technical debt and potential bugs",
154 confidence=0.95,
155 ),
156 )
157 elif context.lint_errors_count > 5:
158 recommendations.append(
159 AIRecommendation(
160 category="code_quality",
161 priority="medium",
162 title="Clean Up Code Style",
163 description=f"Found {context.lint_errors_count} minor lint issues to resolve.",
164 action_command="python-m crackerjack",
165 reasoning="Clean code is easier to maintain and has fewer bugs",
166 confidence=0.8,
167 ),
168 )
170 return recommendations
172 def _get_security_recommendations(
173 self,
174 context: ProjectContext,
175 ) -> list[AIRecommendation]:
176 recommendations = []
178 if context.security_issues:
179 recommendations.append(
180 AIRecommendation(
181 category="security",
182 priority="high",
183 title="Address Security Vulnerabilities",
184 description=f"Found {len(context.security_issues)} security issues in dependencies.",
185 action_command="python - m crackerjack - - check-dependencies",
186 reasoning="Security vulnerabilities can expose your application to attacks",
187 confidence=0.95,
188 ),
189 )
191 return recommendations
193 def _get_maintenance_recommendations(
194 self,
195 context: ProjectContext,
196 ) -> list[AIRecommendation]:
197 recommendations = []
199 if len(context.outdated_dependencies) > 10:
200 recommendations.append(
201 AIRecommendation(
202 category="maintenance",
203 priority="medium",
204 title="Update Dependencies",
205 description=f"Found {len(context.outdated_dependencies)} outdated dependencies.",
206 action_command="python - m crackerjack - - check-dependencies",
207 reasoning="Outdated dependencies may have security vulnerabilities or performance issues",
208 confidence=0.75,
209 ),
210 )
212 return recommendations
214 def _get_workflow_recommendations(
215 self,
216 context: ProjectContext,
217 ) -> list[AIRecommendation]:
218 recommendations = []
220 if not context.has_ci_cd and context.project_size != "small":
221 recommendations.append(
222 AIRecommendation(
223 category="workflow",
224 priority="medium",
225 title="Set Up CI / CD Pipeline",
226 description="No CI / CD configuration found. Automated testing and deployment improve reliability.",
227 reasoning="CI / CD prevents 60 % of deployment issues and improves team productivity",
228 confidence=0.8,
229 ),
230 )
232 return recommendations
234 def _get_documentation_recommendations(
235 self,
236 context: ProjectContext,
237 ) -> list[AIRecommendation]:
238 recommendations = []
240 if not context.has_documentation and context.project_type in ("library", "api"):
241 recommendations.append(
242 AIRecommendation(
243 category="documentation",
244 priority="medium",
245 title="Add Documentation",
246 description="No documentation found. Good documentation improves adoption and maintenance.",
247 reasoning="Well-documented projects get 3x more contributors and have better longevity",
248 confidence=0.7,
249 ),
250 )
252 return recommendations
254 def _has_test_directory(self) -> bool:
255 test_dirs = ["tests", "test", "testing"]
256 return any((self.project_root / dirname).exists() for dirname in test_dirs)
258 def _get_current_coverage(self) -> float:
259 from contextlib import suppress
261 with suppress(Exception):
262 coverage_file = self.project_root / ".coverage"
263 if coverage_file.exists():
264 result = subprocess.run(
265 ["uv", "run", "coverage", "report", "--format=json"],
266 check=False,
267 capture_output=True,
268 text=True,
269 timeout=10,
270 cwd=self.project_root,
271 )
273 if result.returncode == 0 and result.stdout:
274 data = json.loads(result.stdout)
275 return float(data.get("totals", {}).get("percent_covered", 0))
276 return 0.0
278 def _count_current_lint_errors(self) -> int:
279 from contextlib import suppress
281 with suppress(Exception):
282 result = subprocess.run(
283 ["uv", "run", "ruff", "check", ".", "- - output-format=json"],
284 check=False,
285 capture_output=True,
286 text=True,
287 timeout=30,
288 cwd=self.project_root,
289 )
291 if result.returncode != 0 and result.stdout:
292 with suppress(json.JSONDecodeError):
293 lint_data = json.loads(result.stdout)
294 return len(lint_data) if isinstance(lint_data, list) else 0
295 return len(result.stdout.splitlines())
296 return 0
298 def _determine_project_size(self) -> str:
299 try:
300 python_files = list(self.project_root.rglob("*.py"))
301 if len(python_files) < 10:
302 return "small"
303 if len(python_files) < 50:
304 return "medium"
305 return "large"
306 except Exception:
307 return "small"
309 def _detect_main_languages(self) -> list[str]:
310 languages = []
312 if (self.project_root / "pyproject.toml").exists():
313 languages.append("python")
315 if (self.project_root / "package.json").exists():
316 languages.append("javascript")
317 if any(self.project_root.glob("*.ts")):
318 languages.append("typescript")
320 if (self.project_root / "Cargo.toml").exists():
321 languages.append("rust")
323 if (self.project_root / "go.mod").exists():
324 languages.append("go")
326 return languages or ["python"]
328 def _has_ci_cd_config(self) -> bool:
329 ci_files = [
330 ".github / workflows",
331 ".gitlab-ci.yml",
332 "azure-pipelines.yml",
333 "Jenkinsfile",
334 ".travis.yml",
335 ]
336 return any((self.project_root / path).exists() for path in ci_files)
338 def _has_documentation(self) -> bool:
339 doc_indicators = [
340 "README.md",
341 "README.rst",
342 "docs",
343 "documentation",
344 "doc",
345 ]
346 return any((self.project_root / path).exists() for path in doc_indicators)
348 def _determine_project_type(self) -> str:
349 try:
350 if self.pyproject_path.exists():
351 with self.pyproject_path.open("rb") as f:
352 data = tomllib.load(f)
354 project_data = data.get("project", {})
355 scripts = project_data.get("scripts", {})
357 if scripts or "console_scripts" in project_data.get("entry-points", {}):
358 return "cli"
360 dependencies = project_data.get("dependencies", [])
361 web_frameworks = ["fastapi", "flask", "django", "starlette"]
362 if any(fw in str(dependencies).lower() for fw in web_frameworks):
363 return "api"
365 if (self.project_root / "__main__.py").exists():
366 return "application"
368 return "library"
369 except Exception:
370 return "library"
372 def _days_since_last_commit(self) -> int:
373 from contextlib import suppress
375 with suppress(Exception):
376 result = subprocess.run(
377 ["git", "log", "- 1", "--format=% ct"],
378 check=False,
379 capture_output=True,
380 text=True,
381 timeout=5,
382 cwd=self.project_root,
383 )
385 if result.returncode == 0 and result.stdout.strip():
386 last_commit_timestamp = int(result.stdout.strip())
387 current_timestamp = time.time()
388 return int((current_timestamp - last_commit_timestamp) / 86400)
389 return 0
391 def _detect_security_issues(self) -> list[str]:
392 issues = []
393 from contextlib import suppress
395 with suppress(Exception):
396 result = subprocess.run(
397 ["uv", "run", "bandit", "- r", ".", "- f", "json"],
398 check=False,
399 capture_output=True,
400 text=True,
401 timeout=30,
402 cwd=self.project_root,
403 )
405 if result.returncode != 0 and result.stdout:
406 with suppress(json.JSONDecodeError):
407 bandit_data = json.loads(result.stdout)
408 results = bandit_data.get("results", [])
409 for issue in results[:5]:
410 test_id = issue.get("test_id", "unknown")
411 issues.append(f"Security issue: {test_id}")
413 return issues
415 def _get_outdated_dependencies(self) -> list[str]:
416 outdated = []
418 from contextlib import suppress
420 with suppress(Exception):
421 if self.pyproject_path.exists():
422 with self.pyproject_path.open("rb") as f:
423 data = tomllib.load(f)
425 dependencies = data.get("project", {}).get("dependencies", [])
427 old_patterns = [" == 1.", " == 0.", " >= 1.", "~ = 1."]
428 for dep in dependencies:
429 if any(pattern in dep for pattern in old_patterns):
430 pkg_name = (
431 dep.split(" == ")[0]
432 .split(" >= ")[0]
433 .split("~ = ")[0]
434 .strip()
435 )
436 outdated.append(pkg_name)
438 return outdated
440 def display_recommendations(self, recommendations: list[AIRecommendation]) -> None:
441 if not recommendations:
442 self.console.print(
443 "[green]✨ Great job ! No immediate recommendations.[/ green]",
444 )
445 return
447 self.console.print("\n[bold cyan]🤖 AI Assistant Recommendations[/ bold cyan]")
448 self.console.print("[dim]Based on your current project context[/ dim]\n")
450 for i, rec in enumerate(recommendations, 1):
451 priority_color = {"high": "red", "medium": "yellow", "low": "blue"}.get(
452 rec.priority,
453 "white",
454 )
456 category_emoji = {
457 "testing": "🧪",
458 "code_quality": "🔧",
459 "security": "🔒",
460 "maintenance": "📦",
461 "workflow": "⚙️",
462 "documentation": "📚",
463 "architecture": "🏗️",
464 "performance": "⚡",
465 }.get(rec.category, "💡")
467 self.console.print(
468 f"[bold]{i}. {category_emoji} {rec.title}[/ bold] [{priority_color}]({rec.priority})[/{priority_color}]",
469 )
470 self.console.print(f" {rec.description}")
472 if rec.action_command:
473 self.console.print(
474 f" [dim]Run: [/ dim] [cyan]{rec.action_command}[/ cyan]",
475 )
477 if rec.reasoning:
478 self.console.print(f" [dim italic]💭 {rec.reasoning}[/ dim italic]")
480 confidence_bar = "█" * int(rec.confidence * 10) + "▒" * (
481 10 - int(rec.confidence * 10)
482 )
483 self.console.print(
484 f" [dim]Confidence: [{confidence_bar}] {rec.confidence: .1 %}[/ dim]",
485 )
487 if i < len(recommendations):
488 self.console.print()
490 def get_quick_help(self, query: str) -> str:
491 query_lower = query.lower()
493 if "coverage" in query_lower:
494 return "Check test coverage with: python - m crackerjack-t\nView HTML report: uv run coverage html"
496 if "security" in query_lower or "vulnerabilit" in query_lower:
497 return "Check security with: python - m crackerjack - - check - dependencies\nRun security audit: uv run bandit-r ."
499 if "lint" in query_lower or "format" in query_lower:
500 return "Fix code style with: python - m crackerjack\nFor AI - powered fixes: python - m crackerjack - - ai-agent"
502 if "test" in query_lower:
503 return "Run tests with: python - m crackerjack - t\nFor AI - powered test fixes: python - m crackerjack - - ai - agent-t"
505 if "publish" in query_lower or "release" in query_lower:
506 return "Publish to PyPI: python - m crackerjack - p patch\nBump version only: python - m crackerjack-b patch"
508 if "clean" in query_lower:
509 return "Clean code: python - m crackerjack-x\nNote: Resolve TODOs first before cleaning"
511 if "dashboard" in query_lower or "monitor" in query_lower:
512 return "Start monitoring dashboard: python - m crackerjack - - dashboard\nStart WebSocket server: python - m crackerjack - - start - websocket-server"
514 return "For full help, run: python - m crackerjack - - help\nFor AI assistance: python - m crackerjack - - ai-agent"