Skip to main content

pmat/services/
git_analysis.rs

1#![cfg_attr(coverage_nightly, coverage(off))]
2//! Git repository analysis and code churn metrics.
3//!
4//! This module provides analysis of git repositories to extract code churn
5//! metrics, contribution patterns, and file activity over time. Code churn
6//! is a key indicator of technical debt and maintenance burden.
7//!
8//! # Metrics Calculated
9//!
10//! - **File Churn**: Additions, deletions, and modifications per file
11//! - **Author Activity**: Contributions by developer over time
12//! - **Hotspots**: Files with high change frequency
13//! - **Stability**: Files that haven't changed recently
14//!
15//! # Example
16//!
17//! ```ignore
18//! use pmat::services::git_analysis::GitAnalysisService;
19//! use std::path::Path;
20//!
21//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
22//! // Analyze code churn for the last 30 days
23//! let project_path = Path::new(".");
24//! let analysis = GitAnalysisService::analyze_code_churn(project_path, 30)?;
25//!
26//! println!("Total commits: {}", analysis.summary.total_commits);
27//! println!("Files changed: {}", analysis.summary.files_changed);
28//! println!("Active authors: {}", analysis.summary.active_authors);
29//!
30//! // Find hotspots (files with high churn)
31//! for file in &analysis.files {
32//!     if file.commits > 10 {
33//!         println!("Hotspot: {} ({} commits)", file.file_path.display(), file.commits);
34//!     }
35//! }
36//! # Ok(())
37//! # }
38//! ```ignore
39
40use crate::models::churn::{ChurnSummary, CodeChurnAnalysis, FileChurnMetrics};
41use crate::models::error::TemplateError;
42use chrono::{DateTime, Duration, Utc};
43use std::collections::{HashMap, HashSet};
44use std::path::{Path, PathBuf};
45use std::process::Command;
46use tracing::info;
47
48/// Git analysis service.
49pub struct GitAnalysisService;
50
51impl GitAnalysisService {
52    /// Find the git repository root that *contains* `start`, the way git
53    /// itself does: walk up until a `.git` entry is found.
54    ///
55    /// #657: churn was silently unmeasured for every non-root path because the
56    /// only check was `project_path.join(".git").exists()`. Asking for
57    /// `<repo>/src/utils` inside a repository with 3855 commits reported
58    /// "No git repository found" and produced null churn for every file.
59    ///
60    /// `.git` may be a directory (normal clone) or a file (submodule / linked
61    /// worktree), so existence — not `is_dir()` — is the test.
62    #[must_use]
63    pub fn discover_repository_root(start: &Path) -> Option<PathBuf> {
64        // Canonicalize so `..` components and symlinks don't stop the walk
65        // early; fall back to the path as given if it cannot be resolved.
66        let start = start.canonicalize().unwrap_or_else(|_| start.to_path_buf());
67        let mut current: Option<&Path> = Some(start.as_path());
68        while let Some(dir) = current {
69            if dir.join(".git").exists() {
70                return Some(dir.to_path_buf());
71            }
72            current = dir.parent();
73        }
74        None
75    }
76
77    /// Path of `target` relative to `root`, or `None` when `target` *is* the
78    /// root (i.e. the query is unscoped).
79    fn scope_within_root(root: &Path, target: &Path) -> Option<PathBuf> {
80        let target = target
81            .canonicalize()
82            .unwrap_or_else(|_| target.to_path_buf());
83        let rel = target.strip_prefix(root).ok()?;
84        if rel.as_os_str().is_empty() {
85            None
86        } else {
87            Some(rel.to_path_buf())
88        }
89    }
90
91    #[inline]
92    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "path_exists")]
93    /// Analyze code churn.
94    ///
95    /// `project_path` may be the repository root or **any directory inside
96    /// it**; the repository root is discovered by walking up (#657) and the
97    /// git query is then scoped to the requested subtree, so asking for
98    /// `<repo>/src/utils` measures churn for `src/utils` rather than failing.
99    pub fn analyze_code_churn(
100        project_path: &Path,
101        period_days: u32,
102    ) -> Result<CodeChurnAnalysis, TemplateError> {
103        let repo_root = Self::discover_repository_root(project_path).ok_or_else(|| {
104            TemplateError::NotFound(format!(
105                "No git repository found at {project_path:?} or any of its parent directories"
106            ))
107        })?;
108        let scope = Self::scope_within_root(&repo_root, project_path);
109
110        // Checked arithmetic: `Utc::now() - Duration::days(...)` aborts the
111        // process with SIGABRT ("`DateTime - TimeDelta` overflowed") past
112        // roughly 10^8 days, reachable from the CLI as `-d 2147483647`. A
113        // user-supplied integer must never reach unchecked calendar arithmetic.
114        // See contracts/pmat-no-fabrication-v1.yaml, `bounded_time_arithmetic`.
115        //
116        // The floor is the Unix epoch, not the limit of chrono's range. Checked
117        // arithmetic alone was not enough: 400_000 days is ~year 931, which
118        // chrono represents happily and `git log --since` then parses
119        // erratically. On a 2-commit repo that produced a NON-MONOTONIC series
120        // -- -d 400000 found 1 file, -d 730000 found ZERO ("Analyzed 0 files
121        // with changes" on a live repo), -d 800000 found 1 again. Asking for
122        // more history must never return less, and a confident zero is a
123        // fabrication.
124        //
125        // Any window reaching past 1970 means "all of history", which is
126        // expressed to git by OMITTING --since rather than naming a date git
127        // will mis-parse.
128        let epoch = DateTime::from_timestamp(0, 0).unwrap_or_else(Utc::now);
129        let since_str = Duration::try_days(i64::from(period_days))
130            .and_then(|d| Utc::now().checked_sub_signed(d))
131            .filter(|since| *since >= epoch)
132            .map(|since| since.format("%Y-%m-%d").to_string());
133
134        info!("Analyzing code churn for last {} days", period_days);
135
136        let (file_metrics, total_commits) =
137            Self::get_file_metrics(&repo_root, since_str.as_deref(), scope.as_deref())?;
138        let summary = Self::generate_summary(&file_metrics, total_commits);
139
140        Ok(CodeChurnAnalysis {
141            generated_at: Utc::now(),
142            period_days,
143            repository_root: repo_root,
144            files: file_metrics,
145            summary,
146        })
147    }
148
149    /// Per-file churn metrics plus the number of DISTINCT commits in the window.
150    ///
151    /// The commit count is returned separately because it cannot be recovered
152    /// from `FileChurnMetrics`: summing `commit_count` over files counts one
153    /// commit once per file it touched. That sum was what "Total commits"
154    /// reported (GH #660) — 756 for a window git puts at 40, and 2 for a
155    /// fixture repo with a single commit touching two files.
156    /// Run `git log --numstat` in a timeout-guarded thread (#245) and return
157    /// its stdout as text.
158    ///
159    /// `Ok(None)` means "there is nothing to report and it is not an error" —
160    /// either the 60s timeout fired (logged as a warning) or git reported the
161    /// empty-repository case (`does not have any commits yet`). Both were
162    /// `return Ok((Vec::new(), 0))` early-returns in the original function;
163    /// callers must still perform that early return themselves.
164    fn capture_git_log_output(
165        project_path: &Path,
166        since_date: Option<&str>,
167        scope: Option<&Path>,
168    ) -> Result<Option<String>, TemplateError> {
169        let (tx, rx) = std::sync::mpsc::channel();
170        let project_dir = project_path.to_path_buf();
171        let since = since_date.map(std::string::ToString::to_string);
172        let scope = scope.map(Path::to_path_buf);
173        std::thread::spawn(move || {
174            let result = Self::git_log_numstat_command(since.as_deref(), scope.as_deref())
175                .current_dir(&project_dir)
176                .output();
177            let _ = tx.send(result);
178        });
179
180        let timeout = std::time::Duration::from_secs(60);
181        let output = match rx.recv_timeout(timeout) {
182            Ok(result) => result.map_err(TemplateError::Io)?,
183            Err(_) => {
184                tracing::warn!(
185                    "git log --numstat timed out after {}s for {}",
186                    timeout.as_secs(),
187                    project_path.display()
188                );
189                return Ok(None);
190            }
191        };
192
193        if !output.status.success() {
194            let error_msg = String::from_utf8_lossy(&output.stderr);
195            // Handle empty repository case
196            if error_msg.contains("does not have any commits yet") {
197                return Ok(None);
198            }
199            return Err(TemplateError::NotFound(format!(
200                "Git log failed: {error_msg}"
201            )));
202        }
203
204        Ok(Some(String::from_utf8_lossy(&output.stdout).into_owned()))
205    }
206
207    /// The `git log --numstat` invocation, optionally bounded by `--since`
208    /// and restricted to the `scope` subtree.
209    fn git_log_numstat_command(since: Option<&str>, scope: Option<&Path>) -> Command {
210        let mut command = Command::new("git");
211        command.arg("log");
212        // No --since at all means "all history", which is what a lookback
213        // reaching past the Unix epoch asks for. Naming an extreme date
214        // instead makes `git log --since` return erratic, sometimes empty,
215        // results -- see the monotonicity note above.
216        if let Some(since) = since {
217            command.arg("--since").arg(since);
218        }
219        command.arg("--pretty=format:%H|%an|%aI").arg("--numstat");
220        // #657: restrict the history to the requested subtree so a
221        // subdirectory query reports that subtree's churn, not the whole
222        // repository's.
223        if let Some(scope) = scope {
224            command.arg("--").arg(scope);
225        }
226        command
227    }
228
229    /// Parse `git log --pretty=format:%H|%an|%aI --numstat` output into
230    /// per-file stats plus the set of distinct commit hashes seen.
231    ///
232    /// Extracted verbatim from the loop body in [`Self::get_file_metrics`];
233    /// the commit-hash set is returned separately for the same reason noted
234    /// on `get_file_metrics` itself — it cannot be recovered from the stats.
235    fn parse_log_into_file_stats(
236        log_output: &str,
237    ) -> (HashMap<PathBuf, FileStats>, HashSet<String>) {
238        let mut file_stats: HashMap<PathBuf, FileStats> = HashMap::with_capacity(64);
239        let mut current_commit: Option<CommitInfo> = None;
240        let mut commit_hashes: HashSet<String> = HashSet::with_capacity(64);
241
242        for line in log_output.lines() {
243            if line.is_empty() {
244                continue;
245            }
246
247            if let Some((hash, author, date)) = Self::parse_commit_line(line) {
248                commit_hashes.insert(hash.clone());
249                current_commit = Some(CommitInfo { hash, author, date });
250            } else if let Some(ref commit) = current_commit {
251                if let Some(change) = Self::parse_numstat_line(line) {
252                    Self::record_file_change(&mut file_stats, commit, change);
253                }
254            }
255        }
256
257        (file_stats, commit_hashes)
258    }
259
260    /// Credit one numstat line `(additions, deletions, path)` of `commit` to
261    /// that file's running stats, widening its first-seen/last-modified span.
262    fn record_file_change(
263        file_stats: &mut HashMap<PathBuf, FileStats>,
264        commit: &CommitInfo,
265        (additions, deletions, file_path): (usize, usize, String),
266    ) {
267        let stats = file_stats
268            .entry(PathBuf::from(&file_path))
269            .or_insert_with(|| FileStats {
270                commits: Vec::new(),
271                authors: HashSet::with_capacity(64),
272                total_additions: 0,
273                total_deletions: 0,
274                first_seen: commit.date.clone(),
275                last_modified: commit.date.clone(),
276            });
277
278        stats.commits.push(commit.hash.clone());
279        stats.authors.insert(commit.author.clone());
280        stats.total_additions += additions;
281        stats.total_deletions += deletions;
282
283        if commit.date > stats.last_modified {
284            stats.last_modified = commit.date.clone();
285        }
286        if commit.date < stats.first_seen {
287            stats.first_seen = commit.date.clone();
288        }
289    }
290
291    /// Turn per-file stats into ranked `FileChurnMetrics`, in the deterministic
292    /// order documented on [`Self::churn_rank_cmp`].
293    fn build_churn_metrics(
294        project_path: &Path,
295        file_stats: HashMap<PathBuf, FileStats>,
296    ) -> Vec<FileChurnMetrics> {
297        let max_commits = file_stats
298            .values()
299            .map(|s| s.commits.len())
300            .max()
301            .unwrap_or(1);
302        let max_changes = file_stats
303            .values()
304            .map(|s| s.total_additions + s.total_deletions)
305            .max()
306            .unwrap_or(1);
307
308        let mut metrics: Vec<FileChurnMetrics> = file_stats
309            .into_iter()
310            .map(|(path, stats)| {
311                let mut metric = FileChurnMetrics {
312                    path: project_path.join(&path),
313                    relative_path: path.to_string_lossy().to_string(),
314                    commit_count: stats.commits.len(),
315                    // `authors` is a `HashSet`; unsorted it reached the JSON
316                    // document in a per-process random order.
317                    unique_authors: {
318                        let mut authors: Vec<String> = stats.authors.into_iter().collect();
319                        authors.sort_unstable();
320                        authors
321                    },
322                    additions: stats.total_additions,
323                    deletions: stats.total_deletions,
324                    churn_score: 0.0,
325                    last_modified: DateTime::parse_from_rfc3339(&stats.last_modified)
326                        .unwrap_or_else(|_| Utc::now().into())
327                        .with_timezone(&Utc),
328                    first_seen: DateTime::parse_from_rfc3339(&stats.first_seen)
329                        .unwrap_or_else(|_| Utc::now().into())
330                        .with_timezone(&Utc),
331                };
332                metric.calculate_churn_score(max_commits, max_changes);
333                metric
334            })
335            .collect();
336
337        metrics.sort_by(Self::churn_rank_cmp);
338        metrics
339    }
340
341    fn get_file_metrics(
342        project_path: &Path,
343        since_date: Option<&str>,
344        scope: Option<&Path>,
345    ) -> Result<(Vec<FileChurnMetrics>, usize), TemplateError> {
346        let log_output = match Self::capture_git_log_output(project_path, since_date, scope)? {
347            Some(log) => log,
348            None => return Ok((Vec::new(), 0)),
349        };
350
351        let (file_stats, commit_hashes) = Self::parse_log_into_file_stats(&log_output);
352        let metrics = Self::build_churn_metrics(project_path, file_stats);
353
354        Ok((metrics, commit_hashes.len()))
355    }
356
357    /// The order `analyze churn` ranks files in: churn score descending, then
358    /// path ascending.
359    ///
360    /// DETERMINISM: `file_stats` above is a `HashMap`, so `into_iter()` hands
361    /// the metrics over in a per-process random order, and `sort_by` is stable
362    /// — every group of files sharing a churn score therefore kept that random
363    /// order. On a repo of any size nearly every low-churn file ties, so two
364    /// back-to-back `analyze churn` runs over an unchanged tree printed
365    /// different "Stable Files (Low Churn)" lists and the section could be
366    /// neither diffed nor committed as a baseline. The path tie-break makes the
367    /// whole report a function of the tree: hotspots, stable files and the
368    /// ranked listing all follow from this one order.
369    pub(crate) fn churn_rank_cmp(a: &FileChurnMetrics, b: &FileChurnMetrics) -> std::cmp::Ordering {
370        b.churn_score
371            .partial_cmp(&a.churn_score)
372            .expect("internal error")
373            .then_with(|| a.relative_path.cmp(&b.relative_path))
374    }
375
376    fn parse_commit_line(line: &str) -> Option<(String, String, String)> {
377        let parts: Vec<&str> = line.split('|').collect();
378        if parts.len() == 3 {
379            Some((
380                parts[0].to_string(),
381                parts[1].to_string(),
382                parts[2].to_string(),
383            ))
384        } else {
385            None
386        }
387    }
388
389    fn parse_numstat_line(line: &str) -> Option<(usize, usize, String)> {
390        let parts: Vec<&str> = line.split_whitespace().collect();
391        if parts.len() >= 3 {
392            let additions = parts[0].parse::<usize>().ok()?;
393            let deletions = parts[1].parse::<usize>().ok()?;
394            let file_path = Self::resolve_rename_path(&parts[2..].join(" "));
395            Some((additions, deletions, file_path))
396        } else {
397            None
398        }
399    }
400
401    /// The path a `--numstat` entry refers to today.
402    ///
403    /// `git log --numstat` does not print a plain path for a rename; it prints
404    /// either `old/path.rs => new/path.rs` or, when the two share a prefix
405    /// and/or a suffix, `shared/{old => new}/tail.rs`. Both were stored
406    /// verbatim as the file path, so `analyze churn` reported churn for
407    /// `{server/src => src}/tdg/analyzer.rs` — a path that exists nowhere on
408    /// disk — in `stable_files` and `hotspots`, and split one file's history
409    /// across the rename instead of accumulating it under the current name.
410    fn resolve_rename_path(raw: &str) -> String {
411        if !raw.contains("=>") {
412            return raw.to_string();
413        }
414
415        // Braced form: keep the shared prefix and suffix, take the new middle.
416        if let Some(open) = raw.find('{') {
417            if let Some(close) = raw[open..].find('}').map(|offset| offset + open) {
418                if let Some((_old, new)) = raw[open + 1..close].split_once("=>") {
419                    let rebuilt = format!("{}{}{}", &raw[..open], new.trim(), &raw[close + 1..]);
420                    // An empty side (`{ => modules}` / `{src => }`) leaves a
421                    // doubled or leading separator behind.
422                    let mut collapsed = rebuilt;
423                    while collapsed.contains("//") {
424                        collapsed = collapsed.replace("//", "/");
425                    }
426                    if !raw.starts_with('/') {
427                        collapsed = collapsed.trim_start_matches('/').to_string();
428                    }
429                    return collapsed;
430                }
431            }
432        }
433
434        // Plain form: `old => new`.
435        match raw.split_once("=>") {
436            Some((_old, new)) => new.trim().to_string(),
437            None => raw.to_string(),
438        }
439    }
440
441    /// Build the summary. `total_commits` is the count of DISTINCT commits in
442    /// the window, supplied by the caller.
443    ///
444    /// It used to be computed here as `sum(file.commit_count)`, i.e. the number
445    /// of file revisions, and was still labelled "Total commits" (GH #660).
446    fn generate_summary(files: &[FileChurnMetrics], total_commits: usize) -> ChurnSummary {
447        let mut author_contributions: std::collections::BTreeMap<String, usize> =
448            std::collections::BTreeMap::new();
449
450        for file in files {
451            for author in &file.unique_authors {
452                *author_contributions.entry(author.clone()).or_insert(0) += 1;
453            }
454        }
455
456        let hotspot_files: Vec<PathBuf> = files
457            .iter()
458            .take(10)
459            .filter(|f| f.churn_score > 0.5)
460            .map(|f| f.path.clone())
461            .collect();
462
463        let stable_files: Vec<PathBuf> = files
464            .iter()
465            .rev()
466            .take(10)
467            .filter(|f| f.churn_score < 0.1 && f.commit_count > 0)
468            .map(|f| f.path.clone())
469            .collect();
470
471        // Calculate churn score statistics
472        let (mean_churn_score, variance_churn_score, stddev_churn_score) = if files.is_empty() {
473            (0.0, 0.0, 0.0)
474        } else {
475            let scores: Vec<f64> = files.iter().map(|f| f64::from(f.churn_score)).collect();
476            let n = scores.len() as f64;
477            let sum: f64 = scores.iter().sum();
478            let mean = sum / n;
479            let variance = scores.iter().map(|&s| (s - mean).powi(2)).sum::<f64>() / n;
480            let stddev = variance.sqrt();
481            (mean, variance, stddev)
482        };
483
484        ChurnSummary {
485            total_commits,
486            total_files_changed: files.len(),
487            hotspot_files,
488            stable_files,
489            author_contributions,
490            mean_churn_score,
491            variance_churn_score,
492            stddev_churn_score,
493        }
494    }
495}
496
497struct FileStats {
498    commits: Vec<String>,
499    authors: HashSet<String>,
500    total_additions: usize,
501    total_deletions: usize,
502    first_seen: String,
503    last_modified: String,
504}
505
506struct CommitInfo {
507    hash: String,
508    author: String,
509    date: String,
510}
511
512#[cfg_attr(coverage_nightly, coverage(off))]
513#[cfg(test)]
514mod tests {
515    use super::*;
516    use tempfile::TempDir;
517
518    #[test]
519    fn test_git_analysis_basic() {
520        // Basic test
521        assert_eq!(1 + 1, 2);
522    }
523
524    #[test]
525    fn test_parse_commit_line_valid() {
526        let line = "abc123|John Doe|2024-01-15T10:30:00Z";
527        let result = GitAnalysisService::parse_commit_line(line);
528        assert!(result.is_some());
529        let (hash, author, date) = result.unwrap();
530        assert_eq!(hash, "abc123");
531        assert_eq!(author, "John Doe");
532        assert_eq!(date, "2024-01-15T10:30:00Z");
533    }
534
535    #[test]
536    fn test_parse_commit_line_invalid_too_few() {
537        let line = "abc123|John Doe";
538        let result = GitAnalysisService::parse_commit_line(line);
539        assert!(result.is_none());
540    }
541
542    #[test]
543    fn test_parse_commit_line_invalid_empty() {
544        let line = "";
545        let result = GitAnalysisService::parse_commit_line(line);
546        assert!(result.is_none());
547    }
548
549    #[test]
550    fn test_parse_numstat_line_valid() {
551        let line = "10\t20\tsrc/main.rs";
552        let result = GitAnalysisService::parse_numstat_line(line);
553        assert!(result.is_some());
554        let (additions, deletions, path) = result.unwrap();
555        assert_eq!(additions, 10);
556        assert_eq!(deletions, 20);
557        assert_eq!(path, "src/main.rs");
558    }
559
560    #[test]
561    fn test_parse_numstat_line_with_spaces() {
562        let line = "5\t15\tpath/to file.rs";
563        let result = GitAnalysisService::parse_numstat_line(line);
564        assert!(result.is_some());
565        let (additions, deletions, path) = result.unwrap();
566        assert_eq!(additions, 5);
567        assert_eq!(deletions, 15);
568        assert_eq!(path, "path/to file.rs");
569    }
570
571    /// `git log --numstat` prints a rename as `old => new` or
572    /// `shared/{old => new}/tail.rs`. Both were stored verbatim, so churn
573    /// reported paths like `{server/src => src}/tdg/analyzer.rs`, which exist
574    /// nowhere on disk.
575    #[test]
576    fn test_parse_numstat_line_resolves_renames_to_the_current_path() {
577        let cases = [
578            (
579                "3\t1\t{server/src => src}/tdg/analyzer.rs",
580                "src/tdg/analyzer.rs",
581            ),
582            (
583                "1\t0\tserver/tests/{ => modules}/unit_mcp_semantic_tools.rs",
584                "server/tests/modules/unit_mcp_semantic_tools.rs",
585            ),
586            ("4\t4\t{src => }/main.rs", "main.rs"),
587            ("2\t2\told/path.rs => new/path.rs", "new/path.rs"),
588            ("7\t0\tsrc/{a.rs => b.rs}", "src/b.rs"),
589        ];
590
591        for (line, expected) in cases {
592            let (_, _, path) =
593                GitAnalysisService::parse_numstat_line(line).expect("numstat line must parse");
594            assert_eq!(path, expected, "line {line:?}");
595            assert!(
596                !path.contains("=>") && !path.contains('{'),
597                "rename syntax survived into the path: {path:?}"
598            );
599        }
600    }
601
602    /// A path that merely contains a brace is not a rename.
603    #[test]
604    fn test_parse_numstat_line_leaves_ordinary_paths_alone() {
605        let (_, _, path) = GitAnalysisService::parse_numstat_line("1\t1\tsrc/{weird}/f.rs")
606            .expect("numstat line must parse");
607        assert_eq!(path, "src/{weird}/f.rs");
608    }
609
610    #[test]
611    fn test_parse_numstat_line_invalid() {
612        let line = "invalid";
613        let result = GitAnalysisService::parse_numstat_line(line);
614        assert!(result.is_none());
615    }
616
617    #[test]
618    fn test_parse_numstat_line_binary() {
619        let line = "-\t-\timage.png";
620        let result = GitAnalysisService::parse_numstat_line(line);
621        assert!(result.is_none()); // '-' can't parse as usize
622    }
623
624    #[test]
625    fn test_generate_summary_empty() {
626        let files: Vec<FileChurnMetrics> = vec![];
627        let summary = GitAnalysisService::generate_summary(&files, 0);
628        assert_eq!(summary.total_commits, 0);
629        assert_eq!(summary.total_files_changed, 0);
630        assert!(summary.hotspot_files.is_empty());
631        assert!(summary.stable_files.is_empty());
632        assert_eq!(summary.mean_churn_score, 0.0);
633    }
634
635    #[test]
636    fn test_generate_summary_single_file() {
637        let files = vec![FileChurnMetrics {
638            path: PathBuf::from("src/main.rs"),
639            relative_path: "src/main.rs".to_string(),
640            commit_count: 5,
641            unique_authors: vec!["Author1".to_string()],
642            additions: 100,
643            deletions: 50,
644            churn_score: 0.7,
645            last_modified: Utc::now(),
646            first_seen: Utc::now(),
647        }];
648        // #660: the summary reports the DISTINCT commit count it is given, not
649        // sum(commit_count). Here 5 revisions of one file came from 3 commits
650        // (two of them touched it twice via amends/rebases in the window), so
651        // "Total commits" must be 3 — the old code answered 5.
652        let summary = GitAnalysisService::generate_summary(&files, 3);
653        assert_eq!(summary.total_commits, 3);
654        assert_eq!(summary.total_files_changed, 1);
655        assert_eq!(summary.hotspot_files.len(), 1); // churn_score > 0.5
656    }
657
658    #[test]
659    fn test_generate_summary_multiple_authors() {
660        let files = vec![
661            FileChurnMetrics {
662                path: PathBuf::from("file1.rs"),
663                relative_path: "file1.rs".to_string(),
664                commit_count: 3,
665                unique_authors: vec!["Author1".to_string(), "Author2".to_string()],
666                additions: 50,
667                deletions: 20,
668                churn_score: 0.3,
669                last_modified: Utc::now(),
670                first_seen: Utc::now(),
671            },
672            FileChurnMetrics {
673                path: PathBuf::from("file2.rs"),
674                relative_path: "file2.rs".to_string(),
675                commit_count: 2,
676                unique_authors: vec!["Author2".to_string()],
677                additions: 30,
678                deletions: 10,
679                churn_score: 0.05,
680                last_modified: Utc::now(),
681                first_seen: Utc::now(),
682            },
683        ];
684        // #660: two files with 3 and 2 revisions can come from as few as 3
685        // commits. The old code reported 5 "commits" for exactly this shape.
686        let summary = GitAnalysisService::generate_summary(&files, 3);
687        assert_eq!(summary.total_commits, 3);
688        assert_eq!(summary.total_files_changed, 2);
689        assert_eq!(summary.author_contributions.len(), 2);
690    }
691
692    #[test]
693    fn test_analyze_code_churn_no_git() {
694        let temp_dir = TempDir::new().unwrap();
695        let result = GitAnalysisService::analyze_code_churn(temp_dir.path(), 30);
696        assert!(result.is_err());
697    }
698
699    #[test]
700    fn test_generate_summary_stable_files() {
701        let files = vec![FileChurnMetrics {
702            path: PathBuf::from("stable.rs"),
703            relative_path: "stable.rs".to_string(),
704            commit_count: 1,
705            unique_authors: vec!["Author".to_string()],
706            additions: 10,
707            deletions: 5,
708            churn_score: 0.05, // Low churn
709            last_modified: Utc::now(),
710            first_seen: Utc::now(),
711        }];
712        let summary = GitAnalysisService::generate_summary(&files, 1);
713        assert_eq!(summary.stable_files.len(), 1);
714    }
715
716    #[test]
717    fn test_churn_summary_statistics() {
718        let files = vec![
719            FileChurnMetrics {
720                path: PathBuf::from("f1.rs"),
721                relative_path: "f1.rs".to_string(),
722                commit_count: 2,
723                unique_authors: vec![],
724                additions: 0,
725                deletions: 0,
726                churn_score: 0.2,
727                last_modified: Utc::now(),
728                first_seen: Utc::now(),
729            },
730            FileChurnMetrics {
731                path: PathBuf::from("f2.rs"),
732                relative_path: "f2.rs".to_string(),
733                commit_count: 4,
734                unique_authors: vec![],
735                additions: 0,
736                deletions: 0,
737                churn_score: 0.8,
738                last_modified: Utc::now(),
739                first_seen: Utc::now(),
740            },
741        ];
742        let summary = GitAnalysisService::generate_summary(&files, 4);
743        // Mean of 0.2 and 0.8 = 0.5
744        assert!((summary.mean_churn_score - 0.5).abs() < 0.01);
745        // Variance and stddev should be calculated
746        assert!(summary.variance_churn_score >= 0.0);
747        assert!(summary.stddev_churn_score >= 0.0);
748    }
749
750    // ── #657: churn must be measurable from any directory inside a repo ─────
751
752    /// Build a throwaway repo with commits under `src/utils/` and `docs/`.
753    fn init_repo_with_subdir_commits() -> TempDir {
754        let temp = TempDir::new().unwrap();
755        let root = temp.path();
756
757        let git = |args: &[&str]| {
758            let status = std::process::Command::new("git")
759                .args(args)
760                .current_dir(root)
761                .output()
762                .expect("git must be available for this test");
763            assert!(
764                status.status.success(),
765                "git {args:?} failed: {}",
766                String::from_utf8_lossy(&status.stderr)
767            );
768        };
769
770        git(&["init", "--initial-branch=main"]);
771        git(&["config", "user.email", "test@example.com"]);
772        git(&["config", "user.name", "Test User"]);
773
774        std::fs::create_dir_all(root.join("src/utils")).unwrap();
775        std::fs::create_dir_all(root.join("docs")).unwrap();
776
777        for i in 0..3 {
778            std::fs::write(
779                root.join("src/utils/helper.rs"),
780                format!("pub fn helper() {{ let _ = {i}; }}\n"),
781            )
782            .unwrap();
783            std::fs::write(root.join("docs/readme.md"), format!("doc revision {i}\n")).unwrap();
784            git(&["add", "."]);
785            git(&["commit", "-m", &format!("change {i}")]);
786        }
787
788        temp
789    }
790
791    #[test]
792    fn test_discover_repository_root_walks_up() {
793        let temp = init_repo_with_subdir_commits();
794        let expected = temp.path().canonicalize().unwrap();
795
796        // From the root itself, and from two levels down.
797        for start in [
798            temp.path().to_path_buf(),
799            temp.path().join("src"),
800            temp.path().join("src/utils"),
801        ] {
802            assert_eq!(
803                GitAnalysisService::discover_repository_root(&start),
804                Some(expected.clone()),
805                "should have walked up to the repo root from {start:?}"
806            );
807        }
808    }
809
810    #[test]
811    fn test_discover_repository_root_none_outside_repo() {
812        let temp = TempDir::new().unwrap();
813        assert!(GitAnalysisService::discover_repository_root(temp.path()).is_none());
814    }
815
816    /// #657 regression: `analyze_code_churn` on a SUBDIRECTORY used to return
817    /// `NotFound("No git repository found at .../src/utils")` because the only
818    /// check was `.git` in the path itself. It must now measure that subtree.
819    #[test]
820    fn test_analyze_code_churn_from_subdirectory_is_measured() {
821        let temp = init_repo_with_subdir_commits();
822        let subdir = temp.path().join("src/utils");
823
824        let analysis = GitAnalysisService::analyze_code_churn(&subdir, 365)
825            .expect("churn inside a repository must be measurable from a subdirectory");
826
827        assert_eq!(
828            analysis.repository_root,
829            temp.path().canonicalize().unwrap(),
830            "repository_root must be the discovered root, not the queried subpath"
831        );
832        assert!(
833            !analysis.files.is_empty(),
834            "subdirectory churn must not be empty for a subtree with commits"
835        );
836        assert!(
837            analysis.summary.total_commits > 0,
838            "total_commits must be measured, got {}",
839            analysis.summary.total_commits
840        );
841    }
842
843    /// The subtree query must be *scoped* — `docs/` commits must not leak into
844    /// a `src/utils` query, otherwise "output derived from input" fails.
845    #[test]
846    fn test_analyze_code_churn_subdirectory_is_scoped() {
847        let temp = init_repo_with_subdir_commits();
848
849        let scoped = GitAnalysisService::analyze_code_churn(&temp.path().join("src/utils"), 365)
850            .expect("scoped churn");
851        let whole = GitAnalysisService::analyze_code_churn(temp.path(), 365).expect("root churn");
852
853        assert!(
854            scoped
855                .files
856                .iter()
857                .all(|f| f.relative_path.starts_with("src/utils")),
858            "scoped query returned files outside the requested subtree: {:?}",
859            scoped
860                .files
861                .iter()
862                .map(|f| f.relative_path.clone())
863                .collect::<Vec<_>>()
864        );
865        assert!(
866            whole.files.len() > scoped.files.len(),
867            "whole-repo churn ({}) must cover more files than src/utils ({})",
868            whole.files.len(),
869            scoped.files.len()
870        );
871    }
872
873    /// Identical input, identical output — five runs, byte-compared.
874    #[test]
875    fn test_analyze_code_churn_is_deterministic_over_5_runs() {
876        let temp = init_repo_with_subdir_commits();
877        let subdir = temp.path().join("src/utils");
878
879        let fingerprint = |a: &CodeChurnAnalysis| {
880            a.files
881                .iter()
882                .map(|f| {
883                    format!(
884                        "{}|{}|{}|{}|{:.6}",
885                        f.relative_path, f.commit_count, f.additions, f.deletions, f.churn_score
886                    )
887                })
888                .collect::<Vec<_>>()
889                .join("\n")
890        };
891
892        let first = fingerprint(&GitAnalysisService::analyze_code_churn(&subdir, 365).unwrap());
893        for i in 1..5 {
894            let again = fingerprint(&GitAnalysisService::analyze_code_churn(&subdir, 365).unwrap());
895            assert_eq!(first, again, "churn output differed on run {i}");
896        }
897    }
898
899    fn churn_metric(path: &str, score: f32) -> FileChurnMetrics {
900        FileChurnMetrics {
901            path: PathBuf::from(path),
902            relative_path: path.to_string(),
903            commit_count: 1,
904            unique_authors: vec!["a".to_string()],
905            additions: 1,
906            deletions: 1,
907            churn_score: score,
908            last_modified: Utc::now(),
909            first_seen: Utc::now(),
910        }
911    }
912
913    /// Regression: the ranking comparator only compared churn scores, and
914    /// `sort_by` is stable, so files with EQUAL scores kept the random order
915    /// the source `HashMap` handed them in. Nearly every low-churn file ties,
916    /// so entries 2-5 of "Stable Files (Low Churn)" changed between two
917    /// back-to-back runs over an unchanged tree.
918    #[test]
919    fn test_churn_rank_cmp_breaks_score_ties_on_path() {
920        let forward = vec![
921            churn_metric("src/a.rs", 0.05),
922            churn_metric("src/b.rs", 0.05),
923            churn_metric("src/c.rs", 0.05),
924            churn_metric("src/hot.rs", 0.9),
925        ];
926        let mut reversed: Vec<FileChurnMetrics> = forward.iter().rev().cloned().collect();
927        let mut forward = forward;
928
929        forward.sort_by(GitAnalysisService::churn_rank_cmp);
930        reversed.sort_by(GitAnalysisService::churn_rank_cmp);
931
932        let paths = |v: &[FileChurnMetrics]| {
933            v.iter()
934                .map(|f| f.relative_path.clone())
935                .collect::<Vec<_>>()
936        };
937        assert_eq!(
938            paths(&forward),
939            vec!["src/hot.rs", "src/a.rs", "src/b.rs", "src/c.rs"],
940            "score descending, then path ascending"
941        );
942        assert_eq!(
943            paths(&forward),
944            paths(&reversed),
945            "the ranking must not depend on the order the metrics arrived in"
946        );
947    }
948}