debtmap 0.17.0

Code complexity and technical debt analyzer
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
# Context Providers

Context providers enhance debtmap's risk analysis by incorporating additional factors beyond complexity and test coverage. They analyze critical execution paths, dependency relationships, and version control history to provide a more comprehensive understanding of technical risk.

## Table of Contents

- [Overview]#overview
- [Critical Path Provider]#critical-path-provider
- [Dependency Provider]#dependency-provider
- [Git History Provider]#git-history-provider
- [Enabling Context Providers]#enabling-context-providers
- [Provider Weights]#provider-weights
- [How Context Affects Scoring]#how-context-affects-scoring
- [Context Details Structure]#context-details-structure
- [Practical Examples]#practical-examples
- [Configuration]#configuration
- [Performance Considerations]#performance-considerations
- [Troubleshooting]#troubleshooting
- [Advanced Usage]#advanced-usage
- [Best Practices]#best-practices
- [See Also]#see-also

## Overview

Context providers implement the `ContextProvider` trait, which gathers risk-relevant information about functions and modules. Each provider analyzes a specific dimension of risk:

- **Critical Path Provider**: Identifies functions on critical execution paths
- **Dependency Provider**: Analyzes call graph relationships and blast radius
- **Git History Provider**: Integrates version control history for change patterns

Context providers help debtmap understand:
- Which code paths are most critical
- How functions depend on each other
- Which code changes most frequently
- Where bugs are likely to occur

This context-aware analysis improves prioritization accuracy and reduces false positives.

The `ContextAggregator` combines context from multiple enabled providers and adjusts risk scores using the formula:

```
contextual_risk = base_risk × (1.0 + context_contribution)
```

Where `context_contribution` is the weighted sum of all provider contributions:

```
context_contribution = Σ(provider.contribution × provider.weight)
```

> **Configuration Note**: Provider-specific TOML configuration (like `[context.critical_path]`) is a planned feature not yet implemented. All providers currently use hard-coded defaults from the implementation. Use CLI flags (`--context`, `--context-providers`, `--disable-context`) to control providers. See the [Enabling Context Providers]#enabling-context-providers section for working examples.

## Critical Path Provider

The Critical Path provider identifies functions that lie on critical execution paths through your application. Functions on these paths have elevated risk because failures directly impact user-facing functionality.

### Entry Point Detection

The provider automatically detects entry points based on function names and file paths. These weights determine the base criticality of execution paths:

| Entry Type | Weight | Detection Pattern | User-Facing |
|------------|--------|-------------------|-------------|
| Main | 10.0 | Function named `main` | Yes |
| API Endpoint | 8.0 | `handle_*`, `*_handler`, `get_*`, `post_*` in `api/`, `handler/`, `route/` paths | Yes |
| CLI Command | 7.0 | `cmd_*`, `command_*`, `*_command` in `cli/`, `command/` paths | Yes |
| Web Handler | 7.0 | Functions with `route`, `handler` in `web/`, `http/` paths | Yes |
| Event Handler | 5.0 | `on_*`, `*_listener`, contains `event` | No |
| Test Entry | 2.0 | `test_*`, in `test/` paths | No |

**Note on API Endpoint detection:** Detection requires BOTH conditions: (1) path contains `api/`, `handler/`, or `route/` AND (2) function starts with `handle_*`, `get_*`, `post_*`, `put_*`, `delete_*` or ends with `*_handler`. This combined matching ensures accurate classification of HTTP endpoint handlers.

**What it detects:**
- Entry points (main functions, CLI handlers, API endpoints)
- Error handling paths
- Data processing pipelines
- Resource initialization

### Path Weighting

Functions on critical paths receive contribution scores based on:

- **Path weight**: The maximum entry point weight leading to the function
- **User-facing flag**: Doubles contribution for user-facing paths

The contribution formula consists of two steps:

```rust
// Step 1: Calculate base contribution (normalized 0-1)
base_contribution = path_weight / max_weight

// Step 2: Apply user-facing multiplier
final_contribution = base_contribution × user_facing_multiplier

// Example: main entry path (weight 10.0, user-facing)
base = 10.0 / 10.0 = 1.0
final = 1.0 × 2.0 = 2.0

// Example: event handler path (weight 5.0, non-user-facing)
base = 5.0 / 10.0 = 0.5
final = 0.5 × 1.0 = 0.5
```

**Impact on scoring:**
- Functions on critical paths get higher priority
- Entry point multiplier: 1.5x
- Business logic multiplier: 1.2x

### Use Cases

- **API prioritization**: Identify critical endpoints that need careful review
- **Refactoring safety**: Avoid breaking user-facing execution paths
- **Test coverage**: Ensure critical paths have adequate test coverage

### Enable

```bash
debtmap analyze . --context-providers critical_path
```

**Configuration:**
```toml
[analysis]
context_providers = ["critical_path"]

# Note: Provider-specific TOML sections below are planned features.
# Currently, providers use hard-coded defaults. Use CLI flags for now.

[context.critical_path]
# Multiplier for entry points (default: 1.5)
entry_point_multiplier = 1.5

# Multiplier for business logic (default: 1.2)
business_logic_multiplier = 1.2
```

## Dependency Provider

The Dependency provider analyzes call graph relationships to identify functions with high architectural impact. It calculates how changes propagate through the dependency graph and determines the blast radius of modifications.

### Dependency Chain Analysis

The provider builds a dependency graph where:

- **Modules** contain functions and have intrinsic risk scores
- **Edges** represent dependencies with coupling strength (0.0-1.0)
- **Risk propagation** flows through dependencies using iterative refinement

**Convergence Parameters:** The risk propagation algorithm uses iterative convergence with a maximum of 10 iterations. Convergence is reached when the maximum risk change between iterations falls below 0.01. This ensures risk stabilizes throughout the dependency graph.

**What it detects:**
- Upstream dependencies (functions this function calls)
- Downstream dependencies (functions that call this function)
- Transitive dependencies through the call graph
- Dependency criticality

### Blast Radius Calculation

The blast radius represents how many modules would be affected by changes to a function. It counts unique modules reachable through transitive dependencies by traversing the dependency graph edges.

| Blast Radius | Contribution | Impact Level |
|--------------|--------------|--------------|
| > 10 modules | 1.5 | Critical dependency affecting many modules |
| > 5 modules | 1.0 | Important dependency with moderate impact |
| > 2 modules | 0.5 | Medium impact |
| ≤ 2 modules | 0.2 | Minimal or isolated component |

### Risk Propagation Formula

Risk propagation uses an iterative convergence algorithm to stabilize risk scores throughout the dependency graph:

```rust
propagated_risk = base_risk × criticality_factor + Σ(caller.risk × 0.3)

where:
  criticality_factor = 1.0 + min(0.5, dependents.len() × 0.1)
  The 0.3 factor dampens risk propagation from callers
```

**Iterative Convergence:** The algorithm runs with a maximum of 10 iterations and converges when the maximum risk change between iterations falls below 0.01. This ensures risk stabilizes throughout the dependency graph without requiring manual tuning.

**Note**: The constants (0.5, 0.1, 0.3) are currently hard-coded based on empirical analysis. Future versions may make these configurable.

**Impact on scoring:**
```
dependency_factor = normalized_to_0_10(upstream + downstream)

Ranges:
- 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)
```

### Use Cases

- **Architectural refactoring**: Identify high-impact modules to refactor carefully
- **Change impact analysis**: Understand downstream effects of modifications
- **Module decoupling**: Find tightly coupled modules with high blast radius

### Enable

```bash
debtmap analyze . --context-providers dependency
```

**Configuration:**
```toml
[analysis]
context_providers = ["dependency"]

# Note: Provider-specific TOML sections below are planned features.
# Currently, providers use hard-coded defaults. Use CLI flags for now.

[context.dependency]
# Include transitive dependencies (default: true)
include_transitive = true

# Maximum depth for transitive analysis (default: 5)
max_depth = 5
```

## Git History Provider

The Git History provider integrates version control data to detect change-prone code and bug patterns. Files with frequent changes and bug fixes indicate higher maintenance risk.

### Metrics Collected

The provider analyzes Git history to calculate:

- **Change frequency**: Commits per month (recent activity indicator)
- **Bug density**: Ratio of bug fix commits to total commits
- **Age**: Days since first commit (maturity indicator)
- **Author count**: Number of unique contributors (complexity indicator)
- **Total commits**: Total number of commits to the file
- **Last modified**: Timestamp of the most recent commit
- **Stability score**: Weighted combination of churn, bug fixes, and age (0.0-1.0)

**What it analyzes:**
- Commit frequency per file/function
- Bug fix patterns (commits with "fix" in message)
- Code churn (lines added/removed)
- Recent activity

### Risk Classification

The table below shows approximate contribution thresholds for understanding risk levels:

| Category | Conditions | Contribution | Explanation |
|----------|------------|--------------|-------------|
| Very unstable | freq > 5.0 AND bug_density > 0.3 | 2.0 | High churn with many bug fixes |
| Moderately unstable | freq > 2.0 OR bug_density > 0.2 | 1.0 | Frequent changes or bug-prone |
| Slightly unstable | freq > 1.0 OR bug_density > 0.1 | 0.5 | Some instability |
| Stable | freq ≤ 1.0 AND bug_density ≤ 0.1 | 0.1 | Low change rate, few bugs |

#### Continuous Scoring Model

The actual implementation uses a **continuous scoring formula** rather than discrete thresholds. This provides more accurate differentiation between risk levels (from `src/risk/context/git_history.rs:495`):

```rust
contribution = (bug_density * 1.5) + min(change_frequency / 20.0, 0.5)
```

**Scoring breakdown:**

- **Bug density** (primary signal): Scales linearly from 0.0 to 1.5
  - 0% bugs → 0.0 contribution
  - 50% bugs → 0.75 contribution
  - 100% bugs → 1.5 contribution

- **Change frequency** (secondary signal): Scales from 0.0 to 0.5, saturates at 10/month
  - 0/month → 0.0
  - 5/month → 0.25
  - 10+/month → 0.5 (capped)

- **Total** is capped at 2.0 to prevent excessive score amplification
- Stable code with no bugs and no changes contributes 0.0 (no risk increase)

**Example calculations:**

| Scenario | Frequency | Bug Density | Contribution |
|----------|-----------|-------------|--------------|
| Stable code | 0.0/month | 0% | 0.0 |
| Low activity, some bugs | 2.0/month | 25% | 0.475 |
| High churn, no bugs | 10.0/month | 0% | 0.5 |
| Bug-prone | 0.5/month | 100% | 1.525 |
| Critical hotspot | 10.0/month | 50% | 1.25 |

### Bug Fix Detection

The provider identifies bug fixes using sophisticated pattern matching with **word boundary detection** to minimize false positives from substring matches like "prefix" or "debug".

**Detection Patterns:**

The analyzer searches commit messages for these word-boundary-matched patterns (case-insensitive):

- `\bfix\b`, `\bfixes\b`, `\bfixed\b`, `\bfixing\b` - Matches "fix" as a complete word, excluding "prefix", "suffix", "fixture"
- `\bbug\b` - Matches "bug" as a complete word, excluding "debug", "debugging"
- `\bhotfix\b` - Matches emergency fixes

**Git Command:**

```bash
git log --oneline \
  --grep='\bfix\b' --grep='\bfixes\b' --grep='\bfixed\b' \
  --grep='\bfixing\b' --grep='\bbug\b' --grep='\bhotfix\b' \
  -i -- <file>
```

**Exclusion Filters:**

To further reduce false positives, commits are filtered out if they match non-bug-fix patterns:

| Exclusion Type | Keywords | Rationale |
|---------------|----------|-----------|
| Conventional Commits | `style:`, `chore:`, `docs:`, `test:` | Not bug fixes, just maintenance |
| Maintenance | `formatting`, `linting`, `whitespace`, `typo` | Cosmetic changes, not functional bugs |
| Refactoring | `refactor:` (without bug keywords) | Code improvements without fixing bugs |

**Examples of Detection:**

| Commit Message | Detected? | Reason |
|----------------|-----------|--------|
| `fix: resolve login bug` | ✅ Yes | Contains "fix" and "bug" as complete words |
| `Fixed the payment issue` | ✅ Yes | Contains "fixed" as complete word |
| `hotfix: urgent database fix` | ✅ Yes | Contains "hotfix" and "fix" |
| `Bug fix for issue #123` | ✅ Yes | Contains "bug" and "fix" |
| `style: apply formatting fixes` | ❌ No | Excluded: conventional commit type "style:" |
| `refactor: improve prefix handling` | ❌ No | Excluded: refactor without bug keywords, "prefix" is substring |
| `Add debugging tools` | ❌ No | "debugging" contains "bug" but not as word boundary |
| `chore: fix linting issues` | ❌ No | Excluded: conventional commit type "chore:" |
| `update: add fixture for testing` | ❌ No | "fixture" contains "fix" but not as word boundary |

**Bug Density Calculation:**

```
bug_density = bug_fix_count / total_commits
```

For example, if a file has 10 total commits and 3 are genuine bug fixes (after exclusion filtering):
- Bug density = 3/10 = 0.30 (30%)

A file with 100% bug density means every commit to that file was a bug fix, which is a strong signal that the code is problematic.

### Research Background: The Bug Magnet Hypothesis

The use of git history for risk assessment is backed by extensive empirical research in software engineering. The core theory, often called the **"Bug Magnet Hypothesis"**, states that **code with a history of bugs is significantly more likely to contain future bugs**.

#### Empirical Evidence

Multiple large-scale studies have validated this approach:

- **Microsoft Study (Nagappan & Ball, 2005)**: Analyzed Windows Server 2003 and found that modules with prior bugs were **4-16 times more likely** to have future bugs than modules without bug history.

- **Mozilla Study (Hassan, 2009)**: Found that bug prediction models based on change history achieved **73% accuracy** in identifying future buggy files.

- **Linux Kernel Study (Kim et al., 2007)**: Showed that files with bug fixes in their recent history had a significantly higher probability of containing latent defects.

#### Why Past Bugs Predict Future Bugs

There are four key mechanisms that explain this phenomenon:

1. **Inherent Complexity**: Code that attracted bugs in the past is often more complex, making it harder to fix correctly and more prone to regression.

2. **Incomplete Understanding**: If developers repeatedly introduce bugs in the same area, it suggests the code is difficult to understand or has subtle edge cases.

3. **Technical Debt Accumulation**: Bug fixes under time pressure often introduce workarounds rather than proper solutions, creating technical debt that leads to more bugs.

4. **Broken Window Effect**: Once code develops a reputation for being buggy, it may receive less careful maintenance, perpetuating the cycle.

#### Interpreting Bug Density Scores

| Bug Density | Interpretation | Action |
|-------------|----------------|--------|
| 0% - 10% | Healthy | Typical for stable, well-tested code |
| 10% - 30% | Moderate concern | Consider adding tests or documentation |
| 30% - 50% | High risk | Strong candidate for refactoring |
| 50% - 100% | Critical | Almost certainly needs redesign or major refactoring |

**Example from real output:**
```
├─ GIT HISTORY: 2.0 changes/month, 100.0% bugs, 30 days old, 1 authors
│  └─ Risk Impact: base_risk=39.7 → contextual_risk=88.9 (2.2x multiplier)
```

This shows a file where **every single commit** was a bug fix (100% bug density), resulting in a 2.2x risk multiplier. This is a critical red flag indicating code that needs immediate attention.

#### Limitations and False Positives

The improved detection methodology with word boundary matching and exclusion filters significantly reduces false positives, but some limitations remain:

**Reduced Issues** (handled by word boundaries and exclusion filters):
- **Substring matches**: Word boundary matching (`\bfix\b`) now correctly excludes "prefix", "fixture", "suffix", and "debugging"
-**Style/formatting commits**: Conventional commit prefixes (`style:`, `chore:`) are automatically excluded
-**Maintenance changes**: Keywords like "formatting", "linting", "whitespace", "typo" are filtered out
-**Non-bug refactorings**: Refactoring commits without bug-related keywords are excluded

**Remaining Limitations:**
- **Commit message quality**: Still relies on developers mentioning "fix" or "bug" in commit messages
  - Underreporting: Some bug fixes may not be mentioned in commit messages
  - Example: A commit "Update authentication logic" that actually fixes a bug won't be detected
- **New code**: Cannot assess code without commit history
  - Files with <5 commits may not have enough data for reliable bug density calculation
- **Language barriers**: Non-English commit messages may use different bug-fix keywords
- **Informal commits**: Internal repos may use different conventions (e.g., ticket IDs only)

**Accuracy Improvements:**

Before word boundary matching and exclusion filters:
- False positive rate: ~15-25% (substring matches, style commits, etc.)

After improvements:
- False positive rate: ~5-10% (primarily commit message quality issues)
- Precision: Significantly improved, particularly for conventional commit style repositories

**Recommended practice**: Use git history as one signal among many. Combine it with complexity metrics, test coverage, and dependency analysis for a complete risk picture. The bug density metric is most reliable when:
- Repository uses consistent commit message conventions
- Files have at least 10+ commits in their history
- Development team follows English-based conventional commit style

### Stability Score

Stability is calculated using weighted factors:

```rust
stability = (churn_factor × 0.4) + (bug_factor × 0.4) + (age_factor × 0.2)

where:
  churn_factor = 1.0 / (1.0 + monthly_churn)
  bug_factor = 1.0 - (bug_fixes / total_commits)
  age_factor = min(1.0, age_days / 365.0)
```

### Stability Status Classifications

The provider internally classifies files into stability statuses based on the calculated metrics:

| Status | Criteria | Explanation |
|--------|----------|-------------|
| HighlyUnstable | freq > 5.0 AND bug_density > 0.3 | Extremely high churn combined with many bug fixes |
| FrequentlyChanged | freq > 2.0 | High change rate regardless of bug density |
| BugProne | bug_density > 0.2 | High proportion of bug fix commits |
| MatureStable | age > 365 days | Code older than one year (unless unstable) |
| RelativelyStable | (default) | Moderate activity, typical stability |

These classifications are used internally for contribution calculations and appear in verbose output.

**Impact on scoring:**
- High-churn functions get higher priority
- Recently fixed bugs indicate risk areas
- Stable code (no recent changes) gets lower priority

### Use Cases

- **Find change-prone code**: Identify files that change frequently and need attention
- **Detect bug hotspots**: Locate areas with high bug fix rates
- **Prioritize refactoring**: Target unstable code for improvement
- **Team collaboration patterns**: Files touched by many authors may need better documentation

### Enable

```bash
debtmap analyze . --context-providers git_history
```

**Configuration:**
```toml
[analysis]
context_providers = ["git_history"]

# Note: Provider-specific TOML sections below are planned features.
# Currently, providers use hard-coded defaults. Use CLI flags for now.

[context.git_history]
# Commits to analyze (default: 100)
max_commits = 100

# Time range in days (default: 90)
time_range_days = 90

# Minimum commits to consider "high churn" (default: 10)
high_churn_threshold = 10
```

### Troubleshooting

**Git repository not found**: The provider requires a Git repository. If analysis fails:

```bash
# Verify you're in a git repository
git rev-parse --git-dir

# If not a git repo, initialize one or disable git_history provider
# Option 1: Enable context but exclude git_history
debtmap analyze . --context --disable-context git_history

# Option 2: Use only specific providers
debtmap analyze . --context-providers critical_path,dependency
```

**Performance issues**: Git history analysis can be slow for large repositories:

```bash
# Use only lightweight providers
debtmap analyze . --context-providers critical_path,dependency
```

## Enabling Context Providers

Context-aware analysis is disabled by default. Enable it using CLI flags:

### Enable All Providers

```bash
# Enable all available context providers
debtmap analyze . --context
# or
debtmap analyze . --enable-context
```

### Enable Specific Providers

```bash
# Enable only critical_path and dependency
debtmap analyze . --context-providers critical_path,dependency

# Enable only git_history
debtmap analyze . --context-providers git_history

# Enable all three explicitly
debtmap analyze . --context-providers critical_path,dependency,git_history
```

### Disable Specific Providers

```bash
# Enable context but disable git_history (useful for non-git repos)
debtmap analyze . --context --disable-context git_history

# Enable context but disable dependency analysis
debtmap analyze . --context --disable-context dependency
```

### Enabling Multiple Providers

Combine providers for comprehensive analysis:

```bash
debtmap analyze . --context-providers critical_path,dependency,git_history
```

Or via config:
```toml
[analysis]
context_providers = ["critical_path", "dependency", "git_history"]
```

## Provider Weights

Each provider has a weight that determines its influence on the final risk score:

| Provider | Weight | Rationale |
|----------|--------|-----------|
| critical_path | 1.5 | Critical paths have high impact on users |
| dependency_risk | 1.2 | Architectural dependencies affect many modules |
| git_history | 1.0 | Historical patterns indicate future risk |

The total context contribution is calculated as:

```rust
total_contribution = Σ(contribution_i × weight_i)

Example with all providers:
  critical_path: 2.0 × 1.5 = 3.0
  dependency:    1.0 × 1.2 = 1.2
  git_history:   0.5 × 1.0 = 0.5
  ────────────────────────────
  total_contribution = 4.7

contextual_risk = base_risk × (1.0 + 4.7) = base_risk × 5.7
```

## How Context Affects Scoring

### Base Scoring (No Context)

```
Base Score = (Complexity × 0.40) + (Coverage × 0.40) + (Dependency × 0.20)
```

### With Context Providers

```
Context-Adjusted Score = Base Score × Role Multiplier × Churn Multiplier

Role Multiplier (from critical path & dependency analysis):
- Entry points: 1.5x
- Business logic: 1.2x
- Data access: 1.0x
- Infrastructure: 0.8x
- Utilities: 0.5x
- Test code: 0.1x

Churn Multiplier (from git history):
- High churn (10+ commits/month): 1.3x
- Medium churn (5-10 commits/month): 1.1x
- Low churn (1-5 commits/month): 1.0x
- Stable (0 commits/6 months): 0.8x
```

## Context Details Structure

When using `--format json`, context information is included in the output. The `ContextDetails` enum contains provider-specific data:

### CriticalPath

```json
{
  "provider": "critical_path",
  "weight": 1.5,
  "contribution": 2.0,
  "details": {
    "CriticalPath": {
      "entry_points": ["main (Main)", "handle_request (ApiEndpoint)"],
      "path_weight": 10.0,
      "is_user_facing": true
    }
  }
}
```

### DependencyChain

```json
{
  "provider": "dependency_risk",
  "weight": 1.2,
  "contribution": 1.5,
  "details": {
    "DependencyChain": {
      "depth": 3,
      "propagated_risk": 8.5,
      "dependents": ["module_a", "module_b", "module_c"],
      "blast_radius": 12
    }
  }
}
```

### Historical

```json
{
  "provider": "git_history",
  "weight": 1.0,
  "contribution": 1.0,
  "details": {
    "Historical": {
      "change_frequency": 3.5,
      "bug_density": 0.25,
      "age_days": 180,
      "author_count": 5
    }
  }
}
```

## Practical Examples

### Example 1: Entry Point vs Utility

**Without context providers:**
```
Function: main() - Entry point
Complexity: 8
Coverage: 50%
Score: 6.0 [MEDIUM]

Function: format_string() - Utility
Complexity: 8
Coverage: 50%
Score: 6.0 [MEDIUM]
```

Both functions have the same score.

**With context providers:**
```
Function: main() - Entry point
Complexity: 8
Coverage: 50%
Base Score: 6.0
Role Multiplier: 1.5x (entry point)
Final Score: 9.0 [CRITICAL]

Function: format_string() - Utility
Complexity: 8
Coverage: 50%
Base Score: 6.0
Role Multiplier: 0.5x (utility)
Final Score: 3.0 [LOW]
```

Entry point is prioritized over utility.

### Example 2: High-Churn Function

**Without git history:**
```
Function: process_payment()
Complexity: 12
Coverage: 60%
Score: 7.5 [HIGH]
```

**With git history:**
```
Function: process_payment()
Complexity: 12
Coverage: 60%
Base Score: 7.5
Churn: 15 commits in last month (bug fixes)
Churn Multiplier: 1.3x
Final Score: 9.75 [CRITICAL]
```

High-churn function is elevated to critical.

### Example 3: Stable Well-Tested Code

**Without context:**
```
Function: legacy_parser()
Complexity: 15
Coverage: 95%
Score: 3.5 [LOW]
```

**With context:**
```
Function: legacy_parser()
Complexity: 15
Coverage: 95%
Base Score: 3.5
Churn: 0 commits in last 2 years
Churn Multiplier: 0.8x
Role: Data access (stable)
Role Multiplier: 1.0x
Final Score: 2.8 [LOW]
```

Stable, well-tested code gets even lower priority.

### Example 4: API Endpoint Prioritization

Analyze a web service to identify critical API endpoints:

```bash
debtmap analyze . --context-providers critical_path --format json
```

Functions on API endpoint paths will receive elevated risk scores. Use this to prioritize code review and testing for user-facing functionality.

### Example 5: Finding Change-Prone Code

Identify files with high change frequency and bug fixes:

```bash
debtmap analyze . --context-providers git_history --top 20
```

This highlights unstable areas of the codebase that may benefit from refactoring or increased test coverage.

### Example 6: Architectural Impact Analysis

Find high-impact modules with large blast radius:

```bash
debtmap analyze . --context-providers dependency --format json | \
  jq '.[] | select(.blast_radius > 10)'
```

Use this to identify architectural choke points that require careful change management.

### Example 7: Comprehensive Risk Assessment

Combine all providers for holistic risk analysis:

```bash
debtmap analyze . --context -v
```

The verbose output shows how each provider contributes to the final risk score:

```
function: process_payment
  base_risk: 5.0
  critical_path: +3.0 (on main path, user-facing)
  dependency: +1.2 (12 dependent modules)
  git_history: +1.0 (3.5 changes/month, 0.25 bug density)
  ──────────────────
  contextual_risk: 26.0
```

## Configuration

> ⚠️ **Configuration Limitation**: Provider-specific TOML configuration sections shown below are planned features not yet implemented. Currently, all provider settings use hard-coded defaults from the implementation. Use CLI flags (`--context`, `--context-providers`, `--disable-context`) to control providers. See the CLI examples throughout this chapter for working configurations.

Configure context providers in `.debtmap.toml`:

```toml
[analysis]
# Enable context-aware analysis (default: false)
enable_context = true

# Specify which providers to use
context_providers = ["critical_path", "dependency", "git_history"]

# Disable specific providers (use CLI flag --disable-context instead)
# disable_context = ["git_history"]  # Not yet implemented in config

[context.git_history]
# Commits to analyze (default: 100) - PLANNED
max_commits = 100

# Time range in days (default: 90) - PLANNED
time_range_days = 90

# Minimum commits to consider "high churn" (default: 10) - PLANNED
high_churn_threshold = 10

[context.critical_path]
# Multiplier for entry points (default: 1.5) - PLANNED
entry_point_multiplier = 1.5

# Multiplier for business logic (default: 1.2) - PLANNED
business_logic_multiplier = 1.2

[context.dependency]
# Include transitive dependencies (default: true) - PLANNED
include_transitive = true

# Maximum depth for transitive analysis (default: 5) - PLANNED
max_depth = 5
```

## Performance Considerations

Context providers add computational overhead to analysis:

**Impact on analysis time:**
- Critical path: +10-15% (fast - call graph traversal)
- Dependency: +20-30% (moderate - iterative risk propagation)
- Git history: +30-50% (slow for large repos - multiple git commands per file)

**Combined overhead:** ~60-80% increase in analysis time

### Batched Git History Optimization

The git history provider uses a **batched loading strategy** to minimize subprocess overhead. Instead of running separate git commands for each file (which would create N subprocess calls for N files), the provider:

1. Fetches all git history data upfront in a single batch (`BatchedGitHistory`)
2. Parses the complete log output into an in-memory index
3. Serves subsequent file lookups via O(1) HashMap access

This optimization reduces the git subprocess calls from O(N) to O(1), making git history analysis practical even for large repositories.

**Implementation details** (from `src/risk/context/git_history/batched.rs`):
- On initialization, runs a single `git log --numstat` to fetch all file changes
- Builds per-file indexes for change frequency, bug density, authors, etc.
- Falls back to direct git queries only if batch loading fails

### Optimization Tips

1. **Start minimal**: Use `--context-providers critical_path,dependency` initially
2. **Add git_history selectively**: Enable for critical modules only
3. **Use caching**: The `ContextAggregator` caches results by `file:function` key
4. **Profile with verbose flags**: Use `-vvv` to see provider execution times

### For Large Projects

```bash
# Disable git history for faster analysis
debtmap analyze . --disable-context git_history

# Or disable all context
debtmap analyze . --no-context-aware
```

### For CI/CD

```bash
# Full analysis with context (run nightly)
debtmap analyze . --context-providers critical_path,dependency,git_history

# Fast analysis without context (run on every commit)
debtmap analyze . --no-context-aware
```

### When to Use Each Provider

| Scenario | Recommended Providers |
|----------|----------------------|
| API service refactoring | `critical_path` |
| Legacy codebase analysis | `git_history` |
| Microservice boundaries | `dependency` |
| Pre-release risk review | All providers (`--context`) |
| CI/CD integration | `critical_path,dependency` (faster) |

## Troubleshooting

### Git History Analysis Slow

**Issue:** Analysis takes much longer with git history enabled

**Solutions:**

**Reduce commit history:**
```toml
[context.git_history]
max_commits = 50
time_range_days = 30
```

**Use shallow clone in CI:**
```bash
git clone --depth 50 repo.git
debtmap analyze . --context-providers critical_path,dependency
```

### Incorrect Role Classification

**Issue:** Function classified as wrong role (e.g., utility instead of business logic)

**Possible causes:**
1. Function naming doesn't match patterns
2. Call graph analysis incomplete
3. Function is misplaced in codebase

**Solutions:**

**Check with verbose output:**
```bash
debtmap analyze . -vv | grep "Role classification"
```

**Manually verify call graph:**
```bash
debtmap analyze . --debug-call-graph --call-graph-stats
```

### Context Providers Not Available

**Issue:** `--context-providers` flag not recognized

**Solution:** Ensure you're using a recent version:
```bash
debtmap --version
# Should be 0.2.0 or later
```

Update debtmap:
```bash
cargo install debtmap --force
```

### Common Issues

**Issue**: Context providers not affecting scores

**Solution**: Ensure providers are enabled with `--context` or `--context-providers`

```bash
# Wrong: context flag missing
debtmap analyze .

# Correct: context enabled
debtmap analyze . --context
```

---

**Issue**: Git history provider fails with "Not a git repository"

**Solution**: Disable git_history if not using version control

```bash
debtmap analyze . --context --disable-context git_history
```

---

**Issue**: Dependency analysis errors

**Solution**: Check for circular dependencies or disable dependency provider

```bash
debtmap analyze . --context --disable-context dependency
```

---

**Issue**: Slow analysis with all providers

**Solution**: Use selective providers or increase verbosity to identify bottlenecks

```bash
# Faster: skip git_history
debtmap analyze . --context-providers critical_path,dependency

# Debug: see provider execution times
debtmap analyze . --context -vvv
```

---

For more troubleshooting guidance, see the [Troubleshooting](troubleshooting.md) chapter.

## Advanced Usage

### Interpreting Context Contribution

Enable verbose output to see detailed context contributions:

```bash
debtmap analyze . --context -v
```

Each function shows:
- Base risk score from complexity/coverage
- Individual provider contributions
- Total contextual risk score
- Provider-specific explanations

### Architecture Exploration

The `ContextAggregator` caches context by `file:function` key to avoid redundant analysis during a single run.

**Cache Lifetime:** The cache is in-memory per `ContextAggregator` instance and is cleared when a new instance is created or when analyzing a different codebase. This enables efficient re-analysis within the same run without requiring external cache management:

```rust
let mut aggregator = ContextAggregator::new()
    .with_provider(Box::new(CriticalPathProvider::new(analyzer)))
    .with_provider(Box::new(DependencyRiskProvider::new(graph)))
    .with_provider(Box::new(GitHistoryProvider::new(repo_root)?));

let context = aggregator.analyze(&target);
let contribution = context.total_contribution();
```

### Custom Provider Implementation

Advanced users can implement custom context providers by implementing the `ContextProvider` trait:

```rust
pub trait ContextProvider: Send + Sync {
    fn name(&self) -> &str;
    fn gather(&self, target: &AnalysisTarget) -> Result<Context>;
    fn weight(&self) -> f64;
    fn explain(&self, context: &Context) -> String;
}
```

See `src/risk/context/mod.rs` for the trait definition and `src/risk/context/` for built-in provider implementations.

## Future Enhancements

### Business Context Provider (Planned)

A Business context provider is defined but not yet implemented. It will support:

```rust
Business {
    priority: Priority,      // Critical, High, Medium, Low
    impact: Impact,          // Revenue, UserExperience, Security, Compliance
    annotations: Vec<String> // Custom business metadata
}
```

This will allow manual prioritization based on business requirements through code annotations or configuration files.

## Best Practices

1. **Use all providers for comprehensive analysis** - Especially for production code
2. **Disable git history in CI** - Use shallow clones or disable for speed
3. **Verify role classifications** - Use `-vv` to see how functions are classified
4. **Tune multipliers for your project** - Adjust in config based on architecture
5. **Combine with coverage data** - Context providers enhance coverage-based risk analysis

## Summary

Context providers transform debtmap from a static complexity analyzer into a comprehensive risk assessment tool. By combining:

- **Critical path analysis** for user impact
- **Dependency analysis** for architectural risk
- **Git history analysis** for maintenance patterns

You gain actionable insights for prioritizing technical debt and refactoring efforts. Start with `--context` to enable all providers, then refine based on your project's needs.

## See Also

- [Analysis Guide]analysis-guide/index.md - Core analysis concepts
- [Risk Scoring]analysis-guide/risk-scoring.md - Risk scoring methodology
- [Scoring Strategies]scoring-strategies.md - File-level and function-level scoring
- [Configuration]configuration.md - Complete configuration reference
- [Parallel Processing]parallel-processing.md - Performance optimization
- [Troubleshooting]troubleshooting.md - Common issues and solutions