attune-ai 2.0.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.
- attune/__init__.py +358 -0
- attune/adaptive/__init__.py +13 -0
- attune/adaptive/task_complexity.py +127 -0
- attune/agent_monitoring.py +414 -0
- attune/cache/__init__.py +117 -0
- attune/cache/base.py +166 -0
- attune/cache/dependency_manager.py +256 -0
- attune/cache/hash_only.py +251 -0
- attune/cache/hybrid.py +457 -0
- attune/cache/storage.py +285 -0
- attune/cache_monitor.py +356 -0
- attune/cache_stats.py +298 -0
- attune/cli/__init__.py +152 -0
- attune/cli/__main__.py +12 -0
- attune/cli/commands/__init__.py +1 -0
- attune/cli/commands/batch.py +264 -0
- attune/cli/commands/cache.py +248 -0
- attune/cli/commands/help.py +331 -0
- attune/cli/commands/info.py +140 -0
- attune/cli/commands/inspect.py +436 -0
- attune/cli/commands/inspection.py +57 -0
- attune/cli/commands/memory.py +48 -0
- attune/cli/commands/metrics.py +92 -0
- attune/cli/commands/orchestrate.py +184 -0
- attune/cli/commands/patterns.py +207 -0
- attune/cli/commands/profiling.py +202 -0
- attune/cli/commands/provider.py +98 -0
- attune/cli/commands/routing.py +285 -0
- attune/cli/commands/setup.py +96 -0
- attune/cli/commands/status.py +235 -0
- attune/cli/commands/sync.py +166 -0
- attune/cli/commands/tier.py +121 -0
- attune/cli/commands/utilities.py +114 -0
- attune/cli/commands/workflow.py +579 -0
- attune/cli/core.py +32 -0
- attune/cli/parsers/__init__.py +68 -0
- attune/cli/parsers/batch.py +118 -0
- attune/cli/parsers/cache.py +65 -0
- attune/cli/parsers/help.py +41 -0
- attune/cli/parsers/info.py +26 -0
- attune/cli/parsers/inspect.py +66 -0
- attune/cli/parsers/metrics.py +42 -0
- attune/cli/parsers/orchestrate.py +61 -0
- attune/cli/parsers/patterns.py +54 -0
- attune/cli/parsers/provider.py +40 -0
- attune/cli/parsers/routing.py +110 -0
- attune/cli/parsers/setup.py +42 -0
- attune/cli/parsers/status.py +47 -0
- attune/cli/parsers/sync.py +31 -0
- attune/cli/parsers/tier.py +33 -0
- attune/cli/parsers/workflow.py +77 -0
- attune/cli/utils/__init__.py +1 -0
- attune/cli/utils/data.py +242 -0
- attune/cli/utils/helpers.py +68 -0
- attune/cli_legacy.py +3957 -0
- attune/cli_minimal.py +1159 -0
- attune/cli_router.py +437 -0
- attune/cli_unified.py +814 -0
- attune/config/__init__.py +66 -0
- attune/config/xml_config.py +286 -0
- attune/config.py +545 -0
- attune/coordination.py +870 -0
- attune/core.py +1511 -0
- attune/core_modules/__init__.py +15 -0
- attune/cost_tracker.py +626 -0
- attune/dashboard/__init__.py +41 -0
- attune/dashboard/app.py +512 -0
- attune/dashboard/simple_server.py +435 -0
- attune/dashboard/standalone_server.py +547 -0
- attune/discovery.py +306 -0
- attune/emergence.py +306 -0
- attune/exceptions.py +123 -0
- attune/feedback_loops.py +373 -0
- attune/hot_reload/README.md +473 -0
- attune/hot_reload/__init__.py +62 -0
- attune/hot_reload/config.py +83 -0
- attune/hot_reload/integration.py +229 -0
- attune/hot_reload/reloader.py +298 -0
- attune/hot_reload/watcher.py +183 -0
- attune/hot_reload/websocket.py +177 -0
- attune/levels.py +577 -0
- attune/leverage_points.py +441 -0
- attune/logging_config.py +261 -0
- attune/mcp/__init__.py +10 -0
- attune/mcp/server.py +506 -0
- attune/memory/__init__.py +237 -0
- attune/memory/claude_memory.py +469 -0
- attune/memory/config.py +224 -0
- attune/memory/control_panel.py +1290 -0
- attune/memory/control_panel_support.py +145 -0
- attune/memory/cross_session.py +845 -0
- attune/memory/edges.py +179 -0
- attune/memory/encryption.py +159 -0
- attune/memory/file_session.py +770 -0
- attune/memory/graph.py +570 -0
- attune/memory/long_term.py +913 -0
- attune/memory/long_term_types.py +99 -0
- attune/memory/mixins/__init__.py +25 -0
- attune/memory/mixins/backend_init_mixin.py +249 -0
- attune/memory/mixins/capabilities_mixin.py +208 -0
- attune/memory/mixins/handoff_mixin.py +208 -0
- attune/memory/mixins/lifecycle_mixin.py +49 -0
- attune/memory/mixins/long_term_mixin.py +352 -0
- attune/memory/mixins/promotion_mixin.py +109 -0
- attune/memory/mixins/short_term_mixin.py +182 -0
- attune/memory/nodes.py +179 -0
- attune/memory/redis_bootstrap.py +540 -0
- attune/memory/security/__init__.py +31 -0
- attune/memory/security/audit_logger.py +932 -0
- attune/memory/security/pii_scrubber.py +640 -0
- attune/memory/security/secrets_detector.py +678 -0
- attune/memory/short_term.py +2192 -0
- attune/memory/simple_storage.py +302 -0
- attune/memory/storage/__init__.py +15 -0
- attune/memory/storage_backend.py +167 -0
- attune/memory/summary_index.py +583 -0
- attune/memory/types.py +446 -0
- attune/memory/unified.py +182 -0
- attune/meta_workflows/__init__.py +74 -0
- attune/meta_workflows/agent_creator.py +248 -0
- attune/meta_workflows/builtin_templates.py +567 -0
- attune/meta_workflows/cli_commands/__init__.py +56 -0
- attune/meta_workflows/cli_commands/agent_commands.py +321 -0
- attune/meta_workflows/cli_commands/analytics_commands.py +442 -0
- attune/meta_workflows/cli_commands/config_commands.py +232 -0
- attune/meta_workflows/cli_commands/memory_commands.py +182 -0
- attune/meta_workflows/cli_commands/template_commands.py +354 -0
- attune/meta_workflows/cli_commands/workflow_commands.py +382 -0
- attune/meta_workflows/cli_meta_workflows.py +59 -0
- attune/meta_workflows/form_engine.py +292 -0
- attune/meta_workflows/intent_detector.py +409 -0
- attune/meta_workflows/models.py +569 -0
- attune/meta_workflows/pattern_learner.py +738 -0
- attune/meta_workflows/plan_generator.py +384 -0
- attune/meta_workflows/session_context.py +397 -0
- attune/meta_workflows/template_registry.py +229 -0
- attune/meta_workflows/workflow.py +984 -0
- attune/metrics/__init__.py +12 -0
- attune/metrics/collector.py +31 -0
- attune/metrics/prompt_metrics.py +194 -0
- attune/models/__init__.py +172 -0
- attune/models/__main__.py +13 -0
- attune/models/adaptive_routing.py +437 -0
- attune/models/auth_cli.py +444 -0
- attune/models/auth_strategy.py +450 -0
- attune/models/cli.py +655 -0
- attune/models/empathy_executor.py +354 -0
- attune/models/executor.py +257 -0
- attune/models/fallback.py +762 -0
- attune/models/provider_config.py +282 -0
- attune/models/registry.py +472 -0
- attune/models/tasks.py +359 -0
- attune/models/telemetry/__init__.py +71 -0
- attune/models/telemetry/analytics.py +594 -0
- attune/models/telemetry/backend.py +196 -0
- attune/models/telemetry/data_models.py +431 -0
- attune/models/telemetry/storage.py +489 -0
- attune/models/token_estimator.py +420 -0
- attune/models/validation.py +280 -0
- attune/monitoring/__init__.py +52 -0
- attune/monitoring/alerts.py +946 -0
- attune/monitoring/alerts_cli.py +448 -0
- attune/monitoring/multi_backend.py +271 -0
- attune/monitoring/otel_backend.py +362 -0
- attune/optimization/__init__.py +19 -0
- attune/optimization/context_optimizer.py +272 -0
- attune/orchestration/__init__.py +67 -0
- attune/orchestration/agent_templates.py +707 -0
- attune/orchestration/config_store.py +499 -0
- attune/orchestration/execution_strategies.py +2111 -0
- attune/orchestration/meta_orchestrator.py +1168 -0
- attune/orchestration/pattern_learner.py +696 -0
- attune/orchestration/real_tools.py +931 -0
- attune/pattern_cache.py +187 -0
- attune/pattern_library.py +542 -0
- attune/patterns/debugging/all_patterns.json +81 -0
- attune/patterns/debugging/workflow_20260107_1770825e.json +77 -0
- attune/patterns/refactoring_memory.json +89 -0
- attune/persistence.py +564 -0
- attune/platform_utils.py +265 -0
- attune/plugins/__init__.py +28 -0
- attune/plugins/base.py +361 -0
- attune/plugins/registry.py +268 -0
- attune/project_index/__init__.py +32 -0
- attune/project_index/cli.py +335 -0
- attune/project_index/index.py +667 -0
- attune/project_index/models.py +504 -0
- attune/project_index/reports.py +474 -0
- attune/project_index/scanner.py +777 -0
- attune/project_index/scanner_parallel.py +291 -0
- attune/prompts/__init__.py +61 -0
- attune/prompts/config.py +77 -0
- attune/prompts/context.py +177 -0
- attune/prompts/parser.py +285 -0
- attune/prompts/registry.py +313 -0
- attune/prompts/templates.py +208 -0
- attune/redis_config.py +302 -0
- attune/redis_memory.py +799 -0
- attune/resilience/__init__.py +56 -0
- attune/resilience/circuit_breaker.py +256 -0
- attune/resilience/fallback.py +179 -0
- attune/resilience/health.py +300 -0
- attune/resilience/retry.py +209 -0
- attune/resilience/timeout.py +135 -0
- attune/routing/__init__.py +43 -0
- attune/routing/chain_executor.py +433 -0
- attune/routing/classifier.py +217 -0
- attune/routing/smart_router.py +234 -0
- attune/routing/workflow_registry.py +343 -0
- attune/scaffolding/README.md +589 -0
- attune/scaffolding/__init__.py +35 -0
- attune/scaffolding/__main__.py +14 -0
- attune/scaffolding/cli.py +240 -0
- attune/scaffolding/templates/base_wizard.py.jinja2 +121 -0
- attune/scaffolding/templates/coach_wizard.py.jinja2 +321 -0
- attune/scaffolding/templates/domain_wizard.py.jinja2 +408 -0
- attune/scaffolding/templates/linear_flow_wizard.py.jinja2 +203 -0
- attune/socratic/__init__.py +256 -0
- attune/socratic/ab_testing.py +958 -0
- attune/socratic/blueprint.py +533 -0
- attune/socratic/cli.py +703 -0
- attune/socratic/collaboration.py +1114 -0
- attune/socratic/domain_templates.py +924 -0
- attune/socratic/embeddings.py +738 -0
- attune/socratic/engine.py +794 -0
- attune/socratic/explainer.py +682 -0
- attune/socratic/feedback.py +772 -0
- attune/socratic/forms.py +629 -0
- attune/socratic/generator.py +732 -0
- attune/socratic/llm_analyzer.py +637 -0
- attune/socratic/mcp_server.py +702 -0
- attune/socratic/session.py +312 -0
- attune/socratic/storage.py +667 -0
- attune/socratic/success.py +730 -0
- attune/socratic/visual_editor.py +860 -0
- attune/socratic/web_ui.py +958 -0
- attune/telemetry/__init__.py +39 -0
- attune/telemetry/agent_coordination.py +475 -0
- attune/telemetry/agent_tracking.py +367 -0
- attune/telemetry/approval_gates.py +545 -0
- attune/telemetry/cli.py +1231 -0
- attune/telemetry/commands/__init__.py +14 -0
- attune/telemetry/commands/dashboard_commands.py +696 -0
- attune/telemetry/event_streaming.py +409 -0
- attune/telemetry/feedback_loop.py +567 -0
- attune/telemetry/usage_tracker.py +591 -0
- attune/templates.py +754 -0
- attune/test_generator/__init__.py +38 -0
- attune/test_generator/__main__.py +14 -0
- attune/test_generator/cli.py +234 -0
- attune/test_generator/generator.py +355 -0
- attune/test_generator/risk_analyzer.py +216 -0
- attune/test_generator/templates/unit_test.py.jinja2 +272 -0
- attune/tier_recommender.py +384 -0
- attune/tools.py +183 -0
- attune/trust/__init__.py +28 -0
- attune/trust/circuit_breaker.py +579 -0
- attune/trust_building.py +527 -0
- attune/validation/__init__.py +19 -0
- attune/validation/xml_validator.py +281 -0
- attune/vscode_bridge.py +173 -0
- attune/workflow_commands.py +780 -0
- attune/workflow_patterns/__init__.py +33 -0
- attune/workflow_patterns/behavior.py +249 -0
- attune/workflow_patterns/core.py +76 -0
- attune/workflow_patterns/output.py +99 -0
- attune/workflow_patterns/registry.py +255 -0
- attune/workflow_patterns/structural.py +288 -0
- attune/workflows/__init__.py +539 -0
- attune/workflows/autonomous_test_gen.py +1268 -0
- attune/workflows/base.py +2667 -0
- attune/workflows/batch_processing.py +342 -0
- attune/workflows/bug_predict.py +1084 -0
- attune/workflows/builder.py +273 -0
- attune/workflows/caching.py +253 -0
- attune/workflows/code_review.py +1048 -0
- attune/workflows/code_review_adapters.py +312 -0
- attune/workflows/code_review_pipeline.py +722 -0
- attune/workflows/config.py +645 -0
- attune/workflows/dependency_check.py +644 -0
- attune/workflows/document_gen/__init__.py +25 -0
- attune/workflows/document_gen/config.py +30 -0
- attune/workflows/document_gen/report_formatter.py +162 -0
- attune/workflows/document_gen/workflow.py +1426 -0
- attune/workflows/document_manager.py +216 -0
- attune/workflows/document_manager_README.md +134 -0
- attune/workflows/documentation_orchestrator.py +1205 -0
- attune/workflows/history.py +510 -0
- attune/workflows/keyboard_shortcuts/__init__.py +39 -0
- attune/workflows/keyboard_shortcuts/generators.py +391 -0
- attune/workflows/keyboard_shortcuts/parsers.py +416 -0
- attune/workflows/keyboard_shortcuts/prompts.py +295 -0
- attune/workflows/keyboard_shortcuts/schema.py +193 -0
- attune/workflows/keyboard_shortcuts/workflow.py +509 -0
- attune/workflows/llm_base.py +363 -0
- attune/workflows/manage_docs.py +87 -0
- attune/workflows/manage_docs_README.md +134 -0
- attune/workflows/manage_documentation.py +821 -0
- attune/workflows/new_sample_workflow1.py +149 -0
- attune/workflows/new_sample_workflow1_README.md +150 -0
- attune/workflows/orchestrated_health_check.py +849 -0
- attune/workflows/orchestrated_release_prep.py +600 -0
- attune/workflows/output.py +413 -0
- attune/workflows/perf_audit.py +863 -0
- attune/workflows/pr_review.py +762 -0
- attune/workflows/progress.py +785 -0
- attune/workflows/progress_server.py +322 -0
- attune/workflows/progressive/README 2.md +454 -0
- attune/workflows/progressive/README.md +454 -0
- attune/workflows/progressive/__init__.py +82 -0
- attune/workflows/progressive/cli.py +219 -0
- attune/workflows/progressive/core.py +488 -0
- attune/workflows/progressive/orchestrator.py +723 -0
- attune/workflows/progressive/reports.py +520 -0
- attune/workflows/progressive/telemetry.py +274 -0
- attune/workflows/progressive/test_gen.py +495 -0
- attune/workflows/progressive/workflow.py +589 -0
- attune/workflows/refactor_plan.py +694 -0
- attune/workflows/release_prep.py +895 -0
- attune/workflows/release_prep_crew.py +969 -0
- attune/workflows/research_synthesis.py +404 -0
- attune/workflows/routing.py +168 -0
- attune/workflows/secure_release.py +593 -0
- attune/workflows/security_adapters.py +297 -0
- attune/workflows/security_audit.py +1329 -0
- attune/workflows/security_audit_phase3.py +355 -0
- attune/workflows/seo_optimization.py +633 -0
- attune/workflows/step_config.py +234 -0
- attune/workflows/telemetry_mixin.py +269 -0
- attune/workflows/test5.py +125 -0
- attune/workflows/test5_README.md +158 -0
- attune/workflows/test_coverage_boost_crew.py +849 -0
- attune/workflows/test_gen/__init__.py +52 -0
- attune/workflows/test_gen/ast_analyzer.py +249 -0
- attune/workflows/test_gen/config.py +88 -0
- attune/workflows/test_gen/data_models.py +38 -0
- attune/workflows/test_gen/report_formatter.py +289 -0
- attune/workflows/test_gen/test_templates.py +381 -0
- attune/workflows/test_gen/workflow.py +655 -0
- attune/workflows/test_gen.py +54 -0
- attune/workflows/test_gen_behavioral.py +477 -0
- attune/workflows/test_gen_parallel.py +341 -0
- attune/workflows/test_lifecycle.py +526 -0
- attune/workflows/test_maintenance.py +627 -0
- attune/workflows/test_maintenance_cli.py +590 -0
- attune/workflows/test_maintenance_crew.py +840 -0
- attune/workflows/test_runner.py +622 -0
- attune/workflows/tier_tracking.py +531 -0
- attune/workflows/xml_enhanced_crew.py +285 -0
- attune_ai-2.0.0.dist-info/METADATA +1026 -0
- attune_ai-2.0.0.dist-info/RECORD +457 -0
- attune_ai-2.0.0.dist-info/WHEEL +5 -0
- attune_ai-2.0.0.dist-info/entry_points.txt +26 -0
- attune_ai-2.0.0.dist-info/licenses/LICENSE +201 -0
- attune_ai-2.0.0.dist-info/licenses/LICENSE_CHANGE_ANNOUNCEMENT.md +101 -0
- attune_ai-2.0.0.dist-info/top_level.txt +5 -0
- attune_healthcare/__init__.py +13 -0
- attune_healthcare/monitors/__init__.py +9 -0
- attune_healthcare/monitors/clinical_protocol_monitor.py +315 -0
- attune_healthcare/monitors/monitoring/__init__.py +44 -0
- attune_healthcare/monitors/monitoring/protocol_checker.py +300 -0
- attune_healthcare/monitors/monitoring/protocol_loader.py +214 -0
- attune_healthcare/monitors/monitoring/sensor_parsers.py +306 -0
- attune_healthcare/monitors/monitoring/trajectory_analyzer.py +389 -0
- attune_llm/README.md +553 -0
- attune_llm/__init__.py +28 -0
- attune_llm/agent_factory/__init__.py +53 -0
- attune_llm/agent_factory/adapters/__init__.py +85 -0
- attune_llm/agent_factory/adapters/autogen_adapter.py +312 -0
- attune_llm/agent_factory/adapters/crewai_adapter.py +483 -0
- attune_llm/agent_factory/adapters/haystack_adapter.py +298 -0
- attune_llm/agent_factory/adapters/langchain_adapter.py +362 -0
- attune_llm/agent_factory/adapters/langgraph_adapter.py +333 -0
- attune_llm/agent_factory/adapters/native.py +228 -0
- attune_llm/agent_factory/adapters/wizard_adapter.py +423 -0
- attune_llm/agent_factory/base.py +305 -0
- attune_llm/agent_factory/crews/__init__.py +67 -0
- attune_llm/agent_factory/crews/code_review.py +1113 -0
- attune_llm/agent_factory/crews/health_check.py +1262 -0
- attune_llm/agent_factory/crews/refactoring.py +1128 -0
- attune_llm/agent_factory/crews/security_audit.py +1018 -0
- attune_llm/agent_factory/decorators.py +287 -0
- attune_llm/agent_factory/factory.py +558 -0
- attune_llm/agent_factory/framework.py +193 -0
- attune_llm/agent_factory/memory_integration.py +328 -0
- attune_llm/agent_factory/resilient.py +320 -0
- attune_llm/agents_md/__init__.py +22 -0
- attune_llm/agents_md/loader.py +218 -0
- attune_llm/agents_md/parser.py +271 -0
- attune_llm/agents_md/registry.py +307 -0
- attune_llm/claude_memory.py +466 -0
- attune_llm/cli/__init__.py +8 -0
- attune_llm/cli/sync_claude.py +487 -0
- attune_llm/code_health.py +1313 -0
- attune_llm/commands/__init__.py +51 -0
- attune_llm/commands/context.py +375 -0
- attune_llm/commands/loader.py +301 -0
- attune_llm/commands/models.py +231 -0
- attune_llm/commands/parser.py +371 -0
- attune_llm/commands/registry.py +429 -0
- attune_llm/config/__init__.py +29 -0
- attune_llm/config/unified.py +291 -0
- attune_llm/context/__init__.py +22 -0
- attune_llm/context/compaction.py +455 -0
- attune_llm/context/manager.py +434 -0
- attune_llm/contextual_patterns.py +361 -0
- attune_llm/core.py +907 -0
- attune_llm/git_pattern_extractor.py +435 -0
- attune_llm/hooks/__init__.py +24 -0
- attune_llm/hooks/config.py +306 -0
- attune_llm/hooks/executor.py +289 -0
- attune_llm/hooks/registry.py +302 -0
- attune_llm/hooks/scripts/__init__.py +39 -0
- attune_llm/hooks/scripts/evaluate_session.py +201 -0
- attune_llm/hooks/scripts/first_time_init.py +285 -0
- attune_llm/hooks/scripts/pre_compact.py +207 -0
- attune_llm/hooks/scripts/session_end.py +183 -0
- attune_llm/hooks/scripts/session_start.py +163 -0
- attune_llm/hooks/scripts/suggest_compact.py +225 -0
- attune_llm/learning/__init__.py +30 -0
- attune_llm/learning/evaluator.py +438 -0
- attune_llm/learning/extractor.py +514 -0
- attune_llm/learning/storage.py +560 -0
- attune_llm/levels.py +227 -0
- attune_llm/pattern_confidence.py +414 -0
- attune_llm/pattern_resolver.py +272 -0
- attune_llm/pattern_summary.py +350 -0
- attune_llm/providers.py +967 -0
- attune_llm/routing/__init__.py +32 -0
- attune_llm/routing/model_router.py +362 -0
- attune_llm/security/IMPLEMENTATION_SUMMARY.md +413 -0
- attune_llm/security/PHASE2_COMPLETE.md +384 -0
- attune_llm/security/PHASE2_SECRETS_DETECTOR_COMPLETE.md +271 -0
- attune_llm/security/QUICK_REFERENCE.md +316 -0
- attune_llm/security/README.md +262 -0
- attune_llm/security/__init__.py +62 -0
- attune_llm/security/audit_logger.py +929 -0
- attune_llm/security/audit_logger_example.py +152 -0
- attune_llm/security/pii_scrubber.py +640 -0
- attune_llm/security/secrets_detector.py +678 -0
- attune_llm/security/secrets_detector_example.py +304 -0
- attune_llm/security/secure_memdocs.py +1192 -0
- attune_llm/security/secure_memdocs_example.py +278 -0
- attune_llm/session_status.py +745 -0
- attune_llm/state.py +246 -0
- attune_llm/utils/__init__.py +5 -0
- attune_llm/utils/tokens.py +349 -0
- attune_software/SOFTWARE_PLUGIN_README.md +57 -0
- attune_software/__init__.py +13 -0
- attune_software/cli/__init__.py +120 -0
- attune_software/cli/inspect.py +362 -0
- attune_software/cli.py +574 -0
- attune_software/plugin.py +188 -0
- workflow_scaffolding/__init__.py +11 -0
- workflow_scaffolding/__main__.py +12 -0
- workflow_scaffolding/cli.py +206 -0
- workflow_scaffolding/generator.py +265 -0
|
@@ -0,0 +1,1262 @@
|
|
|
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 attune_llm.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 attune_llm.agent_factory import AgentFactory, Framework
|
|
510
|
+
|
|
511
|
+
# Check if CrewAI is available
|
|
512
|
+
try:
|
|
513
|
+
from attune_llm.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 attune.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: # noqa: BLE001
|
|
769
|
+
# INTENTIONAL: Memory Graph is optional - continue health check if unavailable
|
|
770
|
+
logger.warning(f"Error querying Memory Graph: {e}")
|
|
771
|
+
|
|
772
|
+
# Build task for the crew to analyze and generate fixes
|
|
773
|
+
check_task = self._build_check_task(path, checks_run, issues, auto_fix, context)
|
|
774
|
+
|
|
775
|
+
# Execute the workflow for analysis
|
|
776
|
+
try:
|
|
777
|
+
result = await self._workflow.run(check_task, initial_state=context)
|
|
778
|
+
|
|
779
|
+
# Parse fixes from result
|
|
780
|
+
fixes = self._parse_fixes(result, issues)
|
|
781
|
+
|
|
782
|
+
# Apply auto-fixes if enabled
|
|
783
|
+
if auto_fix:
|
|
784
|
+
fixes = await self._apply_fixes(fixes, path)
|
|
785
|
+
|
|
786
|
+
except Exception as e: # noqa: BLE001
|
|
787
|
+
# INTENTIONAL: Analysis failure shouldn't crash - return partial results
|
|
788
|
+
logger.error(f"Health check analysis failed: {e}")
|
|
789
|
+
|
|
790
|
+
# Calculate health score
|
|
791
|
+
health_score = self._calculate_health_score(issues)
|
|
792
|
+
|
|
793
|
+
# Build the report
|
|
794
|
+
duration = time.time() - start_time
|
|
795
|
+
report = HealthCheckReport(
|
|
796
|
+
target=path,
|
|
797
|
+
issues=issues,
|
|
798
|
+
fixes=fixes,
|
|
799
|
+
health_score=health_score,
|
|
800
|
+
check_duration_seconds=duration,
|
|
801
|
+
agents_used=list(self._agents.keys()),
|
|
802
|
+
memory_graph_hits=memory_hits,
|
|
803
|
+
checks_run={k: {"passed": v.get("passed", False)} for k, v in checks_run.items()},
|
|
804
|
+
metadata={
|
|
805
|
+
"auto_fix": auto_fix,
|
|
806
|
+
"framework": str(self._factory.framework.value) if self._factory else "unknown",
|
|
807
|
+
"xml_prompts": self.config.xml_prompts_enabled,
|
|
808
|
+
},
|
|
809
|
+
)
|
|
810
|
+
|
|
811
|
+
# Store check in Memory Graph
|
|
812
|
+
if self._graph and self.config.memory_graph_enabled:
|
|
813
|
+
try:
|
|
814
|
+
self._graph.add_finding(
|
|
815
|
+
"health_check_crew",
|
|
816
|
+
{
|
|
817
|
+
"type": "health_check",
|
|
818
|
+
"name": f"check:{path}",
|
|
819
|
+
"description": f"Health score: {health_score}/100",
|
|
820
|
+
"health_score": health_score,
|
|
821
|
+
"issues_found": len(issues),
|
|
822
|
+
"fixes_applied": len(report.applied_fixes),
|
|
823
|
+
},
|
|
824
|
+
)
|
|
825
|
+
self._graph._save()
|
|
826
|
+
except Exception as e: # noqa: BLE001
|
|
827
|
+
# INTENTIONAL: Memory Graph storage is optional - continue without it
|
|
828
|
+
logger.warning(f"Error storing check in Memory Graph: {e}")
|
|
829
|
+
|
|
830
|
+
return report
|
|
831
|
+
|
|
832
|
+
async def _run_lint_check(self, path: str) -> dict:
|
|
833
|
+
"""Run ruff lint check."""
|
|
834
|
+
issues = []
|
|
835
|
+
passed = True
|
|
836
|
+
|
|
837
|
+
try:
|
|
838
|
+
result = subprocess.run(
|
|
839
|
+
["python", "-m", "ruff", "check", path, "--output-format=json"],
|
|
840
|
+
check=False,
|
|
841
|
+
capture_output=True,
|
|
842
|
+
text=True,
|
|
843
|
+
timeout=60,
|
|
844
|
+
)
|
|
845
|
+
|
|
846
|
+
if result.returncode != 0:
|
|
847
|
+
passed = False
|
|
848
|
+
|
|
849
|
+
# Parse JSON output
|
|
850
|
+
import json
|
|
851
|
+
|
|
852
|
+
try:
|
|
853
|
+
violations = json.loads(result.stdout) if result.stdout else []
|
|
854
|
+
for v in violations[:50]: # Limit to 50
|
|
855
|
+
issues.append(
|
|
856
|
+
HealthIssue(
|
|
857
|
+
title=f"{v.get('code', 'LINT')}: {v.get('message', 'Lint error')}",
|
|
858
|
+
description=v.get("message", ""),
|
|
859
|
+
category=HealthCategory.LINT,
|
|
860
|
+
severity=IssueSeverity.MEDIUM,
|
|
861
|
+
file_path=v.get("filename"),
|
|
862
|
+
line_number=v.get("location", {}).get("row"),
|
|
863
|
+
rule_id=v.get("code"),
|
|
864
|
+
tool="ruff",
|
|
865
|
+
),
|
|
866
|
+
)
|
|
867
|
+
except json.JSONDecodeError:
|
|
868
|
+
pass
|
|
869
|
+
|
|
870
|
+
except (subprocess.TimeoutExpired, FileNotFoundError) as e:
|
|
871
|
+
logger.warning(f"Lint check failed: {e}")
|
|
872
|
+
|
|
873
|
+
return {"passed": passed, "issues": issues, "tool": "ruff"}
|
|
874
|
+
|
|
875
|
+
async def _run_type_check(self, path: str) -> dict:
|
|
876
|
+
"""Run mypy type check."""
|
|
877
|
+
issues = []
|
|
878
|
+
passed = True
|
|
879
|
+
|
|
880
|
+
# Only scan production code packages
|
|
881
|
+
production_packages = [
|
|
882
|
+
"attune",
|
|
883
|
+
"empathy_software_plugin",
|
|
884
|
+
"empathy_healthcare_plugin",
|
|
885
|
+
"empathy_llm_toolkit",
|
|
886
|
+
"patterns",
|
|
887
|
+
]
|
|
888
|
+
|
|
889
|
+
# Use production packages if checking current directory
|
|
890
|
+
scan_args = []
|
|
891
|
+
if path in [".", "./"]:
|
|
892
|
+
# Use package notation for packages in src/
|
|
893
|
+
for pkg in production_packages:
|
|
894
|
+
scan_args.extend(["-p", pkg])
|
|
895
|
+
else:
|
|
896
|
+
# For specific paths, use file notation
|
|
897
|
+
scan_args.append(path)
|
|
898
|
+
|
|
899
|
+
try:
|
|
900
|
+
result = subprocess.run(
|
|
901
|
+
["python", "-m", "mypy"]
|
|
902
|
+
+ scan_args
|
|
903
|
+
+ ["--ignore-missing-imports", "--no-error-summary"],
|
|
904
|
+
check=False,
|
|
905
|
+
capture_output=True,
|
|
906
|
+
text=True,
|
|
907
|
+
timeout=120,
|
|
908
|
+
)
|
|
909
|
+
|
|
910
|
+
if result.returncode != 0:
|
|
911
|
+
passed = False
|
|
912
|
+
|
|
913
|
+
# Parse text output
|
|
914
|
+
for line in result.stdout.splitlines()[:50]:
|
|
915
|
+
if ": error:" in line:
|
|
916
|
+
parts = line.split(": error:", 1)
|
|
917
|
+
location = parts[0] if parts else ""
|
|
918
|
+
message = parts[1].strip() if len(parts) > 1 else line
|
|
919
|
+
|
|
920
|
+
file_path = None
|
|
921
|
+
line_num = None
|
|
922
|
+
if ":" in location:
|
|
923
|
+
loc_parts = location.rsplit(":", 2)
|
|
924
|
+
file_path = loc_parts[0]
|
|
925
|
+
try:
|
|
926
|
+
line_num = int(loc_parts[1]) if len(loc_parts) > 1 else None
|
|
927
|
+
except ValueError:
|
|
928
|
+
pass
|
|
929
|
+
|
|
930
|
+
issues.append(
|
|
931
|
+
HealthIssue(
|
|
932
|
+
title=f"Type error: {message[:60]}",
|
|
933
|
+
description=message,
|
|
934
|
+
category=HealthCategory.TYPES,
|
|
935
|
+
severity=IssueSeverity.MEDIUM,
|
|
936
|
+
file_path=file_path,
|
|
937
|
+
line_number=line_num,
|
|
938
|
+
tool="mypy",
|
|
939
|
+
),
|
|
940
|
+
)
|
|
941
|
+
|
|
942
|
+
except (subprocess.TimeoutExpired, FileNotFoundError) as e:
|
|
943
|
+
logger.warning(f"Type check failed: {e}")
|
|
944
|
+
|
|
945
|
+
return {"passed": passed, "issues": issues, "tool": "mypy"}
|
|
946
|
+
|
|
947
|
+
async def _run_test_check(self, path: str) -> dict:
|
|
948
|
+
"""Run pytest test check."""
|
|
949
|
+
issues = []
|
|
950
|
+
passed = True
|
|
951
|
+
|
|
952
|
+
# Only run tests in tests/ directory for production health check
|
|
953
|
+
test_path = "tests/" if path in [".", "./"] else path
|
|
954
|
+
|
|
955
|
+
try:
|
|
956
|
+
result = subprocess.run(
|
|
957
|
+
["python", "-m", "pytest", test_path, "--collect-only", "-q"],
|
|
958
|
+
check=False,
|
|
959
|
+
capture_output=True,
|
|
960
|
+
text=True,
|
|
961
|
+
timeout=60,
|
|
962
|
+
)
|
|
963
|
+
|
|
964
|
+
if result.returncode != 0:
|
|
965
|
+
passed = False
|
|
966
|
+
|
|
967
|
+
# Check for collection errors in stderr
|
|
968
|
+
error_output = result.stderr + result.stdout
|
|
969
|
+
for line in error_output.splitlines()[:50]:
|
|
970
|
+
if "ERROR" in line or "INTERNALERROR" in line:
|
|
971
|
+
# Only report actual errors, not counts
|
|
972
|
+
if "error" in line.lower() and not line.strip().startswith("="):
|
|
973
|
+
issues.append(
|
|
974
|
+
HealthIssue(
|
|
975
|
+
title=f"Test error: {line[:50]}",
|
|
976
|
+
description=line,
|
|
977
|
+
category=HealthCategory.TESTS,
|
|
978
|
+
severity=IssueSeverity.CRITICAL,
|
|
979
|
+
tool="pytest",
|
|
980
|
+
),
|
|
981
|
+
)
|
|
982
|
+
|
|
983
|
+
except (subprocess.TimeoutExpired, FileNotFoundError) as e:
|
|
984
|
+
logger.warning(f"Test check failed: {e}")
|
|
985
|
+
|
|
986
|
+
return {"passed": passed, "issues": issues, "tool": "pytest"}
|
|
987
|
+
|
|
988
|
+
async def _run_dep_check(self, path: str) -> dict:
|
|
989
|
+
"""Run dependency security check."""
|
|
990
|
+
issues = []
|
|
991
|
+
passed = True
|
|
992
|
+
|
|
993
|
+
# Try pip-audit first
|
|
994
|
+
try:
|
|
995
|
+
result = subprocess.run(
|
|
996
|
+
["pip-audit", "--format=json"],
|
|
997
|
+
check=False,
|
|
998
|
+
capture_output=True,
|
|
999
|
+
text=True,
|
|
1000
|
+
timeout=60,
|
|
1001
|
+
cwd=path if Path(path).is_dir() else ".",
|
|
1002
|
+
)
|
|
1003
|
+
|
|
1004
|
+
if result.returncode != 0:
|
|
1005
|
+
passed = False
|
|
1006
|
+
|
|
1007
|
+
import json
|
|
1008
|
+
|
|
1009
|
+
try:
|
|
1010
|
+
vulns = json.loads(result.stdout) if result.stdout else []
|
|
1011
|
+
# Ensure vulns is a list
|
|
1012
|
+
if isinstance(vulns, dict):
|
|
1013
|
+
vulns = vulns.get("vulnerabilities", []) or list(vulns.values())
|
|
1014
|
+
if not isinstance(vulns, list):
|
|
1015
|
+
vulns = []
|
|
1016
|
+
for v in vulns[:20]:
|
|
1017
|
+
# Handle different vulnerability formats
|
|
1018
|
+
if not isinstance(v, dict):
|
|
1019
|
+
# Skip non-dict items or convert to basic format
|
|
1020
|
+
continue
|
|
1021
|
+
|
|
1022
|
+
severity = IssueSeverity.HIGH
|
|
1023
|
+
if "critical" in str(v).lower():
|
|
1024
|
+
severity = IssueSeverity.CRITICAL
|
|
1025
|
+
|
|
1026
|
+
issues.append(
|
|
1027
|
+
HealthIssue(
|
|
1028
|
+
title=f"Vulnerability in {v.get('name', 'unknown')}",
|
|
1029
|
+
description=v.get("description", str(v)),
|
|
1030
|
+
category=HealthCategory.DEPENDENCIES,
|
|
1031
|
+
severity=severity,
|
|
1032
|
+
rule_id=v.get("id"),
|
|
1033
|
+
tool="pip-audit",
|
|
1034
|
+
metadata={"fix_versions": v.get("fix_versions", [])},
|
|
1035
|
+
),
|
|
1036
|
+
)
|
|
1037
|
+
except json.JSONDecodeError:
|
|
1038
|
+
pass
|
|
1039
|
+
|
|
1040
|
+
except (subprocess.TimeoutExpired, FileNotFoundError):
|
|
1041
|
+
# pip-audit not installed, try basic pip check
|
|
1042
|
+
try:
|
|
1043
|
+
result = subprocess.run(
|
|
1044
|
+
["pip", "check"],
|
|
1045
|
+
check=False,
|
|
1046
|
+
capture_output=True,
|
|
1047
|
+
text=True,
|
|
1048
|
+
timeout=30,
|
|
1049
|
+
)
|
|
1050
|
+
if result.returncode != 0:
|
|
1051
|
+
passed = False
|
|
1052
|
+
for line in result.stdout.splitlines()[:10]:
|
|
1053
|
+
issues.append(
|
|
1054
|
+
HealthIssue(
|
|
1055
|
+
title=f"Dependency conflict: {line[:50]}",
|
|
1056
|
+
description=line,
|
|
1057
|
+
category=HealthCategory.DEPENDENCIES,
|
|
1058
|
+
severity=IssueSeverity.MEDIUM,
|
|
1059
|
+
tool="pip",
|
|
1060
|
+
),
|
|
1061
|
+
)
|
|
1062
|
+
except (subprocess.TimeoutExpired, FileNotFoundError):
|
|
1063
|
+
pass
|
|
1064
|
+
|
|
1065
|
+
return {"passed": passed, "issues": issues, "tool": "pip-audit/pip"}
|
|
1066
|
+
|
|
1067
|
+
def _build_check_task(
|
|
1068
|
+
self,
|
|
1069
|
+
path: str,
|
|
1070
|
+
checks_run: dict,
|
|
1071
|
+
issues: list[HealthIssue],
|
|
1072
|
+
auto_fix: bool,
|
|
1073
|
+
context: dict,
|
|
1074
|
+
) -> str:
|
|
1075
|
+
"""Build the check task description for the crew."""
|
|
1076
|
+
issues_summary = "\n".join(
|
|
1077
|
+
f" - [{i.severity.value.upper()}] {i.category.value}: {i.title}" for i in issues[:30]
|
|
1078
|
+
)
|
|
1079
|
+
|
|
1080
|
+
task = f"""Analyze health check results and generate fixes.
|
|
1081
|
+
|
|
1082
|
+
Target: {path}
|
|
1083
|
+
Auto-fix enabled: {auto_fix}
|
|
1084
|
+
|
|
1085
|
+
Checks Run:
|
|
1086
|
+
- Lint (ruff): {"PASS" if checks_run.get("lint", {}).get("passed") else "FAIL"}
|
|
1087
|
+
- Types (mypy): {"PASS" if checks_run.get("types", {}).get("passed") else "FAIL"}
|
|
1088
|
+
- Tests (pytest): {"PASS" if checks_run.get("tests", {}).get("passed") else "FAIL"}
|
|
1089
|
+
- Dependencies: {"PASS" if checks_run.get("deps", {}).get("passed") else "FAIL"}
|
|
1090
|
+
|
|
1091
|
+
Issues Found ({len(issues)}):
|
|
1092
|
+
{issues_summary}
|
|
1093
|
+
|
|
1094
|
+
Workflow:
|
|
1095
|
+
1. Health Lead coordinates analysis
|
|
1096
|
+
2. Lint Fixer analyzes and suggests fixes for lint issues
|
|
1097
|
+
3. Type Resolver suggests type annotations
|
|
1098
|
+
4. Test Doctor diagnoses test failures
|
|
1099
|
+
5. Dep Auditor suggests dependency updates
|
|
1100
|
+
|
|
1101
|
+
For each issue, provide:
|
|
1102
|
+
- Root cause analysis
|
|
1103
|
+
- Fix recommendation (code if applicable)
|
|
1104
|
+
- Safety assessment (safe to auto-fix or needs review)
|
|
1105
|
+
- Priority (1=critical, 2=high, 3=medium, 4=low)
|
|
1106
|
+
|
|
1107
|
+
Generate a prioritized fix plan.
|
|
1108
|
+
"""
|
|
1109
|
+
|
|
1110
|
+
if context.get("past_checks"):
|
|
1111
|
+
task += f"""
|
|
1112
|
+
Past Health Checks Found: {len(context["past_checks"])}
|
|
1113
|
+
Consider patterns from past fixes.
|
|
1114
|
+
"""
|
|
1115
|
+
|
|
1116
|
+
return task
|
|
1117
|
+
|
|
1118
|
+
def _parse_fixes(self, result: dict, issues: list[HealthIssue]) -> list[HealthFix]:
|
|
1119
|
+
"""Parse fixes from workflow result."""
|
|
1120
|
+
fixes = []
|
|
1121
|
+
|
|
1122
|
+
# Check for structured fixes in metadata
|
|
1123
|
+
metadata = result.get("metadata", {})
|
|
1124
|
+
if "fixes" in metadata:
|
|
1125
|
+
for f in metadata["fixes"]:
|
|
1126
|
+
fixes.append(
|
|
1127
|
+
HealthFix(
|
|
1128
|
+
title=f.get("title", "Fix"),
|
|
1129
|
+
description=f.get("description", ""),
|
|
1130
|
+
category=HealthCategory(f.get("category", "general")),
|
|
1131
|
+
status=FixStatus.SUGGESTED,
|
|
1132
|
+
file_path=f.get("file_path"),
|
|
1133
|
+
before_code=f.get("before_code"),
|
|
1134
|
+
after_code=f.get("after_code"),
|
|
1135
|
+
patch=f.get("patch"),
|
|
1136
|
+
),
|
|
1137
|
+
)
|
|
1138
|
+
return fixes
|
|
1139
|
+
|
|
1140
|
+
# Generate suggested fixes based on issues
|
|
1141
|
+
for issue in issues:
|
|
1142
|
+
if issue.category == HealthCategory.LINT and issue.rule_id:
|
|
1143
|
+
fixes.append(
|
|
1144
|
+
HealthFix(
|
|
1145
|
+
title=f"Fix {issue.rule_id}",
|
|
1146
|
+
description=f"Run: ruff check --fix --select {issue.rule_id}",
|
|
1147
|
+
category=issue.category,
|
|
1148
|
+
status=FixStatus.SUGGESTED,
|
|
1149
|
+
file_path=issue.file_path,
|
|
1150
|
+
related_issues=[issue.title],
|
|
1151
|
+
),
|
|
1152
|
+
)
|
|
1153
|
+
|
|
1154
|
+
return fixes
|
|
1155
|
+
|
|
1156
|
+
async def _apply_fixes(self, fixes: list[HealthFix], path: str) -> list[HealthFix]:
|
|
1157
|
+
"""Apply safe auto-fixes."""
|
|
1158
|
+
updated_fixes = []
|
|
1159
|
+
|
|
1160
|
+
for fix in fixes:
|
|
1161
|
+
if fix.category == HealthCategory.LINT and self.config.fix_safe_only:
|
|
1162
|
+
# Run ruff --fix for lint issues
|
|
1163
|
+
try:
|
|
1164
|
+
result = subprocess.run(
|
|
1165
|
+
["python", "-m", "ruff", "check", path, "--fix"],
|
|
1166
|
+
check=False,
|
|
1167
|
+
capture_output=True,
|
|
1168
|
+
text=True,
|
|
1169
|
+
timeout=60,
|
|
1170
|
+
)
|
|
1171
|
+
fix.status = FixStatus.APPLIED if result.returncode == 0 else FixStatus.FAILED
|
|
1172
|
+
except (subprocess.TimeoutExpired, FileNotFoundError, OSError):
|
|
1173
|
+
fix.status = FixStatus.FAILED
|
|
1174
|
+
else:
|
|
1175
|
+
fix.status = FixStatus.SUGGESTED
|
|
1176
|
+
|
|
1177
|
+
updated_fixes.append(fix)
|
|
1178
|
+
|
|
1179
|
+
return updated_fixes
|
|
1180
|
+
|
|
1181
|
+
def _calculate_health_score(self, issues: list[HealthIssue]) -> float:
|
|
1182
|
+
"""Calculate health score from issues.
|
|
1183
|
+
|
|
1184
|
+
Uses category-capped deductions to prevent one category (e.g., lint)
|
|
1185
|
+
from dominating the score. This makes the score more meaningful -
|
|
1186
|
+
50 lint warnings shouldn't tank a project that passes tests and has
|
|
1187
|
+
no security issues.
|
|
1188
|
+
|
|
1189
|
+
Category caps:
|
|
1190
|
+
- lint: max -15 points
|
|
1191
|
+
- types: max -20 points
|
|
1192
|
+
- tests: max -25 points
|
|
1193
|
+
- security/dependencies: max -30 points
|
|
1194
|
+
- general: max -10 points
|
|
1195
|
+
"""
|
|
1196
|
+
if not issues:
|
|
1197
|
+
return 100.0
|
|
1198
|
+
|
|
1199
|
+
# Per-issue deductions by severity
|
|
1200
|
+
severity_deductions = {
|
|
1201
|
+
IssueSeverity.CRITICAL: 15,
|
|
1202
|
+
IssueSeverity.HIGH: 8,
|
|
1203
|
+
IssueSeverity.MEDIUM: 2,
|
|
1204
|
+
IssueSeverity.LOW: 0.5,
|
|
1205
|
+
IssueSeverity.INFO: 0,
|
|
1206
|
+
}
|
|
1207
|
+
|
|
1208
|
+
# Maximum deduction per category (prevents one area from tanking score)
|
|
1209
|
+
category_caps = {
|
|
1210
|
+
HealthCategory.LINT: 15,
|
|
1211
|
+
HealthCategory.TYPES: 20,
|
|
1212
|
+
HealthCategory.TESTS: 25,
|
|
1213
|
+
HealthCategory.DEPENDENCIES: 30,
|
|
1214
|
+
HealthCategory.SECURITY: 30,
|
|
1215
|
+
HealthCategory.GENERAL: 10,
|
|
1216
|
+
}
|
|
1217
|
+
|
|
1218
|
+
# Calculate deductions per category
|
|
1219
|
+
category_deductions: dict[HealthCategory, float] = {}
|
|
1220
|
+
for issue in issues:
|
|
1221
|
+
cat = issue.category
|
|
1222
|
+
deduction = severity_deductions.get(issue.severity, 0)
|
|
1223
|
+
category_deductions[cat] = category_deductions.get(cat, 0) + deduction
|
|
1224
|
+
|
|
1225
|
+
# Apply caps per category
|
|
1226
|
+
total_deduction = 0.0
|
|
1227
|
+
for cat, deduction in category_deductions.items():
|
|
1228
|
+
cap = category_caps.get(cat, 10)
|
|
1229
|
+
total_deduction += min(deduction, cap)
|
|
1230
|
+
|
|
1231
|
+
return max(0.0, 100.0 - total_deduction)
|
|
1232
|
+
|
|
1233
|
+
@property
|
|
1234
|
+
def agents(self) -> dict[str, Any]:
|
|
1235
|
+
"""Get the crew's agents."""
|
|
1236
|
+
return self._agents
|
|
1237
|
+
|
|
1238
|
+
@property
|
|
1239
|
+
def is_initialized(self) -> bool:
|
|
1240
|
+
"""Check if crew is initialized."""
|
|
1241
|
+
return self._initialized
|
|
1242
|
+
|
|
1243
|
+
async def get_agent_stats(self) -> dict:
|
|
1244
|
+
"""Get statistics about crew agents."""
|
|
1245
|
+
await self._initialize()
|
|
1246
|
+
|
|
1247
|
+
agents_dict: dict = {}
|
|
1248
|
+
stats: dict = {
|
|
1249
|
+
"agent_count": len(self._agents),
|
|
1250
|
+
"agents": agents_dict,
|
|
1251
|
+
"framework": self._factory.framework.value if self._factory else "unknown",
|
|
1252
|
+
"memory_graph_enabled": self.config.memory_graph_enabled,
|
|
1253
|
+
"xml_prompts_enabled": self.config.xml_prompts_enabled,
|
|
1254
|
+
}
|
|
1255
|
+
|
|
1256
|
+
for name, agent in self._agents.items():
|
|
1257
|
+
agents_dict[name] = {
|
|
1258
|
+
"role": agent.config.role if hasattr(agent, "config") else "unknown",
|
|
1259
|
+
"model_tier": getattr(agent.config, "model_tier", "unknown"),
|
|
1260
|
+
}
|
|
1261
|
+
|
|
1262
|
+
return stats
|