Skip to content

Conversation

@michaeljabbour
Copy link

Auto-Healing System for Python Code Quality

Summary

Adds an automated code quality improvement system that analyzes Python modules for complexity, type errors, and code health, then uses Claude to refactor and simplify unhealthy code. The system creates safe, trackable improvements through git branches and atomic file operations.

Features

1. Health Monitoring & Scoring

  • Analyzes Python modules for:
    • Cyclomatic complexity (control flow statements)
    • Lines of code (with penalty for modules >200 lines)
    • Type errors via pyright integration
  • Calculates health scores (0-100 scale)
  • Configurable threshold for identifying unhealthy modules

2. Claude-Powered Code Refactoring

  • Direct Claude Code SDK integration (no external dependencies)
  • Generates refactored code following project philosophy:
    • Ruthless simplicity
    • Improved type safety
    • Reduced complexity
    • Better readability
  • Validates improvements before committing

3. Safety Features

  • Git branch creation: Each healing session gets a timestamped branch
  • Clean working tree checks: Prevents accidental data loss
  • Atomic file writes: Uses temp files + atomic rename to prevent corruption
  • Validation: Checks syntax and imports before committing changes
  • File size limit: Skips files >400 lines to prevent timeouts
  • Critical file protection: Skips patterns like init, setup, config, test_

4. CLI Interface

# Check module health without making changes
amplifier heal --check-only

# Heal up to 3 unhealthy modules (with confirmation)
amplifier heal

# Heal up to 5 modules automatically
amplifier heal --max 5 --yes

# Custom health threshold (default: 70)
amplifier heal --threshold 80

5. Claude Code Integration

  • Slash command: /heal for use within Claude Code sessions
  • Inherits all CLI options
  • Seamless integration with existing workflows
  • Graceful cancellation handling (Ctrl+C)

6. Global Command Access

  • make install-global installs system-wide amplifier command
  • Works on any project from any directory
  • Brings all Amplifier features to external codebases

Implementation Details

New Files

  • amplifier/cli/ - Click-based CLI framework
    • core.py - Main CLI entry point
    • commands/heal.py - Healing command implementation
  • amplifier/healing/ - Core healing logic
    • prompts/simplify.md - Healing prompt template
  • amplifier/tools/ - Utility modules
    • claude_healer.py - Claude SDK integration
    • health_monitor.py - Health scoring engine
    • git_utils.py - Git operations with safety checks
    • auto_healer.py - Batch healing orchestration
  • .claude/commands/heal.md - Command documentation
  • .claude/slash_commands/heal.py - Slash command wrapper
  • test_claude_healer.py - Integration test

Modified Files

  • pyproject.toml - Added [project.scripts] entry point for global command
  • Makefile - Added install-global target
  • README.md - Added comprehensive auto-healing documentation (70+ lines)
  • .gitignore - Added .amplifier/ runtime directory
  • CLAUDE.md - Added REPOSITORY_GUIDELINES.md import
  • REPOSITORY_GUIDELINES.md - Preserved custom guidelines while restoring upstream AGENTS.md

Preserved Upstream Compatibility

  • ✅ Restored original AGENTS.md (707 lines) from microsoft/amplifier
  • ✅ Maintained package name as "workspace"
  • ✅ Created REPOSITORY_GUIDELINES.md for custom guidelines
  • ✅ All changes are additive, no breaking changes

Health Score Calculation

Base score: 100
- Complexity penalty: -2 per control flow statement
- LOC penalty: -0.5 per line over 200
- Type error penalty: -10 per error

Example: A 250-line module with 15 control flow statements and 2 type errors:

  • Base: 100
  • Complexity: -30 (15 × 2)
  • LOC: -25 (50 over × 0.5)
  • Type errors: -20 (2 × 10)
  • Final Score: 25 (Needs healing)

Usage Example

$ amplifier heal --check-only
[INFO] Analyzing Python modules for health issues...
[INFO] Found 3 unhealthy modules (threshold: 70):
  • amplifier/tools/complex_module.py (score: 45)
  • amplifier/healing/old_code.py (score: 52)
  • amplifier/cli/messy.py (score: 61)

$ amplifier heal --max 2 --yes
[INFO] Creating healing branch: heal/20250929_223045
[INFO] Healing amplifier/tools/complex_module.py (score: 45)...
[INFO] ✓ Improved to score: 82
[INFO] Healing amplifier/healing/old_code.py (score: 52)...
[INFO] ✓ Improved to score: 78
[INFO] Healing complete! Healed 2 modules.
[INFO] Review changes in branch: heal/20250929_223045

Limitations

  • File size limit: Modules larger than 400 lines are skipped to prevent timeouts
  • Critical files: Files matching patterns like __init__, setup, config, settings, or test_ are skipped for safety
  • Skipped files show clear messages: ⏭️ filename.py: File too large (692 lines, limit: 400)

Testing

  • ✅ All existing tests pass (make test)
  • ✅ Code quality checks pass (make check)
  • ✅ Integration test included (test_claude_healer.py)
  • ✅ Manually tested with real unhealthy modules

Documentation

  • README.md: Complete user guide with examples
  • .claude/commands/heal.md: Command reference for Claude Code
  • .claude/slash_commands/heal.md: Detailed slash command usage
  • Code comments: Comprehensive docstrings throughout

Breaking Changes

None - This is a pure addition with no modifications to existing functionality.

Test Plan

  • Run make check - All checks pass
  • Run make test - All tests pass
  • Test /heal --check-only - Shows health analysis
  • Test /heal with cancellation - Exits gracefully
  • Test file size limit - Large files skipped with warning
  • Test amplifier heal --yes --max 2 - Would heal small modules (not run on repo to avoid changes)
  • Verify global command installation - make install-global works
  • Check documentation accuracy - All docs match implementation

Follow-up Work

Future enhancements could include:

  • Watch mode for continuous monitoring
  • Integration with pre-commit hooks
  • Configurable healing strategies (aggressive/conservative)
  • Metrics dashboard for tracking code health over time
  • Support for additional languages beyond Python
  • Adjustable file size limits

🤖 Generated with Claude Code

Co-Authored-By: Claude noreply@anthropic.com

michaeljabbour and others added 9 commits September 12, 2025 04:17
🌍 Enable Amplifier's powerful AI agents and tools on any codebase, anywhere

This major enhancement allows developers to harness Amplifier's 20+ specialized
agents (zen-architect, bug-hunter, security-guardian, etc.) on any project
without copying files or modifying existing repositories.

✨ New Features:
- Global 'amplifier' command for system-wide access
- Smart auto-detection of Amplifier installation location
- Enhanced startup scripts with comprehensive error handling
- Seamless integration with existing Claude workflows
- Cross-platform compatibility (macOS, Linux, WSL)

🚀 Usage:
  make install-global    # Install global command
  amplifier ~/my-project # Use Amplifier on any project
  amplifier --help       # Show usage examples

📈 Benefits:
- All 20+ specialized agents available on any codebase
- Shared knowledge base across all projects
- Same powerful automation and quality tools
- Project isolation - changes only affect target project
- No need to modify or copy files to existing projects

🔧 Implementation:
- Enhanced amplifier-anywhere.sh with robust error handling
- New bin/amplifier wrapper for global installation
- Updated Makefile with install-global targets
- Comprehensive documentation in README
- Fixed Claude settings path resolution

This democratizes access to Amplifier's AI development superpowers,
making every codebase instantly compatible with the full Amplifier toolkit.
- Fix handling of Claude flags when no directory specified
- Ensure --version flag works correctly without triggering full startup
- Improve argument parsing logic to handle edge cases
- Maintain backward compatibility with all usage patterns

Tested scenarios:
✅ amplifier --version (shows version only)
✅ amplifier --print 'command' (uses current dir + Claude args)
✅ amplifier /path/to/project --model sonnet (explicit dir + args)
✅ amplifier /nonexistent/path (proper error handling)
✅ amplifier --help (shows help text)
- Modify .gitignore to permit bin/amplifier global command
- Maintain exclusion of other build artifacts
- Enable proper version control of global installation script
- Modified bin/amplifier to capture and pass the original PWD
- Updated amplifier-anywhere.sh to use ORIGINAL_PWD when available
- Fixes issue where 'amplifier' from any directory would default to amplifier repo instead of current dir
Introduces an automated code quality improvement system that analyzes Python modules for complexity, type errors, and code health, then uses Claude to refactor and simplify unhealthy code.

Core Features:
- Health monitoring and scoring (0-100 scale) based on cyclomatic complexity, LOC, and type errors
- Claude-powered code refactoring via direct SDK integration
- Git branch creation for safe, trackable improvements
- Atomic file writes to prevent corruption
- Validation of improvements before committing
- Configurable health threshold and batch size

CLI Interface:
- `amplifier heal` - Check and heal unhealthy modules
- `amplifier heal --check-only` - Report health without healing
- `amplifier heal --max N` - Heal up to N modules
- `amplifier heal --threshold N` - Custom health threshold
- `amplifier heal --yes` - Skip confirmation prompt

Claude Code Integration:
- `/heal` slash command with all CLI options
- Graceful cancellation handling (Ctrl+C)
- Clear progress and results reporting

Safety Features:
- Timestamped git branches for each healing session
- Clean working tree checks
- File size limit (400 lines) to prevent timeouts
- Critical file patterns skipped (__init__, setup, config, test_)
- Syntax and import validation before committing

Files Added:
- amplifier/cli/ - Click-based CLI framework
- amplifier/healing/ - Healing prompts
- amplifier/tools/ - Health monitoring, git utils, Claude integration
- .claude/commands/heal.md - Command documentation
- .claude/slash_commands/heal.py - Slash command wrapper
- test_claude_healer.py - Integration tests

Files Modified:
- pyproject.toml - Added [project.scripts] entry point
- Makefile - Added install-global target
- README.md - Added comprehensive auto-healing documentation
- .gitignore - Added .amplifier/ runtime directory
- CLAUDE.md - Added REPOSITORY_GUIDELINES.md import
- REPOSITORY_GUIDELINES.md - Preserved custom guidelines

Upstream Compatibility:
- Restored AGENTS.md from microsoft/amplifier
- Maintained package name as "workspace"
- All changes are additive, no breaking changes

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
michaeljabbour added a commit to michaeljabbour/amplifier that referenced this pull request Sep 30, 2025
Complete comprehensive technical specification library with all 44 principles:

**People (6 specs)**
- #1 Small AI-first working groups
- #2 Strategic human touchpoints only
- #3 Prompt engineering as core skill
- microsoft#4 Test-based verification over code review
- microsoft#5 Conversation-driven development
- microsoft#6 Human escape hatches always available

**Process (13 specs)**
- microsoft#7 Regenerate, don't edit
- microsoft#8 Contract-first everything
- microsoft#9 Tests as the quality gate
- microsoft#10 Git as safety net
- microsoft#11 Continuous validation with fast feedback
- microsoft#12 Incremental processing as default
- microsoft#13 Parallel exploration by default
- microsoft#14 Context management as discipline
- microsoft#15 Git-based everything
- microsoft#16 Docs define, not describe
- microsoft#17 Prompt versioning and testing
- microsoft#18 Contract evolution with migration paths
- microsoft#19 Cost and token budgeting

**Technology (18 specs)**
- microsoft#20 Self-modifying AI-first codebase
- microsoft#21 Limited and domain-specific by design
- microsoft#22 Layered virtualization
- microsoft#23 Protected self-healing kernel
- microsoft#24 Long-running agent processes
- microsoft#25 Simple interfaces by design
- microsoft#26 Stateless by default
- microsoft#27 Disposable components everywhere
- microsoft#28 CLI-first design
- microsoft#29 Tool ecosystems as extensions
- microsoft#30 Observability baked in
- microsoft#31 Idempotency by design (reference)
- microsoft#32 Error recovery patterns built in
- microsoft#33 Graceful degradation by design
- microsoft#34 Feature flags as deployment strategy
- microsoft#35 Least-privilege automation
- microsoft#36 Dependency pinning and security scanning
- microsoft#37 Declarative over imperative

**Governance (7 specs)**
- microsoft#38 Access control and compliance
- microsoft#39 Metrics and evaluation everywhere
- microsoft#40 Knowledge stewardship and institutional memory
- microsoft#41 Adaptive sandboxing with explicit approvals
- microsoft#42 Data governance and privacy controls
- microsoft#43 Model lifecycle management
- microsoft#44 Self-serve recovery with known-good snapshots

Each specification includes:
- Plain-language definition
- AI-first development rationale
- 4-6 implementation approaches
- 5 good/bad example pairs with working code
- 6 related principles with relationships
- 7 common pitfalls with examples
- Tools organized by category
- 12 actionable checklist items

Statistics:
- 44 specifications totaling ~10,000+ lines
- 220+ good/bad code example pairs
- 240+ implementation approaches
- 300+ documented anti-patterns
- 500+ tools and frameworks
- 250+ cross-principle relationships

Created through parallel AI agent execution demonstrating
Principle microsoft#13 (Parallel Exploration by Default).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
The [project.scripts] entry point was creating a Python CLI that
conflicted with the shell script wrapper. Removing it ensures the
global amplifier command launches Claude Code as intended.

Users should call the Python CLI directly when needed:
  python -m amplifier.cli heal
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant