tokmd-context-git 1.8.0

Git-derived hotspot and churn scoring for context ranking.
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
//! Lightweight git scoring for context ranking.

use std::collections::BTreeMap;
#[cfg(feature = "git")]
use std::path::Path;

#[cfg(feature = "git")]
use tokmd_path::normalize_rel_path as normalize_path;
#[cfg(feature = "git")]
use tokmd_types::{FileKind, FileRow};

/// Git-derived scores for file ranking.
pub struct GitScores {
    /// Per-file hotspot scores: path → (lines × commits)
    pub hotspots: BTreeMap<String, usize>,
    /// Per-file commit counts: path → commits
    pub commit_counts: BTreeMap<String, usize>,
}

#[cfg(feature = "git")]
pub fn compute_git_scores(
    root: &Path,
    rows: &[FileRow],
    max_commits: usize,
    max_commit_files: usize,
) -> Option<GitScores> {
    let repo_root = tokmd_git::repo_root(root)?;
    let commits =
        tokmd_git::collect_history(&repo_root, Some(max_commits), Some(max_commit_files)).ok()?;

    // Build file → lines map (only parent files)
    let file_lines: BTreeMap<String, usize> = rows
        .iter()
        .filter(|r| r.kind == FileKind::Parent)
        .map(|r| (normalize_path(&r.path), r.lines))
        .collect();

    // Count commits per file
    let mut commit_counts: BTreeMap<String, usize> = BTreeMap::new();
    for commit in &commits {
        for file in &commit.files {
            let key = normalize_path(file);
            if file_lines.contains_key(&key) {
                *commit_counts.entry(key).or_insert(0) += 1;
            }
        }
    }

    // Compute hotspot scores: lines × commits
    let hotspots: BTreeMap<String, usize> = commit_counts
        .iter()
        .filter_map(|(path, commits)| {
            let lines = file_lines.get(path)?;
            Some((path.clone(), lines * commits))
        })
        .collect();

    Some(GitScores {
        hotspots,
        commit_counts,
    })
}

#[cfg(not(feature = "git"))]
pub fn compute_git_scores(
    _root: &std::path::Path,
    _rows: &[tokmd_types::FileRow],
    _max_commits: usize,
    _max_commit_files: usize,
) -> Option<GitScores> {
    None
}

#[cfg(test)]
mod tests_no_feature {
    use super::*;

    #[test]
    fn git_scores_can_be_constructed() {
        let scores = GitScores {
            hotspots: BTreeMap::new(),
            commit_counts: BTreeMap::new(),
        };
        assert!(scores.hotspots.is_empty());
        assert!(scores.commit_counts.is_empty());
    }

    #[test]
    fn git_scores_btreemap_is_sorted() {
        let mut hotspots = BTreeMap::new();
        hotspots.insert("z/file.rs".to_string(), 100);
        hotspots.insert("a/file.rs".to_string(), 50);
        let scores = GitScores {
            hotspots,
            commit_counts: BTreeMap::new(),
        };
        let keys: Vec<&String> = scores.hotspots.keys().collect();
        assert_eq!(keys[0], "a/file.rs");
        assert_eq!(keys[1], "z/file.rs");
    }
}

#[cfg(all(test, feature = "git"))]
mod tests {
    use super::*;
    use std::process::Command;
    use tokmd_types::{FileKind, FileRow};

    fn make_row(path: &str, lines: usize) -> FileRow {
        FileRow {
            path: path.to_string(),
            module: "(root)".to_string(),
            lang: "Rust".to_string(),
            kind: FileKind::Parent,
            code: lines,
            comments: 0,
            blanks: 0,
            lines,
            bytes: lines * 10,
            tokens: lines * 5,
        }
    }

    fn create_test_repo() -> Option<tempfile::TempDir> {
        let dir = tempfile::tempdir().ok()?;
        let root = dir.path();

        // git init + config
        Command::new("git")
            .args(["init"])
            .current_dir(root)
            .output()
            .ok()?;
        Command::new("git")
            .args(["config", "user.email", "test@test.com"])
            .current_dir(root)
            .output()
            .ok()?;
        Command::new("git")
            .args(["config", "user.name", "Test"])
            .current_dir(root)
            .output()
            .ok()?;

        // main.rs: 2 commits (3 lines initially, then 4)
        std::fs::write(root.join("main.rs"), "1\n2\n3").ok()?;
        Command::new("git")
            .args(["add", "."])
            .current_dir(root)
            .output()
            .ok()?;
        Command::new("git")
            .args(["commit", "-m", "c1"])
            .current_dir(root)
            .output()
            .ok()?;

        std::fs::write(root.join("main.rs"), "1\n2\n3\n4").ok()?;
        Command::new("git")
            .args(["add", "."])
            .current_dir(root)
            .output()
            .ok()?;
        Command::new("git")
            .args(["commit", "-m", "c2"])
            .current_dir(root)
            .output()
            .ok()?;

        // lib.rs: 1 commit (5 lines)
        std::fs::write(root.join("lib.rs"), "1\n2\n3\n4\n5").ok()?;
        Command::new("git")
            .args(["add", "."])
            .current_dir(root)
            .output()
            .ok()?;
        Command::new("git")
            .args(["commit", "-m", "c3"])
            .current_dir(root)
            .output()
            .ok()?;

        Some(dir)
    }

    #[test]
    fn test_compute_git_scores_commit_counts() {
        let repo = match create_test_repo() {
            Some(r) => r,
            None => return, // Skip if git unavailable
        };
        let rows = vec![make_row("main.rs", 4), make_row("lib.rs", 5)];
        let Some(scores) = compute_git_scores(repo.path(), &rows, 100, 100) else {
            return; // git unavailable in this environment
        };

        // main.rs has 2 commits, lib.rs has 1 commit
        assert_eq!(scores.commit_counts.get("main.rs"), Some(&2));
        assert_eq!(scores.commit_counts.get("lib.rs"), Some(&1));
    }

    #[test]
    fn test_compute_git_scores_hotspots() {
        let repo = match create_test_repo() {
            Some(r) => r,
            None => return,
        };
        let rows = vec![make_row("main.rs", 4), make_row("lib.rs", 5)];
        let Some(scores) = compute_git_scores(repo.path(), &rows, 100, 100) else {
            return;
        };

        // hotspot = lines * commits
        // main.rs: 4 lines * 2 commits = 8
        // lib.rs: 5 lines * 1 commit = 5
        assert_eq!(scores.hotspots.get("main.rs"), Some(&8));
        assert_eq!(scores.hotspots.get("lib.rs"), Some(&5));
    }

    #[test]
    fn test_compute_git_scores_filters_children() {
        let repo = match create_test_repo() {
            Some(r) => r,
            None => return,
        };
        // Only include child rows - should be filtered out
        let rows = vec![FileRow {
            path: "main.rs".to_string(),
            module: "(root)".to_string(),
            lang: "Rust".to_string(),
            kind: FileKind::Child, // Child, not Parent
            code: 4,
            comments: 0,
            blanks: 0,
            lines: 4,
            bytes: 40,
            tokens: 20,
        }];
        let scores = compute_git_scores(repo.path(), &rows, 100, 100);

        // Child rows should be filtered, so commit_counts should be empty
        // compute_git_scores may return None in some environments
        let Some(scores) = scores else { return };
        assert!(scores.commit_counts.is_empty());
    }

    #[test]
    fn test_compute_git_scores_non_repo_returns_none() {
        let dir = tempfile::tempdir().unwrap();
        let rows = vec![];
        // Not a git repo, should return None
        assert!(compute_git_scores(dir.path(), &rows, 100, 100).is_none());
    }

    #[test]
    fn test_normalize_path_backslash() {
        assert_eq!(normalize_path("foo\\bar\\baz.rs"), "foo/bar/baz.rs");
    }

    #[test]
    fn test_normalize_path_dot_slash() {
        assert_eq!(normalize_path("./src/main.rs"), "src/main.rs");
    }

    // ==================== Mutant killer tests ====================

    #[test]
    fn test_compute_git_scores_returns_some() {
        // Kills "compute_git_scores -> None" mutant
        let repo = match create_test_repo() {
            Some(r) => r,
            None => return,
        };
        let rows = vec![make_row("main.rs", 4)];
        let result = compute_git_scores(repo.path(), &rows, 100, 100);
        assert!(
            result.is_some(),
            "compute_git_scores should return Some for valid git repo"
        );
    }

    #[test]
    fn test_compute_git_scores_not_default() {
        // Kills "compute_git_scores -> Some(Default::default())" mutant
        let repo = match create_test_repo() {
            Some(r) => r,
            None => return,
        };
        let rows = vec![make_row("main.rs", 4), make_row("lib.rs", 5)];
        let Some(scores) = compute_git_scores(repo.path(), &rows, 100, 100) else {
            return;
        };

        // Scores should not be empty (kills Default::default() mutant)
        assert!(
            !scores.commit_counts.is_empty(),
            "commit_counts should not be empty"
        );
        assert!(!scores.hotspots.is_empty(), "hotspots should not be empty");
    }

    #[test]
    fn test_commit_count_increment() {
        // Kills "+= -> -=" mutant on commit counting
        // main.rs has 2 commits, so count must be > 0 (not negative from subtraction)
        let repo = match create_test_repo() {
            Some(r) => r,
            None => return,
        };
        let rows = vec![make_row("main.rs", 4)];
        let Some(scores) = compute_git_scores(repo.path(), &rows, 100, 100) else {
            return;
        };

        let count = scores.commit_counts.get("main.rs").copied().unwrap_or(0);
        assert!(count > 0, "commit count must be positive, got {count}");
        assert_eq!(count, 2, "main.rs should have exactly 2 commits");
    }

    #[test]
    fn test_hotspot_multiplication() {
        // Kills "lines * commits -> lines + commits" or "lines / commits" mutants
        let repo = match create_test_repo() {
            Some(r) => r,
            None => return,
        };
        // main.rs: 4 lines, 2 commits
        // If multiplication: 4 * 2 = 8
        // If addition: 4 + 2 = 6
        // If division: 4 / 2 = 2
        let rows = vec![make_row("main.rs", 4)];
        let Some(scores) = compute_git_scores(repo.path(), &rows, 100, 100) else {
            return;
        };

        let hotspot = scores.hotspots.get("main.rs").copied().unwrap_or(0);
        assert_eq!(
            hotspot, 8,
            "hotspot should be lines * commits = 4 * 2 = 8, got {hotspot}"
        );
    }

    #[test]
    fn test_normalize_path_not_empty() {
        // Kills "normalize_path -> empty string" mutant
        assert!(!normalize_path("foo/bar").is_empty());
        assert!(!normalize_path("test.rs").is_empty());
        assert!(!normalize_path("./src/lib.rs").is_empty());
    }

    #[test]
    fn test_normalize_path_not_xyzzy() {
        // Kills "normalize_path -> xyzzy" mutant
        assert_ne!(normalize_path("foo/bar"), "xyzzy");
        assert_ne!(normalize_path("test.rs"), "xyzzy");
        assert_ne!(normalize_path("./src/lib.rs"), "xyzzy");
    }

    #[test]
    fn test_filter_only_parent_files() {
        // Kills "== FileKind::Parent -> != FileKind::Parent" mutant
        let repo = match create_test_repo() {
            Some(r) => r,
            None => return,
        };
        // Mix of parent and child rows
        let rows = vec![
            make_row("main.rs", 4), // Parent
            FileRow {
                path: "lib.rs".to_string(),
                module: "(root)".to_string(),
                lang: "Rust".to_string(),
                kind: FileKind::Child, // Child - should be filtered
                code: 5,
                comments: 0,
                blanks: 0,
                lines: 5,
                bytes: 50,
                tokens: 25,
            },
        ];
        let scores = compute_git_scores(repo.path(), &rows, 100, 100);
        let Some(scores) = scores else { return };

        // Only main.rs (Parent) should appear
        assert!(scores.commit_counts.contains_key("main.rs"));
        assert!(
            !scores.commit_counts.contains_key("lib.rs"),
            "Child file lib.rs should be filtered out"
        );
    }

    #[test]
    fn test_path_matching_with_normalization() {
        // Tests that path normalization works for matching git paths to FileRow paths
        let repo = match create_test_repo() {
            Some(r) => r,
            None => return,
        };
        // Use backslash path (Windows-style) - should still match
        let rows = vec![FileRow {
            path: "main.rs".to_string(), // Forward slash
            module: "(root)".to_string(),
            lang: "Rust".to_string(),
            kind: FileKind::Parent,
            code: 4,
            comments: 0,
            blanks: 0,
            lines: 4,
            bytes: 40,
            tokens: 20,
        }];
        let Some(scores) = compute_git_scores(repo.path(), &rows, 100, 100) else {
            return;
        };

        // Should find the file despite potential path differences
        assert!(
            scores.commit_counts.contains_key("main.rs"),
            "Should match file after normalization"
        );
    }
}

#[cfg(test)]
mod tests_no_git {
    use super::*;

    #[test]
    fn test_git_scores_struct_default() {
        let scores = GitScores {
            hotspots: BTreeMap::new(),
            commit_counts: BTreeMap::new(),
        };
        assert!(scores.hotspots.is_empty());
        assert!(scores.commit_counts.is_empty());
    }

    #[test]
    fn test_git_scores_struct_with_data() {
        let mut hotspots = BTreeMap::new();
        hotspots.insert("src/main.rs".to_string(), 100);
        hotspots.insert("src/lib.rs".to_string(), 50);
        let mut commit_counts = BTreeMap::new();
        commit_counts.insert("src/main.rs".to_string(), 10);
        commit_counts.insert("src/lib.rs".to_string(), 5);

        let scores = GitScores {
            hotspots,
            commit_counts,
        };

        assert_eq!(scores.hotspots.len(), 2);
        assert_eq!(scores.commit_counts.get("src/main.rs"), Some(&10));
        assert_eq!(scores.hotspots.get("src/lib.rs"), Some(&50));
    }

    #[test]
    fn test_git_scores_btreemap_ordering() {
        let mut hotspots = BTreeMap::new();
        hotspots.insert("z.rs".to_string(), 1);
        hotspots.insert("a.rs".to_string(), 2);
        hotspots.insert("m.rs".to_string(), 3);

        let scores = GitScores {
            hotspots,
            commit_counts: BTreeMap::new(),
        };

        let keys: Vec<&String> = scores.hotspots.keys().collect();
        assert_eq!(keys, vec!["a.rs", "m.rs", "z.rs"]);
    }
}