# Todo
## Roadmap
### A. Test Coverage Ingestion
- Ingest LCOV/JSON from `cargo llvm-cov` or `cargo test -- --coverage`.
- Render to terminal, HTML, Markdown, and JSONL.
- Support path normalization: `--root`, `--strip-prefix`, `--ignore-regex`.
- Support Git diff coverage.
### B. AST-Based Clone Detection
- Compare abstract syntax trees or subtrees.
- Identify clones resilient to renamed variables or formatting changes.
- Require per-language AST adapters.
### C. Cognitive Complexity
- Score human comprehension cost.
- Reward flattened control flow and penalize deep nesting.
- Require AST-level traversal.
### D. Halstead Complexity
- Count distinct and total operators and operands.
- Compute vocabulary, length, volume, difficulty, and effort.
- Complement Cyclomatic Complexity with lexical complexity.
### E. Maintainability Index
- Combine Cyclomatic, Halstead, and LOC into a single number.
- Useful for dashboards and longitudinal tracking.
### F. Semantic Clone Detection
- Go beyond syntax to identify logically equivalent code.
- Require control/data-flow analysis.
### G. Dependency Metrics
- Coupling, fan-in/fan-out, and depth of inheritance.
- Require language-specific type resolution or symbol graph extraction.
### H. Hotspot Analysis
- Combine Git history and complexity metrics.
- Identify files that change often and are complex.
### I. Incremental Mode
- Cache hashes and graphs.
- Analyze only changed files and touched boundaries.
### J. Rich Reports
- HTML dashboards.
- SVG graphs for CFG visualization.
- JSON with stable schema for CI systems.
## Coverage Completion
### Tasks
#### HTML
- [x] Implement `coverage_html.rs` reporter.
- [x] Generate static HTML reports as a `genhtml` alternative.
- [x] Add index page with sortable directory tree.
- [x] Add per-file source views with syntax highlighting and coverage annotation.
- [x] Add CLI flag: `--html
` for HTML output.
#### Filtering Features
- [ ] Self-check: run mccabre coverage on its own `lcov.info`.
- [ ] Implement `--fail-under-coverage ` flag.
- [ ] Add `--ignore-patterns ` to exclude files, for example tests or vendored code.
- [ ] Add glob-based file filtering in core.
#### Agentic Enhancements
- [ ] Add `--output jsonl` for `coverage show`, which is currently terminal only.
- [ ] Add semantic exit codes for coverage gate: `0` = pass, `2` = below threshold.
- [ ] Add `--diff [` mode for coverage delta on changed files only.
- [ ] Add JSON Schema for coverage output using `schemars`.
#### Build System Integration
- [ ] Artifact generation for README Markdown.
### Definition of Done
- [ ] `mccabre coverage report --html ` produces a valid static site.
- [ ] `mccabre coverage report --fail-under-coverage 80` exits `2` if below threshold.
- [ ] `mccabre coverage --diff main` shows coverage delta for changed files.
- [ ] All coverage commands support `--output json|jsonl|plain`.
## Clone Detection Improvements
### Direction
Keep the clone detector language-agnostic and rolling-hash based for the near term. Improve the quality of the existing `mccabre clones` output before adding AST-level or language-specific clone detection.
### Tasks
#### Configuration
- [ ] Add `min_lines` to `CloneConfig` so short token matches on one or two lines can be filtered out.
- [ ] Add `min_occurrences` to `CloneConfig` for projects that only care about repeated boilerplate appearing three or more times.
- [ ] Add `max_duplicate_lines_percent` to support simple CI gating without introducing a new workflow.
- [ ] Add `ignore_patterns` to the existing file/filtering configuration and use it across `analyze`, `clones`, `complexity`, and `loc`.
- [ ] Add conservative default ignores for common vendored/generated directories: `target`, `node_modules`, `dist`, `build`, `coverage`.
#### CLI Shape
- [ ] Extend the existing `clones` command instead of adding new clone subcommands.
- [ ] Add flags:
- `--min-lines/--min-ln `
- `--min-occurrences/--min-occ `
- `--fail-over-duplicates `
- `--ignore-pattern ` repeatable
- `--top `
- [ ] Use exit code `0` for success, `1` for threshold failure, and existing error handling for runtime/config failures.
#### Token Pipeline
- [ ] Refactor clone detection into small internal stages:
- collect significant tokens
- normalize tokens
- hash windows
- verify matched windows
- merge matched ranges
- build report
- [ ] Add an internal `CloneToken` or `NormalizedToken` type with token kind, text/category, line, column, and hash.
- [ ] Keep default matching exact at the token level; do not require AST parsing for MVP clone improvements.
- [ ] Add optional coarse normalization for the existing tokenizer:
- identifiers can hash as ``
- literals can hash as ``
- operators and punctuation remain exact
- [ ] Compare normalized token slices after a hash match to guard against hash collisions.
#### Clone Group Quality
- [ ] Extend matching windows forward while tokens remain equal so reports show the full duplicated range.
- [ ] Merge overlapping windows from the same duplicate region into one clone group.
- [ ] Drop clone groups fully contained inside larger clone groups.
- [ ] Deduplicate identical locations before assigning group IDs.
- [ ] Sort clone groups deterministically by descending duplicated lines, then path, then line.
- [ ] Keep numeric display IDs, but make their order deterministic across repeated runs.
#### Reporting
- [ ] Add clone summary fields to `Report::summary`:
- files with clones
- duplicate line count
- duplicate token count
- duplicate line percentage
- clone instance count
- [ ] Include a stable `fingerprint` field on each clone in JSON output while keeping numeric IDs for terminal output.
- [ ] Show estimated duplicated lines per clone group in plaintext output.
- [ ] When `--highlight` is enabled, show only the merged duplicate region, not every overlapping window.
- [ ] Add JSON Schema for the full report once clone output stabilizes.
#### Tests & Benchmarks
- [ ] Add fixtures for exact clones, renamed-variable clones under coarse normalization, literal-only differences, overlapping windows, and generated-directory ignores.
- [ ] Add regression tests proving clone IDs and fingerprints are stable across repeated runs.
- [ ] Add benchmark fixtures for 10, 100, and 1,000 file projects.
- [ ] Add a self-check that runs `mccabre clones` against this repository.
### Later
- [ ] Add `--changed-since ][` after the project has a shared Git-diff utility for coverage and hotspots.
- [ ] Add persistent token caching as part of the broader incremental mode work.
- [ ] Evaluate suffix-array/LCP clone extraction only if rolling-hash range extension remains noisy or slow.
- [ ] Move Type II/III clone classification into the AST-Based Clone Detection milestone.
### Definition of Done
- [ ] `mccabre clones . --min-tokens 30 --min-lines 5` reports merged clone ranges.
- [ ] Clone output is deterministic across repeated runs.
- [ ] JSON output includes clone fingerprints and duplicate-line summary metrics.
- [ ] `--fail-over-duplicates 5` exits `1` when duplicate lines exceed 5%.
- [ ] The existing `analyze` command can include the improved clone summary without changing its public shape.
## AST Foundation & Language Adapters
### Tasks
- [ ] Add tree-sitter core dependency to core crate.
- [ ] Define `LanguageAdapter` trait with methods:
- `nesting_constructs()` for cognitive complexity.
- `function_definition()` / `call_expression()` for call graphs.
- `import_statement()` for coupling metrics.
- `identifier_kinds()` / `literal_kinds()` for clone normalization.
- [ ] Implement `RustAdapter` with `tree-sitter-rust` as an optional feature.
- [ ] Implement `PythonAdapter` with `tree-sitter-python` as an optional feature.
- [ ] Create adapter registry with auto-detection by file extension.
- [ ] Create `ast` module with shared parsing utilities.
- [ ] Implement AST traversal helpers using a visitor pattern.
### Definition of Done
- [ ] `get_adapter("src/main.rs")` returns `RustAdapter`.
- [ ] `get_adapter("app.py")` returns `PythonAdapter`.
- [ ] AST traversal works with any registered adapter.
- [ ] Language grammars are optional Cargo features.
## Cognitive Complexity
### Tasks
- [ ] Implement nesting-aware AST traversal using `adapter.nesting_constructs()`.
- [ ] Add scoring rules per SonarQube specification:
- +1 base for nesting constructs, language-specific via adapter.
- +nesting level for nested structures.
- +1 for logical operators via `adapter.logical_operators()`.
- +1 for labeled breaks/continues.
- +1 for recursion.
- [ ] Create `cognitive` CLI subcommand.
- [ ] Add `--max` threshold and `--fail-on-exceed` flag.
- [ ] Add JSON output with breakdown per construct.
### Dependencies
- Requires: AST Foundation & Language Adapters.
### Definition of Done
- [ ] `mccabre cognitive src/` outputs per-function cognitive scores.
- [ ] Scores match SonarQube/rust-code-analysis for reference files.
- [ ] `--max 15 --fail-on-exceed` returns exit code `2` if any function exceeds.
## Halstead Complexity
### Direction
Add Halstead as a token-based metric before Maintainability Index. Keep the first implementation simple and deterministic: use the existing tokenizer where possible, classify tokens into operators and operands, and report file-level values before adding per-function breakdowns.
### Metrics
Halstead is based on counts of operators and operands:
- `n1`: distinct operators
- `n2`: distinct operands
- `N1`: total operators
- `N2`: total operands
- Vocabulary: `n = n1 + n2`
- Length: `N = N1 + N2`
- Volume: `V = N * log2(n)`
- Difficulty: `D = (n1 / 2) * (N2 / n2)`
- Effort: `E = D * V`
### Tasks
- [ ] Extend tokenizer output or add a classifier that maps existing tokens to operator and operand categories.
- [ ] Treat keywords and punctuation that affect expressions/control flow as operators.
- [ ] Treat identifiers and literals as operands.
- [ ] Decide how comments, whitespace, delimiters, and language-specific keywords should be excluded or classified.
- [ ] Add `HalsteadMetrics` to `crates/core/src/complexity`.
- [ ] Include raw counts and computed values in JSON output.
- [ ] Add a `halstead` CLI subcommand, or include Halstead in `complexity` once output compatibility is decided.
- [ ] Add threshold options only after the metric is validated against fixtures.
- [ ] Document limitations clearly: token-based classification, no type resolution, no semantic equivalence.
### Tests
- [ ] Add small fixtures with hand-calculated Halstead counts.
- [ ] Add language coverage for Rust, JavaScript/TypeScript, Go, Java, and C/C++.
- [ ] Add regression tests for empty files, comment-only files, string literals, and repeated identifiers.
- [ ] Compare output against at least one reference implementation where practical.
### Dependencies
- Uses existing: tokenizer and file loader.
- Feeds future: Maintainability Index.
### Definition of Done
- [ ] `mccabre halstead src/` reports Halstead counts and computed metrics per file.
- [ ] JSON output includes stable field names for counts, vocabulary, length, volume, difficulty, and effort.
- [ ] Values match hand-calculated fixtures within floating-point tolerance.
- [ ] Maintainability Index can consume Halstead Volume without recomputing token classifications.
### References
-
-
## Maintainability Index
### Tasks
- [ ] Combine planned Halstead, existing Cyclomatic, and existing LOC metrics.
- [ ] Implement Visual Studio normalized formula on a 0–100 scale:
```text
MI = max(0, (171 - 5.2*ln(HV) - 0.23*CC - 16.2*ln(LOC)) * 100/171)
```
- [ ] Add qualitative ratings: High, Moderate, Low, VeryLow.
- [ ] Create `maintainability` CLI subcommand.
- [ ] Add `--min-score` threshold and `--fail-under` flag.
- [ ] Add JSON output with contributing factors.
### Dependencies
- Requires: Halstead Complexity.
- Uses existing: Cyclomatic, LOC.
### Definition of Done
- [ ] `mccabre maintainability src/` outputs per-file MI scores.
- [ ] Scores are within tolerance of Visual Studio/reference implementations.
- [ ] `--min-score 60 --fail-under` returns exit code `2` if below.
## AST-Based Clone Detection
### Tasks
- [ ] Implement sub-tree hashing algorithm.
- [ ] Use `adapter.identifier_kinds()` / `adapter.literal_kinds()` for normalization.
- [ ] Configure minimum AST node count threshold.
- [ ] Add `--method ast` flag to existing `clones` command.
- [ ] Implement similarity threshold for near-miss clones.
- [ ] Add JSON output with clone type classification: I, II, III.
### Dependencies
- Requires: AST Foundation & Language Adapters.
### Definition of Done
- [ ] `mccabre clones . --method ast` detects Type I and II clones.
- [ ] Clones are detected even with renamed variables.
- [ ] Output includes clone type and similarity score.
- [ ] Performance is acceptable for codebases with more than 100 files.
## Coupling Metrics
### Tasks
- [ ] Parse import statements using `adapter.import_statement()`.
- [ ] Build module dependency graph using `petgraph`.
- [ ] Calculate afferent coupling (`Ca`): who depends on this module.
- [ ] Calculate efferent coupling (`Ce`): what this module depends on.
- [ ] Calculate instability: `I = Ce / (Ca + Ce)`.
- [ ] Calculate abstractness: `A = abstract types / total types`.
- [ ] Calculate distance from main sequence: `D = |A + I - 1|`.
- [ ] Identify zones of pain and uselessness.
- [ ] Create `coupling` CLI subcommand.
- [ ] Add DOT output for dependency graph visualization.
### Dependencies
- Requires: AST Foundation & Language Adapters, `petgraph`.
### Definition of Done
- [ ] `mccabre coupling src/` outputs per-module coupling metrics.
- [ ] `--output dot > deps.dot` produces valid Graphviz diagram.
- [ ] `--show-zones` identifies modules in problem zones.
- [ ] Metrics align with Robert C. Martin's package principles.
## Call Graphs & Data-Flow Graphs
### Tasks
- [ ] Extract function/method definitions using `adapter.function_definition()`.
- [ ] Detect call sites using `adapter.call_expression()`.
- [ ] Build call graph using `petgraph` `DiGraph`.
- [ ] Calculate fan-in: callers per function.
- [ ] Calculate fan-out: callees per function.
- [ ] Identify entry points with no callers and leaves with no callees.
- [ ] Create `callgraph` CLI subcommand.
- [ ] Add DOT, JSON, and SVG output formats.
- [ ] Add `--function` filter and `--depth` limit.
### Dependencies
- Requires: AST Foundation & Language Adapters, `petgraph`.
### Definition of Done
- [ ] `mccabre callgraph src/main.rs` outputs call graph for file.
- [ ] `--output dot > cg.dot && dot -Tsvg cg.dot > cg.svg` produces visualization.
- [ ] `--function foo --include-callers` shows call chain to function.
- [ ] Static and method calls are detected accurately.
## Summary
### MVP
- LOC
- Cyclomatic Complexity
- Rabin-Karp Clone Detection
- Halstead Complexity
### v1
- Call graphs and data-flow graphs
- AST-based clones
- Cognitive Complexity
- Maintainability Index
- Coupling metrics
### v2
- Hotspot analysis
- Incremental scanning
]