empathy-framework 3.7.0__py3-none-any.whl → 3.8.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (274) hide show
  1. coach_wizards/code_reviewer_README.md +60 -0
  2. coach_wizards/code_reviewer_wizard.py +180 -0
  3. {empathy_framework-3.7.0.dist-info → empathy_framework-3.8.0.dist-info}/METADATA +148 -11
  4. empathy_framework-3.8.0.dist-info/RECORD +333 -0
  5. {empathy_framework-3.7.0.dist-info → empathy_framework-3.8.0.dist-info}/top_level.txt +5 -1
  6. empathy_healthcare_plugin/monitors/__init__.py +9 -0
  7. empathy_healthcare_plugin/monitors/clinical_protocol_monitor.py +315 -0
  8. empathy_healthcare_plugin/monitors/monitoring/__init__.py +44 -0
  9. empathy_healthcare_plugin/monitors/monitoring/protocol_checker.py +300 -0
  10. empathy_healthcare_plugin/monitors/monitoring/protocol_loader.py +214 -0
  11. empathy_healthcare_plugin/monitors/monitoring/sensor_parsers.py +306 -0
  12. empathy_healthcare_plugin/monitors/monitoring/trajectory_analyzer.py +389 -0
  13. empathy_llm_toolkit/agent_factory/__init__.py +53 -0
  14. empathy_llm_toolkit/agent_factory/adapters/__init__.py +85 -0
  15. empathy_llm_toolkit/agent_factory/adapters/autogen_adapter.py +312 -0
  16. empathy_llm_toolkit/agent_factory/adapters/crewai_adapter.py +454 -0
  17. empathy_llm_toolkit/agent_factory/adapters/haystack_adapter.py +298 -0
  18. empathy_llm_toolkit/agent_factory/adapters/langchain_adapter.py +362 -0
  19. empathy_llm_toolkit/agent_factory/adapters/langgraph_adapter.py +333 -0
  20. empathy_llm_toolkit/agent_factory/adapters/native.py +228 -0
  21. empathy_llm_toolkit/agent_factory/adapters/wizard_adapter.py +426 -0
  22. empathy_llm_toolkit/agent_factory/base.py +305 -0
  23. empathy_llm_toolkit/agent_factory/crews/__init__.py +67 -0
  24. empathy_llm_toolkit/agent_factory/crews/code_review.py +1113 -0
  25. empathy_llm_toolkit/agent_factory/crews/health_check.py +1246 -0
  26. empathy_llm_toolkit/agent_factory/crews/refactoring.py +1128 -0
  27. empathy_llm_toolkit/agent_factory/crews/security_audit.py +1018 -0
  28. empathy_llm_toolkit/agent_factory/decorators.py +286 -0
  29. empathy_llm_toolkit/agent_factory/factory.py +558 -0
  30. empathy_llm_toolkit/agent_factory/framework.py +192 -0
  31. empathy_llm_toolkit/agent_factory/memory_integration.py +324 -0
  32. empathy_llm_toolkit/agent_factory/resilient.py +320 -0
  33. empathy_llm_toolkit/cli/__init__.py +8 -0
  34. empathy_llm_toolkit/cli/sync_claude.py +487 -0
  35. empathy_llm_toolkit/code_health.py +150 -3
  36. empathy_llm_toolkit/config/__init__.py +29 -0
  37. empathy_llm_toolkit/config/unified.py +295 -0
  38. empathy_llm_toolkit/routing/__init__.py +32 -0
  39. empathy_llm_toolkit/routing/model_router.py +362 -0
  40. empathy_llm_toolkit/security/IMPLEMENTATION_SUMMARY.md +413 -0
  41. empathy_llm_toolkit/security/PHASE2_COMPLETE.md +384 -0
  42. empathy_llm_toolkit/security/PHASE2_SECRETS_DETECTOR_COMPLETE.md +271 -0
  43. empathy_llm_toolkit/security/QUICK_REFERENCE.md +316 -0
  44. empathy_llm_toolkit/security/README.md +262 -0
  45. empathy_llm_toolkit/security/__init__.py +62 -0
  46. empathy_llm_toolkit/security/audit_logger.py +929 -0
  47. empathy_llm_toolkit/security/audit_logger_example.py +152 -0
  48. empathy_llm_toolkit/security/pii_scrubber.py +640 -0
  49. empathy_llm_toolkit/security/secrets_detector.py +678 -0
  50. empathy_llm_toolkit/security/secrets_detector_example.py +304 -0
  51. empathy_llm_toolkit/security/secure_memdocs.py +1192 -0
  52. empathy_llm_toolkit/security/secure_memdocs_example.py +278 -0
  53. empathy_llm_toolkit/wizards/__init__.py +38 -0
  54. empathy_llm_toolkit/wizards/base_wizard.py +364 -0
  55. empathy_llm_toolkit/wizards/customer_support_wizard.py +190 -0
  56. empathy_llm_toolkit/wizards/healthcare_wizard.py +362 -0
  57. empathy_llm_toolkit/wizards/patient_assessment_README.md +64 -0
  58. empathy_llm_toolkit/wizards/patient_assessment_wizard.py +193 -0
  59. empathy_llm_toolkit/wizards/technology_wizard.py +194 -0
  60. empathy_os/__init__.py +52 -52
  61. empathy_os/adaptive/__init__.py +13 -0
  62. empathy_os/adaptive/task_complexity.py +127 -0
  63. empathy_os/cache/__init__.py +117 -0
  64. empathy_os/cache/base.py +166 -0
  65. empathy_os/cache/dependency_manager.py +253 -0
  66. empathy_os/cache/hash_only.py +248 -0
  67. empathy_os/cache/hybrid.py +390 -0
  68. empathy_os/cache/storage.py +282 -0
  69. empathy_os/cli.py +118 -8
  70. empathy_os/cli_unified.py +121 -1
  71. empathy_os/config/__init__.py +63 -0
  72. empathy_os/config/xml_config.py +239 -0
  73. empathy_os/config.py +2 -1
  74. empathy_os/dashboard/__init__.py +15 -0
  75. empathy_os/dashboard/server.py +743 -0
  76. empathy_os/memory/__init__.py +195 -0
  77. empathy_os/memory/claude_memory.py +466 -0
  78. empathy_os/memory/config.py +224 -0
  79. empathy_os/memory/control_panel.py +1298 -0
  80. empathy_os/memory/edges.py +179 -0
  81. empathy_os/memory/graph.py +567 -0
  82. empathy_os/memory/long_term.py +1194 -0
  83. empathy_os/memory/nodes.py +179 -0
  84. empathy_os/memory/redis_bootstrap.py +540 -0
  85. empathy_os/memory/security/__init__.py +31 -0
  86. empathy_os/memory/security/audit_logger.py +930 -0
  87. empathy_os/memory/security/pii_scrubber.py +640 -0
  88. empathy_os/memory/security/secrets_detector.py +678 -0
  89. empathy_os/memory/short_term.py +2119 -0
  90. empathy_os/memory/storage/__init__.py +15 -0
  91. empathy_os/memory/summary_index.py +583 -0
  92. empathy_os/memory/unified.py +619 -0
  93. empathy_os/metrics/__init__.py +12 -0
  94. empathy_os/metrics/prompt_metrics.py +190 -0
  95. empathy_os/models/__init__.py +136 -0
  96. empathy_os/models/__main__.py +13 -0
  97. empathy_os/models/cli.py +655 -0
  98. empathy_os/models/empathy_executor.py +354 -0
  99. empathy_os/models/executor.py +252 -0
  100. empathy_os/models/fallback.py +671 -0
  101. empathy_os/models/provider_config.py +563 -0
  102. empathy_os/models/registry.py +382 -0
  103. empathy_os/models/tasks.py +302 -0
  104. empathy_os/models/telemetry.py +548 -0
  105. empathy_os/models/token_estimator.py +378 -0
  106. empathy_os/models/validation.py +274 -0
  107. empathy_os/monitoring/__init__.py +52 -0
  108. empathy_os/monitoring/alerts.py +23 -0
  109. empathy_os/monitoring/alerts_cli.py +268 -0
  110. empathy_os/monitoring/multi_backend.py +271 -0
  111. empathy_os/monitoring/otel_backend.py +363 -0
  112. empathy_os/optimization/__init__.py +19 -0
  113. empathy_os/optimization/context_optimizer.py +272 -0
  114. empathy_os/plugins/__init__.py +28 -0
  115. empathy_os/plugins/base.py +361 -0
  116. empathy_os/plugins/registry.py +268 -0
  117. empathy_os/project_index/__init__.py +30 -0
  118. empathy_os/project_index/cli.py +335 -0
  119. empathy_os/project_index/crew_integration.py +430 -0
  120. empathy_os/project_index/index.py +425 -0
  121. empathy_os/project_index/models.py +501 -0
  122. empathy_os/project_index/reports.py +473 -0
  123. empathy_os/project_index/scanner.py +538 -0
  124. empathy_os/prompts/__init__.py +61 -0
  125. empathy_os/prompts/config.py +77 -0
  126. empathy_os/prompts/context.py +177 -0
  127. empathy_os/prompts/parser.py +285 -0
  128. empathy_os/prompts/registry.py +313 -0
  129. empathy_os/prompts/templates.py +208 -0
  130. empathy_os/resilience/__init__.py +56 -0
  131. empathy_os/resilience/circuit_breaker.py +256 -0
  132. empathy_os/resilience/fallback.py +179 -0
  133. empathy_os/resilience/health.py +300 -0
  134. empathy_os/resilience/retry.py +209 -0
  135. empathy_os/resilience/timeout.py +135 -0
  136. empathy_os/routing/__init__.py +43 -0
  137. empathy_os/routing/chain_executor.py +433 -0
  138. empathy_os/routing/classifier.py +217 -0
  139. empathy_os/routing/smart_router.py +234 -0
  140. empathy_os/routing/wizard_registry.py +307 -0
  141. empathy_os/trust/__init__.py +28 -0
  142. empathy_os/trust/circuit_breaker.py +579 -0
  143. empathy_os/validation/__init__.py +19 -0
  144. empathy_os/validation/xml_validator.py +281 -0
  145. empathy_os/wizard_factory_cli.py +170 -0
  146. empathy_os/workflows/__init__.py +360 -0
  147. empathy_os/workflows/base.py +1660 -0
  148. empathy_os/workflows/bug_predict.py +962 -0
  149. empathy_os/workflows/code_review.py +960 -0
  150. empathy_os/workflows/code_review_adapters.py +310 -0
  151. empathy_os/workflows/code_review_pipeline.py +720 -0
  152. empathy_os/workflows/config.py +600 -0
  153. empathy_os/workflows/dependency_check.py +648 -0
  154. empathy_os/workflows/document_gen.py +1069 -0
  155. empathy_os/workflows/documentation_orchestrator.py +1205 -0
  156. empathy_os/workflows/health_check.py +679 -0
  157. empathy_os/workflows/keyboard_shortcuts/__init__.py +39 -0
  158. empathy_os/workflows/keyboard_shortcuts/generators.py +386 -0
  159. empathy_os/workflows/keyboard_shortcuts/parsers.py +414 -0
  160. empathy_os/workflows/keyboard_shortcuts/prompts.py +295 -0
  161. empathy_os/workflows/keyboard_shortcuts/schema.py +193 -0
  162. empathy_os/workflows/keyboard_shortcuts/workflow.py +505 -0
  163. empathy_os/workflows/manage_documentation.py +804 -0
  164. empathy_os/workflows/new_sample_workflow1.py +146 -0
  165. empathy_os/workflows/new_sample_workflow1_README.md +150 -0
  166. empathy_os/workflows/perf_audit.py +687 -0
  167. empathy_os/workflows/pr_review.py +748 -0
  168. empathy_os/workflows/progress.py +445 -0
  169. empathy_os/workflows/progress_server.py +322 -0
  170. empathy_os/workflows/refactor_plan.py +693 -0
  171. empathy_os/workflows/release_prep.py +808 -0
  172. empathy_os/workflows/research_synthesis.py +404 -0
  173. empathy_os/workflows/secure_release.py +585 -0
  174. empathy_os/workflows/security_adapters.py +297 -0
  175. empathy_os/workflows/security_audit.py +1046 -0
  176. empathy_os/workflows/step_config.py +234 -0
  177. empathy_os/workflows/test5.py +125 -0
  178. empathy_os/workflows/test5_README.md +158 -0
  179. empathy_os/workflows/test_gen.py +1855 -0
  180. empathy_os/workflows/test_lifecycle.py +526 -0
  181. empathy_os/workflows/test_maintenance.py +626 -0
  182. empathy_os/workflows/test_maintenance_cli.py +590 -0
  183. empathy_os/workflows/test_maintenance_crew.py +821 -0
  184. empathy_os/workflows/xml_enhanced_crew.py +285 -0
  185. empathy_software_plugin/cli/__init__.py +120 -0
  186. empathy_software_plugin/cli/inspect.py +362 -0
  187. empathy_software_plugin/cli.py +3 -1
  188. empathy_software_plugin/wizards/__init__.py +42 -0
  189. empathy_software_plugin/wizards/advanced_debugging_wizard.py +392 -0
  190. empathy_software_plugin/wizards/agent_orchestration_wizard.py +511 -0
  191. empathy_software_plugin/wizards/ai_collaboration_wizard.py +503 -0
  192. empathy_software_plugin/wizards/ai_context_wizard.py +441 -0
  193. empathy_software_plugin/wizards/ai_documentation_wizard.py +503 -0
  194. empathy_software_plugin/wizards/base_wizard.py +288 -0
  195. empathy_software_plugin/wizards/book_chapter_wizard.py +519 -0
  196. empathy_software_plugin/wizards/code_review_wizard.py +606 -0
  197. empathy_software_plugin/wizards/debugging/__init__.py +50 -0
  198. empathy_software_plugin/wizards/debugging/bug_risk_analyzer.py +414 -0
  199. empathy_software_plugin/wizards/debugging/config_loaders.py +442 -0
  200. empathy_software_plugin/wizards/debugging/fix_applier.py +469 -0
  201. empathy_software_plugin/wizards/debugging/language_patterns.py +383 -0
  202. empathy_software_plugin/wizards/debugging/linter_parsers.py +470 -0
  203. empathy_software_plugin/wizards/debugging/verification.py +369 -0
  204. empathy_software_plugin/wizards/enhanced_testing_wizard.py +537 -0
  205. empathy_software_plugin/wizards/memory_enhanced_debugging_wizard.py +816 -0
  206. empathy_software_plugin/wizards/multi_model_wizard.py +501 -0
  207. empathy_software_plugin/wizards/pattern_extraction_wizard.py +422 -0
  208. empathy_software_plugin/wizards/pattern_retriever_wizard.py +400 -0
  209. empathy_software_plugin/wizards/performance/__init__.py +9 -0
  210. empathy_software_plugin/wizards/performance/bottleneck_detector.py +221 -0
  211. empathy_software_plugin/wizards/performance/profiler_parsers.py +278 -0
  212. empathy_software_plugin/wizards/performance/trajectory_analyzer.py +429 -0
  213. empathy_software_plugin/wizards/performance_profiling_wizard.py +305 -0
  214. empathy_software_plugin/wizards/prompt_engineering_wizard.py +425 -0
  215. empathy_software_plugin/wizards/rag_pattern_wizard.py +461 -0
  216. empathy_software_plugin/wizards/security/__init__.py +32 -0
  217. empathy_software_plugin/wizards/security/exploit_analyzer.py +290 -0
  218. empathy_software_plugin/wizards/security/owasp_patterns.py +241 -0
  219. empathy_software_plugin/wizards/security/vulnerability_scanner.py +604 -0
  220. empathy_software_plugin/wizards/security_analysis_wizard.py +322 -0
  221. empathy_software_plugin/wizards/security_learning_wizard.py +740 -0
  222. empathy_software_plugin/wizards/tech_debt_wizard.py +726 -0
  223. empathy_software_plugin/wizards/testing/__init__.py +27 -0
  224. empathy_software_plugin/wizards/testing/coverage_analyzer.py +459 -0
  225. empathy_software_plugin/wizards/testing/quality_analyzer.py +531 -0
  226. empathy_software_plugin/wizards/testing/test_suggester.py +533 -0
  227. empathy_software_plugin/wizards/testing_wizard.py +274 -0
  228. hot_reload/README.md +473 -0
  229. hot_reload/__init__.py +62 -0
  230. hot_reload/config.py +84 -0
  231. hot_reload/integration.py +228 -0
  232. hot_reload/reloader.py +298 -0
  233. hot_reload/watcher.py +179 -0
  234. hot_reload/websocket.py +176 -0
  235. scaffolding/README.md +589 -0
  236. scaffolding/__init__.py +35 -0
  237. scaffolding/__main__.py +14 -0
  238. scaffolding/cli.py +240 -0
  239. test_generator/__init__.py +38 -0
  240. test_generator/__main__.py +14 -0
  241. test_generator/cli.py +226 -0
  242. test_generator/generator.py +325 -0
  243. test_generator/risk_analyzer.py +216 -0
  244. workflow_patterns/__init__.py +33 -0
  245. workflow_patterns/behavior.py +249 -0
  246. workflow_patterns/core.py +76 -0
  247. workflow_patterns/output.py +99 -0
  248. workflow_patterns/registry.py +255 -0
  249. workflow_patterns/structural.py +288 -0
  250. workflow_scaffolding/__init__.py +11 -0
  251. workflow_scaffolding/__main__.py +12 -0
  252. workflow_scaffolding/cli.py +206 -0
  253. workflow_scaffolding/generator.py +265 -0
  254. agents/code_inspection/patterns/inspection/recurring_B112.json +0 -18
  255. agents/code_inspection/patterns/inspection/recurring_F541.json +0 -16
  256. agents/code_inspection/patterns/inspection/recurring_FORMAT.json +0 -25
  257. agents/code_inspection/patterns/inspection/recurring_bug_20250822_def456.json +0 -16
  258. agents/code_inspection/patterns/inspection/recurring_bug_20250915_abc123.json +0 -16
  259. agents/code_inspection/patterns/inspection/recurring_bug_20251212_3c5b9951.json +0 -16
  260. agents/code_inspection/patterns/inspection/recurring_bug_20251212_97c0f72f.json +0 -16
  261. agents/code_inspection/patterns/inspection/recurring_bug_20251212_a0871d53.json +0 -16
  262. agents/code_inspection/patterns/inspection/recurring_bug_20251212_a9b6ec41.json +0 -16
  263. agents/code_inspection/patterns/inspection/recurring_bug_null_001.json +0 -16
  264. agents/code_inspection/patterns/inspection/recurring_builtin.json +0 -16
  265. agents/compliance_anticipation_agent.py +0 -1422
  266. agents/compliance_db.py +0 -339
  267. agents/epic_integration_wizard.py +0 -530
  268. agents/notifications.py +0 -291
  269. agents/trust_building_behaviors.py +0 -872
  270. empathy_framework-3.7.0.dist-info/RECORD +0 -105
  271. {empathy_framework-3.7.0.dist-info → empathy_framework-3.8.0.dist-info}/WHEEL +0 -0
  272. {empathy_framework-3.7.0.dist-info → empathy_framework-3.8.0.dist-info}/entry_points.txt +0 -0
  273. {empathy_framework-3.7.0.dist-info → empathy_framework-3.8.0.dist-info}/licenses/LICENSE +0 -0
  274. /empathy_os/{monitoring.py → agent_monitoring.py} +0 -0
@@ -0,0 +1,1246 @@
1
+ """Health Check Crew
2
+
3
+ A multi-agent crew that diagnoses and fixes project health issues.
4
+ Uses XML-enhanced prompts for structured, consistent output.
5
+
6
+ Agents:
7
+ 1. Health Lead (Coordinator) - Orchestrates checks, prioritizes fixes
8
+ 2. Lint Fixer - Runs ruff, generates auto-fix patches
9
+ 3. Type Resolver - Runs mypy, suggests type annotations
10
+ 4. Test Doctor - Runs pytest, diagnoses and fixes test failures
11
+ 5. Dep Auditor - Checks outdated/vulnerable dependencies
12
+
13
+ Usage:
14
+ from empathy_llm_toolkit.agent_factory.crews import HealthCheckCrew
15
+
16
+ crew = HealthCheckCrew(api_key="...")
17
+ report = await crew.check(path=".", auto_fix=True)
18
+
19
+ print(f"Health Score: {report.health_score}")
20
+ for fix in report.applied_fixes:
21
+ print(f" Fixed: {fix.title}")
22
+
23
+ Copyright 2025 Smart-AI-Memory
24
+ Licensed under Fair Source License 0.9
25
+ """
26
+
27
+ import logging
28
+ import subprocess
29
+ from dataclasses import dataclass, field
30
+ from enum import Enum
31
+ from pathlib import Path
32
+ from typing import Any
33
+
34
+ logger = logging.getLogger(__name__)
35
+
36
+
37
+ class HealthCategory(Enum):
38
+ """Health check categories."""
39
+
40
+ LINT = "lint"
41
+ TYPES = "types"
42
+ TESTS = "tests"
43
+ DEPENDENCIES = "dependencies"
44
+ SECURITY = "security"
45
+ GENERAL = "general"
46
+
47
+
48
+ class IssueSeverity(Enum):
49
+ """Issue severity levels."""
50
+
51
+ CRITICAL = "critical"
52
+ HIGH = "high"
53
+ MEDIUM = "medium"
54
+ LOW = "low"
55
+ INFO = "info"
56
+
57
+
58
+ class FixStatus(Enum):
59
+ """Status of an attempted fix."""
60
+
61
+ APPLIED = "applied"
62
+ SUGGESTED = "suggested"
63
+ FAILED = "failed"
64
+ SKIPPED = "skipped"
65
+
66
+
67
+ @dataclass
68
+ class HealthIssue:
69
+ """A single health issue found."""
70
+
71
+ title: str
72
+ description: str
73
+ category: HealthCategory
74
+ severity: IssueSeverity
75
+ file_path: str | None = None
76
+ line_number: int | None = None
77
+ code_snippet: str | None = None
78
+ tool: str | None = None
79
+ rule_id: str | None = None
80
+ metadata: dict = field(default_factory=dict)
81
+
82
+ def to_dict(self) -> dict:
83
+ """Convert issue to dictionary."""
84
+ return {
85
+ "title": self.title,
86
+ "description": self.description,
87
+ "category": self.category.value,
88
+ "severity": self.severity.value,
89
+ "file_path": self.file_path,
90
+ "line_number": self.line_number,
91
+ "code_snippet": self.code_snippet,
92
+ "tool": self.tool,
93
+ "rule_id": self.rule_id,
94
+ "metadata": self.metadata,
95
+ }
96
+
97
+
98
+ @dataclass
99
+ class HealthFix:
100
+ """A fix applied or suggested."""
101
+
102
+ title: str
103
+ description: str
104
+ category: HealthCategory
105
+ status: FixStatus
106
+ file_path: str | None = None
107
+ before_code: str | None = None
108
+ after_code: str | None = None
109
+ patch: str | None = None
110
+ related_issues: list[str] = field(default_factory=list)
111
+ metadata: dict = field(default_factory=dict)
112
+
113
+ def to_dict(self) -> dict:
114
+ """Convert fix to dictionary."""
115
+ return {
116
+ "title": self.title,
117
+ "description": self.description,
118
+ "category": self.category.value,
119
+ "status": self.status.value,
120
+ "file_path": self.file_path,
121
+ "before_code": self.before_code,
122
+ "after_code": self.after_code,
123
+ "patch": self.patch,
124
+ "related_issues": self.related_issues,
125
+ "metadata": self.metadata,
126
+ }
127
+
128
+
129
+ @dataclass
130
+ class HealthCheckReport:
131
+ """Complete health check report."""
132
+
133
+ target: str
134
+ issues: list[HealthIssue]
135
+ fixes: list[HealthFix]
136
+ health_score: float
137
+ check_duration_seconds: float = 0.0
138
+ agents_used: list[str] = field(default_factory=list)
139
+ memory_graph_hits: int = 0
140
+ checks_run: dict = field(default_factory=dict)
141
+ metadata: dict = field(default_factory=dict)
142
+
143
+ @property
144
+ def critical_issues(self) -> list[HealthIssue]:
145
+ """Get critical severity issues."""
146
+ return [i for i in self.issues if i.severity == IssueSeverity.CRITICAL]
147
+
148
+ @property
149
+ def applied_fixes(self) -> list[HealthFix]:
150
+ """Get successfully applied fixes."""
151
+ return [f for f in self.fixes if f.status == FixStatus.APPLIED]
152
+
153
+ @property
154
+ def issues_by_category(self) -> dict[str, list[HealthIssue]]:
155
+ """Group issues by category."""
156
+ result: dict[str, list[HealthIssue]] = {}
157
+ for issue in self.issues:
158
+ cat = issue.category.value
159
+ if cat not in result:
160
+ result[cat] = []
161
+ result[cat].append(issue)
162
+ return result
163
+
164
+ @property
165
+ def is_healthy(self) -> bool:
166
+ """Check if project is healthy (score >= 80)."""
167
+ return self.health_score >= 80.0
168
+
169
+ def to_dict(self) -> dict:
170
+ """Convert report to dictionary."""
171
+ return {
172
+ "target": self.target,
173
+ "issues": [i.to_dict() for i in self.issues],
174
+ "fixes": [f.to_dict() for f in self.fixes],
175
+ "health_score": self.health_score,
176
+ "check_duration_seconds": self.check_duration_seconds,
177
+ "agents_used": self.agents_used,
178
+ "memory_graph_hits": self.memory_graph_hits,
179
+ "checks_run": self.checks_run,
180
+ "is_healthy": self.is_healthy,
181
+ "issue_counts": {
182
+ "critical": len(self.critical_issues),
183
+ "total": len(self.issues),
184
+ "by_category": {k: len(v) for k, v in self.issues_by_category.items()},
185
+ },
186
+ "fix_counts": {
187
+ "applied": len(self.applied_fixes),
188
+ "total": len(self.fixes),
189
+ },
190
+ "metadata": self.metadata,
191
+ }
192
+
193
+
194
+ @dataclass
195
+ class HealthCheckConfig:
196
+ """Configuration for health check crew."""
197
+
198
+ # API Configuration
199
+ provider: str = "anthropic"
200
+ api_key: str | None = None
201
+
202
+ # Check Configuration
203
+ check_lint: bool = True
204
+ check_types: bool = True
205
+ check_tests: bool = True
206
+ check_deps: bool = True
207
+ auto_fix: bool = False # Apply fixes automatically
208
+ fix_safe_only: bool = True # Only apply safe fixes
209
+
210
+ # Paths
211
+ target_path: str = "."
212
+ exclude_paths: list[str] = field(default_factory=lambda: [".git", "venv", "__pycache__"])
213
+
214
+ # Memory Graph
215
+ memory_graph_enabled: bool = True
216
+ memory_graph_path: str = "patterns/health_check_memory.json"
217
+
218
+ # Agent Tiers
219
+ lead_tier: str = "premium"
220
+ lint_tier: str = "capable"
221
+ types_tier: str = "capable"
222
+ tests_tier: str = "capable"
223
+ deps_tier: str = "capable"
224
+
225
+ # XML Prompts
226
+ xml_prompts_enabled: bool = True
227
+ xml_schema_version: str = "1.0"
228
+
229
+ # Resilience
230
+ resilience_enabled: bool = True
231
+ timeout_seconds: float = 300.0
232
+
233
+
234
+ # XML Prompt Templates for Health Check Agents
235
+ XML_PROMPT_TEMPLATES = {
236
+ "health_lead": """<agent role="health_lead" version="{schema_version}">
237
+ <identity>
238
+ <role>Health Check Coordinator</role>
239
+ <expertise>Project health assessment, issue prioritization, fix orchestration</expertise>
240
+ </identity>
241
+
242
+ <goal>
243
+ Coordinate the health check team to diagnose and fix project issues.
244
+ Synthesize findings from all agents into a prioritized action plan.
245
+ </goal>
246
+
247
+ <instructions>
248
+ <step>Review health check results from all team members</step>
249
+ <step>Prioritize issues by severity and impact</step>
250
+ <step>Identify quick wins (easy fixes with high impact)</step>
251
+ <step>Create an ordered fix plan</step>
252
+ <step>Calculate overall health score (0-100)</step>
253
+ <step>Generate executive summary with recommendations</step>
254
+ </instructions>
255
+
256
+ <constraints>
257
+ <rule>Be conservative with auto-fix recommendations</rule>
258
+ <rule>Prioritize breaking issues first</rule>
259
+ <rule>Consider fix dependencies (some fixes enable others)</rule>
260
+ <rule>Flag risky fixes that need human review</rule>
261
+ </constraints>
262
+
263
+ <output_format>
264
+ <section name="summary">Executive summary of health status</section>
265
+ <section name="health_score">Numeric score 0-100</section>
266
+ <section name="critical_issues">Blocking issues requiring immediate attention</section>
267
+ <section name="fix_plan">Ordered list of recommended fixes</section>
268
+ <section name="metrics">Lint errors, type errors, test failures, dep issues</section>
269
+ </output_format>
270
+ </agent>""",
271
+ "lint_fixer": """<agent role="lint_fixer" version="{schema_version}">
272
+ <identity>
273
+ <role>Lint Analyst & Fixer</role>
274
+ <expertise>Code style, ruff rules, auto-formatting, code quality</expertise>
275
+ </identity>
276
+
277
+ <goal>
278
+ Analyze lint issues and generate fixes. Apply safe auto-fixes when enabled.
279
+ </goal>
280
+
281
+ <instructions>
282
+ <step>Parse ruff output to identify all lint violations</step>
283
+ <step>Categorize by rule type (style, error, security)</step>
284
+ <step>Identify auto-fixable issues (ruff --fix compatible)</step>
285
+ <step>Generate patch for complex issues requiring manual fix</step>
286
+ <step>Explain why each fix is necessary</step>
287
+ </instructions>
288
+
289
+ <constraints>
290
+ <rule>Only auto-fix style and formatting issues</rule>
291
+ <rule>Flag security-related lint issues as high priority</rule>
292
+ <rule>Preserve code semantics - never change behavior</rule>
293
+ <rule>Respect noqa comments and intentional suppressions</rule>
294
+ </constraints>
295
+
296
+ <tools>
297
+ <tool name="ruff">python -m ruff check --output-format=json</tool>
298
+ <tool name="ruff_fix">python -m ruff check --fix</tool>
299
+ </tools>
300
+
301
+ <output_format>
302
+ <section name="issues">List of lint issues with file, line, rule, message</section>
303
+ <section name="auto_fixable">Issues that can be auto-fixed</section>
304
+ <section name="manual_fixes">Issues requiring manual intervention with suggested code</section>
305
+ <section name="summary">Count by category and severity</section>
306
+ </output_format>
307
+ </agent>""",
308
+ "type_resolver": """<agent role="type_resolver" version="{schema_version}">
309
+ <identity>
310
+ <role>Type Error Resolver</role>
311
+ <expertise>Python type hints, mypy, type inference, generic types</expertise>
312
+ </identity>
313
+
314
+ <goal>
315
+ Diagnose type errors and suggest type annotations to resolve them.
316
+ </goal>
317
+
318
+ <instructions>
319
+ <step>Parse mypy output to identify all type errors</step>
320
+ <step>Categorize errors (missing annotation, incompatible types, etc.)</step>
321
+ <step>Infer correct types from context and usage</step>
322
+ <step>Generate type stub suggestions for third-party libraries</step>
323
+ <step>Suggest incremental typing strategy for untyped code</step>
324
+ </instructions>
325
+
326
+ <constraints>
327
+ <rule>Prefer simple types over complex generics when possible</rule>
328
+ <rule>Use | union syntax (Python 3.10+) over Union</rule>
329
+ <rule>Suggest Any only as last resort</rule>
330
+ <rule>Consider runtime type checking implications</rule>
331
+ </constraints>
332
+
333
+ <tools>
334
+ <tool name="mypy">python -m mypy --output=json</tool>
335
+ </tools>
336
+
337
+ <output_format>
338
+ <section name="errors">List of type errors with file, line, message</section>
339
+ <section name="fixes">Suggested type annotations for each error</section>
340
+ <section name="stubs">Type stubs needed for third-party packages</section>
341
+ <section name="summary">Error count and typing coverage estimate</section>
342
+ </output_format>
343
+ </agent>""",
344
+ "test_doctor": """<agent role="test_doctor" version="{schema_version}">
345
+ <identity>
346
+ <role>Test Failure Diagnostician</role>
347
+ <expertise>pytest, test fixtures, mocking, assertion debugging</expertise>
348
+ </identity>
349
+
350
+ <goal>
351
+ Diagnose test failures and suggest fixes to make tests pass.
352
+ </goal>
353
+
354
+ <instructions>
355
+ <step>Parse pytest output to identify failing tests</step>
356
+ <step>Analyze failure type (assertion, exception, timeout, fixture)</step>
357
+ <step>Determine root cause (test bug vs code bug)</step>
358
+ <step>Generate fix for test-side issues</step>
359
+ <step>Flag code-side issues for other agents</step>
360
+ <step>Identify flaky tests that need stabilization</step>
361
+ </instructions>
362
+
363
+ <constraints>
364
+ <rule>Distinguish between test bugs and code bugs</rule>
365
+ <rule>Never suggest removing assertions to fix tests</rule>
366
+ <rule>Prefer fixing test setup over mocking more</rule>
367
+ <rule>Flag tests that test implementation not behavior</rule>
368
+ </constraints>
369
+
370
+ <tools>
371
+ <tool name="pytest">python -m pytest --tb=short -q</tool>
372
+ <tool name="pytest_collect">python -m pytest --collect-only -q</tool>
373
+ </tools>
374
+
375
+ <output_format>
376
+ <section name="failures">List of failing tests with traceback summary</section>
377
+ <section name="diagnosis">Root cause analysis for each failure</section>
378
+ <section name="test_fixes">Fixes for test-side issues</section>
379
+ <section name="code_issues">Code bugs discovered via tests</section>
380
+ <section name="summary">Pass/fail counts and coverage if available</section>
381
+ </output_format>
382
+ </agent>""",
383
+ "dep_auditor": """<agent role="dep_auditor" version="{schema_version}">
384
+ <identity>
385
+ <role>Dependency Auditor</role>
386
+ <expertise>pip, package versions, security advisories, compatibility</expertise>
387
+ </identity>
388
+
389
+ <goal>
390
+ Audit dependencies for security vulnerabilities and outdated packages.
391
+ </goal>
392
+
393
+ <instructions>
394
+ <step>Parse requirements.txt/pyproject.toml for dependencies</step>
395
+ <step>Check for known security vulnerabilities (pip-audit)</step>
396
+ <step>Identify outdated packages with available updates</step>
397
+ <step>Assess update risk (major vs minor vs patch)</step>
398
+ <step>Check for dependency conflicts</step>
399
+ <step>Suggest safe update path</step>
400
+ </instructions>
401
+
402
+ <constraints>
403
+ <rule>Prioritize security vulnerabilities over outdated packages</rule>
404
+ <rule>Be conservative with major version upgrades</rule>
405
+ <rule>Check changelog for breaking changes before suggesting upgrades</rule>
406
+ <rule>Consider transitive dependency impacts</rule>
407
+ </constraints>
408
+
409
+ <tools>
410
+ <tool name="pip_audit">pip-audit --format=json</tool>
411
+ <tool name="pip_outdated">pip list --outdated --format=json</tool>
412
+ </tools>
413
+
414
+ <output_format>
415
+ <section name="vulnerabilities">Security issues with CVE and severity</section>
416
+ <section name="outdated">Packages with available updates</section>
417
+ <section name="conflicts">Dependency conflicts detected</section>
418
+ <section name="update_plan">Safe update sequence</section>
419
+ <section name="summary">Vulnerability count and overall dep health</section>
420
+ </output_format>
421
+ </agent>""",
422
+ }
423
+
424
+
425
+ class HealthCheckCrew:
426
+ """Multi-agent crew for project health diagnosis and fixing.
427
+
428
+ The crew consists of 5 specialized agents using XML-enhanced prompts:
429
+
430
+ 1. **Health Lead** (Coordinator)
431
+ - Orchestrates the health check team
432
+ - Synthesizes findings from all agents
433
+ - Prioritizes fixes by impact
434
+ - Calculates health score
435
+ - Model: Premium tier
436
+
437
+ 2. **Lint Fixer** (Analyst)
438
+ - Runs ruff for lint checking
439
+ - Identifies auto-fixable issues
440
+ - Generates patches for manual fixes
441
+ - Model: Capable tier
442
+
443
+ 3. **Type Resolver** (Analyst)
444
+ - Runs mypy for type checking
445
+ - Suggests type annotations
446
+ - Generates type stubs
447
+ - Model: Capable tier
448
+
449
+ 4. **Test Doctor** (Analyst)
450
+ - Runs pytest for test checking
451
+ - Diagnoses test failures
452
+ - Distinguishes test bugs from code bugs
453
+ - Model: Capable tier
454
+
455
+ 5. **Dep Auditor** (Analyst)
456
+ - Checks for vulnerabilities
457
+ - Identifies outdated packages
458
+ - Suggests safe update paths
459
+ - Model: Capable tier
460
+
461
+ Example:
462
+ crew = HealthCheckCrew(api_key="...")
463
+ report = await crew.check(path=".", auto_fix=True)
464
+
465
+ if report.is_healthy:
466
+ print("Project is healthy!")
467
+ else:
468
+ print(f"Health Score: {report.health_score}/100")
469
+ for issue in report.critical_issues:
470
+ print(f" - {issue.title}")
471
+
472
+ """
473
+
474
+ def __init__(self, config: HealthCheckConfig | None = None, **kwargs: Any):
475
+ """Initialize the Health Check Crew.
476
+
477
+ Args:
478
+ config: HealthCheckConfig or pass individual params as kwargs
479
+ **kwargs: Individual config parameters (api_key, provider, etc.)
480
+
481
+ """
482
+ if config:
483
+ self.config = config
484
+ else:
485
+ self.config = HealthCheckConfig(**kwargs)
486
+
487
+ self._factory: Any = None
488
+ self._agents: dict[str, Any] = {}
489
+ self._workflow: Any = None
490
+ self._graph: Any = None
491
+ self._initialized = False
492
+
493
+ def _render_xml_prompt(self, template_key: str) -> str:
494
+ """Render XML prompt template with config values."""
495
+ template = XML_PROMPT_TEMPLATES.get(template_key, "")
496
+ return template.format(schema_version=self.config.xml_schema_version)
497
+
498
+ def _get_system_prompt(self, agent_key: str, fallback: str) -> str:
499
+ """Get system prompt - XML if enabled, fallback otherwise."""
500
+ if self.config.xml_prompts_enabled:
501
+ return self._render_xml_prompt(agent_key)
502
+ return fallback
503
+
504
+ async def _initialize(self) -> None:
505
+ """Lazy initialization of agents and workflow."""
506
+ if self._initialized:
507
+ return
508
+
509
+ from empathy_llm_toolkit.agent_factory import AgentFactory, Framework
510
+
511
+ # Check if CrewAI is available
512
+ try:
513
+ from empathy_llm_toolkit.agent_factory.adapters.crewai_adapter import _check_crewai
514
+
515
+ use_crewai = _check_crewai()
516
+ except ImportError:
517
+ use_crewai = False
518
+
519
+ # Use CrewAI if available, otherwise fall back to Native
520
+ framework = Framework.CREWAI if use_crewai else Framework.NATIVE
521
+
522
+ self._factory = AgentFactory(
523
+ framework=framework,
524
+ provider=self.config.provider,
525
+ api_key=self.config.api_key,
526
+ )
527
+
528
+ # Initialize Memory Graph if enabled
529
+ if self.config.memory_graph_enabled:
530
+ try:
531
+ from empathy_os.memory import MemoryGraph
532
+
533
+ self._graph = MemoryGraph(path=self.config.memory_graph_path)
534
+ except ImportError:
535
+ logger.warning("Memory Graph not available, continuing without it")
536
+
537
+ # Create the 5 specialized agents
538
+ await self._create_agents()
539
+
540
+ # Create hierarchical workflow
541
+ await self._create_workflow()
542
+
543
+ self._initialized = True
544
+
545
+ async def _create_agents(self) -> None:
546
+ """Create the 5 specialized health check agents with XML prompts."""
547
+ # 1. Health Lead (Coordinator)
548
+ self._agents["lead"] = self._factory.create_agent(
549
+ name="health_lead",
550
+ role="coordinator",
551
+ description="Senior engineer who orchestrates the health check team",
552
+ system_prompt=self._get_system_prompt(
553
+ "health_lead",
554
+ """You are the Health Lead, coordinating project health checks.
555
+
556
+ Your responsibilities:
557
+ 1. Coordinate the health check team
558
+ 2. Synthesize findings from all checkers
559
+ 3. Prioritize issues by severity and impact
560
+ 4. Calculate overall health score (0-100)
561
+ 5. Generate actionable fix plan
562
+
563
+ Health Score calculation:
564
+ - Start at 100
565
+ - Deduct 25 per critical issue
566
+ - Deduct 10 per high issue
567
+ - Deduct 3 per medium issue
568
+ - Deduct 1 per low issue
569
+
570
+ Be constructive and prioritize quick wins.""",
571
+ ),
572
+ model_tier=self.config.lead_tier,
573
+ memory_graph_enabled=self.config.memory_graph_enabled,
574
+ memory_graph_path=self.config.memory_graph_path,
575
+ resilience_enabled=self.config.resilience_enabled,
576
+ )
577
+
578
+ # 2. Lint Fixer
579
+ self._agents["lint"] = self._factory.create_agent(
580
+ name="lint_fixer",
581
+ role="analyst",
582
+ description="Expert at identifying and fixing lint issues",
583
+ system_prompt=self._get_system_prompt(
584
+ "lint_fixer",
585
+ """You are the Lint Fixer, a code quality expert.
586
+
587
+ Your focus:
588
+ 1. Parse ruff output for lint violations
589
+ 2. Categorize by type (style, error, security)
590
+ 3. Identify auto-fixable issues
591
+ 4. Generate patches for complex fixes
592
+ 5. Explain each fix
593
+
594
+ Rules:
595
+ - Only auto-fix safe style issues
596
+ - Flag security-related issues as high priority
597
+ - Never change code behavior
598
+ - Respect noqa comments""",
599
+ ),
600
+ model_tier=self.config.lint_tier,
601
+ memory_graph_enabled=self.config.memory_graph_enabled,
602
+ memory_graph_path=self.config.memory_graph_path,
603
+ )
604
+
605
+ # 3. Type Resolver
606
+ self._agents["types"] = self._factory.create_agent(
607
+ name="type_resolver",
608
+ role="analyst",
609
+ description="Expert at resolving type errors",
610
+ system_prompt=self._get_system_prompt(
611
+ "type_resolver",
612
+ """You are the Type Resolver, a typing expert.
613
+
614
+ Your focus:
615
+ 1. Parse mypy output for type errors
616
+ 2. Categorize errors by type
617
+ 3. Infer correct types from context
618
+ 4. Generate type annotations
619
+ 5. Suggest typing strategy
620
+
621
+ Rules:
622
+ - Prefer simple types over complex generics
623
+ - Use | union syntax (Python 3.10+)
624
+ - Suggest Any only as last resort
625
+ - Consider runtime implications""",
626
+ ),
627
+ model_tier=self.config.types_tier,
628
+ memory_graph_enabled=self.config.memory_graph_enabled,
629
+ memory_graph_path=self.config.memory_graph_path,
630
+ )
631
+
632
+ # 4. Test Doctor
633
+ self._agents["tests"] = self._factory.create_agent(
634
+ name="test_doctor",
635
+ role="analyst",
636
+ description="Expert at diagnosing test failures",
637
+ system_prompt=self._get_system_prompt(
638
+ "test_doctor",
639
+ """You are the Test Doctor, a testing expert.
640
+
641
+ Your focus:
642
+ 1. Parse pytest output for failures
643
+ 2. Analyze failure type (assertion, exception, timeout)
644
+ 3. Determine root cause (test bug vs code bug)
645
+ 4. Generate fixes for test issues
646
+ 5. Identify flaky tests
647
+
648
+ Rules:
649
+ - Distinguish test bugs from code bugs
650
+ - Never remove assertions to fix tests
651
+ - Prefer fixing setup over mocking
652
+ - Flag implementation-coupled tests""",
653
+ ),
654
+ model_tier=self.config.tests_tier,
655
+ memory_graph_enabled=self.config.memory_graph_enabled,
656
+ memory_graph_path=self.config.memory_graph_path,
657
+ )
658
+
659
+ # 5. Dep Auditor
660
+ self._agents["deps"] = self._factory.create_agent(
661
+ name="dep_auditor",
662
+ role="analyst",
663
+ description="Expert at auditing dependencies",
664
+ system_prompt=self._get_system_prompt(
665
+ "dep_auditor",
666
+ """You are the Dep Auditor, a dependency expert.
667
+
668
+ Your focus:
669
+ 1. Check for security vulnerabilities
670
+ 2. Identify outdated packages
671
+ 3. Assess update risk
672
+ 4. Check for conflicts
673
+ 5. Suggest safe update paths
674
+
675
+ Rules:
676
+ - Prioritize security over outdated
677
+ - Be conservative with major upgrades
678
+ - Check changelogs for breaking changes
679
+ - Consider transitive impacts""",
680
+ ),
681
+ model_tier=self.config.deps_tier,
682
+ memory_graph_enabled=self.config.memory_graph_enabled,
683
+ memory_graph_path=self.config.memory_graph_path,
684
+ )
685
+
686
+ async def _create_workflow(self) -> None:
687
+ """Create hierarchical workflow with Health Lead as manager."""
688
+ agents = list(self._agents.values())
689
+
690
+ self._workflow = self._factory.create_workflow(
691
+ name="health_check_workflow",
692
+ agents=agents,
693
+ mode="hierarchical",
694
+ description="Comprehensive health check with coordinated diagnosis and fixes",
695
+ )
696
+
697
+ async def check(
698
+ self,
699
+ path: str = ".",
700
+ auto_fix: bool | None = None,
701
+ context: dict | None = None,
702
+ ) -> HealthCheckReport:
703
+ """Perform a comprehensive health check.
704
+
705
+ Args:
706
+ path: Path to check (default: current directory)
707
+ auto_fix: Override config auto_fix setting
708
+ context: Optional context (focus areas, previous checks, etc.)
709
+
710
+ Returns:
711
+ HealthCheckReport with issues, fixes, and health score
712
+
713
+ """
714
+ import time
715
+
716
+ start_time = time.time()
717
+
718
+ # Initialize if needed
719
+ await self._initialize()
720
+
721
+ context = context or {}
722
+ auto_fix = auto_fix if auto_fix is not None else self.config.auto_fix
723
+ issues: list[HealthIssue] = []
724
+ fixes: list[HealthFix] = []
725
+ checks_run: dict[str, dict] = {}
726
+ memory_hits = 0
727
+
728
+ # Run the individual checks first to gather data
729
+ if self.config.check_lint:
730
+ lint_result = await self._run_lint_check(path)
731
+ checks_run["lint"] = lint_result
732
+ issues.extend(lint_result.get("issues", []))
733
+
734
+ if self.config.check_types:
735
+ types_result = await self._run_type_check(path)
736
+ checks_run["types"] = types_result
737
+ issues.extend(types_result.get("issues", []))
738
+
739
+ if self.config.check_tests:
740
+ tests_result = await self._run_test_check(path)
741
+ checks_run["tests"] = tests_result
742
+ issues.extend(tests_result.get("issues", []))
743
+
744
+ if self.config.check_deps:
745
+ deps_result = await self._run_dep_check(path)
746
+ checks_run["deps"] = deps_result
747
+ issues.extend(deps_result.get("issues", []))
748
+
749
+ # Check Memory Graph for similar past issues
750
+ if self._graph and self.config.memory_graph_enabled:
751
+ try:
752
+ similar = self._graph.find_similar(
753
+ {"name": f"health_check:{path}", "description": f"Health check of {path}"},
754
+ threshold=0.4,
755
+ limit=10,
756
+ )
757
+ if similar:
758
+ memory_hits = len(similar)
759
+ context["past_checks"] = [
760
+ {
761
+ "name": node.name,
762
+ "health_score": node.metadata.get("health_score", 0),
763
+ "issues_found": node.metadata.get("issues_found", 0),
764
+ }
765
+ for node, score in similar
766
+ ]
767
+ logger.info(f"Found {memory_hits} similar past health checks")
768
+ except Exception as e:
769
+ logger.warning(f"Error querying Memory Graph: {e}")
770
+
771
+ # Build task for the crew to analyze and generate fixes
772
+ check_task = self._build_check_task(path, checks_run, issues, auto_fix, context)
773
+
774
+ # Execute the workflow for analysis
775
+ try:
776
+ result = await self._workflow.run(check_task, initial_state=context)
777
+
778
+ # Parse fixes from result
779
+ fixes = self._parse_fixes(result, issues)
780
+
781
+ # Apply auto-fixes if enabled
782
+ if auto_fix:
783
+ fixes = await self._apply_fixes(fixes, path)
784
+
785
+ except Exception as e:
786
+ logger.error(f"Health check analysis failed: {e}")
787
+
788
+ # Calculate health score
789
+ health_score = self._calculate_health_score(issues)
790
+
791
+ # Build the report
792
+ duration = time.time() - start_time
793
+ report = HealthCheckReport(
794
+ target=path,
795
+ issues=issues,
796
+ fixes=fixes,
797
+ health_score=health_score,
798
+ check_duration_seconds=duration,
799
+ agents_used=list(self._agents.keys()),
800
+ memory_graph_hits=memory_hits,
801
+ checks_run={k: {"passed": v.get("passed", False)} for k, v in checks_run.items()},
802
+ metadata={
803
+ "auto_fix": auto_fix,
804
+ "framework": str(self._factory.framework.value) if self._factory else "unknown",
805
+ "xml_prompts": self.config.xml_prompts_enabled,
806
+ },
807
+ )
808
+
809
+ # Store check in Memory Graph
810
+ if self._graph and self.config.memory_graph_enabled:
811
+ try:
812
+ self._graph.add_finding(
813
+ "health_check_crew",
814
+ {
815
+ "type": "health_check",
816
+ "name": f"check:{path}",
817
+ "description": f"Health score: {health_score}/100",
818
+ "health_score": health_score,
819
+ "issues_found": len(issues),
820
+ "fixes_applied": len(report.applied_fixes),
821
+ },
822
+ )
823
+ self._graph._save()
824
+ except Exception as e:
825
+ logger.warning(f"Error storing check in Memory Graph: {e}")
826
+
827
+ return report
828
+
829
+ async def _run_lint_check(self, path: str) -> dict:
830
+ """Run ruff lint check."""
831
+ issues = []
832
+ passed = True
833
+
834
+ try:
835
+ result = subprocess.run(
836
+ ["python", "-m", "ruff", "check", path, "--output-format=json"],
837
+ check=False,
838
+ capture_output=True,
839
+ text=True,
840
+ timeout=60,
841
+ )
842
+
843
+ if result.returncode != 0:
844
+ passed = False
845
+
846
+ # Parse JSON output
847
+ import json
848
+
849
+ try:
850
+ violations = json.loads(result.stdout) if result.stdout else []
851
+ for v in violations[:50]: # Limit to 50
852
+ issues.append(
853
+ HealthIssue(
854
+ title=f"{v.get('code', 'LINT')}: {v.get('message', 'Lint error')}",
855
+ description=v.get("message", ""),
856
+ category=HealthCategory.LINT,
857
+ severity=IssueSeverity.MEDIUM,
858
+ file_path=v.get("filename"),
859
+ line_number=v.get("location", {}).get("row"),
860
+ rule_id=v.get("code"),
861
+ tool="ruff",
862
+ ),
863
+ )
864
+ except json.JSONDecodeError:
865
+ pass
866
+
867
+ except (subprocess.TimeoutExpired, FileNotFoundError) as e:
868
+ logger.warning(f"Lint check failed: {e}")
869
+
870
+ return {"passed": passed, "issues": issues, "tool": "ruff"}
871
+
872
+ async def _run_type_check(self, path: str) -> dict:
873
+ """Run mypy type check."""
874
+ issues = []
875
+ passed = True
876
+
877
+ try:
878
+ result = subprocess.run(
879
+ ["python", "-m", "mypy", path, "--ignore-missing-imports", "--no-error-summary"],
880
+ check=False,
881
+ capture_output=True,
882
+ text=True,
883
+ timeout=120,
884
+ )
885
+
886
+ if result.returncode != 0:
887
+ passed = False
888
+
889
+ # Parse text output
890
+ for line in result.stdout.splitlines()[:50]:
891
+ if ": error:" in line:
892
+ parts = line.split(": error:", 1)
893
+ location = parts[0] if parts else ""
894
+ message = parts[1].strip() if len(parts) > 1 else line
895
+
896
+ file_path = None
897
+ line_num = None
898
+ if ":" in location:
899
+ loc_parts = location.rsplit(":", 2)
900
+ file_path = loc_parts[0]
901
+ try:
902
+ line_num = int(loc_parts[1]) if len(loc_parts) > 1 else None
903
+ except ValueError:
904
+ pass
905
+
906
+ issues.append(
907
+ HealthIssue(
908
+ title=f"Type error: {message[:60]}",
909
+ description=message,
910
+ category=HealthCategory.TYPES,
911
+ severity=IssueSeverity.MEDIUM,
912
+ file_path=file_path,
913
+ line_number=line_num,
914
+ tool="mypy",
915
+ ),
916
+ )
917
+
918
+ except (subprocess.TimeoutExpired, FileNotFoundError) as e:
919
+ logger.warning(f"Type check failed: {e}")
920
+
921
+ return {"passed": passed, "issues": issues, "tool": "mypy"}
922
+
923
+ async def _run_test_check(self, path: str) -> dict:
924
+ """Run pytest test check."""
925
+ issues = []
926
+ passed = True
927
+
928
+ try:
929
+ result = subprocess.run(
930
+ ["python", "-m", "pytest", path, "--tb=line", "-q", "--no-header"],
931
+ check=False,
932
+ capture_output=True,
933
+ text=True,
934
+ timeout=180,
935
+ cwd=path if Path(path).is_dir() else ".",
936
+ )
937
+
938
+ if result.returncode != 0:
939
+ passed = False
940
+
941
+ # Parse output for failures
942
+ for line in result.stdout.splitlines()[:50]:
943
+ if "FAILED" in line:
944
+ # Extract test name
945
+ test_name = line.split("FAILED")[0].strip()
946
+ issues.append(
947
+ HealthIssue(
948
+ title=f"Test failed: {test_name[:50]}",
949
+ description=line,
950
+ category=HealthCategory.TESTS,
951
+ severity=IssueSeverity.HIGH,
952
+ file_path=test_name.split("::")[0] if "::" in test_name else None,
953
+ tool="pytest",
954
+ ),
955
+ )
956
+ elif "ERROR" in line and "test" in line.lower():
957
+ issues.append(
958
+ HealthIssue(
959
+ title=f"Test error: {line[:50]}",
960
+ description=line,
961
+ category=HealthCategory.TESTS,
962
+ severity=IssueSeverity.CRITICAL,
963
+ tool="pytest",
964
+ ),
965
+ )
966
+
967
+ except (subprocess.TimeoutExpired, FileNotFoundError) as e:
968
+ logger.warning(f"Test check failed: {e}")
969
+
970
+ return {"passed": passed, "issues": issues, "tool": "pytest"}
971
+
972
+ async def _run_dep_check(self, path: str) -> dict:
973
+ """Run dependency security check."""
974
+ issues = []
975
+ passed = True
976
+
977
+ # Try pip-audit first
978
+ try:
979
+ result = subprocess.run(
980
+ ["pip-audit", "--format=json"],
981
+ check=False,
982
+ capture_output=True,
983
+ text=True,
984
+ timeout=60,
985
+ cwd=path if Path(path).is_dir() else ".",
986
+ )
987
+
988
+ if result.returncode != 0:
989
+ passed = False
990
+
991
+ import json
992
+
993
+ try:
994
+ vulns = json.loads(result.stdout) if result.stdout else []
995
+ # Ensure vulns is a list
996
+ if isinstance(vulns, dict):
997
+ vulns = vulns.get("vulnerabilities", []) or list(vulns.values())
998
+ if not isinstance(vulns, list):
999
+ vulns = []
1000
+ for v in vulns[:20]:
1001
+ # Handle different vulnerability formats
1002
+ if not isinstance(v, dict):
1003
+ # Skip non-dict items or convert to basic format
1004
+ continue
1005
+
1006
+ severity = IssueSeverity.HIGH
1007
+ if "critical" in str(v).lower():
1008
+ severity = IssueSeverity.CRITICAL
1009
+
1010
+ issues.append(
1011
+ HealthIssue(
1012
+ title=f"Vulnerability in {v.get('name', 'unknown')}",
1013
+ description=v.get("description", str(v)),
1014
+ category=HealthCategory.DEPENDENCIES,
1015
+ severity=severity,
1016
+ rule_id=v.get("id"),
1017
+ tool="pip-audit",
1018
+ metadata={"fix_versions": v.get("fix_versions", [])},
1019
+ ),
1020
+ )
1021
+ except json.JSONDecodeError:
1022
+ pass
1023
+
1024
+ except (subprocess.TimeoutExpired, FileNotFoundError):
1025
+ # pip-audit not installed, try basic pip check
1026
+ try:
1027
+ result = subprocess.run(
1028
+ ["pip", "check"],
1029
+ check=False,
1030
+ capture_output=True,
1031
+ text=True,
1032
+ timeout=30,
1033
+ )
1034
+ if result.returncode != 0:
1035
+ passed = False
1036
+ for line in result.stdout.splitlines()[:10]:
1037
+ issues.append(
1038
+ HealthIssue(
1039
+ title=f"Dependency conflict: {line[:50]}",
1040
+ description=line,
1041
+ category=HealthCategory.DEPENDENCIES,
1042
+ severity=IssueSeverity.MEDIUM,
1043
+ tool="pip",
1044
+ ),
1045
+ )
1046
+ except (subprocess.TimeoutExpired, FileNotFoundError):
1047
+ pass
1048
+
1049
+ return {"passed": passed, "issues": issues, "tool": "pip-audit/pip"}
1050
+
1051
+ def _build_check_task(
1052
+ self,
1053
+ path: str,
1054
+ checks_run: dict,
1055
+ issues: list[HealthIssue],
1056
+ auto_fix: bool,
1057
+ context: dict,
1058
+ ) -> str:
1059
+ """Build the check task description for the crew."""
1060
+ issues_summary = "\n".join(
1061
+ f" - [{i.severity.value.upper()}] {i.category.value}: {i.title}" for i in issues[:30]
1062
+ )
1063
+
1064
+ task = f"""Analyze health check results and generate fixes.
1065
+
1066
+ Target: {path}
1067
+ Auto-fix enabled: {auto_fix}
1068
+
1069
+ Checks Run:
1070
+ - Lint (ruff): {"PASS" if checks_run.get("lint", {}).get("passed") else "FAIL"}
1071
+ - Types (mypy): {"PASS" if checks_run.get("types", {}).get("passed") else "FAIL"}
1072
+ - Tests (pytest): {"PASS" if checks_run.get("tests", {}).get("passed") else "FAIL"}
1073
+ - Dependencies: {"PASS" if checks_run.get("deps", {}).get("passed") else "FAIL"}
1074
+
1075
+ Issues Found ({len(issues)}):
1076
+ {issues_summary}
1077
+
1078
+ Workflow:
1079
+ 1. Health Lead coordinates analysis
1080
+ 2. Lint Fixer analyzes and suggests fixes for lint issues
1081
+ 3. Type Resolver suggests type annotations
1082
+ 4. Test Doctor diagnoses test failures
1083
+ 5. Dep Auditor suggests dependency updates
1084
+
1085
+ For each issue, provide:
1086
+ - Root cause analysis
1087
+ - Fix recommendation (code if applicable)
1088
+ - Safety assessment (safe to auto-fix or needs review)
1089
+ - Priority (1=critical, 2=high, 3=medium, 4=low)
1090
+
1091
+ Generate a prioritized fix plan.
1092
+ """
1093
+
1094
+ if context.get("past_checks"):
1095
+ task += f"""
1096
+ Past Health Checks Found: {len(context["past_checks"])}
1097
+ Consider patterns from past fixes.
1098
+ """
1099
+
1100
+ return task
1101
+
1102
+ def _parse_fixes(self, result: dict, issues: list[HealthIssue]) -> list[HealthFix]:
1103
+ """Parse fixes from workflow result."""
1104
+ fixes = []
1105
+
1106
+ # Check for structured fixes in metadata
1107
+ metadata = result.get("metadata", {})
1108
+ if "fixes" in metadata:
1109
+ for f in metadata["fixes"]:
1110
+ fixes.append(
1111
+ HealthFix(
1112
+ title=f.get("title", "Fix"),
1113
+ description=f.get("description", ""),
1114
+ category=HealthCategory(f.get("category", "general")),
1115
+ status=FixStatus.SUGGESTED,
1116
+ file_path=f.get("file_path"),
1117
+ before_code=f.get("before_code"),
1118
+ after_code=f.get("after_code"),
1119
+ patch=f.get("patch"),
1120
+ ),
1121
+ )
1122
+ return fixes
1123
+
1124
+ # Generate suggested fixes based on issues
1125
+ for issue in issues:
1126
+ if issue.category == HealthCategory.LINT and issue.rule_id:
1127
+ fixes.append(
1128
+ HealthFix(
1129
+ title=f"Fix {issue.rule_id}",
1130
+ description=f"Run: ruff check --fix --select {issue.rule_id}",
1131
+ category=issue.category,
1132
+ status=FixStatus.SUGGESTED,
1133
+ file_path=issue.file_path,
1134
+ related_issues=[issue.title],
1135
+ ),
1136
+ )
1137
+
1138
+ return fixes
1139
+
1140
+ async def _apply_fixes(self, fixes: list[HealthFix], path: str) -> list[HealthFix]:
1141
+ """Apply safe auto-fixes."""
1142
+ updated_fixes = []
1143
+
1144
+ for fix in fixes:
1145
+ if fix.category == HealthCategory.LINT and self.config.fix_safe_only:
1146
+ # Run ruff --fix for lint issues
1147
+ try:
1148
+ result = subprocess.run(
1149
+ ["python", "-m", "ruff", "check", path, "--fix"],
1150
+ check=False,
1151
+ capture_output=True,
1152
+ text=True,
1153
+ timeout=60,
1154
+ )
1155
+ fix.status = FixStatus.APPLIED if result.returncode == 0 else FixStatus.FAILED
1156
+ except Exception:
1157
+ fix.status = FixStatus.FAILED
1158
+ else:
1159
+ fix.status = FixStatus.SUGGESTED
1160
+
1161
+ updated_fixes.append(fix)
1162
+
1163
+ return updated_fixes
1164
+
1165
+ def _calculate_health_score(self, issues: list[HealthIssue]) -> float:
1166
+ """Calculate health score from issues.
1167
+
1168
+ Uses category-capped deductions to prevent one category (e.g., lint)
1169
+ from dominating the score. This makes the score more meaningful -
1170
+ 50 lint warnings shouldn't tank a project that passes tests and has
1171
+ no security issues.
1172
+
1173
+ Category caps:
1174
+ - lint: max -15 points
1175
+ - types: max -20 points
1176
+ - tests: max -25 points
1177
+ - security/dependencies: max -30 points
1178
+ - general: max -10 points
1179
+ """
1180
+ if not issues:
1181
+ return 100.0
1182
+
1183
+ # Per-issue deductions by severity
1184
+ severity_deductions = {
1185
+ IssueSeverity.CRITICAL: 15,
1186
+ IssueSeverity.HIGH: 8,
1187
+ IssueSeverity.MEDIUM: 2,
1188
+ IssueSeverity.LOW: 0.5,
1189
+ IssueSeverity.INFO: 0,
1190
+ }
1191
+
1192
+ # Maximum deduction per category (prevents one area from tanking score)
1193
+ category_caps = {
1194
+ HealthCategory.LINT: 15,
1195
+ HealthCategory.TYPES: 20,
1196
+ HealthCategory.TESTS: 25,
1197
+ HealthCategory.DEPENDENCIES: 30,
1198
+ HealthCategory.SECURITY: 30,
1199
+ HealthCategory.GENERAL: 10,
1200
+ }
1201
+
1202
+ # Calculate deductions per category
1203
+ category_deductions: dict[HealthCategory, float] = {}
1204
+ for issue in issues:
1205
+ cat = issue.category
1206
+ deduction = severity_deductions.get(issue.severity, 0)
1207
+ category_deductions[cat] = category_deductions.get(cat, 0) + deduction
1208
+
1209
+ # Apply caps per category
1210
+ total_deduction = 0.0
1211
+ for cat, deduction in category_deductions.items():
1212
+ cap = category_caps.get(cat, 10)
1213
+ total_deduction += min(deduction, cap)
1214
+
1215
+ return max(0.0, 100.0 - total_deduction)
1216
+
1217
+ @property
1218
+ def agents(self) -> dict[str, Any]:
1219
+ """Get the crew's agents."""
1220
+ return self._agents
1221
+
1222
+ @property
1223
+ def is_initialized(self) -> bool:
1224
+ """Check if crew is initialized."""
1225
+ return self._initialized
1226
+
1227
+ async def get_agent_stats(self) -> dict:
1228
+ """Get statistics about crew agents."""
1229
+ await self._initialize()
1230
+
1231
+ agents_dict: dict = {}
1232
+ stats: dict = {
1233
+ "agent_count": len(self._agents),
1234
+ "agents": agents_dict,
1235
+ "framework": self._factory.framework.value if self._factory else "unknown",
1236
+ "memory_graph_enabled": self.config.memory_graph_enabled,
1237
+ "xml_prompts_enabled": self.config.xml_prompts_enabled,
1238
+ }
1239
+
1240
+ for name, agent in self._agents.items():
1241
+ agents_dict[name] = {
1242
+ "role": agent.config.role if hasattr(agent, "config") else "unknown",
1243
+ "model_tier": getattr(agent.config, "model_tier", "unknown"),
1244
+ }
1245
+
1246
+ return stats