Metadata-Version: 2.4
Name: code-health-system
Version: 5.1.0
Summary: Comprehensive Python code health analysis toolkit - dead code detection, dependency analysis, refactoring risk assessment, and more
Author: Code Health System Contributors
License: MIT
Project-URL: Homepage, https://github.com/atm0sph3re/code-health-system
Project-URL: Documentation, https://github.com/atm0sph3re/code-health-system#readme
Project-URL: Repository, https://github.com/atm0sph3re/code-health-system.git
Project-URL: Issues, https://github.com/atm0sph3re/code-health-system/issues
Keywords: static-analysis,dead-code,code-health,refactoring,dependency-analysis,code-quality,mcp,ai-tools
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Quality Assurance
Classifier: Topic :: Software Development :: Testing
Classifier: Topic :: Utilities
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: mcp>=1.0.0
Requires-Dist: vulture>=2.0
Requires-Dist: radon>=6.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0; extra == "dev"
Requires-Dist: mypy>=1.0; extra == "dev"
Requires-Dist: ruff>=0.1.0; extra == "dev"
Requires-Dist: black>=23.0; extra == "dev"
Provides-Extra: coverage
Requires-Dist: coverage>=7.0; extra == "coverage"
Provides-Extra: git
Requires-Dist: gitpython>=3.0; extra == "git"
Dynamic: license-file

# 🏥 Code Health System

**Comprehensive Python code health analysis toolkit** — dead code detection, dependency analysis, refactoring risk assessment, and more.

[![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![MCP Compatible](https://img.shields.io/badge/MCP-compatible-green.svg)](https://modelcontextprotocol.io/)

## ✨ 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

```bash
pip install code-health-system
```

### CLI Usage

```bash
# 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)

```bash
# Start MCP server
code-health-mcp
```

Add to your MCP client config:

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

## 📖 Usage Examples

### Ask Questions (Natural Language)

```python
# 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

```python
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

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

### Python Configuration

```python
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`)

```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

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

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

### 2. Pre-Refactor Analysis

```bash
# 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

```yaml
# .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](CONTRIBUTING.md) for guidelines.

## 📝 License

MIT License - see [LICENSE](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.
