hotspots-core 1.42.0

Core library for finding the riskiest code by combining complexity with git change history (Local Risk Score) across TypeScript, JavaScript, Go, Python, Rust, Java, C#, and C
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
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
//! Git context extraction
//!
//! Extracts git metadata for the current commit deterministically.
//!
//! Global invariants enforced:
//! - Commit hash is the sole identity
//! - Branch names are metadata only
//! - Missing parents produce baselines, not errors
//!
//! Uses git CLI directly (no libgit2) for portability.

use anyhow::{Context, Result};
use regex::Regex;
use std::path::Path;
use std::process::Command;
use std::sync::OnceLock;

static JIRA_RE: OnceLock<Regex> = OnceLock::new();
static GITHUB_RE: OnceLock<Regex> = OnceLock::new();

fn jira_re() -> &'static Regex {
    JIRA_RE.get_or_init(|| Regex::new(r"([A-Z]+-\d+)").unwrap())
}

fn github_re() -> &'static Regex {
    GITHUB_RE.get_or_init(|| Regex::new(r"(?:fixes|closes|fixed|closed)?\s*#(\d+)").unwrap())
}

/// Git context for the current commit
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GitContext {
    pub head_sha: String,
    pub parent_shas: Vec<String>,
    pub timestamp: i64,
    pub branch: Option<String>,
    pub is_detached: bool,
    pub message: Option<String>,
    pub author: Option<String>,
    pub is_fix_commit: Option<bool>,
    pub is_revert_commit: Option<bool>,
    pub ticket_ids: Vec<String>,
}

/// File churn metrics (lines added/deleted)
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FileChurn {
    pub file: String,
    pub lines_added: usize,
    pub lines_deleted: usize,
}

/// Batched touch metrics for all files in a repository.
///
/// Computed by two git log calls instead of one per file, reducing subprocess
/// overhead from O(files) to O(1).
#[derive(Debug, Clone)]
pub struct BatchedTouchMetrics {
    /// Number of commits touching each file in the 30-day window, keyed by relative path.
    pub touch_count_30d: std::collections::HashMap<String, usize>,
    /// Days since last change for each file, keyed by relative path.
    pub days_since_last_change: std::collections::HashMap<String, u32>,
}

/// Environment variables git uses to locate a repository, bypassing normal
/// cwd-based discovery entirely when set. If the calling process inherits
/// these (e.g. hotspots-core is invoked from within a git hook, where git
/// sets `GIT_DIR` for the hook subprocess), a bare `git` invocation silently
/// operates on whatever repo `GIT_DIR` points at instead of the caller's
/// intended cwd/path -- `current_dir()`/`-C` are ignored once `GIT_DIR` is
/// present. Every git invocation below clears these first so behavior is
/// determined solely by the explicit cwd/path this module was given.
const GIT_DISCOVERY_ENV_VARS: [&str; 3] = ["GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE"];

/// Execute a git command and return the trimmed stdout
fn git(args: &[&str]) -> Result<String> {
    let mut cmd = Command::new("git");
    for var in GIT_DISCOVERY_ENV_VARS {
        cmd.env_remove(var);
    }
    let output = cmd.args(args).output().context("failed to invoke git")?;

    if !output.status.success() {
        anyhow::bail!(
            "git {:?} failed: {}",
            args,
            String::from_utf8_lossy(&output.stderr)
        );
    }

    Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
}

/// Execute a git command in a specific directory and return the trimmed stdout
fn git_at(repo_path: &Path, args: &[&str]) -> Result<String> {
    let mut cmd = Command::new("git");
    for var in GIT_DISCOVERY_ENV_VARS {
        cmd.env_remove(var);
    }
    let output = cmd
        .current_dir(repo_path)
        .args(args)
        .output()
        .context("failed to invoke git")?;

    if !output.status.success() {
        anyhow::bail!(
            "git {:?} failed: {}",
            args,
            String::from_utf8_lossy(&output.stderr)
        );
    }

    Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
}

/// Extract git context for the current commit
///
/// Returns context including HEAD SHA, parent SHAs, timestamp, and branch name.
/// Handles detached HEAD (branch = None) and shallow clones gracefully.
///
/// # Errors
///
/// Returns error if:
/// - Not in a git repository
/// - Git commands fail for reasons other than shallow history
///
/// # Shallow Clone Handling
///
/// If parent SHAs cannot be resolved (shallow clone), this function warns
/// and continues. Missing parents are treated as baseline = true.
pub fn extract_git_context() -> Result<GitContext> {
    // Check if we're in a git repository
    // Use `rev-parse --git-dir` which returns non-zero exit code if not in a repo
    if git(&["rev-parse", "--git-dir"]).is_err() {
        anyhow::bail!("not in a git repository");
    }

    let head_sha = git(&["rev-parse", "HEAD"]).context("failed to extract HEAD SHA")?;

    // Extract parent SHAs
    // Use `rev-list --parents -n 1 HEAD` which outputs: HEAD_SHA PARENT1 PARENT2 ...
    let parents_raw = git(&["rev-list", "--parents", "-n", "1", "HEAD"])
        .context("failed to extract parent SHAs")?;

    // Parse parent SHAs (first token is HEAD, rest are parents)
    let mut parts = parents_raw.split_whitespace();
    let _ = parts.next(); // Skip HEAD SHA (we already have it)
    let parent_shas = parts.map(|s| s.to_string()).collect::<Vec<_>>();

    // Warn if no parents (shouldn't happen for normal commits, but handle gracefully)
    if parent_shas.is_empty() && head_sha != "4b825dc642cb6eb9a060e54bf8d69288fbee4904" {
        // The SHA above is git's empty tree, which is expected to have no parents
        // For other commits with no parents, this is likely an initial commit
        // which is valid, so we don't warn here
    }

    // Extract commit timestamp (%ct = Unix timestamp)
    let timestamp = git(&["show", "-s", "--format=%ct", "HEAD"])
        .context("failed to extract commit timestamp")?
        .parse::<i64>()
        .context("failed to parse commit timestamp")?;

    // Extract branch name (best effort, None if detached)
    let branch = git(&["symbolic-ref", "--short", "HEAD"]).ok();

    // Extract commit message and author
    let message = git(&["log", "-1", "--format=%B", "HEAD"]).ok();
    let author = git(&["log", "-1", "--format=%an", "HEAD"]).ok();

    // Detect fix and revert commits
    let is_fix_commit = message.as_ref().map(|m| detect_fix_commit(m));
    let is_revert_commit = message.as_ref().map(|m| detect_revert_commit(m));

    // Extract ticket IDs
    let ticket_ids = message
        .as_ref()
        .map(|m| extract_ticket_ids(m, branch.as_deref()))
        .unwrap_or_default();

    Ok(GitContext {
        head_sha,
        parent_shas,
        timestamp,
        is_detached: branch.is_none(),
        branch,
        message,
        author,
        is_fix_commit,
        is_revert_commit,
        ticket_ids,
    })
}

/// Extract git context for a specific repository path
///
/// This variant accepts a repository path instead of using the current working directory.
/// Useful for tests and scenarios where you don't want to change the process-wide directory.
///
/// # Arguments
///
/// * `repo_path` - Path to the git repository root
///
/// # Errors
///
/// Returns error if:
/// - Not in a git repository at the specified path
/// - Git commands fail for reasons other than shallow history
pub fn extract_git_context_at(repo_path: &Path) -> Result<GitContext> {
    // Check if we're in a git repository
    if git_at(repo_path, &["rev-parse", "--git-dir"]).is_err() {
        anyhow::bail!("not in a git repository at {}", repo_path.display());
    }

    let head_sha =
        git_at(repo_path, &["rev-parse", "HEAD"]).context("failed to extract HEAD SHA")?;

    // Extract parent SHAs
    let parents_raw = git_at(repo_path, &["rev-list", "--parents", "-n", "1", "HEAD"])
        .context("failed to extract parent SHAs")?;

    // Parse parent SHAs (first token is HEAD, rest are parents)
    let mut parts = parents_raw.split_whitespace();
    let _ = parts.next(); // Skip HEAD SHA (we already have it)
    let parent_shas = parts.map(|s| s.to_string()).collect::<Vec<_>>();

    // Extract commit timestamp (%ct = Unix timestamp)
    let timestamp = git_at(repo_path, &["show", "-s", "--format=%ct", "HEAD"])
        .context("failed to extract commit timestamp")?
        .parse::<i64>()
        .context("failed to parse commit timestamp")?;

    // Extract branch name (best effort, None if detached)
    let branch = git_at(repo_path, &["symbolic-ref", "--short", "HEAD"]).ok();

    // Extract commit message and author
    let message = git_at(repo_path, &["log", "-1", "--format=%B", "HEAD"]).ok();
    let author = git_at(repo_path, &["log", "-1", "--format=%an", "HEAD"]).ok();

    // Detect fix and revert commits
    let is_fix_commit = message.as_ref().map(|m| detect_fix_commit(m));
    let is_revert_commit = message.as_ref().map(|m| detect_revert_commit(m));

    // Extract ticket IDs
    let ticket_ids = message
        .as_ref()
        .map(|m| extract_ticket_ids(m, branch.as_deref()))
        .unwrap_or_default();

    Ok(GitContext {
        head_sha,
        parent_shas,
        timestamp,
        is_detached: branch.is_none(),
        branch,
        message,
        author,
        is_fix_commit,
        is_revert_commit,
        ticket_ids,
    })
}

/// PR context information
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PrContext {
    pub is_pr: bool,
    pub merge_base: Option<String>,
}

/// Detect if we're in a PR context via CI environment variables
///
/// Checks CI environment variables (GitHub: `GITHUB_EVENT_NAME`, `GITHUB_REF`).
/// Best-effort detection - returns `is_pr=false` if context is ambiguous.
/// Never hard-fails on ambiguous context.
pub fn detect_pr_context() -> PrContext {
    // Check GitHub Actions environment variables
    let github_event_name = std::env::var("GITHUB_EVENT_NAME").ok();
    let github_ref = std::env::var("GITHUB_REF").ok();

    // Check if this looks like a PR (pull_request event)
    let is_pr = match (&github_event_name, &github_ref) {
        (Some(event), Some(ref_name)) => {
            // GitHub PR events have event_name = "pull_request" and ref starts with "refs/pull/"
            event == "pull_request" || ref_name.starts_with("refs/pull/")
        }
        _ => false,
    };

    PrContext {
        is_pr,
        merge_base: None, // Will be computed later if needed
    }
}

/// Resolve merge-base between current HEAD and target branch
///
/// For PRs, this finds the common ancestor with the base branch.
/// Falls back to direct parent if merge-base cannot be resolved.
///
/// # Arguments
///
/// * `target_branch` - Target branch (e.g., "main", "master")
///
/// # Returns
///
/// Returns merge-base SHA, or None if merge-base fails (falls back to parent)
pub fn resolve_merge_base(target_branch: &str) -> Result<Option<String>> {
    // Try to get merge-base with target branch
    // git merge-base HEAD <target_branch>
    match git(&["merge-base", "HEAD", target_branch]) {
        Ok(sha) => Ok(Some(sha)),
        Err(_) => {
            // Merge-base failed - fall back to direct parent
            // This is acceptable (best-effort), so we just return None
            // The caller will use direct parent instead
            Ok(None)
        }
    }
}

/// Resolve merge-base with common target branches
///
/// Tries local and remote-tracking names (main, origin/main, master, …) so
/// this works both locally (where `main` is checked out) and in CI shallow
/// clones (where only `origin/main` exists as a remote-tracking ref).
pub fn resolve_merge_base_auto() -> Option<String> {
    let base_names = ["main", "master", "develop", "trunk"];

    for base in &base_names {
        if let Ok(Some(sha)) = resolve_merge_base(base) {
            return Some(sha);
        }
        // In CI (GitHub Actions), local branch refs don't exist; only
        // remote-tracking refs like origin/main are available.
        let remote = format!("origin/{base}");
        if let Ok(Some(sha)) = resolve_merge_base(&remote) {
            return Some(sha);
        }
    }

    None
}

/// Resolve a git ref (branch, tag, SHA, HEAD~N, etc.) to a full 40-character SHA.
///
/// Runs `git rev-parse <ref>` in the given repository root.
///
/// # Errors
///
/// Returns an error if the ref does not exist or git fails.
pub fn resolve_ref_to_sha(repo_root: &Path, git_ref: &str) -> Result<String> {
    git_at(repo_root, &["rev-parse", "--verify", git_ref])
        .with_context(|| format!("failed to resolve git ref '{git_ref}'"))
}

/// A temporary git worktree that is removed when dropped.
///
/// Created by [`create_worktree`]. The worktree directory is cleaned up via
/// `git worktree remove --force` on drop, so it is always removed even if the
/// caller returns an error mid-analysis.
pub struct TempWorktree {
    /// Absolute path to the worktree root.
    pub path: std::path::PathBuf,
    /// Repo root used to issue `git worktree remove`.
    repo_root: std::path::PathBuf,
}

impl Drop for TempWorktree {
    fn drop(&mut self) {
        let result = git_at(
            &self.repo_root,
            &[
                "worktree",
                "remove",
                "--force",
                &self.path.to_string_lossy(),
            ],
        );
        if let Err(e) = result {
            eprintln!(
                "warning: failed to remove temporary worktree {}: {e}",
                self.path.display()
            );
        }
    }
}

/// Create a temporary detached worktree at `sha` and return a drop guard.
///
/// The directory name includes the current process ID so concurrent hotspots
/// processes analyzing the same SHA use separate paths. Any stale directory
/// left by an interrupted previous run with the same PID is removed before
/// creating the new worktree. The worktree is automatically torn down when
/// the returned [`TempWorktree`] is dropped.
pub fn create_worktree(repo_root: &Path, sha: &str) -> Result<TempWorktree> {
    let dir = std::env::temp_dir().join(format!("hotspots-worktree-{sha}-{}", std::process::id()));

    // Always attempt to unregister any stale git worktree entry first.
    // A temp cleaner may have removed the directory while the .git/worktrees
    // metadata entry remains; `git worktree add` fails in that case even though
    // `dir.exists()` returns false.
    if let Err(e) = git_at(
        repo_root,
        &["worktree", "remove", "--force", &dir.to_string_lossy()],
    ) {
        // Not fatal — the entry simply may not exist yet.
        eprintln!(
            "warning: failed to remove existing git worktree at {}: {e}",
            dir.display()
        );
    }
    // Remove the directory itself if it is still present.
    if dir.exists() {
        std::fs::remove_dir_all(&dir).with_context(|| {
            format!(
                "failed to remove existing worktree directory {}; \
                 try removing it manually and re-run",
                dir.display()
            )
        })?;
    }

    git_at(
        repo_root,
        &["worktree", "add", "--detach", &dir.to_string_lossy(), sha],
    )
    .with_context(|| format!("failed to create worktree for {sha} at {}", dir.display()))?;
    Ok(TempWorktree {
        path: dir,
        repo_root: repo_root.to_path_buf(),
    })
}

/// Find the merge-base SHA and Unix timestamp between HEAD and main/master.
/// Returns None when already on main (merge-base == HEAD) or no divergence found.
pub fn find_merge_base(repo_root: &Path) -> Option<(String, i64)> {
    for branch in &["main", "master", "origin/HEAD"] {
        if let Ok(sha) = git_at(repo_root, &["merge-base", "HEAD", branch]) {
            let sha = sha.trim().to_string();
            if sha.is_empty() {
                continue;
            }
            if let Ok(head) = git_at(repo_root, &["rev-parse", "HEAD"]) {
                if head.trim() == sha {
                    return None; // already on main
                }
            }
            if let Ok(ts_str) = git_at(repo_root, &["log", "-1", "--format=%ct", &sha]) {
                if let Ok(ts) = ts_str.trim().parse::<i64>() {
                    return Some((sha, ts));
                }
            }
        }
    }
    None
}

/// Days since the last change to `file` at or before `before_sha`.
/// Returns None if the file has no history before that SHA.
pub fn days_since_last_change_at_sha(
    repo_root: &Path,
    file: &str,
    before_sha: &str,
    as_of_timestamp: i64,
) -> Option<u32> {
    git_at(
        repo_root,
        &["log", "-1", "--format=%ct", before_sha, "--", file],
    )
    .ok()
    .and_then(|out| out.trim().parse::<i64>().ok())
    .map(|ts| ((as_of_timestamp - ts).max(0) / 86400) as u32)
}

/// Extract commit churn (lines added/deleted per file)
///
/// Uses `git show --numstat <sha>` to get churn data for all files in the commit.
/// Binary files (shown as `-\t-\t<file>`) are skipped.
///
/// # Arguments
///
/// * `sha` - Commit SHA to analyze
///
/// # Returns
///
/// Returns vector of FileChurn entries, one per changed file.
/// Returns empty vector for:
/// - Initial commits (no parent)
/// - Merge commits (uses first parent only)
/// - Commits with no file changes
///
/// # Errors
///
/// Returns error if git command fails or output cannot be parsed
pub fn extract_commit_churn(sha: &str) -> Result<Vec<FileChurn>> {
    // Use git show --numstat to get lines added/deleted per file
    // Format: <added>\t<deleted>\t<file>
    // Binary files show: -\t-\t<file>
    let output = match git(&["show", "--numstat", "--format=", sha]) {
        Ok(out) => out,
        Err(_) => {
            // If git show fails (e.g., initial commit with no parent), return empty
            return Ok(Vec::new());
        }
    };

    let mut churns = Vec::new();
    for line in output.lines() {
        let line = line.trim();
        if line.is_empty() {
            continue;
        }

        let parts: Vec<&str> = line.split('\t').collect();
        if parts.len() < 3 {
            continue; // Invalid line, skip
        }

        let added_str = parts[0];
        let deleted_str = parts[1];
        let file = parts[2].to_string();

        // Skip binary files (shown as -)
        if added_str == "-" || deleted_str == "-" {
            continue;
        }

        // Parse numbers
        let lines_added = added_str
            .parse::<usize>()
            .with_context(|| format!("Failed to parse lines added: {}", added_str))?;
        let lines_deleted = deleted_str
            .parse::<usize>()
            .with_context(|| format!("Failed to parse lines deleted: {}", deleted_str))?;

        churns.push(FileChurn {
            file,
            lines_added,
            lines_deleted,
        });
    }

    Ok(churns)
}

/// Extract commit churn at a specific repository path
///
/// Like `extract_commit_churn`, but operates on a repository at a specific path.
///
/// # Arguments
///
/// * `repo_path` - Path to git repository
/// * `sha` - Commit SHA to analyze
///
/// # Returns
///
/// Returns vector of FileChurn entries for the commit
pub fn extract_commit_churn_at(repo_path: &Path, sha: &str) -> Result<Vec<FileChurn>> {
    let output = match git_at(repo_path, &["show", "--numstat", "--format=", sha]) {
        Ok(out) => out,
        Err(_) => {
            return Ok(Vec::new());
        }
    };

    let mut churns = Vec::new();
    for line in output.lines() {
        let line = line.trim();
        if line.is_empty() {
            continue;
        }

        let parts: Vec<&str> = line.split('\t').collect();
        if parts.len() < 3 {
            continue;
        }

        let added_str = parts[0];
        let deleted_str = parts[1];
        let file = parts[2].to_string();

        if added_str == "-" || deleted_str == "-" {
            continue;
        }

        let lines_added = added_str
            .parse::<usize>()
            .with_context(|| format!("Failed to parse lines added: {}", added_str))?;
        let lines_deleted = deleted_str
            .parse::<usize>()
            .with_context(|| format!("Failed to parse lines deleted: {}", deleted_str))?;

        churns.push(FileChurn {
            file,
            lines_added,
            lines_deleted,
        });
    }

    Ok(churns)
}

/// Per-file changed-line numbers from a unified diff, split by old-file (deleted/context-shifted
/// lines) and new-file (added lines) line numbers. Keyed by the file's path as it appears in the
/// diff header (`b/<path>` for the new side, used as the map key; `--- /dev/null` new-file adds
/// and `+++ /dev/null` deletes are handled via whichever side has a real path).
#[derive(Debug, Default)]
pub struct DiffLineSet {
    pub old_lines: std::collections::BTreeSet<u32>,
    pub new_lines: std::collections::BTreeSet<u32>,
}

/// Parse `git diff -U0 base..head`'s hunk headers (`@@ -oldStart[,oldCount] +newStart[,newCount] @@`)
/// into per-file changed-line sets, old and new file line numbers kept separate.
///
/// `-U0` (zero context lines) means every line in a hunk's old/new range is an actual
/// addition/deletion, not surrounding context — exactly the "changed lines" this needs, with no
/// extra filtering required.
pub fn diff_line_sets_at(
    repo_path: &Path,
    base_sha: &str,
    head_sha: &str,
) -> Result<std::collections::HashMap<String, DiffLineSet>> {
    let range = format!("{base_sha}..{head_sha}");
    let output = match git_at(repo_path, &["diff", "-U0", "--no-color", &range]) {
        Ok(out) => out,
        Err(_) => return Ok(std::collections::HashMap::new()),
    };

    let mut result: std::collections::HashMap<String, DiffLineSet> =
        std::collections::HashMap::new();
    let mut current_file: Option<String> = None;

    for line in output.lines() {
        if let Some(path) = line.strip_prefix("+++ b/") {
            current_file = Some(path.to_string());
        } else if let Some(path) = line.strip_prefix("+++ ") {
            // "+++ /dev/null" (pure deletion) — keep the old-side path from the preceding "--- a/..."
            if path == "/dev/null" {
                // current_file already set from "--- a/<path>" handling below; leave as-is
            }
        } else if let Some(path) = line.strip_prefix("--- a/") {
            // Only used when the file is later deleted entirely (no "+++ b/..." line follows);
            // "+++ b/..." above takes precedence when both are present (the common case).
            current_file.get_or_insert_with(|| path.to_string());
        } else if let Some(hunk) = line.strip_prefix("@@ ") {
            let Some(file) = current_file.clone() else {
                continue;
            };
            if let Some((old_range, new_range)) = parse_hunk_header(hunk) {
                let entry = result.entry(file).or_default();
                entry.old_lines.extend(old_range);
                entry.new_lines.extend(new_range);
            }
        } else if line.starts_with("diff --git ") {
            current_file = None; // reset between files; next --- / +++ lines set it again
        }
    }

    Ok(result)
}

/// Parses one hunk header's body (everything after `"@@ "`, e.g. `"-12,3 +12,5 @@ fn foo() {"`)
/// into (old_line_numbers, new_line_numbers). A missing count (`-12` with no `,count`) means 1.
/// A count of 0 (pure add/delete at that side) contributes no lines on that side.
fn parse_hunk_header(hunk: &str) -> Option<(Vec<u32>, Vec<u32>)> {
    let end = hunk.find(" @@")?;
    let ranges = &hunk[..end];
    let mut parts = ranges.split_whitespace();
    let old = parts.next()?.strip_prefix('-')?;
    let new = parts.next()?.strip_prefix('+')?;

    let parse_range = |s: &str| -> Option<Vec<u32>> {
        let mut it = s.splitn(2, ',');
        let start: u32 = it.next()?.parse().ok()?;
        let count: u32 = match it.next() {
            Some(c) => c.parse().ok()?,
            None => 1,
        };
        Some((start..start + count).collect())
    };

    Some((parse_range(old)?, parse_range(new)?))
}

/// `fn_changed_lines` (hotspots-research F132/F159/F161): the number of diff-changed lines that
/// fall inside a function touched by this PR — restricted to functions, not the whole file
/// (tests/docs/config changes elsewhere in the same file don't count). The confirmed strongest
/// tested predictor of which PRs later need a defect fix in this corpus: it beat every
/// LRS-weighted composite tried, including `pr_risk_score` itself (F161: 0 of 20 tested variants
/// beat this size-matched baseline).
///
/// For each New/Modified function, counts new-file changed lines inside its `[line, line+loc-1]`
/// span (using the head snapshot's line numbers, since that's the version those lines exist in).
/// For each Deleted function, counts old-file changed lines inside its base-snapshot span. This
/// mirrors the research's own method (F161: "restricted to functions overlapping a changed
/// hunk") using whichever side of the diff a function's lines actually exist on, avoiding
/// double-counting between the old/new line sets for the same function.
///
/// Function spans are estimated as `[line, line + loc - 1]`, the same approximation F161's own
/// Limitations section names ("the CLI gives start line and `loc`, not end line") — this can
/// overshoot on functions with trailing blank lines or undershoot on ones the parser measures
/// `loc` for differently than raw line count, but it's the same measure `hotspots analyze`
/// already reports, not a new approximation invented for this feature.
pub fn compute_fn_changed_lines(
    repo_root: &Path,
    deltas: &[crate::delta::FunctionDeltaEntry],
    head_snapshot: &crate::snapshot::Snapshot,
    base_snapshot: &crate::snapshot::Snapshot,
    diff_lines: &std::collections::HashMap<String, DiffLineSet>,
) -> usize {
    use crate::delta::FunctionStatus;
    use std::collections::HashMap;

    // FunctionSnapshot.file is absolute; diff_lines is keyed by the repo-relative path git
    // diff prints (`+++ b/<path>`). Same abs->rel conversion this crate already uses
    // elsewhere (e.g. snapshot.rs's touch-metrics file matching) — without it every lookup
    // below misses and this silently returns 0 (caught live via this feature's own dogfood
    // test on this repo: a 9-function, 400+ line PR reported fn_changed_lines=0).
    let rel = |abs: &str| -> String {
        Path::new(abs)
            .strip_prefix(repo_root)
            .map(|r| r.to_string_lossy().replace('\\', "/"))
            .unwrap_or_else(|_| abs.to_string())
    };

    let head_by_id: HashMap<&str, &crate::snapshot::FunctionSnapshot> = head_snapshot
        .functions
        .iter()
        .map(|f| (f.function_id.as_str(), f))
        .collect();
    let base_by_id: HashMap<&str, &crate::snapshot::FunctionSnapshot> = base_snapshot
        .functions
        .iter()
        .map(|f| (f.function_id.as_str(), f))
        .collect();

    let mut total = 0usize;
    for entry in deltas {
        let (snapshot_func, side_lines) = match entry.status {
            FunctionStatus::New | FunctionStatus::Modified => {
                let func = head_by_id.get(entry.function_id.as_str());
                let lines = func
                    .and_then(|f| diff_lines.get(&rel(&f.file)))
                    .map(|d| &d.new_lines);
                (func, lines)
            }
            FunctionStatus::Deleted => {
                let func = base_by_id.get(entry.function_id.as_str());
                let lines = func
                    .and_then(|f| diff_lines.get(&rel(&f.file)))
                    .map(|d| &d.old_lines);
                (func, lines)
            }
            FunctionStatus::Unchanged => continue,
        };
        let (Some(func), Some(lines)) = (snapshot_func, side_lines) else {
            continue;
        };
        let start = func.line;
        let end = start + func.metrics.loc.saturating_sub(1);
        total += lines.range(start..=end).count();
    }
    total
}

/// The touch window, in days, for `batch_touch_metrics_at`'s `touch_count_30d` /
/// `days_since_last_change` pair.
///
/// Widened from 30 to 365 per hotspots-research F165 (confirmed, pre-registered,
/// 13-repo cutoff-safe gate): substituting a 365-day window for the 30-day one raised
/// mean rho by +0.029 and mean P@10% by +0.015 with both bootstrap CI lower bounds
/// positive, monotonically across the whole tested grid with no peak — and a paired
/// size-confound check (partial correlation controlling for loc) found the gain is
/// not just "counting more commits." The `touch_count_30d` field/struct names are kept
/// as-is for JSON/schema compatibility with existing consumers (dashboards, `--compare`,
/// hotspots-cloud) even though they now measure a 365-day window — see F165's own note
/// that this cost was not separately measured (the git walk here is still one process
/// call, just scanning a wider `--since` range).
pub const TOUCH_WINDOW_DAYS: i64 = 365;

/// Compute touch metrics for all files in a repository using two git log calls.
///
/// Replaces the previous O(files) approach (one subprocess per file) with two
/// batched calls, reducing overhead from ~7.5 ms × N to ~40 ms total.
///
/// # Algorithm
///
/// Call 1: `git log --format="COMMIT %ct" --name-only --since=X --until=Y`
///   → builds `touch_count_30d` (a `TOUCH_WINDOW_DAYS`-wide window, see its doc
///   comment) and finds last-change timestamp for files in window.
///
/// Call 2 (fallback): for any file not seen in call 1, a single `git log -1 --format=%ct`
///   call per file (typically very few files; most active files appear in the window).
pub fn batch_touch_metrics_at(
    repo_root: &Path,
    as_of_timestamp: i64,
    window_days: u32,
) -> Result<BatchedTouchMetrics> {
    use std::collections::HashMap;

    let thirty_days_ago = as_of_timestamp - (window_days as i64 * 24 * 60 * 60);
    let since_arg = format!("--since={}", thirty_days_ago);
    let until_arg = format!("--until={}", as_of_timestamp);

    // Call 1: all commits in the 30-day window
    let window_output = git_at(
        repo_root,
        &[
            "log",
            "--format=COMMIT %ct",
            "--name-only",
            &since_arg,
            &until_arg,
        ],
    )
    .unwrap_or_default();

    let mut touch_count: HashMap<String, usize> = HashMap::new();
    let mut last_touch_ts: HashMap<String, i64> = HashMap::new();
    let mut current_ts: i64 = 0;

    for line in window_output.lines() {
        if let Some(ts_str) = line.strip_prefix("COMMIT ") {
            current_ts = ts_str.trim().parse().unwrap_or(0);
        } else if !line.trim().is_empty() {
            let file = line.trim().to_string();
            *touch_count.entry(file.clone()).or_insert(0) += 1;
            // First occurrence = most recent (git log is newest-first)
            last_touch_ts.entry(file).or_insert(current_ts);
        }
    }

    // Build days_since map from what we have so far
    let days_since: HashMap<String, u32> = last_touch_ts
        .iter()
        .map(|(file, &ts)| {
            let days = ((as_of_timestamp - ts).max(0) / (24 * 60 * 60)) as u32;
            (file.clone(), days)
        })
        .collect();

    Ok(BatchedTouchMetrics {
        touch_count_30d: touch_count,
        days_since_last_change: days_since,
    })
}

/// For files absent from the 30-day window, find the most recent commit timestamp
/// for each using a single unrestricted `git log --name-only` walk.
///
/// This replaces one full-history, path-limited `git log -- <500 paths>` per 500
/// files: each of those walked the entire history, so cost grew with history length
/// times stale files / 500 (minutes on large repos). One walk with no pathspec
/// resolves every file at once. It also sees commits that reached a file through a
/// merged side branch, which path-limited history simplification can prune, so a
/// value is never older than the old method's and is occasionally more recent.
pub fn batch_last_touch_for_files(
    repo_path: &Path,
    stale_files: &std::collections::HashSet<&str>,
    as_of_timestamp: i64,
) -> std::collections::HashMap<String, u32> {
    use std::collections::HashMap;
    if stale_files.is_empty() {
        return HashMap::new();
    }

    let until_arg = format!("--until={}", as_of_timestamp);
    let output = match git_at(
        repo_path,
        &["log", "--format=COMMIT %ct", "--name-only", &until_arg],
    ) {
        Ok(o) => o,
        Err(_) => return HashMap::new(),
    };

    let mut result: HashMap<String, u32> = HashMap::new();
    let mut current_ts: i64 = 0;
    for line in output.lines() {
        if let Some(ts_str) = line.strip_prefix("COMMIT ") {
            current_ts = ts_str.trim().parse().unwrap_or(0);
        } else if current_ts > 0 && !line.trim().is_empty() {
            let file = line.trim();
            if stale_files.contains(file) {
                // entry() only inserts on first (= most recent) occurrence
                result.entry(file.to_string()).or_insert_with(|| {
                    ((as_of_timestamp - current_ts).max(0) / (24 * 60 * 60)) as u32
                });
                if result.len() == stale_files.len() {
                    break;
                }
            }
        }
    }

    result
}

/// Per-function touch metrics using `git log -L start,end:file`.
///
/// Returns `(touch_count_30d, days_since_last_change)` for the specific line range.
/// More accurate than file-level metrics but ~50× slower per function.
///
/// # Arguments
///
/// * `repo_path` - Path to git repository
/// * `file` - Relative path to file from repository root
/// * `start_line` - First line of function (1-based)
/// * `end_line` - Last line of function (1-based)
/// * `as_of_timestamp` - Unix timestamp to use as "now"
pub fn function_touch_metrics_at(
    repo_path: &Path,
    file: &str,
    start_line: u32,
    end_line: u32,
    as_of_timestamp: i64,
) -> Result<(usize, Option<u32>)> {
    let thirty_days_ago = as_of_timestamp - (30 * 24 * 60 * 60);
    let since_arg = format!("--since={}", thirty_days_ago);
    let until_arg = format!("--until={}", as_of_timestamp);
    let range_arg = format!("-L{},{}:{}", start_line, end_line, file);

    // Count touches in 30-day window; filter diff output by looking for "COMMIT <ts>" markers
    let window_output = git_at(
        repo_path,
        &[
            "log",
            &range_arg,
            "--format=COMMIT %ct",
            &since_arg,
            &until_arg,
        ],
    )
    .unwrap_or_default();

    let window_timestamps: Vec<i64> = window_output
        .lines()
        .filter_map(|l| l.strip_prefix("COMMIT "))
        .filter_map(|ts| ts.trim().parse::<i64>().ok())
        .collect();

    let touch_count = window_timestamps.len();

    let days_since = if let Some(&ts) = window_timestamps.first() {
        Some(((as_of_timestamp - ts).max(0) / (24 * 60 * 60)) as u32)
    } else {
        // Not in 30-day window: find most recent commit touching this range
        let recent_until = format!("--until={}", as_of_timestamp);
        let recent_output = git_at(
            repo_path,
            &[
                "log",
                &range_arg,
                "--format=COMMIT %ct",
                "-1",
                &recent_until,
            ],
        )
        .unwrap_or_default();

        recent_output
            .lines()
            .filter_map(|l| l.strip_prefix("COMMIT "))
            .filter_map(|ts| ts.trim().parse::<i64>().ok())
            .next()
            .map(|ts| ((as_of_timestamp - ts).max(0) / (24 * 60 * 60)) as u32)
    };

    Ok((touch_count, days_since))
}

/// Count how many commits touched a file in the last 30 days
///
/// Counts commits relative to a specific timestamp (typically the commit timestamp),
/// not wall clock time. This allows deterministic analysis of historical commits.
///
/// Returns count of commits in the 30 days before `as_of_timestamp`, or 0 if none.
pub fn count_file_touches_30d(file: &str, as_of_timestamp: i64) -> Result<usize> {
    // Calculate 30 days before the reference timestamp
    let thirty_days_ago = as_of_timestamp - (30 * 24 * 60 * 60);

    // Use git log with --since and --until to get commits in the window
    // Format: --since=<timestamp> --until=<timestamp>
    let since_arg = format!("--since={}", thirty_days_ago);
    let until_arg = format!("--until={}", as_of_timestamp);

    let output = match git(&["log", &since_arg, &until_arg, "--oneline", "--", file]) {
        Ok(out) => out,
        Err(_) => {
            // File doesn't exist or no commits in window
            return Ok(0);
        }
    };

    // Count non-empty lines
    let count = output
        .lines()
        .filter(|line| !line.trim().is_empty())
        .count();
    Ok(count)
}

/// Count file touches at a specific repository path
pub fn count_file_touches_30d_at(
    repo_path: &Path,
    file: &str,
    as_of_timestamp: i64,
) -> Result<usize> {
    let thirty_days_ago = as_of_timestamp - (30 * 24 * 60 * 60);
    let since_arg = format!("--since={}", thirty_days_ago);
    let until_arg = format!("--until={}", as_of_timestamp);

    let output = match git_at(
        repo_path,
        &["log", &since_arg, &until_arg, "--oneline", "--", file],
    ) {
        Ok(out) => out,
        Err(_) => {
            return Ok(0);
        }
    };

    let count = output
        .lines()
        .filter(|line| !line.trim().is_empty())
        .count();
    Ok(count)
}

/// Calculate days since last change to a file
///
/// Returns number of days between the file's last modification and the reference timestamp.
///
/// # Arguments
///
/// * `file` - Relative path to file from repository root
/// * `as_of_timestamp` - Unix timestamp to use as "now" (typically commit timestamp)
///
/// # Returns
///
/// Returns days since last change, or 0 if file was just modified.
/// Returns 0 if file doesn't exist or has no history.
pub fn days_since_last_change(file: &str, as_of_timestamp: i64) -> Result<u32> {
    // Get the timestamp of the most recent commit that modified this file
    // Use: git log -1 --format=%ct -- <file>
    let output = match git(&["log", "-1", "--format=%ct", "--", file]) {
        Ok(out) => out,
        Err(_) => {
            // File doesn't exist or has no history
            return Ok(0);
        }
    };

    let last_change_timestamp = output
        .trim()
        .parse::<i64>()
        .context("failed to parse last change timestamp")?;

    // Calculate days difference
    let seconds_diff = as_of_timestamp - last_change_timestamp;
    let days = (seconds_diff / (24 * 60 * 60)).max(0) as u32;

    Ok(days)
}

/// Calculate days since last change at a specific repository path
pub fn days_since_last_change_at(
    repo_path: &Path,
    file: &str,
    as_of_timestamp: i64,
) -> Result<u32> {
    let output = match git_at(repo_path, &["log", "-1", "--format=%ct", "--", file]) {
        Ok(out) => out,
        Err(_) => {
            return Ok(0);
        }
    };

    let last_change_timestamp = output
        .trim()
        .parse::<i64>()
        .context("failed to parse last change timestamp")?;

    let seconds_diff = as_of_timestamp - last_change_timestamp;
    let days = (seconds_diff / (24 * 60 * 60)).max(0) as u32;

    Ok(days)
}

/// Detect if a commit message indicates a fix/bug fix
///
/// Looks for common keywords: "fix", "bug", "hotfix", "bugfix", etc.
pub fn detect_fix_commit(message: &str) -> bool {
    let lower = message.to_lowercase();
    lower.contains("fix")
        || lower.contains("bug")
        || lower.contains("hotfix")
        || lower.contains("bugfix")
}

/// Detect if a commit is a revert
///
/// Looks for "revert" keyword in the message
pub fn detect_revert_commit(message: &str) -> bool {
    let lower = message.to_lowercase();
    lower.contains("revert")
}

/// Extract ticket IDs from commit message and branch name
///
/// Supports formats:
/// - JIRA-1234
/// - ABC-123
/// - #123
/// - fixes #123
/// - closes #123
pub fn extract_ticket_ids(message: &str, branch: Option<&str>) -> Vec<String> {
    let mut tickets = Vec::new();

    // Pattern for JIRA-style tickets: PROJECT-123
    for cap in jira_re().captures_iter(message) {
        if let Some(ticket) = cap.get(1) {
            let ticket_str = ticket.as_str().to_string();
            if !tickets.contains(&ticket_str) {
                tickets.push(ticket_str);
            }
        }
    }

    // Pattern for GitHub issues: #123, fixes #123, closes #123
    for cap in github_re().captures_iter(message) {
        if let Some(number) = cap.get(1) {
            let ticket_str = format!("#{}", number.as_str());
            if !tickets.contains(&ticket_str) {
                tickets.push(ticket_str);
            }
        }
    }

    // Also extract from branch name if provided
    if let Some(branch_name) = branch {
        for cap in jira_re().captures_iter(branch_name) {
            if let Some(ticket) = cap.get(1) {
                let ticket_str = ticket.as_str().to_string();
                if !tickets.contains(&ticket_str) {
                    tickets.push(ticket_str);
                }
            }
        }

        for cap in github_re().captures_iter(branch_name) {
            if let Some(number) = cap.get(1) {
                let ticket_str = format!("#{}", number.as_str());
                if !tickets.contains(&ticket_str) {
                    tickets.push(ticket_str);
                }
            }
        }
    }

    tickets
}

/// A pair of files that frequently change together in the same commit
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct CoChangePair {
    pub file_a: String,
    pub file_b: String,
    /// Number of commits where both files changed
    pub co_change_count: usize,
    /// co_change_count / min(total_changes_a, total_changes_b)
    pub coupling_ratio: f64,
    /// "high" if ratio > 0.5 and no static dep, "moderate" if > 0.25 and no static dep,
    /// "expected" if a direct import exists between the two files, else "low"
    pub risk: String,
    /// Whether a direct import relationship exists between file_a and file_b
    pub has_static_dep: bool,
}

/// Returns true for pairs that are trivially expected to co-change (test+source,
/// mod.rs+sibling) and should be excluded from coupling analysis.
fn is_trivial_pair(file_a: &str, file_b: &str) -> bool {
    // foo.rs + foo_test.rs or foo_tests.rs (same dir, same stem)
    let dir_a = std::path::Path::new(file_a)
        .parent()
        .unwrap_or(std::path::Path::new(""));
    let dir_b = std::path::Path::new(file_b)
        .parent()
        .unwrap_or(std::path::Path::new(""));
    let stem_a = std::path::Path::new(file_a)
        .file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or("");
    let stem_b = std::path::Path::new(file_b)
        .file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or("");

    if dir_a == dir_b {
        // Test file paired with its source: foo + foo_test or foo_tests
        if stem_b == format!("{}_test", stem_a) || stem_b == format!("{}_tests", stem_a) {
            return true;
        }
        if stem_a == format!("{}_test", stem_b) || stem_a == format!("{}_tests", stem_b) {
            return true;
        }
        // mod.rs paired with any sibling in the same directory
        if stem_a == "mod" || stem_b == "mod" {
            return true;
        }
    }
    false
}

/// Mine co-change pairs from git log over the last `window_days` days.
///
/// Returns pairs that co-changed at least `min_count` times, ranked by
/// coupling_ratio descending. Pairs where both files are the same are excluded.
pub fn extract_co_change_pairs(
    repo_root: &Path,
    window_days: u64,
    min_count: usize,
) -> Result<Vec<CoChangePair>> {
    let since = format!("{} days ago", window_days);
    let output = git_at(
        repo_root,
        &[
            "log",
            "--name-only",
            "--format=COMMIT:%H",
            &format!("--since={}", since),
            "--diff-filter=AM",
        ],
    )
    .unwrap_or_default();

    // Parse into per-commit file sets
    let mut commit_files: Vec<Vec<String>> = Vec::new();
    let mut current: Vec<String> = Vec::new();
    for line in output.lines() {
        if line.starts_with("COMMIT:") {
            if !current.is_empty() {
                commit_files.push(std::mem::take(&mut current));
            }
        } else if !line.trim().is_empty() {
            current.push(line.trim().to_string());
        }
    }
    if !current.is_empty() {
        commit_files.push(current);
    }

    // Count per-file total appearances and per-pair co-occurrences
    let mut file_counts: std::collections::HashMap<String, usize> =
        std::collections::HashMap::new();
    let mut pair_counts: std::collections::HashMap<(String, String), usize> =
        std::collections::HashMap::new();

    // Skip commits that touch more than this many files — they are mass-change
    // commits (version bumps, renames, reformats) that produce O(n²) pairs and
    // dominate memory without adding meaningful co-change signal.
    const MAX_FILES_PER_COMMIT: usize = 200;

    for files in &commit_files {
        for f in files {
            *file_counts.entry(f.clone()).or_insert(0) += 1;
        }
        if files.len() > MAX_FILES_PER_COMMIT {
            continue;
        }
        // All unique pairs in this commit
        let mut sorted = files.clone();
        sorted.sort();
        sorted.dedup();
        for i in 0..sorted.len() {
            for j in (i + 1)..sorted.len() {
                let key = (sorted[i].clone(), sorted[j].clone());
                *pair_counts.entry(key).or_insert(0) += 1;
            }
        }
    }

    let mut pairs: Vec<CoChangePair> = pair_counts
        .into_iter()
        .filter(|(_, count)| *count >= min_count)
        .filter(|((file_a, file_b), _)| {
            // Skip pairs where either file no longer exists (e.g. renamed/deleted files)
            repo_root.join(file_a).exists() && repo_root.join(file_b).exists()
        })
        .filter(|((file_a, file_b), _)| !is_trivial_pair(file_a, file_b))
        .map(|((file_a, file_b), co_change_count)| {
            let count_a = file_counts.get(&file_a).copied().unwrap_or(1);
            let count_b = file_counts.get(&file_b).copied().unwrap_or(1);
            let coupling_ratio = co_change_count as f64 / count_a.min(count_b) as f64;
            let risk = if coupling_ratio > 0.5 {
                "high".to_string()
            } else if coupling_ratio > 0.25 {
                "moderate".to_string()
            } else {
                "low".to_string()
            };
            CoChangePair {
                file_a,
                file_b,
                co_change_count,
                coupling_ratio: (coupling_ratio * 1000.0).round() / 1000.0,
                risk,
                has_static_dep: false, // annotated later in compute_snapshot_aggregates
            }
        })
        .collect();

    pairs.sort_by(|a, b| {
        b.coupling_ratio
            .partial_cmp(&a.coupling_ratio)
            .unwrap_or(std::cmp::Ordering::Equal)
            .then(a.file_a.cmp(&b.file_a))
            .then(a.file_b.cmp(&b.file_b))
    });

    Ok(pairs)
}

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

    // ── parse_hunk_header ────────────────────────────────────────────────────

    #[test]
    fn hunk_header_both_sides_with_counts() {
        let (old, new) = parse_hunk_header("-12,3 +12,5 @@ fn foo() {").unwrap();
        assert_eq!(old, vec![12, 13, 14]);
        assert_eq!(new, vec![12, 13, 14, 15, 16]);
    }

    #[test]
    fn hunk_header_missing_count_means_one() {
        // "-12 +12" (no ",count") is git's shorthand for a single-line hunk.
        let (old, new) = parse_hunk_header("-12 +14 @@").unwrap();
        assert_eq!(old, vec![12]);
        assert_eq!(new, vec![14]);
    }

    #[test]
    fn hunk_header_zero_count_is_pure_add_or_delete() {
        // Pure addition: old side has 0 lines (insertion point only).
        let (old, new) = parse_hunk_header("-5,0 +6,3 @@").unwrap();
        assert_eq!(old, Vec::<u32>::new());
        assert_eq!(new, vec![6, 7, 8]);
    }

    #[test]
    fn hunk_header_malformed_returns_none() {
        assert!(parse_hunk_header("not a hunk header").is_none());
        assert!(parse_hunk_header("-12,3 @@").is_none()); // missing new side
    }

    // ── diff_line_sets_at (hunk parsing over a real unified diff) ───────────

    #[test]
    fn diff_line_sets_parses_multi_file_multi_hunk_output() {
        // A hand-written unified diff (-U0 shape) covering two files, to test the
        // line-level parser without needing a real git repo.
        let diff = "\
diff --git a/src/a.rs b/src/a.rs
index 1111111..2222222 100644
--- a/src/a.rs
+++ b/src/a.rs
@@ -10,2 +10,1 @@ fn a() {
-old line 1
-old line 2
+new line 1
@@ -20,0 +19,2 @@ fn b() {
+added line 1
+added line 2
diff --git a/src/c.rs b/src/c.rs
index 3333333..4444444 100644
--- a/src/c.rs
+++ b/src/c.rs
@@ -5,1 +5,0 @@ fn c() {
-removed line
";
        let sets = parse_diff_output_for_test(diff);

        let a = sets.get("src/a.rs").expect("src/a.rs present");
        // Second hunk (@@ -20,0 +19,2 @@) has a zero-count old side (pure insertion) — 20
        // correctly does not appear in old_lines.
        assert_eq!(a.old_lines, [10, 11].into_iter().collect());
        assert_eq!(a.new_lines, [10, 19, 20].into_iter().collect());

        let c = sets.get("src/c.rs").expect("src/c.rs present");
        assert_eq!(c.old_lines, [5].into_iter().collect());
        assert_eq!(c.new_lines, Default::default());
    }

    /// Test-only helper: runs `diff_line_sets_at`'s parsing logic over a literal diff string
    /// instead of shelling out to git, by duplicating just the line-loop (kept in sync by the
    /// test above exercising the same hunk-header format `diff_line_sets_at` parses from git).
    fn parse_diff_output_for_test(output: &str) -> std::collections::HashMap<String, DiffLineSet> {
        let mut result: std::collections::HashMap<String, DiffLineSet> =
            std::collections::HashMap::new();
        let mut current_file: Option<String> = None;
        for line in output.lines() {
            if let Some(path) = line.strip_prefix("+++ b/") {
                current_file = Some(path.to_string());
            } else if let Some(path) = line.strip_prefix("--- a/") {
                current_file.get_or_insert_with(|| path.to_string());
            } else if let Some(hunk) = line.strip_prefix("@@ ") {
                let Some(file) = current_file.clone() else {
                    continue;
                };
                if let Some((old_range, new_range)) = parse_hunk_header(hunk) {
                    let entry = result.entry(file).or_default();
                    entry.old_lines.extend(old_range);
                    entry.new_lines.extend(new_range);
                }
            } else if line.starts_with("diff --git ") {
                current_file = None;
            }
        }
        result
    }

    // ── compute_fn_changed_lines ─────────────────────────────────────────────

    fn make_fn_snapshot(
        id: &str,
        file: &str,
        line: u32,
        loc: u32,
    ) -> crate::snapshot::FunctionSnapshot {
        crate::snapshot::FunctionSnapshot {
            function_id: id.to_string(),
            file: file.to_string(),
            line,
            language: crate::language::Language::Rust,
            metrics: crate::report::MetricsReport {
                cc: 1,
                nd: 0,
                fo: 0,
                ns: 0,
                loc,
            },
            lrs: 1.0,
            band: crate::risk::RiskBand::Low,
            suppression_reason: None,
            churn: None,
            touch_count_30d: None,
            days_since_last_change: None,
            callgraph: None,
            activity_risk: None,
            risk_factors: None,
            percentile: None,
            driver: None,
            driver_detail: None,
            quadrant: None,
            patterns: vec![],
            pattern_details: None,
            subsystem: None,
            authors_90d: None,
            directed_coupling: None,
            jaccard_label_stability: None,
            convention_bug_fix_count: None,
            burst_score: None,
            commit_count: None,
            author_count: None,
            author_entropy: None,
            isolation_rate: None,
            age_days: None,
            last_touch_days: None,
            newcomer_rate: None,
            explanation: None,
        }
    }

    fn make_snapshot(
        functions: Vec<crate::snapshot::FunctionSnapshot>,
    ) -> crate::snapshot::Snapshot {
        crate::snapshot::Snapshot {
            schema_version: 1,
            commit: crate::snapshot::CommitInfo {
                sha: "head".to_string(),
                parents: vec!["base".to_string()],
                timestamp: 0,
                branch: None,
                message: None,
                author: None,
                is_fix_commit: None,
                is_revert_commit: None,
                ticket_ids: vec![],
            },
            analysis: crate::snapshot::AnalysisInfo {
                scope: "full".to_string(),
                tool_version: "test".to_string(),
                formula_version: 1,
            },
            functions,
            summary: None,
            aggregates: None,
        }
    }

    fn make_delta_entry(
        id: &str,
        status: crate::delta::FunctionStatus,
    ) -> crate::delta::FunctionDeltaEntry {
        crate::delta::FunctionDeltaEntry {
            function_id: id.to_string(),
            status,
            before: None,
            after: None,
            delta: None,
            band_transition: None,
            suppression_reason: None,
            rename_hint: None,
        }
    }

    #[test]
    fn fn_changed_lines_counts_new_function_lines_from_new_side() {
        // Function spans lines 10..=14 (line=10, loc=5) in the head snapshot; new-side diff
        // touched lines 12 and 20 — only 12 falls inside the span.
        let head = make_snapshot(vec![make_fn_snapshot("f.rs::foo", "f.rs", 10, 5)]);
        let base = make_snapshot(vec![]);
        let mut diff_lines = std::collections::HashMap::new();
        diff_lines.insert(
            "f.rs".to_string(),
            DiffLineSet {
                old_lines: Default::default(),
                new_lines: [12u32, 20].into_iter().collect(),
            },
        );
        let deltas = vec![make_delta_entry(
            "f.rs::foo",
            crate::delta::FunctionStatus::New,
        )];
        assert_eq!(
            compute_fn_changed_lines(Path::new("/repo"), &deltas, &head, &base, &diff_lines),
            1
        );
    }

    #[test]
    fn fn_changed_lines_counts_deleted_function_lines_from_old_side() {
        // Deleted function only exists in the base snapshot — must use the old-side line set.
        let head = make_snapshot(vec![]);
        let base = make_snapshot(vec![make_fn_snapshot("f.rs::gone", "f.rs", 100, 3)]);
        let mut diff_lines = std::collections::HashMap::new();
        diff_lines.insert(
            "f.rs".to_string(),
            DiffLineSet {
                old_lines: [100u32, 101, 999].into_iter().collect(),
                new_lines: Default::default(),
            },
        );
        let deltas = vec![make_delta_entry(
            "f.rs::gone",
            crate::delta::FunctionStatus::Deleted,
        )];
        // 100 and 101 fall in [100, 102]; 999 does not.
        assert_eq!(
            compute_fn_changed_lines(Path::new("/repo"), &deltas, &head, &base, &diff_lines),
            2
        );
    }

    #[test]
    fn fn_changed_lines_ignores_unchanged_and_missing_functions() {
        let head = make_snapshot(vec![make_fn_snapshot("f.rs::foo", "f.rs", 1, 5)]);
        let base = make_snapshot(vec![]);
        let mut diff_lines = std::collections::HashMap::new();
        diff_lines.insert(
            "f.rs".to_string(),
            DiffLineSet {
                old_lines: Default::default(),
                new_lines: [1u32, 2, 3].into_iter().collect(),
            },
        );
        let deltas = vec![
            make_delta_entry("f.rs::foo", crate::delta::FunctionStatus::Unchanged),
            make_delta_entry("f.rs::missing", crate::delta::FunctionStatus::New), // not in any snapshot
        ];
        assert_eq!(
            compute_fn_changed_lines(Path::new("/repo"), &deltas, &head, &base, &diff_lines),
            0
        );
    }

    #[test]
    fn fn_changed_lines_zero_when_file_has_no_diff_entry() {
        let head = make_snapshot(vec![make_fn_snapshot("f.rs::foo", "f.rs", 1, 5)]);
        let base = make_snapshot(vec![]);
        let diff_lines = std::collections::HashMap::new(); // no entry for f.rs at all
        let deltas = vec![make_delta_entry(
            "f.rs::foo",
            crate::delta::FunctionStatus::New,
        )];
        assert_eq!(
            compute_fn_changed_lines(Path::new("/repo"), &deltas, &head, &base, &diff_lines),
            0
        );
    }

    /// Serializes tests that depend on (or mutate) the process' ambient working
    /// directory. `git()` (as opposed to `git_at()`) always runs relative to
    /// `std::env::current_dir()`, and `cargo test` runs tests in parallel
    /// threads within one process — CWD is shared, global, mutable state.
    /// `resolve_merge_base_auto_returns_none_in_no_git_repo` below temporarily
    /// points CWD at a git-free tempdir; without this lock, any other test in
    /// this module that shells out to `git()` expecting to be in the repo can
    /// race against that window and fail nondeterministically.
    static CWD_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

    fn lock_cwd() -> std::sync::MutexGuard<'static, ()> {
        CWD_TEST_LOCK
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
    }

    #[test]
    fn test_extract_git_context() {
        let _guard = lock_cwd();
        // This test requires a git repository
        // Skip if not in a git repo (e.g., in CI without git context)
        if git(&["rev-parse", "--git-dir"]).is_err() {
            eprintln!("Skipping test: not in a git repository");
            return;
        }

        let context = extract_git_context().expect("should extract git context");

        // HEAD SHA should be 40 characters (full SHA) or 7+ characters (short SHA)
        assert!(!context.head_sha.is_empty(), "HEAD SHA should not be empty");

        // Timestamp should be reasonable (after 2005-04-07, before year 2100)
        assert!(
            context.timestamp > 1112832000,
            "timestamp should be after 2005"
        );
        assert!(
            context.timestamp < 4102444800,
            "timestamp should be before 2100"
        );

        // is_detached should be consistent with branch
        assert_eq!(
            context.is_detached,
            context.branch.is_none(),
            "is_detached should match branch presence"
        );
    }

    #[test]
    fn test_extract_commit_churn() {
        let _guard = lock_cwd();
        // Skip if not in a git repo
        if git(&["rev-parse", "--git-dir"]).is_err() {
            eprintln!("Skipping test: not in a git repository");
            return;
        }

        let context = match extract_git_context() {
            Ok(ctx) => ctx,
            Err(_) => {
                eprintln!("Skipping test: could not extract git context");
                return;
            }
        };

        // Skip if this is an initial commit (no parents)
        if context.parent_shas.is_empty() {
            eprintln!("Skipping test: initial commit has no churn");
            return;
        }

        // Extract churn for HEAD
        let churns = extract_commit_churn(&context.head_sha).expect("should extract churn");

        // Churn should be a list (may be empty for commits with no changes)
        // We just verify it doesn't error
        println!("Extracted {} file churns for HEAD", churns.len());

        // Validate structure if we have any churns
        for churn in &churns {
            assert!(!churn.file.is_empty(), "file path should not be empty");
            // lines_added and lines_deleted can be 0, so just check they parse
        }
    }

    #[test]
    fn test_resolve_ref_to_sha_head() {
        let _guard = lock_cwd();
        let cwd = std::env::current_dir().expect("failed to get cwd");
        if git_at(&cwd, &["rev-parse", "--git-dir"]).is_err() {
            eprintln!("Skipping test: not in a git repository");
            return;
        }

        let sha = resolve_ref_to_sha(&cwd, "HEAD").expect("should resolve HEAD");

        // Full SHA is 40 hex characters
        assert_eq!(sha.len(), 40, "resolved SHA should be 40 characters");
        assert!(
            sha.chars().all(|c| c.is_ascii_hexdigit()),
            "resolved SHA should be hex"
        );
    }

    #[test]
    fn test_resolve_ref_to_sha_abbreviated() {
        let _guard = lock_cwd();
        let cwd = std::env::current_dir().expect("failed to get cwd");
        if git_at(&cwd, &["rev-parse", "--git-dir"]).is_err() {
            eprintln!("Skipping test: not in a git repository");
            return;
        }

        // Get HEAD SHA, then resolve its first 8 characters as an abbreviated ref
        let full_sha = resolve_ref_to_sha(&cwd, "HEAD").expect("should resolve HEAD");
        let abbrev = &full_sha[..8];
        let resolved = resolve_ref_to_sha(&cwd, abbrev).expect("should resolve abbreviated SHA");

        assert_eq!(
            resolved, full_sha,
            "abbreviated SHA should resolve to the same full SHA as HEAD"
        );
    }

    #[test]
    fn test_resolve_ref_to_sha_invalid_ref() {
        let _guard = lock_cwd();
        let cwd = std::env::current_dir().expect("failed to get cwd");
        if git_at(&cwd, &["rev-parse", "--git-dir"]).is_err() {
            eprintln!("Skipping test: not in a git repository");
            return;
        }

        let result = resolve_ref_to_sha(&cwd, "refs/heads/this-branch-definitely-does-not-exist");
        assert!(result.is_err(), "invalid ref should return an error");
    }

    #[test]
    fn resolve_merge_base_auto_does_not_panic() {
        let _guard = lock_cwd();
        // This function returns None when no common branch exists — that is
        // the expected outcome in environments where the repo has no main/master
        // branch (e.g., a detached shallow clone with only origin/* refs).
        // The important invariant: it must not panic regardless of git state.
        let _result: Option<String> = resolve_merge_base_auto();
        // No assertion on value — just verifying no panic and correct return type.
    }

    #[test]
    fn resolve_merge_base_auto_returns_none_in_no_git_repo() {
        let _guard = lock_cwd();
        // In a tempdir with no git repo every merge-base attempt fails → None.
        let tmp = tempfile::tempdir().unwrap();
        let old_dir = std::env::current_dir().unwrap();
        std::env::set_current_dir(tmp.path()).unwrap();

        let result = resolve_merge_base_auto();

        std::env::set_current_dir(old_dir).unwrap();
        assert!(
            result.is_none(),
            "should return None when not in a git repo"
        );
    }

    // -- batch_last_touch_for_files (single unrestricted walk) --

    const DAY: i64 = 24 * 60 * 60;

    fn run_git_dated(dir: &Path, ts: i64, args: &[&str]) {
        let date = format!("{ts} +0000");
        let mut cmd = Command::new("git");
        for var in GIT_DISCOVERY_ENV_VARS {
            cmd.env_remove(var);
        }
        let out = cmd
            .current_dir(dir)
            .args(args)
            .env("GIT_AUTHOR_NAME", "t")
            .env("GIT_AUTHOR_EMAIL", "t@example.com")
            .env("GIT_COMMITTER_NAME", "t")
            .env("GIT_COMMITTER_EMAIL", "t@example.com")
            .env("GIT_AUTHOR_DATE", &date)
            .env("GIT_COMMITTER_DATE", &date)
            .env("GIT_CONFIG_GLOBAL", "/dev/null")
            .env("GIT_CONFIG_SYSTEM", "/dev/null")
            .output()
            .expect("run git");
        assert!(
            out.status.success(),
            "git {args:?} failed: {}",
            String::from_utf8_lossy(&out.stderr)
        );
    }

    fn write_commit(dir: &Path, ts: i64, files: &[(&str, &str)]) {
        for (name, content) in files {
            std::fs::write(dir.join(name), content).unwrap();
        }
        run_git_dated(dir, ts, &["add", "-A"]);
        run_git_dated(dir, ts, &["commit", "-q", "-m", "c"]);
    }

    /// The pre-change implementation (one path-limited full-history walk per 500
    /// files), kept only to assert equivalence on linear history.
    fn last_touch_reference_pathspec(
        repo_path: &Path,
        stale_files: &std::collections::HashSet<&str>,
        as_of_timestamp: i64,
    ) -> std::collections::HashMap<String, u32> {
        let until_arg = format!("--until={}", as_of_timestamp);
        let files: Vec<&str> = stale_files.iter().copied().collect();
        let mut result = std::collections::HashMap::new();
        for chunk in files.chunks(500) {
            let mut args: Vec<&str> = vec![
                "log",
                "--format=COMMIT %ct",
                "--name-only",
                &until_arg,
                "--",
            ];
            args.extend_from_slice(chunk);
            let output = git_at(repo_path, &args).unwrap();
            let mut current_ts: i64 = 0;
            for line in output.lines() {
                if let Some(ts_str) = line.strip_prefix("COMMIT ") {
                    current_ts = ts_str.trim().parse().unwrap_or(0);
                } else if current_ts > 0 && !line.trim().is_empty() {
                    let file = line.trim();
                    if stale_files.contains(file) {
                        result.entry(file.to_string()).or_insert_with(|| {
                            ((as_of_timestamp - current_ts).max(0) / DAY) as u32
                        });
                    }
                }
            }
        }
        result
    }

    #[test]
    fn last_touch_single_walk_matches_reference_on_linear_history() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path();
        let x = 1_600_000_000;
        run_git_dated(dir, x, &["init", "-q", "-b", "main"]);
        write_commit(dir, x, &[("a.txt", "1"), ("b.txt", "1")]);
        write_commit(dir, x + DAY, &[("a.txt", "2"), ("c.txt", "1")]);
        std::fs::rename(dir.join("c.txt"), dir.join("d.txt")).unwrap();
        write_commit(dir, x + 2 * DAY, &[]);

        let stale: std::collections::HashSet<&str> =
            ["a.txt", "b.txt", "c.txt", "d.txt"].into_iter().collect();
        let as_of = x + 10 * DAY;
        let new = batch_last_touch_for_files(dir, &stale, as_of);
        let reference = last_touch_reference_pathspec(dir, &stale, as_of);

        assert_eq!(new, reference);
        assert_eq!(new["a.txt"], 9);
        assert_eq!(new["b.txt"], 10);
        assert_eq!(new["d.txt"], 8);
    }

    #[test]
    fn last_touch_single_walk_ignores_commits_after_as_of() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path();
        let x = 1_600_000_000;
        run_git_dated(dir, x, &["init", "-q", "-b", "main"]);
        write_commit(dir, x, &[("a.txt", "1")]);
        write_commit(dir, x + 20 * DAY, &[("a.txt", "2")]);

        let stale: std::collections::HashSet<&str> = ["a.txt"].into_iter().collect();
        let new = batch_last_touch_for_files(dir, &stale, x + 10 * DAY);

        assert_eq!(new["a.txt"], 10);
    }

    #[test]
    fn last_touch_single_walk_empty_input_spawns_no_git() {
        let stale: std::collections::HashSet<&str> = std::collections::HashSet::new();
        let new = batch_last_touch_for_files(Path::new("/nonexistent/not-a-repo"), &stale, 0);
        assert!(new.is_empty());
    }

    #[test]
    fn last_touch_single_walk_omits_files_absent_from_history() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path();
        let x = 1_600_000_000;
        run_git_dated(dir, x, &["init", "-q", "-b", "main"]);
        write_commit(dir, x, &[("a.txt", "1")]);

        let stale: std::collections::HashSet<&str> =
            ["a.txt", "never-committed.txt"].into_iter().collect();
        let new = batch_last_touch_for_files(dir, &stale, x + 5 * DAY);

        assert!(new.contains_key("a.txt"));
        assert!(!new.contains_key("never-committed.txt"));
    }

    #[test]
    fn last_touch_single_walk_sees_side_branch_commits_the_old_method_pruned() {
        // A side-branch commit touches f.txt; the merge keeps the first parent's
        // tree (`-s ours`), so the merge is TREESAME to the first parent and the
        // old path-limited walk prunes the side branch: it reports f.txt as last
        // touched at the base commit. The single walk sees the side commit.
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path();
        let x = 1_600_000_000;
        run_git_dated(dir, x, &["init", "-q", "-b", "main"]);
        write_commit(dir, x, &[("f.txt", "base"), ("g.txt", "base")]);
        run_git_dated(dir, x, &["checkout", "-q", "-b", "side"]);
        write_commit(dir, x + 2 * DAY, &[("f.txt", "side")]);
        run_git_dated(dir, x + 2 * DAY, &["checkout", "-q", "main"]);
        write_commit(dir, x + DAY, &[("g.txt", "main")]);
        run_git_dated(
            dir,
            x + 3 * DAY,
            &["merge", "-q", "-s", "ours", "--no-edit", "side"],
        );

        let stale: std::collections::HashSet<&str> = ["f.txt", "g.txt"].into_iter().collect();
        let as_of = x + 10 * DAY;
        let new = batch_last_touch_for_files(dir, &stale, as_of);
        let reference = last_touch_reference_pathspec(dir, &stale, as_of);

        for file in ["f.txt", "g.txt"] {
            assert!(
                new[file] <= reference[file],
                "{file}: new must never be older"
            );
        }
        assert_eq!(new["g.txt"], reference["g.txt"]);
        assert_eq!(reference["f.txt"], 10);
        assert_eq!(new["f.txt"], 8);
    }
}