Skip to main content

Comprehensive Python code health analysis toolkit - dead code detection, dependency analysis, refactoring risk assessment, and more

Project description

๐Ÿฅ Code Health System

Comprehensive Python code health analysis toolkit โ€” dead code detection, dependency analysis, refactoring risk assessment, and more.

Python 3.10+ License: MIT MCP Compatible

โœจ Features

๐Ÿ” Dead Code Detection

  • Find truly unused files, functions, and classes
  • Detect unreachable modules from entry points
  • Identify "dead islands" โ€” clusters of mutually-dependent but unused code

๐Ÿ”— Dependency Analysis

  • Build complete import graph
  • Find circular dependencies
  • Identify critical "hub" files with many dependents
  • Trace what depends on a specific file

๐Ÿ’š Code Health Metrics

  • Refactoring Risk Score โ€” know which files are dangerous to change
  • Code Churn Analysis โ€” see which files change frequently
  • Business Criticality โ€” understand what's important in your codebase

๐Ÿง  Smart Analysis

  • Intent Analyzer โ€” understand what a file does without reading it
  • Impact Predictor โ€” predict blast radius of changes
  • Incremental Analysis โ€” analyze only changed files (CI/CD friendly)

๐Ÿค– AI Integration

  • MCP Server โ€” use with Claude, Cline, and other AI assistants
  • Smart Ask โ€” ask questions in natural language
  • Batch Pipeline โ€” efficient multi-task analysis

๐Ÿš€ Quick Start

Installation

pip install code-health-system

CLI Usage

# Quick project analysis
code-health analyze

# Find dead code
code-health dead-code

# Analyze dependencies
code-health contrast-flow

# Generate cleanup plan
code-health generate-plan

MCP Server (for AI Assistants)

# Start MCP server
code-health-mcp

Add to your MCP client config:

{
  "mcpServers": {
    "code-health": {
      "command": "code-health-mcp"
    }
  }
}

๐Ÿ“– Usage Examples

Ask Questions (Natural Language)

# With MCP client
ask("Can I delete services/old.py?")
# โ†’ {"verdict": "โœ… SAFE TO QUARANTINE", "reasons": [...]}

ask("What happens if I change handlers/auth.py?")
# โ†’ {"blast_radius": 15, "by_risk": {"high": 2, "medium": 5}}

ask("Show me all database files")
# โ†’ {"found_count": 12, "files": [...]}

ask("Project health")
# โ†’ {"health_score": 96, "status": "good"}

Python API

from code_health import (
    CleanupPipeline,
    ContrastFlowV2,
    RefactoringRiskAnalyzer,
    IntentAnalyzer,
)

# Full project analysis
pipeline = CleanupPipeline()
result = pipeline.run(mode="full")
print(f"Health Score: {result.health_score}")
print(f"Dead Files: {len(result.candidates_for_deletion)}")

# Dependency analysis
analyzer = ContrastFlowV2()
reached, unreached = analyzer.analyze_blue(["main.py"])
print(f"Unreached modules: {unreached}")

# Risk analysis
risk = RefactoringRiskAnalyzer()
report = risk.analyze_project()
for file in report.high_risk_files[:5]:
    print(f"โš ๏ธ {file.file_path}: risk={file.risk_score}")

# Intent analysis
intent = IntentAnalyzer()
result = intent.analyze("services/payment.py")
print(f"Domain: {result.primary_domain}")
print(f"Criticality: {result.business_criticality}")

๐Ÿ› ๏ธ MCP Tools

Tool Description
analyze_project Full project analysis (quick/full/deep modes)
analyze_file Deep analysis of a single file
analyze_dependencies Dependency graph analysis
analyze_health Code health metrics
find_duplicates Find duplicate/similar code
generate_plan Generate prioritized cleanup plan
ask Natural language questions
analyze_incremental Analyze only changed files
analyze_intent Understand file purpose
predict_impact Predict change impact
batch_request Execute multiple tasks efficiently

๐Ÿ“ Project Structure

your-project/
โ”œโ”€โ”€ .code_health/           # Analysis data (auto-created)
โ”‚   โ”œโ”€โ”€ reports/            # Generated reports
โ”‚   โ”œโ”€โ”€ quarantine/         # Quarantined files
โ”‚   โ”œโ”€โ”€ archive/            # Archived files
โ”‚   โ””โ”€โ”€ logs/               # Analysis logs
โ”œโ”€โ”€ src/
โ”‚   โ””โ”€โ”€ your_package/
โ””โ”€โ”€ pyproject.toml

โš™๏ธ Configuration

Environment Variables

# Override project root
export CODE_HEALTH_PROJECT_ROOT=/path/to/project

Python Configuration

from code_health import CodeHealthConfig

# Set project root
CodeHealthConfig.set_project_root("/path/to/project")

# Add custom entry points
CodeHealthConfig.add_entry_point("worker", "worker.py", "Background worker")

Config File (.code_health.yaml)

entry_points:
  - name: main
    path: main.py
  - name: api
    path: api/server.py

protected_patterns:
  - "*.md"
  - "docs/**/*"

excluded_dirs:
  - "vendor"
  - "generated"

๐ŸŽฏ Use Cases

1. Legacy Code Cleanup

# Find dead code
code-health dead-code --min-confidence 85

# Generate cleanup script
code-health generate-script --output cleanup.sh

2. Pre-Refactor Analysis

# Check risk before refactoring
code-health analyze --output report.json

# See what depends on a file
code-health contrast-flow --entry main.py

3. CI/CD Integration

# .github/workflows/code-health.yml
name: Code Health Check
on: [push, pull_request]

jobs:
  analyze:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: pip install code-health-system
      - run: code-health analyze-incremental --mode quick_stats

4. AI-Assisted Development

Use with Claude, Cline, or other MCP-compatible AI assistants:

You: "Can I delete the old_api.py file?"
AI: *uses analyze_file tool*
AI: "No, old_api.py is imported by 5 files and has 3 endpoints. 
     It's not safe to delete without migration."

๐Ÿ“Š Sample Output

๐Ÿ” PROJECT ANALYSIS
โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”

Health Score: 96% โœ…

๐Ÿ“Š Summary:
   Total files:     458
   Dead files:      12
   Unreached:       5
   Whitelisted:     28

๐Ÿ”ด Dead Code Candidates:
   โ€ข utils/old_helpers.py (0 imports, 234 days old)
   โ€ข services/deprecated_api.py (0 imports, 156 days old)
   โ€ข handlers/legacy_handler.py (0 imports, 89 days old)

โš ๏ธ High Risk Files:
   โ€ข core/database.py (risk=72, 23 dependents)
   โ€ข api/auth.py (risk=65, 18 dependents)

๐Ÿ’ก Recommendations:
   1. Review dead code candidates (12 files)
   2. Add tests for high-risk files
   3. Consider refactoring hub files

๐Ÿค Contributing

Contributions are welcome! Please see CONTRIBUTING.md for guidelines.

๐Ÿ“ License

MIT License - see LICENSE for details.

๐Ÿ™ Acknowledgments

  • Built for the AI-assisted development era
  • Inspired by vulture, radon, and other great tools
  • MCP protocol by Anthropic

Code Health System โ€” give your AI assistant full visibility into your codebase architecture.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distributions

No source distribution files available for this release.See tutorial on generating distribution archives.

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

code_health_system-5.1.0-py3-none-any.whl (222.8 kB view details)

Uploaded Python 3

File details

Details for the file code_health_system-5.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for code_health_system-5.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 852046d67918efac0d31a0a287ec207a5cd949df88cd12e7900fa764a6f06ea8
MD5 a3b595bf8fcb6731eab7ce7432f9c808
BLAKE2b-256 4d2cd8860f1b89be659b06051caa756896bdd7ba26de9b0d02f74274c1be13eb

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page