debtmap
đ§ Early Prototype - This project is under active development and APIs may change
A fast, language-agnostic code complexity and technical debt analyzer written in Rust. Debtmap identifies which code to refactor for maximum cognitive debt reduction and which code to test for maximum risk reduction, providing data-driven ROI calculations for both.
Why Debtmap?
đ¯ What Makes Debtmap Different
Unlike traditional static analysis tools that simply flag complex code, debtmap answers two critical questions:
- "What should I refactor to reduce cognitive burden?" - Identifies overly complex code that slows down development
- "What should I test first to reduce the most risk?" - Pinpoints untested complex code that threatens stability
Unique Capabilities:
- Cognitive Complexity Analysis: Goes beyond cyclomatic complexity to measure how hard code is to understand, identifying functions that need refactoring to reduce mental load
- Coverage-Risk Correlation: The only tool that combines complexity metrics with test coverage to identify genuinely risky code (high complexity + low coverage = critical risk)
- ROI-Driven Prioritization: Calculates actual return on investment for both refactoring and testing efforts, showing which changes will have the most impact
- Actionable Refactoring Guidance: Provides specific recommendations like "extract nested conditions" or "split this 80-line function" rather than just flagging issues
- Quantified Impact: Provides concrete metrics like "refactoring this will reduce complexity by 60%" or "testing this will reduce risk by 5%"
- Language-Agnostic Coverage Integration: Works with any tool that generates LCOV format (Jest, pytest, cargo-tarpaulin, etc.)
- Context-Aware False Positive Reduction: Intelligently reduces false positives by understanding code context and patterns (enabled by default)
Speed:
- Written in Rust for 10-100x faster analysis than Java/Python-based competitors
- Parallel processing with Rayon for analyzing massive codebases in seconds
- Incremental analysis caches results for lightning-fast re-runs
Features
- Multi-language support - Fully supports Rust, Python, JavaScript, and TypeScript
- Comprehensive debt detection - Identifies technical debt across security, organization, testing, and resource management
- Security vulnerability detection - Finds hardcoded secrets, weak crypto, SQL injection risks, and unsafe code patterns
- Resource management analysis - Identifies inefficient allocations, nested loops, and blocking I/O patterns
- Code organization analysis - Detects god objects, feature envy, primitive obsession, and magic values
- Testing quality assessment - Analyzes test complexity, flaky patterns, and assertion quality
- Context-aware analysis - Reduces false positives through intelligent context detection (enabled by default)
- Enhanced scoring system - Advanced scoring differentiation for better prioritization
- Macro expansion support - Handles Rust macro expansions with configurable warnings and statistics
- Verbosity controls - Multiple verbosity levels (-v, -vv, -vvv) for progressive detail
- Resource management review - Finds async/await misuse, resource leaks, and collection inefficiencies
- Coverage-based risk analysis - Uniquely correlates complexity with test coverage to identify truly risky code
- ROI-driven testing recommendations - Prioritizes testing efforts by calculating risk reduction per test case
- Parallel processing - Built with Rust and Rayon for blazing-fast analysis of large codebases
- Multiple output formats - JSON, TOML, and human-readable table formats
- Configurable thresholds - Customize complexity and duplication thresholds to match your standards
- Incremental analysis - Smart caching system for analyzing only changed files
- Flexible suppression - Inline comment-based suppression for specific code sections and configuration-based ignore patterns
- Test-friendly - Easily exclude test fixtures and example code from debt analysis
Installation
Quick Install (Recommended)
Install the latest release with a single command:
|
Or with wget:
|
This will:
- Automatically detect your OS and architecture
- Download the appropriate pre-built binary from the latest GitHub release
- Install debtmap to
~/.cargo/binif it exists, otherwise~/.local/bin(or$INSTALL_DIRif set) - Offer to automatically add the install directory to your PATH if needed
Using Cargo
From Source
# Clone the repository
# Build and install
Quick Start
# Analyze current directory
# Analyze with coverage data for risk scoring
# Generate coverage with cargo tarpaulin (Rust projects)
# Analyze with custom thresholds
# Output as JSON
# Analyze specific languages only
# Show only top 10 high-priority issues with verbose scoring
# Focus on security issues only
# Group results by debt category
# Initialize configuration file
# Validate project against thresholds
Commands
analyze
Comprehensive analysis with unified prioritization that identifies the highest-value improvements for both testing and refactoring efforts.
)
)
)
)
)
)
)
)
)
)
)
)
)
)
init
Initialize a configuration file for the project.
validate
Validate code against configured thresholds and fail if metrics exceed limits. Supports risk-based validation with coverage data.
)
)
)
)
)
Verbosity Levels
Control the amount of detail in the output using the -v flag:
# Standard output (no verbosity)
# Level 1 (-v): Show main score factors
# Level 2 (-vv): Show detailed calculations
# Level 3 (-vvv): Show all debug information
# Show macro expansion warnings and statistics
Example Output
Unified Priority Output (Default)
debtmap analyze . --lcov target/coverage/lcov.info --top 3
ââââââââââââââââââââââââââââââââââââââââââââ
PRIORITY TECHNICAL DEBT FIXES
ââââââââââââââââââââââââââââââââââââââââââââ
đ¯ TOP 3 RECOMMENDATIONS (by unified priority)
#1 SCORE: 8.9 [CRITICAL]
ââ TEST GAP: ./src/analyzers/rust_call_graph.rs:38 add_function_to_graph()
ââ ACTION: Add 6 unit tests for full coverage
ââ IMPACT: Full test coverage, -3.7 risk
ââ COMPLEXITY: cyclomatic=6, branches=6, cognitive=8, nesting=2, lines=32
ââ DEPENDENCIES: 0 upstream, 11 downstream
ââ WHY: Business logic with 0% coverage, manageable complexity (cyclo=6, cog=8)
#2 SCORE: 8.9 [CRITICAL]
ââ TEST GAP: ./src/debt/smells.rs:196 detect_data_clumps()
ââ ACTION: Add 5 unit tests for full coverage
ââ IMPACT: Full test coverage, -3.7 risk
ââ COMPLEXITY: cyclomatic=5, branches=5, cognitive=11, nesting=5, lines=31
ââ DEPENDENCIES: 0 upstream, 4 downstream
ââ WHY: Business logic with 0% coverage, manageable complexity (cyclo=5, cog=11)
#3 SCORE: 8.6 [CRITICAL]
ââ TEST GAP: ./src/risk/context/dependency.rs:247 explain()
ââ ACTION: Add 5 unit tests for full coverage
ââ IMPACT: Full test coverage, -3.6 risk
ââ COMPLEXITY: cyclomatic=5, branches=5, cognitive=9, nesting=1, lines=24
ââ DEPENDENCIES: 0 upstream, 1 downstream
ââ WHY: Business logic with 0% coverage, manageable complexity (cyclo=5, cog=9)
đ TOTAL DEBT SCORE: 4907
đ OVERALL COVERAGE: 67.12%
JSON Output Format
Analysis Modes
Debtmap offers several specialized analysis modes for focused technical debt assessment:
Comprehensive Analysis (Default)
Runs all analyzers across all categories to provide a complete technical debt assessment:
Category-Specific Analysis
Focus on specific aspects of technical debt:
# Security-focused analysis
# Code organization analysis
# Testing quality analysis
# Resource management analysis
Combined Filtering
Combine multiple options for precise analysis:
# High-priority security issues only
# Group by category with coverage data
# Filter specific debt categories
How Debtmap Works
Analysis Workflow
graph TD
A[Start: debtmap analyze] --> B[Parse Source Files]
B --> C{Language?}
C -->|Rust| D[syn AST Parser]
C -->|Python| E[rustpython Parser]
C -->|JS/TS| F[tree-sitter Parser]
D --> G[Extract Metrics]
E --> G
F --> G
G --> H[Build Call Graph]
H --> I[Semantic Classification]
G --> J[Calculate Complexity]
J --> K[Cyclomatic Complexity]
J --> L[Cognitive Complexity]
J --> M[Nesting Depth]
G --> N[Detect Patterns]
N --> O[Code Duplication]
N --> P[Technical Debt Markers]
N --> Q[Long Functions]
I --> R{Coverage Data?}
R -->|Yes| S[Parse LCOV]
R -->|No| T[Assume No Coverage]
S --> U[Coverage Propagation]
T --> U
U --> V[Unified Scoring]
V --> W[Calculate Factors]
W --> X[Complexity Factor: 25%]
W --> Y[Coverage Factor: 35%]
W --> Z[ROI Factor: 25%]
W --> AA[Semantic Factor: 15%]
X --> AB[Final Score]
Y --> AB
Z --> AB
AA --> AB
AB --> AC[Apply Role Multiplier]
AC --> AD[Sort by Priority]
AD --> AE[Generate Recommendations]
AE --> AF[Output Results]
Unified Scoring Algorithm
Debtmap uses a sophisticated multi-factor scoring system to prioritize technical debt:
1. Base Score Calculation
Each function receives a score from 0-10 based on four weighted factors:
Base Score = (Complexity à 0.25) + (Coverage à 0.35) + (ROI à 0.25) + (Semantic à 0.15)
Factor Breakdown:
-
Complexity Factor (25%): Combines cyclomatic and cognitive complexity
- Normalized using:
min(10, (cyclomatic / 10 + cognitive / 20) Ã 5) - Higher complexity = higher score = higher priority
- Normalized using:
-
Coverage Factor (35%): Urgency of adding test coverage
- Test functions: 0 (they don't need coverage)
- With coverage data:
10 Ã (1 - coverage_percentage) Ã complexity_weight - Without coverage data: 10 (assume worst case)
- Considers transitive coverage through call graph
-
ROI Factor (25%): Return on investment for fixing
- Based on: function size, downstream dependencies, change frequency
- Normalized to 0-10 scale
- Higher ROI = higher priority
-
Semantic Factor (15%): Importance based on function role
- Entry points: 8-10 (critical path)
- Business logic: 6-8 (core functionality)
- Data access: 5-7 (important but stable)
- Utilities: 3-5 (lower priority)
- Test helpers: 1-3 (lowest priority)
2. Role Multiplier
The base score is adjusted by a role-based multiplier:
Final Score = Base Score à Role Multiplier
Multipliers by Function Role:
- Entry Points: 1.5Ã (main, handlers, API endpoints)
- Business Logic: 1.2Ã (core domain functions)
- Data Access: 1.0Ã (database, file I/O)
- Infrastructure: 0.8Ã (logging, configuration)
- Utilities: 0.5Ã (helpers, formatters)
- Test Code: 0.1Ã (test functions, fixtures)
3. Coverage Propagation
Coverage impact flows through the call graph:
Transitive Coverage = Direct Coverage + ÎŖ(Caller Coverage à Weight)
- Functions called by well-tested code have reduced urgency
- Functions that many others depend on have increased urgency
- Weights decrease with distance in call graph
4. Priority Classification
Based on final scores:
- CRITICAL (9.0-10.0): Immediate action required
- HIGH (7.0-8.9): Should be addressed soon
- MEDIUM (5.0-6.9): Plan for next sprint
- LOW (3.0-4.9): Nice to have
- MINIMAL (0.0-2.9): Can be deferred
Metrics Explained
Cyclomatic Complexity
Measures the number of linearly independent paths through code. Higher values indicate more complex, harder-to-test code.
- 1-5: Simple, easy to test
- 6-10: Moderate complexity
- 11-20: Complex, consider refactoring
- 20+: Very complex, high risk
Cognitive Complexity
Measures how difficult code is to understand. Unlike cyclomatic complexity, it considers nesting depth and control flow interruptions.
Code Duplication
Identifies similar code blocks that could be refactored into shared functions.
Technical Debt Patterns
Core Patterns
- Long methods/functions: Functions exceeding recommended line counts
- Deep nesting: Code with excessive indentation levels
- Large files: Files that have grown too large to maintain easily
- Circular dependencies: Modules that depend on each other
- High coupling: Excessive dependencies between modules
- TODO/FIXME/HACK markers: Development debt markers requiring attention
- Code duplication: Similar code blocks that could be refactored
- High complexity: Functions with excessive cyclomatic or cognitive complexity
- Error swallowing: Catch blocks that suppress errors without proper handling
- Dead code: Unused functions and modules that can be removed
- Testing gaps: Complex functions lacking adequate test coverage
- Risk hotspots: Functions combining high complexity with low coverage
Security Anti-patterns
- Hardcoded secrets: API keys, passwords, and tokens in source code
- Weak cryptography: Use of deprecated or insecure cryptographic algorithms
- SQL injection risks: Unsafe dynamic SQL query construction
- Unsafe code blocks: Unnecessary or poorly justified unsafe operations
- Input validation gaps: Missing validation for user inputs and external data
Resource Management Issues
- Inefficient allocations: Unnecessary heap allocations and memory waste
- String concatenation: Inefficient string building in loops
- Nested loops: O(n²) and higher complexity patterns
- Blocking I/O: Synchronous operations in async contexts
- Suboptimal data structures: Using wrong collections for access patterns
Code Organization Issues
- God objects: Classes/modules with too many responsibilities
- Feature envy: Methods using more data from other classes than their own
- Primitive obsession: Overuse of basic types instead of domain objects
- Magic numbers/strings: Unexplained literal values throughout code
Testing Quality Issues
- Complex test assertions: Tests that are hard to understand or maintain
- Flaky test patterns: Non-deterministic test behaviors
- Excessive test complexity: Tests with high cyclomatic complexity
Resource Management Issues
- Async/await misuse: Improper handling of asynchronous operations
- Resource leaks: Missing cleanup for files, connections, or memory
- Collection inefficiencies: Suboptimal use of data collections
Risk Analysis (With Coverage Data)
When LCOV coverage data is provided via --lcov, debtmap performs sophisticated risk analysis:
Risk Scoring
Functions are scored based on complexity-coverage correlation:
- Critical Risk (50+): High complexity + low/no coverage
- High Risk (25-49): Medium-high complexity with poor coverage
- Medium Risk (10-24): Moderate complexity or coverage gaps
- Low Risk (5-9): Well-tested or simple functions
Testing Recommendations
- ROI-based prioritization: Functions ranked by risk reduction potential
- Test effort estimation: Complexity-based test case recommendations
- Actionable insights: Concrete steps to reduce overall codebase risk
Coverage Integration
Supports LCOV format from popular coverage tools:
- Rust:
cargo tarpaulin --out lcov - JavaScript/TypeScript:
jest --coverage --coverageReporters=lcov - Python:
pytest --cov --cov-report=lcov - Go:
go test -coverprofile=coverage.out && gocover-cobertura < coverage.out > coverage.lcov
Suppressing Technical Debt Detection
Debtmap provides two ways to exclude code from technical debt analysis:
1. Inline Suppression Comments
You can suppress debt detection for specific code sections using inline comments. This is useful for test fixtures, example code, or intentional technical debt.
Suppression Formats
// Rust example
// debtmap:ignore-start -- Optional reason
// TODO: This will be ignored
// FIXME: This too
// debtmap:ignore-end
// Suppress next line only
// debtmap:ignore-next-line
// TODO: Just this line is ignored
// Suppress current line
// TODO: Ignored // debtmap:ignore
// Type-specific suppression
// debtmap:ignore-start[todo] -- Only suppress TODOs
// TODO: Ignored
// FIXME: Not ignored
// debtmap:ignore-end
# Python example
# debtmap:ignore-start
# TODO: Ignored in Python
# debtmap:ignore-end
// JavaScript/TypeScript example
// debtmap:ignore-start -- Test fixture data
// TODO: Ignored in JS/TS
// HACK: This too
// debtmap:ignore-end
/* Block comments also work */
/* debtmap:ignore-start */
// TODO: Ignored
/* debtmap:ignore-end */
Suppression Types
debtmap:ignore- Suppress all debt types on current linedebtmap:ignore-next-line- Suppress all debt types on next linedebtmap:ignore-start/debtmap:ignore-end- Suppress block of codedebtmap:ignore[todo]- Suppress only TODO markersdebtmap:ignore[fixme]- Suppress only FIXME markersdebtmap:ignore[hack]- Suppress only HACK markersdebtmap:ignore[*]- Suppress all types (wildcard)
2. Configuration File Ignores
Use the .debtmap.toml configuration file to ignore entire files or directories:
Pattern Syntax
*- Matches any sequence of characters except path separator**- Matches any sequence of characters including path separators?- Matches any single character[abc]- Matches any character in the set[!abc]- Matches any character not in the set
Examples:
tests/**/*- All files under any tests directory**/*.test.rs- All files ending with .test.rs anywheresrc/**/test_*.py- Python test files in any subdirectory of src[!.]*.rs- Rust files not starting with a dot
Configuration
Create a .debtmap.toml file in your project root:
[]
= 15
= 25
= 500
= 50
= 4
# Minimum thresholds for including items in debt analysis
# These help filter out trivial functions that aren't really technical debt
= 1.0 # Minimum unified score to include (0.0-10.0, default: 1.0)
= 2 # Skip functions with cyclomatic <= this value (default: 2)
= 3 # Skip functions with cognitive <= this value (default: 3)
= 1.0 # Minimum risk score for Risk debt types (default: 1.0)
[]
# Customize scoring weights (must sum to 1.0)
= 0.35 # Weight for coverage factor
= 0.25 # Weight for complexity factor
= 0.15 # Weight for semantic factor
= 0.10 # Weight for dependency criticality
= 0.10 # Weight for security issues
= 0.05 # Weight for code organization issues
[]
# File and directory patterns to ignore during analysis (glob patterns)
= [
"tests/**/*", # Ignore all files in tests directory
"**/*.test.rs", # Ignore all .test.rs files
"**/*_test.py", # Ignore Python test files
"**/fixtures/**", # Ignore fixture directories
"benches/**", # Ignore benchmark files
"*.generated.rs", # Ignore generated code
"*.pb.go", # Ignore protobuf files
"*.min.js", # Ignore minified JS
"target/**", # Rust build directory
"node_modules/**", # Node dependencies
".venv/**", # Python virtual environments
]
[]
# Languages to analyze (rust, python, javascript, typescript)
= ["rust", "python", "javascript"]
[]
# Control external API detection for dead code analysis
# Set to false for CLI tools and applications that don't expose a library API
= true # default: true
# Explicitly mark functions as external APIs (won't be flagged as dead code)
= [
"parse", # Simple function name
"Parser::new", # Struct method
"client::connect", # Module-qualified function
]
# Mark files containing external APIs (all public functions in these files are APIs)
= [
"src/lib.rs", # Exact file path
"src/api.rs", # Another exact path
"src/public/*.rs", # Glob pattern for multiple files
"**/api/*.rs", # Recursive glob pattern
]
Customizing Scoring Weights
You can customize how debtmap prioritizes different aspects of technical debt by adjusting the scoring weights in your configuration file. These weights must sum to 1.0:
[]
# Default weights (must sum to 1.0)
= 0.35 # Weight for test coverage gaps (35%)
= 0.25 # Weight for code complexity (25%)
= 0.15 # Weight for semantic importance (15%)
= 0.10 # Weight for dependency criticality (10%)
= 0.10 # Weight for security issues (10%)
= 0.05 # Weight for code organization issues (5%)
# Example: Prioritize security and coverage
# [scoring]
# security = 0.30
# coverage = 0.30
# complexity = 0.20
# semantic = 0.10
# dependency = 0.05
# organization = 0.05
Output Examples
Terminal Format (Default)
âââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââŽ
â Debtmap Analysis Report â
âââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¤
â File â Complexity â Debt Items â Issues â
ââââââââââââââââââââââââââââŧâââââââââââââŧâââââââââââââŧâââââââââ¤
â src/analyzers/rust.rs â 15 â 3 â 2 â
â src/core/metrics.rs â 8 â 1 â 0 â
â src/debt/patterns.rs â 22 â 5 â 3 â
â°ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¯
JSON Format
Architecture
Debtmap is built with a functional, modular architecture designed for extensibility and speed:
Core Modules
-
analyzers/- Language-specific AST parsers and analyzers- Rust analyzer using
synfor full AST parsing - Python analyzer using
rustpython-parser - JavaScript/TypeScript analyzer using
tree-sitter - Call graph extraction for dependency analysis
- Rust analyzer using
-
priority/- Unified prioritization system- Call graph construction and analysis
- Coverage propagation through dependencies
- Semantic function classification (entry points, business logic, utilities)
- ROI-based scoring and recommendations
-
risk/- Risk analysis and coverage integration- LCOV parser for coverage data
- Risk scoring based on complexity-coverage correlation
- Context providers for enhanced risk assessment
- Test effort estimation
-
debt/- Technical debt pattern detection- Code duplication detection with similarity scoring
- TODO/FIXME/HACK marker extraction
- Complexity-based debt identification
- Suppression comment handling
-
security/- Security vulnerability detection- Hardcoded secret detection
- Weak cryptography identification
- SQL injection risk analysis
- Unsafe code block assessment
- Input validation gap detection
-
organization/- Code organization analysis- God object detection
- Feature envy identification
- Primitive obsession patterns
- Magic value detection
-
testing/- Testing quality assessment- Test assertion complexity
- Flaky test pattern detection
- Test complexity analysis
-
resource/- Resource management review- Async/await pattern analysis
- Resource leak detection
- Collection usage efficiency
-
core/- Core data structures and traits- Language-agnostic metrics types
- Shared analysis results structures
- Configuration management
-
io/- File I/O and output formatting- Parallel file walking with ignore patterns
- Multiple output formats (Terminal, JSON, Markdown)
- Pretty-printing with colored output
Contributing
We welcome contributions! This is an early-stage project, so there's plenty of room for improvement.
Areas for Contribution
- Language support: Add analyzers for Go, Java, etc.
- New metrics: Implement additional complexity or quality metrics
- Speed: Optimize analysis algorithms
- Documentation: Improve docs and add examples
- Testing: Expand test coverage
Development
This project uses Just for task automation. Run just to see available commands.
# Common development tasks
# CI and quality checks
# See all available commands
Automated Technical Debt Reduction
We use mmm (Memento Mori) for automated technical debt reduction through AI-driven workflows. This allows us to continuously improve code quality without manual intervention.
Quick Start
# Run automated debt reduction (5 iterations)
This command:
- Creates an isolated git worktree for safe experimentation
- Runs up to 5 iterations of automated improvements
- Each iteration identifies and fixes the highest-risk technical debt
- Validates all changes with tests and linting
- Commits improvements with detailed metrics
What Gets Fixed
The workflow automatically addresses:
- High complexity functions (cyclomatic complexity > 10)
- Untested complex code (low coverage on risky functions)
- Code duplication (repeated blocks > 50 lines)
- Deep nesting and long functions
- Code style inconsistencies
Documentation
For detailed information on our development process:
- MMM Workflow Guide - Using mmm for automated debt reduction
- Claude Workflow Guide - Manual debt reduction with Claude Code
Example Session
After the workflow completes, review and merge the improvements:
# Review changes
# If satisfied, merge to main
License
MIT License - see LICENSE file for details
Dependency Licensing Note
Debtmap includes Python parsing functionality via rustpython-parser, which depends on malachite (LGPL-3.0 licensed) for arbitrary-precision arithmetic. This LGPL dependency is used only for Python AST parsing and does not affect the MIT licensing of debtmap itself. For use cases requiring strict MIT-only dependencies, Python support can be disabled or replaced with an alternative parser.
Roadmap
Language Support
- Rust - Full support with AST parsing and macro expansion
- Python - Full support via rustpython-parser
- JavaScript/TypeScript - Full support via tree-sitter
- Go - Planned
- C/C++ - Planned
- C# - Planned
- Java - Planned
Core Features
- Inline suppression comments
- LCOV coverage integration with risk analysis
- ROI-based testing prioritization
- Comprehensive debt detection (20+ pattern types)
- Security vulnerability detection
- Resource management analysis
- Code organization assessment
- Testing quality evaluation
- Resource management review
- Historical trend tracking
- Automated refactoring suggestions
Integrations
- GitHub Actions marketplace
- GitLab CI integration
- VSCode extension
- IntelliJ plugin
- Pre-commit hooks
Acknowledgments
Built with excellent Rust crates including:
- syn for Rust AST parsing
- rustpython-parser for Python parsing
- tree-sitter for JavaScript/TypeScript parsing
- rayon for parallel processing
- clap for CLI parsing
Note: This is a prototype tool under active development. Please report issues and feedback on GitHub.